├── .gitignore ├── .whitesource ├── LICENSE.txt ├── README.md ├── assembly.xml ├── build.sh ├── demo ├── 1.png ├── click_in │ ├── html │ │ └── click_in_demo.html │ ├── img │ │ ├── left_area.png │ │ ├── right_area.png │ │ └── target.png │ └── testsuite_clickin.txt ├── drag_and_drop │ ├── FILE1 │ ├── FILE2 │ ├── img │ │ ├── src1.png │ │ ├── src2.png │ │ └── target.png │ └── testsuite_dragdrop.txt ├── hello_world │ ├── img │ │ ├── close.png │ │ ├── dont_save.png │ │ ├── notepad.png │ │ ├── notepad_title.png │ │ ├── notepad_workspace.png │ │ ├── search_input.png │ │ └── windows_start_menu.png │ ├── ruby_demo.rb │ └── testsuite_sikuli_demo.txt └── test.robot ├── docs ├── SikuliLibrary.html ├── SikuliLibrary_2.0.3.html ├── SikuliLibrary_dark.html └── img │ ├── architecture.png │ └── log.png ├── pom.xml ├── pyproject.toml ├── setup.cfg ├── setup.py └── src ├── java ├── META-INF │ └── MANIFEST.MF └── com │ └── github │ └── rainmanwy │ └── robotframework │ └── sikulilib │ ├── SikuliLibrary.java │ ├── exceptions │ ├── ScreenOperationException.java │ └── TimeoutException.java │ ├── keywords │ ├── ApplicationKeywords.java │ ├── ScreenKeywords.java │ └── SettingsKeywords.java │ └── utils │ └── CaptureFolder.java └── python ├── __init__.py ├── sikuli.py └── version.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.idea 2 | class 3 | dist 4 | target 5 | *.iml 6 | teste 7 | .vscode 8 | .classpath 9 | .project 10 | .settings/ 11 | pom.xml 12 | build/ 13 | -------------------------------------------------------------------------------- /.whitesource: -------------------------------------------------------------------------------- 1 | ########################################################## 2 | #### WhiteSource Integration configuration file #### 3 | ########################################################## 4 | 5 | # Configuration # 6 | #---------------# 7 | ws.repo.scan=true 8 | vulnerable.check.run.conclusion.level=failure 9 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Sikuli Robot Framework Library 2 | ============================== 3 | 4 | ## Introduction 5 | Sikuli Robot Framework Library provides keywords to be used within [Robot Framework's](https://robotframework.org/) environment to test UI through [Sikulix](http://sikulix.com/), a automation tool that uses image recognition to identify and interact with UI components. 6 | 7 | This library supports python 2.x, and python 3.x 8 | 9 | ## Mapping With Sikulix API Version 10 | As this library is depended with sikulixapi, below table describe the mapping between SikuliLibrary version and sikulixapi version. 11 | Before using this library, please check [doc of sikulix](https://sikulix-2014.readthedocs.io/en/latest/index.html), and make sure the environment satisfy the requirement of sikulix. 12 | 13 | | SikuliLibrary | sikulixapi | 14 | | --- | --- | 15 | | master | 2.0.5 | 16 | | 2.0.5 | 2.0.5 | 17 | | 2.0.3 | 2.0.4 | 18 | | 2.0.0 | 2.0.4 | 19 | | 1.0.8 | 2.0.1 | 20 | 21 | 22 | 23 | ## Overview 24 | ![](https://github.com/MarketSquare/robotframework-SikuliLibrary/blob/master/docs/img/architecture.png "architecture") 25 | * This library is implemented with [Robot Framework Remote Interface](https://github.com/robotframework/RemoteInterface) 26 | * Sikuli api is encapsulated as Robot keywords, and explored to clients with [jrobotremoteserver](https://github.com/robotframework/jrobotremoteserver) 27 | * Client is implemented with python and use [Robot Framework Remote Library](https://github.com/robotframework/PythonRemoteServer) to communicate with server side 28 | * Users could implement their own clients with different languages which support XML RPC 29 | 30 | 31 | ## Keyword Documentation 32 | 33 | Here is a list of the available [Keywords :full_moon_with_face:](http://marketSquare.github.io/robotframework-SikuliLibrary/docs/SikuliLibrary.html) | [Keywords :new_moon_with_face:](http://marketSquare.github.io/robotframework-SikuliLibrary/docs/SikuliLibrary_dark.html). 34 | 35 | Previous version, [2.0.3 :full_moon_with_face:](http://marketSquare.github.io/robotframework-SikuliLibrary/docs/SikuliLibrary_2.0.3.html). 36 | 37 | # Getting Started 38 | 39 | This guide will take you through setting up Robot Framework with Sikuli Library, on a Windows machine. 40 | 41 | 42 | ## Step 1: Install the basic components 43 | 44 | Make sure you have at least Java 11 installed, and Python 3.8 to 3.13, and [pip](https://pypi.org/project/pip/) 45 | 46 | Run the command line below to check the currently version that you have installed: 47 | 48 | To check java version: ``` java -version ``` 49 | 50 | To check python version: ``` python --version ``` 51 | 52 | To check pip version: ``` pip --version ``` 53 | 54 | ## Step 2: Install Robot Framework and Sikuli Library 55 | 56 | Using pip, you can install Robot Framework 57 | 58 | ``` 59 | pip install robotframework 60 | ``` 61 | And then install the library 62 | ``` 63 | pip install robotframework-SikuliLibrary 64 | ``` 65 | 66 | * You can see SikuliLibrary project at [PyPi page](https://pypi.python.org/pypi/robotframework-SikuliLibrary) 67 | 68 | ## Building SikuliLibrary 69 | 70 | ### Build With Maven 71 | * Make sure you have Java configured (for example): 72 | ``` 73 | export JAVA_HOME=/usr/lib/jvm/java 74 | ``` 75 | * Clone this project, and execute the commands: 76 | ``` 77 | mvn package 78 | ``` 79 | * One zip archive will be created in "target" folder, you can unzip this file and add to PYTHONPATH 80 | * To install with Python, you create a wheel package and then install: 81 | ``` 82 | pip wheel . 83 | pip install ./robotframework_sikulilibrary-2.0.5-py3-none-any.whl 84 | ``` 85 | 86 | ### Note 87 | * For Linux, there are some dependencies that needs to be installed, please check [sikuli quick start](http://www.sikulix.com/specials/files/linux-setup-prerequisites.html) to get more details. 88 | * Python should be installed as maven will execute python command 89 | * OS should allow Java process access Internet 90 | 91 | # Writing your first test 92 | 93 | ### Hello World Example 94 | ``` 95 | *** Settings *** 96 | Documentation Sikuli Library Demo 97 | Test Setup Add Needed Image Path 98 | Test Teardown Stop Remote Server 99 | Library SikuliLibrary 100 | 101 | *** Variables *** 102 | ${IMAGE_DIR} ${CURDIR}\\img 103 | 104 | *** Test Cases *** 105 | Windows Notepad Hello World 106 | Open Windows Start Menu 107 | Open Notepad 108 | Input In Notepad 109 | Quit Without Save 110 | 111 | *** Keywords *** 112 | Add Needed Image Path 113 | Add Image Path ${IMAGE_DIR} 114 | 115 | Open Windows Start Menu 116 | Click windows_start_menu.png 117 | 118 | Open Notepad 119 | Input Text search_input.png notepad 120 | Click notepad.png 121 | Double Click notepad_title.png 122 | 123 | Input In Notepad 124 | Input Text notepad_workspace.png Hello World 125 | Text Should Exist Hello World 126 | 127 | Quit Without Save 128 | Click close.png 129 | Click dont_save.png 130 | ``` 131 | ### Click In Example 132 | ``` 133 | *** Settings *** 134 | Documentation Sikuli Library Click In Example 135 | Test Setup Add Needed Image Path 136 | Test Teardown Stop Remote Server 137 | Library SikuliLibrary 138 | Library OperatingSystem 139 | 140 | *** Variables *** 141 | ${IMAGE_DIR} ${CURDIR}\\img 142 | 143 | *** Test Cases *** 144 | Click In Example 145 | Open Example UI 146 | Click Right OK Button 147 | Click Left OK Button 148 | 149 | *** Keywords *** 150 | Add Needed Image Path 151 | Add Image Path ${IMAGE_DIR} 152 | 153 | Open Example UI 154 | Run chrome ${CURDIR}\\html\\click_in_demo.html 155 | 156 | Click Right OK Button 157 | Click In right_area.png target.png 158 | 159 | Click Left OK Button 160 | Click In left_area.png target.png 161 | 162 | ``` 163 | ### Ruby Client Example 164 | ```ruby 165 | require "xmlrpc/client" 166 | require "pathname" 167 | 168 | client = XMLRPC::Client.new("127.0.0.1", "/", 10000) 169 | client.call("get_keyword_names") 170 | client.call("run_keyword", "addImagePath", [Pathname.new(File.dirname(__FILE__)).realpath.to_s+"/img"]) 171 | client.call("run_keyword", "click", ["windows_start_menu.png"]) 172 | client.call("run_keyword", "waitUntilScreenContain", ["search_input.png", "5"]) 173 | client.call("run_keyword", "input_text", ["search_input.png", "notepad"]) 174 | client.call("run_keyword", "click", ["notepad.png"]) 175 | client.call("run_keyword", "doubleClick", ["notepad_title.png"]) 176 | client.call("run_keyword", "click", ["close.png"]) 177 | ``` 178 | 179 | 180 | 181 | # Advanced Options 182 | 183 | ## Start Server Manually 184 | SikuliLibrary contains a standalone jar file which could be started in command line. Sometimes user want to do test on different OS. The steps are: 185 | * Find SikuliLibrary.jar in "SikuliLibrary/lib" folder and upload to target OS. 186 | * Start jar with command 187 | ``` 188 | java -jar SikuliLibrary.jar 189 | ``` 190 | * User could use different clients to connect to server and call keywords. For example [Remote Library](https://github.com/robotframework/RemoteInterface) in robot framework. 191 | ``` 192 | Library Remote http://:/ 193 | ``` 194 | 195 | ## "NEW" mode 196 | * By default, SikuliLibrary will start Sikuli Java process implicitly when library is initializing by Robot Framework. This behavior brings some problems. 197 | * Now with **"NEW"** mode, user could use keyword [Start Sikuli Process](http://marketSquare.github.io/robotframework-SikuliLibrary/docs/SikuliLibrary.html#Start%20Sikuli%20Process) to start the process explicitly. 198 | You may check the detail in [issue 16](https://github.com/MarketSquare/robotframework-SikuliLibrary/issues/16) 199 | * Example: 200 | ``` 201 | *** Settings *** 202 | Library SikuliLibrary mode=NEW 203 | Suite Setup Start Sikuli Process 204 | Suite Teardown Stop Remote Server 205 | 206 | *** Test Cases *** 207 | New Mode 208 | Add Image Path E:/config 209 | Click click.png 210 | ``` 211 | 212 | 213 | ### Start Server 214 | ``` 215 | java -jar SikuliLibrary.jar 10000 . 216 | 217 | 0 [main] INFO org.robotframework.remoteserver.RemoteServer - Mapped path / to library com.github.rainmanwy.robotframework.sikulilib.SikuliLibrary. 218 | 1 [main] INFO org.robotframework.remoteserver.RemoteServer - Robot Framework remote server starting 219 | 1 [main] INFO org.eclipse.jetty.server.Server - jetty-7.x.y-SNAPSHOT 220 | 28 [main] INFO org.eclipse.jetty.server.handler.ContextHandler - started o.e.j.s.ServletContextHandler{/,null} 221 | 129 [main] INFO org.eclipse.jetty.server.AbstractConnector - Started SelectChannelConnector@0.0.0.0:10000 222 | 129 [main] INFO org.robotframework.remoteserver.RemoteServer - Robot Framework remote server started on port 10000. 223 | ``` 224 | 225 | ## Disable Java Process Log File 226 | You can configure environment variable *DISABLE_SIKULI_LOG* to disable create log files 227 | ``` 228 | Linux: export DISABLE_SIKULI_LOG=yes 229 | ``` 230 | 231 | ## Microsoft Management Console (MMC) 232 | In Windows environment, some applications are created using MMC. SikuliX is only able to interact with MMC if you launch as Administrator the Sikuli IDE or the test script using SikuliX library. 233 | 234 | If you start seeing errors like the below, you are running your tests against an MMC application as a non-admin: 235 | ``` 236 | [log] CLICK on L(1061,118)@S(0)[0,0 1920x1080] 237 | [error] RobotDesktop: checkMousePosition: should be L(1061,118)@S(0)[0,0 1920x1080] 238 | but after move is L(137,215)@S(0)[0,0 1920x1080] 239 | Possible cause in case you did not touch the mouse while script was running: 240 | Mouse actions are blocked generally or by the frontmost application. 241 | You might try to run the SikuliX stuff as admin. 242 | ``` 243 | Another symptom is that your mouse will not move, and if it moves (there are random instances when the mouse moves), it will not click, so your test will fail. 244 | 245 | Setting UAC to the lowest level (not to notify the user) will reduce the instances of MMC dialogs. This does not mean that UAC is turned off, just that it does not have any unnecessary popup when your tests are being run (or you will have to take care of them in your test scripts). 246 | 247 | 248 | ## Differences With Other Similiar Sikuli Libraries 249 | * Robot Remote Library technology is used, different client part program languages are supported 250 | * Do not plan to expose sikuli api to Robot Framework directly. All sikuli api are encapsulated as Keywords. 251 | * Wait functionality is added for each operations 252 | ```java 253 | public void click(String image) throws Exception{ 254 | wait(image, Double.toString(this.timeout)); 255 | try { 256 | screen.click(image); 257 | } 258 | catch (FindFailed e) { 259 | capture(); 260 | throw new ScreenOperationException("Click "+image+" failed"+e.getMessage(), e); 261 | } 262 | } 263 | ``` 264 | * Keyword to handle similiar images issue, could check "click_in" test suite in demo folder to get details 265 | ```java 266 | public void clickIn(String areaImage, String targetImage) throws Exception { 267 | wait(areaImage, Double.toString(this.timeout)); 268 | Match match = screen.find(areaImage); 269 | System.out.println(areaImage + " is found!"); 270 | match.click(targetImage); 271 | capture(match.find(targetImage)); 272 | } 273 | ``` 274 | * Operating images could be shown in robot logs, easy to troubleshooting 275 | ![](https://github.com/MarketSquare/robotframework-SikuliLibrary/blob/master/docs/img/log.png "log") 276 | 277 | 278 | ## Robot Framework Community - MarketSquare 279 | 280 | This project was created by [rainmanwy](https://github.com/rainmanwy) and is maintained by the Robot Framework Community at [MarketSquare](https://marketsquare.github.io/index.html) since May, 2025. 281 | -------------------------------------------------------------------------------- /assembly.xml: -------------------------------------------------------------------------------- 1 | 3 | ${version} 4 | 5 | zip 6 | 7 | true 8 | 9 | 10 | 11 | src/python 12 | 13 | **/* 14 | 15 | 16 | 17 | lib 18 | ${project.build.directory} 19 | 20 | SikuliLibrary.jar 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #! /usr/bin/bash 2 | 3 | # Tested on Fedora 42, Java 21, Python 13 4 | export JAVA_HOME=/usr/lib/jvm/java 5 | export DISABLE_SIKULI_LOG=1 6 | 7 | mvn package 8 | 9 | if [[ $? -eq 0 ]]; 10 | then 11 | pip wheel . 12 | libdoc --theme DARK build/lib/SikuliLibrary docs/SikuliLibrary_2.0.5_dark.html 13 | fi 14 | -------------------------------------------------------------------------------- /demo/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarketSquare/robotframework-SikuliLibrary/8d6411023d6138fdaf7f906d335d949ed8495bc5/demo/1.png -------------------------------------------------------------------------------- /demo/click_in/html/click_in_demo.html: -------------------------------------------------------------------------------- 1 | 2 | Click In Example 3 | 4 | 5 | 6 | 7 |
8 |
9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /demo/click_in/img/left_area.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarketSquare/robotframework-SikuliLibrary/8d6411023d6138fdaf7f906d335d949ed8495bc5/demo/click_in/img/left_area.png -------------------------------------------------------------------------------- /demo/click_in/img/right_area.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarketSquare/robotframework-SikuliLibrary/8d6411023d6138fdaf7f906d335d949ed8495bc5/demo/click_in/img/right_area.png -------------------------------------------------------------------------------- /demo/click_in/img/target.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarketSquare/robotframework-SikuliLibrary/8d6411023d6138fdaf7f906d335d949ed8495bc5/demo/click_in/img/target.png -------------------------------------------------------------------------------- /demo/click_in/testsuite_clickin.txt: -------------------------------------------------------------------------------- 1 | *** Settings *** 2 | Documentation Sikuli Library Click In Example 3 | Test Setup Add Needed Image Path 4 | Test Teardown Run Keywords Terminate All Processes Stop Remote Server 5 | Library SikuliLibrary 6 | Library Process 7 | 8 | *** Variables *** 9 | ${IMAGE_DIR} ${CURDIR}/img 10 | 11 | *** Test Cases *** 12 | Click In Example 13 | Open Example UI 14 | Click Right OK Button 15 | Click Left OK Button 16 | 17 | *** Keywords *** 18 | Add Needed Image Path 19 | Add Image Path ${IMAGE_DIR} 20 | 21 | Open Example UI 22 | Start Process firefox ${CURDIR}/html/click_in_demo.html 23 | Wait Until Screen Contain right_area.png 10 24 | 25 | Click Right OK Button 26 | Click In right_area.png target.png 27 | 28 | Click Left OK Button 29 | Click In left_area.png target.png 30 | -------------------------------------------------------------------------------- /demo/drag_and_drop/FILE1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarketSquare/robotframework-SikuliLibrary/8d6411023d6138fdaf7f906d335d949ed8495bc5/demo/drag_and_drop/FILE1 -------------------------------------------------------------------------------- /demo/drag_and_drop/FILE2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarketSquare/robotframework-SikuliLibrary/8d6411023d6138fdaf7f906d335d949ed8495bc5/demo/drag_and_drop/FILE2 -------------------------------------------------------------------------------- /demo/drag_and_drop/img/src1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarketSquare/robotframework-SikuliLibrary/8d6411023d6138fdaf7f906d335d949ed8495bc5/demo/drag_and_drop/img/src1.png -------------------------------------------------------------------------------- /demo/drag_and_drop/img/src2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarketSquare/robotframework-SikuliLibrary/8d6411023d6138fdaf7f906d335d949ed8495bc5/demo/drag_and_drop/img/src2.png -------------------------------------------------------------------------------- /demo/drag_and_drop/img/target.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarketSquare/robotframework-SikuliLibrary/8d6411023d6138fdaf7f906d335d949ed8495bc5/demo/drag_and_drop/img/target.png -------------------------------------------------------------------------------- /demo/drag_and_drop/testsuite_dragdrop.txt: -------------------------------------------------------------------------------- 1 | *** Settings *** 2 | Documentation Sikuli Library Demo 3 | Suite Setup Add Needed Image Path 4 | Suite Teardown Stop Remote Server 5 | Library SikuliLibrary 6 | 7 | *** Variables *** 8 | ${IMAGE_DIR} ${CURDIR}/img 9 | 10 | *** Test Cases *** 11 | Demo1 12 | Drag File To Folder 13 | 14 | Demo2 15 | Drag File To Folder With Empty Source 16 | 17 | *** Keywords *** 18 | Add Needed Image Path 19 | Add Image Path ${IMAGE_DIR} 20 | 21 | Drag File To Folder 22 | Drag And Drop src1.png target.png 23 | Wait Until Screen Not Contain src1.png 10 24 | 25 | Drag File To Folder With Empty Source 26 | Screen Should Contain src2.png 27 | Drag And Drop ${EMPTY} target.png 28 | Wait Until Screen Not Contain src2.png 10 29 | -------------------------------------------------------------------------------- /demo/hello_world/img/close.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarketSquare/robotframework-SikuliLibrary/8d6411023d6138fdaf7f906d335d949ed8495bc5/demo/hello_world/img/close.png -------------------------------------------------------------------------------- /demo/hello_world/img/dont_save.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarketSquare/robotframework-SikuliLibrary/8d6411023d6138fdaf7f906d335d949ed8495bc5/demo/hello_world/img/dont_save.png -------------------------------------------------------------------------------- /demo/hello_world/img/notepad.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarketSquare/robotframework-SikuliLibrary/8d6411023d6138fdaf7f906d335d949ed8495bc5/demo/hello_world/img/notepad.png -------------------------------------------------------------------------------- /demo/hello_world/img/notepad_title.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarketSquare/robotframework-SikuliLibrary/8d6411023d6138fdaf7f906d335d949ed8495bc5/demo/hello_world/img/notepad_title.png -------------------------------------------------------------------------------- /demo/hello_world/img/notepad_workspace.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarketSquare/robotframework-SikuliLibrary/8d6411023d6138fdaf7f906d335d949ed8495bc5/demo/hello_world/img/notepad_workspace.png -------------------------------------------------------------------------------- /demo/hello_world/img/search_input.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarketSquare/robotframework-SikuliLibrary/8d6411023d6138fdaf7f906d335d949ed8495bc5/demo/hello_world/img/search_input.png -------------------------------------------------------------------------------- /demo/hello_world/img/windows_start_menu.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarketSquare/robotframework-SikuliLibrary/8d6411023d6138fdaf7f906d335d949ed8495bc5/demo/hello_world/img/windows_start_menu.png -------------------------------------------------------------------------------- /demo/hello_world/ruby_demo.rb: -------------------------------------------------------------------------------- 1 | require "xmlrpc/client" 2 | require "pathname" 3 | 4 | client = XMLRPC::Client.new("127.0.0.1", "/", 10000) 5 | ret = client.call("get_keyword_names") 6 | client.call("run_keyword", "addImagePath", [Pathname.new(File.dirname(__FILE__)).realpath.to_s+"/img"]) 7 | client.call("run_keyword", "click", ["windows_start_menu.png"]) 8 | client.call("run_keyword", "waitUntilScreenContain", ["search_input.png", "5"]) 9 | client.call("run_keyword", "input_text", ["search_input.png", "notepad"]) 10 | client.call("run_keyword", "click", ["notepad.png"]) 11 | client.call("run_keyword", "doubleClick", ["notepad_title.png"]) 12 | client.call("run_keyword", "click", ["close.png"]) -------------------------------------------------------------------------------- /demo/hello_world/testsuite_sikuli_demo.txt: -------------------------------------------------------------------------------- 1 | *** Settings *** 2 | Documentation Sikuli Library Demo 3 | Test Setup Add Needed Image Path 4 | Test Teardown Stop Remote Server 5 | Library SikuliLibrary 6 | 7 | *** Variables *** 8 | ${IMAGE_DIR} ${CURDIR}/img 9 | 10 | *** Test Cases *** 11 | Windows Notepad Hello World 12 | Open Windows Start Menu 13 | Open Notepad 14 | Input In Notepad 15 | Quit Without Save 16 | 17 | *** Keywords *** 18 | Add Needed Image Path 19 | Add Image Path ${IMAGE_DIR} 20 | 21 | Open Windows Start Menu 22 | Click windows_start_menu.png 23 | 24 | Open Notepad 25 | Input Text search_input.png notepad 26 | Sleep 1s 27 | Click notepad.png 28 | Double Click notepad_title.png 29 | 30 | Input In Notepad 31 | Click notepad_workspace.png 32 | Input Text ${EMPTY} Hello World 33 | 34 | Quit Without Save 35 | Click close.png 36 | Click dont_save.png 37 | -------------------------------------------------------------------------------- /demo/test.robot: -------------------------------------------------------------------------------- 1 | *** Keywords *** 2 | Open Image 3 | [Arguments] ${image} 4 | ${sys}= Evaluate os.path.sep == '/' 5 | IF ${sys} 6 | Start Process gwenview ${image} 7 | SikuliLibrary.Wait Until Screen Contain ${image} 30 8 | END 9 | 10 | *** Settings *** 11 | Suite Teardown Stop Remote Server 12 | Library SikuliLibrary 13 | Library Process 14 | 15 | *** Test Cases *** 16 | My Test 17 | Add Image Path . 18 | Set Always Resize 0 19 | #Double Click 1.png xOffset=0 yOffset=-100 20 | #Right Click 1.png 21 | Open Image 1.png 22 | Click 1.png 23 | #${coor} \ \ Create List \ 0 \ 0 \ 300 \ 300 24 | #Click Region ${coor} 25 | #${text} \ \ Get Text 26 | #Log \ \ ${text} 27 | -------------------------------------------------------------------------------- /docs/img/architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarketSquare/robotframework-SikuliLibrary/8d6411023d6138fdaf7f906d335d949ed8495bc5/docs/img/architecture.png -------------------------------------------------------------------------------- /docs/img/log.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarketSquare/robotframework-SikuliLibrary/8d6411023d6138fdaf7f906d335d949ed8495bc5/docs/img/log.png -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.github.rainmanwy.robotframework 5 | robotframework-SikuliLibrary 6 | 2.0.5 7 | jar 8 | robotframework-SikuliLibrary 9 | 10 | 11 | UTF-8 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | junit 21 | junit 22 | 4.13.1 23 | test 24 | 25 | 26 | com.sikulix 27 | sikulixapi 28 | 2.0.5 29 | 30 | 31 | org.robotframework 32 | javalib-core 33 | 2.0.3 34 | 35 | 36 | org.eclipse.jetty 37 | jetty-servlet 38 | 9.4.45.v20220203 39 | 40 | 41 | org.apache.logging.log4j 42 | log4j-core 43 | 2.17.2 44 | 45 | 46 | org.apache.logging.log4j 47 | log4j-jcl 48 | 2.17.2 49 | 50 | 51 | org.apache.xmlrpc 52 | xmlrpc-server 53 | 3.1.3 54 | 55 | 56 | org.apache.commons 57 | commons-lang3 58 | 3.12.0 59 | 60 | 61 | org.apache.commons 62 | commons-text 63 | 1.10.0 64 | 65 | 66 | 67 | org.robotframework 68 | jrobotremoteserver 69 | 4.1.0 70 | 71 | 72 | 73 | 74 | 75 | 76 | src/java 77 | 78 | 79 | 80 | org.apache.maven.plugins 81 | maven-compiler-plugin 82 | 3.8.1 83 | 84 | 1.8 85 | 1.8 86 | 87 | 88 | 89 | 90 | org.apache.maven.plugins 91 | maven-assembly-plugin 92 | 3.7.1 93 | 94 | 95 | SikuliLibrary 96 | false 97 | 98 | jar-with-dependencies 99 | 100 | 101 | 102 | com.github.rainmanwy.robotframework.sikulilib.SikuliLibrary 103 | true 104 | 105 | 106 | 107 | 108 | 109 | make-assembly 110 | package 111 | 112 | single 113 | 114 | 115 | 116 | dist 117 | package 118 | 119 | single 120 | 121 | 122 | 123 | assembly.xml 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | org.apache.maven.plugins 132 | maven-antrun-plugin 133 | 1.6 134 | 135 | 136 | dist 137 | package 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | run 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description_file = README.md 3 | name = robotframework-SikuliLibrary 4 | version = 2.0.5 5 | 6 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | ''' 3 | Created on 2015/12/10 4 | 5 | Author: by wang_yang1980@hotmail.com 6 | ''' 7 | from setuptools import setup 8 | 9 | from os.path import abspath, dirname, join 10 | with open(join(dirname(abspath(__file__)), 'target', 'src', 'SikuliLibrary', 'version.py')) as f: 11 | exec(f.read()) 12 | 13 | with open("README.md", encoding="utf-8") as f: 14 | long_description = f.read() 15 | 16 | DESCRIPTION = "Sikuli Robot Framework Library provide keywords for Robot Framework to test UI through Sikuli." 17 | 18 | setup_kwargs = { 19 | "name": "robotframework-SikuliLibrary", 20 | "version": VERSION, 21 | "description": DESCRIPTION, 22 | "long_description": long_description, 23 | "long_description_content_type": "text/markdown", 24 | "author": "Wang Yang", 25 | "author_email": "wang_yang1980@hotmail.com", 26 | "maintainer": "Hélio Guilherme", 27 | "maintainer_email": "helioxentric@gmail.com", 28 | "url": "https://github.com/MarketSquare/robotframework-SikuliLibrary", 29 | "license": "Apache-2.0", 30 | "keywords": "robotframework testing testautomation sikuli UI", 31 | "platforms": "any", 32 | "package_dir": {"" : "target/src"}, 33 | "packages": ["SikuliLibrary"], 34 | "package_data": {"SikuliLibrary": ["lib/*.jar",]}, 35 | "python_requires": ">=3.8,<4.0", 36 | "classifiers": [ 37 | "Development Status :: 5 - Production/Stable", 38 | "Operating System :: OS Independent", 39 | "Programming Language :: Java", 40 | "Programming Language :: Python :: 3", 41 | "Topic :: Software Development :: Testing", 42 | "Framework :: Robot Framework", 43 | "Framework :: Robot Framework :: Library", 44 | ], 45 | "include_package_data": True 46 | } 47 | 48 | 49 | setup(**setup_kwargs) 50 | 51 | -------------------------------------------------------------------------------- /src/java/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Main-Class: com.github.rainmanwy.robotframework.sikulilib.SikuliLibrary 3 | -------------------------------------------------------------------------------- /src/java/com/github/rainmanwy/robotframework/sikulilib/SikuliLibrary.java: -------------------------------------------------------------------------------- 1 | package com.github.rainmanwy.robotframework.sikulilib; 2 | 3 | import org.robotframework.javalib.library.RobotFrameworkDynamicAPI; 4 | import org.robotframework.javalib.library.KeywordDocumentationRepository; 5 | import org.robotframework.javalib.library.AnnotationLibrary; 6 | import org.robotframework.remoteserver.RemoteServer; 7 | 8 | import com.github.rainmanwy.robotframework.sikulilib.utils.CaptureFolder; 9 | 10 | import java.util.List; 11 | import java.util.Map; 12 | 13 | /** 14 | * Created by Wang Yang on 2015/8/19. 15 | */ 16 | public class SikuliLibrary implements KeywordDocumentationRepository, RobotFrameworkDynamicAPI { 17 | 18 | private final AnnotationLibrary annotationLibrary = new AnnotationLibrary("com/github/rainmanwy/robotframework/sikulilib/keywords/**/*.class"); 19 | 20 | public static void main(String[] args) throws Exception { 21 | if (args.length == 0) { 22 | throw new RuntimeException("Port number should be provided"); 23 | } 24 | if (args.length >= 2) { 25 | CaptureFolder.getInstance().setCaptureFolder(args[1]); 26 | } 27 | RemoteServer.configureLogging(); 28 | RemoteServer server = new RemoteServer(Integer.parseInt(args[0])); 29 | server.putLibrary("/", new SikuliLibrary()); 30 | server.start(); 31 | } 32 | 33 | @Override 34 | public Object runKeyword(String keywordName, List args) 35 | { 36 | return this.annotationLibrary.runKeyword(keywordName, args); 37 | } 38 | 39 | @Override 40 | public Object runKeyword(String keywordName, List args, Map kwargs) 41 | { 42 | return this.annotationLibrary.runKeyword(keywordName, args, kwargs); 43 | } 44 | 45 | @Override 46 | public List getKeywordNames() 47 | { 48 | return this.annotationLibrary.getKeywordNames(); 49 | } 50 | 51 | @Override 52 | public String getKeywordDocumentation(String name) { 53 | return this.annotationLibrary.getKeywordDocumentation(name); 54 | } 55 | 56 | @Override 57 | public List getKeywordArguments(String name) { 58 | return this.annotationLibrary.getKeywordArguments(name); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/java/com/github/rainmanwy/robotframework/sikulilib/exceptions/ScreenOperationException.java: -------------------------------------------------------------------------------- 1 | package com.github.rainmanwy.robotframework.sikulilib.exceptions; 2 | 3 | /** 4 | * Created by Wang Yang on 2015/8/19. 5 | */ 6 | public class ScreenOperationException extends Exception { 7 | 8 | public ScreenOperationException(String message) { 9 | super(message); 10 | } 11 | 12 | public ScreenOperationException(String message, Throwable cause) { 13 | super(message, cause); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/java/com/github/rainmanwy/robotframework/sikulilib/exceptions/TimeoutException.java: -------------------------------------------------------------------------------- 1 | package com.github.rainmanwy.robotframework.sikulilib.exceptions; 2 | 3 | /** 4 | * Created by Wang Yang on 2015/8/19. 5 | */ 6 | public class TimeoutException extends Exception { 7 | 8 | public TimeoutException(String message) { 9 | super(message); 10 | } 11 | 12 | public TimeoutException(String message, Throwable cause) { 13 | super(message, cause); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/java/com/github/rainmanwy/robotframework/sikulilib/keywords/ApplicationKeywords.java: -------------------------------------------------------------------------------- 1 | package com.github.rainmanwy.robotframework.sikulilib.keywords; 2 | 3 | import org.robotframework.javalib.annotation.ArgumentNames; 4 | import org.robotframework.javalib.annotation.RobotKeyword; 5 | import org.robotframework.javalib.annotation.RobotKeywords; 6 | 7 | import org.sikuli.script.App; 8 | 9 | /** 10 | * Created by Rajesh Taneja on 2018/10/23. 11 | */ 12 | 13 | @RobotKeywords 14 | public class ApplicationKeywords { 15 | 16 | @RobotKeyword("Open application" 17 | + "\n To open app with parameters, refer:" 18 | + "\n https://sikulix-2014.readthedocs.io/en/latest/appclass.html#App.App") 19 | @ArgumentNames({"path"}) 20 | public App openApplication(String path) { 21 | return App.open(path); 22 | } 23 | 24 | @RobotKeyword("Close application") 25 | @ArgumentNames({"name"}) 26 | public Boolean closeApplication(String name) { 27 | return App.close(name); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/java/com/github/rainmanwy/robotframework/sikulilib/keywords/ScreenKeywords.java: -------------------------------------------------------------------------------- 1 | package com.github.rainmanwy.robotframework.sikulilib.keywords; 2 | 3 | import java.io.File; 4 | import java.util.*; 5 | 6 | 7 | 8 | import org.robotframework.javalib.annotation.ArgumentNames; 9 | import org.robotframework.javalib.annotation.RobotKeyword; 10 | import org.robotframework.javalib.annotation.RobotKeywords; 11 | import org.robotframework.javalib.annotation.RobotKeywordOverload; 12 | 13 | import com.github.rainmanwy.robotframework.sikulilib.exceptions.TimeoutException; 14 | import com.github.rainmanwy.robotframework.sikulilib.exceptions.ScreenOperationException; 15 | import com.github.rainmanwy.robotframework.sikulilib.utils.CaptureFolder; 16 | 17 | import org.sikuli.basics.Settings; 18 | import org.sikuli.script.*; 19 | 20 | 21 | 22 | /** 23 | * Created by Wang Yang on 2015/8/19. 24 | */ 25 | 26 | @RobotKeywords 27 | public class ScreenKeywords { 28 | 29 | private static double DEFAULT_TIMEOUT = 3.0; 30 | private static Screen screen = new Screen(); 31 | private static Region region = new Region(screen); 32 | private double timeout; 33 | private Boolean isCaptureMatchedImage = true; 34 | private Map highlightMap = new HashMap(); 35 | 36 | public ScreenKeywords() { 37 | timeout = DEFAULT_TIMEOUT; 38 | } 39 | 40 | public static Screen getScreen() { 41 | return screen; 42 | } 43 | 44 | public static Region getRegion() { 45 | return region; 46 | } 47 | 48 | private Pattern getPattern(String locator) { 49 | /** 50 | * Parse locator string. It can be either of the following: 51 | * - Image.png 52 | * - Text 53 | * - Image.png = 0.9 54 | * This will return pattern and similarity by parsing above. 55 | */ 56 | Pattern pattern = null; 57 | if (locator.contains(".png")) { 58 | if (locator.contains("=")) { 59 | locator = locator.replace(" ", ""); 60 | pattern = new Pattern(locator.substring(0, locator.indexOf("="))).similar(Float.parseFloat(locator.substring(locator.indexOf("=") + 1))); 61 | } else { 62 | pattern = new Pattern(locator).similar((float)Settings.MinSimilarity); 63 | } 64 | } else { 65 | pattern = new Pattern(locator); 66 | } 67 | 68 | return pattern; 69 | } 70 | 71 | @RobotKeyword("Set timeout" 72 | + "\n\nSet Sikuli timeout(seconds)" 73 | + "\nExamples:" 74 | + "\n| Set timeout | 10 |") 75 | @ArgumentNames({"timeout"}) 76 | public String setTimeout(String timeout) { 77 | double oldTimeout = this.timeout; 78 | this.timeout = Double.parseDouble(timeout); 79 | return Double.toString(oldTimeout); 80 | } 81 | 82 | @RobotKeyword("Add image path") 83 | @ArgumentNames({"path"}) 84 | public boolean addImagePath(String path) { 85 | return ImagePath.add(path); 86 | } 87 | 88 | @RobotKeyword("Remove image path") 89 | @ArgumentNames({"path"}) 90 | public boolean removeImagePath(String path) { 91 | return ImagePath.remove(path); 92 | } 93 | 94 | @RobotKeyword("Set captured folder" 95 | + "\n\nSet folder for captured images" 96 | + "\nExamples:" 97 | + "\n| Set captured folder | PATH |") 98 | @ArgumentNames({"path"}) 99 | public void setCaptureFolder(String path) { 100 | CaptureFolder.getInstance().setCaptureFolder(path); 101 | } 102 | 103 | @RobotKeyword("Set capture matched image" 104 | + "\n\nSet capture matched images, the default value is true" 105 | + "\nExamples:" 106 | + "\n| Set Capture Matched Image | false |") 107 | @ArgumentNames({"value"}) 108 | public void setCaptureMatchedImage(boolean value) { 109 | isCaptureMatchedImage = value; 110 | } 111 | 112 | @RobotKeyword("Click" 113 | + "\n\nClick on an image with similarity and offset." 114 | + "\nExamples:" 115 | + "\n| Click | hello.png |") 116 | @ArgumentNames({"image", "xOffset=0", "yOffset=0"}) 117 | public int[] click(String image, int xOffset, int yOffset) throws Exception{ 118 | Match match = wait(image, Double.toString(this.timeout)); 119 | Location center = match.getCenter(); 120 | try { 121 | int newX = center.getX() + xOffset; 122 | int newY = center.getY() + yOffset; 123 | Location newLocation = new Location(newX, newY); 124 | region.click(newLocation); 125 | } 126 | catch (FindFailed e) { 127 | capture(); 128 | throw new ScreenOperationException("Click "+image+" failed"+e.getMessage(), e); 129 | } 130 | 131 | return regionFromMatch(match); 132 | } 133 | 134 | @RobotKeywordOverload 135 | public int[] click(String image) throws Exception{ 136 | wait(image, Double.toString(this.timeout)); 137 | try { 138 | region.click(getPattern(image)); 139 | Match match = region.getLastMatch(); 140 | return regionFromMatch(match); 141 | } 142 | catch (FindFailed e) { 143 | capture(); 144 | throw new ScreenOperationException("Click "+image+" failed"+e.getMessage(), e); 145 | } 146 | } 147 | 148 | private int[] regionFromMatch(Match match) { 149 | int[] reg = new int[4]; 150 | reg[0] = match.getX(); 151 | reg[1] = match.getY(); 152 | reg[2] = match.getW(); 153 | reg[3] = match.getH(); 154 | return reg; 155 | } 156 | 157 | @RobotKeyword("Click Text" 158 | + "\n\nClick on text." 159 | + "\nExamples:" 160 | + "\n| Click Text | Hello |") 161 | @ArgumentNames({"text"}) 162 | public int[] clickText(String text) throws Exception{ 163 | Match match = screen.findLine(text); 164 | if (match != null) { 165 | match.click(); 166 | return regionFromMatch(match); 167 | } else { 168 | capture(); 169 | throw new ScreenOperationException("Click text '"+ text+"' failed with findWord method"); 170 | } 171 | } 172 | 173 | @RobotKeyword("Region Click Text" 174 | + "\n\nClick on text in region." 175 | + "\nSet a region before." 176 | + "\nExamples:" 177 | + "\n| Region Click Text | Hello |") 178 | @ArgumentNames({"text"}) 179 | public int[] RegionClickText(String text) throws Exception{ 180 | Match match = region.findLine(text); 181 | if (match != null) { 182 | match.click(); 183 | return regionFromMatch(match); 184 | } else { 185 | capture(); 186 | throw new ScreenOperationException("Region Click Text '"+ text+"' failed with findWord method"); 187 | } 188 | } 189 | 190 | @RobotKeyword("Click region" 191 | + "\n\n Click on defined region cooridinates." 192 | + "\n Optionally Wait for specified time to ensure region has changed." 193 | + "\n Also, optionally set highlight" 194 | + "\n\n Examples:" 195 | + "\n | ${coor} | Create List | 0 | 0 | 100 | 100 |" 196 | + "\n | Click Region | ${coor} |" 197 | + "\n | Click Region | ${coor} | 0 |" 198 | + "\n | Click Region | ${coor} | 0 | 2 |") 199 | @ArgumentNames({"coordinates", "waitChange=0", "timeout=0"}) 200 | public void clickRegion(ArrayList coordinates, double waitChange, int highlight_timeout) { 201 | int x = Integer.parseInt(coordinates.get(0).toString()); 202 | int y = Integer.parseInt(coordinates.get(1).toString()); 203 | int w = Integer.parseInt(coordinates.get(2).toString()); 204 | int h = Integer.parseInt(coordinates.get(3).toString()); 205 | Region region = new Region(x, y, w, h); 206 | // After clicking on plugin, make sure it has changed, before returning from this step. 207 | String img = capture(region); 208 | region.click(); 209 | if (waitChange > 0) { 210 | region.waitVanish(img, waitChange); 211 | capture(region); 212 | } 213 | if (highlight_timeout > 0) { 214 | region.highlight(highlight_timeout); 215 | } 216 | } 217 | 218 | @RobotKeywordOverload 219 | public void clickRegion(ArrayList coordinates, double waitChange) { 220 | clickRegion(coordinates, waitChange, 0); 221 | } 222 | 223 | @RobotKeywordOverload 224 | public void clickRegion(ArrayList coordinates) { 225 | clickRegion(coordinates, this.timeout, 0); 226 | } 227 | 228 | @RobotKeyword("Click nth" 229 | + "\n\n Click on specific image." 230 | + "\n Optionally pass similarity and sort by column or row." 231 | + "\n\n Examples:" 232 | + "\n | Click on nth image in region | image.png | 1 |" 233 | + "\n | Click on nth image in region | image.png | 1 | ${FALSE} |") 234 | @ArgumentNames({"image", "index", "sortByColumn=true"}) 235 | public int[] clickNth(String image, int index, Boolean sortByColumn) throws Exception { 236 | List matches = null; 237 | if (sortByColumn) { 238 | matches = region.findAllByColumn(getPattern(image)); 239 | } else{ 240 | matches = region.findAllByRow(getPattern(image)); 241 | } 242 | Match match = matches.get(index); 243 | capture(match); 244 | matches.get(index).click(); 245 | return regionFromMatch(match); 246 | } 247 | 248 | @RobotKeywordOverload 249 | public int[] clickNth(String image, int index) throws Exception { 250 | return clickNth(image, index, true); 251 | } 252 | 253 | @RobotKeywordOverload 254 | public int[] doubleClick(String image) throws Exception{ 255 | wait(image, Double.toString(this.timeout)); 256 | try { 257 | region.doubleClick(getPattern(image)); 258 | } 259 | catch (FindFailed e) { 260 | throw new ScreenOperationException("Click "+image+" failed"+e.getMessage(), e); 261 | } 262 | Match match = region.getLastMatch(); 263 | return regionFromMatch(match); 264 | } 265 | 266 | //added by auyong 267 | @RobotKeyword("Double click") 268 | @ArgumentNames({"image", "xOffset=0", "yOffset=0"}) 269 | public int[] doubleClick(String image, int xOffset, int yOffset) throws Exception{ 270 | Match match = wait(image, Double.toString(this.timeout)); 271 | Location center = match.getCenter(); 272 | try { 273 | int newX = center.getX() + xOffset; 274 | int newY = center.getY() + yOffset; 275 | Location newLocation = new Location(newX, newY); 276 | region.doubleClick(newLocation); 277 | } 278 | catch (FindFailed e) { 279 | capture(); 280 | throw new ScreenOperationException("Double Click "+image+" failed"+e.getMessage(), e); 281 | } 282 | return regionFromMatch(match); 283 | } 284 | 285 | @RobotKeywordOverload 286 | public int[] rightClick(String image) throws Exception { 287 | wait(image, Double.toString(this.timeout)); 288 | try { 289 | region.rightClick(getPattern(image)); 290 | } catch (FindFailed e) { 291 | capture(); 292 | throw new ScreenOperationException("Click " + image + " failed" + e.getMessage(), e); 293 | } 294 | Match match = region.getLastMatch(); 295 | return regionFromMatch(match); 296 | } 297 | 298 | @RobotKeyword("Right click" 299 | + "\n\nClick on an image with similarity and offset." 300 | + "\nExamples:" 301 | + "\n| Click | hello.png |") 302 | @ArgumentNames({"image", "xOffset=0", "yOffset=0"}) 303 | public int[] rightClick(String image, int xOffset, int yOffset) throws Exception { 304 | Match match = wait(image, Double.toString(this.timeout)); 305 | Location center = match.getCenter(); 306 | try { 307 | int newX = center.getX() + xOffset; 308 | int newY = center.getY() + yOffset; 309 | Location newLocation = new Location(newX, newY); 310 | region.rightClick(newLocation); 311 | } catch (FindFailed e) { 312 | capture(); 313 | throw new ScreenOperationException("Click " + image + " failed" + e.getMessage(), e); 314 | } 315 | 316 | return regionFromMatch(match); 317 | } 318 | 319 | private Match wait(String image, String timeout) throws TimeoutException { 320 | try { 321 | Match match = region.wait(getPattern(image), Double.parseDouble(timeout)); 322 | capture(match); 323 | return match; 324 | } 325 | catch(FindFailed e) { 326 | capture(region); 327 | throw new TimeoutException("Timeout happened, could not find "+ getPattern(image).toString(), e); 328 | } 329 | } 330 | 331 | private Match find(String image) { 332 | try { 333 | Match match = region.find(getPattern(image)); 334 | capture(match); 335 | return match; 336 | } catch (FindFailed e) { 337 | System.out.println("Could not find " + getPattern(image).toString()); 338 | return null; 339 | } 340 | } 341 | 342 | @RobotKeyword("Wait until screen contain" 343 | + "\n Wait until image shown in screen") 344 | @ArgumentNames({"image", "timeout"}) 345 | public void waitUntilScreenContain(String image, String timeout) throws TimeoutException { 346 | wait(image, timeout); 347 | } 348 | 349 | @RobotKeyword("Wait until screen not contain" 350 | + "\n Wait until image not in screen") 351 | @ArgumentNames({"image", "timeout"}) 352 | public void waitUntilScreenNotContain(String image, String timeout) throws TimeoutException { 353 | boolean result = region.waitVanish(getPattern(image), Double.parseDouble(timeout)); 354 | capture(region); 355 | if (!result) { 356 | throw new TimeoutException(image+" is still in screen"); 357 | } 358 | } 359 | 360 | @RobotKeyword("Screen should contain") 361 | @ArgumentNames({"image"}) 362 | public void screenShouldContain(String image) throws ScreenOperationException { 363 | Match match = find(image); 364 | if (match == null) { 365 | capture(); 366 | throw new ScreenOperationException("Screen should contain "+image); 367 | } 368 | } 369 | 370 | @RobotKeyword("Screen should not contain" 371 | + "\n Screen should not contain image" 372 | + "\n\n Examples:" 373 | + "\n | Screen should not contain | image.png |") 374 | @ArgumentNames({"image"}) 375 | public void screenShouldNotContain(String image) throws ScreenOperationException { 376 | Match match = find(image); 377 | if (match != null) { 378 | capture(); 379 | throw new ScreenOperationException("Screen should not contain "+image); 380 | } 381 | } 382 | 383 | @RobotKeyword("Input text." 384 | + "\n Image could be empty" 385 | + "\n\n Examples:" 386 | + "\n | Input text | image.png | Sikuli |" 387 | + "\n | Input text | ${EMPTY} | Sikuli |") 388 | @ArgumentNames({"image", "text"}) 389 | public void inputText(String image, String text) throws Exception { 390 | System.out.println("Input Text:"); 391 | System.out.println(text); 392 | if ( !"".equals(image) ) { 393 | this.click(image); 394 | } 395 | int result = region.type(text); 396 | if (result == 0) { 397 | throw new ScreenOperationException("Input text failed"); 398 | } 399 | } 400 | 401 | @RobotKeyword("Type with modifiers" + 402 | "\n\n Examples:" + 403 | "\n |Type With Modifiers| A | CTRL |") 404 | @ArgumentNames({"text", "*modifiers"}) 405 | public void typeWithModifiers(String text, String[] modifiers) throws Exception { 406 | System.out.println("Input Text:"); 407 | String keys = ""; 408 | for (String modifier : modifiers) { 409 | keys += modifier + "+"; 410 | } 411 | keys = keys + text; 412 | System.out.println(keys); 413 | 414 | int sum = 0; 415 | for (String modifer : modifiers) { 416 | try { 417 | Object key = KeyModifier.class.getField(modifer).get(null); 418 | sum = sum + (Integer) key; 419 | } catch(ReflectiveOperationException e){ 420 | throw new ScreenOperationException("No " +modifer.toString() + " in class org.sikuli.script.Key "); 421 | } 422 | } 423 | region.type(text, sum); 424 | } 425 | 426 | @RobotKeyword("Paste text. Image could be empty") 427 | @ArgumentNames({"image", "text"}) 428 | public void pasteText(String image, String text) throws Exception { 429 | System.out.println("Paste Text:"); 430 | System.out.println(text); 431 | if ( !"".equals(image) ) { 432 | this.click(image); 433 | } 434 | int result = region.paste(text); 435 | if (result != 1) { 436 | throw new ScreenOperationException("Paste text failed"); 437 | } 438 | } 439 | 440 | @RobotKeyword("Click in. \nClick target image in area image.") 441 | @ArgumentNames({"areaImage", "targetImage"}) 442 | public void clickIn(String areaImage, String targetImage) throws Exception { 443 | Match match = wait(areaImage, Double.toString(this.timeout)); 444 | System.out.println(areaImage + " is found!"); 445 | capture(match.find(getPattern(targetImage))); 446 | match.click(getPattern(targetImage)); 447 | } 448 | 449 | @RobotKeyword("Double click in. \nDouble click target image in area image.") 450 | @ArgumentNames({"areaImage", "targetImage"}) 451 | public void doubleClickIn(String areaImage, String targetImage) throws Exception { 452 | Match match = wait(areaImage, Double.toString(this.timeout)); 453 | System.out.println(areaImage + " is found!"); 454 | capture(match.find(getPattern(targetImage))); 455 | match.doubleClick(getPattern(targetImage)); 456 | } 457 | 458 | @RobotKeyword("Right click in. \nRight click target image in area image.") 459 | @ArgumentNames({"areaImage", "targetImage"}) 460 | public void rightClickIn(String areaImage, String targetImage) throws Exception { 461 | Match match = wait(areaImage, Double.toString(this.timeout)); 462 | System.out.println(areaImage + " is found!"); 463 | capture(match.find(getPattern(targetImage))); 464 | match.rightClick(getPattern(targetImage)); 465 | } 466 | 467 | private String capture() { 468 | ScreenImage image = screen.capture(region); 469 | return saveImage(image); 470 | } 471 | 472 | private String capture(Region region) { 473 | return capture(region, null); 474 | } 475 | 476 | private String capture(Region region, String imageName) { 477 | if (isCaptureMatchedImage) { 478 | ScreenImage image = screen.capture(region); 479 | return saveImage(image, imageName); 480 | } 481 | return null; 482 | } 483 | 484 | @RobotKeyword("Capture region\n" 485 | + "\n\nCapture region passed" 486 | + "\nExamples:" 487 | + "\n| ${coor} | Create List | x | y | w | h |" 488 | + "\n| ${screenshotname}= | Capture region | ${coor} | demo.png |" 489 | + "\n| ${screenshotname}= | Capture region | ${coor} | ") 490 | @ArgumentNames({"coordinates", "imageName="}) 491 | public static String captureRegion(ArrayList coordinates, String imageName) { 492 | int x = Integer.parseInt(coordinates.get(0).toString()); 493 | int y = Integer.parseInt(coordinates.get(1).toString()); 494 | int w = Integer.parseInt(coordinates.get(2).toString()); 495 | int h = Integer.parseInt(coordinates.get(3).toString()); 496 | Region region = new Region(x, y, w, h); 497 | ScreenImage image = ScreenKeywords.getScreen().capture(region); 498 | return saveImage(image, imageName); 499 | } 500 | 501 | @RobotKeywordOverload 502 | public static String captureRegion(ArrayList coordinates) { 503 | return captureRegion(coordinates, null); 504 | } 505 | 506 | @RobotKeyword("Capture Roi") 507 | @ArgumentNames({"imageName="}) 508 | public String captureRoi(String imageName){ 509 | return capture(region, imageName); 510 | } 511 | 512 | @RobotKeywordOverload 513 | public String captureRoi(){ 514 | return capture(region); 515 | } 516 | 517 | @RobotKeyword("Capture whole screen, file name is returned") 518 | @ArgumentNames({}) 519 | public String captureScreen(){ 520 | return capture(); 521 | } 522 | 523 | @RobotKeyword("Highlight matched image.\n If secs is set, highlight will vanish automatically after setted seconds") 524 | @ArgumentNames({"image", "secs="}) 525 | public void highlight(String image, Integer secs) throws Exception{ 526 | Match match = null; 527 | if (highlightMap.containsKey(image)==false) { 528 | match = region.find(getPattern(image)); 529 | if (secs != null) { 530 | match.highlight(secs); 531 | } else { 532 | highlightMap.put(image, match); 533 | match.highlight(); 534 | } 535 | capture(); 536 | } else { 537 | System.out.println("*WARN* "+image+" was already highlighted"); 538 | } 539 | } 540 | 541 | @RobotKeywordOverload 542 | public void highlight(String image) throws Exception{ 543 | this.highlight(image, null); 544 | } 545 | 546 | 547 | @RobotKeyword("Clear highlight from screen") 548 | @ArgumentNames({"image"}) 549 | public void clearHighlight(String image) { 550 | if (highlightMap.containsKey(image)) { 551 | Match match = highlightMap.get(image); 552 | match.highlight(); 553 | highlightMap.remove(image); 554 | } else { 555 | System.out.println("*WARN* " + image + " was not highlighted before"); 556 | } 557 | } 558 | 559 | @RobotKeyword("Clear all highlights from screen") 560 | @ArgumentNames({}) 561 | public void clearAllHighlights() { 562 | for(Match match : highlightMap.values()) { 563 | match.highlight(); 564 | } 565 | highlightMap.clear(); 566 | } 567 | 568 | @RobotKeyword("Highlight region") 569 | @ArgumentNames({"coordinates", "timeout"}) 570 | public void highlightRegion(ArrayList coordinates, int timeout) { 571 | int x = Integer.parseInt(coordinates.get(0).toString()); 572 | int y = Integer.parseInt(coordinates.get(1).toString()); 573 | int w = Integer.parseInt(coordinates.get(2).toString()); 574 | int h = Integer.parseInt(coordinates.get(3).toString()); 575 | Region region = new Region(x, y, w, h); 576 | region.highlight(timeout); 577 | capture(region); 578 | } 579 | 580 | @RobotKeyword("Highlight ROI") 581 | @ArgumentNames({"timeout"}) 582 | public void highlightRoi(int timeout) { 583 | region.highlight(timeout); 584 | capture(region); 585 | } 586 | 587 | @RobotKeyword("Drag the source image to target image.\nIf source image is empty, drag the last match and drop at given target") 588 | @ArgumentNames({"srcImage", "targetImage"}) 589 | public void dragAndDrop(String srcImage, String targetImage) throws Exception { 590 | int result = 0; 591 | if ( "".equals(srcImage) ) { 592 | result = region.dragDrop(targetImage); 593 | wait(targetImage, Double.toString(this.timeout)); 594 | } else { 595 | Match srcMatch = wait(srcImage, Double.toString(this.timeout)); 596 | Match targetMatch = wait(targetImage, Double.toString(this.timeout)); 597 | result = region.dragDrop(srcMatch, targetMatch); 598 | } 599 | if (result==0) { 600 | capture(); 601 | throw new ScreenOperationException("Failed to drag "+srcImage+" to " +targetImage); 602 | } 603 | } 604 | 605 | @RobotKeyword("Drag the source image to target by offset.\nIf source image is empty, drag the last match and drop at given target") 606 | @ArgumentNames({"srcImage", "xOffset", "yOffset"}) 607 | public void dragAndDropByOffset(String srcImage, int xOffset, int yOffset) throws Exception { 608 | int result = 0; 609 | Match srcMatch; 610 | if ( "".equals(srcImage) ) { 611 | srcMatch = region.getLastMatch(); 612 | if(srcMatch == null) { 613 | throw new ScreenOperationException("Please input srcImage"); 614 | } 615 | } else { 616 | srcMatch = wait(srcImage, Double.toString(this.timeout)); 617 | } 618 | int newX = srcMatch.getX() + xOffset; 619 | int newY = srcMatch.getY() + yOffset; 620 | Location newLocation = new Location(newX, newY); 621 | result = region.dragDrop(newLocation); 622 | if (result==0) { 623 | capture(); 624 | throw new ScreenOperationException("Failed to drag "+srcImage+" to " +newLocation); 625 | } 626 | } 627 | 628 | @RobotKeyword("Get match score" 629 | + "Tries to find the image on the screen, returns accuracy score (0-1)" 630 | + "\n\n Examples:" 631 | + "\n | ${score} = | Get Match Score | somethingThatMayExist.png |" 632 | + "\n | Run Keyword if | ${score} > 0.95 | keyword1 | ELSE | keyword2 |") 633 | @ArgumentNames({"image"}) 634 | public Double getMatchScore(String image) throws ScreenOperationException { 635 | Match match = find(image); 636 | if (match == null) { 637 | return 0.0; 638 | }else{ 639 | return match.getScore(); 640 | } 641 | } 642 | 643 | @RobotKeyword("Press special key" 644 | + "\n Presses a special keyboard key." 645 | + "\n\n For a list of possible Keys view docs for org.sikuli.script.Key ." 646 | + "\n\n Examples:" 647 | + "\n | Double Click | textFieldWithDefaultText.png | " 648 | + "\n | Press Special Key | DELETE | ") 649 | @ArgumentNames({"keyConstant"}) 650 | public void pressSpecialKey(String specialCharName) throws ScreenOperationException{ 651 | try{ 652 | Object key = Key.class.getField(specialCharName).get(null); 653 | region.type(key.toString()); 654 | } 655 | catch(ReflectiveOperationException e){ 656 | throw new ScreenOperationException("No " +specialCharName.toString() + " in class org.sikuli.script.Key "); 657 | } 658 | } 659 | 660 | @RobotKeyword("Key down" 661 | + "\n Press keyboard key and hold it." 662 | + "\n\n For a list of possible Keys view docs for org.sikuli.script.Key ." 663 | + "\n\n Examples:" 664 | + "\n | Key down | CTRL | " 665 | + "\n | Click | textFieldWithDefaultText.png | ") 666 | @ArgumentNames({"keyConstant"}) 667 | public void keyDown(String specialCharName) throws ScreenOperationException{ 668 | try{ 669 | Object key = Key.class.getField(specialCharName).get(null); 670 | region.keyDown(key.toString()); 671 | } 672 | catch(ReflectiveOperationException e){ 673 | throw new ScreenOperationException("No " +specialCharName.toString() + " in class org.sikuli.script.Key "); 674 | } 675 | } 676 | 677 | @RobotKeyword("Key up" 678 | + "\n Release keyboard key." 679 | + "\n\n For a list of possible Keys view docs for org.sikuli.script.Key ." 680 | + "\n\n Examples:" 681 | + "\n | Click | textFieldWithDefaultText.png | " 682 | + "\n | Key UP | CTRL | ") 683 | @ArgumentNames({"keyConstant"}) 684 | public void keyUp(String specialCharName) throws ScreenOperationException{ 685 | try{ 686 | Object key = Key.class.getField(specialCharName).get(null); 687 | region.keyUp(key.toString()); 688 | } 689 | catch(ReflectiveOperationException e){ 690 | throw new ScreenOperationException("No " +specialCharName.toString() + " in class org.sikuli.script.Key "); 691 | } 692 | } 693 | 694 | 695 | @RobotKeyword("Mouse move" 696 | + "Move the mouse pointer to the target" 697 | + "\n\n @image: if image is empty, will move mouse to the last matched." 698 | + "\n\n Examples:" 699 | + "\n | Mouse Move | test.png | " 700 | + "\n | Screen Should Contain | test.png | " 701 | + "\n | Mouse Move |") 702 | @ArgumentNames({"image="}) 703 | public void mouseMove(String image) throws Exception{ 704 | Match match = wait(image, Double.toString(this.timeout)); 705 | int result = match.mouseMove(getPattern(image)); 706 | if (result == 0) { 707 | throw new ScreenOperationException("Failed to move mouse to "+image); 708 | } 709 | } 710 | 711 | @RobotKeywordOverload 712 | public void mouseMove() throws Exception{ 713 | int result = region.mouseMove(); 714 | if (result==0) { 715 | throw new ScreenOperationException("Failed to move mouse to last matched image"); 716 | } 717 | } 718 | 719 | @RobotKeyword("Mouse move region" 720 | + "Move the mouse pointer to the target region" 721 | + "\n\n @coordinates: coordinates where mouse should move" 722 | + "\n\n Examples:" 723 | + "\n | Mouse Move region | [20, 20, 20, 20] |") 724 | @ArgumentNames({"coordinates", "highlight_timeout"}) 725 | public void mouseMoveRegion(ArrayList coordinates, int highlight_timeout) throws Exception { 726 | int x = Integer.parseInt(coordinates.get(0).toString()); 727 | int y = Integer.parseInt(coordinates.get(1).toString()); 728 | int w = Integer.parseInt(coordinates.get(2).toString()); 729 | int h = Integer.parseInt(coordinates.get(3).toString()); 730 | Region region = new Region(x, y, w, h); 731 | int result = region.mouseMove(); 732 | if (result==0) { 733 | throw new ScreenOperationException("Failed to move mouse to last matched image"); 734 | } 735 | if (highlight_timeout > 0) { 736 | region.highlight(highlight_timeout); 737 | } 738 | } 739 | 740 | @RobotKeywordOverload 741 | public void mouseMoveRegion(ArrayList coordinates) throws Exception { 742 | mouseMoveRegion(coordinates, 0); 743 | } 744 | 745 | @RobotKeyword("Mouse move location" 746 | + "Move the mouse pointer to the target location" 747 | + "\n\n @x: x cooridnate where mouse should move" 748 | + "\n\n @y: y cooridnate where mouse should move" 749 | + "\n\n Examples:" 750 | + "\n | Mouse Move Location | 20 | 20 |") 751 | @ArgumentNames({"x=0", "y=0"}) 752 | public void mouseMoveLocation(int x, int y) throws Exception { 753 | Location location = new Location(x, y); 754 | int result = region.mouseMove(location); 755 | if (result==0) { 756 | throw new ScreenOperationException("Failed to move mouse to last matched image"); 757 | } 758 | } 759 | 760 | @RobotKeyword("Mouse down" 761 | + "\n Press and hold the specified buttons" 762 | + "\n\n @mouseButtons: Could be LEFT, MIDDLE, RIGHT" 763 | + "\n\n Examples:" 764 | + "\n | Mouse Move | test.png | " 765 | + "\n | Mouse Down | LEFT | RIGHT |" 766 | + "\n | Mouse Up |") 767 | @ArgumentNames({"*mouseButtons"}) 768 | public void mouseDown(String[] mouseButtons) throws Exception{ 769 | String currentButton = ""; 770 | try{ 771 | int sum = 0; 772 | for (String button : mouseButtons) { 773 | currentButton = button; 774 | int buttonValue = (Integer) Button.class.getField(button).get(null); 775 | sum = sum + buttonValue; 776 | } 777 | region.mouseDown(sum); 778 | } 779 | catch(ReflectiveOperationException e){ 780 | throw new ScreenOperationException("No " +currentButton + " in class org.sikuli.script.Button "); 781 | } 782 | } 783 | 784 | @RobotKeyword("Mouse up" 785 | + "\n Release the specified mouse buttons" 786 | + "\n\n @mouseButtons: Could be LEFT, MIDDLE, RIGHT. If empty, all currently held buttons are released" 787 | + "\n\n Examples:" 788 | + "\n | Mouse Move | test.png | " 789 | + "\n | Mouse Down | LEFT | RIGHT |" 790 | + "\n | Mouse Up | LEFT | RIGHT |") 791 | @ArgumentNames({"*mouseButtons"}) 792 | public void mouseUp(String[] mouseButtons) throws Exception{ 793 | String currentButton = ""; 794 | try{ 795 | int sum = 0; 796 | for (String button : mouseButtons) { 797 | currentButton = button; 798 | int buttonValue = (Integer) Button.class.getField(button).get(null); 799 | sum = sum + buttonValue; 800 | } 801 | region.mouseUp(sum); 802 | } 803 | catch(ReflectiveOperationException e){ 804 | throw new ScreenOperationException("No " +currentButton + " in class org.sikuli.script.Button "); 805 | } 806 | } 807 | 808 | @RobotKeywordOverload 809 | public void mouseUp() throws Exception{ 810 | region.mouseUp(); 811 | } 812 | 813 | @RobotKeyword("Wheel up" 814 | + "\n Move mouse to the target, and wheel up with give steps" 815 | + "\n\n Examples:" 816 | + "\n | Wheel Up | 5 | " 817 | + "\n | Wheel Up | 5 | test.png |") 818 | @ArgumentNames({"steps", "image="}) 819 | public void wheelUp(int steps, String image) throws Exception{ 820 | wait(image, Double.toString(this.timeout)); 821 | region.wheel(getPattern(image), Button.WHEEL_UP, steps); 822 | } 823 | 824 | @RobotKeywordOverload 825 | public void wheelUp(int steps) throws Exception{ 826 | region.wheel(Button.WHEEL_UP, steps); 827 | } 828 | 829 | @RobotKeyword("Wheel down" 830 | + "\n Move mouse to the target, and wheel down with give steps" 831 | + "\n\n Examples:" 832 | + "\n | Wheel Down | 5 | " 833 | + "\n | Wheel Down | 5 | test.png |") 834 | @ArgumentNames({"steps", "image="}) 835 | public void wheelDown(int steps, String image) throws Exception{ 836 | wait(image, Double.toString(this.timeout)); 837 | region.wheel(getPattern(image), Button.WHEEL_DOWN, steps); 838 | } 839 | 840 | @RobotKeywordOverload 841 | public void wheelDown(int steps) throws Exception{ 842 | region.wheel(Button.WHEEL_DOWN, steps); 843 | } 844 | 845 | @RobotKeywordOverload 846 | public String getText() throws Exception { 847 | return region.text(); 848 | } 849 | 850 | @RobotKeyword("Get text" 851 | + "\n\n If image is not given, keyword will get text from whole Screen" 852 | + "\n If image is given, keyword will get text from matched region" 853 | + "\n Call keyword setOcrTextRead to set OcrTextRead as true, before using text recognition keywords" 854 | + "\n\n Examples:" 855 | + "\n | Set Ocr Text Read | true |" 856 | + "\n | Get Text |" 857 | + "\n | Get Text | test.png |") 858 | @ArgumentNames({"image="}) 859 | public String getText(String image) throws Exception { 860 | Match match = find(image); 861 | if (match == null) { 862 | capture(region); 863 | throw new ScreenOperationException("Could not find " + image); 864 | } 865 | Image matchImage = match.getImage(); 866 | return matchImage.text(); 867 | } 868 | 869 | @RobotKeyword("Wait For Image" 870 | + "\n\n Check wantedImage exist. If notWantedImage appear or timeout happened, throw exception" 871 | + "\n\n @wantedImage: expected image in screen" 872 | + "\n\n @notWantedImage: unexpected image in screen" 873 | + "\n\n @timeout: wait seconds" 874 | + "\n\n Examples:" 875 | + "\n | Wait For Image | wanted.png | notWanted.png | 5 |") 876 | @ArgumentNames({"wantedImage", "notWantedImage", "timeout"}) 877 | public void waitForImage(String wantedImage, String notWantedImage, int timeout) throws Exception { 878 | Date begineTime = new Date(); 879 | while (System.currentTimeMillis() - begineTime.getTime() < timeout*1000) { 880 | Match wantedMatch = region.exists(getPattern(wantedImage), 0); 881 | Match notWantedMatch = region.exists(getPattern(notWantedImage), 0); 882 | if (wantedMatch != null) { 883 | return; 884 | } else if ( notWantedMatch != null ) { 885 | capture(notWantedMatch); 886 | throw new ScreenOperationException(notWantedImage + " is founded! " + notWantedMatch); 887 | } else { 888 | Thread.sleep(500); 889 | } 890 | } 891 | capture(region); 892 | throw new TimeoutException("Could not find " + wantedImage); 893 | 894 | } 895 | 896 | @RobotKeyword("Wait For Multiple Images" 897 | + "\n\n Check if images exists in expectedImages or notExpectedImages list. " 898 | + "If image appears that is listed in notExpectedImages list or timeout happened, throw exception " 899 | + "If image appears that is listed in expectedImageslist return succesfully. " 900 | + "\n\n @timeout: wait seconds" 901 | + "\n\n @pollingInterval: time in seconds between screen checks" 902 | + "\n\n @expectedImages: list of expected images in screen" 903 | + "\n\n @notExpectedImages: list of not expected images in screen" 904 | + "\n\n Examples:" 905 | + "\n | @{wanted_images} = | Create List | wanted_image1.png | wanted_image2.png |" 906 | + "\n | @{not_wanted_images} = | Create List | not_wanted_image1.png | not_wanted_image2.png | not_wanted_image3.png |" 907 | + "\n | Wait For Multiple Images | 900 | 10 | ${wanted_images} | ${not_wanted_images} |") 908 | @ArgumentNames({"timeout", "pollingInterval", "expectedImages", "notExpectedImages"}) 909 | public String waitForMultipleImages(int timeout, int pollingInterval, 910 | ArrayList expectedImages, ArrayList notExpectedImages) throws Exception { 911 | 912 | Date beginTime = new Date(); 913 | 914 | while (System.currentTimeMillis() - beginTime.getTime() < timeout*1000) { 915 | 916 | for (String wantedImage : expectedImages) 917 | { 918 | Match wantedMatch = region.exists(getPattern(wantedImage), 0); 919 | 920 | if (wantedMatch != null) { 921 | return wantedImage; 922 | } 923 | } 924 | 925 | for (String notWantedImage : notExpectedImages) { 926 | Match notWantedMatch = region.exists(getPattern(notWantedImage), 0); 927 | 928 | if (notWantedMatch != null) { 929 | capture(); 930 | throw new ScreenOperationException(notWantedImage + " is found! " + notWantedMatch); 931 | } 932 | } 933 | 934 | Thread.sleep(pollingInterval * 1000); 935 | } 936 | 937 | capture(); 938 | throw new TimeoutException("Could not find any images " + Arrays.toString(expectedImages.toArray()) + 939 | Arrays.toString(notExpectedImages.toArray())); 940 | 941 | } 942 | 943 | @RobotKeyword("Image Count" 944 | + "\n Count how many times the same picture is detected in screen." 945 | + "\n\n Examples:" 946 | + "\n | ${image_cnt}= | Image Count | test.png |") 947 | @ArgumentNames({"image"}) 948 | public int imageCount(String image){ 949 | int count = 0; 950 | Iterator matches; 951 | try{ 952 | matches = region.findAll(getPattern(image)); 953 | }catch(FindFailed e){ 954 | return 0; 955 | } 956 | while(matches.hasNext()){ 957 | count++; 958 | matches.next(); 959 | } 960 | return count; 961 | } 962 | 963 | @RobotKeyword("Exists" 964 | + "\n\n Check whether image exists in screen" 965 | + "\n @image: expected image in screen" 966 | + "\n @timeout: wait seconds" 967 | + "\n\n Examples:" 968 | + "\n | ${is_exist}= | Exists | image.png | 0 |") 969 | @ArgumentNames({"image", "timeout="}) 970 | public Boolean exists(String image, int timeout) { 971 | Match match = region.exists(getPattern(image), timeout); 972 | if (match != null) { 973 | return true; 974 | } 975 | return false; 976 | } 977 | 978 | @RobotKeywordOverload 979 | public Boolean exists(String image) throws Exception{ 980 | return exists(image, 0); 981 | } 982 | 983 | @RobotKeyword("Change screen id" 984 | + "\n For multi display, user could use this keyword to switch to the correct screen" 985 | + "\n\n Examples:" 986 | + "\n | Change screen id | 1 |") 987 | @ArgumentNames({"screenId"}) 988 | public void changeScreenId(int screenId) { 989 | screen = new Screen(screenId); 990 | region = new Region(screen); 991 | } 992 | 993 | @RobotKeyword("Reset Roi" 994 | + "\n Set Region of interest to full screen" 995 | + "\n\n Examples:" 996 | + "\n | Reset roi |") 997 | @ArgumentNames({}) 998 | public void resetRoi() { 999 | region = new Region(screen); 1000 | } 1001 | 1002 | @RobotKeyword("Get current screen id") 1003 | @ArgumentNames({}) 1004 | public int getCurrentScreenId() { 1005 | return screen.getID(); 1006 | } 1007 | 1008 | @RobotKeyword("Get number of screens") 1009 | @ArgumentNames({}) 1010 | public int getNumberOfScreens() { 1011 | return Screen.getNumberScreens(); 1012 | } 1013 | 1014 | @RobotKeyword("Get screen coordinates" 1015 | + "\n\nReturn screen coordinates for active screen" 1016 | + "\n\nExamples:" 1017 | + "\n| @{coordinates}= | Get Screen Coordinates | 0 |") 1018 | @ArgumentNames({}) 1019 | public int[] getScreenCoordinates() { 1020 | int[] coordinates = new int[4]; 1021 | coordinates[0] = screen.getX(); 1022 | coordinates[1] = screen.getY(); 1023 | coordinates[2] = screen.getW(); 1024 | coordinates[3] = screen.getH(); 1025 | return coordinates; 1026 | } 1027 | 1028 | @RobotKeyword("Get Image Coordinates" 1029 | + "\n\n Return image coordinates, within region" 1030 | + "\n Examples:" 1031 | + "\n | ${imageCoordinates}= | Get Image Coordinates | image.png=0.75 |" 1032 | + "\n | ${imageCoordinates}= | Get Image Coordinates | image.png=0.75 | [x, y, w, z] |") 1033 | @ArgumentNames({"image", "coordinates=[]"}) 1034 | public int[] getImageCoordinates(String image, ArrayList coordinates) throws Exception { 1035 | Match match = null; 1036 | if (coordinates.isEmpty()) { 1037 | match = ScreenKeywords.getScreen().find(getPattern(image)); 1038 | } else { 1039 | int x = Integer.parseInt(coordinates.get(0).toString()); 1040 | int y = Integer.parseInt(coordinates.get(1).toString()); 1041 | int w = Integer.parseInt(coordinates.get(2).toString()); 1042 | int h = Integer.parseInt(coordinates.get(3).toString()); 1043 | Region region = new Region(x, y, w, h); 1044 | match = region.find(getPattern(image)); 1045 | } 1046 | 1047 | int [] image_coordinates = new int[4]; 1048 | image_coordinates[0] = match.getX(); 1049 | image_coordinates[1] = match.getY(); 1050 | image_coordinates[2] = match.getW(); 1051 | image_coordinates[3] = match.getH(); 1052 | return image_coordinates; 1053 | } 1054 | 1055 | @RobotKeywordOverload 1056 | public int[] getImageCoordinates(String image) throws Exception{ 1057 | return getImageCoordinates(image, new ArrayList()); 1058 | } 1059 | 1060 | @RobotKeyword("Get extended region from" 1061 | + "\n Extended the given image creating a region above or below with the same width" 1062 | + "\n The height can change using the multiplier @number_of_times_to_repeat, if 2 is given the new region will have twice the height of the orignalge ") 1063 | @ArgumentNames({"image", "direction", "number_of_times_to_repeat"}) 1064 | public int[] getExtendedRegionFrom(String image, String direction, int number_of_times_to_repeat) throws Exception { 1065 | 1066 | Match match = null; 1067 | try{ 1068 | match = screen.find(getPattern(image)); 1069 | Region new_region = new Region(match); 1070 | int height = new_region.h; 1071 | int width = new_region.w; 1072 | 1073 | Region r = null; 1074 | int [] result = new int[4]; 1075 | if (direction.equals("below")){ 1076 | r = new_region.below(height * number_of_times_to_repeat); 1077 | r.highlight(1); 1078 | } 1079 | else if(direction.equals("above")){ 1080 | r = new_region.above(height * number_of_times_to_repeat); 1081 | r.highlight(1); 1082 | } 1083 | else if(direction.equals("left")){ 1084 | r = new_region.left(width * number_of_times_to_repeat); 1085 | r.highlight(1); 1086 | } 1087 | else if(direction.equals("right")){ 1088 | r = new_region.right(width * number_of_times_to_repeat); 1089 | r.highlight(1); 1090 | } 1091 | else{ 1092 | r = new_region; 1093 | } 1094 | 1095 | result[0] = r.x; 1096 | result[1] = r.y; 1097 | result[2] = r.w; 1098 | result[3] = r.h; 1099 | return result; 1100 | } 1101 | catch (FindFailed e) { 1102 | capture(); 1103 | throw new ScreenOperationException("Extended image "+image+" failed" + e.getMessage(), e); 1104 | } 1105 | 1106 | } 1107 | 1108 | @RobotKeyword("Read text from region") 1109 | @ArgumentNames({"reg"}) 1110 | public String readTextFromRegion(ArrayList reg){ 1111 | System.out.println("reg variable: " + reg); 1112 | 1113 | int x = Integer.parseInt(reg.get(0).toString()); 1114 | int y = Integer.parseInt(reg.get(1).toString()); 1115 | int w = Integer.parseInt(reg.get(2).toString()); 1116 | int h = Integer.parseInt(reg.get(3).toString()); 1117 | 1118 | Region region = new Region(x,y,w,h); 1119 | 1120 | return region.text(); 1121 | } 1122 | 1123 | @RobotKeyword("Set ROI" 1124 | + "\n\n Set region of interest on screen" 1125 | + "\n Optionally pass highlight timeout." 1126 | + "\n\n Examples:" 1127 | +"${coordinates} | set variable | @{x, y, w, h] |" 1128 | + "\n | Set ROI | ${coordinates} |" 1129 | + "\n | Set ROI | ${coordinates} | 2 |") 1130 | @ArgumentNames({"coordinates", "timeout=0"}) 1131 | public void setRoi(ArrayList coordinates, int timeout) { 1132 | int x = Integer.parseInt(coordinates.get(0).toString()); 1133 | int y = Integer.parseInt(coordinates.get(1).toString()); 1134 | int w = Integer.parseInt(coordinates.get(2).toString()); 1135 | int h = Integer.parseInt(coordinates.get(3).toString()); 1136 | region.setROI(x, y, w, h); 1137 | if (timeout > 0) { 1138 | this.highlightRoi(timeout); 1139 | } 1140 | } 1141 | 1142 | @RobotKeywordOverload 1143 | public void setRoi(ArrayList coordinates) { 1144 | setRoi(coordinates, 0); 1145 | } 1146 | 1147 | @RobotKeyword("Select Region" 1148 | + "\n\n Allow user to select a region and capture it." 1149 | + "\n Return array of [capturedImagePath, x, y, w, h]" 1150 | + "\n\n Examples:" 1151 | + "\n | @{SelectedRegion}= | Select region |") 1152 | @ArgumentNames({"message"}) 1153 | public String[] selectRegion(String message) { 1154 | Region region = screen.selectRegion(message); 1155 | String imagePath = capture(region); 1156 | String[] retval = new String[5]; 1157 | retval[0] = imagePath; 1158 | retval[1] = String.valueOf(region.getX()); 1159 | retval[2] = String.valueOf(region.getY()); 1160 | retval[3] = String.valueOf(region.getW()); 1161 | retval[4] = String.valueOf(region.getH()); 1162 | return retval; 1163 | } 1164 | 1165 | @RobotKeyword("Double Click On Region" + 1166 | "\n there's no offset to be configured" + 1167 | "\n works with the keyword Get Extended Region From") 1168 | @ArgumentNames("region") 1169 | public void doubleClickOnRegion(ArrayList region) throws Exception{ 1170 | int x = Integer.parseInt(region.get(0).toString()); 1171 | int y = Integer.parseInt(region.get(1).toString()); 1172 | int w = Integer.parseInt(region.get(2).toString()); 1173 | int h = Integer.parseInt(region.get(3).toString()); 1174 | 1175 | try{ 1176 | Region _region = new Region(x,y,w,h); 1177 | _region.doubleClick(); 1178 | } 1179 | catch(Exception e){ 1180 | throw new Exception("error on doubleClickOnRegion, message: " + e); 1181 | } 1182 | } 1183 | 1184 | @RobotKeyword("Click On Region" + 1185 | "\n there's no offset to be configured" + 1186 | "\n works with the keyword Get Extended Region From") 1187 | @ArgumentNames("region") 1188 | public void clickOnRegion(ArrayList region) throws Exception{ 1189 | int x = Integer.parseInt(region.get(0).toString()); 1190 | int y = Integer.parseInt(region.get(1).toString()); 1191 | int w = Integer.parseInt(region.get(2).toString()); 1192 | int h = Integer.parseInt(region.get(3).toString()); 1193 | 1194 | try{ 1195 | Region _region = new Region(x,y,w,h); 1196 | _region.click(); 1197 | } 1198 | catch(Exception e){ 1199 | throw new Exception("error on clickOnRegion, message: " + e); 1200 | } 1201 | } 1202 | 1203 | @RobotKeyword("Double Click On Match" + 1204 | "\n there's no offset to be configured" + 1205 | "\n works with the keyword Return Match From Region") 1206 | @ArgumentNames("match") 1207 | public void doubleClickOnMatch(ArrayList match) throws Exception{ 1208 | int x = Integer.parseInt(match.get(0).toString()); 1209 | int y = Integer.parseInt(match.get(1).toString()); 1210 | int w = Integer.parseInt(match.get(2).toString()); 1211 | int h = Integer.parseInt(match.get(3).toString()); 1212 | double sc = Double.parseDouble(match.get(4).toString()); 1213 | try{ 1214 | Region reg = new Region(x,y,w,h); 1215 | Match _el = new Match(reg, sc); 1216 | screen.doubleClick(_el); 1217 | }catch (FindFailed e){ 1218 | capture(); 1219 | throw new FindFailed("not found "); 1220 | } 1221 | } 1222 | 1223 | @RobotKeyword("Click On Match" + 1224 | "\n there's no offset to be configured" + 1225 | "\n works with the keyword Return Match From Region") 1226 | @ArgumentNames("match") 1227 | public void clickOnMatch(ArrayList match) throws Exception{ 1228 | int x = Integer.parseInt(match.get(0).toString()); 1229 | int y = Integer.parseInt(match.get(1).toString()); 1230 | int w = Integer.parseInt(match.get(2).toString()); 1231 | int h = Integer.parseInt(match.get(3).toString()); 1232 | double sc = Double.parseDouble(match.get(4).toString()); 1233 | try{ 1234 | Region reg = new Region(x,y,w,h); 1235 | Match el = new Match(reg, sc); 1236 | screen.click(el); 1237 | }catch (FindFailed e){ 1238 | capture(); 1239 | throw new FindFailed("not found "); 1240 | } 1241 | } 1242 | 1243 | @RobotKeyword("Return Match From Region" + 1244 | "\n expect a region (from keyword Get Extended Region From) and a target to be search for (an image.png)" + 1245 | "\n returns the target as a object (string), it can be used with Click On Match keywords") 1246 | 1247 | @ArgumentNames({"region", "target"}) 1248 | public ArrayList returnMatchFromRegion(ArrayList region, String image)throws Exception{ 1249 | 1250 | ArrayList ob = new ArrayList(); 1251 | int x = Integer.parseInt(region.get(0).toString()); 1252 | int y = Integer.parseInt(region.get(1).toString()); 1253 | int w = Integer.parseInt(region.get(2).toString()); 1254 | int h = Integer.parseInt(region.get(3).toString()); 1255 | 1256 | System.out.print("x: " + x); 1257 | System.out.print("x: " + y); 1258 | System.out.print("x: " + w); 1259 | System.out.print("x: " + h); 1260 | 1261 | Region new_region = new Region(x,y,w,h); 1262 | 1263 | try{ 1264 | Match el = new_region.find(image); 1265 | ob.add(el.x); 1266 | ob.add(el.y); 1267 | ob.add(el.w); 1268 | ob.add(el.h); 1269 | ob.add(el.getScore()); 1270 | return ob; 1271 | } 1272 | catch (FindFailed e){ 1273 | return ob; 1274 | } 1275 | } 1276 | 1277 | @RobotKeyword("From Region Jump To" + 1278 | "\n Create a region and translate it related to the given region, the created region will have the exactly same height and width as the passed one " + 1279 | "\n ${jumps} = number of 'jumps' to move, like on a chess game, jumps will be the number of squares a piece moves " + 1280 | "\n ${direction} = | below | above | left | right | " + 1281 | "\n ${margem} = add a space between jumps, must be >= 1 " + 1282 | "\n |${translated_region} = | From Region Jump To | ${original_region} | below | 4 | 1 |") 1283 | @ArgumentNames({"region", "direction", "jumps", "margin"}) 1284 | public ArrayList fromRegionJumpTo(ArrayList region, String direction, String jumps, String margem) throws Exception { 1285 | ArrayList result = new ArrayList(); 1286 | 1287 | int Jumps = Integer.parseInt(jumps); 1288 | int Margem = Integer.parseInt(margem); 1289 | int x = Integer.parseInt(region.get(0).toString()); 1290 | int y = Integer.parseInt(region.get(1).toString()); 1291 | int w = Integer.parseInt(region.get(2).toString()); 1292 | int h = Integer.parseInt(region.get(3).toString()); 1293 | 1294 | Region original = new Region(x,y,w,h); 1295 | Region r = null; 1296 | Location location = new Location(original.x, original.y); 1297 | 1298 | 1299 | if (direction.equals("below")){ 1300 | location.translate(0, ((original.h * Jumps) - (Jumps * Margem))); 1301 | r = new Region(location.x, location.y, w , h ); 1302 | } 1303 | else if(direction.equals("above")){ 1304 | location.translate(0, -((original.h * Jumps) - (Jumps * Margem))); 1305 | r = new Region(location.x, location.y, w , h ); 1306 | } 1307 | else if(direction.equals("left")){ 1308 | location.translate(-((original.w * Jumps) + (Jumps * Margem)), 0); 1309 | r = new Region(location.x, location.y, w , h ); 1310 | } 1311 | else if(direction.equals("right")){ 1312 | location.translate(((original.w * Jumps) + (Jumps * Margem)), 0); 1313 | r = new Region(location.x, location.y, w , h ); 1314 | } 1315 | else{ 1316 | throw new Exception("direction has a invalid value"); 1317 | } 1318 | 1319 | result.add(r.x); 1320 | result.add(r.y); 1321 | result.add(r.w); 1322 | result.add(r.h); 1323 | 1324 | return result; 1325 | } 1326 | 1327 | @RobotKeyword("Get Extended Region From Region" + 1328 | "\n Extended the given image creating a region above, below, in the left side or on the right, with the same height and width" + 1329 | "\n The height and width can change using the multiplier @number_of_times_to_repeat " + 1330 | "\n If 2 is given and direction = below the new region will have twice the height of the orignal and will be located right below it" + 1331 | "\n |${below_region} = | Get Extended Region From Region | ${another_region} | below | 1 |") 1332 | 1333 | @ArgumentNames({"image", "direction", "number of times to repeat"}) 1334 | public ArrayList getExtendedRegionFromRegion(ArrayList region, String direction, String number_of_times_to_repeat) throws Exception { 1335 | int number = Integer.parseInt(number_of_times_to_repeat); 1336 | 1337 | int x = Integer.parseInt(region.get(0).toString()); 1338 | int y = Integer.parseInt(region.get(1).toString()); 1339 | int w = Integer.parseInt(region.get(2).toString()); 1340 | int h = Integer.parseInt(region.get(3).toString()); 1341 | 1342 | try{ 1343 | Region new_region = new Region(x,y,w,h); 1344 | int height = new_region.h; 1345 | int width = new_region.w; 1346 | 1347 | Region r = null; 1348 | ArrayList result = new ArrayList(); 1349 | 1350 | if (direction.equals("below")){ 1351 | r = new_region.below(height * number); 1352 | } 1353 | else if(direction.equals("above")){ 1354 | r = new_region.above(height * number); 1355 | } 1356 | else if(direction.equals("left")){ 1357 | r = new_region.left(width * number); 1358 | } 1359 | else if(direction.equals("right")){ 1360 | r = new_region.right(width * number); 1361 | } 1362 | else if(direction.equals("original")){ 1363 | r = new_region; 1364 | } 1365 | else{ 1366 | throw new Exception("direction has a invalid value"); 1367 | } 1368 | 1369 | result.add(r.x); 1370 | result.add(r.y); 1371 | result.add(r.w); 1372 | result.add(r.h); 1373 | 1374 | System.out.println("[log] Get extended region from region result: " + result); 1375 | return result; 1376 | } 1377 | catch (Exception e) { 1378 | capture(); 1379 | throw new Exception("Error: " + e); 1380 | } 1381 | } 1382 | 1383 | @RobotKeyword("Get Extended Region From Image" + 1384 | "\n Extended the given image creating a new region above, below, on the left or on the right side, with the same height and width" + 1385 | "\n The height and width can change using the multiplier @number_of_times_to_repeat " + 1386 | "\n If orginal if giver as arguments, the region will be exactly the same location as the image, last argument is ignored " + 1387 | "\n Ex: If 2 is given and direction = below the new region will have twice the height of the given image and will be located right below it" + 1388 | "\n |${region} = | Get Extended Region From Image | image.png | below | 1 |" + 1389 | "\n |${region} = | Get Extended Region From Image | image.png | original | 1 #this argument is ignored |") 1390 | 1391 | @ArgumentNames({"image", "direction", "number of times to repeat"}) 1392 | public int[] getExtendedRegionFromImage(String image, String direction, String number_of_times_to_repeat) throws Exception { 1393 | try{ 1394 | int number = Integer.parseInt(number_of_times_to_repeat); 1395 | Match match = screen.find(image); 1396 | Region new_region = new Region(match); 1397 | 1398 | Region r = null; 1399 | int [] result = new int[4]; 1400 | 1401 | if (direction.equals("below")){ 1402 | r = new_region.below(new_region.h * number); 1403 | } 1404 | else if(direction.equals("above")){ 1405 | r = new_region.above(new_region.h * number); 1406 | } 1407 | else if(direction.equals("left")){ 1408 | r = new_region.left(new_region.w * number); 1409 | } 1410 | else if(direction.equals("right")){ 1411 | r = new_region.right(new_region.w * number); 1412 | } 1413 | else if(direction.equals("original")){ 1414 | r = new_region; 1415 | } 1416 | else{ 1417 | throw new Exception("direction has a invalid value"); 1418 | } 1419 | 1420 | result[0] = r.x; 1421 | result[1] = r.y; 1422 | result[2] = r.w; 1423 | result[3] = r.h; 1424 | 1425 | System.out.println("[log] Get extended region from image result: " + result); 1426 | return result; 1427 | } 1428 | catch (FindFailed e) { 1429 | capture(); 1430 | throw new ScreenOperationException("Extended image not found on the screen "+ image +" failed" + e.getMessage(), e); 1431 | } 1432 | } 1433 | 1434 | private static String saveImage(ScreenImage image) { 1435 | return saveImage(image, null); 1436 | } 1437 | 1438 | private static String saveImage(ScreenImage image, String name) { 1439 | String imagePath; 1440 | if (name == null || name.equals("")) { 1441 | imagePath = image.save(CaptureFolder.getInstance().getCaptureFolder()); 1442 | } else { 1443 | imagePath = image.save(CaptureFolder.getInstance().getCaptureFolder(), name); 1444 | } 1445 | System.out.println("*DEBUG* Saved path: " + imagePath); 1446 | File file = new File(imagePath); 1447 | String fileName = file.getName(); 1448 | System.out.println("*HTML* "); 1449 | return imagePath; 1450 | } 1451 | } 1452 | -------------------------------------------------------------------------------- /src/java/com/github/rainmanwy/robotframework/sikulilib/keywords/SettingsKeywords.java: -------------------------------------------------------------------------------- 1 | package com.github.rainmanwy.robotframework.sikulilib.keywords; 2 | 3 | import org.robotframework.javalib.annotation.ArgumentNames; 4 | import org.robotframework.javalib.annotation.RobotKeyword; 5 | import org.robotframework.javalib.annotation.RobotKeywords; 6 | import org.sikuli.basics.Settings; 7 | 8 | 9 | /** 10 | * Created by Wang Yang on 2016/5/5. 11 | * 20201018 addings: 12 | * - Set OCR language keyword 13 | * - Set OCD Read documentation clarified 14 | */ 15 | 16 | @RobotKeywords 17 | public class SettingsKeywords { 18 | 19 | @RobotKeyword("Set min similarity (accuracy of matching elements)." 20 | + "\n\nminSimilarity can be a decimal number between 0 and 1" 21 | + "\n\nExample:" 22 | + "\n\n| Set Min Similarity | 0.85 |") 23 | @ArgumentNames({"minSimilarity"}) 24 | public String setMinSimilarity(String minSimilarity) { 25 | double prevMinSimilarity = Settings.MinSimilarity; 26 | Settings.MinSimilarity = Double.parseDouble(minSimilarity); 27 | return Double.toString(prevMinSimilarity); 28 | } 29 | 30 | @RobotKeyword("OCR text read" 31 | + "\nIf needed use Set OCR Language before." 32 | + "`\nDefault language : English (eng).") 33 | @ArgumentNames({"ocrTextRead"}) 34 | public void setOcrTextRead(boolean ocrTextRead) { 35 | Settings.OcrTextRead = ocrTextRead; 36 | } 37 | 38 | @RobotKeyword("Set OCR language" 39 | + "\n\nSet OCR language" 40 | + "\nThree letters parameter" 41 | + "\nDefault : eng for English language" 42 | + "\nExamples:" 43 | + "\n| Set OCR Language | eng |" 44 | + "\n| Set OCR Language | fra |") 45 | @ArgumentNames({"ocrTextLanguage"}) 46 | public void setOcrLanguage(String ocrTextLanguage) { 47 | Settings.OcrLanguage = ocrTextLanguage; 48 | } 49 | 50 | @RobotKeyword("Set show actions") 51 | @ArgumentNames({"showActions"}) 52 | public void setShowActions(boolean showActions) { 53 | Settings.setShowActions(showActions); 54 | } 55 | 56 | @RobotKeyword("Set move mouse delay") 57 | @ArgumentNames({"delay"}) 58 | public void setMoveMouseDelay(float delay) { 59 | Settings.MoveMouseDelay = delay; 60 | } 61 | 62 | @RobotKeyword("Set slow motion delay" 63 | + "\n Control the duration of the visual effect (seconds).") 64 | @ArgumentNames({"delay"}) 65 | public void setSlowMotionDelay(float delay) { 66 | Settings.SlowMotionDelay = delay; 67 | } 68 | 69 | @RobotKeyword("Set wait scan rate" 70 | + "\n Specify the number of times actual search operations are performed per second while waiting for a pattern to appear or vanish.") 71 | @ArgumentNames({"delay"}) 72 | public void setWaitScanRate(float scanRate) { 73 | Settings.WaitScanRate = scanRate; 74 | } 75 | 76 | @RobotKeyword("Set Always Resize" 77 | + "\nA decimal value greater 0 and not equal to 1 to switch the feature on." 78 | + "\nWith this setting you can tell SikuliX to generally resize all given images before a search operation using the given factor, which is applied to both width and height. The implementation internally uses the standard behavior of resizing a Java-AWT-BufferedImage." 79 | + "\n\nTo switch the feature off again, just assign 0 or 1." 80 | ) 81 | @ArgumentNames({"resize"}) 82 | public void setAlwaysResize(float resize) { 83 | Settings.AlwaysResize = resize; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/java/com/github/rainmanwy/robotframework/sikulilib/utils/CaptureFolder.java: -------------------------------------------------------------------------------- 1 | package com.github.rainmanwy.robotframework.sikulilib.utils; 2 | 3 | import java.io.File; 4 | 5 | /** 6 | * Created by Wang Yang on 2015/10/8. 7 | */ 8 | 9 | public class CaptureFolder { 10 | 11 | private String captureFolder = "."; 12 | private static String SUB_FOLDER = "sikuli_captured"; 13 | private static CaptureFolder MYSELF = null; 14 | private boolean setted = false; 15 | 16 | public Boolean isCaptureMatchedImage = true; 17 | 18 | private CaptureFolder() {} 19 | 20 | public static CaptureFolder getInstance() { 21 | if (MYSELF == null) { 22 | MYSELF = new CaptureFolder(); 23 | } 24 | return MYSELF; 25 | } 26 | 27 | public void setCaptureFolder(String captureFolder) { 28 | this.captureFolder = captureFolder + "/" + CaptureFolder.SUB_FOLDER; 29 | setted = true; 30 | File file = new File(this.captureFolder); 31 | if (!file.exists()) { 32 | file.mkdirs(); 33 | } 34 | } 35 | 36 | public String getCaptureFolder() { 37 | return captureFolder; 38 | } 39 | 40 | public String getSubFolder() { 41 | if (setted) { 42 | return CaptureFolder.SUB_FOLDER; 43 | } else { 44 | return "."; 45 | } 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/python/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on 2015-08-20 3 | 4 | @author: wang_yang1980@hotmail.com 5 | """ 6 | 7 | from .sikuli import SikuliLibrary 8 | 9 | 10 | def main(): 11 | lib = SikuliLibrary(mode='CREATE') 12 | 13 | 14 | if __name__ == '__main__': 15 | main() 16 | 17 | -------------------------------------------------------------------------------- /src/python/sikuli.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on 2015-08-19 3 | 4 | @author: wang_yang1980@hotmail.com 5 | """ 6 | 7 | import socket 8 | import logging 9 | import sys 10 | import os 11 | import glob 12 | import time 13 | import threading 14 | import codecs 15 | 16 | try: 17 | from urllib import urlopen 18 | except ImportError: 19 | from urllib.request import urlopen 20 | try: 21 | from xmlrpclib import ProtocolError 22 | except ImportError: 23 | from xmlrpc.client import ProtocolError 24 | from robot.libraries.Process import Process 25 | from robot.libraries.Remote import Remote 26 | from robot.libraries.BuiltIn import BuiltIn 27 | from .version import VERSION 28 | try: 29 | from .keywords import KEYWORDS 30 | except ImportError: 31 | pass 32 | 33 | 34 | class SikuliLibrary(object): 35 | ROBOT_LIBRARY_SCOPE = 'GLOBAL' 36 | ROBOT_LIBRARY_VERSION = VERSION 37 | 38 | def __init__(self, port=0, timeout=3.0, mode='OLD'): 39 | """ 40 | @port: sikuli java process socket port 41 | @timeout: Timeout of waiting java process started 42 | @mode: if set as 'DOC', will stop java process automatically, 43 | if set as 'PYTHON', means library is running out of robot environment 44 | if set as 'CREATE', it is only for mvn package usage, will create keywords.py file 45 | if set as 'OLD'(default), sikuli java process will be started when library is inited 46 | if set as 'NEW', user should use 'start_sikuli_process' to start java process 47 | """ 48 | self.logger = self._init_logger() 49 | self.timeout = float(timeout) 50 | self.port = None 51 | self.remote = None 52 | self.mode = mode.upper().strip() 53 | if mode == 'OLD': 54 | self.start_sikuli_process(port) 55 | if mode.upper().strip() == 'DOC': 56 | self.start_sikuli_process() 57 | self._stop_thread(4) 58 | elif mode.upper().strip() == 'PYTHON': 59 | self.connect_sikuli_process(port) 60 | elif mode.upper().strip() == 'CREATE': 61 | self._create_keywords_file() 62 | elif mode.upper().strip() != 'NEW': 63 | self._check_robot_running() 64 | 65 | def start_sikuli_process(self, port=None): 66 | """ 67 | This keyword is used to start sikuli java process. 68 | If library is inited with mode "OLD", sikuli java process is started automatically. 69 | If library is inited with mode "NEW", this keyword should be used. 70 | 71 | :param port: port of sikuli java process, if value is None or 0, a random free port will be used 72 | :return: None 73 | """ 74 | if port is None or int(port) == 0: 75 | port = self._get_free_tcp_port() 76 | self.port = port 77 | start_retries = 0 78 | started = False 79 | while start_retries < 5: 80 | try: 81 | self._start_sikuli_java_process() 82 | except RuntimeError as err: 83 | print('error........%s' % err) 84 | if self.process: 85 | self.process.terminate_process() 86 | self.port = self._get_free_tcp_port() 87 | start_retries += 1 88 | continue 89 | started = True 90 | break 91 | if not started: 92 | raise RuntimeError('Start sikuli java process failed!') 93 | self.remote = self._connect_remote_library() 94 | 95 | def connect_sikuli_process(self, port): 96 | self.port = port 97 | self.remote = self._connect_remote_library() 98 | 99 | def _create_keywords_file(self): 100 | keywordDict = {} 101 | self.start_sikuli_process() 102 | try: 103 | keywordList = self.get_keyword_names() 104 | for keywordName in keywordList: 105 | keywordDict[keywordName] = {} 106 | keywordDict[keywordName]['arg'] = self.get_keyword_arguments(keywordName) 107 | keywordDict[keywordName]['doc'] = self.get_keyword_documentation(keywordName) 108 | with codecs.open(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'keywords.py'), 'w', 109 | encoding='utf-8') as f: 110 | f.write('# -*- coding: utf-8 -*-\n') 111 | # keywords = ','.join(['"%s": %s' % (k, keywordDict[k]) for k in keywordDict.keys()]) 112 | f.write('KEYWORDS = %s' % keywordDict ) 113 | finally: 114 | self._stop_thread(3) 115 | 116 | def _check_robot_running(self): 117 | try: 118 | BuiltIn().get_variable_value('${SUITE SOURCE}') 119 | except Exception as err: 120 | self.logger.warn('Robot may not running, stop java process: %s' % err) 121 | self._stop_thread(1) 122 | 123 | def _init_logger(self): 124 | robotLogLevels = {'TRACE': int(logging.DEBUG / 2), 125 | 'DEBUG': logging.DEBUG, 126 | 'INFO': logging.INFO, 127 | 'HTML': logging.INFO, 128 | 'WARN': logging.WARN} 129 | builtIn = BuiltIn() 130 | handler = logging.StreamHandler(sys.stdout) 131 | formatter = logging.Formatter('%(message)s') 132 | handler.setFormatter(formatter) 133 | logger = logging.getLogger('SikuliLibraryLogger') 134 | logger.addHandler(handler) 135 | level = logging.DEBUG 136 | try: 137 | logLevel = builtIn.get_variable_value('${LOG_LEVEL}') 138 | level = robotLogLevels[logLevel] 139 | except Exception: 140 | pass 141 | logger.setLevel(level) 142 | return logger 143 | 144 | def _get_free_tcp_port(self): 145 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 146 | sock.bind(('localhost', 0)) 147 | sock.listen(1) 148 | host, port = sock.getsockname() 149 | self.logger.debug('Free TCP port is: %d' % port) 150 | sock.close() 151 | return port 152 | 153 | def _start_sikuli_java_process(self): 154 | libFolder = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'lib') 155 | jarList = glob.glob(libFolder + os.sep + '*.jar') 156 | if len(jarList) != 1: 157 | raise Exception('Sikuli jar package should be exist in lib folder') 158 | sikuliJar = jarList[0] 159 | java = 'java' 160 | arguments = ['-jar', sikuliJar, str(self.port), self._get_output_folder()] 161 | self.process = Process() 162 | if os.getenv("DISABLE_SIKULI_LOG"): 163 | self.process.start_process(java, *arguments, shell=True) 164 | else: 165 | self.process.start_process(java, *arguments, shell=True, stdout=self._output_file(), 166 | stderr=self._err_file()) 167 | self.logger.info('Start sikuli java process on port %s' % str(self.port)) 168 | self._wait_process_started() 169 | self.logger.info('Sikuli java process is started') 170 | 171 | def _wait_process_started(self): 172 | url = "http://127.0.0.1:%s/" % str(self.port) 173 | currentTime = startedTime = time.time() 174 | started = False 175 | while (currentTime - startedTime) < self.timeout: 176 | try: 177 | urlopen(url).read() 178 | except Exception: 179 | currentTime = time.time() 180 | time.sleep(1.0) 181 | continue 182 | started = True 183 | break 184 | if not started: 185 | raise RuntimeError('Start sikuli java process failed!') 186 | 187 | def _output_file(self): 188 | outputDir = self._get_output_folder() 189 | outputFile = 'Sikuli_java_stdout_' + str(time.time()) + '.txt' 190 | return os.path.join(outputDir, outputFile) 191 | 192 | def _err_file(self): 193 | outputDir = self._get_output_folder() 194 | errFile = 'Sikuli_java_stderr_' + str(time.time()) + '.txt' 195 | return os.path.join(outputDir, errFile) 196 | 197 | def _get_output_folder(self): 198 | outputDir = os.path.abspath(os.curdir) 199 | try: 200 | outputDir = BuiltIn().get_variable_value('${OUTPUTDIR}') 201 | except Exception: 202 | pass 203 | return outputDir 204 | 205 | def _connect_remote_library(self): 206 | remoteUrl = 'http://127.0.0.1:%s/' % str(self.port) 207 | remote = Remote(remoteUrl) 208 | self._test_get_keyword_names(remote) 209 | return remote 210 | 211 | def _test_get_keyword_names(self, remote): 212 | currentTime = startedTime = time.time() 213 | started = False 214 | while (currentTime - startedTime) < self.timeout: 215 | try: 216 | remote.get_keyword_names() 217 | except Exception as err: 218 | self.logger.warn("Test get_keyword_names failed! %s" % err) 219 | currentTime = time.time() 220 | time.sleep(1.0) 221 | continue 222 | started = True 223 | break 224 | if not started: 225 | raise RuntimeError('Failed to get_keyword_names!') 226 | 227 | def get_keyword_names(self): 228 | if self.mode == 'CREATE': 229 | return self.remote.get_keyword_names() + ['start_sikuli_process'] 230 | return list(KEYWORDS.keys()) + ['start_sikuli_process'] 231 | # return self.remote.get_keyword_names() + ['start_sikuli_process'] 232 | 233 | def get_keyword_arguments(self, name): 234 | if name == 'start_sikuli_process': 235 | return ['port=None'] 236 | if self.mode == 'CREATE': 237 | return self.remote.get_keyword_arguments(name) 238 | return KEYWORDS[name]['arg'] 239 | 240 | def get_keyword_documentation(self, name): 241 | if name == 'start_sikuli_process': 242 | return self.start_sikuli_process.__doc__ 243 | elif name == '__intro__': 244 | return SikuliLibrary.__doc__ 245 | elif name == '__init__': 246 | return getattr(self, name).__doc__ 247 | if self.mode == 'CREATE': 248 | return self.remote.get_keyword_documentation(name) 249 | return KEYWORDS[name]['doc'] 250 | 251 | def run_keyword(self, name, arguments=[]): 252 | if name == 'start_sikuli_process': 253 | return self.start_sikuli_process(*arguments) 254 | return self.remote.run_keyword(name, arguments, None) 255 | 256 | def _stop_thread(self, timeout): 257 | def stop(): 258 | time.sleep(float(timeout)) 259 | self.run_keyword('stop_remote_server') 260 | 261 | thread = threading.Thread(target=stop, args=()) 262 | thread.start() 263 | -------------------------------------------------------------------------------- /src/python/version.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Created on 2015/12/10 3 | 4 | Author: by wang_yang1980@hotmail.com 5 | ''' 6 | VERSION = '2.0.5' --------------------------------------------------------------------------------