├── .gitignore ├── LICENSE ├── NOTICE ├── README.md ├── ahkunwrapped ├── __init__.py ├── autohotkey.py ├── lib │ └── AutoHotkey │ │ ├── AutoHotkey.exe │ │ └── NOTICE └── py.typed ├── example.ahk ├── example.py ├── example.spec ├── pyproject.toml ├── requirements.txt ├── setup.cfg ├── tests.ahk └── tests.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.egg-info/ 2 | .hypothesis/ 3 | .idea/ 4 | .pytest_cache/ 5 | __pycache__/ 6 | build/ 7 | dist/ 8 | venv/ 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright (C) 2019, 2020, 2021 Christopher S. Galpin 2 | 3 | This program is free software: you can redistribute it and/or modify 4 | it under the terms of the GNU Affero General Public License as published 5 | by the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. 7 | 8 | This program is distributed in the hope that it will be useful, 9 | but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | GNU Affero General Public License for more details. 12 | 13 | You should have received a copy of the GNU Affero General Public License 14 | along with this program. If not, see . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ahkUnwrapped 2 | I wanted to automate Windows with the coverage and simplicity of the _complete_ [AutoHotkey API](https://www.autohotkey.com/), yet code in Python, so I created `ahkUnwrapped`. 3 | 4 | AutoHotkey already abstracts the Windows API, so another layer to introduce complexity and slowdowns is undesirable. 5 | 6 | Instead, we bundle and bridge *AutoHotkey.exe*, sending your initial script [via stdin](https://www.autohotkey.com/docs/AHKL_ChangeLog.htm#v1.1.17.00) with minimal boilerplate to listen for [window messages](https://www.autohotkey.com/docs/commands/OnMessage.htm) from Python and respond [via stdout](https://docs.python.org/3.7/library/subprocess.html). 7 | 8 | ## Features 9 | * **All** of AutoHotkey! 10 | * Execute arbitrary AHK code or load scripts. 11 | * [Hypothesis](https://hypothesis.readthedocs.io/en/latest/) powered testing of convoluted unicode, et al. 12 | * Warnings for loss of precision (maximum 6 decimal places). 13 | * Errors for unsupported values (`NaN` `Inf` `\0`). 14 | * Unhandled AHK exceptions carry over to Python. 15 | * Won't explode when used from multiple threads. 16 | * Separate auto-execute sections to ease scripting. 17 | * Supports [PyInstaller](https://www.pyinstaller.org/) for _onefile/onedir_ installations. 18 | * Special care for: 19 | * Descriptive errors with accurate line numbers. 20 | * Persistent _Windows notification area_ settings. 21 | * Unexpected exit handling. 22 | * Minimal latency. 23 | 24 | ## Get started 25 | `> pip install ahkunwrapped` 26 | 27 | `call(proc, ...)` `f(func, ...)` `get(var)` `set(var, val)` 28 | 29 | ```python 30 | from ahkunwrapped import Script 31 | 32 | ahk = Script() 33 | # built-in functions are directly callable 34 | isNotepadActive = ahk.f('WinActive', 'ahk_class Notepad') 35 | # built-in variables (and user globals) can be set directly 36 | ahk.set('Clipboard', "Copied text!") 37 | print(isNotepadActive) 38 | ``` 39 | --- 40 | ```python 41 | from ahkunwrapped import Script 42 | 43 | ahk = Script(''' 44 | LuckyMinimize(winTitle) { 45 | global myVar 46 | myVar := 7 47 | 48 | WinMinimize, % winTitle 49 | Clipboard := "You minimized: " winTitle 50 | } 51 | ''') 52 | 53 | ahk.call('LuckyMinimize', 'ahk_class Notepad') 54 | print("Lucky number", ahk.get('myVar')) 55 | ``` 56 | --- 57 | ```python 58 | from pathlib import Path 59 | from ahkunwrapped import Script 60 | 61 | ahk = Script.from_file(Path('my_msg.ahk')) 62 | ahk.call('MyMsg', "Wooo!") 63 | ``` 64 | 65 | _my_msg.ahk:_ 66 | ```autohotkey 67 | ; auto-execute section when ran standalone 68 | #SingleInstance force 69 | #Warn 70 | AutoExec() ; we can call this if we want 71 | MyMsg("test our function") 72 | return 73 | 74 | ; auto-execute section when ran from Python 75 | AutoExec() { 76 | SetBatchLines, 100ms ; slow our code to reduce CPU 77 | } 78 | 79 | MyMsg(text) { 80 | MsgBox, % text 81 | } 82 | ``` 83 | 84 | Settings from [AutoExec()](https://www.autohotkey.com/docs/Scripts.htm#auto) will [still apply](https://www.autohotkey.com/docs/commands/OnMessage.htm#Remarks) even though we execute directly from the message listening thread for speed. 85 | (AutoHotkey's [#Warn](https://www.autohotkey.com/docs/commands/_Warn.htm#Remarks) is special and will apply to both standalone and from-Python execution, unless you add/remove it dynamically.) 86 | 87 | ## Usage 88 | `call(proc, ...)` is for performance, to avoid receiving a large unneeded result. 89 | 90 | `get(var)` `set(var, val)` are shorthand for accessing global variables and [built-ins](https://www.autohotkey.com/docs/Variables.htm#BuiltIn) like `A_TimeIdle`. 91 | 92 | `f(func, ...)` `get(var)` will infer `float` and `int` (base-16 beginning with `0x`) like AutoHotkey. 93 | 94 | `f_raw(func, ...)` `get_raw(var)` will return the raw string as-stored. 95 | 96 | `call_main(proc, ...)` `f_main(func, ...)` `f_raw_main(func, ...)` will execute on AutoHotkey's main thread instead of the [OnMessage()](https://www.autohotkey.com/docs/commands/OnMessage.htm#Remarks) listener. 97 | This avoids `AhkCantCallOutInInputSyncCallError`, e.g. from some uses of [ComObjCreate()](https://www.autohotkey.com/docs/commands/ComObjCreate.htm). 98 | This is slower (except with very large data), but still fast and unlikely to bottleneck. 99 | 100 | ## Event loop with hotkeys 101 | 102 | ```python 103 | import sys 104 | import time 105 | from datetime import datetime 106 | from enum import Enum 107 | from pathlib import Path 108 | 109 | from ahkunwrapped import Script, AhkExitException 110 | 111 | choice = None 112 | HOTKEY_SEND_CHOICE = 'F2' 113 | 114 | 115 | class Event(Enum): 116 | QUIT, SEND_CHOICE, CLEAR_CHOICE, CHOOSE_MONTH, CHOOSE_DAY = range(5) 117 | 118 | 119 | # format_dict= so we can use {{VARIABLE}} within example.ahk 120 | ahk = Script.from_file(Path('example.ahk'), format_dict=globals()) 121 | 122 | 123 | def main() -> None: 124 | print("Scroll your mousewheel in Notepad.") 125 | 126 | ts = 0 127 | while True: 128 | try: 129 | # ahk.poll() # detect exit, but all ahk functions include this 130 | 131 | s_elapsed = time.time() - ts 132 | if s_elapsed >= 60: 133 | ts = time.time() 134 | print_minute() 135 | 136 | event = ahk.get('event') # contains ahk.poll() 137 | if event: 138 | ahk.set('event', '') 139 | on_event(event) 140 | except AhkExitException as ex: 141 | sys.exit(ex.args[0]) 142 | time.sleep(0.01) 143 | 144 | 145 | def print_minute() -> None: 146 | print(f"It is now {datetime.now().time()}") 147 | 148 | 149 | def on_event(event: str) -> None: 150 | global choice 151 | 152 | def get_choice() -> str: 153 | return choice or datetime.now().strftime('%#I:%M %p') 154 | 155 | if event == str(Event.QUIT): 156 | ahk.exit() 157 | if event == str(Event.CLEAR_CHOICE): 158 | choice = None 159 | if event == str(Event.SEND_CHOICE): 160 | ahk.call('Send', f'{get_choice()} ') 161 | if event == str(Event.CHOOSE_MONTH): 162 | choice = datetime.now().strftime('%b') 163 | ahk.call('ToolTip', f"Month is {get_choice()}, {HOTKEY_SEND_CHOICE} to insert.") 164 | if event == str(Event.CHOOSE_DAY): 165 | choice = datetime.now().strftime('%#d') 166 | ahk.call('ToolTip', f"Day is {get_choice()}, {HOTKEY_SEND_CHOICE} to insert.") 167 | 168 | 169 | if __name__ == '__main__': 170 | main() 171 | ``` 172 | 173 | _example.ahk:_ 174 | ```autohotkey 175 | #SingleInstance, force 176 | #Warn 177 | ToolTip("Standalone script test!") 178 | return 179 | 180 | AutoExec() { 181 | global event 182 | event := "" 183 | SendMode, input 184 | } 185 | 186 | Send(text) { 187 | Send, % text 188 | } 189 | 190 | ToolTip(text, s := 2) { 191 | ToolTip, % text 192 | ; negative for non-repeating 193 | SetTimer, RemoveToolTip, % s * -1000 194 | } 195 | 196 | RemoveToolTip: 197 | ToolTip, 198 | event = {{Event.CLEAR_CHOICE}} 199 | return 200 | 201 | MouseIsOver(winTitle) { 202 | MouseGetPos,,, winId 203 | result := WinExist(winTitle " ahk_id " winId) 204 | return result 205 | } 206 | 207 | #If WinActive("ahk_class Notepad") 208 | {{HOTKEY_SEND_CHOICE}}::event = {{Event.SEND_CHOICE}} 209 | ^Q::event = {{Event.QUIT}} 210 | #If MouseIsOver("ahk_class Notepad") 211 | WheelUp::event = {{Event.CHOOSE_MONTH}} 212 | WheelDown::event = {{Event.CHOOSE_DAY}} 213 | ``` 214 | 215 | ## PyInstaller (single _.exe_ or folder) 216 | _example.[spec](https://pyinstaller.readthedocs.io/en/stable/spec-files.html):_ 217 | 218 | ```python 219 | # -*- mode: python -*- 220 | from pathlib import Path 221 | 222 | import ahkunwrapped 223 | 224 | a = Analysis( 225 | ['example.py'], 226 | datas=[ 227 | (Path(ahkunwrapped.__file__).parent / 'lib', 'lib'), # required 228 | ('example.ahk', '.'), 229 | ] 230 | ) 231 | pyz = PYZ(a.pure) 232 | 233 | # for onefile 234 | exe = EXE(pyz, a.scripts, a.binaries, a.datas, name='my-example', upx=True, console=False) 235 | 236 | # for onedir 237 | # exe = EXE(pyz, a.scripts, exclude_binaries=True, name='my-example', upx=True, console=False) 238 | # dir = COLLECT(exe, a.binaries, a.datas, name='my-example-folder') 239 | ``` 240 | 241 | ### Folder considerations 242 | 243 | _example.py:_ 244 | ```python 245 | from pathlib import Path 246 | 247 | from ahkunwrapped import Script 248 | 249 | # tray icon visibility settings rely on consistent exe paths 250 | LOCALAPP_DIR = Path(os.getenv('LOCALAPPDATA') / 'pyinstaller-example') 251 | 252 | # working directory is different between onefile and onedir modes 253 | # https://pyinstaller.readthedocs.io/en/stable/runtime-information.html 254 | CUR_DIR = Path(getattr(sys, '_MEIPASS', Path(__file__).parent)) 255 | 256 | ahk = Script.from_file(CUR_DIR / 'example.ahk', format_dict=globals(), execute_from=LOCALAPP_DIR) 257 | 258 | # ... 259 | ``` 260 | 261 | _example.ahk:_ 262 | ```autohotkey 263 | AutoExec() { 264 | Menu, Tray, Icon, {{CUR_DIR}}\black.ico 265 | Menu, Tray, Icon ; unhide 266 | } 267 | 268 | ; ... 269 | ``` -------------------------------------------------------------------------------- /ahkunwrapped/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '2.2.1' 2 | from .autohotkey import * 3 | -------------------------------------------------------------------------------- /ahkunwrapped/autohotkey.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2019-2022 Christopher S. Galpin. Licensed under AGPL-3.0-or-later. See /NOTICE. 2 | import array 3 | import atexit 4 | import math 5 | import os 6 | import shutil 7 | import string 8 | import struct 9 | import subprocess 10 | import sys 11 | import threading 12 | import time 13 | # import traceback 14 | from contextlib import suppress, contextmanager 15 | from itertools import chain 16 | from pathlib import Path 17 | from subprocess import TimeoutExpired 18 | from typing import ClassVar, Mapping, Optional, Sequence, Tuple, Union, ContextManager 19 | from warnings import warn 20 | 21 | import pywintypes 22 | import win32api 23 | import win32con 24 | import win32job 25 | # noinspection PyUnresolvedReferences 26 | from win32api import OutputDebugString 27 | 28 | IN_PYINSTALLER = getattr(sys, 'frozen', False) 29 | # noinspection PyProtectedMember,PyUnresolvedReferences 30 | PACKAGE_PATH = Path(sys._MEIPASS) if IN_PYINSTALLER else Path(__file__).parent 31 | SINGLE_JOB_ASSIGNMENTS = sys.getwindowsversion().major < 8 # https://stackoverflow.com/q/13449531/ 32 | if SINGLE_JOB_ASSIGNMENTS: 33 | import inspect 34 | 35 | 36 | class AhkException(Exception): pass # noqa: E701 37 | class AhkExitException(AhkException): pass # noqa: E701 38 | class AhkError(AhkException): pass # noqa: E701 39 | class AhkFuncNotFoundError(AhkError): pass # noqa: E701 40 | class AhkUnsupportedValueError(AhkError): pass # noqa: E701 41 | class AhkCantCallOutInInputSyncCallError(AhkError): pass # noqa: E701 42 | class AhkWarning(UserWarning): pass # noqa: E701 43 | 44 | 45 | class AhkLossOfPrecisionWarning(AhkWarning): 46 | def __init__(self, val: float, val_str: str): 47 | super().__init__(f'loss of precision from {val} to {val_str}') 48 | 49 | 50 | # Python 3.7 would use @dataclass 51 | class AhkUserException(AhkException): 52 | def __init__(self, from_exception_obj: str, message: str, what: str, extra: str, file: str, line: str): 53 | self.from_exception_obj: bool = from_exception_obj == "1" 54 | self.message: str = message 55 | self.what: str = what 56 | self.extra: str = extra 57 | self.file: str = file 58 | self.line: str = line 59 | 60 | def __str__(self) -> str: 61 | # Python 3.8 would use return f"{message=}, {what=}, {extra=}, {file=}, {line=}" 62 | return f"(message={repr(self.message)}, what={repr(self.what)}, extra={repr(self.extra)}, file={repr(self.file)}, line={repr(self.line)})" 63 | 64 | def __repr__(self) -> str: 65 | return f"{self.__class__.__name__}{self}" 66 | 67 | 68 | class AhkCaughtNonExceptionWarning(AhkWarning): 69 | def __init__(self, exception: AhkUserException): 70 | message = f"""got "throw X"; recommend "throw Exception(X)" to preserve line info. 71 | \tAlternatively, catch within script https://www.autohotkey.com/docs/commands/Throw.htm#Exception . 72 | \tException message: '{exception.message}'""" 73 | if not exception.message: 74 | message += "\n\tMay have been an AutoHotkey object e.g. {abc: 123} intended for use within 'catch'." 75 | super().__init__(message) 76 | 77 | 78 | class WinXPJobObjectWarning(UserWarning): # for Vista and Windows 7 79 | def __init__(self, message: str): 80 | message += f""" 81 | \tRecommend polling within AutoHotkey: https://github.com/CodeOptimist/ahkunwrapped/issues/1 82 | \tAlternatives: https://stackoverflow.com/q/13471611 83 | \tThis isn't an issue on Windows 8+ due to nestable jobs.""" 84 | super().__init__(message) 85 | 86 | class ExistingWinXPJobObjectWarning(WinXPJobObjectWarning): pass 87 | class SingleWinXPJobObjectWarning(WinXPJobObjectWarning): pass 88 | 89 | 90 | def comment_debug() -> str: 91 | return ";" if "pytest" not in sys.modules else "" 92 | 93 | 94 | Primitive = Union[bool, float, int, str] 95 | 96 | 97 | class Script: 98 | # Python 3.8 would use Final instead of ClassVar https://www.python.org/dev/peps/pep-0591/#id14 99 | MSG_GET: ClassVar[int] = 0x8001 100 | MSG_SET: ClassVar[int] = 0x8002 101 | MSG_F: ClassVar[int] = 0x8003 102 | MSG_F_MAIN: ClassVar[int] = 0x8004 103 | MSG_MORE: ClassVar[int] = 0x8005 104 | MSG_EXIT: ClassVar[int] = 0x8006 105 | 106 | SEPARATOR: ClassVar[str] = '\3' 107 | EOM_MORE: ClassVar[str] = SEPARATOR * 2 108 | EOM_END: ClassVar[str] = SEPARATOR * 3 109 | 110 | BUFFER_SIZE: ClassVar[int] = 4096 111 | BUFFER_W_MORE_SIZE: ClassVar[int] = BUFFER_SIZE - len(EOM_MORE) * 2 - len('\n') - 1 # :SingleByteNewline 112 | assert BUFFER_W_MORE_SIZE % 2 == 0 # utf-16 is 2 bytes 113 | BUFFER_W_END_SIZE: ClassVar[int] = BUFFER_SIZE - len(EOM_END) * 2 - len('\n') - 1 114 | assert BUFFER_W_END_SIZE % 2 == 0 115 | 116 | python_pid: ClassVar = os.getpid() 117 | python_job: ClassVar = None 118 | 119 | CORE: ClassVar[str] = ''' 120 | _pyUserBatchLines := A_BatchLines 121 | SetBatchLines, -1 122 | Process, Exist, ''' + str(python_pid) + ''' 123 | if (ErrorLevel = 0) 124 | ExitApp ; https://stackoverflow.com/q/73506891/#comment129808240_73506891 :AvoidJobRace 125 | #NoEnv 126 | #NoTrayIcon 127 | #Persistent 128 | SetWorkingDir, ''' + os.getcwd() + ''' 129 | _PY_SEPARATOR := ''' + f'Chr({ord(SEPARATOR)})' + ''' 130 | _pyStdOut := FileOpen("*", "w", "utf-16-raw") 131 | _pyStdErr := FileOpen("**", "w", "utf-16-raw") 132 | 133 | _Py_Response(ByRef pipe, ByRef text, ByRef offset, ByRef onMain) { 134 | textSize := Max(StrLen(text) * 2 + StrLen(Chr(0)) * 2 - offset, 0) 135 | isEnd := onMain or textSize <= ''' + str(BUFFER_W_END_SIZE) + ''' 136 | ;MsgBox % "offset: " offset " textSize: " textSize " isEnd: " isEnd 137 | 138 | pipe.RawWrite(&text + offset, isEnd ? textSize : ''' + str(BUFFER_W_MORE_SIZE) + ''') 139 | if (isEnd) 140 | pipe.Write(''' + ' '.join(f'Chr({ord(c)})' for c in EOM_END) + ''') 141 | else 142 | pipe.Write(''' + ' '.join(f'Chr({ord(c)})' for c in EOM_MORE) + ''') 143 | newLine := "`n" 144 | pipe.RawWrite(newLine, 1) ; :SingleByteNewline 145 | pipe.Read(0) 146 | } 147 | 148 | _Py_MsgMore(ByRef wParam, ByRef lParam, ByRef msg, ByRef hwnd) { 149 | global _pyStdOut, _pyOutText, _pyOutOffset, _pyStdErr, _pyErrText, _pyErrOffset 150 | SetBatchLines, -1 151 | ''' + comment_debug() + '''DebugMsg(wParam, msg) 152 | 153 | numRead := ''' + str(BUFFER_W_MORE_SIZE) + ''' 154 | _Py_Response(_pyStdOut, _pyOutText, _pyOutOffset += numRead, False) 155 | _Py_Response(_pyStdErr, _pyErrText, _pyErrOffset += numRead, False) 156 | return 1 157 | } 158 | 159 | ; we can't peek() stdout/stderr, so always write to both or we will over-read and hang waiting 160 | _Py_StdOut(ByRef outText, ByRef onMain := False) { 161 | global _pyStdOut, _pyOutText, _pyOutOffset, _pyStdErr, _pyErrText, _pyErrOffset 162 | _Py_Response(_pyStdOut, _pyOutText := outText, _pyOutOffset := 0, onMain) 163 | _Py_Response(_pyStdErr, _pyErrText := "", _pyErrOffset := 0, onMain) 164 | return 1 165 | } 166 | _Py_StdErr(ByRef name, ByRef errText, onMain := False) { 167 | global _pyStdOut, _pyOutText, _pyOutOffset, _pyStdErr, _pyErrText, _pyErrOffset, _PY_SEPARATOR 168 | _Py_Response(_pyStdOut, _pyOutText := "", _pyOutOffset := 0, onMain) 169 | _Py_Response(_pyStdErr, _pyErrText := name _PY_SEPARATOR errText, _pyErrOffset := 0, onMain) 170 | return 1 171 | } 172 | 173 | _Py_MsgCopyData(ByRef wParam, ByRef lParam, ByRef msg, ByRef hwnd) { 174 | global _pyThreadMsgData, _PY_SEPARATOR 175 | SetBatchLines, -1 176 | ''' + comment_debug() + '''DebugMsg(wParam, msg) 177 | 178 | ;dataTypeId := NumGet(lParam + 0*A_PtrSize) ; unneeded atm 179 | dataSize := NumGet(lParam + 1*A_PtrSize) 180 | strAddr := NumGet(lParam + 2*A_PtrSize) 181 | ; limitation of StrGet(): data is truncated after \\0 182 | data := StrGet(strAddr, dataSize, "utf-8") 183 | ; OutputDebug, Received: '%data%' 184 | 185 | ; Since messages can arrive from multiple threads—e.g. clicking 'Reload' within OBS Studio 'Scripts' window, 186 | ; while a timer is also running within said script—we need to keep their input data separate. 187 | _pyThreadMsgData[wParam] := [] 188 | ; limitation of Parse and StrSplit(): separator must be a single character 189 | Loop, Parse, data, % _PY_SEPARATOR 190 | { 191 | ; see Python function _to_ahk_str() 192 | type := RTrim(SubStr(A_LoopField, 1, 5)) 193 | val := SubStr(A_LoopField, 7) 194 | ; others are automatic 195 | if (type = "bool") 196 | val := val == "True" ? 1 : 0 ; same as True/False 197 | _pyThreadMsgData[wParam].Push(val) 198 | } 199 | return 1 200 | } 201 | 202 | ; call on main thread, much slower but may be necessary for DllCall() to avoid: 203 | ; Error 0x8001010d An outgoing call cannot be made since the application is dispatching an input-synchronous call. 204 | _Py_MsgFMain(ByRef wParam, ByRef lParam, ByRef msg, ByRef hwnd) { 205 | global _pyMsgFMainData 206 | SetBatchLines, -1 207 | ''' + comment_debug() + '''DebugMsg(wParam, msg) 208 | 209 | _pyMsgFMainData.Push(hwnd) 210 | _pyMsgFMainData.Push(msg) 211 | _pyMsgFMainData.Push(lParam) 212 | _pyMsgFMainData.Push(wParam) 213 | ''' + comment_debug() + '''OutputDebug, SENDING TO MAIN THREAD 214 | ; continue on main thread at below label 215 | ; ordinarily a new message can interrupt this, but none will be sent because of our lock 216 | SetTimer, _Py_MsgFMain, -0 ; negative for one-time, and 0 is indeed quicker than 1 217 | return 1 218 | } 219 | 220 | _Py_MsgF(ByRef wParam, ByRef lParam, ByRef msg, ByRef hwnd, ByRef onMain := False) { 221 | global _pyThreadMsgData, _pyUserBatchLines, _PY_SEPARATOR 222 | SetBatchLines, -1 223 | ''' + comment_debug() + '''if (not onMain) 224 | ''' + comment_debug() + ''' DebugMsg(wParam, msg) 225 | 226 | func := _pyThreadMsgData[wParam].RemoveAt(1) 227 | if (not IsFunc(func)) { 228 | _pyThreadMsgData.Delete(wParam) 229 | return _Py_StdErr("''' + AhkFuncNotFoundError.__name__ + '''", func, onMain) 230 | } 231 | needResult := _pyThreadMsgData[wParam].RemoveAt(1) 232 | 233 | SetBatchLines, % _pyUserBatchLines 234 | try result := %func%(_pyThreadMsgData[wParam]*) 235 | catch e { 236 | SetBatchLines, -1 237 | _pyThreadMsgData.Delete(wParam) 238 | 239 | ; Exception() just results in a normal object; no easy way to distinguish 240 | ; https://www.autohotkey.com/docs/commands/Throw.htm 241 | ; https://web.archive.org/web/20201202074148/https://www.autohotkey.com/boards/viewtopic.php?t=44081 242 | isExceptionObj := IsObject(e) and (e.Count() == 4 or e.Count() == 5) and e.HasKey("Message") and e.HasKey("What") and e.HasKey("File") and e.HasKey("Line") 243 | if (isExceptionObj and e.Count() == 5 and !e.HasKey("Extra")) 244 | isExceptionObj := False 245 | 246 | if (!isExceptionObj) 247 | e := {Message: e} 248 | 249 | return _Py_StdErr("''' + AhkUserException.__name__ + '''" 250 | , isExceptionObj _PY_SEPARATOR e.Message _PY_SEPARATOR e.What _PY_SEPARATOR e.Extra _PY_SEPARATOR e.File _PY_SEPARATOR e.Line 251 | , onMain) 252 | } 253 | 254 | SetBatchLines, -1 255 | _pyThreadMsgData.Delete(wParam) 256 | return _Py_StdOut(needResult ? result : "", onMain) 257 | } 258 | 259 | _Py_MsgGet(ByRef wParam, ByRef lParam, ByRef msg, ByRef hwnd) { 260 | local name, val 261 | SetBatchLines, -1 262 | ''' + comment_debug() + '''DebugMsg(wParam, msg) 263 | name := _pyThreadMsgData[wParam].RemoveAt(1) 264 | val := %name% 265 | _pyThreadMsgData.Delete(wParam) 266 | return _Py_StdOut(val) 267 | } 268 | 269 | _Py_MsgSet(ByRef wParam, ByRef lParam, ByRef msg, ByRef hwnd) { 270 | local name 271 | SetBatchLines, -1 272 | ''' + comment_debug() + '''DebugMsg(wParam, msg) 273 | name := _pyThreadMsgData[wParam].RemoveAt(1) 274 | %name% := _pyThreadMsgData[wParam].RemoveAt(1) 275 | _pyThreadMsgData.Delete(wParam) 276 | return 1 277 | } 278 | 279 | _Py_MsgExit() { 280 | ExitApp 281 | return 1 ; required even after ExitApp 282 | } 283 | 284 | DebugMsg(wParam, msg) { 285 | OutputDebug, % Format("msg {:#06x}\t\tthread {:#05} -> {:#05}\t\tprocess {:#05} -> {:#05}" 286 | , msg, wParam, DllCall("GetCurrentThreadId"), ''' + str(python_pid) + ''', DllCall("GetCurrentProcessId")) 287 | } 288 | 289 | _pyThreadMsgData := {} 290 | _pyMsgFMainData := [] 291 | 292 | ; these all must return non-zero to signal completion 293 | OnMessage(''' + str(win32con.WM_COPYDATA) + ''', Func("_Py_MsgCopyData")) 294 | OnMessage(''' + str(MSG_GET) + ''', Func("_Py_MsgGet")) 295 | OnMessage(''' + str(MSG_SET) + ''', Func("_Py_MsgSet")) 296 | OnMessage(''' + str(MSG_F) + ''', Func("_Py_MsgF")) 297 | OnMessage(''' + str(MSG_F_MAIN) + ''', Func("_Py_MsgFMain")) 298 | OnMessage(''' + str(MSG_MORE) + ''', Func("_Py_MsgMore")) 299 | OnMessage(''' + str(MSG_EXIT) + ''', Func("_Py_MsgExit")) 300 | 301 | _Py_StdOut(A_ScriptHwnd) 302 | 303 | SetBatchLines, % _pyUserBatchLines 304 | Func("AutoExec").Call() ; call if exists 305 | _pyUserBatchLines := A_BatchLines 306 | 307 | _Py_StdOut("Initialized") 308 | return 309 | 310 | ; from _Py_MsgFMain() 311 | _Py_MsgFMain: 312 | SetBatchLines, -1 313 | ''' + comment_debug() + '''OutputDebug, RECEIVED IN MAIN THREAD 314 | _Py_MsgF(_pyMsgFMainData.Pop(), _pyMsgFMainData.Pop(), _pyMsgFMainData.Pop(), _pyMsgFMainData.Pop(), True) 315 | return 316 | 317 | ; an unused label so #Warn won't complain that the user script's auto-execute section is unreachable 318 | ; it is intentionally unreachable (we use AutoExec() instead) so scripts can run exclusive standalone code 319 | _Py_SuppressUnreachableWarning: 320 | AutoTrim, % A_AutoTrim ; does nothing and never called, but makes label happy 321 | ''' 322 | 323 | def __init__(self, script: str = "", ahk_path: Path = None, execute_from: Path = None, kill_process_tree_on_exit: bool = False) -> None: 324 | """Launch an AutoHotkey process. 325 | 326 | :param script: Actual AutoHotkey script. Optional if you only need built-in functions and variables. 327 | :param ahk_path: Path to an alternative AutoHotkey executable than the one included (`ahk.get('A_AhkVersion')`). 328 | :param execute_from: Path AutoHotkey executable will be hard-linked/copied to, for the benefit of individual show/hide status in system tray. 329 | :param kill_process_tree_on_exit: Descendants of AutoHotkey process will inherit its win32 job object and terminate with it. 330 | `Script.exit()` (an intentional exit) can override this. 331 | *Caution*: Universal Windows Platform (UWP) apps (e.g. Windows 10's notepad.exe and calc.exe) discard our job object; 332 | suggest using AutoHotkey's `OnExit()` in those cases: https://github.com/CodeOptimist/ahkunwrapped/issues/1 333 | """ 334 | self.file = None 335 | self.script = script 336 | self.kill_process_tree_on_exit = kill_process_tree_on_exit 337 | 338 | if ahk_path is None: 339 | ahk_path = PACKAGE_PATH / r'lib\AutoHotkey\AutoHotkey.exe' 340 | if IN_PYINSTALLER and not ahk_path.is_file(): 341 | raise FileNotFoundError(f"""Couldn't find AutoHotkey at '{ahk_path}'. 342 | \tEdit your `.spec` file (may have been auto-generated) to contain: 343 | \t from pathlib import Path 344 | \t import ahkunwrapped 345 | \t 346 | \t a = Analysis(... 347 | \t datas=[ 348 | \t (Path(ahkunwrapped.__file__).parent / 'lib', 'lib'), 349 | \t ('your_script.ahk', '.'), # if using `Script.from_file()` 350 | \t ], 351 | \tAnd pass it to PyInstaller (or it will be overwritten), e.g. `pyinstaller example.spec`.""") 352 | 353 | if not ahk_path.is_file(): 354 | raise FileNotFoundError(f"Couldn't find file '{ahk_path}' for `ahk_path`.") 355 | 356 | # Windows notification area relies on consistent exe path 357 | if execute_from is not None: 358 | execute_from_dir = Path(execute_from) 359 | if not execute_from_dir.is_dir(): 360 | raise NotADirectoryError(f"Couldn't find folder '{execute_from_dir}' for `execute_from`.") 361 | ahk_into_folder = execute_from_dir / ahk_path.name 362 | 363 | try: 364 | if os.path.getmtime(ahk_into_folder) != os.path.getmtime(ahk_path): 365 | os.remove(ahk_into_folder) 366 | except FileNotFoundError: 367 | pass 368 | 369 | try: 370 | os.link(ahk_path, ahk_into_folder) 371 | except FileExistsError: 372 | pass 373 | except OSError as ex: 374 | # 5: "Access is denied" 375 | # 17: "The system cannot move the file to a different disk drive" 376 | if ex.winerror in (5, 17): 377 | shutil.copyfile(ahk_path, ahk_into_folder) 378 | ahk_path = ahk_into_folder 379 | 380 | # user script exceptions are already caught and sent to stderr, so /ErrorStdOut would only affect debugging CORE 381 | # self.cmd = [str(ahk_path), "/ErrorStdOut=utf-16-raw", "/CP65001", "*"] 382 | self.cmd = [str(ahk_path), "/CP65001", "*"] 383 | 384 | self.popen = subprocess.Popen(self.cmd, bufsize=Script.BUFFER_SIZE, executable=str(ahk_path), 385 | # must pipe all three for PyInstaller onefile exe 386 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 387 | 388 | # NOTE: PROCESS EXPLORER WILL SHOW ONE OR THE OTHER JOB BUT NOT BOTH @Chris 2022-10 389 | # https://learn.microsoft.com/en-gb/windows/win32/api/winbase/nf-winbase-createjobobjecta 390 | # job containing all AutoHotkey processes to terminate with Python 391 | Script.python_job = win32job.CreateJobObject(None, f"ahkUnwrapped:python.exe:{Script.python_pid}") # will find existing or create 392 | extended_info = win32job.QueryInformationJobObject(Script.python_job, win32job.JobObjectExtendedLimitInformation) 393 | # silent breakaway so child processes won't inherit job 394 | extended_info['BasicLimitInformation']['LimitFlags'] = win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | win32job.JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK 395 | win32job.SetInformationJobObject(Script.python_job, win32job.JobObjectExtendedLimitInformation, extended_info) 396 | 397 | # Both job objects "execute" when their last handle closes (Python exits), but here KILL_ON_JOB_CLOSE (for descendants) is optional. 398 | # Separately, we can force terminate at any time. :TerminateJob 399 | self.tree_job = win32job.CreateJobObject(None, f"ahkUnwrapped:AutoHotkey.exe:{self.popen.pid}") # new job for descendants (and ourself) 400 | extended_info = win32job.QueryInformationJobObject(self.tree_job, win32job.JobObjectExtendedLimitInformation) 401 | # no breakaway; this job object will be inherited 402 | if self.kill_process_tree_on_exit: 403 | extended_info['BasicLimitInformation']['LimitFlags'] |= win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE 404 | win32job.SetInformationJobObject(self.tree_job, win32job.JobObjectExtendedLimitInformation, extended_info) 405 | 406 | @contextmanager 407 | def get_handle(handle: object) -> ContextManager[object]: 408 | try: yield handle 409 | finally: win32api.CloseHandle(handle) 410 | 411 | with get_handle(win32api.OpenProcess(win32con.PROCESS_TERMINATE | win32con.PROCESS_SET_QUOTA, False, self.popen.pid)) as ahk_handle: # both flags required 412 | if SINGLE_JOB_ASSIGNMENTS: 413 | try: 414 | has_tree_job = win32job.AssignProcessToJobObject(self.tree_job, ahk_handle) # the better choice when we can only have 1 415 | win32job.AssignProcessToJobObject(Script.python_job, ahk_handle) # this will fail 416 | except pywintypes.error as ex: 417 | if ex.winerror != 5: 418 | raise 419 | stacklevel = 3 if inspect.currentframe().f_back.f_code.co_name == 'from_file' else 2 # :FromFile 420 | if 'has_tree_job' in locals(): 421 | message = f"""Could only assign AutoHotkey (PID {self.popen.pid}) to a single job object: its process tree. 422 | \tAs such, AutoHotkey will only automatically terminate when Python exits unexpectedly if `kill_process_tree_on_exit` is set `True`.""" 423 | warn(SingleWinXPJobObjectWarning(message), stacklevel=stacklevel) 424 | else: 425 | message = f"""Couldn't assign AutoHotkey (PID {self.popen.pid}) to a job object because one was already inherited (breakaway is unlikely to succeed). 426 | \tAs such, `Script.exit(kill_descendants=True)` and `Script(kill_process_tree_on_exit=True)` have no effect, nor will AutoHotkey terminate if Python exits unexpectedly.""" 427 | warn(ExistingWinXPJobObjectWarning(message), stacklevel=stacklevel) 428 | else: 429 | win32job.AssignProcessToJobObject(Script.python_job, ahk_handle) # this one needs to be first to avoid 'Access denied', also see :AvoidJobRace 430 | win32job.AssignProcessToJobObject(self.tree_job, ahk_handle) # no race here, AutoHotkey won't `Run` a child process before "Initialized" 431 | 432 | self.popen.stdin.write(Script.CORE.encode('utf-8')) 433 | self.popen.stdin.write(self.script.encode('utf-8')) 434 | self.popen.stdin.close() 435 | 436 | self.lock = None 437 | self.hwnd = int(self._read_response(), 16) 438 | assert self._read_response() == "Initialized" 439 | self.lock = threading.Lock() 440 | 441 | # last to make sure things went okay since it runs on its own thread 442 | atexit.register(self._on_python_exit) # if we exit, exit AutoHotkey 443 | 444 | @staticmethod 445 | def from_file(path: Path, format_dict: Mapping[str, str] = None, ahk_path: Path = None, execute_from: Path = None, kill_process_tree_on_exit: bool = None) -> 'Script': # :FromFile 446 | """Launch an AutoHotkey process from a script file. 447 | 448 | :param path: Path to file. 449 | :param format_dict: `.format()` dict to use {{variable}} within script. `globals()` is a common choice. 450 | :param ahk_path: See `Script()`. 451 | :param execute_from: See `Script()`. 452 | :param kill_process_tree_on_exit: See `Script()`. 453 | """ 454 | with path.open(encoding='utf-8') as f: 455 | script = f.read() 456 | if format_dict is not None: 457 | script = script.replace(r'{', r'{{').replace(r'}', r'}}').replace(r'{{{', r'').replace(r'}}}', r'') 458 | script = script.format(**format_dict) 459 | script = Script(script, ahk_path, execute_from, kill_process_tree_on_exit) 460 | script.file = path # for exceptions 461 | return script 462 | 463 | def _read_pipes(self) -> Tuple[str, str]: 464 | more = bytes(Script.EOM_MORE, 'utf-16-le') + b'\n' # :SingleByteNewline 465 | end = bytes(Script.EOM_END, 'utf-16-le') + b'\n' 466 | 467 | err, out = bytearray(), bytearray() 468 | while True: 469 | def has_all(bytearray_: bytearray) -> bool: 470 | self.poll() 471 | return bytearray_.endswith(end) or bytearray_.endswith(more) 472 | 473 | # we're careful not to over-read into the next response, 474 | # but we can at least go line by line since we end with \n 475 | err_buffer, out_buffer = bytearray(), bytearray() 476 | while not has_all(out_buffer): 477 | out_buffer += self.popen.stdout.readline() # :SingleByteNewline 478 | while not has_all(err_buffer): 479 | err_buffer += self.popen.stderr.readline() 480 | 481 | is_end = out_buffer.endswith(end) and err_buffer.endswith(end) 482 | 483 | def strip_eom(buffer) -> str: 484 | head, sep, tail = buffer.rpartition(end) 485 | return head if sep else buffer.rpartition(more)[0] 486 | 487 | err += strip_eom(err_buffer) 488 | out += strip_eom(out_buffer) 489 | 490 | if is_end: 491 | break 492 | self._send_message(Script.MSG_MORE) 493 | if self.lock is not None: 494 | self.lock.release() 495 | return (err.decode('utf-16-le')), (out.decode('utf-16-le')) 496 | 497 | def _read_response(self) -> str: 498 | err, out = self._read_pipes() 499 | if err: 500 | name, args = err.split(Script.SEPARATOR, 1) 501 | 502 | exception_class = next((ex for ex in chain(AhkError.__subclasses__(), AhkException.__subclasses__(), (AhkException,)) if ex.__name__ == name), None) 503 | if exception_class: 504 | exception = exception_class(*args.split(Script.SEPARATOR)) 505 | if isinstance(exception, AhkUserException): 506 | if exception.from_exception_obj and Script._is_num(exception.line): 507 | exception.file = self.file or exception.file 508 | exception.line = int(exception.line) - Script.CORE.count('\n') 509 | 510 | if exception.message == '2147549453': 511 | exception.message = '0x8001010D - An outgoing call cannot be made since the application is dispatching an input-synchronous call.' 512 | if exception.message.startswith('0x8001010D - '): 513 | outer_msg = 'Failed a remote procedure call from OnMessage() thread. Solve this with f_main(), call_main() or f_raw_main().' 514 | raise AhkCantCallOutInInputSyncCallError(outer_msg) from exception 515 | else: 516 | warn(AhkCaughtNonExceptionWarning(exception), stacklevel=4) 517 | raise exception 518 | 519 | warning_class = next((w for w in chain(AhkWarning.__subclasses__(), (AhkWarning,)) if w.__name__ == name), None) 520 | if warning_class: 521 | warning = warning_class(*args.split(Script.SEPARATOR)) 522 | warn(warning, stacklevel=4) 523 | 524 | return out 525 | 526 | # https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendmessage 527 | def _send_message(self, msg: int, lparam: bytes = None) -> None: 528 | # this is essential because messages are ignored if uninterruptible (e.g. in menu) 529 | # wparam is normally source window handle, but in our case source thread id 530 | while not win32api.SendMessage(self.hwnd, msg, threading.get_ident(), lparam): 531 | self.poll() 532 | time.sleep(0.01) 533 | 534 | def _send(self, msg: int, data: Sequence[Primitive]) -> None: 535 | data_str = Script.SEPARATOR.join(Script._to_ahk_str(v) for v in data) 536 | # OutputDebugString(f"Sent: {data}") 537 | # https://learn.microsoft.com/en-us/windows/win32/dataxchg/wm-copydata 538 | char_buffer = array.array('b', bytes(data_str, 'utf-8')) 539 | addr, size = char_buffer.buffer_info() 540 | data_type_id = msg # anything; unneeded atm 541 | struct_ = struct.pack('PLP', data_type_id, size, addr) 542 | self._send_message(win32con.WM_COPYDATA, struct_) 543 | self.lock.acquire(blocking=True) # False to witness test failure 544 | self._send_message(msg) 545 | 546 | @staticmethod 547 | def _to_ahk_str(val: Primitive) -> str: 548 | if isinstance(val, float): 549 | if math.isnan(val) or math.isinf(val): 550 | raise AhkUnsupportedValueError(val) 551 | val_str = f'{val:.6f}' # 6 decimal precision to match AutoHotkey 552 | if float(val_str) != val: 553 | warn(AhkLossOfPrecisionWarning(val, val_str), stacklevel=6) 554 | val_str = val_str.rstrip('0').rstrip('.') # less text to send the better 555 | else: 556 | if isinstance(val, str): 557 | if '\x00' in val: 558 | raise AhkUnsupportedValueError(r"string contains null terminator '\x00' which AutoHotkey ignores characters beyond") 559 | if Script.SEPARATOR in val: 560 | raise AhkUnsupportedValueError(f'string contains {repr(Script.SEPARATOR)} which is reserved for messages to AutoHotkey') 561 | val_str = str(val) 562 | return f"{type(val).__name__[:5]:<5} {val_str}" 563 | 564 | def _f(self, msg: int, name: str, *args: Primitive, need_result: bool, coerce_result: bool = False) -> Optional[str]: 565 | self._send(msg, [name, need_result] + list(args)) 566 | response = self._read_response() 567 | return self._from_ahk_str(response) if coerce_result else response 568 | 569 | def call(self, name: str, *args: Primitive) -> None: 570 | """Call a script function without receiving the result, if any. Least latency.""" 571 | self._f(Script.MSG_F, name, *args, need_result=False) 572 | 573 | def call_main(self, name: str, *args: Primitive) -> None: 574 | """Same as `call()` but executed on AutoHotkey's main thread. 575 | Worse latency, but solution to `AhkCantCallOutInInputSyncCallError`.""" 576 | self._f(Script.MSG_F_MAIN, name, *args, need_result=False) 577 | 578 | def f_raw(self, name: str, *args: Primitive) -> str: 579 | """Call a script function and return the result as its raw string (don't mimic AutoHotkey's type inference).""" 580 | return self._f(Script.MSG_F, name, *args, need_result=True) 581 | 582 | def f_raw_main(self, name: str, *args: Primitive) -> str: 583 | """Same as `f_raw()` but executed on AutoHotkey's main thread. 584 | Worse latency, but solution to `AhkCantCallOutInInputSyncCallError`.""" 585 | return self._f(Script.MSG_F_MAIN, name, *args, need_result=True) 586 | 587 | def f(self, name: str, *args: Primitive) -> Primitive: 588 | """Call a script function and return the result.""" 589 | return self._f(Script.MSG_F, name, *args, need_result=True, coerce_result=True) 590 | 591 | def f_main(self, name: str, *args: Primitive) -> Primitive: 592 | """Same as `f()` but executed on AutoHotkey's main thread. 593 | Worse latency, but solution to `AhkCantCallOutInInputSyncCallError`.""" 594 | return self._f(Script.MSG_F_MAIN, name, *args, need_result=True, coerce_result=True) 595 | 596 | @staticmethod 597 | def _is_num(str_: str) -> bool: 598 | return str_.isdigit() or (str_.startswith('-') and str_[1:].isdigit()) 599 | 600 | @staticmethod 601 | def _from_ahk_str(str_: str) -> Primitive: 602 | is_hex = str_.startswith('0x') and all(c in string.hexdigits for c in str_[2:]) 603 | if is_hex: 604 | return int(str_, 16) 605 | 606 | if Script._is_num(str_): 607 | return int(str_.lstrip('0') or '0', 0) 608 | if Script._is_num(str_.replace('.', '', 1)): 609 | return float(str_) 610 | return str_ 611 | 612 | def get_raw(self, name: str) -> str: 613 | """Get a global script variable or built-in as its raw string (don't mimic AutoHotkey's type inference).""" 614 | self._send(Script.MSG_GET, [name]) 615 | return self._read_response() 616 | 617 | def get(self, name: str) -> Primitive: 618 | """Get a global script variable or built-in like `A_TimeIdle`.""" 619 | self._send(Script.MSG_GET, [name]) 620 | return Script._from_ahk_str(self._read_response()) 621 | 622 | def set(self, name: str, val: Primitive) -> None: 623 | """Set a global script variable.""" 624 | # Every _send() will lock, so others are finished before we set(). 625 | # We don't need a confirmation response, just the ensurance that it finishes before others begin. 626 | self._send(Script.MSG_SET, [name, val]) 627 | self.lock.release() 628 | 629 | # if AutoHotkey is terminated, get error code 630 | def poll(self) -> None: 631 | """Detect when AutoHotkey process exits, typically within a loop, by raising `AhkExitException`. 632 | (Only needed in contexts without other Script functions, as they all run this internally.)""" 633 | exit_code = self.popen.poll() 634 | if exit_code is not None: 635 | # OutputDebugString(f"Exit code: {exit_code}; call stack: {traceback.format_stack()}") 636 | atexit.unregister(self._on_python_exit) 637 | raise AhkExitException(exit_code) 638 | 639 | def _on_python_exit(self) -> None: 640 | with suppress(AhkExitException): # Expected and not exceptional. 641 | self.exit() 642 | 643 | def exit(self, timeout: float = 5.0, kill_descendants: Optional[bool] = None) -> None: 644 | """Ask AutoHotkey to exit cleanly (remove system tray icon, etc.). 645 | To my knowledge only an `OnExit()` callback could delay this. 646 | 647 | :param timeout: Seconds to wait before terminating. `None` for infinity. 648 | :param kill_descendants: Uses `Script()`'s `kill_process_tree_on_exit` (default `False`) unless overriden here. 649 | """ 650 | 651 | if kill_descendants is None: 652 | kill_descendants = self.kill_process_tree_on_exit 653 | 654 | # No need to &= ~KILL_ON_JOB_CLOSE if `kill_descendants` is `False` and `self.kill_process_tree_on_exit` is `True` 655 | # because jobs only *automatically* execute when *Python* exits (job handle closes), not AutoHotkey by itself. 656 | 657 | atexit.unregister(self._on_python_exit) 658 | 659 | exit_code = None 660 | try: 661 | try: 662 | # clean; removes tray icons etc. 663 | # OutputDebugString(f"Sending ExitApp from thread {threading.get_ident()}") 664 | self._send_message(Script.MSG_EXIT) 665 | except AhkExitException as ex: # exited immediately 666 | exit_code = ex.args[0] # for 'finally' 667 | raise 668 | 669 | exit_code = self.popen.wait(timeout) # exited after a delay, before timeout 670 | raise AhkExitException(exit_code) 671 | except TimeoutExpired as ex: # never exited before timeout 672 | self.popen.terminate() 673 | exit_code = 1 674 | raise AhkExitException(exit_code) from ex 675 | finally: 676 | if kill_descendants: 677 | win32job.TerminateJobObject(self.tree_job, exit_code) # :TerminateJob 678 | -------------------------------------------------------------------------------- /ahkunwrapped/lib/AutoHotkey/AutoHotkey.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CodeOptimist/ahkunwrapped/b574229bb3628c6ab6e9159279441235c2a9a84e/ahkunwrapped/lib/AutoHotkey/AutoHotkey.exe -------------------------------------------------------------------------------- /ahkunwrapped/lib/AutoHotkey/NOTICE: -------------------------------------------------------------------------------- 1 | AutoHotkey.exe included under terms of the GPLv3 ("any later version") 2 | https://www.autohotkey.com/download/ 3 | Source: https://github.com/Lexikos/AutoHotkey_L/ 4 | 5 | AutoHotkey 6 | 7 | Copyright 2003-2009 Chris Mallett (support@autohotkey.com) 8 | This program is free software; you can redistribute it and/or 9 | modify it under the terms of the GNU General Public License 10 | as published by the Free Software Foundation; either version 2 11 | of the License, or (at your option) any later version. 12 | 13 | This program is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. -------------------------------------------------------------------------------- /ahkunwrapped/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CodeOptimist/ahkunwrapped/b574229bb3628c6ab6e9159279441235c2a9a84e/ahkunwrapped/py.typed -------------------------------------------------------------------------------- /example.ahk: -------------------------------------------------------------------------------- 1 | #SingleInstance, force 2 | #Warn 3 | ToolTip("Standalone script test!") 4 | return 5 | 6 | AutoExec() { 7 | global event 8 | event := "" 9 | SendMode, input 10 | } 11 | 12 | Send(text) { 13 | Send, % text 14 | } 15 | 16 | ToolTip(text, s := 2) { 17 | ToolTip, % text 18 | ; negative for non-repeating 19 | SetTimer, RemoveToolTip, % s * -1000 20 | } 21 | 22 | RemoveToolTip: 23 | ToolTip, 24 | event = {{Event.CLEAR_CHOICE}} 25 | return 26 | 27 | MouseIsOver(winTitle) { 28 | MouseGetPos,,, winId 29 | result := WinExist(winTitle " ahk_id " winId) 30 | return result 31 | } 32 | 33 | #If WinActive("ahk_class Notepad") 34 | {{HOTKEY_SEND_CHOICE}}::event = {{Event.SEND_CHOICE}} 35 | ^Q::event = {{Event.QUIT}} 36 | #If MouseIsOver("ahk_class Notepad") 37 | WheelUp::event = {{Event.CHOOSE_MONTH}} 38 | WheelDown::event = {{Event.CHOOSE_DAY}} 39 | -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import time 3 | from datetime import datetime 4 | from enum import Enum 5 | from pathlib import Path 6 | 7 | from ahkunwrapped import Script, AhkExitException 8 | 9 | choice = None 10 | HOTKEY_SEND_CHOICE = 'F2' 11 | 12 | 13 | class Event(Enum): 14 | QUIT, SEND_CHOICE, CLEAR_CHOICE, CHOOSE_MONTH, CHOOSE_DAY = range(5) 15 | 16 | 17 | # format_dict= so we can use {{VARIABLE}} within example.ahk 18 | ahk = Script.from_file(Path('example.ahk'), format_dict=globals()) 19 | 20 | 21 | def main() -> None: 22 | print("Scroll your mousewheel in Notepad.") 23 | 24 | ts = 0 25 | while True: 26 | try: 27 | # ahk.poll() # detect exit, but all ahk functions include this 28 | 29 | s_elapsed = time.time() - ts 30 | if s_elapsed >= 60: 31 | ts = time.time() 32 | print_minute() 33 | 34 | event = ahk.get('event') # contains ahk.poll() 35 | if event: 36 | ahk.set('event', '') 37 | on_event(event) 38 | except AhkExitException as ex: 39 | sys.exit(ex.args[0]) 40 | time.sleep(0.01) 41 | 42 | 43 | def print_minute() -> None: 44 | print(f"It is now {datetime.now().time()}") 45 | 46 | 47 | def on_event(event: str) -> None: 48 | global choice 49 | 50 | def get_choice() -> str: 51 | return choice or datetime.now().strftime('%#I:%M %p') 52 | 53 | if event == str(Event.QUIT): 54 | ahk.exit() 55 | if event == str(Event.CLEAR_CHOICE): 56 | choice = None 57 | if event == str(Event.SEND_CHOICE): 58 | ahk.call('Send', f'{get_choice()} ') 59 | if event == str(Event.CHOOSE_MONTH): 60 | choice = datetime.now().strftime('%b') 61 | ahk.call('ToolTip', f"Month is {get_choice()}, {HOTKEY_SEND_CHOICE} to insert.") 62 | if event == str(Event.CHOOSE_DAY): 63 | choice = datetime.now().strftime('%#d') 64 | ahk.call('ToolTip', f"Day is {get_choice()}, {HOTKEY_SEND_CHOICE} to insert.") 65 | 66 | 67 | if __name__ == '__main__': 68 | main() 69 | -------------------------------------------------------------------------------- /example.spec: -------------------------------------------------------------------------------- 1 | # -*- mode: python -*- 2 | from pathlib import Path 3 | 4 | import ahkunwrapped 5 | 6 | a = Analysis( 7 | ['example.py'], 8 | datas=[ 9 | (Path(ahkunwrapped.__file__).parent / 'lib', 'lib'), # required 10 | ('example.ahk', '.'), 11 | ] 12 | ) 13 | pyz = PYZ(a.pure) 14 | 15 | # for onefile 16 | exe = EXE(pyz, a.scripts, a.binaries, a.datas, name='my-example', upx=True, console=False) 17 | # for onedir 18 | # exe = EXE(pyz, a.scripts, exclude_binaries=True, name='my-example', upx=True, console=False) 19 | # dir = COLLECT(exe, a.binaries, a.datas, name='my-example-folder') 20 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = [ 3 | "setuptools>=46.4.0", 4 | "wheel" 5 | ] 6 | build-backend = "setuptools.build_meta" 7 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pywin32>=227 2 | pytest~=7.0.1 3 | hypothesis~=6.31.6 4 | psutil~=5.9.3 5 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = ahkunwrapped 3 | version = attr: ahkunwrapped.__version__ 4 | author = Christopher Galpin 5 | url = https://github.com/CodeOptimist/ahkunwrapped 6 | project_urls = 7 | Discord = https://discord.gg/Uz5rnWUkrV 8 | description = Bundled and bridged AutoHotkey for full native code execution from Python. 9 | long_description = file: README.md 10 | long_description_content_type = text/markdown 11 | keywords = AutoHotkey, AHK 12 | classifiers = 13 | License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+) 14 | Development Status :: 5 - Production/Stable 15 | Operating System :: Microsoft :: Windows :: Windows Vista 16 | Operating System :: Microsoft :: Windows :: Windows 7 17 | Operating System :: Microsoft :: Windows :: Windows 8 18 | Operating System :: Microsoft :: Windows :: Windows 8.1 19 | Operating System :: Microsoft :: Windows :: Windows 10 20 | Programming Language :: Python :: 3 :: Only 21 | Programming Language :: Python :: 3.6 22 | Programming Language :: Python :: 3.7 23 | Programming Language :: Python :: 3.8 24 | Programming Language :: Python :: 3.9 25 | Programming Language :: Python :: 3.10 26 | Environment :: Win32 (MS Windows) 27 | Topic :: Software Development :: Libraries :: Python Modules 28 | 29 | [options] 30 | zip_safe = False 31 | python_requires = >= 3.6 32 | packages = ahkunwrapped 33 | install_requires = 34 | pywin32 >= 227; platform_system=='Windows' 35 | 36 | [options.package_data] 37 | ahkunwrapped = py.typed, lib/AutoHotkey/* 38 | -------------------------------------------------------------------------------- /tests.ahk: -------------------------------------------------------------------------------- 1 | ; Copyright (C) 2019, 2020, 2021 Christopher S. Galpin. Licensed under AGPL-3.0-or-later. See /NOTICE. 2 | #SingleInstance, force 3 | #Warn 4 | return 5 | 6 | HasUtf16Internals() { 7 | str := "0.333333" 8 | float := 1 / 3 ; stored identically to above 9 | 10 | loop, % (StrLen(str) + 1) * 2 { ; include null-terminator, and 2 bytes each 11 | ; MsgBox % A_Index - 1 " str: " NumGet(str, A_Index - 1, "UChar") " float: " NumGet(float, A_Index - 1, "UChar") 12 | if (NumGet(str, A_Index - 1, "UChar") != NumGet(float, A_Index - 1, "UChar")) 13 | return False 14 | } 15 | return True 16 | } 17 | 18 | GetSmile() { 19 | return "🙂" 20 | } 21 | 22 | ComMsGraphCall() { 23 | comMsGraph := ComObjCreate("MSGraph.Application") 24 | } 25 | 26 | ComFsoTempName() { 27 | comFso := ComObjCreate("Scripting.FileSystemObject") 28 | return comFso.GetTempName() 29 | } 30 | 31 | UserException() { 32 | throw Exception("UserException", "example what", "example extra") 33 | } 34 | 35 | NonException1() { 36 | throw 12345 37 | } 38 | 39 | NonException2() { 40 | throw "hello" 41 | } 42 | 43 | NonException3() { 44 | throw {abc: 123, def: "hi"} 45 | } 46 | 47 | NonException4() { 48 | throw {Message: "example message", What: "example what", File: "some file", Line: "not a number"} 49 | } 50 | 51 | ContrivedException() { 52 | throw {Message: "ContrivedException", What: "example what", File: "some file", Line: 9999999999} 53 | } 54 | 55 | Echo(val) { 56 | return val 57 | } 58 | 59 | Copy(val) { 60 | Clipboard := val 61 | } 62 | -------------------------------------------------------------------------------- /tests.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2019-2022 Christopher S. Galpin. Licensed under AGPL-3.0-or-later. See /NOTICE. 2 | import itertools 3 | import math 4 | import os 5 | import random 6 | import signal 7 | # noinspection PyUnresolvedReferences 8 | import sys 9 | import time 10 | import timeit 11 | import warnings 12 | from contextlib import suppress 13 | from datetime import timedelta 14 | from functools import partial 15 | from inspect import currentframe, getframeinfo 16 | from pathlib import Path 17 | from threading import Thread 18 | 19 | import hypothesis.strategies as st 20 | import psutil 21 | import pytest 22 | from hypothesis import given, settings 23 | from win32api import OutputDebugString 24 | 25 | import ahkunwrapped as autohotkey 26 | from ahkunwrapped import Script, AhkExitException 27 | 28 | ahk = Script.from_file(Path('tests.ahk')) 29 | 30 | 31 | def print_timings(): 32 | setup = r''' 33 | from ahkunwrapped import Script 34 | ahk = Script('Echo(val) {\nreturn val\n}') 35 | ''' 36 | 37 | for number in (100, 1000): 38 | print(f'number={number}'.rjust(30), "1 buffer".rjust(20), "".rjust(20), "~100 buffers".rjust(20)) 39 | for func in ('call', 'f', 'call_main', 'f_main'): 40 | single_buffer = timeit.timeit(f"ahk.{func}('Echo', ' ' * 2000)", setup=setup, number=number) 41 | many_buffers = timeit.timeit(f"ahk.{func}('Echo', ' ' * 200000)", setup=setup, number=number) 42 | print(f"{func}('Echo', ...)".rjust(30), f'{single_buffer:.4f}'.rjust(20), f'x {many_buffers / single_buffer:.1f} ='.rjust(20), f'{many_buffers:.4f}'.rjust(20)) 43 | 44 | 45 | if __name__ == '__main__': 46 | print_timings() 47 | 48 | 49 | def test_utf16_internals(): 50 | assert ahk.f('HasUtf16Internals') 51 | 52 | 53 | @given(st.sampled_from([ahk.f, ahk.f_main])) 54 | def test_smile(f): 55 | assert f('GetSmile') == '🙂' 56 | 57 | 58 | @given(st.sampled_from([ahk.call, ahk.call_main, ahk.f, ahk.f_main])) 59 | def test_missing_func(func): 60 | with pytest.raises(autohotkey.AhkFuncNotFoundError): 61 | func('ThisDoesntExist') 62 | 63 | 64 | # This test may fail the first time after a computer restart. 65 | @settings(deadline=timedelta(seconds=1)) 66 | @given(st.sampled_from([ahk.call, ahk.f]), st.sampled_from([ahk.call_main, ahk.f_main])) 67 | def test_main_thread_required(func, func_main): 68 | with pytest.raises(autohotkey.AhkCantCallOutInInputSyncCallError): 69 | func('ComMsGraphCall') 70 | func_main('ComMsGraphCall') 71 | 72 | 73 | @given(st.sampled_from([ahk.call, ahk.call_main]), st.sampled_from([ahk.f, ahk.f_main])) 74 | def test_main_thread_not_required(call, f): 75 | call('ComFsoTempName') 76 | assert f('ComFsoTempName').endswith('.tmp') 77 | 78 | 79 | def test_userexception(): 80 | try: 81 | ahk.call('UserException') 82 | assert False 83 | except autohotkey.AhkUserException as e: 84 | assert e.message == "UserException" 85 | assert e.what == "example what" 86 | assert e.extra == "example extra" 87 | assert e.file == ahk.file 88 | 89 | 90 | def test_userexception_lineno(): 91 | try: 92 | ahk.call('UserException') 93 | assert False 94 | except autohotkey.AhkUserException as e: 95 | line_num = 1 + next(num for (num, line) in enumerate(ahk.script.split('\n')) if line.startswith(' throw Exception("UserException"')) 96 | assert e.line == line_num 97 | 98 | 99 | # Documenting that we can't distinguish between Exception() with good data and a contrived object with bad. They're the same within AHK. 100 | @pytest.mark.xfail(strict=True) # expected fail 101 | def test_userexception_lineno_for_contrived(): 102 | try: 103 | ahk.call('ContrivedException') 104 | assert False 105 | except autohotkey.AhkUserException as e: 106 | line_num = 1 + next(num for (num, line) in enumerate(ahk.script.split('\n')) if line.startswith(' throw {Message: "ContrivedException"')) 107 | assert e.line == line_num 108 | 109 | 110 | def test_nonexception_warning(): 111 | for i in range(1, 4): 112 | with pytest.warns(autohotkey.AhkCaughtNonExceptionWarning): 113 | with pytest.raises(autohotkey.AhkUserException): 114 | ahk.call(f'NonException{i}') 115 | 116 | 117 | # Documenting that we can't distinguish between Exception() with good data and a contrived object with bad. They're the same within AHK. 118 | @pytest.mark.xfail(strict=True) # expected fail 119 | def test_nonexception_warning_for_contrived(): 120 | with pytest.warns(autohotkey.AhkCaughtNonExceptionWarning): 121 | with pytest.raises(autohotkey.AhkUserException): 122 | ahk.call(f'ContrivedException') 123 | 124 | 125 | # if fail, adjust its stacklevel= 126 | def test_nonexception_warning_lineno(): 127 | for i in range(1, 4): 128 | with warnings.catch_warnings(record=True) as w: 129 | with pytest.raises(autohotkey.AhkUserException): 130 | ahk.call(f'NonException{i}') 131 | assert w[0].filename == getframeinfo(currentframe()).filename and w[0].lineno == currentframe().f_lineno - 1 132 | 133 | 134 | # if fail, adjust its stacklevel= 135 | def test_warning_lineno(): 136 | with warnings.catch_warnings(record=True) as w: 137 | ahk.call('_Py_StdErr', autohotkey.AhkWarning.__name__, "some generic warning") # get directly because unused atm 138 | assert w[0].filename == getframeinfo(currentframe()).filename and w[0].lineno == currentframe().f_lineno - 1 139 | # eat the redundant output from call() finishing 140 | ahk.popen.stdout.readline() 141 | ahk.popen.stderr.readline() 142 | 143 | 144 | # warning covered in test_float() 145 | # if fail, adjust its stacklevel= 146 | def test_precisionwarning_lineno(): 147 | with warnings.catch_warnings(record=True) as w: 148 | echo(1 / 3) # AhkLossOfPrecisionWarning 149 | assert w[0].filename == getframeinfo(currentframe()).filename and w[0].lineno == currentframe().f_lineno - 1 150 | 151 | 152 | echo = partial(ahk.f, 'Echo') 153 | echo_main = partial(ahk.f_main, 'Echo') 154 | 155 | 156 | def set_get(val): 157 | ahk.set('myVar', val) 158 | return ahk.get('myVar') 159 | 160 | 161 | result_funcs = st.sampled_from([echo, echo_main, set_get]) 162 | 163 | 164 | @given(result_funcs, st.booleans()) 165 | def test_bool(f, bool_): 166 | assert f(bool_) == bool_ 167 | 168 | 169 | @given(result_funcs, st.integers()) 170 | def test_int(f, int_): 171 | assert f(int_) == int_ 172 | 173 | 174 | @given(result_funcs, st.from_type(float)) 175 | def test_float(f, float_): 176 | if math.isnan(float_) or math.isinf(float_): 177 | with pytest.raises(autohotkey.AhkUnsupportedValueError): 178 | f(float_) 179 | else: 180 | ahk_float = float(f'{float_:.6f}') 181 | if ahk_float != float_: 182 | with pytest.warns(autohotkey.AhkLossOfPrecisionWarning): 183 | assert f(float_) == ahk_float 184 | else: 185 | assert f(float_) == float_ 186 | 187 | 188 | echo_raw = partial(ahk.f_raw, 'Echo') 189 | echo_raw_main = partial(ahk.f_raw_main, 'Echo') 190 | 191 | 192 | def set_get_raw(val): 193 | ahk.set('myVar', val) 194 | return ahk.get_raw('myVar') 195 | 196 | 197 | raw_result_funcs = st.sampled_from([echo_raw, echo_raw_main, set_get_raw]) 198 | newlines = [''.join(x) for x in itertools.product('a\n\r', repeat=3)] 199 | 200 | 201 | @given(raw_result_funcs, st.one_of(st.from_type(str), st.sampled_from(newlines))) 202 | def test_str(f, str_): 203 | if '\0' in str_ or Script.SEPARATOR in str_: 204 | with pytest.raises(autohotkey.AhkUnsupportedValueError): 205 | f(str_) 206 | else: 207 | assert f(str_) == str_ 208 | 209 | 210 | @pytest.mark.filterwarnings('error') 211 | @given(raw_result_funcs, st.text()) 212 | def test_text(f, text): 213 | try: 214 | assert f(text) == text 215 | except (autohotkey.AhkWarning, autohotkey.AhkUnsupportedValueError): 216 | return 217 | 218 | 219 | def test_eommore_corrupted_to_eomend(): 220 | # Script.SEPARATOR is b'\x03\x00' 221 | val = ' ' * 2044 222 | val += b'\x00\x03'.decode('utf-16-le') # grave accent diacritic 223 | ahk.set('myVar', val) 224 | assert val == ahk.get_raw('myVar') 225 | 226 | 227 | @pytest.mark.filterwarnings('error') 228 | @given(raw_result_funcs, st.text()) 229 | def test_long_text(f, text): 230 | try: 231 | assert f(text) == text 232 | except (autohotkey.AhkWarning, autohotkey.AhkUnsupportedValueError): 233 | return 234 | 235 | rand_len = random.randint(2000, 4000) 236 | # ahk.call('Copy', f"{repr(text)} * {rand_len}") 237 | long_text = text * rand_len 238 | # print(len(long_text), file=sys.stderr) 239 | assert f(long_text) == long_text 240 | 241 | 242 | # At > 100 Scripts: 243 | # > win32job.AssignProcessToJobObject(job, handle) 244 | # E pywintypes.error: (50, 'AssignProcessToJobObject', 'The request is not supported.') 245 | def test_job_script_limit(): 246 | for _ in range(101): 247 | Script() 248 | 249 | 250 | def test_kill_descendants(): 251 | charmap = """ 252 | AutoExec() { 253 | global pid 254 | Run, charmap,,, pid 255 | } 256 | """ 257 | 258 | for kill_process_tree_on_exit in (True, False): 259 | kill_proc = Script(charmap, kill_process_tree_on_exit=kill_process_tree_on_exit) 260 | kill_pid = kill_proc.get('pid') 261 | orphan_proc = Script(charmap, kill_process_tree_on_exit=kill_process_tree_on_exit) 262 | orphan_pid = orphan_proc.get('pid') 263 | 264 | with suppress(AhkExitException): 265 | kill_proc.exit(kill_descendants=True) 266 | orphan_proc.exit(kill_descendants=False) 267 | 268 | time.sleep(1) 269 | assert not psutil.pid_exists(kill_pid), f"kill_process_tree_on_exit={kill_process_tree_on_exit}" 270 | try: 271 | assert psutil.pid_exists(orphan_pid), f"kill_process_tree_on_exit={kill_process_tree_on_exit}" 272 | finally: 273 | os.kill(orphan_pid, signal.SIGTERM) 274 | 275 | 276 | @pytest.mark.skipif(sys.getwindowsversion().major < 10, reason="Calculator was replaced with a UWP app in Windows 10.") 277 | @pytest.mark.xfail(strict=True) # expected fail 278 | def test_kill_uwp_descendants(): 279 | calc = """ 280 | AutoExec() { 281 | global calc_pid 282 | Run, calc,,, calc_pid 283 | } 284 | """ 285 | 286 | kill_proc = Script(calc) 287 | kill_pid = kill_proc.get('calc_pid') 288 | with suppress(AhkExitException): 289 | kill_proc.exit(kill_descendants=True) 290 | 291 | time.sleep(1) 292 | try: 293 | assert not psutil.pid_exists(kill_pid) 294 | finally: 295 | os.kill(kill_pid, signal.SIGTERM) 296 | 297 | 298 | # Recommend DebugView++ to view OutputDebugString https://github.com/CobaltFusion/DebugViewPP/releases 299 | # Have to manually kill this test if it takes longer than 5 seconds, hypothesis 'deadline' doesn't seem to help. 300 | # https://docs.pytest.org/en/latest/how-to/failures.html#warning-about-unraisable-exceptions-and-unhandled-thread-exceptions 301 | def test_threads_5sec(): 302 | # https://stackoverflow.com/a/50935020/879 303 | exception = None 304 | 305 | def thread(): 306 | nonlocal exception 307 | try: 308 | end_time = time.time() + 5 309 | while time.time() < end_time: 310 | f = random.choice((echo, echo_main)) 311 | # to throw in some MSG_MORE 312 | text = random.choice(("a" * int(Script.BUFFER_SIZE / 3), "b" * int(Script.BUFFER_SIZE * 3))) 313 | assert f(text) == text 314 | if random.choice((False, True)): 315 | ahk.set('myVar', text) 316 | time.sleep(random.random() / 10) 317 | except Exception as e: 318 | exception = e 319 | 320 | OutputDebugString("STARTING THREADS") 321 | threads = [Thread(target=thread, daemon=True), Thread(target=thread, daemon=True), Thread(target=thread, daemon=True)] 322 | for t in threads: 323 | t.start() 324 | for t in threads: 325 | t.join() 326 | OutputDebugString("THREADS FINISHED") 327 | if exception: 328 | raise exception 329 | --------------------------------------------------------------------------------