diff --git a/WebDriverAgent/.azure-pipelines.yml b/WebDriverAgent/.azure-pipelines.yml index 89887d258a..eca3f55cf8 100644 --- a/WebDriverAgent/.azure-pipelines.yml +++ b/WebDriverAgent/.azure-pipelines.yml @@ -1,6 +1,6 @@ # https://docs.microsoft.com/en-us/azure/devops/pipelines/agents/hosted?view=azure-devops&tabs=yaml variables: - MIN_VM_IMAGE: macOS-14 + MIN_VM_IMAGE: macOS-13 MIN_XCODE_VERSION: 14.3.1 MIN_PLATFORM_VERSION: 16.4 MIN_TV_PLATFORM_VERSION: 16.4 diff --git a/WebDriverAgent/.eslintignore b/WebDriverAgent/.eslintignore deleted file mode 100644 index 84930aead4..0000000000 --- a/WebDriverAgent/.eslintignore +++ /dev/null @@ -1,3 +0,0 @@ -Resources -coverage -build diff --git a/WebDriverAgent/.eslintrc.json b/WebDriverAgent/.eslintrc.json deleted file mode 100644 index 3d7db0846d..0000000000 --- a/WebDriverAgent/.eslintrc.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "extends": ["@appium/eslint-config-appium-ts"], - "overrides": [ - { - "files": "test/**/*.js", - "rules": { - "func-names": "off", - "@typescript-eslint/no-var-requires": "off" - } - }, - { - "files": "Scripts/**/*.js", - "parserOptions": {"sourceType": "script"}, - "rules": { - "@typescript-eslint/no-var-requires": "off" - } - }, - { - "files": "ci-jobs/scripts/*.js", - "parserOptions": {"sourceType": "script"}, - "rules": { - "@typescript-eslint/no-var-requires": "off" - } - } - ], - "rules": { - "require-await": "error" - } -} diff --git a/WebDriverAgent/.releaserc b/WebDriverAgent/.releaserc index 0cb17f2207..3987c1e97d 100644 --- a/WebDriverAgent/.releaserc +++ b/WebDriverAgent/.releaserc @@ -35,7 +35,11 @@ ["@semantic-release/github", { "assets": [ "WebDriverAgentRunner-Runner.zip", - "WebDriverAgentRunner_tvOS-Runner.zip" + "WebDriverAgentRunner_tvOS-Runner.zip", + "WebDriverAgentRunner-Build-Sim-arm64.zip", + "WebDriverAgentRunner-Build-Sim-x86_64.zip", + "WebDriverAgentRunner_tvOS-Build-Sim-arm64.zip", + "WebDriverAgentRunner_tvOS-Build-Sim-x86_64.zip" ]}] ] } diff --git a/WebDriverAgent/CHANGELOG.md b/WebDriverAgent/CHANGELOG.md index 1a56783d3a..fe6e4b8587 100644 --- a/WebDriverAgent/CHANGELOG.md +++ b/WebDriverAgent/CHANGELOG.md @@ -1,3 +1,414 @@ +## [10.4.2](https://github.com/appium/WebDriverAgent/compare/v10.4.1...v10.4.2) (2025-12-11) + +### Miscellaneous Chores + +* **deps-dev:** bump @types/node from 24.10.3 to 25.0.0 ([#1081](https://github.com/appium/WebDriverAgent/issues/1081)) ([6157d8e](https://github.com/appium/WebDriverAgent/commit/6157d8edd12f0e40938fd38fa8473d84999ce360)) + +## [10.4.1](https://github.com/appium/WebDriverAgent/compare/v10.4.0...v10.4.1) (2025-12-07) + +### Miscellaneous Chores + +* Ditch usage of @appium/test-support ([#1080](https://github.com/appium/WebDriverAgent/issues/1080)) ([5c7cd2e](https://github.com/appium/WebDriverAgent/commit/5c7cd2ef2dec11b00dddd7a357bdaafd6df62e73)) + +## [10.4.0](https://github.com/appium/WebDriverAgent/compare/v10.3.0...v10.4.0) (2025-12-06) + +### Features + +* Migrate IntegrationApp to use UIScene lifecycle ([#1079](https://github.com/appium/WebDriverAgent/issues/1079)) ([dfba786](https://github.com/appium/WebDriverAgent/commit/dfba7863195651535a498c246e7b6461eaa24f8b)) + +## [10.3.0](https://github.com/appium/WebDriverAgent/compare/v10.2.7...v10.3.0) (2025-12-03) + +### Features + +* Deprecate CFNetwork usage ([#1078](https://github.com/appium/WebDriverAgent/issues/1078)) ([6df0c5f](https://github.com/appium/WebDriverAgent/commit/6df0c5fb442879a1af115f02ac79055a7ed76719)) + +## [10.2.7](https://github.com/appium/WebDriverAgent/compare/v10.2.6...v10.2.7) (2025-12-03) + +### Miscellaneous Chores + +* use any iphone/tvos simulator devices to build WDA for sim ([#1077](https://github.com/appium/WebDriverAgent/issues/1077)) ([9600d83](https://github.com/appium/WebDriverAgent/commit/9600d837bf35f420f71d00772fc682e3db9f257d)) + +## [10.2.6](https://github.com/appium/WebDriverAgent/compare/v10.2.5...v10.2.6) (2025-12-02) + +### Miscellaneous Chores + +* **deps:** bump actions/setup-node from 4 to 6 ([#1075](https://github.com/appium/WebDriverAgent/issues/1075)) ([5042063](https://github.com/appium/WebDriverAgent/commit/504206338a1d7038f1d95ef241006997c5512757)) + +## [10.2.5](https://github.com/appium/WebDriverAgent/compare/v10.2.4...v10.2.5) (2025-11-29) + +### Miscellaneous Chores + +* **deps:** bump actions/checkout from 4 to 6 ([#1076](https://github.com/appium/WebDriverAgent/issues/1076)) ([276be79](https://github.com/appium/WebDriverAgent/commit/276be795ad36ea4d3beddff47b0ed3aa2c1f9461)) + +## [10.2.4](https://github.com/appium/WebDriverAgent/compare/v10.2.3...v10.2.4) (2025-11-29) + +### Miscellaneous Chores + +* Deprecate idb ([#1073](https://github.com/appium/WebDriverAgent/issues/1073)) ([260bc31](https://github.com/appium/WebDriverAgent/commit/260bc319795aff26468eca261d5f286b31216270)) +* **deps:** bump appium-ios-simulator from 7.0.3 to 8.0.0 ([#1070](https://github.com/appium/WebDriverAgent/issues/1070)) ([7cb4b6e](https://github.com/appium/WebDriverAgent/commit/7cb4b6ecd37717c7aad214f8e387c404d4937534)) + +## [10.2.3](https://github.com/appium/WebDriverAgent/compare/v10.2.2...v10.2.3) (2025-11-29) + +### Bug Fixes + +* fix type and mark deprecated as no usage for unused xcodeVersion and deprecated idb ([#1072](https://github.com/appium/WebDriverAgent/issues/1072)) ([4499fb2](https://github.com/appium/WebDriverAgent/commit/4499fb22ae4884df84e5e2d2bd0570c90ee4848b)) + +## [10.2.2](https://github.com/appium/WebDriverAgent/compare/v10.2.1...v10.2.2) (2025-11-15) + +### Miscellaneous Chores + +* publish via trusted publisher ([#1068](https://github.com/appium/WebDriverAgent/issues/1068)) ([6321379](https://github.com/appium/WebDriverAgent/commit/6321379d3e97dfa846bf0ff6f0b8e8b9ef85ba1c)) + +## [10.2.1](https://github.com/appium/WebDriverAgent/compare/v10.2.0...v10.2.1) (2025-11-01) + +### Miscellaneous Chores + +* update xcodebuild commands for the new binding ip capability ([#1067](https://github.com/appium/WebDriverAgent/issues/1067)) ([d12f421](https://github.com/appium/WebDriverAgent/commit/d12f4214b958855022c21b4d700b6726740294c1)) + +## [10.2.0](https://github.com/appium/WebDriverAgent/compare/v10.1.4...v10.2.0) (2025-10-31) + +### Features + +* Let binding IP address to be configurable via USE_IP environment variable ([#1066](https://github.com/appium/WebDriverAgent/issues/1066)) ([70ed7cf](https://github.com/appium/WebDriverAgent/commit/70ed7cf0a74e0df3763b99f6155a7923dde17c9d)) + +## [10.1.4](https://github.com/appium/WebDriverAgent/compare/v10.1.3...v10.1.4) (2025-10-31) + +### Miscellaneous Chores + +* Improve type declarations ([#1065](https://github.com/appium/WebDriverAgent/issues/1065)) ([5aadcb8](https://github.com/appium/WebDriverAgent/commit/5aadcb8fa99459e7f8852f75d2549a76f3e55b07)) + +## [10.1.3](https://github.com/appium/WebDriverAgent/compare/v10.1.2...v10.1.3) (2025-10-17) + +### Miscellaneous Chores + +* **deps-dev:** bump semantic-release from 24.2.9 to 25.0.0 ([#1064](https://github.com/appium/WebDriverAgent/issues/1064)) ([6c2cffa](https://github.com/appium/WebDriverAgent/commit/6c2cffa4ee6fcd0c86ae7aa171f25cb800908932)) + +## [10.1.2](https://github.com/appium/WebDriverAgent/compare/v10.1.1...v10.1.2) (2025-10-08) + +### Miscellaneous Chores + +* Skip staleness checks for subelement lookups ([#1063](https://github.com/appium/WebDriverAgent/issues/1063)) ([ada7760](https://github.com/appium/WebDriverAgent/commit/ada77604f9fa9bfc85c61cabbd2a9f4de00aceb9)) + +## [10.1.1](https://github.com/appium/WebDriverAgent/compare/v10.1.0...v10.1.1) (2025-09-12) + +### Miscellaneous Chores + +* remove patents file ([#1061](https://github.com/appium/WebDriverAgent/issues/1061)) ([b001c4e](https://github.com/appium/WebDriverAgent/commit/b001c4e39ef71cb8b91ef7391b418f32a7ebe21c)) + +## [10.1.0](https://github.com/appium/WebDriverAgent/compare/v10.0.1...v10.1.0) (2025-09-03) + +### Features + +* Add process and bundle identifiers to the application node in the XML source ([#1055](https://github.com/appium/WebDriverAgent/issues/1055)) ([088cff2](https://github.com/appium/WebDriverAgent/commit/088cff2b2bc19ddde698ec06f1db37c6989cf392)) + +## [10.0.1](https://github.com/appium/WebDriverAgent/compare/v10.0.0...v10.0.1) (2025-08-23) + +### Miscellaneous Chores + +* **deps-dev:** bump chai from 5.3.2 to 6.0.0 ([#1053](https://github.com/appium/WebDriverAgent/issues/1053)) ([9e9ec38](https://github.com/appium/WebDriverAgent/commit/9e9ec381bd6695e1c8b89f2a9c304b12385c0134)) + +## [10.0.0](https://github.com/appium/WebDriverAgent/compare/v9.15.3...v10.0.0) (2025-08-17) + +### ⚠ BREAKING CHANGES + +* Required Node.js version has been bumped to ^20.19.0 || ^22.12.0 || >=24.0.0 +* Required npm version has been bumped to >=10 +* Required base driver version has been bumped to >=10.0.0-rc.1 + +### Features + +* Update server compatibility ([#1051](https://github.com/appium/WebDriverAgent/issues/1051)) ([f9ea1e5](https://github.com/appium/WebDriverAgent/commit/f9ea1e5e2f5306030387d5293f073b2a6fe658e7)) + +## [9.15.3](https://github.com/appium/WebDriverAgent/compare/v9.15.2...v9.15.3) (2025-08-12) + +### Miscellaneous Chores + +* Cache application instances for their PIDs ([#1049](https://github.com/appium/WebDriverAgent/issues/1049)) ([e9cbf64](https://github.com/appium/WebDriverAgent/commit/e9cbf640c21243c304b476a497f33802e0501a7d)) + +## [9.15.2](https://github.com/appium/WebDriverAgent/compare/v9.15.1...v9.15.2) (2025-08-04) + +### Miscellaneous Chores + +* bump appium-ios-device to 2.9.0 ([#1047](https://github.com/appium/WebDriverAgent/issues/1047)) ([305019d](https://github.com/appium/WebDriverAgent/commit/305019d4dde89853e44c58170e17ec23c89de2f3)) + +## [9.15.1](https://github.com/appium/WebDriverAgent/compare/v9.15.0...v9.15.1) (2025-07-17) + +### Miscellaneous Chores + +* Remove the redundant check after activating the system app ([#1043](https://github.com/appium/WebDriverAgent/issues/1043)) ([33ccba1](https://github.com/appium/WebDriverAgent/commit/33ccba1ab3bc2980349f8553fd30aa5b08141b6b)) + +## [9.15.0](https://github.com/appium/WebDriverAgent/compare/v9.14.6...v9.15.0) (2025-07-10) + +### Features + +* HTTPS support for wda-client if webDriverAgentUrl is set ([#1042](https://github.com/appium/WebDriverAgent/issues/1042)) ([f7c4193](https://github.com/appium/WebDriverAgent/commit/f7c41939c793cdbc62e9c14d8eb91e06957bb566)) + +## [9.14.6](https://github.com/appium/WebDriverAgent/compare/v9.14.5...v9.14.6) (2025-06-24) + +### Miscellaneous Chores + +* add missing arch ([#1039](https://github.com/appium/WebDriverAgent/issues/1039)) ([a8dd958](https://github.com/appium/WebDriverAgent/commit/a8dd958bd92ef685bc1798ec04e92080b798d7d2)) + +## [9.14.5](https://github.com/appium/WebDriverAgent/compare/v9.14.4...v9.14.5) (2025-06-24) + +### Miscellaneous Chores + +* keep entire app for simulators ([d2bbcc6](https://github.com/appium/WebDriverAgent/commit/d2bbcc6d7af6b8eea076e24cd18429b74eeaffd6)) + +## [9.14.4](https://github.com/appium/WebDriverAgent/compare/v9.14.3...v9.14.4) (2025-06-23) + +### Miscellaneous Chores + +* include wda sim prebuilt for gh release ([#1038](https://github.com/appium/WebDriverAgent/issues/1038)) ([4423ecb](https://github.com/appium/WebDriverAgent/commit/4423ecb4f23c50343d8ffbf56a7753b985cbab81)) + +## [9.14.3](https://github.com/appium/WebDriverAgent/compare/v9.14.2...v9.14.3) (2025-06-13) + +### Miscellaneous Chores + +* **deps-dev:** bump sinon from 20.0.0 to 21.0.0 ([#1034](https://github.com/appium/WebDriverAgent/issues/1034)) ([5b205f4](https://github.com/appium/WebDriverAgent/commit/5b205f493f35cd1744cf9e33bce21e0f9e7c3bea)) + +## [9.14.2](https://github.com/appium/WebDriverAgent/compare/v9.14.1...v9.14.2) (2025-06-10) + +### Miscellaneous Chores + +* **deps-dev:** bump @types/node from 22.15.31 to 24.0.0 ([#1033](https://github.com/appium/WebDriverAgent/issues/1033)) ([e9705d9](https://github.com/appium/WebDriverAgent/commit/e9705d964e63222daaf0710bd3b860ca2ba6850f)) + +## [9.14.1](https://github.com/appium/WebDriverAgent/compare/v9.14.0...v9.14.1) (2025-06-09) + +### Miscellaneous Chores + +* add -Wno-reserved-identifier option ([#1032](https://github.com/appium/WebDriverAgent/issues/1032)) ([005dc21](https://github.com/appium/WebDriverAgent/commit/005dc216d9f41757763fe5b1714b68697fa8ee30)) + +## [9.14.0](https://github.com/appium/WebDriverAgent/compare/v9.13.0...v9.14.0) (2025-06-09) + +### Features + +* add minimum and maximum value attributes to page source ([#1031](https://github.com/appium/WebDriverAgent/issues/1031)) ([0e4e7e7](https://github.com/appium/WebDriverAgent/commit/0e4e7e7c483b9196edae576481f4e37f99fc8705)) + +## [9.13.0](https://github.com/appium/WebDriverAgent/compare/v9.12.0...v9.13.0) (2025-06-05) + +### Features + +* expose nativeFrame attribute in XML page source ([#1029](https://github.com/appium/WebDriverAgent/issues/1029)) ([5b56a45](https://github.com/appium/WebDriverAgent/commit/5b56a453f836cbc4358ce24ae43032658467c35c)) + +## [9.12.0](https://github.com/appium/WebDriverAgent/compare/v9.11.0...v9.12.0) (2025-06-04) + +### Features + +* add accessibility traits to XML page source ([#1028](https://github.com/appium/WebDriverAgent/issues/1028)) ([2df6649](https://github.com/appium/WebDriverAgent/commit/2df6649cb532d65a8c14633591b76c90185644cb)) + +## [9.11.0](https://github.com/appium/WebDriverAgent/compare/v9.10.1...v9.11.0) (2025-06-03) + +### Features + +* Add includeHittableInSource setting for including real hittable attribute in XML source ([#1026](https://github.com/appium/WebDriverAgent/issues/1026)) ([0fa4e74](https://github.com/appium/WebDriverAgent/commit/0fa4e7417404b5975445d381d111753fe681edd4)) + +## [9.10.1](https://github.com/appium/WebDriverAgent/compare/v9.10.0...v9.10.1) (2025-05-30) + +### Miscellaneous Chores + +* Make sure the same import style is used everywhere ([#1024](https://github.com/appium/WebDriverAgent/issues/1024)) ([1c50072](https://github.com/appium/WebDriverAgent/commit/1c50072457a8b82eec3684029386ccfa9432eccc)) + +## [9.10.0](https://github.com/appium/WebDriverAgent/compare/v9.9.0...v9.10.0) (2025-05-27) + +### Features + +* Add accessibility traits of the element ([#1020](https://github.com/appium/WebDriverAgent/issues/1020)) ([9465aaf](https://github.com/appium/WebDriverAgent/commit/9465aafd5e81ef57be7f78e9f2e188d3c1ba1bee)) + +### Bug Fixes + +* Use native snapshots if hittable attribute is requested in xPath ([#1023](https://github.com/appium/WebDriverAgent/issues/1023)) ([49d26cb](https://github.com/appium/WebDriverAgent/commit/49d26cb02a8515d1a1b52b65b7cb65512dfd749b)) + +## [9.9.0](https://github.com/appium/WebDriverAgent/compare/v9.8.0...v9.9.0) (2025-05-26) + +### Features + +* Use another snapshotting mechanism for the hittable attribute calculation ([#1022](https://github.com/appium/WebDriverAgent/issues/1022)) ([13c9f45](https://github.com/appium/WebDriverAgent/commit/13c9f453d890ad9b78fa7c47728ebae33880966a)) + +## [9.8.0](https://github.com/appium/WebDriverAgent/compare/v9.7.1...v9.8.0) (2025-05-21) + +### Features + +* Add a native frame property of the element ([#1017](https://github.com/appium/WebDriverAgent/issues/1017)) ([09214c4](https://github.com/appium/WebDriverAgent/commit/09214c4228ed5a49c02adead452cb0bb8dd83b6d)) + +## [9.7.1](https://github.com/appium/WebDriverAgent/compare/v9.7.0...v9.7.1) (2025-05-21) + +### Miscellaneous Chores + +* **deps-dev:** bump conventional-changelog-conventionalcommits ([#1019](https://github.com/appium/WebDriverAgent/issues/1019)) ([7108f7f](https://github.com/appium/WebDriverAgent/commit/7108f7f79575a1758bc7f05bd4ef790fd7694784)) + +## [9.7.0](https://github.com/appium/WebDriverAgent/compare/v9.6.3...v9.7.0) (2025-05-20) + +### Features + +* add placeholderValue to page source tree ([#1016](https://github.com/appium/WebDriverAgent/issues/1016)) ([509c207](https://github.com/appium/WebDriverAgent/commit/509c207b1366dd8582ba273edcdf77bfb30f53c9)) + +## [9.6.3](https://github.com/appium/WebDriverAgent/compare/v9.6.2...v9.6.3) (2025-05-18) + +### Miscellaneous Chores + +* Move the FBDoesElementSupportInnerText helper to a separate utility file ([#1018](https://github.com/appium/WebDriverAgent/issues/1018)) ([f17b07d](https://github.com/appium/WebDriverAgent/commit/f17b07d03abb6c2100405fda04326b7c35bfb48b)) + +## [9.6.2](https://github.com/appium/WebDriverAgent/compare/v9.6.1...v9.6.2) (2025-05-01) + +### Bug Fixes + +* release element screenshot data ([#1013](https://github.com/appium/WebDriverAgent/issues/1013)) ([a85f327](https://github.com/appium/WebDriverAgent/commit/a85f3271991556941234fbc888528051b1569db1)) + +## [9.6.1](https://github.com/appium/WebDriverAgent/compare/v9.6.0...v9.6.1) (2025-04-22) + +### Bug Fixes + +* allow setting precise resolution for the MJPEG stream ([#1009](https://github.com/appium/WebDriverAgent/issues/1009)) ([3f86eda](https://github.com/appium/WebDriverAgent/commit/3f86edafda42d955929f7cca870e2b8da54ae930)) + +## [9.6.0](https://github.com/appium/WebDriverAgent/compare/v9.5.2...v9.6.0) (2025-04-20) + +### Features + +* Split custom and standard snapshotting methods ([#1008](https://github.com/appium/WebDriverAgent/issues/1008)) ([8358856](https://github.com/appium/WebDriverAgent/commit/8358856f5968977b13d5cbdafac97f3053dae56e)) + +## [9.5.2](https://github.com/appium/WebDriverAgent/compare/v9.5.1...v9.5.2) (2025-04-19) + +### Bug Fixes + +* Missing text in long text for get text/value ([#1007](https://github.com/appium/WebDriverAgent/issues/1007)) ([6603a0b](https://github.com/appium/WebDriverAgent/commit/6603a0ba384917d39389509958ccac03ad174610)) + +## [9.5.1](https://github.com/appium/WebDriverAgent/compare/v9.5.0...v9.5.1) (2025-04-10) + +### Bug Fixes + +* Make sure we don't store element snapshot in the cache ([#1001](https://github.com/appium/WebDriverAgent/issues/1001)) ([cfe052b](https://github.com/appium/WebDriverAgent/commit/cfe052bb3adb3f3b24d0a34f386c60cf1516b308)) + +## [9.5.0](https://github.com/appium/WebDriverAgent/compare/v9.4.1...v9.5.0) (2025-04-10) + +### Features + +* Add support for the autoClickAlertSelector setting ([#1002](https://github.com/appium/WebDriverAgent/issues/1002)) ([fd31b95](https://github.com/appium/WebDriverAgent/commit/fd31b9589199d0a7bc76919f6aa7c7c74c498b90)) + +## [9.4.1](https://github.com/appium/WebDriverAgent/compare/v9.4.0...v9.4.1) (2025-04-05) + +### Miscellaneous Chores + +* bump appium-ios-simulator ([445741d](https://github.com/appium/WebDriverAgent/commit/445741d03313019016d4232f49e656d50f673f16)) + +## [9.4.0](https://github.com/appium/WebDriverAgent/compare/v9.3.3...v9.4.0) (2025-04-02) + +### Features + +* Always apply the native snapshotting strategy for XCUIApplication instances ([#998](https://github.com/appium/WebDriverAgent/issues/998)) ([60f5aef](https://github.com/appium/WebDriverAgent/commit/60f5aeffdda85faffd60aba416dc9d92987f19ac)) + +## [9.3.3](https://github.com/appium/WebDriverAgent/compare/v9.3.2...v9.3.3) (2025-03-27) + +### Bug Fixes + +* Properly set snapshot lookup scope if limitXpathContextScope is disabled ([#996](https://github.com/appium/WebDriverAgent/issues/996)) ([03ca7cd](https://github.com/appium/WebDriverAgent/commit/03ca7cd27b7cd92a45b344eb661db973c5dde809)) + +## [9.3.2](https://github.com/appium/WebDriverAgent/compare/v9.3.1...v9.3.2) (2025-03-26) + +### Bug Fixes + +* Adjust limitXPathContextScope setting name ([#995](https://github.com/appium/WebDriverAgent/issues/995)) ([9789e39](https://github.com/appium/WebDriverAgent/commit/9789e393b55bc682a9a8ef5a65fba5e4dbf752ce)) + +## [9.3.1](https://github.com/appium/WebDriverAgent/compare/v9.3.0...v9.3.1) (2025-03-25) + +### Miscellaneous Chores + +* **deps-dev:** bump sinon from 19.0.5 to 20.0.0 ([#994](https://github.com/appium/WebDriverAgent/issues/994)) ([f55462f](https://github.com/appium/WebDriverAgent/commit/f55462f4fa63314dfea48670d17ee54dc5fe2d96)) + +## [9.3.0](https://github.com/appium/WebDriverAgent/compare/v9.2.0...v9.3.0) (2025-03-21) + +### Features + +* Add /window/rect W3C endpoint ([#991](https://github.com/appium/WebDriverAgent/issues/991)) ([34f9510](https://github.com/appium/WebDriverAgent/commit/34f95107997bdec63219a2fd917de899de3e198c)) + +## [9.2.0](https://github.com/appium/WebDriverAgent/compare/v9.1.0...v9.2.0) (2025-03-13) + +### Features + +* Add 'limitXpathContextScope' setting ([#988](https://github.com/appium/WebDriverAgent/issues/988)) ([9c9d8af](https://github.com/appium/WebDriverAgent/commit/9c9d8af9c98ba7b2843a42f54354b78e126d2d27)) + +## [9.1.0](https://github.com/appium/WebDriverAgent/compare/v9.0.6...v9.1.0) (2025-03-09) + +### Features + +* add placeholderValue ([#987](https://github.com/appium/WebDriverAgent/issues/987)) ([8c3a1cb](https://github.com/appium/WebDriverAgent/commit/8c3a1cb30655ed8d1a77d25bbeca71ee48c2ec3e)) + +## [9.0.6](https://github.com/appium/WebDriverAgent/compare/v9.0.5...v9.0.6) (2025-02-28) + +### Bug Fixes + +* optimize LRU cache ([#985](https://github.com/appium/WebDriverAgent/issues/985)) ([46dc417](https://github.com/appium/WebDriverAgent/commit/46dc417da9f4a843838b414c0b154d6f478dbc0b)) + +## [9.0.5](https://github.com/appium/WebDriverAgent/compare/v9.0.4...v9.0.5) (2025-02-26) + +### Bug Fixes + +* add autorelease pool to drain temporary objects ([#983](https://github.com/appium/WebDriverAgent/issues/983)) ([f92f1cd](https://github.com/appium/WebDriverAgent/commit/f92f1cde0fe914086103a110844bbe3bc0e3c4a6)) + +## [9.0.4](https://github.com/appium/WebDriverAgent/compare/v9.0.3...v9.0.4) (2025-02-21) + +### Bug Fixes + +* Accept reqBasePath proxy option ([#982](https://github.com/appium/WebDriverAgent/issues/982)) ([19efbdd](https://github.com/appium/WebDriverAgent/commit/19efbdd69ff9edff20c0c318bd39c29963d4d51d)) + +## [9.0.3](https://github.com/appium/WebDriverAgent/compare/v9.0.2...v9.0.3) (2025-02-05) + +### Bug Fixes + +* add nullable signature ([#979](https://github.com/appium/WebDriverAgent/issues/979)) ([34b303c](https://github.com/appium/WebDriverAgent/commit/34b303c4e226d6a75a45a14eee7ca5e253e67737)) + +## [9.0.2](https://github.com/appium/WebDriverAgent/compare/v9.0.1...v9.0.2) (2025-02-03) + +### Bug Fixes + +* update docs link in xcodebuild error message ([#978](https://github.com/appium/WebDriverAgent/issues/978)) ([ea3863a](https://github.com/appium/WebDriverAgent/commit/ea3863a67d5cfa8bc2e48a1dc2c59052acd47937)) + +## [9.0.1](https://github.com/appium/WebDriverAgent/compare/v9.0.0...v9.0.1) (2025-01-17) + +### Miscellaneous Chores + +* Optimize stable instance retrieval ([#973](https://github.com/appium/WebDriverAgent/issues/973)) ([f2c752d](https://github.com/appium/WebDriverAgent/commit/f2c752db4707b3864efb62b95b64abb487d28e4b)) + +## [9.0.0](https://github.com/appium/WebDriverAgent/compare/v8.12.2...v9.0.0) (2025-01-16) + +### ⚠ BREAKING CHANGES + +* snapshotTimeout and customSnapshotTimeout settings have been removed as a result of the custom snapshotting logic removal + +### Features + +* Refactor snapshotting mechanism ([#970](https://github.com/appium/WebDriverAgent/issues/970)) ([08f1306](https://github.com/appium/WebDriverAgent/commit/08f13060119c710f53b34a98c95683287c0365a0)) + +## [8.12.2](https://github.com/appium/WebDriverAgent/compare/v8.12.1...v8.12.2) (2025-01-13) + +### Miscellaneous Chores + +* Exclude element visibility and accessibility info from the accessibility audit details ([#968](https://github.com/appium/WebDriverAgent/issues/968)) ([f62afc3](https://github.com/appium/WebDriverAgent/commit/f62afc372c123bdd8dd7bb493f653bb128144d24)) + +## [8.12.1](https://github.com/appium/WebDriverAgent/compare/v8.12.0...v8.12.1) (2025-01-03) + +### Miscellaneous Chores + +* Bump eslint ([#965](https://github.com/appium/WebDriverAgent/issues/965)) ([17f49ec](https://github.com/appium/WebDriverAgent/commit/17f49ec5a54e97b0ef0d20a3e39fc96b32575e43)) + +## [8.12.0](https://github.com/appium/WebDriverAgent/compare/v8.11.3...v8.12.0) (2024-12-13) + +### Features + +* look for critical notification in respectSystemAlerts ([#962](https://github.com/appium/WebDriverAgent/issues/962)) ([916c8c5](https://github.com/appium/WebDriverAgent/commit/916c8c557a9366608df211f33b5b7fbb0354dad3)) + +## [8.11.3](https://github.com/appium/WebDriverAgent/compare/v8.11.2...v8.11.3) (2024-12-06) + +### Miscellaneous Chores + +* **deps:** bump @appium/support from 5.1.8 to 6.0.0 ([#960](https://github.com/appium/WebDriverAgent/issues/960)) ([dbeb09c](https://github.com/appium/WebDriverAgent/commit/dbeb09c89f8c02e00a7bdffe7899650d435f3575)) + +## [8.11.2](https://github.com/appium/WebDriverAgent/compare/v8.11.1...v8.11.2) (2024-12-03) + +### Miscellaneous Chores + +* **deps-dev:** bump mocha from 10.8.2 to 11.0.1 ([#959](https://github.com/appium/WebDriverAgent/issues/959)) ([55b49c8](https://github.com/appium/WebDriverAgent/commit/55b49c83581c9e88f70806d98015238de3104f19)) + ## [8.11.1](https://github.com/appium/WebDriverAgent/compare/v8.11.0...v8.11.1) (2024-11-11) ### Miscellaneous Chores diff --git a/WebDriverAgent/Configurations/IOSSettings.xcconfig b/WebDriverAgent/Configurations/IOSSettings.xcconfig index b9969a48b2..3bde5a21f2 100644 --- a/WebDriverAgent/Configurations/IOSSettings.xcconfig +++ b/WebDriverAgent/Configurations/IOSSettings.xcconfig @@ -28,4 +28,4 @@ RUN_CLANG_STATIC_ANALYZER = YES GCC_PREPROCESSOR_DEFINITIONS = $(inherited) -WARNING_CFLAGS = $(inherited) -Weverything -Wno-objc-missing-property-synthesis -Wno-unused-macros -Wno-disabled-macro-expansion -Wno-gnu-statement-expression -Wno-language-extension-token -Wno-overriding-method-mismatch -Wno-missing-variable-declarations -Rno-module-build -Wno-auto-import -Wno-objc-interface-ivars -Wno-documentation-unknown-command -Wno-reserved-id-macro -Wno-unused-parameter -Wno-gnu-conditional-omitted-operand -Wno-explicit-ownership-type -Wno-date-time -Wno-cast-align -Wno-cstring-format-directive -Wno-double-promotion -Wno-partial-availability -Wno-declaration-after-statement -Wno-objc-messaging-id -Wno-direct-ivar-access -Wno-cast-qual -Wno-deprecated-declarations +WARNING_CFLAGS = $(inherited) -Weverything -Wno-objc-missing-property-synthesis -Wno-unused-macros -Wno-disabled-macro-expansion -Wno-gnu-statement-expression -Wno-language-extension-token -Wno-overriding-method-mismatch -Wno-missing-variable-declarations -Rno-module-build -Wno-auto-import -Wno-objc-interface-ivars -Wno-documentation-unknown-command -Wno-reserved-id-macro -Wno-unused-parameter -Wno-gnu-conditional-omitted-operand -Wno-explicit-ownership-type -Wno-date-time -Wno-cast-align -Wno-cstring-format-directive -Wno-double-promotion -Wno-partial-availability -Wno-declaration-after-statement -Wno-objc-messaging-id -Wno-direct-ivar-access -Wno-cast-qual -Wno-deprecated-declarations -Wno-reserved-identifier diff --git a/WebDriverAgent/Configurations/TVOSSettings.xcconfig b/WebDriverAgent/Configurations/TVOSSettings.xcconfig index b9969a48b2..3bde5a21f2 100644 --- a/WebDriverAgent/Configurations/TVOSSettings.xcconfig +++ b/WebDriverAgent/Configurations/TVOSSettings.xcconfig @@ -28,4 +28,4 @@ RUN_CLANG_STATIC_ANALYZER = YES GCC_PREPROCESSOR_DEFINITIONS = $(inherited) -WARNING_CFLAGS = $(inherited) -Weverything -Wno-objc-missing-property-synthesis -Wno-unused-macros -Wno-disabled-macro-expansion -Wno-gnu-statement-expression -Wno-language-extension-token -Wno-overriding-method-mismatch -Wno-missing-variable-declarations -Rno-module-build -Wno-auto-import -Wno-objc-interface-ivars -Wno-documentation-unknown-command -Wno-reserved-id-macro -Wno-unused-parameter -Wno-gnu-conditional-omitted-operand -Wno-explicit-ownership-type -Wno-date-time -Wno-cast-align -Wno-cstring-format-directive -Wno-double-promotion -Wno-partial-availability -Wno-declaration-after-statement -Wno-objc-messaging-id -Wno-direct-ivar-access -Wno-cast-qual -Wno-deprecated-declarations +WARNING_CFLAGS = $(inherited) -Weverything -Wno-objc-missing-property-synthesis -Wno-unused-macros -Wno-disabled-macro-expansion -Wno-gnu-statement-expression -Wno-language-extension-token -Wno-overriding-method-mismatch -Wno-missing-variable-declarations -Rno-module-build -Wno-auto-import -Wno-objc-interface-ivars -Wno-documentation-unknown-command -Wno-reserved-id-macro -Wno-unused-parameter -Wno-gnu-conditional-omitted-operand -Wno-explicit-ownership-type -Wno-date-time -Wno-cast-align -Wno-cstring-format-directive -Wno-double-promotion -Wno-partial-availability -Wno-declaration-after-statement -Wno-objc-messaging-id -Wno-direct-ivar-access -Wno-cast-qual -Wno-deprecated-declarations -Wno-reserved-identifier diff --git a/WebDriverAgent/Configurations/TVOSTestSettings.xcconfig b/WebDriverAgent/Configurations/TVOSTestSettings.xcconfig index 08679e4214..17824cc366 100644 --- a/WebDriverAgent/Configurations/TVOSTestSettings.xcconfig +++ b/WebDriverAgent/Configurations/TVOSTestSettings.xcconfig @@ -1,2 +1 @@ EXCLUDED_ARCHS = i386 - diff --git a/WebDriverAgent/PATENTS b/WebDriverAgent/PATENTS deleted file mode 100644 index f5c989c54e..0000000000 --- a/WebDriverAgent/PATENTS +++ /dev/null @@ -1,33 +0,0 @@ -Additional Grant of Patent Rights Version 2 - -"Software" means the WebDriverAgent software distributed by Facebook, Inc. - -Facebook, Inc. ("Facebook") hereby grants to each recipient of the Software -("you") a perpetual, worldwide, royalty-free, non-exclusive, irrevocable -(subject to the termination provision below) license under any Necessary -Claims, to make, have made, use, sell, offer to sell, import, and otherwise -transfer the Software. For avoidance of doubt, no license is granted under -Facebook’s rights in any patent claims that are infringed by (i) modifications -to the Software made by you or any third party or (ii) the Software in -combination with any software or other technology. - -The license granted hereunder will terminate, automatically and without notice, -if you (or any of your subsidiaries, corporate affiliates or agents) initiate -directly or indirectly, or take a direct financial interest in, any Patent -Assertion: (i) against Facebook or any of its subsidiaries or corporate -affiliates, (ii) against any party if such Patent Assertion arises in whole or -in part from any software, technology, product or service of Facebook or any of -its subsidiaries or corporate affiliates, or (iii) against any party relating -to the Software. Notwithstanding the foregoing, if Facebook or any of its -subsidiaries or corporate affiliates files a lawsuit alleging patent -infringement against you in the first instance, and you respond by filing a -patent infringement counterclaim in that lawsuit against that party that is -unrelated to the Software, the license granted hereunder will not terminate -under section (i) of this paragraph due to such counterclaim. - -A "Necessary Claim" is a claim of a patent owned by Facebook that is -necessarily infringed by the Software standing alone. - -A "Patent Assertion" is any lawsuit or other action alleging direct, indirect, -or contributory infringement or inducement to infringe any patent, including a -cross-claim or counterclaim. diff --git a/WebDriverAgent/PrivateHeaders/XCTest/XCTestManager_ManagerInterface-Protocol.h b/WebDriverAgent/PrivateHeaders/XCTest/XCTestManager_ManagerInterface-Protocol.h index 8ed03ebf75..d68f25c179 100644 --- a/WebDriverAgent/PrivateHeaders/XCTest/XCTestManager_ManagerInterface-Protocol.h +++ b/WebDriverAgent/PrivateHeaders/XCTest/XCTestManager_ManagerInterface-Protocol.h @@ -27,6 +27,7 @@ - (void)_XCT_requestElementAtPoint:(CGPoint)arg1 reply:(void (^)(id/*XCAccessibilityElement*/, NSError *))arg2; - (void)_XCT_fetchParameterizedAttributeForElement:(id/*XCAccessibilityElement*/)arg1 attributes:(NSNumber *)arg2 parameter:(id)arg3 reply:(void (^)(id, NSError *))arg4; - (void)_XCT_setAttribute:(NSNumber *)arg1 value:(id)arg2 element:(id/*XCAccessibilityElement*/)arg3 reply:(void (^)(BOOL, NSError *))arg4; +- (void)_XCT_fetchAttributes:(id)attributes forElement:(id)element reply:(void (^)(NSDictionary *, NSError *))reply; - (void)_XCT_fetchAttributesForElement:(id/*XCAccessibilityElement*/)arg1 attributes:(NSArray *)arg2 reply:(void (^)(NSDictionary *, NSError *))arg3; - (void)_XCT_terminateApplicationWithBundleID:(NSString *)arg1 completion:(void (^)(NSError *))arg2; - (void)_XCT_performAccessibilityAction:(int)arg1 onElement:(id/*XCAccessibilityElement*/)arg2 withValue:(id)arg3 reply:(void (^)(NSError *))arg4; diff --git a/WebDriverAgent/README.md b/WebDriverAgent/README.md index 547559ebc8..a367763f77 100644 --- a/WebDriverAgent/README.md +++ b/WebDriverAgent/README.md @@ -40,7 +40,7 @@ Then, you find `WebDriverAgentRunner-Runner-sim-.zip` for iOS and `Web ## License -[`WebDriverAgent` is BSD-licensed](LICENSE). We also provide an additional [patent grant](PATENTS). +[`WebDriverAgent` is BSD-licensed](LICENSE). ## Third Party Sources diff --git a/WebDriverAgent/Scripts/build-webdriveragent.js b/WebDriverAgent/Scripts/build-webdriveragent.js index 1958b876da..b37bcbbc91 100644 --- a/WebDriverAgent/Scripts/build-webdriveragent.js +++ b/WebDriverAgent/Scripts/build-webdriveragent.js @@ -34,7 +34,7 @@ async function buildWebDriverAgent (xcodeVersion) { await exec('xcodebuild', ['clean', '-derivedDataPath', DERIVED_DATA_PATH, '-scheme', 'WebDriverAgentRunner'], { cwd: ROOT_DIR }); - } catch (ign) {} + } catch {} // Get Xcode version xcodeVersion = xcodeVersion || await xcode.getVersion(); diff --git a/WebDriverAgent/Scripts/build.sh b/WebDriverAgent/Scripts/build.sh old mode 100644 new mode 100755 index 64195368c3..698d58b006 --- a/WebDriverAgent/Scripts/build.sh +++ b/WebDriverAgent/Scripts/build.sh @@ -4,8 +4,7 @@ # All rights reserved. # # This source code is licensed under the BSD-style license found in the -# LICENSE file in the root directory of this source tree. An additional grant -# of patent rights can be found in the PATENTS file in the same directory. +# LICENSE file in the root directory of this source tree. # set -ex diff --git a/WebDriverAgent/Scripts/ci/build-real.sh b/WebDriverAgent/Scripts/ci/build-real.sh old mode 100644 new mode 100755 index 93eec11451..bb41b0b6f3 --- a/WebDriverAgent/Scripts/ci/build-real.sh +++ b/WebDriverAgent/Scripts/ci/build-real.sh @@ -1,7 +1,5 @@ #!/bin/bash -# To run build script for CI - xcodebuild clean build-for-testing \ -project WebDriverAgent.xcodeproj \ -derivedDataPath $DERIVED_DATA_PATH \ @@ -9,15 +7,18 @@ xcodebuild clean build-for-testing \ -destination "$DESTINATION" \ CODE_SIGNING_ALLOWED=NO ARCHS=arm64 -# Only .app is needed. - pushd $WD -# to remove test packages to refer to the device local instead of embedded ones -# XCTAutomationSupport.framework, XCTest.framewor, XCTestCore.framework, -# XCUIAutomation.framework, XCUnit.framework -rm -rf $SCHEME-Runner.app/Frameworks/XC*.framework - -zip -r $ZIP_PKG_NAME $SCHEME-Runner.app +# The reason why here excludes several frameworks are: +# - to remove test packages to refer to the device local instead of embedded ones +# XCTAutomationSupport.framework, XCTest.framewor, XCTestCore.framework, +# XCUIAutomation.framework, XCUnit.framework. +# This can be excluded only for real devices. +# - Xcode 16 started generating 5.9MB of 'Testing.framework', but it might not be necessary for WDA. +# - libXCTestSwiftSupport is used for Swift testing. WDA doesn't include Swift stuff, thus this is not needed. +zip -r $ZIP_PKG_NAME $SCHEME-Runner.app \ + -x "$SCHEME-Runner.app/Frameworks/XC*.framework*" \ + "$SCHEME-Runner.app/Frameworks/Testing.framework*" \ + "$SCHEME-Runner.app/Frameworks/libXCTestSwiftSupport.dylib" popd mv $WD/$ZIP_PKG_NAME ./ diff --git a/WebDriverAgent/Scripts/ci/build-sim.sh b/WebDriverAgent/Scripts/ci/build-sim.sh old mode 100644 new mode 100755 index de52abccf1..b04cb48b60 --- a/WebDriverAgent/Scripts/ci/build-sim.sh +++ b/WebDriverAgent/Scripts/ci/build-sim.sh @@ -1,19 +1,15 @@ #!/bin/bash -# To run build script for CI - xcodebuild clean build-for-testing \ -project WebDriverAgent.xcodeproj \ - -derivedDataPath wda_build \ + -derivedDataPath $DERIVED_DATA_PATH \ -scheme $SCHEME \ -destination "$DESTINATION" \ CODE_SIGNING_ALLOWED=NO ARCHS=$ARCHS -# simulator needs to build entire build files +pushd $WD -pushd wda_build -# to remove unnecessary space consuming files -rm -rf Build/Intermediates.noindex -zip -r $ZIP_PKG_NAME Build +# Simulators might have an issue to lauch if we drop frameworks even we don't use them. +zip -r $ZIP_PKG_NAME $SCHEME-Runner.app popd -mv wda_build/$ZIP_PKG_NAME ./ +mv $WD/$ZIP_PKG_NAME ./ diff --git a/WebDriverAgent/Scripts/fetch-prebuilt-wda.js b/WebDriverAgent/Scripts/fetch-prebuilt-wda.js index 8bedd9a3d5..4bd6840fac 100644 --- a/WebDriverAgent/Scripts/fetch-prebuilt-wda.js +++ b/WebDriverAgent/Scripts/fetch-prebuilt-wda.js @@ -47,7 +47,7 @@ async function fetchPrebuiltWebDriverAgentAssets () { try { const nameOfAgent = _.last(url.split('/')); agentsDownloading.push(downloadAgent(url, path.join(webdriveragentsDir, nameOfAgent))); - } catch (ign) { } + } catch { } } // Wait for them all to finish diff --git a/WebDriverAgent/WebDriverAgent.xcodeproj/project.pbxproj b/WebDriverAgent/WebDriverAgent.xcodeproj/project.pbxproj index bfc4868641..fa64f46fe2 100644 --- a/WebDriverAgent/WebDriverAgent.xcodeproj/project.pbxproj +++ b/WebDriverAgent/WebDriverAgent.xcodeproj/project.pbxproj @@ -7,6 +7,10 @@ objects = { /* Begin PBXBuildFile section */ + 0E0413382DF1E15100AF007C /* XCUIElement+FBMinMax.m in Sources */ = {isa = PBXBuildFile; fileRef = 0E0413372DF1E15100AF007C /* XCUIElement+FBMinMax.m */; }; + 0E0413392DF1E15100AF007C /* XCUIElement+FBMinMax.m in Sources */ = {isa = PBXBuildFile; fileRef = 0E0413372DF1E15100AF007C /* XCUIElement+FBMinMax.m */; }; + 0E04133B2DF1E15900AF007C /* XCUIElement+FBMinMax.h in Headers */ = {isa = PBXBuildFile; fileRef = 0E04133A2DF1E15900AF007C /* XCUIElement+FBMinMax.h */; }; + 0E04133C2DF1E15900AF007C /* XCUIElement+FBMinMax.h in Headers */ = {isa = PBXBuildFile; fileRef = 0E04133A2DF1E15900AF007C /* XCUIElement+FBMinMax.h */; }; 1357E296233D05240054BDB8 /* XCUIHitPointResult.h in Headers */ = {isa = PBXBuildFile; fileRef = 1357E295233D05240054BDB8 /* XCUIHitPointResult.h */; }; 1357E297233D05240054BDB8 /* XCUIHitPointResult.h in Headers */ = {isa = PBXBuildFile; fileRef = 1357E295233D05240054BDB8 /* XCUIHitPointResult.h */; }; 13815F6F2328D20400CDAB61 /* FBActiveAppDetectionPoint.h in Headers */ = {isa = PBXBuildFile; fileRef = 13815F6D2328D20400CDAB61 /* FBActiveAppDetectionPoint.h */; }; @@ -21,12 +25,12 @@ 13DE7A4A287C4005003243C6 /* FBXCDeviceEvent.h in Headers */ = {isa = PBXBuildFile; fileRef = 13DE7A47287C4005003243C6 /* FBXCDeviceEvent.h */; }; 13DE7A4B287C4005003243C6 /* FBXCDeviceEvent.m in Sources */ = {isa = PBXBuildFile; fileRef = 13DE7A48287C4005003243C6 /* FBXCDeviceEvent.m */; }; 13DE7A4C287C4005003243C6 /* FBXCDeviceEvent.m in Sources */ = {isa = PBXBuildFile; fileRef = 13DE7A48287C4005003243C6 /* FBXCDeviceEvent.m */; }; - 13DE7A4F287C46BB003243C6 /* FBXCElementSnapshot.h in Headers */ = {isa = PBXBuildFile; fileRef = 13DE7A4D287C46BB003243C6 /* FBXCElementSnapshot.h */; }; - 13DE7A50287C46BB003243C6 /* FBXCElementSnapshot.h in Headers */ = {isa = PBXBuildFile; fileRef = 13DE7A4D287C46BB003243C6 /* FBXCElementSnapshot.h */; }; + 13DE7A4F287C46BB003243C6 /* FBXCElementSnapshot.h in Headers */ = {isa = PBXBuildFile; fileRef = 13DE7A4D287C46BB003243C6 /* FBXCElementSnapshot.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 13DE7A50287C46BB003243C6 /* FBXCElementSnapshot.h in Headers */ = {isa = PBXBuildFile; fileRef = 13DE7A4D287C46BB003243C6 /* FBXCElementSnapshot.h */; settings = {ATTRIBUTES = (Public, ); }; }; 13DE7A51287C46BB003243C6 /* FBXCElementSnapshot.m in Sources */ = {isa = PBXBuildFile; fileRef = 13DE7A4E287C46BB003243C6 /* FBXCElementSnapshot.m */; }; 13DE7A52287C46BB003243C6 /* FBXCElementSnapshot.m in Sources */ = {isa = PBXBuildFile; fileRef = 13DE7A4E287C46BB003243C6 /* FBXCElementSnapshot.m */; }; - 13DE7A55287CA1EC003243C6 /* FBXCElementSnapshotWrapper.h in Headers */ = {isa = PBXBuildFile; fileRef = 13DE7A53287CA1EC003243C6 /* FBXCElementSnapshotWrapper.h */; }; - 13DE7A56287CA1EC003243C6 /* FBXCElementSnapshotWrapper.h in Headers */ = {isa = PBXBuildFile; fileRef = 13DE7A53287CA1EC003243C6 /* FBXCElementSnapshotWrapper.h */; }; + 13DE7A55287CA1EC003243C6 /* FBXCElementSnapshotWrapper.h in Headers */ = {isa = PBXBuildFile; fileRef = 13DE7A53287CA1EC003243C6 /* FBXCElementSnapshotWrapper.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 13DE7A56287CA1EC003243C6 /* FBXCElementSnapshotWrapper.h in Headers */ = {isa = PBXBuildFile; fileRef = 13DE7A53287CA1EC003243C6 /* FBXCElementSnapshotWrapper.h */; settings = {ATTRIBUTES = (Public, ); }; }; 13DE7A57287CA1EC003243C6 /* FBXCElementSnapshotWrapper.m in Sources */ = {isa = PBXBuildFile; fileRef = 13DE7A54287CA1EC003243C6 /* FBXCElementSnapshotWrapper.m */; }; 13DE7A58287CA1EC003243C6 /* FBXCElementSnapshotWrapper.m in Sources */ = {isa = PBXBuildFile; fileRef = 13DE7A54287CA1EC003243C6 /* FBXCElementSnapshotWrapper.m */; }; 13DE7A5B287CA444003243C6 /* FBXCElementSnapshotWrapper+Helpers.h in Headers */ = {isa = PBXBuildFile; fileRef = 13DE7A59287CA444003243C6 /* FBXCElementSnapshotWrapper+Helpers.h */; }; @@ -374,6 +378,10 @@ 7155D704211DCEF400166C20 /* FBMjpegServer.m in Sources */ = {isa = PBXBuildFile; fileRef = 7155D702211DCEF400166C20 /* FBMjpegServer.m */; }; 7157B291221DADD2001C348C /* FBXCAXClientProxy.h in Headers */ = {isa = PBXBuildFile; fileRef = 7157B28F221DADD2001C348C /* FBXCAXClientProxy.h */; }; 7157B292221DADD2001C348C /* FBXCAXClientProxy.m in Sources */ = {isa = PBXBuildFile; fileRef = 7157B290221DADD2001C348C /* FBXCAXClientProxy.m */; }; + 715A84CF2DD92AD3007134CC /* FBElementHelpers.m in Sources */ = {isa = PBXBuildFile; fileRef = 715A84CE2DD92AD3007134CC /* FBElementHelpers.m */; }; + 715A84D02DD92AD3007134CC /* FBElementHelpers.h in Headers */ = {isa = PBXBuildFile; fileRef = 715A84CD2DD92AD3007134CC /* FBElementHelpers.h */; }; + 715A84D12DD92AD3007134CC /* FBElementHelpers.m in Sources */ = {isa = PBXBuildFile; fileRef = 715A84CE2DD92AD3007134CC /* FBElementHelpers.m */; }; + 715A84D22DD92AD3007134CC /* FBElementHelpers.h in Headers */ = {isa = PBXBuildFile; fileRef = 715A84CD2DD92AD3007134CC /* FBElementHelpers.h */; }; 715AFAC11FFA29180053896D /* FBScreen.h in Headers */ = {isa = PBXBuildFile; fileRef = 715AFABF1FFA29180053896D /* FBScreen.h */; }; 715AFAC21FFA29180053896D /* FBScreen.m in Sources */ = {isa = PBXBuildFile; fileRef = 715AFAC01FFA29180053896D /* FBScreen.m */; }; 715AFAC41FFA2AAF0053896D /* FBScreenTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 715AFAC31FFA2AAF0053896D /* FBScreenTests.m */; }; @@ -451,6 +459,10 @@ 71A7EAFA1E224648001DA4F2 /* FBClassChainQueryParser.m in Sources */ = {isa = PBXBuildFile; fileRef = 71A7EAF81E224648001DA4F2 /* FBClassChainQueryParser.m */; }; 71A7EAFC1E229302001DA4F2 /* FBClassChainTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 71A7EAFB1E229302001DA4F2 /* FBClassChainTests.m */; }; 71ACF5B8242F2FDC00F0AAD4 /* FBSafariAlertTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 71ACF5B7242F2FDC00F0AAD4 /* FBSafariAlertTests.m */; }; + 71AE3CF72D38EE8E0039FC36 /* XCUIElement+FBVisibleFrame.h in Headers */ = {isa = PBXBuildFile; fileRef = 71AE3CF52D38EE8E0039FC36 /* XCUIElement+FBVisibleFrame.h */; }; + 71AE3CF82D38EE8E0039FC36 /* XCUIElement+FBVisibleFrame.m in Sources */ = {isa = PBXBuildFile; fileRef = 71AE3CF62D38EE8E0039FC36 /* XCUIElement+FBVisibleFrame.m */; }; + 71AE3CF92D38EE8E0039FC36 /* XCUIElement+FBVisibleFrame.h in Headers */ = {isa = PBXBuildFile; fileRef = 71AE3CF52D38EE8E0039FC36 /* XCUIElement+FBVisibleFrame.h */; }; + 71AE3CFA2D38EE8E0039FC36 /* XCUIElement+FBVisibleFrame.m in Sources */ = {isa = PBXBuildFile; fileRef = 71AE3CF62D38EE8E0039FC36 /* XCUIElement+FBVisibleFrame.m */; }; 71B155DA23070ECF00646AFB /* FBHTTPStatusCodes.h in Headers */ = {isa = PBXBuildFile; fileRef = 71B155D923070ECF00646AFB /* FBHTTPStatusCodes.h */; settings = {ATTRIBUTES = (Public, ); }; }; 71B155DC230711E900646AFB /* FBCommandStatus.m in Sources */ = {isa = PBXBuildFile; fileRef = 71B155DB230711E900646AFB /* FBCommandStatus.m */; }; 71B155DF23080CA600646AFB /* FBProtocolHelpers.h in Headers */ = {isa = PBXBuildFile; fileRef = 71B155DD23080CA600646AFB /* FBProtocolHelpers.h */; }; @@ -531,6 +543,10 @@ ADBC39981D07842800327304 /* XCUIElementDouble.m in Sources */ = {isa = PBXBuildFile; fileRef = ADBC39971D07842800327304 /* XCUIElementDouble.m */; }; ADDA07241D6BB2BF001700AC /* FBScrollViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = ADDA07231D6BB2BF001700AC /* FBScrollViewController.m */; }; ADEF63AF1D09DEBE0070A7E3 /* FBRuntimeUtilsTests.m in Sources */ = {isa = PBXBuildFile; fileRef = ADEF63AE1D09DEBE0070A7E3 /* FBRuntimeUtilsTests.m */; }; + B316351C2DDF0CF5007D9317 /* FBAccessibilityTraits.m in Sources */ = {isa = PBXBuildFile; fileRef = B316351B2DDF0CF5007D9317 /* FBAccessibilityTraits.m */; }; + B316351D2DDF0CF5007D9317 /* FBAccessibilityTraits.m in Sources */ = {isa = PBXBuildFile; fileRef = B316351B2DDF0CF5007D9317 /* FBAccessibilityTraits.m */; }; + B316351F2DDF0D0B007D9317 /* FBAccessibilityTraits.h in Headers */ = {isa = PBXBuildFile; fileRef = B316351E2DDF0D0B007D9317 /* FBAccessibilityTraits.h */; }; + B31635202DDF0D0B007D9317 /* FBAccessibilityTraits.h in Headers */ = {isa = PBXBuildFile; fileRef = B316351E2DDF0D0B007D9317 /* FBAccessibilityTraits.h */; }; C845206222D5E79400EA68CB /* FBUnattachedAppLauncher.h in Headers */ = {isa = PBXBuildFile; fileRef = C8FB547722D4C1FC00B69954 /* FBUnattachedAppLauncher.h */; }; C845206322D5E79700EA68CB /* FBUnattachedAppLauncher.m in Sources */ = {isa = PBXBuildFile; fileRef = C8FB547822D4C1FC00B69954 /* FBUnattachedAppLauncher.m */; }; C8FB547422D3949C00B69954 /* LSApplicationWorkspace.h in Headers */ = {isa = PBXBuildFile; fileRef = C8FB547322D3949C00B69954 /* LSApplicationWorkspace.h */; }; @@ -783,6 +799,7 @@ EE9B76591CF7987800275851 /* FBRouteTests.m in Sources */ = {isa = PBXBuildFile; fileRef = EE9B76571CF7987300275851 /* FBRouteTests.m */; }; EE9B768E1CF7997600275851 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = EE9B76831CF7997600275851 /* AppDelegate.m */; }; EE9B768F1CF7997600275851 /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = EE9B76851CF7997600275851 /* ViewController.m */; }; + AABBCCDDEEFF001122334457 /* SceneDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = AABBCCDDEEFF001122334456 /* SceneDelegate.m */; }; EE9B76911CF7997600275851 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = EE9B76871CF7997600275851 /* main.m */; }; EE9B76941CF7997600275851 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = EE9B768C1CF7997600275851 /* Main.storyboard */; }; EE9B769A1CF799F400275851 /* FBAlertTests.m in Sources */ = {isa = PBXBuildFile; fileRef = EE9B76991CF799F400275851 /* FBAlertTests.m */; }; @@ -906,6 +923,8 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + 0E0413372DF1E15100AF007C /* XCUIElement+FBMinMax.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "XCUIElement+FBMinMax.m"; sourceTree = ""; }; + 0E04133A2DF1E15900AF007C /* XCUIElement+FBMinMax.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "XCUIElement+FBMinMax.h"; sourceTree = ""; }; 1357E295233D05240054BDB8 /* XCUIHitPointResult.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = XCUIHitPointResult.h; sourceTree = ""; }; 13815F6D2328D20400CDAB61 /* FBActiveAppDetectionPoint.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = FBActiveAppDetectionPoint.h; sourceTree = ""; }; 13815F6E2328D20400CDAB61 /* FBActiveAppDetectionPoint.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FBActiveAppDetectionPoint.m; sourceTree = ""; }; @@ -1002,6 +1021,8 @@ 7155D702211DCEF400166C20 /* FBMjpegServer.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FBMjpegServer.m; sourceTree = ""; }; 7157B28F221DADD2001C348C /* FBXCAXClientProxy.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = FBXCAXClientProxy.h; sourceTree = ""; }; 7157B290221DADD2001C348C /* FBXCAXClientProxy.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FBXCAXClientProxy.m; sourceTree = ""; }; + 715A84CD2DD92AD3007134CC /* FBElementHelpers.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = FBElementHelpers.h; sourceTree = ""; }; + 715A84CE2DD92AD3007134CC /* FBElementHelpers.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FBElementHelpers.m; sourceTree = ""; }; 715AFABF1FFA29180053896D /* FBScreen.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = FBScreen.h; sourceTree = ""; }; 715AFAC01FFA29180053896D /* FBScreen.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FBScreen.m; sourceTree = ""; }; 715AFAC31FFA2AAF0053896D /* FBScreenTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FBScreenTests.m; sourceTree = ""; }; @@ -1050,6 +1071,8 @@ 71A7EAF81E224648001DA4F2 /* FBClassChainQueryParser.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FBClassChainQueryParser.m; sourceTree = ""; }; 71A7EAFB1E229302001DA4F2 /* FBClassChainTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FBClassChainTests.m; sourceTree = ""; }; 71ACF5B7242F2FDC00F0AAD4 /* FBSafariAlertTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FBSafariAlertTests.m; sourceTree = ""; }; + 71AE3CF52D38EE8E0039FC36 /* XCUIElement+FBVisibleFrame.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "XCUIElement+FBVisibleFrame.h"; sourceTree = ""; }; + 71AE3CF62D38EE8E0039FC36 /* XCUIElement+FBVisibleFrame.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "XCUIElement+FBVisibleFrame.m"; sourceTree = ""; }; 71B155D923070ECF00646AFB /* FBHTTPStatusCodes.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = FBHTTPStatusCodes.h; sourceTree = ""; }; 71B155DB230711E900646AFB /* FBCommandStatus.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FBCommandStatus.m; sourceTree = ""; }; 71B155DD23080CA600646AFB /* FBProtocolHelpers.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = FBProtocolHelpers.h; sourceTree = ""; }; @@ -1103,6 +1126,8 @@ ADDA07221D6BB2BF001700AC /* FBScrollViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FBScrollViewController.h; sourceTree = ""; }; ADDA07231D6BB2BF001700AC /* FBScrollViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FBScrollViewController.m; sourceTree = ""; }; ADEF63AE1D09DEBE0070A7E3 /* FBRuntimeUtilsTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FBRuntimeUtilsTests.m; sourceTree = ""; }; + B316351B2DDF0CF5007D9317 /* FBAccessibilityTraits.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FBAccessibilityTraits.m; sourceTree = ""; }; + B316351E2DDF0D0B007D9317 /* FBAccessibilityTraits.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = FBAccessibilityTraits.h; sourceTree = ""; }; C8FB547322D3949C00B69954 /* LSApplicationWorkspace.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LSApplicationWorkspace.h; sourceTree = ""; }; C8FB547722D4C1FC00B69954 /* FBUnattachedAppLauncher.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = FBUnattachedAppLauncher.h; sourceTree = ""; }; C8FB547822D4C1FC00B69954 /* FBUnattachedAppLauncher.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = FBUnattachedAppLauncher.m; sourceTree = ""; }; @@ -1344,6 +1369,8 @@ EE9B76581CF7987300275851 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; EE9B76821CF7997600275851 /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; EE9B76831CF7997600275851 /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; + AABBCCDDEEFF001122334455 /* SceneDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SceneDelegate.h; sourceTree = ""; }; + AABBCCDDEEFF001122334456 /* SceneDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SceneDelegate.m; sourceTree = ""; }; EE9B76841CF7997600275851 /* ViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = ""; }; EE9B76851CF7997600275851 /* ViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = ""; }; EE9B76861CF7997600275851 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; @@ -1767,6 +1794,8 @@ EE8DDD7C20C5733B004D4925 /* XCUIElement+FBForceTouch.m */, EE9AB7471CAEDF0C008C271F /* XCUIElement+FBIsVisible.h */, EE9AB7481CAEDF0C008C271F /* XCUIElement+FBIsVisible.m */, + 0E04133A2DF1E15900AF007C /* XCUIElement+FBMinMax.h */, + 0E0413372DF1E15100AF007C /* XCUIElement+FBMinMax.m */, 7136A4771E8918E60024FC3D /* XCUIElement+FBPickerWheel.h */, 7136A4781E8918E60024FC3D /* XCUIElement+FBPickerWheel.m */, 71D3B3D3267FC7260076473D /* XCUIElement+FBResolve.h */, @@ -1781,6 +1810,8 @@ 71B49EC61ED1A58100D51AD6 /* XCUIElement+FBUID.m */, EEE3763F1D59F81400ED88DD /* XCUIElement+FBUtilities.h */, EEE376401D59F81400ED88DD /* XCUIElement+FBUtilities.m */, + 71AE3CF52D38EE8E0039FC36 /* XCUIElement+FBVisibleFrame.h */, + 71AE3CF62D38EE8E0039FC36 /* XCUIElement+FBVisibleFrame.m */, EEE376471D59FAE900ED88DD /* XCUIElement+FBWebDriverAttributes.h */, EEE376481D59FAE900ED88DD /* XCUIElement+FBWebDriverAttributes.m */, 641EE7042240CDCF00173FCB /* XCUIElement+FBTVFocuse.h */, @@ -1904,6 +1935,8 @@ EE9B76A21CF7A43900275851 /* FBConfiguration.m */, EE7E27181D06C69F001BEC7B /* FBDebugLogDelegateDecorator.h */, EE7E27191D06C69F001BEC7B /* FBDebugLogDelegateDecorator.m */, + 715A84CD2DD92AD3007134CC /* FBElementHelpers.h */, + 715A84CE2DD92AD3007134CC /* FBElementHelpers.m */, EE9AB78F1CAEDF0C008C271F /* FBElementTypeTransformer.h */, EE9AB7901CAEDF0C008C271F /* FBElementTypeTransformer.m */, EE3A18601CDE618F00DE4205 /* FBErrorBuilder.h */, @@ -1963,6 +1996,8 @@ EE6B64FC1D0F86EF00E85F5D /* XCTestPrivateSymbols.m */, 633E904A220DEE7F007CADF9 /* XCUIApplicationProcessDelay.h */, 6385F4A5220A40760095BBDB /* XCUIApplicationProcessDelay.m */, + B316351B2DDF0CF5007D9317 /* FBAccessibilityTraits.m */, + B316351E2DDF0D0B007D9317 /* FBAccessibilityTraits.h */, ); name = Utilities; path = WebDriverAgentLib/Utilities; @@ -2075,6 +2110,8 @@ children = ( EE9B76821CF7997600275851 /* AppDelegate.h */, EE9B76831CF7997600275851 /* AppDelegate.m */, + AABBCCDDEEFF001122334455 /* SceneDelegate.h */, + AABBCCDDEEFF001122334456 /* SceneDelegate.m */, EE1E06E51D182E95007CF043 /* FBAlertViewController.h */, EE1E06E61D182E95007CF043 /* FBAlertViewController.m */, EE8BA9781DCCED9A00A9DEF8 /* FBNavigationController.h */, @@ -2276,6 +2313,8 @@ 641EE6392240C5CA00173FCB /* FBRouteRequest.h in Headers */, 648C10AC22AAAD9C00B81B9A /* UIKeyboardImpl.h in Headers */, 718226CD2587443700661B83 /* GCDAsyncSocket.h in Headers */, + 13DE7A50287C46BB003243C6 /* FBXCElementSnapshot.h in Headers */, + 13DE7A56287CA1EC003243C6 /* FBXCElementSnapshotWrapper.h in Headers */, 71F3E7D525417FF400E0C22B /* FBSettings.h in Headers */, 641EE63A2240C5CA00173FCB /* XCTest.h in Headers */, 641EE63B2240C5CA00173FCB /* FBAlertsMonitor.h in Headers */, @@ -2324,7 +2363,6 @@ 641EE6632240C5CA00173FCB /* FBUnknownCommands.h in Headers */, 641EE7062240CDCF00173FCB /* XCUIElement+FBTVFocuse.h in Headers */, 71822738258744B800661B83 /* HTTPConnection.h in Headers */, - 13DE7A56287CA1EC003243C6 /* FBXCElementSnapshotWrapper.h in Headers */, 641EE6642240C5CA00173FCB /* NSPredicate+FBFormat.h in Headers */, 641EE6652240C5CA00173FCB /* UILongPressGestureRecognizer-RecordingAdditions.h in Headers */, 641EE6662240C5CA00173FCB /* XCTestCase.h in Headers */, @@ -2346,11 +2384,13 @@ 641EE6732240C5CA00173FCB /* FBDebugCommands.h in Headers */, 641EE6742240C5CA00173FCB /* XCTestSuite.h in Headers */, 641EE6752240C5CA00173FCB /* XCUICoordinate.h in Headers */, + 715A84D22DD92AD3007134CC /* FBElementHelpers.h in Headers */, 641EE6762240C5CA00173FCB /* XCTNSPredicateExpectation.h in Headers */, 641EE6772240C5CA00173FCB /* XCTestObservationCenter.h in Headers */, 641EE6782240C5CA00173FCB /* XCTNSNotificationExpectation.h in Headers */, 641EE6792240C5CA00173FCB /* XCUIRecorderNodeFinder.h in Headers */, 641EE67A2240C5CA00173FCB /* XCUIElement+FBAccessibility.h in Headers */, + 0E04133C2DF1E15900AF007C /* XCUIElement+FBMinMax.h in Headers */, 641EE67B2240C5CA00173FCB /* XCUIRecorderUtilities.h in Headers */, 6496A5DA230D6EB30087F8CB /* AXSettings.h in Headers */, 641EE67C2240C5CA00173FCB /* XCTestCaseRun.h in Headers */, @@ -2399,9 +2439,11 @@ 641EE6A42240C5CA00173FCB /* FBCommandHandler.h in Headers */, 641EE6A52240C5CA00173FCB /* FBSessionCommands.h in Headers */, 641EE70C2240CE2D00173FCB /* FBTVNavigationTracker.h in Headers */, + 71AE3CF72D38EE8E0039FC36 /* XCUIElement+FBVisibleFrame.h in Headers */, 641EE6A62240C5CA00173FCB /* FBImageProcessor.h in Headers */, 641EE6A72240C5CA00173FCB /* FBSession-Private.h in Headers */, 641EE6A82240C5CA00173FCB /* NSString+FBXMLSafeString.h in Headers */, + B316351F2DDF0D0B007D9317 /* FBAccessibilityTraits.h in Headers */, 64E3502F2AC0B6FE005F3ACB /* NSDictionary+FBUtf8SafeDictionary.h in Headers */, 641EE6A92240C5CA00173FCB /* FBCommandStatus.h in Headers */, 71822702258744A400661B83 /* HTTPResponseProxy.h in Headers */, @@ -2483,7 +2525,6 @@ 641EE6E72240C5CA00173FCB /* XCUIElement+FBFind.h in Headers */, 641EE6E82240C5CA00173FCB /* XCTestManager_ManagerInterface-Protocol.h in Headers */, 641EE6E92240C5CA00173FCB /* FBFailureProofTestCase.h in Headers */, - 13DE7A50287C46BB003243C6 /* FBXCElementSnapshot.h in Headers */, 641EE6EA2240C5CA00173FCB /* XCTTestRunSessionDelegate-Protocol.h in Headers */, 641EE6EB2240C5CA00173FCB /* XCTestCaseSuite.h in Headers */, 641EE6EC2240C5CA00173FCB /* _XCInternalTestRun.h in Headers */, @@ -2554,6 +2595,7 @@ EE35AD721E3B77D600A02D78 /* XCUIElementHitPointCoordinate.h in Headers */, EE35AD3F1E3B77D600A02D78 /* XCTDarwinNotificationExpectation.h in Headers */, EE35AD5F1E3B77D600A02D78 /* XCTRunnerAutomationSession.h in Headers */, + 13DE7A4F287C46BB003243C6 /* FBXCElementSnapshot.h in Headers */, 71C9EAAC25E8415A00470CD8 /* FBScreenshot.h in Headers */, EE35AD371E3B77D600A02D78 /* XCSourceCodeTreeNodeEnumerator.h in Headers */, EE158AB01CBD456F00A3E3F0 /* XCUIElement+FBIsVisible.h in Headers */, @@ -2585,6 +2627,7 @@ 714EAA0D2673FDFE005C5B47 /* FBCapabilities.h in Headers */, EE35AD5C1E3B77D600A02D78 /* XCTNSPredicateExpectation.h in Headers */, EE35AD521E3B77D600A02D78 /* XCTestObservationCenter.h in Headers */, + 71AE3CF92D38EE8E0039FC36 /* XCUIElement+FBVisibleFrame.h in Headers */, EE35AD5B1E3B77D600A02D78 /* XCTNSNotificationExpectation.h in Headers */, E444DC97249131D40060D7EB /* HTTPServer.h in Headers */, E444DCAE24913C220060D7EB /* HTTPResponseProxy.h in Headers */, @@ -2595,6 +2638,7 @@ EE35AD781E3B77D600A02D78 /* XCUIRecorderUtilities.h in Headers */, EE35AD421E3B77D600A02D78 /* XCTestCaseRun.h in Headers */, EE35AD441E3B77D600A02D78 /* XCTestConfiguration.h in Headers */, + 715A84D02DD92AD3007134CC /* FBElementHelpers.h in Headers */, EE35AD0B1E3B77D600A02D78 /* _XCTDarwinNotificationExpectationImplementation.h in Headers */, 718226CA2587443700661B83 /* GCDAsyncUdpSocket.h in Headers */, EE35AD491E3B77D600A02D78 /* XCTestExpectation.h in Headers */, @@ -2649,7 +2693,6 @@ EE158AB81CBD456F00A3E3F0 /* FBAlertViewCommands.h in Headers */, EE35AD651E3B77D600A02D78 /* XCTWaiter.h in Headers */, EE35AD681E3B77D600A02D78 /* XCTWaiterManagement-Protocol.h in Headers */, - 13DE7A4F287C46BB003243C6 /* FBXCElementSnapshot.h in Headers */, EE35AD451E3B77D600A02D78 /* XCTestContext.h in Headers */, EE35AD661E3B77D600A02D78 /* XCTWaiterDelegate-Protocol.h in Headers */, EE35AD0E1E3B77D600A02D78 /* _XCTestExpectationImplementation.h in Headers */, @@ -2672,6 +2715,7 @@ EEE9B4721CD02B88009D2030 /* FBRunLoopSpinner.h in Headers */, EE3A18621CDE618F00DE4205 /* FBErrorBuilder.h in Headers */, EE35AD261E3B77D600A02D78 /* XCApplicationMonitor_iOS.h in Headers */, + 0E04133B2DF1E15900AF007C /* XCUIElement+FBMinMax.h in Headers */, EE3A18661CDE734B00DE4205 /* FBKeyboard.h in Headers */, AD6C269C1CF2494200F8B5FF /* XCUIApplication+FBHelpers.h in Headers */, 714D88CC2733FB970074A925 /* FBXMLGenerationOptions.h in Headers */, @@ -2692,6 +2736,7 @@ EE35AD571E3B77D600A02D78 /* XCTestSuiteRun.h in Headers */, EE35AD701E3B77D600A02D78 /* XCUIElementAsynchronousHandlerWrapper.h in Headers */, EE35AD4C1E3B77D600A02D78 /* XCTestLog.h in Headers */, + B31635202DDF0D0B007D9317 /* FBAccessibilityTraits.h in Headers */, 71BB58E82B96328700CB9BFE /* FBScreenRecordingRequest.h in Headers */, EE35AD231E3B77D600A02D78 /* UITapGestureRecognizer-RecordingAdditions.h in Headers */, EE35AD2A1E3B77D600A02D78 /* XCDebugLogDelegate-Protocol.h in Headers */, @@ -3153,6 +3198,7 @@ 641EE6082240C5CA00173FCB /* FBRuntimeUtils.m in Sources */, 641EE6092240C5CA00173FCB /* XCUIElement+FBUtilities.m in Sources */, 641EE60A2240C5CA00173FCB /* FBLogger.m in Sources */, + B316351D2DDF0CF5007D9317 /* FBAccessibilityTraits.m in Sources */, 641EE60B2240C5CA00173FCB /* FBCustomCommands.m in Sources */, 71BB58E42B9631F100CB9BFE /* FBScreenRecordingPromise.m in Sources */, 641EE60C2240C5CA00173FCB /* XCUIDevice+FBHelpers.m in Sources */, @@ -3160,6 +3206,8 @@ 641EE60E2240C5CA00173FCB /* XCUIElement+FBTyping.m in Sources */, 641EE60F2240C5CA00173FCB /* XCUIElement+FBAccessibility.m in Sources */, 641EE6102240C5CA00173FCB /* FBImageUtils.m in Sources */, + 71AE3CF82D38EE8E0039FC36 /* XCUIElement+FBVisibleFrame.m in Sources */, + 715A84D12DD92AD3007134CC /* FBElementHelpers.m in Sources */, 641EE6112240C5CA00173FCB /* FBSession.m in Sources */, 641EE6122240C5CA00173FCB /* FBFindElementCommands.m in Sources */, 71A5C67629A4F39600421C37 /* XCTIssue+FBPatcher.m in Sources */, @@ -3169,6 +3217,7 @@ 71BB58F92B96531900CB9BFE /* FBScreenRecordingContainer.m in Sources */, 641EE6152240C5CA00173FCB /* XCUIElement+FBScrolling.m in Sources */, 641EE6162240C5CA00173FCB /* FBSessionCommands.m in Sources */, + 0E0413392DF1E15100AF007C /* XCUIElement+FBMinMax.m in Sources */, 641EE6192240C5CA00173FCB /* FBConfiguration.m in Sources */, 641EE61A2240C5CA00173FCB /* FBElementCache.m in Sources */, 71F5BE26252E576C00EE9EBA /* XCUIElement+FBSwiping.m in Sources */, @@ -3216,6 +3265,7 @@ 13DE7A45287C2A8D003243C6 /* FBXCAccessibilityElement.m in Sources */, 641EE70E2240CE4800173FCB /* FBTVNavigationTracker.m in Sources */, 71BD20741F86116100B36EC2 /* XCUIApplication+FBTouchAction.m in Sources */, + 0E0413382DF1E15100AF007C /* XCUIElement+FBMinMax.m in Sources */, EE158AE71CBD456F00A3E3F0 /* FBWebServer.m in Sources */, 715557D4211DBCE700613B26 /* FBTCPSocket.m in Sources */, EE3A18631CDE618F00DE4205 /* FBErrorBuilder.m in Sources */, @@ -3232,8 +3282,10 @@ 713AE576243A53BE0000D657 /* FBW3CActionsHelpers.m in Sources */, 71B155E123080CA600646AFB /* FBProtocolHelpers.m in Sources */, EE158AB11CBD456F00A3E3F0 /* XCUIElement+FBIsVisible.m in Sources */, + 71AE3CFA2D38EE8E0039FC36 /* XCUIElement+FBVisibleFrame.m in Sources */, EEBBD48C1D47746D00656A81 /* XCUIElement+FBFind.m in Sources */, EE158ADD1CBD456F00A3E3F0 /* FBResponsePayload.m in Sources */, + B316351C2DDF0CF5007D9317 /* FBAccessibilityTraits.m in Sources */, E444DCB524913C220060D7EB /* RouteRequest.m in Sources */, C8FB547A22D4C1FC00B69954 /* FBUnattachedAppLauncher.m in Sources */, EE158ADF1CBD456F00A3E3F0 /* FBRoute.m in Sources */, @@ -3302,6 +3354,7 @@ EE158AB31CBD456F00A3E3F0 /* XCUIElement+FBScrolling.m in Sources */, 718226CE2587443700661B83 /* GCDAsyncSocket.m in Sources */, EE158AC91CBD456F00A3E3F0 /* FBSessionCommands.m in Sources */, + 715A84CF2DD92AD3007134CC /* FBElementHelpers.m in Sources */, EE9B76A71CF7A43900275851 /* FBConfiguration.m in Sources */, E444DC9C249131D40060D7EB /* HTTPServer.m in Sources */, 71414ED82670A1EE003A8C5D /* LRUCache.m in Sources */, @@ -3405,6 +3458,7 @@ buildActionMask = 2147483647; files = ( EE9B768E1CF7997600275851 /* AppDelegate.m in Sources */, + AABBCCDDEEFF001122334457 /* SceneDelegate.m in Sources */, EE1E06E71D182E95007CF043 /* FBAlertViewController.m in Sources */, 315A15072518CC2800A3A064 /* TouchSpotView.m in Sources */, EE9B76911CF7997600275851 /* main.m in Sources */, @@ -3525,7 +3579,6 @@ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = "iPhone Developer"; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - DEVELOPMENT_TEAM = 48LP2W34XH; ENABLE_TESTING_SEARCH_PATHS = YES; GCC_C_LANGUAGE_STANDARD = gnu11; INFOPLIST_FILE = WebDriverAgentRunner/Info.plist; @@ -3540,7 +3593,7 @@ ); MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; - PRODUCT_BUNDLE_IDENTIFIER = com.vkqa.WebDriverAgentRunner; + PRODUCT_BUNDLE_IDENTIFIER = com.facebook.WebDriverAgentRunner; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = appletvos; TARGETED_DEVICE_FAMILY = 3; @@ -3586,7 +3639,6 @@ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = "iPhone Developer"; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - DEVELOPMENT_TEAM = 48LP2W34XH; ENABLE_TESTING_SEARCH_PATHS = YES; GCC_C_LANGUAGE_STANDARD = gnu11; INFOPLIST_FILE = WebDriverAgentRunner/Info.plist; @@ -3601,7 +3653,7 @@ ); MTL_FAST_MATH = YES; ONLY_ACTIVE_ARCH = YES; - PRODUCT_BUNDLE_IDENTIFIER = com.vkqa.WebDriverAgentRunner; + PRODUCT_BUNDLE_IDENTIFIER = com.facebook.WebDriverAgentRunner; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = appletvos; TARGETED_DEVICE_FAMILY = 3; @@ -3662,7 +3714,7 @@ /Developer/Library/Frameworks, ); OTHER_LDFLAGS = ""; - PRODUCT_BUNDLE_IDENTIFIER = com.vkqa.WebDriverAgentLib; + PRODUCT_BUNDLE_IDENTIFIER = com.facebook.WebDriverAgentLib; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = appletvos; SKIP_INSTALL = YES; @@ -3729,7 +3781,7 @@ ); ONLY_ACTIVE_ARCH = YES; OTHER_LDFLAGS = ""; - PRODUCT_BUNDLE_IDENTIFIER = com.vkqa.WebDriverAgentLib; + PRODUCT_BUNDLE_IDENTIFIER = com.facebook.WebDriverAgentLib; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE_SPECIFIER = ""; SDKROOT = appletvos; @@ -3960,11 +4012,9 @@ baseConfigurationReference = EEE5CABF1C80361500CBBDD9 /* IOSSettings.xcconfig */; buildSettings = { CLANG_STATIC_ANALYZER_MODE = deep; - CODE_SIGN_IDENTITY = "Apple Development"; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = NO; - DEVELOPMENT_TEAM = 48LP2W34XH; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; @@ -3986,7 +4036,7 @@ /System/Developer/Library/Frameworks, ); OTHER_LDFLAGS = ""; - PRODUCT_BUNDLE_IDENTIFIER = com.vkqa.WebDriverAgentLib; + PRODUCT_BUNDLE_IDENTIFIER = com.facebook.WebDriverAgentLib; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; VERSIONING_SYSTEM = "apple-generic"; @@ -4027,10 +4077,8 @@ baseConfigurationReference = EEE5CABF1C80361500CBBDD9 /* IOSSettings.xcconfig */; buildSettings = { CLANG_STATIC_ANALYZER_MODE = deep; - CODE_SIGN_IDENTITY = "Apple Development"; CURRENT_PROJECT_VERSION = 1; DEFINES_MODULE = NO; - DEVELOPMENT_TEAM = 48LP2W34XH; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; @@ -4053,7 +4101,7 @@ ); ONLY_ACTIVE_ARCH = YES; OTHER_LDFLAGS = ""; - PRODUCT_BUNDLE_IDENTIFIER = com.vkqa.WebDriverAgentLib; + PRODUCT_BUNDLE_IDENTIFIER = com.facebook.WebDriverAgentLib; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; VERSIONING_SYSTEM = "apple-generic"; @@ -4207,6 +4255,7 @@ CLANG_ANALYZER_NONNULL = YES; DEBUG_INFORMATION_FORMAT = dwarf; INFOPLIST_FILE = WebDriverAgentTests/IntegrationApp/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -4223,6 +4272,7 @@ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ANALYZER_NONNULL = YES; INFOPLIST_FILE = WebDriverAgentTests/IntegrationApp/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -4277,7 +4327,6 @@ buildSettings = { CLANG_STATIC_ANALYZER_MODE = deep; DEBUG_INFORMATION_FORMAT = dwarf; - DEVELOPMENT_TEAM = 48LP2W34XH; ENABLE_TESTING_SEARCH_PATHS = YES; FRAMEWORK_SEARCH_PATHS = "$(inherited)"; INFOPLIST_FILE = WebDriverAgentRunner/Info.plist; @@ -4294,7 +4343,7 @@ "$(inherited)", "-all_load", ); - PRODUCT_BUNDLE_IDENTIFIER = com.vkqa.WebDriverAgentRunner; + PRODUCT_BUNDLE_IDENTIFIER = com.facebook.WebDriverAgentRunner; PRODUCT_NAME = "$(TARGET_NAME)"; USES_XCTRUNNER = YES; WARNING_CFLAGS = ( @@ -4330,7 +4379,6 @@ baseConfigurationReference = EEE5CABF1C80361500CBBDD9 /* IOSSettings.xcconfig */; buildSettings = { CLANG_STATIC_ANALYZER_MODE = deep; - DEVELOPMENT_TEAM = 48LP2W34XH; ENABLE_TESTING_SEARCH_PATHS = YES; FRAMEWORK_SEARCH_PATHS = "$(inherited)"; INFOPLIST_FILE = WebDriverAgentRunner/Info.plist; @@ -4348,7 +4396,7 @@ "$(inherited)", "-all_load", ); - PRODUCT_BUNDLE_IDENTIFIER = com.vkqa.WebDriverAgentRunner; + PRODUCT_BUNDLE_IDENTIFIER = com.facebook.WebDriverAgentRunner; PRODUCT_NAME = "$(TARGET_NAME)"; USES_XCTRUNNER = YES; WARNING_CFLAGS = ( diff --git a/WebDriverAgent/WebDriverAgent.xcodeproj/xcshareddata/xcschemes/WebDriverAgentRunner.xcscheme b/WebDriverAgent/WebDriverAgent.xcodeproj/xcshareddata/xcschemes/WebDriverAgentRunner.xcscheme index 8857b934cf..4c2919f78f 100644 --- a/WebDriverAgent/WebDriverAgent.xcodeproj/xcshareddata/xcschemes/WebDriverAgentRunner.xcscheme +++ b/WebDriverAgent/WebDriverAgent.xcodeproj/xcshareddata/xcschemes/WebDriverAgentRunner.xcscheme @@ -66,6 +66,11 @@ value = "$(USE_PORT)" isEnabled = "YES"> + + + + snapshot, NSArray *types); @@ -65,10 +68,17 @@ - (NSString *)fb_description } - (id)fb_attributeValue:(NSString *)attribute + error:(NSError **)error { + NSDate *start = [NSDate date]; NSDictionary *result = [FBXCAXClientProxy.sharedClient attributesForElement:[self accessibilityElement] - attributes:@[attribute]]; - return result[attribute]; + attributes:@[attribute] + error:error]; + NSTimeInterval elapsed = ABS([start timeIntervalSinceNow]); + if (elapsed > ATTRIBUTE_FETCH_WARN_TIME_LIMIT) { + NSLog(@"! Fetching of %@ value for %@ took %@s", attribute, self.fb_description, @(elapsed)); + } + return [result objectForKey:attribute]; } inline static BOOL areValuesEqual(id value1, id value2); @@ -140,29 +150,6 @@ - (BOOL)fb_framelessFuzzyMatchesElement:(id)snapshot return targetCellSnapshot; } -- (CGRect)fb_visibleFrameWithFallback -{ - CGRect thisVisibleFrame = [self visibleFrame]; - if (!CGRectIsEmpty(thisVisibleFrame)) { - return thisVisibleFrame; - } - - NSDictionary *visibleFrameDict = (NSDictionary*)[self fb_attributeValue:@"XC_kAXXCAttributeVisibleFrame"]; - if (visibleFrameDict == nil) { - return thisVisibleFrame; - } - - id x = [visibleFrameDict objectForKey:@"X"]; - id y = [visibleFrameDict objectForKey:@"Y"]; - id height = [visibleFrameDict objectForKey:@"Height"]; - id width = [visibleFrameDict objectForKey:@"Width"]; - if (x != nil && y != nil && height != nil && width != nil) { - return CGRectMake([x doubleValue], [y doubleValue], [width doubleValue], [height doubleValue]); - } - - return thisVisibleFrame; -} - - (NSValue *)fb_hitPoint { NSError *error; diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/NSDictionary+FBUtf8SafeDictionary.h b/WebDriverAgent/WebDriverAgentLib/Categories/NSDictionary+FBUtf8SafeDictionary.h index 0f657ab6f1..cb2b539a1a 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/NSDictionary+FBUtf8SafeDictionary.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/NSDictionary+FBUtf8SafeDictionary.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/NSDictionary+FBUtf8SafeDictionary.m b/WebDriverAgent/WebDriverAgentLib/Categories/NSDictionary+FBUtf8SafeDictionary.m index 399769142e..0a5905daf8 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/NSDictionary+FBUtf8SafeDictionary.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/NSDictionary+FBUtf8SafeDictionary.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "NSDictionary+FBUtf8SafeDictionary.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/NSExpression+FBFormat.h b/WebDriverAgent/WebDriverAgentLib/Categories/NSExpression+FBFormat.h index feafbac458..274d420118 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/NSExpression+FBFormat.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/NSExpression+FBFormat.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/NSExpression+FBFormat.m b/WebDriverAgent/WebDriverAgentLib/Categories/NSExpression+FBFormat.m index 81858d65aa..d4c32aeba5 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/NSExpression+FBFormat.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/NSExpression+FBFormat.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "NSExpression+FBFormat.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/NSString+FBVisualLength.h b/WebDriverAgent/WebDriverAgentLib/Categories/NSString+FBVisualLength.h index a24eb690ae..ec065e28f4 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/NSString+FBVisualLength.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/NSString+FBVisualLength.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/NSString+FBVisualLength.m b/WebDriverAgent/WebDriverAgentLib/Categories/NSString+FBVisualLength.m index 9487bbebe3..652f1a06a8 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/NSString+FBVisualLength.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/NSString+FBVisualLength.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "NSString+FBVisualLength.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/NSString+FBXMLSafeString.h b/WebDriverAgent/WebDriverAgentLib/Categories/NSString+FBXMLSafeString.h index e51407b793..7cdceb7962 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/NSString+FBXMLSafeString.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/NSString+FBXMLSafeString.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/NSString+FBXMLSafeString.m b/WebDriverAgent/WebDriverAgentLib/Categories/NSString+FBXMLSafeString.m index cdc7ab3b5f..dbb7573f06 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/NSString+FBXMLSafeString.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/NSString+FBXMLSafeString.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "NSString+FBXMLSafeString.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCAXClient_iOS+FBSnapshotReqParams.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCAXClient_iOS+FBSnapshotReqParams.h index 8080f20975..d984e0b9e9 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCAXClient_iOS+FBSnapshotReqParams.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCAXClient_iOS+FBSnapshotReqParams.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCAXClient_iOS+FBSnapshotReqParams.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCAXClient_iOS+FBSnapshotReqParams.m index 3dc6754d56..0d39ba0b21 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCAXClient_iOS+FBSnapshotReqParams.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCAXClient_iOS+FBSnapshotReqParams.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCAXClient_iOS+FBSnapshotReqParams.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCTIssue+FBPatcher.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCTIssue+FBPatcher.h index b4cdf1d44c..fc81daa045 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCTIssue+FBPatcher.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCTIssue+FBPatcher.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCTIssue+FBPatcher.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCTIssue+FBPatcher.m index a3b0993096..70472e4a21 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCTIssue+FBPatcher.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCTIssue+FBPatcher.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCTIssue+FBPatcher.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBAlert.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBAlert.h index 7c057699b9..01bea467d6 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBAlert.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBAlert.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBAlert.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBAlert.m index 38b6586ef2..36628bc611 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBAlert.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBAlert.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIApplication+FBAlert.h" @@ -52,7 +51,7 @@ - (nullable XCUIElement *)fb_alertElementFromSafariWithScrollView:(XCUIElement * // and conatins at least one text view __block NSUInteger buttonsCount = 0; __block NSUInteger textViewsCount = 0; - id snapshot = candidate.fb_cachedSnapshot ?: candidate.fb_takeSnapshot; + id snapshot = candidate.fb_cachedSnapshot ?: [candidate fb_customSnapshot]; [snapshot enumerateDescendantsUsingBlock:^(id descendant) { XCUIElementType curType = descendant.elementType; if (curType == XCUIElementTypeButton) { @@ -73,7 +72,7 @@ - (XCUIElement *)fb_alertElement if (nil == alert) { return nil; } - id alertSnapshot = alert.fb_cachedSnapshot ?: alert.fb_takeSnapshot; + id alertSnapshot = alert.fb_cachedSnapshot ?: [alert fb_customSnapshot]; if (alertSnapshot.elementType == XCUIElementTypeAlert) { return alert; diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBFocused.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBFocused.h index 6951e760c4..4df5025c08 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBFocused.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBFocused.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBHelpers.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBHelpers.h index 54d4bd2816..f5d358ff90 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBHelpers.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBHelpers.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBHelpers.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBHelpers.m index 6cdae945bd..e5abde9057 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBHelpers.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBHelpers.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIApplication+FBHelpers.h" @@ -37,9 +36,21 @@ #import "XCUIElement+FBUtilities.h" #import "XCUIElement+FBWebDriverAttributes.h" #import "XCUIElementQuery.h" +#import "FBElementHelpers.h" static NSString* const FBUnknownBundleId = @"unknown"; +static NSString* const FBExclusionAttributeFrame = @"frame"; +static NSString* const FBExclusionAttributeEnabled = @"enabled"; +static NSString* const FBExclusionAttributeVisible = @"visible"; +static NSString* const FBExclusionAttributeAccessible = @"accessible"; +static NSString* const FBExclusionAttributeFocused = @"focused"; +static NSString* const FBExclusionAttributePlaceholderValue = @"placeholderValue"; +static NSString* const FBExclusionAttributeNativeFrame = @"nativeFrame"; +static NSString* const FBExclusionAttributeTraits = @"traits"; +static NSString* const FBExclusionAttributeMinValue = @"minValue"; +static NSString* const FBExclusionAttributeMaxValue = @"maxValue"; + _Nullable id extractIssueProperty(id issue, NSString *propertyName) { SEL selector = NSSelectorFromString(propertyName); NSMethodSignature *methodSignature = [issue methodSignatureForSelector:selector]; @@ -88,6 +99,17 @@ _Nullable id extractIssueProperty(id issue, NSString *propertyName) { return result; } +NSDictionary *customExclusionAttributesMap(void) { + static dispatch_once_t onceToken; + static NSDictionary *result; + dispatch_once(&onceToken, ^{ + result = @{ + FBExclusionAttributeVisible: FB_XCAXAIsVisibleAttributeName, + FBExclusionAttributeAccessible: FB_XCAXAIsElementAttributeName, + }; + }); + return result; +} @implementation XCUIApplication (FBHelpers) @@ -156,25 +178,23 @@ - (NSDictionary *)fb_tree return [self fb_tree:nil]; } -- (NSDictionary *)fb_tree:(nullable NSSet *) excludedAttributes +- (NSDictionary *)fb_tree:(nullable NSSet *)excludedAttributes { - id snapshot = self.fb_isResolvedFromCache.boolValue - ? self.lastSnapshot - : [self fb_snapshotWithAllAttributesAndMaxDepth:nil]; - return [self.class dictionaryForElement:snapshot recursive:YES excludedAttributes:excludedAttributes]; + id snapshot = [self fb_standardSnapshot]; + return [self.class dictionaryForElement:snapshot + recursive:YES + excludedAttributes:excludedAttributes]; } - (NSDictionary *)fb_accessibilityTree { - id snapshot = self.fb_isResolvedFromCache.boolValue - ? self.lastSnapshot - : [self fb_snapshotWithAllAttributesAndMaxDepth:nil]; + id snapshot = [self fb_standardSnapshot]; return [self.class accessibilityInfoForElement:snapshot]; } + (NSDictionary *)dictionaryForElement:(id)snapshot recursive:(BOOL)recursive - excludedAttributes:(nullable NSSet *) excludedAttributes + excludedAttributes:(nullable NSSet *)excludedAttributes { NSMutableDictionary *info = [[NSMutableDictionary alloc] init]; info[@"type"] = [FBElementTypeTransformer shortStringWithElementType:snapshot.elementType]; @@ -185,28 +205,21 @@ + (NSDictionary *)dictionaryForElement:(id)snapshot info[@"label"] = FBValueOrNull(wrappedSnapshot.wdLabel); info[@"rect"] = wrappedSnapshot.wdRect; - NSDictionary *attributeBlocks = @{ - @"frame": ^{ - return NSStringFromCGRect(wrappedSnapshot.wdFrame); - }, - @"enabled": ^{ - return [@([wrappedSnapshot isWDEnabled]) stringValue]; - }, - @"visible": ^{ - return [@([wrappedSnapshot isWDVisible]) stringValue]; - }, - @"accessible": ^{ - return [@([wrappedSnapshot isWDAccessible]) stringValue]; - }, - @"focused": ^{ - return [@([wrappedSnapshot isWDFocused]) stringValue]; - } - }; + NSDictionary *attributeBlocks = [self fb_attributeBlockMapForWrappedSnapshot:wrappedSnapshot]; + + NSSet *nonPrefixedKeys = [NSSet setWithObjects: + FBExclusionAttributeFrame, + FBExclusionAttributePlaceholderValue, + FBExclusionAttributeNativeFrame, + FBExclusionAttributeTraits, + FBExclusionAttributeMinValue, + FBExclusionAttributeMaxValue, + nil]; for (NSString *key in attributeBlocks) { if (excludedAttributes == nil || ![excludedAttributes containsObject:key]) { NSString *value = ((NSString * (^)(void))attributeBlocks[key])(); - if ([key isEqualToString:@"frame"]) { + if ([nonPrefixedKeys containsObject:key]) { info[key] = value; } else { info[[NSString stringWithFormat:@"is%@", [key capitalizedString]]] = value; @@ -222,14 +235,69 @@ + (NSDictionary *)dictionaryForElement:(id)snapshot if ([childElements count]) { info[@"children"] = [[NSMutableArray alloc] init]; for (id childSnapshot in childElements) { - [info[@"children"] addObject:[self dictionaryForElement:childSnapshot - recursive:YES - excludedAttributes:excludedAttributes]]; + @autoreleasepool { + [info[@"children"] addObject:[self dictionaryForElement:childSnapshot + recursive:YES + excludedAttributes:excludedAttributes]]; + } } } return info; } +// Helper used by `dictionaryForElement:` to assemble attribute value blocks, +// including both common attributes and conditionally included ones like placeholderValue. ++ (NSDictionary *)fb_attributeBlockMapForWrappedSnapshot:(FBXCElementSnapshotWrapper *)wrappedSnapshot + +{ + // Base attributes common to every element + NSMutableDictionary *blocks = + [@{ + FBExclusionAttributeFrame: ^{ + return NSStringFromCGRect(wrappedSnapshot.wdFrame); + }, + FBExclusionAttributeNativeFrame: ^{ + return NSStringFromCGRect(wrappedSnapshot.wdNativeFrame); + }, + FBExclusionAttributeEnabled: ^{ + return [@([wrappedSnapshot isWDEnabled]) stringValue]; + }, + FBExclusionAttributeVisible: ^{ + return [@([wrappedSnapshot isWDVisible]) stringValue]; + }, + FBExclusionAttributeAccessible: ^{ + return [@([wrappedSnapshot isWDAccessible]) stringValue]; + }, + FBExclusionAttributeFocused: ^{ + return [@([wrappedSnapshot isWDFocused]) stringValue]; + }, + FBExclusionAttributeTraits: ^{ + return wrappedSnapshot.wdTraits; + } + } mutableCopy]; + + XCUIElementType elementType = wrappedSnapshot.elementType; + + // Text-input placeholder (only for elements that support inner text) + if (FBDoesElementSupportInnerText(elementType)) { + blocks[FBExclusionAttributePlaceholderValue] = ^{ + return (NSString *)FBValueOrNull(wrappedSnapshot.wdPlaceholderValue); + }; + } + + // Only for elements that support min/max value + if (FBDoesElementSupportMinMaxValue(elementType)) { + blocks[FBExclusionAttributeMinValue] = ^{ + return wrappedSnapshot.wdMinValue; + }; + blocks[FBExclusionAttributeMaxValue] = ^{ + return wrappedSnapshot.wdMaxValue; + }; + } + + return [blocks copy]; +} + + (NSDictionary *)accessibilityInfoForElement:(id)snapshot { FBXCElementSnapshotWrapper *wrappedSnapshot = [FBXCElementSnapshotWrapper ensureWrapped:snapshot]; @@ -246,9 +314,11 @@ + (NSDictionary *)accessibilityInfoForElement:(id)snapshot } else { NSMutableArray *children = [[NSMutableArray alloc] init]; for (id childSnapshot in snapshot.children) { - NSDictionary *childInfo = [self accessibilityInfoForElement:childSnapshot]; - if ([childInfo count]) { - [children addObject: childInfo]; + @autoreleasepool { + NSDictionary *childInfo = [self accessibilityInfoForElement:childSnapshot]; + if ([childInfo count]) { + [children addObject: childInfo]; + } } } if ([children count]) { @@ -396,35 +466,41 @@ - (BOOL)fb_dismissKeyboardWithKeyNames:(nullable NSArray *)keyNames return nil; } + // These custom attributes could take too long to fetch, thus excluded + NSSet *customAttributesToExclude = [NSSet setWithArray:[customExclusionAttributesMap() allKeys]]; NSMutableArray *resultArray = [NSMutableArray array]; NSMethodSignature *methodSignature = [self methodSignatureForSelector:selector]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature]; [invocation setSelector:selector]; [invocation setArgument:&auditTypes atIndex:2]; BOOL (^issueHandler)(id) = ^BOOL(id issue) { - NSString *auditType = @""; - NSDictionary *valuesToNamesMap = auditTypeValuesToNames(); - NSNumber *auditTypeValue = [issue valueForKey:@"auditType"]; - if (nil != auditTypeValue) { - auditType = valuesToNamesMap[auditTypeValue] ?: [auditTypeValue stringValue]; - } - - id extractedElement = extractIssueProperty(issue, @"element"); - - id elementSnapshot = [extractedElement fb_takeSnapshot]; - NSDictionary *elementAttributes = elementSnapshot - ? [self.class dictionaryForElement:elementSnapshot recursive:NO excludedAttributes:nil] + @autoreleasepool { + NSString *auditType = @""; + NSDictionary *valuesToNamesMap = auditTypeValuesToNames(); + NSNumber *auditTypeValue = [issue valueForKey:@"auditType"]; + if (nil != auditTypeValue) { + auditType = valuesToNamesMap[auditTypeValue] ?: [auditTypeValue stringValue]; + } + + id extractedElement = extractIssueProperty(issue, @"element"); + + id elementSnapshot = [extractedElement fb_cachedSnapshot] ?: [extractedElement fb_standardSnapshot]; + NSDictionary *elementAttributes = elementSnapshot + ? [self.class dictionaryForElement:elementSnapshot + recursive:NO + excludedAttributes:customAttributesToExclude] : @{}; - - [resultArray addObject:@{ - @"detailedDescription": extractIssueProperty(issue, @"detailedDescription") ?: @"", - @"compactDescription": extractIssueProperty(issue, @"compactDescription") ?: @"", - @"auditType": auditType, - @"element": [extractedElement description] ?: @"", - @"elementDescription": [extractedElement debugDescription] ?: @"", - @"elementAttributes": elementAttributes ?: @{}, - }]; - return YES; + + [resultArray addObject:@{ + @"detailedDescription": extractIssueProperty(issue, @"detailedDescription") ?: @"", + @"compactDescription": extractIssueProperty(issue, @"compactDescription") ?: @"", + @"auditType": auditType, + @"element": [extractedElement description] ?: @"", + @"elementDescription": [extractedElement debugDescription] ?: @"", + @"elementAttributes": elementAttributes ?: @{}, + }]; + return YES; + } }; [invocation setArgument:&issueHandler atIndex:3]; [invocation setArgument:&error atIndex:4]; @@ -544,23 +620,17 @@ + (BOOL)fb_switchToSystemApplicationWithError:(NSError **)error { XCUIApplication *systemApp = self.fb_systemApplication; @try { - if (!systemApp.running) { - [systemApp launch]; - } else { + if (systemApp.running) { [systemApp activate]; + } else { + [systemApp launch]; } } @catch (NSException *e) { return [[[FBErrorBuilder alloc] withDescription:nil == e ? @"Cannot open the home screen" : e.reason] buildError:error]; } - return [[[[FBRunLoopSpinner new] - timeout:5] - timeoutErrorMessage:@"Timeout waiting until the home screen is visible"] - spinUntilTrue:^BOOL{ - return [systemApp fb_isSameAppAs:self.fb_activeApplication]; - } - error:error]; + return YES; } - (BOOL)fb_isSameAppAs:(nullable XCUIApplication *)otherApp diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBQuiescence.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBQuiescence.h index ef036053ee..962a481464 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBQuiescence.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBQuiescence.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBQuiescence.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBQuiescence.m index 66f1f118bf..72febaa51d 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBQuiescence.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBQuiescence.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIApplication+FBQuiescence.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBTouchAction.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBTouchAction.h index 6be298b498..79b220c507 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBTouchAction.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBTouchAction.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBTouchAction.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBTouchAction.m index 622dac479e..bbd1e5746b 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBTouchAction.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBTouchAction.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBUIInterruptions.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBUIInterruptions.h index 2078d8c20c..e95273216b 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBUIInterruptions.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBUIInterruptions.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBUIInterruptions.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBUIInterruptions.m index 5d48dffa64..b662a1e5a9 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBUIInterruptions.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplication+FBUIInterruptions.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIApplication+FBUIInterruptions.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplicationProcess+FBQuiescence.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplicationProcess+FBQuiescence.h index f7aacb5c51..f911cbfdcf 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplicationProcess+FBQuiescence.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplicationProcess+FBQuiescence.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplicationProcess+FBQuiescence.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplicationProcess+FBQuiescence.m index 9c1d06eba7..1f6272dbce 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplicationProcess+FBQuiescence.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIApplicationProcess+FBQuiescence.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIApplicationProcess+FBQuiescence.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBHealthCheck.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBHealthCheck.h index 65257ee1f6..1c1ab63cd8 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBHealthCheck.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBHealthCheck.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBHealthCheck.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBHealthCheck.m index 315f06744b..8f9de6ee2c 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBHealthCheck.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBHealthCheck.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIDevice+FBHealthCheck.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBHelpers.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBHelpers.h index ca7fc53d8f..2f9c9d86ff 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBHelpers.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBHelpers.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBHelpers.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBHelpers.m index ef8664fb6f..660885630f 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBHelpers.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBHelpers.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIDevice+FBHelpers.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBRotation.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBRotation.h index 993c301c7d..b947fcdda7 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBRotation.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBRotation.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBRotation.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBRotation.m index 68b9b20a9b..164b23e7ba 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBRotation.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIDevice+FBRotation.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIDevice+FBRotation.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBAccessibility.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBAccessibility.h index 2af37a8d59..baa56565de 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBAccessibility.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBAccessibility.h @@ -3,12 +3,11 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import -#import "FBXCElementSnapshotWrapper.h" +#import NS_ASSUME_NONNULL_BEGIN diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBAccessibility.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBAccessibility.m index 327b2171a3..47d62e58f5 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBAccessibility.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBAccessibility.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIElement+FBAccessibility.h" @@ -18,8 +17,7 @@ @implementation XCUIElement (FBAccessibility) - (BOOL)fb_isAccessibilityElement { - id snapshot = [self fb_snapshotWithAttributes:@[FB_XCAXAIsElementAttributeName] - maxDepth:@1]; + id snapshot = [self fb_standardSnapshot]; return [FBXCElementSnapshotWrapper ensureWrapped:snapshot].fb_isAccessibilityElement; } @@ -33,8 +31,20 @@ - (BOOL)fb_isAccessibilityElement if (nil != isAccessibilityElement) { return isAccessibilityElement.boolValue; } - - return [(NSNumber *)[self fb_attributeValue:FB_XCAXAIsElementAttributeName] boolValue]; + + NSError *error; + NSNumber *attributeValue = [self fb_attributeValue:FB_XCAXAIsElementAttributeName + error:&error]; + if (nil != attributeValue) { + NSMutableDictionary *updatedValue = [NSMutableDictionary dictionaryWithDictionary:self.additionalAttributes ?: @{}]; + [updatedValue setObject:attributeValue forKey:FB_XCAXAIsElementAttribute]; + self.snapshot.additionalAttributes = updatedValue.copy; + return [attributeValue boolValue]; + } + + NSLog(@"Cannot determine accessibility of '%@' natively: %@. Defaulting to: %@", + self.fb_description, error.description, @(NO)); + return NO; } @end diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBCaching.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBCaching.h index 109a263711..119723aaa7 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBCaching.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBCaching.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import @@ -13,9 +12,6 @@ NS_ASSUME_NONNULL_BEGIN @interface XCUIElement (FBCaching) -/*! This property is set to YES if the given element has been resolved from the cache, so it is safe to use the `lastSnapshot` property */ -@property (nullable, nonatomic) NSNumber *fb_isResolvedFromCache; - @property (nonatomic, readonly) NSString *fb_cacheId; @end diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBCaching.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBCaching.m index faa42ea86f..c2e9f11211 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBCaching.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBCaching.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIElement+FBCaching.h" @@ -18,20 +17,6 @@ @implementation XCUIElement (FBCaching) -static char XCUIELEMENT_IS_RESOLVED_FROM_CACHE_KEY; - -@dynamic fb_isResolvedFromCache; - -- (void)setFb_isResolvedFromCache:(NSNumber *)isResolvedFromCache -{ - objc_setAssociatedObject(self, &XCUIELEMENT_IS_RESOLVED_FROM_CACHE_KEY, isResolvedFromCache, OBJC_ASSOCIATION_RETAIN_NONATOMIC); -} - -- (NSNumber *)fb_isResolvedFromCache -{ - return (NSNumber *)objc_getAssociatedObject(self, &XCUIELEMENT_IS_RESOLVED_FROM_CACHE_KEY); -} - static char XCUIELEMENT_CACHE_ID_KEY; @dynamic fb_cacheId; @@ -43,14 +28,7 @@ - (NSString *)fb_cacheId return (NSString *)result; } - NSString *uid; - if ([self isKindOfClass:XCUIApplication.class]) { - uid = self.fb_uid; - } else { - id snapshot = self.fb_cachedSnapshot ?: self.fb_takeSnapshot; - uid = [FBXCElementSnapshotWrapper wdUIDWithSnapshot:snapshot]; - } - + NSString *uid = self.fb_uid; objc_setAssociatedObject(self, &XCUIELEMENT_CACHE_ID_KEY, uid, OBJC_ASSOCIATION_RETAIN_NONATOMIC); return uid; } diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBClassChain.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBClassChain.h index 1cd1e8b937..0e56bfeaa9 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBClassChain.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBClassChain.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import @@ -50,7 +49,8 @@ NS_ASSUME_NONNULL_BEGIN @return an array of descendants matching given class chain @throws FBUnknownAttributeException if any of predicates in the chain contains unknown attribute(s) */ -- (NSArray *)fb_descendantsMatchingClassChain:(NSString *)classChainQuery shouldReturnAfterFirstMatch:(BOOL)shouldReturnAfterFirstMatch; +- (NSArray *)fb_descendantsMatchingClassChain:(NSString *)classChainQuery + shouldReturnAfterFirstMatch:(BOOL)shouldReturnAfterFirstMatch; @end diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBClassChain.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBClassChain.m index 9f70955bbb..88197eccda 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBClassChain.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBClassChain.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIElement+FBClassChain.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBFind.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBFind.h index 664d828b01..8a91fcdb83 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBFind.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBFind.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBFind.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBFind.m index 4d46f4c8f2..ceab0adf05 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBFind.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBFind.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ @@ -12,6 +11,7 @@ #import "FBMacros.h" #import "FBElementTypeTransformer.h" +#import "FBConfiguration.h" #import "NSPredicate+FBFormat.h" #import "FBXCElementSnapshotWrapper+Helpers.h" #import "FBXCodeCompatibility.h" @@ -109,9 +109,9 @@ @implementation XCUIElement (FBFind) id snapshot = matchingSnapshots.firstObject; matchingSnapshots = @[snapshot]; } - return [self fb_filterDescendantsWithSnapshots:matchingSnapshots - selfUID:[FBXCElementSnapshotWrapper wdUIDWithSnapshot:self.lastSnapshot] - onlyChildren:NO]; + XCUIElement *scopeRoot = FBConfiguration.limitXpathContextScope ? self : self.application; + return [scopeRoot fb_filterDescendantsWithSnapshots:matchingSnapshots + onlyChildren:NO]; } @@ -122,7 +122,9 @@ @implementation XCUIElement (FBFind) { NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id snapshot, NSDictionary * _Nullable bindings) { - return [[FBXCElementSnapshotWrapper wdNameWithSnapshot:snapshot] isEqualToString:accessibilityId]; + @autoreleasepool { + return [[FBXCElementSnapshotWrapper wdNameWithSnapshot:snapshot] isEqualToString:accessibilityId]; + } }]; return [self fb_descendantsMatchingPredicate:predicate shouldReturnAfterFirstMatch:shouldReturnAfterFirstMatch]; diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBForceTouch.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBForceTouch.h index 154cab24e4..8005b22933 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBForceTouch.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBForceTouch.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBForceTouch.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBForceTouch.m index 1c7a9ce0ef..bd5d0bdd37 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBForceTouch.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBForceTouch.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIElement+FBForceTouch.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBIsVisible.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBIsVisible.h index 2acc56511c..fd17acca61 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBIsVisible.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBIsVisible.h @@ -3,11 +3,10 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ -#import "FBXCElementSnapshotWrapper.h" +#import NS_ASSUME_NONNULL_BEGIN diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBIsVisible.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBIsVisible.m index 87841fc387..75a228a3e0 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBIsVisible.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBIsVisible.m @@ -3,218 +3,76 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIElement+FBIsVisible.h" -#import "FBConfiguration.h" #import "FBElementUtils.h" -#import "FBMathUtils.h" -#import "FBActiveAppDetectionPoint.h" -#import "FBSession.h" -#import "FBXCAccessibilityElement.h" #import "FBXCodeCompatibility.h" #import "FBXCElementSnapshotWrapper+Helpers.h" #import "XCUIElement+FBUtilities.h" -#import "XCUIElement+FBUID.h" +#import "XCUIElement+FBVisibleFrame.h" #import "XCTestPrivateSymbols.h" -@implementation XCUIElement (FBIsVisible) - -- (BOOL)fb_isVisible +NSNumber* _Nullable fetchSnapshotVisibility(id snapshot) { - id snapshot = [self fb_snapshotWithAttributes:@[FB_XCAXAIsVisibleAttributeName] - maxDepth:@1]; - return [FBXCElementSnapshotWrapper ensureWrapped:snapshot].fb_isVisible; + return nil == snapshot.additionalAttributes ? nil : snapshot.additionalAttributes[FB_XCAXAIsVisibleAttribute]; } -@end - -@implementation FBXCElementSnapshotWrapper (FBIsVisible) - -+ (NSString *)fb_uniqIdWithSnapshot:(id)snapshot -{ - return [FBXCElementSnapshotWrapper wdUIDWithSnapshot:snapshot] ?: [NSString stringWithFormat:@"%p", (void *)snapshot]; -} +@implementation XCUIElement (FBIsVisible) -- (nullable NSNumber *)fb_cachedVisibilityValue +- (BOOL)fb_isVisible { - NSMutableDictionary *cache = FBSession.activeSession.elementsVisibilityCache; - if (nil == cache) { - return nil; + @autoreleasepool { + id snapshot = [self fb_standardSnapshot]; + return [FBXCElementSnapshotWrapper ensureWrapped:snapshot].fb_isVisible; } - - NSDictionary *result = cache[@(self.generation)]; - if (nil == result) { - // There is no need to keep the cached data for the previous generations - [cache removeAllObjects]; - cache[@(self.generation)] = [NSMutableDictionary dictionary]; - return nil; - } - return result[[self.class fb_uniqIdWithSnapshot:self.snapshot]]; } -- (BOOL)fb_cacheVisibilityWithValue:(BOOL)isVisible - forAncestors:(nullable NSArray> *)ancestors -{ - NSMutableDictionary *cache = FBSession.activeSession.elementsVisibilityCache; - if (nil == cache) { - return isVisible; - } - NSMutableDictionary *destination = cache[@(self.generation)]; - if (nil == destination) { - return isVisible; - } - - NSNumber *visibleObj = [NSNumber numberWithBool:isVisible]; - destination[[self.class fb_uniqIdWithSnapshot:self.snapshot]] = visibleObj; - if (isVisible && nil != ancestors) { - // if an element is visible then all its ancestors must be visible as well - for (id ancestor in ancestors) { - NSString *ancestorId = [self.class fb_uniqIdWithSnapshot:ancestor]; - if (nil == destination[ancestorId]) { - destination[ancestorId] = visibleObj; - } - } - } - return isVisible; -} +@end -- (CGRect)fb_frameInContainer:(id)container - hierarchyIntersection:(nullable NSValue *)intersectionRectange -{ - CGRect currentRectangle = nil == intersectionRectange ? self.frame : [intersectionRectange CGRectValue]; - id parent = self.parent; - CGRect parentFrame = parent.frame; - CGRect containerFrame = container.frame; - if (CGSizeEqualToSize(parentFrame.size, CGSizeZero) && - CGPointEqualToPoint(parentFrame.origin, CGPointZero)) { - // Special case (or XCTest bug). Shift the origin and return immediately after shift - id nextParent = parent.parent; - BOOL isGrandparent = YES; - while (nextParent && nextParent != container) { - CGRect nextParentFrame = nextParent.frame; - if (isGrandparent && - CGSizeEqualToSize(nextParentFrame.size, CGSizeZero) && - CGPointEqualToPoint(nextParentFrame.origin, CGPointZero)) { - // Double zero-size container inclusion means that element coordinates are absolute - return CGRectIntersection(currentRectangle, containerFrame); - } - isGrandparent = NO; - if (!CGPointEqualToPoint(nextParentFrame.origin, CGPointZero)) { - currentRectangle.origin.x += nextParentFrame.origin.x; - currentRectangle.origin.y += nextParentFrame.origin.y; - return CGRectIntersection(currentRectangle, containerFrame); - } - nextParent = nextParent.parent; - } - return CGRectIntersection(currentRectangle, containerFrame); - } - // Skip parent containers if they are outside of the viewport - CGRect intersectionWithParent = CGRectIntersectsRect(parentFrame, containerFrame) || parent.elementType != XCUIElementTypeOther - ? CGRectIntersection(currentRectangle, parentFrame) - : currentRectangle; - if (CGRectIsEmpty(intersectionWithParent) && - parent != container && - self.elementType == XCUIElementTypeOther) { - // Special case (or XCTest bug). Shift the origin - if (CGSizeEqualToSize(parentFrame.size, containerFrame.size) || - // The size might be inverted in landscape - CGSizeEqualToSize(parentFrame.size, CGSizeMake(containerFrame.size.height, containerFrame.size.width)) || - CGSizeEqualToSize(self.frame.size, CGSizeZero)) { - // Covers ActivityListView and RemoteBridgeView cases - currentRectangle.origin.x += parentFrame.origin.x; - currentRectangle.origin.y += parentFrame.origin.y; - return CGRectIntersection(currentRectangle, containerFrame); - } - } - if (CGRectIsEmpty(intersectionWithParent) || parent == container) { - return intersectionWithParent; - } - return [[FBXCElementSnapshotWrapper ensureWrapped:parent] fb_frameInContainer:container - hierarchyIntersection:[NSValue valueWithCGRect:intersectionWithParent]]; -} +@implementation FBXCElementSnapshotWrapper (FBIsVisible) -- (BOOL)fb_hasAnyVisibleLeafs +- (BOOL)fb_hasVisibleDescendants { - NSArray> *children = self.children; - if (0 == children.count) { - return self.fb_isVisible; - } - - for (id child in children) { - if ([FBXCElementSnapshotWrapper ensureWrapped:child].fb_hasAnyVisibleLeafs) { + for (id descendant in (self._allDescendants ?: @[])) { + if ([fetchSnapshotVisibility(descendant) boolValue]) { return YES; } } - return NO; } - (BOOL)fb_isVisible { - NSNumber *isVisible = self.additionalAttributes[FB_XCAXAIsVisibleAttribute]; - if (isVisible != nil) { + NSNumber *isVisible = fetchSnapshotVisibility(self); + if (nil != isVisible) { return isVisible.boolValue; } - - NSNumber *cachedValue = [self fb_cachedVisibilityValue]; - if (nil != cachedValue) { - return [cachedValue boolValue]; - } - CGRect selfFrame = self.frame; - if (CGRectIsEmpty(selfFrame)) { - return [self fb_cacheVisibilityWithValue:NO forAncestors:nil]; + // Fetching the attribute value is expensive. + // Shortcircuit here to save time and assume if any of descendants + // is already determined as visible then the container should be visible as well + if ([self fb_hasVisibleDescendants]) { + return YES; } - NSArray> *ancestors = self.fb_ancestors; - if ([FBConfiguration shouldUseTestManagerForVisibilityDetection]) { - BOOL visibleAttrValue = [(NSNumber *)[self fb_attributeValue:FB_XCAXAIsVisibleAttributeName] boolValue]; - return [self fb_cacheVisibilityWithValue:visibleAttrValue forAncestors:ancestors]; - } - - id parentWindow = ancestors.count > 1 ? [ancestors objectAtIndex:ancestors.count - 2] : nil; - CGRect visibleRect = selfFrame; - if (nil != parentWindow) { - visibleRect = [self fb_frameInContainer:parentWindow hierarchyIntersection:nil]; - } - if (CGRectIsEmpty(visibleRect)) { - return [self fb_cacheVisibilityWithValue:NO forAncestors:ancestors]; - } - CGPoint midPoint = CGPointMake(visibleRect.origin.x + visibleRect.size.width / 2, - visibleRect.origin.y + visibleRect.size.height / 2); - id hitElement = [FBActiveAppDetectionPoint axElementWithPoint:midPoint]; - if (nil != hitElement) { - if (FBIsAXElementEqualToOther(self.accessibilityElement, hitElement)) { - return [self fb_cacheVisibilityWithValue:YES forAncestors:ancestors]; - } - for (id ancestor in ancestors) { - if (FBIsAXElementEqualToOther(hitElement, ancestor.accessibilityElement)) { - return [self fb_cacheVisibilityWithValue:YES forAncestors:ancestors]; - } + NSError *error; + NSNumber *attributeValue = [self fb_attributeValue:FB_XCAXAIsVisibleAttributeName + error:&error]; + if (nil != attributeValue) { + NSMutableDictionary *updatedValue = [NSMutableDictionary dictionaryWithDictionary:self.additionalAttributes ?: @{}]; + [updatedValue setObject:attributeValue forKey:FB_XCAXAIsVisibleAttribute]; + self.snapshot.additionalAttributes = updatedValue.copy; + @autoreleasepool { + return [attributeValue boolValue]; } } - if (self.children.count > 0) { - if (nil != hitElement) { - for (id descendant in self._allDescendants) { - if (FBIsAXElementEqualToOther(hitElement, descendant.accessibilityElement)) { - return [self fb_cacheVisibilityWithValue:YES - forAncestors:[FBXCElementSnapshotWrapper ensureWrapped:descendant].fb_ancestors]; - } - } - } - if (self.fb_hasAnyVisibleLeafs) { - return [self fb_cacheVisibilityWithValue:YES forAncestors:ancestors]; - } - } else if (nil == hitElement) { - // Sometimes XCTest returns nil for leaf elements hit test even if such elements are hittable - // Assume such elements are visible if their rectInContainer is visible - return [self fb_cacheVisibilityWithValue:YES forAncestors:ancestors]; - } - return [self fb_cacheVisibilityWithValue:NO forAncestors:ancestors]; + + NSLog(@"Cannot determine visiblity of %@ natively: %@. Defaulting to: %@", + self.fb_description, error.description, @(NO)); + return NO; } @end diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBMinMax.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBMinMax.h new file mode 100644 index 0000000000..0873a65a41 --- /dev/null +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBMinMax.h @@ -0,0 +1,33 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface XCUIElement (FBMinMax) + +/*! Minimum value (minValue) – may be nil if the element does not have this attribute */ +@property (nonatomic, readonly, nullable) NSNumber *fb_minValue; + +/*! Maximum value (maxValue) - may be nil if the element does not have this attribute */ +@property (nonatomic, readonly, nullable) NSNumber *fb_maxValue; + +@end + +@interface FBXCElementSnapshotWrapper (FBMinMax) + +/*! Minimum value (minValue) – may be nil if the element does not have this attribute */ +@property (nonatomic, readonly, nullable) NSNumber *fb_minValue; + +/*! Maximum value (maxValue) - may be nil if the element does not have this attribute */ +@property (nonatomic, readonly, nullable) NSNumber *fb_maxValue; + +@end + +NS_ASSUME_NONNULL_END diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBMinMax.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBMinMax.m new file mode 100644 index 0000000000..875149060f --- /dev/null +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBMinMax.m @@ -0,0 +1,75 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import "FBLogger.h" +#import "XCUIElement+FBMinMax.h" +#import "FBXCElementSnapshotWrapper+Helpers.h" +#import "XCUIElement+FBUtilities.h" +#import "XCTestPrivateSymbols.h" + +@interface FBXCElementSnapshotWrapper (FBMinMaxInternal) + +- (NSNumber *)fb_numericAttribute:(NSString *)attributeName symbol:(NSNumber *)symbol; + +@end + +@implementation XCUIElement (FBMinMax) + +- (NSNumber *)fb_minValue +{ + @autoreleasepool { + id snapshot = [self fb_standardSnapshot]; + return [[FBXCElementSnapshotWrapper ensureWrapped:snapshot] fb_minValue]; + } +} + +- (NSNumber *)fb_maxValue +{ + @autoreleasepool { + id snapshot = [self fb_standardSnapshot]; + return [[FBXCElementSnapshotWrapper ensureWrapped:snapshot] fb_maxValue]; + } +} + +@end + +@implementation FBXCElementSnapshotWrapper (FBMinMax) + +- (NSNumber *)fb_minValue +{ + return [self fb_numericAttribute:FB_XCAXACustomMinValueAttributeName + symbol:FB_XCAXACustomMinValueAttribute]; +} + +- (NSNumber *)fb_maxValue +{ + return [self fb_numericAttribute:FB_XCAXACustomMaxValueAttributeName + symbol:FB_XCAXACustomMaxValueAttribute]; +} + +- (NSNumber *)fb_numericAttribute:(NSString *)attributeName symbol:(NSNumber *)symbol +{ + NSNumber *cached = (self.snapshot.additionalAttributes ?: @{})[symbol]; + if (cached) { + return cached; + } + + NSError *error = nil; + NSNumber *raw = [self fb_attributeValue:attributeName error:&error]; + if (nil != raw) { + NSMutableDictionary *updated = [NSMutableDictionary dictionaryWithDictionary:self.additionalAttributes ?: @{}]; + updated[symbol] = raw; + self.snapshot.additionalAttributes = updated.copy; + return raw; + } + + [FBLogger logFmt:@"[FBMinMax] Cannot determine %@ for %@: %@", attributeName, self.fb_description, error.localizedDescription]; + return nil; +} + +@end diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBPickerWheel.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBPickerWheel.h index a63cf934e9..72762a3c43 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBPickerWheel.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBPickerWheel.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBPickerWheel.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBPickerWheel.m index 71ebaf6524..551892135c 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBPickerWheel.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBPickerWheel.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIElement+FBPickerWheel.h" @@ -12,6 +11,7 @@ #import "FBRunLoopSpinner.h" #import "FBXCElementSnapshot.h" #import "FBXCodeCompatibility.h" +#import "XCUIElement+FBUID.h" #import "XCUICoordinate.h" #import "XCUIElement+FBCaching.h" #import "XCUIElement+FBResolve.h" @@ -23,9 +23,7 @@ @implementation XCUIElement (FBPickerWheel) - (BOOL)fb_scrollWithOffset:(CGFloat)relativeHeightOffset error:(NSError **)error { - id snapshot = self.fb_isResolvedFromCache.boolValue - ? self.lastSnapshot - : self.fb_takeSnapshot; + id snapshot = [self fb_standardSnapshot]; NSString *previousValue = snapshot.value; XCUICoordinate *startCoord = [self coordinateWithNormalizedOffset:CGVectorMake(0.5, 0.5)]; XCUICoordinate *endCoord = [startCoord coordinateWithOffset:CGVectorMake(0.0, relativeHeightOffset * snapshot.frame.size.height)]; @@ -35,7 +33,7 @@ - (BOOL)fb_scrollWithOffset:(CGFloat)relativeHeightOffset error:(NSError **)erro // Fetching stable instance of an element allows it to be bounded to the // unique element identifier (UID), so it could be found next time even if its // id is different from the initial one. See https://github.com/appium/appium/issues/17569 - XCUIElement *stableInstance = self.fb_stableInstance; + XCUIElement *stableInstance = [self fb_stableInstanceWithUid:[FBXCElementSnapshotWrapper wdUIDWithSnapshot:snapshot]]; [endCoord tap]; return [[[[FBRunLoopSpinner new] timeout:VALUE_CHANGE_TIMEOUT] diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBResolve.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBResolve.h index 80b218b066..09b174f22c 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBResolve.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBResolve.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import @@ -27,10 +26,11 @@ NS_ASSUME_NONNULL_BEGIN Although, if the cached element instance is the one returned by this API call then the same element is going to be matched and no staleness exception will be thrown. + @param uid Element UUID @return Either the same element instance if `fb_isResolvedNatively` was set to NO (usually the cache for elements matched by xpath locators) or the stable instance of the self element based on the query by element's UUID. */ -- (XCUIElement *)fb_stableInstance; +- (XCUIElement *)fb_stableInstanceWithUid:(NSString *__nullable)uid; @end diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBResolve.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBResolve.m index f52c72bf6d..f288114dde 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBResolve.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBResolve.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIElement+FBResolve.h" @@ -32,23 +31,21 @@ - (NSNumber *)fb_isResolvedNatively return nil == result ? @YES : result; } -- (XCUIElement *)fb_stableInstance +- (XCUIElement *)fb_stableInstanceWithUid:(NSString *)uid { - if (![self.fb_isResolvedNatively boolValue]) { + if (nil == uid || ![self.fb_isResolvedNatively boolValue] || [self isKindOfClass:XCUIApplication.class]) { return self; } - - XCUIElementQuery *query = [self isKindOfClass:XCUIApplication.class] - ? self.application.fb_query - : [self.application.fb_query descendantsMatchingType:XCUIElementTypeAny]; - NSString *uid = nil == self.fb_cachedSnapshot - ? self.fb_uid - : [FBXCElementSnapshotWrapper wdUIDWithSnapshot:(id)self.fb_cachedSnapshot]; - if (nil == uid) { - return self; + NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K = %@", FBStringify(FBXCElementSnapshotWrapper, fb_uid), uid]; + @autoreleasepool { + XCUIElementQuery *query = [self.application.fb_query descendantsMatchingType:XCUIElementTypeAny]; + XCUIElement *result = [query matchingPredicate:predicate].allElementsBoundByIndex.firstObject; + if (nil != result) { + result.fb_isResolvedNatively = @NO; + return result; + } } - NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K = %@",FBStringify(FBXCElementSnapshotWrapper, fb_uid), uid]; - return [query matchingPredicate:predicate].allElementsBoundByIndex.firstObject ?: self; + return self; } @end diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBScrolling.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBScrolling.h index 680fddbfc3..416544e370 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBScrolling.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBScrolling.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBScrolling.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBScrolling.m index 52be1a5574..6b63d0a987 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBScrolling.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBScrolling.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIElement+FBScrolling.h" @@ -20,9 +19,11 @@ #import "XCUIApplication.h" #import "XCUICoordinate.h" #import "XCUIElement+FBIsVisible.h" +#import "XCUIElement+FBVisibleFrame.h" #import "XCUIElement.h" #import "XCUIElement+FBUtilities.h" #import "XCUIElement+FBWebDriverAttributes.h" +#import "XCTestPrivateSymbols.h" const CGFloat FBFuzzyPointThreshold = 20.f; //Smallest determined value that is not interpreted as touch const CGFloat FBScrollToVisibleNormalizedDistance = .5f; @@ -47,45 +48,35 @@ @implementation XCUIElement (FBScrolling) - (BOOL)fb_nativeScrollToVisibleWithError:(NSError **)error { - id snapshot = self.fb_isResolvedFromCache.boolValue - ? self.lastSnapshot - : self.fb_takeSnapshot; + id snapshot = [self fb_customSnapshot]; return nil != [self _hitPointByAttemptingToScrollToVisibleSnapshot:snapshot error:error]; } - (void)fb_scrollUpByNormalizedDistance:(CGFloat)distance { - id snapshot = self.fb_isResolvedFromCache.boolValue - ? self.lastSnapshot - : self.fb_takeSnapshot; + id snapshot = [self fb_customSnapshot]; [[FBXCElementSnapshotWrapper ensureWrapped:snapshot] fb_scrollUpByNormalizedDistance:distance inApplication:self.application]; } - (void)fb_scrollDownByNormalizedDistance:(CGFloat)distance { - id snapshot = self.fb_isResolvedFromCache.boolValue - ? self.lastSnapshot - : self.fb_takeSnapshot; + id snapshot = [self fb_customSnapshot]; [[FBXCElementSnapshotWrapper ensureWrapped:snapshot] fb_scrollDownByNormalizedDistance:distance inApplication:self.application]; } - (void)fb_scrollLeftByNormalizedDistance:(CGFloat)distance { - id snapshot = self.fb_isResolvedFromCache.boolValue - ? self.lastSnapshot - : self.fb_takeSnapshot; + id snapshot = [self fb_customSnapshot]; [[FBXCElementSnapshotWrapper ensureWrapped:snapshot] fb_scrollLeftByNormalizedDistance:distance inApplication:self.application]; } - (void)fb_scrollRightByNormalizedDistance:(CGFloat)distance { - id snapshot = self.fb_isResolvedFromCache.boolValue - ? self.lastSnapshot - : self.fb_takeSnapshot; + id snapshot = [self fb_customSnapshot]; [[FBXCElementSnapshotWrapper ensureWrapped:snapshot] fb_scrollRightByNormalizedDistance:distance inApplication:self.application]; } @@ -95,7 +86,8 @@ - (BOOL)fb_scrollToVisibleWithError:(NSError **)error return [self fb_scrollToVisibleWithNormalizedScrollDistance:FBScrollToVisibleNormalizedDistance error:error]; } -- (BOOL)fb_scrollToVisibleWithNormalizedScrollDistance:(CGFloat)normalizedScrollDistance error:(NSError **)error +- (BOOL)fb_scrollToVisibleWithNormalizedScrollDistance:(CGFloat)normalizedScrollDistance + error:(NSError **)error { return [self fb_scrollToVisibleWithNormalizedScrollDistance:normalizedScrollDistance scrollDirection:FBXCUIElementScrollDirectionUnknown @@ -106,7 +98,8 @@ - (BOOL)fb_scrollToVisibleWithNormalizedScrollDistance:(CGFloat)normalizedScroll scrollDirection:(FBXCUIElementScrollDirection)scrollDirection error:(NSError **)error { - FBXCElementSnapshotWrapper *prescrollSnapshot = [FBXCElementSnapshotWrapper ensureWrapped:[self fb_takeSnapshot]]; + FBXCElementSnapshotWrapper *prescrollSnapshot = [FBXCElementSnapshotWrapper ensureWrapped:[self fb_customSnapshot]]; + if (prescrollSnapshot.isWDVisible) { return YES; } @@ -138,12 +131,12 @@ - (BOOL)fb_scrollToVisibleWithNormalizedScrollDistance:(CGFloat)normalizedScroll FBXCElementSnapshotWrapper *wrappedCellSnapshot = [FBXCElementSnapshotWrapper ensureWrapped:cellSnapshot]; if (wrappedCellSnapshot.wdVisible) { [visibleCellSnapshots addObject:cellSnapshot]; + if (visibleCellSnapshots.count > 1) { + return YES; + } } } - if (visibleCellSnapshots.count > 1) { - return YES; - } return NO; }]; @@ -184,23 +177,25 @@ - (BOOL)fb_scrollToVisibleWithNormalizedScrollDistance:(CGFloat)normalizedScroll FBXCElementSnapshotWrapper *scrollViewWrapped = [FBXCElementSnapshotWrapper ensureWrapped:scrollView]; // Scrolling till cell is visible and get current value of frames while (![self fb_isEquivalentElementSnapshotVisible:prescrollSnapshot] && scrollCount < maxScrollCount) { - if (targetCellIndex < visibleCellIndex) { - scrollDirection == FBXCUIElementScrollDirectionVertical ? - [scrollViewWrapped fb_scrollUpByNormalizedDistance:normalizedScrollDistance - inApplication:self.application] : - [scrollViewWrapped fb_scrollLeftByNormalizedDistance:normalizedScrollDistance - inApplication:self.application]; - } - else { - scrollDirection == FBXCUIElementScrollDirectionVertical ? - [scrollViewWrapped fb_scrollDownByNormalizedDistance:normalizedScrollDistance + @autoreleasepool { + if (targetCellIndex < visibleCellIndex) { + scrollDirection == FBXCUIElementScrollDirectionVertical ? + [scrollViewWrapped fb_scrollUpByNormalizedDistance:normalizedScrollDistance inApplication:self.application] : - [scrollViewWrapped fb_scrollRightByNormalizedDistance:normalizedScrollDistance - inApplication:self.application]; + [scrollViewWrapped fb_scrollLeftByNormalizedDistance:normalizedScrollDistance + inApplication:self.application]; + } + else { + scrollDirection == FBXCUIElementScrollDirectionVertical ? + [scrollViewWrapped fb_scrollDownByNormalizedDistance:normalizedScrollDistance + inApplication:self.application] : + [scrollViewWrapped fb_scrollRightByNormalizedDistance:normalizedScrollDistance + inApplication:self.application]; + } + scrollCount++; + // Wait for scroll animation + [self fb_waitUntilStableWithTimeout:FBConfiguration.animationCoolOffTimeout]; } - scrollCount++; - // Wait for scroll animation - [self fb_waitUntilStableWithTimeout:FBConfiguration.animationCoolOffTimeout]; } if (scrollCount >= maxScrollCount) { @@ -213,9 +208,9 @@ - (BOOL)fb_scrollToVisibleWithNormalizedScrollDistance:(CGFloat)normalizedScroll // Cell is now visible, but it might be only partialy visible, scrolling till whole frame is visible. // Sometimes, attempting to grab the parent snapshot of the target cell after scrolling is complete causes a stale element reference exception. // Trying fb_cachedSnapshot first - FBXCElementSnapshotWrapper *targetCellSnapshotWrapped = [FBXCElementSnapshotWrapper ensureWrapped:([self fb_cachedSnapshot] ?: [self fb_takeSnapshot])]; + FBXCElementSnapshotWrapper *targetCellSnapshotWrapped = [FBXCElementSnapshotWrapper ensureWrapped:[self fb_customSnapshot]]; targetCellSnapshot = [targetCellSnapshotWrapped fb_parentCellSnapshot]; - CGRect visibleFrame = [FBXCElementSnapshotWrapper ensureWrapped:targetCellSnapshot].fb_visibleFrameWithFallback; + CGRect visibleFrame = [FBXCElementSnapshotWrapper ensureWrapped:targetCellSnapshot].fb_visibleFrame; CGVector scrollVector = CGVectorMake(visibleFrame.size.width - targetCellSnapshot.frame.size.width, visibleFrame.size.height - targetCellSnapshot.frame.size.height @@ -233,7 +228,7 @@ - (BOOL)fb_isEquivalentElementSnapshotVisible:(id)snapshot return YES; } - id appSnapshot = [self.application fb_takeSnapshot]; + id appSnapshot = [self.application fb_standardSnapshot]; for (id elementSnapshot in appSnapshot._allDescendants.copy) { FBXCElementSnapshotWrapper *wrappedElementSnapshot = [FBXCElementSnapshotWrapper ensureWrapped:elementSnapshot]; // We are comparing pre-scroll snapshot so frames are irrelevant. @@ -255,27 +250,32 @@ - (CGRect)scrollingFrame return self.visibleFrame; } -- (void)fb_scrollUpByNormalizedDistance:(CGFloat)distance inApplication:(XCUIApplication *)application +- (void)fb_scrollUpByNormalizedDistance:(CGFloat)distance + inApplication:(XCUIApplication *)application { [self fb_scrollByNormalizedVector:CGVectorMake(0.0, distance) inApplication:application]; } -- (void)fb_scrollDownByNormalizedDistance:(CGFloat)distance inApplication:(XCUIApplication *)application +- (void)fb_scrollDownByNormalizedDistance:(CGFloat)distance + inApplication:(XCUIApplication *)application { [self fb_scrollByNormalizedVector:CGVectorMake(0.0, -distance) inApplication:application]; } -- (void)fb_scrollLeftByNormalizedDistance:(CGFloat)distance inApplication:(XCUIApplication *)application +- (void)fb_scrollLeftByNormalizedDistance:(CGFloat)distance + inApplication:(XCUIApplication *)application { [self fb_scrollByNormalizedVector:CGVectorMake(distance, 0.0) inApplication:application]; } -- (void)fb_scrollRightByNormalizedDistance:(CGFloat)distance inApplication:(XCUIApplication *)application +- (void)fb_scrollRightByNormalizedDistance:(CGFloat)distance + inApplication:(XCUIApplication *)application { [self fb_scrollByNormalizedVector:CGVectorMake(-distance, 0.0) inApplication:application]; } -- (BOOL)fb_scrollByNormalizedVector:(CGVector)normalizedScrollVector inApplication:(XCUIApplication *)application +- (BOOL)fb_scrollByNormalizedVector:(CGVector)normalizedScrollVector + inApplication:(XCUIApplication *)application { CGVector scrollVector = CGVectorMake(CGRectGetWidth(self.scrollingFrame) * normalizedScrollVector.dx, CGRectGetHeight(self.scrollingFrame) * normalizedScrollVector.dy @@ -283,7 +283,9 @@ - (BOOL)fb_scrollByNormalizedVector:(CGVector)normalizedScrollVector inApplicati return [self fb_scrollByVector:scrollVector inApplication:application error:nil]; } -- (BOOL)fb_scrollByVector:(CGVector)vector inApplication:(XCUIApplication *)application error:(NSError **)error +- (BOOL)fb_scrollByVector:(CGVector)vector + inApplication:(XCUIApplication *)application + error:(NSError **)error { CGVector scrollBoundingVector = CGVectorMake( CGRectGetWidth(self.scrollingFrame) * FBScrollTouchProportion, @@ -314,7 +316,9 @@ - (CGVector)fb_hitPointOffsetForScrollingVector:(CGVector)scrollingVector return CGVectorMake((CGFloat)floor(x), (CGFloat)floor(y)); } -- (BOOL)fb_scrollAncestorScrollViewByVectorWithinScrollViewFrame:(CGVector)vector inApplication:(XCUIApplication *)application error:(NSError **)error +- (BOOL)fb_scrollAncestorScrollViewByVectorWithinScrollViewFrame:(CGVector)vector + inApplication:(XCUIApplication *)application + error:(NSError **)error { CGVector hitpointOffset = [self fb_hitPointOffsetForScrollingVector:vector]; diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBSwiping.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBSwiping.h index c30707dffb..4a2b5c1a1c 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBSwiping.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBSwiping.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBSwiping.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBSwiping.m index 4be4d34dc3..8f64b4832a 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBSwiping.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBSwiping.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIElement+FBSwiping.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBTVFocuse.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBTVFocuse.h index 6b25f9ab4f..0a3bc0794a 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBTVFocuse.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBTVFocuse.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBTVFocuse.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBTVFocuse.m index 30037646db..5aa8508435 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBTVFocuse.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBTVFocuse.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIElement+FBTVFocuse.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBTyping.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBTyping.h index c44aa7c57d..0b775589d2 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBTyping.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBTyping.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBTyping.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBTyping.m index 8b59ad0319..1d76f6ca04 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBTyping.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBTyping.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIElement+FBTyping.h" @@ -91,7 +90,7 @@ - (void)fb_prepareForTextInputWithSnapshot:(FBXCElementSnapshotWrapper *)snapsho [FBLogger logFmt:@"Trying to tap the \"%@\" element to have it focused", snapshot.fb_description]; [self tap]; // It might take some time to update the UI - [self fb_takeSnapshot]; + [self fb_standardSnapshot]; #endif } @@ -110,9 +109,7 @@ - (BOOL)fb_typeText:(NSString *)text frequency:(NSUInteger)frequency error:(NSError **)error { - id snapshot = self.fb_isResolvedFromCache.boolValue - ? self.lastSnapshot - : self.fb_takeSnapshot; + id snapshot = [self fb_standardSnapshot]; FBXCElementSnapshotWrapper *wrapped = [FBXCElementSnapshotWrapper ensureWrapped:snapshot]; [self fb_prepareForTextInputWithSnapshot:wrapped]; if (shouldClear && ![self fb_clearTextWithSnapshot:wrapped shouldPrepareForInput:NO error:error]) { @@ -123,9 +120,7 @@ - (BOOL)fb_typeText:(NSString *)text - (BOOL)fb_clearTextWithError:(NSError **)error { - id snapshot = self.fb_isResolvedFromCache.boolValue - ? self.lastSnapshot - : self.fb_takeSnapshot; + id snapshot = [self fb_standardSnapshot]; return [self fb_clearTextWithSnapshot:[FBXCElementSnapshotWrapper ensureWrapped:snapshot] shouldPrepareForInput:YES error:error]; @@ -182,7 +177,7 @@ - (BOOL)fb_clearTextWithSnapshot:(FBXCElementSnapshotWrapper *)snapshot return NO; } - currentValue = self.fb_takeSnapshot.value; + currentValue = [self fb_standardSnapshot].value; if (nil != placeholderValue && [currentValue isEqualToString:placeholderValue]) { // Short circuit if only the placeholder value left return YES; diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBUID.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBUID.h index 8b1a2da649..5a406adeae 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBUID.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBUID.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBXCElementSnapshotWrapper.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBUID.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBUID.m index ecac2cd91a..ebbb066549 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBUID.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBUID.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import @@ -22,14 +21,14 @@ - (unsigned long long)fb_accessibiltyId { return [FBElementUtils idWithAccessibilityElement:([self isKindOfClass:XCUIApplication.class] ? [(XCUIApplication *)self accessibilityElement] - : [self fb_takeSnapshot].accessibilityElement)]; + : [self fb_standardSnapshot].accessibilityElement)]; } - (NSString *)fb_uid { return [self isKindOfClass:XCUIApplication.class] ? [FBElementUtils uidWithAccessibilityElement:[(XCUIApplication *)self accessibilityElement]] - : [FBXCElementSnapshotWrapper ensureWrapped:[self fb_takeSnapshot]].fb_uid; + : [FBXCElementSnapshotWrapper ensureWrapped:[self fb_standardSnapshot]].fb_uid; } @end diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBUtilities.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBUtilities.h index 66b9ee2c93..6f4666688c 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBUtilities.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBUtilities.h @@ -3,13 +3,12 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import #import -#import "FBXCElementSnapshot.h" +#import NS_ASSUME_NONNULL_BEGIN @@ -18,70 +17,71 @@ NS_ASSUME_NONNULL_BEGIN /** Gets the most recent snapshot of the current element. The element will be automatically resolved if the snapshot is not available yet. - Calls to this method mutate the `lastSnapshot` instance property.. - Calls to this method reset the `fb_isResolvedFromCache` property value to `NO`. + Calls to this method mutate the `lastSnapshot` instance property. + The snapshot is taken by the native API provided by XCTest. + The maximum snapshot tree depth is set by `FBConfiguration.snapshotMaxDepth` + + Snapshot specifics: + - Most performant + - Memory-friedly + - `children` property is set to `nil` if not taken from XCUIApplication + - `value` property is cut off to max 512 bytes @return The recent snapshot of the element @throws FBStaleElementException if the element is not present in DOM and thus no snapshot could be made */ -- (id)fb_takeSnapshot; +- (id)fb_standardSnapshot; /** - Extracts the cached element snapshot from its query. - No requests to the accessiblity framework is made. - It is only safe to use this call right after element lookup query - has been executed. + Gets the most recent snapshot of the current element. The element will be + automatically resolved if the snapshot is not available yet. + Calls to this method mutate the `lastSnapshot` instance property. + The maximum snapshot tree depth is set by `FBConfiguration.snapshotMaxDepth` - @return Either the cached snapshot or nil + Snapshot specifics: + - Less performant in comparison to the standard one + - `children` property is always defined + - `value` property is not cut off + + @return The recent snapshot of the element + @throws FBStaleElementException if the element is not present in DOM and thus no snapshot could be made */ -- (nullable id)fb_cachedSnapshot; +- (id)fb_customSnapshot; /** - Gets the most recent snapshot of the current element and already resolves the accessibility attributes - needed for creating the page source of this element. No additional calls to the accessibility layer - are required. + Gets the most recent snapshot of the current element. The element will be + automatically resolved if the snapshot is not available yet. Calls to this method mutate the `lastSnapshot` instance property. - Calls to this method reset the `fb_isResolvedFromCache` property value to `NO`. + The maximum snapshot tree depth is set by `FBConfiguration.snapshotMaxDepth` + + Snapshot specifics: + - Less performant in comparison to the standard one + - The `hittable` property calculation is aligned with the native calculation logic - @param maxDepth The maximum depth of the snapshot. nil value means to use the default depth. - with custom attributes cannot be resolved - - @return The recent snapshot of the element with all attributes resolved or a snapshot with default - attributes resolved if there was a failure while resolving additional attributes + @return The recent snapshot of the element @throws FBStaleElementException if the element is not present in DOM and thus no snapshot could be made */ -- (nullable id)fb_snapshotWithAllAttributesAndMaxDepth:(nullable NSNumber *)maxDepth; +- (id)fb_nativeSnapshot; /** - Gets the most recent snapshot of the current element with given attributes resolved. - No additional calls to the accessibility layer are required. - Calls to this method mutate the `lastSnapshot` instance property. - Calls to this method reset the `fb_isResolvedFromCache` property value to `NO`. - - @param attributeNames The list of attribute names to resolve. Must be one of - FB_...Name values exported by XCTestPrivateSymbols.h module. - `nil` value means that only the default attributes must be extracted - @param maxDepth The maximum depth of the snapshot. nil value means to use the default depth. + Extracts the cached element snapshot from its query. + No requests to the accessiblity framework is made. + It is only safe to use this call right after element lookup query + has been executed. - @return The recent snapshot of the element with the given attributes resolved or a snapshot with default - attributes resolved if there was a failure while resolving additional attributes - @throws FBStaleElementException if the element is not present in DOM and thus no snapshot could be made -*/ -- (nullable id)fb_snapshotWithAttributes:(nullable NSArray *)attributeNames - maxDepth:(nullable NSNumber *)maxDepth; + @return Either the cached snapshot or nil + */ +- (nullable id)fb_cachedSnapshot; /** Filters elements by matching them to snapshots from the corresponding array @param snapshots Array of snapshots to be matched with - @param selfUID Optionally the unique identifier of the current element. - Providing it as an argument improves the performance of the method. @param onlyChildren Whether to only look for direct element children @return Array of filtered elements, which have matches in snapshots array */ - (NSArray *)fb_filterDescendantsWithSnapshots:(NSArray> *)snapshots - selfUID:(nullable NSString *)selfUID onlyChildren:(BOOL)onlyChildren; /** diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBUtilities.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBUtilities.m index 5f9fd96f4a..b627fc862f 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBUtilities.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBUtilities.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIElement+FBUtilities.h" @@ -14,6 +13,7 @@ #import "FBConfiguration.h" #import "FBExceptions.h" #import "FBImageUtils.h" +#import "FBElementUtils.h" #import "FBLogger.h" #import "FBMacros.h" #import "FBMathUtils.h" @@ -32,6 +32,7 @@ #import "XCTestPrivateSymbols.h" #import "XCTRunnerDaemonSession.h" #import "XCUIApplicationProcess+FBQuiescence.h" +#import "XCUIApplication.h" #import "XCUIElement+FBCaching.h" #import "XCUIElement+FBWebDriverAttributes.h" #import "XCUIElementQuery.h" @@ -40,94 +41,50 @@ #import "XCUIScreen.h" #import "XCUIElement+FBResolve.h" -#define DEFAULT_AX_TIMEOUT 60. - @implementation XCUIElement (FBUtilities) -- (id)fb_takeSnapshot +- (id)fb_takeSnapshot:(BOOL)isCustom { - NSError *error = nil; - self.fb_isResolvedFromCache = @(NO); - self.lastSnapshot = [self.fb_query fb_uniqueSnapshotWithError:&error]; - if (nil == self.lastSnapshot) { - NSString *hintText = @"Make sure the application UI has the expected state"; - if (nil != error - && [error.localizedDescription containsString:@"Identity Binding"]) { - hintText = [NSString stringWithFormat:@"%@. You could also try to switch the binding strategy using the 'boundElementsByIndex' setting for the element lookup", hintText]; - } - NSString *reason = [NSString stringWithFormat:@"The previously found element \"%@\" is not present in the current view anymore. %@", self.description, hintText]; - if (nil != error) { - reason = [NSString stringWithFormat:@"%@. Original error: %@", reason, error.localizedDescription]; + __block id snapshot = nil; + @autoreleasepool { + NSError *error = nil; + snapshot = isCustom + ? [self.fb_query fb_uniqueSnapshotWithError:&error] + : (id)[self snapshotWithError:&error]; + if (nil == snapshot) { + [self fb_raiseStaleElementExceptionWithError:error]; } - @throw [NSException exceptionWithName:FBStaleElementException reason:reason userInfo:@{}]; } + self.lastSnapshot = snapshot; return self.lastSnapshot; } -- (id)fb_cachedSnapshot +- (id)fb_standardSnapshot { - return [self.query fb_cachedSnapshot]; + return [self fb_takeSnapshot:NO]; } -- (nullable id)fb_snapshotWithAllAttributesAndMaxDepth:(NSNumber *)maxDepth +- (id)fb_customSnapshot { - NSMutableArray *allNames = [NSMutableArray arrayWithArray:FBStandardAttributeNames()]; - [allNames addObjectsFromArray:FBCustomAttributeNames()]; - return [self fb_snapshotWithAttributes:allNames.copy - maxDepth:maxDepth]; + return [self fb_takeSnapshot:YES]; } -- (nullable id)fb_snapshotWithAttributes:(NSArray *)attributeNames - maxDepth:(NSNumber *)maxDepth +- (id)fb_nativeSnapshot { - NSSet *standardAttributes = [NSSet setWithArray:FBStandardAttributeNames()]; - id snapshot = self.fb_takeSnapshot; - NSTimeInterval axTimeout = FBConfiguration.customSnapshotTimeout; - if (nil == attributeNames - || [[NSSet setWithArray:attributeNames] isSubsetOfSet:standardAttributes] - || axTimeout < DBL_EPSILON) { - // return the "normal" element snapshot if no custom attributes are requested - return snapshot; - } - - id axElement = snapshot.accessibilityElement; - if (nil == axElement) { - return nil; - } - - NSError *setTimeoutError; - BOOL isTimeoutSet = [FBXCAXClientProxy.sharedClient setAXTimeout:axTimeout - error:&setTimeoutError]; - if (!isTimeoutSet) { - [FBLogger logFmt:@"Cannot set snapshoting timeout to %.1fs. Original error: %@", - axTimeout, setTimeoutError.localizedDescription]; - } - - NSError *error; - id snapshotWithAttributes = [FBXCAXClientProxy.sharedClient snapshotForElement:axElement - attributes:attributeNames - maxDepth:maxDepth - error:&error]; - if (nil == snapshotWithAttributes) { - NSString *description = [FBXCElementSnapshotWrapper ensureWrapped:snapshot].fb_description; - [FBLogger logFmt:@"Cannot take a snapshot with attribute(s) %@ of '%@' after %.2f seconds", - attributeNames, description, axTimeout]; - [FBLogger logFmt:@"This timeout could be customized via '%@' setting", FB_SETTING_CUSTOM_SNAPSHOT_TIMEOUT]; - [FBLogger logFmt:@"Internal error: %@", error.localizedDescription]; - [FBLogger logFmt:@"Falling back to the default snapshotting mechanism for the element '%@' (some attribute values, like visibility or accessibility might not be precise though)", description]; - snapshotWithAttributes = self.lastSnapshot; - } else { - self.lastSnapshot = snapshotWithAttributes; + NSError *error = nil; + BOOL isSuccessful = [self resolveOrRaiseTestFailure:NO error:&error]; + if (nil == self.lastSnapshot || !isSuccessful) { + [self fb_raiseStaleElementExceptionWithError:error]; } + return self.lastSnapshot; +} - if (isTimeoutSet) { - [FBXCAXClientProxy.sharedClient setAXTimeout:DEFAULT_AX_TIMEOUT error:nil]; - } - return snapshotWithAttributes; +- (id)fb_cachedSnapshot +{ + return [self.query fb_cachedSnapshot]; } - (NSArray *)fb_filterDescendantsWithSnapshots:(NSArray> *)snapshots - selfUID:(NSString *)selfUID onlyChildren:(BOOL)onlyChildren { if (0 == snapshots.count) { @@ -135,21 +92,19 @@ @implementation XCUIElement (FBUtilities) } NSMutableArray *matchedIds = [NSMutableArray new]; for (id snapshot in snapshots) { - NSString *uid = [FBXCElementSnapshotWrapper wdUIDWithSnapshot:snapshot]; - if (nil != uid) { - [matchedIds addObject:uid]; + @autoreleasepool { + NSString *uid = [FBXCElementSnapshotWrapper wdUIDWithSnapshot:snapshot]; + if (nil != uid) { + [matchedIds addObject:uid]; + } } } NSMutableArray *matchedElements = [NSMutableArray array]; - NSString *uid = selfUID; - if (nil == uid) { - uid = self.fb_isResolvedFromCache.boolValue - ? [FBXCElementSnapshotWrapper wdUIDWithSnapshot:self.lastSnapshot] - : self.fb_uid; - } + NSString *uid = nil == self.lastSnapshot + ? self.fb_uid + : [FBXCElementSnapshotWrapper wdUIDWithSnapshot:self.lastSnapshot]; if (nil != uid && [matchedIds containsObject:uid]) { - XCUIElement *stableSelf = self.fb_stableInstance; - stableSelf.fb_isResolvedNatively = @NO; + XCUIElement *stableSelf = [self fb_stableInstanceWithUid:uid]; if (1 == snapshots.count) { return @[stableSelf]; } @@ -198,4 +153,18 @@ - (void)fb_waitUntilStableWithTimeout:(NSTimeInterval)timeout FBConfiguration.waitForIdleTimeout = previousTimeout; } +- (void)fb_raiseStaleElementExceptionWithError:(NSError *)error __attribute__((noreturn)) +{ + NSString *hintText = @"Make sure the application UI has the expected state"; + if (nil != error && [error.localizedDescription containsString:@"Identity Binding"]) { + hintText = [NSString stringWithFormat:@"%@. You could also try to switch the binding strategy using the 'boundElementsByIndex' setting for the element lookup", hintText]; + } + NSString *reason = [NSString stringWithFormat:@"The previously found element \"%@\" is not present in the current view anymore. %@", + self.description, hintText]; + if (nil != error) { + reason = [NSString stringWithFormat:@"%@. Original error: %@", reason, error.localizedDescription]; + } + @throw [NSException exceptionWithName:FBStaleElementException reason:reason userInfo:@{}]; +} + @end diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBVisibleFrame.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBVisibleFrame.h new file mode 100644 index 0000000000..e2355c9951 --- /dev/null +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBVisibleFrame.h @@ -0,0 +1,35 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import "FBXCElementSnapshotWrapper.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface XCUIElement (FBVisibleFrame) + +/** + Returns the snapshot visibleFrame with a fallback to direct attribute retrieval from FBXCAXClient in case of a snapshot fault (nil visibleFrame) + + @return the snapshot visibleFrame + */ +- (CGRect)fb_visibleFrame; + +@end + +@interface FBXCElementSnapshotWrapper (FBVisibleFrame) + +/** + Returns the snapshot visibleFrame with a fallback to direct attribute retrieval from FBXCAXClient in case of a snapshot fault (nil visibleFrame) + + @return the snapshot visibleFrame + */ +- (CGRect)fb_visibleFrame; + +@end + +NS_ASSUME_NONNULL_END diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBVisibleFrame.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBVisibleFrame.m new file mode 100644 index 0000000000..8ba5b0eaca --- /dev/null +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBVisibleFrame.m @@ -0,0 +1,52 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import "XCUIElement+FBVisibleFrame.h" +#import "FBElementUtils.h" +#import "FBXCodeCompatibility.h" +#import "FBXCElementSnapshotWrapper+Helpers.h" +#import "XCUIElement+FBUtilities.h" +#import "XCTestPrivateSymbols.h" + +@implementation XCUIElement (FBVisibleFrame) + +- (CGRect)fb_visibleFrame +{ + id snapshot = [self fb_standardSnapshot]; + return [FBXCElementSnapshotWrapper ensureWrapped:snapshot].fb_visibleFrame; +} + +@end + +@implementation FBXCElementSnapshotWrapper (FBVisibleFrame) + +- (CGRect)fb_visibleFrame +{ + CGRect thisVisibleFrame = [self visibleFrame]; + if (!CGRectIsEmpty(thisVisibleFrame)) { + return thisVisibleFrame; + } + + NSDictionary *visibleFrameDict = [self fb_attributeValue:FB_XCAXAVisibleFrameAttributeName + error:nil]; + if (nil == visibleFrameDict) { + return thisVisibleFrame; + } + + id x = [visibleFrameDict objectForKey:@"X"]; + id y = [visibleFrameDict objectForKey:@"Y"]; + id height = [visibleFrameDict objectForKey:@"Height"]; + id width = [visibleFrameDict objectForKey:@"Width"]; + if (x != nil && y != nil && height != nil && width != nil) { + return CGRectMake([x doubleValue], [y doubleValue], [width doubleValue], [height doubleValue]); + } + + return thisVisibleFrame; +} + +@end diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBWebDriverAttributes.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBWebDriverAttributes.h index fdeedaf91d..8e598d7a67 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBWebDriverAttributes.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBWebDriverAttributes.h @@ -3,13 +3,12 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import #import -#import "FBXCElementSnapshotWrapper.h" +#import NS_ASSUME_NONNULL_BEGIN diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBWebDriverAttributes.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBWebDriverAttributes.m index b29c5a8b26..ca3023bfbc 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBWebDriverAttributes.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElement+FBWebDriverAttributes.m @@ -3,13 +3,13 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIElement+FBWebDriverAttributes.h" #import "FBElementTypeTransformer.h" +#import "FBElementHelpers.h" #import "FBLogger.h" #import "FBMacros.h" #import "FBXCElementSnapshotWrapper.h" @@ -21,6 +21,8 @@ #import "FBElementUtils.h" #import "XCTestPrivateSymbols.h" #import "XCUIHitPointResult.h" +#import "FBAccessibilityTraits.h" +#import "XCUIElement+FBMinMax.h" #define BROKEN_RECT CGRectMake(-1, -1, 0, 0) @@ -28,24 +30,20 @@ @implementation XCUIElement (WebDriverAttributesForwarding) - (id)fb_snapshotForAttributeName:(NSString *)name { - // These attributes are special, because we can only retrieve them from - // the snapshot if we explicitly ask XCTest to include them into the query while taking it. - // That is why fb_snapshotWithAllAttributes method must be used instead of the default snapshot - // call - if ([name isEqualToString:FBStringify(XCUIElement, isWDVisible)]) { - return [self fb_snapshotWithAttributes:@[FB_XCAXAIsVisibleAttributeName] - maxDepth:@1]; + // https://github.com/appium/appium-xcuitest-driver/pull/2565 + if ([name isEqualToString:FBStringify(XCUIElement, isWDHittable)]) { + return [self fb_nativeSnapshot]; } - if ([name isEqualToString:FBStringify(XCUIElement, isWDAccessible)]) { - return [self fb_snapshotWithAttributes:@[FB_XCAXAIsElementAttributeName] - maxDepth:@1]; + // https://github.com/appium/appium-xcuitest-driver/issues/2552 + BOOL isValueRequest = [name isEqualToString:FBStringify(XCUIElement, wdValue)]; + if ([self isKindOfClass:XCUIApplication.class] && !isValueRequest) { + return [self fb_standardSnapshot]; } - if ([name isEqualToString:FBStringify(XCUIElement, isWDAccessibilityContainer)]) { - return [self fb_snapshotWithAttributes:@[FB_XCAXAIsElementAttributeName] - maxDepth:nil]; - } - - return self.fb_takeSnapshot; + BOOL isCustomSnapshot = [name isEqualToString:FBStringify(XCUIElement, isWDAccessible)] + || [name isEqualToString:FBStringify(XCUIElement, isWDAccessibilityContainer)] + || [name isEqualToString:FBStringify(XCUIElement, wdIndex)] + || isValueRequest; + return isCustomSnapshot ? [self fb_customSnapshot] : [self fb_standardSnapshot]; } - (id)fb_valueForWDAttributeName:(NSString *)name @@ -78,6 +76,16 @@ - (id)fb_valueForWDAttributeName:(NSString *)name return [self valueForKey:[FBElementUtils wdAttributeNameForAttributeName:name]]; } +- (NSNumber *)wdMinValue +{ + return self.fb_minValue; +} + +- (NSNumber *)wdMaxValue +{ + return self.fb_maxValue; +} + - (NSString *)wdValue { id value = self.value; @@ -90,9 +98,7 @@ - (NSString *)wdValue value = FBFirstNonEmptyValue(value, isSelected); } else if (elementType == XCUIElementTypeSwitch) { value = @([value boolValue]); - } else if (elementType == XCUIElementTypeTextView || - elementType == XCUIElementTypeTextField || - elementType == XCUIElementTypeSecureTextField) { + } else if (FBDoesElementSupportInnerText(elementType)) { NSString *placeholderValue = self.placeholderValue; value = FBFirstNonEmptyValue(value, placeholderValue); } @@ -120,12 +126,18 @@ - (NSString *)wdName - (NSString *)wdLabel { - NSString *label = self.label; XCUIElementType elementType = self.elementType; - if (elementType == XCUIElementTypeTextField || elementType == XCUIElementTypeSecureTextField ) { - return label; - } - return FBTransferEmptyStringToNil(label); + return (elementType == XCUIElementTypeTextField + || elementType == XCUIElementTypeSecureTextField) + ? self.label + : FBTransferEmptyStringToNil(self.label); +} + +- (NSString *)wdPlaceholderValue +{ + return FBDoesElementSupportInnerText(self.elementType) + ? self.placeholderValue + : FBTransferEmptyStringToNil(self.placeholderValue); } - (NSString *)wdType @@ -150,6 +162,30 @@ - (CGRect)wdFrame : CGRectIntegral(frame); } +- (CGRect)wdNativeFrame +{ + // To avoid confusion regarding the frame returned by `wdFrame`, + // the current property is provided to represent the element's + // actual rendered frame. + return self.frame; +} + +/** + Returns a comma-separated string of accessibility traits for the element. + This method converts the element's accessibility traits bitmask into human-readable strings + using FBAccessibilityTraitsToStringsArray. The traits represent various accessibility + characteristics of the element such as Button, Link, Image, etc. + You can find the list of possible traits in the Apple documentation: + https://developer.apple.com/documentation/uikit/uiaccessibilitytraits?language=objc + + @return A comma-separated string of accessibility traits, or an empty string if no traits are set + */ +- (NSString *)wdTraits +{ + NSArray *traits = FBAccessibilityTraitsToStringsArray(self.snapshot.traits); + return [traits componentsJoinedByString:@", "]; +} + - (BOOL)isWDVisible { return self.fb_isVisible; @@ -183,8 +219,8 @@ - (BOOL)isWDAccessible // In the scenario when table provides Search results controller, table could be marked as accessible element, even though it isn't // As it is highly unlikely that table view should ever be an accessibility element itself, // for now we work around that by skipping Table View in container checks - if ([FBXCElementSnapshotWrapper ensureWrapped:parentSnapshot].fb_isAccessibilityElement - && parentSnapshot.elementType != XCUIElementTypeTable) { + if (parentSnapshot.elementType != XCUIElementTypeTable + && [FBXCElementSnapshotWrapper ensureWrapped:parentSnapshot].fb_isAccessibilityElement) { return NO; } parentSnapshot = parentSnapshot.parent; diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElementQuery+FBHelpers.h b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElementQuery+FBHelpers.h index 04ff8bfad1..8c82890741 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElementQuery+FBHelpers.h +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElementQuery+FBHelpers.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElementQuery+FBHelpers.m b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElementQuery+FBHelpers.m index 81e2a522e6..d2438a0cb6 100644 --- a/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElementQuery+FBHelpers.m +++ b/WebDriverAgent/WebDriverAgentLib/Categories/XCUIElementQuery+FBHelpers.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIElementQuery+FBHelpers.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBAlertViewCommands.h b/WebDriverAgent/WebDriverAgentLib/Commands/FBAlertViewCommands.h index 3d4c2638cc..687c39ce02 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBAlertViewCommands.h +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBAlertViewCommands.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBAlertViewCommands.m b/WebDriverAgent/WebDriverAgentLib/Commands/FBAlertViewCommands.m index 760244629a..50479936e0 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBAlertViewCommands.m +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBAlertViewCommands.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBAlertViewCommands.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBCustomCommands.h b/WebDriverAgent/WebDriverAgentLib/Commands/FBCustomCommands.h index 869d14fd1a..dca1542293 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBCustomCommands.h +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBCustomCommands.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBCustomCommands.m b/WebDriverAgent/WebDriverAgentLib/Commands/FBCustomCommands.m index 2ab039e6b5..d20c485d0b 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBCustomCommands.m +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBCustomCommands.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBCustomCommands.h" @@ -567,7 +566,8 @@ + (NSString *)timeZone FBElementCache *elementCache = request.session.elementCache; BOOL hasElement = ![request.parameters[@"uuid"] isEqual:@"0"]; XCUIElement *destination = hasElement - ? [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"]] + ? [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"] + checkStaleness:YES] : request.session.activeApplication; id keys = request.arguments[@"keys"]; diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBDebugCommands.h b/WebDriverAgent/WebDriverAgentLib/Commands/FBDebugCommands.h index 32f28b1b23..99728e03af 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBDebugCommands.h +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBDebugCommands.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBDebugCommands.m b/WebDriverAgent/WebDriverAgentLib/Commands/FBDebugCommands.m index c3f9a78160..42ea74b3d5 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBDebugCommands.m +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBDebugCommands.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBDebugCommands.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBElementCommands.h b/WebDriverAgent/WebDriverAgentLib/Commands/FBElementCommands.h index fcd1c86ea9..3c07ee6d60 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBElementCommands.h +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBElementCommands.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBElementCommands.m b/WebDriverAgent/WebDriverAgentLib/Commands/FBElementCommands.m index 762bad3275..9c2ea009cd 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBElementCommands.m +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBElementCommands.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBElementCommands.h" @@ -35,6 +34,7 @@ #import "XCUIElement+FBWebDriverAttributes.h" #import "XCUIElement+FBTVFocuse.h" #import "XCUIElement+FBResolve.h" +#import "XCUIElement+FBUID.h" #import "FBElementTypeTransformer.h" #import "XCUIElement.h" #import "XCUIElementQuery.h" @@ -52,6 +52,7 @@ + (NSArray *)routes return @[ [[FBRoute GET:@"/window/size"] respondWithTarget:self action:@selector(handleGetWindowSize:)], + [[FBRoute GET:@"/window/rect"] respondWithTarget:self action:@selector(handleGetWindowRect:)], [[FBRoute GET:@"/window/size"].withoutSession respondWithTarget:self action:@selector(handleGetWindowSize:)], [[FBRoute GET:@"/element/:uuid/enabled"] respondWithTarget:self action:@selector(handleGetEnabled:)], [[FBRoute GET:@"/element/:uuid/rect"] respondWithTarget:self action:@selector(handleGetRect:)], @@ -126,38 +127,22 @@ + (NSArray *)routes { FBElementCache *elementCache = request.session.elementCache; XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"]]; - BOOL isEnabled = [FBXCElementSnapshotWrapper ensureWrapped:element.lastSnapshot].isWDEnabled; - return FBResponseWithObject(isEnabled ? @YES : @NO); + return FBResponseWithObject(@(element.isWDEnabled)); } + (id)handleGetRect:(FBRouteRequest *)request { FBElementCache *elementCache = request.session.elementCache; XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"]]; - return FBResponseWithObject([FBXCElementSnapshotWrapper ensureWrapped:element.lastSnapshot].wdRect); + return FBResponseWithObject(element.wdRect); } + (id)handleGetAttribute:(FBRouteRequest *)request { FBElementCache *elementCache = request.session.elementCache; NSString *attributeName = request.parameters[@"name"]; - NSString *wdAttributeName = [FBElementUtils wdAttributeNameForAttributeName:attributeName]; - NSArray *additionalAttributes = nil; - NSNumber *maxDepth = nil; - if ([wdAttributeName isEqualToString:FBStringify(XCUIElement, isWDVisible)]) { - additionalAttributes = @[FB_XCAXAIsVisibleAttributeName]; - maxDepth = @1; - } else if ([wdAttributeName isEqualToString:FBStringify(XCUIElement, isWDEnabled)]) { - additionalAttributes = @[FB_XCAXAIsElementAttributeName]; - maxDepth = @1; - } else if ([wdAttributeName isEqualToString:FBStringify(XCUIElement, isWDAccessibilityContainer)]) { - additionalAttributes = @[FB_XCAXAIsElementAttributeName]; - } - XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"] - resolveForAdditionalAttributes:additionalAttributes - andMaxDepth:maxDepth]; - FBXCElementSnapshotWrapper *wrappedSnapshot = [FBXCElementSnapshotWrapper ensureWrapped:element.lastSnapshot]; - id attributeValue = [wrappedSnapshot fb_valueForWDAttributeName:attributeName]; + XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"]]; + id attributeValue = [element fb_valueForWDAttributeName:attributeName]; return FBResponseWithObject(attributeValue ?: [NSNull null]); } @@ -165,7 +150,9 @@ + (NSArray *)routes { FBElementCache *elementCache = request.session.elementCache; XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"]]; - FBXCElementSnapshotWrapper *wrappedSnapshot = [FBXCElementSnapshotWrapper ensureWrapped:element.lastSnapshot]; + // https://github.com/appium/appium-xcuitest-driver/issues/2552 + id snapshot = [element fb_customSnapshot]; + FBXCElementSnapshotWrapper *wrappedSnapshot = [FBXCElementSnapshotWrapper ensureWrapped:snapshot]; id text = FBFirstNonEmptyValue(wrappedSnapshot.wdValue, wrappedSnapshot.wdLabel); return FBResponseWithObject(text ?: @""); } @@ -173,48 +160,43 @@ + (NSArray *)routes + (id)handleGetDisplayed:(FBRouteRequest *)request { FBElementCache *elementCache = request.session.elementCache; - XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"] - resolveForAdditionalAttributes:@[FB_XCAXAIsVisibleAttributeName] - andMaxDepth:@1]; - return FBResponseWithObject(@([FBXCElementSnapshotWrapper ensureWrapped:element.lastSnapshot].isWDVisible)); + XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"]]; + return FBResponseWithObject(@(element.isWDVisible)); } + (id)handleGetAccessible:(FBRouteRequest *)request { FBElementCache *elementCache = request.session.elementCache; - XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"] - resolveForAdditionalAttributes:@[FB_XCAXAIsElementAttributeName] - andMaxDepth:@1]; - return FBResponseWithObject(@([FBXCElementSnapshotWrapper ensureWrapped:element.lastSnapshot].isWDAccessible)); + XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"]]; + return FBResponseWithObject(@(element.isWDAccessible)); } + (id)handleGetIsAccessibilityContainer:(FBRouteRequest *)request { FBElementCache *elementCache = request.session.elementCache; - XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"] - resolveForAdditionalAttributes:@[FB_XCAXAIsElementAttributeName] - andMaxDepth:nil]; - return FBResponseWithObject(@([FBXCElementSnapshotWrapper ensureWrapped:element.lastSnapshot].isWDAccessibilityContainer)); + XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"]]; + return FBResponseWithObject(@(element.isWDAccessibilityContainer)); } + (id)handleGetName:(FBRouteRequest *)request { FBElementCache *elementCache = request.session.elementCache; XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"]]; - return FBResponseWithObject([FBXCElementSnapshotWrapper ensureWrapped:element.lastSnapshot].wdType); + return FBResponseWithObject(element.wdType); } + (id)handleGetSelected:(FBRouteRequest *)request { FBElementCache *elementCache = request.session.elementCache; XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"]]; - return FBResponseWithObject(@([FBXCElementSnapshotWrapper ensureWrapped:element.lastSnapshot].wdSelected)); + return FBResponseWithObject(@(element.wdSelected)); } + (id)handleSetValue:(FBRouteRequest *)request { FBElementCache *elementCache = request.session.elementCache; - XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"]]; + XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"] + checkStaleness:YES]; id value = request.arguments[@"value"] ?: request.arguments[@"text"]; if (!value) { return FBResponseWithStatus([FBCommandStatus invalidArgumentErrorWithMessage:@"Neither 'value' nor 'text' parameter is provided" traceback:nil]); @@ -222,7 +204,7 @@ + (NSArray *)routes NSString *textToType = [value isKindOfClass:NSArray.class] ? [value componentsJoinedByString:@""] : value; - XCUIElementType elementType = [(id)element.lastSnapshot elementType]; + XCUIElementType elementType = [element elementType]; #if !TARGET_OS_TV if (elementType == XCUIElementTypePickerWheel) { [element adjustToPickerWheelValue:textToType]; @@ -251,7 +233,7 @@ + (NSArray *)routes + (id)handleClick:(FBRouteRequest *)request { FBElementCache *elementCache = request.session.elementCache; - XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"]]; + XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"] checkStaleness:YES]; #if TARGET_OS_IOS [element tap]; #elif TARGET_OS_TV @@ -285,7 +267,10 @@ + (NSArray *)routes if (focusedElement != nil) { FBElementCache *elementCache = request.session.elementCache; BOOL useNativeCachingStrategy = request.session.useNativeCachingStrategy; - NSString *focusedUUID = [elementCache storeElement:(useNativeCachingStrategy ? focusedElement : focusedElement.fb_stableInstance)]; + NSString *focusedUUID = [elementCache storeElement:(useNativeCachingStrategy + ? focusedElement + : [focusedElement fb_stableInstanceWithUid:focusedElement.fb_uid])]; + focusedElement.lastSnapshot = nil; if (focusedUUID && [focusedUUID isEqualToString:(id)request.parameters[@"uuid"]]) { isFocused = YES; } @@ -353,7 +338,7 @@ + (NSArray *)routes FBElementCache *elementCache = request.session.elementCache; XCUIElement *element = [self targetFromRequest:request]; [element pressForDuration:[request.arguments[@"pressDuration"] doubleValue] - thenDragToElement:[elementCache elementForUUID:(NSString *)request.arguments[@"toElement"]] + thenDragToElement:[elementCache elementForUUID:(NSString *)request.arguments[@"toElement"] checkStaleness:YES] withVelocity:[request.arguments[@"velocity"] doubleValue] thenHoldForDuration:[request.arguments[@"holdDuration"] doubleValue]]; return FBResponseWithOK(); @@ -441,10 +426,7 @@ + (NSArray *)routes + (id)handleDrag:(FBRouteRequest *)request { - NSString *elementUdid = (NSString *)request.parameters[@"uuid"]; - XCUIElement *target = nil == elementUdid - ? request.session.activeApplication - : [request.session.elementCache elementForUUID:elementUdid]; + XCUIElement *target = [self targetFromRequest:request]; CGVector startOffset = CGVectorMake([request.arguments[@"fromX"] doubleValue], [request.arguments[@"fromY"] doubleValue]); XCUICoordinate *startCoordinate = [self.class gestureCoordinateWithOffset:startOffset element:target]; @@ -546,13 +528,32 @@ + (NSArray *)routes { XCUIApplication *app = request.session.activeApplication ?: XCUIApplication.fb_activeApplication; + CGRect frame = app.wdFrame; #if TARGET_OS_TV - CGSize screenSize = app.frame.size; + CGSize screenSize = frame.size; #else + CGSize screenSize = FBAdjustDimensionsForApplication(frame.size, app.interfaceOrientation); +#endif + return FBResponseWithObject(@{ + @"width": @(screenSize.width), + @"height": @(screenSize.height), + }); +} + + ++ (id)handleGetWindowRect:(FBRouteRequest *)request +{ + XCUIApplication *app = request.session.activeApplication ?: XCUIApplication.fb_activeApplication; + CGRect frame = app.wdFrame; +#if TARGET_OS_TV + CGSize screenSize = frame.size; +#else CGSize screenSize = FBAdjustDimensionsForApplication(frame.size, app.interfaceOrientation); #endif return FBResponseWithObject(@{ + @"x": @(frame.origin.x), + @"y": @(frame.origin.y), @"width": @(screenSize.width), @"height": @(screenSize.height), }); @@ -560,16 +561,23 @@ + (NSArray *)routes + (id)handleElementScreenshot:(FBRouteRequest *)request { - FBElementCache *elementCache = request.session.elementCache; - XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"]]; - NSData *screenshotData = [element.screenshot PNGRepresentation]; - if (nil == screenshotData) { - NSString *errMsg = [NSString stringWithFormat:@"Cannot take a screenshot of %@", element.description]; - return FBResponseWithStatus([FBCommandStatus unableToCaptureScreenErrorWithMessage:errMsg - traceback:nil]); + @autoreleasepool { + FBElementCache *elementCache = request.session.elementCache; + XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"] + checkStaleness:YES]; + NSData *screenshotData = nil; + @autoreleasepool { + screenshotData = [element.screenshot PNGRepresentation]; + if (nil == screenshotData) { + NSString *errMsg = [NSString stringWithFormat:@"Cannot take a screenshot of %@", element.description]; + return FBResponseWithStatus([FBCommandStatus unableToCaptureScreenErrorWithMessage:errMsg + traceback:nil]); + } + } + NSString *screenshot = [screenshotData base64EncodedStringWithOptions:0]; + screenshotData = nil; + return FBResponseWithObject(screenshot); } - NSString *screenshot = [screenshotData base64EncodedStringWithOptions:0]; - return FBResponseWithObject(screenshot); } @@ -581,8 +589,9 @@ + (NSArray *)routes + (id)handleWheelSelect:(FBRouteRequest *)request { FBElementCache *elementCache = request.session.elementCache; - XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"]]; - if ([element.lastSnapshot elementType] != XCUIElementTypePickerWheel) { + XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"] + checkStaleness:YES]; + if ([element elementType] != XCUIElementTypePickerWheel) { NSString *errMsg = [NSString stringWithFormat:@"The element is expected to be a valid Picker Wheel control. '%@' was given instead", element.wdType]; return FBResponseWithStatus([FBCommandStatus invalidArgumentErrorWithMessage:errMsg traceback:[NSString stringWithFormat:@"%@", NSThread.callStackSymbols]]); @@ -688,7 +697,7 @@ + (XCUIElement *)targetFromRequest:(FBRouteRequest *)request NSString *elementUuid = (NSString *)request.parameters[@"uuid"]; return nil == elementUuid ? request.session.activeApplication - : [elementCache elementForUUID:elementUuid]; + : [elementCache elementForUUID:elementUuid checkStaleness:YES]; } #endif diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBFindElementCommands.h b/WebDriverAgent/WebDriverAgentLib/Commands/FBFindElementCommands.h index 9c20b0d459..7349e10c9b 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBFindElementCommands.h +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBFindElementCommands.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBFindElementCommands.m b/WebDriverAgent/WebDriverAgentLib/Commands/FBFindElementCommands.m index ba30a71707..c370f11cef 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBFindElementCommands.m +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBFindElementCommands.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBFindElementCommands.h" @@ -80,15 +79,13 @@ + (NSArray *)routes + (id)handleFindVisibleCells:(FBRouteRequest *)request { FBElementCache *elementCache = request.session.elementCache; - XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"] - resolveForAdditionalAttributes:@[FB_XCAXAIsVisibleAttributeName] - andMaxDepth:nil]; - NSArray> *visibleCellSnapshots = [element.lastSnapshot descendantsByFilteringWithBlock:^BOOL(id snapshot) { - return snapshot.elementType == XCUIElementTypeCell - && [FBXCElementSnapshotWrapper ensureWrapped:snapshot].wdVisible; + XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"]]; + id snapshot = [element fb_customSnapshot]; + NSArray> *visibleCellSnapshots = [snapshot descendantsByFilteringWithBlock:^BOOL(id shot) { + return shot.elementType == XCUIElementTypeCell + && [FBXCElementSnapshotWrapper ensureWrapped:shot].wdVisible; }]; NSArray *cells = [element fb_filterDescendantsWithSnapshots:visibleCellSnapshots - selfUID:[FBXCElementSnapshotWrapper wdUIDWithSnapshot:element.lastSnapshot] onlyChildren:NO]; return FBResponseWithCachedElements(cells, request.session.elementCache, FBConfiguration.shouldUseCompactResponses); } @@ -96,7 +93,8 @@ + (NSArray *)routes + (id)handleFindSubElement:(FBRouteRequest *)request { FBElementCache *elementCache = request.session.elementCache; - XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"]]; + XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"] + checkStaleness:NO]; XCUIElement *foundElement = [self.class elementUsing:request.arguments[@"using"] withValue:request.arguments[@"value"] under:element]; @@ -109,7 +107,8 @@ + (NSArray *)routes + (id)handleFindSubElements:(FBRouteRequest *)request { FBElementCache *elementCache = request.session.elementCache; - XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"]]; + XCUIElement *element = [elementCache elementForUUID:(NSString *)request.parameters[@"uuid"] + checkStaleness:NO]; NSArray *foundElements = [self.class elementsUsing:request.arguments[@"using"] withValue:request.arguments[@"value"] under:element diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBOrientationCommands.h b/WebDriverAgent/WebDriverAgentLib/Commands/FBOrientationCommands.h index 50bd5b6b11..1aaaacd63b 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBOrientationCommands.h +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBOrientationCommands.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBOrientationCommands.m b/WebDriverAgent/WebDriverAgentLib/Commands/FBOrientationCommands.m index aa4de26f7f..8e0bea4394 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBOrientationCommands.m +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBOrientationCommands.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBOrientationCommands.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBScreenshotCommands.h b/WebDriverAgent/WebDriverAgentLib/Commands/FBScreenshotCommands.h index ecb4a5eb85..3f4fa4a2ce 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBScreenshotCommands.h +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBScreenshotCommands.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBScreenshotCommands.m b/WebDriverAgent/WebDriverAgentLib/Commands/FBScreenshotCommands.m index 0b6e424274..71d6ba594e 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBScreenshotCommands.m +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBScreenshotCommands.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBScreenshotCommands.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBSessionCommands.h b/WebDriverAgent/WebDriverAgentLib/Commands/FBSessionCommands.h index 3f925aca8b..95f3f258fd 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBSessionCommands.h +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBSessionCommands.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBSessionCommands.m b/WebDriverAgent/WebDriverAgentLib/Commands/FBSessionCommands.m index 1972186d2c..1a9ddf417c 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBSessionCommands.m +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBSessionCommands.m @@ -3,13 +3,13 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBSessionCommands.h" #import "FBCapabilities.h" +#import "FBClassChainQueryParser.h" #import "FBConfiguration.h" #import "FBExceptions.h" #import "FBLogger.h" @@ -336,7 +336,6 @@ + (NSArray *)routes FB_SETTING_SCREENSHOT_QUALITY: @([FBConfiguration screenshotQuality]), FB_SETTING_KEYBOARD_AUTOCORRECTION: @([FBConfiguration keyboardAutocorrection]), FB_SETTING_KEYBOARD_PREDICTION: @([FBConfiguration keyboardPrediction]), - FB_SETTING_CUSTOM_SNAPSHOT_TIMEOUT: @([FBConfiguration customSnapshotTimeout]), FB_SETTING_SNAPSHOT_MAX_DEPTH: @([FBConfiguration snapshotMaxDepth]), FB_SETTING_USE_FIRST_MATCH: @([FBConfiguration useFirstMatch]), FB_SETTING_WAIT_FOR_IDLE_TIMEOUT: @([FBConfiguration waitForIdleTimeout]), @@ -348,10 +347,15 @@ + (NSArray *)routes FB_SETTING_INCLUDE_NON_MODAL_ELEMENTS: @([FBConfiguration includeNonModalElements]), FB_SETTING_ACCEPT_ALERT_BUTTON_SELECTOR: FBConfiguration.acceptAlertButtonSelector, FB_SETTING_DISMISS_ALERT_BUTTON_SELECTOR: FBConfiguration.dismissAlertButtonSelector, + FB_SETTING_AUTO_CLICK_ALERT_SELECTOR: FBConfiguration.autoClickAlertSelector, FB_SETTING_DEFAULT_ALERT_ACTION: request.session.defaultAlertAction ?: @"", FB_SETTING_MAX_TYPING_FREQUENCY: @([FBConfiguration maxTypingFrequency]), FB_SETTING_RESPECT_SYSTEM_ALERTS: @([FBConfiguration shouldRespectSystemAlerts]), FB_SETTING_USE_CLEAR_TEXT_SHORTCUT: @([FBConfiguration useClearTextShortcut]), + FB_SETTING_INCLUDE_HITTABLE_IN_PAGE_SOURCE: @([FBConfiguration includeHittableInPageSource]), + FB_SETTING_INCLUDE_NATIVE_FRAME_IN_PAGE_SOURCE: @([FBConfiguration includeNativeFrameInPageSource]), + FB_SETTING_INCLUDE_MIN_MAX_VALUE_IN_PAGE_SOURCE: @([FBConfiguration includeMinMaxValueInPageSource]), + FB_SETTING_LIMIT_XPATH_CONTEXT_SCOPE: @([FBConfiguration limitXpathContextScope]), #if !TARGET_OS_TV FB_SETTING_SCREENSHOT_ORIENTATION: [FBConfiguration humanReadableScreenshotOrientation], #endif @@ -381,7 +385,7 @@ + (NSArray *)routes [FBConfiguration setScreenshotQuality:[[settings objectForKey:FB_SETTING_SCREENSHOT_QUALITY] unsignedIntegerValue]]; } if (nil != [settings objectForKey:FB_SETTING_MJPEG_SCALING_FACTOR]) { - [FBConfiguration setMjpegScalingFactor:[[settings objectForKey:FB_SETTING_MJPEG_SCALING_FACTOR] unsignedIntegerValue]]; + [FBConfiguration setMjpegScalingFactor:[[settings objectForKey:FB_SETTING_MJPEG_SCALING_FACTOR] floatValue]]; } if (nil != [settings objectForKey:FB_SETTING_MJPEG_FIX_ORIENTATION]) { [FBConfiguration setMjpegShouldFixOrientation:[[settings objectForKey:FB_SETTING_MJPEG_FIX_ORIENTATION] boolValue]]; @@ -395,13 +399,6 @@ + (NSArray *)routes if (nil != [settings objectForKey:FB_SETTING_RESPECT_SYSTEM_ALERTS]) { [FBConfiguration setShouldRespectSystemAlerts:[[settings objectForKey:FB_SETTING_RESPECT_SYSTEM_ALERTS] boolValue]]; } - // SNAPSHOT_TIMEOUT setting is deprecated. Please use CUSTOM_SNAPSHOT_TIMEOUT instead - if (nil != [settings objectForKey:FB_SETTING_SNAPSHOT_TIMEOUT]) { - [FBConfiguration setCustomSnapshotTimeout:[[settings objectForKey:FB_SETTING_SNAPSHOT_TIMEOUT] doubleValue]]; - } - if (nil != [settings objectForKey:FB_SETTING_CUSTOM_SNAPSHOT_TIMEOUT]) { - [FBConfiguration setCustomSnapshotTimeout:[[settings objectForKey:FB_SETTING_CUSTOM_SNAPSHOT_TIMEOUT] doubleValue]]; - } if (nil != [settings objectForKey:FB_SETTING_SNAPSHOT_MAX_DEPTH]) { [FBConfiguration setSnapshotMaxDepth:[[settings objectForKey:FB_SETTING_SNAPSHOT_MAX_DEPTH] intValue]]; } @@ -438,6 +435,13 @@ + (NSArray *)routes if (nil != [settings objectForKey:FB_SETTING_DISMISS_ALERT_BUTTON_SELECTOR]) { [FBConfiguration setDismissAlertButtonSelector:(NSString *)[settings objectForKey:FB_SETTING_DISMISS_ALERT_BUTTON_SELECTOR]]; } + if (nil != [settings objectForKey:FB_SETTING_AUTO_CLICK_ALERT_SELECTOR]) { + FBCommandStatus *status = [self.class configureAutoClickAlertWithSelector:settings[FB_SETTING_AUTO_CLICK_ALERT_SELECTOR] + forSession:request.session]; + if (status.hasError) { + return FBResponseWithStatus(status); + } + } if (nil != [settings objectForKey:FB_SETTING_WAIT_FOR_IDLE_TIMEOUT]) { [FBConfiguration setWaitForIdleTimeout:[[settings objectForKey:FB_SETTING_WAIT_FOR_IDLE_TIMEOUT] doubleValue]]; } @@ -453,6 +457,18 @@ + (NSArray *)routes if (nil != [settings objectForKey:FB_SETTING_USE_CLEAR_TEXT_SHORTCUT]) { [FBConfiguration setUseClearTextShortcut:[[settings objectForKey:FB_SETTING_USE_CLEAR_TEXT_SHORTCUT] boolValue]]; } + if (nil != [settings objectForKey:FB_SETTING_INCLUDE_HITTABLE_IN_PAGE_SOURCE]) { + [FBConfiguration setIncludeHittableInPageSource:[[settings objectForKey:FB_SETTING_INCLUDE_HITTABLE_IN_PAGE_SOURCE] boolValue]]; + } + if (nil != [settings objectForKey:FB_SETTING_INCLUDE_NATIVE_FRAME_IN_PAGE_SOURCE]) { + [FBConfiguration setIncludeNativeFrameInPageSource:[[settings objectForKey:FB_SETTING_INCLUDE_NATIVE_FRAME_IN_PAGE_SOURCE] boolValue]]; + } + if (nil != [settings objectForKey:FB_SETTING_INCLUDE_MIN_MAX_VALUE_IN_PAGE_SOURCE]) { + [FBConfiguration setIncludeMinMaxValueInPageSource:[[settings objectForKey:FB_SETTING_INCLUDE_MIN_MAX_VALUE_IN_PAGE_SOURCE] boolValue]]; + } + if (nil != [settings objectForKey:FB_SETTING_LIMIT_XPATH_CONTEXT_SCOPE]) { + [FBConfiguration setLimitXpathContextScope:[[settings objectForKey:FB_SETTING_LIMIT_XPATH_CONTEXT_SCOPE] boolValue]]; + } #if !TARGET_OS_TV if (nil != [settings objectForKey:FB_SETTING_SCREENSHOT_ORIENTATION]) { @@ -471,6 +487,26 @@ + (NSArray *)routes #pragma mark - Helpers ++ (FBCommandStatus *)configureAutoClickAlertWithSelector:(NSString *)selector + forSession:(FBSession *)session +{ + if (0 == [selector length]) { + [FBConfiguration setAutoClickAlertSelector:selector]; + [session disableAlertsMonitor]; + return [FBCommandStatus ok]; + } + + NSError *error; + FBClassChain *parsedChain = [FBClassChainQueryParser parseQuery:selector error:&error]; + if (nil == parsedChain) { + return [FBCommandStatus invalidSelectorErrorWithMessage:error.localizedDescription + traceback:nil]; + } + [FBConfiguration setAutoClickAlertSelector:selector]; + [session enableAlertsMonitor]; + return [FBCommandStatus ok]; +} + + (NSString *)buildTimestamp { return [NSString stringWithFormat:@"%@ %@", diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBTouchActionCommands.h b/WebDriverAgent/WebDriverAgentLib/Commands/FBTouchActionCommands.h index b3a8e3f2aa..d9b84fc7d6 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBTouchActionCommands.h +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBTouchActionCommands.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBTouchActionCommands.m b/WebDriverAgent/WebDriverAgentLib/Commands/FBTouchActionCommands.m index c14edcb631..7788175e85 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBTouchActionCommands.m +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBTouchActionCommands.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBTouchActionCommands.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBTouchIDCommands.h b/WebDriverAgent/WebDriverAgentLib/Commands/FBTouchIDCommands.h index 6240a5f0ae..ffcf2e8126 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBTouchIDCommands.h +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBTouchIDCommands.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBTouchIDCommands.m b/WebDriverAgent/WebDriverAgentLib/Commands/FBTouchIDCommands.m index f965c1f080..9594dd6f5e 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBTouchIDCommands.m +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBTouchIDCommands.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBTouchIDCommands.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBUnknownCommands.h b/WebDriverAgent/WebDriverAgentLib/Commands/FBUnknownCommands.h index 54262cafb5..3e37d7894c 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBUnknownCommands.h +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBUnknownCommands.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBUnknownCommands.m b/WebDriverAgent/WebDriverAgentLib/Commands/FBUnknownCommands.m index ca27e9a757..7fc35b96b6 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBUnknownCommands.m +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBUnknownCommands.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBUnknownCommands.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBVideoCommands.h b/WebDriverAgent/WebDriverAgentLib/Commands/FBVideoCommands.h index b2e3eb795c..a3e7a0a650 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBVideoCommands.h +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBVideoCommands.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Commands/FBVideoCommands.m b/WebDriverAgent/WebDriverAgentLib/Commands/FBVideoCommands.m index 8366c3a796..a5c36a564e 100644 --- a/WebDriverAgent/WebDriverAgentLib/Commands/FBVideoCommands.m +++ b/WebDriverAgent/WebDriverAgentLib/Commands/FBVideoCommands.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBVideoCommands.h" diff --git a/WebDriverAgent/WebDriverAgentLib/FBAlert.h b/WebDriverAgent/WebDriverAgentLib/FBAlert.h index 22f28a710a..8e9ec8cda5 100644 --- a/WebDriverAgent/WebDriverAgentLib/FBAlert.h +++ b/WebDriverAgent/WebDriverAgentLib/FBAlert.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/FBAlert.m b/WebDriverAgent/WebDriverAgentLib/FBAlert.m index b06e267888..2e2de763d8 100644 --- a/WebDriverAgent/WebDriverAgentLib/FBAlert.m +++ b/WebDriverAgent/WebDriverAgentLib/FBAlert.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBAlert.h" @@ -50,7 +49,7 @@ - (BOOL)isPresent if (nil == self.alertElement) { return NO; } - [self.alertElement fb_takeSnapshot]; + [self.alertElement fb_customSnapshot]; return YES; } @catch (NSException *) { return NO; @@ -82,7 +81,7 @@ - (NSString *)text } NSMutableArray *resultText = [NSMutableArray array]; - id snapshot = self.alertElement.lastSnapshot; + id snapshot = self.alertElement.lastSnapshot ?: [self.alertElement fb_customSnapshot]; BOOL isSafariAlert = [self.class isSafariWebAlertWithSnapshot:snapshot]; [snapshot enumerateDescendantsUsingBlock:^(id descendant) { XCUIElementType elementType = descendant.elementType; @@ -145,7 +144,8 @@ - (NSArray *)buttonLabels } NSMutableArray *labels = [NSMutableArray array]; - [self.alertElement.lastSnapshot enumerateDescendantsUsingBlock:^(id descendant) { + id alertSnapshot = self.alertElement.lastSnapshot ?: [self.alertElement fb_customSnapshot]; + [alertSnapshot enumerateDescendantsUsingBlock:^(id descendant) { if (descendant.elementType != XCUIElementTypeButton) { return; } @@ -163,7 +163,7 @@ - (BOOL)acceptWithError:(NSError **)error return [self notPresentWithError:error]; } - id alertSnapshot = self.alertElement.lastSnapshot; + id alertSnapshot = self.alertElement.lastSnapshot ?: [self.alertElement fb_customSnapshot]; XCUIElement *acceptButton = nil; if (FBConfiguration.acceptAlertButtonSelector.length) { NSString *errorReason = nil; @@ -204,7 +204,7 @@ - (BOOL)dismissWithError:(NSError **)error return [self notPresentWithError:error]; } - id alertSnapshot = self.alertElement.lastSnapshot; + id alertSnapshot = self.alertElement.lastSnapshot ?: [self.alertElement fb_customSnapshot]; XCUIElement *dismissButton = nil; if (FBConfiguration.dismissAlertButtonSelector.length) { NSString *errorReason = nil; diff --git a/WebDriverAgent/WebDriverAgentLib/Info.plist b/WebDriverAgent/WebDriverAgentLib/Info.plist index 4dd4120c63..4b6601c1a4 100644 --- a/WebDriverAgent/WebDriverAgentLib/Info.plist +++ b/WebDriverAgent/WebDriverAgentLib/Info.plist @@ -1,26 +1,26 @@ - - CFBundleDevelopmentRegion - en - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - FMWK - CFBundleShortVersionString - 8.11.1 - CFBundleSignature - ???? - CFBundleVersion - 8.11.1 - NSPrincipalClass - - + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + FMWK + CFBundleShortVersionString + 10.4.2 + CFBundleSignature + ???? + CFBundleVersion + 10.4.2 + NSPrincipalClass + + diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBCommandHandler.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBCommandHandler.h index bde028d68b..c4ac83b714 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBCommandHandler.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBCommandHandler.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBCommandStatus.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBCommandStatus.h index 82bee1f606..0929ff10ce 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBCommandStatus.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBCommandStatus.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import @@ -19,7 +18,7 @@ NS_ASSUME_NONNULL_BEGIN @property (nonatomic, nullable, readonly) NSString* message; @property (nonatomic, nullable, readonly) NSString* traceback; @property (nonatomic, readonly) HTTPStatusCode statusCode; - +@property (nonatomic, readonly) BOOL hasError; + (instancetype)ok; diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBCommandStatus.m b/WebDriverAgent/WebDriverAgentLib/Routing/FBCommandStatus.m index 453fb6192c..fb5d2439e7 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBCommandStatus.m +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBCommandStatus.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBCommandStatus.h" @@ -109,6 +108,11 @@ - (instancetype)initWithError:(NSString *)error return self; } +- (BOOL)hasError +{ + return self.statusCode != kHTTPStatusCodeOK; +} + + (instancetype)ok { return [[FBCommandStatus alloc] initWithValue:nil]; diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBElement.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBElement.h index 7cc8f269c2..b4e6a75224 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBElement.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBElement.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import @@ -20,6 +19,9 @@ NS_ASSUME_NONNULL_BEGIN /*! Element's frame in normalized (rounded dimensions without Infinity values) CGRect format */ @property (nonatomic, readonly, assign) CGRect wdFrame; +/*! Represents the element's frame as a CGRect, preserving the actual values. */ +@property (nonatomic, readonly, assign) CGRect wdNativeFrame; + /*! Element's wsFrame in NSDictionary format */ @property (nonatomic, readonly, copy) NSDictionary *wdRect; @@ -35,6 +37,9 @@ NS_ASSUME_NONNULL_BEGIN /*! Element's type */ @property (nonatomic, readonly, copy) NSString *wdType; +/*! Element's accessibility traits as a comma-separated string */ +@property (nonatomic, readonly, copy) NSString *wdTraits; + /*! Element's value */ @property (nonatomic, readonly, strong, nullable) NSString *wdValue; @@ -62,6 +67,15 @@ NS_ASSUME_NONNULL_BEGIN /*! Element's index relatively to its parent. Starts from zero */ @property (nonatomic, readonly) NSUInteger wdIndex; +/*! Element's placeholder value */ +@property (nonatomic, readonly, copy, nullable) NSString *wdPlaceholderValue; + +/*! Element's minimum value */ +@property (nonatomic, readonly, strong, nullable) NSNumber *wdMinValue; + +/*! Element's maximum value */ +@property (nonatomic, readonly, strong, nullable) NSNumber *wdMaxValue; + /** Returns value of given property specified in WebDriver Spec Check the FBElement protocol to get list of supported attributes. diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBElementCache.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBElementCache.h index 13100eeb2c..1c7eb47642 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBElementCache.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBElementCache.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import @@ -35,26 +34,20 @@ extern const int ELEMENT_CACHE_SIZE; @param uuid uuid of element to fetch @return element - @throws FBStaleElementException if the found element is not present in DOM anymore @throws FBInvalidArgumentException if uuid is nil */ - (XCUIElement *)elementForUUID:(NSString *)uuid; /** - Returns cached element + Returns cached element resolved with default snapshot attributes @param uuid uuid of element to fetch - @param additionalAttributes Add additonal attribute names if the snapshot should contain - them in `addtionalAttributes` section. nil value resolves the snapshot with standard attributes. - @param maxDepth The maximum depth of the snapshot. Only works if additional attributes are provided. - `nil` value means to use the default maximum depth value. + @param checkStaleness Whether to throw FBStaleElementException if the found element is not present in DOM anymore @return element - @throws FBStaleElementException if the found element is not present in DOM anymore + @throws FBStaleElementException if `checkStaleness` is enabled @throws FBInvalidArgumentException if uuid is nil */ -- (XCUIElement *)elementForUUID:(NSString *)uuid - resolveForAdditionalAttributes:(nullable NSArray *)additionalAttributes - andMaxDepth:(nullable NSNumber *)maxDepth; +- (XCUIElement *)elementForUUID:(NSString *)uuid checkStaleness:(BOOL)checkStaleness; /** Checks element existence in the cache diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBElementCache.m b/WebDriverAgent/WebDriverAgentLib/Routing/FBElementCache.m index 1f069bec65..756624246a 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBElementCache.m +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBElementCache.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBElementCache.h" @@ -26,7 +25,6 @@ @interface FBElementCache () @property (nonatomic, strong) LRUCache *elementCache; -@property (nonatomic) BOOL elementsNeedReset; @end @implementation FBElementCache @@ -38,7 +36,6 @@ - (instancetype)init return nil; } _elementCache = [[LRUCache alloc] initWithCapacity:ELEMENT_CACHE_SIZE]; - _elementsNeedReset = NO; return self; } @@ -50,19 +47,16 @@ - (NSString *)storeElement:(XCUIElement *)element } @synchronized (self.elementCache) { [self.elementCache setObject:element forKey:uuid]; - self.elementsNeedReset = YES; } return uuid; } - (XCUIElement *)elementForUUID:(NSString *)uuid { - return [self elementForUUID:uuid resolveForAdditionalAttributes:nil andMaxDepth:nil]; + return [self elementForUUID:uuid checkStaleness:NO]; } -- (XCUIElement *)elementForUUID:(NSString *)uuid - resolveForAdditionalAttributes:(NSArray *)additionalAttributes - andMaxDepth:(NSNumber *)maxDepth +- (XCUIElement *)elementForUUID:(NSString *)uuid checkStaleness:(BOOL)checkStaleness { if (!uuid) { NSString *reason = [NSString stringWithFormat:@"Cannot extract cached element for UUID: %@", uuid]; @@ -71,23 +65,25 @@ - (XCUIElement *)elementForUUID:(NSString *)uuid XCUIElement *element; @synchronized (self.elementCache) { - [self resetElements]; element = [self.elementCache objectForKey:uuid]; } if (nil == element) { NSString *reason = [NSString stringWithFormat:@"The element identified by \"%@\" is either not present or it has expired from the internal cache. Try to find it again", uuid]; @throw [NSException exceptionWithName:FBStaleElementException reason:reason userInfo:@{}]; } - // This will throw FBStaleElementException exception if the element is stale - // or resolve the element and set lastSnapshot property - if (nil == additionalAttributes) { - [element fb_takeSnapshot]; - } else { - NSMutableArray *attributes = [NSMutableArray arrayWithArray:FBStandardAttributeNames()]; - [attributes addObjectsFromArray:additionalAttributes]; - [element fb_snapshotWithAttributes:attributes.copy maxDepth:maxDepth]; + if (checkStaleness) { + @try { + [element fb_standardSnapshot]; + } @catch (NSException *exception) { + // if the snapshot method threw FBStaleElementException (implying the element is stale) we need to explicitly remove it from the cache, PR: https://github.com/appium/WebDriverAgent/pull/985 + if ([exception.name isEqualToString:FBStaleElementException]) { + @synchronized (self.elementCache) { + [self.elementCache removeObjectForKey:uuid]; + } + } + @throw exception; + } } - element.fb_isResolvedFromCache = @(YES); return element; } @@ -101,20 +97,4 @@ - (BOOL)hasElementWithUUID:(NSString *)uuid } } -- (void)resetElements -{ - if (!self.elementsNeedReset) { - return; - } - - for (XCUIElement *element in self.elementCache.allObjects) { - element.lastSnapshot = nil; - if (nil != element.query) { - element.query.rootElementSnapshot = nil; - } - element.fb_isResolvedFromCache = @(NO); - } - self.elementsNeedReset = NO; -} - @end diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBElementUtils.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBElementUtils.h index a0b6da8394..0c4de4b7f1 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBElementUtils.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBElementUtils.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBElementUtils.m b/WebDriverAgent/WebDriverAgentLib/Routing/FBElementUtils.m index 8aec9d8a85..cc89d2fc7c 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBElementUtils.m +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBElementUtils.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBExceptionHandler.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBExceptionHandler.h index 693e5c4078..cc1dc0f221 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBExceptionHandler.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBExceptionHandler.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBExceptionHandler.m b/WebDriverAgent/WebDriverAgentLib/Routing/FBExceptionHandler.m index 811a0efb50..b5e1ec0606 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBExceptionHandler.m +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBExceptionHandler.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBExceptionHandler.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBExceptions.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBExceptions.h index 13fda9f4ce..b802da673b 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBExceptions.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBExceptions.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBExceptions.m b/WebDriverAgent/WebDriverAgentLib/Routing/FBExceptions.m index 93c1837e75..feb8a4d50c 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBExceptions.m +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBExceptions.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBExceptions.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBResponseJSONPayload.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBResponseJSONPayload.h index 14f6c1c84b..8c863e9992 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBResponseJSONPayload.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBResponseJSONPayload.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBResponseJSONPayload.m b/WebDriverAgent/WebDriverAgentLib/Routing/FBResponseJSONPayload.m index 4ad1c37ad1..8782b8e9e2 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBResponseJSONPayload.m +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBResponseJSONPayload.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBResponseJSONPayload.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBResponsePayload.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBResponsePayload.h index 9ff7a9308f..b29b8f98a4 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBResponsePayload.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBResponsePayload.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBResponsePayload.m b/WebDriverAgent/WebDriverAgentLib/Routing/FBResponsePayload.m index 08fcd63fed..809cd41e8b 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBResponsePayload.m +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBResponsePayload.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBResponsePayload.h" @@ -34,24 +33,41 @@ return FBResponseWithStatus([FBCommandStatus okWithValue:object]); } -id FBResponseWithCachedElement(XCUIElement *element, FBElementCache *elementCache, BOOL compact) +XCUIElement *maybeStable(XCUIElement *element) { BOOL useNativeCachingStrategy = nil == FBSession.activeSession ? YES : FBSession.activeSession.useNativeCachingStrategy; - [elementCache storeElement:(useNativeCachingStrategy ? element : element.fb_stableInstance)]; - return FBResponseWithStatus([FBCommandStatus okWithValue:FBDictionaryResponseWithElement(element, compact)]); + if (useNativeCachingStrategy) { + return element; + } + + XCUIElement *result = element; + id snapshot = element.lastSnapshot + ?: element.fb_cachedSnapshot + ?: [element fb_standardSnapshot]; + NSString *uid = [FBXCElementSnapshotWrapper wdUIDWithSnapshot:snapshot]; + if (nil != uid) { + result = [element fb_stableInstanceWithUid:uid]; + } + return result; +} + +id FBResponseWithCachedElement(XCUIElement *element, FBElementCache *elementCache, BOOL compact) +{ + [elementCache storeElement:maybeStable(element)]; + NSDictionary *response = FBDictionaryResponseWithElement(element, compact); + element.lastSnapshot = nil; + return FBResponseWithStatus([FBCommandStatus okWithValue:response]); } id FBResponseWithCachedElements(NSArray *elements, FBElementCache *elementCache, BOOL compact) { NSMutableArray *elementsResponse = [NSMutableArray array]; - BOOL useNativeCachingStrategy = nil == FBSession.activeSession - ? YES - : FBSession.activeSession.useNativeCachingStrategy; for (XCUIElement *element in elements) { - [elementCache storeElement:(useNativeCachingStrategy ? element : element.fb_stableInstance)]; + [elementCache storeElement:maybeStable(element)]; [elementsResponse addObject:FBDictionaryResponseWithElement(element, compact)]; + element.lastSnapshot = nil; } return FBResponseWithStatus([FBCommandStatus okWithValue:elementsResponse]); } @@ -91,41 +107,42 @@ inline NSDictionary *FBDictionaryResponseWithElement(XCUIElement *element, BOOL compact) { - id snapshot = nil; - if (nil != element.query.rootElementSnapshot) { - snapshot = element.fb_cachedSnapshot; - } - if (nil == snapshot) { - snapshot = element.lastSnapshot ?: element.fb_takeSnapshot; - } - NSDictionary *compactResult = FBToElementDict((NSString *)[FBXCElementSnapshotWrapper wdUIDWithSnapshot:snapshot]); - if (compact) { - return compactResult; - } + __block NSDictionary *elementResponse = nil; + @autoreleasepool { + id snapshot = element.lastSnapshot + ?: element.fb_cachedSnapshot + ?: [element fb_customSnapshot]; + NSDictionary *compactResult = FBToElementDict((NSString *)[FBXCElementSnapshotWrapper wdUIDWithSnapshot:snapshot]); + if (compact) { + elementResponse = compactResult; + return elementResponse; + } - NSMutableDictionary *result = compactResult.mutableCopy; - FBXCElementSnapshotWrapper *wrappedSnapshot = [FBXCElementSnapshotWrapper ensureWrapped:snapshot]; - NSArray *fields = [FBConfiguration.elementResponseAttributes componentsSeparatedByString:@","]; - for (NSString *field in fields) { - // 'name' here is the w3c-approved identifier for what we mean by 'type' - if ([field isEqualToString:@"name"] || [field isEqualToString:@"type"]) { - result[field] = wrappedSnapshot.wdType; - } else if ([field isEqualToString:@"text"]) { - result[field] = FBFirstNonEmptyValue(wrappedSnapshot.wdValue, wrappedSnapshot.wdLabel) ?: [NSNull null]; - } else if ([field isEqualToString:@"rect"]) { - result[field] = wrappedSnapshot.wdRect; - } else if ([field isEqualToString:@"enabled"]) { - result[field] = @(wrappedSnapshot.wdEnabled); - } else if ([field isEqualToString:@"displayed"]) { - result[field] = @(wrappedSnapshot.wdVisible); - } else if ([field isEqualToString:@"selected"]) { - result[field] = @(wrappedSnapshot.wdSelected); - } else if ([field isEqualToString:@"label"]) { - result[field] = wrappedSnapshot.wdLabel ?: [NSNull null]; - } else if ([field hasPrefix:arbitraryAttrPrefix]) { - NSString *attributeName = [field substringFromIndex:[arbitraryAttrPrefix length]]; - result[field] = [wrappedSnapshot fb_valueForWDAttributeName:attributeName] ?: [NSNull null]; + NSMutableDictionary *result = compactResult.mutableCopy; + FBXCElementSnapshotWrapper *wrappedSnapshot = [FBXCElementSnapshotWrapper ensureWrapped:snapshot]; + NSArray *fields = [FBConfiguration.elementResponseAttributes componentsSeparatedByString:@","]; + for (NSString *field in fields) { + // 'name' here is the w3c-approved identifier for what we mean by 'type' + if ([field isEqualToString:@"name"] || [field isEqualToString:@"type"]) { + result[field] = wrappedSnapshot.wdType; + } else if ([field isEqualToString:@"text"]) { + result[field] = FBFirstNonEmptyValue(wrappedSnapshot.wdValue, wrappedSnapshot.wdLabel) ?: [NSNull null]; + } else if ([field isEqualToString:@"rect"]) { + result[field] = wrappedSnapshot.wdRect; + } else if ([field isEqualToString:@"enabled"]) { + result[field] = @(wrappedSnapshot.wdEnabled); + } else if ([field isEqualToString:@"displayed"]) { + result[field] = @(wrappedSnapshot.wdVisible); + } else if ([field isEqualToString:@"selected"]) { + result[field] = @(wrappedSnapshot.wdSelected); + } else if ([field isEqualToString:@"label"]) { + result[field] = wrappedSnapshot.wdLabel ?: [NSNull null]; + } else if ([field hasPrefix:arbitraryAttrPrefix]) { + NSString *attributeName = [field substringFromIndex:[arbitraryAttrPrefix length]]; + result[field] = [wrappedSnapshot fb_valueForWDAttributeName:attributeName] ?: [NSNull null]; + } } + elementResponse = result.copy; } - return result.copy; + return elementResponse; } diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBRoute.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBRoute.h index 2d3138686c..fce8dd8a98 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBRoute.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBRoute.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBRoute.m b/WebDriverAgent/WebDriverAgentLib/Routing/FBRoute.m index 5d740de7e3..fbe69b8c3c 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBRoute.m +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBRoute.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBRoute.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBRouteRequest-Private.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBRouteRequest-Private.h index d5bd31f10d..7144bd80ba 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBRouteRequest-Private.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBRouteRequest-Private.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBRouteRequest.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBRouteRequest.h index 7647cd823f..c7938d5d67 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBRouteRequest.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBRouteRequest.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBRouteRequest.m b/WebDriverAgent/WebDriverAgentLib/Routing/FBRouteRequest.m index e7d2743f23..b8656d2852 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBRouteRequest.m +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBRouteRequest.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBRouteRequest-Private.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingContainer.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingContainer.h index 48e5c7481a..ce655dd7c0 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingContainer.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingContainer.h @@ -4,8 +4,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingContainer.m b/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingContainer.m index b0a744dc0a..608d7bfdfc 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingContainer.m +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingContainer.m @@ -4,8 +4,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBScreenRecordingContainer.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingPromise.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingPromise.h index a869187617..6b3fcb3c6d 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingPromise.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingPromise.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingPromise.m b/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingPromise.m index 9de9dbaf11..e1193a1335 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingPromise.m +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingPromise.m @@ -4,8 +4,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBScreenRecordingPromise.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingRequest.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingRequest.h index 5e24e5588d..f0a61ef247 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingRequest.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingRequest.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingRequest.m b/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingRequest.m index 5249b76b03..32c5b05796 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingRequest.m +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBScreenRecordingRequest.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBScreenRecordingRequest.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBSession-Private.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBSession-Private.h index 45d5a8c3c9..792fcd7384 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBSession-Private.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBSession-Private.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBSession.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBSession.h index b617ae0960..61b1f87429 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBSession.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBSession.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import @@ -121,6 +120,22 @@ extern NSString* const FB_SAFARI_BUNDLE_ID; */ - (NSUInteger)applicationStateWithBundleId:(NSString *)bundleIdentifier; +/** + Allows to enable automated session alerts monitoring. + Repeated calls are ignored if alerts monitoring has been already enabled. + + @returns YES if the actual alerts monitoring state has been changed + */ +- (BOOL)enableAlertsMonitor; + +/** + Allows to disable automated alerts monitoring + Repeated calls are ignored if alerts monitoring has been already disabled. + + @returns YES if the actual alerts monitoring state has been changed + */ +- (BOOL)disableAlertsMonitor; + @end NS_ASSUME_NONNULL_END diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBSession.m b/WebDriverAgent/WebDriverAgentLib/Routing/FBSession.m index a4460b4a88..b8de5edf6a 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBSession.m +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBSession.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBSession.h" @@ -25,6 +24,7 @@ #import "FBXCTestDaemonsProxy.h" #import "XCUIApplication+FBQuiescence.h" #import "XCUIElement.h" +#import "XCUIElement+FBClassChain.h" /*! The intial value for the default application property. @@ -53,6 +53,22 @@ @implementation FBSession (FBAlertsMonitorDelegate) - (void)didDetectAlert:(FBAlert *)alert { + NSString *autoClickAlertSelector = FBConfiguration.autoClickAlertSelector; + if ([autoClickAlertSelector length] > 0) { + @try { + NSArray *matches = [alert.alertElement fb_descendantsMatchingClassChain:autoClickAlertSelector + shouldReturnAfterFirstMatch:YES]; + if (matches.count > 0) { + [[matches objectAtIndex:0] tap]; + } + } @catch (NSException *e) { + [FBLogger logFmt:@"Could not click at the alert element '%@'. Original error: %@", + autoClickAlertSelector, e.description]; + } + // This setting has priority over other settings if enabled + return; + } + if (nil == self.defaultAlertAction || 0 == self.defaultAlertAction.length) { return; } @@ -125,23 +141,41 @@ + (instancetype)initWithApplication:(nullable XCUIApplication *)application defaultAlertAction:(NSString *)defaultAlertAction { FBSession *session = [self.class initWithApplication:application]; - session.alertsMonitor = [[FBAlertsMonitor alloc] init]; - session.alertsMonitor.delegate = (id)session; session.defaultAlertAction = [defaultAlertAction lowercaseString]; - [session.alertsMonitor enable]; + [session enableAlertsMonitor]; return session; } +- (BOOL)enableAlertsMonitor +{ + if (nil != self.alertsMonitor) { + return NO; + } + + self.alertsMonitor = [[FBAlertsMonitor alloc] init]; + self.alertsMonitor.delegate = (id)self; + [self.alertsMonitor enable]; + return YES; +} + +- (BOOL)disableAlertsMonitor +{ + if (nil == self.alertsMonitor) { + return NO; + } + + [self.alertsMonitor disable]; + self.alertsMonitor = nil; + return YES; +} + - (void)kill { if (nil == _activeSession) { return; } - if (nil != self.alertsMonitor) { - [self.alertsMonitor disable]; - self.alertsMonitor = nil; - } + [self disableAlertsMonitor]; FBScreenRecordingPromise *activeScreenRecording = FBScreenRecordingContainer.sharedInstance.screenRecordingPromise; if (nil != activeScreenRecording) { @@ -178,10 +212,13 @@ - (XCUIApplication *)activeApplication if (nil != self.testedApplication) { XCUIApplicationState testedAppState = self.testedApplication.state; if (testedAppState >= XCUIApplicationStateRunningForeground) { - // We look for `SBTransientOverlayWindow` elements for half modals. See https://github.com/appium/WebDriverAgent/pull/946 - NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K == %@ OR %K == %@", + NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K == %@ OR %K IN {%@, %@}", @"elementType", @(XCUIElementTypeAlert), - @"identifier", @"SBTransientOverlayWindow"]; + // To look for `SBTransientOverlayWindow` elements. See https://github.com/appium/WebDriverAgent/pull/946 + @"identifier", @"SBTransientOverlayWindow", + // To look for 'criticalAlertSetting' elements https://developer.apple.com/documentation/usernotifications/unnotificationsettings/criticalalertsetting + // See https://github.com/appium/appium/issues/20835 + @"NotificationShortLookView"]; if ([FBConfiguration shouldRespectSystemAlerts] && [[XCUIApplication.fb_systemApplication descendantsMatchingType:XCUIElementTypeAny] matchingPredicate:searchPredicate].count > 0) { diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBTCPSocket.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBTCPSocket.h index 895ae75f54..31adc7e22f 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBTCPSocket.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBTCPSocket.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "GCDAsyncSocket.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBTCPSocket.m b/WebDriverAgent/WebDriverAgentLib/Routing/FBTCPSocket.m index 527acdf4aa..fabd22074b 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBTCPSocket.m +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBTCPSocket.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBTCPSocket.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBWebServer.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBWebServer.h index a857a10c95..34bca6515d 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBWebServer.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBWebServer.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBWebServer.m b/WebDriverAgent/WebDriverAgentLib/Routing/FBWebServer.m index ff9e4c424b..0b82eaff58 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBWebServer.m +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBWebServer.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBWebServer.h" @@ -93,6 +92,12 @@ - (void)startHTTPServer [self registerServerKeyRouteHandlers]; NSRange serverPortRange = FBConfiguration.bindingPortRange; + NSString *bindingIP = FBConfiguration.bindingIPAddress; + if (bindingIP != nil) { + [self.server setInterface:bindingIP]; + [FBLogger logFmt:@"Using custom binding IP address: %@", bindingIP]; + } + NSError *error; BOOL serverStarted = NO; @@ -112,7 +117,9 @@ - (void)startHTTPServer [FBLogger logFmt:@"Last attempt to start web server failed with error %@", [error description]]; abort(); } - [FBLogger logFmt:@"%@http://%@:%d%@", FBServerURLBeginMarker, [XCUIDevice sharedDevice].fb_wifiIPAddress ?: @"localhost", [self.server port], FBServerURLEndMarker]; + + NSString *serverHost = bindingIP ?: ([XCUIDevice sharedDevice].fb_wifiIPAddress ?: @"127.0.0.1"); + [FBLogger logFmt:@"%@http://%@:%d%@", FBServerURLBeginMarker, serverHost, [self.server port], FBServerURLEndMarker]; } - (void)initScreenshotsBroadcaster @@ -142,7 +149,7 @@ - (void)readMjpegSettingsFromEnv NSDictionary *env = NSProcessInfo.processInfo.environment; NSString *scalingFactor = [env objectForKey:@"MJPEG_SCALING_FACTOR"]; if (scalingFactor != nil && [scalingFactor length] > 0) { - [FBConfiguration setMjpegScalingFactor:[scalingFactor integerValue]]; + [FBConfiguration setMjpegScalingFactor:[scalingFactor floatValue]]; } NSString *screenshotQuality = [env objectForKey:@"MJPEG_SERVER_SCREENSHOT_QUALITY"]; if (screenshotQuality != nil && [screenshotQuality length] > 0) { diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBXCAccessibilityElement.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBXCAccessibilityElement.h index 701edcd8db..dd35a37855 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBXCAccessibilityElement.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBXCAccessibilityElement.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBXCAccessibilityElement.m b/WebDriverAgent/WebDriverAgentLib/Routing/FBXCAccessibilityElement.m index 4535be6761..39f22913cf 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBXCAccessibilityElement.m +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBXCAccessibilityElement.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBXCAccessibilityElement.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBXCDeviceEvent.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBXCDeviceEvent.h index b27b667e0f..64139f9f64 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBXCDeviceEvent.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBXCDeviceEvent.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBXCDeviceEvent.m b/WebDriverAgent/WebDriverAgentLib/Routing/FBXCDeviceEvent.m index 8f2c9609b3..6a673e1518 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBXCDeviceEvent.m +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBXCDeviceEvent.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBXCDeviceEvent.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBXCElementSnapshot.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBXCElementSnapshot.h index a3076ec25c..500d9a8463 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBXCElementSnapshot.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBXCElementSnapshot.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBXCElementSnapshot.m b/WebDriverAgent/WebDriverAgentLib/Routing/FBXCElementSnapshot.m index 11d106890c..5fe6020488 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBXCElementSnapshot.m +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBXCElementSnapshot.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBXCElementSnapshot.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBXCElementSnapshotWrapper.h b/WebDriverAgent/WebDriverAgentLib/Routing/FBXCElementSnapshotWrapper.h index e9b763143c..2309d6b580 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBXCElementSnapshotWrapper.h +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBXCElementSnapshotWrapper.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBXCElementSnapshot.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Routing/FBXCElementSnapshotWrapper.m b/WebDriverAgent/WebDriverAgentLib/Routing/FBXCElementSnapshotWrapper.m index 1beb87bb29..4b3e0e7f5e 100644 --- a/WebDriverAgent/WebDriverAgentLib/Routing/FBXCElementSnapshotWrapper.m +++ b/WebDriverAgent/WebDriverAgentLib/Routing/FBXCElementSnapshotWrapper.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBXCElementSnapshotWrapper.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBAccessibilityTraits.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBAccessibilityTraits.h new file mode 100644 index 0000000000..b5ffa5998f --- /dev/null +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBAccessibilityTraits.h @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + Converts accessibility traits bitmask to an array of string representations + @param traits The accessibility traits bitmask + @return Array of strings representing the accessibility traits + */ +NSArray *FBAccessibilityTraitsToStringsArray(unsigned long long traits); + +NS_ASSUME_NONNULL_END diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBAccessibilityTraits.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBAccessibilityTraits.m new file mode 100644 index 0000000000..74ce9ec7ce --- /dev/null +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBAccessibilityTraits.m @@ -0,0 +1,61 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import "FBAccessibilityTraits.h" + +NSArray *FBAccessibilityTraitsToStringsArray(unsigned long long traits) { + NSMutableArray *traitStringsArray; + NSNumber *key; + + static NSDictionary *traitsMapping; + static dispatch_once_t onceToken; + + dispatch_once(&onceToken, ^{ + NSMutableDictionary *mapping = [@{ + @(UIAccessibilityTraitNone): @"None", + @(UIAccessibilityTraitButton): @"Button", + @(UIAccessibilityTraitLink): @"Link", + @(UIAccessibilityTraitHeader): @"Header", + @(UIAccessibilityTraitSearchField): @"SearchField", + @(UIAccessibilityTraitImage): @"Image", + @(UIAccessibilityTraitSelected): @"Selected", + @(UIAccessibilityTraitPlaysSound): @"PlaysSound", + @(UIAccessibilityTraitKeyboardKey): @"KeyboardKey", + @(UIAccessibilityTraitStaticText): @"StaticText", + @(UIAccessibilityTraitSummaryElement): @"SummaryElement", + @(UIAccessibilityTraitNotEnabled): @"NotEnabled", + @(UIAccessibilityTraitUpdatesFrequently): @"UpdatesFrequently", + @(UIAccessibilityTraitStartsMediaSession): @"StartsMediaSession", + @(UIAccessibilityTraitAdjustable): @"Adjustable", + @(UIAccessibilityTraitAllowsDirectInteraction): @"AllowsDirectInteraction", + @(UIAccessibilityTraitCausesPageTurn): @"CausesPageTurn", + @(UIAccessibilityTraitTabBar): @"TabBar" + } mutableCopy]; + + #if __clang_major__ >= 16 + // Add iOS 17.0 specific traits if available + if (@available(iOS 17.0, *)) { + [mapping addEntriesFromDictionary:@{ + @(UIAccessibilityTraitToggleButton): @"ToggleButton", + @(UIAccessibilityTraitSupportsZoom): @"SupportsZoom" + }]; + } + #endif + + traitsMapping = [mapping copy]; + }); + + traitStringsArray = [NSMutableArray array]; + for (key in traitsMapping) { + if (traits & [key unsignedLongLongValue] && nil != traitsMapping[key]) { + [traitStringsArray addObject:(id)traitsMapping[key]]; + } + } + + return [traitStringsArray copy]; +} diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBActiveAppDetectionPoint.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBActiveAppDetectionPoint.h index 6bc4887e93..a65bd38800 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBActiveAppDetectionPoint.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBActiveAppDetectionPoint.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBActiveAppDetectionPoint.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBActiveAppDetectionPoint.m index db571b5843..2f05ab8787 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBActiveAppDetectionPoint.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBActiveAppDetectionPoint.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the -* LICENSE file in the root directory of this source tree. An additional grant -* of patent rights can be found in the PATENTS file in the same directory. +* LICENSE file in the root directory of this source tree. */ #import "FBActiveAppDetectionPoint.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBAlertsMonitor.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBAlertsMonitor.h index 79bb6a3f1a..069a73474a 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBAlertsMonitor.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBAlertsMonitor.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBAlertsMonitor.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBAlertsMonitor.m index 1a1b6f34c8..3dd221198c 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBAlertsMonitor.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBAlertsMonitor.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBAlertsMonitor.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBBaseActionsSynthesizer.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBBaseActionsSynthesizer.h index 5f779194fd..7dc7c424fe 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBBaseActionsSynthesizer.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBBaseActionsSynthesizer.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBElementCache.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBBaseActionsSynthesizer.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBBaseActionsSynthesizer.m index 6d4c046a52..57f9d2d8e0 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBBaseActionsSynthesizer.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBBaseActionsSynthesizer.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBBaseActionsSynthesizer.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBCapabilities.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBCapabilities.h index 20dad743e4..d1339c7a66 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBCapabilities.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBCapabilities.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBCapabilities.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBCapabilities.m index b6ccc9ce43..351f23e684 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBCapabilities.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBCapabilities.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBCapabilities.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBClassChainQueryParser.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBClassChainQueryParser.h index 080810647d..c2ca9c524b 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBClassChainQueryParser.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBClassChainQueryParser.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBClassChainQueryParser.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBClassChainQueryParser.m index f04240d0de..933d0ad890 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBClassChainQueryParser.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBClassChainQueryParser.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBClassChainQueryParser.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBConfiguration.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBConfiguration.h index 7c337826cb..e6a7d45528 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBConfiguration.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBConfiguration.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import @@ -103,6 +102,14 @@ extern NSString *const FBSnapshotMaxDepthKey; + (NSUInteger)mjpegServerFramerate; + (void)setMjpegServerFramerate:(NSUInteger)framerate; +/** + Whether to limit the XPath scope to descendant items only while performing a lookup + in an element context. Enabled by default. Being disabled, allows to use XPath locators + like ".." in order to match parent items of the current context root. + */ ++ (BOOL)limitXpathContextScope; ++ (void)setLimitXpathContextScope:(BOOL)enabled; + /** The quality of display screenshots. The higher quality you set is the bigger screenshot size is. The highest quality value is 0 (lossless PNG) or 3 (lossless HEIC). The lowest quality is 2 (highly compressed JPEG). @@ -117,6 +124,12 @@ extern NSString *const FBSnapshotMaxDepthKey; */ + (NSRange)bindingPortRange; +/** + The IP address that the HTTP Server should bind to on launch. + Returns nil if not specified, which causes the server to listen on all interfaces. + */ ++ (NSString * _Nullable)bindingIPAddress; + /** The port number where the background screenshots broadcaster is supposed to run */ @@ -128,8 +141,8 @@ extern NSString *const FBSnapshotMaxDepthKey; ! Setting this to a value less than 100, especially together with orientation fixing enabled ! may lead to WDA process termination because of an excessive CPU usage. */ -+ (NSUInteger)mjpegScalingFactor; -+ (void)setMjpegScalingFactor:(NSUInteger)scalingFactor; ++ (CGFloat)mjpegScalingFactor; ++ (void)setMjpegScalingFactor:(CGFloat)scalingFactor; /** YES if verbose logging is enabled. NO otherwise. @@ -177,14 +190,6 @@ typedef NS_ENUM(NSInteger, FBConfigurationKeyboardPreference) { + (void)setKeyboardPrediction:(BOOL)isEnabled; + (FBConfigurationKeyboardPreference)keyboardPrediction; -/** - * The maximum time to wait until accessibility snapshot is taken - * - * @param timeout The number of float seconds to wait (15 seconds by default) - */ -+ (void)setCustomSnapshotTimeout:(NSTimeInterval)timeout; -+ (NSTimeInterval)customSnapshotTimeout; - /** Sets maximum depth for traversing elements tree from parents to children while requesting XCElementSnapshot. Used to set maxDepth value in a dictionary provided by XCAXClient_iOS's method defaultParams. @@ -283,6 +288,12 @@ typedef NS_ENUM(NSInteger, FBConfigurationKeyboardPreference) { + (void)setDismissAlertButtonSelector:(NSString *)classChainSelector; + (NSString *)dismissAlertButtonSelector; +/** + Sets class chain selector to apply for an automated alert click + */ ++ (void)setAutoClickAlertSelector:(NSString *)classChainSelector; ++ (NSString *)autoClickAlertSelector; + /** * Whether to use HIDEvent for text clear. * By default this is enabled and HIDEvent is used for text clear. @@ -326,6 +337,45 @@ typedef NS_ENUM(NSInteger, FBConfigurationKeyboardPreference) { */ + (void)resetSessionSettings; +/** + * Whether to calculate `hittable` attribute using native APIs + * instead of legacy heuristics. + * This flag improves accuracy, but may affect performance. + * Disabled by default. + * + * @param enabled Either YES or NO + */ ++ (void)setIncludeHittableInPageSource:(BOOL)enabled; ++ (BOOL)includeHittableInPageSource; + +/** + * Whether to include `nativeFrame` attribute in the XML page source. + * + * When enabled, the XML representation will contain the precise rendered + * frame of the UI element. + * + * This value is more accurate than the legacy `wdFrame`, which applies rounding + * and may introduce inconsistencies in size and position calculations. + * + * The value is disabled by default to avoid potential performance overhead. + * + * @param enabled Either YES or NO + */ ++ (void)setIncludeNativeFrameInPageSource:(BOOL)enabled; ++ (BOOL)includeNativeFrameInPageSource; + +/** + * Whether to include `minValue`/`maxValue` attributes in the page source. + * These attributes are retrieved from native element snapshots and represent + * value boundaries for elements like sliders or progress indicators. + * This may affect performance if used on many elements. + * Disabled by default. + * + * @param enabled Either YES or NO + */ ++ (void)setIncludeMinMaxValueInPageSource:(BOOL)enabled; ++ (BOOL)includeMinMaxValueInPageSource; + @end NS_ASSUME_NONNULL_END diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBConfiguration.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBConfiguration.m index dab8cb4dba..8dfe31bf05 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBConfiguration.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBConfiguration.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBConfiguration.h" @@ -37,7 +36,7 @@ static BOOL FBShouldUseSingletonTestManager = YES; static BOOL FBShouldRespectSystemAlerts = NO; -static NSUInteger FBMjpegScalingFactor = 100; +static CGFloat FBMjpegScalingFactor = 100.0; static BOOL FBMjpegShouldFixOrientation = NO; static NSUInteger FBMjpegServerScreenshotQuality = 25; static NSUInteger FBMjpegServerFramerate = 10; @@ -46,20 +45,24 @@ static BOOL FBShouldTerminateApp; static NSNumber* FBMaxTypingFrequency; static NSUInteger FBScreenshotQuality; -static NSTimeInterval FBCustomSnapshotTimeout; static BOOL FBShouldUseFirstMatch; static BOOL FBShouldBoundElementsByIndex; static BOOL FBIncludeNonModalElements; static NSString *FBAcceptAlertButtonSelector; static NSString *FBDismissAlertButtonSelector; +static NSString *FBAutoClickAlertSelector; static NSTimeInterval FBWaitForIdleTimeout; static NSTimeInterval FBAnimationCoolOffTimeout; static BOOL FBShouldUseCompactResponses; static NSString *FBElementResponseAttributes; static BOOL FBUseClearTextShortcut; +static BOOL FBLimitXpathContextScope = YES; #if !TARGET_OS_TV static UIInterfaceOrientation FBScreenshotOrientation; #endif +static BOOL FBShouldIncludeHittableInPageSource = NO; +static BOOL FBShouldIncludeNativeFrameInPageSource = NO; +static BOOL FBShouldIncludeMinMaxValueInPageSource = NO; @implementation FBConfiguration @@ -134,6 +137,17 @@ + (NSRange)bindingPortRange return NSMakeRange(DefaultStartingPort, DefaultPortRange); } ++ (NSString *)bindingIPAddress +{ + // Existence of USE_IP in the environment allows specifying which interface to bind to + if (NSProcessInfo.processInfo.environment[@"USE_IP"] && + [NSProcessInfo.processInfo.environment[@"USE_IP"] length] > 0) { + return NSProcessInfo.processInfo.environment[@"USE_IP"]; + } + + return nil; +} + + (NSInteger)mjpegServerPort { if (self.mjpegServerPortFromArguments != NSNotFound) { @@ -148,12 +162,12 @@ + (NSInteger)mjpegServerPort return DefaultMjpegServerPort; } -+ (NSUInteger)mjpegScalingFactor ++ (CGFloat)mjpegScalingFactor { return FBMjpegScalingFactor; } -+ (void)setMjpegScalingFactor:(NSUInteger)scalingFactor { ++ (void)setMjpegScalingFactor:(CGFloat)scalingFactor { FBMjpegScalingFactor = scalingFactor; } @@ -359,16 +373,6 @@ + (void)setKeyboardPrediction:(BOOL)isEnabled [self configureKeyboardsPreference:isEnabled forPreferenceKey:FBKeyboardPredictionKey]; } -+ (void)setCustomSnapshotTimeout:(NSTimeInterval)timeout -{ - FBCustomSnapshotTimeout = timeout; -} - -+ (NSTimeInterval)customSnapshotTimeout -{ - return FBCustomSnapshotTimeout; -} - + (void)setSnapshotMaxDepth:(int)maxDepth { FBSetCustomParameterForElementSnapshot(FBSnapshotMaxDepthKey, @(maxDepth)); @@ -439,6 +443,16 @@ + (NSString *)dismissAlertButtonSelector return FBDismissAlertButtonSelector; } ++ (void)setAutoClickAlertSelector:(NSString *)classChainSelector +{ + FBAutoClickAlertSelector = classChainSelector; +} + ++ (NSString *)autoClickAlertSelector +{ + return FBAutoClickAlertSelector; +} + + (void)setUseClearTextShortcut:(BOOL)enabled { FBUseClearTextShortcut = enabled; @@ -449,6 +463,16 @@ + (BOOL)useClearTextShortcut return FBUseClearTextShortcut; } ++ (BOOL)limitXpathContextScope +{ + return FBLimitXpathContextScope; +} + ++ (void)setLimitXpathContextScope:(BOOL)enabled +{ + FBLimitXpathContextScope = enabled; +} + #if !TARGET_OS_TV + (BOOL)setScreenshotOrientation:(NSString *)orientation error:(NSError **)error { @@ -491,6 +515,7 @@ + (NSString *)humanReadableScreenshotOrientation return @"landscapeLeft"; case UIInterfaceOrientationUnknown: return @"auto"; + default: break; } } #endif @@ -502,7 +527,6 @@ + (void)resetSessionSettings FBElementResponseAttributes = @"type,label"; FBMaxTypingFrequency = @([self defaultTypingFrequency]); FBScreenshotQuality = 3; - FBCustomSnapshotTimeout = 15.; FBShouldUseFirstMatch = NO; FBShouldBoundElementsByIndex = NO; // This is diabled by default because enabling it prevents the accessbility snapshot to be taken @@ -510,11 +534,13 @@ + (void)resetSessionSettings FBIncludeNonModalElements = NO; FBAcceptAlertButtonSelector = @""; FBDismissAlertButtonSelector = @""; + FBAutoClickAlertSelector = @""; FBWaitForIdleTimeout = 10.; FBAnimationCoolOffTimeout = 2.; // 50 should be enough for the majority of the cases. The performance is acceptable for values up to 100. FBSetCustomParameterForElementSnapshot(FBSnapshotMaxDepthKey, @50); FBUseClearTextShortcut = YES; + FBLimitXpathContextScope = YES; #if !TARGET_OS_TV FBScreenshotOrientation = UIInterfaceOrientationUnknown; #endif @@ -630,4 +656,34 @@ + (BOOL)reduceMotionEnabled return NO; } ++ (void)setIncludeHittableInPageSource:(BOOL)enabled +{ + FBShouldIncludeHittableInPageSource = enabled; +} + ++ (BOOL)includeHittableInPageSource +{ + return FBShouldIncludeHittableInPageSource; +} + ++ (void)setIncludeNativeFrameInPageSource:(BOOL)enabled +{ + FBShouldIncludeNativeFrameInPageSource = enabled; +} + ++ (BOOL)includeNativeFrameInPageSource +{ + return FBShouldIncludeNativeFrameInPageSource; +} + ++ (void)setIncludeMinMaxValueInPageSource:(BOOL)enabled +{ + FBShouldIncludeMinMaxValueInPageSource = enabled; +} + ++ (BOOL)includeMinMaxValueInPageSource +{ + return FBShouldIncludeMinMaxValueInPageSource; +} + @end diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBDebugLogDelegateDecorator.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBDebugLogDelegateDecorator.h index edc1c0fc43..02ebf89dd2 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBDebugLogDelegateDecorator.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBDebugLogDelegateDecorator.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBDebugLogDelegateDecorator.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBDebugLogDelegateDecorator.m index 2846a1813e..b4c2c5399b 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBDebugLogDelegateDecorator.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBDebugLogDelegateDecorator.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBDebugLogDelegateDecorator.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBElementHelpers.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBElementHelpers.h new file mode 100644 index 0000000000..d0cf1b3db5 --- /dev/null +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBElementHelpers.h @@ -0,0 +1,29 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + Checks if the element is a text field + + @param elementType XCTest element type + @return YES if the element is a text field + */ +BOOL FBDoesElementSupportInnerText(XCUIElementType elementType); + +/** + Checks if the element supports min/max value attributes + + @param elementType XCTest element type + @return YES if the element type supports min/max value attributes + */ +BOOL FBDoesElementSupportMinMaxValue(XCUIElementType elementType); + +NS_ASSUME_NONNULL_END diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBElementHelpers.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBElementHelpers.m new file mode 100644 index 0000000000..6b9d340fed --- /dev/null +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBElementHelpers.m @@ -0,0 +1,21 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import "FBElementHelpers.h" + +BOOL FBDoesElementSupportInnerText(XCUIElementType elementType) { + return elementType == XCUIElementTypeTextView + || elementType == XCUIElementTypeTextField + || elementType == XCUIElementTypeSearchField + || elementType == XCUIElementTypeSecureTextField; +} + +BOOL FBDoesElementSupportMinMaxValue(XCUIElementType elementType) { + return elementType == XCUIElementTypeSlider + || elementType == XCUIElementTypeStepper; +} diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBElementTypeTransformer.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBElementTypeTransformer.h index b4097eee42..a94ff62a93 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBElementTypeTransformer.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBElementTypeTransformer.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBElementTypeTransformer.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBElementTypeTransformer.m index 7dc5b1e62b..d3748a44c2 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBElementTypeTransformer.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBElementTypeTransformer.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBElementTypeTransformer.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBErrorBuilder.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBErrorBuilder.h index 7678daf191..8435eba98d 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBErrorBuilder.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBErrorBuilder.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBErrorBuilder.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBErrorBuilder.m index cafaf503be..3ee5d8fa76 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBErrorBuilder.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBErrorBuilder.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBErrorBuilder.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBFailureProofTestCase.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBFailureProofTestCase.h index 5d744107e9..80d86483ed 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBFailureProofTestCase.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBFailureProofTestCase.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBFailureProofTestCase.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBFailureProofTestCase.m index 72d79ee1c6..ab91fd94d1 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBFailureProofTestCase.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBFailureProofTestCase.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBFailureProofTestCase.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBImageProcessor.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBImageProcessor.h index a350bd9ce0..e83b830f70 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBImageProcessor.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBImageProcessor.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBImageProcessor.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBImageProcessor.m index 16601ce8e7..7d2ada7593 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBImageProcessor.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBImageProcessor.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBImageProcessor.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBImageUtils.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBImageUtils.h index 15a04f6fe1..07501657fe 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBImageUtils.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBImageUtils.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBImageUtils.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBImageUtils.m index b1d2f9b5b8..d991cea180 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBImageUtils.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBImageUtils.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBImageUtils.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBKeyboard.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBKeyboard.h index fa1515e6b6..c3c5f8ecf0 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBKeyboard.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBKeyboard.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBKeyboard.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBKeyboard.m index d90a68e295..af3529eb3f 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBKeyboard.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBKeyboard.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBKeyboard.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBLogger.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBLogger.h index 3626fa520f..c92b7ef7e7 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBLogger.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBLogger.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBLogger.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBLogger.m index 9466b86c45..060b8f00ba 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBLogger.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBLogger.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBLogger.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBMacros.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBMacros.h index dae0c5fafb..ba77c2b596 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBMacros.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBMacros.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ // Typedef to help with storing constant strings for enums. diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBMathUtils.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBMathUtils.h index 2d52d3e6db..2dbce05a55 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBMathUtils.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBMathUtils.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBMathUtils.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBMathUtils.m index 44ee257dc9..87a7ecf637 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBMathUtils.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBMathUtils.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBMathUtils.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBMjpegServer.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBMjpegServer.h index 6ab15a300c..294c399f83 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBMjpegServer.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBMjpegServer.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBTCPSocket.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBMjpegServer.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBMjpegServer.m index 691e57746b..4c786ba030 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBMjpegServer.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBMjpegServer.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBMjpegServer.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBNotificationsHelper.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBNotificationsHelper.h index b0ca35b361..b337cb116e 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBNotificationsHelper.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBNotificationsHelper.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBNotificationsHelper.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBNotificationsHelper.m index 60cc509d6d..457047888a 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBNotificationsHelper.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBNotificationsHelper.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBNotificationsHelper.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBPasteboard.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBPasteboard.h index 9595162d41..f61d7d64cc 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBPasteboard.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBPasteboard.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBPasteboard.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBPasteboard.m index 0171b259ca..08e4e9f339 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBPasteboard.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBPasteboard.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBPasteboard.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBProtocolHelpers.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBProtocolHelpers.h index eff0a518b5..e25573e7ed 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBProtocolHelpers.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBProtocolHelpers.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBProtocolHelpers.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBProtocolHelpers.m index 3cd0375867..a463294a94 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBProtocolHelpers.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBProtocolHelpers.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBProtocolHelpers.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBReflectionUtils.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBReflectionUtils.h index 0e4cca3147..262702a072 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBReflectionUtils.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBReflectionUtils.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBReflectionUtils.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBReflectionUtils.m index 9114c312f1..8ef8419fa8 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBReflectionUtils.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBReflectionUtils.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBReflectionUtils.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBRunLoopSpinner.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBRunLoopSpinner.h index bc6b543c33..5f8faf52ec 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBRunLoopSpinner.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBRunLoopSpinner.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBRunLoopSpinner.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBRunLoopSpinner.m index 386238734d..0912325421 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBRunLoopSpinner.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBRunLoopSpinner.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBRunLoopSpinner.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBRuntimeUtils.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBRuntimeUtils.h index 8e54ed4c5f..b16b123ade 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBRuntimeUtils.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBRuntimeUtils.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBRuntimeUtils.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBRuntimeUtils.m index bb08de7e3e..6904cf7602 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBRuntimeUtils.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBRuntimeUtils.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBRuntimeUtils.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBScreen.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBScreen.h index 9c4cca87ed..87c22c7cb4 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBScreen.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBScreen.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBScreen.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBScreen.m index 17b7d8b19b..dc6536408a 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBScreen.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBScreen.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBScreen.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBScreenshot.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBScreenshot.h index 74e6b5886c..b0fdfbe712 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBScreenshot.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBScreenshot.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBScreenshot.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBScreenshot.m index 3d9716deaf..f13f967386 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBScreenshot.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBScreenshot.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBScreenshot.h" @@ -28,7 +27,7 @@ NSString *formatTimeInterval(NSTimeInterval interval) { NSUInteger milliseconds = (NSUInteger)(interval * 1000); - return [NSString stringWithFormat:@"%ld ms", milliseconds]; + return [NSString stringWithFormat:@"%lu ms", milliseconds]; } @implementation FBScreenshot diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBSettings.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBSettings.h index b1f2f1fca5..b98a070b6c 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBSettings.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBSettings.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import @@ -22,9 +21,6 @@ extern NSString* const FB_SETTING_MJPEG_SCALING_FACTOR; extern NSString* const FB_SETTING_SCREENSHOT_QUALITY; extern NSString* const FB_SETTING_KEYBOARD_AUTOCORRECTION; extern NSString* const FB_SETTING_KEYBOARD_PREDICTION; -// This setting is deprecated. Please use CUSTOM_SNAPSHOT_TIMEOUT instead -extern NSString* const FB_SETTING_SNAPSHOT_TIMEOUT; -extern NSString* const FB_SETTING_CUSTOM_SNAPSHOT_TIMEOUT; extern NSString* const FB_SETTING_SNAPSHOT_MAX_DEPTH; extern NSString* const FB_SETTING_USE_FIRST_MATCH; extern NSString* const FB_SETTING_BOUND_ELEMENTS_BY_INDEX; @@ -41,6 +37,10 @@ extern NSString* const FB_SETTING_ANIMATION_COOL_OFF_TIMEOUT; extern NSString* const FB_SETTING_MAX_TYPING_FREQUENCY; extern NSString* const FB_SETTING_RESPECT_SYSTEM_ALERTS; extern NSString* const FB_SETTING_USE_CLEAR_TEXT_SHORTCUT; - +extern NSString* const FB_SETTING_LIMIT_XPATH_CONTEXT_SCOPE; +extern NSString* const FB_SETTING_AUTO_CLICK_ALERT_SELECTOR; +extern NSString *const FB_SETTING_INCLUDE_HITTABLE_IN_PAGE_SOURCE; +extern NSString *const FB_SETTING_INCLUDE_NATIVE_FRAME_IN_PAGE_SOURCE; +extern NSString *const FB_SETTING_INCLUDE_MIN_MAX_VALUE_IN_PAGE_SOURCE; NS_ASSUME_NONNULL_END diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBSettings.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBSettings.m index ada529eed5..17b8ab79d1 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBSettings.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBSettings.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBSettings.h" @@ -18,8 +17,6 @@ NSString* const FB_SETTING_SCREENSHOT_QUALITY = @"screenshotQuality"; NSString* const FB_SETTING_KEYBOARD_AUTOCORRECTION = @"keyboardAutocorrection"; NSString* const FB_SETTING_KEYBOARD_PREDICTION = @"keyboardPrediction"; -NSString* const FB_SETTING_SNAPSHOT_TIMEOUT = @"snapshotTimeout"; -NSString* const FB_SETTING_CUSTOM_SNAPSHOT_TIMEOUT = @"customSnapshotTimeout"; NSString* const FB_SETTING_SNAPSHOT_MAX_DEPTH = @"snapshotMaxDepth"; NSString* const FB_SETTING_USE_FIRST_MATCH = @"useFirstMatch"; NSString* const FB_SETTING_BOUND_ELEMENTS_BY_INDEX = @"boundElementsByIndex"; @@ -36,3 +33,8 @@ NSString* const FB_SETTING_MAX_TYPING_FREQUENCY = @"maxTypingFrequency"; NSString* const FB_SETTING_RESPECT_SYSTEM_ALERTS = @"respectSystemAlerts"; NSString* const FB_SETTING_USE_CLEAR_TEXT_SHORTCUT = @"useClearTextShortcut"; +NSString* const FB_SETTING_LIMIT_XPATH_CONTEXT_SCOPE = @"limitXPathContextScope"; +NSString* const FB_SETTING_AUTO_CLICK_ALERT_SELECTOR = @"autoClickAlertSelector"; +NSString* const FB_SETTING_INCLUDE_HITTABLE_IN_PAGE_SOURCE = @"includeHittableInPageSource"; +NSString* const FB_SETTING_INCLUDE_NATIVE_FRAME_IN_PAGE_SOURCE = @"includeNativeFrameInPageSource"; +NSString* const FB_SETTING_INCLUDE_MIN_MAX_VALUE_IN_PAGE_SOURCE = @"includeMinMaxValueInPageSource"; diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBTVNavigationTracker-Private.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBTVNavigationTracker-Private.h index 2496ccbdaa..8b7f775dfa 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBTVNavigationTracker-Private.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBTVNavigationTracker-Private.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBTVNavigationTracker.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBTVNavigationTracker.h index 9e539f9e09..3a80583b44 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBTVNavigationTracker.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBTVNavigationTracker.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBTVNavigationTracker.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBTVNavigationTracker.m index 11becfa72d..19fa4a0b61 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBTVNavigationTracker.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBTVNavigationTracker.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBTVNavigationTracker.h" @@ -57,9 +56,7 @@ - (instancetype)initWithTargetElement:(XCUIElement *)targetElement self = [super init]; if (self) { _targetElement = targetElement; - CGRect frame = targetElement.fb_isResolvedFromCache.boolValue - ? [FBXCElementSnapshotWrapper ensureWrapped:targetElement.lastSnapshot].wdFrame - : targetElement.wdFrame; + CGRect frame = targetElement.wdFrame; _targetCenter = FBRectGetCenter(frame); _navigationItems = [NSMutableDictionary dictionary]; } diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBUnattachedAppLauncher.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBUnattachedAppLauncher.h index eabf476f74..f640405b04 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBUnattachedAppLauncher.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBUnattachedAppLauncher.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBUnattachedAppLauncher.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBUnattachedAppLauncher.m index f877b67c65..a8679a872a 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBUnattachedAppLauncher.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBUnattachedAppLauncher.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBUnattachedAppLauncher.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBW3CActionsHelpers.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBW3CActionsHelpers.h index 3c194d4cd9..3add9b1b67 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBW3CActionsHelpers.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBW3CActionsHelpers.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the -* LICENSE file in the root directory of this source tree. An additional grant -* of patent rights can be found in the PATENTS file in the same directory. +* LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBW3CActionsHelpers.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBW3CActionsHelpers.m index ae0270dc3d..f7a052d4f0 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBW3CActionsHelpers.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBW3CActionsHelpers.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the -* LICENSE file in the root directory of this source tree. An additional grant -* of patent rights can be found in the PATENTS file in the same directory. +* LICENSE file in the root directory of this source tree. */ #import "FBW3CActionsHelpers.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBW3CActionsSynthesizer.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBW3CActionsSynthesizer.h index e5ed479a74..746c38e36f 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBW3CActionsSynthesizer.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBW3CActionsSynthesizer.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBBaseActionsSynthesizer.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBW3CActionsSynthesizer.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBW3CActionsSynthesizer.m index c488ca4ac4..ef17e03508 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBW3CActionsSynthesizer.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBW3CActionsSynthesizer.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBW3CActionsSynthesizer.h" @@ -661,7 +660,7 @@ @implementation FBW3CActionsSynthesizer if ([origin isKindOfClass:XCUIElement.class]) { instance = origin; } else if ([origin isKindOfClass:NSString.class]) { - instance = [self.elementCache elementForUUID:(NSString *)origin]; + instance = [self.elementCache elementForUUID:(NSString *)origin checkStaleness:YES]; } else { [result addObject:actionItem]; continue; diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBWebServerParams.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBWebServerParams.h index c92daecb2c..aba0fa34f7 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBWebServerParams.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBWebServerParams.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBWebServerParams.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBWebServerParams.m index 65e85f65a2..9ced0a38de 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBWebServerParams.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBWebServerParams.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBWebServerParams.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCAXClientProxy.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCAXClientProxy.h index cf6f497a9b..b216e303f5 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCAXClientProxy.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCAXClientProxy.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import @@ -27,7 +26,7 @@ NS_ASSUME_NONNULL_BEGIN - (nullable id)snapshotForElement:(id)element attributes:(nullable NSArray *)attributes - maxDepth:(nullable NSNumber *)maxDepth + inDepth:(BOOL)inDepth error:(NSError **)error; - (NSArray> *)activeApplications; @@ -39,10 +38,11 @@ NS_ASSUME_NONNULL_BEGIN - (void)notifyWhenNoAnimationsAreActiveForApplication:(XCUIApplication *)application reply:(void (^)(void))reply; -- (NSDictionary *)attributesForElement:(id)element - attributes:(NSArray *)attributes; +- (nullable NSDictionary *)attributesForElement:(id)element + attributes:(NSArray *)attributes + error:(NSError**)error; -- (XCUIApplication *)monitoredApplicationWithProcessIdentifier:(int)pid; +- (nullable XCUIApplication *)monitoredApplicationWithProcessIdentifier:(int)pid; @end diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCAXClientProxy.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCAXClientProxy.m index 907bb25b1b..f84f803fb1 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCAXClientProxy.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCAXClientProxy.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBXCAXClientProxy.h" @@ -14,9 +13,16 @@ #import "FBMacros.h" #import "XCAXClient_iOS+FBSnapshotReqParams.h" #import "XCUIDevice.h" +#import "XCUIApplication.h" static id FBAXClient = nil; +@interface FBXCAXClientProxy () + +@property (nonatomic) NSMutableDictionary *appsCache; + +@end + @implementation FBXCAXClientProxy + (instancetype)sharedClient @@ -25,6 +31,7 @@ + (instancetype)sharedClient static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ instance = [[self alloc] init]; + instance.appsCache = [NSMutableDictionary dictionary]; FBAXClient = [XCUIDevice.sharedDevice accessibilityInterface]; }); return instance; @@ -37,12 +44,12 @@ - (BOOL)setAXTimeout:(NSTimeInterval)timeout error:(NSError **)error - (id)snapshotForElement:(id)element attributes:(NSArray *)attributes - maxDepth:(nullable NSNumber *)maxDepth + inDepth:(BOOL)inDepth error:(NSError **)error { NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithDictionary:self.defaultParameters]; - if (nil != maxDepth) { - parameters[FBSnapshotMaxDepthKey] = maxDepth; + if (!inDepth) { + parameters[FBSnapshotMaxDepthKey] = @1; } id result = [FBAXClient requestSnapshotForElement:element @@ -76,20 +83,37 @@ - (void)notifyWhenNoAnimationsAreActiveForApplication:(XCUIApplication *)applica - (NSDictionary *)attributesForElement:(id)element attributes:(NSArray *)attributes + error:(NSError**)error; { - NSError *error = nil; - NSDictionary* result = [FBAXClient attributesForElement:element - attributes:attributes - error:&error]; - if (error) { - [FBLogger logFmt:@"Cannot retrieve element attribute(s) %@. Original error: %@", attributes, error.description]; - } - return result; + return [FBAXClient attributesForElement:element + attributes:attributes + error:error]; } - (XCUIApplication *)monitoredApplicationWithProcessIdentifier:(int)pid { - return [[FBAXClient applicationProcessTracker] monitoredApplicationWithProcessIdentifier:pid]; + NSMutableSet *terminatedAppIds = [NSMutableSet set]; + for (NSNumber *appPid in self.appsCache) { + if (![self.appsCache[appPid] running]) { + [terminatedAppIds addObject:appPid]; + } + } + for (NSNumber *appPid in terminatedAppIds) { + [self.appsCache removeObjectForKey:appPid]; + } + + XCUIApplication *result = [self.appsCache objectForKey:@(pid)]; + if (nil != result) { + return result; + } + + XCUIApplication *app = [[FBAXClient applicationProcessTracker] + monitoredApplicationWithProcessIdentifier:pid]; + if (nil == app) { + return nil; + } + [self.appsCache setObject:app forKey:@(pid)]; + return app; } @end diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCTestDaemonsProxy.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCTestDaemonsProxy.h index 18761248bf..41514a5cd2 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCTestDaemonsProxy.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCTestDaemonsProxy.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCTestDaemonsProxy.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCTestDaemonsProxy.m index 59e3a64be8..e29b94e995 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCTestDaemonsProxy.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCTestDaemonsProxy.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBXCTestDaemonsProxy.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCodeCompatibility.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCodeCompatibility.h index 0a7dd9a0c4..75d1ee2035 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCodeCompatibility.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCodeCompatibility.h @@ -3,13 +3,14 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import #import "XCPointerEvent.h" +@class FBXCElementSnapshot; + /** The version of testmanagerd process which is running on the device. @@ -46,7 +47,7 @@ NS_ASSUME_NONNULL_BEGIN @param error The error instance if there was a failure while retrieveing the snapshot @returns The cached unqiue snapshot or nil if the element is stale */ -- (nullable XCElementSnapshot *)fb_uniqueSnapshotWithError:(NSError **)error; +- (nullable id)fb_uniqueSnapshotWithError:(NSError **)error; @end diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCodeCompatibility.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCodeCompatibility.m index b13a79e554..f2cf03a24a 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCodeCompatibility.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXCodeCompatibility.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBXCodeCompatibility.h" @@ -20,9 +19,9 @@ @implementation XCUIElementQuery (FBCompatibility) -- (XCElementSnapshot *)fb_uniqueSnapshotWithError:(NSError **)error +- (id)fb_uniqueSnapshotWithError:(NSError **)error { - return [self uniqueMatchingSnapshotWithError:error]; + return (id)[self uniqueMatchingSnapshotWithError:error]; } - (XCUIElement *)fb_firstMatch diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXMLGenerationOptions.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXMLGenerationOptions.h index 0fd71e1392..8a014c12bd 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXMLGenerationOptions.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXMLGenerationOptions.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXMLGenerationOptions.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXMLGenerationOptions.m index 23bfa5892a..40dcebd232 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXMLGenerationOptions.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXMLGenerationOptions.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBXMLGenerationOptions.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXPath-Private.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXPath-Private.h index 31bb403bf1..db9732c41f 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXPath-Private.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXPath-Private.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import @@ -25,7 +24,7 @@ NS_ASSUME_NONNULL_BEGIN If `query` argument is assigned then `excludedAttributes` argument is effectively ignored. @return zero if the method has completed successfully */ -+ (int)xmlRepresentationWithRootElement:(id)root ++ (int)xmlRepresentationWithRootElement:(id)root writer:(xmlTextWriterPtr)writer elementStore:(nullable NSMutableDictionary *)elementStore query:(nullable NSString*)query @@ -45,9 +44,12 @@ NS_ASSUME_NONNULL_BEGIN @param xpathQuery actual query. Should be valid XPath 1.0-compatible expression @param document libxml2-compatible document pointer + @param contextNode Optonal context node instance @return pointer to a libxml2-compatible structure with set of matched nodes or NULL in case of failure */ -+ (xmlXPathObjectPtr)evaluate:(NSString *)xpathQuery document:(xmlDocPtr)doc; ++ (xmlXPathObjectPtr)evaluate:(NSString *)xpathQuery + document:(xmlDocPtr)doc + contextNode:(nullable xmlNodePtr)contextNode; @end diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXPath.h b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXPath.h index 50c8519782..1135c7228a 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXPath.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXPath.h @@ -3,13 +3,12 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import #import -#import "FBXCElementSnapshot.h" +#import #ifdef __clang__ #pragma clang diagnostic push diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXPath.m b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXPath.m index eae3ee4383..79e8f75f38 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/FBXPath.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/FBXPath.m @@ -3,24 +3,28 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBXPath.h" #import "FBConfiguration.h" #import "FBExceptions.h" +#import "FBElementUtils.h" #import "FBLogger.h" #import "FBMacros.h" #import "FBXMLGenerationOptions.h" #import "FBXCElementSnapshotWrapper+Helpers.h" #import "NSString+FBXMLSafeString.h" +#import "XCUIApplication.h" #import "XCUIElement.h" #import "XCUIElement+FBCaching.h" #import "XCUIElement+FBUtilities.h" #import "XCUIElement+FBWebDriverAttributes.h" #import "XCTestPrivateSymbols.h" +#import "FBElementHelpers.h" +#import "FBXCAXClientProxy.h" +#import "FBXCAccessibilityElement.h" @interface FBElementAttribute : NSObject @@ -31,6 +35,7 @@ + (nonnull NSString *)name; + (nullable NSString *)valueForElement:(id)element; + (int)recordWithWriter:(xmlTextWriterPtr)writer forElement:(id)element; ++ (int)recordWithWriter:(xmlTextWriterPtr)writer forValue:(nullable NSString *)value; + (NSArray *)supportedAttributes; @@ -96,7 +101,33 @@ @interface FBInternalIndexAttribute : FBElementAttribute @property (nonatomic, nonnull, readonly) NSString* indexValue; -+ (int)recordWithWriter:(xmlTextWriterPtr)writer forValue:(NSString *)value; +@end + +@interface FBApplicationBundleIdAttribute : FBElementAttribute + +@end + +@interface FBApplicationPidAttribute : FBElementAttribute + +@end + +@interface FBPlaceholderValueAttribute : FBElementAttribute + +@end + +@interface FBNativeFrameAttribute : FBElementAttribute + +@end + +@interface FBTraitsAttribute : FBElementAttribute + +@end + +@interface FBMinValueAttribute : FBElementAttribute + +@end + +@interface FBMaxValueAttribute : FBElementAttribute @end @@ -141,7 +172,11 @@ + (nullable NSString *)xmlStringWithRootElement:(id)root } if (rc >= 0) { - rc = [self xmlRepresentationWithRootElement:root + [self waitUntilStableWithElement:root]; + // If 'includeHittableInPageSource' setting is enabled, then use native snapshots + // to calculate a more accurate value for the 'hittable' attribute. + rc = [self xmlRepresentationWithRootElement:[self snapshotWithRoot:root + useNative:FBConfiguration.includeHittableInPageSource] writer:writer elementStore:nil query:nil @@ -189,10 +224,35 @@ + (nullable NSString *)xmlStringWithRootElement:(id)root } NSMutableDictionary *elementStore = [NSMutableDictionary dictionary]; int rc = xmlTextWriterStartDocument(writer, NULL, _UTF8Encoding, NULL); + id lookupScopeSnapshot = nil; + id contextRootSnapshot = nil; + BOOL useNativeSnapshot = nil == xpathQuery + ? NO + : [[self.class elementAttributesWithXPathQuery:xpathQuery] containsObject:FBHittableAttribute.class]; if (rc < 0) { [FBLogger logFmt:@"Failed to invoke libxml2>xmlTextWriterStartDocument. Error code: %d", rc]; } else { - rc = [self xmlRepresentationWithRootElement:root + [self waitUntilStableWithElement:root]; + if (FBConfiguration.limitXpathContextScope) { + lookupScopeSnapshot = [self snapshotWithRoot:root useNative:useNativeSnapshot]; + } else { + if ([root isKindOfClass:XCUIElement.class]) { + lookupScopeSnapshot = [self snapshotWithRoot:[(XCUIElement *)root application] + useNative:useNativeSnapshot]; + contextRootSnapshot = [root isKindOfClass:XCUIApplication.class] + ? nil + : ([(XCUIElement *)root lastSnapshot] ?: [self snapshotWithRoot:(XCUIElement *)root + useNative:useNativeSnapshot]); + } else { + lookupScopeSnapshot = (id)root; + contextRootSnapshot = nil == lookupScopeSnapshot.parent ? nil : (id)root; + while (nil != lookupScopeSnapshot.parent) { + lookupScopeSnapshot = lookupScopeSnapshot.parent; + } + } + } + + rc = [self xmlRepresentationWithRootElement:lookupScopeSnapshot writer:writer elementStore:elementStore query:xpathQuery @@ -210,7 +270,22 @@ + (nullable NSString *)xmlStringWithRootElement:(id)root return [self throwException:FBXPathQueryEvaluationException forQuery:xpathQuery]; } - xmlXPathObjectPtr queryResult = [self evaluate:xpathQuery document:doc]; + xmlXPathObjectPtr contextNodeQueryResult = [self matchNodeInDocument:doc + elementStore:elementStore.copy + forSnapshot:contextRootSnapshot]; + xmlNodePtr contextNode = NULL; + if (NULL != contextNodeQueryResult) { + xmlNodeSetPtr nodeSet = contextNodeQueryResult->nodesetval; + if (!xmlXPathNodeSetIsEmpty(nodeSet)) { + contextNode = nodeSet->nodeTab[0]; + } + } + xmlXPathObjectPtr queryResult = [self evaluate:xpathQuery + document:doc + contextNode:contextNode]; + if (NULL != contextNodeQueryResult) { + xmlXPathFreeObject(contextNodeQueryResult); + } if (NULL == queryResult) { xmlFreeTextWriter(writer); xmlFreeDoc(doc); @@ -252,6 +327,36 @@ + (NSArray *)collectMatchingSnapshots:(xmlNodeSetPtr)nodeSet return matchingSnapshots.copy; } ++ (nullable xmlXPathObjectPtr)matchNodeInDocument:(xmlDocPtr)doc + elementStore:(NSDictionary> *)elementStore + forSnapshot:(nullable id)snapshot +{ + if (nil == snapshot) { + return NULL; + } + + NSString *contextRootUid = [FBElementUtils uidWithAccessibilityElement:[(id)snapshot accessibilityElement]]; + if (nil == contextRootUid) { + return NULL; + } + + for (NSString *key in elementStore) { + id value = [elementStore objectForKey:key]; + NSString *snapshotUid = [FBElementUtils uidWithAccessibilityElement:[value accessibilityElement]]; + if (nil == snapshotUid || ![snapshotUid isEqualToString:contextRootUid]) { + continue; + } + NSString *indexQuery = [NSString stringWithFormat:@"//*[@%@=\"%@\"]", kXMLIndexPathKey, key]; + xmlXPathObjectPtr queryResult = [self evaluate:indexQuery + document:doc + contextNode:NULL]; + if (NULL != queryResult) { + return queryResult; + } + } + return NULL; +} + + (NSSet *)elementAttributesWithXPathQuery:(NSString *)query { if ([query rangeOfString:@"[^\\w@]@\\*[^\\w]" options:NSRegularExpressionSearch].location != NSNotFound) { @@ -267,7 +372,7 @@ + (NSArray *)collectMatchingSnapshots:(xmlNodeSetPtr)nodeSet return result.copy; } -+ (int)xmlRepresentationWithRootElement:(id)root ++ (int)xmlRepresentationWithRootElement:(id)root writer:(xmlTextWriterPtr)writer elementStore:(nullable NSMutableDictionary *)elementStore query:(nullable NSString*)query @@ -278,9 +383,20 @@ + (int)xmlRepresentationWithRootElement:(id)root NSMutableSet *includedAttributes; if (nil == query) { includedAttributes = [NSMutableSet setWithArray:FBElementAttribute.supportedAttributes]; - // The hittable attribute is expensive to calculate for each snapshot item - // thus we only include it when requested by an xPath query - [includedAttributes removeObject:FBHittableAttribute.class]; + if (!FBConfiguration.includeHittableInPageSource) { + // The hittable attribute is expensive to calculate for each snapshot item + // thus we only include it when requested explicitly + [includedAttributes removeObject:FBHittableAttribute.class]; + } + if (!FBConfiguration.includeNativeFrameInPageSource) { + // Include nativeFrame only when requested + [includedAttributes removeObject:FBNativeFrameAttribute.class]; + } + if (!FBConfiguration.includeMinMaxValueInPageSource) { + // minValue/maxValue are retrieved from private APIs and may be slow on deep trees + [includedAttributes removeObject:FBMinValueAttribute.class]; + [includedAttributes removeObject:FBMaxValueAttribute.class]; + } if (nil != excludedAttributes) { for (NSString *excludedAttributeName in excludedAttributes) { for (Class supportedAttribute in FBElementAttribute.supportedAttributes) { @@ -308,14 +424,16 @@ + (int)xmlRepresentationWithRootElement:(id)root return 0; } -+ (xmlXPathObjectPtr)evaluate:(NSString *)xpathQuery document:(xmlDocPtr)doc ++ (xmlXPathObjectPtr)evaluate:(NSString *)xpathQuery + document:(xmlDocPtr)doc + contextNode:(nullable xmlNodePtr)contextNode { xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc); if (NULL == xpathCtx) { [FBLogger logFmt:@"Failed to invoke libxml2>xmlXPathNewContext for XPath query \"%@\"", xpathQuery]; return NULL; } - xpathCtx->node = doc->children; + xpathCtx->node = NULL == contextNode ? doc->children : contextNode; xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression((const xmlChar *)[xpathQuery UTF8String], xpathCtx); if (NULL == xpathObj) { @@ -342,6 +460,16 @@ + (int)recordElementAttributes:(xmlTextWriterPtr)writer if (includedAttributes && ![includedAttributes containsObject:attributeCls]) { continue; } + // Text-input placeholder (only for elements that support inner text) + if ((attributeCls == FBPlaceholderValueAttribute.class) && + !FBDoesElementSupportInnerText(element.elementType)) { + continue; + } + // Only for elements that support min/max value + if ((attributeCls == FBMinValueAttribute.class || attributeCls == FBMaxValueAttribute.class) && + !FBDoesElementSupportMinMaxValue(element.elementType)) { + continue; + } int rc = [attributeCls recordWithWriter:writer forElement:[FBXCElementSnapshotWrapper ensureWrapped:element]]; if (rc < 0) { @@ -353,10 +481,31 @@ + (int)recordElementAttributes:(xmlTextWriterPtr)writer // index path is the special case return [FBInternalIndexAttribute recordWithWriter:writer forValue:indexPath]; } + if (element.elementType == XCUIElementTypeApplication) { + // only record process identifier and bundle identifier for the application element + int pid = [element.accessibilityElement processIdentifier]; + if (pid > 0) { + int rc = [FBApplicationPidAttribute recordWithWriter:writer + forValue:[NSString stringWithFormat:@"%d", pid]]; + if (rc < 0) { + return rc; + } + XCUIApplication *app = [[FBXCAXClientProxy sharedClient] + monitoredApplicationWithProcessIdentifier:pid]; + NSString *bundleID = [app bundleID]; + if (nil != bundleID) { + rc = [FBApplicationBundleIdAttribute recordWithWriter:writer + forValue:bundleID]; + if (rc < 0) { + return rc; + } + } + } + } return 0; } -+ (int)writeXmlWithRootElement:(id)root ++ (int)writeXmlWithRootElement:(id)root indexPath:(nullable NSString *)indexPath elementStore:(nullable NSMutableDictionary *)elementStore includedAttributes:(nullable NSSet *)includedAttributes @@ -364,30 +513,13 @@ + (int)writeXmlWithRootElement:(id)root { NSAssert((indexPath == nil && elementStore == nil) || (indexPath != nil && elementStore != nil), @"Either both or none of indexPath and elementStore arguments should be equal to nil", nil); - id currentSnapshot; - NSArray> *children; - if ([root isKindOfClass:XCUIElement.class]) { - XCUIElement *element = (XCUIElement *)root; - NSMutableArray *snapshotAttributes = [NSMutableArray arrayWithArray:FBStandardAttributeNames()]; - if (nil == includedAttributes || [includedAttributes containsObject:FBVisibleAttribute.class]) { - [snapshotAttributes addObject:FB_XCAXAIsVisibleAttributeName]; - // If the app is not idle state while we retrieve the visiblity state - // then the snapshot retrieval operation might freeze and time out - [element.application fb_waitUntilStableWithTimeout:FBConfiguration.animationCoolOffTimeout]; - } - currentSnapshot = [element fb_snapshotWithAttributes:snapshotAttributes.copy - maxDepth:nil]; - children = currentSnapshot.children; - } else { - currentSnapshot = (id)root; - children = currentSnapshot.children; - } + NSArray> *children = root.children; if (elementStore != nil && indexPath != nil && [indexPath isEqualToString:topNodeIndexPath]) { - [elementStore setObject:currentSnapshot forKey:topNodeIndexPath]; + [elementStore setObject:root forKey:topNodeIndexPath]; } - FBXCElementSnapshotWrapper *wrappedSnapshot = [FBXCElementSnapshotWrapper ensureWrapped:currentSnapshot]; + FBXCElementSnapshotWrapper *wrappedSnapshot = [FBXCElementSnapshotWrapper ensureWrapped:root]; int rc = xmlTextWriterStartElement(writer, (xmlChar *)[wrappedSnapshot.wdType UTF8String]); if (rc < 0) { [FBLogger logFmt:@"Failed to invoke libxml2>xmlTextWriterStartElement for the tag value '%@'. Error code: %d", wrappedSnapshot.wdType, rc]; @@ -395,7 +527,7 @@ + (int)writeXmlWithRootElement:(id)root } rc = [self recordElementAttributes:writer - forElement:currentSnapshot + forElement:root indexPath:indexPath includedAttributes:includedAttributes]; if (rc < 0) { @@ -403,18 +535,20 @@ + (int)writeXmlWithRootElement:(id)root } for (NSUInteger i = 0; i < [children count]; i++) { - id childSnapshot = [children objectAtIndex:i]; - NSString *newIndexPath = (indexPath != nil) ? [indexPath stringByAppendingFormat:@",%lu", (unsigned long)i] : nil; - if (elementStore != nil && newIndexPath != nil) { - [elementStore setObject:childSnapshot forKey:(id)newIndexPath]; - } - rc = [self writeXmlWithRootElement:[FBXCElementSnapshotWrapper ensureWrapped:childSnapshot] - indexPath:newIndexPath - elementStore:elementStore - includedAttributes:includedAttributes - writer:writer]; - if (rc < 0) { - return rc; + @autoreleasepool { + id childSnapshot = [children objectAtIndex:i]; + NSString *newIndexPath = (indexPath != nil) ? [indexPath stringByAppendingFormat:@",%lu", (unsigned long)i] : nil; + if (elementStore != nil && newIndexPath != nil) { + [elementStore setObject:childSnapshot forKey:(id)newIndexPath]; + } + rc = [self writeXmlWithRootElement:[FBXCElementSnapshotWrapper ensureWrapped:childSnapshot] + indexPath:newIndexPath + elementStore:elementStore + includedAttributes:includedAttributes + writer:writer]; + if (rc < 0) { + return rc; + } } } @@ -426,6 +560,30 @@ + (int)writeXmlWithRootElement:(id)root return 0; } ++ (id)snapshotWithRoot:(id)root + useNative:(BOOL)useNative +{ + if (![root isKindOfClass:XCUIElement.class]) { + return (id)root; + } + + if (useNative) { + return [(XCUIElement *)root fb_nativeSnapshot]; + } + return [root isKindOfClass:XCUIApplication.class] + ? [(XCUIElement *)root fb_standardSnapshot] + : [(XCUIElement *)root fb_customSnapshot]; +} + ++ (void)waitUntilStableWithElement:(id)root +{ + if ([root isKindOfClass:XCUIElement.class]) { + // If the app is not idle state while we retrieve the visiblity state + // then the snapshot retrieval operation might freeze and time out + [[(XCUIElement *)root application] fb_waitUntilStableWithTimeout:FBConfiguration.animationCoolOffTimeout]; + } +} + @end @@ -457,6 +615,11 @@ + (NSString *)valueForElement:(id)element + (int)recordWithWriter:(xmlTextWriterPtr)writer forElement:(id)element { NSString *value = [self valueForElement:element]; + return [self recordWithWriter:writer forValue:value]; +} + ++ (int)recordWithWriter:(xmlTextWriterPtr)writer forValue:(nullable NSString *)value +{ if (nil == value) { // Skip the attribute if the value equals to nil return 0; @@ -490,6 +653,11 @@ + (int)recordWithWriter:(xmlTextWriterPtr)writer forElement:(id)eleme FBHeightAttribute.class, FBIndexAttribute.class, FBHittableAttribute.class, + FBPlaceholderValueAttribute.class, + FBTraitsAttribute.class, + FBNativeFrameAttribute.class, + FBMinValueAttribute.class, + FBMaxValueAttribute.class, ]; } @@ -697,18 +865,90 @@ + (NSString *)name return kXMLIndexPathKey; } -+ (int)recordWithWriter:(xmlTextWriterPtr)writer forValue:(NSString *)value +@end + +@implementation FBApplicationBundleIdAttribute : FBElementAttribute + ++ (NSString *)name { - if (nil == value) { - // Skip the attribute if the value equals to nil - return 0; - } - int rc = xmlTextWriterWriteAttribute(writer, - (xmlChar *)[[FBXPath safeXmlStringWithString:[self name]] UTF8String], - (xmlChar *)[[FBXPath safeXmlStringWithString:value] UTF8String]); - if (rc < 0) { - [FBLogger logFmt:@"Failed to invoke libxml2>xmlTextWriterWriteAttribute(%@='%@'). Error code: %d", [self name], value, rc]; - } - return rc; + return @"bundleId"; } + +@end + +@implementation FBApplicationPidAttribute : FBElementAttribute + ++ (NSString *)name +{ + return @"processId"; +} + +@end + +@implementation FBPlaceholderValueAttribute + ++ (NSString *)name +{ + return @"placeholderValue"; +} + ++ (NSString *)valueForElement:(id)element +{ + return element.wdPlaceholderValue; +} +@end + +@implementation FBNativeFrameAttribute + ++ (NSString *)name +{ + return @"nativeFrame"; +} + ++ (NSString *)valueForElement:(id)element +{ + return NSStringFromCGRect(element.wdNativeFrame); +} +@end + +@implementation FBTraitsAttribute + ++ (NSString *)name +{ + return @"traits"; +} + ++ (NSString *)valueForElement:(id)element +{ + return element.wdTraits; +} + +@end + +@implementation FBMinValueAttribute + ++ (NSString *)name +{ + return @"minValue"; +} + ++ (NSString *)valueForElement:(id)element +{ + return [element.wdMinValue stringValue]; +} + +@end + +@implementation FBMaxValueAttribute + ++ (NSString *)name +{ + return @"maxValue"; +} + ++ (NSString *)valueForElement:(id)element +{ + return [element.wdMaxValue stringValue]; +} + @end diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/LRUCache/LRUCache.h b/WebDriverAgent/WebDriverAgentLib/Utilities/LRUCache/LRUCache.h index 70614235f6..dbfb4cfbc4 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/LRUCache/LRUCache.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/LRUCache/LRUCache.h @@ -54,6 +54,13 @@ NS_ASSUME_NONNULL_BEGIN */ - (NSArray *)allObjects; +/** + Removes the object associated with the specified key from the cache. + + @param key The key identifying the object to remove. + */ +- (void)removeObjectForKey:(id)key; + @end NS_ASSUME_NONNULL_END diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/LRUCache/LRUCache.m b/WebDriverAgent/WebDriverAgentLib/Utilities/LRUCache/LRUCache.m index 4f3a9ad0d2..731d744046 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/LRUCache/LRUCache.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/LRUCache/LRUCache.m @@ -135,4 +135,12 @@ - (void)alignSize } } +- (void)removeObjectForKey:(id)key +{ + LRUCacheNode *node = self.store[key]; + if (node != nil) { + [self removeNode:node]; + } +} + @end diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/NSPredicate+FBFormat.h b/WebDriverAgent/WebDriverAgentLib/Utilities/NSPredicate+FBFormat.h index 89ce4adeeb..a7ad285d53 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/NSPredicate+FBFormat.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/NSPredicate+FBFormat.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/NSPredicate+FBFormat.m b/WebDriverAgent/WebDriverAgentLib/Utilities/NSPredicate+FBFormat.m index 8a033e7076..65af951a09 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/NSPredicate+FBFormat.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/NSPredicate+FBFormat.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "NSPredicate+FBFormat.h" @@ -59,8 +58,10 @@ + (instancetype)fb_snapshotBlockPredicateWithPredicate:(NSPredicate *)input NSPredicate *wdPredicate = [self.class fb_formatSearchPredicate:input]; return [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary * _Nullable bindings) { - FBXCElementSnapshotWrapper *wrappedSnapshot = [FBXCElementSnapshotWrapper ensureWrapped:evaluatedObject]; - return [wdPredicate evaluateWithObject:wrappedSnapshot]; + @autoreleasepool { + FBXCElementSnapshotWrapper *wrappedSnapshot = [FBXCElementSnapshotWrapper ensureWrapped:evaluatedObject]; + return [wdPredicate evaluateWithObject:wrappedSnapshot]; + } }]; } diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/XCTestPrivateSymbols.h b/WebDriverAgent/WebDriverAgentLib/Utilities/XCTestPrivateSymbols.h index 87199ff35c..853ba414dc 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/XCTestPrivateSymbols.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/XCTestPrivateSymbols.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import @@ -19,6 +18,17 @@ extern NSString *FB_XCAXAIsVisibleAttributeName; extern NSNumber *FB_XCAXAIsElementAttribute; extern NSString *FB_XCAXAIsElementAttributeName; +/*! Accessibility identifier for visible frame attribute */ +extern NSString *FB_XCAXAVisibleFrameAttributeName; + +/*! Accessibility identifier для минимума */ +extern NSNumber *FB_XCAXACustomMinValueAttribute; +extern NSString *FB_XCAXACustomMinValueAttributeName; + +/*! Accessibility identifier для максимума */ +extern NSNumber *FB_XCAXACustomMaxValueAttribute; +extern NSString *FB_XCAXACustomMaxValueAttributeName; + /*! Getter for XCTest logger */ extern id (*XCDebugLogger)(void); diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/XCTestPrivateSymbols.m b/WebDriverAgent/WebDriverAgentLib/Utilities/XCTestPrivateSymbols.m index 861a78660b..244e3fdbf2 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/XCTestPrivateSymbols.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/XCTestPrivateSymbols.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCTestPrivateSymbols.h" @@ -18,6 +17,11 @@ NSString *FB_XCAXAIsVisibleAttributeName = @"XC_kAXXCAttributeIsVisible"; NSNumber *FB_XCAXAIsElementAttribute; NSString *FB_XCAXAIsElementAttributeName = @"XC_kAXXCAttributeIsElement"; +NSString *FB_XCAXAVisibleFrameAttributeName = @"XC_kAXXCAttributeVisibleFrame"; +NSNumber *FB_XCAXACustomMinValueAttribute; +NSString *FB_XCAXACustomMinValueAttributeName = @"XC_kAXXCAttributeMinValue"; +NSNumber *FB_XCAXACustomMaxValueAttribute; +NSString *FB_XCAXACustomMaxValueAttributeName = @"XC_kAXXCAttributeMaxValue"; void (*XCSetDebugLogger)(id ); id (*XCDebugLogger)(void); @@ -41,6 +45,16 @@ NSCAssert(FB_XCAXAIsVisibleAttribute != nil , @"Failed to retrieve FB_XCAXAIsVisibleAttribute", FB_XCAXAIsVisibleAttribute); NSCAssert(FB_XCAXAIsElementAttribute != nil , @"Failed to retrieve FB_XCAXAIsElementAttribute", FB_XCAXAIsElementAttribute); + + NSString *XC_kAXXCAttributeMinValue = *(NSString *__autoreleasing *)FBRetrieveXCTestSymbol([FB_XCAXACustomMinValueAttributeName UTF8String]); + NSString *XC_kAXXCAttributeMaxValue = *(NSString *__autoreleasing *)FBRetrieveXCTestSymbol([FB_XCAXACustomMaxValueAttributeName UTF8String]); + + NSArray *minMaxAttrs = XCAXAccessibilityAttributesForStringAttributes(@[XC_kAXXCAttributeMinValue, XC_kAXXCAttributeMaxValue]); + FB_XCAXACustomMinValueAttribute = minMaxAttrs[0]; + FB_XCAXACustomMaxValueAttribute = minMaxAttrs[1]; + + NSCAssert(FB_XCAXACustomMinValueAttribute != nil, @"Failed to retrieve FB_XCAXACustomMinValueAttribute", FB_XCAXACustomMinValueAttribute); + NSCAssert(FB_XCAXACustomMaxValueAttribute != nil, @"Failed to retrieve FB_XCAXACustomMaxValueAttribute", FB_XCAXACustomMaxValueAttribute); } void *FBRetrieveXCTestSymbol(const char *name) @@ -73,7 +87,9 @@ dispatch_once(&onceCustomAttributeNamesToken, ^{ customNames = @[ FB_XCAXAIsVisibleAttributeName, - FB_XCAXAIsElementAttributeName + FB_XCAXAIsElementAttributeName, + FB_XCAXACustomMinValueAttributeName, + FB_XCAXACustomMaxValueAttributeName ]; }); return customNames; diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/XCUIApplicationProcessDelay.h b/WebDriverAgent/WebDriverAgentLib/Utilities/XCUIApplicationProcessDelay.h index ed11a9a51c..3cbb5efb0c 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/XCUIApplicationProcessDelay.h +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/XCUIApplicationProcessDelay.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentLib/Utilities/XCUIApplicationProcessDelay.m b/WebDriverAgent/WebDriverAgentLib/Utilities/XCUIApplicationProcessDelay.m index 86c1fc45cb..e41a0a78c0 100644 --- a/WebDriverAgent/WebDriverAgentLib/Utilities/XCUIApplicationProcessDelay.m +++ b/WebDriverAgent/WebDriverAgentLib/Utilities/XCUIApplicationProcessDelay.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "XCUIApplicationProcessDelay.h" diff --git a/WebDriverAgent/WebDriverAgentLib/Vendor/CocoaAsyncSocket/GCDAsyncSocket.m b/WebDriverAgent/WebDriverAgentLib/Vendor/CocoaAsyncSocket/GCDAsyncSocket.m old mode 100644 new mode 100755 index de18142fe9..480c116a6e --- a/WebDriverAgent/WebDriverAgentLib/Vendor/CocoaAsyncSocket/GCDAsyncSocket.m +++ b/WebDriverAgent/WebDriverAgentLib/Vendor/CocoaAsyncSocket/GCDAsyncSocket.m @@ -1,6 +1,6 @@ // // GCDAsyncSocket.m -// +// // This class is in the public domain. // Originally created by Robbie Hanson in Q4 2010. // Updated and maintained by Deusty LLC and the Apple development community. @@ -11,7 +11,17 @@ #import "GCDAsyncSocket.h" #if TARGET_OS_IPHONE -#import +#import +#import +// Note: CFStream APIs are still used for TLS support and are part of CoreFoundation +// CFStream SSL constants are needed only for the legacy CFStream TLS path (when GCDAsyncSocketUseCFStreamForTLS is set) +// The default path uses SecureTransport which doesn't require these constants +// Declare SSL constants as extern to avoid importing deprecated CFNetwork framework +// These symbols are linked at runtime from CFNetwork framework +extern const CFStringRef kCFStreamPropertySSLSettings; +extern const CFStringRef kCFStreamSSLPeerName; +extern const CFStringRef kCFStreamSSLCertificates; +extern const CFStringRef kCFStreamSSLIsServer; #endif #import @@ -48,7 +58,7 @@ // Logging uses the CocoaLumberjack framework (which is also GCD based). // https://github.com/robbiehanson/CocoaLumberjack -// +// // It allows us to do a lot of logging without significantly slowing down the code. #import "DDLog.h" @@ -184,16 +194,16 @@ * than is being requested by current read request. * In this case we slurp up all data from the socket (to minimize sys calls), * and store additional yet unread data in a "prebuffer". - * + * * The prebuffer is entirely drained before we read from the socket again. * In other words, a large chunk of data is written is written to the prebuffer. * The prebuffer is then drained via a series of one or more reads (for subsequent read request(s)). - * + * * A ring buffer was once used for this purpose. * But a ring buffer takes up twice as much memory as needed (double the size for mirroring). * In fact, it generally takes up more than twice the needed size as everything has to be rounded up to vm_page_size. * And since the prebuffer is always completely drained after being written to, a full ring buffer isn't needed. - * + * * The current design is very simple and straight-forward, while also keeping memory requirements lower. **/ @@ -201,7 +211,7 @@ @interface GCDAsyncSocketPreBuffer : NSObject { uint8_t *preBuffer; size_t preBufferSize; - + uint8_t *readPointer; uint8_t *writePointer; } @@ -242,7 +252,7 @@ - (instancetype)initWithCapacity:(size_t)numBytes { preBufferSize = numBytes; preBuffer = malloc(preBufferSize); - + readPointer = preBuffer; writePointer = preBuffer; } @@ -258,20 +268,20 @@ - (void)dealloc - (void)ensureCapacityForWrite:(size_t)numBytes { size_t availableSpace = [self availableSpace]; - + if (numBytes > availableSpace) { size_t additionalBytes = numBytes - availableSpace; - + size_t newPreBufferSize = preBufferSize + additionalBytes; uint8_t *newPreBuffer = realloc(preBuffer, newPreBufferSize); - + size_t readPointerOffset = readPointer - preBuffer; size_t writePointerOffset = writePointer - preBuffer; - + preBuffer = newPreBuffer; preBufferSize = newPreBufferSize; - + readPointer = preBuffer + readPointerOffset; writePointer = preBuffer + writePointerOffset; } @@ -296,7 +306,7 @@ - (void)getReadBuffer:(uint8_t **)bufferPtr availableBytes:(size_t *)availableBy - (void)didRead:(size_t)bytesRead { readPointer += bytesRead; - + if (readPointer == writePointer) { // The prebuffer has been drained. Reset pointers. @@ -404,7 +414,7 @@ - (instancetype)initWithData:(NSMutableData *)d readLength = l; term = [e copy]; tag = i; - + if (d) { buffer = d; @@ -418,7 +428,7 @@ - (instancetype)initWithData:(NSMutableData *)d buffer = [[NSMutableData alloc] initWithLength:readLength]; else buffer = [[NSMutableData alloc] initWithLength:0]; - + startOffset = 0; bufferOwner = YES; originalBufferLength = 0; @@ -434,13 +444,13 @@ - (void)ensureCapacityForAdditionalDataOfLength:(NSUInteger)bytesToRead { NSUInteger buffSize = [buffer length]; NSUInteger buffUsed = startOffset + bytesDone; - + NSUInteger buffSpace = buffSize - buffUsed; - + if (bytesToRead > buffSpace) { NSUInteger buffInc = bytesToRead - buffSpace; - + [buffer increaseLengthBy:buffInc]; } } @@ -448,23 +458,23 @@ - (void)ensureCapacityForAdditionalDataOfLength:(NSUInteger)bytesToRead /** * This method is used when we do NOT know how much data is available to be read from the socket. * This method returns the default value unless it exceeds the specified readLength or maxLength. - * + * * Furthermore, the shouldPreBuffer decision is based upon the packet type, * and whether the returned value would fit in the current buffer without requiring a resize of the buffer. **/ - (NSUInteger)optimalReadLengthWithDefault:(NSUInteger)defaultValue shouldPreBuffer:(BOOL *)shouldPreBufferPtr { NSUInteger result; - + if (readLength > 0) { // Read a specific length of data result = readLength - bytesDone; - + // There is no need to prebuffer since we know exactly how much data we need to read. // Even if the buffer isn't currently big enough to fit this amount of data, // it would have to be resized eventually anyway. - + if (shouldPreBufferPtr) *shouldPreBufferPtr = NO; } @@ -472,88 +482,88 @@ - (NSUInteger)optimalReadLengthWithDefault:(NSUInteger)defaultValue shouldPreBuf { // Either reading until we find a specified terminator, // or we're simply reading all available data. - // + // // In other words, one of: - // + // // - readDataToData packet // - readDataWithTimeout packet - + if (maxLength > 0) result = MIN(defaultValue, (maxLength - bytesDone)); else result = defaultValue; - + // Since we don't know the size of the read in advance, // the shouldPreBuffer decision is based upon whether the returned value would fit // in the current buffer without requiring a resize of the buffer. - // + // // This is because, in all likelyhood, the amount read from the socket will be less than the default value. // Thus we should avoid over-allocating the read buffer when we can simply use the pre-buffer instead. - + if (shouldPreBufferPtr) { NSUInteger buffSize = [buffer length]; NSUInteger buffUsed = startOffset + bytesDone; - + NSUInteger buffSpace = buffSize - buffUsed; - + if (buffSpace >= result) *shouldPreBufferPtr = NO; else *shouldPreBufferPtr = YES; } } - + return result; } /** * For read packets without a set terminator, returns the amount of data * that can be read without exceeding the readLength or maxLength. - * + * * The given parameter indicates the number of bytes estimated to be available on the socket, * which is taken into consideration during the calculation. - * + * * The given hint MUST be greater than zero. **/ - (NSUInteger)readLengthForNonTermWithHint:(NSUInteger)bytesAvailable { NSAssert(term == nil, @"This method does not apply to term reads"); NSAssert(bytesAvailable > 0, @"Invalid parameter: bytesAvailable"); - + if (readLength > 0) { // Read a specific length of data - + return MIN(bytesAvailable, (readLength - bytesDone)); - + // No need to avoid resizing the buffer. // If the user provided their own buffer, // and told us to read a certain length of data that exceeds the size of the buffer, // then it is clear that our code will resize the buffer during the read operation. - // + // // This method does not actually do any resizing. // The resizing will happen elsewhere if needed. } else { // Read all available data - + NSUInteger result = bytesAvailable; - + if (maxLength > 0) { result = MIN(result, (maxLength - bytesDone)); } - + // No need to avoid resizing the buffer. // If the user provided their own buffer, // and told us to read all available data without giving us a maxLength, // then it is clear that our code might resize the buffer during the read operation. - // + // // This method does not actually do any resizing. // The resizing will happen elsewhere if needed. - + return result; } } @@ -561,10 +571,10 @@ - (NSUInteger)readLengthForNonTermWithHint:(NSUInteger)bytesAvailable /** * For read packets with a set terminator, returns the amount of data * that can be read without exceeding the maxLength. - * + * * The given parameter indicates the number of bytes estimated to be available on the socket, * which is taken into consideration during the calculation. - * + * * To optimize memory allocations, mem copies, and mem moves * the shouldPreBuffer boolean value will indicate if the data should be read into a prebuffer first, * or if the data can be read directly into the read packet's buffer. @@ -573,41 +583,41 @@ - (NSUInteger)readLengthForTermWithHint:(NSUInteger)bytesAvailable shouldPreBuff { NSAssert(term != nil, @"This method does not apply to non-term reads"); NSAssert(bytesAvailable > 0, @"Invalid parameter: bytesAvailable"); - - + + NSUInteger result = bytesAvailable; - + if (maxLength > 0) { result = MIN(result, (maxLength - bytesDone)); } - + // Should the data be read into the read packet's buffer, or into a pre-buffer first? - // + // // One would imagine the preferred option is the faster one. // So which one is faster? - // + // // Reading directly into the packet's buffer requires: // 1. Possibly resizing packet buffer (malloc/realloc) // 2. Filling buffer (read) // 3. Searching for term (memcmp) // 4. Possibly copying overflow into prebuffer (malloc/realloc, memcpy) - // + // // Reading into prebuffer first: // 1. Possibly resizing prebuffer (malloc/realloc) // 2. Filling buffer (read) // 3. Searching for term (memcmp) // 4. Copying underflow into packet buffer (malloc/realloc, memcpy) // 5. Removing underflow from prebuffer (memmove) - // + // // Comparing the performance of the two we can see that reading // data into the prebuffer first is slower due to the extra memove. - // + // // However: // The implementation of NSMutableData is open source via core foundation's CFMutableData. // Decreasing the length of a mutable data object doesn't cause a realloc. // In other words, the capacity of a mutable data object can grow, but doesn't shrink. - // + // // This means the prebuffer will rarely need a realloc. // The packet buffer, on the other hand, may often need a realloc. // This is especially true if we are the buffer owner. @@ -615,24 +625,24 @@ - (NSUInteger)readLengthForTermWithHint:(NSUInteger)bytesAvailable shouldPreBuff // and then moving the overflow into the prebuffer, // then we're consistently over-allocating memory for each term read. // And now we get into a bit of a tradeoff between speed and memory utilization. - // + // // The end result is that the two perform very similarly. // And we can answer the original question very simply by another means. - // + // // If we can read all the data directly into the packet's buffer without resizing it first, // then we do so. Otherwise we use the prebuffer. - + if (shouldPreBufferPtr) { NSUInteger buffSize = [buffer length]; NSUInteger buffUsed = startOffset + bytesDone; - + if ((buffSize - buffUsed) >= result) *shouldPreBufferPtr = NO; else *shouldPreBufferPtr = YES; } - + return result; } @@ -640,103 +650,103 @@ - (NSUInteger)readLengthForTermWithHint:(NSUInteger)bytesAvailable shouldPreBuff * For read packets with a set terminator, * returns the amount of data that can be read from the given preBuffer, * without going over a terminator or the maxLength. - * + * * It is assumed the terminator has not already been read. **/ - (NSUInteger)readLengthForTermWithPreBuffer:(GCDAsyncSocketPreBuffer *)preBuffer found:(BOOL *)foundPtr { NSAssert(term != nil, @"This method does not apply to non-term reads"); NSAssert([preBuffer availableBytes] > 0, @"Invoked with empty pre buffer!"); - + // We know that the terminator, as a whole, doesn't exist in our own buffer. // But it is possible that a _portion_ of it exists in our buffer. // So we're going to look for the terminator starting with a portion of our own buffer. - // + // // Example: - // + // // term length = 3 bytes // bytesDone = 5 bytes // preBuffer length = 5 bytes - // + // // If we append the preBuffer to our buffer, // it would look like this: - // + // // --------------------- // |B|B|B|B|B|P|P|P|P|P| // --------------------- - // + // // So we start our search here: - // + // // --------------------- // |B|B|B|B|B|P|P|P|P|P| // -------^-^-^--------- - // + // // And move forwards... - // + // // --------------------- // |B|B|B|B|B|P|P|P|P|P| // ---------^-^-^------- - // + // // Until we find the terminator or reach the end. - // + // // --------------------- // |B|B|B|B|B|P|P|P|P|P| // ---------------^-^-^- - + BOOL found = NO; - + NSUInteger termLength = [term length]; NSUInteger preBufferLength = [preBuffer availableBytes]; - + if ((bytesDone + preBufferLength) < termLength) { // Not enough data for a full term sequence yet return preBufferLength; } - + NSUInteger maxPreBufferLength; if (maxLength > 0) { maxPreBufferLength = MIN(preBufferLength, (maxLength - bytesDone)); - + // Note: maxLength >= termLength } else { maxPreBufferLength = preBufferLength; } - + #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wvla" uint8_t seq[termLength]; #pragma clang diagnostic pop const void *termBuf = [term bytes]; - + NSUInteger bufLen = MIN(bytesDone, (termLength - 1)); uint8_t *buf = (uint8_t *)[buffer mutableBytes] + startOffset + bytesDone - bufLen; - + NSUInteger preLen = termLength - bufLen; const uint8_t *pre = [preBuffer readBuffer]; - + NSUInteger loopCount = bufLen + maxPreBufferLength - termLength + 1; // Plus one. See example above. - + NSUInteger result = maxPreBufferLength; - + NSUInteger i; for (i = 0; i < loopCount; i++) { if (bufLen > 0) { // Combining bytes from buffer and preBuffer - + memcpy(seq, buf, bufLen); memcpy(seq + bufLen, pre, preLen); - + if (memcmp(seq, termBuf, termLength) == 0) { result = preLen; found = YES; break; } - + buf++; bufLen--; preLen++; @@ -744,22 +754,22 @@ - (NSUInteger)readLengthForTermWithPreBuffer:(GCDAsyncSocketPreBuffer *)preBuffe else { // Comparing directly from preBuffer - + if (memcmp(pre, termBuf, termLength) == 0) { NSUInteger preOffset = pre - [preBuffer readBuffer]; // pointer arithmetic - + result = preOffset + termLength; found = YES; break; } - + pre++; } } - + // There is no need to avoid resizing the buffer in this particular situation. - + if (foundPtr) *foundPtr = found; return result; } @@ -767,12 +777,12 @@ - (NSUInteger)readLengthForTermWithPreBuffer:(GCDAsyncSocketPreBuffer *)preBuffe /** * For read packets with a set terminator, scans the packet buffer for the term. * It is assumed the terminator had not been fully read prior to the new bytes. - * + * * If the term is found, the number of excess bytes after the term are returned. * If the term is not found, this method will return -1. - * + * * Note: A return value of zero means the term was found at the very end. - * + * * Prerequisites: * The given number of bytes have been added to the end of our buffer. * Our bytesDone variable has NOT been changed due to the prebuffered bytes. @@ -780,33 +790,33 @@ - (NSUInteger)readLengthForTermWithPreBuffer:(GCDAsyncSocketPreBuffer *)preBuffe - (NSInteger)searchForTermAfterPreBuffering:(ssize_t)numBytes { NSAssert(term != nil, @"This method does not apply to non-term reads"); - + // The implementation of this method is very similar to the above method. // See the above method for a discussion of the algorithm used here. - + uint8_t *buff = [buffer mutableBytes]; NSUInteger buffLength = bytesDone + numBytes; - + const void *termBuff = [term bytes]; NSUInteger termLength = [term length]; - + // Note: We are dealing with unsigned integers, // so make sure the math doesn't go below zero. - + NSUInteger i = ((buffLength - numBytes) >= termLength) ? (buffLength - numBytes - termLength + 1) : 0; - + while (i + termLength <= buffLength) { uint8_t *subBuffer = buff + startOffset + i; - + if (memcmp(subBuffer, termBuff, termLength) == 0) { return buffLength - (i + termLength); } - + i++; } - + return -1; } @@ -900,10 +910,10 @@ @implementation GCDAsyncSocket { uint32_t flags; uint16_t config; - + __weak id delegate; dispatch_queue_t delegateQueue; - + int socket4FD; int socket6FD; int socketUN; @@ -912,9 +922,9 @@ @implementation GCDAsyncSocket NSData * connectInterface4; NSData * connectInterface6; NSData * connectInterfaceUN; - + dispatch_queue_t socketQueue; - + dispatch_source_t accept4Source; dispatch_source_t accept6Source; dispatch_source_t acceptUNSource; @@ -923,17 +933,17 @@ @implementation GCDAsyncSocket dispatch_source_t writeSource; dispatch_source_t readTimer; dispatch_source_t writeTimer; - + NSMutableArray *readQueue; NSMutableArray *writeQueue; - + GCDAsyncReadPacket *currentRead; GCDAsyncWritePacket *currentWrite; - + unsigned long socketFDBytesAvailable; - + GCDAsyncSocketPreBuffer *preBuffer; - + #if TARGET_OS_IPHONE CFStreamClientContext streamContext; CFReadStreamRef readStream; @@ -944,9 +954,9 @@ @implementation GCDAsyncSocket size_t sslWriteCachedLength; OSStatus sslErrCode; OSStatus lastSSLHandshakeError; - + void *IsOnSocketQueueOrTargetQueueKey; - + id userData; NSTimeInterval alternateAddressDelay; } @@ -972,17 +982,17 @@ - (instancetype)initWithDelegate:(id)aDelegate delegateQ { delegate = aDelegate; delegateQueue = dq; - + #if !OS_OBJECT_USE_OBJC if (dq) dispatch_retain(dq); #endif - + socket4FD = SOCKET_NULL; socket6FD = SOCKET_NULL; socketUN = SOCKET_NULL; socketUrl = nil; stateIndex = 0; - + if (sq) { NSAssert(sq != dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), @@ -991,7 +1001,7 @@ - (instancetype)initWithDelegate:(id)aDelegate delegateQ @"The given socketQueue parameter must not be a concurrent queue."); NSAssert(sq != dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), @"The given socketQueue parameter must not be a concurrent queue."); - + socketQueue = sq; #if !OS_OBJECT_USE_OBJC dispatch_retain(sq); @@ -1001,7 +1011,7 @@ - (instancetype)initWithDelegate:(id)aDelegate delegateQ { socketQueue = dispatch_queue_create([GCDAsyncSocketQueueName UTF8String], NULL); } - + // The dispatch_queue_set_specific() and dispatch_get_specific() functions take a "void *key" parameter. // From the documentation: // @@ -1018,18 +1028,18 @@ - (instancetype)initWithDelegate:(id)aDelegate delegateQ // So we're going to make it so it doesn't matter if we use the '&' or not, // by assigning the value of the ivar to the address of the ivar. // Thus: IsOnSocketQueueOrTargetQueueKey == &IsOnSocketQueueOrTargetQueueKey; - + IsOnSocketQueueOrTargetQueueKey = &IsOnSocketQueueOrTargetQueueKey; - + void *nonNullUnusedPointer = (__bridge void *)self; dispatch_queue_set_specific(socketQueue, IsOnSocketQueueOrTargetQueueKey, nonNullUnusedPointer, NULL); - + readQueue = [[NSMutableArray alloc] initWithCapacity:5]; currentRead = nil; - + writeQueue = [[NSMutableArray alloc] initWithCapacity:5]; currentWrite = nil; - + preBuffer = [[GCDAsyncSocketPreBuffer alloc] initWithCapacity:(1024 * 4)]; alternateAddressDelay = 0.3; } @@ -1039,11 +1049,11 @@ - (instancetype)initWithDelegate:(id)aDelegate delegateQ - (void)dealloc { LogInfo(@"%@ - %@ (start)", THIS_METHOD, self); - + // Set dealloc flag. // This is used by closeWithError to ensure we don't accidentally retain ourself. flags |= kDealloc; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) { [self closeWithError:nil]; @@ -1054,19 +1064,19 @@ - (void)dealloc [self closeWithError:nil]; }); } - + delegate = nil; - + #if !OS_OBJECT_USE_OBJC if (delegateQueue) dispatch_release(delegateQueue); #endif delegateQueue = NULL; - + #if !OS_OBJECT_USE_OBJC if (socketQueue) dispatch_release(socketQueue); #endif socketQueue = NULL; - + LogInfo(@"%@ - %@ (finish)", THIS_METHOD, self); } @@ -1094,7 +1104,7 @@ + (nullable instancetype)socketFromConnectedSocketFD:(int)socketFD delegate:(nul NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncSocketOtherError", @"GCDAsyncSocket", [NSBundle mainBundle], @"Attempt to create socket from socket FD failed. getpeername() failed", nil); - + NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg}; innerError = [NSError errorWithDomain:GCDAsyncSocketErrorDomain @@ -1102,7 +1112,7 @@ + (nullable instancetype)socketFromConnectedSocketFD:(int)socketFD delegate:(nul userInfo:userInfo]; return; } - + if (addr.sa_family == AF_INET) { socket->socket4FD = socketFD; @@ -1116,9 +1126,9 @@ + (nullable instancetype)socketFromConnectedSocketFD:(int)socketFD delegate:(nul NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncSocketOtherError", @"GCDAsyncSocket", [NSBundle mainBundle], @"Attempt to create socket from socket FD failed. socket FD is neither IPv4 nor IPv6", nil); - + NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg}; - + innerError = [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketOtherError userInfo:userInfo]; @@ -1148,11 +1158,11 @@ - (id)delegate else { __block id result; - + dispatch_sync(socketQueue, ^{ result = self->delegate; }); - + return result; } } @@ -1162,7 +1172,7 @@ - (void)setDelegate:(id)newDelegate synchronously:(BOOL)synchronously dispatch_block_t block = ^{ self->delegate = newDelegate; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) { block(); } @@ -1193,11 +1203,11 @@ - (dispatch_queue_t)delegateQueue else { __block dispatch_queue_t result; - + dispatch_sync(socketQueue, ^{ result = self->delegateQueue; }); - + return result; } } @@ -1205,15 +1215,15 @@ - (dispatch_queue_t)delegateQueue - (void)setDelegateQueue:(dispatch_queue_t)newDelegateQueue synchronously:(BOOL)synchronously { dispatch_block_t block = ^{ - + #if !OS_OBJECT_USE_OBJC if (self->delegateQueue) dispatch_release(self->delegateQueue); if (newDelegateQueue) dispatch_retain(newDelegateQueue); #endif - + self->delegateQueue = newDelegateQueue; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) { block(); } @@ -1246,12 +1256,12 @@ - (void)getDelegate:(id *)delegatePtr delegateQueue:(dis { __block id dPtr = NULL; __block dispatch_queue_t dqPtr = NULL; - + dispatch_sync(socketQueue, ^{ dPtr = self->delegate; dqPtr = self->delegateQueue; }); - + if (delegatePtr) *delegatePtr = dPtr; if (delegateQueuePtr) *delegateQueuePtr = dqPtr; } @@ -1260,17 +1270,17 @@ - (void)getDelegate:(id *)delegatePtr delegateQueue:(dis - (void)setDelegate:(id)newDelegate delegateQueue:(dispatch_queue_t)newDelegateQueue synchronously:(BOOL)synchronously { dispatch_block_t block = ^{ - + self->delegate = newDelegate; - + #if !OS_OBJECT_USE_OBJC if (self->delegateQueue) dispatch_release(self->delegateQueue); if (newDelegateQueue) dispatch_retain(newDelegateQueue); #endif - + self->delegateQueue = newDelegateQueue; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) { block(); } @@ -1295,7 +1305,7 @@ - (void)synchronouslySetDelegate:(id)newDelegate delegat - (BOOL)isIPv4Enabled { // Note: YES means kIPv4Disabled is OFF - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) { return ((config & kIPv4Disabled) == 0); @@ -1303,11 +1313,11 @@ - (BOOL)isIPv4Enabled else { __block BOOL result; - + dispatch_sync(socketQueue, ^{ result = ((self->config & kIPv4Disabled) == 0); }); - + return result; } } @@ -1315,15 +1325,15 @@ - (BOOL)isIPv4Enabled - (void)setIPv4Enabled:(BOOL)flag { // Note: YES means kIPv4Disabled is OFF - + dispatch_block_t block = ^{ - + if (flag) self->config &= ~kIPv4Disabled; else self->config |= kIPv4Disabled; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else @@ -1333,7 +1343,7 @@ - (void)setIPv4Enabled:(BOOL)flag - (BOOL)isIPv6Enabled { // Note: YES means kIPv6Disabled is OFF - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) { return ((config & kIPv6Disabled) == 0); @@ -1341,11 +1351,11 @@ - (BOOL)isIPv6Enabled else { __block BOOL result; - + dispatch_sync(socketQueue, ^{ result = ((self->config & kIPv6Disabled) == 0); }); - + return result; } } @@ -1353,15 +1363,15 @@ - (BOOL)isIPv6Enabled - (void)setIPv6Enabled:(BOOL)flag { // Note: YES means kIPv6Disabled is OFF - + dispatch_block_t block = ^{ - + if (flag) self->config &= ~kIPv6Disabled; else self->config |= kIPv6Disabled; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else @@ -1371,7 +1381,7 @@ - (void)setIPv6Enabled:(BOOL)flag - (BOOL)isIPv4PreferredOverIPv6 { // Note: YES means kPreferIPv6 is OFF - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) { return ((config & kPreferIPv6) == 0); @@ -1379,11 +1389,11 @@ - (BOOL)isIPv4PreferredOverIPv6 else { __block BOOL result; - + dispatch_sync(socketQueue, ^{ result = ((self->config & kPreferIPv6) == 0); }); - + return result; } } @@ -1391,15 +1401,15 @@ - (BOOL)isIPv4PreferredOverIPv6 - (void)setIPv4PreferredOverIPv6:(BOOL)flag { // Note: YES means kPreferIPv6 is OFF - + dispatch_block_t block = ^{ - + if (flag) self->config &= ~kPreferIPv6; else self->config |= kPreferIPv6; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else @@ -1431,30 +1441,30 @@ - (void) setAlternateAddressDelay:(NSTimeInterval)delay { - (id)userData { __block id result = nil; - + dispatch_block_t block = ^{ - + result = self->userData; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + return result; } - (void)setUserData:(id)arbitraryUserData { dispatch_block_t block = ^{ - + if (self->userData != arbitraryUserData) { self->userData = arbitraryUserData; } }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else @@ -1473,189 +1483,189 @@ - (BOOL)acceptOnPort:(uint16_t)port error:(NSError **)errPtr - (BOOL)acceptOnInterface:(NSString *)inInterface port:(uint16_t)port error:(NSError **)errPtr { LogTrace(); - + // Just in-case interface parameter is immutable. NSString *interface = [inInterface copy]; - + __block BOOL result = NO; __block NSError *err = nil; - + // CreateSocket Block // This block will be invoked within the dispatch block below. - + int(^createSocket)(int, NSData*) = ^int (int domain, NSData *interfaceAddr) { - + int socketFD = socket(domain, SOCK_STREAM, 0); - + if (socketFD == SOCKET_NULL) { NSString *reason = @"Error in socket() function"; err = [self errorWithErrno:errno reason:reason]; - + return SOCKET_NULL; } - + int status; - + // Set socket options - + status = fcntl(socketFD, F_SETFL, O_NONBLOCK); if (status == -1) { NSString *reason = @"Error enabling non-blocking IO on socket (fcntl)"; err = [self errorWithErrno:errno reason:reason]; - + LogVerbose(@"close(socketFD)"); close(socketFD); return SOCKET_NULL; } - + int reuseOn = 1; status = setsockopt(socketFD, SOL_SOCKET, SO_REUSEADDR, &reuseOn, sizeof(reuseOn)); if (status == -1) { NSString *reason = @"Error enabling address reuse (setsockopt)"; err = [self errorWithErrno:errno reason:reason]; - + LogVerbose(@"close(socketFD)"); close(socketFD); return SOCKET_NULL; } - + // Bind socket - + status = bind(socketFD, (const struct sockaddr *)[interfaceAddr bytes], (socklen_t)[interfaceAddr length]); if (status == -1) { NSString *reason = @"Error in bind() function"; err = [self errorWithErrno:errno reason:reason]; - + LogVerbose(@"close(socketFD)"); close(socketFD); return SOCKET_NULL; } - + // Listen - + status = listen(socketFD, 1024); if (status == -1) { NSString *reason = @"Error in listen() function"; err = [self errorWithErrno:errno reason:reason]; - + LogVerbose(@"close(socketFD)"); close(socketFD); return SOCKET_NULL; } - + return socketFD; }; - + // Create dispatch block and run on socketQueue - + dispatch_block_t block = ^{ @autoreleasepool { - + if (self->delegate == nil) // Must have delegate set { NSString *msg = @"Attempting to accept without a delegate. Set a delegate first."; err = [self badConfigError:msg]; - + return_from_block; } - + if (self->delegateQueue == NULL) // Must have delegate queue set { NSString *msg = @"Attempting to accept without a delegate queue. Set a delegate queue first."; err = [self badConfigError:msg]; - + return_from_block; } - + BOOL isIPv4Disabled = (self->config & kIPv4Disabled) ? YES : NO; BOOL isIPv6Disabled = (self->config & kIPv6Disabled) ? YES : NO; - + if (isIPv4Disabled && isIPv6Disabled) // Must have IPv4 or IPv6 enabled { NSString *msg = @"Both IPv4 and IPv6 have been disabled. Must enable at least one protocol first."; err = [self badConfigError:msg]; - + return_from_block; } - + if (![self isDisconnected]) // Must be disconnected { NSString *msg = @"Attempting to accept while connected or accepting connections. Disconnect first."; err = [self badConfigError:msg]; - + return_from_block; } - + // Clear queues (spurious read/write requests post disconnect) [self->readQueue removeAllObjects]; [self->writeQueue removeAllObjects]; - + // Resolve interface from description - + NSMutableData *interface4 = nil; NSMutableData *interface6 = nil; - + [self getInterfaceAddress4:&interface4 address6:&interface6 fromDescription:interface port:port]; - + if ((interface4 == nil) && (interface6 == nil)) { NSString *msg = @"Unknown interface. Specify valid interface by name (e.g. \"en1\") or IP address."; err = [self badParamError:msg]; - + return_from_block; } - + if (isIPv4Disabled && (interface6 == nil)) { NSString *msg = @"IPv4 has been disabled and specified interface doesn't support IPv6."; err = [self badParamError:msg]; - + return_from_block; } - + if (isIPv6Disabled && (interface4 == nil)) { NSString *msg = @"IPv6 has been disabled and specified interface doesn't support IPv4."; err = [self badParamError:msg]; - + return_from_block; } - + BOOL enableIPv4 = !isIPv4Disabled && (interface4 != nil); BOOL enableIPv6 = !isIPv6Disabled && (interface6 != nil); - + // Create sockets, configure, bind, and listen - + if (enableIPv4) { LogVerbose(@"Creating IPv4 socket"); self->socket4FD = createSocket(AF_INET, interface4); - + if (self->socket4FD == SOCKET_NULL) { return_from_block; } } - + if (enableIPv6) { LogVerbose(@"Creating IPv6 socket"); - + if (enableIPv4 && (port == 0)) { // No specific port was specified, so we allowed the OS to pick an available port for us. // Now we need to make sure the IPv6 socket listens on the same port as the IPv4 socket. - + struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)[interface6 mutableBytes]; addr6->sin6_port = htons([self localPort4]); } - + self->socket6FD = createSocket(AF_INET6, interface6); - + if (self->socket6FD == SOCKET_NULL) { if (self->socket4FD != SOCKET_NULL) @@ -1664,241 +1674,241 @@ - (BOOL)acceptOnInterface:(NSString *)inInterface port:(uint16_t)port error:(NSE close(self->socket4FD); self->socket4FD = SOCKET_NULL; } - + return_from_block; } } - + // Create accept sources - + if (enableIPv4) { self->accept4Source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, self->socket4FD, 0, self->socketQueue); - + int socketFD = self->socket4FD; dispatch_source_t acceptSource = self->accept4Source; - + __weak GCDAsyncSocket *weakSelf = self; - + dispatch_source_set_event_handler(self->accept4Source, ^{ @autoreleasepool { #pragma clang diagnostic push #pragma clang diagnostic warning "-Wimplicit-retain-self" - + __strong GCDAsyncSocket *strongSelf = weakSelf; if (strongSelf == nil) return_from_block; - + LogVerbose(@"event4Block"); - + unsigned long i = 0; unsigned long numPendingConnections = dispatch_source_get_data(acceptSource); - + LogVerbose(@"numPendingConnections: %lu", numPendingConnections); - + while ([strongSelf doAccept:socketFD] && (++i < numPendingConnections)); - + #pragma clang diagnostic pop }}); - - + + dispatch_source_set_cancel_handler(self->accept4Source, ^{ #pragma clang diagnostic push #pragma clang diagnostic warning "-Wimplicit-retain-self" - + #if !OS_OBJECT_USE_OBJC LogVerbose(@"dispatch_release(accept4Source)"); dispatch_release(acceptSource); #endif - + LogVerbose(@"close(socket4FD)"); close(socketFD); - + #pragma clang diagnostic pop }); - + LogVerbose(@"dispatch_resume(accept4Source)"); dispatch_resume(self->accept4Source); } - + if (enableIPv6) { self->accept6Source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, self->socket6FD, 0, self->socketQueue); - + int socketFD = self->socket6FD; dispatch_source_t acceptSource = self->accept6Source; - + __weak GCDAsyncSocket *weakSelf = self; - + dispatch_source_set_event_handler(self->accept6Source, ^{ @autoreleasepool { #pragma clang diagnostic push #pragma clang diagnostic warning "-Wimplicit-retain-self" - + __strong GCDAsyncSocket *strongSelf = weakSelf; if (strongSelf == nil) return_from_block; - + LogVerbose(@"event6Block"); - + unsigned long i = 0; unsigned long numPendingConnections = dispatch_source_get_data(acceptSource); - + LogVerbose(@"numPendingConnections: %lu", numPendingConnections); - + while ([strongSelf doAccept:socketFD] && (++i < numPendingConnections)); - + #pragma clang diagnostic pop }}); - + dispatch_source_set_cancel_handler(self->accept6Source, ^{ #pragma clang diagnostic push #pragma clang diagnostic warning "-Wimplicit-retain-self" - + #if !OS_OBJECT_USE_OBJC LogVerbose(@"dispatch_release(accept6Source)"); dispatch_release(acceptSource); #endif - + LogVerbose(@"close(socket6FD)"); close(socketFD); - + #pragma clang diagnostic pop }); - + LogVerbose(@"dispatch_resume(accept6Source)"); dispatch_resume(self->accept6Source); } - + self->flags |= kSocketStarted; - + result = YES; }}; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + if (result == NO) { LogInfo(@"Error in accept: %@", err); - + if (errPtr) *errPtr = err; } - + return result; } - (BOOL)acceptOnUrl:(NSURL *)url error:(NSError **)errPtr { LogTrace(); - + __block BOOL result = NO; __block NSError *err = nil; - + // CreateSocket Block // This block will be invoked within the dispatch block below. - + int(^createSocket)(int, NSData*) = ^int (int domain, NSData *interfaceAddr) { - + int socketFD = socket(domain, SOCK_STREAM, 0); - + if (socketFD == SOCKET_NULL) { NSString *reason = @"Error in socket() function"; err = [self errorWithErrno:errno reason:reason]; - + return SOCKET_NULL; } - + int status; - + // Set socket options - + status = fcntl(socketFD, F_SETFL, O_NONBLOCK); if (status == -1) { NSString *reason = @"Error enabling non-blocking IO on socket (fcntl)"; err = [self errorWithErrno:errno reason:reason]; - + LogVerbose(@"close(socketFD)"); close(socketFD); return SOCKET_NULL; } - + int reuseOn = 1; status = setsockopt(socketFD, SOL_SOCKET, SO_REUSEADDR, &reuseOn, sizeof(reuseOn)); if (status == -1) { NSString *reason = @"Error enabling address reuse (setsockopt)"; err = [self errorWithErrno:errno reason:reason]; - + LogVerbose(@"close(socketFD)"); close(socketFD); return SOCKET_NULL; } - + // Bind socket - + status = bind(socketFD, (const struct sockaddr *)[interfaceAddr bytes], (socklen_t)[interfaceAddr length]); if (status == -1) { NSString *reason = @"Error in bind() function"; err = [self errorWithErrno:errno reason:reason]; - + LogVerbose(@"close(socketFD)"); close(socketFD); return SOCKET_NULL; } - + // Listen - + status = listen(socketFD, 1024); if (status == -1) { NSString *reason = @"Error in listen() function"; err = [self errorWithErrno:errno reason:reason]; - + LogVerbose(@"close(socketFD)"); close(socketFD); return SOCKET_NULL; } - + return socketFD; }; - + // Create dispatch block and run on socketQueue - + dispatch_block_t block = ^{ @autoreleasepool { - + if (self->delegate == nil) // Must have delegate set { NSString *msg = @"Attempting to accept without a delegate. Set a delegate first."; err = [self badConfigError:msg]; - + return_from_block; } - + if (self->delegateQueue == NULL) // Must have delegate queue set { NSString *msg = @"Attempting to accept without a delegate queue. Set a delegate queue first."; err = [self badConfigError:msg]; - + return_from_block; } - + if (![self isDisconnected]) // Must be disconnected { NSString *msg = @"Attempting to accept while connected or accepting connections. Disconnect first."; err = [self badConfigError:msg]; - + return_from_block; } - + // Clear queues (spurious read/write requests post disconnect) [self->readQueue removeAllObjects]; [self->writeQueue removeAllObjects]; - + // Remove a previous socket - + NSError *error = nil; NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *urlPath = url.path; @@ -1906,155 +1916,155 @@ - (BOOL)acceptOnUrl:(NSURL *)url error:(NSError **)errPtr if (![fileManager removeItemAtURL:url error:&error]) { NSString *msg = @"Could not remove previous unix domain socket at given url."; err = [self otherError:msg]; - + return_from_block; } } - + // Resolve interface from description - + NSData *interface = [self getInterfaceAddressFromUrl:url]; - + if (interface == nil) { NSString *msg = @"Invalid unix domain url. Specify a valid file url that does not exist (e.g. \"file:///tmp/socket\")"; err = [self badParamError:msg]; - + return_from_block; } - + // Create sockets, configure, bind, and listen - + LogVerbose(@"Creating unix domain socket"); self->socketUN = createSocket(AF_UNIX, interface); - + if (self->socketUN == SOCKET_NULL) { return_from_block; } - + self->socketUrl = url; - + // Create accept sources - + self->acceptUNSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, self->socketUN, 0, self->socketQueue); - + int socketFD = self->socketUN; dispatch_source_t acceptSource = self->acceptUNSource; - + __weak GCDAsyncSocket *weakSelf = self; - + dispatch_source_set_event_handler(self->acceptUNSource, ^{ @autoreleasepool { - + __strong GCDAsyncSocket *strongSelf = weakSelf; - + LogVerbose(@"eventUNBlock"); - + unsigned long i = 0; unsigned long numPendingConnections = dispatch_source_get_data(acceptSource); - + LogVerbose(@"numPendingConnections: %lu", numPendingConnections); - + while ([strongSelf doAccept:socketFD] && (++i < numPendingConnections)); }}); - + dispatch_source_set_cancel_handler(self->acceptUNSource, ^{ - + #if !OS_OBJECT_USE_OBJC LogVerbose(@"dispatch_release(acceptUNSource)"); dispatch_release(acceptSource); #endif - + LogVerbose(@"close(socketUN)"); close(socketFD); }); - + LogVerbose(@"dispatch_resume(acceptUNSource)"); dispatch_resume(self->acceptUNSource); - + self->flags |= kSocketStarted; - + result = YES; }}; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + if (result == NO) { LogInfo(@"Error in accept: %@", err); - + if (errPtr) *errPtr = err; } - - return result; + + return result; } - (BOOL)doAccept:(int)parentSocketFD { LogTrace(); - + int socketType; int childSocketFD; NSData *childSocketAddress; - + if (parentSocketFD == socket4FD) { socketType = 0; - + struct sockaddr_in addr; socklen_t addrLen = sizeof(addr); - + childSocketFD = accept(parentSocketFD, (struct sockaddr *)&addr, &addrLen); - + if (childSocketFD == -1) { LogWarn(@"Accept failed with error: %@", [self errnoError]); return NO; } - + childSocketAddress = [NSData dataWithBytes:&addr length:addrLen]; } else if (parentSocketFD == socket6FD) { socketType = 1; - + struct sockaddr_in6 addr; socklen_t addrLen = sizeof(addr); - + childSocketFD = accept(parentSocketFD, (struct sockaddr *)&addr, &addrLen); - + if (childSocketFD == -1) { LogWarn(@"Accept failed with error: %@", [self errnoError]); return NO; } - + childSocketAddress = [NSData dataWithBytes:&addr length:addrLen]; } else // if (parentSocketFD == socketUN) { socketType = 2; - + struct sockaddr_un addr; socklen_t addrLen = sizeof(addr); - + childSocketFD = accept(parentSocketFD, (struct sockaddr *)&addr, &addrLen); - + if (childSocketFD == -1) { LogWarn(@"Accept failed with error: %@", [self errnoError]); return NO; } - + childSocketAddress = [NSData dataWithBytes:&addr length:addrLen]; } - + // Enable non-blocking IO on the socket - + int result = fcntl(childSocketFD, F_SETFL, O_NONBLOCK); if (result == -1) { @@ -2063,69 +2073,69 @@ - (BOOL)doAccept:(int)parentSocketFD close(childSocketFD); return NO; } - + // Prevent SIGPIPE signals - + int nosigpipe = 1; setsockopt(childSocketFD, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe)); - + // Notify delegate - + if (delegateQueue) { __strong id theDelegate = delegate; - + dispatch_async(delegateQueue, ^{ @autoreleasepool { - + // Query delegate for custom socket queue - + dispatch_queue_t childSocketQueue = NULL; - + if ([theDelegate respondsToSelector:@selector(newSocketQueueForConnectionFromAddress:onSocket:)]) { childSocketQueue = [theDelegate newSocketQueueForConnectionFromAddress:childSocketAddress onSocket:self]; } - + // Create GCDAsyncSocket instance for accepted socket - + GCDAsyncSocket *acceptedSocket = [[[self class] alloc] initWithDelegate:theDelegate delegateQueue:self->delegateQueue socketQueue:childSocketQueue]; - + if (socketType == 0) acceptedSocket->socket4FD = childSocketFD; else if (socketType == 1) acceptedSocket->socket6FD = childSocketFD; else acceptedSocket->socketUN = childSocketFD; - + acceptedSocket->flags = (kSocketStarted | kConnected); - + // Setup read and write sources for accepted socket - + dispatch_async(acceptedSocket->socketQueue, ^{ @autoreleasepool { - + [acceptedSocket setupReadAndWriteSourcesForNewlyConnectedSocket:childSocketFD]; }}); - + // Notify delegate - + if ([theDelegate respondsToSelector:@selector(socket:didAcceptNewSocket:)]) { [theDelegate socket:self didAcceptNewSocket:acceptedSocket]; } - + // Release the socket queue returned from the delegate (it was retained by acceptedSocket) #if !OS_OBJECT_USE_OBJC if (childSocketQueue) dispatch_release(childSocketQueue); #endif - + // The accepted socket should have been retained by the delegate. // Otherwise it gets properly released when exiting the block. }}); } - + return YES; } @@ -2136,12 +2146,12 @@ - (BOOL)doAccept:(int)parentSocketFD /** * This method runs through the various checks required prior to a connection attempt. * It is shared between the connectToHost and connectToAddress methods. - * + * **/ - (BOOL)preConnectWithInterface:(NSString *)interface error:(NSError **)errPtr { NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - + if (delegate == nil) // Must have delegate set { if (errPtr) @@ -2151,7 +2161,7 @@ - (BOOL)preConnectWithInterface:(NSString *)interface error:(NSError **)errPtr } return NO; } - + if (delegateQueue == NULL) // Must have delegate queue set { if (errPtr) @@ -2161,7 +2171,7 @@ - (BOOL)preConnectWithInterface:(NSString *)interface error:(NSError **)errPtr } return NO; } - + if (![self isDisconnected]) // Must be disconnected { if (errPtr) @@ -2171,10 +2181,10 @@ - (BOOL)preConnectWithInterface:(NSString *)interface error:(NSError **)errPtr } return NO; } - + BOOL isIPv4Disabled = (config & kIPv4Disabled) ? YES : NO; BOOL isIPv6Disabled = (config & kIPv6Disabled) ? YES : NO; - + if (isIPv4Disabled && isIPv6Disabled) // Must have IPv4 or IPv6 enabled { if (errPtr) @@ -2184,14 +2194,14 @@ - (BOOL)preConnectWithInterface:(NSString *)interface error:(NSError **)errPtr } return NO; } - + if (interface) { NSMutableData *interface4 = nil; NSMutableData *interface6 = nil; - + [self getInterfaceAddress4:&interface4 address6:&interface6 fromDescription:interface port:0]; - + if ((interface4 == nil) && (interface6 == nil)) { if (errPtr) @@ -2201,7 +2211,7 @@ - (BOOL)preConnectWithInterface:(NSString *)interface error:(NSError **)errPtr } return NO; } - + if (isIPv4Disabled && (interface6 == nil)) { if (errPtr) @@ -2211,7 +2221,7 @@ - (BOOL)preConnectWithInterface:(NSString *)interface error:(NSError **)errPtr } return NO; } - + if (isIPv6Disabled && (interface4 == nil)) { if (errPtr) @@ -2221,22 +2231,22 @@ - (BOOL)preConnectWithInterface:(NSString *)interface error:(NSError **)errPtr } return NO; } - + connectInterface4 = interface4; connectInterface6 = interface6; } - + // Clear queues (spurious read/write requests post disconnect) [readQueue removeAllObjects]; [writeQueue removeAllObjects]; - + return YES; } - (BOOL)preConnectWithUrl:(NSURL *)url error:(NSError **)errPtr { NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - + if (delegate == nil) // Must have delegate set { if (errPtr) @@ -2246,7 +2256,7 @@ - (BOOL)preConnectWithUrl:(NSURL *)url error:(NSError **)errPtr } return NO; } - + if (delegateQueue == NULL) // Must have delegate queue set { if (errPtr) @@ -2256,7 +2266,7 @@ - (BOOL)preConnectWithUrl:(NSURL *)url error:(NSError **)errPtr } return NO; } - + if (![self isDisconnected]) // Must be disconnected { if (errPtr) @@ -2266,9 +2276,9 @@ - (BOOL)preConnectWithUrl:(NSURL *)url error:(NSError **)errPtr } return NO; } - + NSData *interface = [self getInterfaceAddressFromUrl:url]; - + if (interface == nil) { if (errPtr) @@ -2278,13 +2288,13 @@ - (BOOL)preConnectWithUrl:(NSURL *)url error:(NSError **)errPtr } return NO; } - + connectInterfaceUN = interface; - + // Clear queues (spurious read/write requests post disconnect) [readQueue removeAllObjects]; [writeQueue removeAllObjects]; - + return YES; } @@ -2308,64 +2318,64 @@ - (BOOL)connectToHost:(NSString *)inHost error:(NSError **)errPtr { LogTrace(); - + // Just in case immutable objects were passed NSString *host = [inHost copy]; NSString *interface = [inInterface copy]; - + __block BOOL result = NO; __block NSError *preConnectErr = nil; - + dispatch_block_t block = ^{ @autoreleasepool { - + // Check for problems with host parameter - + if ([host length] == 0) { NSString *msg = @"Invalid host parameter (nil or \"\"). Should be a domain name or IP address string."; preConnectErr = [self badParamError:msg]; - + return_from_block; } - + // Run through standard pre-connect checks - + if (![self preConnectWithInterface:interface error:&preConnectErr]) { return_from_block; } - + // We've made it past all the checks. // It's time to start the connection process. - + self->flags |= kSocketStarted; - + LogVerbose(@"Dispatching DNS lookup..."); - + // It's possible that the given host parameter is actually a NSMutableString. // So we want to copy it now, within this block that will be executed synchronously. // This way the asynchronous lookup block below doesn't have to worry about it changing. - + NSString *hostCpy = [host copy]; - + int aStateIndex = self->stateIndex; __weak GCDAsyncSocket *weakSelf = self; - + dispatch_queue_t globalConcurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(globalConcurrentQueue, ^{ @autoreleasepool { #pragma clang diagnostic push #pragma clang diagnostic warning "-Wimplicit-retain-self" - + NSError *lookupErr = nil; NSMutableArray *addresses = [[self class] lookupHost:hostCpy port:port error:&lookupErr]; - + __strong GCDAsyncSocket *strongSelf = weakSelf; if (strongSelf == nil) return_from_block; - + if (lookupErr) { dispatch_async(strongSelf->socketQueue, ^{ @autoreleasepool { - + [strongSelf lookup:aStateIndex didFail:lookupErr]; }}); } @@ -2373,7 +2383,7 @@ - (BOOL)connectToHost:(NSString *)inHost { NSData *address4 = nil; NSData *address6 = nil; - + for (NSData *address in addresses) { if (!address4 && [[self class] isIPv4Address:address]) @@ -2385,27 +2395,27 @@ - (BOOL)connectToHost:(NSString *)inHost address6 = address; } } - + dispatch_async(strongSelf->socketQueue, ^{ @autoreleasepool { - + [strongSelf lookup:aStateIndex didSucceedWithAddress4:address4 address6:address6]; }}); } - + #pragma clang diagnostic pop }}); - + [self startConnectTimeout:timeout]; - + result = YES; }}; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - - + + if (errPtr) *errPtr = preConnectErr; return result; } @@ -2426,25 +2436,25 @@ - (BOOL)connectToAddress:(NSData *)inRemoteAddr error:(NSError **)errPtr { LogTrace(); - + // Just in case immutable objects were passed NSData *remoteAddr = [inRemoteAddr copy]; NSString *interface = [inInterface copy]; - + __block BOOL result = NO; __block NSError *err = nil; - + dispatch_block_t block = ^{ @autoreleasepool { - + // Check for problems with remoteAddr parameter - + NSData *address4 = nil; NSData *address6 = nil; - + if ([remoteAddr length] >= sizeof(struct sockaddr)) { const struct sockaddr *sockaddr = (const struct sockaddr *)[remoteAddr bytes]; - + if (sockaddr->sa_family == AF_INET) { if ([remoteAddr length] == sizeof(struct sockaddr_in)) @@ -2460,169 +2470,169 @@ - (BOOL)connectToAddress:(NSData *)inRemoteAddr } } } - + if ((address4 == nil) && (address6 == nil)) { NSString *msg = @"A valid IPv4 or IPv6 address was not given"; err = [self badParamError:msg]; - + return_from_block; } - + BOOL isIPv4Disabled = (self->config & kIPv4Disabled) ? YES : NO; BOOL isIPv6Disabled = (self->config & kIPv6Disabled) ? YES : NO; - + if (isIPv4Disabled && (address4 != nil)) { NSString *msg = @"IPv4 has been disabled and an IPv4 address was passed."; err = [self badParamError:msg]; - + return_from_block; } - + if (isIPv6Disabled && (address6 != nil)) { NSString *msg = @"IPv6 has been disabled and an IPv6 address was passed."; err = [self badParamError:msg]; - + return_from_block; } - + // Run through standard pre-connect checks - + if (![self preConnectWithInterface:interface error:&err]) { return_from_block; } - + // We've made it past all the checks. // It's time to start the connection process. - + if (![self connectWithAddress4:address4 address6:address6 error:&err]) { return_from_block; } - + self->flags |= kSocketStarted; - + [self startConnectTimeout:timeout]; - + result = YES; }}; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + if (result == NO) { if (errPtr) *errPtr = err; } - + return result; } - (BOOL)connectToUrl:(NSURL *)url withTimeout:(NSTimeInterval)timeout error:(NSError **)errPtr { LogTrace(); - + __block BOOL result = NO; __block NSError *err = nil; - + dispatch_block_t block = ^{ @autoreleasepool { - + // Check for problems with host parameter - + if ([url.path length] == 0) { NSString *msg = @"Invalid unix domain socket url."; err = [self badParamError:msg]; - + return_from_block; } - + // Run through standard pre-connect checks - + if (![self preConnectWithUrl:url error:&err]) { return_from_block; } - + // We've made it past all the checks. // It's time to start the connection process. - + self->flags |= kSocketStarted; - + // Start the normal connection process - + NSError *connectError = nil; if (![self connectWithAddressUN:self->connectInterfaceUN error:&connectError]) { [self closeWithError:connectError]; - + return_from_block; } [self startConnectTimeout:timeout]; - + result = YES; }}; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + if (result == NO) { if (errPtr) *errPtr = err; } - + return result; } - (void)lookup:(int)aStateIndex didSucceedWithAddress4:(NSData *)address4 address6:(NSData *)address6 { LogTrace(); - + NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); NSAssert(address4 || address6, @"Expected at least one valid address"); - + if (aStateIndex != stateIndex) { LogInfo(@"Ignoring lookupDidSucceed, already disconnected"); - + // The connect operation has been cancelled. // That is, socket was disconnected, or connection has already timed out. return; } - + // Check for problems - + BOOL isIPv4Disabled = (config & kIPv4Disabled) ? YES : NO; BOOL isIPv6Disabled = (config & kIPv6Disabled) ? YES : NO; - + if (isIPv4Disabled && (address6 == nil)) { NSString *msg = @"IPv4 has been disabled and DNS lookup found no IPv6 address."; - + [self closeWithError:[self otherError:msg]]; return; } - + if (isIPv6Disabled && (address4 == nil)) { NSString *msg = @"IPv6 has been disabled and DNS lookup found no IPv4 address."; - + [self closeWithError:[self otherError:msg]]; return; } - + // Start the normal connection process - + NSError *err = nil; if (![self connectWithAddress4:address4 address6:address6 error:&err]) { @@ -2633,7 +2643,7 @@ - (void)lookup:(int)aStateIndex didSucceedWithAddress4:(NSData *)address4 addres /** * This method is called if the DNS lookup fails. * This method is executed on the socketQueue. - * + * * Since the DNS lookup executed synchronously on a global concurrent queue, * the original connection request may have already been cancelled or timed-out by the time this method is invoked. * The lookupIndex tells us whether the lookup is still valid or not. @@ -2641,19 +2651,19 @@ - (void)lookup:(int)aStateIndex didSucceedWithAddress4:(NSData *)address4 addres - (void)lookup:(int)aStateIndex didFail:(NSError *)error { LogTrace(); - + NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - - + + if (aStateIndex != stateIndex) { LogInfo(@"Ignoring lookup:didFail: - already disconnected"); - + // The connect operation has been cancelled. // That is, socket was disconnected, or connection has already timed out. return; } - + [self endConnectTimeout]; [self closeWithError:error]; } @@ -2661,59 +2671,59 @@ - (void)lookup:(int)aStateIndex didFail:(NSError *)error - (BOOL)bindSocket:(int)socketFD toInterface:(NSData *)connectInterface error:(NSError **)errPtr { // Bind the socket to the desired interface (if needed) - + if (connectInterface) { LogVerbose(@"Binding socket..."); - + if ([[self class] portFromAddress:connectInterface] > 0) { // Since we're going to be binding to a specific port, // we should turn on reuseaddr to allow us to override sockets in time_wait. - + int reuseOn = 1; setsockopt(socketFD, SOL_SOCKET, SO_REUSEADDR, &reuseOn, sizeof(reuseOn)); } - + const struct sockaddr *interfaceAddr = (const struct sockaddr *)[connectInterface bytes]; - + int result = bind(socketFD, interfaceAddr, (socklen_t)[connectInterface length]); if (result != 0) { if (errPtr) *errPtr = [self errorWithErrno:errno reason:@"Error in bind() function"]; - + return NO; } } - + return YES; } - (int)createSocket:(int)family connectInterface:(NSData *)connectInterface errPtr:(NSError **)errPtr { int socketFD = socket(family, SOCK_STREAM, 0); - + if (socketFD == SOCKET_NULL) { if (errPtr) *errPtr = [self errorWithErrno:errno reason:@"Error in socket() function"]; - + return socketFD; } - + if (![self bindSocket:socketFD toInterface:connectInterface error:errPtr]) { [self closeSocket:socketFD]; - + return SOCKET_NULL; } - + // Prevent SIGPIPE signals - + int nosigpipe = 1; setsockopt(socketFD, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe)); - + return socketFD; } @@ -2725,40 +2735,40 @@ - (void)connectSocket:(int)socketFD address:(NSData *)address stateIndex:(int)aS [self closeSocket:socketFD]; return; } - + // Start the connection process in a background queue - + __weak GCDAsyncSocket *weakSelf = self; - + dispatch_queue_t globalConcurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(globalConcurrentQueue, ^{ #pragma clang diagnostic push #pragma clang diagnostic warning "-Wimplicit-retain-self" - + int result = connect(socketFD, (const struct sockaddr *)[address bytes], (socklen_t)[address length]); int err = errno; - + __strong GCDAsyncSocket *strongSelf = weakSelf; if (strongSelf == nil) return_from_block; - + dispatch_async(strongSelf->socketQueue, ^{ @autoreleasepool { - + if (strongSelf.isConnected) { [strongSelf closeSocket:socketFD]; return_from_block; } - + if (result == 0) { [self closeUnusedSocket:socketFD]; - + [strongSelf didConnect:aStateIndex]; } else { [strongSelf closeSocket:socketFD]; - + // If there are no more sockets trying to connect, we inform the error to the delegate if (strongSelf.socket4FD == SOCKET_NULL && strongSelf.socket6FD == SOCKET_NULL) { @@ -2767,10 +2777,10 @@ - (void)connectSocket:(int)socketFD address:(NSData *)address stateIndex:(int)aS } } }}); - + #pragma clang diagnostic pop }); - + LogVerbose(@"Connecting..."); } @@ -2780,7 +2790,7 @@ - (void)closeSocket:(int)socketFD (socketFD == socket6FD || socketFD == socket4FD)) { close(socketFD); - + if (socketFD == socket4FD) { LogVerbose(@"close(socket4FD)"); @@ -2809,40 +2819,40 @@ - (void)closeUnusedSocket:(int)usedSocketFD - (BOOL)connectWithAddress4:(NSData *)address4 address6:(NSData *)address6 error:(NSError **)errPtr { LogTrace(); - + NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - + LogVerbose(@"IPv4: %@:%hu", [[self class] hostFromAddress:address4], [[self class] portFromAddress:address4]); LogVerbose(@"IPv6: %@:%hu", [[self class] hostFromAddress:address6], [[self class] portFromAddress:address6]); - + // Determine socket type - + BOOL preferIPv6 = (config & kPreferIPv6) ? YES : NO; - + // Create and bind the sockets - + if (address4) { LogVerbose(@"Creating IPv4 socket"); - + socket4FD = [self createSocket:AF_INET connectInterface:connectInterface4 errPtr:errPtr]; } - + if (address6) { LogVerbose(@"Creating IPv6 socket"); - + socket6FD = [self createSocket:AF_INET6 connectInterface:connectInterface6 errPtr:errPtr]; } - + if (socket4FD == SOCKET_NULL && socket6FD == SOCKET_NULL) { return NO; } - + int socketFD, alternateSocketFD; NSData *address, *alternateAddress; - + if ((preferIPv6 && socket6FD != SOCKET_NULL) || socket4FD == SOCKET_NULL) { socketFD = socket6FD; @@ -2859,79 +2869,79 @@ - (BOOL)connectWithAddress4:(NSData *)address4 address6:(NSData *)address6 error } int aStateIndex = stateIndex; - + [self connectSocket:socketFD address:address stateIndex:aStateIndex]; - + if (alternateAddress) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(alternateAddressDelay * NSEC_PER_SEC)), socketQueue, ^{ [self connectSocket:alternateSocketFD address:alternateAddress stateIndex:aStateIndex]; }); } - + return YES; } - (BOOL)connectWithAddressUN:(NSData *)address error:(NSError **)errPtr { LogTrace(); - + NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - + // Create the socket - + int socketFD; - + LogVerbose(@"Creating unix domain socket"); - + socketUN = socket(AF_UNIX, SOCK_STREAM, 0); - + socketFD = socketUN; - + if (socketFD == SOCKET_NULL) { if (errPtr) *errPtr = [self errorWithErrno:errno reason:@"Error in socket() function"]; - + return NO; } - + // Bind the socket to the desired interface (if needed) - + LogVerbose(@"Binding socket..."); - + int reuseOn = 1; setsockopt(socketFD, SOL_SOCKET, SO_REUSEADDR, &reuseOn, sizeof(reuseOn)); // const struct sockaddr *interfaceAddr = (const struct sockaddr *)[address bytes]; -// +// // int result = bind(socketFD, interfaceAddr, (socklen_t)[address length]); // if (result != 0) // { // if (errPtr) // *errPtr = [self errnoErrorWithReason:@"Error in bind() function"]; -// +// // return NO; // } - + // Prevent SIGPIPE signals - + int nosigpipe = 1; setsockopt(socketFD, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe)); - + // Start the connection process in a background queue - + int aStateIndex = stateIndex; - + dispatch_queue_t globalConcurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(globalConcurrentQueue, ^{ - + const struct sockaddr *addr = (const struct sockaddr *)[address bytes]; int result = connect(socketFD, addr, addr->sa_len); if (result == 0) { dispatch_async(self->socketQueue, ^{ @autoreleasepool { - + [self didConnect:aStateIndex]; }}); } @@ -2940,112 +2950,112 @@ - (BOOL)connectWithAddressUN:(NSData *)address error:(NSError **)errPtr // TODO: Bad file descriptor perror("connect"); NSError *error = [self errorWithErrno:errno reason:@"Error in connect() function"]; - + dispatch_async(self->socketQueue, ^{ @autoreleasepool { - + [self didNotConnect:aStateIndex error:error]; }}); } }); - + LogVerbose(@"Connecting..."); - + return YES; } - (void)didConnect:(int)aStateIndex { LogTrace(); - + NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - - + + if (aStateIndex != stateIndex) { LogInfo(@"Ignoring didConnect, already disconnected"); - + // The connect operation has been cancelled. // That is, socket was disconnected, or connection has already timed out. return; } - + flags |= kConnected; - + [self endConnectTimeout]; - + #if TARGET_OS_IPHONE // The endConnectTimeout method executed above incremented the stateIndex. aStateIndex = stateIndex; #endif - + // Setup read/write streams (as workaround for specific shortcomings in the iOS platform) - // + // // Note: // There may be configuration options that must be set by the delegate before opening the streams. // The primary example is the kCFStreamNetworkServiceTypeVoIP flag, which only works on an unopened stream. - // + // // Thus we wait until after the socket:didConnectToHost:port: delegate method has completed. // This gives the delegate time to properly configure the streams if needed. - + dispatch_block_t SetupStreamsPart1 = ^{ #if TARGET_OS_IPHONE - + if (![self createReadAndWriteStream]) { [self closeWithError:[self otherError:@"Error creating CFStreams"]]; return; } - + if (![self registerForStreamCallbacksIncludingReadWrite:NO]) { [self closeWithError:[self otherError:@"Error in CFStreamSetClient"]]; return; } - + #endif }; dispatch_block_t SetupStreamsPart2 = ^{ #if TARGET_OS_IPHONE - + if (aStateIndex != self->stateIndex) { // The socket has been disconnected. return; } - + if (![self addStreamsToRunLoop]) { [self closeWithError:[self otherError:@"Error in CFStreamScheduleWithRunLoop"]]; return; } - + if (![self openStreams]) { [self closeWithError:[self otherError:@"Error creating CFStreams"]]; return; } - + #endif }; - + // Notify delegate - + NSString *host = [self connectedHost]; uint16_t port = [self connectedPort]; NSURL *url = [self connectedUrl]; - + __strong id theDelegate = delegate; if (delegateQueue && host != nil && [theDelegate respondsToSelector:@selector(socket:didConnectToHost:port:)]) { SetupStreamsPart1(); - + dispatch_async(delegateQueue, ^{ @autoreleasepool { - + [theDelegate socket:self didConnectToHost:host port:port]; - + dispatch_async(self->socketQueue, ^{ @autoreleasepool { - + SetupStreamsPart2(); }}); }}); @@ -3053,13 +3063,13 @@ - (void)didConnect:(int)aStateIndex else if (delegateQueue && url != nil && [theDelegate respondsToSelector:@selector(socket:didConnectToUrl:)]) { SetupStreamsPart1(); - + dispatch_async(delegateQueue, ^{ @autoreleasepool { - + [theDelegate socket:self didConnectToUrl:url]; - + dispatch_async(self->socketQueue, ^{ @autoreleasepool { - + SetupStreamsPart2(); }}); }}); @@ -3069,28 +3079,28 @@ - (void)didConnect:(int)aStateIndex SetupStreamsPart1(); SetupStreamsPart2(); } - + // Get the connected socket - + int socketFD = (socket4FD != SOCKET_NULL) ? socket4FD : (socket6FD != SOCKET_NULL) ? socket6FD : socketUN; - + // Enable non-blocking IO on the socket - + int result = fcntl(socketFD, F_SETFL, O_NONBLOCK); if (result == -1) { NSString *errMsg = @"Error enabling non-blocking IO on socket (fcntl)"; [self closeWithError:[self otherError:errMsg]]; - + return; } - + // Setup our read/write sources - + [self setupReadAndWriteSourcesForNewlyConnectedSocket:socketFD]; - + // Dequeue any pending read/write requests - + [self maybeDequeueRead]; [self maybeDequeueWrite]; } @@ -3098,19 +3108,19 @@ - (void)didConnect:(int)aStateIndex - (void)didNotConnect:(int)aStateIndex error:(NSError *)error { LogTrace(); - + NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - - + + if (aStateIndex != stateIndex) { LogInfo(@"Ignoring didNotConnect, already disconnected"); - + // The connect operation has been cancelled. // That is, socket was disconnected, or connection has already timed out. return; } - + [self closeWithError:error]; } @@ -3119,37 +3129,37 @@ - (void)startConnectTimeout:(NSTimeInterval)timeout if (timeout >= 0.0) { connectTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, socketQueue); - + __weak GCDAsyncSocket *weakSelf = self; - + dispatch_source_set_event_handler(connectTimer, ^{ @autoreleasepool { #pragma clang diagnostic push #pragma clang diagnostic warning "-Wimplicit-retain-self" - + __strong GCDAsyncSocket *strongSelf = weakSelf; if (strongSelf == nil) return_from_block; - + [strongSelf doConnectTimeout]; - + #pragma clang diagnostic pop }}); - + #if !OS_OBJECT_USE_OBJC dispatch_source_t theConnectTimer = connectTimer; dispatch_source_set_cancel_handler(connectTimer, ^{ #pragma clang diagnostic push #pragma clang diagnostic warning "-Wimplicit-retain-self" - + LogVerbose(@"dispatch_release(connectTimer)"); dispatch_release(theConnectTimer); - + #pragma clang diagnostic pop }); #endif - + dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeout * NSEC_PER_SEC)); dispatch_source_set_timer(connectTimer, tt, DISPATCH_TIME_FOREVER, 0); - + dispatch_resume(connectTimer); } } @@ -3157,21 +3167,21 @@ - (void)startConnectTimeout:(NSTimeInterval)timeout - (void)endConnectTimeout { LogTrace(); - + if (connectTimer) { dispatch_source_cancel(connectTimer); connectTimer = NULL; } - + // Increment stateIndex. // This will prevent us from processing results from any related background asynchronous operations. - // + // // Note: This should be called from close method even if connectTimer is NULL. // This is because one might disconnect a socket prior to a successful connection which had no timeout. - + stateIndex++; - + if (connectInterface4) { connectInterface4 = nil; @@ -3185,7 +3195,7 @@ - (void)endConnectTimeout - (void)doConnectTimeout { LogTrace(); - + [self endConnectTimeout]; [self closeWithError:[self connectTimeoutError]]; } @@ -3198,23 +3208,23 @@ - (void)closeWithError:(NSError *)error { LogTrace(); NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - + [self endConnectTimeout]; - + if (currentRead != nil) [self endCurrentRead]; if (currentWrite != nil) [self endCurrentWrite]; - + [readQueue removeAllObjects]; [writeQueue removeAllObjects]; - + [preBuffer reset]; - + #if TARGET_OS_IPHONE { if (readStream || writeStream) { [self removeStreamsFromRunLoop]; - + if (readStream) { CFReadStreamSetClient(readStream, kCFStreamEventNone, NULL, NULL); @@ -3232,31 +3242,31 @@ - (void)closeWithError:(NSError *)error } } #endif - + [sslPreBuffer reset]; sslErrCode = lastSSLHandshakeError = noErr; - + if (sslContext) { // Getting a linker error here about the SSLx() functions? // You need to add the Security Framework to your application. - + SSLClose(sslContext); - + #if TARGET_OS_IPHONE || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 1080) CFRelease(sslContext); #else SSLDisposeContext(sslContext); #endif - + sslContext = NULL; } - + // For some crazy reason (in my opinion), cancelling a dispatch source doesn't // invoke the cancel handler if the dispatch source is paused. // So we have to unpause the source if needed. // This allows the cancel handler to be run, which in turn releases the source and closes the socket. - + if (!accept4Source && !accept6Source && !acceptUNSource && !readSource && !writeSource) { LogVerbose(@"manually closing close"); @@ -3274,7 +3284,7 @@ - (void)closeWithError:(NSError *)error close(socket6FD); socket6FD = SOCKET_NULL; } - + if (socketUN != SOCKET_NULL) { LogVerbose(@"close(socketUN)"); @@ -3290,96 +3300,96 @@ - (void)closeWithError:(NSError *)error { LogVerbose(@"dispatch_source_cancel(accept4Source)"); dispatch_source_cancel(accept4Source); - + // We never suspend accept4Source - + accept4Source = NULL; } - + if (accept6Source) { LogVerbose(@"dispatch_source_cancel(accept6Source)"); dispatch_source_cancel(accept6Source); - + // We never suspend accept6Source - + accept6Source = NULL; } - + if (acceptUNSource) { LogVerbose(@"dispatch_source_cancel(acceptUNSource)"); dispatch_source_cancel(acceptUNSource); - + // We never suspend acceptUNSource - + acceptUNSource = NULL; } - + if (readSource) { LogVerbose(@"dispatch_source_cancel(readSource)"); dispatch_source_cancel(readSource); - + [self resumeReadSource]; - + readSource = NULL; } - + if (writeSource) { LogVerbose(@"dispatch_source_cancel(writeSource)"); dispatch_source_cancel(writeSource); - + [self resumeWriteSource]; - + writeSource = NULL; } - + // The sockets will be closed by the cancel handlers of the corresponding source - + socket4FD = SOCKET_NULL; socket6FD = SOCKET_NULL; socketUN = SOCKET_NULL; } - + // If the client has passed the connect/accept method, then the connection has at least begun. // Notify delegate that it is now ending. BOOL shouldCallDelegate = (flags & kSocketStarted) ? YES : NO; BOOL isDeallocating = (flags & kDealloc) ? YES : NO; - + // Clear stored socket info and all flags (config remains as is) socketFDBytesAvailable = 0; flags = 0; sslWriteCachedLength = 0; - + if (shouldCallDelegate) { __strong id theDelegate = delegate; __strong id theSelf = isDeallocating ? nil : self; - + if (delegateQueue && [theDelegate respondsToSelector: @selector(socketDidDisconnect:withError:)]) { dispatch_async(delegateQueue, ^{ @autoreleasepool { - + [theDelegate socketDidDisconnect:theSelf withError:error]; }}); - } + } } } - (void)disconnect { dispatch_block_t block = ^{ @autoreleasepool { - + if (self->flags & kSocketStarted) { [self closeWithError:nil]; } }}; - + // Synchronous disconnection, as documented in the header file - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else @@ -3389,7 +3399,7 @@ - (void)disconnect - (void)disconnectAfterReading { dispatch_async(socketQueue, ^{ @autoreleasepool { - + if (self->flags & kSocketStarted) { self->flags |= (kForbidReadsWrites | kDisconnectAfterReads); @@ -3401,7 +3411,7 @@ - (void)disconnectAfterReading - (void)disconnectAfterWriting { dispatch_async(socketQueue, ^{ @autoreleasepool { - + if (self->flags & kSocketStarted) { self->flags |= (kForbidReadsWrites | kDisconnectAfterWrites); @@ -3413,7 +3423,7 @@ - (void)disconnectAfterWriting - (void)disconnectAfterReadingAndWriting { dispatch_async(socketQueue, ^{ @autoreleasepool { - + if (self->flags & kSocketStarted) { self->flags |= (kForbidReadsWrites | kDisconnectAfterReads | kDisconnectAfterWrites); @@ -3430,9 +3440,9 @@ - (void)disconnectAfterReadingAndWriting - (void)maybeClose { NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - + BOOL shouldClose = NO; - + if (flags & kDisconnectAfterReads) { if (([readQueue count] == 0) && (currentRead == nil)) @@ -3457,7 +3467,7 @@ - (void)maybeClose shouldClose = YES; } } - + if (shouldClose) { [self closeWithError:nil]; @@ -3471,14 +3481,14 @@ - (void)maybeClose - (NSError *)badConfigError:(NSString *)errMsg { NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg}; - + return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketBadConfigError userInfo:userInfo]; } - (NSError *)badParamError:(NSString *)errMsg { NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg}; - + return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketBadParamError userInfo:userInfo]; } @@ -3486,7 +3496,7 @@ + (NSError *)gaiError:(int)gai_error { NSString *errMsg = [NSString stringWithCString:gai_strerror(gai_error) encoding:NSASCIIStringEncoding]; NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg}; - + return [NSError errorWithDomain:@"kCFStreamErrorDomainNetDB" code:gai_error userInfo:userInfo]; } @@ -3495,7 +3505,7 @@ - (NSError *)errorWithErrno:(int)err reason:(NSString *)reason NSString *errMsg = [NSString stringWithUTF8String:strerror(err)]; NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg, NSLocalizedFailureReasonErrorKey : reason}; - + return [NSError errorWithDomain:NSPOSIXErrorDomain code:err userInfo:userInfo]; } @@ -3503,7 +3513,7 @@ - (NSError *)errnoError { NSString *errMsg = [NSString stringWithUTF8String:strerror(errno)]; NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg}; - + return [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:userInfo]; } @@ -3511,7 +3521,7 @@ - (NSError *)sslError:(OSStatus)ssl_error { NSString *msg = @"Error code definition can be found in Apple's SecureTransport.h"; NSDictionary *userInfo = @{NSLocalizedRecoverySuggestionErrorKey : msg}; - + return [NSError errorWithDomain:@"kCFStreamErrorDomainSSL" code:ssl_error userInfo:userInfo]; } @@ -3520,9 +3530,9 @@ - (NSError *)connectTimeoutError NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncSocketConnectTimeoutError", @"GCDAsyncSocket", [NSBundle mainBundle], @"Attempt to connect to host timed out", nil); - + NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg}; - + return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketConnectTimeoutError userInfo:userInfo]; } @@ -3534,9 +3544,9 @@ - (NSError *)readMaxedOutError NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncSocketReadMaxedOutError", @"GCDAsyncSocket", [NSBundle mainBundle], @"Read operation reached set maximum length", nil); - + NSDictionary *info = @{NSLocalizedDescriptionKey : errMsg}; - + return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketReadMaxedOutError userInfo:info]; } @@ -3548,9 +3558,9 @@ - (NSError *)readTimeoutError NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncSocketReadTimeoutError", @"GCDAsyncSocket", [NSBundle mainBundle], @"Read operation timed out", nil); - + NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg}; - + return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketReadTimeoutError userInfo:userInfo]; } @@ -3562,9 +3572,9 @@ - (NSError *)writeTimeoutError NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncSocketWriteTimeoutError", @"GCDAsyncSocket", [NSBundle mainBundle], @"Write operation timed out", nil); - + NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg}; - + return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketWriteTimeoutError userInfo:userInfo]; } @@ -3573,16 +3583,16 @@ - (NSError *)connectionClosedError NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncSocketClosedError", @"GCDAsyncSocket", [NSBundle mainBundle], @"Socket closed by remote peer", nil); - + NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg}; - + return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketClosedError userInfo:userInfo]; } - (NSError *)otherError:(NSString *)errMsg { NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg}; - + return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketOtherError userInfo:userInfo]; } @@ -3593,32 +3603,32 @@ - (NSError *)otherError:(NSString *)errMsg - (BOOL)isDisconnected { __block BOOL result = NO; - + dispatch_block_t block = ^{ result = (self->flags & kSocketStarted) ? NO : YES; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + return result; } - (BOOL)isConnected { __block BOOL result = NO; - + dispatch_block_t block = ^{ result = (self->flags & kConnected) ? YES : NO; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + return result; } @@ -3630,21 +3640,21 @@ - (NSString *)connectedHost return [self connectedHostFromSocket4:socket4FD]; if (socket6FD != SOCKET_NULL) return [self connectedHostFromSocket6:socket6FD]; - + return nil; } else { __block NSString *result = nil; - + dispatch_sync(socketQueue, ^{ @autoreleasepool { - + if (self->socket4FD != SOCKET_NULL) result = [self connectedHostFromSocket4:self->socket4FD]; else if (self->socket6FD != SOCKET_NULL) result = [self connectedHostFromSocket6:self->socket6FD]; }}); - + return result; } } @@ -3657,22 +3667,22 @@ - (uint16_t)connectedPort return [self connectedPortFromSocket4:socket4FD]; if (socket6FD != SOCKET_NULL) return [self connectedPortFromSocket6:socket6FD]; - + return 0; } else { __block uint16_t result = 0; - + dispatch_sync(socketQueue, ^{ // No need for autorelease pool - + if (self->socket4FD != SOCKET_NULL) result = [self connectedPortFromSocket4:self->socket4FD]; else if (self->socket6FD != SOCKET_NULL) result = [self connectedPortFromSocket6:self->socket6FD]; }); - + return result; } } @@ -3683,19 +3693,19 @@ - (NSURL *)connectedUrl { if (socketUN != SOCKET_NULL) return [self connectedUrlFromSocketUN:socketUN]; - + return nil; } else { __block NSURL *result = nil; - + dispatch_sync(socketQueue, ^{ @autoreleasepool { - + if (self->socketUN != SOCKET_NULL) result = [self connectedUrlFromSocketUN:self->socketUN]; }}); - + return result; } } @@ -3708,21 +3718,21 @@ - (NSString *)localHost return [self localHostFromSocket4:socket4FD]; if (socket6FD != SOCKET_NULL) return [self localHostFromSocket6:socket6FD]; - + return nil; } else { __block NSString *result = nil; - + dispatch_sync(socketQueue, ^{ @autoreleasepool { - + if (self->socket4FD != SOCKET_NULL) result = [self localHostFromSocket4:self->socket4FD]; else if (self->socket6FD != SOCKET_NULL) result = [self localHostFromSocket6:self->socket6FD]; }}); - + return result; } } @@ -3735,22 +3745,22 @@ - (uint16_t)localPort return [self localPortFromSocket4:socket4FD]; if (socket6FD != SOCKET_NULL) return [self localPortFromSocket6:socket6FD]; - + return 0; } else { __block uint16_t result = 0; - + dispatch_sync(socketQueue, ^{ // No need for autorelease pool - + if (self->socket4FD != SOCKET_NULL) result = [self localPortFromSocket4:self->socket4FD]; else if (self->socket6FD != SOCKET_NULL) result = [self localPortFromSocket6:self->socket6FD]; }); - + return result; } } @@ -3759,7 +3769,7 @@ - (NSString *)connectedHost4 { if (socket4FD != SOCKET_NULL) return [self connectedHostFromSocket4:socket4FD]; - + return nil; } @@ -3767,7 +3777,7 @@ - (NSString *)connectedHost6 { if (socket6FD != SOCKET_NULL) return [self connectedHostFromSocket6:socket6FD]; - + return nil; } @@ -3775,7 +3785,7 @@ - (uint16_t)connectedPort4 { if (socket4FD != SOCKET_NULL) return [self connectedPortFromSocket4:socket4FD]; - + return 0; } @@ -3783,7 +3793,7 @@ - (uint16_t)connectedPort6 { if (socket6FD != SOCKET_NULL) return [self connectedPortFromSocket6:socket6FD]; - + return 0; } @@ -3791,7 +3801,7 @@ - (NSString *)localHost4 { if (socket4FD != SOCKET_NULL) return [self localHostFromSocket4:socket4FD]; - + return nil; } @@ -3799,7 +3809,7 @@ - (NSString *)localHost6 { if (socket6FD != SOCKET_NULL) return [self localHostFromSocket6:socket6FD]; - + return nil; } @@ -3807,7 +3817,7 @@ - (uint16_t)localPort4 { if (socket4FD != SOCKET_NULL) return [self localPortFromSocket4:socket4FD]; - + return 0; } @@ -3815,7 +3825,7 @@ - (uint16_t)localPort6 { if (socket6FD != SOCKET_NULL) return [self localPortFromSocket6:socket6FD]; - + return 0; } @@ -3823,7 +3833,7 @@ - (NSString *)connectedHostFromSocket4:(int)socketFD { struct sockaddr_in sockaddr4; socklen_t sockaddr4len = sizeof(sockaddr4); - + if (getpeername(socketFD, (struct sockaddr *)&sockaddr4, &sockaddr4len) < 0) { return nil; @@ -3835,7 +3845,7 @@ - (NSString *)connectedHostFromSocket6:(int)socketFD { struct sockaddr_in6 sockaddr6; socklen_t sockaddr6len = sizeof(sockaddr6); - + if (getpeername(socketFD, (struct sockaddr *)&sockaddr6, &sockaddr6len) < 0) { return nil; @@ -3847,7 +3857,7 @@ - (uint16_t)connectedPortFromSocket4:(int)socketFD { struct sockaddr_in sockaddr4; socklen_t sockaddr4len = sizeof(sockaddr4); - + if (getpeername(socketFD, (struct sockaddr *)&sockaddr4, &sockaddr4len) < 0) { return 0; @@ -3859,7 +3869,7 @@ - (uint16_t)connectedPortFromSocket6:(int)socketFD { struct sockaddr_in6 sockaddr6; socklen_t sockaddr6len = sizeof(sockaddr6); - + if (getpeername(socketFD, (struct sockaddr *)&sockaddr6, &sockaddr6len) < 0) { return 0; @@ -3871,7 +3881,7 @@ - (NSURL *)connectedUrlFromSocketUN:(int)socketFD { struct sockaddr_un sockaddr; socklen_t sockaddrlen = sizeof(sockaddr); - + if (getpeername(socketFD, (struct sockaddr *)&sockaddr, &sockaddrlen) < 0) { return 0; @@ -3883,7 +3893,7 @@ - (NSString *)localHostFromSocket4:(int)socketFD { struct sockaddr_in sockaddr4; socklen_t sockaddr4len = sizeof(sockaddr4); - + if (getsockname(socketFD, (struct sockaddr *)&sockaddr4, &sockaddr4len) < 0) { return nil; @@ -3895,7 +3905,7 @@ - (NSString *)localHostFromSocket6:(int)socketFD { struct sockaddr_in6 sockaddr6; socklen_t sockaddr6len = sizeof(sockaddr6); - + if (getsockname(socketFD, (struct sockaddr *)&sockaddr6, &sockaddr6len) < 0) { return nil; @@ -3907,7 +3917,7 @@ - (uint16_t)localPortFromSocket4:(int)socketFD { struct sockaddr_in sockaddr4; socklen_t sockaddr4len = sizeof(sockaddr4); - + if (getsockname(socketFD, (struct sockaddr *)&sockaddr4, &sockaddr4len) < 0) { return 0; @@ -3919,7 +3929,7 @@ - (uint16_t)localPortFromSocket6:(int)socketFD { struct sockaddr_in6 sockaddr6; socklen_t sockaddr6len = sizeof(sockaddr6); - + if (getsockname(socketFD, (struct sockaddr *)&sockaddr6, &sockaddr6len) < 0) { return 0; @@ -3930,72 +3940,72 @@ - (uint16_t)localPortFromSocket6:(int)socketFD - (NSData *)connectedAddress { __block NSData *result = nil; - + dispatch_block_t block = ^{ if (self->socket4FD != SOCKET_NULL) { struct sockaddr_in sockaddr4; socklen_t sockaddr4len = sizeof(sockaddr4); - + if (getpeername(self->socket4FD, (struct sockaddr *)&sockaddr4, &sockaddr4len) == 0) { result = [[NSData alloc] initWithBytes:&sockaddr4 length:sockaddr4len]; } } - + if (self->socket6FD != SOCKET_NULL) { struct sockaddr_in6 sockaddr6; socklen_t sockaddr6len = sizeof(sockaddr6); - + if (getpeername(self->socket6FD, (struct sockaddr *)&sockaddr6, &sockaddr6len) == 0) { result = [[NSData alloc] initWithBytes:&sockaddr6 length:sockaddr6len]; } } }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + return result; } - (NSData *)localAddress { __block NSData *result = nil; - + dispatch_block_t block = ^{ if (self->socket4FD != SOCKET_NULL) { struct sockaddr_in sockaddr4; socklen_t sockaddr4len = sizeof(sockaddr4); - + if (getsockname(self->socket4FD, (struct sockaddr *)&sockaddr4, &sockaddr4len) == 0) { result = [[NSData alloc] initWithBytes:&sockaddr4 length:sockaddr4len]; } } - + if (self->socket6FD != SOCKET_NULL) { struct sockaddr_in6 sockaddr6; socklen_t sockaddr6len = sizeof(sockaddr6); - + if (getsockname(self->socket6FD, (struct sockaddr *)&sockaddr6, &sockaddr6len) == 0) { result = [[NSData alloc] initWithBytes:&sockaddr6 length:sockaddr6len]; } } }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + return result; } @@ -4008,11 +4018,11 @@ - (BOOL)isIPv4 else { __block BOOL result = NO; - + dispatch_sync(socketQueue, ^{ result = (self->socket4FD != SOCKET_NULL); }); - + return result; } } @@ -4026,11 +4036,11 @@ - (BOOL)isIPv6 else { __block BOOL result = NO; - + dispatch_sync(socketQueue, ^{ result = (self->socket6FD != SOCKET_NULL); }); - + return result; } } @@ -4044,11 +4054,11 @@ - (BOOL)isSecure else { __block BOOL result; - + dispatch_sync(socketQueue, ^{ result = (self->flags & kSocketSecure) ? YES : NO; }); - + return result; } } @@ -4060,10 +4070,10 @@ - (BOOL)isSecure /** * Finds the address of an interface description. * An inteface description may be an interface name (en0, en1, lo0) or corresponding IP (192.168.4.34). - * + * * The interface description may optionally contain a port number at the end, separated by a colon. * If a non-zero port parameter is provided, any port number in the interface description is ignored. - * + * * The returned value is a 'struct sockaddr' wrapped in an NSMutableData object. **/ - (void)getInterfaceAddress4:(NSMutableData **)interfaceAddr4Ptr @@ -4073,9 +4083,9 @@ - (void)getInterfaceAddress4:(NSMutableData **)interfaceAddr4Ptr { NSMutableData *addr4 = nil; NSMutableData *addr6 = nil; - + NSString *interface = nil; - + NSArray *components = [interfaceDescription componentsSeparatedByString:@":"]; if ([components count] > 0) { @@ -4089,66 +4099,66 @@ - (void)getInterfaceAddress4:(NSMutableData **)interfaceAddr4Ptr { NSString *temp = [components objectAtIndex:1]; long portL = strtol([temp UTF8String], NULL, 10); - + if (portL > 0 && portL <= UINT16_MAX) { port = (uint16_t)portL; } } - + if (interface == nil) { // ANY address - + struct sockaddr_in sockaddr4; memset(&sockaddr4, 0, sizeof(sockaddr4)); - + sockaddr4.sin_len = sizeof(sockaddr4); sockaddr4.sin_family = AF_INET; sockaddr4.sin_port = htons(port); sockaddr4.sin_addr.s_addr = htonl(INADDR_ANY); - + struct sockaddr_in6 sockaddr6; memset(&sockaddr6, 0, sizeof(sockaddr6)); - + sockaddr6.sin6_len = sizeof(sockaddr6); sockaddr6.sin6_family = AF_INET6; sockaddr6.sin6_port = htons(port); sockaddr6.sin6_addr = in6addr_any; - + addr4 = [NSMutableData dataWithBytes:&sockaddr4 length:sizeof(sockaddr4)]; addr6 = [NSMutableData dataWithBytes:&sockaddr6 length:sizeof(sockaddr6)]; } else if ([interface isEqualToString:@"localhost"] || [interface isEqualToString:@"loopback"]) { // LOOPBACK address - + struct sockaddr_in sockaddr4; memset(&sockaddr4, 0, sizeof(sockaddr4)); - + sockaddr4.sin_len = sizeof(sockaddr4); sockaddr4.sin_family = AF_INET; sockaddr4.sin_port = htons(port); sockaddr4.sin_addr.s_addr = htonl(INADDR_LOOPBACK); - + struct sockaddr_in6 sockaddr6; memset(&sockaddr6, 0, sizeof(sockaddr6)); - + sockaddr6.sin6_len = sizeof(sockaddr6); sockaddr6.sin6_family = AF_INET6; sockaddr6.sin6_port = htons(port); sockaddr6.sin6_addr = in6addr_loopback; - + addr4 = [NSMutableData dataWithBytes:&sockaddr4 length:sizeof(sockaddr4)]; addr6 = [NSMutableData dataWithBytes:&sockaddr6 length:sizeof(sockaddr6)]; } else { const char *iface = [interface UTF8String]; - + struct ifaddrs *addrs; const struct ifaddrs *cursor; - + if ((getifaddrs(&addrs) == 0)) { cursor = addrs; @@ -4157,30 +4167,30 @@ - (void)getInterfaceAddress4:(NSMutableData **)interfaceAddr4Ptr if ((addr4 == nil) && (cursor->ifa_addr->sa_family == AF_INET)) { // IPv4 - + struct sockaddr_in nativeAddr4; memcpy(&nativeAddr4, cursor->ifa_addr, sizeof(nativeAddr4)); - + if (strcmp(cursor->ifa_name, iface) == 0) { // Name match - + nativeAddr4.sin_port = htons(port); - + addr4 = [NSMutableData dataWithBytes:&nativeAddr4 length:sizeof(nativeAddr4)]; } else { char ip[INET_ADDRSTRLEN]; - + const char *conversion = inet_ntop(AF_INET, &nativeAddr4.sin_addr, ip, sizeof(ip)); - + if ((conversion != NULL) && (strcmp(ip, iface) == 0)) { // IP match - + nativeAddr4.sin_port = htons(port); - + addr4 = [NSMutableData dataWithBytes:&nativeAddr4 length:sizeof(nativeAddr4)]; } } @@ -4188,42 +4198,42 @@ - (void)getInterfaceAddress4:(NSMutableData **)interfaceAddr4Ptr else if ((addr6 == nil) && (cursor->ifa_addr->sa_family == AF_INET6)) { // IPv6 - + struct sockaddr_in6 nativeAddr6; memcpy(&nativeAddr6, cursor->ifa_addr, sizeof(nativeAddr6)); - + if (strcmp(cursor->ifa_name, iface) == 0) { // Name match - + nativeAddr6.sin6_port = htons(port); - + addr6 = [NSMutableData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)]; } else { char ip[INET6_ADDRSTRLEN]; - + const char *conversion = inet_ntop(AF_INET6, &nativeAddr6.sin6_addr, ip, sizeof(ip)); - + if ((conversion != NULL) && (strcmp(ip, iface) == 0)) { // IP match - + nativeAddr6.sin6_port = htons(port); - + addr6 = [NSMutableData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)]; } } } - + cursor = cursor->ifa_next; } - + freeifaddrs(addrs); } } - + if (interfaceAddr4Ptr) *interfaceAddr4Ptr = addr4; if (interfaceAddr6Ptr) *interfaceAddr6Ptr = addr6; } @@ -4234,13 +4244,13 @@ - (NSData *)getInterfaceAddressFromUrl:(NSURL *)url if (path.length == 0) { return nil; } - + struct sockaddr_un nativeAddr; nativeAddr.sun_family = AF_UNIX; strlcpy(nativeAddr.sun_path, path.fileSystemRepresentation, sizeof(nativeAddr.sun_path)); nativeAddr.sun_len = (unsigned char)SUN_LEN(&nativeAddr); NSData *interface = [NSData dataWithBytes:&nativeAddr length:sizeof(struct sockaddr_un)]; - + return interface; } @@ -4248,104 +4258,104 @@ - (void)setupReadAndWriteSourcesForNewlyConnectedSocket:(int)socketFD { readSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, socketFD, 0, socketQueue); writeSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE, socketFD, 0, socketQueue); - + // Setup event handlers - + __weak GCDAsyncSocket *weakSelf = self; - + dispatch_source_set_event_handler(readSource, ^{ @autoreleasepool { #pragma clang diagnostic push #pragma clang diagnostic warning "-Wimplicit-retain-self" - + __strong GCDAsyncSocket *strongSelf = weakSelf; if (strongSelf == nil) return_from_block; - + LogVerbose(@"readEventBlock"); - + strongSelf->socketFDBytesAvailable = dispatch_source_get_data(strongSelf->readSource); LogVerbose(@"socketFDBytesAvailable: %lu", strongSelf->socketFDBytesAvailable); - + if (strongSelf->socketFDBytesAvailable > 0) [strongSelf doReadData]; else [strongSelf doReadEOF]; - + #pragma clang diagnostic pop }}); - + dispatch_source_set_event_handler(writeSource, ^{ @autoreleasepool { #pragma clang diagnostic push #pragma clang diagnostic warning "-Wimplicit-retain-self" - + __strong GCDAsyncSocket *strongSelf = weakSelf; if (strongSelf == nil) return_from_block; - + LogVerbose(@"writeEventBlock"); - + strongSelf->flags |= kSocketCanAcceptBytes; [strongSelf doWriteData]; - + #pragma clang diagnostic pop }}); - + // Setup cancel handlers - + __block int socketFDRefCount = 2; - + #if !OS_OBJECT_USE_OBJC dispatch_source_t theReadSource = readSource; dispatch_source_t theWriteSource = writeSource; #endif - + dispatch_source_set_cancel_handler(readSource, ^{ #pragma clang diagnostic push #pragma clang diagnostic warning "-Wimplicit-retain-self" - + LogVerbose(@"readCancelBlock"); - + #if !OS_OBJECT_USE_OBJC LogVerbose(@"dispatch_release(readSource)"); dispatch_release(theReadSource); #endif - + if (--socketFDRefCount == 0) { LogVerbose(@"close(socketFD)"); close(socketFD); } - + #pragma clang diagnostic pop }); - + dispatch_source_set_cancel_handler(writeSource, ^{ #pragma clang diagnostic push #pragma clang diagnostic warning "-Wimplicit-retain-self" - + LogVerbose(@"writeCancelBlock"); - + #if !OS_OBJECT_USE_OBJC LogVerbose(@"dispatch_release(writeSource)"); dispatch_release(theWriteSource); #endif - + if (--socketFDRefCount == 0) { LogVerbose(@"close(socketFD)"); close(socketFD); } - + #pragma clang diagnostic pop }); - + // We will not be able to read until data arrives. // But we should be able to write immediately. - + socketFDBytesAvailable = 0; flags &= ~kReadSourceSuspended; - + LogVerbose(@"dispatch_resume(readSource)"); dispatch_resume(readSource); - + flags |= kSocketCanAcceptBytes; flags |= kWriteSourceSuspended; } @@ -4353,34 +4363,34 @@ - (void)setupReadAndWriteSourcesForNewlyConnectedSocket:(int)socketFD - (BOOL)usingCFStreamForTLS { #if TARGET_OS_IPHONE - + if ((flags & kSocketSecure) && (flags & kUsingCFStreamForTLS)) { // The startTLS method was given the GCDAsyncSocketUseCFStreamForTLS flag. - + return YES; } - + #endif - + return NO; } - (BOOL)usingSecureTransportForTLS { // Invoking this method is equivalent to ![self usingCFStreamForTLS] (just more readable) - + #if TARGET_OS_IPHONE - + if ((flags & kSocketSecure) && (flags & kUsingCFStreamForTLS)) { // The startTLS method was given the GCDAsyncSocketUseCFStreamForTLS flag. - + return NO; } - + #endif - + return YES; } @@ -4389,7 +4399,7 @@ - (void)suspendReadSource if (!(flags & kReadSourceSuspended)) { LogVerbose(@"dispatch_suspend(readSource)"); - + dispatch_suspend(readSource); flags |= kReadSourceSuspended; } @@ -4400,7 +4410,7 @@ - (void)resumeReadSource if (flags & kReadSourceSuspended) { LogVerbose(@"dispatch_resume(readSource)"); - + dispatch_resume(readSource); flags &= ~kReadSourceSuspended; } @@ -4411,7 +4421,7 @@ - (void)suspendWriteSource if (!(flags & kWriteSourceSuspended)) { LogVerbose(@"dispatch_suspend(writeSource)"); - + dispatch_suspend(writeSource); flags |= kWriteSourceSuspended; } @@ -4422,7 +4432,7 @@ - (void)resumeWriteSource if (flags & kWriteSourceSuspended) { LogVerbose(@"dispatch_resume(writeSource)"); - + dispatch_resume(writeSource); flags &= ~kWriteSourceSuspended; } @@ -4455,7 +4465,7 @@ - (void)readDataWithTimeout:(NSTimeInterval)timeout LogWarn(@"Cannot read: offset > [buffer length]"); return; } - + GCDAsyncReadPacket *packet = [[GCDAsyncReadPacket alloc] initWithData:buffer startOffset:offset maxLength:length @@ -4463,18 +4473,18 @@ - (void)readDataWithTimeout:(NSTimeInterval)timeout readLength:0 terminator:nil tag:tag]; - + dispatch_async(socketQueue, ^{ @autoreleasepool { - + LogTrace(); - + if ((self->flags & kSocketStarted) && !(self->flags & kForbidReadsWrites)) { [self->readQueue addObject:packet]; [self maybeDequeueRead]; } }}); - + // Do not rely on the block being run in order to release the packet, // as the queue might get released without the block completing. } @@ -4498,7 +4508,7 @@ - (void)readDataToLength:(NSUInteger)length LogWarn(@"Cannot read: offset > [buffer length]"); return; } - + GCDAsyncReadPacket *packet = [[GCDAsyncReadPacket alloc] initWithData:buffer startOffset:offset maxLength:0 @@ -4506,18 +4516,18 @@ - (void)readDataToLength:(NSUInteger)length readLength:length terminator:nil tag:tag]; - + dispatch_async(socketQueue, ^{ @autoreleasepool { - + LogTrace(); - + if ((self->flags & kSocketStarted) && !(self->flags & kForbidReadsWrites)) { [self->readQueue addObject:packet]; [self maybeDequeueRead]; } }}); - + // Do not rely on the block being run in order to release the packet, // as the queue might get released without the block completing. } @@ -4560,7 +4570,7 @@ - (void)readDataToData:(NSData *)data LogWarn(@"Cannot read: maxLength > 0 && maxLength < [data length]"); return; } - + GCDAsyncReadPacket *packet = [[GCDAsyncReadPacket alloc] initWithData:buffer startOffset:offset maxLength:maxLength @@ -4568,18 +4578,18 @@ - (void)readDataToData:(NSData *)data readLength:0 terminator:data tag:tag]; - + dispatch_async(socketQueue, ^{ @autoreleasepool { - + LogTrace(); - + if ((self->flags & kSocketStarted) && !(self->flags & kForbidReadsWrites)) { [self->readQueue addObject:packet]; [self maybeDequeueRead]; } }}); - + // Do not rely on the block being run in order to release the packet, // as the queue might get released without the block completing. } @@ -4587,17 +4597,17 @@ - (void)readDataToData:(NSData *)data - (float)progressOfReadReturningTag:(long *)tagPtr bytesDone:(NSUInteger *)donePtr total:(NSUInteger *)totalPtr { __block float result = 0.0F; - + dispatch_block_t block = ^{ - + if (!self->currentRead || ![self->currentRead isKindOfClass:[GCDAsyncReadPacket class]]) { // We're not reading anything right now. - + if (tagPtr != NULL) *tagPtr = 0; if (donePtr != NULL) *donePtr = 0; if (totalPtr != NULL) *totalPtr = 0; - + result = NAN; } else @@ -4605,44 +4615,44 @@ - (float)progressOfReadReturningTag:(long *)tagPtr bytesDone:(NSUInteger *)doneP // It's only possible to know the progress of our read if we're reading to a certain length. // If we're reading to data, we of course have no idea when the data will arrive. // If we're reading to timeout, then we have no idea when the next chunk of data will arrive. - + NSUInteger done = self->currentRead->bytesDone; NSUInteger total = self->currentRead->readLength; - + if (tagPtr != NULL) *tagPtr = self->currentRead->tag; if (donePtr != NULL) *donePtr = done; if (totalPtr != NULL) *totalPtr = total; - + if (total > 0) result = (float)done / (float)total; else result = 1.0F; } }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + return result; } /** * This method starts a new read, if needed. - * + * * It is called when: * - a user requests a read * - after a read request has finished (to handle the next request) * - immediately after the socket opens to handle any pending requests - * + * * This method also handles auto-disconnect post read/write completion. **/ - (void)maybeDequeueRead { LogTrace(); NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - + // If we're not currently processing a read AND we have an available read stream if ((currentRead == nil) && (flags & kConnected)) { @@ -4651,25 +4661,25 @@ - (void)maybeDequeueRead // Dequeue the next object in the write queue currentRead = [readQueue objectAtIndex:0]; [readQueue removeObjectAtIndex:0]; - - + + if ([currentRead isKindOfClass:[GCDAsyncSpecialPacket class]]) { LogVerbose(@"Dequeued GCDAsyncSpecialPacket"); - + // Attempt to start TLS flags |= kStartingReadTLS; - + // This method won't do anything unless both kStartingReadTLS and kStartingWriteTLS are set [self maybeStartTLS]; } else { LogVerbose(@"Dequeued GCDAsyncReadPacket"); - + // Setup read timer (if needed) [self setupReadTimerWithTimeout:currentRead->timeout]; - + // Immediately read, if possible [self doReadData]; } @@ -4691,17 +4701,17 @@ - (void)maybeDequeueRead else if (flags & kSocketSecure) { [self flushSSLBuffers]; - + // Edge case: - // + // // We just drained all data from the ssl buffers, // and all known data from the socket (socketFDBytesAvailable). - // + // // If we didn't get any data from this process, // then we may have reached the end of the TCP stream. - // + // // Be sure callbacks are enabled so we're notified about a disconnection. - + if ([preBuffer availableBytes] == 0) { if ([self usingCFStreamForTLS]) { @@ -4718,99 +4728,99 @@ - (void)maybeDequeueRead - (void)flushSSLBuffers { LogTrace(); - + NSAssert((flags & kSocketSecure), @"Cannot flush ssl buffers on non-secure socket"); - + if ([preBuffer availableBytes] > 0) { // Only flush the ssl buffers if the prebuffer is empty. // This is to avoid growing the prebuffer inifinitely large. - + return; } - + #if TARGET_OS_IPHONE - + if ([self usingCFStreamForTLS]) { if ((flags & kSecureSocketHasBytesAvailable) && CFReadStreamHasBytesAvailable(readStream)) { LogVerbose(@"%@ - Flushing ssl buffers into prebuffer...", THIS_METHOD); - + CFIndex defaultBytesToRead = (1024 * 4); - + [preBuffer ensureCapacityForWrite:defaultBytesToRead]; - + uint8_t *buffer = [preBuffer writeBuffer]; - + CFIndex result = CFReadStreamRead(readStream, buffer, defaultBytesToRead); LogVerbose(@"%@ - CFReadStreamRead(): result = %i", THIS_METHOD, (int)result); - + if (result > 0) { [preBuffer didWrite:result]; } - + flags &= ~kSecureSocketHasBytesAvailable; } - + return; } - + #endif - + __block NSUInteger estimatedBytesAvailable = 0; - + dispatch_block_t updateEstimatedBytesAvailable = ^{ - + // Figure out if there is any data available to be read - // + // // socketFDBytesAvailable <- Number of encrypted bytes we haven't read from the bsd socket // [sslPreBuffer availableBytes] <- Number of encrypted bytes we've buffered from bsd socket // sslInternalBufSize <- Number of decrypted bytes SecureTransport has buffered - // + // // We call the variable "estimated" because we don't know how many decrypted bytes we'll get // from the encrypted bytes in the sslPreBuffer. // However, we do know this is an upper bound on the estimation. - + estimatedBytesAvailable = self->socketFDBytesAvailable + [self->sslPreBuffer availableBytes]; - + size_t sslInternalBufSize = 0; SSLGetBufferedReadSize(self->sslContext, &sslInternalBufSize); - + estimatedBytesAvailable += sslInternalBufSize; }; - + updateEstimatedBytesAvailable(); - + if (estimatedBytesAvailable > 0) { LogVerbose(@"%@ - Flushing ssl buffers into prebuffer...", THIS_METHOD); - + BOOL done = NO; do { LogVerbose(@"%@ - estimatedBytesAvailable = %lu", THIS_METHOD, (unsigned long)estimatedBytesAvailable); - + // Make sure there's enough room in the prebuffer - + [preBuffer ensureCapacityForWrite:estimatedBytesAvailable]; - + // Read data into prebuffer - + uint8_t *buffer = [preBuffer writeBuffer]; size_t bytesRead = 0; - + OSStatus result = SSLRead(sslContext, buffer, (size_t)estimatedBytesAvailable, &bytesRead); LogVerbose(@"%@ - read from secure socket = %u", THIS_METHOD, (unsigned)bytesRead); - + if (bytesRead > 0) { [preBuffer didWrite:bytesRead]; } - + LogVerbose(@"%@ - prebuffer.length = %zu", THIS_METHOD, [preBuffer availableBytes]); - + if (result != noErr) { done = YES; @@ -4819,7 +4829,7 @@ - (void)flushSSLBuffers { updateEstimatedBytesAvailable(); } - + } while (!done && estimatedBytesAvailable > 0); } } @@ -4827,35 +4837,35 @@ - (void)flushSSLBuffers - (void)doReadData { LogTrace(); - + // This method is called on the socketQueue. // It might be called directly, or via the readSource when data is available to be read. - + if ((currentRead == nil) || (flags & kReadsPaused)) { LogVerbose(@"No currentRead or kReadsPaused"); - + // Unable to read at this time - + if (flags & kSocketSecure) { // Here's the situation: - // + // // We have an established secure connection. // There may not be a currentRead, but there might be encrypted data sitting around for us. // When the user does get around to issuing a read, that encrypted data will need to be decrypted. - // + // // So why make the user wait? // We might as well get a head start on decrypting some data now. - // + // // The other reason we do this has to do with detecting a socket disconnection. // The SSL/TLS protocol has it's own disconnection handshake. // So when a secure socket is closed, a "goodbye" packet comes across the wire. // We want to make sure we read the "goodbye" packet so we can properly detect the TCP disconnection. - + [self flushSSLBuffers]; } - + if ([self usingCFStreamForTLS]) { // CFReadStream only fires once when there is available data. @@ -4865,10 +4875,10 @@ - (void)doReadData { // If the readSource is firing, we need to pause it // or else it will continue to fire over and over again. - // + // // If the readSource is not firing, // we want it to continue monitoring the socket. - + if (socketFDBytesAvailable > 0) { [self suspendReadSource]; @@ -4876,96 +4886,96 @@ - (void)doReadData } return; } - + BOOL hasBytesAvailable = NO; unsigned long estimatedBytesAvailable = 0; - + if ([self usingCFStreamForTLS]) { #if TARGET_OS_IPHONE - + // Requested CFStream, rather than SecureTransport, for TLS (via GCDAsyncSocketUseCFStreamForTLS) - + estimatedBytesAvailable = 0; if ((flags & kSecureSocketHasBytesAvailable) && CFReadStreamHasBytesAvailable(readStream)) hasBytesAvailable = YES; else hasBytesAvailable = NO; - + #endif } else { estimatedBytesAvailable = socketFDBytesAvailable; - + if (flags & kSocketSecure) { // There are 2 buffers to be aware of here. - // + // // We are using SecureTransport, a TLS/SSL security layer which sits atop TCP. // We issue a read to the SecureTranport API, which in turn issues a read to our SSLReadFunction. // Our SSLReadFunction then reads from the BSD socket and returns the encrypted data to SecureTransport. // SecureTransport then decrypts the data, and finally returns the decrypted data back to us. - // + // // The first buffer is one we create. // SecureTransport often requests small amounts of data. // This has to do with the encypted packets that are coming across the TCP stream. // But it's non-optimal to do a bunch of small reads from the BSD socket. // So our SSLReadFunction reads all available data from the socket (optimizing the sys call) // and may store excess in the sslPreBuffer. - + estimatedBytesAvailable += [sslPreBuffer availableBytes]; - + // The second buffer is within SecureTransport. // As mentioned earlier, there are encrypted packets coming across the TCP stream. // SecureTransport needs the entire packet to decrypt it. // But if the entire packet produces X bytes of decrypted data, // and we only asked SecureTransport for X/2 bytes of data, // it must store the extra X/2 bytes of decrypted data for the next read. - // + // // The SSLGetBufferedReadSize function will tell us the size of this internal buffer. // From the documentation: - // + // // "This function does not block or cause any low-level read operations to occur." - + size_t sslInternalBufSize = 0; SSLGetBufferedReadSize(sslContext, &sslInternalBufSize); - + estimatedBytesAvailable += sslInternalBufSize; } - + hasBytesAvailable = (estimatedBytesAvailable > 0); } - + if ((hasBytesAvailable == NO) && ([preBuffer availableBytes] == 0)) { LogVerbose(@"No data available to read..."); - + // No data available to read. - + if (![self usingCFStreamForTLS]) { // Need to wait for readSource to fire and notify us of // available data in the socket's internal read buffer. - + [self resumeReadSource]; } return; } - + if (flags & kStartingReadTLS) { LogVerbose(@"Waiting for SSL/TLS handshake to complete"); - + // The readQueue is waiting for SSL/TLS handshake to complete. - + if (flags & kStartingWriteTLS) { if ([self usingSecureTransportForTLS] && lastSSLHandshakeError == errSSLWouldBlock) { // We are in the process of a SSL Handshake. // We were waiting for incoming data which has just arrived. - + [self ssl_continueSSLHandshake]; } } @@ -4973,90 +4983,90 @@ - (void)doReadData { // We are still waiting for the writeQueue to drain and start the SSL/TLS process. // We now know data is available to read. - + if (![self usingCFStreamForTLS]) { // Suspend the read source or else it will continue to fire nonstop. - + [self suspendReadSource]; } } - + return; } - + BOOL done = NO; // Completed read operation NSError *error = nil; // Error occurred - + NSUInteger totalBytesReadForCurrentRead = 0; - - // + + // // STEP 1 - READ FROM PREBUFFER - // - + // + if ([preBuffer availableBytes] > 0) { // There are 3 types of read packets: - // + // // 1) Read all available data. // 2) Read a specific length of data. // 3) Read up to a particular terminator. - + NSUInteger bytesToCopy; - + if (currentRead->term != nil) { // Read type #3 - read up to a terminator - + bytesToCopy = [currentRead readLengthForTermWithPreBuffer:preBuffer found:&done]; } else { // Read type #1 or #2 - + bytesToCopy = [currentRead readLengthForNonTermWithHint:[preBuffer availableBytes]]; } - + // Make sure we have enough room in the buffer for our read. - + [currentRead ensureCapacityForAdditionalDataOfLength:bytesToCopy]; - + // Copy bytes from prebuffer into packet buffer - + uint8_t *buffer = (uint8_t *)[currentRead->buffer mutableBytes] + currentRead->startOffset + currentRead->bytesDone; - + memcpy(buffer, [preBuffer readBuffer], bytesToCopy); - + // Remove the copied bytes from the preBuffer [preBuffer didRead:bytesToCopy]; - + LogVerbose(@"copied(%lu) preBufferLength(%zu)", (unsigned long)bytesToCopy, [preBuffer availableBytes]); - + // Update totals - + currentRead->bytesDone += bytesToCopy; totalBytesReadForCurrentRead += bytesToCopy; - + // Check to see if the read operation is done - + if (currentRead->readLength > 0) { // Read type #2 - read a specific length of data - + done = (currentRead->bytesDone == currentRead->readLength); } else if (currentRead->term != nil) { // Read type #3 - read up to a terminator - + // Our 'done' variable was updated via the readLengthForTermWithPreBuffer:found: method - + if (!done && currentRead->maxLength > 0) { // We're not done and there's a set maxLength. // Have we reached that maxLength yet? - + if (currentRead->bytesDone >= currentRead->maxLength) { error = [self readMaxedOutError]; @@ -5066,69 +5076,69 @@ - (void)doReadData else { // Read type #1 - read all available data - // + // // We're done as soon as // - we've read all available data (in prebuffer and socket) // - we've read the maxLength of read packet. - + done = ((currentRead->maxLength > 0) && (currentRead->bytesDone == currentRead->maxLength)); } - + } - - // + + // // STEP 2 - READ FROM SOCKET - // - + // + BOOL socketEOF = (flags & kSocketHasReadEOF) ? YES : NO; // Nothing more to read via socket (end of file) BOOL waiting = !done && !error && !socketEOF && !hasBytesAvailable; // Ran out of data, waiting for more - + if (!done && !error && !socketEOF && hasBytesAvailable) { NSAssert(([preBuffer availableBytes] == 0), @"Invalid logic"); - + BOOL readIntoPreBuffer = NO; uint8_t *buffer = NULL; size_t bytesRead = 0; - + if (flags & kSocketSecure) { if ([self usingCFStreamForTLS]) { #if TARGET_OS_IPHONE - + // Using CFStream, rather than SecureTransport, for TLS - + NSUInteger defaultReadLength = (1024 * 32); - + NSUInteger bytesToRead = [currentRead optimalReadLengthWithDefault:defaultReadLength shouldPreBuffer:&readIntoPreBuffer]; - + // Make sure we have enough room in the buffer for our read. // // We are either reading directly into the currentRead->buffer, // or we're reading into the temporary preBuffer. - + if (readIntoPreBuffer) { [preBuffer ensureCapacityForWrite:bytesToRead]; - + buffer = [preBuffer writeBuffer]; } else { [currentRead ensureCapacityForAdditionalDataOfLength:bytesToRead]; - + buffer = (uint8_t *)[currentRead->buffer mutableBytes] + currentRead->startOffset + currentRead->bytesDone; } - + // Read data into buffer - + CFIndex result = CFReadStreamRead(readStream, buffer, (CFIndex)bytesToRead); LogVerbose(@"CFReadStreamRead(): result = %i", (int)result); - + if (result < 0) { error = (__bridge_transfer NSError *)CFReadStreamCopyError(readStream); @@ -5142,12 +5152,12 @@ - (void)doReadData waiting = YES; bytesRead = (size_t)result; } - + // We only know how many decrypted bytes were read. // The actual number of bytes read was likely more due to the overhead of the encryption. // So we reset our flag, and rely on the next callback to alert us of more data. flags &= ~kSecureSocketHasBytesAvailable; - + #endif } else @@ -5163,63 +5173,63 @@ - (void)doReadData // - how many encypted bytes are sitting in the sslContext // // So we play the regular game of using an upper bound instead. - + NSUInteger defaultReadLength = (1024 * 32); - + if (defaultReadLength < estimatedBytesAvailable) { defaultReadLength = estimatedBytesAvailable + (1024 * 16); } - + NSUInteger bytesToRead = [currentRead optimalReadLengthWithDefault:defaultReadLength shouldPreBuffer:&readIntoPreBuffer]; - + if (bytesToRead > SIZE_MAX) { // NSUInteger may be bigger than size_t bytesToRead = SIZE_MAX; } - + // Make sure we have enough room in the buffer for our read. // // We are either reading directly into the currentRead->buffer, // or we're reading into the temporary preBuffer. - + if (readIntoPreBuffer) { [preBuffer ensureCapacityForWrite:bytesToRead]; - + buffer = [preBuffer writeBuffer]; } else { [currentRead ensureCapacityForAdditionalDataOfLength:bytesToRead]; - + buffer = (uint8_t *)[currentRead->buffer mutableBytes] + currentRead->startOffset + currentRead->bytesDone; } - + // The documentation from Apple states: - // + // // "a read operation might return errSSLWouldBlock, // indicating that less data than requested was actually transferred" - // + // // However, starting around 10.7, the function will sometimes return noErr, // even if it didn't read as much data as requested. So we need to watch out for that. - + OSStatus result; do { void *loop_buffer = buffer + bytesRead; size_t loop_bytesToRead = (size_t)bytesToRead - bytesRead; size_t loop_bytesRead = 0; - + result = SSLRead(sslContext, loop_buffer, loop_bytesToRead, &loop_bytesRead); LogVerbose(@"read from secure socket = %u", (unsigned)loop_bytesRead); - + bytesRead += loop_bytesRead; - + } while ((result == noErr) && (bytesRead < bytesToRead)); - - + + if (result != noErr) { if (result == errSSLWouldBlock) @@ -5241,13 +5251,13 @@ - (void)doReadData // It's possible that bytesRead > 0, even if the result was errSSLWouldBlock. // This happens when the SSLRead function is able to read some data, // but not the entire amount we requested. - + if (bytesRead <= 0) { bytesRead = 0; } } - + // Do not modify socketFDBytesAvailable. // It will be updated via the SSLReadFunction(). } @@ -5255,67 +5265,67 @@ - (void)doReadData else { // Normal socket operation - + NSUInteger bytesToRead; - + // There are 3 types of read packets: // // 1) Read all available data. // 2) Read a specific length of data. // 3) Read up to a particular terminator. - + if (currentRead->term != nil) { // Read type #3 - read up to a terminator - + bytesToRead = [currentRead readLengthForTermWithHint:estimatedBytesAvailable shouldPreBuffer:&readIntoPreBuffer]; } else { // Read type #1 or #2 - + bytesToRead = [currentRead readLengthForNonTermWithHint:estimatedBytesAvailable]; } - + if (bytesToRead > SIZE_MAX) { // NSUInteger may be bigger than size_t (read param 3) bytesToRead = SIZE_MAX; } - + // Make sure we have enough room in the buffer for our read. // // We are either reading directly into the currentRead->buffer, // or we're reading into the temporary preBuffer. - + if (readIntoPreBuffer) { [preBuffer ensureCapacityForWrite:bytesToRead]; - + buffer = [preBuffer writeBuffer]; } else { [currentRead ensureCapacityForAdditionalDataOfLength:bytesToRead]; - + buffer = (uint8_t *)[currentRead->buffer mutableBytes] + currentRead->startOffset + currentRead->bytesDone; } - + // Read data into buffer - + int socketFD = (socket4FD != SOCKET_NULL) ? socket4FD : (socket6FD != SOCKET_NULL) ? socket6FD : socketUN; - + ssize_t result = read(socketFD, buffer, (size_t)bytesToRead); LogVerbose(@"read from socket = %i", (int)result); - + if (result < 0) { if (errno == EWOULDBLOCK) waiting = YES; else error = [self errorWithErrno:errno reason:@"Error in read() function"]; - + socketFDBytesAvailable = 0; } else if (result == 0) @@ -5326,7 +5336,7 @@ - (void)doReadData else { bytesRead = result; - + if (bytesRead < bytesToRead) { // The read returned less data than requested. @@ -5341,81 +5351,81 @@ - (void)doReadData else socketFDBytesAvailable -= bytesRead; } - + if (socketFDBytesAvailable == 0) { waiting = YES; } } } - + if (bytesRead > 0) { // Check to see if the read operation is done - + if (currentRead->readLength > 0) { // Read type #2 - read a specific length of data - // + // // Note: We should never be using a prebuffer when we're reading a specific length of data. - + NSAssert(readIntoPreBuffer == NO, @"Invalid logic"); - + currentRead->bytesDone += bytesRead; totalBytesReadForCurrentRead += bytesRead; - + done = (currentRead->bytesDone == currentRead->readLength); } else if (currentRead->term != nil) { // Read type #3 - read up to a terminator - + if (readIntoPreBuffer) { // We just read a big chunk of data into the preBuffer - + [preBuffer didWrite:bytesRead]; LogVerbose(@"read data into preBuffer - preBuffer.length = %zu", [preBuffer availableBytes]); - + // Search for the terminating sequence - + NSUInteger bytesToCopy = [currentRead readLengthForTermWithPreBuffer:preBuffer found:&done]; LogVerbose(@"copying %lu bytes from preBuffer", (unsigned long)bytesToCopy); - + // Ensure there's room on the read packet's buffer - + [currentRead ensureCapacityForAdditionalDataOfLength:bytesToCopy]; - + // Copy bytes from prebuffer into read buffer - + uint8_t *readBuf = (uint8_t *)[currentRead->buffer mutableBytes] + currentRead->startOffset + currentRead->bytesDone; - + memcpy(readBuf, [preBuffer readBuffer], bytesToCopy); - + // Remove the copied bytes from the prebuffer [preBuffer didRead:bytesToCopy]; LogVerbose(@"preBuffer.length = %zu", [preBuffer availableBytes]); - + // Update totals currentRead->bytesDone += bytesToCopy; totalBytesReadForCurrentRead += bytesToCopy; - + // Our 'done' variable was updated via the readLengthForTermWithPreBuffer:found: method above } else { // We just read a big chunk of data directly into the packet's buffer. // We need to move any overflow into the prebuffer. - + NSInteger overflow = [currentRead searchForTermAfterPreBuffering:bytesRead]; - + if (overflow == 0) { // Perfect match! // Every byte we read stays in the read buffer, // and the last byte we read was the last byte of the term. - + currentRead->bytesDone += bytesRead; totalBytesReadForCurrentRead += bytesRead; done = YES; @@ -5425,22 +5435,22 @@ - (void)doReadData // The term was found within the data that we read, // and there are extra bytes that extend past the end of the term. // We need to move these excess bytes out of the read packet and into the prebuffer. - + NSInteger underflow = bytesRead - overflow; - + // Copy excess data into preBuffer - + LogVerbose(@"copying %ld overflow bytes into preBuffer", (long)overflow); [preBuffer ensureCapacityForWrite:overflow]; - + uint8_t *overflowBuffer = buffer + underflow; memcpy([preBuffer writeBuffer], overflowBuffer, overflow); - + [preBuffer didWrite:overflow]; LogVerbose(@"preBuffer.length = %zu", [preBuffer availableBytes]); - + // Note: The completeCurrentRead method will trim the buffer for us. - + currentRead->bytesDone += underflow; totalBytesReadForCurrentRead += underflow; done = YES; @@ -5448,18 +5458,18 @@ - (void)doReadData else { // The term was not found within the data that we read. - + currentRead->bytesDone += bytesRead; totalBytesReadForCurrentRead += bytesRead; done = NO; } } - + if (!done && currentRead->maxLength > 0) { // We're not done and there's a set maxLength. // Have we reached that maxLength yet? - + if (currentRead->bytesDone >= currentRead->maxLength) { error = [self readMaxedOutError]; @@ -5469,32 +5479,32 @@ - (void)doReadData else { // Read type #1 - read all available data - + if (readIntoPreBuffer) { // We just read a chunk of data into the preBuffer - + [preBuffer didWrite:bytesRead]; - + // Now copy the data into the read packet. - // + // // Recall that we didn't read directly into the packet's buffer to avoid // over-allocating memory since we had no clue how much data was available to be read. - // + // // Ensure there's room on the read packet's buffer - + [currentRead ensureCapacityForAdditionalDataOfLength:bytesRead]; - + // Copy bytes from prebuffer into read buffer - + uint8_t *readBuf = (uint8_t *)[currentRead->buffer mutableBytes] + currentRead->startOffset + currentRead->bytesDone; - + memcpy(readBuf, [preBuffer readBuffer], bytesRead); - + // Remove the copied bytes from the prebuffer [preBuffer didRead:bytesRead]; - + // Update totals currentRead->bytesDone += bytesRead; totalBytesReadForCurrentRead += bytesRead; @@ -5504,30 +5514,30 @@ - (void)doReadData currentRead->bytesDone += bytesRead; totalBytesReadForCurrentRead += bytesRead; } - + done = YES; } - + } // if (bytesRead > 0) - + } // if (!done && !error && !socketEOF && hasBytesAvailable) - - + + if (!done && currentRead->readLength == 0 && currentRead->term == nil) { // Read type #1 - read all available data - // + // // We might arrive here if we read data from the prebuffer but not from the socket. - + done = (totalBytesReadForCurrentRead > 0); } - + // Check to see if we're done, or if we've made progress - + if (done) { [self completeCurrentRead]; - + if (!error && (!socketEOF || [preBuffer availableBytes] > 0)) { [self maybeDequeueRead]; @@ -5544,20 +5554,20 @@ - (void)doReadData waiting = YES; __strong id theDelegate = delegate; - + if (delegateQueue && [theDelegate respondsToSelector:@selector(socket:didReadPartialDataOfLength:tag:)]) { long theReadTag = currentRead->tag; - + dispatch_async(delegateQueue, ^{ @autoreleasepool { - + [theDelegate socket:self didReadPartialDataOfLength:totalBytesReadForCurrentRead tag:theReadTag]; }}); } } - + // Check for errors - + if (error) { [self closeWithError:error]; @@ -5574,37 +5584,37 @@ - (void)doReadData [self resumeReadSource]; } } - + // Do not add any code here without first adding return statements in the error cases above. } - (void)doReadEOF { LogTrace(); - + // This method may be called more than once. // If the EOF is read while there is still data in the preBuffer, // then this method may be called continually after invocations of doReadData to see if it's time to disconnect. - + flags |= kSocketHasReadEOF; - + if (flags & kSocketSecure) { // If the SSL layer has any buffered data, flush it into the preBuffer now. - + [self flushSSLBuffers]; } - + BOOL shouldDisconnect = NO; NSError *error = nil; - + if ((flags & kStartingReadTLS) || (flags & kStartingWriteTLS)) { // We received an EOF during or prior to startTLS. // The SSL/TLS handshake is now impossible, so this is an unrecoverable situation. - + shouldDisconnect = YES; - + if ([self usingSecureTransportForTLS]) { error = [self sslError:errSSLClosedAbort]; @@ -5616,19 +5626,19 @@ - (void)doReadEOF // The config allows half-duplex connections. // We've previously checked the socket, and it appeared writeable. // So we marked the read stream as closed and notified the delegate. - // + // // As per the half-duplex contract, the socket will be closed when a write fails, // or when the socket is manually closed. - + shouldDisconnect = NO; } else if ([preBuffer availableBytes] > 0) { LogVerbose(@"Socket reached EOF, but there is still data available in prebuffer"); - + // Although we won't be able to read any more data from the socket, // there is existing data that has been prebuffered that we can read. - + shouldDisconnect = NO; } else if (config & kAllowHalfDuplexConnection) @@ -5636,33 +5646,33 @@ - (void)doReadEOF // We just received an EOF (end of file) from the socket's read stream. // This means the remote end of the socket (the peer we're connected to) // has explicitly stated that it will not be sending us any more data. - // + // // Query the socket to see if it is still writeable. (Perhaps the peer will continue reading data from us) - + int socketFD = (socket4FD != SOCKET_NULL) ? socket4FD : (socket6FD != SOCKET_NULL) ? socket6FD : socketUN; - + struct pollfd pfd[1]; pfd[0].fd = socketFD; pfd[0].events = POLLOUT; pfd[0].revents = 0; - + poll(pfd, 1, 0); - + if (pfd[0].revents & POLLOUT) { // Socket appears to still be writeable - + shouldDisconnect = NO; flags |= kReadStreamClosed; - + // Notify the delegate that we're going half-duplex - + __strong id theDelegate = delegate; if (delegateQueue && [theDelegate respondsToSelector:@selector(socketDidCloseReadStream:)]) { dispatch_async(delegateQueue, ^{ @autoreleasepool { - + [theDelegate socketDidCloseReadStream:self]; }}); } @@ -5676,8 +5686,8 @@ - (void)doReadEOF { shouldDisconnect = YES; } - - + + if (shouldDisconnect) { if (error == nil) @@ -5705,7 +5715,7 @@ - (void)doReadEOF if (![self usingCFStreamForTLS]) { // Suspend the read source (if needed) - + [self suspendReadSource]; } } @@ -5714,18 +5724,18 @@ - (void)doReadEOF - (void)completeCurrentRead { LogTrace(); - + NSAssert(currentRead, @"Trying to complete current read when there is no current read."); - - + + NSData *result = nil; - + if (currentRead->bufferOwner) { // We created the buffer on behalf of the user. // Trim our buffer to be the proper size. [currentRead->buffer setLength:currentRead->bytesDone]; - + result = currentRead->buffer; } else @@ -5733,34 +5743,34 @@ - (void)completeCurrentRead // We did NOT create the buffer. // The buffer is owned by the caller. // Only trim the buffer if we had to increase its size. - + if ([currentRead->buffer length] > currentRead->originalBufferLength) { NSUInteger readSize = currentRead->startOffset + currentRead->bytesDone; NSUInteger origSize = currentRead->originalBufferLength; - + NSUInteger buffSize = MAX(readSize, origSize); - + [currentRead->buffer setLength:buffSize]; } - + uint8_t *buffer = (uint8_t *)[currentRead->buffer mutableBytes] + currentRead->startOffset; - + result = [NSData dataWithBytesNoCopy:buffer length:currentRead->bytesDone freeWhenDone:NO]; } - + __strong id theDelegate = delegate; if (delegateQueue && [theDelegate respondsToSelector:@selector(socket:didReadData:withTag:)]) { GCDAsyncReadPacket *theRead = currentRead; // Ensure currentRead retained since result may not own buffer - + dispatch_async(delegateQueue, ^{ @autoreleasepool { - + [theDelegate socket:self didReadData:result withTag:theRead->tag]; }}); } - + [self endCurrentRead]; } @@ -5771,7 +5781,7 @@ - (void)endCurrentRead dispatch_source_cancel(readTimer); readTimer = NULL; } - + currentRead = nil; } @@ -5780,36 +5790,36 @@ - (void)setupReadTimerWithTimeout:(NSTimeInterval)timeout if (timeout >= 0.0) { readTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, socketQueue); - + __weak GCDAsyncSocket *weakSelf = self; - + dispatch_source_set_event_handler(readTimer, ^{ @autoreleasepool { #pragma clang diagnostic push #pragma clang diagnostic warning "-Wimplicit-retain-self" - + __strong GCDAsyncSocket *strongSelf = weakSelf; if (strongSelf == nil) return_from_block; - + [strongSelf doReadTimeout]; - + #pragma clang diagnostic pop }}); - + #if !OS_OBJECT_USE_OBJC dispatch_source_t theReadTimer = readTimer; dispatch_source_set_cancel_handler(readTimer, ^{ #pragma clang diagnostic push #pragma clang diagnostic warning "-Wimplicit-retain-self" - + LogVerbose(@"dispatch_release(readTimer)"); dispatch_release(theReadTimer); - + #pragma clang diagnostic pop }); #endif - + dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeout * NSEC_PER_SEC)); - + dispatch_source_set_timer(readTimer, tt, DISPATCH_TIME_FOREVER, 0); dispatch_resume(readTimer); } @@ -5821,25 +5831,25 @@ - (void)doReadTimeout // Ideally we'd like to synchronously query the delegate about a timeout extension. // But if we do so synchronously we risk a possible deadlock. // So instead we have to do so asynchronously, and callback to ourselves from within the delegate block. - + flags |= kReadsPaused; - + __strong id theDelegate = delegate; if (delegateQueue && [theDelegate respondsToSelector:@selector(socket:shouldTimeoutReadWithTag:elapsed:bytesDone:)]) { GCDAsyncReadPacket *theRead = currentRead; - + dispatch_async(delegateQueue, ^{ @autoreleasepool { - + NSTimeInterval timeoutExtension = 0.0; - + timeoutExtension = [theDelegate socket:self shouldTimeoutReadWithTag:theRead->tag elapsed:theRead->timeout bytesDone:theRead->bytesDone]; - + dispatch_async(self->socketQueue, ^{ @autoreleasepool { - + [self doReadTimeoutWithExtension:timeoutExtension]; }}); }}); @@ -5857,11 +5867,11 @@ - (void)doReadTimeoutWithExtension:(NSTimeInterval)timeoutExtension if (timeoutExtension > 0.0) { currentRead->timeout += timeoutExtension; - + // Reschedule the timer dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeoutExtension * NSEC_PER_SEC)); dispatch_source_set_timer(readTimer, tt, DISPATCH_TIME_FOREVER, 0); - + // Unpause reads, and continue flags &= ~kReadsPaused; [self doReadData]; @@ -5869,7 +5879,7 @@ - (void)doReadTimeoutWithExtension:(NSTimeInterval)timeoutExtension else { LogVerbose(@"ReadTimeout"); - + [self closeWithError:[self readTimeoutError]]; } } @@ -5882,20 +5892,20 @@ - (void)doReadTimeoutWithExtension:(NSTimeInterval)timeoutExtension - (void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag { if ([data length] == 0) return; - + GCDAsyncWritePacket *packet = [[GCDAsyncWritePacket alloc] initWithData:data timeout:timeout tag:tag]; - + dispatch_async(socketQueue, ^{ @autoreleasepool { - + LogTrace(); - + if ((self->flags & kSocketStarted) && !(self->flags & kForbidReadsWrites)) { [self->writeQueue addObject:packet]; [self maybeDequeueWrite]; } }}); - + // Do not rely on the block being run in order to release the packet, // as the queue might get released without the block completing. } @@ -5903,56 +5913,56 @@ - (void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)t - (float)progressOfWriteReturningTag:(long *)tagPtr bytesDone:(NSUInteger *)donePtr total:(NSUInteger *)totalPtr { __block float result = 0.0F; - + dispatch_block_t block = ^{ - + if (!self->currentWrite || ![self->currentWrite isKindOfClass:[GCDAsyncWritePacket class]]) { // We're not writing anything right now. - + if (tagPtr != NULL) *tagPtr = 0; if (donePtr != NULL) *donePtr = 0; if (totalPtr != NULL) *totalPtr = 0; - + result = NAN; } else { NSUInteger done = self->currentWrite->bytesDone; NSUInteger total = [self->currentWrite->buffer length]; - + if (tagPtr != NULL) *tagPtr = self->currentWrite->tag; if (donePtr != NULL) *donePtr = done; if (totalPtr != NULL) *totalPtr = total; - + result = (float)done / (float)total; } }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + return result; } /** * Conditionally starts a new write. - * + * * It is called when: * - a user requests a write * - after a write request has finished (to handle the next request) * - immediately after the socket opens to handle any pending requests - * + * * This method also handles auto-disconnect post read/write completion. **/ - (void)maybeDequeueWrite { LogTrace(); NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - - + + // If we're not currently processing a write AND we have an available write stream if ((currentWrite == nil) && (flags & kConnected)) { @@ -5961,25 +5971,25 @@ - (void)maybeDequeueWrite // Dequeue the next object in the write queue currentWrite = [writeQueue objectAtIndex:0]; [writeQueue removeObjectAtIndex:0]; - - + + if ([currentWrite isKindOfClass:[GCDAsyncSpecialPacket class]]) { LogVerbose(@"Dequeued GCDAsyncSpecialPacket"); - + // Attempt to start TLS flags |= kStartingWriteTLS; - + // This method won't do anything unless both kStartingReadTLS and kStartingWriteTLS are set [self maybeStartTLS]; } else { LogVerbose(@"Dequeued GCDAsyncWritePacket"); - + // Setup write timer (if needed) [self setupWriteTimerWithTimeout:currentWrite->timeout]; - + // Immediately write, if possible [self doWriteData]; } @@ -6004,15 +6014,15 @@ - (void)maybeDequeueWrite - (void)doWriteData { LogTrace(); - + // This method is called by the writeSource via the socketQueue - + if ((currentWrite == nil) || (flags & kWritesPaused)) { LogVerbose(@"No currentWrite or kWritesPaused"); - + // Unable to write at this time - + if ([self usingCFStreamForTLS]) { // CFWriteStream only fires once when there is available data. @@ -6022,7 +6032,7 @@ - (void)doWriteData { // If the writeSource is firing, we need to pause it // or else it will continue to fire over and over again. - + if (flags & kSocketCanAcceptBytes) { [self suspendWriteSource]; @@ -6030,36 +6040,36 @@ - (void)doWriteData } return; } - + if (!(flags & kSocketCanAcceptBytes)) { LogVerbose(@"No space available to write..."); - + // No space available to write. - + if (![self usingCFStreamForTLS]) { // Need to wait for writeSource to fire and notify us of // available space in the socket's internal write buffer. - + [self resumeWriteSource]; } return; } - + if (flags & kStartingWriteTLS) { LogVerbose(@"Waiting for SSL/TLS handshake to complete"); - + // The writeQueue is waiting for SSL/TLS handshake to complete. - + if (flags & kStartingReadTLS) { if ([self usingSecureTransportForTLS] && lastSSLHandshakeError == errSSLWouldBlock) { // We are in the process of a SSL Handshake. // We were waiting for available space in the socket's internal OS buffer to continue writing. - + [self ssl_continueSSLHandshake]; } } @@ -6067,46 +6077,46 @@ - (void)doWriteData { // We are still waiting for the readQueue to drain and start the SSL/TLS process. // We now know we can write to the socket. - + if (![self usingCFStreamForTLS]) { // Suspend the write source or else it will continue to fire nonstop. - + [self suspendWriteSource]; } } - + return; } - + // Note: This method is not called if currentWrite is a GCDAsyncSpecialPacket (startTLS packet) - + BOOL waiting = NO; NSError *error = nil; size_t bytesWritten = 0; - + if (flags & kSocketSecure) { if ([self usingCFStreamForTLS]) { #if TARGET_OS_IPHONE - - // + + // // Writing data using CFStream (over internal TLS) - // - + // + const uint8_t *buffer = (const uint8_t *)[currentWrite->buffer bytes] + currentWrite->bytesDone; - + NSUInteger bytesToWrite = [currentWrite->buffer length] - currentWrite->bytesDone; - + if (bytesToWrite > SIZE_MAX) // NSUInteger may be bigger than size_t (write param 3) { bytesToWrite = SIZE_MAX; } - + CFIndex result = CFWriteStreamWrite(writeStream, buffer, (CFIndex)bytesToWrite); LogVerbose(@"CFWriteStreamWrite(%lu) = %li", (unsigned long)bytesToWrite, result); - + if (result < 0) { error = (__bridge_transfer NSError *)CFWriteStreamCopyError(writeStream); @@ -6114,75 +6124,75 @@ - (void)doWriteData else { bytesWritten = (size_t)result; - + // We always set waiting to true in this scenario. // CFStream may have altered our underlying socket to non-blocking. // Thus if we attempt to write without a callback, we may end up blocking our queue. waiting = YES; } - + #endif } else { // We're going to use the SSLWrite function. - // + // // OSStatus SSLWrite(SSLContextRef context, const void *data, size_t dataLength, size_t *processed) - // + // // Parameters: // context - An SSL session context reference. // data - A pointer to the buffer of data to write. // dataLength - The amount, in bytes, of data to write. // processed - On return, the length, in bytes, of the data actually written. - // + // // It sounds pretty straight-forward, // but there are a few caveats you should be aware of. - // + // // The SSLWrite method operates in a non-obvious (and rather annoying) manner. // According to the documentation: - // + // // Because you may configure the underlying connection to operate in a non-blocking manner, // a write operation might return errSSLWouldBlock, indicating that less data than requested // was actually transferred. In this case, you should repeat the call to SSLWrite until some // other result is returned. - // + // // This sounds perfect, but when our SSLWriteFunction returns errSSLWouldBlock, // then the SSLWrite method returns (with the proper errSSLWouldBlock return value), // but it sets processed to dataLength !! - // + // // In other words, if the SSLWrite function doesn't completely write all the data we tell it to, // then it doesn't tell us how many bytes were actually written. So, for example, if we tell it to // write 256 bytes then it might actually write 128 bytes, but then report 0 bytes written. - // + // // You might be wondering: // If the SSLWrite function doesn't tell us how many bytes were written, // then how in the world are we supposed to update our parameters (buffer & bytesToWrite) // for the next time we invoke SSLWrite? - // + // // The answer is that SSLWrite cached all the data we told it to write, // and it will push out that data next time we call SSLWrite. // If we call SSLWrite with new data, it will push out the cached data first, and then the new data. // If we call SSLWrite with empty data, then it will simply push out the cached data. - // + // // For this purpose we're going to break large writes into a series of smaller writes. // This allows us to report progress back to the delegate. - + OSStatus result; - + BOOL hasCachedDataToWrite = (sslWriteCachedLength > 0); BOOL hasNewDataToWrite = YES; - + if (hasCachedDataToWrite) { size_t processed = 0; - + result = SSLWrite(sslContext, NULL, 0, &processed); - + if (result == noErr) { bytesWritten = sslWriteCachedLength; sslWriteCachedLength = 0; - + if ([currentWrite->buffer length] == (currentWrite->bytesDone + bytesWritten)) { // We've written all data for the current write. @@ -6199,42 +6209,42 @@ - (void)doWriteData { error = [self sslError:result]; } - + // Can't write any new data since we were unable to write the cached data. hasNewDataToWrite = NO; } } - + if (hasNewDataToWrite) { const uint8_t *buffer = (const uint8_t *)[currentWrite->buffer bytes] + currentWrite->bytesDone + bytesWritten; - + NSUInteger bytesToWrite = [currentWrite->buffer length] - currentWrite->bytesDone - bytesWritten; - + if (bytesToWrite > SIZE_MAX) // NSUInteger may be bigger than size_t (write param 3) { bytesToWrite = SIZE_MAX; } - + size_t bytesRemaining = bytesToWrite; - + BOOL keepLooping = YES; while (keepLooping) { const size_t sslMaxBytesToWrite = 32768; size_t sslBytesToWrite = MIN(bytesRemaining, sslMaxBytesToWrite); size_t sslBytesWritten = 0; - + result = SSLWrite(sslContext, buffer, sslBytesToWrite, &sslBytesWritten); - + if (result == noErr) { buffer += sslBytesWritten; bytesWritten += sslBytesWritten; bytesRemaining -= sslBytesWritten; - + keepLooping = (bytesRemaining > 0); } else @@ -6248,35 +6258,35 @@ - (void)doWriteData { error = [self sslError:result]; } - + keepLooping = NO; } - + } // while (keepLooping) - + } // if (hasNewDataToWrite) } } else { - // + // // Writing data directly over raw socket - // - + // + int socketFD = (socket4FD != SOCKET_NULL) ? socket4FD : (socket6FD != SOCKET_NULL) ? socket6FD : socketUN; - + const uint8_t *buffer = (const uint8_t *)[currentWrite->buffer bytes] + currentWrite->bytesDone; - + NSUInteger bytesToWrite = [currentWrite->buffer length] - currentWrite->bytesDone; - + if (bytesToWrite > SIZE_MAX) // NSUInteger may be bigger than size_t (write param 3) { bytesToWrite = SIZE_MAX; } - + ssize_t result = write(socketFD, buffer, (size_t)bytesToWrite); LogVerbose(@"wrote to socket = %zd", result); - + // Check results if (result < 0) { @@ -6294,48 +6304,48 @@ - (void)doWriteData bytesWritten = result; } } - + // We're done with our writing. // If we explictly ran into a situation where the socket told us there was no room in the buffer, // then we immediately resume listening for notifications. - // + // // We must do this before we dequeue another write, // as that may in turn invoke this method again. - // + // // Note that if CFStream is involved, it may have maliciously put our socket in blocking mode. - + if (waiting) { flags &= ~kSocketCanAcceptBytes; - + if (![self usingCFStreamForTLS]) { [self resumeWriteSource]; } } - + // Check our results - + BOOL done = NO; - + if (bytesWritten > 0) { // Update total amount read for the current write currentWrite->bytesDone += bytesWritten; LogVerbose(@"currentWrite->bytesDone = %lu", (unsigned long)currentWrite->bytesDone); - + // Is packet done? done = (currentWrite->bytesDone == [currentWrite->buffer length]); } - + if (done) { [self completeCurrentWrite]; - + if (!error) { dispatch_async(socketQueue, ^{ @autoreleasepool{ - + [self maybeDequeueWrite]; }}); } @@ -6344,66 +6354,66 @@ - (void)doWriteData { // We were unable to finish writing the data, // so we're waiting for another callback to notify us of available space in the lower-level output buffer. - + if (!waiting && !error) { // This would be the case if our write was able to accept some data, but not all of it. - + flags &= ~kSocketCanAcceptBytes; - + if (![self usingCFStreamForTLS]) { [self resumeWriteSource]; } } - + if (bytesWritten > 0) { // We're not done with the entire write, but we have written some bytes - + __strong id theDelegate = delegate; if (delegateQueue && [theDelegate respondsToSelector:@selector(socket:didWritePartialDataOfLength:tag:)]) { long theWriteTag = currentWrite->tag; - + dispatch_async(delegateQueue, ^{ @autoreleasepool { - + [theDelegate socket:self didWritePartialDataOfLength:bytesWritten tag:theWriteTag]; }}); } } } - + // Check for errors - + if (error) { [self closeWithError:[self errorWithErrno:errno reason:@"Error in write() function"]]; } - + // Do not add any code here without first adding a return statement in the error case above. } - (void)completeCurrentWrite { LogTrace(); - + NSAssert(currentWrite, @"Trying to complete current write when there is no current write."); - + __strong id theDelegate = delegate; - + if (delegateQueue && [theDelegate respondsToSelector:@selector(socket:didWriteDataWithTag:)]) { long theWriteTag = currentWrite->tag; - + dispatch_async(delegateQueue, ^{ @autoreleasepool { - + [theDelegate socket:self didWriteDataWithTag:theWriteTag]; }}); } - + [self endCurrentWrite]; } @@ -6414,7 +6424,7 @@ - (void)endCurrentWrite dispatch_source_cancel(writeTimer); writeTimer = NULL; } - + currentWrite = nil; } @@ -6423,36 +6433,36 @@ - (void)setupWriteTimerWithTimeout:(NSTimeInterval)timeout if (timeout >= 0.0) { writeTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, socketQueue); - + __weak GCDAsyncSocket *weakSelf = self; - + dispatch_source_set_event_handler(writeTimer, ^{ @autoreleasepool { #pragma clang diagnostic push #pragma clang diagnostic warning "-Wimplicit-retain-self" - + __strong GCDAsyncSocket *strongSelf = weakSelf; if (strongSelf == nil) return_from_block; - + [strongSelf doWriteTimeout]; - + #pragma clang diagnostic pop }}); - + #if !OS_OBJECT_USE_OBJC dispatch_source_t theWriteTimer = writeTimer; dispatch_source_set_cancel_handler(writeTimer, ^{ #pragma clang diagnostic push #pragma clang diagnostic warning "-Wimplicit-retain-self" - + LogVerbose(@"dispatch_release(writeTimer)"); dispatch_release(theWriteTimer); - + #pragma clang diagnostic pop }); #endif - + dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeout * NSEC_PER_SEC)); - + dispatch_source_set_timer(writeTimer, tt, DISPATCH_TIME_FOREVER, 0); dispatch_resume(writeTimer); } @@ -6464,25 +6474,25 @@ - (void)doWriteTimeout // Ideally we'd like to synchronously query the delegate about a timeout extension. // But if we do so synchronously we risk a possible deadlock. // So instead we have to do so asynchronously, and callback to ourselves from within the delegate block. - + flags |= kWritesPaused; - + __strong id theDelegate = delegate; if (delegateQueue && [theDelegate respondsToSelector:@selector(socket:shouldTimeoutWriteWithTag:elapsed:bytesDone:)]) { GCDAsyncWritePacket *theWrite = currentWrite; - + dispatch_async(delegateQueue, ^{ @autoreleasepool { - + NSTimeInterval timeoutExtension = 0.0; - + timeoutExtension = [theDelegate socket:self shouldTimeoutWriteWithTag:theWrite->tag elapsed:theWrite->timeout bytesDone:theWrite->bytesDone]; - + dispatch_async(self->socketQueue, ^{ @autoreleasepool { - + [self doWriteTimeoutWithExtension:timeoutExtension]; }}); }}); @@ -6500,11 +6510,11 @@ - (void)doWriteTimeoutWithExtension:(NSTimeInterval)timeoutExtension if (timeoutExtension > 0.0) { currentWrite->timeout += timeoutExtension; - + // Reschedule the timer dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeoutExtension * NSEC_PER_SEC)); dispatch_source_set_timer(writeTimer, tt, DISPATCH_TIME_FOREVER, 0); - + // Unpause writes, and continue flags &= ~kWritesPaused; [self doWriteData]; @@ -6512,7 +6522,7 @@ - (void)doWriteTimeoutWithExtension:(NSTimeInterval)timeoutExtension else { LogVerbose(@"WriteTimeout"); - + [self closeWithError:[self writeTimeoutError]]; } } @@ -6525,36 +6535,36 @@ - (void)doWriteTimeoutWithExtension:(NSTimeInterval)timeoutExtension - (void)startTLS:(NSDictionary *)tlsSettings { LogTrace(); - + if (tlsSettings == nil) { // Passing nil/NULL to CFReadStreamSetProperty will appear to work the same as passing an empty dictionary, // but causes problems if we later try to fetch the remote host's certificate. - // + // // To be exact, it causes the following to return NULL instead of the normal result: // CFReadStreamCopyProperty(readStream, kCFStreamPropertySSLPeerCertificates) - // + // // So we use an empty dictionary instead, which works perfectly. - + tlsSettings = [NSDictionary dictionary]; } - + GCDAsyncSpecialPacket *packet = [[GCDAsyncSpecialPacket alloc] initWithTLSSettings:tlsSettings]; - + dispatch_async(socketQueue, ^{ @autoreleasepool { - + if ((self->flags & kSocketStarted) && !(self->flags & kQueuedTLS) && !(self->flags & kForbidReadsWrites)) { [self->readQueue addObject:packet]; [self->writeQueue addObject:packet]; - + self->flags |= kQueuedTLS; - + [self maybeDequeueRead]; [self maybeDequeueWrite]; } }}); - + } - (void)maybeStartTLS @@ -6562,13 +6572,13 @@ - (void)maybeStartTLS // We can't start TLS until: // - All queued reads prior to the user calling startTLS are complete // - All queued writes prior to the user calling startTLS are complete - // + // // We'll know these conditions are met when both kStartingReadTLS and kStartingWriteTLS are set - + if ((flags & kStartingReadTLS) && (flags & kStartingWriteTLS)) { BOOL useSecureTransport = YES; - + #if TARGET_OS_IPHONE { GCDAsyncSpecialPacket *tlsPacket = (GCDAsyncSpecialPacket *)currentRead; @@ -6581,7 +6591,7 @@ - (void)maybeStartTLS useSecureTransport = NO; } #endif - + if (useSecureTransport) { [self ssl_startTLS]; @@ -6602,82 +6612,82 @@ - (void)maybeStartTLS - (OSStatus)sslReadWithBuffer:(void *)buffer length:(size_t *)bufferLength { LogVerbose(@"sslReadWithBuffer:%p length:%lu", buffer, (unsigned long)*bufferLength); - + if ((socketFDBytesAvailable == 0) && ([sslPreBuffer availableBytes] == 0)) { LogVerbose(@"%@ - No data available to read...", THIS_METHOD); - + // No data available to read. - // + // // Need to wait for readSource to fire and notify us of // available data in the socket's internal read buffer. - + [self resumeReadSource]; - + *bufferLength = 0; return errSSLWouldBlock; } - + size_t totalBytesRead = 0; size_t totalBytesLeftToBeRead = *bufferLength; - + BOOL done = NO; BOOL socketError = NO; - - // + + // // STEP 1 : READ FROM SSL PRE BUFFER - // - + // + size_t sslPreBufferLength = [sslPreBuffer availableBytes]; - + if (sslPreBufferLength > 0) { LogVerbose(@"%@: Reading from SSL pre buffer...", THIS_METHOD); - + size_t bytesToCopy; if (sslPreBufferLength > totalBytesLeftToBeRead) bytesToCopy = totalBytesLeftToBeRead; else bytesToCopy = sslPreBufferLength; - + LogVerbose(@"%@: Copying %zu bytes from sslPreBuffer", THIS_METHOD, bytesToCopy); - + memcpy(buffer, [sslPreBuffer readBuffer], bytesToCopy); [sslPreBuffer didRead:bytesToCopy]; - + LogVerbose(@"%@: sslPreBuffer.length = %zu", THIS_METHOD, [sslPreBuffer availableBytes]); - + totalBytesRead += bytesToCopy; totalBytesLeftToBeRead -= bytesToCopy; - + done = (totalBytesLeftToBeRead == 0); - + if (done) LogVerbose(@"%@: Complete", THIS_METHOD); } - - // + + // // STEP 2 : READ FROM SOCKET - // - + // + if (!done && (socketFDBytesAvailable > 0)) { LogVerbose(@"%@: Reading from socket...", THIS_METHOD); - + int socketFD = (socket4FD != SOCKET_NULL) ? socket4FD : (socket6FD != SOCKET_NULL) ? socket6FD : socketUN; - + BOOL readIntoPreBuffer; size_t bytesToRead; uint8_t *buf; - + if (socketFDBytesAvailable > totalBytesLeftToBeRead) { // Read all available data from socket into sslPreBuffer. // Then copy requested amount into dataBuffer. - + LogVerbose(@"%@: Reading into sslPreBuffer...", THIS_METHOD); - + [sslPreBuffer ensureCapacityForWrite:socketFDBytesAvailable]; - + readIntoPreBuffer = YES; bytesToRead = (size_t)socketFDBytesAvailable; buf = [sslPreBuffer writeBuffer]; @@ -6685,58 +6695,58 @@ - (OSStatus)sslReadWithBuffer:(void *)buffer length:(size_t *)bufferLength else { // Read available data from socket directly into dataBuffer. - + LogVerbose(@"%@: Reading directly into dataBuffer...", THIS_METHOD); - + readIntoPreBuffer = NO; bytesToRead = totalBytesLeftToBeRead; buf = (uint8_t *)buffer + totalBytesRead; } - + ssize_t result = read(socketFD, buf, bytesToRead); LogVerbose(@"%@: read from socket = %zd", THIS_METHOD, result); - + if (result < 0) { LogVerbose(@"%@: read errno = %i", THIS_METHOD, errno); - + if (errno != EWOULDBLOCK) { socketError = YES; } - + socketFDBytesAvailable = 0; } else if (result == 0) { LogVerbose(@"%@: read EOF", THIS_METHOD); - + socketError = YES; socketFDBytesAvailable = 0; } else { size_t bytesReadFromSocket = result; - + if (socketFDBytesAvailable > bytesReadFromSocket) socketFDBytesAvailable -= bytesReadFromSocket; else socketFDBytesAvailable = 0; - + if (readIntoPreBuffer) { [sslPreBuffer didWrite:bytesReadFromSocket]; - + size_t bytesToCopy = MIN(totalBytesLeftToBeRead, bytesReadFromSocket); - + LogVerbose(@"%@: Copying %zu bytes out of sslPreBuffer", THIS_METHOD, bytesToCopy); - + memcpy((uint8_t *)buffer + totalBytesRead, [sslPreBuffer readBuffer], bytesToCopy); [sslPreBuffer didRead:bytesToCopy]; - + totalBytesRead += bytesToCopy; totalBytesLeftToBeRead -= bytesToCopy; - + LogVerbose(@"%@: sslPreBuffer.length = %zu", THIS_METHOD, [sslPreBuffer availableBytes]); } else @@ -6744,21 +6754,21 @@ - (OSStatus)sslReadWithBuffer:(void *)buffer length:(size_t *)bufferLength totalBytesRead += bytesReadFromSocket; totalBytesLeftToBeRead -= bytesReadFromSocket; } - + done = (totalBytesLeftToBeRead == 0); - + if (done) LogVerbose(@"%@: Complete", THIS_METHOD); } } - + *bufferLength = totalBytesRead; - + if (done) return noErr; - + if (socketError) return errSSLClosedAbort; - + return errSSLWouldBlock; } @@ -6767,33 +6777,33 @@ - (OSStatus)sslWriteWithBuffer:(const void *)buffer length:(size_t *)bufferLengt if (!(flags & kSocketCanAcceptBytes)) { // Unable to write. - // + // // Need to wait for writeSource to fire and notify us of // available space in the socket's internal write buffer. - + [self resumeWriteSource]; - + *bufferLength = 0; return errSSLWouldBlock; } - + size_t bytesToWrite = *bufferLength; size_t bytesWritten = 0; - + BOOL done = NO; BOOL socketError = NO; - + int socketFD = (socket4FD != SOCKET_NULL) ? socket4FD : (socket6FD != SOCKET_NULL) ? socket6FD : socketUN; - + ssize_t result = write(socketFD, buffer, bytesToWrite); - + if (result < 0) { if (errno != EWOULDBLOCK) { socketError = YES; } - + flags &= ~kSocketCanAcceptBytes; } else if (result == 0) @@ -6803,69 +6813,69 @@ - (OSStatus)sslWriteWithBuffer:(const void *)buffer length:(size_t *)bufferLengt else { bytesWritten = result; - + done = (bytesWritten == bytesToWrite); } - + *bufferLength = bytesWritten; - + if (done) return noErr; - + if (socketError) return errSSLClosedAbort; - + return errSSLWouldBlock; } static OSStatus SSLReadFunction(SSLConnectionRef connection, void *data, size_t *dataLength) { GCDAsyncSocket *asyncSocket = (__bridge GCDAsyncSocket *)connection; - + NSCAssert(dispatch_get_specific(asyncSocket->IsOnSocketQueueOrTargetQueueKey), @"What the deuce?"); - + return [asyncSocket sslReadWithBuffer:data length:dataLength]; } static OSStatus SSLWriteFunction(SSLConnectionRef connection, const void *data, size_t *dataLength) { GCDAsyncSocket *asyncSocket = (__bridge GCDAsyncSocket *)connection; - + NSCAssert(dispatch_get_specific(asyncSocket->IsOnSocketQueueOrTargetQueueKey), @"What the deuce?"); - + return [asyncSocket sslWriteWithBuffer:data length:dataLength]; } - (void)ssl_startTLS { LogTrace(); - + LogVerbose(@"Starting TLS (via SecureTransport)..."); - + OSStatus status; - + GCDAsyncSpecialPacket *tlsPacket = (GCDAsyncSpecialPacket *)currentRead; if (tlsPacket == nil) // Code to quiet the analyzer { NSAssert(NO, @"Logic error"); - + [self closeWithError:[self otherError:@"Logic error"]]; return; } NSDictionary *tlsSettings = tlsPacket->tlsSettings; - + // Create SSLContext, and setup IO callbacks and connection ref - + NSNumber *isServerNumber = [tlsSettings objectForKey:(__bridge NSString *)kCFStreamSSLIsServer]; BOOL isServer = [isServerNumber boolValue]; - + #if TARGET_OS_IPHONE || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 1080) { if (isServer) sslContext = SSLCreateContext(kCFAllocatorDefault, kSSLServerSide, kSSLStreamType); else sslContext = SSLCreateContext(kCFAllocatorDefault, kSSLClientSide, kSSLStreamType); - + if (sslContext == NULL) { [self closeWithError:[self otherError:@"Error in SSLCreateContext"]]; @@ -6882,14 +6892,14 @@ - (void)ssl_startTLS } } #endif - + status = SSLSetIOFuncs(sslContext, &SSLReadFunction, &SSLWriteFunction); if (status != noErr) { [self closeWithError:[self otherError:@"Error in SSLSetIOFuncs"]]; return; } - + status = SSLSetConnection(sslContext, (__bridge SSLConnectionRef)self); if (status != noErr) { @@ -6906,35 +6916,35 @@ - (void)ssl_startTLS [self closeWithError:[self otherError:@"Manual trust validation is not supported for server sockets"]]; return; } - + status = SSLSetSessionOption(sslContext, kSSLSessionOptionBreakOnServerAuth, true); if (status != noErr) { [self closeWithError:[self otherError:@"Error in SSLSetSessionOption"]]; return; } - + #if !TARGET_OS_IPHONE && (__MAC_OS_X_VERSION_MIN_REQUIRED < 1080) - + // Note from Apple's documentation: // // It is only necessary to call SSLSetEnableCertVerify on the Mac prior to OS X 10.8. // On OS X 10.8 and later setting kSSLSessionOptionBreakOnServerAuth always disables the // built-in trust evaluation. All versions of iOS behave like OS X 10.8 and thus // SSLSetEnableCertVerify is not available on that platform at all. - + status = SSLSetEnableCertVerify(sslContext, NO); if (status != noErr) { [self closeWithError:[self otherError:@"Error in SSLSetEnableCertVerify"]]; return; } - + #endif } // Configure SSLContext from given settings - // + // // Checklist: // 1. kCFStreamSSLPeerName // 2. kCFStreamSSLCertificates @@ -6953,19 +6963,19 @@ - (void)ssl_startTLS // 12. kCFStreamSSLAllowsExpiredCertificates // 13. kCFStreamSSLValidatesCertificateChain // 14. kCFStreamSSLLevel - + NSObject *value; - + // 1. kCFStreamSSLPeerName - + value = [tlsSettings objectForKey:(__bridge NSString *)kCFStreamSSLPeerName]; if ([value isKindOfClass:[NSString class]]) { NSString *peerName = (NSString *)value; - + const char *peer = [peerName UTF8String]; size_t peerLen = strlen(peer); - + status = SSLSetPeerDomainName(sslContext, peer, peerLen); if (status != noErr) { @@ -6976,18 +6986,18 @@ - (void)ssl_startTLS else if (value) { NSAssert(NO, @"Invalid value for kCFStreamSSLPeerName. Value must be of type NSString."); - + [self closeWithError:[self otherError:@"Invalid value for kCFStreamSSLPeerName."]]; return; } - + // 2. kCFStreamSSLCertificates - + value = [tlsSettings objectForKey:(__bridge NSString *)kCFStreamSSLCertificates]; if ([value isKindOfClass:[NSArray class]]) { NSArray *certs = (NSArray *)value; - + status = SSLSetCertificate(sslContext, (__bridge CFArrayRef)certs); if (status != noErr) { @@ -6998,18 +7008,18 @@ - (void)ssl_startTLS else if (value) { NSAssert(NO, @"Invalid value for kCFStreamSSLCertificates. Value must be of type NSArray."); - + [self closeWithError:[self otherError:@"Invalid value for kCFStreamSSLCertificates."]]; return; } - + // 3. GCDAsyncSocketSSLPeerID - + value = [tlsSettings objectForKey:GCDAsyncSocketSSLPeerID]; if ([value isKindOfClass:[NSData class]]) { NSData *peerIdData = (NSData *)value; - + status = SSLSetPeerID(sslContext, [peerIdData bytes], [peerIdData length]); if (status != noErr) { @@ -7022,13 +7032,13 @@ - (void)ssl_startTLS NSAssert(NO, @"Invalid value for GCDAsyncSocketSSLPeerID. Value must be of type NSData." @" (You can convert strings to data using a method like" @" [string dataUsingEncoding:NSUTF8StringEncoding])"); - + [self closeWithError:[self otherError:@"Invalid value for GCDAsyncSocketSSLPeerID."]]; return; } - + // 4. GCDAsyncSocketSSLProtocolVersionMin - + value = [tlsSettings objectForKey:GCDAsyncSocketSSLProtocolVersionMin]; if ([value isKindOfClass:[NSNumber class]]) { @@ -7046,13 +7056,13 @@ - (void)ssl_startTLS else if (value) { NSAssert(NO, @"Invalid value for GCDAsyncSocketSSLProtocolVersionMin. Value must be of type NSNumber."); - + [self closeWithError:[self otherError:@"Invalid value for GCDAsyncSocketSSLProtocolVersionMin."]]; return; } - + // 5. GCDAsyncSocketSSLProtocolVersionMax - + value = [tlsSettings objectForKey:GCDAsyncSocketSSLProtocolVersionMax]; if ([value isKindOfClass:[NSNumber class]]) { @@ -7070,13 +7080,13 @@ - (void)ssl_startTLS else if (value) { NSAssert(NO, @"Invalid value for GCDAsyncSocketSSLProtocolVersionMax. Value must be of type NSNumber."); - + [self closeWithError:[self otherError:@"Invalid value for GCDAsyncSocketSSLProtocolVersionMax."]]; return; } - + // 6. GCDAsyncSocketSSLSessionOptionFalseStart - + value = [tlsSettings objectForKey:GCDAsyncSocketSSLSessionOptionFalseStart]; if ([value isKindOfClass:[NSNumber class]]) { @@ -7091,13 +7101,13 @@ - (void)ssl_startTLS else if (value) { NSAssert(NO, @"Invalid value for GCDAsyncSocketSSLSessionOptionFalseStart. Value must be of type NSNumber."); - + [self closeWithError:[self otherError:@"Invalid value for GCDAsyncSocketSSLSessionOptionFalseStart."]]; return; } - + // 7. GCDAsyncSocketSSLSessionOptionSendOneByteRecord - + value = [tlsSettings objectForKey:GCDAsyncSocketSSLSessionOptionSendOneByteRecord]; if ([value isKindOfClass:[NSNumber class]]) { @@ -7114,13 +7124,13 @@ - (void)ssl_startTLS { NSAssert(NO, @"Invalid value for GCDAsyncSocketSSLSessionOptionSendOneByteRecord." @" Value must be of type NSNumber."); - + [self closeWithError:[self otherError:@"Invalid value for GCDAsyncSocketSSLSessionOptionSendOneByteRecord."]]; return; } - + // 8. GCDAsyncSocketSSLCipherSuites - + value = [tlsSettings objectForKey:GCDAsyncSocketSSLCipherSuites]; if ([value isKindOfClass:[NSArray class]]) { @@ -7130,14 +7140,14 @@ - (void)ssl_startTLS #pragma clang diagnostic ignored "-Wvla" SSLCipherSuite ciphers[numberCiphers]; #pragma clang diagnostic pop - + NSUInteger cipherIndex; for (cipherIndex = 0; cipherIndex < numberCiphers; cipherIndex++) { NSNumber *cipherObject = [cipherSuites objectAtIndex:cipherIndex]; ciphers[cipherIndex] = (SSLCipherSuite)[cipherObject unsignedIntValue]; } - + status = SSLSetEnabledCiphers(sslContext, ciphers, numberCiphers); if (status != noErr) { @@ -7148,19 +7158,19 @@ - (void)ssl_startTLS else if (value) { NSAssert(NO, @"Invalid value for GCDAsyncSocketSSLCipherSuites. Value must be of type NSArray."); - + [self closeWithError:[self otherError:@"Invalid value for GCDAsyncSocketSSLCipherSuites."]]; return; } - + // 9. GCDAsyncSocketSSLDiffieHellmanParameters - + #if !TARGET_OS_IPHONE value = [tlsSettings objectForKey:GCDAsyncSocketSSLDiffieHellmanParameters]; if ([value isKindOfClass:[NSData class]]) { NSData *diffieHellmanData = (NSData *)value; - + status = SSLSetDiffieHellmanParams(sslContext, [diffieHellmanData bytes], [diffieHellmanData length]); if (status != noErr) { @@ -7171,7 +7181,7 @@ - (void)ssl_startTLS else if (value) { NSAssert(NO, @"Invalid value for GCDAsyncSocketSSLDiffieHellmanParameters. Value must be of type NSData."); - + [self closeWithError:[self otherError:@"Invalid value for GCDAsyncSocketSSLDiffieHellmanParameters."]]; return; } @@ -7201,15 +7211,15 @@ - (void)ssl_startTLS else if (value) { NSAssert(NO, @"Invalid value for GCDAsyncSocketSSLALPN. Value must be of type NSArray."); - + [self closeWithError:[self otherError:@"Invalid value for GCDAsyncSocketSSLALPN."]]; return; } - + // DEPRECATED checks - + // 10. kCFStreamSSLAllowsAnyRoot - + #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" value = [tlsSettings objectForKey:(__bridge NSString *)kCFStreamSSLAllowsAnyRoot]; @@ -7218,13 +7228,13 @@ - (void)ssl_startTLS { NSAssert(NO, @"Security option unavailable - kCFStreamSSLAllowsAnyRoot" @" - You must use manual trust evaluation"); - + [self closeWithError:[self otherError:@"Security option unavailable - kCFStreamSSLAllowsAnyRoot"]]; return; } - + // 11. kCFStreamSSLAllowsExpiredRoots - + #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" value = [tlsSettings objectForKey:(__bridge NSString *)kCFStreamSSLAllowsExpiredRoots]; @@ -7233,13 +7243,13 @@ - (void)ssl_startTLS { NSAssert(NO, @"Security option unavailable - kCFStreamSSLAllowsExpiredRoots" @" - You must use manual trust evaluation"); - + [self closeWithError:[self otherError:@"Security option unavailable - kCFStreamSSLAllowsExpiredRoots"]]; return; } - + // 12. kCFStreamSSLValidatesCertificateChain - + #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" value = [tlsSettings objectForKey:(__bridge NSString *)kCFStreamSSLValidatesCertificateChain]; @@ -7248,13 +7258,13 @@ - (void)ssl_startTLS { NSAssert(NO, @"Security option unavailable - kCFStreamSSLValidatesCertificateChain" @" - You must use manual trust evaluation"); - + [self closeWithError:[self otherError:@"Security option unavailable - kCFStreamSSLValidatesCertificateChain"]]; return; } - + // 13. kCFStreamSSLAllowsExpiredCertificates - + #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" value = [tlsSettings objectForKey:(__bridge NSString *)kCFStreamSSLAllowsExpiredCertificates]; @@ -7263,13 +7273,13 @@ - (void)ssl_startTLS { NSAssert(NO, @"Security option unavailable - kCFStreamSSLAllowsExpiredCertificates" @" - You must use manual trust evaluation"); - + [self closeWithError:[self otherError:@"Security option unavailable - kCFStreamSSLAllowsExpiredCertificates"]]; return; } - + // 14. kCFStreamSSLLevel - + #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" value = [tlsSettings objectForKey:(__bridge NSString *)kCFStreamSSLLevel]; @@ -7278,79 +7288,79 @@ - (void)ssl_startTLS { NSAssert(NO, @"Security option unavailable - kCFStreamSSLLevel" @" - You must use GCDAsyncSocketSSLProtocolVersionMin & GCDAsyncSocketSSLProtocolVersionMax"); - + [self closeWithError:[self otherError:@"Security option unavailable - kCFStreamSSLLevel"]]; return; } - + // Setup the sslPreBuffer - // + // // Any data in the preBuffer needs to be moved into the sslPreBuffer, // as this data is now part of the secure read stream. - + sslPreBuffer = [[GCDAsyncSocketPreBuffer alloc] initWithCapacity:(1024 * 4)]; - + size_t preBufferLength = [preBuffer availableBytes]; - + if (preBufferLength > 0) { [sslPreBuffer ensureCapacityForWrite:preBufferLength]; - + memcpy([sslPreBuffer writeBuffer], [preBuffer readBuffer], preBufferLength); [preBuffer didRead:preBufferLength]; [sslPreBuffer didWrite:preBufferLength]; } - + sslErrCode = lastSSLHandshakeError = noErr; - + // Start the SSL Handshake process - + [self ssl_continueSSLHandshake]; } - (void)ssl_continueSSLHandshake { LogTrace(); - + // If the return value is noErr, the session is ready for normal secure communication. // If the return value is errSSLWouldBlock, the SSLHandshake function must be called again. // If the return value is errSSLServerAuthCompleted, we ask delegate if we should trust the // server and then call SSLHandshake again to resume the handshake or close the connection // errSSLPeerBadCert SSL error. // Otherwise, the return value indicates an error code. - + OSStatus status = SSLHandshake(sslContext); lastSSLHandshakeError = status; - + if (status == noErr) { LogVerbose(@"SSLHandshake complete"); - + flags &= ~kStartingReadTLS; flags &= ~kStartingWriteTLS; - + flags |= kSocketSecure; - + __strong id theDelegate = delegate; if (delegateQueue && [theDelegate respondsToSelector:@selector(socketDidSecure:)]) { dispatch_async(delegateQueue, ^{ @autoreleasepool { - + [theDelegate socketDidSecure:self]; }}); } - + [self endCurrentRead]; [self endCurrentWrite]; - + [self maybeDequeueRead]; [self maybeDequeueWrite]; } else if (status == errSSLPeerAuthCompleted) { LogVerbose(@"SSLHandshake peerAuthCompleted - awaiting delegate approval"); - + __block SecTrustRef trust = NULL; status = SSLCopyPeerTrust(sslContext, &trust); if (status != noErr) @@ -7358,39 +7368,39 @@ - (void)ssl_continueSSLHandshake [self closeWithError:[self sslError:status]]; return; } - + int aStateIndex = stateIndex; dispatch_queue_t theSocketQueue = socketQueue; - + __weak GCDAsyncSocket *weakSelf = self; - + void (^comletionHandler)(BOOL) = ^(BOOL shouldTrust){ @autoreleasepool { #pragma clang diagnostic push #pragma clang diagnostic warning "-Wimplicit-retain-self" - + dispatch_async(theSocketQueue, ^{ @autoreleasepool { - + if (trust) { CFRelease(trust); trust = NULL; } - + __strong GCDAsyncSocket *strongSelf = weakSelf; if (strongSelf) { [strongSelf ssl_shouldTrustPeer:shouldTrust stateIndex:aStateIndex]; } }}); - + #pragma clang diagnostic pop }}; - + __strong id theDelegate = delegate; - + if (delegateQueue && [theDelegate respondsToSelector:@selector(socket:didReceiveTrust:completionHandler:)]) { dispatch_async(delegateQueue, ^{ @autoreleasepool { - + [theDelegate socket:self didReceiveTrust:trust completionHandler:comletionHandler]; }}); } @@ -7400,10 +7410,10 @@ - (void)ssl_continueSSLHandshake CFRelease(trust); trust = NULL; } - + NSString *msg = @"GCDAsyncSocketManuallyEvaluateTrust specified in tlsSettings," @" but delegate doesn't implement socket:shouldTrustPeer:"; - + [self closeWithError:[self otherError:msg]]; return; } @@ -7411,9 +7421,9 @@ - (void)ssl_continueSSLHandshake else if (status == errSSLWouldBlock) { LogVerbose(@"SSLHandshake continues..."); - + // Handshake continues... - // + // // This method will be called again from doReadData or doWriteData. } else @@ -7425,22 +7435,22 @@ - (void)ssl_continueSSLHandshake - (void)ssl_shouldTrustPeer:(BOOL)shouldTrust stateIndex:(int)aStateIndex { LogTrace(); - + if (aStateIndex != stateIndex) { LogInfo(@"Ignoring ssl_shouldTrustPeer - invalid state (maybe disconnected)"); - + // One of the following is true // - the socket was disconnected // - the startTLS operation timed out // - the completionHandler was already invoked once - + return; } - + // Increment stateIndex to ensure completionHandler can only be called once. stateIndex++; - + if (shouldTrust) { NSAssert(lastSSLHandshakeError == errSSLPeerAuthCompleted, @"ssl_shouldTrustPeer called when last error is %d and not errSSLPeerAuthCompleted", (int)lastSSLHandshakeError); @@ -7461,27 +7471,27 @@ - (void)ssl_shouldTrustPeer:(BOOL)shouldTrust stateIndex:(int)aStateIndex - (void)cf_finishSSLHandshake { LogTrace(); - + if ((flags & kStartingReadTLS) && (flags & kStartingWriteTLS)) { flags &= ~kStartingReadTLS; flags &= ~kStartingWriteTLS; - + flags |= kSocketSecure; - + __strong id theDelegate = delegate; if (delegateQueue && [theDelegate respondsToSelector:@selector(socketDidSecure:)]) { dispatch_async(delegateQueue, ^{ @autoreleasepool { - + [theDelegate socketDidSecure:self]; }}); } - + [self endCurrentRead]; [self endCurrentWrite]; - + [self maybeDequeueRead]; [self maybeDequeueWrite]; } @@ -7490,12 +7500,12 @@ - (void)cf_finishSSLHandshake - (void)cf_abortSSLHandshake:(NSError *)error { LogTrace(); - + if ((flags & kStartingReadTLS) && (flags & kStartingWriteTLS)) { flags &= ~kStartingReadTLS; flags &= ~kStartingWriteTLS; - + [self closeWithError:error]; } } @@ -7503,87 +7513,87 @@ - (void)cf_abortSSLHandshake:(NSError *)error - (void)cf_startTLS { LogTrace(); - + LogVerbose(@"Starting TLS (via CFStream)..."); - + if ([preBuffer availableBytes] > 0) { NSString *msg = @"Invalid TLS transition. Handshake has already been read from socket."; - + [self closeWithError:[self otherError:msg]]; return; } - + [self suspendReadSource]; [self suspendWriteSource]; - + socketFDBytesAvailable = 0; flags &= ~kSocketCanAcceptBytes; flags &= ~kSecureSocketHasBytesAvailable; - + flags |= kUsingCFStreamForTLS; - + if (![self createReadAndWriteStream]) { [self closeWithError:[self otherError:@"Error in CFStreamCreatePairWithSocket"]]; return; } - + if (![self registerForStreamCallbacksIncludingReadWrite:YES]) { [self closeWithError:[self otherError:@"Error in CFStreamSetClient"]]; return; } - + if (![self addStreamsToRunLoop]) { [self closeWithError:[self otherError:@"Error in CFStreamScheduleWithRunLoop"]]; return; } - + NSAssert([currentRead isKindOfClass:[GCDAsyncSpecialPacket class]], @"Invalid read packet for startTLS"); NSAssert([currentWrite isKindOfClass:[GCDAsyncSpecialPacket class]], @"Invalid write packet for startTLS"); - + GCDAsyncSpecialPacket *tlsPacket = (GCDAsyncSpecialPacket *)currentRead; CFDictionaryRef tlsSettings = (__bridge CFDictionaryRef)tlsPacket->tlsSettings; - + // Getting an error concerning kCFStreamPropertySSLSettings ? - // You need to add the CFNetwork framework to your iOS application. - + // CFNetwork/CFStream.h is imported for SSL constants needed by CFStream TLS support. + BOOL r1 = CFReadStreamSetProperty(readStream, kCFStreamPropertySSLSettings, tlsSettings); BOOL r2 = CFWriteStreamSetProperty(writeStream, kCFStreamPropertySSLSettings, tlsSettings); - + // For some reason, starting around the time of iOS 4.3, // the first call to set the kCFStreamPropertySSLSettings will return true, // but the second will return false. - // + // // Order doesn't seem to matter. // So you could call CFReadStreamSetProperty and then CFWriteStreamSetProperty, or you could reverse the order. // Either way, the first call will return true, and the second returns false. - // + // // Interestingly, this doesn't seem to affect anything. // Which is not altogether unusual, as the documentation seems to suggest that (for many settings) // setting it on one side of the stream automatically sets it for the other side of the stream. - // + // // Although there isn't anything in the documentation to suggest that the second attempt would fail. - // + // // Furthermore, this only seems to affect streams that are negotiating a security upgrade. // In other words, the socket gets connected, there is some back-and-forth communication over the unsecure // connection, and then a startTLS is issued. // So this mostly affects newer protocols (XMPP, IMAP) as opposed to older protocols (HTTPS). - + if (!r1 && !r2) // Yes, the && is correct - workaround for apple bug. { [self closeWithError:[self otherError:@"Error in CFStreamSetProperty"]]; return; } - + if (![self openStreams]) { [self closeWithError:[self otherError:@"Error in CFStreamOpen"]]; return; } - + LogVerbose(@"Waiting for SSL Handshake to complete..."); } @@ -7601,16 +7611,16 @@ + (void)ignore:(id)_ + (void)startCFStreamThreadIfNeeded { LogTrace(); - + static dispatch_once_t predicate; dispatch_once(&predicate, ^{ - + cfstreamThreadRetainCount = 0; cfstreamThreadSetupQueue = dispatch_queue_create("GCDAsyncSocket-CFStreamThreadSetup", DISPATCH_QUEUE_SERIAL); }); - + dispatch_sync(cfstreamThreadSetupQueue, ^{ @autoreleasepool { - + if (++cfstreamThreadRetainCount == 1) { cfstreamThread = [[NSThread alloc] initWithTarget:self @@ -7624,38 +7634,38 @@ + (void)startCFStreamThreadIfNeeded + (void)stopCFStreamThreadIfNeeded { LogTrace(); - + // The creation of the cfstreamThread is relatively expensive. // So we'd like to keep it available for recycling. // However, there's a tradeoff here, because it shouldn't remain alive forever. // So what we're going to do is use a little delay before taking it down. // This way it can be reused properly in situations where multiple sockets are continually in flux. - + int delayInSeconds = 30; dispatch_time_t when = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); dispatch_after(when, cfstreamThreadSetupQueue, ^{ @autoreleasepool { #pragma clang diagnostic push #pragma clang diagnostic warning "-Wimplicit-retain-self" - + if (cfstreamThreadRetainCount == 0) { LogWarn(@"Logic error concerning cfstreamThread start / stop"); return_from_block; } - + if (--cfstreamThreadRetainCount == 0) { [cfstreamThread cancel]; // set isCancelled flag - + // wake up the thread [[self class] performSelector:@selector(ignore:) onThread:cfstreamThread withObject:[NSNull null] waitUntilDone:NO]; - + cfstreamThread = nil; } - + #pragma clang diagnostic pop }}); } @@ -7663,9 +7673,9 @@ + (void)stopCFStreamThreadIfNeeded + (void)cfstreamThread:(id)unused { @autoreleasepool { [[NSThread currentThread] setName:GCDAsyncSocketThreadName]; - + LogInfo(@"CFStreamThread: Started"); - + // We can't run the run loop unless it has an associated input source or a timer. // So we'll just create a timer that will never fire - unless the server runs for decades. [NSTimer scheduledTimerWithTimeInterval:[[NSDate distantFuture] timeIntervalSinceNow] @@ -7673,17 +7683,17 @@ + (void)cfstreamThread:(id)unused { @autoreleasepool selector:@selector(ignore:) userInfo:nil repeats:YES]; - + NSThread *currentThread = [NSThread currentThread]; NSRunLoop *currentRunLoop = [NSRunLoop currentRunLoop]; - + BOOL isCancelled = [currentThread isCancelled]; - + while (!isCancelled && [currentRunLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) { isCancelled = [currentThread isCancelled]; } - + LogInfo(@"CFStreamThread: Stopped"); }} @@ -7691,12 +7701,12 @@ + (void)scheduleCFStreams:(GCDAsyncSocket *)asyncSocket { LogTrace(); NSAssert([NSThread currentThread] == cfstreamThread, @"Invoked on wrong thread"); - + CFRunLoopRef runLoop = CFRunLoopGetCurrent(); - + if (asyncSocket->readStream) CFReadStreamScheduleWithRunLoop(asyncSocket->readStream, runLoop, kCFRunLoopDefaultMode); - + if (asyncSocket->writeStream) CFWriteStreamScheduleWithRunLoop(asyncSocket->writeStream, runLoop, kCFRunLoopDefaultMode); } @@ -7705,12 +7715,12 @@ + (void)unscheduleCFStreams:(GCDAsyncSocket *)asyncSocket { LogTrace(); NSAssert([NSThread currentThread] == cfstreamThread, @"Invoked on wrong thread"); - + CFRunLoopRef runLoop = CFRunLoopGetCurrent(); - + if (asyncSocket->readStream) CFReadStreamUnscheduleFromRunLoop(asyncSocket->readStream, runLoop, kCFRunLoopDefaultMode); - + if (asyncSocket->writeStream) CFWriteStreamUnscheduleFromRunLoop(asyncSocket->writeStream, runLoop, kCFRunLoopDefaultMode); } @@ -7726,17 +7736,17 @@ static void CFReadStreamCallback (CFReadStreamRef stream, CFStreamEventType type case kCFStreamEventHasBytesAvailable: { dispatch_async(asyncSocket->socketQueue, ^{ @autoreleasepool { - + LogCVerbose(@"CFReadStreamCallback - HasBytesAvailable"); - + if (asyncSocket->readStream != stream) return_from_block; - + if ((asyncSocket->flags & kStartingReadTLS) && (asyncSocket->flags & kStartingWriteTLS)) { // If we set kCFStreamPropertySSLSettings before we opened the streams, this might be a lie. // (A callback related to the tcp stream, but not to the SSL layer). - + if (CFReadStreamHasBytesAvailable(asyncSocket->readStream)) { asyncSocket->flags |= kSecureSocketHasBytesAvailable; @@ -7749,25 +7759,25 @@ static void CFReadStreamCallback (CFReadStreamRef stream, CFStreamEventType type [asyncSocket doReadData]; } }}); - + break; } default: { NSError *error = (__bridge_transfer NSError *)CFReadStreamCopyError(stream); - + if (error == nil && type == kCFStreamEventEndEncountered) { error = [asyncSocket connectionClosedError]; } - + dispatch_async(asyncSocket->socketQueue, ^{ @autoreleasepool { - + LogCVerbose(@"CFReadStreamCallback - Other"); - + if (asyncSocket->readStream != stream) return_from_block; - + if ((asyncSocket->flags & kStartingReadTLS) && (asyncSocket->flags & kStartingWriteTLS)) { [asyncSocket cf_abortSSLHandshake:error]; @@ -7777,7 +7787,7 @@ static void CFReadStreamCallback (CFReadStreamRef stream, CFStreamEventType type [asyncSocket closeWithError:error]; } }}); - + break; } } @@ -7795,17 +7805,17 @@ static void CFWriteStreamCallback (CFWriteStreamRef stream, CFStreamEventType ty case kCFStreamEventCanAcceptBytes: { dispatch_async(asyncSocket->socketQueue, ^{ @autoreleasepool { - + LogCVerbose(@"CFWriteStreamCallback - CanAcceptBytes"); - + if (asyncSocket->writeStream != stream) return_from_block; - + if ((asyncSocket->flags & kStartingReadTLS) && (asyncSocket->flags & kStartingWriteTLS)) { // If we set kCFStreamPropertySSLSettings before we opened the streams, this might be a lie. // (A callback related to the tcp stream, but not to the SSL layer). - + if (CFWriteStreamCanAcceptBytes(asyncSocket->writeStream)) { asyncSocket->flags |= kSocketCanAcceptBytes; @@ -7818,25 +7828,25 @@ static void CFWriteStreamCallback (CFWriteStreamRef stream, CFStreamEventType ty [asyncSocket doWriteData]; } }}); - + break; } default: { NSError *error = (__bridge_transfer NSError *)CFWriteStreamCopyError(stream); - + if (error == nil && type == kCFStreamEventEndEncountered) { error = [asyncSocket connectionClosedError]; } - + dispatch_async(asyncSocket->socketQueue, ^{ @autoreleasepool { - + LogCVerbose(@"CFWriteStreamCallback - Other"); - + if (asyncSocket->writeStream != stream) return_from_block; - + if ((asyncSocket->flags & kStartingReadTLS) && (asyncSocket->flags & kStartingWriteTLS)) { [asyncSocket cf_abortSSLHandshake:error]; @@ -7846,7 +7856,7 @@ static void CFWriteStreamCallback (CFWriteStreamRef stream, CFStreamEventType ty [asyncSocket closeWithError:error]; } }}); - + break; } } @@ -7856,46 +7866,46 @@ static void CFWriteStreamCallback (CFWriteStreamRef stream, CFStreamEventType ty - (BOOL)createReadAndWriteStream { LogTrace(); - + NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - - + + if (readStream || writeStream) { // Streams already created return YES; } - + int socketFD = (socket4FD != SOCKET_NULL) ? socket4FD : (socket6FD != SOCKET_NULL) ? socket6FD : socketUN; - + if (socketFD == SOCKET_NULL) { // Cannot create streams without a file descriptor return NO; } - + if (![self isConnected]) { // Cannot create streams until file descriptor is connected return NO; } - + LogVerbose(@"Creating read and write stream..."); - + CFStreamCreatePairWithSocket(NULL, (CFSocketNativeHandle)socketFD, &readStream, &writeStream); - + // The kCFStreamPropertyShouldCloseNativeSocket property should be false by default (for our case). // But let's not take any chances. - + if (readStream) CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanFalse); if (writeStream) CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanFalse); - + if ((readStream == NULL) || (writeStream == NULL)) { LogWarn(@"Unable to create read and write stream..."); - + if (readStream) { CFReadStreamClose(readStream); @@ -7908,58 +7918,58 @@ - (BOOL)createReadAndWriteStream CFRelease(writeStream); writeStream = NULL; } - + return NO; } - + return YES; } - (BOOL)registerForStreamCallbacksIncludingReadWrite:(BOOL)includeReadWrite { LogVerbose(@"%@ %@", THIS_METHOD, (includeReadWrite ? @"YES" : @"NO")); - + NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); NSAssert((readStream != NULL && writeStream != NULL), @"Read/Write stream is null"); - + streamContext.version = 0; streamContext.info = (__bridge void *)(self); streamContext.retain = nil; streamContext.release = nil; streamContext.copyDescription = nil; - + CFOptionFlags readStreamEvents = kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered; if (includeReadWrite) readStreamEvents |= kCFStreamEventHasBytesAvailable; - + if (!CFReadStreamSetClient(readStream, readStreamEvents, &CFReadStreamCallback, &streamContext)) { return NO; } - + CFOptionFlags writeStreamEvents = kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered; if (includeReadWrite) writeStreamEvents |= kCFStreamEventCanAcceptBytes; - + if (!CFWriteStreamSetClient(writeStream, writeStreamEvents, &CFWriteStreamCallback, &streamContext)) { return NO; } - + return YES; } - (BOOL)addStreamsToRunLoop { LogTrace(); - + NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); NSAssert((readStream != NULL && writeStream != NULL), @"Read/Write stream is null"); - + if (!(flags & kAddedStreamsToRunLoop)) { LogVerbose(@"Adding streams to runloop..."); - + [[self class] startCFStreamThreadIfNeeded]; dispatch_sync(cfstreamThreadSetupQueue, ^{ [[self class] performSelector:@selector(scheduleCFStreams:) @@ -7969,21 +7979,21 @@ - (BOOL)addStreamsToRunLoop }); flags |= kAddedStreamsToRunLoop; } - + return YES; } - (void)removeStreamsFromRunLoop { LogTrace(); - + NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); NSAssert((readStream != NULL && writeStream != NULL), @"Read/Write stream is null"); - + if (flags & kAddedStreamsToRunLoop) { LogVerbose(@"Removing streams from runloop..."); - + dispatch_sync(cfstreamThreadSetupQueue, ^{ [[self class] performSelector:@selector(unscheduleCFStreams:) onThread:cfstreamThread @@ -7991,7 +8001,7 @@ - (void)removeStreamsFromRunLoop waitUntilDone:YES]; }); [[self class] stopCFStreamThreadIfNeeded]; - + flags &= ~kAddedStreamsToRunLoop; } } @@ -7999,27 +8009,27 @@ - (void)removeStreamsFromRunLoop - (BOOL)openStreams { LogTrace(); - + NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); NSAssert((readStream != NULL && writeStream != NULL), @"Read/Write stream is null"); - + CFStreamStatus readStatus = CFReadStreamGetStatus(readStream); CFStreamStatus writeStatus = CFWriteStreamGetStatus(writeStream); - + if ((readStatus == kCFStreamStatusNotOpen) || (writeStatus == kCFStreamStatusNotOpen)) { LogVerbose(@"Opening read and write stream..."); - + BOOL r1 = CFReadStreamOpen(readStream); BOOL r2 = CFWriteStreamOpen(writeStream); - + if (!r1 || !r2) { LogError(@"Error in CFStreamOpen"); return NO; } } - + return YES; } @@ -8035,7 +8045,7 @@ - (BOOL)openStreams - (BOOL)autoDisconnectOnClosedReadStream { // Note: YES means kAllowHalfDuplexConnection is OFF - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) { return ((config & kAllowHalfDuplexConnection) == 0); @@ -8043,11 +8053,11 @@ - (BOOL)autoDisconnectOnClosedReadStream else { __block BOOL result; - + dispatch_sync(socketQueue, ^{ result = ((self->config & kAllowHalfDuplexConnection) == 0); }); - + return result; } } @@ -8058,15 +8068,15 @@ - (BOOL)autoDisconnectOnClosedReadStream - (void)setAutoDisconnectOnClosedReadStream:(BOOL)flag { // Note: YES means kAllowHalfDuplexConnection is OFF - + dispatch_block_t block = ^{ - + if (flag) self->config &= ~kAllowHalfDuplexConnection; else self->config |= kAllowHalfDuplexConnection; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else @@ -8112,7 +8122,7 @@ - (int)socketFD LogWarn(@"%@ - Method only available from within the context of a performBlock: invocation", THIS_METHOD); return SOCKET_NULL; } - + if (socket4FD != SOCKET_NULL) return socket4FD; else @@ -8129,7 +8139,7 @@ - (int)socket4FD LogWarn(@"%@ - Method only available from within the context of a performBlock: invocation", THIS_METHOD); return SOCKET_NULL; } - + return socket4FD; } @@ -8143,7 +8153,7 @@ - (int)socket6FD LogWarn(@"%@ - Method only available from within the context of a performBlock: invocation", THIS_METHOD); return SOCKET_NULL; } - + return socket6FD; } @@ -8159,10 +8169,10 @@ - (CFReadStreamRef)readStream LogWarn(@"%@ - Method only available from within the context of a performBlock: invocation", THIS_METHOD); return NULL; } - + if (readStream == NULL) [self createReadAndWriteStream]; - + return readStream; } @@ -8176,10 +8186,10 @@ - (CFWriteStreamRef)writeStream LogWarn(@"%@ - Method only available from within the context of a performBlock: invocation", THIS_METHOD); return NULL; } - + if (writeStream == NULL) [self createReadAndWriteStream]; - + return writeStream; } @@ -8190,11 +8200,11 @@ - (BOOL)enableBackgroundingOnSocketWithCaveat:(BOOL)caveat // Error occurred creating streams (perhaps socket isn't open) return NO; } - + BOOL r1, r2; - + LogVerbose(@"Enabling backgrouding on socket"); - + #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" r1 = CFReadStreamSetProperty(readStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP); @@ -8205,7 +8215,7 @@ - (BOOL)enableBackgroundingOnSocketWithCaveat:(BOOL)caveat { return NO; } - + if (!caveat) { if (![self openStreams]) @@ -8213,7 +8223,7 @@ - (BOOL)enableBackgroundingOnSocketWithCaveat:(BOOL)caveat return NO; } } - + return YES; } @@ -8223,13 +8233,13 @@ - (BOOL)enableBackgroundingOnSocketWithCaveat:(BOOL)caveat - (BOOL)enableBackgroundingOnSocket { LogTrace(); - + if (!dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) { LogWarn(@"%@ - Method only available from within the context of a performBlock: invocation", THIS_METHOD); return NO; } - + return [self enableBackgroundingOnSocketWithCaveat:NO]; } @@ -8238,15 +8248,15 @@ - (BOOL)enableBackgroundingOnSocketWithCaveat // Deprecated in iOS 4.??? // This method was created as a workaround for a bug in iOS. // Apple has since fixed this bug. // I'm not entirely sure which version of iOS they fixed it in... - + LogTrace(); - + if (!dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) { LogWarn(@"%@ - Method only available from within the context of a performBlock: invocation", THIS_METHOD); return NO; } - + return [self enableBackgroundingOnSocketWithCaveat:YES]; } @@ -8259,7 +8269,7 @@ - (SSLContextRef)sslContext LogWarn(@"%@ - Method only available from within the context of a performBlock: invocation", THIS_METHOD); return NULL; } - + return sslContext; } @@ -8270,10 +8280,10 @@ - (SSLContextRef)sslContext + (NSMutableArray *)lookupHost:(NSString *)host port:(uint16_t)port error:(NSError **)errPtr { LogTrace(); - + NSMutableArray *addresses = nil; NSError *error = nil; - + if ([host isEqualToString:@"localhost"] || [host isEqualToString:@"loopback"]) { // Use LOOPBACK address @@ -8283,7 +8293,7 @@ + (NSMutableArray *)lookupHost:(NSString *)host port:(uint16_t)port error:(NSErr nativeAddr4.sin_port = htons(port); nativeAddr4.sin_addr.s_addr = htonl(INADDR_LOOPBACK); memset(&(nativeAddr4.sin_zero), 0, sizeof(nativeAddr4.sin_zero)); - + struct sockaddr_in6 nativeAddr6; nativeAddr6.sin6_len = sizeof(struct sockaddr_in6); nativeAddr6.sin6_family = AF_INET6; @@ -8291,12 +8301,12 @@ + (NSMutableArray *)lookupHost:(NSString *)host port:(uint16_t)port error:(NSErr nativeAddr6.sin6_flowinfo = 0; nativeAddr6.sin6_addr = in6addr_loopback; nativeAddr6.sin6_scope_id = 0; - + // Wrap the native address structures - + NSData *address4 = [NSData dataWithBytes:&nativeAddr4 length:sizeof(nativeAddr4)]; NSData *address6 = [NSData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)]; - + addresses = [NSMutableArray arrayWithCapacity:2]; [addresses addObject:address4]; [addresses addObject:address6]; @@ -8304,16 +8314,16 @@ + (NSMutableArray *)lookupHost:(NSString *)host port:(uint16_t)port error:(NSErr else { NSString *portStr = [NSString stringWithFormat:@"%hu", port]; - + struct addrinfo hints, *res, *res0; - + memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; - + int gai_error = getaddrinfo([host UTF8String], [portStr UTF8String], &hints, &res0); - + if (gai_error) { error = [self gaiError:gai_error]; @@ -8327,16 +8337,16 @@ + (NSMutableArray *)lookupHost:(NSString *)host port:(uint16_t)port error:(NSErr capacity++; } } - + addresses = [NSMutableArray arrayWithCapacity:capacity]; - + for (res = res0; res; res = res->ai_next) { if (res->ai_family == AF_INET) { // Found IPv4 address. // Wrap the native address structure, and add to results. - + NSData *address4 = [NSData dataWithBytes:res->ai_addr length:res->ai_addrlen]; [addresses addObject:address4]; } @@ -8344,10 +8354,10 @@ + (NSMutableArray *)lookupHost:(NSString *)host port:(uint16_t)port error:(NSErr { // Fixes connection issues with IPv6 // https://github.com/robbiehanson/CocoaAsyncSocket/issues/429#issuecomment-222477158 - + // Found IPv6 address. // Wrap the native address structure, and add to results. - + struct sockaddr_in6 *sockaddr = (struct sockaddr_in6 *)(void *)res->ai_addr; in_port_t *portPtr = &sockaddr->sin6_port; if ((portPtr != NULL) && (*portPtr == 0)) { @@ -8359,14 +8369,14 @@ + (NSMutableArray *)lookupHost:(NSString *)host port:(uint16_t)port error:(NSErr } } freeaddrinfo(res0); - + if ([addresses count] == 0) { error = [self gaiError:EAI_FAIL]; } } } - + if (errPtr) *errPtr = error; return addresses; } @@ -8374,24 +8384,24 @@ + (NSMutableArray *)lookupHost:(NSString *)host port:(uint16_t)port error:(NSErr + (NSString *)hostFromSockaddr4:(const struct sockaddr_in *)pSockaddr4 { char addrBuf[INET_ADDRSTRLEN]; - + if (inet_ntop(AF_INET, &pSockaddr4->sin_addr, addrBuf, (socklen_t)sizeof(addrBuf)) == NULL) { addrBuf[0] = '\0'; } - + return [NSString stringWithCString:addrBuf encoding:NSASCIIStringEncoding]; } + (NSString *)hostFromSockaddr6:(const struct sockaddr_in6 *)pSockaddr6 { char addrBuf[INET6_ADDRSTRLEN]; - + if (inet_ntop(AF_INET6, &pSockaddr6->sin6_addr, addrBuf, (socklen_t)sizeof(addrBuf)) == NULL) { addrBuf[0] = '\0'; } - + return [NSString stringWithCString:addrBuf encoding:NSASCIIStringEncoding]; } @@ -8414,7 +8424,7 @@ + (NSURL *)urlFromSockaddrUN:(const struct sockaddr_un *)pSockaddr + (NSString *)hostFromAddress:(NSData *)address { NSString *host; - + if ([self getHost:&host port:NULL fromAddress:address]) return host; else @@ -8424,7 +8434,7 @@ + (NSString *)hostFromAddress:(NSData *)address + (uint16_t)portFromAddress:(NSData *)address { uint16_t port; - + if ([self getHost:NULL port:&port fromAddress:address]) return port; else @@ -8436,12 +8446,12 @@ + (BOOL)isIPv4Address:(NSData *)address if ([address length] >= sizeof(struct sockaddr)) { const struct sockaddr *sockaddrX = [address bytes]; - + if (sockaddrX->sa_family == AF_INET) { return YES; } } - + return NO; } @@ -8450,12 +8460,12 @@ + (BOOL)isIPv6Address:(NSData *)address if ([address length] >= sizeof(struct sockaddr)) { const struct sockaddr *sockaddrX = [address bytes]; - + if (sockaddrX->sa_family == AF_INET6) { return YES; } } - + return NO; } @@ -8469,18 +8479,18 @@ + (BOOL)getHost:(NSString **)hostPtr port:(uint16_t *)portPtr family:(sa_family_ if ([address length] >= sizeof(struct sockaddr)) { const struct sockaddr *sockaddrX = [address bytes]; - + if (sockaddrX->sa_family == AF_INET) { if ([address length] >= sizeof(struct sockaddr_in)) { struct sockaddr_in sockaddr4; memcpy(&sockaddr4, sockaddrX, sizeof(sockaddr4)); - + if (hostPtr) *hostPtr = [self hostFromSockaddr4:&sockaddr4]; if (portPtr) *portPtr = [self portFromSockaddr4:&sockaddr4]; if (afPtr) *afPtr = AF_INET; - + return YES; } } @@ -8490,16 +8500,16 @@ + (BOOL)getHost:(NSString **)hostPtr port:(uint16_t *)portPtr family:(sa_family_ { struct sockaddr_in6 sockaddr6; memcpy(&sockaddr6, sockaddrX, sizeof(sockaddr6)); - + if (hostPtr) *hostPtr = [self hostFromSockaddr6:&sockaddr6]; if (portPtr) *portPtr = [self portFromSockaddr6:&sockaddr6]; if (afPtr) *afPtr = AF_INET6; - + return YES; } } } - + return NO; } @@ -8523,6 +8533,6 @@ + (NSData *)ZeroData return [NSData dataWithBytes:"" length:1]; } -@end +@end #pragma clang diagnostic pop diff --git a/WebDriverAgent/WebDriverAgentLib/Vendor/CocoaAsyncSocket/GCDAsyncUdpSocket.m b/WebDriverAgent/WebDriverAgentLib/Vendor/CocoaAsyncSocket/GCDAsyncUdpSocket.m old mode 100644 new mode 100755 index 8972caa62c..5f65f9717d --- a/WebDriverAgent/WebDriverAgentLib/Vendor/CocoaAsyncSocket/GCDAsyncUdpSocket.m +++ b/WebDriverAgent/WebDriverAgentLib/Vendor/CocoaAsyncSocket/GCDAsyncUdpSocket.m @@ -1,10 +1,10 @@ -// +// // GCDAsyncUdpSocket -// +// // This class is in the public domain. // Originally created by Robbie Hanson of Deusty LLC. // Updated and maintained by Deusty LLC and the Apple development community. -// +// // https://github.com/robbiehanson/CocoaAsyncSocket // @@ -16,8 +16,11 @@ #endif #if TARGET_OS_IPHONE - #import + #import #import + #import + // Note: CFStream APIs are still used for backgrounding support and are part of CoreFoundation + // kCFStreamPropertyShouldCloseNativeSocket is available from CoreFoundation/CFStream.h #endif #import @@ -37,7 +40,7 @@ // Logging uses the CocoaLumberjack framework (which is also GCD based). // https://github.com/robbiehanson/CocoaLumberjack -// +// // It allows us to do a lot of logging without significantly slowing down the code. #import "DDLog.h" @@ -99,7 +102,7 @@ /** * Just to type less code. **/ -#define AutoreleasedBlock(block) ^{ @autoreleasepool { block(); }} +#define AutoreleasedBlock(block) ^{ @autoreleasepool { block(); }} @class GCDAsyncUdpSendPacket; @@ -154,57 +157,57 @@ @interface GCDAsyncUdpSocket () __unsafe_unretained id delegate; #endif dispatch_queue_t delegateQueue; - + GCDAsyncUdpSocketReceiveFilterBlock receiveFilterBlock; dispatch_queue_t receiveFilterQueue; BOOL receiveFilterAsync; - + GCDAsyncUdpSocketSendFilterBlock sendFilterBlock; dispatch_queue_t sendFilterQueue; BOOL sendFilterAsync; - + uint32_t flags; uint16_t config; - + uint16_t max4ReceiveSize; uint32_t max6ReceiveSize; - + uint16_t maxSendSize; - + int socket4FD; int socket6FD; - + dispatch_queue_t socketQueue; - + dispatch_source_t send4Source; dispatch_source_t send6Source; dispatch_source_t receive4Source; dispatch_source_t receive6Source; dispatch_source_t sendTimer; - + GCDAsyncUdpSendPacket *currentSend; NSMutableArray *sendQueue; - + unsigned long socket4FDBytesAvailable; unsigned long socket6FDBytesAvailable; - + uint32_t pendingFilterOperations; - + NSData *cachedLocalAddress4; NSString *cachedLocalHost4; uint16_t cachedLocalPort4; - + NSData *cachedLocalAddress6; NSString *cachedLocalHost6; uint16_t cachedLocalPort6; - + NSData *cachedConnectedAddress; NSString *cachedConnectedHost; uint16_t cachedConnectedPort; int cachedConnectedFamily; - void *IsOnSocketQueueOrTargetQueueKey; - + void *IsOnSocketQueueOrTargetQueueKey; + #if TARGET_OS_IPHONE CFStreamClientContext streamContext; CFReadStreamRef readStream4; @@ -212,7 +215,7 @@ @interface GCDAsyncUdpSocket () CFWriteStreamRef writeStream4; CFWriteStreamRef writeStream6; #endif - + id userData; } @@ -272,13 +275,13 @@ @interface GCDAsyncUdpSendPacket : NSObject { NSData *buffer; NSTimeInterval timeout; long tag; - + BOOL resolveInProgress; BOOL filterInProgress; - + NSArray *resolvedAddresses; NSError *resolveError; - + NSData *address; int addressFamily; } @@ -303,7 +306,7 @@ - (instancetype)initWithData:(NSData *)d timeout:(NSTimeInterval)t tag:(long)i buffer = d; timeout = t; tag = i; - + resolveInProgress = NO; } return self; @@ -319,9 +322,9 @@ - (instancetype)initWithData:(NSData *)d timeout:(NSTimeInterval)t tag:(long)i @interface GCDAsyncUdpSpecialPacket : NSObject { @public // uint8_t type; - + BOOL resolveInProgress; - + NSArray *addresses; NSError *error; } @@ -350,32 +353,32 @@ @implementation GCDAsyncUdpSocket - (instancetype)init { LogTrace(); - + return [self initWithDelegate:nil delegateQueue:NULL socketQueue:NULL]; } - (instancetype)initWithSocketQueue:(dispatch_queue_t)sq { LogTrace(); - + return [self initWithDelegate:nil delegateQueue:NULL socketQueue:sq]; } - (instancetype)initWithDelegate:(id)aDelegate delegateQueue:(dispatch_queue_t)dq { LogTrace(); - + return [self initWithDelegate:aDelegate delegateQueue:dq socketQueue:NULL]; } - (instancetype)initWithDelegate:(id)aDelegate delegateQueue:(dispatch_queue_t)dq socketQueue:(dispatch_queue_t)sq { LogTrace(); - + if ((self = [super init])) { delegate = aDelegate; - + if (dq) { delegateQueue = dq; @@ -383,15 +386,15 @@ - (instancetype)initWithDelegate:(id)aDelegate delega dispatch_retain(delegateQueue); #endif } - + max4ReceiveSize = 65535; max6ReceiveSize = 65535; - + maxSendSize = 65535; - + socket4FD = SOCKET_NULL; socket6FD = SOCKET_NULL; - + if (sq) { NSAssert(sq != dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), @@ -400,7 +403,7 @@ - (instancetype)initWithDelegate:(id)aDelegate delega @"The given socketQueue parameter must not be a concurrent queue."); NSAssert(sq != dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), @"The given socketQueue parameter must not be a concurrent queue."); - + socketQueue = sq; #if !OS_OBJECT_USE_OBJC dispatch_retain(socketQueue); @@ -432,10 +435,10 @@ - (instancetype)initWithDelegate:(id)aDelegate delega void *nonNullUnusedPointer = (__bridge void *)self; dispatch_queue_set_specific(socketQueue, IsOnSocketQueueOrTargetQueueKey, nonNullUnusedPointer, NULL); - + currentSend = nil; sendQueue = [[NSMutableArray alloc] initWithCapacity:5]; - + #if TARGET_OS_IPHONE [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground:) @@ -449,11 +452,11 @@ - (instancetype)initWithDelegate:(id)aDelegate delega - (void)dealloc { LogInfo(@"%@ - %@ (start)", THIS_METHOD, self); - + #if TARGET_OS_IPHONE [[NSNotificationCenter defaultCenter] removeObserver:self]; #endif - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) { [self closeWithError:nil]; @@ -464,18 +467,18 @@ - (void)dealloc [self closeWithError:nil]; }); } - + delegate = nil; #if !OS_OBJECT_USE_OBJC if (delegateQueue) dispatch_release(delegateQueue); #endif delegateQueue = NULL; - + #if !OS_OBJECT_USE_OBJC if (socketQueue) dispatch_release(socketQueue); #endif socketQueue = NULL; - + LogInfo(@"%@ - %@ (finish)", THIS_METHOD, self); } @@ -492,11 +495,11 @@ - (void)dealloc else { __block id result = nil; - + dispatch_sync(socketQueue, ^{ result = self->delegate; }); - + return result; } } @@ -506,7 +509,7 @@ - (void)setDelegate:(id)newDelegate synchronously:(BO dispatch_block_t block = ^{ self->delegate = newDelegate; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) { block(); } @@ -537,11 +540,11 @@ - (dispatch_queue_t)delegateQueue else { __block dispatch_queue_t result = NULL; - + dispatch_sync(socketQueue, ^{ result = self->delegateQueue; }); - + return result; } } @@ -549,15 +552,15 @@ - (dispatch_queue_t)delegateQueue - (void)setDelegateQueue:(dispatch_queue_t)newDelegateQueue synchronously:(BOOL)synchronously { dispatch_block_t block = ^{ - + #if !OS_OBJECT_USE_OBJC if (self->delegateQueue) dispatch_release(self->delegateQueue); if (newDelegateQueue) dispatch_retain(newDelegateQueue); #endif - + self->delegateQueue = newDelegateQueue; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) { block(); } @@ -590,12 +593,12 @@ - (void)getDelegate:(id *)delegatePtr delegateQueue:( { __block id dPtr = NULL; __block dispatch_queue_t dqPtr = NULL; - + dispatch_sync(socketQueue, ^{ dPtr = self->delegate; dqPtr = self->delegateQueue; }); - + if (delegatePtr) *delegatePtr = dPtr; if (delegateQueuePtr) *delegateQueuePtr = dqPtr; } @@ -604,17 +607,17 @@ - (void)getDelegate:(id *)delegatePtr delegateQueue:( - (void)setDelegate:(id)newDelegate delegateQueue:(dispatch_queue_t)newDelegateQueue synchronously:(BOOL)synchronously { dispatch_block_t block = ^{ - + self->delegate = newDelegate; - + #if !OS_OBJECT_USE_OBJC if (self->delegateQueue) dispatch_release(self->delegateQueue); if (newDelegateQueue) dispatch_retain(newDelegateQueue); #endif - + self->delegateQueue = newDelegateQueue; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) { block(); } @@ -639,36 +642,36 @@ - (void)synchronouslySetDelegate:(id)newDelegate dele - (BOOL)isIPv4Enabled { // Note: YES means kIPv4Disabled is OFF - + __block BOOL result = NO; - + dispatch_block_t block = ^{ - + result = ((self->config & kIPv4Disabled) == 0); }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + return result; } - (void)setIPv4Enabled:(BOOL)flag { // Note: YES means kIPv4Disabled is OFF - + dispatch_block_t block = ^{ - + LogVerbose(@"%@ %@", THIS_METHOD, (flag ? @"YES" : @"NO")); - + if (flag) self->config &= ~kIPv4Disabled; else self->config |= kIPv4Disabled; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else @@ -678,36 +681,36 @@ - (void)setIPv4Enabled:(BOOL)flag - (BOOL)isIPv6Enabled { // Note: YES means kIPv6Disabled is OFF - + __block BOOL result = NO; - + dispatch_block_t block = ^{ - + result = ((self->config & kIPv6Disabled) == 0); }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + return result; } - (void)setIPv6Enabled:(BOOL)flag { // Note: YES means kIPv6Disabled is OFF - + dispatch_block_t block = ^{ - + LogVerbose(@"%@ %@", THIS_METHOD, (flag ? @"YES" : @"NO")); - + if (flag) self->config &= ~kIPv6Disabled; else self->config |= kIPv6Disabled; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else @@ -717,62 +720,62 @@ - (void)setIPv6Enabled:(BOOL)flag - (BOOL)isIPv4Preferred { __block BOOL result = NO; - + dispatch_block_t block = ^{ result = (self->config & kPreferIPv4) ? YES : NO; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + return result; } - (BOOL)isIPv6Preferred { __block BOOL result = NO; - + dispatch_block_t block = ^{ result = (self->config & kPreferIPv6) ? YES : NO; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + return result; } - (BOOL)isIPVersionNeutral { __block BOOL result = NO; - + dispatch_block_t block = ^{ result = (self->config & (kPreferIPv4 | kPreferIPv6)) == 0; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + return result; } - (void)setPreferIPv4 { dispatch_block_t block = ^{ - + LogTrace(); - + self->config |= kPreferIPv4; self->config &= ~kPreferIPv6; - + }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else @@ -782,14 +785,14 @@ - (void)setPreferIPv4 - (void)setPreferIPv6 { dispatch_block_t block = ^{ - + LogTrace(); - + self->config &= ~kPreferIPv4; self->config |= kPreferIPv6; - + }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else @@ -799,14 +802,14 @@ - (void)setPreferIPv6 - (void)setIPVersionNeutral { dispatch_block_t block = ^{ - + LogTrace(); - + self->config &= ~kPreferIPv4; self->config &= ~kPreferIPv6; - + }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else @@ -816,29 +819,29 @@ - (void)setIPVersionNeutral - (uint16_t)maxReceiveIPv4BufferSize { __block uint16_t result = 0; - + dispatch_block_t block = ^{ - + result = self->max4ReceiveSize; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + return result; } - (void)setMaxReceiveIPv4BufferSize:(uint16_t)max { dispatch_block_t block = ^{ - + LogVerbose(@"%@ %u", THIS_METHOD, (unsigned)max); - + self->max4ReceiveSize = max; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else @@ -848,29 +851,29 @@ - (void)setMaxReceiveIPv4BufferSize:(uint16_t)max - (uint32_t)maxReceiveIPv6BufferSize { __block uint32_t result = 0; - + dispatch_block_t block = ^{ - + result = self->max6ReceiveSize; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + return result; } - (void)setMaxReceiveIPv6BufferSize:(uint32_t)max { dispatch_block_t block = ^{ - + LogVerbose(@"%@ %u", THIS_METHOD, (unsigned)max); - + self->max6ReceiveSize = max; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else @@ -880,12 +883,12 @@ - (void)setMaxReceiveIPv6BufferSize:(uint32_t)max - (void)setMaxSendBufferSize:(uint16_t)max { dispatch_block_t block = ^{ - + LogVerbose(@"%@ %u", THIS_METHOD, (unsigned)max); - + self->maxSendSize = max; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else @@ -895,47 +898,47 @@ - (void)setMaxSendBufferSize:(uint16_t)max - (uint16_t)maxSendBufferSize { __block uint16_t result = 0; - + dispatch_block_t block = ^{ - + result = self->maxSendSize; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + return result; } - (id)userData { __block id result = nil; - + dispatch_block_t block = ^{ - + result = self->userData; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + return result; } - (void)setUserData:(id)arbitraryUserData { dispatch_block_t block = ^{ - + if (self->userData != arbitraryUserData) { self->userData = arbitraryUserData; } }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else @@ -949,14 +952,14 @@ - (void)setUserData:(id)arbitraryUserData - (void)notifyDidConnectToAddress:(NSData *)anAddress { LogTrace(); - + __strong id theDelegate = delegate; if (delegateQueue && [theDelegate respondsToSelector:@selector(udpSocket:didConnectToAddress:)]) { NSData *address = [anAddress copy]; // In case param is NSMutableData - + dispatch_async(delegateQueue, ^{ @autoreleasepool { - + [theDelegate udpSocket:self didConnectToAddress:address]; }}); } @@ -965,12 +968,12 @@ - (void)notifyDidConnectToAddress:(NSData *)anAddress - (void)notifyDidNotConnect:(NSError *)error { LogTrace(); - + __strong id theDelegate = delegate; if (delegateQueue && [theDelegate respondsToSelector:@selector(udpSocket:didNotConnect:)]) { dispatch_async(delegateQueue, ^{ @autoreleasepool { - + [theDelegate udpSocket:self didNotConnect:error]; }}); } @@ -979,12 +982,12 @@ - (void)notifyDidNotConnect:(NSError *)error - (void)notifyDidSendDataWithTag:(long)tag { LogTrace(); - + __strong id theDelegate = delegate; if (delegateQueue && [theDelegate respondsToSelector:@selector(udpSocket:didSendDataWithTag:)]) { dispatch_async(delegateQueue, ^{ @autoreleasepool { - + [theDelegate udpSocket:self didSendDataWithTag:tag]; }}); } @@ -993,12 +996,12 @@ - (void)notifyDidSendDataWithTag:(long)tag - (void)notifyDidNotSendDataWithTag:(long)tag dueToError:(NSError *)error { LogTrace(); - + __strong id theDelegate = delegate; if (delegateQueue && [theDelegate respondsToSelector:@selector(udpSocket:didNotSendDataWithTag:dueToError:)]) { dispatch_async(delegateQueue, ^{ @autoreleasepool { - + [theDelegate udpSocket:self didNotSendDataWithTag:tag dueToError:error]; }}); } @@ -1007,14 +1010,14 @@ - (void)notifyDidNotSendDataWithTag:(long)tag dueToError:(NSError *)error - (void)notifyDidReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)context { LogTrace(); - + SEL selector = @selector(udpSocket:didReceiveData:fromAddress:withFilterContext:); - + __strong id theDelegate = delegate; if (delegateQueue && [theDelegate respondsToSelector:selector]) { dispatch_async(delegateQueue, ^{ @autoreleasepool { - + [theDelegate udpSocket:self didReceiveData:data fromAddress:address withFilterContext:context]; }}); } @@ -1023,12 +1026,12 @@ - (void)notifyDidReceiveData:(NSData *)data fromAddress:(NSData *)address withFi - (void)notifyDidCloseWithError:(NSError *)error { LogTrace(); - + __strong id theDelegate = delegate; if (delegateQueue && [theDelegate respondsToSelector:@selector(udpSocketDidClose:withError:)]) { dispatch_async(delegateQueue, ^{ @autoreleasepool { - + [theDelegate udpSocketDidClose:self withError:error]; }}); } @@ -1041,7 +1044,7 @@ - (void)notifyDidCloseWithError:(NSError *)error - (NSError *)badConfigError:(NSString *)errMsg { NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg}; - + return [NSError errorWithDomain:GCDAsyncUdpSocketErrorDomain code:GCDAsyncUdpSocketBadConfigError userInfo:userInfo]; @@ -1050,7 +1053,7 @@ - (NSError *)badConfigError:(NSString *)errMsg - (NSError *)badParamError:(NSString *)errMsg { NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg}; - + return [NSError errorWithDomain:GCDAsyncUdpSocketErrorDomain code:GCDAsyncUdpSocketBadParamError userInfo:userInfo]; @@ -1060,7 +1063,7 @@ - (NSError *)gaiError:(int)gai_error { NSString *errMsg = [NSString stringWithCString:gai_strerror(gai_error) encoding:NSASCIIStringEncoding]; NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg}; - + return [NSError errorWithDomain:@"kCFStreamErrorDomainNetDB" code:gai_error userInfo:userInfo]; } @@ -1068,13 +1071,13 @@ - (NSError *)errnoErrorWithReason:(NSString *)reason { NSString *errMsg = [NSString stringWithUTF8String:strerror(errno)]; NSDictionary *userInfo; - + if (reason) userInfo = @{NSLocalizedDescriptionKey : errMsg, NSLocalizedFailureReasonErrorKey : reason}; else userInfo = @{NSLocalizedDescriptionKey : errMsg}; - + return [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:userInfo]; } @@ -1091,9 +1094,9 @@ - (NSError *)sendTimeoutError NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncUdpSocketSendTimeoutError", @"GCDAsyncUdpSocket", [NSBundle mainBundle], @"Send operation timed out", nil); - + NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg}; - + return [NSError errorWithDomain:GCDAsyncUdpSocketErrorDomain code:GCDAsyncUdpSocketSendTimeoutError userInfo:userInfo]; @@ -1104,16 +1107,16 @@ - (NSError *)socketClosedError NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncUdpSocketClosedError", @"GCDAsyncUdpSocket", [NSBundle mainBundle], @"Socket closed", nil); - + NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg}; - + return [NSError errorWithDomain:GCDAsyncUdpSocketErrorDomain code:GCDAsyncUdpSocketClosedError userInfo:userInfo]; } - (NSError *)otherError:(NSString *)errMsg { NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg}; - + return [NSError errorWithDomain:GCDAsyncUdpSocketErrorDomain code:GCDAsyncUdpSocketOtherError userInfo:userInfo]; @@ -1126,7 +1129,7 @@ - (NSError *)otherError:(NSString *)errMsg - (BOOL)preOp:(NSError **)errPtr { NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - + if (delegate == nil) // Must have delegate set { if (errPtr) @@ -1136,7 +1139,7 @@ - (BOOL)preOp:(NSError **)errPtr } return NO; } - + if (delegateQueue == NULL) // Must have delegate queue set { if (errPtr) @@ -1146,7 +1149,7 @@ - (BOOL)preOp:(NSError **)errPtr } return NO; } - + return YES; } @@ -1159,56 +1162,56 @@ - (void)asyncResolveHost:(NSString *)aHost withCompletionBlock:(void (^)(NSArray *addresses, NSError *error))completionBlock { LogTrace(); - + // Check parameter(s) - + if (aHost == nil) { NSString *msg = @"The host param is nil. Should be domain name or IP address string."; NSError *error = [self badParamError:msg]; - + // We should still use dispatch_async since this method is expected to be asynchronous - + dispatch_async(socketQueue, ^{ @autoreleasepool { - + completionBlock(nil, error); }}); - + return; } - + // It's possible that the given aHost parameter is actually a NSMutableString. // So we want to copy it now, within this block that will be executed synchronously. // This way the asynchronous lookup block below doesn't have to worry about it changing. - + NSString *host = [aHost copy]; - - + + dispatch_queue_t globalConcurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(globalConcurrentQueue, ^{ @autoreleasepool { - + NSMutableArray *addresses = [NSMutableArray arrayWithCapacity:2]; NSError *error = nil; - + if ([host isEqualToString:@"localhost"] || [host isEqualToString:@"loopback"]) { // Use LOOPBACK address struct sockaddr_in sockaddr4; memset(&sockaddr4, 0, sizeof(sockaddr4)); - + sockaddr4.sin_len = sizeof(struct sockaddr_in); sockaddr4.sin_family = AF_INET; sockaddr4.sin_port = htons(port); sockaddr4.sin_addr.s_addr = htonl(INADDR_LOOPBACK); - + struct sockaddr_in6 sockaddr6; memset(&sockaddr6, 0, sizeof(sockaddr6)); - + sockaddr6.sin6_len = sizeof(struct sockaddr_in6); sockaddr6.sin6_family = AF_INET6; sockaddr6.sin6_port = htons(port); sockaddr6.sin6_addr = in6addr_loopback; - + // Wrap the native address structures and add to list [addresses addObject:[NSData dataWithBytes:&sockaddr4 length:sizeof(sockaddr4)]]; [addresses addObject:[NSData dataWithBytes:&sockaddr6 length:sizeof(sockaddr6)]]; @@ -1216,16 +1219,16 @@ - (void)asyncResolveHost:(NSString *)aHost else { NSString *portStr = [NSString stringWithFormat:@"%hu", port]; - + struct addrinfo hints, *res, *res0; - + memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_UDP; - + int gai_error = getaddrinfo([host UTF8String], [portStr UTF8String], &hints, &res0); - + if (gai_error) { error = [self gaiError:gai_error]; @@ -1238,7 +1241,7 @@ - (void)asyncResolveHost:(NSString *)aHost { // Found IPv4 address // Wrap the native address structure and add to list - + [addresses addObject:[NSData dataWithBytes:res->ai_addr length:res->ai_addrlen]]; } else if (res->ai_family == AF_INET6) @@ -1258,26 +1261,26 @@ - (void)asyncResolveHost:(NSString *)aHost } } freeaddrinfo(res0); - + if ([addresses count] == 0) { error = [self gaiError:EAI_FAIL]; } } } - + dispatch_async(self->socketQueue, ^{ @autoreleasepool { - + completionBlock(addresses, error); }}); - + }}); } /** * This method picks an address from the given list of addresses. * The address picked depends upon which protocols are disabled, deactived, & preferred. - * + * * Returns the address family (AF_INET or AF_INET6) of the picked address, * or AF_UNSPEC and the corresponding error is there's a problem. **/ @@ -1285,93 +1288,93 @@ - (int)getAddress:(NSData **)addressPtr error:(NSError **)errorPtr fromAddresses { NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); NSAssert([addresses count] > 0, @"Expected at least one address"); - + int resultAF = AF_UNSPEC; NSData *resultAddress = nil; NSError *resultError = nil; - + // Check for problems - + BOOL resolvedIPv4Address = NO; BOOL resolvedIPv6Address = NO; - + for (NSData *address in addresses) { switch ([[self class] familyFromAddress:address]) { case AF_INET : resolvedIPv4Address = YES; break; case AF_INET6 : resolvedIPv6Address = YES; break; - + default : NSAssert(NO, @"Addresses array contains invalid address"); } } - + BOOL isIPv4Disabled = (config & kIPv4Disabled) ? YES : NO; BOOL isIPv6Disabled = (config & kIPv6Disabled) ? YES : NO; - + if (isIPv4Disabled && !resolvedIPv6Address) { NSString *msg = @"IPv4 has been disabled and DNS lookup found no IPv6 address(es)."; resultError = [self otherError:msg]; - + if (addressPtr) *addressPtr = resultAddress; if (errorPtr) *errorPtr = resultError; - + return resultAF; } - + if (isIPv6Disabled && !resolvedIPv4Address) { NSString *msg = @"IPv6 has been disabled and DNS lookup found no IPv4 address(es)."; resultError = [self otherError:msg]; - + if (addressPtr) *addressPtr = resultAddress; if (errorPtr) *errorPtr = resultError; - + return resultAF; } - + BOOL isIPv4Deactivated = (flags & kIPv4Deactivated) ? YES : NO; BOOL isIPv6Deactivated = (flags & kIPv6Deactivated) ? YES : NO; - + if (isIPv4Deactivated && !resolvedIPv6Address) { NSString *msg = @"IPv4 has been deactivated due to bind/connect, and DNS lookup found no IPv6 address(es)."; resultError = [self otherError:msg]; - + if (addressPtr) *addressPtr = resultAddress; if (errorPtr) *errorPtr = resultError; - + return resultAF; } - + if (isIPv6Deactivated && !resolvedIPv4Address) { NSString *msg = @"IPv6 has been deactivated due to bind/connect, and DNS lookup found no IPv4 address(es)."; resultError = [self otherError:msg]; - + if (addressPtr) *addressPtr = resultAddress; if (errorPtr) *errorPtr = resultError; - + return resultAF; } - + // Extract first IPv4 and IPv6 address in list - + BOOL ipv4WasFirstInList = YES; NSData *address4 = nil; NSData *address6 = nil; - + for (NSData *address in addresses) { int af = [[self class] familyFromAddress:address]; - + if (af == AF_INET) { if (address4 == nil) { address4 = address; - + if (address6) break; else @@ -1383,7 +1386,7 @@ - (int)getAddress:(NSData **)addressPtr error:(NSError **)errorPtr fromAddresses if (address6 == nil) { address6 = address; - + if (address4) break; else @@ -1391,18 +1394,18 @@ - (int)getAddress:(NSData **)addressPtr error:(NSError **)errorPtr fromAddresses } } } - + // Determine socket type - + BOOL preferIPv4 = (config & kPreferIPv4) ? YES : NO; BOOL preferIPv6 = (config & kPreferIPv6) ? YES : NO; - + BOOL useIPv4 = ((preferIPv4 && address4) || (address6 == nil)); BOOL useIPv6 = ((preferIPv6 && address6) || (address4 == nil)); - + NSAssert(!(preferIPv4 && preferIPv6), @"Invalid config state"); NSAssert(!(useIPv4 && useIPv6), @"Invalid logic"); - + if (useIPv4 || (!useIPv6 && ipv4WasFirstInList)) { resultAF = AF_INET; @@ -1413,10 +1416,10 @@ - (int)getAddress:(NSData **)addressPtr error:(NSError **)errorPtr fromAddresses resultAF = AF_INET6; resultAddress = address6; } - + if (addressPtr) *addressPtr = resultAddress; if (errorPtr) *errorPtr = resultError; - + return resultAF; } @@ -1431,27 +1434,27 @@ - (void)convertIntefaceDescription:(NSString *)interfaceDescription { NSData *addr4 = nil; NSData *addr6 = nil; - + if (interfaceDescription == nil) { // ANY address - + struct sockaddr_in sockaddr4; memset(&sockaddr4, 0, sizeof(sockaddr4)); - + sockaddr4.sin_len = sizeof(sockaddr4); sockaddr4.sin_family = AF_INET; sockaddr4.sin_port = htons(port); sockaddr4.sin_addr.s_addr = htonl(INADDR_ANY); - + struct sockaddr_in6 sockaddr6; memset(&sockaddr6, 0, sizeof(sockaddr6)); - + sockaddr6.sin6_len = sizeof(sockaddr6); sockaddr6.sin6_family = AF_INET6; sockaddr6.sin6_port = htons(port); sockaddr6.sin6_addr = in6addr_any; - + addr4 = [NSData dataWithBytes:&sockaddr4 length:sizeof(sockaddr4)]; addr6 = [NSData dataWithBytes:&sockaddr6 length:sizeof(sockaddr6)]; } @@ -1459,33 +1462,33 @@ - (void)convertIntefaceDescription:(NSString *)interfaceDescription [interfaceDescription isEqualToString:@"loopback"]) { // LOOPBACK address - + struct sockaddr_in sockaddr4; memset(&sockaddr4, 0, sizeof(sockaddr4)); - + sockaddr4.sin_len = sizeof(struct sockaddr_in); sockaddr4.sin_family = AF_INET; sockaddr4.sin_port = htons(port); sockaddr4.sin_addr.s_addr = htonl(INADDR_LOOPBACK); - + struct sockaddr_in6 sockaddr6; memset(&sockaddr6, 0, sizeof(sockaddr6)); - + sockaddr6.sin6_len = sizeof(struct sockaddr_in6); sockaddr6.sin6_family = AF_INET6; sockaddr6.sin6_port = htons(port); sockaddr6.sin6_addr = in6addr_loopback; - + addr4 = [NSData dataWithBytes:&sockaddr4 length:sizeof(sockaddr4)]; addr6 = [NSData dataWithBytes:&sockaddr6 length:sizeof(sockaddr6)]; } else { const char *iface = [interfaceDescription UTF8String]; - + struct ifaddrs *addrs; const struct ifaddrs *cursor; - + if ((getifaddrs(&addrs) == 0)) { cursor = addrs; @@ -1494,32 +1497,32 @@ - (void)convertIntefaceDescription:(NSString *)interfaceDescription if ((addr4 == nil) && (cursor->ifa_addr->sa_family == AF_INET)) { // IPv4 - + struct sockaddr_in *addr = (struct sockaddr_in *)(void *)cursor->ifa_addr; - + if (strcmp(cursor->ifa_name, iface) == 0) { // Name match - + struct sockaddr_in nativeAddr4 = *addr; nativeAddr4.sin_port = htons(port); - + addr4 = [NSData dataWithBytes:&nativeAddr4 length:sizeof(nativeAddr4)]; } else { char ip[INET_ADDRSTRLEN]; - + const char *conversion; conversion = inet_ntop(AF_INET, &addr->sin_addr, ip, sizeof(ip)); - + if ((conversion != NULL) && (strcmp(ip, iface) == 0)) { // IP match - + struct sockaddr_in nativeAddr4 = *addr; nativeAddr4.sin_port = htons(port); - + addr4 = [NSData dataWithBytes:&nativeAddr4 length:sizeof(nativeAddr4)]; } } @@ -1527,44 +1530,44 @@ - (void)convertIntefaceDescription:(NSString *)interfaceDescription else if ((addr6 == nil) && (cursor->ifa_addr->sa_family == AF_INET6)) { // IPv6 - + const struct sockaddr_in6 *addr = (const struct sockaddr_in6 *)(const void *)cursor->ifa_addr; - + if (strcmp(cursor->ifa_name, iface) == 0) { // Name match - + struct sockaddr_in6 nativeAddr6 = *addr; nativeAddr6.sin6_port = htons(port); - + addr6 = [NSData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)]; } else { char ip[INET6_ADDRSTRLEN]; - + const char *conversion; conversion = inet_ntop(AF_INET6, &addr->sin6_addr, ip, sizeof(ip)); - + if ((conversion != NULL) && (strcmp(ip, iface) == 0)) { // IP match - + struct sockaddr_in6 nativeAddr6 = *addr; nativeAddr6.sin6_port = htons(port); - + addr6 = [NSData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)]; } } } - + cursor = cursor->ifa_next; } - + freeifaddrs(addrs); } } - + if (interfaceAddr4Ptr) *interfaceAddr4Ptr = addr4; if (interfaceAddr6Ptr) *interfaceAddr6Ptr = addr6; } @@ -1580,19 +1583,19 @@ - (void)convertNumericHost:(NSString *)numericHost { NSData *addr4 = nil; NSData *addr6 = nil; - + if (numericHost) { NSString *portStr = [NSString stringWithFormat:@"%hu", port]; - + struct addrinfo hints, *res, *res0; - + memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_UDP; hints.ai_flags = AI_NUMERICHOST; // No name resolution should be attempted - + if (getaddrinfo([numericHost UTF8String], [portStr UTF8String], &hints, &res0) == 0) { for (res = res0; res; res = res->ai_next) @@ -1613,7 +1616,7 @@ - (void)convertNumericHost:(NSString *)numericHost freeaddrinfo(res0); } } - + if (addr4Ptr) *addr4Ptr = addr4; if (addr6Ptr) *addr6Ptr = addr6; } @@ -1623,15 +1626,15 @@ - (BOOL)isConnectedToAddress4:(NSData *)someAddr4 NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); NSAssert(flags & kDidConnect, @"Not connected"); NSAssert(cachedConnectedAddress, @"Expected cached connected address"); - + if (cachedConnectedFamily != AF_INET) { return NO; } - + const struct sockaddr_in *sSockaddr4 = (const struct sockaddr_in *)[someAddr4 bytes]; const struct sockaddr_in *cSockaddr4 = (const struct sockaddr_in *)[cachedConnectedAddress bytes]; - + if (memcmp(&sSockaddr4->sin_addr, &cSockaddr4->sin_addr, sizeof(struct in_addr)) != 0) { return NO; @@ -1640,7 +1643,7 @@ - (BOOL)isConnectedToAddress4:(NSData *)someAddr4 { return NO; } - + return YES; } @@ -1649,15 +1652,15 @@ - (BOOL)isConnectedToAddress6:(NSData *)someAddr6 NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); NSAssert(flags & kDidConnect, @"Not connected"); NSAssert(cachedConnectedAddress, @"Expected cached connected address"); - + if (cachedConnectedFamily != AF_INET6) { return NO; } - + const struct sockaddr_in6 *sSockaddr6 = (const struct sockaddr_in6 *)[someAddr6 bytes]; const struct sockaddr_in6 *cSockaddr6 = (const struct sockaddr_in6 *)[cachedConnectedAddress bytes]; - + if (memcmp(&sSockaddr6->sin6_addr, &cSockaddr6->sin6_addr, sizeof(struct in6_addr)) != 0) { return NO; @@ -1666,7 +1669,7 @@ - (BOOL)isConnectedToAddress6:(NSData *)someAddr6 { return NO; } - + return YES; } @@ -1676,13 +1679,13 @@ - (unsigned int)indexOfInterfaceAddr4:(NSData *)interfaceAddr4 return 0; if ([interfaceAddr4 length] != sizeof(struct sockaddr_in)) return 0; - + int result = 0; const struct sockaddr_in *ifaceAddr = (const struct sockaddr_in *)[interfaceAddr4 bytes]; - + struct ifaddrs *addrs; const struct ifaddrs *cursor; - + if ((getifaddrs(&addrs) == 0)) { cursor = addrs; @@ -1691,22 +1694,22 @@ - (unsigned int)indexOfInterfaceAddr4:(NSData *)interfaceAddr4 if (cursor->ifa_addr->sa_family == AF_INET) { // IPv4 - + const struct sockaddr_in *addr = (const struct sockaddr_in *)(const void *)cursor->ifa_addr; - + if (memcmp(&addr->sin_addr, &ifaceAddr->sin_addr, sizeof(struct in_addr)) == 0) { result = if_nametoindex(cursor->ifa_name); break; } } - + cursor = cursor->ifa_next; } - + freeifaddrs(addrs); } - + return result; } @@ -1716,13 +1719,13 @@ - (unsigned int)indexOfInterfaceAddr6:(NSData *)interfaceAddr6 return 0; if ([interfaceAddr6 length] != sizeof(struct sockaddr_in6)) return 0; - + int result = 0; const struct sockaddr_in6 *ifaceAddr = (const struct sockaddr_in6 *)[interfaceAddr6 bytes]; - + struct ifaddrs *addrs; const struct ifaddrs *cursor; - + if ((getifaddrs(&addrs) == 0)) { cursor = addrs; @@ -1731,22 +1734,22 @@ - (unsigned int)indexOfInterfaceAddr6:(NSData *)interfaceAddr6 if (cursor->ifa_addr->sa_family == AF_INET6) { // IPv6 - + const struct sockaddr_in6 *addr = (const struct sockaddr_in6 *)(const void *)cursor->ifa_addr; - + if (memcmp(&addr->sin6_addr, &ifaceAddr->sin6_addr, sizeof(struct in6_addr)) == 0) { result = if_nametoindex(cursor->ifa_name); break; } } - + cursor = cursor->ifa_next; } - + freeifaddrs(addrs); } - + return result; } @@ -1754,22 +1757,22 @@ - (void)setupSendAndReceiveSourcesForSocket4 { LogTrace(); NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - + send4Source = dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE, socket4FD, 0, socketQueue); receive4Source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, socket4FD, 0, socketQueue); - + // Setup event handlers - + dispatch_source_set_event_handler(send4Source, ^{ @autoreleasepool { - + LogVerbose(@"send4EventBlock"); LogVerbose(@"dispatch_source_get_data(send4Source) = %lu", dispatch_source_get_data(send4Source)); - + self->flags |= kSock4CanAcceptBytes; - + // If we're ready to send data, do so immediately. // Otherwise pause the send source or it will continue to fire over and over again. - + if (self->currentSend == nil) { LogVerbose(@"Nothing to send"); @@ -1789,74 +1792,74 @@ - (void)setupSendAndReceiveSourcesForSocket4 { [self doSend]; } - + }}); - + dispatch_source_set_event_handler(receive4Source, ^{ @autoreleasepool { - + LogVerbose(@"receive4EventBlock"); - + self->socket4FDBytesAvailable = dispatch_source_get_data(self->receive4Source); LogVerbose(@"socket4FDBytesAvailable: %lu", socket4FDBytesAvailable); - + if (self->socket4FDBytesAvailable > 0) [self doReceive]; else [self doReceiveEOF]; - + }}); - + // Setup cancel handlers - + __block int socketFDRefCount = 2; - + int theSocketFD = socket4FD; - + #if !OS_OBJECT_USE_OBJC dispatch_source_t theSendSource = send4Source; dispatch_source_t theReceiveSource = receive4Source; #endif - + dispatch_source_set_cancel_handler(send4Source, ^{ - + LogVerbose(@"send4CancelBlock"); - + #if !OS_OBJECT_USE_OBJC LogVerbose(@"dispatch_release(send4Source)"); dispatch_release(theSendSource); #endif - + if (--socketFDRefCount == 0) { LogVerbose(@"close(socket4FD)"); close(theSocketFD); } }); - + dispatch_source_set_cancel_handler(receive4Source, ^{ - + LogVerbose(@"receive4CancelBlock"); - + #if !OS_OBJECT_USE_OBJC LogVerbose(@"dispatch_release(receive4Source)"); dispatch_release(theReceiveSource); #endif - + if (--socketFDRefCount == 0) { LogVerbose(@"close(socket4FD)"); close(theSocketFD); } }); - + // We will not be able to receive until the socket is bound to a port, // either explicitly via bind, or implicitly by connect or by sending data. - // + // // But we should be able to send immediately. - + socket4FDBytesAvailable = 0; flags |= kSock4CanAcceptBytes; - + flags |= kSend4SourceSuspended; flags |= kReceive4SourceSuspended; } @@ -1865,22 +1868,22 @@ - (void)setupSendAndReceiveSourcesForSocket6 { LogTrace(); NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - + send6Source = dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE, socket6FD, 0, socketQueue); receive6Source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, socket6FD, 0, socketQueue); - + // Setup event handlers - + dispatch_source_set_event_handler(send6Source, ^{ @autoreleasepool { - + LogVerbose(@"send6EventBlock"); LogVerbose(@"dispatch_source_get_data(send6Source) = %lu", dispatch_source_get_data(send6Source)); - + self->flags |= kSock6CanAcceptBytes; - + // If we're ready to send data, do so immediately. // Otherwise pause the send source or it will continue to fire over and over again. - + if (self->currentSend == nil) { LogVerbose(@"Nothing to send"); @@ -1900,74 +1903,74 @@ - (void)setupSendAndReceiveSourcesForSocket6 { [self doSend]; } - + }}); - + dispatch_source_set_event_handler(receive6Source, ^{ @autoreleasepool { - + LogVerbose(@"receive6EventBlock"); - + self->socket6FDBytesAvailable = dispatch_source_get_data(self->receive6Source); LogVerbose(@"socket6FDBytesAvailable: %lu", socket6FDBytesAvailable); - + if (self->socket6FDBytesAvailable > 0) [self doReceive]; else [self doReceiveEOF]; - + }}); - + // Setup cancel handlers - + __block int socketFDRefCount = 2; - + int theSocketFD = socket6FD; - + #if !OS_OBJECT_USE_OBJC dispatch_source_t theSendSource = send6Source; dispatch_source_t theReceiveSource = receive6Source; #endif - + dispatch_source_set_cancel_handler(send6Source, ^{ - + LogVerbose(@"send6CancelBlock"); - + #if !OS_OBJECT_USE_OBJC LogVerbose(@"dispatch_release(send6Source)"); dispatch_release(theSendSource); #endif - + if (--socketFDRefCount == 0) { LogVerbose(@"close(socket6FD)"); close(theSocketFD); } }); - + dispatch_source_set_cancel_handler(receive6Source, ^{ - + LogVerbose(@"receive6CancelBlock"); - + #if !OS_OBJECT_USE_OBJC LogVerbose(@"dispatch_release(receive6Source)"); dispatch_release(theReceiveSource); #endif - + if (--socketFDRefCount == 0) { LogVerbose(@"close(socket6FD)"); close(theSocketFD); } }); - + // We will not be able to receive until the socket is bound to a port, // either explicitly via bind, or implicitly by connect or by sending data. - // + // // But we should be able to send immediately. - + socket6FDBytesAvailable = 0; flags |= kSock6CanAcceptBytes; - + flags |= kSend6SourceSuspended; flags |= kReceive6SourceSuspended; } @@ -1975,61 +1978,61 @@ - (void)setupSendAndReceiveSourcesForSocket6 - (BOOL)createSocket4:(BOOL)useIPv4 socket6:(BOOL)useIPv6 error:(NSError * __autoreleasing *)errPtr { LogTrace(); - + NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); NSAssert(((flags & kDidCreateSockets) == 0), @"Sockets have already been created"); - + // CreateSocket Block // This block will be invoked below. - + int(^createSocket)(int) = ^int (int domain) { - + int socketFD = socket(domain, SOCK_DGRAM, 0); - + if (socketFD == SOCKET_NULL) { if (errPtr) *errPtr = [self errnoErrorWithReason:@"Error in socket() function"]; - + return SOCKET_NULL; } - + int status; - + // Set socket options - + status = fcntl(socketFD, F_SETFL, O_NONBLOCK); if (status == -1) { if (errPtr) *errPtr = [self errnoErrorWithReason:@"Error enabling non-blocking IO on socket (fcntl)"]; - + close(socketFD); return SOCKET_NULL; } - + int reuseaddr = 1; status = setsockopt(socketFD, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr)); if (status == -1) { if (errPtr) *errPtr = [self errnoErrorWithReason:@"Error enabling address reuse (setsockopt)"]; - + close(socketFD); return SOCKET_NULL; } - + int nosigpipe = 1; status = setsockopt(socketFD, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe)); if (status == -1) { if (errPtr) *errPtr = [self errnoErrorWithReason:@"Error disabling sigpipe (setsockopt)"]; - + close(socketFD); return SOCKET_NULL; } - + /** * The theoretical maximum size of any IPv4 UDP packet is UINT16_MAX = 65535. * The theoretical maximum size of any IPv6 UDP packet is UINT32_MAX = 4294967295. @@ -2043,7 +2046,7 @@ - (BOOL)createSocket4:(BOOL)useIPv4 socket6:(BOOL)useIPv6 error:(NSError * __aut * Enlarge the maximum size of UDP packet. * I can not ensure the protocol type now so that the max size is set to 65535 :) **/ - + status = setsockopt(socketFD, SOL_SOCKET, SO_SNDBUF, (const char*)&self->maxSendSize, sizeof(int)); if (status == -1) { @@ -2052,7 +2055,7 @@ - (BOOL)createSocket4:(BOOL)useIPv4 socket6:(BOOL)useIPv6 error:(NSError * __aut close(socketFD); return SOCKET_NULL; } - + status = setsockopt(socketFD, SOL_SOCKET, SO_RCVBUF, (const char*)&self->maxSendSize, sizeof(int)); if (status == -1) { @@ -2062,16 +2065,16 @@ - (BOOL)createSocket4:(BOOL)useIPv4 socket6:(BOOL)useIPv6 error:(NSError * __aut return SOCKET_NULL; } - + return socketFD; }; - + // Create sockets depending upon given configuration. - + if (useIPv4) { LogVerbose(@"Creating IPv4 socket"); - + socket4FD = createSocket(AF_INET); if (socket4FD == SOCKET_NULL) { @@ -2079,33 +2082,33 @@ - (BOOL)createSocket4:(BOOL)useIPv4 socket6:(BOOL)useIPv6 error:(NSError * __aut return NO; } } - + if (useIPv6) { LogVerbose(@"Creating IPv6 socket"); - + socket6FD = createSocket(AF_INET6); if (socket6FD == SOCKET_NULL) { // errPtr set in local createSocket() block - + if (socket4FD != SOCKET_NULL) { close(socket4FD); socket4FD = SOCKET_NULL; } - + return NO; } } - + // Setup send and receive sources - + if (useIPv4) [self setupSendAndReceiveSourcesForSocket4]; if (useIPv6) [self setupSendAndReceiveSourcesForSocket6]; - + flags |= kDidCreateSockets; return YES; } @@ -2113,10 +2116,10 @@ - (BOOL)createSocket4:(BOOL)useIPv4 socket6:(BOOL)useIPv6 error:(NSError * __aut - (BOOL)createSockets:(NSError **)errPtr { LogTrace(); - + BOOL useIPv4 = [self isIPv4Enabled]; BOOL useIPv6 = [self isIPv6Enabled]; - + return [self createSocket4:useIPv4 socket6:useIPv6 error:errPtr]; } @@ -2125,7 +2128,7 @@ - (void)suspendSend4Source if (send4Source && !(flags & kSend4SourceSuspended)) { LogVerbose(@"dispatch_suspend(send4Source)"); - + dispatch_suspend(send4Source); flags |= kSend4SourceSuspended; } @@ -2136,7 +2139,7 @@ - (void)suspendSend6Source if (send6Source && !(flags & kSend6SourceSuspended)) { LogVerbose(@"dispatch_suspend(send6Source)"); - + dispatch_suspend(send6Source); flags |= kSend6SourceSuspended; } @@ -2147,7 +2150,7 @@ - (void)resumeSend4Source if (send4Source && (flags & kSend4SourceSuspended)) { LogVerbose(@"dispatch_resume(send4Source)"); - + dispatch_resume(send4Source); flags &= ~kSend4SourceSuspended; } @@ -2158,7 +2161,7 @@ - (void)resumeSend6Source if (send6Source && (flags & kSend6SourceSuspended)) { LogVerbose(@"dispatch_resume(send6Source)"); - + dispatch_resume(send6Source); flags &= ~kSend6SourceSuspended; } @@ -2169,7 +2172,7 @@ - (void)suspendReceive4Source if (receive4Source && !(flags & kReceive4SourceSuspended)) { LogVerbose(@"dispatch_suspend(receive4Source)"); - + dispatch_suspend(receive4Source); flags |= kReceive4SourceSuspended; } @@ -2180,7 +2183,7 @@ - (void)suspendReceive6Source if (receive6Source && !(flags & kReceive6SourceSuspended)) { LogVerbose(@"dispatch_suspend(receive6Source)"); - + dispatch_suspend(receive6Source); flags |= kReceive6SourceSuspended; } @@ -2191,7 +2194,7 @@ - (void)resumeReceive4Source if (receive4Source && (flags & kReceive4SourceSuspended)) { LogVerbose(@"dispatch_resume(receive4Source)"); - + dispatch_resume(receive4Source); flags &= ~kReceive4SourceSuspended; } @@ -2202,7 +2205,7 @@ - (void)resumeReceive6Source if (receive6Source && (flags & kReceive6SourceSuspended)) { LogVerbose(@"dispatch_resume(receive6Source)"); - + dispatch_resume(receive6Source); flags &= ~kReceive6SourceSuspended; } @@ -2214,32 +2217,32 @@ - (void)closeSocket4 { LogVerbose(@"dispatch_source_cancel(send4Source)"); dispatch_source_cancel(send4Source); - + LogVerbose(@"dispatch_source_cancel(receive4Source)"); dispatch_source_cancel(receive4Source); - + // For some crazy reason (in my opinion), cancelling a dispatch source doesn't // invoke the cancel handler if the dispatch source is paused. // So we have to unpause the source if needed. // This allows the cancel handler to be run, which in turn releases the source and closes the socket. - + [self resumeSend4Source]; [self resumeReceive4Source]; - + // The sockets will be closed by the cancel handlers of the corresponding source - + send4Source = NULL; receive4Source = NULL; - + socket4FD = SOCKET_NULL; - + // Clear socket states - + socket4FDBytesAvailable = 0; flags &= ~kSock4CanAcceptBytes; - + // Clear cached info - + cachedLocalAddress4 = nil; cachedLocalHost4 = nil; cachedLocalPort4 = 0; @@ -2252,32 +2255,32 @@ - (void)closeSocket6 { LogVerbose(@"dispatch_source_cancel(send6Source)"); dispatch_source_cancel(send6Source); - + LogVerbose(@"dispatch_source_cancel(receive6Source)"); dispatch_source_cancel(receive6Source); - + // For some crazy reason (in my opinion), cancelling a dispatch source doesn't // invoke the cancel handler if the dispatch source is paused. // So we have to unpause the source if needed. // This allows the cancel handler to be run, which in turn releases the source and closes the socket. - + [self resumeSend6Source]; [self resumeReceive6Source]; - + send6Source = NULL; receive6Source = NULL; - + // The sockets will be closed by the cancel handlers of the corresponding source - + socket6FD = SOCKET_NULL; - + // Clear socket states - + socket6FDBytesAvailable = 0; flags &= ~kSock6CanAcceptBytes; - + // Clear cached info - + cachedLocalAddress6 = nil; cachedLocalHost6 = nil; cachedLocalPort6 = 0; @@ -2288,7 +2291,7 @@ - (void)closeSockets { [self closeSocket4]; [self closeSocket6]; - + flags &= ~kDidCreateSockets; } @@ -2302,16 +2305,16 @@ - (BOOL)getLocalAddress:(NSData **)dataPtr forSocket:(int)socketFD withFamily:(int)socketFamily { - + NSData *data = nil; NSString *host = nil; uint16_t port = 0; - + if (socketFamily == AF_INET) { struct sockaddr_in sockaddr4; socklen_t sockaddr4len = sizeof(sockaddr4); - + if (getsockname(socketFD, (struct sockaddr *)&sockaddr4, &sockaddr4len) == 0) { data = [NSData dataWithBytes:&sockaddr4 length:sockaddr4len]; @@ -2327,7 +2330,7 @@ - (BOOL)getLocalAddress:(NSData **)dataPtr { struct sockaddr_in6 sockaddr6; socklen_t sockaddr6len = sizeof(sockaddr6); - + if (getsockname(socketFD, (struct sockaddr *)&sockaddr6, &sockaddr6len) == 0) { data = [NSData dataWithBytes:&sockaddr6 length:sockaddr6len]; @@ -2339,30 +2342,30 @@ - (BOOL)getLocalAddress:(NSData **)dataPtr LogWarn(@"Error in getsockname: %@", [self errnoError]); } } - + if (dataPtr) *dataPtr = data; if (hostPtr) *hostPtr = host; if (portPtr) *portPtr = port; - + return (data != nil); } - (void)maybeUpdateCachedLocalAddress4Info { NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - + if ( cachedLocalAddress4 || ((flags & kDidBind) == 0) || (socket4FD == SOCKET_NULL) ) { return; } - + NSData *address = nil; NSString *host = nil; uint16_t port = 0; - + if ([self getLocalAddress:&address host:&host port:&port forSocket:socket4FD withFamily:AF_INET]) { - + cachedLocalAddress4 = address; cachedLocalHost4 = host; cachedLocalPort4 = port; @@ -2372,19 +2375,19 @@ - (void)maybeUpdateCachedLocalAddress4Info - (void)maybeUpdateCachedLocalAddress6Info { NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - + if ( cachedLocalAddress6 || ((flags & kDidBind) == 0) || (socket6FD == SOCKET_NULL) ) { return; } - + NSData *address = nil; NSString *host = nil; uint16_t port = 0; - + if ([self getLocalAddress:&address host:&host port:&port forSocket:socket6FD withFamily:AF_INET6]) { - + cachedLocalAddress6 = address; cachedLocalHost6 = host; cachedLocalPort6 = port; @@ -2394,9 +2397,9 @@ - (void)maybeUpdateCachedLocalAddress6Info - (NSData *)localAddress { __block NSData *result = nil; - + dispatch_block_t block = ^{ - + if (self->socket4FD != SOCKET_NULL) { [self maybeUpdateCachedLocalAddress4Info]; @@ -2407,23 +2410,23 @@ - (NSData *)localAddress [self maybeUpdateCachedLocalAddress6Info]; result = self->cachedLocalAddress6; } - + }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, AutoreleasedBlock(block)); - + return result; } - (NSString *)localHost { __block NSString *result = nil; - + dispatch_block_t block = ^{ - + if (self->socket4FD != SOCKET_NULL) { [self maybeUpdateCachedLocalAddress4Info]; @@ -2435,21 +2438,21 @@ - (NSString *)localHost result = self->cachedLocalHost6; } }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, AutoreleasedBlock(block)); - + return result; } - (uint16_t)localPort { __block uint16_t result = 0; - + dispatch_block_t block = ^{ - + if (self->socket4FD != SOCKET_NULL) { [self maybeUpdateCachedLocalAddress4Info]; @@ -2461,142 +2464,142 @@ - (uint16_t)localPort result = self->cachedLocalPort6; } }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, AutoreleasedBlock(block)); - + return result; } - (NSData *)localAddress_IPv4 { __block NSData *result = nil; - + dispatch_block_t block = ^{ - + [self maybeUpdateCachedLocalAddress4Info]; result = self->cachedLocalAddress4; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, AutoreleasedBlock(block)); - + return result; } - (NSString *)localHost_IPv4 { __block NSString *result = nil; - + dispatch_block_t block = ^{ - + [self maybeUpdateCachedLocalAddress4Info]; result = self->cachedLocalHost4; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, AutoreleasedBlock(block)); - + return result; } - (uint16_t)localPort_IPv4 { __block uint16_t result = 0; - + dispatch_block_t block = ^{ - + [self maybeUpdateCachedLocalAddress4Info]; result = self->cachedLocalPort4; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, AutoreleasedBlock(block)); - + return result; } - (NSData *)localAddress_IPv6 { __block NSData *result = nil; - + dispatch_block_t block = ^{ - + [self maybeUpdateCachedLocalAddress6Info]; result = self->cachedLocalAddress6; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, AutoreleasedBlock(block)); - + return result; } - (NSString *)localHost_IPv6 { __block NSString *result = nil; - + dispatch_block_t block = ^{ - + [self maybeUpdateCachedLocalAddress6Info]; result = self->cachedLocalHost6; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, AutoreleasedBlock(block)); - + return result; } - (uint16_t)localPort_IPv6 { __block uint16_t result = 0; - + dispatch_block_t block = ^{ - + [self maybeUpdateCachedLocalAddress6Info]; result = self->cachedLocalPort6; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, AutoreleasedBlock(block)); - + return result; } - (void)maybeUpdateCachedConnectedAddressInfo { NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - + if (cachedConnectedAddress || (flags & kDidConnect) == 0) { return; } - + NSData *data = nil; NSString *host = nil; uint16_t port = 0; int family = AF_UNSPEC; - + if (socket4FD != SOCKET_NULL) { struct sockaddr_in sockaddr4; socklen_t sockaddr4len = sizeof(sockaddr4); - + if (getpeername(socket4FD, (struct sockaddr *)&sockaddr4, &sockaddr4len) == 0) { data = [NSData dataWithBytes:&sockaddr4 length:sockaddr4len]; @@ -2613,7 +2616,7 @@ - (void)maybeUpdateCachedConnectedAddressInfo { struct sockaddr_in6 sockaddr6; socklen_t sockaddr6len = sizeof(sockaddr6); - + if (getpeername(socket6FD, (struct sockaddr *)&sockaddr6, &sockaddr6len) == 0) { data = [NSData dataWithBytes:&sockaddr6 length:sockaddr6len]; @@ -2626,8 +2629,8 @@ - (void)maybeUpdateCachedConnectedAddressInfo LogWarn(@"Error in getpeername: %@", [self errnoError]); } } - - + + cachedConnectedAddress = data; cachedConnectedHost = host; cachedConnectedPort = port; @@ -2637,96 +2640,96 @@ - (void)maybeUpdateCachedConnectedAddressInfo - (NSData *)connectedAddress { __block NSData *result = nil; - + dispatch_block_t block = ^{ - + [self maybeUpdateCachedConnectedAddressInfo]; result = self->cachedConnectedAddress; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, AutoreleasedBlock(block)); - + return result; } - (NSString *)connectedHost { __block NSString *result = nil; - + dispatch_block_t block = ^{ - + [self maybeUpdateCachedConnectedAddressInfo]; result = self->cachedConnectedHost; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, AutoreleasedBlock(block)); - + return result; } - (uint16_t)connectedPort { __block uint16_t result = 0; - + dispatch_block_t block = ^{ - + [self maybeUpdateCachedConnectedAddressInfo]; result = self->cachedConnectedPort; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, AutoreleasedBlock(block)); - + return result; } - (BOOL)isConnected { __block BOOL result = NO; - + dispatch_block_t block = ^{ result = (self->flags & kDidConnect) ? YES : NO; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + return result; } - (BOOL)isClosed { __block BOOL result = YES; - + dispatch_block_t block = ^{ - + result = (self->flags & kDidCreateSockets) ? NO : YES; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + return result; } - (BOOL)isIPv4 { __block BOOL result = NO; - + dispatch_block_t block = ^{ - + if (self->flags & kDidCreateSockets) { result = (self->socket4FD != SOCKET_NULL); @@ -2736,21 +2739,21 @@ - (BOOL)isIPv4 result = [self isIPv4Enabled]; } }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + return result; } - (BOOL)isIPv6 { __block BOOL result = NO; - + dispatch_block_t block = ^{ - + if (self->flags & kDidCreateSockets) { result = (self->socket6FD != SOCKET_NULL); @@ -2760,12 +2763,12 @@ - (BOOL)isIPv6 result = [self isIPv6Enabled]; } }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + return result; } @@ -2783,7 +2786,7 @@ - (BOOL)preBind:(NSError **)errPtr { return NO; } - + if (flags & kDidBind) { if (errPtr) @@ -2793,7 +2796,7 @@ - (BOOL)preBind:(NSError **)errPtr } return NO; } - + if ((flags & kConnecting) || (flags & kDidConnect)) { if (errPtr) @@ -2803,10 +2806,10 @@ - (BOOL)preBind:(NSError **)errPtr } return NO; } - + BOOL isIPv4Disabled = (config & kIPv4Disabled) ? YES : NO; BOOL isIPv6Disabled = (config & kIPv6Disabled) ? YES : NO; - + if (isIPv4Disabled && isIPv6Disabled) // Must have IPv4 or IPv6 enabled { if (errPtr) @@ -2816,7 +2819,7 @@ - (BOOL)preBind:(NSError **)errPtr } return NO; } - + return YES; } @@ -2829,57 +2832,57 @@ - (BOOL)bindToPort:(uint16_t)port interface:(NSString *)interface error:(NSError { __block BOOL result = NO; __block NSError *err = nil; - + dispatch_block_t block = ^{ @autoreleasepool { - + // Run through sanity checks - + if (![self preBind:&err]) { return_from_block; } - + // Check the given interface - + NSData *interface4 = nil; NSData *interface6 = nil; - + [self convertIntefaceDescription:interface port:port intoAddress4:&interface4 address6:&interface6]; - + if ((interface4 == nil) && (interface6 == nil)) { NSString *msg = @"Unknown interface. Specify valid interface by name (e.g. \"en1\") or IP address."; err = [self badParamError:msg]; - + return_from_block; } - + BOOL isIPv4Disabled = (self->config & kIPv4Disabled) ? YES : NO; BOOL isIPv6Disabled = (self->config & kIPv6Disabled) ? YES : NO; - + if (isIPv4Disabled && (interface6 == nil)) { NSString *msg = @"IPv4 has been disabled and specified interface doesn't support IPv6."; err = [self badParamError:msg]; - + return_from_block; } - + if (isIPv6Disabled && (interface4 == nil)) { NSString *msg = @"IPv6 has been disabled and specified interface doesn't support IPv4."; err = [self badParamError:msg]; - + return_from_block; } - + // Determine protocol(s) - + BOOL useIPv4 = !isIPv4Disabled && (interface4 != nil); BOOL useIPv6 = !isIPv6Disabled && (interface6 != nil); - + // Create the socket(s) if needed - + if ((self->flags & kDidCreateSockets) == 0) { if (![self createSocket4:useIPv4 socket6:useIPv6 error:&err]) @@ -2887,61 +2890,61 @@ - (BOOL)bindToPort:(uint16_t)port interface:(NSString *)interface error:(NSError return_from_block; } } - + // Bind the socket(s) - + LogVerbose(@"Binding socket to port(%hu) interface(%@)", port, interface); - + if (useIPv4) { int status = bind(self->socket4FD, (const struct sockaddr *)[interface4 bytes], (socklen_t)[interface4 length]); if (status == -1) { [self closeSockets]; - + NSString *reason = @"Error in bind() function"; err = [self errnoErrorWithReason:reason]; - + return_from_block; } } - + if (useIPv6) { int status = bind(self->socket6FD, (const struct sockaddr *)[interface6 bytes], (socklen_t)[interface6 length]); if (status == -1) { [self closeSockets]; - + NSString *reason = @"Error in bind() function"; err = [self errnoErrorWithReason:reason]; - + return_from_block; } } - + // Update flags - + self->flags |= kDidBind; - + if (!useIPv4) self->flags |= kIPv4Deactivated; if (!useIPv6) self->flags |= kIPv6Deactivated; - + result = YES; - + }}; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + if (err) LogError(@"Error binding to port/interface: %@", err); - + if (errPtr) *errPtr = err; - + return result; } @@ -2949,57 +2952,57 @@ - (BOOL)bindToAddress:(NSData *)localAddr error:(NSError **)errPtr { __block BOOL result = NO; __block NSError *err = nil; - + dispatch_block_t block = ^{ @autoreleasepool { - + // Run through sanity checks - + if (![self preBind:&err]) { return_from_block; } - + // Check the given address - + int addressFamily = [[self class] familyFromAddress:localAddr]; - + if (addressFamily == AF_UNSPEC) { NSString *msg = @"A valid IPv4 or IPv6 address was not given"; err = [self badParamError:msg]; - + return_from_block; } - + NSData *localAddr4 = (addressFamily == AF_INET) ? localAddr : nil; NSData *localAddr6 = (addressFamily == AF_INET6) ? localAddr : nil; - + BOOL isIPv4Disabled = (self->config & kIPv4Disabled) ? YES : NO; BOOL isIPv6Disabled = (self->config & kIPv6Disabled) ? YES : NO; - + if (isIPv4Disabled && localAddr4) { NSString *msg = @"IPv4 has been disabled and an IPv4 address was passed."; err = [self badParamError:msg]; - + return_from_block; } - + if (isIPv6Disabled && localAddr6) { NSString *msg = @"IPv6 has been disabled and an IPv6 address was passed."; err = [self badParamError:msg]; - + return_from_block; } - + // Determine protocol(s) - + BOOL useIPv4 = !isIPv4Disabled && (localAddr4 != nil); BOOL useIPv6 = !isIPv6Disabled && (localAddr6 != nil); - + // Create the socket(s) if needed - + if ((self->flags & kDidCreateSockets) == 0) { if (![self createSocket4:useIPv4 socket6:useIPv6 error:&err]) @@ -3007,23 +3010,23 @@ - (BOOL)bindToAddress:(NSData *)localAddr error:(NSError **)errPtr return_from_block; } } - + // Bind the socket(s) - + if (useIPv4) { LogVerbose(@"Binding socket to address(%@:%hu)", [[self class] hostFromAddress:localAddr4], [[self class] portFromAddress:localAddr4]); - + int status = bind(self->socket4FD, (const struct sockaddr *)[localAddr4 bytes], (socklen_t)[localAddr4 length]); if (status == -1) { [self closeSockets]; - + NSString *reason = @"Error in bind() function"; err = [self errnoErrorWithReason:reason]; - + return_from_block; } } @@ -3032,41 +3035,41 @@ - (BOOL)bindToAddress:(NSData *)localAddr error:(NSError **)errPtr LogVerbose(@"Binding socket to address(%@:%hu)", [[self class] hostFromAddress:localAddr6], [[self class] portFromAddress:localAddr6]); - + int status = bind(self->socket6FD, (const struct sockaddr *)[localAddr6 bytes], (socklen_t)[localAddr6 length]); if (status == -1) { [self closeSockets]; - + NSString *reason = @"Error in bind() function"; err = [self errnoErrorWithReason:reason]; - + return_from_block; } } - + // Update flags - + self->flags |= kDidBind; - + if (!useIPv4) self->flags |= kIPv4Deactivated; if (!useIPv6) self->flags |= kIPv6Deactivated; - + result = YES; - + }}; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + if (err) LogError(@"Error binding to address: %@", err); - + if (errPtr) *errPtr = err; - + return result; } @@ -3084,7 +3087,7 @@ - (BOOL)preConnect:(NSError **)errPtr { return NO; } - + if ((flags & kConnecting) || (flags & kDidConnect)) { if (errPtr) @@ -3094,10 +3097,10 @@ - (BOOL)preConnect:(NSError **)errPtr } return NO; } - + BOOL isIPv4Disabled = (config & kIPv4Disabled) ? YES : NO; BOOL isIPv6Disabled = (config & kIPv6Disabled) ? YES : NO; - + if (isIPv4Disabled && isIPv6Disabled) // Must have IPv4 or IPv6 enabled { if (errPtr) @@ -3107,7 +3110,7 @@ - (BOOL)preConnect:(NSError **)errPtr } return NO; } - + return YES; } @@ -3115,28 +3118,28 @@ - (BOOL)connectToHost:(NSString *)host onPort:(uint16_t)port error:(NSError **)e { __block BOOL result = NO; __block NSError *err = nil; - + dispatch_block_t block = ^{ @autoreleasepool { - + // Run through sanity checks. - + if (![self preConnect:&err]) { return_from_block; } - + // Check parameter(s) - + if (host == nil) { NSString *msg = @"The host param is nil. Should be domain name or IP address string."; err = [self badParamError:msg]; - + return_from_block; } - + // Create the socket(s) if needed - + if ((self->flags & kDidCreateSockets) == 0) { if (![self createSockets:&err]) @@ -3144,51 +3147,51 @@ - (BOOL)connectToHost:(NSString *)host onPort:(uint16_t)port error:(NSError **)e return_from_block; } } - + // Create special connect packet - + GCDAsyncUdpSpecialPacket *packet = [[GCDAsyncUdpSpecialPacket alloc] init]; packet->resolveInProgress = YES; - + // Start asynchronous DNS resolve for host:port on background queue - + LogVerbose(@"Dispatching DNS resolve for connect..."); - + [self asyncResolveHost:host port:port withCompletionBlock:^(NSArray *addresses, NSError *error) { - + // The asyncResolveHost:port:: method asynchronously dispatches a task onto the global concurrent queue, // and immediately returns. Once the async resolve task completes, // this block is executed on our socketQueue. - + packet->resolveInProgress = NO; - + packet->addresses = addresses; packet->error = error; - + [self maybeConnect]; }]; - + // Updates flags, add connect packet to send queue, and pump send queue - + self->flags |= kConnecting; - + [self->sendQueue addObject:packet]; [self maybeDequeueSend]; - + result = YES; }}; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + if (err) LogError(@"Error connecting to host/port: %@", err); - + if (errPtr) *errPtr = err; - + return result; } @@ -3196,28 +3199,28 @@ - (BOOL)connectToAddress:(NSData *)remoteAddr error:(NSError **)errPtr { __block BOOL result = NO; __block NSError *err = nil; - + dispatch_block_t block = ^{ @autoreleasepool { - + // Run through sanity checks. - + if (![self preConnect:&err]) { return_from_block; } - + // Check parameter(s) - + if (remoteAddr == nil) { NSString *msg = @"The address param is nil. Should be a valid address."; err = [self badParamError:msg]; - + return_from_block; } - + // Create the socket(s) if needed - + if ((self->flags & kDidCreateSockets) == 0) { if (![self createSockets:&err]) @@ -3225,37 +3228,37 @@ - (BOOL)connectToAddress:(NSData *)remoteAddr error:(NSError **)errPtr return_from_block; } } - + // The remoteAddr parameter could be of type NSMutableData. // So we copy it to be safe. - + NSData *address = [remoteAddr copy]; NSArray *addresses = [NSArray arrayWithObject:address]; - + GCDAsyncUdpSpecialPacket *packet = [[GCDAsyncUdpSpecialPacket alloc] init]; packet->addresses = addresses; - + // Updates flags, add connect packet to send queue, and pump send queue - + self->flags |= kConnecting; - + [self->sendQueue addObject:packet]; [self maybeDequeueSend]; - + result = YES; }}; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + if (err) LogError(@"Error connecting to address: %@", err); - + if (errPtr) *errPtr = err; - + return result; } @@ -3263,14 +3266,14 @@ - (void)maybeConnect { LogTrace(); NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - - + + BOOL sendQueueReady = [currentSend isKindOfClass:[GCDAsyncUdpSpecialPacket class]]; - + if (sendQueueReady) { GCDAsyncUdpSpecialPacket *connectPacket = (GCDAsyncUdpSpecialPacket *)currentSend; - + if (connectPacket->resolveInProgress) { LogVerbose(@"Waiting for DNS resolve..."); @@ -3285,29 +3288,30 @@ - (void)maybeConnect { NSData *address = nil; NSError *error = nil; - + int addressFamily = [self getAddress:&address error:&error fromAddresses:connectPacket->addresses]; - + // Perform connect - + BOOL result = NO; - + switch (addressFamily) { case AF_INET : result = [self connectWithAddress4:address error:&error]; break; case AF_INET6 : result = [self connectWithAddress6:address error:&error]; break; + default: break; } - + if (result) { flags |= kDidBind; flags |= kDidConnect; - + cachedConnectedAddress = address; cachedConnectedHost = [[self class] hostFromAddress:address]; cachedConnectedPort = [[self class] portFromAddress:address]; cachedConnectedFamily = addressFamily; - + [self notifyDidConnectToAddress:address]; } else @@ -3315,9 +3319,9 @@ - (void)maybeConnect [self notifyDidNotConnect:error]; } } - + flags &= ~kConnecting; - + [self endCurrentSend]; [self maybeDequeueSend]; } @@ -3328,19 +3332,19 @@ - (BOOL)connectWithAddress4:(NSData *)address4 error:(NSError **)errPtr { LogTrace(); NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - + int status = connect(socket4FD, (const struct sockaddr *)[address4 bytes], (socklen_t)[address4 length]); if (status != 0) { if (errPtr) *errPtr = [self errnoErrorWithReason:@"Error in connect() function"]; - + return NO; } - + [self closeSocket6]; flags |= kIPv6Deactivated; - + return YES; } @@ -3348,19 +3352,19 @@ - (BOOL)connectWithAddress6:(NSData *)address6 error:(NSError **)errPtr { LogTrace(); NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - + int status = connect(socket6FD, (const struct sockaddr *)[address6 bytes], (socklen_t)[address6 length]); if (status != 0) { if (errPtr) *errPtr = [self errnoErrorWithReason:@"Error in connect() function"]; - + return NO; } - + [self closeSocket4]; flags |= kIPv4Deactivated; - + return YES; } @@ -3374,7 +3378,7 @@ - (BOOL)preJoin:(NSError **)errPtr { return NO; } - + if (!(flags & kDidBind)) { if (errPtr) @@ -3384,7 +3388,7 @@ - (BOOL)preJoin:(NSError **)errPtr } return NO; } - + if ((flags & kConnecting) || (flags & kDidConnect)) { if (errPtr) @@ -3394,7 +3398,7 @@ - (BOOL)preJoin:(NSError **)errPtr } return NO; } - + return YES; } @@ -3427,109 +3431,109 @@ - (BOOL)performMulticastRequest:(int)requestType { __block BOOL result = NO; __block NSError *err = nil; - + dispatch_block_t block = ^{ @autoreleasepool { - + // Run through sanity checks - + if (![self preJoin:&err]) { return_from_block; } - + // Convert group to address - + NSData *groupAddr4 = nil; NSData *groupAddr6 = nil; - + [self convertNumericHost:group port:0 intoAddress4:&groupAddr4 address6:&groupAddr6]; - + if ((groupAddr4 == nil) && (groupAddr6 == nil)) { NSString *msg = @"Unknown group. Specify valid group IP address."; err = [self badParamError:msg]; - + return_from_block; } - + // Convert interface to address - + NSData *interfaceAddr4 = nil; NSData *interfaceAddr6 = nil; - + [self convertIntefaceDescription:interface port:0 intoAddress4:&interfaceAddr4 address6:&interfaceAddr6]; - + if ((interfaceAddr4 == nil) && (interfaceAddr6 == nil)) { NSString *msg = @"Unknown interface. Specify valid interface by name (e.g. \"en1\") or IP address."; err = [self badParamError:msg]; - + return_from_block; } - + // Perform join - + if ((self->socket4FD != SOCKET_NULL) && groupAddr4 && interfaceAddr4) { const struct sockaddr_in *nativeGroup = (const struct sockaddr_in *)[groupAddr4 bytes]; const struct sockaddr_in *nativeIface = (const struct sockaddr_in *)[interfaceAddr4 bytes]; - + struct ip_mreq imreq; imreq.imr_multiaddr = nativeGroup->sin_addr; imreq.imr_interface = nativeIface->sin_addr; - + int status = setsockopt(self->socket4FD, IPPROTO_IP, requestType, (const void *)&imreq, sizeof(imreq)); if (status != 0) { err = [self errnoErrorWithReason:@"Error in setsockopt() function"]; - + return_from_block; } - + // Using IPv4 only [self closeSocket6]; - + result = YES; } else if ((self->socket6FD != SOCKET_NULL) && groupAddr6 && interfaceAddr6) { const struct sockaddr_in6 *nativeGroup = (const struct sockaddr_in6 *)[groupAddr6 bytes]; - + struct ipv6_mreq imreq; imreq.ipv6mr_multiaddr = nativeGroup->sin6_addr; imreq.ipv6mr_interface = [self indexOfInterfaceAddr6:interfaceAddr6]; - + int status = setsockopt(self->socket6FD, IPPROTO_IPV6, requestType, (const void *)&imreq, sizeof(imreq)); if (status != 0) { err = [self errnoErrorWithReason:@"Error in setsockopt() function"]; - + return_from_block; } - + // Using IPv6 only [self closeSocket4]; - + result = YES; } else { NSString *msg = @"Socket, group, and interface do not have matching IP versions"; err = [self badParamError:msg]; - + return_from_block; } - + }}; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + if (errPtr) *errPtr = err; - + return result; } @@ -3552,7 +3556,7 @@ - (BOOL)sendIPv4MulticastOnInterface:(NSString*)interface error:(NSError **)errP return_from_block; } } - + // Convert interface to address NSData *interfaceAddr4 = nil; @@ -3577,7 +3581,7 @@ - (BOOL)sendIPv4MulticastOnInterface:(NSString*)interface error:(NSError **)errP result = YES; } } - + }}; if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) @@ -3610,7 +3614,7 @@ - (BOOL)sendIPv6MulticastOnInterface:(NSString*)interface error:(NSError **)errP return_from_block; } } - + // Convert interface to address NSData *interfaceAddr4 = nil; @@ -3634,7 +3638,7 @@ - (BOOL)sendIPv6MulticastOnInterface:(NSString*)interface error:(NSError **)errP } result = YES; } - + }}; if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) @@ -3656,14 +3660,14 @@ - (BOOL)enableReusePort:(BOOL)flag error:(NSError **)errPtr { __block BOOL result = NO; __block NSError *err = nil; - + dispatch_block_t block = ^{ @autoreleasepool { - + if (![self preOp:&err]) { return_from_block; } - + if ((self->flags & kDidCreateSockets) == 0) { if (![self createSockets:&err]) @@ -3671,44 +3675,44 @@ - (BOOL)enableReusePort:(BOOL)flag error:(NSError **)errPtr return_from_block; } } - + int value = flag ? 1 : 0; if (self->socket4FD != SOCKET_NULL) { int error = setsockopt(self->socket4FD, SOL_SOCKET, SO_REUSEPORT, (const void *)&value, sizeof(value)); - + if (error) { err = [self errnoErrorWithReason:@"Error in setsockopt() function"]; - + return_from_block; } result = YES; } - + if (self->socket6FD != SOCKET_NULL) { int error = setsockopt(self->socket6FD, SOL_SOCKET, SO_REUSEPORT, (const void *)&value, sizeof(value)); - + if (error) { err = [self errnoErrorWithReason:@"Error in setsockopt() function"]; - + return_from_block; } result = YES; } - + }}; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + if (errPtr) *errPtr = err; - + return result; } @@ -3720,14 +3724,14 @@ - (BOOL)enableBroadcast:(BOOL)flag error:(NSError **)errPtr { __block BOOL result = NO; __block NSError *err = nil; - + dispatch_block_t block = ^{ @autoreleasepool { - + if (![self preOp:&err]) { return_from_block; } - + if ((self->flags & kDidCreateSockets) == 0) { if (![self createSockets:&err]) @@ -3735,34 +3739,34 @@ - (BOOL)enableBroadcast:(BOOL)flag error:(NSError **)errPtr return_from_block; } } - + if (self->socket4FD != SOCKET_NULL) { int value = flag ? 1 : 0; int error = setsockopt(self->socket4FD, SOL_SOCKET, SO_BROADCAST, (const void *)&value, sizeof(value)); - + if (error) { err = [self errnoErrorWithReason:@"Error in setsockopt() function"]; - + return_from_block; } result = YES; } - + // IPv6 does not implement broadcast, the ability to send a packet to all hosts on the attached link. // The same effect can be achieved by sending a packet to the link-local all hosts multicast group. - + }}; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + if (errPtr) *errPtr = err; - + return result; } @@ -3778,23 +3782,23 @@ - (void)sendData:(NSData *)data withTag:(long)tag - (void)sendData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag { LogTrace(); - + if ([data length] == 0) { LogWarn(@"Ignoring attempt to send nil/empty data."); return; } - - - + + + GCDAsyncUdpSendPacket *packet = [[GCDAsyncUdpSendPacket alloc] initWithData:data timeout:timeout tag:tag]; - + dispatch_async(socketQueue, ^{ @autoreleasepool { - + [self->sendQueue addObject:packet]; [self maybeDequeueSend]; }}); - + } - (void)sendData:(NSData *)data @@ -3804,59 +3808,59 @@ - (void)sendData:(NSData *)data tag:(long)tag { LogTrace(); - + if ([data length] == 0) { LogWarn(@"Ignoring attempt to send nil/empty data."); return; } - + GCDAsyncUdpSendPacket *packet = [[GCDAsyncUdpSendPacket alloc] initWithData:data timeout:timeout tag:tag]; packet->resolveInProgress = YES; - + [self asyncResolveHost:host port:port withCompletionBlock:^(NSArray *addresses, NSError *error) { - + // The asyncResolveHost:port:: method asynchronously dispatches a task onto the global concurrent queue, // and immediately returns. Once the async resolve task completes, // this block is executed on our socketQueue. - + packet->resolveInProgress = NO; - + packet->resolvedAddresses = addresses; packet->resolveError = error; - + if (packet == self->currentSend) { LogVerbose(@"currentSend - address resolved"); [self doPreSend]; } }]; - + dispatch_async(socketQueue, ^{ @autoreleasepool { - + [self->sendQueue addObject:packet]; [self maybeDequeueSend]; - + }}); - + } - (void)sendData:(NSData *)data toAddress:(NSData *)remoteAddr withTimeout:(NSTimeInterval)timeout tag:(long)tag { LogTrace(); - + if ([data length] == 0) { LogWarn(@"Ignoring attempt to send nil/empty data."); return; } - + GCDAsyncUdpSendPacket *packet = [[GCDAsyncUdpSendPacket alloc] initWithData:data timeout:timeout tag:tag]; packet->addressFamily = [GCDAsyncUdpSocket familyFromAddress:remoteAddr]; packet->address = remoteAddr; - + dispatch_async(socketQueue, ^{ @autoreleasepool { - + [self->sendQueue addObject:packet]; [self maybeDequeueSend]; }}); @@ -3873,29 +3877,29 @@ - (void)setSendFilter:(GCDAsyncUdpSocketSendFilterBlock)filterBlock { GCDAsyncUdpSocketSendFilterBlock newFilterBlock = NULL; dispatch_queue_t newFilterQueue = NULL; - + if (filterBlock) { NSAssert(filterQueue, @"Must provide a dispatch_queue in which to run the filter block."); - + newFilterBlock = [filterBlock copy]; newFilterQueue = filterQueue; #if !OS_OBJECT_USE_OBJC dispatch_retain(newFilterQueue); #endif } - + dispatch_block_t block = ^{ - + #if !OS_OBJECT_USE_OBJC if (self->sendFilterQueue) dispatch_release(self->sendFilterQueue); #endif - + self->sendFilterBlock = newFilterBlock; self->sendFilterQueue = newFilterQueue; self->sendFilterAsync = isAsynchronous; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else @@ -3906,7 +3910,7 @@ - (void)maybeDequeueSend { LogTrace(); NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - + // If we don't have a send operation already in progress if (currentSend == nil) { @@ -3920,38 +3924,38 @@ - (void)maybeDequeueSend return; } } - + while ([sendQueue count] > 0) { // Dequeue the next object in the queue currentSend = [sendQueue objectAtIndex:0]; [sendQueue removeObjectAtIndex:0]; - + if ([currentSend isKindOfClass:[GCDAsyncUdpSpecialPacket class]]) { [self maybeConnect]; - + return; // The maybeConnect method, if it connects, will invoke this method again } else if (currentSend->resolveError) { // Notify delegate [self notifyDidNotSendDataWithTag:currentSend->tag dueToError:currentSend->resolveError]; - + // Clear currentSend currentSend = nil; - + continue; } else { // Start preprocessing checks on the send packet [self doPreSend]; - + break; } } - + if ((currentSend == nil) && (flags & kCloseAfterSends)) { [self closeWithError:nil]; @@ -3963,24 +3967,24 @@ - (void)maybeDequeueSend * This method is called after a sendPacket has been dequeued. * It performs various preprocessing checks on the packet, * and queries the sendFilter (if set) to determine if the packet can be sent. - * + * * If the packet passes all checks, it will be passed on to the doSend method. **/ - (void)doPreSend { LogTrace(); - - // + + // // 1. Check for problems with send packet - // - + // + BOOL waitingForResolve = NO; NSError *error = nil; - + if (flags & kDidConnect) { // Connected socket - + if (currentSend->resolveInProgress || currentSend->resolvedAddresses || currentSend->resolveError) { NSString *msg = @"Cannot specify destination of packet for connected socket"; @@ -3995,7 +3999,7 @@ - (void)doPreSend else { // Non-Connected socket - + if (currentSend->resolveInProgress) { // We're waiting for the packet's destination to be resolved. @@ -4015,67 +4019,67 @@ - (void)doPreSend else { // Pick the proper address to use (out of possibly several resolved addresses) - + NSData *address = nil; int addressFamily = AF_UNSPEC; - + addressFamily = [self getAddress:&address error:&error fromAddresses:currentSend->resolvedAddresses]; - + currentSend->address = address; currentSend->addressFamily = addressFamily; } } } - + if (waitingForResolve) { // We're waiting for the packet's destination to be resolved. - + LogVerbose(@"currentSend - waiting for address resolve"); - + if (flags & kSock4CanAcceptBytes) { [self suspendSend4Source]; } if (flags & kSock6CanAcceptBytes) { [self suspendSend6Source]; } - + return; } - + if (error) { // Unable to send packet due to some error. // Notify delegate and move on. - + [self notifyDidNotSendDataWithTag:currentSend->tag dueToError:error]; [self endCurrentSend]; [self maybeDequeueSend]; - + return; } - - // + + // // 2. Query sendFilter (if applicable) - // - + // + if (sendFilterBlock && sendFilterQueue) { // Query sendFilter - + if (sendFilterAsync) { // Scenario 1 of 3 - Need to asynchronously query sendFilter - + currentSend->filterInProgress = YES; GCDAsyncUdpSendPacket *sendPacket = currentSend; - + dispatch_async(sendFilterQueue, ^{ @autoreleasepool { - + BOOL allowed = self->sendFilterBlock(sendPacket->buffer, sendPacket->address, sendPacket->tag); - + dispatch_async(self->socketQueue, ^{ @autoreleasepool { - + sendPacket->filterInProgress = NO; if (sendPacket == self->currentSend) { @@ -4086,7 +4090,7 @@ - (void)doPreSend else { LogVerbose(@"currentSend - silently dropped by sendFilter"); - + [self notifyDidSendDataWithTag:self->currentSend->tag]; [self endCurrentSend]; [self maybeDequeueSend]; @@ -4098,14 +4102,14 @@ - (void)doPreSend else { // Scenario 2 of 3 - Need to synchronously query sendFilter - + __block BOOL allowed = YES; - + dispatch_sync(sendFilterQueue, ^{ @autoreleasepool { - + allowed = self->sendFilterBlock(self->currentSend->buffer, self->currentSend->address, self->currentSend->tag); }}); - + if (allowed) { [self doSend]; @@ -4113,7 +4117,7 @@ - (void)doPreSend else { LogVerbose(@"currentSend - silently dropped by sendFilter"); - + [self notifyDidSendDataWithTag:currentSend->tag]; [self endCurrentSend]; [self maybeDequeueSend]; @@ -4123,32 +4127,32 @@ - (void)doPreSend else // if (!sendFilterBlock || !sendFilterQueue) { // Scenario 3 of 3 - No sendFilter. Just go straight into sending. - + [self doSend]; } } /** * This method performs the actual sending of data in the currentSend packet. - * It should only be called if the + * It should only be called if the **/ - (void)doSend { LogTrace(); - + NSAssert(currentSend != nil, @"Invalid logic"); - + // Perform the actual send - + ssize_t result = 0; - + if (flags & kDidConnect) { // Connected socket - + const void *buffer = [currentSend->buffer bytes]; size_t length = (size_t)[currentSend->buffer length]; - + if (currentSend->addressFamily == AF_INET) { result = send(socket4FD, buffer, length, 0); @@ -4163,13 +4167,13 @@ - (void)doSend else { // Non-Connected socket - + const void *buffer = [currentSend->buffer bytes]; size_t length = (size_t)[currentSend->buffer length]; - + const void *dst = [currentSend->address bytes]; socklen_t dstSize = (socklen_t)[currentSend->address length]; - + if (currentSend->addressFamily == AF_INET) { result = sendto(socket4FD, buffer, length, 0, dst, dstSize); @@ -4181,24 +4185,24 @@ - (void)doSend LogVerbose(@"sendto(socket6FD) = %d", result); } } - + // If the socket wasn't bound before, it is now - + if ((flags & kDidBind) == 0) { flags |= kDidBind; } - + // Check the results. - // + // // From the send() & sendto() manpage: - // + // // Upon successful completion, the number of bytes which were sent is returned. // Otherwise, -1 is returned and the global variable errno is set to indicate the error. - + BOOL waitingForSocket = NO; NSError *socketError = nil; - + if (result == 0) { waitingForSocket = YES; @@ -4210,26 +4214,26 @@ - (void)doSend else socketError = [self errnoErrorWithReason:@"Error in send() function."]; } - + if (waitingForSocket) { // Not enough room in the underlying OS socket send buffer. // Wait for a notification of available space. - + LogVerbose(@"currentSend - waiting for socket"); - + if (!(flags & kSock4CanAcceptBytes)) { [self resumeSend4Source]; } if (!(flags & kSock6CanAcceptBytes)) { [self resumeSend6Source]; } - + if ((sendTimer == NULL) && (currentSend->timeout >= 0.0)) { // Unable to send packet right away. // Start timer to timeout the send operation. - + [self setupSendTimerWithTimeout:currentSend->timeout]; } } @@ -4258,7 +4262,7 @@ - (void)endCurrentSend #endif sendTimer = NULL; } - + currentSend = nil; } @@ -4268,7 +4272,7 @@ - (void)endCurrentSend - (void)doSendTimeout { LogTrace(); - + [self notifyDidNotSendDataWithTag:currentSend->tag dueToError:[self sendTimeoutError]]; [self endCurrentSend]; [self maybeDequeueSend]; @@ -4282,18 +4286,18 @@ - (void)setupSendTimerWithTimeout:(NSTimeInterval)timeout { NSAssert(sendTimer == NULL, @"Invalid logic"); NSAssert(timeout >= 0.0, @"Invalid logic"); - + LogTrace(); - + sendTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, socketQueue); - + dispatch_source_set_event_handler(sendTimer, ^{ @autoreleasepool { - + [self doSendTimeout]; }}); - + dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeout * NSEC_PER_SEC)); - + dispatch_source_set_timer(sendTimer, tt, DISPATCH_TIME_FOREVER, 0); dispatch_resume(sendTimer); } @@ -4305,104 +4309,104 @@ - (void)setupSendTimerWithTimeout:(NSTimeInterval)timeout - (BOOL)receiveOnce:(NSError **)errPtr { LogTrace(); - + __block BOOL result = NO; __block NSError *err = nil; - + dispatch_block_t block = ^{ - + if ((self->flags & kReceiveOnce) == 0) { if ((self->flags & kDidCreateSockets) == 0) { NSString *msg = @"Must bind socket before you can receive data. " @"You can do this explicitly via bind, or implicitly via connect or by sending data."; - + err = [self badConfigError:msg]; return_from_block; } - + self->flags |= kReceiveOnce; // Enable self->flags &= ~kReceiveContinuous; // Disable - + dispatch_async(self->socketQueue, ^{ @autoreleasepool { - + [self doReceive]; }}); } - + result = YES; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + if (err) LogError(@"Error in beginReceiving: %@", err); - + if (errPtr) *errPtr = err; - + return result; } - (BOOL)beginReceiving:(NSError **)errPtr { LogTrace(); - + __block BOOL result = NO; __block NSError *err = nil; - + dispatch_block_t block = ^{ - + if ((self->flags & kReceiveContinuous) == 0) { if ((self->flags & kDidCreateSockets) == 0) { NSString *msg = @"Must bind socket before you can receive data. " @"You can do this explicitly via bind, or implicitly via connect or by sending data."; - + err = [self badConfigError:msg]; return_from_block; } - + self->flags |= kReceiveContinuous; // Enable self->flags &= ~kReceiveOnce; // Disable - + dispatch_async(self->socketQueue, ^{ @autoreleasepool { - + [self doReceive]; }}); } - + result = YES; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else dispatch_sync(socketQueue, block); - + if (err) LogError(@"Error in beginReceiving: %@", err); - + if (errPtr) *errPtr = err; - + return result; } - (void)pauseReceiving { LogTrace(); - + dispatch_block_t block = ^{ - + self->flags &= ~kReceiveOnce; // Disable self->flags &= ~kReceiveContinuous; // Disable - + if (self->socket4FDBytesAvailable > 0) { [self suspendReceive4Source]; } @@ -4410,7 +4414,7 @@ - (void)pauseReceiving [self suspendReceive6Source]; } }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else @@ -4428,29 +4432,29 @@ - (void)setReceiveFilter:(GCDAsyncUdpSocketReceiveFilterBlock)filterBlock { GCDAsyncUdpSocketReceiveFilterBlock newFilterBlock = NULL; dispatch_queue_t newFilterQueue = NULL; - + if (filterBlock) { NSAssert(filterQueue, @"Must provide a dispatch_queue in which to run the filter block."); - + newFilterBlock = [filterBlock copy]; newFilterQueue = filterQueue; #if !OS_OBJECT_USE_OBJC dispatch_retain(newFilterQueue); #endif } - + dispatch_block_t block = ^{ - + #if !OS_OBJECT_USE_OBJC if (self->receiveFilterQueue) dispatch_release(self->receiveFilterQueue); #endif - + self->receiveFilterBlock = newFilterBlock; self->receiveFilterQueue = newFilterQueue; self->receiveFilterAsync = isAsynchronous; }; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else @@ -4460,71 +4464,71 @@ - (void)setReceiveFilter:(GCDAsyncUdpSocketReceiveFilterBlock)filterBlock - (void)doReceive { LogTrace(); - + if ((flags & (kReceiveOnce | kReceiveContinuous)) == 0) { LogVerbose(@"Receiving is paused..."); - + if (socket4FDBytesAvailable > 0) { [self suspendReceive4Source]; } if (socket6FDBytesAvailable > 0) { [self suspendReceive6Source]; } - + return; } - + if ((flags & kReceiveOnce) && (pendingFilterOperations > 0)) { LogVerbose(@"Receiving is temporarily paused (pending filter operations)..."); - + if (socket4FDBytesAvailable > 0) { [self suspendReceive4Source]; } if (socket6FDBytesAvailable > 0) { [self suspendReceive6Source]; } - + return; } - + if ((socket4FDBytesAvailable == 0) && (socket6FDBytesAvailable == 0)) { LogVerbose(@"No data available to receive..."); - + if (socket4FDBytesAvailable == 0) { [self resumeReceive4Source]; } if (socket6FDBytesAvailable == 0) { [self resumeReceive6Source]; } - + return; } - + // Figure out if we should receive on socket4 or socket6 - + BOOL doReceive4; - + if (flags & kDidConnect) { // Connected socket - + doReceive4 = (socket4FD != SOCKET_NULL); } else { // Non-Connected socket - + if (socket4FDBytesAvailable > 0) { if (socket6FDBytesAvailable > 0) { // Bytes available on socket4 & socket6 - + doReceive4 = (flags & kFlipFlop) ? YES : NO; - + flags ^= kFlipFlop; // flags = flags xor kFlipFlop; (toggle flip flop bit) } else { @@ -4537,42 +4541,42 @@ - (void)doReceive doReceive4 = NO; } } - + // Perform socket IO - + ssize_t result = 0; - + NSData *data = nil; NSData *addr4 = nil; NSData *addr6 = nil; - + if (doReceive4) { NSAssert(socket4FDBytesAvailable > 0, @"Invalid logic"); LogVerbose(@"Receiving on IPv4"); - + struct sockaddr_in sockaddr4; socklen_t sockaddr4len = sizeof(sockaddr4); - - // #222: GCD does not necessarily return the size of an entire UDP packet + + // #222: GCD does not necessarily return the size of an entire UDP packet // from dispatch_source_get_data(), so we must use the maximum packet size. size_t bufSize = max4ReceiveSize; void *buf = malloc(bufSize); - + result = recvfrom(socket4FD, buf, bufSize, 0, (struct sockaddr *)&sockaddr4, &sockaddr4len); LogVerbose(@"recvfrom(socket4FD) = %i", (int)result); - + if (result > 0) { if ((size_t)result >= socket4FDBytesAvailable) socket4FDBytesAvailable = 0; else socket4FDBytesAvailable -= result; - + if ((size_t)result != bufSize) { buf = realloc(buf, result); } - + data = [NSData dataWithBytesNoCopy:buf length:result freeWhenDone:YES]; addr4 = [NSData dataWithBytes:&sockaddr4 length:sockaddr4len]; } @@ -4587,29 +4591,29 @@ - (void)doReceive { NSAssert(socket6FDBytesAvailable > 0, @"Invalid logic"); LogVerbose(@"Receiving on IPv6"); - + struct sockaddr_in6 sockaddr6; socklen_t sockaddr6len = sizeof(sockaddr6); - - // #222: GCD does not necessarily return the size of an entire UDP packet + + // #222: GCD does not necessarily return the size of an entire UDP packet // from dispatch_source_get_data(), so we must use the maximum packet size. size_t bufSize = max6ReceiveSize; void *buf = malloc(bufSize); - + result = recvfrom(socket6FD, buf, bufSize, 0, (struct sockaddr *)&sockaddr6, &sockaddr6len); LogVerbose(@"recvfrom(socket6FD) -> %i", (int)result); - + if (result > 0) { if ((size_t)result >= socket6FDBytesAvailable) socket6FDBytesAvailable = 0; else socket6FDBytesAvailable -= result; - + if ((size_t)result != bufSize) { buf = realloc(buf, result); } - + data = [NSData dataWithBytesNoCopy:buf length:result freeWhenDone:YES]; addr6 = [NSData dataWithBytes:&sockaddr6 length:sockaddr6len]; } @@ -4620,14 +4624,14 @@ - (void)doReceive free(buf); } } - - + + BOOL waitingForSocket = NO; BOOL notifiedDelegate = NO; BOOL ignored = NO; - + NSError *socketError = nil; - + if (result == 0) { waitingForSocket = YES; @@ -4648,30 +4652,30 @@ - (void)doReceive if (addr6 && ![self isConnectedToAddress6:addr6]) ignored = YES; } - + NSData *addr = (addr4 != nil) ? addr4 : addr6; - + if (!ignored) { if (receiveFilterBlock && receiveFilterQueue) { // Run data through filter, and if approved, notify delegate - + __block id filterContext = nil; __block BOOL allowed = NO; - + if (receiveFilterAsync) { pendingFilterOperations++; dispatch_async(receiveFilterQueue, ^{ @autoreleasepool { - + allowed = self->receiveFilterBlock(data, addr, &filterContext); - + // Transition back to socketQueue to get the current delegate / delegateQueue dispatch_async(self->socketQueue, ^{ @autoreleasepool { - + self->pendingFilterOperations--; - + if (allowed) { [self notifyDidReceiveData:data fromAddress:addr withFilterContext:filterContext]; @@ -4680,7 +4684,7 @@ - (void)doReceive { LogVerbose(@"received packet silently dropped by receiveFilter"); } - + if (self->flags & kReceiveOnce) { if (allowed) @@ -4703,10 +4707,10 @@ - (void)doReceive else // if (!receiveFilterAsync) { dispatch_sync(receiveFilterQueue, ^{ @autoreleasepool { - + allowed = self->receiveFilterBlock(data, addr, &filterContext); }}); - + if (allowed) { [self notifyDidReceiveData:data fromAddress:addr withFilterContext:filterContext]; @@ -4726,11 +4730,11 @@ - (void)doReceive } } } - + if (waitingForSocket) { // Wait for a notification of available data. - + if (socket4FDBytesAvailable == 0) { [self resumeReceive4Source]; } @@ -4773,7 +4777,7 @@ - (void)doReceive - (void)doReceiveEOF { LogTrace(); - + [self closeWithError:[self socketClosedError]]; } @@ -4784,26 +4788,26 @@ - (void)doReceiveEOF - (void)closeWithError:(NSError *)error { LogVerbose(@"closeWithError: %@", error); - + NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - + if (currentSend) [self endCurrentSend]; - + [sendQueue removeAllObjects]; - + // If a socket has been created, we should notify the delegate. BOOL shouldCallDelegate = (flags & kDidCreateSockets) ? YES : NO; - + // Close all sockets, send/receive sources, cfstreams, etc #if TARGET_OS_IPHONE [self removeStreamsFromRunLoop]; [self closeReadAndWriteStreams]; #endif [self closeSockets]; - + // Clear all flags (config remains as is) flags = 0; - + if (shouldCallDelegate) { [self notifyDidCloseWithError:error]; @@ -4813,12 +4817,12 @@ - (void)closeWithError:(NSError *)error - (void)close { LogTrace(); - + dispatch_block_t block = ^{ @autoreleasepool { - + [self closeWithError:nil]; }}; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else @@ -4828,17 +4832,17 @@ - (void)close - (void)closeAfterSending { LogTrace(); - + dispatch_block_t block = ^{ @autoreleasepool { - + self->flags |= kCloseAfterSends; - + if (self->currentSend == nil && [self->sendQueue count] == 0) { [self closeWithError:nil]; } }}; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else @@ -4860,7 +4864,7 @@ + (void)startListenerThreadIfNeeded { static dispatch_once_t predicate; dispatch_once(&predicate, ^{ - + listenerThread = [[NSThread alloc] initWithTarget:self selector:@selector(listenerThread:) object:nil]; @@ -4871,11 +4875,11 @@ + (void)startListenerThreadIfNeeded + (void)listenerThread:(id)unused { @autoreleasepool { - + [[NSThread currentThread] setName:GCDAsyncUdpSocketThreadName]; - + LogInfo(@"ListenerThread: Started"); - + // We can't run the run loop unless it has an associated input source or a timer. // So we'll just create a timer that will never fire - unless the server runs for a decades. [NSTimer scheduledTimerWithTimeInterval:[[NSDate distantFuture] timeIntervalSinceNow] @@ -4883,9 +4887,9 @@ + (void)listenerThread:(id)unused selector:@selector(ignore:) userInfo:nil repeats:YES]; - + [[NSRunLoop currentRunLoop] run]; - + LogInfo(@"ListenerThread: Stopped"); } } @@ -4894,18 +4898,18 @@ + (void)addStreamListener:(GCDAsyncUdpSocket *)asyncUdpSocket { LogTrace(); NSAssert([NSThread currentThread] == listenerThread, @"Invoked on wrong thread"); - + CFRunLoopRef runLoop = CFRunLoopGetCurrent(); - + if (asyncUdpSocket->readStream4) CFReadStreamScheduleWithRunLoop(asyncUdpSocket->readStream4, runLoop, kCFRunLoopDefaultMode); - + if (asyncUdpSocket->readStream6) CFReadStreamScheduleWithRunLoop(asyncUdpSocket->readStream6, runLoop, kCFRunLoopDefaultMode); - + if (asyncUdpSocket->writeStream4) CFWriteStreamScheduleWithRunLoop(asyncUdpSocket->writeStream4, runLoop, kCFRunLoopDefaultMode); - + if (asyncUdpSocket->writeStream6) CFWriteStreamScheduleWithRunLoop(asyncUdpSocket->writeStream6, runLoop, kCFRunLoopDefaultMode); } @@ -4914,18 +4918,18 @@ + (void)removeStreamListener:(GCDAsyncUdpSocket *)asyncUdpSocket { LogTrace(); NSAssert([NSThread currentThread] == listenerThread, @"Invoked on wrong thread"); - + CFRunLoopRef runLoop = CFRunLoopGetCurrent(); - + if (asyncUdpSocket->readStream4) CFReadStreamUnscheduleFromRunLoop(asyncUdpSocket->readStream4, runLoop, kCFRunLoopDefaultMode); - + if (asyncUdpSocket->readStream6) CFReadStreamUnscheduleFromRunLoop(asyncUdpSocket->readStream6, runLoop, kCFRunLoopDefaultMode); - + if (asyncUdpSocket->writeStream4) CFWriteStreamUnscheduleFromRunLoop(asyncUdpSocket->writeStream4, runLoop, kCFRunLoopDefaultMode); - + if (asyncUdpSocket->writeStream6) CFWriteStreamUnscheduleFromRunLoop(asyncUdpSocket->writeStream6, runLoop, kCFRunLoopDefaultMode); } @@ -4957,23 +4961,23 @@ static void CFReadStreamCallback(CFReadStreamRef stream, CFStreamEventType type, { error = [asyncUdpSocket socketClosedError]; } - + dispatch_async(asyncUdpSocket->socketQueue, ^{ @autoreleasepool { - + LogCVerbose(@"CFReadStreamCallback - %@", (type == kCFStreamEventErrorOccurred) ? @"Error" : @"EndEncountered"); - + if (stream != asyncUdpSocket->readStream4 && stream != asyncUdpSocket->readStream6 ) { LogCVerbose(@"CFReadStreamCallback - Ignored"); return_from_block; } - + [asyncUdpSocket closeWithError:error]; - + }}); - + break; } default: @@ -5012,23 +5016,23 @@ static void CFWriteStreamCallback(CFWriteStreamRef stream, CFStreamEventType typ { error = [asyncUdpSocket socketClosedError]; } - + dispatch_async(asyncUdpSocket->socketQueue, ^{ @autoreleasepool { - + LogCVerbose(@"CFWriteStreamCallback - %@", (type == kCFStreamEventErrorOccurred) ? @"Error" : @"EndEncountered"); - + if (stream != asyncUdpSocket->writeStream4 && stream != asyncUdpSocket->writeStream6 ) { LogCVerbose(@"CFWriteStreamCallback - Ignored"); return_from_block; } - + [asyncUdpSocket closeWithError:error]; - + }}); - + break; } default: @@ -5044,25 +5048,25 @@ - (BOOL)createReadAndWriteStreams:(NSError **)errPtr { LogTrace(); NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - + NSError *err = nil; - + if (readStream4 || writeStream4 || readStream6 || writeStream6) { // Streams already created return YES; } - + if (socket4FD == SOCKET_NULL && socket6FD == SOCKET_NULL) { err = [self otherError:@"Cannot create streams without a file descriptor"]; goto Failed; } - + // Create streams - + LogVerbose(@"Creating read and write stream(s)..."); - + if (socket4FD != SOCKET_NULL) { CFStreamCreatePairWithSocket(NULL, (CFSocketNativeHandle)socket4FD, &readStream4, &writeStream4); @@ -5072,7 +5076,7 @@ - (BOOL)createReadAndWriteStreams:(NSError **)errPtr goto Failed; } } - + if (socket6FD != SOCKET_NULL) { CFStreamCreatePairWithSocket(NULL, (CFSocketNativeHandle)socket6FD, &readStream6, &writeStream6); @@ -5082,17 +5086,17 @@ - (BOOL)createReadAndWriteStreams:(NSError **)errPtr goto Failed; } } - + // Ensure the CFStream's don't close our underlying socket - + CFReadStreamSetProperty(readStream4, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanFalse); CFWriteStreamSetProperty(writeStream4, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanFalse); - + CFReadStreamSetProperty(readStream6, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanFalse); CFWriteStreamSetProperty(writeStream6, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanFalse); - + return YES; - + Failed: if (readStream4) { @@ -5118,34 +5122,34 @@ - (BOOL)createReadAndWriteStreams:(NSError **)errPtr CFRelease(writeStream6); writeStream6 = NULL; } - + if (errPtr) *errPtr = err; - + return NO; } - (BOOL)registerForStreamCallbacks:(NSError **)errPtr { LogTrace(); - + NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); NSAssert(readStream4 || writeStream4 || readStream6 || writeStream6, @"Read/Write streams are null"); - + NSError *err = nil; - + streamContext.version = 0; streamContext.info = (__bridge void *)self; streamContext.retain = nil; streamContext.release = nil; streamContext.copyDescription = nil; - + CFOptionFlags readStreamEvents = kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered; CFOptionFlags writeStreamEvents = kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered; - + // readStreamEvents |= (kCFStreamEventOpenCompleted | kCFStreamEventHasBytesAvailable); // writeStreamEvents |= (kCFStreamEventOpenCompleted | kCFStreamEventCanAcceptBytes); - + if (socket4FD != SOCKET_NULL) { if (readStream4 == NULL || writeStream4 == NULL) @@ -5153,17 +5157,17 @@ - (BOOL)registerForStreamCallbacks:(NSError **)errPtr err = [self otherError:@"Read/Write stream4 is null"]; goto Failed; } - + BOOL r1 = CFReadStreamSetClient(readStream4, readStreamEvents, &CFReadStreamCallback, &streamContext); BOOL r2 = CFWriteStreamSetClient(writeStream4, writeStreamEvents, &CFWriteStreamCallback, &streamContext); - + if (!r1 || !r2) { err = [self otherError:@"Error in CFStreamSetClient(), [IPv4]"]; goto Failed; } } - + if (socket6FD != SOCKET_NULL) { if (readStream6 == NULL || writeStream6 == NULL) @@ -5171,19 +5175,19 @@ - (BOOL)registerForStreamCallbacks:(NSError **)errPtr err = [self otherError:@"Read/Write stream6 is null"]; goto Failed; } - + BOOL r1 = CFReadStreamSetClient(readStream6, readStreamEvents, &CFReadStreamCallback, &streamContext); BOOL r2 = CFWriteStreamSetClient(writeStream6, writeStreamEvents, &CFWriteStreamCallback, &streamContext); - + if (!r1 || !r2) { err = [self otherError:@"Error in CFStreamSetClient() [IPv6]"]; goto Failed; } } - + return YES; - + Failed: if (readStream4) { CFReadStreamSetClient(readStream4, kCFStreamEventNone, NULL, NULL); @@ -5197,7 +5201,7 @@ - (BOOL)registerForStreamCallbacks:(NSError **)errPtr if (writeStream6) { CFWriteStreamSetClient(writeStream6, kCFStreamEventNone, NULL, NULL); } - + if (errPtr) *errPtr = err; return NO; } @@ -5205,10 +5209,10 @@ - (BOOL)registerForStreamCallbacks:(NSError **)errPtr - (BOOL)addStreamsToRunLoop:(NSError **)errPtr { LogTrace(); - + NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); NSAssert(readStream4 || writeStream4 || readStream6 || writeStream6, @"Read/Write streams are null"); - + if (!(flags & kAddedStreamListener)) { [[self class] startListenerThreadIfNeeded]; @@ -5216,48 +5220,48 @@ - (BOOL)addStreamsToRunLoop:(NSError **)errPtr onThread:listenerThread withObject:self waitUntilDone:YES]; - + flags |= kAddedStreamListener; } - + return YES; } - (BOOL)openStreams:(NSError **)errPtr { LogTrace(); - + NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); NSAssert(readStream4 || writeStream4 || readStream6 || writeStream6, @"Read/Write streams are null"); - + NSError *err = nil; - + if (socket4FD != SOCKET_NULL) { BOOL r1 = CFReadStreamOpen(readStream4); BOOL r2 = CFWriteStreamOpen(writeStream4); - + if (!r1 || !r2) { err = [self otherError:@"Error in CFStreamOpen() [IPv4]"]; goto Failed; } } - + if (socket6FD != SOCKET_NULL) { BOOL r1 = CFReadStreamOpen(readStream6); BOOL r2 = CFWriteStreamOpen(writeStream6); - + if (!r1 || !r2) { err = [self otherError:@"Error in CFStreamOpen() [IPv6]"]; goto Failed; } } - + return YES; - + Failed: if (errPtr) *errPtr = err; return NO; @@ -5267,14 +5271,14 @@ - (void)removeStreamsFromRunLoop { LogTrace(); NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue"); - + if (flags & kAddedStreamListener) { [[self class] performSelector:@selector(removeStreamListener:) onThread:listenerThread withObject:self waitUntilDone:YES]; - + flags &= ~kAddedStreamListener; } } @@ -5282,7 +5286,7 @@ - (void)removeStreamsFromRunLoop - (void)closeReadAndWriteStreams { LogTrace(); - + if (readStream4) { CFReadStreamSetClient(readStream4, kCFStreamEventNone, NULL, NULL); @@ -5319,16 +5323,16 @@ - (void)closeReadAndWriteStreams - (void)applicationWillEnterForeground:(NSNotification *)notification { LogTrace(); - + // If the application was backgrounded, then iOS may have shut down our sockets. // So we take a quick look to see if any of them received an EOF. - + dispatch_block_t block = ^{ @autoreleasepool { - + [self resumeReceive4Source]; [self resumeReceive6Source]; }}; - + if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) block(); else @@ -5373,7 +5377,7 @@ - (int)socketFD THIS_FILE, THIS_METHOD); return SOCKET_NULL; } - + if (socket4FD != SOCKET_NULL) return socket4FD; else @@ -5388,7 +5392,7 @@ - (int)socket4FD THIS_FILE, THIS_METHOD); return SOCKET_NULL; } - + return socket4FD; } @@ -5400,7 +5404,7 @@ - (int)socket6FD THIS_FILE, THIS_METHOD); return SOCKET_NULL; } - + return socket6FD; } @@ -5414,16 +5418,16 @@ - (CFReadStreamRef)readStream THIS_FILE, THIS_METHOD); return NULL; } - + NSError *err = nil; if (![self createReadAndWriteStreams:&err]) { LogError(@"Error creating CFStream(s): %@", err); return NULL; } - + // Todo... - + if (readStream4) return readStream4; else @@ -5438,14 +5442,14 @@ - (CFWriteStreamRef)writeStream THIS_FILE, THIS_METHOD); return NULL; } - + NSError *err = nil; if (![self createReadAndWriteStreams:&err]) { LogError(@"Error creating CFStream(s): %@", err); return NULL; } - + if (writeStream4) return writeStream4; else @@ -5460,54 +5464,54 @@ - (BOOL)enableBackgroundingOnSockets THIS_FILE, THIS_METHOD); return NO; } - + // Why is this commented out? // See comments below. - + // NSError *err = nil; // if (![self createReadAndWriteStreams:&err]) // { // LogError(@"Error creating CFStream(s): %@", err); // return NO; // } -// +// // LogVerbose(@"Enabling backgrouding on socket"); -// +// // BOOL r1, r2; -// +// // if (readStream4 && writeStream4) // { // r1 = CFReadStreamSetProperty(readStream4, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP); // r2 = CFWriteStreamSetProperty(writeStream4, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP); -// +// // if (!r1 || !r2) // { // LogError(@"Error setting voip type (IPv4)"); // return NO; // } // } -// +// // if (readStream6 && writeStream6) // { // r1 = CFReadStreamSetProperty(readStream6, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP); // r2 = CFWriteStreamSetProperty(writeStream6, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP); -// +// // if (!r1 || !r2) // { // LogError(@"Error setting voip type (IPv6)"); // return NO; // } // } -// +// // return YES; - + // The above code will actually appear to work. // The methods will return YES, and everything will appear fine. - // + // // One tiny problem: the sockets will still get closed when the app gets backgrounded. - // + // // Apple does not officially support backgrounding UDP sockets. - + return NO; } @@ -5520,24 +5524,24 @@ - (BOOL)enableBackgroundingOnSockets + (NSString *)hostFromSockaddr4:(const struct sockaddr_in *)pSockaddr4 { char addrBuf[INET_ADDRSTRLEN]; - + if (inet_ntop(AF_INET, &pSockaddr4->sin_addr, addrBuf, (socklen_t)sizeof(addrBuf)) == NULL) { addrBuf[0] = '\0'; } - + return [NSString stringWithCString:addrBuf encoding:NSASCIIStringEncoding]; } + (NSString *)hostFromSockaddr6:(const struct sockaddr_in6 *)pSockaddr6 { char addrBuf[INET6_ADDRSTRLEN]; - + if (inet_ntop(AF_INET6, &pSockaddr6->sin6_addr, addrBuf, (socklen_t)sizeof(addrBuf)) == NULL) { addrBuf[0] = '\0'; } - + return [NSString stringWithCString:addrBuf encoding:NSASCIIStringEncoding]; } @@ -5555,7 +5559,7 @@ + (NSString *)hostFromAddress:(NSData *)address { NSString *host = nil; [self getHost:&host port:NULL family:NULL fromAddress:address]; - + return host; } @@ -5563,7 +5567,7 @@ + (uint16_t)portFromAddress:(NSData *)address { uint16_t port = 0; [self getHost:NULL port:&port family:NULL fromAddress:address]; - + return port; } @@ -5571,7 +5575,7 @@ + (int)familyFromAddress:(NSData *)address { int af = AF_UNSPEC; [self getHost:NULL port:NULL family:&af fromAddress:address]; - + return af; } @@ -5579,7 +5583,7 @@ + (BOOL)isIPv4Address:(NSData *)address { int af = AF_UNSPEC; [self getHost:NULL port:NULL family:&af fromAddress:address]; - + return (af == AF_INET); } @@ -5587,7 +5591,7 @@ + (BOOL)isIPv6Address:(NSData *)address { int af = AF_UNSPEC; [self getHost:NULL port:NULL family:&af fromAddress:address]; - + return (af == AF_INET6); } @@ -5601,17 +5605,17 @@ + (BOOL)getHost:(NSString **)hostPtr port:(uint16_t *)portPtr family:(int *)afPt if ([address length] >= sizeof(struct sockaddr)) { const struct sockaddr *addrX = (const struct sockaddr *)[address bytes]; - + if (addrX->sa_family == AF_INET) { if ([address length] >= sizeof(struct sockaddr_in)) { const struct sockaddr_in *addr4 = (const struct sockaddr_in *)(const void *)addrX; - + if (hostPtr) *hostPtr = [self hostFromSockaddr4:addr4]; if (portPtr) *portPtr = [self portFromSockaddr4:addr4]; if (afPtr) *afPtr = AF_INET; - + return YES; } } @@ -5620,20 +5624,20 @@ + (BOOL)getHost:(NSString **)hostPtr port:(uint16_t *)portPtr family:(int *)afPt if ([address length] >= sizeof(struct sockaddr_in6)) { const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)(const void *)addrX; - + if (hostPtr) *hostPtr = [self hostFromSockaddr6:addr6]; if (portPtr) *portPtr = [self portFromSockaddr6:addr6]; if (afPtr) *afPtr = AF_INET6; - + return YES; } } } - + if (hostPtr) *hostPtr = nil; if (portPtr) *portPtr = 0; if (afPtr) *afPtr = AF_UNSPEC; - + return NO; } diff --git a/WebDriverAgent/WebDriverAgentLib/Vendor/CocoaHTTPServer/HTTPMessage.h b/WebDriverAgent/WebDriverAgentLib/Vendor/CocoaHTTPServer/HTTPMessage.h index 04e0bd2f40..401830e56f 100644 --- a/WebDriverAgent/WebDriverAgentLib/Vendor/CocoaHTTPServer/HTTPMessage.h +++ b/WebDriverAgent/WebDriverAgentLib/Vendor/CocoaHTTPServer/HTTPMessage.h @@ -1,21 +1,26 @@ /** - * The HTTPMessage class is a simple Objective-C wrapper around Apple's CFHTTPMessage class. + * The HTTPMessage class is a simple Objective-C wrapper for HTTP message parsing. + * Migrated from CFHTTPMessage to use Foundation and Network framework. **/ #import -#if TARGET_OS_IPHONE -// Note: You may need to add the CFNetwork Framework to your project -#import -#endif - -#define HTTPVersion1_0 ((NSString *)kCFHTTPVersion1_0) -#define HTTPVersion1_1 ((NSString *)kCFHTTPVersion1_1) +#define HTTPVersion1_0 @"HTTP/1.0" +#define HTTPVersion1_1 @"HTTP/1.1" @interface HTTPMessage : NSObject { - CFHTTPMessageRef message; + NSMutableDictionary *_headers; + NSMutableData *_body; + NSString *_version; + NSString *_method; + NSURL *_url; + NSInteger _statusCode; + NSString *_statusDescription; + BOOL _isRequest; + BOOL _headerComplete; + NSMutableData *_rawData; } - (id)initEmptyRequest; diff --git a/WebDriverAgent/WebDriverAgentLib/Vendor/CocoaHTTPServer/HTTPMessage.m b/WebDriverAgent/WebDriverAgentLib/Vendor/CocoaHTTPServer/HTTPMessage.m index 345d84759e..920f7a2800 100644 --- a/WebDriverAgent/WebDriverAgentLib/Vendor/CocoaHTTPServer/HTTPMessage.m +++ b/WebDriverAgent/WebDriverAgentLib/Vendor/CocoaHTTPServer/HTTPMessage.m @@ -8,107 +8,350 @@ @implementation HTTPMessage -- (id)initEmptyRequest +- (id)init { if ((self = [super init])) { - message = CFHTTPMessageCreateEmpty(NULL, YES); + _headers = [[NSMutableDictionary alloc] init]; + _body = [[NSMutableData alloc] init]; + _rawData = [[NSMutableData alloc] init]; + _version = HTTPVersion1_1; + _headerComplete = NO; + _isRequest = YES; + } + return self; +} + +- (id)initEmptyRequest +{ + if ((self = [self init])) + { + _isRequest = YES; } return self; } - (id)initRequestWithMethod:(NSString *)method URL:(NSURL *)url version:(NSString *)version { - if ((self = [super init])) + if ((self = [self init])) { - message = CFHTTPMessageCreateRequest(NULL, - (__bridge CFStringRef)method, - (__bridge CFURLRef)url, - (__bridge CFStringRef)version); + _isRequest = YES; + _method = [method copy]; + _url = [url copy]; + _version = version ? [version copy] : HTTPVersion1_1; } return self; } - (id)initResponseWithStatusCode:(NSInteger)code description:(NSString *)description version:(NSString *)version { - if ((self = [super init])) + if ((self = [self init])) { - message = CFHTTPMessageCreateResponse(NULL, - (CFIndex)code, - (__bridge CFStringRef)description, - (__bridge CFStringRef)version); + _isRequest = NO; + _statusCode = code; + _statusDescription = [description copy]; + _version = version ? [version copy] : HTTPVersion1_1; } return self; } -- (void)dealloc +- (BOOL)appendData:(NSData *)data { - if (message) + if (!data || [data length] == 0) { - CFRelease(message); + return NO; } + + [_rawData appendData:data]; + + if (!_headerComplete) + { + // Look for the end of headers (CRLF CRLF or LF LF) + NSData *headerEndMarker = [@"\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]; + NSRange headerEndRange = [_rawData rangeOfData:headerEndMarker options:0 range:NSMakeRange(0, [_rawData length])]; + + if (headerEndRange.location == NSNotFound) + { + // Also check for LF LF (some clients use this) + NSData *lfMarker = [@"\n\n" dataUsingEncoding:NSASCIIStringEncoding]; + headerEndRange = [_rawData rangeOfData:lfMarker options:0 range:NSMakeRange(0, [_rawData length])]; + } + + if (headerEndRange.location != NSNotFound) + { + _headerComplete = YES; + + // Parse the header data + NSData *headerData = [_rawData subdataWithRange:NSMakeRange(0, headerEndRange.location + headerEndRange.length)]; + NSString *headerString = [[NSString alloc] initWithData:headerData encoding:NSASCIIStringEncoding]; + + if (headerString) + { + [self parseHeaders:headerString]; + } + + // Extract body data if any + NSUInteger bodyStart = headerEndRange.location + headerEndRange.length; + if ([_rawData length] > bodyStart) + { + NSData *bodyData = [_rawData subdataWithRange:NSMakeRange(bodyStart, [_rawData length] - bodyStart)]; + [_body appendData:bodyData]; + } + + [_rawData setLength:0]; + } + } + else + { + // Headers are complete, append to body + [_body appendData:data]; + } + + return YES; } -- (BOOL)appendData:(NSData *)data +- (void)parseHeaders:(NSString *)headerString { - return CFHTTPMessageAppendBytes(message, [data bytes], [data length]); + NSArray *lines; + + // Try splitting by "\r\n" first (standard HTTP line ending) + // Check if the string actually contains "\r\n" delimiter + if ([headerString rangeOfString:@"\r\n"].location != NSNotFound) + { + // Found "\r\n" delimiter, use this split + lines = [headerString componentsSeparatedByString:@"\r\n"]; + } + else + { + // No "\r\n" found, try "\n" (some clients use just LF) + lines = [headerString componentsSeparatedByString:@"\n"]; + } + + // componentsSeparatedByString: always returns at least one element, + // so check if we have meaningful content (non-empty first line) + if ([lines count] == 0 || [[lines objectAtIndex:0] length] == 0) + { + return; + } + + // Parse first line (request line or status line) + NSString *firstLine = [lines objectAtIndex:0]; + NSArray *firstLineParts = [firstLine componentsSeparatedByString:@" "]; + + if (_isRequest && [firstLineParts count] >= 3) + { + // Request line: METHOD URL VERSION + _method = [[firstLineParts objectAtIndex:0] copy]; + NSString *urlString = [firstLineParts objectAtIndex:1]; + + // Handle both absolute URLs and relative paths + // Try absolute URL first + NSURL *parsedURL = [NSURL URLWithString:urlString]; + + // If that fails (nil), it's likely a relative path like "/endpoint" + // Create a URL with a base URL to handle relative paths + if (!parsedURL) + { + // Use a dummy base URL to allow relative path parsing + NSURL *baseURL = [NSURL URLWithString:@"http://localhost"]; + parsedURL = [NSURL URLWithString:urlString relativeToURL:baseURL]; + } + + _url = [parsedURL copy]; + if ([firstLineParts count] >= 3) + { + _version = [[firstLineParts objectAtIndex:2] copy]; + } + } + else if (!_isRequest && [firstLineParts count] >= 3) + { + // Status line: VERSION CODE DESCRIPTION + _version = [[firstLineParts objectAtIndex:0] copy]; + _statusCode = [[firstLineParts objectAtIndex:1] integerValue]; + NSMutableArray *descParts = [NSMutableArray arrayWithArray:firstLineParts]; + [descParts removeObjectAtIndex:0]; + [descParts removeObjectAtIndex:0]; + _statusDescription = [[descParts componentsJoinedByString:@" "] copy]; + } + + // Parse header fields + for (NSUInteger i = 1; i < [lines count]; i++) + { + NSString *line = [lines objectAtIndex:i]; + if ([line length] == 0) + { + continue; + } + + NSRange colonRange = [line rangeOfString:@":"]; + if (colonRange.location != NSNotFound) + { + NSString *headerName = [[line substringToIndex:colonRange.location] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; + NSString *headerValue = [[line substringFromIndex:colonRange.location + 1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; + + if ([headerName length] > 0) + { + // HTTP headers are case-insensitive, but we'll store them with their original case + // For lookup, we'll use case-insensitive comparison + [_headers setObject:headerValue forKey:headerName]; + } + } + } } - (BOOL)isHeaderComplete { - return CFHTTPMessageIsHeaderComplete(message); + return _headerComplete; } - (NSString *)version { - return (__bridge_transfer NSString *)CFHTTPMessageCopyVersion(message); + return _version; } - (NSString *)method { - return (__bridge_transfer NSString *)CFHTTPMessageCopyRequestMethod(message); + return _method; } - (NSURL *)url { - return (__bridge_transfer NSURL *)CFHTTPMessageCopyRequestURL(message); + return _url; } - (NSInteger)statusCode { - return (NSInteger)CFHTTPMessageGetResponseStatusCode(message); + return _statusCode; } - (NSDictionary *)allHeaderFields { - return (__bridge_transfer NSDictionary *)CFHTTPMessageCopyAllHeaderFields(message); + return [_headers copy]; } - (NSString *)headerField:(NSString *)headerField { - return (__bridge_transfer NSString *)CFHTTPMessageCopyHeaderFieldValue(message, (__bridge CFStringRef)headerField); + // Case-insensitive lookup + for (NSString *key in [_headers allKeys]) + { + if ([key caseInsensitiveCompare:headerField] == NSOrderedSame) + { + return [_headers objectForKey:key]; + } + } + return nil; } - (void)setHeaderField:(NSString *)headerField value:(NSString *)headerFieldValue { - CFHTTPMessageSetHeaderFieldValue(message, - (__bridge CFStringRef)headerField, - (__bridge CFStringRef)headerFieldValue); + if (headerField && headerFieldValue) + { + // Remove existing header with same name (case-insensitive) + NSMutableArray *keysToRemove = [NSMutableArray array]; + for (NSString *key in [_headers allKeys]) + { + if ([key caseInsensitiveCompare:headerField] == NSOrderedSame) + { + [keysToRemove addObject:key]; + } + } + [_headers removeObjectsForKeys:keysToRemove]; + + // Add new header + [_headers setObject:headerFieldValue forKey:headerField]; + } } - (NSData *)messageData { - return (__bridge_transfer NSData *)CFHTTPMessageCopySerializedMessage(message); + NSMutableString *messageString = [NSMutableString string]; + + if (_isRequest) + { + // Request line + // For relative URLs, use the path component; for absolute URLs, use absoluteString + NSString *urlString = nil; + if (_url) + { + // If it's a relative URL (has a base), use the relative path + // Otherwise use absoluteString or path + if ([_url baseURL]) + { + // Relative URL - use the relative portion + urlString = [_url relativeString]; + } + else + { + // Absolute URL + urlString = [_url absoluteString]; + if (!urlString) + { + urlString = [_url path]; + } + } + } + [messageString appendFormat:@"%@ %@ %@\r\n", _method ?: @"GET", urlString ?: @"/", _version ?: HTTPVersion1_1]; + } + else + { + // Status line + [messageString appendFormat:@"%@ %ld %@\r\n", _version ?: HTTPVersion1_1, (long)_statusCode, _statusDescription ?: @""]; + } + + // Headers + for (NSString *key in [_headers allKeys]) + { + NSString *value = [_headers objectForKey:key]; + [messageString appendFormat:@"%@: %@\r\n", key, value]; + } + + // Empty line to separate headers from body + [messageString appendString:@"\r\n"]; + + NSMutableData *data = [NSMutableData dataWithData:(id)[messageString dataUsingEncoding:NSASCIIStringEncoding]]; + + // Append body if present + if ([_body length] > 0) + { + [data appendData:_body]; + } + + return data; } - (NSData *)body { - return (__bridge_transfer NSData *)CFHTTPMessageCopyBody(message); + return [_body copy]; } - (void)setBody:(NSData *)body { - CFHTTPMessageSetBody(message, (__bridge CFDataRef)body); + if (body) + { + _body = [body mutableCopy]; + } + else + { + _body = [[NSMutableData alloc] init]; + } +} + +- (void)dealloc +{ + // ARC automatically releases all instance variables, but we include this + // for clarity and to match the pattern of the original CFNetwork implementation. + // All Objective-C objects (_headers, _body, _rawData, _version, _method, _url, _statusDescription) + // will be automatically released by ARC when this object is deallocated. +#if ! __has_feature(objc_arc) + [_headers release]; + [_body release]; + [_rawData release]; + [_version release]; + [_method release]; + [_url release]; + [_statusDescription release]; + [super dealloc]; +#endif } @end diff --git a/WebDriverAgent/WebDriverAgentLib/WebDriverAgentLib.h b/WebDriverAgent/WebDriverAgentLib/WebDriverAgentLib.h index f14994b861..d0e3f7391b 100644 --- a/WebDriverAgent/WebDriverAgentLib/WebDriverAgentLib.h +++ b/WebDriverAgent/WebDriverAgentLib/WebDriverAgentLib.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import @@ -15,6 +14,7 @@ FOUNDATION_EXPORT double WebDriverAgentLib_VersionNumber; //! Project version string for WebDriverAgentLib_. FOUNDATION_EXPORT const unsigned char WebDriverAgentLib_VersionString[]; +#import #import #import #import @@ -38,9 +38,17 @@ FOUNDATION_EXPORT const unsigned char WebDriverAgentLib_VersionString[]; #import #import #import +#import +#import +#import +#import +#import +#import +#import #import #import #import +#import #import #import #import diff --git a/WebDriverAgent/WebDriverAgentRunner/UITestingUITests.m b/WebDriverAgent/WebDriverAgentRunner/UITestingUITests.m index cc7c780739..ad2ff45504 100644 --- a/WebDriverAgent/WebDriverAgentRunner/UITestingUITests.m +++ b/WebDriverAgent/WebDriverAgentRunner/UITestingUITests.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/AppDelegate.h b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/AppDelegate.h index 9561057fd9..ff03ff7766 100644 --- a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/AppDelegate.h +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/AppDelegate.h @@ -3,14 +3,12 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import #import -@interface AppDelegate : UIResponder -@property (strong, nonatomic) UIWindow *window; +@interface AppDelegate : UIResponder @end diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/AppDelegate.m b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/AppDelegate.m index 0a0e1d46dd..102b1887b4 100644 --- a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/AppDelegate.m +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/AppDelegate.m @@ -3,14 +3,36 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "AppDelegate.h" +#import "SceneDelegate.h" @interface AppDelegate () @end @implementation AppDelegate + +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { + // Override point for customization after application launch. + return YES; +} + +#pragma mark - UISceneSession lifecycle + +- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options { + // Called when a new scene session is being created. + // Use this method to select a configuration to create the new scene with. + UISceneConfiguration *configuration = [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role]; + configuration.delegateClass = [SceneDelegate class]; + return configuration; +} + +- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet *)sceneSessions { + // Called when the user discards a scene session. + // If any sessions were discarded while the application was not running, this will be called shortly after `application:didFinishLaunchingWithOptions`. + // Use this method to release any resources that were specific to the discarded scenes, as they will not return. +} + @end diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBAlertViewController.h b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBAlertViewController.h index deb3ddfb40..e5b2088c87 100644 --- a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBAlertViewController.h +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBAlertViewController.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBAlertViewController.m b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBAlertViewController.m index e431e8684d..1f1c77e11b 100644 --- a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBAlertViewController.m +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBAlertViewController.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBAlertViewController.h" diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBNavigationController.h b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBNavigationController.h index c83f8d262f..e9a6b8d95d 100644 --- a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBNavigationController.h +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBNavigationController.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBNavigationController.m b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBNavigationController.m index f404c0ba3e..3b0bec2663 100644 --- a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBNavigationController.m +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBNavigationController.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBNavigationController.h" diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBScrollViewController.h b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBScrollViewController.h index 4c79fb0f51..7cd517b43e 100644 --- a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBScrollViewController.h +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBScrollViewController.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBScrollViewController.m b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBScrollViewController.m index 4a49f9ce6c..a8fe797739 100644 --- a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBScrollViewController.m +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBScrollViewController.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBScrollViewController.h" diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBTableDataSource.h b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBTableDataSource.h index 28cbe4783a..d82f8b6513 100644 --- a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBTableDataSource.h +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBTableDataSource.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBTableDataSource.m b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBTableDataSource.m index ba28aed797..335f28afd5 100644 --- a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBTableDataSource.m +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/FBTableDataSource.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "FBTableDataSource.h" diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/SceneDelegate.h b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/SceneDelegate.h new file mode 100644 index 0000000000..972eb671e9 --- /dev/null +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/SceneDelegate.h @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface SceneDelegate : UIResponder + +@property (strong, nonatomic) UIWindow *window; + +@end + +NS_ASSUME_NONNULL_END + diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/SceneDelegate.m b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/SceneDelegate.m new file mode 100644 index 0000000000..646192cd4a --- /dev/null +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/SceneDelegate.m @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import "SceneDelegate.h" + +@implementation SceneDelegate + +- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions { + // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. + // If using a storyboard, the `window` property will automatically be set and attached to the scene. + // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession:` instead). +} + +- (void)sceneDidDisconnect:(UIScene *)scene { + // Called as the scene is being released by the system. + // This occurs shortly after the scene enters the background, or when its session is discarded. + // Release any resources associated with this scene that can be re-created the next time the scene connects. + // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). +} + +- (void)sceneDidBecomeActive:(UIScene *)scene { + // Called when the scene has moved from an inactive state to an active state. + // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. +} + +- (void)sceneWillResignActive:(UIScene *)scene { + // Called when the scene will move from an active state to an inactive state. + // This may occur due to temporary interruptions (ex. an incoming phone call). +} + +- (void)sceneWillEnterForeground:(UIScene *)scene { + // Called as the scene transitions from the background to the foreground. + // Use this method to undo the changes made on entering the background. +} + +- (void)sceneDidEnterBackground:(UIScene *)scene { + // Called as the scene transitions from the foreground to the background. + // Use this method to save data, release shared resources, and store enough scene-specific state information + // to restore the scene back to its current state. +} + +@end + diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchSpotView.h b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchSpotView.h index 3a312cb884..ed6a9cd6c5 100644 --- a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchSpotView.h +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchSpotView.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the -* LICENSE file in the root directory of this source tree. An additional grant -* of patent rights can be found in the PATENTS file in the same directory. +* LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchSpotView.m b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchSpotView.m index 539add43d7..ed7969404a 100644 --- a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchSpotView.m +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchSpotView.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the -* LICENSE file in the root directory of this source tree. An additional grant -* of patent rights can be found in the PATENTS file in the same directory. +* LICENSE file in the root directory of this source tree. */ #import "TouchSpotView.h" diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchViewController.h b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchViewController.h index 33bd085985..7125306a3a 100644 --- a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchViewController.h +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchViewController.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the -* LICENSE file in the root directory of this source tree. An additional grant -* of patent rights can be found in the PATENTS file in the same directory. +* LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchViewController.m b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchViewController.m index 1fd07671c3..25b3f99300 100644 --- a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchViewController.m +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchViewController.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the -* LICENSE file in the root directory of this source tree. An additional grant -* of patent rights can be found in the PATENTS file in the same directory. +* LICENSE file in the root directory of this source tree. */ #import "TouchViewController.h" diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchableView.h b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchableView.h index 46111c0185..53d0c1836e 100644 --- a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchableView.h +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchableView.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the -* LICENSE file in the root directory of this source tree. An additional grant -* of patent rights can be found in the PATENTS file in the same directory. +* LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchableView.m b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchableView.m index 55b2fd11ef..9e7412ab7b 100644 --- a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchableView.m +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/TouchableView.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the -* LICENSE file in the root directory of this source tree. An additional grant -* of patent rights can be found in the PATENTS file in the same directory. +* LICENSE file in the root directory of this source tree. */ #import "TouchableView.h" diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/ViewController.h b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/ViewController.h index e4df859ab4..9349604846 100644 --- a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/ViewController.h +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/ViewController.h @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/ViewController.m b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/ViewController.m index 7807e59f11..1267c28be4 100644 --- a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/ViewController.m +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Classes/ViewController.m @@ -3,8 +3,7 @@ * All rights reserved. * * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. An additional grant - * of patent rights can be found in the PATENTS file in the same directory. + * LICENSE file in the root directory of this source tree. */ #import "ViewController.h" diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Info.plist b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Info.plist index 2dfb754cd6..5dc963a62d 100644 --- a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Info.plist +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Info.plist @@ -32,8 +32,23 @@ Yo Yo UILaunchStoryboardName LaunchScreen - UIMainStoryboardFile - Main + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneConfigurationName + Default Configuration + UISceneStoryboardFile + Main + + + + UIRequiredDeviceCapabilities armv7 diff --git a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Resources/Base.lproj/Main.storyboard b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Resources/Base.lproj/Main.storyboard index db52210458..5fb805f28f 100644 --- a/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Resources/Base.lproj/Main.storyboard +++ b/WebDriverAgent/WebDriverAgentTests/IntegrationApp/Resources/Base.lproj/Main.storyboard @@ -1,9 +1,10 @@ - + - + + @@ -19,7 +20,7 @@ - - - - - - - - - -