commit 9e00f40996debe2149247ba9ee8a01a2fe27d9f4 Author: simeonvartik Date: Mon Jul 13 02:37:05 2026 +0200 Release the tag update diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..bcaca02 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +gradlew text eol=lf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c70661d --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +# Gradle / build output +.gradle/ +build/ +out/ +run/ + +# IDE +.idea/ +*.iml +.vscode/ + +# OS +.DS_Store +Thumbs.db diff --git a/CREDITS.md b/CREDITS.md new file mode 100644 index 0000000..0664d1f --- /dev/null +++ b/CREDITS.md @@ -0,0 +1,41 @@ +# Credits + +AUTISM Client includes original code written for this project, but it also uses, references, or derives ideas/code from other open-source Minecraft client projects. + +Huge credit to the following developers and projects: + +## OpSec by aurickk + +Parts of AUTISM Client related to client privacy, mod detection protection, compatibility handling, and anti-fingerprinting behavior are inspired by or derived from OpSec. + +Project: https://github.com/aurickk/OpSec +License: GPL-3.0 + +## Meteor Client + +AUTISM Client uses ideas, structure, APIs, or source-code references from Meteor Client, especially around Fabric client architecture, modules, utilities, and client-side systems. + +Project: https://github.com/MeteorDevelopment/meteor-client +License: GPL-3.0 + +## Wurst Client + +AUTISM Client uses ideas, references, or code patterns from Wurst Client, one of the long-running open-source Minecraft utility clients. + +Project: https://github.com/Wurst-Imperium/Wurst7 +License: GPL-3.0 + +## ExploitPreventer by NikOverflow + +AUTISM Client uses ideas, references, or derived logic from ExploitPreventer for protection against known client-side exploits. + +Project: https://github.com/NikOverflow/ExploitPreventer +License: MIT + +## License Notice + +Because AUTISM Client uses and/or derives from GPL-licensed projects, AUTISM Client is released under the GNU General Public License v3.0. + +Source code must stay available to users, and any redistributed modified versions must follow the same GPL-3.0 license terms. + +If any credit is missing or inaccurate, contact the maintainers so it can be corrected. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3877ae0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..fd74ce6 --- /dev/null +++ b/README.md @@ -0,0 +1,79 @@ +# AUTISM Client + +AUTISM Client is the best Duping/Debugging client built for people who actually want control over what actions server recieves. + +It is not trying to be a bloated all-in-one mess with 400 random buttons nobody uses. The point is simple: useful modules, a strong macro system, clean addon support, and tools that make testing, automation, and server interaction less painful. + +This client is built around speed, control, and not pretending that users are too stupid to touch advanced features. + +## What It Includes + +AUTISM Client includes the normal client stuff you would expect, but the main focus is on systems that are actually useful. + +Main features include: + +* module system +* macro editor +* custom macro actions +* custom macro conditions +* addon support +* addon presets +* LAN sync tools +* custom payload sender +* NBT viewer +* packet and payload testing tools +* HUD elements +* commands +* event system + +The client is made to be expandable. If the base client is not enough, addons can add their own modules, macro actions, conditions, presets, HUD elements, commands, events, and mixins. + +--- + +# Credits + +AUTISM Client includes original code written for this project, but it also uses, references, or derives ideas/code from other open-source Minecraft client projects. + +Huge credit to the following developers and projects: + +## OpSec by aurickk + +Parts of AUTISM Client related to client privacy, mod detection protection, compatibility handling, and anti-fingerprinting behavior are inspired by or derived from OpSec. + +Project: https://github.com/aurickk/OpSec +License: GPL-3.0 + +## Meteor Client + +AUTISM Client uses ideas, structure, APIs, or source-code references from Meteor Client, especially around Fabric client architecture, modules, utilities, and client-side systems. + +Project: https://github.com/MeteorDevelopment/meteor-client +License: GPL-3.0 + +## Wurst Client + +AUTISM Client uses ideas, references, or code patterns from Wurst Client, one of the long-running open-source Minecraft utility clients. + +Project: https://github.com/Wurst-Imperium/Wurst7 +License: GPL-3.0 + +## ExploitPreventer by NikOverflow + +AUTISM Client uses ideas, references, or derived logic from ExploitPreventer for protection against known client-side exploits. + +Project: https://github.com/NikOverflow/ExploitPreventer +License: MIT + +## Dupe Radar by ErneTalu + +The Radar idea is credited to Dupe Radar by ErneTalu. + +Project: https://github.com/ErneTalu/Dupe-Radar + +## License Notice + +Because AUTISM Client uses and/or derives from GPL-licensed projects, AUTISM Client is released under the GNU General Public License v3.0. + +Source code must stay available to users, and any redistributed modified versions must follow the same GPL-3.0 license terms. + +If any credit is missing or inaccurate, contact the maintainers so it can be corrected. diff --git a/addon-templates/README.md b/addon-templates/README.md new file mode 100644 index 0000000..7c08d3e --- /dev/null +++ b/addon-templates/README.md @@ -0,0 +1,136 @@ +# AUTISM Client Addon Templates + +These are the official addon templates for AUTISM Client. + +Put these in the same repo as the client source. They are standalone Fabric mod projects, but they depend on the AUTISM Client API being published to your local Maven repo first. + +This is not some magical separate SDK. Build the client API locally, then build your addon. + +## Templates + +- `minimal/` - This is the one you should probably start with. + +It gives you the clean basic setup without throwing the entire client architecture at your face. It includes: + +one module +one simple macro action +one simple wait condition +the beginner-friendly API setup + +It is intentionally small. You can actually read it without needing to reverse engineer the entire client. + +- `advanced/` - This is the full reference template. + +Use this when you want to see how the bigger stuff is supposed to be wired. It includes: + +modules +macro actions +macro conditions +presets +commands +HUD elements +events +a mixin + +Addon presets are fully supported. They show up in the macro editor `Presets` picker under your addon's +own category, the same way addon modules/actions/conditions do. + +Category names are intentionally simple: your addon name is the public category. If an API lets you pass a +custom category label, treat that as local organization only. The user-facing UI still groups your stuff under +the addon name so the menu does not turn into a junk drawer. + +Use this when you want to see how everything works together, or when the minimal template stops being enough. + +## Build Flow + +From the main AUTISM Client folder, publish the API locally: + +.\gradlew.bat publishToMavenLocal --no-daemon + +Then build the template you want. + +Minimal: + +cd addon-templates\minimal +.\gradlew.bat build --no-daemon + +Advanced: + +cd addon-templates\advanced +.\gradlew.bat build --no-daemon + +Your addon jar will be in: + +build/libs/ + +That is the file you load as the addon. + +## Toolkit + +The toolkit renames addon projects for you so you don't hand-edit Gradle files into a cursed broken +state. It's one cross-platform program (`addon-toolkit.py`) with a launcher for each platform - they all +do the exact same thing, so pick whatever fits your OS. + +Windows (PowerShell), same commands as before: + +.\addon-templates\addon-toolkit.ps1 +.\addon-templates\addon-toolkit.ps1 -Action Setup -Template minimal -OutputPath ..\MyAddon +.\addon-templates\addon-toolkit.ps1 -Action Scan -ProjectPath ..\MyAddon +.\addon-templates\addon-toolkit.ps1 -Action BuildAll + +Linux / macOS / anywhere with Python 3: + +python addon-templates/addon-toolkit.py +python addon-templates/addon-toolkit.py setup --template minimal --output ../MyAddon +python addon-templates/addon-toolkit.py scan --project ../MyAddon +python addon-templates/addon-toolkit.py build-all + +(./addon-templates/addon-toolkit.sh ... is the same thing if you'd rather run a shell script.) + +Through Gradle. Building needs only the JDK; the scaffold/scan tasks call the Python toolkit: + +./gradlew buildAllTemplates # no Python needed +./gradlew newAddon -Pname="My Addon" -Ptemplate=minimal -Pout=../MyAddon # needs Python +./gradlew scanAddon -Pproject=../MyAddon # needs Python +./gradlew validateAddons # needs Python + +Setup asks for: + +addon name +output folder +version +author + +If you leave the version blank, it bumps the current template version by one. + +It also generates the annoying stuff automatically: + +addon id +package name +Maven group +jar name +description +Fabric entrypoints +mixin references + +This matters because half renaming a mod is one of the easiest ways to make Gradle look like it hates you personally. + +If you want to set every value yourself, use: + +.\addon-templates\addon-toolkit.ps1 -Action Setup -Template advanced -Advanced + +Do that only if you actually need control over everything. Or edit the files directly. + + +## Public Repo Rule + +Commit the source, Gradle wrapper files, and config files. + +Do not commit: + +.gradle/ +build/ + +They are already ignored by the root .gitignore. + +If it is generated trash from your machine, it probably does not belong in the repo. diff --git a/addon-templates/addon-toolkit.ps1 b/addon-templates/addon-toolkit.ps1 new file mode 100644 index 0000000..d637e27 --- /dev/null +++ b/addon-templates/addon-toolkit.ps1 @@ -0,0 +1,77 @@ +param( + [ValidateSet("Menu", "Setup", "Scan", "Validate", "PublishApi", "Build", "BuildAll", "Clean")] + [string] $Action = "Menu", + + [ValidateSet("minimal", "advanced")] + [string] $Template = "minimal", + + [string] $ProjectPath, + [string] $OutputPath, + [string] $AddonId, + [string] $AddonName, + [string] $AddonVersion, + [string] $Package, + [string] $Author, + [string] $Description, + [string] $MavenGroup, + [string] $ArchiveName, + [switch] $Advanced, + [switch] $DebugStack, + [switch] $NoPublish, + [switch] $Yes, + [switch] $NonInteractive +) + +# Forwards to addon-toolkit.py, keeping the old -Action/-Param interface. + +$ErrorActionPreference = "Stop" +$toolkit = Join-Path $PSScriptRoot "addon-toolkit.py" +if (-not (Test-Path -LiteralPath $toolkit)) { + Write-Error "addon-toolkit.py not found next to this launcher." + exit 1 +} + +function Resolve-PythonCommand { + # Probe --version (not just existence) so we skip Windows' Store-alias stub that exits non-zero. + foreach ($candidate in @(@('py', '-3'), @('python'), @('python3'))) { + $exe = $candidate[0] + if (-not (Get-Command $exe -ErrorAction SilentlyContinue)) { continue } + $pre = if ($candidate.Count -gt 1) { $candidate[1..($candidate.Count - 1)] } else { @() } + try { & $exe @pre '--version' *> $null } catch { continue } + if ($LASTEXITCODE -eq 0) { return , $candidate } + } + return $null +} + +$python = Resolve-PythonCommand +if (-not $python) { + Write-Error "Python 3 was not found on PATH. Install Python 3, or use the Gradle tasks (gradlew newAddon, scanAddon, ...)." + exit 1 +} + +$actionMap = @{ + Menu = 'menu'; Setup = 'setup'; Scan = 'scan'; Validate = 'validate' + PublishApi = 'publish-api'; Build = 'build'; BuildAll = 'build-all'; Clean = 'clean' +} + +$pyArgs = @($toolkit, $actionMap[$Action], '--template', $Template) +if ($ProjectPath) { $pyArgs += @('--project', $ProjectPath) } +if ($OutputPath) { $pyArgs += @('--output', $OutputPath) } +if ($AddonId) { $pyArgs += @('--addon-id', $AddonId) } +if ($AddonName) { $pyArgs += @('--name', $AddonName) } +if ($AddonVersion) { $pyArgs += @('--addon-version', $AddonVersion) } +if ($Package) { $pyArgs += @('--package', $Package) } +if ($Author) { $pyArgs += @('--author', $Author) } +if ($Description) { $pyArgs += @('--description', $Description) } +if ($MavenGroup) { $pyArgs += @('--maven-group', $MavenGroup) } +if ($ArchiveName) { $pyArgs += @('--archive-name', $ArchiveName) } +if ($Advanced) { $pyArgs += '--advanced' } +if ($NoPublish) { $pyArgs += '--no-publish' } +if ($Yes) { $pyArgs += '--yes' } +if ($NonInteractive) { $pyArgs += '--non-interactive' } +if ($DebugStack) { $pyArgs += '--debug-stack' } + +$pyExe = $python[0] +$pyPre = if ($python.Count -gt 1) { $python[1..($python.Count - 1)] } else { @() } +& $pyExe @pyPre @pyArgs +exit $LASTEXITCODE diff --git a/addon-templates/addon-toolkit.py b/addon-templates/addon-toolkit.py new file mode 100644 index 0000000..ec1f559 --- /dev/null +++ b/addon-templates/addon-toolkit.py @@ -0,0 +1,759 @@ +#!/usr/bin/env python3 +"""AUTISM addon toolkit: scaffold, scan, validate and build addons. Runs anywhere with Python 3. + + python addon-toolkit.py # menu + python addon-toolkit.py setup --template minimal --name "My Addon" --output ../MyAddon + python addon-toolkit.py scan --project ../MyAddon + python addon-toolkit.py build --project ../MyAddon +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +from pathlib import Path + +SCRIPT_DIR = Path(__file__).resolve().parent +REPO_ROOT = SCRIPT_DIR.parent +TEMPLATES = ("minimal", "advanced") +TEXT_EXTS = {".java", ".json", ".kts", ".toml", ".properties", ".md", ".yml", ".yaml"} + + +class ToolkitError(Exception): + """Expected failure, shown without a traceback.""" + + +def info(msg: str) -> None: print(f"[AUTISM] {msg}") +def ok(msg: str) -> None: print(f"[OK] {msg}") +def warn(msg: str) -> None: print(f"[WARN] {msg}") +def bad(msg: str) -> None: print(f"[FAIL] {msg}") + + +def path_line(label: str, path) -> None: + print(f"{label}:") + print(str(path)) + + +def failure_item(msg: str) -> None: + if re.match(r"^[A-Za-z]:[\\/]", msg) or msg.startswith("/") or re.match(r"^\.{1,2}[\\/]", msg): + path_line("Path", msg) + else: + bad(f" - {msg}") + + +def is_interactive(args) -> bool: + return not getattr(args, "non_interactive", False) and sys.stdin.isatty() + + +def read_text(path: Path) -> str: + return path.read_text(encoding="utf-8") + + +def write_text(path: Path, text: str) -> None: + path.write_text(text, encoding="utf-8", newline="") + + +def to_folder_name(name: str) -> str: + if not name or not name.strip(): + return "MyAddon" + parts = re.findall(r"[A-Za-z0-9]+", name) + if not parts: + return "MyAddon" + folder = "".join(p.upper() if len(p) == 1 else p[0].upper() + p[1:] for p in parts) + return folder[:48] + + +def to_package_segment(value: str) -> str: + segment = re.sub(r"[^a-z0-9]+", "", value.lower()) + if not segment: + segment = "myaddon" + if not segment[0].isalpha(): + segment = "addon" + segment + return segment + + +def to_mod_id(name: str) -> str: + mod_id = re.sub(r"[^a-z0-9_-]+", "-", name.lower()).strip("-_") + if not mod_id: + return "my-autism-addon" + if not mod_id[0].isalpha(): + mod_id = "addon-" + mod_id + if len(mod_id) > 64: + mod_id = mod_id[:64].strip("-_") + return mod_id + + +def default_author() -> str: + return os.environ.get("USERNAME") or os.environ.get("USER") or "You" + + +def test_mod_id(value: str) -> bool: + return bool(re.match(r"^[a-z][a-z0-9_-]{1,63}$", value or "")) + + +def test_java_package(value: str) -> bool: + return bool(re.match(r"^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)+$", value or "")) + + +def test_version(value: str) -> bool: + return bool(re.match(r"^[0-9A-Za-z][0-9A-Za-z._+-]*$", value or "")) + + +def step_version(version: str) -> str: + if not version or not version.strip(): + return "1.0.0" + m = re.match(r"^(.*?)(\d+)(\D*)$", version) + if not m: + return version + ".1" + prefix, digits, suffix = m.group(1), m.group(2), m.group(3) + nxt = str(int(digits) + 1) + if len(digits) > 1 and len(nxt) < len(digits): + nxt = nxt.rjust(len(digits), "0") + return f"{prefix}{nxt}{suffix}" + + +def get_toml_version(path: Path, key: str) -> str: + m = re.search(r'(?m)^\s*' + re.escape(key) + r'\s*=\s*"([^"]+)"', read_text(path)) + return m.group(1) if m else "" + + +def set_toml_version(path: Path, key: str, value: str) -> None: + text = read_text(path) + pattern = r'(?m)^(\s*' + re.escape(key) + r'\s*=\s*)"[^"]*"' + if re.search(pattern, text): + text = re.sub(pattern, lambda m: m.group(1) + f'"{value}"', text) + else: + text += f'\n{key} = "{value}"\n' + write_text(path, text) + + +def set_properties_value(path: Path, key: str, value: str) -> None: + text = read_text(path) + pattern = r"(?m)^" + re.escape(key) + r"=.*$" + if re.search(pattern, text): + text = re.sub(pattern, f"{key}={value}", text) + else: + text += f"\n{key}={value}\n" + write_text(path, text) + + +def set_root_project_name(path: Path, name: str) -> None: + text = read_text(path) + pattern = r'(?m)^(rootProject\.name\s*=\s*)"[^"]*"' + if re.search(pattern, text): + text = re.sub(pattern, lambda m: m.group(1) + f'"{name}"', text) + else: + text += f'\nrootProject.name = "{name}"\n' + write_text(path, text) + + +def get_json(path: Path): + return json.loads(read_text(path)) + + +def save_json(path: Path, data) -> None: + write_text(path, json.dumps(data, indent=2, ensure_ascii=False) + "\n") + + +def is_under_build_or_gradle(path: Path, project: Path) -> bool: + try: + parts = path.relative_to(project).parts + except ValueError: + return False + return "build" in parts or ".gradle" in parts + + +def resolve_full_path(path: str) -> Path | None: + if not path or not path.strip(): + return None + p = Path(path) + if p.is_absolute(): + return p.resolve() + return (REPO_ROOT / p).resolve() + + +def is_shipped_template(path: Path) -> bool: + full = path.resolve() + return any(full == (REPO_ROOT / "addon-templates" / name).resolve() for name in TEMPLATES) + + +def get_first_java_package(project: Path) -> str: + entry = project / "src/main/resources/fabric.mod.json" + if entry.is_file(): + data = get_json(entry) + classes = [] + eps = data.get("entrypoints", {}) if isinstance(data, dict) else {} + for kind in ("client", "autism"): + if eps.get(kind): + classes += list(eps[kind]) if isinstance(eps[kind], list) else [eps[kind]] + for cls in classes: + m = re.match(r"^(.+)\.[^.]+$", str(cls)) + if m: + return m.group(1) + java_root = project / "src/main/java" + if java_root.is_dir(): + for java in sorted(java_root.rglob("*.java")): + m = re.search(r"(?m)^\s*package\s+([^;]+);", read_text(java)) + if m: + return m.group(1).strip() + return "com.example.addon" + + +def class_simple_name(class_name: str, fallback: str) -> str: + m = re.search(r"\.([^.]+)$", class_name or "") + return m.group(1) if m else fallback + + +def replace_in_project_files(project: Path, old: str, new: str) -> None: + if not old or old == new: + return + for file in project.rglob("*"): + if not file.is_file() or file.suffix not in TEXT_EXTS: + continue + if is_under_build_or_gradle(file, project): + continue + text = read_text(file) + if old in text: + write_text(file, text.replace(old, new)) + + +def move_java_package(project: Path, old_pkg: str, new_pkg: str) -> None: + if old_pkg == new_pkg: + return + src_root = project / "src/main/java" + old_path = src_root / old_pkg.replace(".", os.sep) + new_path = src_root / new_pkg.replace(".", os.sep) + if not old_path.is_dir(): + return + if new_path.exists(): + warn("Package path already exists. Not moving files.") + path_line("Path", new_path) + return + new_path.parent.mkdir(parents=True, exist_ok=True) + shutil.move(str(old_path), str(new_path)) + cursor = old_path.parent + while src_root in cursor.parents and not any(cursor.iterdir()): + parent = cursor.parent + cursor.rmdir() + cursor = parent + + +def copy_addon_template(template_name: str, target: Path) -> None: + source = REPO_ROOT / "addon-templates" / template_name + if not source.is_dir(): + path_line("Missing template", source) + raise ToolkitError("Template not found.") + if target.exists(): + warn("Output already exists. Editing it in place.") + path_line("Path", target) + return + target.mkdir(parents=True, exist_ok=True) + for item in source.rglob("*"): + if is_under_build_or_gradle(item, source): + continue + rel = item.relative_to(source) + dest = target / rel + if item.is_dir(): + dest.mkdir(parents=True, exist_ok=True) + else: + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(item, dest) + + +def prompt(label: str, default: str, validator=None, interactive: bool = True) -> str: + if not interactive: + return default + while True: + suffix = f" [{default}]" if default else "" + try: + value = input(f"{label}{suffix}: ").strip() + except EOFError: + return default + if not value: + value = default + if validator is None or validator(value): + return value + warn("Bad value. Fix it.") + + +def prompt_version(current: str, interactive: bool) -> str: + base = current if current and current.strip() else "1.0.0" + nxt = step_version(base) + if not interactive: + return nxt + while True: + try: + value = input(f"Version current {base}, blank = {nxt}: ").strip() + except EOFError: + return nxt + if not value: + return nxt + if test_version(value): + return value + warn("Bad version. Fix it.") + + +def get_setup_project_path(args, name_for_output: str) -> Path: + if args.project and args.project.strip(): + project = resolve_full_path(args.project) + if is_shipped_template(project): + raise ToolkitError("No. The shipped templates stay clean. Use --output to copy one, or pick a real addon folder.") + return project + output = args.output + if not output or not output.strip(): + default_out = str((REPO_ROOT / ".." / to_folder_name(name_for_output)).resolve()) + output = prompt("Output folder", default_out, lambda v: bool(v and v.strip()), is_interactive(args)) + target = resolve_full_path(output) + if is_shipped_template(target): + raise ToolkitError("No. The shipped templates stay clean. Pick a different output folder.") + copy_addon_template(args.template, target) + return target + + +def configure_addon(args) -> Path: + interactive = is_interactive(args) + addon_name = args.addon_name + if not addon_name or not addon_name.strip(): + default_name = "My Advanced Addon" if args.template == "advanced" else "My Addon" + addon_name = prompt("Addon name", default_name, lambda v: bool(v and v.strip()), interactive) + + project = get_setup_project_path(args, addon_name) + if not project.is_dir(): + path_line("Missing addon folder", project) + raise ToolkitError("Addon project not found.") + + fabric_path = project / "src/main/resources/fabric.mod.json" + versions_path = project / "gradle/libs.versions.toml" + properties_path = project / "gradle.properties" + settings_path = project / "settings.gradle.kts" + for required in (fabric_path, versions_path, properties_path, settings_path): + if not required.is_file(): + path_line("Missing file", required) + raise ToolkitError("Missing required addon file.") + + fabric = get_json(fabric_path) + old_id = str(fabric.get("id", "")) + old_package = get_first_java_package(project) + old_version = get_toml_version(versions_path, "mod-version") + eps = fabric.get("entrypoints", {}) or {} + old_client = str((eps.get("client") or [f"{old_package}.Init"])[0]) + old_addon = str((eps.get("autism") or [f"{old_package}.Addon"])[0]) + original_mixin = str((fabric.get("mixins") or [""])[0]) + client_simple = class_simple_name(old_client, "Init") + addon_simple = class_simple_name(old_addon, "Addon") + + advanced = args.advanced + + addon_id = args.addon_id + if not addon_id or not addon_id.strip(): + suggested = to_mod_id(addon_name) if "template" in old_id else old_id + addon_id = prompt("Addon id", suggested, test_mod_id, interactive) if advanced else suggested + + addon_version = args.addon_version + if not addon_version or not addon_version.strip(): + addon_version = prompt_version(old_version or "1.0.0", interactive) + + package = args.package + if not package or not package.strip(): + suggested_pkg = f"com.{to_package_segment(addon_id)}.addon" + package = prompt("Java package", suggested_pkg, test_java_package, interactive) if advanced else suggested_pkg + + maven_group = args.maven_group + if not maven_group or not maven_group.strip(): + maven_group = prompt("Maven group", package, test_java_package, interactive) if advanced else package + + archive_name = args.archive_name + if not archive_name or not archive_name.strip(): + archive_name = prompt("Jar/archive base name", addon_id, test_mod_id, interactive) if advanced else addon_id + + author = args.author + if not author or not author.strip(): + author = prompt("Author", default_author(), lambda v: bool(v and v.strip()), interactive) + + description = args.description + if not description or not description.strip(): + suggested_desc = f"{addon_name} addon for AUTISM Client." + description = prompt("Description", suggested_desc, lambda v: bool(v and v.strip()), interactive) if advanced else suggested_desc + + replace_in_project_files(project, old_package, package) + replace_in_project_files(project, old_id, addon_id) + move_java_package(project, old_package, package) + + fabric = get_json(fabric_path) + fabric["id"] = addon_id + fabric["name"] = addon_name + fabric["version"] = "${version}" + fabric["description"] = description + fabric["authors"] = [author] + fabric.setdefault("entrypoints", {}) + fabric["entrypoints"]["client"] = [f"{package}.{client_simple}"] + fabric["entrypoints"]["autism"] = [f"{package}.{addon_simple}"] + + if fabric.get("mixins"): + old_mixin_name = original_mixin or str(fabric["mixins"][0]) + new_mixin_name = f"{addon_id}.mixins.json" + resource_dir = project / "src/main/resources" + old_mixin = resource_dir / old_mixin_name + new_mixin = resource_dir / new_mixin_name + if old_mixin.is_file() and old_mixin != new_mixin: + shutil.move(str(old_mixin), str(new_mixin)) + if new_mixin.is_file(): + mixin_json = get_json(new_mixin) + mixin_json["package"] = f"{package}.mixin" + save_json(new_mixin, mixin_json) + fabric["mixins"] = [new_mixin_name] + + save_json(fabric_path, fabric) + set_toml_version(versions_path, "mod-version", addon_version) + set_properties_value(properties_path, "maven_group", maven_group) + set_properties_value(properties_path, "archives_base_name", archive_name) + set_root_project_name(settings_path, addon_id) + + ok("Addon rewritten.") + path_line("Addon folder", project) + print(f" id: {addon_id}") + print(f" name: {addon_name}") + print(f" version: {addon_version}") + print(f" package: {package}") + print() + print("Next:") + print(f" python addon-templates/addon-toolkit.py build --project \"{project}\"") + path_line("Jar folder", project / "build" / "libs") + return project + + +def test_addon_project(project: Path, allow_template_names: bool = False): + failures: list[str] = [] + warnings: list[str] = [] + + if not project.is_dir(): + failures.append("Project folder does not exist.") + failures.append(str(project)) + return failures, warnings + + required = [ + "build.gradle.kts", "settings.gradle.kts", "gradle.properties", + "gradle/libs.versions.toml", "src/main/resources/fabric.mod.json", + ] + for item in required: + if not (project / item).is_file(): + failures.append(f"Missing {item}") + if not (project / "gradlew.bat").is_file() and not (project / "gradlew").is_file(): + failures.append("Missing gradlew / gradlew.bat") + + fabric_path = project / "src/main/resources/fabric.mod.json" + if fabric_path.is_file(): + try: + fabric = get_json(fabric_path) + if not test_mod_id(str(fabric.get("id", ""))): + failures.append(f"fabric.mod.json id is invalid: {fabric.get('id')}") + if not str(fabric.get("name", "")).strip(): + failures.append("fabric.mod.json name is empty.") + eps = fabric.get("entrypoints", {}) or {} + if not eps.get("autism"): + failures.append("Missing autism entrypoint in fabric.mod.json.") + else: + for entry in eps["autism"]: + cls = project / ("src/main/java/" + str(entry).replace(".", "/") + ".java") + if not cls.is_file(): + failures.append(f"Autism entrypoint class file is missing: {entry}") + if not (fabric.get("depends", {}) or {}).get("autism"): + failures.append("fabric.mod.json must depend on autism.") + if not allow_template_names: + if re.search(r"template|example", str(fabric.get("id", ""))): + warnings.append("Addon id still looks like a template/example.") + if re.search(r"Template|Example", str(fabric.get("name", ""))): + warnings.append("Addon name still looks like a template/example.") + if "You" in (fabric.get("authors") or []): + warnings.append("Author is still 'You'.") + except json.JSONDecodeError as exc: + failures.append(f"fabric.mod.json is not valid JSON: {exc}") + + versions_path = project / "gradle/libs.versions.toml" + if versions_path.is_file(): + if not test_version(get_toml_version(versions_path, "mod-version")): + failures.append("Addon mod-version is missing or invalid.") + if not get_toml_version(versions_path, "autism").strip(): + failures.append("AUTISM dependency version is missing from gradle/libs.versions.toml.") + + if (project / ".gradle").exists(): + warnings.append(".gradle cache exists locally. Ignored; do not upload it.") + if (project / "build").exists(): + warnings.append("build output exists locally. Ignored; do not upload it.") + if (project / ".github").exists(): + warnings.append(".github exists inside this addon project. Fine for a copied template, but it is not root repo CI unless you move it.") + + leftovers = ( + "autism-minimal-addon-template", "autism-advanced-addon-template", + "AUTISM Minimal Addon Template", "AUTISM Advanced Addon Template", + ) + for file in project.rglob("*"): + if not file.is_file() or file.suffix not in TEXT_EXTS or is_under_build_or_gradle(file, project): + continue + text = read_text(file) + if re.search(r"[ÂÃâ]", text): + warnings.append(f"Mojibake-looking text in {file}") + if not allow_template_names: + for leftover in leftovers: + if leftover in text: + warnings.append(f"Template leftover '{leftover}' in {file}") + break + return failures, warnings + + +def get_addon_project_path(args) -> Path: + if args.project and args.project.strip(): + return resolve_full_path(args.project) + if args.output and args.output.strip(): + target = resolve_full_path(args.output) + copy_addon_template(args.template, target) + return target + return REPO_ROOT / "addon-templates" / args.template + + +def scan_addon(args) -> None: + project = get_addon_project_path(args) + failures, warnings = test_addon_project(project) + info("Scanned addon project.") + path_line("Addon folder", project) + for w in warnings: + warn(f"Heads up: {w}") + if failures: + bad("Scan found broken stuff:") + for f in failures: + failure_item(f) + raise ToolkitError("Scan failed.") + ok("Scan clean.") + + +def validate_addon_system(args) -> None: + failures: list[str] = [] + warnings: list[str] = [] + + root_required = [ + "src/main/java/autismclient/addons/AddonManager.java", + "src/main/java/autismclient/api/AutismAddon.java", + "src/main/java/autismclient/api/SimpleAddon.java", + "src/main/java/autismclient/api/AutismAddons.java", + "src/main/java/autismclient/api/ApiVersion.java", + "src/main/java/autismclient/api/module/SimpleModule.java", + "src/main/java/autismclient/api/macro/SimpleAction.java", + "src/main/java/autismclient/api/macro/SimpleCondition.java", + "src/main/java/autismclient/api/macro/MacroActionRegistry.java", + "src/main/java/autismclient/api/macro/MacroPresetRegistry.java", + "src/main/java/autismclient/api/hud/HudElements.java", + "src/main/java/autismclient/api/event/AddonEvents.java", + "src/main/java/autismclient/gui/screen/AutismAddonsScreen.java", + "src/main/java/autismclient/util/macro/MissingAddonAction.java", + "addon-templates/README.md", + "addon-templates/addon-toolkit.py", + "addon-templates/addon-toolkit.ps1", + "addon-templates/addon-toolkit.sh", + ] + for f in root_required: + if not (REPO_ROOT / f).is_file(): + failures.append(f"Missing {f}") + + gitignore = REPO_ROOT / ".gitignore" + if gitignore.is_file(): + ignore_text = read_text(gitignore) + for pattern in ("!/src/", "!/addon-templates/", "!/addon-templates/**", + "/addon-templates/**/build/", "/addon-templates/**/.gradle/", "/mc-src*/"): + if pattern not in ignore_text: + failures.append(f".gitignore is missing {pattern}") + else: + failures.append("Missing .gitignore") + + main_version = get_toml_version(REPO_ROOT / "gradle/libs.versions.toml", "mod-version") + for template_name in TEMPLATES: + project = REPO_ROOT / "addon-templates" / template_name + t_failures, t_warnings = test_addon_project(project, allow_template_names=True) + failures += [f"{template_name} template: {x}" for x in t_failures] + warnings += [f"{template_name} template: {x}" for x in t_warnings] + target_version = get_toml_version(project / "gradle/libs.versions.toml", "autism") + if main_version and target_version and main_version != target_version: + failures.append(f"{template_name} template targets AUTISM {target_version}, main client is {main_version}.") + + for w in warnings: + warn(f"Heads up: {w}") + if failures: + bad("Addon system is broken:") + for f in failures: + failure_item(f) + raise ToolkitError("Addon system validation failed.") + ok("Addon system clean.") + + +def run_gradle(project: Path, gradle_args: list[str]) -> None: + wrapper = project / ("gradlew.bat" if os.name == "nt" else "gradlew") + if not wrapper.is_file(): + path_line("Missing Gradle wrapper", wrapper) + raise ToolkitError("Missing Gradle wrapper.") + cmd = [str(wrapper)] + gradle_args + if os.name != "nt" and not os.access(wrapper, os.X_OK): + cmd = ["sh", str(wrapper)] + gradle_args + result = subprocess.run(cmd, cwd=str(project)) + if result.returncode != 0: + path_line("Gradle project", project) + raise ToolkitError(f"Gradle failed with exit code {result.returncode}.") + + +def publish_api(args) -> None: + info("Publishing client API to Maven Local.") + run_gradle(REPO_ROOT, ["publishToMavenLocal", "--no-daemon"]) + ok("Client API published.") + + +def build_addon(args) -> None: + project = get_addon_project_path(args) + if not project.is_dir(): + path_line("Addon folder", project) + raise ToolkitError("Wrong addon folder.") + if not (project / "gradlew.bat").is_file() and not (project / "gradlew").is_file(): + path_line("Addon folder", project) + raise ToolkitError("No Gradle wrapper there. Wrong addon folder.") + if not args.no_publish: + publish_api(args) + info("Building addon.") + path_line("Addon folder", project) + run_gradle(project, ["build", "--no-daemon"]) + ok("Addon built.") + path_line("Jar folder", project / "build" / "libs") + + +def build_all_templates(args) -> None: + if not args.no_publish: + publish_api(args) + for template_name in TEMPLATES: + project = REPO_ROOT / "addon-templates" / template_name + info(f"Building {template_name} template.") + run_gradle(project, ["build", "--no-daemon"]) + ok(f"{template_name} template built.") + + +def clean_addon(args) -> None: + project = get_addon_project_path(args) + interactive = is_interactive(args) + for folder in (".gradle", "build"): + path = project / folder + if path.exists(): + confirmed = args.yes or (interactive and input(f"Remove {path} ? Type YES: ").strip() == "YES") + if confirmed: + shutil.rmtree(path) + ok("Deleted local build junk.") + path_line("Path", path) + + +def menu(args) -> None: + last_path = "" + while True: + print() + print("AUTISM ADDON KIT") + print("1. New addon") + print("2. Build addon") + print("3. Scan addon") + print("4. Test shipped templates") + print("5. Publish client API") + print("6. Delete local build junk") + print("0. Leave") + try: + choice = input("> ").strip() + except EOFError: + return + try: + if choice == "1": + args.template = prompt("Template minimal/advanced", args.template, lambda v: v in TEMPLATES, True) + args.project = "" + args.output = "" + last_path = str(configure_addon(args)) + elif choice == "2": + default_path = last_path or str((REPO_ROOT / ".." / to_folder_name("")).resolve()) + args.project = prompt("Addon folder", default_path, lambda v: bool(v and v.strip()), True) + build_addon(args) + elif choice == "3": + default_path = last_path or str((REPO_ROOT / ".." / to_folder_name("")).resolve()) + args.project = prompt("Addon folder", default_path, lambda v: bool(v and v.strip()), True) + scan_addon(args) + elif choice == "4": + validate_addon_system(args) + build_all_templates(args) + elif choice == "5": + publish_api(args) + elif choice == "6": + default_path = last_path or str((REPO_ROOT / ".." / to_folder_name("")).resolve()) + args.project = prompt("Addon folder", default_path, lambda v: bool(v and v.strip()), True) + clean_addon(args) + elif choice == "0": + return + else: + warn("Bad choice.") + except ToolkitError as exc: + bad(str(exc)) + try: + input("Press Enter. The error stays here until you do") + except EOFError: + return + + +def normalize_action(value: str) -> str: + v = value.strip().lower() + return {"publishapi": "publish-api", "buildall": "build-all"}.get(v, v) + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description="AUTISM addon toolkit.") + parser.add_argument("action", nargs="?", default="menu", type=normalize_action, + choices=["menu", "setup", "scan", "validate", "publish-api", "build", "build-all", "clean"]) + parser.add_argument("--template", type=str.lower, choices=list(TEMPLATES), default="minimal") + parser.add_argument("--project", "--project-path", dest="project") + parser.add_argument("--output", "--output-path", dest="output") + parser.add_argument("--addon-id", dest="addon_id") + parser.add_argument("--name", "--addon-name", dest="addon_name") + parser.add_argument("--addon-version", dest="addon_version") + parser.add_argument("--package") + parser.add_argument("--author") + parser.add_argument("--description") + parser.add_argument("--maven-group", dest="maven_group") + parser.add_argument("--archive-name", dest="archive_name") + parser.add_argument("--advanced", action="store_true") + parser.add_argument("--no-publish", action="store_true", dest="no_publish") + parser.add_argument("--yes", action="store_true") + parser.add_argument("--non-interactive", action="store_true", dest="non_interactive") + parser.add_argument("--debug-stack", action="store_true", dest="debug_stack") + return parser + + +ACTIONS = { + "menu": menu, + "setup": configure_addon, + "scan": scan_addon, + "validate": validate_addon_system, + "publish-api": publish_api, + "build": build_addon, + "build-all": build_all_templates, + "clean": clean_addon, +} + + +def main(argv: list[str]) -> int: + args = build_parser().parse_args(argv) + try: + ACTIONS[args.action](args) + return 0 + except ToolkitError as exc: + bad(str(exc)) + if args.debug_stack: + raise + return 1 + except KeyboardInterrupt: + print() + return 130 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/addon-templates/addon-toolkit.sh b/addon-templates/addon-toolkit.sh new file mode 100755 index 0000000..6e8e5bd --- /dev/null +++ b/addon-templates/addon-toolkit.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env sh +# Forwards to addon-toolkit.py. Example: ./addon-toolkit.sh setup --template minimal --output ../MyAddon +set -e + +DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" +TOOLKIT="$DIR/addon-toolkit.py" +if [ ! -f "$TOOLKIT" ]; then + echo "addon-toolkit.py not found next to this launcher." >&2 + exit 1 +fi + +# Probe --version (not just existence) so we skip Windows' Store-alias stub that exits 49. +for PY in python3 python py; do + if "$PY" --version >/dev/null 2>&1; then + exec "$PY" "$TOOLKIT" "$@" + fi +done + +echo "Python 3 was not found on PATH. Install Python 3, or use the Gradle tasks (./gradlew newAddon, scanAddon, ...)." >&2 +exit 1 diff --git a/addon-templates/advanced/.editorconfig b/addon-templates/advanced/.editorconfig new file mode 100644 index 0000000..e1c9428 --- /dev/null +++ b/addon-templates/advanced/.editorconfig @@ -0,0 +1,15 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 4 + +[*.{json,yml,yaml}] +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false diff --git a/addon-templates/advanced/.github/workflows/build.yml b/addon-templates/advanced/.github/workflows/build.yml new file mode 100644 index 0000000..9a609ed --- /dev/null +++ b/addon-templates/advanced/.github/workflows/build.yml @@ -0,0 +1,45 @@ +name: Build + +on: + push: + pull_request: + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Set up JDK 25 + uses: actions/setup-java@v4 + with: + distribution: 'temurin' + java-version: 25 + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v4 + + # NOTE: the build needs the AUTISM Client API artifact (com.autismclient:autism) to be resolvable. + # mavenLocal() is empty on a fresh CI runner, so make it available one of these ways: + # - publish AUTISM to a maven repo your build.gradle.kts lists (GitHub Packages, a maven server), or + # - commit the AUTISM jar into a `libs/` folder and add `flatDir { dirs("libs") }` to repositories. + - name: Build + run: ./gradlew build --stacktrace + + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: addon-jar + path: build/libs/*.jar + + - name: Release dev build + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + uses: softprops/action-gh-release@v2 + with: + tag_name: dev + name: Dev Build + prerelease: true + files: build/libs/*.jar diff --git a/addon-templates/advanced/.gitignore b/addon-templates/advanced/.gitignore new file mode 100644 index 0000000..95d91a2 --- /dev/null +++ b/addon-templates/advanced/.gitignore @@ -0,0 +1,6 @@ +.gradle/ +build/ +run/ +*.log +.idea/ +*.iml diff --git a/addon-templates/advanced/README.md b/addon-templates/advanced/README.md new file mode 100644 index 0000000..e1f1aa8 --- /dev/null +++ b/addon-templates/advanced/README.md @@ -0,0 +1,95 @@ +# AUTISM Advanced Addon Template + +A standalone reference addon for AUTISM Client. It registers one of each supported extension point, so +you can copy it when you need the full API surface. + +Start small: keep `ExampleModule`, build once, then add macro actions, commands, HUD elements, events, +or mixins as needed. + +## What It Demonstrates + +| Extension point | File | +| --- | --- | +| Addon lifecycle | `ExampleAddon` | +| Module | `modules/ExampleModule` | +| Macro action | `macro/ExampleSayAction` | +| Macro condition | `macro/ExampleHeightCondition` + `macro/ExampleCondition` | +| Macro preset | `macro/ExamplePresets` | +| Command | `commands/ExampleCommand` | +| HUD element | `hud/ExampleHud` | +| Event hooks | `events/ExampleEvents` | +| Mixin | `mixin/ExampleMixin` + `autism-advanced-addon-template.mixins.json` | + +Presets are first-class addon entries. `ExamplePresets` appears in the macro editor `Presets` picker +under this addon's category, and it can insert any normal stack of macro actions. + +Your modules, macro actions, conditions and presets automatically group under a category named after +your addon from `fabric.mod.json`. Custom categories are scoped under your addon so they cannot collide +with built-ins or another addon. + +## Build + +1. In the AUTISM Client project, publish the API to your local Maven repo: + ```sh + ./gradlew publishToMavenLocal + ``` +2. Make sure the `autism` version in `gradle/libs.versions.toml` matches what you published. +3. Build this addon: + ```sh + ./gradlew build + ``` + +The addon jar lands in `build/libs/`. + +## Run + +Drop both jars into your `mods/` folder: + +- the AUTISM Client jar; +- this addon's jar from `build/libs/`. + +## Make It Yours + +Recommended (any OS, from the AUTISM Client repo root): + +```sh +python addon-templates/addon-toolkit.py setup --template advanced --output ../MyAdvancedAddon +``` + +Windows PowerShell works the same: `.\addon-templates\addon-toolkit.ps1 -Action Setup -Template advanced -OutputPath ..\MyAdvancedAddon`. See `../README.md` for the Gradle (`./gradlew newAddon`) and `.sh` variants. + +The toolkit asks for the addon name, output folder, version, and author. Blank version bumps the current +template version by one patch step. It derives the boring stuff and rewrites Gradle files, package paths, +`fabric.mod.json`, entrypoints, and the mixin config in one shot. + +Manual path: + +1. Rename the package `com.example.addon`. +2. Change `ExampleAddon.ID`. +3. Update `src/main/resources/fabric.mod.json`: `id`, `name`, `entrypoints`, `mixins`, and `autism:color`. +4. Rename `autism-advanced-addon-template.mixins.json` and update its `package`. +5. Keep `apiVersion()` and the `autism` dependency range honest for the client version you target. + +## Project Structure + +```text +addon-templates/advanced/ +|-- gradle/ +|-- src/main/java/com/example/addon/ +| |-- ExampleAddon.java +| |-- ExampleInit.java +| |-- modules/ExampleModule.java +| |-- macro/ExampleSayAction.java +| |-- macro/ExampleHeightCondition.java +| |-- macro/ExampleCondition.java +| |-- macro/ExamplePresets.java +| |-- commands/ExampleCommand.java +| |-- hud/ExampleHud.java +| |-- events/ExampleEvents.java +| `-- mixin/ExampleMixin.java +|-- src/main/resources/ +| |-- fabric.mod.json +| `-- autism-advanced-addon-template.mixins.json +|-- build.gradle.kts +`-- gradle.properties +``` diff --git a/addon-templates/advanced/build.gradle.kts b/addon-templates/advanced/build.gradle.kts new file mode 100644 index 0000000..d24e3ff --- /dev/null +++ b/addon-templates/advanced/build.gradle.kts @@ -0,0 +1,67 @@ +plugins { + alias(libs.plugins.fabric.loom) +} + +base { + archivesName = properties["archives_base_name"] as String + version = libs.versions.mod.version.get() + group = properties["maven_group"] as String +} + +repositories { + // AUTISM Client is consumed from your local Maven repo. In the AUTISM project run: + // ./gradlew publishToMavenLocal + mavenLocal() + maven("https://maven.fabricmc.net/") { name = "Fabric" } + mavenCentral() +} + +dependencies { + // Mirrors the AUTISM Client build: official Mojang mappings are implicit for the configured version, so there is no + // explicit `mappings(...)` line and dependencies use plain `implementation`. + minecraft(libs.minecraft) + implementation(libs.fabric.loader) + implementation(libs.fabric.api) + + // The AUTISM Client API (published to mavenLocal from the AUTISM project). + implementation(libs.autism) +} + +// Turns an exact Minecraft version (e.g. "26.2") into a compatible range ("~26.2") so the addon +// keeps loading across patch releases instead of pinning one exact build. +fun toMinecraftCompat(version: String): String { + val m = Regex("""^(\d+)\.(\d+)(?:\.(\d+))?$""").matchEntire(version) + ?: return version + val (year, drop, _) = m.destructured + return "~$year.$drop" +} + +tasks { + processResources { + val propertyMap = mapOf( + "version" to project.version, + "mc_version" to libs.versions.minecraft.get(), + "mc_compat" to toMinecraftCompat(libs.versions.minecraft.get()), + "fabric_api_version" to libs.versions.fabric.api.get(), + "autism_api_version" to libs.versions.autism.get() + ) + inputs.properties(propertyMap) + filteringCharset = "UTF-8" + filesMatching("fabric.mod.json") { + expand(propertyMap) + } + } + + java { + sourceCompatibility = JavaVersion.VERSION_25 + targetCompatibility = JavaVersion.VERSION_25 + toolchain { + languageVersion.set(JavaLanguageVersion.of(25)) + } + } + + withType { + options.encoding = "UTF-8" + options.release.set(25) + } +} diff --git a/addon-templates/advanced/gradle.properties b/addon-templates/advanced/gradle.properties new file mode 100644 index 0000000..44ffddf --- /dev/null +++ b/addon-templates/advanced/gradle.properties @@ -0,0 +1,7 @@ +org.gradle.jvmargs=-Xmx2G +org.gradle.parallel=true +org.gradle.caching=true +org.gradle.configuration-cache=false + +maven_group=com.example.addon +archives_base_name=autism-advanced-addon-template diff --git a/addon-templates/advanced/gradle/libs.versions.toml b/addon-templates/advanced/gradle/libs.versions.toml new file mode 100644 index 0000000..8bdcbfb --- /dev/null +++ b/addon-templates/advanced/gradle/libs.versions.toml @@ -0,0 +1,23 @@ +# In this repo these are auto-synced from the client: run `gradlew syncAddonTemplateVersions` (it also runs +# on publishToMavenLocal), which pins minecraft/fabric-loader/fabric-api/loom/autism to the client's +# gradle/libs.versions.toml. In a copied-out addon, set them to the AUTISM Client release you build against. +[versions] +mod-version = "1.0.0" + +minecraft = "26.2" +fabric-loader = "0.19.3" +fabric-api = "0.152.2+26.2" +# The AUTISM Client release you compile against. The generated fabric.mod.json depends on `>=` this version, so a +# built addon keeps loading on newer hosts in the same major line (the API-version handshake gates real breaks). +autism = "3.4" + +loom = "1.17.11" + +[libraries] +minecraft = { module = "com.mojang:minecraft", version.ref = "minecraft" } +fabric-loader = { module = "net.fabricmc:fabric-loader", version.ref = "fabric-loader" } +fabric-api = { module = "net.fabricmc.fabric-api:fabric-api", version.ref = "fabric-api" } +autism = { module = "com.autismclient:autism", version.ref = "autism" } + +[plugins] +fabric-loom = { id = "net.fabricmc.fabric-loom", version.ref = "loom" } diff --git a/addon-templates/advanced/gradle/wrapper/gradle-wrapper.jar b/addon-templates/advanced/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..f8e1ee3 Binary files /dev/null and b/addon-templates/advanced/gradle/wrapper/gradle-wrapper.jar differ diff --git a/addon-templates/advanced/gradle/wrapper/gradle-wrapper.properties b/addon-templates/advanced/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..5dd3c01 --- /dev/null +++ b/addon-templates/advanced/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/addon-templates/advanced/gradlew b/addon-templates/advanced/gradlew new file mode 100755 index 0000000..adff685 --- /dev/null +++ b/addon-templates/advanced/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/addon-templates/advanced/gradlew.bat b/addon-templates/advanced/gradlew.bat new file mode 100644 index 0000000..c4bdd3a --- /dev/null +++ b/addon-templates/advanced/gradlew.bat @@ -0,0 +1,93 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/addon-templates/advanced/settings.gradle.kts b/addon-templates/advanced/settings.gradle.kts new file mode 100644 index 0000000..e87b8f9 --- /dev/null +++ b/addon-templates/advanced/settings.gradle.kts @@ -0,0 +1,9 @@ +pluginManagement { + repositories { + maven("https://maven.fabricmc.net/") { name = "Fabric" } + mavenCentral() + gradlePluginPortal() + } +} + +rootProject.name = "autism-advanced-addon-template" diff --git a/addon-templates/advanced/src/main/java/com/example/addon/ExampleAddon.java b/addon-templates/advanced/src/main/java/com/example/addon/ExampleAddon.java new file mode 100644 index 0000000..f8c7215 --- /dev/null +++ b/addon-templates/advanced/src/main/java/com/example/addon/ExampleAddon.java @@ -0,0 +1,53 @@ +package com.example.addon; + +import autismclient.api.AutismAddon; +import autismclient.api.AutismAddons; +import autismclient.api.ApiVersion; +import autismclient.api.macro.MacroActionEntry; + +import com.example.addon.commands.ExampleCommand; +import com.example.addon.events.ExampleEvents; +import com.example.addon.hud.ExampleHud; +import com.example.addon.macro.ExampleHeightCondition; +import com.example.addon.macro.ExamplePresets; +import com.example.addon.macro.ExampleSayAction; +import com.example.addon.modules.ExampleModule; + +// Addon entrypoint (the "autism" entrypoint in fabric.mod.json). Start small: +// register only ExampleModule first, launch the client, then add macro/actions/HUD/events as needed. +// Modules, actions, conditions and presets all auto-group under a category named after this addon. +public final class ExampleAddon extends AutismAddon { + public static final String ID = "autism-advanced-addon-template"; + + @Override + public int apiVersion() { + return ApiVersion.CURRENT; + } + + @Override + public void onInitialize() { + AutismAddons.modules().register(new ExampleModule()); + + // Action: appears in the "add action" picker. + AutismAddons.macroActions().register(MacroActionEntry.local("say", ExampleSayAction::new) + .picker("Say", "Send a chat message.") + .build()); + + // Condition: appears in the "add condition" picker (it waits). + AutismAddons.macroActions().register(MacroActionEntry.local("wait-height", ExampleHeightCondition::new) + .condition("Wait Height", "Wait until the player is at or above a Y level.") + .build()); + + AutismAddons.presets().register("Reach Height", "Wait for Y 80, then say.", + ExamplePresets::reachHeightThenSay); + + AutismAddons.commands().register(new ExampleCommand()); + AutismAddons.hud().register(new ExampleHud()); + ExampleEvents.register(); + } + + @Override + public String getPackage() { + return "com.example.addon"; + } +} diff --git a/addon-templates/advanced/src/main/java/com/example/addon/ExampleInit.java b/addon-templates/advanced/src/main/java/com/example/addon/ExampleInit.java new file mode 100644 index 0000000..26326ba --- /dev/null +++ b/addon-templates/advanced/src/main/java/com/example/addon/ExampleInit.java @@ -0,0 +1,9 @@ +package com.example.addon; + +import net.fabricmc.api.ClientModInitializer; + +// Fabric's required client entrypoint. The addon's real work is in ExampleAddon. +public final class ExampleInit implements ClientModInitializer { + @Override + public void onInitializeClient() {} +} diff --git a/addon-templates/advanced/src/main/java/com/example/addon/commands/ExampleCommand.java b/addon-templates/advanced/src/main/java/com/example/addon/commands/ExampleCommand.java new file mode 100644 index 0000000..c888baf --- /dev/null +++ b/addon-templates/advanced/src/main/java/com/example/addon/commands/ExampleCommand.java @@ -0,0 +1,29 @@ +package com.example.addon.commands; + +import autismclient.commands.AutismCommandSource; +import autismclient.commands.Command; +import autismclient.util.AutismClientMessaging; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; + +// A Brigadier command. Users run it with the command prefix, e.g. .example or .example hi. +public final class ExampleCommand extends Command { + public ExampleCommand() { + super("example", "Example addon command."); + } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + AutismClientMessaging.sendPrefixed("\u00a7dExample addon command works!"); + return SUCCESS; + }); + + root.then(RequiredArgumentBuilder.argument("text", StringArgumentType.greedyString()) + .executes(ctx -> { + AutismClientMessaging.sendPrefixed("\u00a7dYou said: \u00a7f" + StringArgumentType.getString(ctx, "text")); + return SUCCESS; + })); + } +} diff --git a/addon-templates/advanced/src/main/java/com/example/addon/events/ExampleEvents.java b/addon-templates/advanced/src/main/java/com/example/addon/events/ExampleEvents.java new file mode 100644 index 0000000..7901354 --- /dev/null +++ b/addon-templates/advanced/src/main/java/com/example/addon/events/ExampleEvents.java @@ -0,0 +1,15 @@ +package com.example.addon.events; + +import autismclient.api.AutismAddons; +import autismclient.util.AutismClientMessaging; + +// Event hooks. Register listeners once in onInitialize(). +// Available: onTick, onPacketSend (return true to cancel), onPacketReceive, onGameJoin, onGameLeft. +public final class ExampleEvents { + private ExampleEvents() {} + + public static void register() { + AutismAddons.events().onGameJoin(() -> + AutismClientMessaging.sendPrefixed("\u00a7a[Example] joined a world!")); + } +} diff --git a/addon-templates/advanced/src/main/java/com/example/addon/hud/ExampleHud.java b/addon-templates/advanced/src/main/java/com/example/addon/hud/ExampleHud.java new file mode 100644 index 0000000..5b311b0 --- /dev/null +++ b/addon-templates/advanced/src/main/java/com/example/addon/hud/ExampleHud.java @@ -0,0 +1,43 @@ +package com.example.addon.hud; + +import com.example.addon.ExampleAddon; +import autismclient.api.hud.HudElementProvider; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphicsExtractor; + +// A HUD element. Report your size via width()/height(); draw in render() with the GuiGraphicsExtractor +// (ctx.text / ctx.fill). The defaultX/Y/anchor/enabled are used until the user moves it in the HUD editor. +public final class ExampleHud implements HudElementProvider { + private static final int MIN_WIDTH = 94; + private static final int TEXT_PAD = 2; + + @Override public String id() { return ExampleAddon.ID + ":clock"; } + @Override public String label() { return "Example Clock"; } + @Override public String description() { return "Shows the in-game tick."; } + + @Override + public int width() { + Font font = Minecraft.getInstance().font; + String text = text(); + int textWidth = font != null ? font.width(text) : text.length() * 6; + return Math.max(MIN_WIDTH, textWidth + TEXT_PAD * 2); + } + + @Override public int height() { return 10; } + + @Override + public void render(GuiGraphicsExtractor ctx, Font font, int x, int y, float alpha) { + ctx.text(font, text(), x + TEXT_PAD, y, 0xFFFFD7FF); + } + + private static String text() { + long tick = Minecraft.getInstance().level != null ? Minecraft.getInstance().level.getGameTime() : 0L; + return "Addon tick: " + tick; + } + + @Override public boolean defaultEnabled() { return false; } + @Override public String defaultAnchor() { return "TOP_LEFT"; } + @Override public int defaultX() { return 4; } + @Override public int defaultY() { return 120; } +} diff --git a/addon-templates/advanced/src/main/java/com/example/addon/macro/ExampleCondition.java b/addon-templates/advanced/src/main/java/com/example/addon/macro/ExampleCondition.java new file mode 100644 index 0000000..bc79373 --- /dev/null +++ b/addon-templates/advanced/src/main/java/com/example/addon/macro/ExampleCondition.java @@ -0,0 +1,18 @@ +package com.example.addon.macro; + +import autismclient.api.macro.AddonCondition; +import net.minecraft.client.Minecraft; + +// A reusable predicate: implement check(). A waiting step blocks on it via ctx.awaitCondition(...). +public final class ExampleCondition extends AddonCondition { + private final double minY; + + public ExampleCondition(double minY) { + this.minY = minY; + } + + @Override + public boolean check(Minecraft mc) { + return mc.player != null && mc.player.getY() >= minY; + } +} diff --git a/addon-templates/advanced/src/main/java/com/example/addon/macro/ExampleHeightCondition.java b/addon-templates/advanced/src/main/java/com/example/addon/macro/ExampleHeightCondition.java new file mode 100644 index 0000000..0ce20e7 --- /dev/null +++ b/addon-templates/advanced/src/main/java/com/example/addon/macro/ExampleHeightCondition.java @@ -0,0 +1,50 @@ +package com.example.addon.macro; + +import com.example.addon.ExampleAddon; +import autismclient.api.macro.ActionSchema; +import autismclient.api.macro.AddonContextAction; +import autismclient.api.macro.MacroExecutionContext; +import net.minecraft.nbt.CompoundTag; + +// A macro condition: a step that waits. Extend AddonContextAction and block in run(), e.g. with +// ctx.awaitCondition(...). Register it with .condition(...) so it lands in the condition picker. +public final class ExampleHeightCondition extends AddonContextAction { + public static final String TYPE_ID = ExampleAddon.ID + ":wait-height"; + + public double minY = 64.0; + + public ExampleHeightCondition() { + super(TYPE_ID); + } + + @Override + public void run(MacroExecutionContext ctx) throws InterruptedException { + ctx.setStatus("Waiting until Y >= " + minY); + ctx.awaitCondition(new ExampleCondition(minY)); + } + + @Override + protected void save(CompoundTag tag) { + putDouble(tag, "minY", minY); + } + + @Override + protected void load(CompoundTag tag) { + minY = getDouble(tag, "minY", minY); + } + + @Override + protected ActionSchema schema() { + return ActionSchema.builder().decimal("minY", "Min Y").decRange(-64, 320).build(); + } + + @Override + public String getDisplayName() { + return "Wait until Y >= " + minY; + } + + @Override + public String getIcon() { + return "Y"; + } +} diff --git a/addon-templates/advanced/src/main/java/com/example/addon/macro/ExamplePresets.java b/addon-templates/advanced/src/main/java/com/example/addon/macro/ExamplePresets.java new file mode 100644 index 0000000..d414126 --- /dev/null +++ b/addon-templates/advanced/src/main/java/com/example/addon/macro/ExamplePresets.java @@ -0,0 +1,26 @@ +package com.example.addon.macro; + +import autismclient.util.macro.MacroAction; + +import java.util.ArrayList; +import java.util.List; + +// Presets insert a ready-made stack of steps. Return a fresh list each call; don't reuse instances. +public final class ExamplePresets { + private ExamplePresets() {} + + // Wait until the player is high up, then announce it. + public static List reachHeightThenSay() { + List stack = new ArrayList<>(); + + ExampleHeightCondition waitForHeight = new ExampleHeightCondition(); + waitForHeight.minY = 80.0; + stack.add(waitForHeight); + + ExampleSayAction say = new ExampleSayAction(); + say.message = "Reached Y 80!"; + stack.add(say); + + return stack; + } +} diff --git a/addon-templates/advanced/src/main/java/com/example/addon/macro/ExampleSayAction.java b/addon-templates/advanced/src/main/java/com/example/addon/macro/ExampleSayAction.java new file mode 100644 index 0000000..ed096f0 --- /dev/null +++ b/addon-templates/advanced/src/main/java/com/example/addon/macro/ExampleSayAction.java @@ -0,0 +1,50 @@ +package com.example.addon.macro; + +import com.example.addon.ExampleAddon; +import autismclient.api.macro.ActionSchema; +import autismclient.api.macro.AddonAction; +import autismclient.util.AutismClientMessaging; +import net.minecraft.client.Minecraft; +import net.minecraft.nbt.CompoundTag; + +// A macro action: runs once when the step is reached. Extend AddonAction and pass a namespaced id. +public final class ExampleSayAction extends AddonAction { + public static final String TYPE_ID = ExampleAddon.ID + ":say"; + + public String message = "Hello from an addon!"; + + public ExampleSayAction() { + super(TYPE_ID); + } + + @Override + protected void run(Minecraft mc) { + AutismClientMessaging.sendPrefixed("\u00a7d[Example] " + message); + } + + // Field keys here, in load(), and in the schema must match. + @Override + protected void save(CompoundTag tag) { + putString(tag, "message", message); + } + + @Override + protected void load(CompoundTag tag) { + message = getString(tag, "message", message); + } + + @Override + protected ActionSchema schema() { + return ActionSchema.builder().text("message", "Say").build(); + } + + @Override + public String getDisplayName() { + return "Say: " + message; + } + + @Override + public String getIcon() { + return "S"; + } +} diff --git a/addon-templates/advanced/src/main/java/com/example/addon/mixin/ExampleMixin.java b/addon-templates/advanced/src/main/java/com/example/addon/mixin/ExampleMixin.java new file mode 100644 index 0000000..bb0d609 --- /dev/null +++ b/addon-templates/advanced/src/main/java/com/example/addon/mixin/ExampleMixin.java @@ -0,0 +1,19 @@ +package com.example.addon.mixin; + +import com.example.addon.ExampleAddon; +import net.minecraft.client.Minecraft; +import net.minecraft.client.main.GameConfig; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +// Example mixin. List your mixin classes in autism-advanced-addon-template.mixins.json (referenced from +// fabric.mod.json). An @Inject handler matches the target method's params, then CallbackInfo. +@Mixin(Minecraft.class) +public abstract class ExampleMixin { + @Inject(method = "", at = @At("TAIL")) + private void onClientInit(GameConfig gameConfig, CallbackInfo ci) { + org.slf4j.LoggerFactory.getLogger(ExampleAddon.ID).info("Hello from ExampleMixin!"); + } +} diff --git a/addon-templates/advanced/src/main/java/com/example/addon/modules/ExampleModule.java b/addon-templates/advanced/src/main/java/com/example/addon/modules/ExampleModule.java new file mode 100644 index 0000000..82b0b0f --- /dev/null +++ b/addon-templates/advanced/src/main/java/com/example/addon/modules/ExampleModule.java @@ -0,0 +1,41 @@ +package com.example.addon.modules; + +import com.example.addon.ExampleAddon; +import autismclient.api.module.BoolSetting; +import autismclient.api.module.EnumSetting; +import autismclient.api.module.IntSetting; +import autismclient.modules.Module; +import autismclient.util.AutismClientMessaging; + +import java.util.Locale; + +// A toggleable module built on the typed setting API. Declare each setting as a final field with +// add(new XSetting(...)) and read it at runtime with field.get() — no string ids, no casting. An EnumSetting +// is backed by a real enum, so reads are compiler-checked (style.get() == Style.LOUD). Visibility is a plain +// predicate over other settings. With no category, the module auto-lands under a menu column named after your addon. +public final class ExampleModule extends Module { + public enum Style { FRIENDLY, LOUD } + + private final BoolSetting greet = add(new BoolSetting("greet", "Greet on enable", true) + .group("General")); + private final IntSetting amount = add(new IntSetting("amount", "Amount", 3, 1, 10, 1) + .group("General")); + private final EnumSetting + + + + + \ No newline at end of file diff --git a/assets/icons/Fabricator.svg b/assets/icons/Fabricator.svg new file mode 100644 index 0000000..09a5488 --- /dev/null +++ b/assets/icons/Fabricator.svg @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/assets/icons/Filter.svg b/assets/icons/Filter.svg new file mode 100644 index 0000000..fdd653b --- /dev/null +++ b/assets/icons/Filter.svg @@ -0,0 +1,12 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/icons/Keybinds.svg b/assets/icons/Keybinds.svg new file mode 100644 index 0000000..9831a47 --- /dev/null +++ b/assets/icons/Keybinds.svg @@ -0,0 +1,26 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/assets/icons/Lansync.svg b/assets/icons/Lansync.svg new file mode 100644 index 0000000..fcec3f9 --- /dev/null +++ b/assets/icons/Lansync.svg @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/assets/icons/Macros.svg b/assets/icons/Macros.svg new file mode 100644 index 0000000..fecf319 --- /dev/null +++ b/assets/icons/Macros.svg @@ -0,0 +1,15 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/icons/MainMenuCategory.svg b/assets/icons/MainMenuCategory.svg new file mode 100644 index 0000000..d577140 --- /dev/null +++ b/assets/icons/MainMenuCategory.svg @@ -0,0 +1,17 @@ + + + + + + + + + + \ No newline at end of file diff --git a/assets/icons/Matchmaking.png b/assets/icons/Matchmaking.png new file mode 100644 index 0000000..7d86a63 Binary files /dev/null and b/assets/icons/Matchmaking.png differ diff --git a/assets/icons/Matchmaking.svg b/assets/icons/Matchmaking.svg new file mode 100644 index 0000000..16b3440 --- /dev/null +++ b/assets/icons/Matchmaking.svg @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/assets/icons/Multi.png b/assets/icons/Multi.png new file mode 100644 index 0000000..8a8d07c Binary files /dev/null and b/assets/icons/Multi.png differ diff --git a/assets/icons/PacketCategory.svg b/assets/icons/PacketCategory.svg new file mode 100644 index 0000000..d337416 --- /dev/null +++ b/assets/icons/PacketCategory.svg @@ -0,0 +1,15 @@ + + + + + + + + \ No newline at end of file diff --git a/assets/icons/PacketQEditor.svg b/assets/icons/PacketQEditor.svg new file mode 100644 index 0000000..930c3a4 --- /dev/null +++ b/assets/icons/PacketQEditor.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/assets/icons/Packetlogger.svg b/assets/icons/Packetlogger.svg new file mode 100644 index 0000000..90fa46e --- /dev/null +++ b/assets/icons/Packetlogger.svg @@ -0,0 +1,18 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/assets/icons/Profiles.svg b/assets/icons/Profiles.svg new file mode 100644 index 0000000..a510190 --- /dev/null +++ b/assets/icons/Profiles.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/ScreenCategory.svg b/assets/icons/ScreenCategory.svg new file mode 100644 index 0000000..b9e5bbc --- /dev/null +++ b/assets/icons/ScreenCategory.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/assets/icons/Serverinfo.svg b/assets/icons/Serverinfo.svg new file mode 100644 index 0000000..c166006 --- /dev/null +++ b/assets/icons/Serverinfo.svg @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..dc5d329 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,704 @@ +import java.io.OutputStream +import java.util.zip.ZipFile + +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath("org.apache.xmlgraphics:batik-transcoder:1.17") + classpath("org.apache.xmlgraphics:batik-codec:1.17") + } +} + +plugins { + alias(libs.plugins.fabric.loom) + `maven-publish` +} + +base { + archivesName = properties["archives_base_name"] as String + // Version = "-" (e.g. 3.1-26.2). Dev/source builds add a "-dev" suffix so they're distinguishable + // from a tagged release; a release is built with: gradlew build -Prelease + version = libs.versions.mod.version.get() + "-" + libs.versions.minecraft.get() + + (if (project.hasProperty("release")) "" else "-dev") + group = properties["maven_group"] as String +} + +repositories { + mavenCentral() +} + +dependencies { + + minecraft(libs.minecraft) + implementation(libs.fabric.loader) + implementation(libs.fabric.api) + + implementation("net.java.dev.jna:jna:5.13.0") + implementation("net.java.dev.jna:jna-platform:5.13.0") + implementation("io.netty:netty-handler-proxy:4.1.118.Final") + implementation("io.netty:netty-codec-socks:4.1.118.Final") + include("io.netty:netty-handler-proxy:4.1.118.Final") + include("io.netty:netty-codec-socks:4.1.118.Final") + implementation("de.florianreuth:waybackauthlib:1.1.0") + include("de.florianreuth:waybackauthlib:1.1.0") + implementation("com.github.weisj:jsvg:2.1.0") + include("com.github.weisj:jsvg:2.1.0") + + // Eclipse Paho MQTT client (standalone, no transitive deps) — powers the redundant MQTT relay mesh + // (EMQX/HiveMQ public brokers over secure WebSocket) so the encrypted matchmaking transport survives any + // single public service timing out. Bundled jar-in-jar like the other runtime libs. + implementation("org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5") + include("org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5") + + // Bundle a newer MixinExtras (jar-in-jar) so Fabric Loader loads it over the old 0.5.0 it ships + // with. Required because ViaFabricPlus (and our own WrapOperation/ModifyExpressionValue mixins) + // need MixinExtras >= 0.5.3; without this, joining a server crashes during mixin application. + implementation("io.github.llamalad7:mixinextras-fabric:0.5.4") + include("io.github.llamalad7:mixinextras-fabric:0.5.4") + + testImplementation(platform("org.junit:junit-bom:5.11.4")) + testImplementation("org.junit.jupiter:junit-jupiter") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") + +} + +tasks.test { + useJUnitPlatform() +} + +val generatedAutismResourcesDir = layout.buildDirectory.dir("generated/resources/autism/main") + +data class SourceFile(val path: String, val text: String) +data class FieldSpec(val name: String, val type: String, val kind: String, val editable: Boolean) +data class PacketSpec( + val className: String, + val protocol: String, + val direction: String, + val codecStyle: String, + val packetType: String, + val source: String, + val complete: Boolean, + val fields: List +) + +sourceSets { + main { + resources.srcDir(generatedAutismResourcesDir) + } +} + + +val generateVanillaUiAssets by tasks.registering { + // Semantic feature icons used by the vanilla-friendly UI. Structural + // actions such as close and reorder are rendered as text symbols. + val iconSourceDir = file("assets/icons") + val outputDir = generatedAutismResourcesDir.map { it.dir("assets/autismclient") } + + inputs.dir(iconSourceDir) + outputs.dir(outputDir) + + doLast { + val targetRoot = outputDir.get().asFile + targetRoot.parentFile.resolve("yu" + "ng" + "light").deleteRecursively() + targetRoot.deleteRecursively() + val iconTargetDir = targetRoot.resolve("textures/gui/vanillaui/icons") + + iconTargetDir.mkdirs() + + val pngTranscoderClass = Class.forName("org.apache.batik.transcoder.image.PNGTranscoder") + val transcoderInputClass = Class.forName("org.apache.batik.transcoder.TranscoderInput") + val transcoderOutputClass = Class.forName("org.apache.batik.transcoder.TranscoderOutput") + val transcodingHintsKeyClass = Class.forName("org.apache.batik.transcoder.TranscodingHints\$Key") + + val transcoder = pngTranscoderClass.getDeclaredConstructor().newInstance() + val widthField = pngTranscoderClass.getField("KEY_WIDTH") + val heightField = pngTranscoderClass.getField("KEY_HEIGHT") + val addHint = pngTranscoderClass.getMethod("addTranscodingHint", transcodingHintsKeyClass, Any::class.java) + addHint.invoke(transcoder, widthField.get(null), 256f) + addHint.invoke(transcoder, heightField.get(null), 256f) + + val inputCtor = transcoderInputClass.getConstructor(String::class.java) + val outputCtor = transcoderOutputClass.getConstructor(OutputStream::class.java) + val transcode = pngTranscoderClass.getMethod("transcode", transcoderInputClass, transcoderOutputClass) + + iconSourceDir.listFiles { file -> file.isFile && file.extension.equals("svg", ignoreCase = true) } + ?.sortedBy { it.name.lowercase() } + ?.forEach { svg -> + val outputFile = iconTargetDir.resolve(svg.nameWithoutExtension.lowercase() + ".png") + outputFile.outputStream().use { out -> + val input = inputCtor.newInstance(svg.toURI().toString()) + val output = outputCtor.newInstance(out) + transcode.invoke(transcoder, input, output) + } + } + + // Raster icons committed directly as PNG (e.g. the Matchmaking logo) are copied as-is; the engine + // recolors/whitens them at draw time just like the SVG-derived icons. + iconSourceDir.listFiles { file -> file.isFile && file.extension.equals("png", ignoreCase = true) } + ?.sortedBy { it.name.lowercase() } + ?.forEach { png -> + png.copyTo(iconTargetDir.resolve(png.nameWithoutExtension.lowercase() + ".png"), overwrite = true) + } + } +} + +val generateAutismInspectorMappings by tasks.registering { + val mappingFiles = fileTree(".gradle/loom-cache/source_mappings") { + include("**/*.tiny") + } + val outputFile = generatedAutismResourcesDir.map { it.file("autism-inspector-mappings.tsv") } + + inputs.files(mappingFiles) + outputs.file(outputFile) + + doLast { + run { + val target = outputFile.get().asFile + target.parentFile.mkdirs() + target.writeText( + "# Official Mojang mappings are used for Minecraft ${libs.versions.minecraft.get()}; no Yarn aliases are generated.\n", + Charsets.UTF_8 + ) + return@doLast + } + + val tinyFile = mappingFiles.files + .filter { it.isFile } + .maxByOrNull { it.lastModified() } + ?: error("Missing Loom source mappings under ${project.file(".gradle/loom-cache/source_mappings").absolutePath}") + + val lines = tinyFile.readLines(Charsets.UTF_8) + val header = lines.firstOrNull { it.startsWith("tiny\t") } + ?: error("Invalid tiny mapping file: ${tinyFile.absolutePath}") + val namespaces = header.split('\t').drop(3) + val namedIndex = namespaces.indexOf("named") + val intermediaryIndex = namespaces.indexOf("intermediary") + require(namedIndex >= 0 && intermediaryIndex >= 0) { + "Tiny mapping header must expose named and intermediary namespaces: $header" + } + + fun readNamespace(parts: List, baseOffset: Int, namespaceIndex: Int): String { + val index = baseOffset + namespaceIndex + return if (index in parts.indices) parts[index].trim() else "" + } + + val namedToIntermediary = linkedMapOf() + val classAliases = linkedMapOf() + + for (raw in lines) { + val trimmed = raw.trimStart('\t') + if (!trimmed.startsWith("c\t")) continue + val parts = trimmed.split('\t') + val namedName = readNamespace(parts, 1, namedIndex) + val intermediaryName = readNamespace(parts, 1, intermediaryIndex) + if (namedName.isBlank() || intermediaryName.isBlank()) continue + namedToIntermediary[namedName] = intermediaryName + classAliases[intermediaryName.replace('/', '.')] = namedName.substringAfterLast('/').replace('$', '.') + } + + fun remapDescriptorToIntermediary(descriptor: String): String { + if (descriptor.isBlank()) return descriptor + val classRef = Regex("L([^;]+);") + return classRef.replace(descriptor) { match -> + val namedInternalName = match.groupValues[1] + val intermediaryInternalName = namedToIntermediary[namedInternalName] ?: namedInternalName + "L$intermediaryInternalName;" + } + } + + fun storeAlias( + target: MutableMap, + ambiguous: MutableSet, + key: String, + alias: String + ) { + if (key.isBlank() || alias.isBlank() || ambiguous.contains(key)) return + val existing = target[key] + if (existing == null) { + target[key] = alias + return + } + if (existing != alias) { + target.remove(key) + ambiguous.add(key) + } + } + + val fieldAliases = linkedMapOf() + val methodAliases = linkedMapOf() + val ambiguousFieldKeys = linkedSetOf() + val ambiguousMethodKeys = linkedSetOf() + + var currentOwner = "" + for (raw in lines) { + val trimmed = raw.trimStart('\t') + if (trimmed.isBlank()) continue + val parts = trimmed.split('\t') + when (parts.firstOrNull()) { + "c" -> { + currentOwner = readNamespace(parts, 1, intermediaryIndex).replace('/', '.') + } + + "f" -> { + if (currentOwner.isBlank()) continue + val descriptor = if (parts.size > 1) remapDescriptorToIntermediary(parts[1]) else "" + val namedName = readNamespace(parts, 2, namedIndex) + val intermediaryName = readNamespace(parts, 2, intermediaryIndex) + if (namedName.isBlank() || intermediaryName.isBlank()) continue + storeAlias(fieldAliases, ambiguousFieldKeys, "$currentOwner#$intermediaryName#$descriptor", namedName) + } + + "m" -> { + if (currentOwner.isBlank()) continue + val descriptor = if (parts.size > 1) remapDescriptorToIntermediary(parts[1]) else "" + val namedName = readNamespace(parts, 2, namedIndex) + val intermediaryName = readNamespace(parts, 2, intermediaryIndex) + if (namedName.isBlank() || intermediaryName.isBlank()) continue + if (namedName == "" || namedName == "") continue + storeAlias(methodAliases, ambiguousMethodKeys, "$currentOwner#$intermediaryName#$descriptor", namedName) + } + } + } + + val authAliasFragments = listOf( + "session", "accesstoken", "refreshtoken", "authtoken", + "clientsession", "playersession", "publicsession" + ) + fun isAuthAlias(alias: String): Boolean { + val normalized = alias.lowercase().replace(Regex("[^a-z0-9]"), "") + return authAliasFragments.any { normalized.contains(it) } + } + + val filteredClassAliases = classAliases.filter { (_, alias) -> !isAuthAlias(alias) } + val blockedOwners = classAliases.keys.filter { owner -> + val alias = classAliases[owner] ?: return@filter false + isAuthAlias(alias) + }.toSet() + + val target = outputFile.get().asFile + target.parentFile.mkdirs() + target.printWriter(Charsets.UTF_8).use { out -> + out.println("# Yarn deobfuscation mappings") + filteredClassAliases.toSortedMap().forEach { (owner, alias) -> + out.println("C\t$owner\t$alias") + } + fieldAliases.toSortedMap().forEach { (key, alias) -> + val parts = key.split('#', limit = 3) + if (parts.size == 3 && !blockedOwners.contains(parts[0]) && !isAuthAlias(alias)) { + out.println("F\t${parts[0]}\t${parts[1]}\t${parts[2]}\t$alias") + } + } + methodAliases.toSortedMap().forEach { (key, alias) -> + val parts = key.split('#', limit = 3) + if (parts.size == 3 && !blockedOwners.contains(parts[0]) && !isAuthAlias(alias)) { + out.println("M\t${parts[0]}\t${parts[1]}\t${parts[2]}\t$alias") + } + } + } + } +} + +val generateAutismPacketSchemas by tasks.registering { + val minecraftVersion = libs.versions.minecraft.get() + val outputFile = generatedAutismResourcesDir.map { it.file("autism-packet-schemas.tsv") } + + outputs.file(outputFile) + + doLast { + fun normalizeWhitespace(value: String): String = value.replace(Regex("\\s+"), " ").trim() + + fun splitTopLevelComma(value: String): List { + val out = mutableListOf() + var depth = 0 + var start = 0 + for (i in value.indices) { + when (value[i]) { + '<', '(', '[', '{' -> depth++ + '>', ')', ']', '}' -> if (depth > 0) depth-- + ',' -> if (depth == 0) { + out += value.substring(start, i).trim() + start = i + 1 + } + } + } + val tail = value.substring(start).trim() + if (tail.isNotBlank()) out += tail + return out + } + + fun protocolFromPath(path: String): String { + val normalized = path.replace('\\', '/') + val marker = "/network/protocol/" + val idx = normalized.indexOf(marker) + val tail = if (idx >= 0) normalized.substring(idx + marker.length) else normalized.substringAfter("net/minecraft/network/protocol/", "") + return tail.substringBefore('/').ifBlank { "unknown" } + } + + fun directionFromName(simpleName: String): String = when { + simpleName.startsWith("Clientbound") -> "S2C" + simpleName.startsWith("Serverbound") -> "C2S" + else -> "ANY" + } + + fun kindForType(type: String): String { + val lower = type.lowercase() + return when { + lower == "byte" || lower == "short" || lower == "int" || lower == "long" || lower == "float" || lower == "double" -> "number" + lower == "boolean" -> "boolean" + lower == "string" -> "string" + lower.contains("itemstack") || lower.contains("hashedstack") -> "item" + lower.contains("component") -> "component" + lower.contains("identifier") || lower.contains("resourcekey") -> "identifier" + lower.contains("holder<") || lower == "holder" -> "holder" + lower.contains("blockpos") || lower.contains("chunkpos") -> "position" + lower.contains("vec3") || lower.contains("positionmoverotation") -> "vector" + lower.contains("uuid") -> "uuid" + lower.startsWith("optional<") || lower.contains(".optional<") -> "optional" + lower.startsWith("list<") || lower.startsWith("set<") || lower.contains("list<") || lower.contains("set<") -> "list" + lower.startsWith("map<") || lower.contains("map<") || lower.contains("int2objectmap") -> "map" + lower.contains("bitset") -> "bitset" + lower.contains("enumset") || lower.contains("relative") || lower.contains("containerinput") -> "enum" + else -> "object" + } + } + + fun editableFor(kind: String): Boolean = kind in setOf("number", "boolean", "string", "identifier", "enum", "uuid") + + fun parseComponent(raw: String): FieldSpec? { + val cleaned = normalizeWhitespace(raw) + .replace(Regex("^@[\\w.]+(?:\\([^)]*\\))?\\s+"), "") + val idx = cleaned.lastIndexOf(' ') + if (idx <= 0 || idx >= cleaned.length - 1) return null + val type = cleaned.substring(0, idx).trim() + val name = cleaned.substring(idx + 1).trim().removeSuffix("...") + if (!name.matches(Regex("[A-Za-z_$][A-Za-z0-9_$]*"))) return null + val kind = kindForType(type) + return FieldSpec(name, type, kind, editableFor(kind)) + } + + fun parseFields(text: String): Pair> { + val record = Regex("""public\s+record\s+\w+\s*\((.*?)\)\s*implements""", setOf(RegexOption.DOT_MATCHES_ALL)) + .find(text) + if (record != null) { + val fields = splitTopLevelComma(record.groupValues[1]).mapNotNull(::parseComponent) + return "record" to fields + } + + val fields = Regex("""(?m)^\s*(?:private|protected)\s+final\s+([^;=]+?)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*;""") + .findAll(text) + .mapNotNull { match -> + val type = normalizeWhitespace(match.groupValues[1]) + val name = match.groupValues[2] + val kind = kindForType(type) + FieldSpec(name, type, kind, editableFor(kind)) + } + .toList() + return if (fields.isNotEmpty()) "fields" to fields else "fallback" to emptyList() + } + + fun loadSources(): List { + val sourcesJar = file("${System.getProperty("user.home")}/.gradle/caches/fabric-loom/minecraftMaven/net/minecraft/minecraft-merged-deobf/$minecraftVersion/minecraft-merged-deobf-$minecraftVersion-sources.jar") + val loomCacheSourceJar = file(".gradle/loom-cache/minecraftMaven/net/minecraft") + .takeIf { it.isDirectory } + ?.walkTopDown() + ?.firstOrNull { file -> + file.isFile && + file.name.endsWith("-$minecraftVersion-sources.jar") && + file.invariantSeparatorsPath.contains("/minecraft-merged-") + } + val sourceArchive = when { + sourcesJar.isFile -> sourcesJar + loomCacheSourceJar != null -> loomCacheSourceJar + else -> null + } + if (sourceArchive != null) { + ZipFile(sourceArchive).use { zip -> + return zip.entries().asSequence() + .filter { !it.isDirectory } + .filter { it.name.startsWith("net/minecraft/network/protocol/") && it.name.endsWith("Packet.java") } + .map { entry -> + SourceFile(entry.name, zip.getInputStream(entry).bufferedReader(Charsets.UTF_8).use { it.readText() }) + } + .toList() + } + } + + val localRoot = file("mc-src$minecraftVersion/libs/net.minecraft.minecraft-merged-deobf/net/minecraft/network/protocol") + if (localRoot.isDirectory) { + return localRoot.walkTopDown() + .filter { it.isFile && it.name.endsWith("Packet.java") } + .map { file -> + SourceFile(file.relativeTo(localRoot.parentFile.parentFile.parentFile.parentFile).invariantSeparatorsPath, file.readText(Charsets.UTF_8)) + } + .toList() + } + + logger.warn("Minecraft packet sources are unavailable for $minecraftVersion; generating an empty packet schema resource and using runtime fallback decoding.") + return emptyList() + } + + fun packetTypeOf(text: String): String { + return Regex("""return\s+([A-Za-z0-9_]+PacketTypes\.[A-Z0-9_]+)\s*;""") + .find(text) + ?.groupValues + ?.get(1) + ?: "" + } + + fun codecStyleOf(text: String): String = when { + text.contains("StreamCodec.unit") -> "UNIT" + text.contains("StreamCodec.composite") -> "COMPOSITE" + text.contains("Packet.codec") -> "PACKET_CODEC" + else -> "CUSTOM" + } + + fun escape(value: String): String = value + .replace('\t', ' ') + .replace('\n', ' ') + .replace('|', '/') + .replace('~', '-') + + val specs = loadSources().mapNotNull { source -> + val pkg = Regex("""package\s+([A-Za-z0-9_.]+)\s*;""").find(source.text)?.groupValues?.get(1) ?: return@mapNotNull null + val simpleName = Regex("""public\s+(?:abstract\s+)?(?:record|class)\s+([A-Za-z0-9_]+Packet)\b""") + .find(source.text) + ?.groupValues + ?.get(1) + ?: return@mapNotNull null + val codecStyle = codecStyleOf(source.text) + val parsed = parseFields(source.text) + val sourceKind = if (codecStyle == "UNIT") "unit" else parsed.first + val complete = codecStyle == "UNIT" || parsed.second.isNotEmpty() + PacketSpec( + "$pkg.$simpleName", + protocolFromPath(source.path), + directionFromName(simpleName), + codecStyle, + packetTypeOf(source.text), + sourceKind, + complete, + if (codecStyle == "UNIT") emptyList() else parsed.second + ) + }.sortedBy { it.className } + + val target = outputFile.get().asFile + target.parentFile.mkdirs() + target.printWriter(Charsets.UTF_8).use { out -> + out.println("# Generated from Minecraft $minecraftVersion packet sources. Fields preserve source/record order where available.") + out.println("# class\tprotocol\tdirection\tcodec\tpacketType\tsource\tcomplete\tfields(name~type~kind~editable|...)") + for (spec in specs) { + val fields = spec.fields.joinToString("|") { field -> + listOf(field.name, field.type, field.kind, field.editable.toString()).joinToString("~", transform = ::escape) + } + val columns = listOf( + spec.className, + spec.protocol, + spec.direction, + spec.codecStyle, + spec.packetType, + spec.source, + spec.complete.toString() + ).joinToString("\t", transform = ::escape) + out.println("$columns\t$fields") + } + } + } +} + +tasks { + processResources { + dependsOn(generateAutismInspectorMappings) + dependsOn(generateAutismPacketSchemas) + dependsOn(generateVanillaUiAssets) + val propertyMap = mapOf( + "version" to project.version, + "mc_version" to libs.versions.minecraft.get(), + "fabric_api_version" to libs.versions.fabric.api.get() + ) + + inputs.properties(propertyMap) + + filteringCharset = "UTF-8" + + exclude("addon-template.mixins.json") + exclude("assets/template/**") + + filesMatching("fabric.mod.json") { + expand(propertyMap) + } + } + + jar { + inputs.property("archivesName", project.base.archivesName.get()) + + from("LICENSE") { + rename { "${it}_${inputs.properties["archivesName"]}" } + } + + // ModMenu API is a compile-only soft dependency: we ship local stubs of its two API + // interfaces so we can compile the integration without a cross-version ModMenu artifact, but + // we must NOT bundle them — at runtime the real ModMenu provides them (and if ModMenu is + // absent, our integration entrypoint is simply never loaded). + exclude("com/terraformersmc/**") + } + + java { + sourceCompatibility = JavaVersion.VERSION_25 + targetCompatibility = JavaVersion.VERSION_25 + toolchain { + languageVersion.set(JavaLanguageVersion.of(25)) + } + } + + withType { + options.encoding = "UTF-8" + options.release.set(25) + options.compilerArgs.add("-Xlint:deprecation") + options.compilerArgs.add("-Xlint:unchecked") + options.compilerArgs.add("-Xlint:-restricted") + } +} + +// Publish the Loom-remapped jar to the local Maven repo so the standalone addon-template (and any +// third-party addon) can depend on it via `modImplementation("com.autismclient:autism:")`. +// Run: ./gradlew publishToMavenLocal +publishing { + publications { + create("mavenJava") { + groupId = "com.autismclient" + artifactId = "autism" + version = project.version.toString() + from(components["java"]) + } + } + repositories { + mavenLocal() + } +} + +// Pin the templates' versions to this client's. Runs on publishToMavenLocal. +val syncAddonTemplateVersions by tasks.registering { + group = "addon templates" + description = "Pin addon-templates/*/gradle/libs.versions.toml to this client's versions." + + val clientCatalog = rootDir.resolve("gradle/libs.versions.toml") + val templateCatalogs = listOf("minimal", "advanced").map { + rootDir.resolve("addon-templates/$it/gradle/libs.versions.toml") + } + inputs.file(clientCatalog) + outputs.files(templateCatalogs) + + doLast { + val client = clientCatalog.readText() + fun readVersion(key: String): String { + val m = Regex("(?m)^\\s*" + Regex.escape(key) + "\\s*=\\s*\"([^\"]*)\"").find(client) + ?: throw GradleException("Key '$key' not found in $clientCatalog") + return m.groupValues[1] + } + // the template's own mod-version is left alone + val values = linkedMapOf( + "minecraft" to readVersion("minecraft"), + "fabric-loader" to readVersion("fabric-loader"), + "fabric-api" to readVersion("fabric-api"), + "loom" to readVersion("loom"), + "autism" to readVersion("mod-version") + ) + templateCatalogs.forEach { file -> + if (!file.exists()) throw GradleException("Missing template catalog: $file") + var text = file.readText() + values.forEach { (key, value) -> + val re = Regex("(?m)^(\\s*" + Regex.escape(key) + "\\s*=\\s*\")[^\"]*(\")") + if (re.containsMatchIn(text)) { + text = re.replace(text) { mr -> mr.groupValues[1] + value + mr.groupValues[2] } + } else { + logger.warn("syncAddonTemplateVersions: '$key' not found in ${file.name}; skipped.") + } + } + file.writeText(text) + } + logger.lifecycle( + "Synced addon templates: minecraft=${values["minecraft"]}, fabric-loader=${values["fabric-loader"]}, " + + "fabric-api=${values["fabric-api"]}, loom=${values["loom"]}, autism=${values["autism"]}" + ) + } +} + +tasks.named("publishToMavenLocal") { + dependsOn(syncAddonTemplateVersions) +} + +// Scaffold/scan tasks call addon-toolkit.py (these need Python 3). Building needs no Python. +fun resolvePythonCommand(): List { + val isWindows = System.getProperty("os.name").lowercase().contains("win") + val candidates = if (isWindows) listOf(listOf("py", "-3"), listOf("python"), listOf("python3")) + else listOf(listOf("python3"), listOf("python")) + for (candidate in candidates) { + try { + if (ProcessBuilder(candidate + "--version").redirectErrorStream(true).start().waitFor() == 0) return candidate + } catch (_: Exception) { + } + } + throw GradleException("Python 3 was not found on PATH (needed for the addon toolkit tasks).") +} + +fun toolkitArgs(project: Project, action: String): List { + val args = mutableListOf( + project.rootDir.resolve("addon-templates/addon-toolkit.py").absolutePath, + action, + "--non-interactive", + ) + // gradleProperty, not findProperty: names like "project"/"name" clash with Project getters. + fun prop(name: String) = project.providers.gradleProperty(name).orNull?.takeIf { it.isNotBlank() } + args += listOf("--template", prop("template") ?: "minimal") + mapOf( + "name" to "--name", "out" to "--output", "project" to "--project", "addonId" to "--addon-id", + "package" to "--package", "author" to "--author", "description" to "--description", + "mavenGroup" to "--maven-group", "archiveName" to "--archive-name", "addonVersion" to "--addon-version", + ).forEach { (propName, flag) -> prop(propName)?.let { args += listOf(flag, it) } } + if (project.providers.gradleProperty("advanced").isPresent) args += "--advanced" + if (project.providers.gradleProperty("yes").isPresent) args += "--yes" + if (project.providers.gradleProperty("noPublish").isPresent) args += "--no-publish" + return args +} + +listOf( + Triple("newAddon", "setup", "Scaffold a new addon. Props: -Pname= -Ptemplate=minimal|advanced -Pout= (optional -PaddonId/-Ppackage/-Pauthor/-Padvanced)."), + Triple("scanAddon", "scan", "Validate one addon project. Prop: -Pproject=."), + Triple("validateAddons", "validate", "Validate the in-repo addon system and shipped templates."), + Triple("cleanAddon", "clean", "Delete an addon project's build/.gradle. Props: -Pproject= -Pyes."), +).forEach { (taskName, action, taskDescription) -> + tasks.register(taskName) { + group = "addon toolkit" + description = taskDescription + doLast { + val command = resolvePythonCommand() + toolkitArgs(project, action) + val process = ProcessBuilder(command).directory(project.rootDir).redirectErrorStream(true).start() + process.inputStream.bufferedReader().forEachLine { logger.lifecycle(it) } + val exit = process.waitFor() + if (exit != 0) throw GradleException("addon toolkit '$action' failed (exit code $exit).") + } + } +} + +// Pure Gradle, no Python: publish the API, then build each shipped template via its own wrapper. +tasks.register("buildAllTemplates") { + group = "addon toolkit" + description = "Publish the API locally and build both shipped templates (no Python needed)." + dependsOn("publishToMavenLocal") + doLast { + val isWindows = System.getProperty("os.name").lowercase().contains("win") + for (name in listOf("minimal", "advanced")) { + val dir = project.rootDir.resolve("addon-templates/$name") + val wrapper = dir.resolve(if (isWindows) "gradlew.bat" else "gradlew") + if (!wrapper.isFile) throw GradleException("Missing Gradle wrapper: $wrapper") + val cmd = if (!isWindows && !wrapper.canExecute()) listOf("sh", wrapper.absolutePath, "build") + else listOf(wrapper.absolutePath, "build") + logger.lifecycle("Building $name template") + val process = ProcessBuilder(cmd).directory(dir).redirectErrorStream(true).start() + process.inputStream.bufferedReader().forEachLine { logger.lifecycle(it) } + if (process.waitFor() != 0) throw GradleException("$name template build failed.") + } + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..f7d7443 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,5 @@ +org.gradle.jvmargs=-Xmx2G +org.gradle.configuration-cache=false + +maven_group=com.autismclient +archives_base_name=AUTISM Client diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..6448e4e --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,17 @@ +[versions] +mod-version = "3.4" + +minecraft = "26.2" +fabric-loader = "0.19.3" +fabric-api = "0.152.2+26.2" + +loom = "1.17.11" + +[libraries] + +minecraft = { module = "com.mojang:minecraft", version.ref = "minecraft" } +fabric-loader = { module = "net.fabricmc:fabric-loader", version.ref = "fabric-loader" } +fabric-api = { module = "net.fabricmc.fabric-api:fabric-api", version.ref = "fabric-api" } + +[plugins] +fabric-loom = { id = "net.fabricmc.fabric-loom", version.ref = "loom" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..f8e1ee3 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..5dd3c01 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..adff685 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..c4bdd3a --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,93 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..8937131 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,12 @@ +pluginManagement { + repositories { + maven { + name = "Fabric" + url = uri("https://maven.fabricmc.net/") + } + mavenCentral() + gradlePluginPortal() + } +} + +rootProject.name = "YungLightUI" diff --git a/src/main/java/autismclient/AutismClientAddon.java b/src/main/java/autismclient/AutismClientAddon.java new file mode 100644 index 0000000..5cafbb4 --- /dev/null +++ b/src/main/java/autismclient/AutismClientAddon.java @@ -0,0 +1,17 @@ +package autismclient; + +import com.mojang.logging.LogUtils; +import net.fabricmc.loader.api.FabricLoader; +import org.slf4j.Logger; + +public final class AutismClientAddon { + public static final Logger LOG = LogUtils.getLogger(); + public static final String MOD_ID = "autism"; + public static final java.io.File FOLDER = FabricLoader.getInstance().getConfigDir().resolve("autism").toFile(); + + static { + FOLDER.mkdirs(); + } + + private AutismClientAddon() {} +} diff --git a/src/main/java/autismclient/AutismClientMod.java b/src/main/java/autismclient/AutismClientMod.java new file mode 100644 index 0000000..073cd6f --- /dev/null +++ b/src/main/java/autismclient/AutismClientMod.java @@ -0,0 +1,166 @@ +package autismclient; + +import autismclient.gui.vanillaui.components.UiText; +import autismclient.modules.PackAutoReconnectState; +import autismclient.modules.AutismModule; +import autismclient.render.AutismFemaleBodyRenderer; +import autismclient.security.AutismProtector; +import autismclient.security.AutismProtectorPackStrip; +import autismclient.security.AutismProtectorServerPackFailureGuard; +import autismclient.security.AutismProtectorTracker; +import autismclient.security.AutismProtectorVanillaKeys; +import autismclient.util.AutismInstaBreakRenderer; +import autismclient.util.AutismFakeGamemode; +import autismclient.util.AutismJoinMacroController; +import autismclient.util.AutismLANSync; +import autismclient.util.AutismOverlayManager; +import autismclient.util.AutismSvgHudLogo; +import autismclient.util.AutismWindowBranding; +import autismclient.util.AutismSharedState; +import net.fabricmc.api.ClientModInitializer; +import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents; +import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; +import net.fabricmc.fabric.api.client.item.v1.ItemTooltipCallback; +import net.fabricmc.fabric.api.client.networking.v1.ClientConfigurationConnectionEvents; +import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents; +import net.fabricmc.fabric.api.resource.ResourceManagerHelper; +import net.minecraft.server.packs.PackType; + +public final class AutismClientMod implements ClientModInitializer { + + private static void runSafe(String where, Runnable action) { + try { + action.run(); + } catch (Throwable t) { + AutismClientAddon.LOG.warn("[Autism] client-event '{}' failed; isolated to protect the client", where, t); + } + } + + private static final java.util.concurrent.ConcurrentHashMap LAST_TICK_ERROR_MS = new java.util.concurrent.ConcurrentHashMap<>(); + + private static void logTickError(String where, Throwable t) { + long now = System.currentTimeMillis(); + Long last = LAST_TICK_ERROR_MS.get(where); + if (last != null && now - last < 5000L) return; + LAST_TICK_ERROR_MS.put(where, now); + AutismClientAddon.LOG.warn("[Autism] tick '{}' failed; isolated to protect the client", where, t); + } + + @Override + @SuppressWarnings("deprecation") + public void onInitializeClient() { + AutismClientAddon.FOLDER.mkdirs(); + + runSafe("initialize", () -> AutismModule.get().initialize()); + + AutismProtectorTracker.bootstrap(); + + if (!AutismProtector.isOverlapExternalProtectorPresent()) { + AutismProtectorVanillaKeys.primeAsync(); + } + if (AutismProtector.isFullExternalProtectorPresent()) { + AutismClientAddon.LOG.info( + "[AutismProtector] External protection mod detected; deferring all anti-fingerprint mixins to it."); + } else if (AutismProtector.isExploitPreventerPresent()) { + AutismClientAddon.LOG.info( + "[AutismProtector] ExploitPreventer detected; deferring overlapping protections while keeping brand/channel hiding active."); + } else { + AutismClientAddon.LOG.info( + "[AutismProtector] Built-in anti-fingerprint layer active."); + } + AutismInstaBreakRenderer.initialize(); + autismclient.util.AutismFreecamHighlightRenderer.initialize(); + AutismFemaleBodyRenderer.initialize(); + autismclient.commands.AutismCommands.init(); + + autismclient.addons.AddonManager.init(); + + ResourceManagerHelper.get(PackType.CLIENT_RESOURCES).registerReloadListener(new net.fabricmc.fabric.api.resource.SimpleSynchronousResourceReloadListener() { + @Override + public net.minecraft.resources.Identifier getFabricId() { + return net.minecraft.resources.Identifier.fromNamespaceAndPath("autismclient", "ui_assets"); + } + + @Override + public void onResourceManagerReload(net.minecraft.server.packs.resources.ResourceManager manager) { + UiText.onClientResourceReload(); + AutismSvgHudLogo.clear(); + } + }); + + ClientTickEvents.END_CLIENT_TICK.register(client -> { + + try { + AutismInstaBreakRenderer.tickPlacePreview(); + } catch (Throwable t) { + logTickError("instaBreak", t); + } + try { + AutismWindowBranding.apply(client); + } catch (Throwable ignored) { } + try { + AutismModule.get().tick(); + } catch (Throwable t) { + logTickError("module", t); + } + try { + AutismJoinMacroController.onClientTick(client); + } catch (Throwable t) { + logTickError("joinMacro", t); + } + try { + autismclient.util.AutismLagWatchdog.onClientTick(client); + } catch (Throwable t) { + logTickError("lagWatchdog", t); + } + }); + ClientTickEvents.END_LEVEL_TICK.register(level -> AutismLANSync.getInstance().onLevelTick(level.getGameTime())); + ClientConfigurationConnectionEvents.INIT.register((listener, client) -> { + runSafe("cfg.hideMenuOverlays", () -> AutismModule.get().hideMenuOverlays()); + runSafe("cfg.configStarted", () -> AutismModule.get().onConfigurationConnectionStarted()); + runSafe("cfg.joinMacro", () -> AutismJoinMacroController.onConfigurationInit(listener)); + }); + ClientConfigurationConnectionEvents.DISCONNECT.register((listener, client) -> { + runSafe("cfg.fakeGamemode", AutismFakeGamemode::clear); + runSafe("cfg.instaBreak", AutismInstaBreakRenderer::clear); + runSafe("cfg.packFailureGuard", AutismProtectorServerPackFailureGuard::clear); + runSafe("cfg.hideOverlays", () -> AutismOverlayManager.get().hideAllInteractiveOverlays()); + runSafe("cfg.onGameLeft", () -> AutismModule.get().onGameLeft()); + runSafe("cfg.joinMacro", AutismJoinMacroController::onConfigurationDisconnect); + }); + ClientPlayConnectionEvents.JOIN.register((handler, sender, client) -> { + + runSafe("join.movementGrace", autismclient.modules.AutismJoinGrace::onJoin); + runSafe("join.hideMenuOverlays", () -> AutismModule.get().hideMenuOverlays()); + runSafe("join.remember", () -> PackAutoReconnectState.remember(client.getCurrentServer())); + runSafe("join.onGameJoin", () -> AutismModule.get().onGameJoin()); + runSafe("join.joinMacro", AutismJoinMacroController::onPlayJoin); + runSafe("join.surfaceFailures", autismclient.addons.AddonManager::surfaceFailuresOnJoin); + runSafe("join.lagWatchdog", autismclient.util.AutismLagWatchdog::reset); + }); + ClientPlayConnectionEvents.DISCONNECT.register((handler, client) -> { + runSafe("leave.movementGrace", autismclient.modules.AutismJoinGrace::clear); + runSafe("leave.fakeGamemode", AutismFakeGamemode::clear); + runSafe("leave.instaBreak", AutismInstaBreakRenderer::clear); + runSafe("leave.packStrip", AutismProtectorPackStrip::clearAll); + runSafe("leave.packFailureGuard", AutismProtectorServerPackFailureGuard::clear); + runSafe("leave.hideOverlays", () -> AutismOverlayManager.get().hideAllInteractiveOverlays()); + runSafe("leave.joinMacro", AutismJoinMacroController::onGameLeft); + runSafe("leave.onGameLeft", () -> AutismModule.get().onGameLeft()); + runSafe("leave.lagWatchdog", autismclient.util.AutismLagWatchdog::reset); + }); + ItemTooltipCallback.EVENT.register((stack, tooltipContext, tooltipType, lines) -> + AutismModule.get().appendTooltip(stack, lines) + ); + + ClientLifecycleEvents.CLIENT_STOPPING.register(client -> { + autismclient.util.mm.MatchmakingManager.get().shutdownLeave(); + + autismclient.util.AutismConfig.flushPendingSaves(2000L); + }); + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + autismclient.util.mm.MatchmakingManager.get().shutdownLeave(); + autismclient.util.AutismConfig.flushPendingSaves(2000L); + }, "mm-shutdown-leave")); + } +} diff --git a/src/main/java/autismclient/addons/AddonManager.java b/src/main/java/autismclient/addons/AddonManager.java new file mode 100644 index 0000000..ae18c10 --- /dev/null +++ b/src/main/java/autismclient/addons/AddonManager.java @@ -0,0 +1,530 @@ +package autismclient.addons; + +import autismclient.AutismClientAddon; +import autismclient.api.ApiVersion; +import autismclient.api.AutismAddon; +import autismclient.util.AutismConfig; +import autismclient.util.AutismNotifications; +import net.fabricmc.loader.api.FabricLoader; +import net.fabricmc.loader.api.ModContainer; +import net.fabricmc.loader.api.entrypoint.EntrypointContainer; +import net.fabricmc.loader.api.metadata.CustomValue; +import net.fabricmc.loader.api.metadata.ModMetadata; +import net.fabricmc.loader.api.metadata.Person; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +public final class AddonManager { + private static final int MAX_UI_ADDON_NAME_LENGTH = 22; + private static final List LOADED = new ArrayList<>(); + private static final Map REPORTS = new LinkedHashMap<>(); + + private record LoadingContext(String addonId, String addonName) {} + private static volatile LoadingContext currentContext = null; + + private static boolean failuresSurfaced = false; + + private AddonManager() {} + + public static void init() { + LOADED.clear(); + REPORTS.clear(); + failuresSurfaced = false; + + AutismConfig config = AutismConfig.getGlobal(); + List accepted = new ArrayList<>(); + for (EntrypointContainer container : FabricLoader.getInstance() + .getEntrypointContainers("autism", AutismAddon.class)) { + ModContainer mod; + try { + mod = container.getProvider(); + } catch (Throwable t) { + AutismClientAddon.LOG.error("[Addons] Failed to inspect an addon entrypoint", t); + continue; + } + + String modId = mod.getMetadata().getId(); + AddonReport report = ensureReport(mod.getMetadata()); + if (isDisabledOnRestart(modId)) { + report.markDisabled("Disabled in AUTISM config. Enable it and restart to load."); + continue; + } + + AutismAddon addon; + try { + addon = container.getEntrypoint(); + } catch (Throwable t) { + report.markFailed("construct", "Failed to construct entrypoint: " + shortError(t)); + AutismClientAddon.LOG.error("[Addons] Failed to construct addon '{}'", modId, t); + continue; + } + + try { + int declared = addon.apiVersion(); + report.setApiVersion(declared); + if (declared <= 0) { + report.markFailed("apiVersion", "Invalid API version " + declared + "."); + AutismClientAddon.LOG.warn("[Addons] Addon '{}' declared invalid API v{}; skipping it.", modId, declared); + continue; + } + if (declared > ApiVersion.CURRENT) { + report.markNeedsNewerApi("Needs API v" + declared + ", host provides v" + ApiVersion.CURRENT + "."); + AutismClientAddon.LOG.warn("[Addons] Addon '{}' needs API v{} but this client provides v{}; skipping it.", + modId, declared, ApiVersion.CURRENT); + continue; + } + if (declared < ApiVersion.CURRENT) { + AutismClientAddon.LOG.info("[Addons] Addon '{}' built against API v{} (current v{}); loading.", + modId, declared, ApiVersion.CURRENT); + } + applyMetadata(addon, mod.getMetadata()); + report.copyRuntimeMetadata(addon); + accepted.add(new LoadedAddon(modId, addon)); + } catch (AbstractMethodError e) { + report.markMissingApiVersion("Missing apiVersion() override."); + AutismClientAddon.LOG.error("[Addons] Addon '{}' does not declare apiVersion(); skipping it.", modId, e); + } catch (Throwable t) { + report.markFailed("prepare", "Failed to prepare: " + shortError(t)); + AutismClientAddon.LOG.error("[Addons] Error preparing addon '{}'", modId, t); + } + } + + List categoryReady = new ArrayList<>(); + for (LoadedAddon la : accepted) { + if (runPhase(la, "onRegisterCategories", la.addon::onRegisterCategories)) { + categoryReady.add(la); + } else { + invokeUnload(la); + rollbackRegistrations(la.modId); + } + } + + for (LoadedAddon la : categoryReady) { + if (runPhase(la, "onInitialize", la.addon::onInitialize)) { + LOADED.add(la.addon); + AddonReport report = REPORTS.get(la.modId); + if (report != null) report.markLoaded(); + } else { + invokeUnload(la); + rollbackRegistrations(la.modId); + } + } + + if (!LOADED.isEmpty()) { + AutismClientAddon.LOG.info("[Addons] Loaded {} addon(s).", LOADED.size()); + } + if (config.disabledAddonIds != null) { + for (String id : config.disabledAddonIds) { + if (id == null || id.isBlank() || REPORTS.containsKey(id)) continue; + AddonReport report = new AddonReport(id.trim(), id.trim(), "", "", 0xFFAA66FF); + report.markDisabled("Disabled in AUTISM config, but no matching addon entrypoint was discovered."); + REPORTS.put(report.modId(), report); + } + } + } + + private static boolean runPhase(LoadedAddon la, String phase, Runnable body) { + String name = la.addon.name == null || la.addon.name.isBlank() ? la.modId : la.addon.name; + currentContext = new LoadingContext(la.modId, name); + AddonReport report = REPORTS.get(la.modId); + if (report != null) report.setPhase(phase); + try { + body.run(); + return true; + } catch (Throwable t) { + if (report != null) report.markFailed(phase, "Threw during " + phase + ": " + shortError(t)); + AutismClientAddon.LOG.error("[Addons] Addon '{}' threw during {}", la.modId, phase, t); + return false; + } finally { + currentContext = null; + } + } + + private static void invokeUnload(LoadedAddon la) { + if (la == null || la.addon == null) return; + try { + la.addon.onUnload(); + } catch (Throwable t) { + AutismClientAddon.LOG.warn("[Addons] Addon '{}' threw during onUnload", la.modId, t); + } + } + + private static void rollbackRegistrations(String addonId) { + if (addonId == null || addonId.isBlank()) return; + AddonReport report = REPORTS.get(addonId); + rollbackStep(addonId, report, "macro actions", () -> autismclient.api.macro.MacroActionRegistry.unregisterAddon(addonId)); + rollbackStep(addonId, report, "custom menu adapters", () -> autismclient.api.custommenu.CustomMenuAdapterRegistry.unregisterAddon(addonId)); + rollbackStep(addonId, report, "presets", () -> autismclient.api.macro.MacroPresetRegistry.unregisterAddon(addonId)); + rollbackStep(addonId, report, "events", () -> autismclient.api.event.AddonEvents.unregisterAddon(addonId)); + rollbackStep(addonId, report, "hud", () -> autismclient.api.hud.HudElements.unregisterAddon(addonId)); + rollbackStep(addonId, report, "modules", () -> autismclient.modules.ModuleRegistry.unregisterAddonModules(addonId)); + rollbackStep(addonId, report, "commands", () -> autismclient.commands.AutismCommands.unregisterAddonCommands(addonId)); + if (report != null) report.addRollback("Rolled back partial registrations after load failure."); + } + + private static void rollbackStep(String addonId, AddonReport report, String kind, Runnable body) { + try { + body.run(); + } catch (Throwable t) { + String detail = "Failed to rollback " + kind + ": " + shortError(t); + if (report != null) report.addRollback(detail); + AutismClientAddon.LOG.warn("[Addons] Addon '{}' rollback failed for {}", addonId, kind, t); + } + } + + private static AddonReport ensureReport(ModMetadata meta) { + String modId = meta.getId(); + AddonReport existing = REPORTS.get(modId); + if (existing != null) return existing; + AddonReport report = new AddonReport( + modId, + meta.getName() == null || meta.getName().isBlank() ? modId : meta.getName(), + meta.getVersion().getFriendlyString(), + meta.getAuthors().stream().map(Person::getName).collect(Collectors.joining(", ")), + metadataColor(meta, 0xFFAA66FF) + ); + REPORTS.put(modId, report); + return report; + } + + private static void applyMetadata(AutismAddon addon, ModMetadata meta) { + addon.name = meta.getName(); + addon.authors = meta.getAuthors().stream().map(Person::getName).collect(Collectors.joining(", ")); + addon.color = metadataColor(meta, addon.color); + } + + private static int metadataColor(ModMetadata meta, int fallback) { + CustomValue color = meta.containsCustomValue("autism:color") ? meta.getCustomValue("autism:color") : null; + if (color != null && color.getType() == CustomValue.CvType.STRING) { + return parseColor(color.getAsString(), fallback); + } + return fallback; + } + + private static int parseColor(String raw, int fallback) { + try { + String[] parts = raw.split(","); + if (parts.length != 3) return fallback; + int r = clamp(Integer.parseInt(parts[0].trim())); + int g = clamp(Integer.parseInt(parts[1].trim())); + int b = clamp(Integer.parseInt(parts[2].trim())); + return 0xFF000000 | (r << 16) | (g << 8) | b; + } catch (Exception e) { + return fallback; + } + } + + private static int clamp(int v) { return Math.max(0, Math.min(255, v)); } + + private static String currentId() { + LoadingContext ctx = currentContext; + return ctx == null ? null : ctx.addonId(); + } + + private static String currentName() { + LoadingContext ctx = currentContext; + return ctx == null ? null : ctx.addonName(); + } + + public static String currentAddonId() { + return currentId(); + } + + public static boolean isLifecycleActive() { + String id = currentId(); + return id != null && !id.isBlank(); + } + + public static String currentAddonName() { + return currentName(); + } + + public static String normalizedAddonName(String name, String fallback) { + String value = name == null ? "" : name.replaceAll("\\s+", " ").trim(); + if (value.isBlank()) value = fallback == null ? "" : fallback.replaceAll("\\s+", " ").trim(); + return value.isBlank() ? "Addon" : value; + } + + public static String compactAddonName(String name, String fallback) { + String value = normalizedAddonName(name, fallback); + if (value.length() <= MAX_UI_ADDON_NAME_LENGTH) return value; + return value.substring(0, Math.max(1, MAX_UI_ADDON_NAME_LENGTH - 3)).trim() + "..."; + } + + public static String scopedId(String rawId) { + String raw = rawId == null ? "" : rawId.trim(); + if (raw.contains(":")) return raw; + String owner = currentId(); + if (owner == null || owner.isBlank()) return raw; + return owner + ":" + raw; + } + + public static String scopedCategoryLabel(String customLabel) { + LoadingContext ctx = currentContext; + String id = ctx == null ? null : ctx.addonId(); + String name = ctx == null ? null : ctx.addonName(); + if (name == null || name.isBlank()) name = id; + return compactAddonName(name, id); + } + + public static List loaded() { + return Collections.unmodifiableList(LOADED); + } + + public static List reports() { + return Collections.unmodifiableList(new ArrayList<>(REPORTS.values())); + } + + public static AddonReport report(String addonId) { + return addonId == null ? null : REPORTS.get(addonId); + } + + public static File modsFolder() { + return FabricLoader.getInstance().getGameDir().resolve("mods").toFile(); + } + + public static boolean isDisabledOnRestart(String addonId) { + if (addonId == null || addonId.isBlank()) return false; + AutismConfig config = AutismConfig.getGlobal(); + if (config.disabledAddonIds == null) return false; + String needle = addonId.trim().toLowerCase(Locale.ROOT); + for (String id : config.disabledAddonIds) { + if (id != null && needle.equals(id.trim().toLowerCase(Locale.ROOT))) return true; + } + return false; + } + + public static void setDisabledOnRestart(String addonId, boolean disabled) { + if (addonId == null || addonId.isBlank()) return; + AutismConfig config = AutismConfig.getGlobal(); + if (config.disabledAddonIds == null) config.disabledAddonIds = new ArrayList<>(); + String normalized = addonId.trim(); + boolean currently = isDisabledOnRestart(normalized); + if (disabled && !currently) { + config.disabledAddonIds.add(normalized); + } else if (!disabled && currently) { + config.disabledAddonIds.removeIf(id -> id != null && normalized.equalsIgnoreCase(id.trim())); + } + config.save(); + } + + public static void recordAcceptedRegistration(String kind, String id) { + AddonReport report = REPORTS.get(currentId()); + if (report != null) report.recordAccepted(kind, id); + } + + public static void recordRejectedRegistration(String addonId, String kind, String id, String reason) { + AddonReport report = REPORTS.get(addonId == null || addonId.isBlank() ? currentId() : addonId); + if (report != null) report.recordRejected(kind, id, reason); + } + + public static void recordRuntimeError(String addonId, String detail) { + AddonReport report = REPORTS.get(addonId); + if (report != null) report.recordRuntimeError(detail); + } + + public static void surfaceFailuresOnJoin() { + if (failuresSurfaced) return; + int issues = issueCount(); + if (issues <= 0) return; + failuresSurfaced = true; + AutismNotifications.warning(issues + " addon issue(s). Open Addons for details."); + } + + private static int issueCount() { + int count = 0; + for (AddonReport report : REPORTS.values()) { + if (report.status().isIssue()) count++; + } + return count; + } + + private static String shortError(Throwable t) { + if (t == null) return "Unknown error"; + String msg = t.getMessage(); + return msg == null || msg.isBlank() ? t.getClass().getSimpleName() : t.getClass().getSimpleName() + ": " + msg; + } + + private record LoadedAddon(String modId, AutismAddon addon) {} + + public enum AddonLoadStatus { + LOADED("Loaded", false), + DISABLED("Disabled on restart", false), + FAILED("Failed", true), + NEEDS_NEWER_API("Needs newer API", true), + MISSING_API_VERSION("Missing apiVersion", true); + + private final String label; + private final boolean issue; + + AddonLoadStatus(String label, boolean issue) { + this.label = label; + this.issue = issue; + } + + public String label() { return label; } + public boolean isIssue() { return issue; } + } + + public static final class AddonReport { + private final String modId; + private String name; + private String version; + private String authors; + private int color; + private int apiVersion = -1; + private int hostApiVersion = ApiVersion.CURRENT; + private AddonLoadStatus status = AddonLoadStatus.FAILED; + private String phase = "discovered"; + private String failureReason = ""; + private final Map accepted = new LinkedHashMap<>(); + private final Map rejected = new LinkedHashMap<>(); + private final List rejectionDetails = new ArrayList<>(); + private final List rollbackDetails = new ArrayList<>(); + private int runtimeErrors; + private String lastRuntimeError = ""; + + private AddonReport(String modId, String name, String version, String authors, int color) { + this.modId = modId == null ? "" : modId; + this.name = name == null || name.isBlank() ? this.modId : name; + this.version = version == null ? "" : version; + this.authors = authors == null ? "" : authors; + this.color = color; + } + + private void copyRuntimeMetadata(AutismAddon addon) { + if (addon == null) return; + if (addon.name != null && !addon.name.isBlank()) this.name = addon.name; + if (addon.authors != null && !addon.authors.isBlank()) this.authors = addon.authors; + this.color = addon.color; + } + + private void setApiVersion(int apiVersion) { + this.apiVersion = apiVersion; + } + + private void setPhase(String phase) { + this.phase = phase == null || phase.isBlank() ? this.phase : phase; + } + + private void markLoaded() { + this.status = AddonLoadStatus.LOADED; + this.phase = "loaded"; + this.failureReason = ""; + } + + private void markDisabled(String reason) { + this.status = AddonLoadStatus.DISABLED; + this.phase = "disabled"; + this.failureReason = reason == null ? "" : reason; + } + + private void markFailed(String phase, String reason) { + this.status = AddonLoadStatus.FAILED; + this.phase = phase == null || phase.isBlank() ? "failed" : phase; + this.failureReason = reason == null ? "" : reason; + } + + private void markNeedsNewerApi(String reason) { + this.status = AddonLoadStatus.NEEDS_NEWER_API; + this.phase = "apiVersion"; + this.failureReason = reason == null ? "" : reason; + } + + private void markMissingApiVersion(String reason) { + this.status = AddonLoadStatus.MISSING_API_VERSION; + this.phase = "apiVersion"; + this.failureReason = reason == null ? "" : reason; + } + + private void recordAccepted(String kind, String id) { + String key = kind == null || kind.isBlank() ? "item" : kind; + accepted.merge(key, 1, Integer::sum); + } + + private void recordRejected(String kind, String id, String reason) { + String key = kind == null || kind.isBlank() ? "item" : kind; + rejected.merge(key, 1, Integer::sum); + String detail = key + (id == null || id.isBlank() ? "" : " " + id) + ": " + + (reason == null || reason.isBlank() ? "rejected" : reason); + rejectionDetails.add(detail); + } + + private void addRollback(String detail) { + if (detail != null && !detail.isBlank()) rollbackDetails.add(detail); + } + + private void recordRuntimeError(String detail) { + runtimeErrors++; + lastRuntimeError = detail == null || detail.isBlank() ? "Runtime error" : detail; + } + + public String modId() { return modId; } + public String name() { return name; } + public String version() { return version; } + public String authors() { return authors; } + public int color() { return color; } + public int apiVersion() { return apiVersion; } + public int hostApiVersion() { return hostApiVersion; } + public AddonLoadStatus status() { return status; } + public String phase() { return phase; } + public String failureReason() { return failureReason; } + public int runtimeErrors() { return runtimeErrors; } + public String lastRuntimeError() { return lastRuntimeError; } + public Map accepted() { return Collections.unmodifiableMap(accepted); } + public Map rejected() { return Collections.unmodifiableMap(rejected); } + public List rejectionDetails() { return Collections.unmodifiableList(rejectionDetails); } + public List rollbackDetails() { return Collections.unmodifiableList(rollbackDetails); } + + public int acceptedTotal() { + int total = 0; + for (int value : accepted.values()) total += value; + return total; + } + + public int rejectedTotal() { + int total = 0; + for (int value : rejected.values()) total += value; + return total; + } + + public String summaryCounts() { + if (accepted.isEmpty()) return "No registered extensions"; + List parts = new ArrayList<>(); + for (Map.Entry entry : accepted.entrySet()) { + parts.add(entry.getValue() + " " + entry.getKey()); + } + return String.join(", ", parts); + } + + public String copyReport() { + StringBuilder sb = new StringBuilder(); + sb.append("Addon: ").append(name).append('\n'); + sb.append("ID: ").append(modId).append('\n'); + if (!version.isBlank()) sb.append("Version: ").append(version).append('\n'); + if (!authors.isBlank()) sb.append("Authors: ").append(authors).append('\n'); + sb.append("Status: ").append(status.label()).append('\n'); + sb.append("Phase: ").append(phase).append('\n'); + sb.append("API: addon v").append(apiVersion < 0 ? "unknown" : Integer.toString(apiVersion)) + .append(", host v").append(hostApiVersion).append('\n'); + sb.append("Disabled on restart: ").append(isDisabledOnRestart(modId)).append('\n'); + if (!failureReason.isBlank()) sb.append("Reason: ").append(failureReason).append('\n'); + sb.append("Accepted: ").append(accepted).append('\n'); + if (!rejected.isEmpty()) sb.append("Rejected: ").append(rejected).append('\n'); + for (String detail : rejectionDetails) sb.append("- ").append(detail).append('\n'); + for (String detail : rollbackDetails) sb.append("- ").append(detail).append('\n'); + if (runtimeErrors > 0) { + sb.append("Runtime errors: ").append(runtimeErrors).append('\n'); + sb.append("Last runtime error: ").append(lastRuntimeError).append('\n'); + } + return sb.toString(); + } + } +} diff --git a/src/main/java/autismclient/api/AddonRegistrationResult.java b/src/main/java/autismclient/api/AddonRegistrationResult.java new file mode 100644 index 0000000..af0c085 --- /dev/null +++ b/src/main/java/autismclient/api/AddonRegistrationResult.java @@ -0,0 +1,16 @@ +package autismclient.api; + +public record AddonRegistrationResult(boolean accepted, String kind, String id, String reason) { + + public static AddonRegistrationResult accepted(String kind, String id) { + return new AddonRegistrationResult(true, clean(kind), clean(id), "Accepted"); + } + + public static AddonRegistrationResult rejected(String kind, String id, String reason) { + return new AddonRegistrationResult(false, clean(kind), clean(id), clean(reason)); + } + + private static String clean(String value) { + return value == null || value.isBlank() ? "" : value.trim(); + } +} diff --git a/src/main/java/autismclient/api/ApiVersion.java b/src/main/java/autismclient/api/ApiVersion.java new file mode 100644 index 0000000..c1fa907 --- /dev/null +++ b/src/main/java/autismclient/api/ApiVersion.java @@ -0,0 +1,8 @@ +package autismclient.api; + +public final class ApiVersion { + + public static final int CURRENT = 3; + + private ApiVersion() {} +} diff --git a/src/main/java/autismclient/api/AutismAddon.java b/src/main/java/autismclient/api/AutismAddon.java new file mode 100644 index 0000000..4d78f46 --- /dev/null +++ b/src/main/java/autismclient/api/AutismAddon.java @@ -0,0 +1,20 @@ +package autismclient.api; + +public abstract class AutismAddon { + + public String name = ""; + + public String authors = ""; + + public int color = 0xFFFFFFFF; + + public abstract int apiVersion(); + + public void onRegisterCategories() {} + + public abstract void onInitialize(); + + public void onUnload() {} + + public abstract String getPackage(); +} diff --git a/src/main/java/autismclient/api/AutismAddons.java b/src/main/java/autismclient/api/AutismAddons.java new file mode 100644 index 0000000..21818b2 --- /dev/null +++ b/src/main/java/autismclient/api/AutismAddons.java @@ -0,0 +1,162 @@ +package autismclient.api; + +import autismclient.addons.AddonManager; +import autismclient.api.event.AddonEvents; +import autismclient.api.custommenu.CustomMenuAdapter; +import autismclient.api.custommenu.CustomMenuAdapterRegistry; +import autismclient.api.hud.HudElementProvider; +import autismclient.api.hud.HudElements; +import autismclient.api.macro.MacroActionEntry; +import autismclient.api.macro.MacroActionRegistry; +import autismclient.api.macro.MacroPresetRegistry; +import autismclient.commands.Command; +import autismclient.modules.Module; +import autismclient.modules.ModuleCategory; +import autismclient.modules.ModuleRegistry; +import autismclient.util.macro.MacroAction; +import net.minecraft.client.Minecraft; +import net.minecraft.network.protocol.Packet; + +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.function.Supplier; + +public final class AutismAddons { + private AutismAddons() {} + + public static Modules modules() { return Modules.INSTANCE; } + + public static Commands commands() { return Commands.INSTANCE; } + + public static MacroActions macroActions() { return MacroActions.INSTANCE; } + + public static Presets presets() { return Presets.INSTANCE; } + + public static Hud hud() { return Hud.INSTANCE; } + + public static Events events() { return Events.INSTANCE; } + + public static CustomMenus customMenus() { return CustomMenus.INSTANCE; } + + public static List list() { return AddonManager.loaded(); } + + public static String id(String localId) { return AddonManager.scopedId(localId); } + + public static int apiVersion() { return ApiVersion.CURRENT; } + + public static final class Modules { + static final Modules INSTANCE = new Modules(); + private Modules() {} + + public boolean register(Module module) { + return ModuleRegistry.registerAddonModule(module, AddonManager.currentAddonId()); + } + + public AddonRegistrationResult registerDetailed(Module module) { + return ModuleRegistry.registerAddonModuleDetailed(module, AddonManager.currentAddonId()); + } + + public ModuleCategory autoCategory() { + return ModuleCategory.registerAddon(AddonManager.currentAddonId(), + AddonManager.scopedCategoryLabel(null)); + } + + public ModuleCategory registerCategory(String label) { + return ModuleCategory.registerAddon(AddonManager.currentAddonId(), + AddonManager.scopedCategoryLabel(label)); + } + } + + public static final class Commands { + static final Commands INSTANCE = new Commands(); + private Commands() {} + + public void register(Command command) { + autismclient.commands.AutismCommands.registerAddonCommand(command, AddonManager.currentAddonId()); + } + + public AddonRegistrationResult registerDetailed(Command command) { + return autismclient.commands.AutismCommands.registerAddonCommandDetailed(command, AddonManager.currentAddonId()); + } + } + + public static final class MacroActions { + static final MacroActions INSTANCE = new MacroActions(); + private MacroActions() {} + + public boolean register(MacroActionEntry entry) { + return MacroActionRegistry.register(entry); + } + + public AddonRegistrationResult registerDetailed(MacroActionEntry entry) { + return MacroActionRegistry.registerDetailed(entry); + } + + public void registerCategory(String id, String label, int color) { + MacroActionRegistry.registerScopedCategory(id, label, color); + } + } + + public static final class CustomMenus { + static final CustomMenus INSTANCE = new CustomMenus(); + private CustomMenus() {} + + public boolean register(CustomMenuAdapter adapter) { + return CustomMenuAdapterRegistry.register(adapter); + } + } + + public static final class Presets { + static final Presets INSTANCE = new Presets(); + private Presets() {} + + public void registerCategory(String id, String label) { + MacroPresetRegistry.registerScopedCategory(id, label); + } + + public void register(String label, String tip, Supplier> builder) { + MacroPresetRegistry.register(MacroPresetRegistry.ensureScopedCategory(null), label, tip, builder); + } + + public AddonRegistrationResult registerDetailed(String label, String tip, Supplier> builder) { + return MacroPresetRegistry.registerDetailed(MacroPresetRegistry.ensureScopedCategory(null), label, tip, builder); + } + + public void register(String categoryId, String label, String tip, Supplier> builder) { + MacroPresetRegistry.register(MacroPresetRegistry.ensureScopedCategory(categoryId), label, tip, builder); + } + + public AddonRegistrationResult registerDetailed(String categoryId, String label, String tip, Supplier> builder) { + return MacroPresetRegistry.registerDetailed(MacroPresetRegistry.ensureScopedCategory(categoryId), label, tip, builder); + } + } + + public static final class Hud { + static final Hud INSTANCE = new Hud(); + private Hud() {} + + public boolean register(HudElementProvider provider) { + return HudElements.register(provider); + } + + public AddonRegistrationResult registerDetailed(HudElementProvider provider) { + return HudElements.registerDetailed(provider); + } + } + + public static final class Events { + static final Events INSTANCE = new Events(); + private Events() {} + + public void onTick(Consumer listener) { AddonEvents.onTick(listener); } + + public void onPacketSend(Predicate> listener) { AddonEvents.onPacketSend(listener); } + + public void onPacketReceive(Consumer> listener) { AddonEvents.onPacketReceive(listener); } + + public void onGameJoin(Runnable listener) { AddonEvents.onGameJoin(listener); } + + public void onGameLeft(Runnable listener) { AddonEvents.onGameLeft(listener); } + } +} diff --git a/src/main/java/autismclient/api/SimpleAddon.java b/src/main/java/autismclient/api/SimpleAddon.java new file mode 100644 index 0000000..0f32984 --- /dev/null +++ b/src/main/java/autismclient/api/SimpleAddon.java @@ -0,0 +1,94 @@ +package autismclient.api; + +import autismclient.api.macro.MacroActionEntry; +import autismclient.api.macro.MacroPresetRegistry; +import autismclient.api.macro.SimpleAction; +import autismclient.api.macro.SimpleCondition; +import autismclient.modules.Module; +import autismclient.util.macro.MacroAction; +import net.minecraft.client.Minecraft; + +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.function.Supplier; + +public abstract class SimpleAddon extends AutismAddon { + private final int apiVersion; + private final String rootPackage; + + protected SimpleAddon(int apiVersion, String rootPackage) { + this.apiVersion = apiVersion; + this.rootPackage = rootPackage == null ? "" : rootPackage; + } + + @Override + public final int apiVersion() { + return apiVersion; + } + + @Override + public final String getPackage() { + return rootPackage; + } + + @Override + public final void onInitialize() { + initialize(); + } + + protected abstract void initialize(); + + protected final String id(String localId) { + return AutismAddons.id(localId); + } + + protected final AddonRegistrationResult registerModule(Module module) { + return AutismAddons.modules().registerDetailed(module); + } + + protected final AddonRegistrationResult registerAction(MacroActionEntry entry) { + return AutismAddons.macroActions().registerDetailed(entry); + } + + protected final AddonRegistrationResult registerPreset(String label, String tip, Supplier> builder) { + return AutismAddons.presets().registerDetailed(label, tip, builder); + } + + protected final AddonRegistrationResult registerSimpleAction( + String localId, String label, String tip, String icon, Consumer runner) { + return registerAction(simpleAction(localId, label, tip, icon, runner)); + } + + protected final AddonRegistrationResult registerSimpleCondition( + String localId, String label, String tip, String status, String icon, Predicate predicate) { + return registerAction(simpleCondition(localId, label, tip, status, icon, predicate)); + } + + protected final MacroActionEntry simpleAction( + String localId, + String label, + String tip, + String icon, + Consumer runner + ) { + String typeId = id(localId); + return MacroActionEntry.builder(typeId, () -> new SimpleAction(typeId, label, icon, runner)) + .picker(label, tip) + .build(); + } + + protected final MacroActionEntry simpleCondition( + String localId, + String label, + String tip, + String status, + String icon, + Predicate predicate + ) { + String typeId = id(localId); + return MacroActionEntry.builder(typeId, () -> new SimpleCondition(typeId, label, status, icon, predicate)) + .condition(label, tip) + .build(); + } +} diff --git a/src/main/java/autismclient/api/custommenu/CustomMenuAdapter.java b/src/main/java/autismclient/api/custommenu/CustomMenuAdapter.java new file mode 100644 index 0000000..6bad1c1 --- /dev/null +++ b/src/main/java/autismclient/api/custommenu/CustomMenuAdapter.java @@ -0,0 +1,11 @@ +package autismclient.api.custommenu; + +import net.minecraft.network.protocol.Packet; + +public interface CustomMenuAdapter { + String id(); + + CustomMenuEvent inspectInbound(Packet packet, String phase); + + CustomMenuSubmitResult submit(CustomMenuSnapshot snapshot, CustomMenuSubmission submission); +} diff --git a/src/main/java/autismclient/api/custommenu/CustomMenuAdapterRegistry.java b/src/main/java/autismclient/api/custommenu/CustomMenuAdapterRegistry.java new file mode 100644 index 0000000..64a3db7 --- /dev/null +++ b/src/main/java/autismclient/api/custommenu/CustomMenuAdapterRegistry.java @@ -0,0 +1,73 @@ +package autismclient.api.custommenu; + +import autismclient.AutismClientAddon; +import autismclient.addons.AddonManager; +import autismclient.util.custommenu.VanillaDialogAdapter; +import net.minecraft.network.protocol.Packet; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public final class CustomMenuAdapterRegistry { + private record Registered(CustomMenuAdapter adapter, String owner) {} + private static final Map ADAPTERS = new LinkedHashMap<>(); + + static { + ADAPTERS.put(VanillaDialogAdapter.ID, new Registered(new VanillaDialogAdapter(), "autismclient")); + } + + private CustomMenuAdapterRegistry() {} + + public static synchronized boolean register(CustomMenuAdapter adapter) { + if (adapter == null || adapter.id() == null || adapter.id().isBlank()) return false; + String id = adapter.id().trim().toLowerCase(java.util.Locale.ROOT); + if (ADAPTERS.containsKey(id)) return false; + ADAPTERS.put(id, new Registered(adapter, AddonManager.currentAddonId())); + return true; + } + + public static synchronized void unregisterAddon(String addonId) { + if (addonId == null || addonId.isBlank()) return; + ADAPTERS.entrySet().removeIf(entry -> addonId.equals(entry.getValue().owner())); + } + + public static CustomMenuEvent inspect(Packet packet, String phase) { + List snapshot; + synchronized (CustomMenuAdapterRegistry.class) { + snapshot = new ArrayList<>(ADAPTERS.values()); + } + for (Registered registered : snapshot) { + try { + CustomMenuEvent event = registered.adapter().inspectInbound(packet, phase); + if (event != null && event.type() != CustomMenuEvent.Type.NONE) return event; + } catch (Throwable error) { + AutismClientAddon.LOG.warn("[CustomMenus] Adapter '{}' failed while reading a packet", registered.adapter().id(), error); + } + } + return CustomMenuEvent.NONE; + } + + public static CustomMenuSubmitResult submit(CustomMenuSnapshot snapshot, CustomMenuSubmission submission) { + if (snapshot == null) return CustomMenuSubmitResult.failure("No custom menu is open"); + Registered registered; + synchronized (CustomMenuAdapterRegistry.class) { + registered = ADAPTERS.get(snapshot.adapterId().toLowerCase(java.util.Locale.ROOT)); + } + if (registered == null) return CustomMenuSubmitResult.failure("Custom menu adapter is unavailable"); + try { + CustomMenuSubmitResult result = registered.adapter().submit(snapshot, submission); + return result == null ? CustomMenuSubmitResult.failure("Custom menu adapter returned no result") : result; + } catch (Throwable error) { + + AutismClientAddon.LOG.warn("[CustomMenus] Adapter '{}' failed while submitting a form ({})", + registered.adapter().id(), error.getClass().getSimpleName()); + return CustomMenuSubmitResult.failure("Custom menu adapter failed"); + } + } + + public static synchronized List ids() { + return List.copyOf(ADAPTERS.keySet()); + } +} diff --git a/src/main/java/autismclient/api/custommenu/CustomMenuButton.java b/src/main/java/autismclient/api/custommenu/CustomMenuButton.java new file mode 100644 index 0000000..be719f2 --- /dev/null +++ b/src/main/java/autismclient/api/custommenu/CustomMenuButton.java @@ -0,0 +1,15 @@ +package autismclient.api.custommenu; + +public record CustomMenuButton(int index, String label, String actionId, Kind kind) { + public enum Kind { CUSTOM, COMMAND, DIALOG, URL, CLIPBOARD, OTHER, EMPTY } + + public CustomMenuButton { + label = label == null ? "" : label; + actionId = actionId == null ? "" : actionId; + kind = kind == null ? Kind.OTHER : kind; + } + + public boolean serverRelevant() { + return kind == Kind.CUSTOM || kind == Kind.COMMAND || kind == Kind.DIALOG; + } +} diff --git a/src/main/java/autismclient/api/custommenu/CustomMenuEvent.java b/src/main/java/autismclient/api/custommenu/CustomMenuEvent.java new file mode 100644 index 0000000..cd7c01a --- /dev/null +++ b/src/main/java/autismclient/api/custommenu/CustomMenuEvent.java @@ -0,0 +1,12 @@ +package autismclient.api.custommenu; + +public record CustomMenuEvent(Type type, CustomMenuSnapshot snapshot) { + public enum Type { NONE, OPEN, CLEAR } + + public static final CustomMenuEvent NONE = new CustomMenuEvent(Type.NONE, null); + public static final CustomMenuEvent CLEAR = new CustomMenuEvent(Type.CLEAR, null); + + public static CustomMenuEvent open(CustomMenuSnapshot snapshot) { + return new CustomMenuEvent(Type.OPEN, snapshot); + } +} diff --git a/src/main/java/autismclient/api/custommenu/CustomMenuInput.java b/src/main/java/autismclient/api/custommenu/CustomMenuInput.java new file mode 100644 index 0000000..8cc4b6b --- /dev/null +++ b/src/main/java/autismclient/api/custommenu/CustomMenuInput.java @@ -0,0 +1,26 @@ +package autismclient.api.custommenu; + +import java.util.List; + +public record CustomMenuInput( + int index, + String key, + String label, + Kind kind, + String initialValue, + int maxLength, + double min, + double max, + double step, + List options +) { + public enum Kind { TEXT, BOOLEAN, NUMBER, OPTION } + + public CustomMenuInput { + key = key == null ? "" : key; + label = label == null ? "" : label; + kind = kind == null ? Kind.TEXT : kind; + initialValue = initialValue == null ? "" : initialValue; + options = options == null ? List.of() : List.copyOf(options); + } +} diff --git a/src/main/java/autismclient/api/custommenu/CustomMenuSnapshot.java b/src/main/java/autismclient/api/custommenu/CustomMenuSnapshot.java new file mode 100644 index 0000000..51c6784 --- /dev/null +++ b/src/main/java/autismclient/api/custommenu/CustomMenuSnapshot.java @@ -0,0 +1,25 @@ +package autismclient.api.custommenu; + +import java.util.List; + +public record CustomMenuSnapshot( + String adapterId, + String phase, + long generation, + String title, + List inputs, + List buttons, + Object adapterState +) { + public CustomMenuSnapshot { + adapterId = adapterId == null ? "" : adapterId; + phase = phase == null ? "" : phase; + title = title == null ? "" : title; + inputs = inputs == null ? List.of() : List.copyOf(inputs); + buttons = buttons == null ? List.of() : List.copyOf(buttons); + } + + public CustomMenuSnapshot withConnectionState(String newPhase, long newGeneration) { + return new CustomMenuSnapshot(adapterId, newPhase, newGeneration, title, inputs, buttons, adapterState); + } +} diff --git a/src/main/java/autismclient/api/custommenu/CustomMenuSubmission.java b/src/main/java/autismclient/api/custommenu/CustomMenuSubmission.java new file mode 100644 index 0000000..46e532d --- /dev/null +++ b/src/main/java/autismclient/api/custommenu/CustomMenuSubmission.java @@ -0,0 +1,9 @@ +package autismclient.api.custommenu; + +import java.util.Map; + +public record CustomMenuSubmission(Map values, CustomMenuButton button) { + public CustomMenuSubmission { + values = values == null ? Map.of() : Map.copyOf(values); + } +} diff --git a/src/main/java/autismclient/api/custommenu/CustomMenuSubmitResult.java b/src/main/java/autismclient/api/custommenu/CustomMenuSubmitResult.java new file mode 100644 index 0000000..d670e53 --- /dev/null +++ b/src/main/java/autismclient/api/custommenu/CustomMenuSubmitResult.java @@ -0,0 +1,30 @@ +package autismclient.api.custommenu; + +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.chat.ClickEvent; +import java.util.List; + +public record CustomMenuSubmitResult( + boolean success, + String error, + List> packets, + CustomMenuSnapshot replacement, + ClickEvent clientAction +) { + public CustomMenuSubmitResult { + error = error == null ? "" : error; + packets = packets == null ? List.of() : List.copyOf(packets); + } + + public static CustomMenuSubmitResult failure(String error) { + return new CustomMenuSubmitResult(false, error, List.of(), null, null); + } + + public static CustomMenuSubmitResult packets(List> packets) { + return new CustomMenuSubmitResult(true, "", packets, null, null); + } + + public static CustomMenuSubmitResult replacement(CustomMenuSnapshot replacement, ClickEvent clientAction) { + return new CustomMenuSubmitResult(true, "", List.of(), replacement, clientAction); + } +} diff --git a/src/main/java/autismclient/api/event/AddonEvents.java b/src/main/java/autismclient/api/event/AddonEvents.java new file mode 100644 index 0000000..11d9d01 --- /dev/null +++ b/src/main/java/autismclient/api/event/AddonEvents.java @@ -0,0 +1,153 @@ +package autismclient.api.event; + +import autismclient.AutismClientAddon; +import autismclient.addons.AddonManager; +import autismclient.modules.PackHideState; +import net.minecraft.client.Minecraft; +import net.minecraft.network.protocol.Packet; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.Consumer; +import java.util.function.Predicate; + +public final class AddonEvents { + private static final List> TICK = new CopyOnWriteArrayList<>(); + private static final List>> PACKET_SEND = new CopyOnWriteArrayList<>(); + private static final List>> PACKET_RECEIVE = new CopyOnWriteArrayList<>(); + private static final List GAME_JOIN = new CopyOnWriteArrayList<>(); + private static final List GAME_LEFT = new CopyOnWriteArrayList<>(); + + private static final long ERROR_LOG_INTERVAL_MS = 5_000L; + private static final Map LAST_ERROR_LOG_MS = new ConcurrentHashMap<>(); + + private AddonEvents() {} + + public static void onTick(Consumer listener) { + String owner = ownerOrReject("tick"); + if (owner != null && listener != null) { + TICK.add(new OwnedConsumer<>(owner, listener)); + AddonManager.recordAcceptedRegistration("event", "tick"); + } + } + + public static void onPacketSend(Predicate> listener) { + String owner = ownerOrReject("packetSend"); + if (owner != null && listener != null) { + PACKET_SEND.add(new OwnedPredicate<>(owner, listener)); + AddonManager.recordAcceptedRegistration("event", "packetSend"); + } + } + + public static void onPacketReceive(Consumer> listener) { + String owner = ownerOrReject("packetReceive"); + if (owner != null && listener != null) { + PACKET_RECEIVE.add(new OwnedConsumer<>(owner, listener)); + AddonManager.recordAcceptedRegistration("event", "packetReceive"); + } + } + + public static void onGameJoin(Runnable listener) { + String owner = ownerOrReject("gameJoin"); + if (owner != null && listener != null) { + GAME_JOIN.add(new OwnedRunnable(owner, listener)); + AddonManager.recordAcceptedRegistration("event", "gameJoin"); + } + } + + public static void onGameLeft(Runnable listener) { + String owner = ownerOrReject("gameLeft"); + if (owner != null && listener != null) { + GAME_LEFT.add(new OwnedRunnable(owner, listener)); + AddonManager.recordAcceptedRegistration("event", "gameLeft"); + } + } + + private static String ownerOrReject(String event) { + String owner = AddonManager.currentAddonId(); + if (owner == null || owner.isBlank()) { + AutismClientAddon.LOG.warn("[Addons] Rejecting {} listener outside an addon lifecycle", event); + AddonManager.recordRejectedRegistration(owner, "event", event, "registration outside an addon lifecycle - register from onInitialize() or onRegisterCategories()"); + return null; + } + return owner; + } + + public static void unregisterAddon(String addonId) { + if (addonId == null || addonId.isBlank()) return; + TICK.removeIf(listener -> addonId.equals(listener.owner())); + PACKET_SEND.removeIf(listener -> addonId.equals(listener.owner())); + PACKET_RECEIVE.removeIf(listener -> addonId.equals(listener.owner())); + GAME_JOIN.removeIf(listener -> addonId.equals(listener.owner())); + GAME_LEFT.removeIf(listener -> addonId.equals(listener.owner())); + LAST_ERROR_LOG_MS.keySet().removeIf(key -> key.startsWith(addonId + ":")); + } + + public static void fireTick(Minecraft mc) { + if (PackHideState.isHardLocked()) return; + if (TICK.isEmpty()) return; + for (OwnedConsumer l : TICK) { + try { l.listener().accept(mc); } catch (Throwable t) { logThrottled(l.owner(), "tick", t); } + } + } + + public static boolean hasTickListeners() { + if (PackHideState.isHardLocked()) return false; + return !TICK.isEmpty(); + } + + public static boolean hasPacketListeners() { + if (PackHideState.isHardLocked()) return false; + return !PACKET_SEND.isEmpty() || !PACKET_RECEIVE.isEmpty(); + } + + public static boolean firePacketSend(Packet packet) { + if (PackHideState.isHardLocked()) return false; + if (PACKET_SEND.isEmpty()) return false; + boolean cancel = false; + for (OwnedPredicate> l : PACKET_SEND) { + try { cancel |= l.listener().test(packet); } catch (Throwable t) { logThrottled(l.owner(), "packetSend", t); } + } + return cancel; + } + + public static void firePacketReceive(Packet packet) { + if (PackHideState.isHardLocked()) return; + if (PACKET_RECEIVE.isEmpty()) return; + for (OwnedConsumer> l : PACKET_RECEIVE) { + try { l.listener().accept(packet); } catch (Throwable t) { logThrottled(l.owner(), "packetReceive", t); } + } + } + + public static void fireGameJoin() { + if (PackHideState.isHardLocked()) return; + if (GAME_JOIN.isEmpty()) return; + for (OwnedRunnable l : GAME_JOIN) { + try { l.listener().run(); } catch (Throwable t) { logThrottled(l.owner(), "gameJoin", t); } + } + } + + public static void fireGameLeft() { + if (PackHideState.isHardLocked()) return; + if (GAME_LEFT.isEmpty()) return; + for (OwnedRunnable l : GAME_LEFT) { + try { l.listener().run(); } catch (Throwable t) { logThrottled(l.owner(), "gameLeft", t); } + } + } + + private static void logThrottled(String owner, String event, Throwable t) { + long now = System.currentTimeMillis(); + String key = owner + ":" + event + ":" + t.getClass().getName(); + Long last = LAST_ERROR_LOG_MS.get(key); + if (last != null && now - last < ERROR_LOG_INTERVAL_MS) return; + LAST_ERROR_LOG_MS.put(key, now); + AddonManager.recordRuntimeError(owner, event + " listener threw " + t.getClass().getSimpleName()); + AutismClientAddon.LOG.warn("[Addons] Addon '{}' {} event listener threw", owner, event, t); + } + + private record OwnedConsumer(String owner, Consumer listener) {} + private record OwnedPredicate(String owner, Predicate listener) {} + private record OwnedRunnable(String owner, Runnable listener) {} +} diff --git a/src/main/java/autismclient/api/hud/HudElementProvider.java b/src/main/java/autismclient/api/hud/HudElementProvider.java new file mode 100644 index 0000000..7d19025 --- /dev/null +++ b/src/main/java/autismclient/api/hud/HudElementProvider.java @@ -0,0 +1,27 @@ +package autismclient.api.hud; + +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphicsExtractor; + +public interface HudElementProvider { + + String id(); + + String label(); + + default String description() { return ""; } + + int width(); + + int height(); + + void render(GuiGraphicsExtractor ctx, Font font, int x, int y, float alpha); + + default boolean defaultEnabled() { return false; } + + default String defaultAnchor() { return "TOP_LEFT"; } + + default int defaultX() { return 0; } + + default int defaultY() { return 0; } +} diff --git a/src/main/java/autismclient/api/hud/HudElements.java b/src/main/java/autismclient/api/hud/HudElements.java new file mode 100644 index 0000000..9603cef --- /dev/null +++ b/src/main/java/autismclient/api/hud/HudElements.java @@ -0,0 +1,104 @@ +package autismclient.api.hud; + +import autismclient.AutismClientAddon; +import autismclient.api.AddonRegistrationResult; +import autismclient.addons.AddonManager; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public final class HudElements { + private static final Map PROVIDERS = new LinkedHashMap<>(); + private static final Map OWNERS = new LinkedHashMap<>(); + private static int revision; + + private HudElements() {} + + public static int revision() { + return revision; + } + + public static boolean register(HudElementProvider provider) { + return registerDetailed(provider).accepted(); + } + + public static AddonRegistrationResult registerDetailed(HudElementProvider provider) { + if (provider == null) return AddonRegistrationResult.rejected("hud", "", "provider was null"); + String ownerAddonId = AddonManager.currentAddonId(); + if (ownerAddonId == null || ownerAddonId.isBlank()) { + return reject(ownerAddonId, "", "registration outside an addon lifecycle - register from onInitialize() or onRegisterCategories()"); + } + String id = provider.id(); + if (id == null || !id.contains(":")) { + return reject(ownerAddonId, id, "non-namespaced id - scope it with AutismAddons.id(...) so it becomes addonId:localId"); + } + if (!id.startsWith(ownerAddonId + ":")) { + return reject(ownerAddonId, id, "foreign namespace - the id must start with your addon id; scope it with AutismAddons.id(...)"); + } + if (PROVIDERS.containsKey(id)) { + return reject(ownerAddonId, id, "duplicate id"); + } + AddonRegistrationResult sizeCheck = validateSize(ownerAddonId, id, provider); + if (!sizeCheck.accepted()) return sizeCheck; + PROVIDERS.put(id, provider); + OWNERS.put(id, ownerAddonId); + revision++; + AddonManager.recordAcceptedRegistration("hud", id); + return AddonRegistrationResult.accepted("hud", id); + } + + private static AddonRegistrationResult validateSize(String ownerAddonId, String id, HudElementProvider provider) { + int width; + int height; + try { + width = provider.width(); + height = provider.height(); + } catch (Throwable t) { + AutismClientAddon.LOG.warn("[Hud] Rejecting HUD element '{}': sizing threw", id, t); + AddonManager.recordRejectedRegistration(ownerAddonId, "hud", id, "sizing threw " + t.getClass().getSimpleName()); + return AddonRegistrationResult.rejected("hud", id, "sizing threw " + t.getClass().getSimpleName()); + } + if (width <= 0) return reject(ownerAddonId, id, "width must be positive"); + if (height <= 0) return reject(ownerAddonId, id, "height must be positive"); + return AddonRegistrationResult.accepted("hud", id); + } + + private static AddonRegistrationResult reject(String ownerAddonId, String id, String reason) { + AutismClientAddon.LOG.warn("[Hud] Rejecting HUD element '{}': {}", id, reason); + AddonManager.recordRejectedRegistration(ownerAddonId, "hud", id, reason); + return AddonRegistrationResult.rejected("hud", id, reason); + } + + public static void unregisterAddon(String addonId) { + if (addonId == null || addonId.isBlank()) return; + List remove = new ArrayList<>(); + for (Map.Entry owner : OWNERS.entrySet()) { + if (addonId.equals(owner.getValue())) remove.add(owner.getKey()); + } + if (remove.isEmpty()) return; + for (String id : remove) { + PROVIDERS.remove(id); + OWNERS.remove(id); + } + revision++; + } + + public static HudElementProvider get(String id) { + return id == null ? null : PROVIDERS.get(id); + } + + public static boolean isAddon(String id) { + return id != null && PROVIDERS.containsKey(id); + } + + public static List ids() { + return Collections.unmodifiableList(new ArrayList<>(PROVIDERS.keySet())); + } + + public static boolean isEmpty() { + return PROVIDERS.isEmpty(); + } +} diff --git a/src/main/java/autismclient/api/macro/ActionSchema.java b/src/main/java/autismclient/api/macro/ActionSchema.java new file mode 100644 index 0000000..e6e4049 --- /dev/null +++ b/src/main/java/autismclient/api/macro/ActionSchema.java @@ -0,0 +1,83 @@ +package autismclient.api.macro; + +import autismclient.gui.macro.editor.ActionFieldSchema; + +public final class ActionSchema { + private final ActionFieldSchema internal; + + private ActionSchema(ActionFieldSchema internal) { + this.internal = internal; + } + + public ActionFieldSchema internal() { + return internal; + } + + public static Builder builder() { + return new Builder(); + } + + public static final class Builder { + private final ActionFieldSchema.Builder delegate = ActionFieldSchema.builder(); + + private Builder() {} + + public Builder toggle(String key, String label) { delegate.toggle(key, label); return this; } + + public Builder number(String key, String label) { delegate.number(key, label); return this; } + + public Builder decimal(String key, String label) { delegate.decimal(key, label); return this; } + + public Builder text(String key, String label) { delegate.text(key, label); return this; } + + public Builder macroSelect(String key, String label) { delegate.macroSelect(key, label); return this; } + + public Builder enumField(String key, String label, String... options) { delegate.enumField(key, label, options); return this; } + + public Builder stringList(String key, String label) { delegate.stringList(key, label); return this; } + + public Builder slot(String key, String label) { delegate.slot(key, label); return this; } + + public Builder targetSummary(String key, String label) { delegate.targetSummary(key, label); return this; } + + public Builder capturePacketClick(String key, String label) { delegate.capturePacketClick(key, label); return this; } + + public Builder blockPos(String key, String label) { delegate.blockPos(key, label); return this; } + + public Builder range(int min, int max) { delegate.range(min, max); return this; } + + public Builder decRange(double min, double max) { delegate.decRange(min, max); return this; } + + public Builder showWhen(String key) { delegate.showWhen(key); return this; } + + public Builder hideWhen(String key) { delegate.hideWhen(key); return this; } + + public Builder showWhenEnum(String key, String value) { delegate.showWhenEnum(key, value); return this; } + + public Builder hideWhenEnum(String key, String value) { delegate.hideWhenEnum(key, value); return this; } + + public Builder addLabel(String label) { delegate.addLabel(label); return this; } + + public Builder xyzKeys(String... keys) { delegate.xyzKeys(keys); return this; } + + public Builder xyzDouble(boolean value) { delegate.xyzDouble(value); return this; } + + public Builder captureBlock() { delegate.captureBlock(); return this; } + + public Builder captureEntity() { delegate.captureEntity(); return this; } + + public Builder captureCatalog() { delegate.captureCatalog(); return this; } + + public Builder captureItemSlot() { delegate.captureItemSlot(); return this; } + + public Builder capturePacketName() { delegate.capturePacketName(); return this; } + + public Builder exclusiveWith(String... keys) { delegate.exclusiveWith(keys); return this; } + + public Builder dynamic() { delegate.dynamic(); return this; } + + public ActionSchema build() { + return new ActionSchema(delegate.build()); + } + } +} diff --git a/src/main/java/autismclient/api/macro/AddonAction.java b/src/main/java/autismclient/api/macro/AddonAction.java new file mode 100644 index 0000000..0ac6625 --- /dev/null +++ b/src/main/java/autismclient/api/macro/AddonAction.java @@ -0,0 +1,61 @@ +package autismclient.api.macro; + +import autismclient.util.macro.MacroAction; +import net.minecraft.nbt.CompoundTag; + +public abstract class AddonAction implements MacroAction { + private final String typeId; + + protected AddonAction(String typeId) { + this.typeId = typeId; + } + + protected abstract void run(net.minecraft.client.Minecraft mc); + + protected void save(CompoundTag tag) {} + + protected void load(CompoundTag tag) {} + + protected ActionSchema schema() { + return null; + } + + @Override + public final void execute(net.minecraft.client.Minecraft mc) { + run(mc); + } + + @Override + public final String getTypeId() { + return typeId; + } + + @Override + public final CompoundTag toTag() { + CompoundTag tag = new CompoundTag(); + tag.putString("type", typeId); + save(tag); + return tag; + } + + @Override + public final void fromTag(CompoundTag tag) { + load(tag); + } + + protected static void putString(CompoundTag tag, String key, String value) { tag.putString(key, value == null ? "" : value); } + protected static void putInt(CompoundTag tag, String key, int value) { tag.putInt(key, value); } + protected static void putDouble(CompoundTag tag, String key, double value) { tag.putDouble(key, value); } + protected static void putBool(CompoundTag tag, String key, boolean value) { tag.putBoolean(key, value); } + + protected static String getString(CompoundTag tag, String key, String def) { return tag.getStringOr(key, def); } + protected static int getInt(CompoundTag tag, String key, int def) { return tag.getIntOr(key, def); } + protected static double getDouble(CompoundTag tag, String key, double def) { return tag.getDoubleOr(key, def); } + protected static boolean getBool(CompoundTag tag, String key, boolean def) { return tag.getBooleanOr(key, def); } + + public static ActionSchema schemaOf(MacroAction action) { + return action instanceof AddonAction a ? a.schema() + : action instanceof AddonContextAction c ? c.schemaInternal() + : null; + } +} diff --git a/src/main/java/autismclient/api/macro/AddonCondition.java b/src/main/java/autismclient/api/macro/AddonCondition.java new file mode 100644 index 0000000..469507c --- /dev/null +++ b/src/main/java/autismclient/api/macro/AddonCondition.java @@ -0,0 +1,10 @@ +package autismclient.api.macro; + +import net.minecraft.client.Minecraft; + +public abstract class AddonCondition { + + public abstract boolean check(Minecraft mc); + + public void onComplete() {} +} diff --git a/src/main/java/autismclient/api/macro/AddonContextAction.java b/src/main/java/autismclient/api/macro/AddonContextAction.java new file mode 100644 index 0000000..0a0fcf5 --- /dev/null +++ b/src/main/java/autismclient/api/macro/AddonContextAction.java @@ -0,0 +1,51 @@ +package autismclient.api.macro; + +import net.minecraft.nbt.CompoundTag; + +public abstract class AddonContextAction implements ContextMacroAction { + private final String typeId; + + protected AddonContextAction(String typeId) { + this.typeId = typeId; + } + + protected void save(CompoundTag tag) {} + + protected void load(CompoundTag tag) {} + + protected ActionSchema schema() { + return null; + } + + ActionSchema schemaInternal() { + return schema(); + } + + @Override + public final String getTypeId() { + return typeId; + } + + @Override + public final CompoundTag toTag() { + CompoundTag tag = new CompoundTag(); + tag.putString("type", typeId); + save(tag); + return tag; + } + + @Override + public final void fromTag(CompoundTag tag) { + load(tag); + } + + protected static void putString(CompoundTag tag, String key, String value) { tag.putString(key, value == null ? "" : value); } + protected static void putInt(CompoundTag tag, String key, int value) { tag.putInt(key, value); } + protected static void putDouble(CompoundTag tag, String key, double value) { tag.putDouble(key, value); } + protected static void putBool(CompoundTag tag, String key, boolean value) { tag.putBoolean(key, value); } + + protected static String getString(CompoundTag tag, String key, String def) { return tag.getStringOr(key, def); } + protected static int getInt(CompoundTag tag, String key, int def) { return tag.getIntOr(key, def); } + protected static double getDouble(CompoundTag tag, String key, double def) { return tag.getDoubleOr(key, def); } + protected static boolean getBool(CompoundTag tag, String key, boolean def) { return tag.getBooleanOr(key, def); } +} diff --git a/src/main/java/autismclient/api/macro/ContextMacroAction.java b/src/main/java/autismclient/api/macro/ContextMacroAction.java new file mode 100644 index 0000000..28d1b2c --- /dev/null +++ b/src/main/java/autismclient/api/macro/ContextMacroAction.java @@ -0,0 +1,14 @@ +package autismclient.api.macro; + +import autismclient.util.macro.MacroAction; +import net.minecraft.client.Minecraft; + +public interface ContextMacroAction extends MacroAction { + + void run(MacroExecutionContext ctx) throws InterruptedException; + + @Override + default void execute(Minecraft mc) { + + } +} diff --git a/src/main/java/autismclient/api/macro/MacroActionEntry.java b/src/main/java/autismclient/api/macro/MacroActionEntry.java new file mode 100644 index 0000000..0b3af51 --- /dev/null +++ b/src/main/java/autismclient/api/macro/MacroActionEntry.java @@ -0,0 +1,103 @@ +package autismclient.api.macro; + +import autismclient.addons.AddonManager; +import autismclient.gui.macro.editor.ActionFieldSchema; +import autismclient.util.macro.MacroAction; + +import java.util.function.Supplier; + +public final class MacroActionEntry { + + public enum Kind { ACTION, CONDITION } + + private final String typeId; + private final Supplier factory; + private final ActionFieldSchema schema; + private String pickerCategory; + private final String pickerLabel; + private final String pickerTip; + private final Kind kind; + + private MacroActionEntry(Builder b) { + this.typeId = b.typeId; + this.factory = b.factory; + this.schema = b.schema; + this.pickerCategory = b.pickerCategory; + this.pickerLabel = b.pickerLabel; + this.pickerTip = b.pickerTip; + this.kind = b.kind; + } + + public String typeId() { return typeId; } + public Supplier factory() { return factory; } + public ActionFieldSchema schema() { return schema; } + + public boolean hasPicker() { return pickerCategory != null && pickerLabel != null; } + + boolean wantsPicker() { return pickerLabel != null; } + public String pickerCategory() { return pickerCategory; } + public String pickerLabel() { return pickerLabel; } + public String pickerTip() { return pickerTip == null ? "" : pickerTip; } + public Kind kind() { return kind; } + public boolean isCondition() { return kind == Kind.CONDITION; } + + void setPickerCategory(String categoryId) { + this.pickerCategory = categoryId; + } + + public static Builder builder(String typeId, Supplier factory) { + return new Builder(typeId, factory); + } + + public static Builder local(String localId, Supplier factory) { + return new Builder(AddonManager.scopedId(localId), factory); + } + + public static final class Builder { + private final String typeId; + private final Supplier factory; + private ActionFieldSchema schema; + private String pickerCategory; + private String pickerLabel; + private String pickerTip; + private Kind kind = Kind.ACTION; + + private Builder(String typeId, Supplier factory) { + this.typeId = typeId; + this.factory = factory; + } + + public Builder schema(ActionSchema schema) { + this.schema = schema == null ? null : schema.internal(); + return this; + } + + public Builder picker(String label, String tip) { + return picker(null, label, tip); + } + + public Builder picker(String categoryId, String label, String tip) { + this.pickerCategory = categoryId; + this.pickerLabel = label; + this.pickerTip = tip; + this.kind = Kind.ACTION; + return this; + } + + public Builder condition(String label, String tip) { + return condition(null, label, tip); + } + + public Builder condition(String categoryId, String label, String tip) { + this.pickerCategory = categoryId; + this.pickerLabel = label; + this.pickerTip = tip; + this.kind = Kind.CONDITION; + return this; + } + + public MacroActionEntry build() { + return new MacroActionEntry(this); + } + } +} diff --git a/src/main/java/autismclient/api/macro/MacroActionRegistry.java b/src/main/java/autismclient/api/macro/MacroActionRegistry.java new file mode 100644 index 0000000..b0e7d85 --- /dev/null +++ b/src/main/java/autismclient/api/macro/MacroActionRegistry.java @@ -0,0 +1,230 @@ +package autismclient.api.macro; + +import autismclient.AutismClientAddon; +import autismclient.api.AddonRegistrationResult; +import autismclient.addons.AddonManager; +import autismclient.gui.macro.editor.ActionFieldSchema; +import autismclient.util.macro.MacroAction; +import autismclient.util.macro.MacroActionType; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.function.Supplier; + +public final class MacroActionRegistry { + private static final Map ENTRIES = new LinkedHashMap<>(); + private static final Map CATEGORIES = new LinkedHashMap<>(); + private static final Map ENTRY_OWNERS = new LinkedHashMap<>(); + private static final Map CATEGORY_OWNERS = new LinkedHashMap<>(); + + private static final Map RESOLVED_SCHEMAS = new LinkedHashMap<>(); + + public record ActionCategory(String id, String label, int color) {} + + public static final int ADDON_AUTO_CATEGORY_COLOR = 0xFFAA66FF; + + private static final String ADDON_CAT_PREFIX = "addon:"; + + private MacroActionRegistry() {} + + public static String scopeCategoryId(String rawId) { + if (AddonManager.isLifecycleActive()) { + String addonId = AddonManager.currentAddonId(); + return ADDON_CAT_PREFIX + (addonId == null || addonId.isBlank() ? "shared" : addonId); + } + if (rawId != null && rawId.startsWith(ADDON_CAT_PREFIX)) return rawId; + String addonId = AddonManager.currentAddonId(); + String base = addonId == null || addonId.isBlank() ? "shared" : addonId; + return rawId == null || rawId.isBlank() + ? ADDON_CAT_PREFIX + base + : ADDON_CAT_PREFIX + base + "/" + rawId; + } + + public static String ensureScopedCategory(String rawId) { + String scopedId = scopeCategoryId(rawId); + if (!CATEGORIES.containsKey(scopedId)) { + registerCategoryInternal(scopedId, AddonManager.scopedCategoryLabel(null), ADDON_AUTO_CATEGORY_COLOR, + AddonManager.currentAddonId()); + } + return scopedId; + } + + public static void registerScopedCategory(String rawId, String label, int color) { + String visible = AddonManager.isLifecycleActive() ? AddonManager.scopedCategoryLabel(null) : label; + registerCategoryInternal(scopeCategoryId(rawId), visible, color, + AddonManager.currentAddonId()); + } + + public static void registerCategory(String id, String label, int color) { + registerCategoryInternal(id, label, color, null); + } + + private static void registerCategoryInternal(String id, String label, int color, String ownerAddonId) { + if (id == null || id.isBlank()) return; + CATEGORIES.put(id, new ActionCategory(id, label == null || label.isBlank() ? id : label, color)); + if (ownerAddonId != null && !ownerAddonId.isBlank()) CATEGORY_OWNERS.put(id, ownerAddonId); + } + + public static ActionCategory category(String id) { + return id == null ? null : CATEGORIES.get(id); + } + + public static boolean register(MacroActionEntry entry) { + return registerDetailed(entry).accepted(); + } + + public static AddonRegistrationResult registerDetailed(MacroActionEntry entry) { + if (entry == null) return AddonRegistrationResult.rejected("macro action", "", "entry was null"); + String ownerAddonId = AddonManager.currentAddonId(); + if (ownerAddonId == null || ownerAddonId.isBlank()) { + return reject(ownerAddonId, "macro action", "", "registration outside an addon lifecycle - register from onInitialize() or onRegisterCategories()"); + } + + String typeId = entry.typeId(); + if (typeId == null || !typeId.contains(":")) { + return reject(ownerAddonId, "macro action", typeId, "non-namespaced type id - scope it with AutismAddons.id(...) so it becomes addonId:localId"); + } + if (!typeId.startsWith(ownerAddonId + ":")) { + return reject(ownerAddonId, "macro action", typeId, "foreign namespace - the id must start with your addon id; scope it with AutismAddons.id(...)"); + } + if (entry.factory() == null) { + return reject(ownerAddonId, "macro action", typeId, "missing factory"); + } + if (isBuiltinName(typeId)) { + return reject(ownerAddonId, "macro action", typeId, "collides with a built-in type"); + } + if (ENTRIES.containsKey(typeId)) { + return reject(ownerAddonId, "macro action", typeId, "duplicate type id"); + } + + if (entry.wantsPicker()) { + entry.setPickerCategory(ensureScopedCategory(entry.pickerCategory())); + } + + ActionFieldSchema effectiveSchema = entry.schema(); + MacroAction probe; + try { + probe = entry.factory().get(); + } catch (Throwable t) { + AutismClientAddon.LOG.warn("[MacroActions] Rejecting action '{}' because its factory threw during validation", typeId, t); + return reject(ownerAddonId, "macro action", typeId, "factory threw: " + errorName(t)); + } + if (probe == null) { + return reject(ownerAddonId, "macro action", typeId, "factory returned null"); + } + if (effectiveSchema == null) { + ActionSchema declared = AddonAction.schemaOf(probe); + if (declared != null) effectiveSchema = declared.internal(); + } + String validationError = validateProbe(typeId, entry, probe, effectiveSchema); + if (validationError != null) return reject(ownerAddonId, "macro action", typeId, validationError); + + ENTRIES.put(typeId, entry); + ENTRY_OWNERS.put(typeId, ownerAddonId); + if (effectiveSchema != null) RESOLVED_SCHEMAS.put(typeId, effectiveSchema); + AddonManager.recordAcceptedRegistration("macro action", typeId); + return AddonRegistrationResult.accepted("macro action", typeId); + } + + private static AddonRegistrationResult reject(String ownerAddonId, String kind, String id, String reason) { + AutismClientAddon.LOG.warn("[MacroActions] Rejecting {} '{}': {}", kind, id, reason); + AddonManager.recordRejectedRegistration(ownerAddonId, kind, id, reason); + return AddonRegistrationResult.rejected(kind, id, reason); + } + + private static String validateProbe(String typeId, MacroActionEntry entry, MacroAction probe, ActionFieldSchema schema) { + String writtenType; + net.minecraft.nbt.CompoundTag tag; + try { + tag = probe.toTag(); + writtenType = tag.getStringOr("type", ""); + } catch (Throwable t) { + AutismClientAddon.LOG.warn("[MacroActions] Rejecting '{}' because toTag() threw", typeId, t); + return "toTag() threw: " + errorName(t); + } + if (!typeId.equals(writtenType)) { + return "writes type=\"" + writtenType + "\" instead of \"" + typeId + "\""; + } + if (schema != null) { + for (autismclient.gui.macro.editor.FieldDef field : schema.fields()) { + String key = field.key(); + if (field.type() == autismclient.gui.macro.editor.FieldType.BLOCK_POS) { + for (String axisKey : field.xyzKeys()) { + if (axisKey != null && !axisKey.isEmpty() && !tag.contains(axisKey)) { + return "schema field '" + axisKey + "' is not written by toTag()/save()"; + } + } + } else if (key != null && !key.isEmpty() && !tag.contains(key)) { + return "schema field '" + key + "' is not written by toTag()/save()"; + } + } + } + if (entry.isCondition() && !(probe instanceof ContextMacroAction)) { + return "conditions must implement ContextMacroAction"; + } + return null; + } + + public static void unregisterAddon(String addonId) { + if (addonId == null || addonId.isBlank()) return; + List removeTypes = new ArrayList<>(); + for (Map.Entry owner : ENTRY_OWNERS.entrySet()) { + if (addonId.equals(owner.getValue())) removeTypes.add(owner.getKey()); + } + for (String typeId : removeTypes) { + ENTRIES.remove(typeId); + RESOLVED_SCHEMAS.remove(typeId); + ENTRY_OWNERS.remove(typeId); + } + + List removeCategories = new ArrayList<>(); + for (Map.Entry owner : CATEGORY_OWNERS.entrySet()) { + if (addonId.equals(owner.getValue())) removeCategories.add(owner.getKey()); + } + for (String categoryId : removeCategories) { + CATEGORIES.remove(categoryId); + CATEGORY_OWNERS.remove(categoryId); + } + } + + public static Supplier factory(String typeId) { + MacroActionEntry e = typeId == null ? null : ENTRIES.get(typeId); + return e == null ? null : e.factory(); + } + + public static ActionFieldSchema schema(String typeId) { + return typeId == null ? null : RESOLVED_SCHEMAS.get(typeId); + } + + public static boolean isCondition(String typeId) { + MacroActionEntry e = typeId == null ? null : ENTRIES.get(typeId); + return e != null && e.isCondition(); + } + + public static String ownerOf(String typeId) { + return typeId == null ? null : ENTRY_OWNERS.get(typeId); + } + + public static List entries() { + return Collections.unmodifiableList(new ArrayList<>(ENTRIES.values())); + } + + private static boolean isBuiltinName(String typeId) { + try { + MacroActionType.valueOf(typeId.toUpperCase(Locale.ROOT)); + return true; + } catch (IllegalArgumentException e) { + return false; + } + } + + private static String errorName(Throwable t) { + if (t == null) return "unknown"; + String message = t.getMessage(); + return message == null || message.isBlank() ? t.getClass().getSimpleName() : t.getClass().getSimpleName() + ": " + message; + } +} diff --git a/src/main/java/autismclient/api/macro/MacroExecutionContext.java b/src/main/java/autismclient/api/macro/MacroExecutionContext.java new file mode 100644 index 0000000..d741a34 --- /dev/null +++ b/src/main/java/autismclient/api/macro/MacroExecutionContext.java @@ -0,0 +1,78 @@ +package autismclient.api.macro; + +import net.minecraft.client.Minecraft; +import net.minecraft.network.protocol.Packet; + +import java.util.concurrent.CompletableFuture; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; +import autismclient.util.macro.MacroTemplate; +import autismclient.util.macro.MacroValue; + +public interface MacroExecutionContext { + + Minecraft mc(); + + void runOnClientThread(Runnable r); + + T callOnClientThread(Supplier s); + + void waitTicks(int ticks); + + void awaitCondition(CompletableFuture future); + + void awaitCondition(AddonCondition condition); + + boolean isActive(); + + void setStatus(String status); + + void sendPacket(Packet packet); + + Optional variable(String name); + + void setVariable(String name, MacroValue value); + + default void setVariable(String name, Object value) { + setVariable(name, MacroValue.text(value)); + } + + void removeVariable(String name); + + Map variables(); + + MacroTemplate.Resolution resolveTemplate(String template); + + default void captureResult(String name, MacroValue value) { + setVariable(name, value); + } + + default void captureResults(Map values) { + if (values != null) values.forEach(this::setVariable); + } + + default Optional resolveInt(String template) { + MacroTemplate.Resolution resolved = resolveTemplate(template); + if (!resolved.success()) return Optional.empty(); + try { return Optional.of(Integer.parseInt(resolved.value().trim())); } + catch (NumberFormatException ignored) { return Optional.empty(); } + } + + default Optional resolveDouble(String template) { + MacroTemplate.Resolution resolved = resolveTemplate(template); + if (!resolved.success()) return Optional.empty(); + try { return Optional.of(Double.parseDouble(resolved.value().trim())); } + catch (NumberFormatException ignored) { return Optional.empty(); } + } + + default > Optional resolveEnum(String template, Class type) { + if (type == null) return Optional.empty(); + MacroTemplate.Resolution resolved = resolveTemplate(template); + if (!resolved.success()) return Optional.empty(); + for (E value : type.getEnumConstants()) { + if (value.name().equalsIgnoreCase(resolved.value().trim())) return Optional.of(value); + } + return Optional.empty(); + } +} diff --git a/src/main/java/autismclient/api/macro/MacroPresetRegistry.java b/src/main/java/autismclient/api/macro/MacroPresetRegistry.java new file mode 100644 index 0000000..da3d7b4 --- /dev/null +++ b/src/main/java/autismclient/api/macro/MacroPresetRegistry.java @@ -0,0 +1,115 @@ +package autismclient.api.macro; + +import autismclient.AutismClientAddon; +import autismclient.api.AddonRegistrationResult; +import autismclient.addons.AddonManager; +import autismclient.util.macro.MacroAction; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +public final class MacroPresetRegistry { + + public record PresetEntry(String categoryId, String label, String tip, Supplier> builder) {} + + private static final List ENTRIES = new ArrayList<>(); + private static final Map ENTRY_OWNERS = new IdentityHashMap<>(); + private static final Map CATEGORY_LABELS = new LinkedHashMap<>(); + private static final Map CATEGORY_OWNERS = new LinkedHashMap<>(); + + private MacroPresetRegistry() {} + + public static void registerCategory(String id, String label) { + registerCategory(id, label, AddonManager.currentAddonId()); + } + + public static String ensureScopedCategory(String rawId) { + String scopedId = MacroActionRegistry.scopeCategoryId(rawId); + if (!CATEGORY_LABELS.containsKey(scopedId)) { + registerCategory(scopedId, AddonManager.scopedCategoryLabel(null), AddonManager.currentAddonId()); + } + return scopedId; + } + + public static void registerScopedCategory(String rawId, String label) { + String visible = AddonManager.isLifecycleActive() ? AddonManager.scopedCategoryLabel(null) : label; + registerCategory(MacroActionRegistry.scopeCategoryId(rawId), visible, + AddonManager.currentAddonId()); + } + + private static void registerCategory(String id, String label, String ownerAddonId) { + if (id == null || id.isBlank()) return; + CATEGORY_LABELS.put(id, label == null || label.isBlank() ? id : label); + if (ownerAddonId != null && !ownerAddonId.isBlank()) CATEGORY_OWNERS.put(id, ownerAddonId); + } + + public static void register(String categoryId, String label, String tip, Supplier> builder) { + registerDetailed(categoryId, label, tip, builder); + } + + public static AddonRegistrationResult registerDetailed(String categoryId, String label, String tip, Supplier> builder) { + String ownerAddonId = AddonManager.currentAddonId(); + if (ownerAddonId == null || ownerAddonId.isBlank()) { + return reject(ownerAddonId, label, "registration outside an addon lifecycle - register from onInitialize() or onRegisterCategories()"); + } + if (categoryId == null || categoryId.isBlank()) return reject(ownerAddonId, label, "missing category"); + if (label == null || label.isBlank()) return reject(ownerAddonId, label, "missing label"); + if (builder == null) return reject(ownerAddonId, label, "missing builder"); + AddonRegistrationResult validation = validateBuilder(ownerAddonId, label, builder); + if (!validation.accepted()) return validation; + PresetEntry entry = new PresetEntry(categoryId, label, tip == null ? "" : tip, builder); + ENTRIES.add(entry); + ENTRY_OWNERS.put(entry, ownerAddonId); + AddonManager.recordAcceptedRegistration("preset", label); + return AddonRegistrationResult.accepted("preset", label); + } + + private static AddonRegistrationResult validateBuilder(String ownerAddonId, String label, Supplier> builder) { + List actions; + try { + actions = builder.get(); + } catch (Throwable t) { + AutismClientAddon.LOG.warn("[MacroPresets] Rejecting preset '{}': builder threw", label, t); + AddonManager.recordRejectedRegistration(ownerAddonId, "preset", label, "builder threw " + t.getClass().getSimpleName()); + return AddonRegistrationResult.rejected("preset", label, "builder threw " + t.getClass().getSimpleName()); + } + if (actions == null) return reject(ownerAddonId, label, "builder returned null"); + for (int i = 0; i < actions.size(); i++) { + if (actions.get(i) == null) { + return reject(ownerAddonId, label, "builder returned null action at index " + i); + } + } + return AddonRegistrationResult.accepted("preset", label); + } + + private static AddonRegistrationResult reject(String ownerAddonId, String label, String reason) { + AutismClientAddon.LOG.warn("[MacroPresets] Rejecting preset '{}': {}", label, reason); + AddonManager.recordRejectedRegistration(ownerAddonId, "preset", label, reason); + return AddonRegistrationResult.rejected("preset", label, reason); + } + + public static void unregisterAddon(String addonId) { + if (addonId == null || addonId.isBlank()) return; + List remove = new ArrayList<>(); + for (PresetEntry entry : ENTRIES) { + if (addonId.equals(ENTRY_OWNERS.get(entry))) remove.add(entry); + } + ENTRIES.removeAll(remove); + for (PresetEntry entry : remove) ENTRY_OWNERS.remove(entry); + CATEGORY_LABELS.entrySet().removeIf(entry -> addonId.equals(CATEGORY_OWNERS.get(entry.getKey()))); + CATEGORY_OWNERS.entrySet().removeIf(entry -> addonId.equals(entry.getValue())); + } + + public static List entries() { + return Collections.unmodifiableList(ENTRIES); + } + + public static String categoryLabel(String id) { + return CATEGORY_LABELS.get(id); + } +} diff --git a/src/main/java/autismclient/api/macro/SimpleAction.java b/src/main/java/autismclient/api/macro/SimpleAction.java new file mode 100644 index 0000000..7775fcb --- /dev/null +++ b/src/main/java/autismclient/api/macro/SimpleAction.java @@ -0,0 +1,33 @@ +package autismclient.api.macro; + +import net.minecraft.client.Minecraft; + +import java.util.function.Consumer; + +public final class SimpleAction extends AddonAction { + private final String displayName; + private final String icon; + private final Consumer runner; + + public SimpleAction(String typeId, String displayName, String icon, Consumer runner) { + super(typeId); + this.displayName = displayName == null || displayName.isBlank() ? typeId : displayName; + this.icon = icon == null || icon.isBlank() ? "*" : icon; + this.runner = runner; + } + + @Override + protected void run(Minecraft mc) { + if (runner != null) runner.accept(mc); + } + + @Override + public String getDisplayName() { + return displayName; + } + + @Override + public String getIcon() { + return icon; + } +} diff --git a/src/main/java/autismclient/api/macro/SimpleCondition.java b/src/main/java/autismclient/api/macro/SimpleCondition.java new file mode 100644 index 0000000..eaa6ea5 --- /dev/null +++ b/src/main/java/autismclient/api/macro/SimpleCondition.java @@ -0,0 +1,41 @@ +package autismclient.api.macro; + +import net.minecraft.client.Minecraft; + +import java.util.function.Predicate; + +public final class SimpleCondition extends AddonContextAction { + private final String displayName; + private final String status; + private final String icon; + private final Predicate predicate; + + public SimpleCondition(String typeId, String displayName, String status, String icon, Predicate predicate) { + super(typeId); + this.displayName = displayName == null || displayName.isBlank() ? typeId : displayName; + this.status = status == null || status.isBlank() ? this.displayName : status; + this.icon = icon == null || icon.isBlank() ? "?" : icon; + this.predicate = predicate; + } + + @Override + public void run(MacroExecutionContext ctx) { + ctx.setStatus(status); + ctx.awaitCondition(new AddonCondition() { + @Override + public boolean check(Minecraft mc) { + return predicate != null && predicate.test(mc); + } + }); + } + + @Override + public String getDisplayName() { + return displayName; + } + + @Override + public String getIcon() { + return icon; + } +} diff --git a/src/main/java/autismclient/api/module/ActionSetting.java b/src/main/java/autismclient/api/module/ActionSetting.java new file mode 100644 index 0000000..b94c5f5 --- /dev/null +++ b/src/main/java/autismclient/api/module/ActionSetting.java @@ -0,0 +1,29 @@ +package autismclient.api.module; + +public final class ActionSetting extends Setting { + private String buttonLabel = "Run"; + + public ActionSetting(String name, String title, Runnable action) { + super(Kind.ACTION, name, title, null); + setAction(action); + } + + public ActionSetting buttonLabel(String buttonLabel) { + this.buttonLabel = buttonLabel == null || buttonLabel.isBlank() ? "Run" : buttonLabel; + return this; + } + + public String buttonLabel() { + return buttonLabel; + } + + @Override + protected Void decode(String raw) { + return null; + } + + @Override + protected String encode(Void value) { + return ""; + } +} diff --git a/src/main/java/autismclient/api/module/Availability.java b/src/main/java/autismclient/api/module/Availability.java new file mode 100644 index 0000000..da3e9f4 --- /dev/null +++ b/src/main/java/autismclient/api/module/Availability.java @@ -0,0 +1,10 @@ +package autismclient.api.module; + +public enum Availability { + + ALWAYS, + + IN_WORLD, + + IN_CONTAINER +} diff --git a/src/main/java/autismclient/api/module/BoolSetting.java b/src/main/java/autismclient/api/module/BoolSetting.java new file mode 100644 index 0000000..a1c6b64 --- /dev/null +++ b/src/main/java/autismclient/api/module/BoolSetting.java @@ -0,0 +1,17 @@ +package autismclient.api.module; + +public final class BoolSetting extends Setting { + public BoolSetting(String name, String title, boolean defaultValue) { + super(Kind.BOOLEAN, name, title, defaultValue); + } + + @Override + protected Boolean decode(String raw) { + return raw != null && Boolean.parseBoolean(raw.trim()); + } + + @Override + protected String encode(Boolean value) { + return Boolean.toString(value != null && value); + } +} diff --git a/src/main/java/autismclient/api/module/ChoiceSetting.java b/src/main/java/autismclient/api/module/ChoiceSetting.java new file mode 100644 index 0000000..90623bc --- /dev/null +++ b/src/main/java/autismclient/api/module/ChoiceSetting.java @@ -0,0 +1,39 @@ +package autismclient.api.module; + +import java.util.Arrays; +import java.util.List; + +public final class ChoiceSetting extends Setting { + public ChoiceSetting(String name, String title, String defaultValue, String... choices) { + super(Kind.ENUM, name, title, defaultValue == null ? "" : defaultValue); + setChoices(choices == null ? List.of() : Arrays.asList(choices)); + } + + public ChoiceSetting(String name, String title, String defaultValue, List choices) { + super(Kind.ENUM, name, title, defaultValue == null ? "" : defaultValue); + setChoices(choices); + } + + @Override + protected String decode(String raw) { + if (raw == null) return defaultValueTyped(); + String needle = raw.trim(); + List options = choices(); + if (options.isEmpty()) return needle; + for (String choice : options) { + if (choice.equalsIgnoreCase(needle)) return choice; + } + return defaultValueTyped(); + } + + @Override + protected String encode(String value) { + if (value == null) return defaultValueTyped(); + List options = choices(); + if (options.isEmpty()) return value; + for (String choice : options) { + if (choice.equalsIgnoreCase(value)) return choice; + } + return defaultValueTyped(); + } +} diff --git a/src/main/java/autismclient/api/module/ColorSetting.java b/src/main/java/autismclient/api/module/ColorSetting.java new file mode 100644 index 0000000..02ad1a9 --- /dev/null +++ b/src/main/java/autismclient/api/module/ColorSetting.java @@ -0,0 +1,36 @@ +package autismclient.api.module; + +import java.util.Locale; + +public final class ColorSetting extends Setting { + public ColorSetting(String name, String title, int defaultArgb) { + super(Kind.COLOR, name, title, defaultArgb); + } + + @Override + protected Integer decode(String raw) { + Integer parsed = parseColor(raw); + return parsed == null ? defaultValueTyped() : parsed; + } + + @Override + protected String encode(Integer value) { + int argb = value == null ? defaultValueTyped() : value; + return String.format(Locale.ROOT, "%08X", argb); + } + + static Integer parseColor(String value) { + if (value == null) return null; + String text = value.trim(); + if (text.isEmpty()) return null; + if (text.startsWith("#")) text = text.substring(1); + else if (text.startsWith("0x") || text.startsWith("0X")) text = text.substring(2); + try { + long parsed = Long.parseUnsignedLong(text, 16); + if (text.length() <= 6) parsed |= 0xFF000000L; + return (int) parsed; + } catch (Exception e) { + return null; + } + } +} diff --git a/src/main/java/autismclient/api/module/DisplayMode.java b/src/main/java/autismclient/api/module/DisplayMode.java new file mode 100644 index 0000000..5c37785 --- /dev/null +++ b/src/main/java/autismclient/api/module/DisplayMode.java @@ -0,0 +1,20 @@ +package autismclient.api.module; + +public enum DisplayMode { + + DEFAULT, + + READONLY_SUMMARY, + + NUMERIC_TEXT_FIELD, + + FILE_PICKER, + + PLAYER_NAME_LIST, + + RANK_TAG_LIST, + + MACRO_PICKER, + + CONDITIONAL_MACRO_PICKER +} diff --git a/src/main/java/autismclient/api/module/DoubleSetting.java b/src/main/java/autismclient/api/module/DoubleSetting.java new file mode 100644 index 0000000..dfd04d0 --- /dev/null +++ b/src/main/java/autismclient/api/module/DoubleSetting.java @@ -0,0 +1,42 @@ +package autismclient.api.module; + +public final class DoubleSetting extends Setting { + public DoubleSetting(String name, String title, double defaultValue, double min, double max, double step) { + super(Kind.DOUBLE, name, title, clamp(defaultValue, min, Math.max(min, max))); + setRange(min, max); + setSliderRange(min, max); + setStep(step <= 0 ? 0.1 : step); + } + + public DoubleSetting sliderRange(double min, double max) { + setSliderRange(min, max); + return this; + } + + @Override + protected Double decode(String raw) { + if (raw == null) return defaultValueTyped(); + try { + return clamp(Double.parseDouble(raw.trim()), min(), max()); + } catch (Exception e) { + return defaultValueTyped(); + } + } + + @Override + protected String encode(Double value) { + double v = value == null ? defaultValueTyped() : value; + return Double.toString(clamp(v, min(), max())); + } + + @Override + protected Double sanitizeTyped(Double value) { + double v = value == null ? defaultValueTyped() : value; + return clamp(v, min(), max()); + } + + private static double clamp(double value, double min, double max) { + if (Double.isNaN(value)) return min; + return Math.max(min, Math.min(max, value)); + } +} diff --git a/src/main/java/autismclient/api/module/EnumSetting.java b/src/main/java/autismclient/api/module/EnumSetting.java new file mode 100644 index 0000000..c9abf70 --- /dev/null +++ b/src/main/java/autismclient/api/module/EnumSetting.java @@ -0,0 +1,70 @@ +package autismclient.api.module; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; + +public final class EnumSetting> extends Setting> { + private final E[] values; + private final Function tokenizer; + + public EnumSetting(String name, String title, E defaultValue, E[] values, Function tokenizer) { + super(Kind.ENUM, name, title, defaultValue); + this.values = values == null ? newArray(defaultValue) : values; + this.tokenizer = tokenizer == null ? Enum::name : tokenizer; + List labels = new ArrayList<>(); + for (E value : this.values) labels.add(token(value)); + setChoices(labels); + } + + public EnumSetting(String name, String title, E defaultValue, E[] values) { + this(name, title, defaultValue, values, EnumSetting::titleCase); + } + + private String token(E value) { + if (value == null) return ""; + try { + String label = tokenizer.apply(value); + return label == null || label.isBlank() ? value.name() : label; + } catch (Throwable t) { + return value.name(); + } + } + + @Override + protected E decode(String raw) { + if (raw == null) return defaultValueTyped(); + String needle = raw.trim(); + if (needle.isEmpty()) return defaultValueTyped(); + for (E value : values) { + if (token(value).equalsIgnoreCase(needle)) return value; + } + for (E value : values) { + if (value.name().equalsIgnoreCase(needle)) return value; + } + return defaultValueTyped(); + } + + @Override + protected String encode(E value) { + return token(value == null ? defaultValueTyped() : value); + } + + @SuppressWarnings("unchecked") + private static > E[] newArray(E single) { + E[] array = (E[]) java.lang.reflect.Array.newInstance(single.getClass(), 1); + array[0] = single; + return array; + } + + public static String titleCase(Enum value) { + String[] words = value.name().toLowerCase(java.util.Locale.ROOT).split("_"); + StringBuilder out = new StringBuilder(); + for (String word : words) { + if (word.isEmpty()) continue; + if (out.length() > 0) out.append(' '); + out.append(Character.toUpperCase(word.charAt(0))).append(word.substring(1)); + } + return out.toString(); + } +} diff --git a/src/main/java/autismclient/api/module/IntSetting.java b/src/main/java/autismclient/api/module/IntSetting.java new file mode 100644 index 0000000..d56481d --- /dev/null +++ b/src/main/java/autismclient/api/module/IntSetting.java @@ -0,0 +1,45 @@ +package autismclient.api.module; + +public final class IntSetting extends Setting { + public IntSetting(String name, String title, int defaultValue, int min, int max, int step) { + super(Kind.INTEGER, name, title, clampStatic(defaultValue, min, Math.max(min, max))); + setRange(min, max); + setSliderRange(min, max); + setStep(Math.max(1, step)); + } + + public IntSetting sliderRange(double min, double max) { + setSliderRange(min, max); + return this; + } + + @Override + protected Integer decode(String raw) { + if (raw == null) return defaultValueTyped(); + try { + return (int) clampStatic((long) Double.parseDouble(raw.trim()), (long) min(), (long) max()); + } catch (Exception e) { + return defaultValueTyped(); + } + } + + @Override + protected String encode(Integer value) { + int v = value == null ? defaultValueTyped() : value; + return Integer.toString((int) clampStatic(v, (long) min(), (long) max())); + } + + @Override + protected Integer sanitizeTyped(Integer value) { + int v = value == null ? defaultValueTyped() : value; + return (int) clampStatic(v, (long) min(), (long) max()); + } + + private static int clampStatic(int value, int min, int max) { + return (int) clampStatic((long) value, (long) min, (long) max); + } + + private static long clampStatic(long value, long min, long max) { + return Math.max(min, Math.min(max, value)); + } +} diff --git a/src/main/java/autismclient/api/module/KeybindSetting.java b/src/main/java/autismclient/api/module/KeybindSetting.java new file mode 100644 index 0000000..0e5d70c --- /dev/null +++ b/src/main/java/autismclient/api/module/KeybindSetting.java @@ -0,0 +1,22 @@ +package autismclient.api.module; + +public final class KeybindSetting extends Setting { + public KeybindSetting(String name, String title, int defaultKey) { + super(Kind.KEYBIND, name, title, defaultKey); + } + + @Override + protected Integer decode(String raw) { + if (raw == null) return defaultValueTyped(); + try { + return Integer.parseInt(raw.trim()); + } catch (Exception e) { + return defaultValueTyped(); + } + } + + @Override + protected String encode(Integer value) { + return Integer.toString(value == null ? defaultValueTyped() : value); + } +} diff --git a/src/main/java/autismclient/api/module/Kind.java b/src/main/java/autismclient/api/module/Kind.java new file mode 100644 index 0000000..2e42449 --- /dev/null +++ b/src/main/java/autismclient/api/module/Kind.java @@ -0,0 +1,19 @@ +package autismclient.api.module; + +public enum Kind { + BOOLEAN, + INTEGER, + DOUBLE, + ENUM, + STRING, + STRING_LIST, + PACKET_LIST, + ITEM_LIST, + BLOCK_LIST, + ENTITY_TYPE_LIST, + SOUND_EVENT_LIST, + STORAGE_LIST, + COLOR, + KEYBIND, + ACTION +} diff --git a/src/main/java/autismclient/api/module/ListSetting.java b/src/main/java/autismclient/api/module/ListSetting.java new file mode 100644 index 0000000..952148a --- /dev/null +++ b/src/main/java/autismclient/api/module/ListSetting.java @@ -0,0 +1,47 @@ +package autismclient.api.module; + +import java.util.ArrayList; +import java.util.List; + +abstract class ListSetting> extends Setting, S> { + protected ListSetting(Kind kind, String name, String title, List defaultValue) { + super(kind, name, title, defaultValue == null ? List.of() : List.copyOf(defaultValue)); + } + + protected ListSetting(Kind kind, String name, String title, String defaultRaw) { + super(kind, name, title, parseRaw(defaultRaw)); + } + + static List parseRaw(String raw) { + if (raw == null || raw.isBlank()) return List.of(); + List out = new ArrayList<>(); + for (String part : raw.split("\\|")) { + String trimmed = part.trim(); + if (!trimmed.isEmpty()) out.add(trimmed); + } + return List.copyOf(out); + } + + @Override + protected List decode(String raw) { + if (raw == null || raw.isBlank()) return List.of(); + List out = new ArrayList<>(); + for (String part : raw.split("\\|")) { + String item = part.trim(); + if (!item.isEmpty()) out.add(item); + } + return List.copyOf(out); + } + + @Override + protected String encode(List value) { + if (value == null || value.isEmpty()) return ""; + List out = new ArrayList<>(); + for (String item : value) { + if (item == null) continue; + String trimmed = item.trim(); + if (!trimmed.isEmpty()) out.add(trimmed); + } + return String.join("|", out); + } +} diff --git a/src/main/java/autismclient/api/module/PacketListSetting.java b/src/main/java/autismclient/api/module/PacketListSetting.java new file mode 100644 index 0000000..0aca558 --- /dev/null +++ b/src/main/java/autismclient/api/module/PacketListSetting.java @@ -0,0 +1,17 @@ +package autismclient.api.module; + +import java.util.List; + +public final class PacketListSetting extends ListSetting { + public PacketListSetting(String name, String title) { + super(Kind.PACKET_LIST, name, title, List.of()); + } + + public PacketListSetting(String name, String title, List defaultValue) { + super(Kind.PACKET_LIST, name, title, defaultValue); + } + + public PacketListSetting(String name, String title, String defaultValue) { + super(Kind.PACKET_LIST, name, title, defaultValue); + } +} diff --git a/src/main/java/autismclient/api/module/RegistryListSetting.java b/src/main/java/autismclient/api/module/RegistryListSetting.java new file mode 100644 index 0000000..ee12f12 --- /dev/null +++ b/src/main/java/autismclient/api/module/RegistryListSetting.java @@ -0,0 +1,67 @@ +package autismclient.api.module; + +import java.util.ArrayList; +import java.util.List; + +public final class RegistryListSetting extends ListSetting { + private RegistryListSetting(Kind kind, String name, String title, String defaultValue) { + super(registryKindOrDefault(kind), name, title, parseDefault(defaultValue)); + } + + public static RegistryListSetting items(String name, String title) { + return items(name, title, ""); + } + + public static RegistryListSetting items(String name, String title, String defaultValue) { + return new RegistryListSetting(Kind.ITEM_LIST, name, title, defaultValue); + } + + public static RegistryListSetting blocks(String name, String title) { + return blocks(name, title, ""); + } + + public static RegistryListSetting blocks(String name, String title, String defaultValue) { + return new RegistryListSetting(Kind.BLOCK_LIST, name, title, defaultValue); + } + + public static RegistryListSetting entityTypes(String name, String title) { + return entityTypes(name, title, ""); + } + + public static RegistryListSetting entityTypes(String name, String title, String defaultValue) { + return new RegistryListSetting(Kind.ENTITY_TYPE_LIST, name, title, defaultValue); + } + + public static RegistryListSetting soundEvents(String name, String title) { + return soundEvents(name, title, ""); + } + + public static RegistryListSetting soundEvents(String name, String title, String defaultValue) { + return new RegistryListSetting(Kind.SOUND_EVENT_LIST, name, title, defaultValue); + } + + public static RegistryListSetting storages(String name, String title) { + return storages(name, title, ""); + } + + public static RegistryListSetting storages(String name, String title, String defaultValue) { + return new RegistryListSetting(Kind.STORAGE_LIST, name, title, defaultValue); + } + + private static List parseDefault(String raw) { + if (raw == null || raw.isBlank()) return List.of(); + List out = new ArrayList<>(); + for (String part : raw.split("\\|")) { + String trimmed = part.trim(); + if (!trimmed.isEmpty()) out.add(trimmed); + } + return List.copyOf(out); + } + + private static Kind registryKindOrDefault(Kind kind) { + return switch (kind == null ? Kind.ITEM_LIST : kind) { + case ITEM_LIST, BLOCK_LIST, ENTITY_TYPE_LIST, SOUND_EVENT_LIST, STORAGE_LIST -> kind; + default -> Kind.ITEM_LIST; + }; + } +} diff --git a/src/main/java/autismclient/api/module/Setting.java b/src/main/java/autismclient/api/module/Setting.java new file mode 100644 index 0000000..5a9ab6f --- /dev/null +++ b/src/main/java/autismclient/api/module/Setting.java @@ -0,0 +1,303 @@ +package autismclient.api.module; + +import java.util.List; +import java.util.Objects; +import java.util.function.BooleanSupplier; +import java.util.function.Function; + +public abstract class Setting> { + private final Kind kind; + private final String name; + private final T def; + private String title; + private String description = ""; + private String group = "General"; + private String unit = ""; + private DisplayMode displayMode = DisplayMode.DEFAULT; + private Availability availability; + private BooleanSupplier visible; + private Function formatter; + private Runnable action; + private String linkedActionId = ""; + private double min; + private double max; + private double sliderMin; + private double sliderMax; + private double step = 1.0; + private List choices = List.of(); + + private SettingOwner owner; + private transient boolean cached; + private transient String cachedRaw; + private transient T cachedValue; + + protected Setting(Kind kind, String name, String title, T def) { + this.kind = kind == null ? Kind.STRING : kind; + this.name = name == null ? "" : name; + this.title = title == null || title.isBlank() ? this.name : title; + this.def = def; + } + + @SuppressWarnings("unchecked") + protected final S self() { + return (S) this; + } + + protected abstract T decode(String raw); + + protected abstract String encode(T value); + + protected T sanitizeTyped(T value) { + return value == null ? def : value; + } + + public final void attach(SettingOwner owner) { + this.owner = owner; + this.cached = false; + } + + private String stored() { + if (owner == null) return defaultValue(); + String raw = owner.settingValue(name); + return raw == null ? defaultValue() : raw; + } + + public final T get() { + String raw = stored(); + if (cached && Objects.equals(raw, cachedRaw)) return cachedValue; + T value = decode(raw); + cachedRaw = raw; + cachedValue = value; + cached = true; + return value; + } + + public final void set(T value) { + if (owner != null) owner.putSettingValue(name, encode(sanitizeTyped(value))); + } + + public final T defaultValueTyped() { + return def; + } + + public final S description(String description) { + this.description = description == null ? "" : description; + return self(); + } + + public final S group(String group) { + this.group = group == null || group.isBlank() ? "General" : group; + return self(); + } + + public final S unit(String unit) { + this.unit = unit == null ? "" : unit; + return self(); + } + + public final S visibleWhen(BooleanSupplier visible) { + this.visible = visible; + return self(); + } + + public final S formatter(Function formatter) { + this.formatter = formatter; + return self(); + } + + public final S displayMode(DisplayMode displayMode) { + this.displayMode = displayMode == null ? DisplayMode.DEFAULT : displayMode; + return self(); + } + + public final S readonlySummary() { + return displayMode(DisplayMode.READONLY_SUMMARY); + } + + public final S numericTextField() { + return displayMode(DisplayMode.NUMERIC_TEXT_FIELD); + } + + public final S playerNameList() { + return displayMode(DisplayMode.PLAYER_NAME_LIST); + } + + public final S rankTagList() { + return displayMode(DisplayMode.RANK_TAG_LIST); + } + + public final S macroPicker() { + return displayMode(DisplayMode.MACRO_PICKER); + } + + public final S conditionalMacroPicker() { + return displayMode(DisplayMode.CONDITIONAL_MACRO_PICKER); + } + + public final S filePicker(String linkedActionId) { + this.linkedActionId = linkedActionId == null ? "" : linkedActionId; + return displayMode(DisplayMode.FILE_PICKER); + } + + public final S linkedActionId(String linkedActionId) { + this.linkedActionId = linkedActionId == null ? "" : linkedActionId; + return self(); + } + + public final S availableOffline() { + this.availability = Availability.ALWAYS; + return self(); + } + + public final S requiresWorld() { + this.availability = Availability.IN_WORLD; + return self(); + } + + public final S requiresContainer() { + this.availability = Availability.IN_CONTAINER; + return self(); + } + + public final S build() { + return self(); + } + + protected final void setRange(double min, double max) { + this.min = min; + this.max = Math.max(min, max); + } + + protected final void setSliderRange(double min, double max) { + this.sliderMin = min; + this.sliderMax = Math.max(min, max); + } + + protected final void setStep(double step) { + this.step = step <= 0 ? 1.0 : step; + } + + protected final void setChoices(List choices) { + this.choices = choices == null ? List.of() : List.copyOf(choices); + } + + protected final void setAction(Runnable action) { + this.action = action; + } + + public final String id() { + return name; + } + + public final String label() { + return title; + } + + public final String description() { + return description; + } + + public final String group() { + return group; + } + + public final Kind kind() { + return kind; + } + + public final DisplayMode displayMode() { + return displayMode; + } + + public final Availability availability() { + return availability == null + ? (kind == Kind.ACTION ? Availability.IN_WORLD : Availability.ALWAYS) + : availability; + } + + public final String unit() { + return unit; + } + + public final List choices() { + return choices; + } + + public final double min() { + return min; + } + + public final double max() { + return max; + } + + public final double sliderMin() { + return sliderMin; + } + + public final double sliderMax() { + return sliderMax; + } + + public final double step() { + return step; + } + + public final Runnable action() { + return action; + } + + public final String linkedActionId() { + return linkedActionId; + } + + public final String defaultValue() { + return encode(def); + } + + public final String serialize() { + return stored(); + } + + public final String displayString() { + return format(serialize()); + } + + public final String format(String value) { + if (formatter == null) return value == null ? "" : value; + try { + return formatter.apply(value); + } catch (Throwable t) { + return value == null ? "" : value; + } + } + + public final String sanitizeUiString(String raw) { + return encode(decode(raw)); + } + + public final String deserialize(String raw) { + return sanitizeUiString(raw); + } + + public final boolean isVisible() { + if (visible == null) return true; + try { + return visible.getAsBoolean(); + } catch (Throwable t) { + return true; + } + } + + public final boolean isAvailable(boolean inWorld, boolean inContainer) { + return switch (availability()) { + case ALWAYS -> true; + case IN_WORLD -> inWorld; + case IN_CONTAINER -> inContainer; + }; + } + + public final boolean isModified() { + return !Objects.equals(serialize(), defaultValue()); + } +} diff --git a/src/main/java/autismclient/api/module/SettingGroup.java b/src/main/java/autismclient/api/module/SettingGroup.java new file mode 100644 index 0000000..d4f6931 --- /dev/null +++ b/src/main/java/autismclient/api/module/SettingGroup.java @@ -0,0 +1,18 @@ +package autismclient.api.module; + +public final class SettingGroup { + private final String name; + + public SettingGroup(String name) { + this.name = name == null || name.isBlank() ? "General" : name; + } + + public String name() { + return name; + } + + public > S apply(S setting) { + if (setting != null) setting.group(name); + return setting; + } +} diff --git a/src/main/java/autismclient/api/module/SettingOwner.java b/src/main/java/autismclient/api/module/SettingOwner.java new file mode 100644 index 0000000..009bd6a --- /dev/null +++ b/src/main/java/autismclient/api/module/SettingOwner.java @@ -0,0 +1,8 @@ +package autismclient.api.module; + +public interface SettingOwner { + + String settingValue(String name); + + void putSettingValue(String name, String value); +} diff --git a/src/main/java/autismclient/api/module/SimpleModule.java b/src/main/java/autismclient/api/module/SimpleModule.java new file mode 100644 index 0000000..8617988 --- /dev/null +++ b/src/main/java/autismclient/api/module/SimpleModule.java @@ -0,0 +1,101 @@ +package autismclient.api.module; + +import autismclient.api.AutismAddons; +import autismclient.modules.Module; + +import java.util.Locale; +import java.util.function.Consumer; + +public class SimpleModule extends Module { + private Consumer enableHandler; + private Consumer disableHandler; + private Consumer tickHandler; + + public SimpleModule(String localId, String name, String description) { + super(AutismAddons.id(localId), name, description); + } + + public final SimpleModule onEnabled(Consumer handler) { + this.enableHandler = handler; + return this; + } + + public final SimpleModule onDisabled(Consumer handler) { + this.disableHandler = handler; + return this; + } + + public final SimpleModule onTick(Consumer handler) { + this.tickHandler = handler; + return this; + } + + public final SimpleModule addBool(String id, String label, boolean defaultValue) { + add(new BoolSetting(id, label, defaultValue)); + return this; + } + + public final SimpleModule addInt(String id, String label, int defaultValue, int min, int max, int step) { + add(new IntSetting(id, label, defaultValue, min, max, step)); + return this; + } + + public final SimpleModule addDouble(String id, String label, double defaultValue, double min, double max, double step) { + add(new DoubleSetting(id, label, defaultValue, min, max, step)); + return this; + } + + public final SimpleModule addChoice(String id, String label, String defaultValue, String... choices) { + add(new ChoiceSetting(id, label, defaultValue, choices == null ? new String[0] : choices)); + return this; + } + + public final SimpleModule addText(String id, String label, String defaultValue) { + add(new StringSetting(id, label, defaultValue)); + return this; + } + + public final SimpleModule addColor(String id, String label, int defaultArgb) { + add(new ColorSetting(id, label, defaultArgb)); + return this; + } + + public final boolean getBool(String id) { + return bool(id); + } + + public final int getInt(String id) { + return integer(id); + } + + public final double getDouble(String id) { + return decimal(id); + } + + public final String getText(String id) { + return text(id); + } + + public final String getChoice(String id) { + return choice(id); + } + + @Override + public void onEnable() { + if (enableHandler != null) enableHandler.accept(this); + } + + @Override + public void onDisable() { + if (disableHandler != null) disableHandler.accept(this); + } + + @Override + public void tick() { + if (tickHandler != null) tickHandler.accept(this); + } + + protected final String upper(String value) { + return value == null ? "" : value.toUpperCase(Locale.ROOT); + } +} diff --git a/src/main/java/autismclient/api/module/StringListSetting.java b/src/main/java/autismclient/api/module/StringListSetting.java new file mode 100644 index 0000000..8520779 --- /dev/null +++ b/src/main/java/autismclient/api/module/StringListSetting.java @@ -0,0 +1,17 @@ +package autismclient.api.module; + +import java.util.List; + +public final class StringListSetting extends ListSetting { + public StringListSetting(String name, String title) { + super(Kind.STRING_LIST, name, title, List.of()); + } + + public StringListSetting(String name, String title, List defaultValue) { + super(Kind.STRING_LIST, name, title, defaultValue); + } + + public StringListSetting(String name, String title, String defaultValue) { + super(Kind.STRING_LIST, name, title, defaultValue); + } +} diff --git a/src/main/java/autismclient/api/module/StringSetting.java b/src/main/java/autismclient/api/module/StringSetting.java new file mode 100644 index 0000000..a530a51 --- /dev/null +++ b/src/main/java/autismclient/api/module/StringSetting.java @@ -0,0 +1,17 @@ +package autismclient.api.module; + +public final class StringSetting extends Setting { + public StringSetting(String name, String title, String defaultValue) { + super(Kind.STRING, name, title, defaultValue == null ? "" : defaultValue); + } + + @Override + protected String decode(String raw) { + return raw == null ? "" : raw; + } + + @Override + protected String encode(String value) { + return value == null ? "" : value; + } +} diff --git a/src/main/java/autismclient/commands/AutismCommandSource.java b/src/main/java/autismclient/commands/AutismCommandSource.java new file mode 100644 index 0000000..13c0cce --- /dev/null +++ b/src/main/java/autismclient/commands/AutismCommandSource.java @@ -0,0 +1,18 @@ +package autismclient.commands; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.multiplayer.ClientPacketListener; + +public final class AutismCommandSource { + public static final AutismCommandSource INSTANCE = new AutismCommandSource(); + + private AutismCommandSource() {} + + public Minecraft mc() { return Minecraft.getInstance(); } + public LocalPlayer player() { return Minecraft.getInstance().player; } + public ClientPacketListener connection() { return Minecraft.getInstance().getConnection(); } + + public boolean hasPlayer() { return Minecraft.getInstance().player != null; } + public boolean hasConnection() { return Minecraft.getInstance().getConnection() != null; } +} diff --git a/src/main/java/autismclient/commands/AutismCommands.java b/src/main/java/autismclient/commands/AutismCommands.java new file mode 100644 index 0000000..2224d73 --- /dev/null +++ b/src/main/java/autismclient/commands/AutismCommands.java @@ -0,0 +1,247 @@ +package autismclient.commands; + +import autismclient.AutismClientAddon; +import autismclient.api.AddonRegistrationResult; +import autismclient.modules.PackHideState; +import autismclient.util.AutismClientMessaging; +import autismclient.util.AutismCompatManager; +import com.mojang.brigadier.CommandDispatcher; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.exceptions.CommandSyntaxException; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Locale; +import java.util.Set; + +public final class AutismCommands { + private static final CommandDispatcher DISPATCHER = new CommandDispatcher<>(); + private static final List ALL = new ArrayList<>(); + private static final Map BY_NAME = new LinkedHashMap<>(); + private static final Map ADDON_COMMAND_OWNERS = new LinkedHashMap<>(); + private static final Map ADDON_COMMAND_OBJECT_OWNERS = new IdentityHashMap<>(); + private static final Set DISABLED_ADDON_COMMAND_NAMES = new HashSet<>(); + private static final List PANIC_PREFIX_FALLBACKS = List.of(".", ",", ";", ":", "'", "\"", "\\", "|", "-", "_", "+", "=", "*", "#", "@", "!", "$", "%", "&", "~"); + private static boolean initialized = false; + + private AutismCommands() {} + + public static synchronized void init() { + if (initialized) return; + initialized = true; + register(new autismclient.commands.impl.ToggleCommand()); + register(new autismclient.commands.impl.MacroCommand()); + register(new autismclient.commands.impl.DelayCommand()); + register(new autismclient.commands.impl.SendCommand()); + register(new autismclient.commands.impl.VClipCommand()); + register(new autismclient.commands.impl.HClipCommand()); + register(new autismclient.commands.impl.NbtCommand()); + register(new autismclient.commands.impl.ServerCommand()); + register(new autismclient.commands.impl.PluginsCommand()); + register(new autismclient.commands.impl.PrefixCommand()); + register(new autismclient.commands.impl.CommandsCommand()); + register(new autismclient.commands.impl.HelpCommand()); + register(new autismclient.commands.impl.ModulesCommand()); + register(new autismclient.commands.impl.BindsCommand()); + register(new autismclient.commands.impl.BindCommand()); + register(new autismclient.commands.impl.DismountCommand()); + register(new autismclient.commands.impl.DisconnectCommand()); + register(new autismclient.commands.impl.SayCommand()); + register(new autismclient.commands.impl.DropCommand()); + register(new autismclient.commands.impl.ChangeSlotCommand()); + register(new autismclient.commands.impl.ClickSlotCommand()); + register(new autismclient.commands.impl.ClickItemCommand()); + register(new autismclient.commands.impl.GamemodeCommand()); + register(new autismclient.commands.impl.GiveCommand()); + register(new autismclient.commands.impl.DamageCommand()); + register(new autismclient.commands.impl.XCarryCommand()); + register(new autismclient.commands.impl.IrcCommand()); + register(new autismclient.commands.impl.MatchmakingCommand()); + register(new autismclient.commands.impl.MultiCommand()); + } + + private static void register(Command command) { + registerWithName(command, command.name(), true); + } + + private static List registerWithName(Command command, String primaryName, boolean registerAliases) { + List registeredNames = new ArrayList<>(); + ALL.add(command); + LiteralArgumentBuilder primary = LiteralArgumentBuilder.literal(primaryName); + command.build(primary); + DISPATCHER.register(primary); + BY_NAME.put(primaryName.toLowerCase(Locale.ROOT), command); + DISABLED_ADDON_COMMAND_NAMES.remove(primaryName.toLowerCase(Locale.ROOT)); + registeredNames.add(primaryName.toLowerCase(Locale.ROOT)); + + if (!registerAliases) return registeredNames; + for (String alias : command.aliases()) { + if (alias == null || alias.isBlank()) continue; + if (BY_NAME.containsKey(alias.toLowerCase(Locale.ROOT))) continue; + LiteralArgumentBuilder aliasBuilder = LiteralArgumentBuilder.literal(alias); + command.build(aliasBuilder); + DISPATCHER.register(aliasBuilder); + BY_NAME.put(alias.toLowerCase(Locale.ROOT), command); + DISABLED_ADDON_COMMAND_NAMES.remove(alias.toLowerCase(Locale.ROOT)); + registeredNames.add(alias.toLowerCase(Locale.ROOT)); + } + return registeredNames; + } + + public static synchronized void registerAddonCommand(Command command, String addonId) { + registerAddonCommandDetailed(command, addonId); + } + + public static synchronized AddonRegistrationResult registerAddonCommandDetailed(Command command, String addonId) { + if (command == null) return AddonRegistrationResult.rejected("command", "", "command was null"); + if (addonId == null || addonId.isBlank()) { + return rejectAddonCommand(addonId, "", "registration outside an addon lifecycle - register from onInitialize() or onRegisterCategories()"); + } + String name = command.name(); + if (name == null || name.isBlank()) { + return rejectAddonCommand(addonId, "", "blank command name"); + } + List registered; + boolean collision = BY_NAME.containsKey(name.toLowerCase(Locale.ROOT)); + if (collision) { + String namespaced = (addonId == null || addonId.isBlank() ? "addon" : addonId) + ":" + name; + AutismClientAddon.LOG.warn("[Commands] Command name '{}' from addon '{}' collides with an existing " + + "command; registering it as '{}' instead", name, addonId, namespaced); + registered = registerWithName(command, namespaced, false); + } else { + registered = registerWithName(command, name, true); + } + ADDON_COMMAND_OBJECT_OWNERS.put(command, addonId); + for (String registeredName : registered) { + ADDON_COMMAND_OWNERS.put(registeredName, addonId); + } + String id = registered.isEmpty() ? name : registered.get(0); + autismclient.addons.AddonManager.recordAcceptedRegistration("command", id); + return AddonRegistrationResult.accepted("command", id); + } + + private static AddonRegistrationResult rejectAddonCommand(String addonId, String id, String reason) { + AutismClientAddon.LOG.warn("[Commands] Rejecting addon command '{}': {}", id, reason); + autismclient.addons.AddonManager.recordRejectedRegistration(addonId, "command", id, reason); + return AddonRegistrationResult.rejected("command", id, reason); + } + + public static synchronized void unregisterAddonCommands(String addonId) { + if (addonId == null || addonId.isBlank()) return; + List removeNames = new ArrayList<>(); + for (Map.Entry owner : ADDON_COMMAND_OWNERS.entrySet()) { + if (addonId.equals(owner.getValue())) removeNames.add(owner.getKey()); + } + for (String name : removeNames) { + BY_NAME.remove(name); + ADDON_COMMAND_OWNERS.remove(name); + DISABLED_ADDON_COMMAND_NAMES.add(name); + } + ALL.removeIf(command -> addonId.equals(ADDON_COMMAND_OBJECT_OWNERS.get(command))); + ADDON_COMMAND_OBJECT_OWNERS.entrySet().removeIf(entry -> addonId.equals(entry.getValue())); + } + + public static CommandDispatcher dispatcher() { return DISPATCHER; } + + public static List all() { return Collections.unmodifiableList(ALL); } + + public static Command find(String nameOrAlias) { + if (nameOrAlias == null) return null; + return BY_NAME.get(nameOrAlias.trim().toLowerCase(Locale.ROOT)); + } + + public static String effectivePrefix() { return AutismCompatManager.effectiveCommandPrefix(); } + + public static boolean isAutismCommandMessage(String message) { + if (message == null || message.isBlank()) return false; + String trimmed = message.trim(); + String prefix = effectivePrefix(); + return !prefix.isEmpty() && trimmed.startsWith(prefix); + } + + public static boolean commandsBlockedByPanic() { + return PackHideState.isHardLocked(); + } + + public static boolean isBlockedPanicCommandMessage(String message) { + return commandsBlockedByPanic() && isPanicBlockedCommandMessage(message); + } + + private static boolean isPanicBlockedCommandMessage(String message) { + if (message == null || message.isBlank()) return false; + String trimmed = message.trim(); + if ("^toggleautism".equalsIgnoreCase(trimmed)) return true; + + String prefix = effectivePrefix(); + if (!prefix.isEmpty() && trimmed.startsWith(prefix)) return true; + + for (String fallback : PANIC_PREFIX_FALLBACKS) { + if (fallback == null || fallback.isEmpty() || fallback.equals(prefix)) continue; + if (!trimmed.startsWith(fallback)) continue; + String body = trimmed.substring(fallback.length()).trim(); + if (body.isEmpty()) continue; + String first = firstToken(body).toLowerCase(Locale.ROOT); + if (BY_NAME.containsKey(first) || DISABLED_ADDON_COMMAND_NAMES.contains(first)) return true; + } + return false; + } + + public static String commandBody(String message) { + if (!isAutismCommandMessage(message)) return ""; + String trimmed = message.trim(); + int prefixLength = effectivePrefix().length(); + return trimmed.length() <= prefixLength ? "" : trimmed.substring(prefixLength).trim(); + } + + public static boolean dispatch(String body) { + if (commandsBlockedByPanic()) return true; + if (body == null) return false; + String trimmed = body.trim(); + if (trimmed.isEmpty()) return false; + if (DISABLED_ADDON_COMMAND_NAMES.contains(firstToken(trimmed).toLowerCase(Locale.ROOT))) { + sendSyntaxError(trimmed, CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownCommand().create()); + return true; + } + try { + DISPATCHER.execute(trimmed, AutismCommandSource.INSTANCE); + return true; + } catch (CommandSyntaxException e) { + sendSyntaxError(trimmed, e); + return true; + } catch (Exception e) { + AutismClientAddon.LOG.warn("[Commands] dispatch failed for '{}'", trimmed, e); + AutismClientMessaging.sendPrefixed("§cCommand error: " + + (e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage())); + return true; + } + } + + private static void sendSyntaxError(String body, CommandSyntaxException e) { + String first = firstToken(body); + Command command = find(first); + String prefix = effectivePrefix(); + if (command == null) { + AutismClientMessaging.sendPrefixed("§cUnknown AUTISM command: §f" + first); + AutismClientMessaging.sendPrefixed("§7Use §f" + prefix + "commands §7or §f" + prefix + "help§7."); + return; + } + + String message = e.getMessage(); + if (message == null || message.isBlank()) message = "Incomplete or invalid command."; + AutismClientMessaging.sendPrefixed("§c" + message); + AutismClientMessaging.sendPrefixed("§7Use §f" + prefix + "help " + command.name() + "§7."); + } + + private static String firstToken(String body) { + if (body == null) return ""; + String trimmed = body.trim(); + if (trimmed.isEmpty()) return ""; + int space = trimmed.indexOf(' '); + return space < 0 ? trimmed : trimmed.substring(0, space); + } +} diff --git a/src/main/java/autismclient/commands/Command.java b/src/main/java/autismclient/commands/Command.java new file mode 100644 index 0000000..f643705 --- /dev/null +++ b/src/main/java/autismclient/commands/Command.java @@ -0,0 +1,33 @@ +package autismclient.commands; + +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.context.CommandContext; + +public abstract class Command { + public static final int SUCCESS = 1; + + private final String name; + private final String description; + private final String[] aliases; + + protected Command(String name, String description, String... aliases) { + this.name = name; + this.description = description == null ? "" : description; + this.aliases = aliases == null ? new String[0] : aliases.clone(); + } + + public final String name() { return name; } + public final String description() { return description; } + public final String[] aliases() { return aliases.clone(); } + + public abstract void build(LiteralArgumentBuilder builder); + + public int run(CommandContext ctx) { + autismclient.util.AutismClientMessaging.sendPrefixed( + "§eUsage: " + AutismCommands.effectivePrefix() + name + (aliases.length > 0 ? " (alias: " + aliases[0] + ")" : "")); + if (!description.isEmpty()) { + autismclient.util.AutismClientMessaging.sendPrefixed("§7" + description); + } + return SUCCESS; + } +} diff --git a/src/main/java/autismclient/commands/CommandSuggest.java b/src/main/java/autismclient/commands/CommandSuggest.java new file mode 100644 index 0000000..8511042 --- /dev/null +++ b/src/main/java/autismclient/commands/CommandSuggest.java @@ -0,0 +1,65 @@ +package autismclient.commands; + +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; + +import java.util.Locale; +import java.util.concurrent.CompletableFuture; + +public final class CommandSuggest { + private CommandSuggest() {} + + public static CompletableFuture literals(SuggestionsBuilder builder, String... values) { + String remaining = builder.getRemaining().toLowerCase(Locale.ROOT); + for (String value : values) { + if (value != null && value.toLowerCase(Locale.ROOT).startsWith(remaining)) builder.suggest(value); + } + return builder.buildFuture(); + } + + public static CompletableFuture state(CommandContext ignored, SuggestionsBuilder builder) { + return literals(builder, "on", "off", "toggle", "enable", "disable"); + } + + public static CompletableFuture offsets(CommandContext ignored, SuggestionsBuilder builder) { + return literals(builder, "1", "5", "10", "50", "100", "-1", "-5", "-10", "-50", "-100"); + } + + public static CompletableFuture vclipSegments(CommandContext ignored, SuggestionsBuilder builder) { + return literals(builder, "1", "5", "10", "20", "50"); + } + + public static CompletableFuture vclipPacketLimits(CommandContext ignored, SuggestionsBuilder builder) { + return literals(builder, "1", "5", "10", "20", "40", "100"); + } + + public static CompletableFuture damage(CommandContext ignored, SuggestionsBuilder builder) { + return literals(builder, "1", "2", "4", "8", "20"); + } + + public static CompletableFuture counts(CommandContext ignored, SuggestionsBuilder builder) { + return literals(builder, "1", "16", "32", "64"); + } + + public static CompletableFuture gamemodes(CommandContext ignored, SuggestionsBuilder builder) { + return literals(builder, "survival", "creative", "adventure", "spectator", "reset", "0", "1", "2", "3"); + } + + public static CompletableFuture prefixes(CommandContext ignored, SuggestionsBuilder builder) { + return literals(builder, ".", "%", "-", "_", "*", "#", "@", "&", "="); + } + + public static CompletableFuture itemIds(CommandContext ignored, SuggestionsBuilder builder) { + String remaining = builder.getRemaining().toLowerCase(Locale.ROOT); + for (Identifier id : BuiltInRegistries.ITEM.keySet()) { + String full = id.toString(); + String shortId = id.getNamespace().equals("minecraft") ? id.getPath() : full; + if (full.toLowerCase(Locale.ROOT).startsWith(remaining)) builder.suggest(full); + if (!shortId.equals(full) && shortId.toLowerCase(Locale.ROOT).startsWith(remaining)) builder.suggest(shortId); + } + return builder.buildFuture(); + } +} diff --git a/src/main/java/autismclient/commands/args/KeyArgumentType.java b/src/main/java/autismclient/commands/args/KeyArgumentType.java new file mode 100644 index 0000000..5583ce4 --- /dev/null +++ b/src/main/java/autismclient/commands/args/KeyArgumentType.java @@ -0,0 +1,72 @@ +package autismclient.commands.args; + +import autismclient.commands.AutismCommandSource; +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; +import net.minecraft.network.chat.Component; +import org.lwjgl.glfw.GLFW; + +import java.lang.reflect.Field; +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +public class KeyArgumentType implements ArgumentType { + private static final Map NAMES = new LinkedHashMap<>(); + private static final SimpleCommandExceptionType UNKNOWN = new SimpleCommandExceptionType(Component.literal("Unknown key")); + + static { + for (Field f : GLFW.class.getDeclaredFields()) { + String n = f.getName(); + if (!n.startsWith("GLFW_KEY_")) continue; + try { + int code = f.getInt(null); + NAMES.put(n.substring("GLFW_KEY_".length()).toUpperCase(Locale.ROOT), code); + } catch (Throwable ignored) { } + } + } + + public static KeyArgumentType key() { return new KeyArgumentType(); } + + public static int get(CommandContext ctx, String name) { + return ctx.getArgument(name, Integer.class); + } + + public static String keyName(int code) { + if (code < 0) return "NONE"; + for (Map.Entry e : NAMES.entrySet()) { + if (e.getValue() == code) return e.getKey(); + } + return "KEY_" + code; + } + + @Override + public Integer parse(StringReader reader) throws CommandSyntaxException { + String raw = reader.readUnquotedString(); + String upper = raw.toUpperCase(Locale.ROOT); + Integer code = NAMES.get(upper); + if (code != null) return code; + + if (upper.length() == 1) { + char c = upper.charAt(0); + if (c >= 'A' && c <= 'Z') return GLFW.GLFW_KEY_A + (c - 'A'); + if (c >= '0' && c <= '9') return GLFW.GLFW_KEY_0 + (c - '0'); + } + throw UNKNOWN.create(); + } + + @Override + public CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) { + String remaining = builder.getRemaining().toUpperCase(Locale.ROOT); + for (String n : NAMES.keySet()) { + if (n.startsWith(remaining)) builder.suggest(n); + } + return builder.buildFuture(); + } +} diff --git a/src/main/java/autismclient/commands/args/MacroArgumentType.java b/src/main/java/autismclient/commands/args/MacroArgumentType.java new file mode 100644 index 0000000..913b75d --- /dev/null +++ b/src/main/java/autismclient/commands/args/MacroArgumentType.java @@ -0,0 +1,41 @@ +package autismclient.commands.args; + +import autismclient.commands.AutismCommandSource; +import autismclient.util.AutismMacroManager; +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; + +import java.util.Locale; +import java.util.concurrent.CompletableFuture; + +public class MacroArgumentType implements ArgumentType { + public static MacroArgumentType macroName() { return new MacroArgumentType(); } + + public static String get(CommandContext ctx, String name) { + return ctx.getArgument(name, String.class); + } + + @Override + public String parse(StringReader reader) throws CommandSyntaxException { + + if (reader.canRead() && reader.peek() == '"') return reader.readQuotedString(); + return reader.readUnquotedString(); + } + + @Override + public CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) { + String remaining = builder.getRemaining().toLowerCase(Locale.ROOT); + for (autismclient.util.AutismMacro macro : AutismMacroManager.get().getAll()) { + if (macro == null || macro.name == null) continue; + String n = macro.name; + if (n.toLowerCase(Locale.ROOT).startsWith(remaining)) { + builder.suggest(n.contains(" ") ? "\"" + n + "\"" : n); + } + } + return builder.buildFuture(); + } +} diff --git a/src/main/java/autismclient/commands/args/MenuSlotArgumentType.java b/src/main/java/autismclient/commands/args/MenuSlotArgumentType.java new file mode 100644 index 0000000..95ce78c --- /dev/null +++ b/src/main/java/autismclient/commands/args/MenuSlotArgumentType.java @@ -0,0 +1,117 @@ +package autismclient.commands.args; + +import autismclient.commands.AutismCommandSource; +import autismclient.util.AutismInventoryHelper; +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; +import net.minecraft.client.Minecraft; +import net.minecraft.network.chat.Component; +import net.minecraft.world.inventory.AbstractContainerMenu; + +import java.util.LinkedHashSet; +import java.util.Locale; +import java.util.Set; +import java.util.concurrent.CompletableFuture; + +public final class MenuSlotArgumentType implements ArgumentType { + private static final SimpleCommandExceptionType INVALID_SLOT = new SimpleCommandExceptionType( + Component.literal("Unknown slot. Use gui1, hotbar1, inventory1, helmet, chestplate, leggings, boots, offhand, or a visible numeric slot id.")); + + private MenuSlotArgumentType() { + } + + public static MenuSlotArgumentType slot() { + return new MenuSlotArgumentType(); + } + + public static int get(CommandContext context, String name) { + return context.getArgument(name, Integer.class); + } + + @Override + public Integer parse(StringReader reader) throws CommandSyntaxException { + String token = reader.readUnquotedString().trim().toLowerCase(Locale.ROOT); + if (token.isEmpty()) throw INVALID_SLOT.create(); + + Integer named = parseNamed(token); + if (named != null) return named; + try { + int numeric = Integer.parseInt(token); + if (numeric >= 0) return numeric; + } catch (NumberFormatException ignored) { } + throw INVALID_SLOT.create(); + } + + @Override + public CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) { + String remaining = builder.getRemaining().toLowerCase(Locale.ROOT); + Set values = new LinkedHashSet<>(); + Minecraft mc = Minecraft.getInstance(); + if (mc.player != null && mc.player.containerMenu != null) { + AbstractContainerMenu menu = mc.player.containerMenu; + for (int handlerSlot = 0; handlerSlot < menu.slots.size(); handlerSlot++) { + int visible = AutismInventoryHelper.toUserVisibleSlot(mc, handlerSlot); + values.add(displayToken(visible)); + values.add(String.valueOf(visible)); + } + } else { + for (int slot = 1; slot <= 9; slot++) values.add("hotbar" + slot); + } + + for (String value : values) { + if (value.toLowerCase(Locale.ROOT).startsWith(remaining)) builder.suggest(value); + } + return builder.buildFuture(); + } + + public static String displayToken(int visibleSlot) { + if (visibleSlot >= AutismInventoryHelper.FIRST_GUI_SLOT) { + return "gui" + (visibleSlot - AutismInventoryHelper.FIRST_GUI_SLOT + 1); + } + if (visibleSlot >= 0 && visibleSlot <= 8) return "hotbar" + (visibleSlot + 1); + if (visibleSlot >= 9 && visibleSlot <= 35) return "inventory" + (visibleSlot - 8); + return switch (visibleSlot) { + case 36 -> "boots"; + case 37 -> "leggings"; + case 38 -> "chestplate"; + case 39 -> "helmet"; + case 40 -> "offhand"; + default -> String.valueOf(visibleSlot); + }; + } + + private static Integer parseNamed(String token) { + return switch (token) { + case "boots" -> 36; + case "leggings" -> 37; + case "chestplate" -> 38; + case "helmet" -> 39; + case "offhand" -> 40; + default -> { + Integer gui = parseIndexed(token, "gui", AutismInventoryHelper.FIRST_GUI_SLOT, Integer.MAX_VALUE); + if (gui != null) yield gui; + Integer hotbar = parseIndexed(token, "hotbar", 0, 9); + if (hotbar != null) yield hotbar; + yield parseIndexed(token, "inventory", 9, 27); + } + }; + } + + private static Integer parseIndexed(String token, String prefix, int offset, int maxIndex) { + if (!token.startsWith(prefix)) return null; + String suffix = token.substring(prefix.length()); + if (suffix.startsWith(":")) suffix = suffix.substring(1); + try { + int oneBased = Integer.parseInt(suffix); + if (oneBased < 1 || oneBased > maxIndex) return null; + return offset + oneBased - 1; + } catch (NumberFormatException ignored) { + return null; + } + } +} diff --git a/src/main/java/autismclient/commands/args/ModuleArgumentType.java b/src/main/java/autismclient/commands/args/ModuleArgumentType.java new file mode 100644 index 0000000..2d9dac4 --- /dev/null +++ b/src/main/java/autismclient/commands/args/ModuleArgumentType.java @@ -0,0 +1,41 @@ +package autismclient.commands.args; + +import autismclient.commands.AutismCommandSource; +import autismclient.modules.ModuleRegistry; +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; + +import java.util.Locale; +import java.util.concurrent.CompletableFuture; + +public class ModuleArgumentType implements ArgumentType { + public static ModuleArgumentType moduleName() { return new ModuleArgumentType(); } + + public static String get(CommandContext ctx, String name) { + return ctx.getArgument(name, String.class); + } + + @Override + public String parse(StringReader reader) throws CommandSyntaxException { + return reader.readUnquotedString(); + } + + @Override + public CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) { + String remaining = builder.getRemaining().toLowerCase(Locale.ROOT); + for (String name : ModuleRegistry.names()) { + if (name == null) continue; + if (name.toLowerCase(Locale.ROOT).startsWith(remaining)) { + builder.suggest(name); + } + } + + if ("all".startsWith(remaining)) builder.suggest("all"); + if ("hud".startsWith(remaining)) builder.suggest("hud"); + return builder.buildFuture(); + } +} diff --git a/src/main/java/autismclient/commands/args/MultiProfileArgumentType.java b/src/main/java/autismclient/commands/args/MultiProfileArgumentType.java new file mode 100644 index 0000000..668de73 --- /dev/null +++ b/src/main/java/autismclient/commands/args/MultiProfileArgumentType.java @@ -0,0 +1,43 @@ +package autismclient.commands.args; + +import autismclient.commands.AutismCommandSource; +import autismclient.util.multi.MultiProfile; +import autismclient.util.multi.MultiProfileManager; +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; + +import java.util.Locale; +import java.util.concurrent.CompletableFuture; + +public class MultiProfileArgumentType implements ArgumentType { + public static MultiProfileArgumentType profileName() { + return new MultiProfileArgumentType(); + } + + public static String get(CommandContext ctx, String name) { + return ctx.getArgument(name, String.class); + } + + @Override + public String parse(StringReader reader) throws CommandSyntaxException { + if (reader.canRead() && reader.peek() == '"') return reader.readQuotedString(); + return reader.readUnquotedString(); + } + + @Override + public CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) { + String remaining = builder.getRemaining().toLowerCase(Locale.ROOT); + for (MultiProfile profile : MultiProfileManager.get()) { + if (profile == null || profile.name == null) continue; + String n = profile.name; + if (n.toLowerCase(Locale.ROOT).startsWith(remaining)) { + builder.suggest(n.contains(" ") ? "\"" + n + "\"" : n); + } + } + return builder.buildFuture(); + } +} diff --git a/src/main/java/autismclient/commands/args/PacketClassArgumentType.java b/src/main/java/autismclient/commands/args/PacketClassArgumentType.java new file mode 100644 index 0000000..3e2d5c6 --- /dev/null +++ b/src/main/java/autismclient/commands/args/PacketClassArgumentType.java @@ -0,0 +1,39 @@ +package autismclient.commands.args; + +import autismclient.commands.AutismCommandSource; +import autismclient.util.AutismPacketRegistry; +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; +import net.minecraft.network.protocol.Packet; + +import java.util.Locale; +import java.util.concurrent.CompletableFuture; + +public class PacketClassArgumentType implements ArgumentType { + public static PacketClassArgumentType packetClass() { return new PacketClassArgumentType(); } + + public static String get(CommandContext ctx, String name) { + return ctx.getArgument(name, String.class); + } + + @Override + public String parse(StringReader reader) throws CommandSyntaxException { + return reader.readUnquotedString(); + } + + @Override + public CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) { + String remaining = builder.getRemaining().toLowerCase(Locale.ROOT); + + for (Class> cls : AutismPacketRegistry.getC2SPackets()) { + String name = AutismPacketRegistry.getName(cls); + if (name == null) continue; + if (name.toLowerCase(Locale.ROOT).contains(remaining)) builder.suggest(name); + } + return builder.buildFuture(); + } +} diff --git a/src/main/java/autismclient/commands/args/VisibleItemNameArgumentType.java b/src/main/java/autismclient/commands/args/VisibleItemNameArgumentType.java new file mode 100644 index 0000000..2d0529b --- /dev/null +++ b/src/main/java/autismclient/commands/args/VisibleItemNameArgumentType.java @@ -0,0 +1,62 @@ +package autismclient.commands.args; + +import autismclient.commands.AutismCommandSource; +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; +import net.minecraft.client.Minecraft; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.item.ItemStack; + +import java.util.LinkedHashSet; +import java.util.Locale; +import java.util.Set; +import java.util.concurrent.CompletableFuture; + +public final class VisibleItemNameArgumentType implements ArgumentType { + private VisibleItemNameArgumentType() { + } + + public static VisibleItemNameArgumentType itemName() { + return new VisibleItemNameArgumentType(); + } + + public static String get(CommandContext context, String name) { + return context.getArgument(name, String.class); + } + + @Override + public String parse(StringReader reader) throws com.mojang.brigadier.exceptions.CommandSyntaxException { + return reader.readString(); + } + + @Override + public CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) { + String remaining = builder.getRemaining().toLowerCase(Locale.ROOT); + if (remaining.startsWith("\"")) remaining = remaining.substring(1); + + Set names = new LinkedHashSet<>(); + Minecraft mc = Minecraft.getInstance(); + if (mc.player != null) { + AbstractContainerMenu menu = mc.player.containerMenu; + if (menu != null) { + for (int slot = 0; slot < menu.slots.size(); slot++) { + ItemStack stack = menu.slots.get(slot).getItem(); + if (stack.isEmpty()) continue; + String displayName = stack.getHoverName().getString().replaceAll("\\s+", " ").trim(); + if (!displayName.isEmpty()) names.add(displayName); + } + } + } + + for (String name : names) { + if (name.toLowerCase(Locale.ROOT).startsWith(remaining)) { + builder.suggest(StringArgumentType.escapeIfRequired(name)); + } + } + return builder.buildFuture(); + } +} diff --git a/src/main/java/autismclient/commands/args/XCarrySlotArgumentType.java b/src/main/java/autismclient/commands/args/XCarrySlotArgumentType.java new file mode 100644 index 0000000..a68f569 --- /dev/null +++ b/src/main/java/autismclient/commands/args/XCarrySlotArgumentType.java @@ -0,0 +1,68 @@ +package autismclient.commands.args; + +import autismclient.commands.AutismCommandSource; +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; +import net.minecraft.network.chat.Component; + +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +public class XCarrySlotArgumentType implements ArgumentType { + public static final int CURSOR = Integer.MIN_VALUE; + + private static final Map TOKENS = new LinkedHashMap<>(); + static { + TOKENS.put("craft1", 1); + TOKENS.put("craft2", 2); + TOKENS.put("craft3", 3); + TOKENS.put("craft4", 4); + TOKENS.put("craft5", 0); + TOKENS.put("crafting5", 0); + TOKENS.put("result", 0); + TOKENS.put("helmet", 5); + TOKENS.put("chestplate", 6); + TOKENS.put("leggings", 7); + TOKENS.put("boots", 8); + TOKENS.put("offhand", 45); + TOKENS.put("cursor", CURSOR); + } + + private static final SimpleCommandExceptionType UNKNOWN = + new SimpleCommandExceptionType(Component.literal("Unknown XCarry slot — use craft1..craft5 / helmet / chestplate / leggings / boots / offhand / cursor.")); + + public static XCarrySlotArgumentType slot() { return new XCarrySlotArgumentType(); } + + public static int get(CommandContext ctx, String name) { + return ctx.getArgument(name, Integer.class); + } + + public static String displayName(int slotId) { + for (Map.Entry e : TOKENS.entrySet()) if (e.getValue() == slotId) return e.getKey(); + return "slot " + slotId; + } + + @Override + public Integer parse(StringReader reader) throws CommandSyntaxException { + String raw = reader.readUnquotedString().toLowerCase(Locale.ROOT); + Integer id = TOKENS.get(raw); + if (id == null) throw UNKNOWN.create(); + return id; + } + + @Override + public CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) { + String remaining = builder.getRemaining().toLowerCase(Locale.ROOT); + for (String name : TOKENS.keySet()) { + if (name.startsWith(remaining)) builder.suggest(name); + } + return builder.buildFuture(); + } +} diff --git a/src/main/java/autismclient/commands/impl/BindCommand.java b/src/main/java/autismclient/commands/impl/BindCommand.java new file mode 100644 index 0000000..6a1423d --- /dev/null +++ b/src/main/java/autismclient/commands/impl/BindCommand.java @@ -0,0 +1,42 @@ +package autismclient.commands.impl; + +import autismclient.commands.Command; +import autismclient.commands.AutismCommandSource; +import autismclient.commands.AutismCommands; +import autismclient.commands.args.KeyArgumentType; +import autismclient.modules.AutismModule; +import autismclient.util.AutismClientMessaging; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; + +public class BindCommand extends Command { + public BindCommand() { super("bind", "Bind a key to a command. Usage: bind | bind clear "); } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + String prefix = AutismCommands.effectivePrefix(); + AutismClientMessaging.sendPrefixed("§eUsage: §f" + prefix + "bind "); + AutismClientMessaging.sendPrefixed("§7Example: §f" + prefix + "bind G " + prefix + "macro myMacro"); + return SUCCESS; + }); + root.then(LiteralArgumentBuilder.literal("clear") + .then(RequiredArgumentBuilder.argument("key", KeyArgumentType.key()) + .executes(ctx -> { + int key = KeyArgumentType.get(ctx, "key"); + AutismModule.get().clearCommandBind(key); + AutismClientMessaging.sendPrefixed("§eCleared bind for §f" + KeyArgumentType.keyName(key)); + return SUCCESS; + }))); + root.then(RequiredArgumentBuilder.argument("key", KeyArgumentType.key()) + .then(RequiredArgumentBuilder.argument("command", StringArgumentType.greedyString()) + .executes(ctx -> { + int key = KeyArgumentType.get(ctx, "key"); + String cmd = StringArgumentType.getString(ctx, "command"); + AutismModule.get().setCommandBind(key, cmd); + AutismClientMessaging.sendPrefixed("§aBound §f" + KeyArgumentType.keyName(key) + "§a → §f" + cmd); + return SUCCESS; + }))); + } +} diff --git a/src/main/java/autismclient/commands/impl/BindsCommand.java b/src/main/java/autismclient/commands/impl/BindsCommand.java new file mode 100644 index 0000000..4c14cf3 --- /dev/null +++ b/src/main/java/autismclient/commands/impl/BindsCommand.java @@ -0,0 +1,27 @@ +package autismclient.commands.impl; + +import autismclient.commands.Command; +import autismclient.commands.AutismCommandSource; +import autismclient.commands.args.KeyArgumentType; +import autismclient.modules.AutismModule; +import autismclient.util.AutismClientMessaging; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; + +import java.util.Map; + +public class BindsCommand extends Command { + public BindsCommand() { super("binds", "List command keybinds (set with `bind`)."); } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + Map binds = AutismModule.get().getCommandBinds(); + if (binds.isEmpty()) { AutismClientMessaging.sendPrefixed("§eNo command keybinds set."); return SUCCESS; } + AutismClientMessaging.sendPrefixed("§e" + binds.size() + " command keybinds:"); + for (Map.Entry e : binds.entrySet()) { + AutismClientMessaging.sendPrefixed("§b" + KeyArgumentType.keyName(e.getKey()) + "§7 → §f" + e.getValue()); + } + return SUCCESS; + }); + } +} diff --git a/src/main/java/autismclient/commands/impl/ChangeSlotCommand.java b/src/main/java/autismclient/commands/impl/ChangeSlotCommand.java new file mode 100644 index 0000000..e639fd8 --- /dev/null +++ b/src/main/java/autismclient/commands/impl/ChangeSlotCommand.java @@ -0,0 +1,44 @@ +package autismclient.commands.impl; + +import autismclient.commands.AutismCommandSource; +import autismclient.commands.AutismCommands; +import autismclient.commands.Command; +import autismclient.commands.CommandSuggest; +import autismclient.util.AutismClientMessaging; +import autismclient.util.AutismInventoryHelper; +import com.mojang.brigadier.arguments.IntegerArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; +import net.minecraft.client.Minecraft; + +public final class ChangeSlotCommand extends Command { + public ChangeSlotCommand() { + super("change-slot", "Select hotbar slot 1-9."); + } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(context -> { + AutismClientMessaging.sendPrefixed( + "§eUsage: §f" + AutismCommands.effectivePrefix() + "change-slot <1-9>"); + return SUCCESS; + }); + root.then(RequiredArgumentBuilder.argument( + "hotbar-slot", IntegerArgumentType.integer(1, 9)) + .suggests((context, builder) -> CommandSuggest.literals( + builder, "1", "2", "3", "4", "5", "6", "7", "8", "9")) + .executes(context -> changeSlot(IntegerArgumentType.getInteger(context, "hotbar-slot")))); + } + + private static int changeSlot(int oneBasedSlot) { + Minecraft mc = Minecraft.getInstance(); + if (mc.player == null || mc.getConnection() == null) { + AutismClientMessaging.sendPrefixed("§cNot in a world."); + return SUCCESS; + } + + AutismInventoryHelper.selectHotbarSlot(mc, oneBasedSlot - 1); + AutismClientMessaging.sendPrefixed("§aSelected hotbar slot §f" + oneBasedSlot + "§a."); + return SUCCESS; + } +} diff --git a/src/main/java/autismclient/commands/impl/ClickItemCommand.java b/src/main/java/autismclient/commands/impl/ClickItemCommand.java new file mode 100644 index 0000000..155c4e6 --- /dev/null +++ b/src/main/java/autismclient/commands/impl/ClickItemCommand.java @@ -0,0 +1,72 @@ +package autismclient.commands.impl; + +import autismclient.commands.AutismCommandSource; +import autismclient.commands.AutismCommands; +import autismclient.commands.Command; +import autismclient.commands.args.VisibleItemNameArgumentType; +import autismclient.util.AutismClientMessaging; +import autismclient.util.macro.ItemTarget; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; +import net.minecraft.client.Minecraft; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.ContainerInput; +import net.minecraft.world.item.ItemStack; + +public final class ClickItemCommand extends Command { + public ClickItemCommand() { + super("click-item", "Click an item by its visible in-game name."); + } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(context -> { + AutismClientMessaging.sendPrefixed( + "§eUsage: §f" + AutismCommands.effectivePrefix() + + "click-item \"\" [click] [times]"); + return SUCCESS; + }); + + RequiredArgumentBuilder item = RequiredArgumentBuilder + .argument("item-name", VisibleItemNameArgumentType.itemName()) + .executes(context -> click(context, ItemClickCommandSupport.ClickSpec.click( + "Left", ContainerInput.PICKUP, 0), 1)); + ItemClickCommandSupport.attachModes(item, ClickItemCommand::click); + root.then(item); + } + + private static int click( + com.mojang.brigadier.context.CommandContext context, + ItemClickCommandSupport.ClickSpec spec, + int times + ) { + Minecraft mc = Minecraft.getInstance(); + if (mc.player == null || mc.player.containerMenu == null) { + AutismClientMessaging.sendPrefixed("§cNo active inventory or GUI."); + return SUCCESS; + } + + String requestedName = VisibleItemNameArgumentType.get(context, "item-name"); + int handlerSlot = findByVisibleName(mc.player.containerMenu, requestedName); + if (handlerSlot < 0) { + AutismClientMessaging.sendPrefixed( + "§cNo visible item named §f" + requestedName + "§c exists in the current GUI."); + return SUCCESS; + } + return ItemClickCommandSupport.clickHandlerSlot( + handlerSlot, spec, times, "\"" + requestedName + "\""); + } + + private static int findByVisibleName(AbstractContainerMenu menu, String requestedName) { + String normalizedTarget = ItemTarget.normalize(requestedName); + if (normalizedTarget.isEmpty()) return -1; + for (int handlerSlot = 0; handlerSlot < menu.slots.size(); handlerSlot++) { + ItemStack stack = menu.slots.get(handlerSlot).getItem(); + if (stack.isEmpty()) continue; + if (normalizedTarget.equals(ItemTarget.normalize(stack.getHoverName().getString()))) { + return handlerSlot; + } + } + return -1; + } +} diff --git a/src/main/java/autismclient/commands/impl/ClickSlotCommand.java b/src/main/java/autismclient/commands/impl/ClickSlotCommand.java new file mode 100644 index 0000000..90c5091 --- /dev/null +++ b/src/main/java/autismclient/commands/impl/ClickSlotCommand.java @@ -0,0 +1,51 @@ +package autismclient.commands.impl; + +import autismclient.commands.AutismCommandSource; +import autismclient.commands.AutismCommands; +import autismclient.commands.Command; +import autismclient.commands.args.MenuSlotArgumentType; +import autismclient.util.AutismClientMessaging; +import autismclient.util.AutismInventoryHelper; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; +import net.minecraft.client.Minecraft; +import net.minecraft.world.inventory.ContainerInput; + +public final class ClickSlotCommand extends Command { + public ClickSlotCommand() { + super("click-slot", "Click a GUI/player slot with Item Click actions."); + } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(context -> { + AutismClientMessaging.sendPrefixed( + "§eUsage: §f" + AutismCommands.effectivePrefix() + "click-slot [click] [times]"); + return SUCCESS; + }); + + RequiredArgumentBuilder slot = RequiredArgumentBuilder + .argument("slot", MenuSlotArgumentType.slot()) + .executes(context -> click(context, ItemClickCommandSupport.ClickSpec.click( + "Left", ContainerInput.PICKUP, 0), 1)); + ItemClickCommandSupport.attachModes(slot, ClickSlotCommand::click); + root.then(slot); + } + + private static int click( + com.mojang.brigadier.context.CommandContext context, + ItemClickCommandSupport.ClickSpec spec, + int times + ) { + Minecraft mc = Minecraft.getInstance(); + if (mc.player == null || mc.player.containerMenu == null) { + AutismClientMessaging.sendPrefixed("§cNo active inventory or GUI."); + return SUCCESS; + } + + int visibleSlot = MenuSlotArgumentType.get(context, "slot"); + int handlerSlot = AutismInventoryHelper.toHandlerSlot(mc, visibleSlot); + return ItemClickCommandSupport.clickHandlerSlot( + handlerSlot, spec, times, MenuSlotArgumentType.displayToken(visibleSlot)); + } +} diff --git a/src/main/java/autismclient/commands/impl/CommandsCommand.java b/src/main/java/autismclient/commands/impl/CommandsCommand.java new file mode 100644 index 0000000..c5f52cc --- /dev/null +++ b/src/main/java/autismclient/commands/impl/CommandsCommand.java @@ -0,0 +1,28 @@ +package autismclient.commands.impl; + +import autismclient.commands.Command; +import autismclient.commands.AutismCommandSource; +import autismclient.commands.AutismCommands; +import autismclient.util.AutismClientMessaging; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; + +public class CommandsCommand extends Command { + public CommandsCommand() { super("commands", "List all available commands.", "cmds"); } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + String prefix = AutismCommands.effectivePrefix(); + AutismClientMessaging.sendPrefixed("§e" + AutismCommands.all().size() + " commands (prefix §f" + prefix + "§e):"); + StringBuilder line = new StringBuilder(); + for (Command c : AutismCommands.all()) { + if (line.length() > 0) line.append("§7, "); + line.append("§f").append(c.name()); + if (line.length() > 200) { AutismClientMessaging.sendPrefixed(line.toString()); line.setLength(0); } + } + if (line.length() > 0) AutismClientMessaging.sendPrefixed(line.toString()); + AutismClientMessaging.sendPrefixed("§7Type §f" + prefix + "help §7 for details."); + return SUCCESS; + }); + } +} diff --git a/src/main/java/autismclient/commands/impl/DamageCommand.java b/src/main/java/autismclient/commands/impl/DamageCommand.java new file mode 100644 index 0000000..ebe17fa --- /dev/null +++ b/src/main/java/autismclient/commands/impl/DamageCommand.java @@ -0,0 +1,32 @@ +package autismclient.commands.impl; + +import autismclient.commands.Command; +import autismclient.commands.AutismCommandSource; +import autismclient.commands.AutismCommands; +import autismclient.commands.CommandSuggest; +import autismclient.util.AutismClientMessaging; +import com.mojang.brigadier.arguments.DoubleArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; +import net.minecraft.client.Minecraft; + +public class DamageCommand extends Command { + public DamageCommand() { super("damage", "Take damage to self (vanilla server allows via /damage if op)."); } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + AutismClientMessaging.sendPrefixed("§eUsage: " + AutismCommands.effectivePrefix() + "damage "); + return SUCCESS; + }); + root.then(RequiredArgumentBuilder.argument("amount", DoubleArgumentType.doubleArg(0.1, 1024.0)) + .suggests(CommandSuggest::damage) + .executes(ctx -> { + double amt = DoubleArgumentType.getDouble(ctx, "amount"); + var conn = Minecraft.getInstance().getConnection(); + if (conn == null) { AutismClientMessaging.sendPrefixed("§cNot connected."); return SUCCESS; } + conn.sendCommand("damage @s " + amt); + return SUCCESS; + })); + } +} diff --git a/src/main/java/autismclient/commands/impl/DelayCommand.java b/src/main/java/autismclient/commands/impl/DelayCommand.java new file mode 100644 index 0000000..ffd22f7 --- /dev/null +++ b/src/main/java/autismclient/commands/impl/DelayCommand.java @@ -0,0 +1,50 @@ +package autismclient.commands.impl; + +import autismclient.commands.AutismCommandSource; +import autismclient.commands.Command; +import autismclient.commands.CommandSuggest; +import autismclient.modules.AutismModule; +import autismclient.util.AutismClientMessaging; +import autismclient.util.AutismSharedState; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; + +public class DelayCommand extends Command { + public DelayCommand() { super("delay", "Toggle the GUI packet delay queue."); } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> apply(null)); + root.then(RequiredArgumentBuilder.argument("state", StringArgumentType.word()) + .suggests(CommandSuggest::state) + .executes(ctx -> apply(StringArgumentType.getString(ctx, "state")))); + } + + private static int apply(String state) { + boolean current = AutismSharedState.get().shouldDelayGuiPackets(); + if (state != null) { + String lower = state.toLowerCase(); + if (!lower.equals("on") && !lower.equals("enable") && !lower.equals("true") && !lower.equals("1") + && !lower.equals("off") && !lower.equals("disable") && !lower.equals("false") && !lower.equals("0") + && !lower.equals("toggle")) { + AutismClientMessaging.sendPrefixed("Unknown delay state: " + state); + AutismClientMessaging.sendPrefixed("Use on, off, or toggle."); + return SUCCESS; + } + } + + boolean target = state == null ? !current + : switch (state.toLowerCase()) { + case "on", "enable", "true", "1" -> true; + case "off", "disable", "false", "0" -> false; + case "toggle" -> !current; + default -> !current; + }; + + AutismModule module = AutismModule.get(); + int flushed = module.applyDelayGuiPacketsUiBehavior(target); + module.notifyDelayPacketsUiResult(target, flushed); + return SUCCESS; + } +} diff --git a/src/main/java/autismclient/commands/impl/DisconnectCommand.java b/src/main/java/autismclient/commands/impl/DisconnectCommand.java new file mode 100644 index 0000000..b53052b --- /dev/null +++ b/src/main/java/autismclient/commands/impl/DisconnectCommand.java @@ -0,0 +1,26 @@ +package autismclient.commands.impl; + +import autismclient.commands.Command; +import autismclient.commands.AutismCommandSource; +import autismclient.util.AutismClientMessaging; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import net.minecraft.client.Minecraft; +import net.minecraft.network.chat.Component; + +public class DisconnectCommand extends Command { + public DisconnectCommand() { super("disconnect", "Disconnect from the current server."); } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + Minecraft mc = Minecraft.getInstance(); + if (mc.getConnection() == null) { AutismClientMessaging.sendPrefixed("§cNot connected."); return SUCCESS; } + try { + mc.getConnection().getConnection().disconnect(Component.literal("Disconnected via .disconnect")); + } catch (Throwable t) { + AutismClientMessaging.sendPrefixed("§cDisconnect failed: " + t.getMessage()); + } + return SUCCESS; + }); + } +} diff --git a/src/main/java/autismclient/commands/impl/DismountCommand.java b/src/main/java/autismclient/commands/impl/DismountCommand.java new file mode 100644 index 0000000..025b6f7 --- /dev/null +++ b/src/main/java/autismclient/commands/impl/DismountCommand.java @@ -0,0 +1,28 @@ +package autismclient.commands.impl; + +import autismclient.commands.Command; +import autismclient.commands.AutismCommandSource; +import autismclient.util.AutismClientMessaging; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import net.minecraft.client.Minecraft; +import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket; + +public class DismountCommand extends Command { + public DismountCommand() { super("dismount", "Force-dismount from any vehicle."); } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + Minecraft mc = Minecraft.getInstance(); + if (mc.player == null || mc.getConnection() == null) { AutismClientMessaging.sendPrefixed("§cNot in a world."); return SUCCESS; } + if (mc.player.getVehicle() == null) { AutismClientMessaging.sendPrefixed("§eNot riding anything."); return SUCCESS; } + try { + mc.player.removeVehicle(); + AutismClientMessaging.sendPrefixed("§aDismounted."); + } catch (Throwable t) { + AutismClientMessaging.sendPrefixed("§cDismount failed: " + t.getMessage()); + } + return SUCCESS; + }); + } +} diff --git a/src/main/java/autismclient/commands/impl/DropCommand.java b/src/main/java/autismclient/commands/impl/DropCommand.java new file mode 100644 index 0000000..3a31253 --- /dev/null +++ b/src/main/java/autismclient/commands/impl/DropCommand.java @@ -0,0 +1,206 @@ +package autismclient.commands.impl; + +import autismclient.commands.AutismCommandSource; +import autismclient.commands.AutismCommands; +import autismclient.commands.Command; +import autismclient.commands.CommandSuggest; +import autismclient.util.AutismClientMessaging; +import autismclient.util.AutismDropHelper; +import autismclient.util.AutismInventoryHelper; +import com.mojang.brigadier.arguments.IntegerArgumentType; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; +import net.minecraft.client.Minecraft; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class DropCommand extends Command { + public DropCommand() { + super("drop", "Drop hand, full inventory, or an amount of a held/specific item."); + } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + showUsage(); + return SUCCESS; + }); + + root.then(LiteralArgumentBuilder.literal("hand") + .executes(ctx -> dropHand())); + root.then(LiteralArgumentBuilder.literal("fullinventory") + .executes(ctx -> dropFullInventory())); + root.then(RequiredArgumentBuilder.argument( + "amount", IntegerArgumentType.integer(1)) + .suggests(CommandSuggest::counts) + .executes(ctx -> dropHeldAmount(IntegerArgumentType.getInteger(ctx, "amount"))) + .then(RequiredArgumentBuilder.argument( + "item", StringArgumentType.word()) + .suggests(CommandSuggest::itemIds) + .executes(ctx -> dropItemAmount( + IntegerArgumentType.getInteger(ctx, "amount"), + StringArgumentType.getString(ctx, "item"))))); + } + + private static void showUsage() { + String prefix = AutismCommands.effectivePrefix(); + AutismClientMessaging.sendPrefixed("§eUsage: §f" + prefix + "drop hand"); + AutismClientMessaging.sendPrefixed("§eUsage: §f" + prefix + "drop fullinventory"); + AutismClientMessaging.sendPrefixed("§eUsage: §f" + prefix + "drop [item_id]"); + } + + private static int dropHand() { + Minecraft mc = Minecraft.getInstance(); + if (!ready(mc)) return SUCCESS; + + ItemStack held = mc.player.getMainHandItem(); + if (held.isEmpty()) { + AutismClientMessaging.sendPrefixed("§cYou are not holding an item."); + return SUCCESS; + } + + int amount = held.getCount(); + Identifier id = BuiltInRegistries.ITEM.getKey(held.getItem()); + mc.player.drop(true); + AutismClientMessaging.sendPrefixed("§aDropped §f" + amount + "x " + id + "§a."); + return SUCCESS; + } + + private static int dropFullInventory() { + Minecraft mc = Minecraft.getInstance(); + if (!ready(mc)) return SUCCESS; + + int droppedItems = 0; + int droppedStacks = 0; + for (int inventorySlot = 0; inventorySlot < 36; inventorySlot++) { + ItemStack stack = mc.player.getInventory().getItem(inventorySlot); + if (stack.isEmpty()) continue; + + int handlerSlot = AutismInventoryHelper.toHandlerSlot(mc, inventorySlot); + if (handlerSlot < 0) continue; + + int stackCount = stack.getCount(); + if (AutismDropHelper.dropFromHandlerSlot(mc, handlerSlot, 0) > 0) { + droppedItems += stackCount; + droppedStacks++; + } + } + + if (droppedStacks == 0) { + AutismClientMessaging.sendPrefixed("§eYour inventory is empty."); + } else { + AutismClientMessaging.sendPrefixed( + "§aDropped §f" + droppedItems + " items §7(" + droppedStacks + " stacks§7)§a."); + } + return SUCCESS; + } + + private static int dropHeldAmount(int requested) { + Minecraft mc = Minecraft.getInstance(); + if (!ready(mc)) return SUCCESS; + + int selectedSlot = mc.player.getInventory().getSelectedSlot(); + ItemStack held = mc.player.getInventory().getItem(selectedSlot); + if (held.isEmpty()) { + AutismClientMessaging.sendPrefixed("§cYou are not holding an item."); + return SUCCESS; + } + + Identifier id = BuiltInRegistries.ITEM.getKey(held.getItem()); + return dropResolvedItemAmount(mc, requested, id, held.getItem()); + } + + private static int dropItemAmount(int requested, String rawItemId) { + Minecraft mc = Minecraft.getInstance(); + if (!ready(mc)) return SUCCESS; + + Identifier id = parseItemId(rawItemId); + Item item = id == null ? null : BuiltInRegistries.ITEM.getOptional(id).orElse(null); + if (item == null) { + AutismClientMessaging.sendPrefixed("§cUnknown item id: §f" + rawItemId); + return SUCCESS; + } + + return dropResolvedItemAmount(mc, requested, id, item); + } + + private static int dropResolvedItemAmount(Minecraft mc, int requested, Identifier id, Item item) { + List matchingSlots = matchingInventorySlots(mc, item); + int available = 0; + for (int slot : matchingSlots) { + available += mc.player.getInventory().getItem(slot).getCount(); + } + if (available == 0) { + AutismClientMessaging.sendPrefixed("§cYou do not have §f" + id + "§c in your inventory."); + return SUCCESS; + } + + int remaining = Math.min(requested, available); + int dropped = 0; + for (int inventorySlot : matchingSlots) { + if (remaining <= 0) break; + ItemStack stack = mc.player.getInventory().getItem(inventorySlot); + if (stack.isEmpty() || stack.getItem() != item) continue; + + int amount = Math.min(remaining, stack.getCount()); + int handlerSlot = AutismInventoryHelper.toHandlerSlot(mc, inventorySlot); + if (handlerSlot < 0) continue; + if (AutismDropHelper.dropFromHandlerSlot(mc, handlerSlot, amount) == 0) continue; + + dropped += amount; + remaining -= amount; + } + + if (dropped == 0) { + AutismClientMessaging.sendPrefixed("§cCould not drop §f" + id + "§c from the current screen."); + } else { + reportDrop(id, dropped, requested); + } + return SUCCESS; + } + + private static List matchingInventorySlots(Minecraft mc, Item item) { + List slots = new ArrayList<>(); + int selected = mc.player.getInventory().getSelectedSlot(); + addIfMatching(mc, item, selected, slots); + for (int slot = 0; slot < 9; slot++) { + if (slot != selected) addIfMatching(mc, item, slot, slots); + } + for (int slot = 9; slot < 36; slot++) { + addIfMatching(mc, item, slot, slots); + } + return slots; + } + + private static void addIfMatching(Minecraft mc, Item item, int slot, List slots) { + ItemStack stack = mc.player.getInventory().getItem(slot); + if (!stack.isEmpty() && stack.getItem() == item) slots.add(slot); + } + + private static Identifier parseItemId(String raw) { + if (raw == null || raw.isBlank()) return null; + String value = raw.trim().toLowerCase(java.util.Locale.ROOT); + return Identifier.tryParse(value.indexOf(':') >= 0 ? value : "minecraft:" + value); + } + + private static void reportDrop(Identifier id, int dropped, int requested) { + if (dropped < requested) { + AutismClientMessaging.sendPrefixed( + "§eDropped §f" + dropped + "/" + requested + "x " + id + "§e (all available)."); + } else { + AutismClientMessaging.sendPrefixed("§aDropped §f" + dropped + "x " + id + "§a."); + } + } + + private static boolean ready(Minecraft mc) { + if (mc.player != null && mc.gameMode != null) return true; + AutismClientMessaging.sendPrefixed("§cNot in a world."); + return false; + } +} diff --git a/src/main/java/autismclient/commands/impl/GamemodeCommand.java b/src/main/java/autismclient/commands/impl/GamemodeCommand.java new file mode 100644 index 0000000..5ddaaff --- /dev/null +++ b/src/main/java/autismclient/commands/impl/GamemodeCommand.java @@ -0,0 +1,44 @@ +package autismclient.commands.impl; + +import autismclient.commands.AutismCommandSource; +import autismclient.commands.AutismCommands; +import autismclient.commands.Command; +import autismclient.commands.CommandSuggest; +import autismclient.util.AutismClientMessaging; +import autismclient.util.AutismFakeGamemode; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; +import net.minecraft.world.level.GameType; + +public class GamemodeCommand extends Command { + public GamemodeCommand() { + super("gamemode", "Set fake client-side game mode."); + } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + AutismClientMessaging.sendPrefixed("§eUsage: " + AutismCommands.effectivePrefix() + "gamemode "); + return SUCCESS; + }); + root.then(RequiredArgumentBuilder.argument("mode", StringArgumentType.word()) + .suggests(CommandSuggest::gamemodes) + .executes(ctx -> { + String mode = StringArgumentType.getString(ctx, "mode").toLowerCase(java.util.Locale.ROOT); + AutismFakeGamemode.Result result; + if ("reset".equals(mode) || "r".equals(mode)) { + result = AutismFakeGamemode.reset(); + } else { + GameType resolved = AutismFakeGamemode.parseMode(mode); + if (resolved == null) { + AutismClientMessaging.sendPrefixed("§cUnknown mode: §f" + mode); + return SUCCESS; + } + result = AutismFakeGamemode.apply(resolved); + } + AutismClientMessaging.sendPrefixed((result.success() ? "§a" : "§c") + result.message()); + return SUCCESS; + })); + } +} diff --git a/src/main/java/autismclient/commands/impl/GiveCommand.java b/src/main/java/autismclient/commands/impl/GiveCommand.java new file mode 100644 index 0000000..a7b0146 --- /dev/null +++ b/src/main/java/autismclient/commands/impl/GiveCommand.java @@ -0,0 +1,52 @@ +package autismclient.commands.impl; + +import autismclient.commands.Command; +import autismclient.commands.AutismCommandSource; +import autismclient.commands.AutismCommands; +import autismclient.commands.CommandSuggest; +import autismclient.util.AutismClientMessaging; +import com.mojang.brigadier.arguments.IntegerArgumentType; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; +import net.minecraft.client.Minecraft; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.network.protocol.game.ServerboundSetCreativeModeSlotPacket; +import net.minecraft.resources.Identifier; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; + +public class GiveCommand extends Command { + public GiveCommand() { super("give", "Give item to self (creative only)."); } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + AutismClientMessaging.sendPrefixed("§eUsage: " + AutismCommands.effectivePrefix() + "give [count]"); + return SUCCESS; + }); + root.then(RequiredArgumentBuilder.argument("item", StringArgumentType.word()) + .suggests(CommandSuggest::itemIds) + .executes(ctx -> give(StringArgumentType.getString(ctx, "item"), 1)) + .then(RequiredArgumentBuilder.argument("count", IntegerArgumentType.integer(1, 64)) + .suggests(CommandSuggest::counts) + .executes(ctx -> give(StringArgumentType.getString(ctx, "item"), IntegerArgumentType.getInteger(ctx, "count"))))); + } + + private static int give(String itemId, int count) { + Minecraft mc = Minecraft.getInstance(); + if (mc.player == null) { AutismClientMessaging.sendPrefixed("§cNot in a world."); return SUCCESS; } + if (!mc.player.getAbilities().instabuild) { AutismClientMessaging.sendPrefixed("§cCreative mode required."); return SUCCESS; } + Identifier id = itemId.contains(":") ? Identifier.tryParse(itemId) : Identifier.tryParse("minecraft:" + itemId); + if (id == null) { AutismClientMessaging.sendPrefixed("§cInvalid item id: §f" + itemId); return SUCCESS; } + Item item = BuiltInRegistries.ITEM.getOptional(id).orElse(null); + if (item == null) { AutismClientMessaging.sendPrefixed("§cUnknown item: §f" + id); return SUCCESS; } + ItemStack stack = new ItemStack(item, count); + int slot = mc.player.getInventory().getSelectedSlot(); + int containerSlot = 36 + slot; + mc.getConnection().send(new ServerboundSetCreativeModeSlotPacket((short) containerSlot, stack)); + mc.player.getInventory().setItem(slot, stack); + AutismClientMessaging.sendPrefixed("§aGave §f" + id + " x" + count); + return SUCCESS; + } +} diff --git a/src/main/java/autismclient/commands/impl/HClipCommand.java b/src/main/java/autismclient/commands/impl/HClipCommand.java new file mode 100644 index 0000000..5675965 --- /dev/null +++ b/src/main/java/autismclient/commands/impl/HClipCommand.java @@ -0,0 +1,132 @@ +package autismclient.commands.impl; + +import autismclient.commands.AutismCommandSource; +import autismclient.commands.AutismCommands; +import autismclient.commands.Command; +import autismclient.commands.CommandSuggest; +import autismclient.util.AutismClientMessaging; +import autismclient.util.macro.HClipAction; +import com.mojang.brigadier.arguments.BoolArgumentType; +import com.mojang.brigadier.arguments.DoubleArgumentType; +import com.mojang.brigadier.arguments.IntegerArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; +import net.minecraft.client.Minecraft; + +public class HClipCommand extends Command { + public HClipCommand() { + super("hclip", "Lets you clip through blocks horizontally (forward) with movement packets."); + } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + String prefix = AutismCommands.effectivePrefix(); + AutismClientMessaging.sendPrefixed("\u00a7eUsage: \u00a7f" + prefix + "hclip "); + AutismClientMessaging.sendPrefixed("\u00a77Modes: \u00a7fdefault, forward, back, padding, single, custom (paper alias still works)"); + AutismClientMessaging.sendPrefixed("\u00a77Examples: \u00a7f" + prefix + "hclip forward \u00a77or \u00a7f" + prefix + "hclip custom -25 10 20 true true true"); + return SUCCESS; + }); + + root.then(blocksArgument("blocks", options -> options)); + root.then(LiteralArgumentBuilder.literal("forward") + .executes(ctx -> { + HClipAction.Options options = HClipAction.Options.defaults(0.0); + options.mode = HClipAction.Mode.FORWARD; + run(options); + return SUCCESS; + })); + root.then(LiteralArgumentBuilder.literal("back") + .executes(ctx -> { + HClipAction.Options options = HClipAction.Options.defaults(0.0); + options.mode = HClipAction.Mode.BACK; + run(options); + return SUCCESS; + })); + root.then(LiteralArgumentBuilder.literal("default") + .then(blocksArgument("blocks", options -> options))); + root.then(LiteralArgumentBuilder.literal("paper") + .then(blocksArgument("blocks", options -> options))); + root.then(LiteralArgumentBuilder.literal("padding") + .then(blocksArgument("blocks", options -> options))); + root.then(LiteralArgumentBuilder.literal("single") + .then(blocksArgument("blocks", HClipAction.Options::singlePacket))); + root.then(LiteralArgumentBuilder.literal("normal") + .then(blocksArgument("blocks", HClipAction.Options::singlePacket))); + root.then(LiteralArgumentBuilder.literal("custom") + .then(RequiredArgumentBuilder.argument("blocks", DoubleArgumentType.doubleArg()) + .suggests(CommandSuggest::offsets) + .then(RequiredArgumentBuilder.argument("segment", IntegerArgumentType.integer(1, 50)) + .suggests(CommandSuggest::vclipSegments) + .executes(ctx -> { + HClipAction.Options options = HClipAction.Options.defaults(DoubleArgumentType.getDouble(ctx, "blocks")); + options.segmentBlocks = IntegerArgumentType.getInteger(ctx, "segment"); + run(options); + return SUCCESS; + }) + .then(RequiredArgumentBuilder.argument("maxPackets", IntegerArgumentType.integer(1, 100)) + .suggests(CommandSuggest::vclipPacketLimits) + .executes(ctx -> { + HClipAction.Options options = HClipAction.Options.defaults(DoubleArgumentType.getDouble(ctx, "blocks")); + options.segmentBlocks = IntegerArgumentType.getInteger(ctx, "segment"); + options.maxPackets = IntegerArgumentType.getInteger(ctx, "maxPackets"); + run(options); + return SUCCESS; + }) + .then(RequiredArgumentBuilder.argument("updateLocal", BoolArgumentType.bool()) + .executes(ctx -> { + HClipAction.Options options = customOptions(ctx); + options.updateLocalPosition = BoolArgumentType.getBool(ctx, "updateLocal"); + run(options); + return SUCCESS; + }) + .then(RequiredArgumentBuilder.argument("vehicle", BoolArgumentType.bool()) + .executes(ctx -> { + HClipAction.Options options = customOptions(ctx); + options.updateLocalPosition = BoolArgumentType.getBool(ctx, "updateLocal"); + options.tryVehicleFirst = BoolArgumentType.getBool(ctx, "vehicle"); + run(options); + return SUCCESS; + }) + .then(RequiredArgumentBuilder.argument("forceGround", BoolArgumentType.bool()) + .executes(ctx -> { + HClipAction.Options options = customOptions(ctx); + options.updateLocalPosition = BoolArgumentType.getBool(ctx, "updateLocal"); + options.tryVehicleFirst = BoolArgumentType.getBool(ctx, "vehicle"); + options.forceGrounded = BoolArgumentType.getBool(ctx, "forceGround"); + run(options); + return SUCCESS; + })))))))); + } + + private interface OptionsCustomizer { + HClipAction.Options apply(HClipAction.Options options); + } + + private static RequiredArgumentBuilder blocksArgument(String name, OptionsCustomizer customizer) { + return RequiredArgumentBuilder.argument(name, DoubleArgumentType.doubleArg()) + .suggests(CommandSuggest::offsets) + .executes(ctx -> { + HClipAction.Options options = HClipAction.Options.defaults(DoubleArgumentType.getDouble(ctx, name)); + run(customizer.apply(options)); + return SUCCESS; + }); + } + + private static HClipAction.Options customOptions(com.mojang.brigadier.context.CommandContext ctx) { + HClipAction.Options options = HClipAction.Options.defaults(DoubleArgumentType.getDouble(ctx, "blocks")); + options.segmentBlocks = IntegerArgumentType.getInteger(ctx, "segment"); + options.maxPackets = IntegerArgumentType.getInteger(ctx, "maxPackets"); + options.maxRoutePackets = options.maxPackets; + return options; + } + + public static void hclip(double blocks) { + run(HClipAction.Options.defaults(blocks)); + } + + private static void run(HClipAction.Options options) { + options.showMessage = true; + HClipAction.perform(Minecraft.getInstance(), options); + } +} diff --git a/src/main/java/autismclient/commands/impl/HelpCommand.java b/src/main/java/autismclient/commands/impl/HelpCommand.java new file mode 100644 index 0000000..b449043 --- /dev/null +++ b/src/main/java/autismclient/commands/impl/HelpCommand.java @@ -0,0 +1,46 @@ +package autismclient.commands.impl; + +import autismclient.commands.Command; +import autismclient.commands.AutismCommandSource; +import autismclient.commands.AutismCommands; +import autismclient.util.AutismClientMessaging; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; +import java.util.Locale; + +public class HelpCommand extends Command { + public HelpCommand() { super("help", "Show usage info for a command (or list all)."); } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { listAll(); return SUCCESS; }); + root.then(RequiredArgumentBuilder.argument("command", StringArgumentType.word()) + .suggests((ctx, builder) -> { + String remaining = builder.getRemaining().toLowerCase(Locale.ROOT); + for (Command command : AutismCommands.all()) { + if (command.name().toLowerCase(Locale.ROOT).startsWith(remaining)) builder.suggest(command.name()); + for (String alias : command.aliases()) { + if (alias != null && alias.toLowerCase(Locale.ROOT).startsWith(remaining)) builder.suggest(alias); + } + } + return builder.buildFuture(); + }) + .executes(ctx -> { + String name = StringArgumentType.getString(ctx, "command"); + Command cmd = AutismCommands.find(name); + if (cmd == null) { AutismClientMessaging.sendPrefixed("§cNo such command: §f" + name); return SUCCESS; } + String prefix = AutismCommands.effectivePrefix(); + AutismClientMessaging.sendPrefixed("§b" + prefix + cmd.name() + " §7" + cmd.description()); + if (cmd.aliases().length > 0) AutismClientMessaging.sendPrefixed("§7aliases: §f" + String.join(", ", cmd.aliases())); + return SUCCESS; + })); + } + + private static void listAll() { + String prefix = AutismCommands.effectivePrefix(); + for (Command c : AutismCommands.all()) { + AutismClientMessaging.sendPrefixed("§b" + prefix + c.name() + "§7 - " + c.description()); + } + } +} diff --git a/src/main/java/autismclient/commands/impl/IrcCommand.java b/src/main/java/autismclient/commands/impl/IrcCommand.java new file mode 100644 index 0000000..bb0c170 --- /dev/null +++ b/src/main/java/autismclient/commands/impl/IrcCommand.java @@ -0,0 +1,34 @@ +package autismclient.commands.impl; + +import autismclient.commands.AutismCommandSource; +import autismclient.commands.AutismCommands; +import autismclient.commands.Command; +import autismclient.util.AutismClientMessaging; +import autismclient.util.mm.MatchmakingManager; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; + +public class IrcCommand extends Command { + public IrcCommand() { super("irc", "Send a message to the Matchmaking lobby chat."); } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + AutismClientMessaging.sendPrefixed("§eUsage: " + AutismCommands.effectivePrefix() + "irc "); + return SUCCESS; + }); + root.then(RequiredArgumentBuilder.argument("message", StringArgumentType.greedyString()) + .executes(ctx -> { + String msg = StringArgumentType.getString(ctx, "message"); + MatchmakingManager mm = MatchmakingManager.get(); + if (!mm.inLobby()) { + AutismClientMessaging.sendPrefixed("§cNot in a lobby. Open Matchmaking and join or create one first."); + return SUCCESS; + } + + mm.sendChat(msg); + return SUCCESS; + })); + } +} diff --git a/src/main/java/autismclient/commands/impl/ItemClickCommandSupport.java b/src/main/java/autismclient/commands/impl/ItemClickCommandSupport.java new file mode 100644 index 0000000..dbc5d41 --- /dev/null +++ b/src/main/java/autismclient/commands/impl/ItemClickCommandSupport.java @@ -0,0 +1,146 @@ +package autismclient.commands.impl; + +import autismclient.commands.AutismCommandSource; +import autismclient.commands.CommandSuggest; +import autismclient.util.AutismClientMessaging; +import autismclient.util.AutismDropHelper; +import autismclient.util.AutismInventoryClickHelper; +import com.mojang.brigadier.arguments.IntegerArgumentType; +import com.mojang.brigadier.builder.ArgumentBuilder; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; +import com.mojang.brigadier.context.CommandContext; +import net.minecraft.client.Minecraft; +import net.minecraft.world.inventory.ContainerInput; +import net.minecraft.world.item.ItemStack; + +final class ItemClickCommandSupport { + private ItemClickCommandSupport() { + } + + record ClickSpec(String label, ContainerInput input, int button, DropMode dropMode) { + static ClickSpec click(String label, ContainerInput input, int button) { + return new ClickSpec(label, input, button, DropMode.NONE); + } + + static ClickSpec drop(String label, DropMode dropMode) { + return new ClickSpec(label, ContainerInput.THROW, dropMode == DropMode.STACK ? 1 : 0, dropMode); + } + } + + enum DropMode { + NONE, + ITEM, + STACK + } + + @FunctionalInterface + interface ClickExecutor { + int execute(CommandContext context, ClickSpec spec, int times); + } + + static void attachModes(ArgumentBuilder target, ClickExecutor executor) { + target.then(repeated("left", ClickSpec.click("Left", ContainerInput.PICKUP, 0), executor)); + target.then(repeated("right", ClickSpec.click("Right", ContainerInput.PICKUP, 1), executor)); + target.then(repeated("middle", ClickSpec.click("Middle", ContainerInput.PICKUP, 2), executor)); + target.then(repeated("shift-left", ClickSpec.click("Shift Left", ContainerInput.QUICK_MOVE, 0), executor)); + target.then(repeated("shift-right", ClickSpec.click("Shift Right", ContainerInput.QUICK_MOVE, 1), executor)); + target.then(repeated("clone", ClickSpec.click("Clone", ContainerInput.CLONE, 2), executor)); + target.then(repeated("pickup-all", ClickSpec.click("Pick Up All", ContainerInput.PICKUP_ALL, 0), executor)); + target.then(repeated("drop-item", ClickSpec.drop("Drop Item", DropMode.ITEM), executor)); + target.then(single("drop-stack", ClickSpec.drop("Drop Stack", DropMode.STACK), executor)); + + LiteralArgumentBuilder swap = LiteralArgumentBuilder.literal("swap"); + RequiredArgumentBuilder hotbar = RequiredArgumentBuilder + .argument("swap-hotbar", IntegerArgumentType.integer(1, 9)) + .suggests((context, builder) -> CommandSuggest.literals( + builder, "1", "2", "3", "4", "5", "6", "7", "8", "9")) + .executes(context -> executor.execute( + context, + ClickSpec.click("Swap " + IntegerArgumentType.getInteger(context, "swap-hotbar"), + ContainerInput.SWAP, + IntegerArgumentType.getInteger(context, "swap-hotbar") - 1), + 1)); + hotbar.then(timesArgument((context, times) -> executor.execute( + context, + ClickSpec.click("Swap " + IntegerArgumentType.getInteger(context, "swap-hotbar"), + ContainerInput.SWAP, + IntegerArgumentType.getInteger(context, "swap-hotbar") - 1), + times))); + swap.then(hotbar); + target.then(swap); + } + + static int clickHandlerSlot(int handlerSlot, ClickSpec spec, int times, String targetLabel) { + Minecraft mc = Minecraft.getInstance(); + if (mc.player == null || mc.gameMode == null || mc.getConnection() == null || mc.player.containerMenu == null) { + AutismClientMessaging.sendPrefixed("§cNo active inventory or GUI."); + return 1; + } + if (handlerSlot < 0 || handlerSlot >= mc.player.containerMenu.slots.size()) { + AutismClientMessaging.sendPrefixed("§cThat slot does not exist in the current GUI."); + return 1; + } + + int requested = Math.max(1, times); + int completed = 0; + if (spec.dropMode() == DropMode.ITEM) { + ItemStack stack = mc.player.containerMenu.slots.get(handlerSlot).getItem(); + if (!stack.isEmpty()) { + int actual = Math.min(requested, stack.getCount()); + if (AutismDropHelper.dropFromHandlerSlot(mc, handlerSlot, actual) > 0) completed = actual; + } + } else if (spec.dropMode() == DropMode.STACK) { + completed = AutismDropHelper.dropFromHandlerSlot(mc, handlerSlot, 0) > 0 ? 1 : 0; + } else { + for (int i = 0; i < requested; i++) { + if (!AutismInventoryClickHelper.click(mc, handlerSlot, spec.button(), spec.input())) { + break; + } + completed++; + } + } + + if (completed == 0) { + AutismClientMessaging.sendPrefixed("§cCould not click §f" + targetLabel + "§c."); + } else { + String repeat = completed > 1 && spec.dropMode() != DropMode.STACK ? " x" + completed : ""; + String partial = completed < requested && spec.dropMode() != DropMode.STACK + ? " §e(" + completed + "/" + requested + ")" + : ""; + AutismClientMessaging.sendPrefixed( + "§a" + spec.label() + " clicked §f" + targetLabel + "§a" + repeat + "." + partial); + } + return 1; + } + + private static LiteralArgumentBuilder repeated( + String literal, + ClickSpec spec, + ClickExecutor executor + ) { + LiteralArgumentBuilder node = single(literal, spec, executor); + node.then(timesArgument((context, times) -> executor.execute(context, spec, times))); + return node; + } + + private static LiteralArgumentBuilder single( + String literal, + ClickSpec spec, + ClickExecutor executor + ) { + return LiteralArgumentBuilder.literal(literal) + .executes(context -> executor.execute(context, spec, 1)); + } + + private static RequiredArgumentBuilder timesArgument(TimesExecutor executor) { + return RequiredArgumentBuilder.argument("times", IntegerArgumentType.integer(1, 1_000)) + .suggests(CommandSuggest::counts) + .executes(context -> executor.execute(context, IntegerArgumentType.getInteger(context, "times"))); + } + + @FunctionalInterface + private interface TimesExecutor { + int execute(CommandContext context, int times); + } +} diff --git a/src/main/java/autismclient/commands/impl/MacroCommand.java b/src/main/java/autismclient/commands/impl/MacroCommand.java new file mode 100644 index 0000000..056646c --- /dev/null +++ b/src/main/java/autismclient/commands/impl/MacroCommand.java @@ -0,0 +1,102 @@ +package autismclient.commands.impl; + +import autismclient.commands.Command; +import autismclient.commands.AutismCommandSource; +import autismclient.commands.AutismCommands; +import autismclient.commands.args.MacroArgumentType; +import autismclient.util.AutismClientMessaging; +import autismclient.util.AutismMacroManager; +import autismclient.util.macro.MacroExecutor; +import com.mojang.brigadier.arguments.IntegerArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; + +public class MacroCommand extends Command { + private static final ConcurrentHashMap RUNNING_LOOPS = new ConcurrentHashMap<>(); + + public MacroCommand() { super("macro", "Run a macro, optionally N times with a delay between starts."); } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + String prefix = AutismCommands.effectivePrefix(); + AutismClientMessaging.sendPrefixed("§eUsage: §f" + prefix + "macro [times] [delayTicks]"); + AutismClientMessaging.sendPrefixed("§7Also: §f" + prefix + "macro stop [name] §7or §f" + prefix + "macro clear"); + return SUCCESS; + }); + + root.then(LiteralArgumentBuilder.literal("stop") + .executes(ctx -> { + stopAllLoops(); + AutismMacroManager.get().stopMacro(); + AutismClientMessaging.sendPrefixed("§eStopped all macros."); + return SUCCESS; + }) + .then(RequiredArgumentBuilder.argument("name", MacroArgumentType.macroName()) + .executes(ctx -> { + String name = MacroArgumentType.get(ctx, "name"); + AtomicBoolean flag = RUNNING_LOOPS.remove(name.toLowerCase()); + if (flag != null) flag.set(false); + MacroExecutor.stopMacro(name); + AutismClientMessaging.sendPrefixed("§eStopped: §f" + name); + return SUCCESS; + }))); + + root.then(LiteralArgumentBuilder.literal("clear") + .executes(ctx -> { stopAllLoops(); AutismClientMessaging.sendPrefixed("§eCleared macro loops."); return SUCCESS; })); + + root.then(RequiredArgumentBuilder.argument("name", MacroArgumentType.macroName()) + .executes(ctx -> startLoop(MacroArgumentType.get(ctx, "name"), 1, 0)) + .then(RequiredArgumentBuilder.argument("times", IntegerArgumentType.integer(1, 100_000)) + .executes(ctx -> startLoop(MacroArgumentType.get(ctx, "name"), IntegerArgumentType.getInteger(ctx, "times"), 0)) + .then(RequiredArgumentBuilder.argument("delayTicks", IntegerArgumentType.integer(0, 20 * 60 * 60)) + .executes(ctx -> startLoop( + MacroArgumentType.get(ctx, "name"), + IntegerArgumentType.getInteger(ctx, "times"), + IntegerArgumentType.getInteger(ctx, "delayTicks")))))); + } + + private static int startLoop(String name, int times, int delayTicks) { + if (AutismMacroManager.get().get(name) == null) { + AutismClientMessaging.sendPrefixed("§cMacro not found: §f" + name); + return SUCCESS; + } + if (times <= 1 && delayTicks <= 0) { + AutismMacroManager.get().executeMacro(name); + return SUCCESS; + } + AtomicBoolean flag = new AtomicBoolean(true); + RUNNING_LOOPS.put(name.toLowerCase(), flag); + long sleepMs = Math.max(0L, delayTicks * 50L); + final int totalTimes = Math.max(1, times); + Thread t = new Thread(() -> { + try { + for (int i = 0; i < totalTimes && flag.get(); i++) { + AutismMacroManager.get().executeMacro(name); + + long start = System.nanoTime(); + long waitTimeoutNanos = 24L * 60L * 60L * 1_000_000_000L; + while (MacroExecutor.isMacroRunning(name) && flag.get() + && System.nanoTime() - start < waitTimeoutNanos) { + Thread.sleep(50); + } + if (!flag.get()) break; + if (i + 1 < totalTimes && sleepMs > 0) Thread.sleep(sleepMs); + } + } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); } + finally { RUNNING_LOOPS.remove(name.toLowerCase(), flag); } + }, "MacroLoop-" + name); + t.setDaemon(true); + t.start(); + AutismClientMessaging.sendPrefixed("§aQueued " + totalTimes + "x §f" + name + "§a (delay " + delayTicks + "t)"); + return SUCCESS; + } + + private static void stopAllLoops() { + for (AtomicBoolean flag : RUNNING_LOOPS.values()) flag.set(false); + RUNNING_LOOPS.clear(); + } +} diff --git a/src/main/java/autismclient/commands/impl/MatchmakingCommand.java b/src/main/java/autismclient/commands/impl/MatchmakingCommand.java new file mode 100644 index 0000000..cf87330 --- /dev/null +++ b/src/main/java/autismclient/commands/impl/MatchmakingCommand.java @@ -0,0 +1,24 @@ +package autismclient.commands.impl; + +import autismclient.commands.AutismCommandSource; +import autismclient.commands.Command; +import autismclient.modules.AutismModule; +import net.minecraft.client.Minecraft; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; + +public class MatchmakingCommand extends Command { + public MatchmakingCommand() { super("matchmaking", "Toggle the Matchmaking overlay.", "mm"); } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + Minecraft mc = Minecraft.getInstance(); + + mc.execute(() -> { + AutismModule mod = AutismModule.get(); + if (mod != null) mod.toggleMatchmakingUiBehavior(); + }); + return SUCCESS; + }); + } +} diff --git a/src/main/java/autismclient/commands/impl/ModulesCommand.java b/src/main/java/autismclient/commands/impl/ModulesCommand.java new file mode 100644 index 0000000..feb17dc --- /dev/null +++ b/src/main/java/autismclient/commands/impl/ModulesCommand.java @@ -0,0 +1,27 @@ +package autismclient.commands.impl; + +import autismclient.commands.Command; +import autismclient.commands.AutismCommandSource; +import autismclient.modules.ModuleRegistry; +import autismclient.util.AutismClientMessaging; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; + +public class ModulesCommand extends Command { + public ModulesCommand() { super("modules", "List installed modules.", "features"); } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + java.util.List names = ModuleRegistry.names(); + AutismClientMessaging.sendPrefixed("§e" + names.size() + " modules:"); + StringBuilder line = new StringBuilder(); + for (String n : names) { + if (line.length() > 0) line.append("§7, "); + line.append("§f").append(n); + if (line.length() > 200) { AutismClientMessaging.sendPrefixed(line.toString()); line.setLength(0); } + } + if (line.length() > 0) AutismClientMessaging.sendPrefixed(line.toString()); + return SUCCESS; + }); + } +} diff --git a/src/main/java/autismclient/commands/impl/MultiCommand.java b/src/main/java/autismclient/commands/impl/MultiCommand.java new file mode 100644 index 0000000..4a62bc2 --- /dev/null +++ b/src/main/java/autismclient/commands/impl/MultiCommand.java @@ -0,0 +1,128 @@ +package autismclient.commands.impl; + +import autismclient.commands.AutismCommandSource; +import autismclient.commands.AutismCommands; +import autismclient.commands.Command; +import autismclient.commands.args.MultiProfileArgumentType; +import autismclient.gui.screen.AutismMultiConsoleScreen; +import autismclient.gui.screen.AutismMultiScreen; +import autismclient.util.AutismClientMessaging; +import autismclient.util.multi.MultiManager; +import autismclient.util.multi.MultiProfile; +import autismclient.util.multi.MultiProfileManager; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ServerData; + +import java.util.Collection; +import java.util.Locale; + +public class MultiCommand extends Command { + public MultiCommand() { + super("multi", "Open the Multi menu, or launch/stop a profile."); + } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { openMenu(); return SUCCESS; }); + + root.then(LiteralArgumentBuilder.literal("open") + .executes(ctx -> { openMenu(); return SUCCESS; })); + + root.then(LiteralArgumentBuilder.literal("stop") + .executes(ctx -> { stopBatch(); return SUCCESS; })); + + root.then(LiteralArgumentBuilder.literal("status") + .executes(ctx -> { status(); return SUCCESS; })); + + root.then(LiteralArgumentBuilder.literal("launch") + .executes(ctx -> { + AutismClientMessaging.sendPrefixed("§eUsage: §f" + AutismCommands.effectivePrefix() + "multi launch "); + return SUCCESS; + }) + .then(RequiredArgumentBuilder.argument("profile", MultiProfileArgumentType.profileName()) + .executes(ctx -> { launch(MultiProfileArgumentType.get(ctx, "profile")); return SUCCESS; }))); + } + + private static void openMenu() { + Minecraft mc = Minecraft.getInstance(); + if (mc == null) return; + mc.execute(() -> { + if (mc.gui.screen() != null) return; + Runnable proceed = () -> { + if (MultiManager.get().isActive()) { + mc.gui.setScreen(new AutismMultiConsoleScreen(null)); + } else { + mc.gui.setScreen(new AutismMultiScreen(null, currentServerAddress(mc))); + } + }; + + autismclient.gui.screen.AutismMultiDisclaimerScreen.open(mc, null, proceed); + }); + } + + private static void launch(String name) { + MultiProfile profile = resolveByName(MultiProfileManager.get().all(), name); + if (profile == null) { + AutismClientMessaging.sendPrefixed("§cNo profile named: §f" + name); + String available = availableNames(); + if (!available.isEmpty()) AutismClientMessaging.sendPrefixed("§7Profiles: §f" + available); + return; + } + MultiManager.StartResult result = MultiManager.get().start(profile); + if (result.ok()) { + AutismClientMessaging.sendPrefixed("§aLaunching Multi profile: §f" + profile.name + + " §7(" + profile.sessions.size() + " account(s)) - run " + + AutismCommands.effectivePrefix() + "multi to open the console."); + } else { + AutismClientMessaging.sendPrefixed("§cCould not launch: §f" + result.message()); + } + } + + private static void stopBatch() { + if (!MultiManager.get().isActive()) { + AutismClientMessaging.sendPrefixed("§7No Multi batch is active."); + return; + } + MultiManager.get().disconnectAll("Stopped via command"); + AutismClientMessaging.sendPrefixed("§eStopped the Multi batch."); + } + + private static void status() { + MultiManager mm = MultiManager.get(); + if (!mm.isActive()) { + AutismClientMessaging.sendPrefixed("§7Multi: no batch active."); + return; + } + MultiProfile active = mm.activeProfile(); + String name = active == null || active.name == null ? "(unknown)" : active.name; + AutismClientMessaging.sendPrefixed("§aMulti: §f" + name + + " §7- §f" + mm.readyCount() + "§7 ready, §f" + mm.connectedCount() + "§7 connected."); + } + + private static String currentServerAddress(Minecraft mc) { + ServerData sd = mc.getCurrentServer(); + return sd == null || sd.ip == null ? "" : sd.ip.trim(); + } + + private static String availableNames() { + StringBuilder sb = new StringBuilder(); + for (MultiProfile p : MultiProfileManager.get().all()) { + if (p == null || p.name == null) continue; + if (sb.length() > 0) sb.append("§7, §f"); + sb.append(p.name); + } + return sb.toString(); + } + + public static MultiProfile resolveByName(Collection profiles, String name) { + if (profiles == null || name == null) return null; + String want = name.trim().toLowerCase(Locale.ROOT); + if (want.isEmpty()) return null; + for (MultiProfile p : profiles) { + if (p != null && p.name != null && p.name.trim().toLowerCase(Locale.ROOT).equals(want)) return p; + } + return null; + } +} diff --git a/src/main/java/autismclient/commands/impl/NbtCommand.java b/src/main/java/autismclient/commands/impl/NbtCommand.java new file mode 100644 index 0000000..c38e597 --- /dev/null +++ b/src/main/java/autismclient/commands/impl/NbtCommand.java @@ -0,0 +1,79 @@ +package autismclient.commands.impl; + +import autismclient.commands.AutismCommandSource; +import autismclient.commands.Command; +import autismclient.gui.screen.AutismOverlayHostScreen; +import autismclient.util.AutismClientMessaging; +import autismclient.util.AutismItemCommandSerializer; +import autismclient.util.AutismItemNbtInspectOverlay; +import autismclient.util.AutismNotifications; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import net.minecraft.client.Minecraft; +import net.minecraft.world.item.ItemStack; + +public class NbtCommand extends Command { + public NbtCommand() { + super("nbt", "Inspect or copy the held item's components (NBT)."); + } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + inspect(); + return SUCCESS; + }); + root.then(LiteralArgumentBuilder.literal("get").executes(ctx -> { + inspect(); + return SUCCESS; + })); + root.then(LiteralArgumentBuilder.literal("copy").executes(ctx -> { + copy(); + return SUCCESS; + })); + } + + private static ItemStack held() { + Minecraft mc = Minecraft.getInstance(); + if (mc.player == null) return ItemStack.EMPTY; + ItemStack main = mc.player.getMainHandItem(); + return !main.isEmpty() ? main : mc.player.getOffhandItem(); + } + + private static void inspect() { + ItemStack stack = held(); + if (stack.isEmpty()) { + AutismClientMessaging.sendPrefixed("\u00a7cHold an item in either hand first."); + return; + } + if (!AutismItemNbtInspectOverlay.openGlobal(stack)) { + AutismClientMessaging.sendPrefixed("\u00a7cCould not open the NBT inspector."); + return; + } + + Minecraft mc = Minecraft.getInstance(); + if (mc != null) { + autismclient.util.AutismItemNbtInspectOverlay overlay = + autismclient.util.AutismItemNbtInspectOverlay.getSharedOverlay(mc.font); + mc.execute(() -> { + + if (mc.gui.screen() == null) { + mc.gui.setScreen(new AutismOverlayHostScreen(overlay)); + } + }); + } + } + + private static void copy() { + ItemStack stack = held(); + if (stack.isEmpty()) { + AutismClientMessaging.sendPrefixed("\u00a7cHold an item in either hand first."); + return; + } + try { + Minecraft.getInstance().keyboardHandler.setClipboard(AutismItemCommandSerializer.giveCommand(stack)); + AutismNotifications.copied("Copied /give command."); + } catch (Throwable t) { + AutismNotifications.error("Copy failed."); + } + } +} diff --git a/src/main/java/autismclient/commands/impl/PluginsCommand.java b/src/main/java/autismclient/commands/impl/PluginsCommand.java new file mode 100644 index 0000000..2396b02 --- /dev/null +++ b/src/main/java/autismclient/commands/impl/PluginsCommand.java @@ -0,0 +1,14 @@ +package autismclient.commands.impl; + +import autismclient.commands.Command; +import autismclient.commands.AutismCommandSource; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; + +public class PluginsCommand extends Command { + public PluginsCommand() { super("plugins", "Open the plugin scanner (alias of `server plugins`)."); } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { ServerCommand.openPlugins(); return SUCCESS; }); + } +} diff --git a/src/main/java/autismclient/commands/impl/PrefixCommand.java b/src/main/java/autismclient/commands/impl/PrefixCommand.java new file mode 100644 index 0000000..60ed52e --- /dev/null +++ b/src/main/java/autismclient/commands/impl/PrefixCommand.java @@ -0,0 +1,48 @@ +package autismclient.commands.impl; + +import autismclient.commands.AutismCommandSource; +import autismclient.commands.Command; +import autismclient.commands.CommandSuggest; +import autismclient.modules.AutismModule; +import autismclient.util.AutismClientMessaging; +import autismclient.util.AutismCompatManager; +import autismclient.util.AutismNotifications; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; + +public class PrefixCommand extends Command { + public PrefixCommand() { + super("prefix", "Change the AUTISM command prefix."); + } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + AutismClientMessaging.sendPrefixed("Current prefix: " + AutismCompatManager.effectiveCommandPrefix()); + return SUCCESS; + }); + root.then(LiteralArgumentBuilder.literal("reset").executes(ctx -> { + String prefix = AutismCompatManager.environmentDefaultCommandPrefix(); + AutismModule.get().setCommandPrefix(prefix); + AutismClientMessaging.sendPrefixed("Prefix reset to " + prefix); + return SUCCESS; + })); + root.then(RequiredArgumentBuilder.argument("new", StringArgumentType.word()) + .suggests(CommandSuggest::prefixes) + .executes(ctx -> { + String requested = StringArgumentType.getString(ctx, "new"); + if (!AutismCompatManager.COMMAND_PREFIX_CHOICES.contains(requested)) { + AutismClientMessaging.sendPrefixed("Prefix must be one of: . % - _ * # @ & ="); + return SUCCESS; + } + String selected = AutismCompatManager.normalizeStoredCommandPrefix(requested); + AutismModule.get().setCommandPrefix(selected); + if (!selected.equals(requested)) { + AutismNotifications.warning("Meteor uses '.'. Prefix kept as '%'."); + } + AutismClientMessaging.sendPrefixed("Prefix set to " + selected); + return SUCCESS; + })); + } +} diff --git a/src/main/java/autismclient/commands/impl/SayCommand.java b/src/main/java/autismclient/commands/impl/SayCommand.java new file mode 100644 index 0000000..024b24d --- /dev/null +++ b/src/main/java/autismclient/commands/impl/SayCommand.java @@ -0,0 +1,31 @@ +package autismclient.commands.impl; + +import autismclient.commands.Command; +import autismclient.commands.AutismCommandSource; +import autismclient.commands.AutismCommands; +import autismclient.util.AutismClientMessaging; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; +import net.minecraft.client.Minecraft; + +public class SayCommand extends Command { + public SayCommand() { super("say", "Send a chat message."); } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + AutismClientMessaging.sendPrefixed("§eUsage: " + AutismCommands.effectivePrefix() + "say "); + return SUCCESS; + }); + root.then(RequiredArgumentBuilder.argument("message", StringArgumentType.greedyString()) + .executes(ctx -> { + String msg = StringArgumentType.getString(ctx, "message"); + var conn = Minecraft.getInstance().getConnection(); + if (conn == null) { AutismClientMessaging.sendPrefixed("§cNot connected."); return SUCCESS; } + if (msg.startsWith("/")) conn.sendCommand(msg.substring(1)); + else conn.sendChat(msg); + return SUCCESS; + })); + } +} diff --git a/src/main/java/autismclient/commands/impl/SendCommand.java b/src/main/java/autismclient/commands/impl/SendCommand.java new file mode 100644 index 0000000..8ebefec --- /dev/null +++ b/src/main/java/autismclient/commands/impl/SendCommand.java @@ -0,0 +1,85 @@ +package autismclient.commands.impl; + +import autismclient.commands.Command; +import autismclient.commands.AutismCommandSource; +import autismclient.commands.AutismCommands; +import autismclient.commands.args.PacketClassArgumentType; +import autismclient.util.AutismClientMessaging; +import autismclient.util.AutismPacketArgumentBuilder; +import autismclient.util.AutismPacketRegistry; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; +import net.minecraft.client.Minecraft; +import net.minecraft.network.protocol.Packet; + +public class SendCommand extends Command { + public SendCommand() { super("send", "Send a raw C2S packet by class name with optional field=value arguments."); } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + AutismClientMessaging.sendPrefixed("§eUsage: §f" + AutismCommands.effectivePrefix() + "send [field=value ...]"); + AutismClientMessaging.sendPrefixed("§7Tip: press Tab after the space to search C2S packet classes."); + AutismClientMessaging.sendPrefixed("§7Example: §f" + AutismCommands.effectivePrefix() + "send ServerboundSetCarriedItemPacket slot=0"); + return SUCCESS; + }); + root.then(RequiredArgumentBuilder.argument("packet", PacketClassArgumentType.packetClass()) + .executes(ctx -> send(PacketClassArgumentType.get(ctx, "packet"), "")) + .then(RequiredArgumentBuilder.argument("args", StringArgumentType.greedyString()) + .suggests((ctx, builder) -> { + Class> cls = AutismPacketRegistry.getPacket(PacketClassArgumentType.get(ctx, "packet")); + return AutismPacketArgumentBuilder.suggest(cls, builder); + }) + .executes(ctx -> send(PacketClassArgumentType.get(ctx, "packet"), StringArgumentType.getString(ctx, "args"))))); + } + + private int send(String name, String args) { + Class> cls = AutismPacketRegistry.getPacket(name); + if (cls == null) { + AutismClientMessaging.sendPrefixed("§cUnknown packet: §f" + name); + return SUCCESS; + } + if (!AutismPacketRegistry.getC2SPackets().contains(cls)) { + AutismClientMessaging.sendPrefixed("§cRefusing to send non-C2S packet: §f" + name); + return SUCCESS; + } + + AutismPacketArgumentBuilder.PreparedArgs prepared; + try { + prepared = AutismPacketArgumentBuilder.prepare(args); + } catch (IllegalArgumentException e) { + AutismClientMessaging.sendPrefixed("§cBad arguments: " + e.getMessage()); + return SUCCESS; + } + AutismPacketArgumentBuilder.Result result = AutismPacketArgumentBuilder.build(cls, prepared.args()); + if (result.help()) { + sendLines("§e", result.message()); + return SUCCESS; + } + if (!result.ok()) { + sendLines("§c", "Failed to build §f" + name + "§c: " + result.message()); + return SUCCESS; + } + + if (prepared.dryRun()) { + AutismClientMessaging.sendPrefixed("§eBuilt §f" + name + "§7 (" + result.source() + ") §e- dry run, not sent."); + return SUCCESS; + } + var conn = Minecraft.getInstance().getConnection(); + if (conn == null) { + AutismClientMessaging.sendPrefixed("§cNo network connection."); + return SUCCESS; + } + autismclient.util.AutismSharedState.get().sendPacketBypassDelay(conn, result.packet()); + AutismClientMessaging.sendPrefixed("§aSent §f" + name + "§7 (" + result.source() + ")"); + return SUCCESS; + } + + private static void sendLines(String color, String message) { + if (message == null || message.isBlank()) return; + for (String line : message.split("\\R")) { + if (!line.isBlank()) AutismClientMessaging.sendPrefixed(color + line); + } + } +} diff --git a/src/main/java/autismclient/commands/impl/ServerCommand.java b/src/main/java/autismclient/commands/impl/ServerCommand.java new file mode 100644 index 0000000..b166659 --- /dev/null +++ b/src/main/java/autismclient/commands/impl/ServerCommand.java @@ -0,0 +1,53 @@ +package autismclient.commands.impl; + +import autismclient.commands.Command; +import autismclient.commands.AutismCommandSource; +import autismclient.gui.screen.AutismOverlayHostScreen; +import autismclient.modules.AutismModule; +import autismclient.util.AutismClientMessaging; +import autismclient.util.AutismOverlayManager; +import autismclient.util.AutismServerInfoOverlay; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import net.minecraft.client.Minecraft; + +public class ServerCommand extends Command { + public ServerCommand() { super("server", "Open the server info panel, or the plugin scanner."); } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { openInfo(); return SUCCESS; }); + root.then(LiteralArgumentBuilder.literal("info").executes(ctx -> { openInfo(); return SUCCESS; })); + root.then(LiteralArgumentBuilder.literal("plugins").executes(ctx -> { openPlugins(); return SUCCESS; })); + root.then(LiteralArgumentBuilder.literal("tps").executes(ctx -> { tps(); return SUCCESS; })); + } + + static void openInfo() { + openOverlay(false); + } + + static void openPlugins() { + openOverlay(true); + } + + private static void openOverlay(boolean pluginsTab) { + AutismServerInfoOverlay overlay = AutismModule.get().getServerDataOverlay(); + if (overlay == null) { AutismClientMessaging.sendPrefixed("§cServer overlay unavailable."); return; } + AutismOverlayManager.get().register(overlay); + if (pluginsTab) overlay.openPluginsTab(); + else overlay.openInfoTab(); + + Minecraft mc = Minecraft.getInstance(); + if (mc != null) { + mc.execute(() -> { + if (mc.gui.screen() == null) { + mc.gui.setScreen(new AutismOverlayHostScreen(overlay)); + } + }); + } + } + + private static void tps() { + double tps = autismclient.util.macro.ServerTickTracker.getEstimatedTps(); + AutismClientMessaging.sendPrefixed(String.format("§eTPS: §f%.2f §7(estimated)", tps)); + } +} diff --git a/src/main/java/autismclient/commands/impl/ToggleCommand.java b/src/main/java/autismclient/commands/impl/ToggleCommand.java new file mode 100644 index 0000000..58fd8d6 --- /dev/null +++ b/src/main/java/autismclient/commands/impl/ToggleCommand.java @@ -0,0 +1,54 @@ +package autismclient.commands.impl; + +import autismclient.commands.Command; +import autismclient.commands.AutismCommandSource; +import autismclient.commands.AutismCommands; +import autismclient.commands.CommandSuggest; +import autismclient.commands.args.ModuleArgumentType; +import autismclient.modules.PackHideState; +import autismclient.modules.ModuleRegistry; +import autismclient.util.AutismClientMessaging; +import autismclient.util.macro.ToggleModuleAction; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; + +public class ToggleCommand extends Command { + public ToggleCommand() { super("toggle", "Toggle a module on/off.", "t"); } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + AutismClientMessaging.sendPrefixed("§eUsage: §f" + AutismCommands.effectivePrefix() + "toggle [on|off|toggle]"); + return SUCCESS; + }); + root.then(RequiredArgumentBuilder.argument("module", ModuleArgumentType.moduleName()) + .executes(ctx -> doToggle(ModuleArgumentType.get(ctx, "module"), ToggleModuleAction.ToggleMode.TOGGLE)) + .then(RequiredArgumentBuilder.argument("state", StringArgumentType.word()) + .suggests(CommandSuggest::state) + .executes(ctx -> { + String state = StringArgumentType.getString(ctx, "state").toLowerCase(); + if (!state.equals("on") && !state.equals("enable") && !state.equals("true") && !state.equals("1") + && !state.equals("off") && !state.equals("disable") && !state.equals("false") && !state.equals("0") + && !state.equals("toggle")) { + AutismClientMessaging.sendPrefixed("§cUnknown toggle state: §f" + state); + AutismClientMessaging.sendPrefixed("§7Use §fon§7, §foff§7, or §ftoggle§7."); + return SUCCESS; + } + ToggleModuleAction.ToggleMode mode = switch (state) { + case "on", "enable", "true", "1" -> ToggleModuleAction.ToggleMode.ENABLE; + case "off", "disable", "false", "0" -> ToggleModuleAction.ToggleMode.DISABLE; + default -> ToggleModuleAction.ToggleMode.TOGGLE; + }; + return doToggle(ModuleArgumentType.get(ctx, "module"), mode); + }))); + } + + private static int doToggle(String moduleName, ToggleModuleAction.ToggleMode mode) { + boolean ok = ModuleRegistry.toggle(moduleName, mode); + if (ok && PackHideState.isHideModuleName(moduleName)) return SUCCESS; + if (ok) AutismClientMessaging.sendPrefixed("§a" + mode.name().toLowerCase() + ": §f" + moduleName); + else AutismClientMessaging.sendPrefixed("§cModule not found: §f" + moduleName); + return SUCCESS; + } +} diff --git a/src/main/java/autismclient/commands/impl/VClipCommand.java b/src/main/java/autismclient/commands/impl/VClipCommand.java new file mode 100644 index 0000000..484e84c --- /dev/null +++ b/src/main/java/autismclient/commands/impl/VClipCommand.java @@ -0,0 +1,129 @@ +package autismclient.commands.impl; + +import autismclient.commands.AutismCommandSource; +import autismclient.commands.AutismCommands; +import autismclient.commands.Command; +import autismclient.commands.CommandSuggest; +import autismclient.util.AutismClientMessaging; +import autismclient.util.macro.VClipAction; +import com.mojang.brigadier.arguments.BoolArgumentType; +import com.mojang.brigadier.arguments.DoubleArgumentType; +import com.mojang.brigadier.arguments.IntegerArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; +import net.minecraft.client.Minecraft; + +public class VClipCommand extends Command { + public VClipCommand() { + super("vclip", "Lets you clip through blocks vertically with movement packets."); + } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + String prefix = AutismCommands.effectivePrefix(); + AutismClientMessaging.sendPrefixed("\u00a7eUsage: \u00a7f" + prefix + "vclip "); + AutismClientMessaging.sendPrefixed("\u00a77Modes: \u00a7fdefault, top, bottom, paper, single, custom"); + AutismClientMessaging.sendPrefixed("\u00a77Examples: \u00a7f" + prefix + "vclip top \u00a77or \u00a7f" + prefix + "vclip custom -25 10 20 true true"); + return SUCCESS; + }); + + root.then(blocksArgument("blocks", options -> options)); + root.then(LiteralArgumentBuilder.literal("top") + .executes(ctx -> { + VClipAction.Options options = VClipAction.Options.defaults(0.0); + options.mode = VClipAction.Mode.TOP; + run(options); + return SUCCESS; + })); + root.then(LiteralArgumentBuilder.literal("bottom") + .executes(ctx -> { + VClipAction.Options options = VClipAction.Options.defaults(0.0); + options.mode = VClipAction.Mode.BOTTOM; + run(options); + return SUCCESS; + })); + root.then(LiteralArgumentBuilder.literal("default") + .then(blocksArgument("blocks", options -> options))); + root.then(LiteralArgumentBuilder.literal("paper") + .then(blocksArgument("blocks", options -> options))); + root.then(LiteralArgumentBuilder.literal("single") + .then(blocksArgument("blocks", VClipAction.Options::singlePacket))); + root.then(LiteralArgumentBuilder.literal("normal") + .then(blocksArgument("blocks", VClipAction.Options::singlePacket))); + root.then(LiteralArgumentBuilder.literal("custom") + .then(RequiredArgumentBuilder.argument("blocks", DoubleArgumentType.doubleArg()) + .suggests(CommandSuggest::offsets) + .then(RequiredArgumentBuilder.argument("segment", IntegerArgumentType.integer(1, 50)) + .suggests(CommandSuggest::vclipSegments) + .executes(ctx -> { + VClipAction.Options options = VClipAction.Options.defaults(DoubleArgumentType.getDouble(ctx, "blocks")); + options.segmentBlocks = IntegerArgumentType.getInteger(ctx, "segment"); + run(options); + return SUCCESS; + }) + .then(RequiredArgumentBuilder.argument("maxPackets", IntegerArgumentType.integer(1, 100)) + .suggests(CommandSuggest::vclipPacketLimits) + .executes(ctx -> { + VClipAction.Options options = VClipAction.Options.defaults(DoubleArgumentType.getDouble(ctx, "blocks")); + options.segmentBlocks = IntegerArgumentType.getInteger(ctx, "segment"); + options.maxPackets = IntegerArgumentType.getInteger(ctx, "maxPackets"); + run(options); + return SUCCESS; + }) + .then(RequiredArgumentBuilder.argument("updateLocal", BoolArgumentType.bool()) + .executes(ctx -> { + VClipAction.Options options = customOptions(ctx); + options.updateLocalPosition = BoolArgumentType.getBool(ctx, "updateLocal"); + run(options); + return SUCCESS; + }) + .then(RequiredArgumentBuilder.argument("vehicle", BoolArgumentType.bool()) + .executes(ctx -> { + VClipAction.Options options = customOptions(ctx); + options.updateLocalPosition = BoolArgumentType.getBool(ctx, "updateLocal"); + options.tryVehicleFirst = BoolArgumentType.getBool(ctx, "vehicle"); + run(options); + return SUCCESS; + }) + .then(RequiredArgumentBuilder.argument("forceGround", BoolArgumentType.bool()) + .executes(ctx -> { + VClipAction.Options options = customOptions(ctx); + options.updateLocalPosition = BoolArgumentType.getBool(ctx, "updateLocal"); + options.tryVehicleFirst = BoolArgumentType.getBool(ctx, "vehicle"); + options.forceGrounded = BoolArgumentType.getBool(ctx, "forceGround"); + run(options); + return SUCCESS; + })))))))); + } + + private interface OptionsCustomizer { + VClipAction.Options apply(VClipAction.Options options); + } + + private static RequiredArgumentBuilder blocksArgument(String name, OptionsCustomizer customizer) { + return RequiredArgumentBuilder.argument(name, DoubleArgumentType.doubleArg()) + .suggests(CommandSuggest::offsets) + .executes(ctx -> { + VClipAction.Options options = VClipAction.Options.defaults(DoubleArgumentType.getDouble(ctx, name)); + run(customizer.apply(options)); + return SUCCESS; + }); + } + + private static VClipAction.Options customOptions(com.mojang.brigadier.context.CommandContext ctx) { + VClipAction.Options options = VClipAction.Options.defaults(DoubleArgumentType.getDouble(ctx, "blocks")); + options.segmentBlocks = IntegerArgumentType.getInteger(ctx, "segment"); + options.maxPackets = IntegerArgumentType.getInteger(ctx, "maxPackets"); + return options; + } + + public static void vclip(double blocks) { + run(VClipAction.Options.defaults(blocks)); + } + + private static void run(VClipAction.Options options) { + options.showMessage = true; + VClipAction.perform(Minecraft.getInstance(), options); + } +} diff --git a/src/main/java/autismclient/commands/impl/XCarryCommand.java b/src/main/java/autismclient/commands/impl/XCarryCommand.java new file mode 100644 index 0000000..7b528d6 --- /dev/null +++ b/src/main/java/autismclient/commands/impl/XCarryCommand.java @@ -0,0 +1,134 @@ +package autismclient.commands.impl; + +import autismclient.commands.Command; +import autismclient.commands.AutismCommandSource; +import autismclient.commands.AutismCommands; +import autismclient.commands.args.XCarrySlotArgumentType; +import autismclient.util.AutismClientMessaging; +import autismclient.util.AutismSharedState; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.inventory.InventoryScreen; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.ContainerInput; +import net.minecraft.world.inventory.InventoryMenu; +import net.minecraft.world.item.ItemStack; + +import java.util.LinkedHashSet; +import java.util.Set; + +public class XCarryCommand extends Command { + public XCarryCommand() { + super("xcarry", + "Stash the held item into an XCarry slot: craft1..craft5 / helmet / chestplate / leggings / boots / offhand / cursor."); + } + + @Override + public void build(LiteralArgumentBuilder root) { + root.executes(ctx -> { + String prefix = AutismCommands.effectivePrefix(); + AutismClientMessaging.sendPrefixed("§eUsage: §f" + prefix + "xcarry "); + AutismClientMessaging.sendPrefixed("§7Slots: §fcraft1§7..§fcraft5§7, §fhelmet§7, §fchestplate§7, §fleggings§7, §fboots§7, §foffhand§7, §fcursor§7."); + return SUCCESS; + }); + root.then(RequiredArgumentBuilder.argument("slot", XCarrySlotArgumentType.slot()) + .executes(ctx -> stash(XCarrySlotArgumentType.get(ctx, "slot")))); + } + + private static int stash(int targetSlot) { + Minecraft mc = Minecraft.getInstance(); + LocalPlayer p = mc.player; + if (p == null || mc.gameMode == null) { + AutismClientMessaging.sendPrefixed("§cNot in a world."); + return SUCCESS; + } + + ItemStack heldStack = p.getMainHandItem().copy(); + if (heldStack == null || heldStack.isEmpty()) { + AutismClientMessaging.sendPrefixed("§cHold an item first."); + return SUCCESS; + } + + if (p.containerMenu != p.inventoryMenu) { + AutismClientMessaging.sendPrefixed("§cOpen your inventory first (E), then run the command."); + return SUCCESS; + } + + AbstractContainerMenu container = p.containerMenu; + + int hotbar = p.getInventory().getSelectedSlot(); + int sourceSlotId = 36 + hotbar; + + AutismSharedState shared = AutismSharedState.get(); + boolean prevBypass = shared.isXCarryArmorBypass(); + shared.setXCarryArmorBypass(true); + try { + + mc.gameMode.handleContainerInput(container.containerId, sourceSlotId, 0, ContainerInput.PICKUP, p); + if (container.getCarried().isEmpty()) { + AutismClientMessaging.sendPrefixed("§cCould not pick up the held item."); + return SUCCESS; + } + + String itemName = heldStack.getHoverName().getString(); + String slotName = XCarrySlotArgumentType.displayName(targetSlot); + LinkedHashSet forcedSlots = mergedForcedSlots(shared); + boolean forcedCursor = shared.isXCarryForced() && shared.isXCarryForcedCarryCursor(); + + if (targetSlot == XCarrySlotArgumentType.CURSOR) { + + shared.setXCarryForcedTargets(forcedSlots, true); + shared.setXCarryForced(true); + shared.setXCarryActive(true); + AutismClientMessaging.sendPrefixed("§aHolding §f" + itemName + "§a on cursor (XCarry)."); + return SUCCESS; + } + + if (targetSlot < 0 || targetSlot >= container.slots.size()) { + AutismClientMessaging.sendPrefixed("§cInvalid slot (" + targetSlot + ")."); + + mc.gameMode.handleContainerInput(container.containerId, sourceSlotId, 0, ContainerInput.PICKUP, p); + return SUCCESS; + } + + mc.gameMode.handleContainerInput(container.containerId, targetSlot, 0, ContainerInput.PICKUP, p); + + boolean placed = container.getCarried().isEmpty() + && targetSlot >= 0 + && targetSlot < container.slots.size() + && !container.slots.get(targetSlot).getItem().isEmpty(); + if (!placed && !container.getCarried().isEmpty()) { + mc.gameMode.handleContainerInput(container.containerId, sourceSlotId, 0, ContainerInput.PICKUP, p); + } + + if (!placed) { + AutismClientMessaging.sendPrefixed("§cCould not stash into §f" + slotName + "§c."); + return SUCCESS; + } + + forcedSlots.add(targetSlot); + shared.setXCarryForcedTargets(forcedSlots, forcedCursor); + shared.setXCarryForced(true); + shared.setXCarryActive(true); + AutismClientMessaging.sendPrefixed("§aStashed §f" + itemName + "§a into §f" + slotName + "§a."); + return SUCCESS; + } finally { + shared.setXCarryArmorBypass(prevBypass); + } + } + + private static LinkedHashSet mergedForcedSlots(AutismSharedState shared) { + LinkedHashSet slots = new LinkedHashSet<>(); + if (shared != null && shared.isXCarryForced()) { + Set existing = shared.getXCarryForcedSlotMask(); + if (existing != null) { + for (Integer slot : existing) { + if (slot != null && slot >= 0) slots.add(slot); + } + } + } + return slots; + } +} diff --git a/src/main/java/autismclient/compat/AutismModMenuConfigScreen.java b/src/main/java/autismclient/compat/AutismModMenuConfigScreen.java new file mode 100644 index 0000000..d13edf3 --- /dev/null +++ b/src/main/java/autismclient/compat/AutismModMenuConfigScreen.java @@ -0,0 +1,381 @@ +package autismclient.compat; + +import autismclient.gui.screen.AutismAddonsScreen; +import autismclient.gui.screen.AutismThemeColorScreen; +import autismclient.gui.vanillaui.UiBounds; +import autismclient.gui.vanillaui.UiContext; +import autismclient.gui.vanillaui.UiContexts; +import autismclient.gui.vanillaui.UiRenderer; +import autismclient.gui.vanillaui.UiScissorStack; +import autismclient.gui.vanillaui.assets.UiAssets; +import autismclient.gui.vanillaui.components.Dropdown; +import autismclient.gui.vanillaui.components.UiText; +import autismclient.modules.AutismModule; +import autismclient.util.AutismBindUtil; +import autismclient.util.AutismCompatManager; +import autismclient.util.AutismConfig; +import autismclient.util.AutismLinks; +import autismclient.util.AutismTheme; +import autismclient.util.AutismTheme.Channel; +import autismclient.util.AutismUiScale; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.Identifier; +import org.lwjgl.glfw.GLFW; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.IntConsumer; +import java.util.function.IntSupplier; + +public class AutismModMenuConfigScreen extends Screen { + private static final int TEXT_COLOR = 0xFFF3ECE7; + private static final int MUTED_COLOR = 0xFFB79E9E; + private static final int ROW_H = 18; + private static final int ROW_GAP = 3; + private static final int ROW_STEP = ROW_H + ROW_GAP; + private static final int HEADER_H = 22; + private static final int FOOTER_H = 30; + + private final Screen parent; + private final List keybinds = new ArrayList<>(); + private int capturing = -1; + private int scroll; + + private final List hits = new ArrayList<>(); + private UiBounds contentViewport = UiBounds.of(0, 0, 0, 0); + private int contentHeight; + private UiContext ctx; + private Dropdown prefixDropdown; + + private record Keybind(String label, IntSupplier getter, IntConsumer setter) {} + private record Hit(UiBounds bounds, Runnable onLeft, Runnable onRight) {} + + public AutismModMenuConfigScreen(Screen parent) { + super(Component.literal("AUTISM Client Settings")); + this.parent = parent; + AutismConfig cfg = AutismConfig.getGlobal(); + keybinds.add(new Keybind("Module Menu", () -> cfg.keybindModuleMenu, v -> { cfg.keybindModuleMenu = v; cfg.save(); })); + keybinds.add(new Keybind("Load GUI", () -> cfg.keybindLoadGui, v -> { cfg.keybindLoadGui = v; cfg.save(); })); + keybinds.add(new Keybind("Flush Queue", () -> cfg.keybindFlushQueue, v -> { cfg.keybindFlushQueue = v; cfg.save(); })); + keybinds.add(new Keybind("Clear Queue", () -> cfg.keybindClearQueue, v -> { cfg.keybindClearQueue = v; cfg.save(); })); + keybinds.add(new Keybind("Toggle Logger", () -> cfg.keybindToggleLogger, v -> { cfg.keybindToggleLogger = v; cfg.save(); })); + keybinds.add(new Keybind("Toggle Send", () -> cfg.keybindToggleSend, v -> { cfg.keybindToggleSend = v; cfg.save(); })); + keybinds.add(new Keybind("Toggle Delay", () -> cfg.keybindToggleDelay, v -> { cfg.keybindToggleDelay = v; cfg.save(); })); + } + + @Override + public boolean isPauseScreen() { + return false; + } + + @Override + public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float delta) { + int mx = AutismUiScale.toVirtualInt(mouseX); + int my = AutismUiScale.toVirtualInt(mouseY); + AutismUiScale.pushOverlayScale(graphics); + try { + hits.clear(); + ctx = UiContexts.overlay(graphics, font, mx, my); + int sw = AutismUiScale.getVirtualScreenWidth(); + int sh = AutismUiScale.getVirtualScreenHeight(); + UiRenderer.rect(graphics, UiBounds.of(0, 0, sw, sh), 0xF0090709); + + int panelW = Math.min(320, sw - 20); + int panelH = Math.min(sh - 20, HEADER_H + FOOTER_H + rows().size() * ROW_STEP + 8); + panelH = Math.max(panelH, HEADER_H + FOOTER_H + ROW_STEP); + int px = (sw - panelW) / 2; + int py = (sh - panelH) / 2; + UiBounds panel = UiBounds.of(px, py, panelW, panelH); + UiRenderer.frame(graphics, panel, 0xE60A0A0C, border()); + + UiBounds header = UiBounds.of(px, py, panelW, HEADER_H); + UiRenderer.rect(graphics, UiBounds.of(px + 1, py + 1, panelW - 2, HEADER_H - 1), p(0x33241A1D, Channel.HEADER)); + drawCentered(graphics, "AUTISM Client Settings", UiAssets.FONT_TITLE, p(TEXT_COLOR, Channel.TEXT), header); + + UiBounds footer = UiBounds.of(px, panel.bottom() - FOOTER_H, panelW, FOOTER_H); + UiBounds done = UiBounds.of(px + 8, footer.y() + 6, panelW - 16, ROW_H); + button(graphics, done, "Done", done.contains(mx, my), true); + addHit(done, this::onClose, null); + + int contentTop = py + HEADER_H + 4; + int contentBottom = footer.y() - 4; + contentViewport = UiBounds.of(px + 4, contentTop, panelW - 8, Math.max(0, contentBottom - contentTop)); + List rows = rows(); + contentHeight = rows.size() * ROW_STEP; + scroll = clampScroll(scroll); + + boolean needsBar = contentHeight > contentViewport.height(); + int rowW = contentViewport.width() - (needsBar ? 6 : 0); + + UiScissorStack.global().push(graphics, contentViewport); + try { + for (int i = 0; i < rows.size(); i++) { + int ry = contentViewport.y() - scroll + i * ROW_STEP; + if (ry + ROW_H < contentViewport.y() || ry > contentViewport.bottom()) continue; + UiBounds rb = UiBounds.of(contentViewport.x(), ry, rowW, ROW_H); + boolean visible = ry >= contentViewport.y() - 1 && ry + ROW_H <= contentViewport.bottom() + 1; + rows.get(i).render(graphics, rb, mx, my, visible); + } + } finally { + UiScissorStack.global().pop(graphics); + } + + if (needsBar) { + int trackX = contentViewport.right() - 4; + int trackH = contentViewport.height(); + UiRenderer.rect(graphics, UiBounds.of(trackX, contentViewport.y(), 3, trackH), 0x40000000); + int thumbH = Math.max(12, (int) ((long) trackH * trackH / contentHeight)); + int maxScroll = contentHeight - trackH; + int thumbY = contentViewport.y() + (maxScroll <= 0 ? 0 : (int) ((long) (trackH - thumbH) * scroll / maxScroll)); + UiRenderer.rect(graphics, UiBounds.of(trackX, thumbY, 3, thumbH), p(0xFFFF3B3B, Channel.ACCENT)); + } + + if (prefixDropdown != null && prefixDropdown.isOpen()) prefixDropdown.render(ctx); + } finally { + AutismUiScale.popOverlayScale(graphics); + } + } + + private interface Row { + void render(GuiGraphicsExtractor g, UiBounds rb, int mx, int my, boolean clickable); + } + + private List rows() { + AutismConfig cfg = AutismConfig.getGlobal(); + AutismModule module = AutismModule.get(); + List out = new ArrayList<>(); + + out.add(toggleRow("Open Inside GUI", () -> cfg.keybindInsideGui, v -> { cfg.keybindInsideGui = v; cfg.save(); })); + out.add(toggleRow("Custom Main Menu", () -> cfg.customMainMenu, v -> { cfg.customMainMenu = v; cfg.save(); })); + out.add(toggleRow("Auto Probe Plugins", () -> cfg.autoProbePlugins, v -> { cfg.autoProbePlugins = v; cfg.save(); })); + + out.add(cycleRow("Overlay Scale", AutismUiScale.getOverlayScaleLabel(), + () -> AutismUiScale.setOverlayScaleMultiplier(AutismUiScale.nextOverlayScaleMultiplier()), + () -> AutismUiScale.setOverlayScaleMultiplier(AutismUiScale.previousOverlayScaleMultiplier()))); + + List prefixes = new ArrayList<>(AutismCompatManager.COMMAND_PREFIX_CHOICES); + if (AutismCompatManager.isMeteorAvailable()) prefixes.remove("."); + String cur = AutismCompatManager.effectiveCommandPrefix(); + if (!prefixes.contains(cur)) cur = prefixes.isEmpty() ? "%" : prefixes.get(0); + out.add(prefixRow(module, prefixes, cur)); + + for (int i = 0; i < keybinds.size(); i++) out.add(keybindRow(i)); + + out.add(actionRow("Theme Color", () -> this.minecraft.gui.setScreen(new AutismThemeColorScreen(this)))); + out.add(actionRow("Addons", () -> this.minecraft.gui.setScreen(new AutismAddonsScreen(this)))); + out.add(splitRow("Donate", () -> AutismLinks.open(AutismLinks.KOFI), + "Discord", () -> AutismLinks.open(AutismLinks.DISCORD))); + return out; + } + + private Row toggleRow(String label, IntSupplierBool getter, java.util.function.Consumer setter) { + return (g, rb, mx, my, clickable) -> { + boolean on = getter.get(); + boolean hover = clickable && rb.contains(mx, my); + UiRenderer.frame(g, rb, hover ? p(0x40201A1D, Channel.BUTTON) : 0x26181A1E, p(0x66662C2C, Channel.OUTLINE)); + draw(g, label, UiAssets.FONT_LABEL, p(TEXT_COLOR, Channel.TEXT), rb.x() + 8, rb.y() + 5); + UiBounds tog = UiBounds.of(rb.right() - 34, rb.y() + 3, 30, rb.height() - 6); + UiRenderer.frame(g, tog, on ? p(0xA8231A1D, Channel.TOGGLE) : 0x40121316, on ? p(0xFFFF6464, Channel.TOGGLE) : 0x66565D66); + int knobX = on ? tog.right() - 12 : tog.x() + 2; + UiRenderer.rect(g, UiBounds.of(knobX, tog.y() + 2, 10, tog.height() - 4), on ? p(0xFFFF3B3B, Channel.TOGGLE) : 0xFF8A8A8A); + if (clickable) addHit(rb, () -> setter.accept(!getter.get()), null); + }; + } + + private Row cycleRow(String label, String value, Runnable onLeft, Runnable onRight) { + return (g, rb, mx, my, clickable) -> { + boolean hover = clickable && rb.contains(mx, my); + UiRenderer.frame(g, rb, hover ? p(0x40201A1D, Channel.BUTTON) : 0x26181A1E, p(0x66662C2C, Channel.OUTLINE)); + draw(g, label, UiAssets.FONT_LABEL, p(TEXT_COLOR, Channel.TEXT), rb.x() + 8, rb.y() + 5); + int vw = UiText.width(font, value, UiAssets.FONT_BODY, MUTED_COLOR); + draw(g, value, UiAssets.FONT_BODY, p(0xFFFF6464, Channel.ACCENT), rb.right() - vw - 8, rb.y() + 5); + if (clickable) addHit(rb, onLeft, onRight); + }; + } + + private Row prefixRow(AutismModule module, List prefixes, String current) { + if (prefixDropdown == null) { + prefixDropdown = new Dropdown(UiBounds.of(0, 0, 0, 0), prefixes, current, module::setCommandPrefix); + } else { + prefixDropdown.setOptions(prefixes); + prefixDropdown.setSelected(current); + } + return (g, rb, mx, my, clickable) -> { + + UiRenderer.frame(g, rb, 0x26181A1E, p(0x66662C2C, Channel.OUTLINE)); + draw(g, "Command Prefix", UiAssets.FONT_LABEL, p(TEXT_COLOR, Channel.TEXT), rb.x() + 8, rb.y() + 5); + int ctrlW = Math.min(110, rb.width() / 2); + UiBounds ctrl = UiBounds.of(rb.right() - ctrlW - 2, rb.y() + 1, ctrlW, rb.height() - 2); + prefixDropdown.setBounds(ctrl); + boolean hover = clickable && ctrl.contains(mx, my); + Dropdown.renderControl(ctx, ctrl, current, hover, prefixDropdown.isOpen()); + if (clickable) { + addHit(ctrl, () -> { if (!prefixDropdown.isOpen()) prefixDropdown.open(); }, null); + } else if (prefixDropdown.isOpen()) { + prefixDropdown.close(); + } + }; + } + + private Row keybindRow(int idx) { + return (g, rb, mx, my, clickable) -> { + Keybind k = keybinds.get(idx); + boolean hover = clickable && rb.contains(mx, my); + boolean active = capturing == idx; + UiRenderer.frame(g, rb, active ? p(0x55241A1D, Channel.ACCENT) : (hover ? p(0x40201A1D, Channel.BUTTON) : 0x26181A1E), + active ? p(0xFFFF6464, Channel.ACCENT) : p(0x66662C2C, Channel.OUTLINE)); + draw(g, k.label(), UiAssets.FONT_LABEL, p(TEXT_COLOR, Channel.TEXT), rb.x() + 8, rb.y() + 5); + String v = active ? "press a key..." : AutismBindUtil.getBindName(k.getter().getAsInt()); + int vw = UiText.width(font, v, UiAssets.FONT_BODY, MUTED_COLOR); + draw(g, v, UiAssets.FONT_BODY, p(MUTED_COLOR, Channel.TEXT), rb.right() - vw - 8, rb.y() + 5); + if (clickable) addHit(rb, () -> startCapture(idx), null); + }; + } + + private Row actionRow(String label, Runnable onClick) { + return (g, rb, mx, my, clickable) -> { + button(g, rb, label, clickable && rb.contains(mx, my), false); + if (clickable) addHit(rb, onClick, null); + }; + } + + private Row splitRow(String labelA, Runnable onA, String labelB, Runnable onB) { + return (g, rb, mx, my, clickable) -> { + int half = (rb.width() - ROW_GAP) / 2; + UiBounds a = UiBounds.of(rb.x(), rb.y(), half, rb.height()); + UiBounds b = UiBounds.of(rb.x() + half + ROW_GAP, rb.y(), rb.width() - half - ROW_GAP, rb.height()); + button(g, a, labelA, clickable && a.contains(mx, my), false); + button(g, b, labelB, clickable && b.contains(mx, my), false); + if (clickable) { + addHit(a, onA, null); + addHit(b, onB, null); + } + }; + } + + private interface IntSupplierBool { boolean get(); } + + private void addHit(UiBounds bounds, Runnable onLeft, Runnable onRight) { + hits.add(new Hit(bounds, onLeft, onRight)); + } + + private int clampScroll(int value) { + int max = Math.max(0, contentHeight - contentViewport.height()); + return Math.max(0, Math.min(value, max)); + } + + private int p(int argb, Channel ch) { + return AutismTheme.recolor(argb, ch); + } + + private int border() { + return p(0xFFB32B2B, Channel.OUTLINE); + } + + private void button(GuiGraphicsExtractor g, UiBounds b, String label, boolean hover, boolean primary) { + UiRenderer.frame(g, b, hover ? p(0x55241A1D, Channel.BUTTON) : 0x33181A1E, + primary ? p(0xFFFF6464, Channel.ACCENT) : p(0x66662C2C, Channel.OUTLINE)); + int tw = UiText.width(font, label, UiAssets.FONT_LABEL, TEXT_COLOR); + draw(g, label, UiAssets.FONT_LABEL, p(TEXT_COLOR, Channel.TEXT), b.x() + (b.width() - tw) / 2, b.y() + (b.height() - 8) / 2); + } + + private void drawCentered(GuiGraphicsExtractor g, String text, Identifier fontId, int color, UiBounds area) { + int tw = UiText.width(font, text, fontId, color); + draw(g, text, fontId, color, area.x() + (area.width() - tw) / 2, area.y() + (area.height() - 8) / 2); + } + + private void draw(GuiGraphicsExtractor g, String text, Identifier fontId, int color, int x, int y) { + UiText.draw(g, this.font, text, fontId, color, x, y, false); + } + + @Override + public boolean mouseClicked(MouseButtonEvent event, boolean doubled) { + int mx = AutismUiScale.toVirtualInt(event.x()); + int my = AutismUiScale.toVirtualInt(event.y()); + boolean right = event.button() == GLFW.GLFW_MOUSE_BUTTON_RIGHT; + if (!right && event.button() != GLFW.GLFW_MOUSE_BUTTON_LEFT) return true; + if (capturing >= 0) { + applyCapture(AutismBindUtil.encodeMouseButton(event.button())); + return true; + } + + if (prefixDropdown != null && prefixDropdown.isOpen()) { + prefixDropdown.mouseClicked(mx, my, event.button()); + return true; + } + + for (int i = hits.size() - 1; i >= 0; i--) { + Hit hit = hits.get(i); + if (!hit.bounds().contains(mx, my)) continue; + Runnable action = right ? hit.onRight() : hit.onLeft(); + if (action != null) action.run(); + return true; + } + return true; + } + + @Override + public boolean mouseReleased(MouseButtonEvent event) { + if (prefixDropdown != null && prefixDropdown.isOpen()) { + prefixDropdown.mouseReleased(AutismUiScale.toVirtualInt(event.x()), AutismUiScale.toVirtualInt(event.y()), event.button()); + return true; + } + return super.mouseReleased(event); + } + + @Override + public boolean mouseDragged(MouseButtonEvent event, double dx, double dy) { + if (prefixDropdown != null && prefixDropdown.isOpen()) { + prefixDropdown.mouseDragged(AutismUiScale.toVirtualInt(event.x()), AutismUiScale.toVirtualInt(event.y()), event.button(), dx, dy); + return true; + } + return super.mouseDragged(event, dx, dy); + } + + @Override + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { + + if (prefixDropdown != null && prefixDropdown.isOpen()) { + prefixDropdown.mouseScrolled(AutismUiScale.toVirtualInt(mouseX), AutismUiScale.toVirtualInt(mouseY), scrollY); + return true; + } + if (scrollY != 0) scroll = clampScroll(scroll - (int) Math.signum(scrollY) * ROW_STEP * 2); + return true; + } + + @Override + public boolean keyPressed(KeyEvent event) { + if (capturing >= 0) { + applyCapture(event.key() == GLFW.GLFW_KEY_ESCAPE ? -1 : event.key()); + return true; + } + if (event.key() == GLFW.GLFW_KEY_ESCAPE) { + if (prefixDropdown != null && prefixDropdown.isOpen()) { + prefixDropdown.close(); + return true; + } + onClose(); + return true; + } + return super.keyPressed(event); + } + + private void startCapture(int idx) { + capturing = idx; + } + + private void applyCapture(int code) { + if (capturing < 0 || capturing >= keybinds.size()) return; + keybinds.get(capturing).setter().accept(code); + capturing = -1; + } + + @Override + public void onClose() { + this.minecraft.gui.setScreen(parent); + } +} diff --git a/src/main/java/autismclient/compat/AutismModMenuIntegration.java b/src/main/java/autismclient/compat/AutismModMenuIntegration.java new file mode 100644 index 0000000..2a4f041 --- /dev/null +++ b/src/main/java/autismclient/compat/AutismModMenuIntegration.java @@ -0,0 +1,11 @@ +package autismclient.compat; + +import com.terraformersmc.modmenu.api.ConfigScreenFactory; +import com.terraformersmc.modmenu.api.ModMenuApi; + +public class AutismModMenuIntegration implements ModMenuApi { + @Override + public ConfigScreenFactory getModConfigScreenFactory() { + return AutismModMenuConfigScreen::new; + } +} diff --git a/src/main/java/autismclient/ducks/AutismExternalButtonScreen.java b/src/main/java/autismclient/ducks/AutismExternalButtonScreen.java new file mode 100644 index 0000000..65cbdef --- /dev/null +++ b/src/main/java/autismclient/ducks/AutismExternalButtonScreen.java @@ -0,0 +1,7 @@ +package autismclient.ducks; + +import net.minecraft.client.gui.GuiGraphicsExtractor; + +public interface AutismExternalButtonScreen { + void autism$renderExternalButtons(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float deltaTicks); +} diff --git a/src/main/java/autismclient/gui/AutismLoadingOverlay.java b/src/main/java/autismclient/gui/AutismLoadingOverlay.java new file mode 100644 index 0000000..9d8fe8a --- /dev/null +++ b/src/main/java/autismclient/gui/AutismLoadingOverlay.java @@ -0,0 +1,213 @@ +package autismclient.gui; + +import autismclient.gui.vanillaui.UiBounds; +import autismclient.gui.vanillaui.UiRenderer; +import autismclient.util.AutismColors; +import autismclient.util.AutismTheme; +import autismclient.util.AutismTheme.Channel; +import autismclient.util.AutismThemeTextures; +import com.mojang.blaze3d.platform.Window; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.gui.screens.LoadingOverlay; +import net.minecraft.client.renderer.RenderPipelines; +import net.minecraft.resources.Identifier; +import net.minecraft.server.packs.resources.ReloadInstance; +import net.minecraft.util.ARGB; +import net.minecraft.util.Mth; +import net.minecraft.util.Util; +import org.joml.Vector4f; + +import java.util.Optional; +import java.util.function.Consumer; + +public class AutismLoadingOverlay extends LoadingOverlay { + private static final Identifier CUSTOM_LOGO = + Identifier.fromNamespaceAndPath("autismclient", "textures/gui/title/loading_logo.png"); + private static final int LOGO_WIDTH = 2106; + private static final int LOGO_HEIGHT = 1297; + private static final int BG_COLOR = AutismColors.loadingBg(); + private static final int BAR_R = 236; + private static final int BAR_G = 32; + private static final int BAR_B = 39; + + private static final long FADE_OUT_TIME = 1000L; + private static final long FADE_IN_TIME = 500L; + + private final Minecraft autism$minecraft; + private final ReloadInstance autism$reload; + private final Consumer> autism$onFinish; + private final boolean autism$fadeIn; + private float autism$currentProgress; + private long autism$fadeOutStart = -1L; + private long autism$fadeInStart = -1L; + + public AutismLoadingOverlay(Minecraft minecraft, ReloadInstance reload, + Consumer> onFinish, boolean fadeIn) { + super(minecraft, reload, onFinish, fadeIn); + this.autism$minecraft = minecraft; + this.autism$reload = reload; + this.autism$onFinish = onFinish; + this.autism$fadeIn = fadeIn; + } + + @Override + public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) { + int width = graphics.guiWidth(); + int height = graphics.guiHeight(); + long now = Util.getMillis(); + + if (this.autism$fadeIn && this.autism$fadeInStart == -1L) { + this.autism$fadeInStart = now; + } + + float fadeOutAnim = this.autism$fadeOutStart > -1L ? (float) (now - this.autism$fadeOutStart) / (float) FADE_OUT_TIME : -1.0F; + float fadeInAnim = this.autism$fadeInStart > -1L ? (float) (now - this.autism$fadeInStart) / (float) FADE_IN_TIME : -1.0F; + float logoAlpha; + + if (fadeOutAnim >= 1.0F) { + if (this.autism$minecraft.gui.screen() != null) { + this.autism$tryRenderScreen(graphics, 0, 0, a); + } else { + this.autism$minecraft.gui.hud.extractDeferredSubtitles(); + } + + int alpha = Mth.ceil((1.0F - Mth.clamp(fadeOutAnim - 1.0F, 0.0F, 1.0F)) * 255.0F); + graphics.nextStratum(); + UiRenderer.rect(graphics, UiBounds.of(0, 0, width, height), replaceAlpha(BG_COLOR, alpha)); + logoAlpha = 1.0F - Mth.clamp(fadeOutAnim - 1.0F, 0.0F, 1.0F); + } else if (this.autism$fadeIn) { + if (this.autism$minecraft.gui.screen() != null && fadeInAnim < 1.0F) { + this.autism$tryRenderScreen(graphics, mouseX, mouseY, a); + } else { + this.autism$minecraft.gui.hud.extractDeferredSubtitles(); + } + + int alpha = Mth.ceil(Mth.clamp((double) fadeInAnim, 0.15, 1.0) * 255.0); + graphics.nextStratum(); + UiRenderer.rect(graphics, UiBounds.of(0, 0, width, height), replaceAlpha(BG_COLOR, alpha)); + logoAlpha = Mth.clamp(fadeInAnim, 0.0F, 1.0F); + } else { + this.autism$minecraft.gameRenderer.gameRenderState().guiRenderState.clearColorOverride = colorVector(BG_COLOR); + logoAlpha = 1.0F; + } + + if (logoAlpha > 0.0F) { + drawCustomLogo(graphics, width, height, logoAlpha); + } + + float actualProgress = this.autism$reload.getActualProgress(); + this.autism$currentProgress = Mth.clamp(this.autism$currentProgress * 0.95F + actualProgress * 0.050000012F, 0.0F, 1.0F); + + if (fadeOutAnim < 1.0F) { + drawProgressBar(graphics, width, height, fadeOutAnim); + } + + if (fadeOutAnim >= 2.0F) { + this.autism$minecraft.gui.setOverlay(null); + } + } + + private void autism$tryRenderScreen(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) { + net.minecraft.client.gui.screens.Screen screen = this.autism$minecraft.gui.screen(); + if (screen == null) return; + try { + screen.extractRenderStateWithTooltipAndSubtitles(graphics, mouseX, mouseY, a); + } catch (Exception ignored) { } + } + + private void drawCustomLogo(GuiGraphicsExtractor graphics, int width, int height, float alpha) { + int centerX = width / 2; + int centerY = height / 2; + + double maxW = width * 0.85; + double maxH = height * 0.85; + double scale = Math.min(maxW / LOGO_WIDTH, maxH / LOGO_HEIGHT) * 0.95; + + int drawW = (int) (LOGO_WIDTH * scale); + int drawH = (int) (LOGO_HEIGHT * scale); + + int x = centerX - drawW / 2; + int y = centerY - drawH / 2; + int color = ARGB.white(alpha); + + graphics.blit( + RenderPipelines.GUI_TEXTURED, + AutismThemeTextures.recolored(CUSTOM_LOGO, Channel.ACCENT), + x, y, 0.0F, 0.0F, + drawW, drawH, + LOGO_WIDTH, LOGO_HEIGHT, + LOGO_WIDTH, LOGO_HEIGHT, + color + ); + } + + private void drawProgressBar(GuiGraphicsExtractor graphics, int width, int height, float fadeOutAnim) { + float barFade = 1.0F - Mth.clamp(fadeOutAnim, 0.0F, 1.0F); + + double maxW = width * 0.85; + double maxH = height * 0.85; + double scale = Math.min(maxW / LOGO_WIDTH, maxH / LOGO_HEIGHT) * 0.95; + int drawW = (int) (LOGO_WIDTH * scale); + int drawH = (int) (LOGO_HEIGHT * scale); + + int centerX = width / 2; + int logoBottom = height / 2 + drawH / 2; + int barY = logoBottom + 10; + + int x0 = centerX - drawW / 2; + int y0 = barY - 5; + int x1 = centerX + drawW / 2; + int y1 = barY + 5; + + int barWidth = Mth.ceil((x1 - x0 - 2) * this.autism$currentProgress); + int alpha = Math.round(barFade * 255.0F); + int barColor = AutismTheme.recolor(ARGB.color(alpha, BAR_R, BAR_G, BAR_B), Channel.ACCENT); + + if (barWidth > 0) { + UiRenderer.rect(graphics, UiBounds.of(x0 + 2, y0 + 2, barWidth, y1 - y0 - 4), barColor); + } + + UiRenderer.outline(graphics, UiBounds.of(x0, y0, x1 - x0, y1 - y0), barColor); + } + + private static int replaceAlpha(int color, int alpha) { + return color & 0x00FFFFFF | (alpha << 24); + } + + private static Vector4f colorVector(int color) { + return new Vector4f( + (float) ((color >>> 16) & 0xFF) / 255.0F, + (float) ((color >>> 8) & 0xFF) / 255.0F, + (float) (color & 0xFF) / 255.0F, + (float) ((color >>> 24) & 0xFF) / 255.0F + ); + } + + @Override + public void tick() { + if (this.autism$fadeOutStart == -1L && this.autism$reload.isDone() && this.autism$isReadyToFadeOut()) { + try { + this.autism$reload.checkExceptions(); + this.autism$onFinish.accept(Optional.empty()); + } catch (Throwable t) { + this.autism$onFinish.accept(Optional.of(t)); + } + + this.autism$fadeOutStart = Util.getMillis(); + if (this.autism$minecraft.gui.screen() != null) { + Window window = this.autism$minecraft.getWindow(); + this.autism$minecraft.gui.screen().init(window.getGuiScaledWidth(), window.getGuiScaledHeight()); + } + } + } + + private boolean autism$isReadyToFadeOut() { + return !this.autism$fadeIn || this.autism$fadeInStart > -1L && Util.getMillis() - this.autism$fadeInStart >= 1000L; + } + + @Override + public boolean isPausing() { + return true; + } +} diff --git a/src/main/java/autismclient/gui/AutismThemeApplyOverlay.java b/src/main/java/autismclient/gui/AutismThemeApplyOverlay.java new file mode 100644 index 0000000..2a305e8 --- /dev/null +++ b/src/main/java/autismclient/gui/AutismThemeApplyOverlay.java @@ -0,0 +1,151 @@ +package autismclient.gui; + +import autismclient.gui.vanillaui.UiBounds; +import autismclient.gui.vanillaui.UiRenderer; +import autismclient.gui.vanillaui.UiTextRenderer; +import autismclient.util.AutismTheme; +import autismclient.util.AutismTheme.Channel; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.gui.screens.Overlay; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.util.Mth; +import net.minecraft.util.Util; + +import java.util.concurrent.atomic.AtomicBoolean; + +public final class AutismThemeApplyOverlay extends Overlay { + private static final Object LOCK = new Object(); + private static final long MIN_VISIBLE_MS = 300L; + private static final long MAX_VISIBLE_MS = 10_000L; + + private static int totalJobs; + private static int doneJobs; + private static String currentTitle = "Applying Theme"; + private static String currentLabel = ""; + private static boolean shown; + + private static Runnable deferredAction; + + private final UiTextRenderer text = new UiTextRenderer(Minecraft.getInstance().font); + private long shownAtMs = -1L; + private float easedProgress; + private int framesRendered; + + private AutismThemeApplyOverlay() {} + + public static Runnable beginJob(String label) { + return beginJob(null, label); + } + + public static Runnable beginJob(String title, String label) { + synchronized (LOCK) { + if (doneJobs >= totalJobs) { + totalJobs = 0; + doneJobs = 0; + currentTitle = (title == null || title.isBlank()) ? "Applying Theme" : title; + } + totalJobs++; + currentLabel = label == null ? "" : label; + } + Minecraft mc = Minecraft.getInstance(); + mc.execute(() -> { + if (shown || mc.gui.overlay() != null) return; + shown = true; + mc.gui.setOverlay(new AutismThemeApplyOverlay()); + }); + AtomicBoolean completed = new AtomicBoolean(); + return () -> { + if (!completed.compareAndSet(false, true)) return; + synchronized (LOCK) { + doneJobs = Math.min(totalJobs, doneJobs + 1); + } + }; + } + + public static void runAfterShown(Runnable action) { + synchronized (LOCK) { + deferredAction = action; + } + } + + @Override + public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float delta) { + Minecraft mc = Minecraft.getInstance(); + long now = Util.getMillis(); + if (shownAtMs < 0) shownAtMs = now; + + Screen screen = mc.gui.screen(); + if (screen != null) { + try { + screen.extractRenderStateWithTooltipAndSubtitles(graphics, mouseX, mouseY, delta); + } catch (Exception ignored) { } + } + + int width = graphics.guiWidth(); + int height = graphics.guiHeight(); + graphics.nextStratum(); + UiRenderer.rect(graphics, UiBounds.of(0, 0, width, height), 0xA8000000); + + float target; + String title; + String label; + boolean finished; + synchronized (LOCK) { + target = totalJobs == 0 ? 1.0f : doneJobs / (float) totalJobs; + title = currentTitle; + label = currentLabel; + finished = doneJobs >= totalJobs; + } + easedProgress = Mth.clamp(easedProgress + (target - easedProgress) * (finished ? 0.35f : 0.15f), 0.0f, 1.0f); + if (finished && easedProgress > 0.98f) easedProgress = 1.0f; + + int panelW = Math.min(260, width - 40); + int panelH = 62; + int px = (width - panelW) / 2; + int py = (height - panelH) / 2; + int border = AutismTheme.recolor(0xFFB32B2B, Channel.OUTLINE); + int accent = AutismTheme.recolor(0xFFFF3B3B, Channel.ACCENT); + int textColor = AutismTheme.recolor(0xFFF3ECE7, Channel.TEXT); + UiRenderer.frame(graphics, UiBounds.of(px, py, panelW, panelH), 0xF5120B0D, border); + + text.drawCentered(graphics, title, UiBounds.of(px, py + 10, panelW, 9), textColor); + if (!label.isBlank()) { + text.drawCentered(graphics, label, UiBounds.of(px, py + 24, panelW, 9), 0xFF9A8F8A); + } + + int barX = px + 16; + int barW = panelW - 32; + int barY = py + panelH - 20; + int barH = 8; + UiRenderer.outline(graphics, UiBounds.of(barX, barY, barW, barH), border); + int fill = Math.round((barW - 4) * easedProgress); + if (fill > 0) { + UiRenderer.rect(graphics, UiBounds.of(barX + 2, barY + 2, fill, barH - 4), accent); + } + + boolean minElapsed = now - shownAtMs >= MIN_VISIBLE_MS; + boolean timedOut = now - shownAtMs >= MAX_VISIBLE_MS; + if ((finished && minElapsed && easedProgress >= 1.0f) || timedOut) { + shown = false; + if (mc.gui.overlay() == this) mc.gui.setOverlay(null); + } + + framesRendered++; + if (framesRendered >= 2) { + Runnable action; + synchronized (LOCK) { + action = deferredAction; + deferredAction = null; + } + if (action != null) { + try { action.run(); } catch (Throwable ignored) { } + } + } + } + + @Override + public boolean isPausing() { + return false; + } +} diff --git a/src/main/java/autismclient/gui/macro/editor/ActionEditorOverlay.java b/src/main/java/autismclient/gui/macro/editor/ActionEditorOverlay.java new file mode 100644 index 0000000..33f5b78 --- /dev/null +++ b/src/main/java/autismclient/gui/macro/editor/ActionEditorOverlay.java @@ -0,0 +1,13523 @@ +package autismclient.gui.macro.editor; + +import autismclient.gui.macro.editor.FieldType; +import autismclient.gui.macro.editor.components.MacroCaptureButton; +import autismclient.gui.macro.editor.components.MacroCaptureSession; +import autismclient.gui.macro.editor.components.MacroTypedListControl; +import autismclient.gui.vanillaui.assets.UiAssets; +import autismclient.gui.vanillaui.components.CompactDropdown; +import autismclient.gui.vanillaui.components.CompactListRenderer; +import autismclient.gui.vanillaui.components.CompactOverlayButton; +import autismclient.gui.vanillaui.components.CompactSurfaces; +import autismclient.gui.vanillaui.direct.DirectRenderContext; +import autismclient.gui.vanillaui.components.CompactScrollbar; +import autismclient.gui.vanillaui.components.UiSizing; +import autismclient.gui.vanillaui.direct.DirectScrollViewport; +import autismclient.util.macro.CraftAction; +import autismclient.util.AutismCraftingHelper; +import autismclient.gui.vanillaui.components.UiText; +import autismclient.gui.vanillaui.components.CompactTheme; +import autismclient.gui.vanillaui.components.UiTone; +import autismclient.gui.vanillaui.UiContexts; +import autismclient.gui.vanillaui.UiBounds; +import autismclient.gui.vanillaui.UiRenderer; +import autismclient.gui.vanillaui.UiScissorStack; +import autismclient.gui.vanillaui.components.ToastStack; +import autismclient.util.IAutismOverlay; +import autismclient.util.AutismChatField; +import autismclient.util.AutismClipboardHelper; +import autismclient.util.AutismClientMessaging; +import autismclient.util.AutismNotifications; +import autismclient.util.AutismColors; +import autismclient.util.AutismOverlayManager; +import autismclient.util.AutismOverlayBase; +import autismclient.util.AutismPacketNamer; +import autismclient.util.AutismPacketRegistry; +import autismclient.util.AutismPayloadJsonSupport; +import autismclient.util.AutismPayloadEditorModel; +import autismclient.util.AutismPayloadSupport; +import autismclient.util.AutismPayloadTemplate; +import autismclient.util.AutismRegistryLabels; +import autismclient.util.AutismPacketSelectorOverlay; +import autismclient.util.AutismSharedState; +import autismclient.util.AutismInstaBreakRenderer; +import autismclient.util.AutismUiScale; +import autismclient.util.AutismWindowLayout; +import autismclient.util.AutismMacro; +import autismclient.util.AutismMacroManager; +import autismclient.util.macro.ItemTarget; +import autismclient.util.macro.MacroAction; +import autismclient.util.macro.MacroActionType; +import autismclient.util.macro.PayloadAction; +import autismclient.util.macro.SendPacketAction; +import autismclient.util.macro.WaitForPacketAction; +import autismclient.util.macro.WaitForSlotChangeAction; +import autismclient.util.macro.WaitPacketMatchAction; +import autismclient.util.macro.WaitsForGui; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParser; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.input.MouseButtonEvent; +import net.minecraft.client.input.MouseButtonInfo; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; +import net.minecraft.client.gui.screens.inventory.InventoryScreen; +import net.minecraft.client.input.CharacterEvent; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.Tag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.StringTag; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.util.FormattedCharSequence; +import net.minecraft.network.chat.Style; +import net.minecraft.network.chat.Component; +import net.minecraft.world.phys.Vec3; +import net.minecraft.resources.Identifier; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import org.lwjgl.glfw.GLFW; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Locale; +import java.util.Optional; +import java.util.function.Function; + +public class ActionEditorOverlay extends AutismOverlayBase { + + private static final Minecraft MC = Minecraft.getInstance(); + + private static final int DEFAULT_W = 280; + private static final int COMPACT_W = 184; + private static final int MIN_W = 168; + private static final int MIN_H = 96; + private static final int COMPACT_MIN_H = 88; + private static final int PAD = 4; + private static final int ROW_H = 15; + private static final int ROW_GAP = 2; + private static final int FOOTER_H = 32; + private static final int LABEL_MIN_W = 44; + private static final int LABEL_MAX_W = 68; + private static final int FIELD_GAP = 3; + private static final int CATALOG_LIST_H = 60; + private static final int CATALOG_ITEM_H = 13; + private static final int CAPTURE_BTN_W = MacroCaptureButton.WIDTH; + private static final int SEL_LIST_MAX_VIS = 4; + private static final int SEL_ITEM_H = 15; + private static final int CONTAINER_LIST_VISIBLE_ROWS = 2; + private static final int CRAFT_LIST_ROWS = 4; + private static final int CRAFT_LIST_H = CATALOG_ITEM_H * CRAFT_LIST_ROWS; + private static final int SCROLLBAR_W = 5; + private static final int WAIT_CHAT_ROW_H = 34; + private static final int WAIT_CHAT_VISIBLE_ROWS = 4; + private static final int CAPTURE_CHAT_VISIBLE_ROWS = 3; + private static final int CAPTURE_CHAT_HISTORY_LIMIT = 6; + private static final int CAPTURE_SCOREBOARD_VISIBLE_ROWS = 5; + private static final int CAPTURE_SCOREBOARD_ROW_H = 22; + private static final int CAPTURE_TABLIST_VISIBLE_ROWS = 5; + private static final int CAPTURE_TABLIST_ROW_H = 14; + private static final long CAPTURE_TABLIST_SCAN_TTL_MS = 500L; + private static final int WAIT_CHAT_PATTERN_H = 40; + private static final double WAIT_ENTITY_NEARBY_LIST_RADIUS = 16.0; + private static final int EDITOR_HINT_ROW_H = 11; + private static final int EDITOR_GHOST_MAX_CHARS = 16; + private static final int PAYLOAD_CONTENT_H = 74; + private static final int PAYLOAD_JSON_H = PAYLOAD_CONTENT_H; + private static final int PAYLOAD_TEXT_H = 30; + private static final int PAYLOAD_RAW_H = 42; + private static final int PAYLOAD_JAVA_H = 48; + private static final int PAYLOAD_FIELD_ROW_H = 18; + private static final int PAYLOAD_SCRIPT_H = 126; + private static final int PAYLOAD_VIEW_H = 138; + private static final Gson PAYLOAD_TEXT_GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); + private static final int CAPTURE_TOAST_SUCCESS = 0xFF66E08A; + private static final int CAPTURE_TOAST_ERROR = 0xFFFF6B6B; + private static final int MACRO_SELECT_VISIBLE_ROWS = 5; + + private static List ALL_BLOCK_IDS; + private static List ALL_SOUND_IDS; + private static List ALL_ENTITY_IDS; + private static List ALL_ITEM_IDS; + + private final Font textRenderer; + private final CompactTheme theme = new CompactTheme(); + private final AutismPacketSelectorOverlay packetSelectorOverlay; + private final RaceStepSelectorOverlay raceStepSelectorOverlay; + + private int panelX = 320, panelY = 60; + private int panelW = DEFAULT_W, panelH = MIN_H; + private boolean visible = false; + private boolean dragging = false; + private double dragOffX, dragOffY; + private boolean restoreVisibleAfterCapture = false; + private boolean worldCaptureAllowed = true; + private boolean configurationOnly = false; + private Screen screenBeforeGBreak; + private Screen screenBeforeCapture; + private boolean autoOpenedInventoryForCapture = false; + private boolean entitySpecificCaptureMode = false; + private boolean suppressCaptureValueAutoPattern = false; + + private MacroAction targetAction; + private int multiEditCount = 1; + private CompoundTag workingTag; + private ActionFieldSchema schema; + private Runnable onSaveCallback; + + private final Map textFields = new LinkedHashMap<>(); + + private final Map toggleStates = new LinkedHashMap<>(); + + private final Map enumIndices = new LinkedHashMap<>(); + + private final Map> stringLists = new LinkedHashMap<>(); + + private final Map editorItemFields = new HashMap<>(); + private final Map> editorItemLists = new HashMap<>(); + + private final Map addFields = new LinkedHashMap<>(); + + private final Map catalogScrollViewports = new HashMap<>(); + + private final Map stringListEditIndex = new HashMap<>(); + + private final Map stringListEditPendingText = new HashMap<>(); + + private final Map> stringListFilteredIndices = new HashMap<>(); + + private final Map> catalogFilteredValues = new HashMap<>(); + + private final Map selectedScrollViewports = new HashMap<>(); + + private final List waitChatFilteredHistory = new ArrayList<>(); + + private final List cachedMacroNames = new ArrayList<>(); + private final List macroNamesWithCurrent = new ArrayList<>(); + private long cachedMacroNamesRevision = -1L; + + private int scrollOffset = 0; + + private autismclient.util.macro.ItemAction itemAction; + + private final MacroCaptureSession captureSession = new MacroCaptureSession(); + private String packetClickCapturePendingKey; + + private final java.util.List enumDropdowns = new ArrayList<>(); + private final java.util.Map enumDropdownCache = new HashMap<>(); + private final List variableTokens = new ArrayList<>(); + private AutismMacro variableMacro; + private int variableActionIndex = -1; + private static final List RACE_CONDITION_CHOICES = List.of( + "Timing / DELAY", + "GUI / WAIT_GUI", + "Chat / WAIT_CHAT", + "Packets / WAIT_PACKET", + "Packets / WAIT_PACKET_MATCH", + "Inventory / WAIT_SLOT_CHANGE", + "Inventory / WAIT_INVENTORY_PREDICATE", + "Inventory / WAIT_DURABILITY", + "Inventory / WAIT_FREE_SLOTS", + "Player / WAIT_HEALTH", + "Player / WAIT_GAMEMODE_CHANGE", + "World / WAIT_BLOCK", + "World / WAIT_ENTITY", + "World / WAIT_MOVEMENT", + "World / WAIT_SOUND", + "State / WAIT_COOLDOWN", + "Sync / WAIT_LAN_STEP", + "Sync / WAIT_MACRO_STEP", + "Sync / TICK_SYNC", + "Sync / REVISION_SYNC", + "Sync / SERVER_TICK_SYNC" + ); + private static final List RACE_ACTION_CHOICES = List.of( + "Inventory / PACKET_CLICK", + "Inventory / ITEM", + "Inventory / CLICK", + "Inventory / CLOSE_GUI", + "Inventory / INVENTORY", + "Inventory / SELECT_SLOT", + "Inventory / SWAP_SLOTS", + "Inventory / DROP", + "Inventory / XCARRY", + "Inventory / CONTAINER_CLICK_SEQUENCE", + "Packets / SEND_PACKET", + "Packets / PACKET_GATE", + "Packets / PACKET_BURST", + "Packets / PAYLOAD", + "Chat / SEND_CHAT", + "Chat / SEND_COMMAND_PACKET", + "Items / USE_ITEM", + "Items / USE_ITEM_PHASE", + "Items / NBT_BOOK", + "World / MINE", + "World / INSTA_BREAK", + "World / BREAK", + "Movement / VCLIP", + "Movement / HCLIP", + "Movement / SNEAK", + "Movement / JUMP", + "Movement / SPRINT", + "Macro / MACRO_VARIABLES", + "Macro / CAPTURE_VALUE", + "Macro / FAKE_GAMEMODE", + "Macro / ASSERT", + "Macro / TOGGLE_MODULE", + "Macro / START_MACRO", + "Macro / STOP_MACRO", + "Misc / PAY", + "Misc / SIGN_EDIT", + "Misc / RESTORE_GUI", + "Misc / SAVE_GUI", + "Misc / DESYNC" + ); + + private List captureHiddenOverlays; + private final ToastStack captureToasts = new ToastStack(700L, 140.0f, 180.0f, 4, 4, 18); + + private List craftEntries; + private List craftAllRecipes; + private List craftFilteredRecipes; + private AutismCraftingHelper.CraftableRecipeOption craftSelectedRecipe; + private int craftRecipeScrollOffset; + private boolean craftUseMax; + private String craftLastQuery; + private int[] craftRecipeListBounds; + + private autismclient.util.macro.DropAction dropAction; + + private PayloadAction payloadAction; + private AutismPayloadEditorModel payloadEditorModel; + private boolean standalonePayloadEditor = false; + private PayloadContentMode payloadContentMode = PayloadContentMode.BINARY_REPLAY; + private int payloadFieldCount = 0; + private int payloadTabIndex = 0; + private boolean payloadContentEdited = false; + private boolean payloadRawEdited = false; + private boolean payloadChannelEdited = false; + private boolean payloadJsonEdited = false; + private boolean payloadModeManuallyChanged = false; + private boolean payloadAddTypeManuallyChanged = false; + private boolean suppressPayloadEditorChange = false; + private int itemEditIndex = -1; + private int dropEditIndex = -1; + private int wscEditIndex = -1; + + private List wscEntries; + + private WaitForSlotChangeAction.WaitMode wscAddMode = WaitForSlotChangeAction.WaitMode.NOT_EMPTY; + private int wscAddCount = 1; + private boolean suppressItemEntryLiveUpdate = false; + private boolean suppressDropEntryLiveUpdate = false; + private boolean suppressWscLiveUpdate = false; + private boolean suppressDropCountEditorUpdate = false; + private boolean waitChatFuzzySliderDragging = false; + private int waitChatFuzzySliderX = -1; + private int waitChatFuzzySliderY = -1; + private int waitChatFuzzySliderW = 0; + private int waitChatFuzzySliderH = 0; + private boolean rotateSmoothnessSliderDragging = false; + private int rotateSmoothnessSliderX = -1; + private int rotateSmoothnessSliderY = -1; + private int rotateSmoothnessSliderW = 0; + private int rotateSmoothnessSliderH = 0; + private boolean xcarrySafeDelaySliderDragging = false; + private int xcarrySafeDelaySliderX = -1; + private int xcarrySafeDelaySliderY = -1; + private int xcarrySafeDelaySliderW = 0; + private int xcarrySafeDelaySliderH = 0; + private boolean suppressWaitChatPatternSync = false; + + private enum PayloadContentMode { + UTF8_TEXT, + BRAND_STRING, + COMMAND_INT, + BINARY_REPLAY + } + + private static final List PAYLOAD_FIELD_TYPES = List.of( + AutismPayloadTemplate.FieldType.BYTE, + AutismPayloadTemplate.FieldType.UNSIGNED_BYTE, + AutismPayloadTemplate.FieldType.BOOLEAN, + AutismPayloadTemplate.FieldType.SHORT, + AutismPayloadTemplate.FieldType.UNSIGNED_SHORT, + AutismPayloadTemplate.FieldType.CHAR, + AutismPayloadTemplate.FieldType.INT, + AutismPayloadTemplate.FieldType.LONG, + AutismPayloadTemplate.FieldType.FLOAT, + AutismPayloadTemplate.FieldType.DOUBLE, + AutismPayloadTemplate.FieldType.JAVA_WRITE_UTF, + AutismPayloadTemplate.FieldType.RAW_BYTES, + AutismPayloadTemplate.FieldType.BYTE_ARRAY, + AutismPayloadTemplate.FieldType.STRING_BYTES, + AutismPayloadTemplate.FieldType.VAR_INT, + AutismPayloadTemplate.FieldType.VAR_LONG, + AutismPayloadTemplate.FieldType.MINECRAFT_STRING, + AutismPayloadTemplate.FieldType.IDENTIFIER, + AutismPayloadTemplate.FieldType.UUID_FIELD, + AutismPayloadTemplate.FieldType.BLOCK_POS, + AutismPayloadTemplate.FieldType.ENUM_VAR_INT, + AutismPayloadTemplate.FieldType.OPTIONAL_VALUE, + AutismPayloadTemplate.FieldType.NBT, + AutismPayloadTemplate.FieldType.ITEM_STACK, + AutismPayloadTemplate.FieldType.TEXT_COMPONENT + ); + + private static final List PAYLOAD_FIELD_TYPE_LABELS = payloadFieldTypeLabels(); + private static final List PAYLOAD_MODE_LABELS = List.of( + "Raw UTF-8", + "Hex", + "DataOutput", + "ByteBuf", + "JSON", + "Mixed" + ); + private static final List PAYLOAD_MODES = List.of( + AutismPayloadTemplate.EncodingMode.RAW_UTF8, + AutismPayloadTemplate.EncodingMode.MANUAL_HEX, + AutismPayloadTemplate.EncodingMode.JAVA_DATA_OUTPUT, + AutismPayloadTemplate.EncodingMode.MINECRAFT_BYTEBUF, + AutismPayloadTemplate.EncodingMode.JSON_TEXT, + AutismPayloadTemplate.EncodingMode.ADVANCED_MIXED + ); + + private static List payloadFieldTypeLabels() { + List labels = new ArrayList<>(); + for (AutismPayloadTemplate.FieldType type : PAYLOAD_FIELD_TYPES) labels.add(type.label()); + return List.copyOf(labels); + } + + private List lanStepEntries; + private List waitPacketMatchRules; + private int waitPacketMatchEditIndex = -1; + private final List payScannedPlayers = new ArrayList<>(); + private final Map payPlayerPrefixes = new HashMap<>(); + + private final Map payPrefixComponents = new HashMap<>(); + private boolean payPlayerScanPerformed = false; + private final List autismModuleNames = new ArrayList<>(); + private final List meteorModuleNames = new ArrayList<>(); + private List toggleModuleEntries; + + private Runnable onPreSave; + + private final List hitRegions = new ArrayList<>(); + private UiBounds bodyInputClip; + private float frameDelta = 0.0f; + + @FunctionalInterface + private interface HitRegionAction { + boolean fire(double mx, double my, int mouseButton); + } + + private static final class HitRegion { + private final int x; + private final int y; + private final int w; + private final int h; + private final HitRegionAction action; + + private HitRegion(int x, int y, int w, int h, Runnable action) { + this(x, y, w, h, (mx, my, mouseButton) -> { + if (mouseButton != 0) return false; + action.run(); + return true; + }); + } + + private HitRegion(CompactOverlayButton button, Runnable action) { + this(button.getX(), button.getY(), button.getWidth(), button.getHeight(), + (mx, my, mouseButton) -> CompactOverlayButton.fireIfHit(button, mx, my, mouseButton)); + } + + private HitRegion(int x, int y, int w, int h, HitRegionAction action) { + this.x = x; + this.y = y; + this.w = w; + this.h = h; + this.action = action; + } + + boolean contains(int mx, int my) { + return mx >= x && mx < x + w && my >= y && my < y + h; + } + + boolean fire(double mx, double my, int mouseButton) { + return action != null && action.fire(mx, my, mouseButton); + } + } + + private record CaptureListAddResult(boolean added, String message, int accentColor) { + } + + private record ScrollDragRegion(int x, int y, int w, int h, java.util.function.IntConsumer handler) { + boolean contains(int mx, int my) { return mx >= x && mx < x+w && my >= y && my < y+h; } + } + private final List scrollDragRegions = new ArrayList<>(); + + private java.util.function.IntConsumer activeScrollDragHandler = null; + + private static ActionEditorOverlay sharedInstance; + + public static ActionEditorOverlay getSharedOverlay() { + if (sharedInstance == null) { + sharedInstance = new ActionEditorOverlay(MC.font); + AutismOverlayManager.get().register(sharedInstance); + } + return sharedInstance; + } + + private static boolean isCompactEditorType(MacroActionType type) { + if (type == null) return false; + return switch (type) { + case INVENTORY, RESTORE_GUI, SAVE_GUI, SEND_TOGGLE, DESYNC -> true; + default -> false; + }; + } + + private int preferredPanelWidthFor(MacroAction action) { + return isCompactEditorType(action == null ? null : action.getType()) ? COMPACT_W : DEFAULT_W; + } + + private int currentMinPanelHeight() { + return isCompactEditorType(targetAction == null ? null : targetAction.getType()) ? COMPACT_MIN_H : MIN_H; + } + + public static boolean supportsActionEditor(MacroAction action) { + if (action == null) return false; + + if (action instanceof autismclient.util.macro.MissingAddonAction) return false; + MacroActionType type = action.getType(); + if (type == null) { + + return !ActionFieldRegistry.get(action).fields().isEmpty(); + } + return switch (type) { + case CRAFT, DROP, ITEM, PAYLOAD, WAIT_LAN_STEP, WAIT_PACKET, WAIT_PACKET_MATCH, WAIT_SLOT_CHANGE -> true; + default -> !ActionFieldRegistry.get(type).fields().isEmpty(); + }; + } + + public static ActionEditorOverlay getSharedOverlayIfExists() { + return sharedInstance; + } + + public boolean isEditingAction(MacroAction action) { + return visible && !standalonePayloadEditor && targetAction == action; + } + + public void setWorldCaptureAllowed(boolean allowed) { + this.worldCaptureAllowed = allowed; + if (!allowed) cancelCaptureIfActive(); + } + + public void setConfigurationOnly(boolean configurationOnly) { + this.configurationOnly = configurationOnly; + if (configurationOnly) setWorldCaptureAllowed(false); + } + + private boolean guardWorldCaptureAction() { + if (worldCaptureAllowed) return true; + AutismNotifications.warning("Pick/Capture only works in-game."); + return false; + } + + private boolean captureControlAvailable(CaptureMode mode) { + + if (mode == CaptureMode.CUSTOM_MENU_BUTTON) return true; + return mode == CaptureMode.PACKET_NAME || worldCaptureAllowed; + } + + public void closeIfEditingAny(java.util.List actions) { + if (!visible || standalonePayloadEditor || targetAction == null || actions == null) return; + if (!actions.contains(targetAction)) closeEditor(false); + } + + public void closeIfEditingAction(MacroAction action) { + if (isEditingAction(action)) closeEditor(false); + } + + public ActionEditorOverlay(Font textRenderer) { + this.textRenderer = textRenderer; + this.packetSelectorOverlay = new AutismPacketSelectorOverlay(textRenderer); + this.raceStepSelectorOverlay = new RaceStepSelectorOverlay(textRenderer); + } + + public void setMacroContext(AutismMacro macro, int actionIndex) { + variableMacro = macro; + variableActionIndex = actionIndex; + rebuildVariableTokens(); + } + + public void open(MacroAction action, Runnable onPreSave, Runnable onSave) { + open(action, onPreSave, onSave, 1); + } + + public void open(MacroAction action, Runnable onPreSave, Runnable onSave, int editCount) { + this.standalonePayloadEditor = false; + this.targetAction = action; + this.multiEditCount = Math.max(1, editCount); + this.onPreSave = onPreSave; + this.onSaveCallback = onSave; + this.workingTag = AutismMacro.serializeAction(action); + this.schema = ActionFieldRegistry.get(action); + this.scrollOffset = 0; + rebuildVariableTokens(); + + textFields.clear(); + toggleStates.clear(); + enumIndices.clear(); + stringLists.clear(); + editorItemFields.clear(); + editorItemLists.clear(); + addFields.clear(); + catalogScrollViewports.clear(); + stringListEditIndex.clear(); + stringListEditPendingText.clear(); + stringListFilteredIndices.clear(); + catalogFilteredValues.clear(); + selectedScrollViewports.clear(); + packetSelectorOverlay.close(); + prepareWorkingTagForEditor(action); + + for (FieldDef field : schema.fields()) { + String key = field.key(); + switch (field.type()) { + + case TOGGLE -> + toggleStates.put(key, workingTag.contains(key) + ? workingTag.getBooleanOr(key, false) : false); + + case NUMBER -> { + int v = workingTag.contains(key) ? workingTag.getIntOr(key, 0) : 0; + AutismChatField f = makeField(80); + if (!field.dynamic()) f.setNumericOnly(true); + String binding = autismclient.util.macro.MacroDynamicBindings.get(action, key); + f.setText(binding.isBlank() ? String.valueOf(v) : binding); + textFields.put(key, f); + } + + case DECIMAL -> { + double v = workingTag.contains(key) ? workingTag.getDoubleOr(key, 0.0) : 0.0; + AutismChatField f = makeField(80); + if (!field.dynamic()) f.setFilter(s -> s.isEmpty() || s.equals("-") || s.matches("-?\\d*\\.?\\d*")); + String binding = autismclient.util.macro.MacroDynamicBindings.get(action, key); + f.setText(binding.isBlank() ? fmtDouble(v) : binding); + textFields.put(key, f); + } + + case TEXT, MACRO_SELECT -> { + String v = workingTag.contains(key) ? workingTag.getStringOr(key, "") : ""; + AutismChatField f = makeField(80); + f.setText(v); + textFields.put(key, f); + } + + case ENUM -> { + String v = workingTag.contains(key) ? workingTag.getStringOr(key, "") : ""; + List opts = field.enumOptions(); + int idx = opts.indexOf(v); + if (idx < 0) idx = opts.indexOf(v.toUpperCase()); + enumIndices.put(key, Math.max(0, idx)); + if (field.dynamic()) { + AutismChatField bindingField = makeField(80); + bindingField.setText(autismclient.util.macro.MacroDynamicBindings.get(action, key)); + textFields.put(key, bindingField); + } + } + + case SLOT -> { + int v = workingTag.contains(key) ? workingTag.getIntOr(key, 0) : 0; + AutismChatField f = makeField(50); + if (!field.dynamic()) f.setFilter(s -> s.isEmpty() || s.equals("-") || s.matches("-?\\d*")); + String binding = autismclient.util.macro.MacroDynamicBindings.get(action, key); + f.setText(binding.isBlank() ? String.valueOf(v) : binding); + textFields.put(key, f); + } + + case BLOCK_POS -> { + String[] xyzKeys = field.xyzKeys(); + boolean dbl = field.xyzDouble(); + for (int i = 0; i < 3; i++) { + AutismChatField f = makeField(50); + if (dbl) { + if (!field.dynamic()) f.setFilter(s -> s.isEmpty() || s.equals("-") || s.matches("-?\\d*\\.?\\d*")); + double v = workingTag.contains(xyzKeys[i]) ? workingTag.getDoubleOr(xyzKeys[i], 0.0) : 0.0; + String binding = autismclient.util.macro.MacroDynamicBindings.get(action, xyzKeys[i]); + f.setText(binding.isBlank() ? fmtDouble(v) : binding); + } else { + if (!field.dynamic()) f.setNumericOnly(true); + int v = workingTag.contains(xyzKeys[i]) ? workingTag.getIntOr(xyzKeys[i], 0) : 0; + String binding = autismclient.util.macro.MacroDynamicBindings.get(action, xyzKeys[i]); + f.setText(binding.isBlank() ? String.valueOf(v) : binding); + } + textFields.put(key + "_" + i, f); + } + } + + case STRING_LIST -> { + List list = new ArrayList<>(); + if (workingTag.contains(key)) { + ListTag nl = workingTag.getList(key).orElse(new ListTag()); + for (Tag el : nl) { + String s = el.asString().orElse(""); + if (!s.isEmpty()) list.add(s); + } + } + stringLists.put(key, list); + + AutismChatField af = makeField(80); + if (field.captureMode() == CaptureMode.BLOCK_CATALOG) { + af.setPlaceholder(Component.literal("Search blocks...")); + } else { + af.setPlaceholder(Component.literal("Search / " + field.addLabel())); + af.setSubmitHandler(text -> { + if (!text.isBlank()) { + List entries = stringLists.get(key); + if (entries != null && addStringListEntry(field, entries, text.strip())) { + af.setText(""); + } + } + return true; + }); + } + addFields.put(key, af); + } + } + } + + if (action instanceof autismclient.util.macro.UseItemAction useItemAction) { + AutismChatField slotField = textFields.get("slot"); + if (slotField != null && useItemAction.slot < 0 && !workingTag.contains("slot")) { + slotField.setText(""); + } + } + + itemAction = null; + captureSession.clearItemSlotCapture(); + itemEditIndex = -1; + dropEditIndex = -1; + if (action instanceof autismclient.util.macro.ItemAction ia) { + itemAction = new autismclient.util.macro.ItemAction(); + itemAction.itemNames = new ArrayList<>(ia.itemNames); + itemAction.itemTargets = copyEditorTargets(ia.itemTargets, ia.itemNames); + itemAction.itemTimes = new ArrayList<>(ia.itemTimes); + itemAction.itemActionIdx = new ArrayList<>(ia.itemActionIdx); + itemAction.itemButtons = new ArrayList<>(ia.itemButtons); + itemAction.itemSearchScopes = new ArrayList<>(ia.itemSearchScopes); + itemAction.stackAmountModes = new ArrayList<>(ia.stackAmountModes); + while (itemAction.itemTimes.size() < itemAction.itemNames.size()) itemAction.itemTimes.add(1); + while (itemAction.itemActionIdx.size() < itemAction.itemNames.size()) itemAction.itemActionIdx.add(0); + while (itemAction.itemButtons.size() < itemAction.itemNames.size()) itemAction.itemButtons.add(0); + while (itemAction.itemSearchScopes.size() < itemAction.itemNames.size()) { + int index = itemAction.itemSearchScopes.size(); + itemAction.itemSearchScopes.add(ia.getItemSearchScope(index).ordinal()); + } + while (itemAction.stackAmountModes.size() < itemAction.itemNames.size()) itemAction.stackAmountModes.add(0); + itemAction.targetSlot = ia.targetSlot; + itemAction.useSlot = ia.useSlot; + itemAction.actionIndex = ia.actionIndex; + itemAction.button = ia.button; + itemAction.times = ia.times; + itemAction.waitForGuiBefore = ia.waitForGuiBefore; + itemAction.waitForGuiAfter = ia.waitForGuiAfter; + itemAction.guiName = ia.guiName != null ? ia.guiName : ""; + itemAction.waitForItem = ia.waitForItem; + itemAction.useCursorItemForPickupAll = ia.useCursorItemForPickupAll; + + for (int i = 0; i < itemAction.itemNames.size(); i++) { + AutismChatField f = makeField(28); + f.setNumericOnly(true); + f.setText(String.valueOf(itemAction.getItemTime(i))); + textFields.put("item_times_" + i, f); + } + + AutismChatField addF = makeField(120); + addF.setPlaceholder(Component.literal("Item name")); + addF.setChangedListener(text -> handleItemEntryEditorChanged()); + addFields.put("_item_add", addF); + AutismChatField addSlotF = makeField(52); + addSlotF.setNumericOnly(true); + addSlotF.setPlaceholder(Component.literal("Slot")); + addSlotF.setChangedListener(text -> handleItemEntryEditorChanged()); + textFields.put("item_entrySlot", addSlotF); + + toggleStates.put("item_waitForGuiBefore", ia.waitForGuiBefore); + toggleStates.put("item_waitForGuiAfter", ia.waitForGuiAfter); + toggleStates.put("item_waitForItem", ia.waitForItem); + toggleStates.put("item_useCursorItemForPickupAll", ia.useCursorItemForPickupAll); + toggleStates.put("item_useClickDelay", ia.useClickDelay); + AutismChatField guiF = makeField(80); + guiF.setText(ia.guiName != null ? ia.guiName : ""); + textFields.put("item_guiName", guiF); + AutismChatField delayF = makeField(60); + delayF.setNumericOnly(true); + delayF.setText(String.valueOf(Math.max(0, ia.clickDelayMs))); + textFields.put("item_clickDelayMs", delayF); + + } + + wscEditIndex = -1; + wscEntries = new ArrayList<>(); + wscAddMode = WaitForSlotChangeAction.WaitMode.NOT_EMPTY; + wscAddCount = 1; + if (action instanceof WaitForSlotChangeAction wsc) { + for (WaitForSlotChangeAction.WaitEntry e : wsc.entries) wscEntries.add(e.copy()); + } + if (action.getType() == MacroActionType.WAIT_SLOT_CHANGE) { + toggleStates.put(MacroAction.LISTEN_DURING_PREVIOUS_KEY, + action.listensDuringPreviousAction()); + AutismChatField wscAddF = makeField(120); + wscAddF.setPlaceholder(Component.literal("Item name (optional)")); + wscAddF.setChangedListener(text -> handleWscEntryEditorChanged()); + addFields.put("_wsc_add", wscAddF); + AutismChatField wscSlotF = makeField(52); + wscSlotF.setNumericOnly(true); + wscSlotF.setPlaceholder(Component.literal("Slot #")); + wscSlotF.setChangedListener(text -> handleWscEntryEditorChanged()); + textFields.put("wsc_slot", wscSlotF); + AutismChatField wscCountF = makeField(36); + wscCountF.setNumericOnly(true); + wscCountF.setPlaceholder(Component.literal("Count")); + wscCountF.setChangedListener(text -> handleWscCountChanged()); + textFields.put("wsc_count", wscCountF); + } + + craftEntries = null; + craftAllRecipes = null; + craftFilteredRecipes = null; + craftSelectedRecipe = null; + craftRecipeScrollOffset = 0; + craftUseMax = false; + craftLastQuery = null; + craftRecipeListBounds = null; + if (action instanceof CraftAction craftAction) { + craftEntries = craftAction.copyEntries(); + for (int i = 0; i < craftEntries.size(); i++) { + CraftAction.CraftEntry entry = craftEntries.get(i); + AutismChatField f = makeField(44); + f.setNumericOnly(true); + f.setText(String.valueOf(entry.amount)); + textFields.put("craft_amount_" + i, f); + toggleStates.put("craft_useMax_" + i, entry.useMaxAmount); + } + + AutismChatField amtF = makeField(44); + amtF.setNumericOnly(true); + amtF.setText("1"); + textFields.put("_craft_amount", amtF); + + AutismChatField srchF = makeField(180); + srchF.setPlaceholder(Component.literal("Search recipes...")); + addFields.put("_craft_search", srchF); + + craftAllRecipes = AutismCraftingHelper.getCraftableRecipes(MC); + craftFilteredRecipes = AutismCraftingHelper.filterRecipes(craftAllRecipes, ""); + } + + if (action instanceof WaitForPacketAction waitForPacketAction) { + stringLists.put("packetNames", sanitizeWaitPacketTargets(waitForPacketAction.effectiveList())); + toggleStates.put(MacroAction.LISTEN_DURING_PREVIOUS_KEY, waitForPacketAction.listenDuringPreviousAction); + } + + waitPacketMatchRules = null; + waitPacketMatchEditIndex = -1; + if (action instanceof WaitPacketMatchAction packetMatchAction) { + waitPacketMatchRules = new ArrayList<>(); + for (WaitPacketMatchAction.Rule rule : packetMatchAction.effectiveRules()) { + waitPacketMatchRules.add(rule.copy()); + } + if (waitPacketMatchRules.isEmpty()) waitPacketMatchRules.add(new WaitPacketMatchAction.Rule()); + waitPacketMatchEditIndex = 0; + toggleStates.put(MacroAction.LISTEN_DURING_PREVIOUS_KEY, packetMatchAction.listenDuringPreviousAction); + AutismChatField valueField = makeField(120); + valueField.setPlaceholder(Component.literal("Value")); + textFields.put("_wpm_value", valueField); + syncWaitPacketMatchValueField(); + } + + dropAction = null; + if (action instanceof autismclient.util.macro.DropAction da) { + dropAction = new autismclient.util.macro.DropAction(); + dropAction.mode = da.mode; + dropAction.dropCount = da.dropCount; + dropAction.itemNames = new ArrayList<>(da.itemNames); + dropAction.itemTargets = copyEditorTargets(da.itemTargets, da.itemNames); + dropAction.itemCounts = new ArrayList<>(da.itemCounts); + dropAction.waitForGuiBefore = da.waitForGuiBefore; + dropAction.waitForGuiAfter = da.waitForGuiAfter; + dropAction.guiName = da.guiName != null ? da.guiName : ""; + dropAction.useHandlerSlots = da.useHandlerSlots; + while (dropAction.itemCounts.size() < dropAction.itemNames.size()) dropAction.itemCounts.add(1); + + for (int i = 0; i < dropAction.itemNames.size(); i++) { + AutismChatField f = makeField(32); + f.setNumericOnly(true); + f.setText(String.valueOf(dropAction.itemCounts.get(i))); + textFields.put("drop_count_" + i, f); + } + + AutismChatField cntF = makeField(60); + cntF.setNumericOnly(true); + cntF.setText(String.valueOf(da.dropCount)); + cntF.setChangedListener(text -> handleDropCountEditorChanged()); + textFields.put("drop_globalCount", cntF); + AutismChatField addDropF = makeField(120); + addDropF.setPlaceholder(Component.literal("Item name...")); + addDropF.setChangedListener(text -> handleDropEntryEditorChanged()); + addFields.put("_drop_add", addDropF); + AutismChatField addDropSlotF = makeField(52); + addDropSlotF.setNumericOnly(true); + addDropSlotF.setPlaceholder(Component.literal("Slot")); + addDropSlotF.setChangedListener(text -> handleDropEntryEditorChanged()); + textFields.put("drop_entrySlot", addDropSlotF); + AutismChatField dropGuiF = makeField(80); + dropGuiF.setText(da.guiName != null ? da.guiName : ""); + textFields.put("drop_guiName", dropGuiF); + + toggleStates.put("drop_waitForGuiBefore", da.waitForGuiBefore); + toggleStates.put("drop_waitForGuiAfter", da.waitForGuiAfter); + toggleStates.put("drop_useHandlerSlots", da.useHandlerSlots); + autismclient.util.macro.DropAction.DropMode[] modes = + autismclient.util.macro.DropAction.DropMode.values(); + int mi = 0; + for (int i = 0; i < modes.length; i++) if (modes[i] == da.mode) { mi = i; break; } + enumIndices.put("drop_mode", mi); + syncDropCountEditorField(); + } + + payloadAction = null; + payloadEditorModel = null; + if (action instanceof PayloadAction pa) { + payloadAction = new PayloadAction(); + payloadAction.fromTag(pa.toTag()); + initializePayloadEditorFields(payloadAction); + } + + lanStepEntries = null; + if (action instanceof autismclient.util.macro.WaitForLanStepAction wls) { + lanStepEntries = new ArrayList<>(); + for (autismclient.util.macro.WaitForLanStepAction.LanStepEntry e : wls.entries) + lanStepEntries.add(new autismclient.util.macro.WaitForLanStepAction.LanStepEntry(e.username, e.step)); + + for (int i = 0; i < lanStepEntries.size(); i++) { + autismclient.util.macro.WaitForLanStepAction.LanStepEntry e = lanStepEntries.get(i); + AutismChatField uf = makeField(80); uf.setText(e.username); + textFields.put("lan_user_" + i, uf); + AutismChatField sf = makeField(40); sf.setNumericOnly(true); + sf.setText(String.valueOf(e.step)); + textFields.put("lan_step_" + i, sf); + } + AutismChatField newUF = makeField(80); + newUF.setPlaceholder(Component.literal("Peer name...")); + addFields.put("_lan_user_add", newUF); + AutismChatField newSF = makeField(40); + newSF.setNumericOnly(true); + newSF.setText("1"); + addFields.put("_lan_step_add", newSF); + AutismChatField dsF = makeField(60); + dsF.setNumericOnly(true); + dsF.setText(String.valueOf(wls.defaultStep)); + textFields.put("lan_defaultStep", dsF); + toggleStates.put("lan_filterByUser", wls.filterByUser); + toggleStates.put(MacroAction.LISTEN_DURING_PREVIOUS_KEY, wls.listenDuringPreviousAction); + + } + + entitySpecificCaptureMode = false; + if (action instanceof autismclient.util.macro.WaitForSoundAction) { + AutismChatField search = addFields.get("soundIds"); + if (search != null) search.setPlaceholder(Component.literal("Search sound id...")); + } + if (action instanceof autismclient.util.macro.WaitForEntityAction) { + AutismChatField search = addFields.get("entityIds"); + if (search != null) search.setPlaceholder(Component.literal("Search entity type...")); + } + if (action instanceof autismclient.util.macro.LookAtBlockAction) { + AutismChatField search = addFields.get("entityIds"); + if (search != null) search.setPlaceholder(Component.literal("Search entity type...")); + } + if (action instanceof autismclient.util.macro.StoreItemAction) { + AutismChatField search = addFields.get("targetItems"); + if (search != null) search.setPlaceholder(Component.literal("Search item id...")); + } + if (action instanceof autismclient.util.macro.InventoryAuditAction) { + AutismChatField search = addFields.get("targetItems"); + if (search != null) search.setPlaceholder(Component.literal("Item name")); + } + payScannedPlayers.clear(); + payPlayerPrefixes.clear(); + payPrefixComponents.clear(); + payPlayerScanPerformed = false; + if (action instanceof autismclient.util.macro.PayAction) { + AutismChatField search = addFields.get("players"); + if (search != null) search.setPlaceholder(Component.literal("Search or add player...")); + } + autismModuleNames.clear(); + meteorModuleNames.clear(); + toggleModuleEntries = null; + if (action instanceof autismclient.util.macro.ToggleModuleAction) { + AutismChatField search = makeField(180); + search.setPlaceholder(Component.literal("Search module...")); + addFields.put("_toggle_module_search", search); + refreshMeteorModuleNames(); + autismclient.util.macro.ToggleModuleAction toggleModuleAction = (autismclient.util.macro.ToggleModuleAction) action; + toggleModuleEntries = new ArrayList<>(); + for (autismclient.util.macro.ToggleModuleAction.ModuleEntry entry : toggleModuleAction.entries) { + if (entry != null && entry.moduleName != null && !entry.moduleName.isBlank()) { + toggleModuleEntries.add(new autismclient.util.macro.ToggleModuleAction.ModuleEntry(entry.moduleName, entry.toggleMode)); + } + } + } + if (action instanceof autismclient.util.macro.WaitForChatAction) { + AutismChatField search = makeField(180); + search.setPlaceholder(Component.literal("Search recent chat...")); + addFields.put("_wait_chat_search", search); + AutismChatField captureName = makeField(100); + captureName.setPlaceholder(Component.literal("Variable name")); + addFields.put("_capture_name", captureName); + waitChatFuzzySliderDragging = false; + clearWaitChatFuzzySliderBounds(); + AutismChatField patternField = textFields.get("pattern"); + if (patternField != null) { + patternField.setMultiline(true); + patternField.setHeight(WAIT_CHAT_PATTERN_H); + String existingPatternJson = workingTag.getStringOr("patternJson", ""); + Component initialPattern = existingPatternJson == null || existingPatternJson.isBlank() + ? Component.literal(autismclient.util.macro.MacroExecutor.normalizeManualText(workingTag.getStringOr("pattern", ""))) + : getWaitChatPatternComponent(workingTag.getStringOr("pattern", "")); + String visiblePattern = initialPattern.getString(); + workingTag.putString("pattern", visiblePattern); + if (existingPatternJson == null || existingPatternJson.isBlank()) workingTag.putString("patternJson", ""); + else workingTag.putString("patternJson", autismclient.util.macro.MacroExecutor.serializeTextComponent(initialPattern)); + patternField.setDisplayTextProvider(this::getWaitChatPatternComponent); + suppressWaitChatPatternSync = true; + patternField.setText(visiblePattern); + suppressWaitChatPatternSync = false; + patternField.setChangedListener(value -> { + if (suppressWaitChatPatternSync) return; + String visibleValue = autismclient.util.macro.MacroExecutor.normalizeManualText(value); + workingTag.putString("pattern", visibleValue); + workingTag.putString("patternJson", ""); + }); + } + } else { + suppressWaitChatPatternSync = false; + waitChatFuzzySliderDragging = false; + clearWaitChatFuzzySliderBounds(); + } + if (action instanceof autismclient.util.macro.WaitForGuiAction) { + AutismChatField captureName = makeField(100); + captureName.setPlaceholder(Component.literal("Variable name")); + addFields.put("_capture_name", captureName); + } + if (action instanceof autismclient.util.macro.CaptureValueAction) { + AutismChatField token = makeField(180); + token.setEditable(false); + token.setFocusEffectsEnabled(false); + token.setPlaceholder(Component.literal("Set a variable name")); + addFields.put("_capture_token", token); + + AutismChatField preview = makeField(180); + preview.setEditable(false); + preview.setFocusEffectsEnabled(false); + preview.setPlaceholder(Component.literal("Nothing available now")); + addFields.put("_capture_preview", preview); + + for (String key : List.of("saveAs", "exampleText", "selectedText")) { + AutismChatField field = textFields.get(key); + if (field != null) field.setChangedListener(ignored -> refreshCaptureValueAutoPattern()); + } + } else { + suppressCaptureValueAutoPattern = false; + } + + if (action instanceof autismclient.util.macro.RotateAction) { + rotateSmoothnessSliderDragging = false; + clearRotateSmoothnessSliderBounds(); + autismclient.util.macro.RotateAction rotateAction = (autismclient.util.macro.RotateAction) action; + AutismChatField smoothnessField = textFields.get("smoothness"); + int smoothness = autismclient.util.macro.RotateAction.clampSmoothness(rotateAction.smoothness); + workingTag.putInt("smoothness", smoothness); + if (smoothnessField != null) smoothnessField.setText(String.valueOf(smoothness)); + } else if (action instanceof autismclient.util.macro.LookAtBlockAction lookAtAction) { + rotateSmoothnessSliderDragging = false; + clearRotateSmoothnessSliderBounds(); + AutismChatField smoothnessField = textFields.get("smoothness"); + int smoothness = autismclient.util.macro.RotateAction.clampSmoothness(lookAtAction.smoothness); + workingTag.putInt("smoothness", smoothness); + if (smoothnessField != null) smoothnessField.setText(String.valueOf(smoothness)); + } else { + rotateSmoothnessSliderDragging = false; + clearRotateSmoothnessSliderBounds(); + } + + if (action instanceof autismclient.util.macro.XCarryAction xCarryAction) { + xcarrySafeDelaySliderDragging = false; + clearXCarrySafeDelaySliderBounds(); + AutismChatField delayField = textFields.get("safeClickDelayTicks"); + int safeDelay = autismclient.util.macro.XCarryAction.clampSafeClickDelayTicks(xCarryAction.safeClickDelayTicks); + workingTag.putInt("safeClickDelayTicks", safeDelay); + workingTag.putBoolean("safeClickDelayAfterPickup", xCarryAction.safeClickDelayAfterPickup); + workingTag.putBoolean("safeClickDelayBeforeReturn", xCarryAction.safeClickDelayBeforeReturn); + toggleStates.put("safeClickDelayAfterPickup", xCarryAction.safeClickDelayAfterPickup); + toggleStates.put("safeClickDelayBeforeReturn", xCarryAction.safeClickDelayBeforeReturn); + if (delayField != null) delayField.setText(String.valueOf(safeDelay)); + } else { + xcarrySafeDelaySliderDragging = false; + clearXCarrySafeDelaySliderBounds(); + } + + if (action.getType() == MacroActionType.INVENTORY + || action.getType() == MacroActionType.CLOSE_GUI + || action.getType() == MacroActionType.SAVE_GUI) { + toggleStates.put("sendPacket", !workingTag.getBooleanOr("sendPacket", true)); + } + if (action.getType() == MacroActionType.STORE_ITEM) { + toggleStates.put("closeSendPkt", !workingTag.getBooleanOr("closeSendPkt", true)); + } + + refreshItemTextDisplayProviders(); + applyEditorPlaceholders(); + + if (action.getType() == MacroActionType.PLACE) { + AutismChatField slotF = makeField(52); + slotF.setNumericOnly(true); + slotF.setPlaceholder(Component.literal("Slot")); + slotF.setChangedListener(text -> syncPlaceItemEditorFields()); + textFields.put("place_itemSlot", slotF); + + if (action instanceof autismclient.util.macro.PlaceAction placeAction) { + toggleStates.put("place_waitForItem", placeAction.waitForItem); + toggleStates.put("place_silentSwitch", placeAction.silentSwitch); + } + + ItemTarget placeTarget = editorItemFields.get("itemName"); + if (placeTarget == null && action instanceof autismclient.util.macro.PlaceAction placeAction) { + placeTarget = resolveEditorTarget(placeAction.itemTarget, placeAction.itemName); + } + if (placeTarget != null) { + slotF.setText(placeTarget.hasSlot() ? String.valueOf(placeTarget.slot) : ""); + } + + AutismChatField nameF = textFields.get("itemName"); + if (nameF != null) { + nameF.setChangedListener(text -> syncPlaceItemEditorFields()); + } + + if (action instanceof autismclient.util.macro.PlaceAction placeAction) { + if (placeAction.blockPos != null) { + AutismInstaBreakRenderer.setTarget(placeAction.blockPos, 0xFFFF3B3B); + } + } + } + + panelW = preferredPanelWidthFor(action); + int contentH = computeContentH(); + int desiredH = HEADER_HEIGHT + PAD + contentH + FOOTER_H + PAD; + int minH = currentMinPanelHeight(); + int maxH = Math.max(minH, AutismUiScale.getVirtualScreenHeight() * 4 / 5); + panelH = Math.max(minH, Math.min(maxH, desiredH)); + + this.visible = true; + AutismOverlayManager.get().bringToFront(this); + } + + public void openStandalonePayloadEditor(PayloadAction action) { + open(action, null, null); + this.standalonePayloadEditor = true; + } + + public boolean updateOpenPayloadChannel(String channel) { + String target = channel == null ? "" : channel.trim(); + if (!visible || target.isBlank()) return false; + if (!(standalonePayloadEditor || payloadAction != null || targetAction instanceof PayloadAction)) return false; + AutismChatField channelField = textFields.get("payload_channel"); + if (channelField == null) return false; + + suppressPayloadEditorChange = true; + try { + channelField.setText(target); + if (payloadEditorModel != null) payloadEditorModel.channel = target; + if (payloadAction != null) payloadAction.channel = target; + if (targetAction instanceof PayloadAction targetPayload) targetPayload.channel = target; + AutismChatField contentField = textFields.get("payload_content"); + if (contentField != null) { + contentField.setText(replacePayloadScriptChannelLine(contentField.getText(), target)); + } + payloadChannelEdited = true; + } finally { + suppressPayloadEditorChange = false; + } + refreshInteractiveLayout(); + AutismOverlayManager.get().bringToFront(this); + return true; + } + + private String replacePayloadScriptChannelLine(String script, String channel) { + String safeScript = script == null ? "" : script.replace("\r\n", "\n").replace('\r', '\n'); + String safeChannel = channel == null || channel.isBlank() ? "minecraft:brand" : channel.trim(); + String[] lines = safeScript.split("\n", -1); + for (int i = 0; i < lines.length; i++) { + String raw = lines[i] == null ? "" : lines[i]; + String stripped = raw.stripLeading(); + if (stripped.startsWith("#")) continue; + int split = firstPayloadDelimiter(raw); + if (split < 0) continue; + String key = raw.substring(0, split).strip(); + if (!"channel".equalsIgnoreCase(key)) continue; + String indent = raw.substring(0, raw.length() - stripped.length()); + lines[i] = indent + "channel = " + safeChannel; + return String.join("\n", lines); + } + if (safeScript.isBlank()) return "channel = " + safeChannel; + return "channel = " + safeChannel + "\n" + safeScript; + } + + @Override public String getOverlayId() { return "autism-action-editor"; } + @Override public int getMinWidth() { return MIN_W; } + @Override public int getMinHeight() { return currentMinPanelHeight(); } + @Override public boolean isVisible() { return visible; } + @Override public void setVisible(boolean v) { + visible = v; + + if (v) { + hitRegions.clear(); + scrollDragRegions.clear(); + } else { + CompactDropdown.closeOpenMenu(enumDropdowns); + packetSelectorOverlay.setVisible(false); + raceStepSelectorOverlay.setVisible(false); + clearTextFieldFocus(); + } + } + + @Override + public boolean isCollapsed() { + return collapsed; + } + + @Override + public void setCollapsed(boolean value) { + if (collapsed == value) return; + super.setCollapsed(value); + if (value) { + CompactDropdown.closeOpenMenu(enumDropdowns); + packetSelectorOverlay.setVisible(false); + raceStepSelectorOverlay.setVisible(false); + hitRegions.clear(); + scrollDragRegions.clear(); + } + } + + @Override + public AutismWindowLayout getBounds() { + return new AutismWindowLayout(panelX, panelY, panelW, panelH, visible, collapsed); + } + + @Override + public void setBounds(AutismWindowLayout b) { + AutismWindowLayout c = clampToScreen(this, b); + panelX = c.x; + panelY = c.y; + panelW = c.width; + panelH = c.height; + visible = c.visible; + collapsed = c.collapsed; + } + + @Override + public boolean isMouseOver(double mx, double my) { + return visible + && (packetSelectorOverlay.isVisible() + || raceStepSelectorOverlay.isVisible() + || CompactDropdown.isMenuOpen(enumDropdowns) + || mx >= panelX && mx < panelX + panelW + && my >= panelY && my < panelY + (collapsed ? HEADER_HEIGHT : panelH)); + } + + @Override + public boolean isOverDragBar(double mx, double my) { + return visible + && mx >= panelX && mx < panelX + panelW + && my >= panelY && my < panelY + HEADER_HEIGHT + && !isOverWindowControl(mx, my, getBounds()); + } + + @Override + public boolean hasTextFieldFocused() { + if (packetSelectorOverlay.hasTextFieldFocused()) return true; + if (raceStepSelectorOverlay.hasTextFieldFocused()) return true; + for (AutismChatField f : textFields.values()) if (f.isFocused()) return true; + for (AutismChatField f : addFields.values()) if (f.isFocused()) return true; + return false; + } + + @Override + public void clearTextFieldFocus() { + textFields.values().forEach(f -> f.setFocused(false)); + addFields.values().forEach(f -> f.setFocused(false)); + } + + public boolean wantsItemSlotCapture() { + return captureSession.hasItemSlotCapture(); + } + + public boolean shouldRenderAbstractContainerScreenCaptureBanner() { + return captureSession.hasItemSlotCapture(); + } + + public String getAbstractContainerScreenCaptureTitle() { + return "Capturing " + getAbstractContainerScreenCaptureTargetLabel() + " - " + getCaptureActionLabel(); + } + + public String getAbstractContainerScreenCaptureInstruction() { + String activeCaptureKey = captureSession.itemSlotKey(); + if ("_item_entries".equals(activeCaptureKey) || "_drop_entries".equals(activeCaptureKey)) { + return "Right-click a slot to set the item. Esc = cancel"; + } + if ("_wsc_entries".equals(activeCaptureKey)) { + return "Right-click slots to add items or exact slots. Esc = done"; + } + if (stringLists.containsKey(activeCaptureKey)) { + if (isXCarryListKey(activeCaptureKey)) { + return "Right-click slots to add items, or empty slots for exact slots. Esc = done"; + } + return "Right-click slots to add item names. Esc = done"; + } + return "Right-click a slot in this screen. Esc = cancel"; + } + + public String getAbstractContainerScreenCaptureHoverText(net.minecraft.world.inventory.Slot slot, String itemName, String registryId) { + if (slot == null) return ""; + int handlerSlot = autismclient.util.AutismInventoryHelper.toMenuSlotId(MC, slot); + int visibleSlot = handlerSlot >= 0 + ? autismclient.util.AutismInventoryHelper.toUserVisibleSlot(MC, handlerSlot) + : -1; + String slotText = visibleSlot >= 0 ? String.valueOf(visibleSlot) : "Handler " + handlerSlot; + String slotDetail = "Handler " + handlerSlot; + String itemText = !registryId.isEmpty() ? registryId : (!itemName.isEmpty() ? itemName : "Empty slot"); + return slotText.equals(slotDetail) + ? "Hover: " + slotText + " | " + itemText + : "Hover: " + slotText + " | " + slotDetail + " | " + itemText; + } + + public boolean cancelCaptureIfActive() { + if (cancelPacketClickCaptureIfActive()) return true; + return captureSession.stopItemSlotCapture(() -> exitCaptureMode(false, false)); + } + + public boolean hasActiveCaptureSession() { + AutismSharedState state = AutismSharedState.get(); + return captureSession.hasItemSlotCapture() + || packetClickCapturePendingKey != null + || captureHiddenOverlays != null + || restoreVisibleAfterCapture + || screenBeforeCapture != null + || screenBeforeGBreak != null + || state.hasCaptureCancelCallback() + || state.hasBlockCaptureCallback() + || state.hasEntityCaptureCallback() + || state.hasAttackCaptureCallback() + || state.isGBreakCapturing(); + } + + public boolean onInventorySlotCapture(net.minecraft.world.inventory.Slot slot, + String itemName, String registryId) { + return onInventorySlotCapture(slot, itemName, registryId, false); + } + + public boolean onInventorySlotCapture(net.minecraft.world.inventory.Slot slot, + String itemName, String registryId, boolean slotMode) { + int visibleSlot = slot != null + ? autismclient.util.AutismInventoryHelper.toUserVisibleSlot(MC, slot) + : -1; + ItemTarget capturedTarget = captureItemTarget(slot, itemName, registryId, visibleSlot); + if (!captureSession.hasItemSlotCapture() || (itemName.isEmpty() && visibleSlot < 0)) return false; + + boolean useSlot = slotMode && visibleSlot >= 0; + if (useSlot) capturedTarget = ItemTarget.slotOnly(Math.max(0, visibleSlot)); + String key = captureSession.itemSlotKey(); + + if ("_item_entries".equals(key) && itemAction != null) { + applyCapturedItemEntry(capturedTarget); + captureSession.clearItemSlotCapture(); + exitCaptureMode(false, false); + return true; + } + + if ("_drop_entries".equals(key) && dropAction != null) { + applyCapturedDropEntry(capturedTarget); + captureSession.clearItemSlotCapture(); + exitCaptureMode(false, false); + return true; + } + + if ("_wsc_entries".equals(key)) { + String rawTarget = capturedTarget.toLegacyEntry(); + if (rawTarget == null) { + showCaptureToast("Nothing to add from that slot", CAPTURE_TOAST_ERROR); + return true; + } + String norm = autismclient.util.macro.StoreItemAction.normalizeTargetEntry(rawTarget); + if (norm == null || norm.isBlank()) { + showCaptureToast("Nothing to add from that slot", CAPTURE_TOAST_ERROR); + return true; + } + String disp = autismclient.util.macro.StoreItemAction.formatTargetEntry(norm); + if (wscEditIndex >= 0 && wscEditIndex < wscEntries.size()) { + + if (!wscTargetExistsOtherThan(norm, wscEditIndex)) { + WaitForSlotChangeAction.WaitEntry entry = wscEntries.get(wscEditIndex); + entry.target = norm; + entry.itemTarget = capturedTarget.copy(); + syncWscEditorFromEntry(entry); + showCaptureToast("Updated: " + disp, CAPTURE_TOAST_SUCCESS); + } else { + showCaptureToast("Already in list: " + disp, CAPTURE_TOAST_ERROR); + } + } else { + if (wscTargetExists(norm)) { + showCaptureToast("Already added: " + disp, CAPTURE_TOAST_ERROR); + } else { + WaitForSlotChangeAction.WaitEntry entry = new WaitForSlotChangeAction.WaitEntry(norm, wscAddMode, wscAddCount); + entry.itemTarget = capturedTarget.copy(); + entry.target = norm; + wscEntries.add(entry); + showCaptureToast("Added: " + disp, CAPTURE_TOAST_SUCCESS); + } + } + return true; + } + + if ("wait_inventory_slot".equals(key)) { + setWaitInventorySlot(Math.max(0, visibleSlot)); + captureSession.clearItemSlotCapture(); + exitCaptureMode(false, false); + showCaptureToast("Slot set: " + Math.max(0, visibleSlot), CAPTURE_TOAST_SUCCESS); + return true; + } + + if ("itemName".equals(key) + && targetAction != null + && targetAction.getType() == MacroActionType.USE_ITEM) { + AutismChatField itemField = textFields.get("itemName"); + AutismChatField slotField = textFields.get("slot"); + if (capturedTarget.hasIdentity()) { + ItemTarget nameOnly = stripSlotFromTarget(capturedTarget); + if (itemField != null) itemField.setText(nameOnly.editorText()); + editorItemFields.put("itemName", nameOnly.copy()); + showCaptureToast("Item set: " + nameOnly.displayLabel(), CAPTURE_TOAST_SUCCESS); + } else if (capturedTarget.hasSlot()) { + if (itemField != null) itemField.setText(""); + editorItemFields.remove("itemName"); + if (slotField != null) slotField.setText(String.valueOf(Math.max(0, capturedTarget.slot))); + showCaptureToast("Slot set: " + Math.max(0, capturedTarget.slot), CAPTURE_TOAST_SUCCESS); + } else { + showCaptureToast("Nothing to capture from that slot", CAPTURE_TOAST_ERROR); + } + captureSession.clearItemSlotCapture(); + exitCaptureMode(false, false); + return true; + } + + if (stringLists.containsKey(key)) { + List list = stringLists.get(key); + if (list == null) return false; + CaptureListAddResult result = isStoreItemTargetListKey(key) + ? tryAddCapturedStoreItemEntry(slot, useSlot ? "" : itemName, useSlot ? "" : registryId, visibleSlot, list) + : tryAddCapturedStringListEntry( + findField(key), + key, + list, + useSlot + ? capturedTarget.toLegacyEntry() + : (isXCarryListKey(key) + ? capturedTarget.toLegacyEntry() + : (isInventoryAuditTargetListKey(key) + ? stripSlotFromTarget(capturedTarget).toLegacyEntry() + : (usesStoreTargetFormatting(key) + ? capturedTarget.toLegacyEntry() + : itemName))) + ); + if (result != null && result.added() && (usesStoreTargetFormatting(key) || isXCarryListKey(key) || isInventoryAuditTargetListKey(key))) { + ItemTarget preservedTarget = isStoreItemTargetListKey(key) + ? storeCaptureTarget(capturedTarget) + : isInventoryAuditTargetListKey(key) + ? (useSlot ? capturedTarget : stripSlotFromTarget(capturedTarget)) + : capturedTarget; + preserveCapturedListTarget(key, list, preservedTarget); + } + if (result != null && result.message() != null && !result.message().isBlank()) { + showCaptureToast(result.message(), result.accentColor()); + } + return true; + } + + AutismChatField tf = textFields.get(key); + if (tf != null) { + FieldDef field = findField(key); + if (field != null && field.type() == FieldType.SLOT) { + + tf.setText(String.valueOf(Math.max(0, visibleSlot))); + } else if (useSlot) { + + tf.setText(capturedTarget.toLegacyEntry()); + if ("itemName".equals(key) || "fromItemName".equals(key) || "toItemName".equals(key) || editorItemFields.containsKey(key)) { + editorItemFields.put(key, capturedTarget.copy()); + } + } else { + + ItemTarget nameOnly = stripSlotFromTarget(capturedTarget); + tf.setText(nameOnly.editorText()); + if ("itemName".equals(key) || "fromItemName".equals(key) || "toItemName".equals(key) || editorItemFields.containsKey(key)) { + editorItemFields.put(key, nameOnly.copy()); + } + } + captureSession.clearItemSlotCapture(); + exitCaptureMode(false, false); + return true; + } + + return false; + } + + @Override + public void render(GuiGraphicsExtractor context, int mouseX, int mouseY, float delta) { + if (!visible) return; + frameDelta = delta; + + hitRegions.clear(); + scrollDragRegions.clear(); + enumDropdowns.clear(); + bodyInputClip = null; + + if (!collapsed) { + int neededH = HEADER_HEIGHT + PAD + computeContentH() + FOOTER_H + PAD; + int minH = currentMinPanelHeight(); + int maxH = Math.max(minH, AutismUiScale.getVirtualScreenHeight() * 4 / 5); + panelH = Math.max(minH, Math.min(maxH, neededH)); + } + AutismWindowLayout clamped = clampToScreen(this, new AutismWindowLayout(panelX, panelY, panelW, panelH, visible, collapsed)); + panelX = clamped.x; + panelY = clamped.y; + panelW = clamped.width; + panelH = clamped.height; + + String title = targetActionTitle(); + + AutismWindowLayout bounds = getBounds(); + renderWindowFrame(context, mouseX, mouseY, bounds, title, collapsed, dragging); + boolean clipBody = beginWindowBodyClip(context, bounds, collapsed); + if (clipBody) { + try { + int frameH = getRenderedFrameHeight(bounds, false); + int bodyTop = panelY + HEADER_HEIGHT; + int bodyBtm = panelY + frameH; + if (bodyBtm > bodyTop + 1) { + renderBody(context, mouseX, mouseY, delta, bodyTop, bodyBtm); + } + if (!enumDropdowns.isEmpty()) { + CompactDropdown.renderButtons(context, textRenderer, enumDropdowns, mouseX, mouseY); + } + } finally { + endWindowBodyClip(context, true); + } + } + renderWindowInactiveOverlay(context, bounds, collapsed, dragging); + + if (!enumDropdowns.isEmpty() && CompactDropdown.isMenuOpen(enumDropdowns)) { + context.nextStratum(); + CompactDropdown.renderOpenMenu(context, textRenderer, enumDropdowns, mouseX, mouseY); + } + + if (packetSelectorOverlay.isVisible()) { + packetSelectorOverlay.render(context, mouseX, mouseY, delta); + } + if (raceStepSelectorOverlay.isVisible()) { + raceStepSelectorOverlay.render(context, mouseX, mouseY, delta); + } + } + + private void renderBody(GuiGraphicsExtractor context, int mouseX, int mouseY, float delta, + int bodyTop, int bodyBtm) { + + if (itemAction != null) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderItemPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (payloadAction != null) { + int contentBtm = bodyBtm - FOOTER_H; + int contentAreaH = contentBtm - bodyTop; + int totalContentH = computeContentH(); + final int maxScroll = Math.max(0, totalContentH - contentAreaH); + scrollOffset = Math.max(0, Math.min(scrollOffset, maxScroll)); + + boolean needsScroll = maxScroll > 0; + int sbReserve = needsScroll ? SCROLLBAR_W + 1 : 0; + int x = panelX + PAD; + int w = panelW - PAD * 2 - sbReserve; + + UiScissorStack.global().push(context, UiBounds.of( + panelX + 1, bodyTop, Math.max(0, panelW - 2), Math.max(0, contentBtm - bodyTop))); + try { + renderPayloadPanel(context, x, bodyTop - scrollOffset, w, mouseX, mouseY, delta); + } finally { + UiScissorStack.global().pop(context); + } + + if (needsScroll) { + int sbX = panelX + panelW - SCROLLBAR_W - 1; + drawScrollbar(context, sbX, bodyTop, contentAreaH, totalContentH, contentAreaH, 1, scrollOffset); + final int capSbY = bodyTop, capSbH = contentAreaH; + scrollDragRegions.add(new ScrollDragRegion(sbX, bodyTop, SCROLLBAR_W, contentAreaH, my -> { + int rel = Math.max(0, Math.min(capSbH, my - capSbY)); + scrollOffset = Math.max(0, Math.min(maxScroll, rel * maxScroll / Math.max(1, capSbH))); + })); + } + } else if (targetAction != null && targetAction.getType() == MacroActionType.SEND_PACKET) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderSendPacketPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.WAIT_PACKET) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderWaitPacketPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.WAIT_PACKET_MATCH) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderWaitPacketMatchPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.WAIT_SOUND) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderWaitSoundPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.WAIT_ENTITY) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderWaitEntityPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.USE_ITEM) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderUseItemPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.LOOK_AT_BLOCK) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderLookAtPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.ROTATE) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderRotatePanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.GO_TO) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderGoToPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.SWAP_SLOTS) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderSwapSlotsPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.CLICK) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderClickPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.DISCONNECT) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderDisconnectPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.WAIT_GUI) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderWaitGuiPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.WAIT_CHAT) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderWaitChatPanel(context, x, bodyTop, bodyBtm - FOOTER_H, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.SELECT_SLOT) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderSelectSlotPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.WAIT_COOLDOWN) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderWaitCooldownPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && (targetAction.getType() == MacroActionType.OPEN_CONTAINER + || targetAction.getType() == MacroActionType.INTERACT_ENTITY)) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderOpenContainerPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.WAIT_SLOT_CHANGE) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderWaitSlotChangePanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.WAIT_INVENTORY_PREDICATE) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderWaitInventoryPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.CAPTURE_VALUE) { + int contentBtm = bodyBtm - FOOTER_H; + int contentAreaH = Math.max(0, contentBtm - bodyTop); + int totalContentH = computeContentH(); + final int maxScroll = Math.max(0, totalContentH - contentAreaH); + scrollOffset = Math.max(0, Math.min(scrollOffset, maxScroll)); + + boolean needsScroll = maxScroll > 0; + int sbReserve = needsScroll ? SCROLLBAR_W + 1 : 0; + int x = panelX + PAD; + int w = panelW - PAD * 2 - sbReserve; + UiBounds clip = UiBounds.of(panelX + 1, bodyTop, + Math.max(0, panelW - 2), contentAreaH); + bodyInputClip = clip; + int firstBodyHit = hitRegions.size(); + + UiScissorStack.global().push(context, clip); + try { + renderCaptureValuePanel(context, x, bodyTop - scrollOffset, w, mouseX, mouseY, delta); + } finally { + UiScissorStack.global().pop(context); + } + clipHitRegions(firstBodyHit, clip); + + if (needsScroll) { + int sbX = panelX + panelW - SCROLLBAR_W - 1; + drawScrollbar(context, sbX, bodyTop, contentAreaH, totalContentH, contentAreaH, 1, scrollOffset); + final int capSbY = bodyTop; + final int capSbH = contentAreaH; + scrollDragRegions.add(new ScrollDragRegion(sbX, bodyTop, SCROLLBAR_W, contentAreaH, my -> { + int rel = Math.max(0, Math.min(capSbH, my - capSbY)); + scrollOffset = Math.max(0, Math.min(maxScroll, + rel * maxScroll / Math.max(1, capSbH))); + })); + } + } else if (targetAction != null && targetAction.getType() == MacroActionType.DELAY_PACKETS) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderDelayPacketsPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.MINE) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderMinePanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.PAY) { + int contentBtm = bodyBtm - FOOTER_H; + int contentAreaH = Math.max(0, contentBtm - bodyTop); + int totalContentH = computeContentH(); + final int maxScroll = Math.max(0, totalContentH - contentAreaH); + scrollOffset = Math.max(0, Math.min(scrollOffset, maxScroll)); + + boolean needsScroll = maxScroll > 0; + int sbReserve = needsScroll ? SCROLLBAR_W + 1 : 0; + int x = panelX + PAD; + int w = panelW - PAD * 2 - sbReserve; + UiBounds clip = UiBounds.of(panelX + 1, bodyTop, Math.max(0, panelW - 2), contentAreaH); + bodyInputClip = clip; + int firstBodyHit = hitRegions.size(); + + UiScissorStack.global().push(context, clip); + try { + renderPayPanel(context, x, bodyTop - scrollOffset, w, mouseX, mouseY, delta); + } finally { + UiScissorStack.global().pop(context); + } + clipHitRegions(firstBodyHit, clip); + + if (needsScroll) { + int sbX = panelX + panelW - SCROLLBAR_W - 1; + drawScrollbar(context, sbX, bodyTop, contentAreaH, totalContentH, contentAreaH, 1, scrollOffset); + final int capSbY = bodyTop; + final int capSbH = contentAreaH; + scrollDragRegions.add(new ScrollDragRegion(sbX, bodyTop, SCROLLBAR_W, contentAreaH, my -> { + int rel = Math.max(0, Math.min(capSbH, my - capSbY)); + scrollOffset = Math.max(0, Math.min(maxScroll, rel * maxScroll / Math.max(1, capSbH))); + })); + } + } else if (targetAction != null && targetAction.getType() == MacroActionType.INVENTORY_AUDIT) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderInventoryAuditPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.STORE_ITEM) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderStoreItemPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (targetAction != null && targetAction.getType() == MacroActionType.TOGGLE_MODULE) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderToggleModulePanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (craftEntries != null) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderCraftPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (dropAction != null) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderDropPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (lanStepEntries != null) { + int x = panelX + PAD; + int w = panelW - PAD * 2; + renderLanStepPanel(context, x, bodyTop, w, mouseX, mouseY, delta); + } else if (schema != null && !schema.fields().isEmpty()) { + int contentBtm = bodyBtm - FOOTER_H; + int contentAreaH = contentBtm - bodyTop; + int totalContentH = computeContentH(); + final int maxScroll = Math.max(0, totalContentH - contentAreaH); + scrollOffset = Math.max(0, Math.min(scrollOffset, maxScroll)); + + boolean needsScroll = maxScroll > 0; + int sbReserve = needsScroll ? SCROLLBAR_W + 1 : 0; + int x = panelX + PAD; + int w = panelW - PAD * 2 - sbReserve; + + UiScissorStack.global().push(context, UiBounds.of( + panelX + 1, bodyTop, Math.max(0, panelW - 2), Math.max(0, contentBtm - bodyTop))); + try { + int y = bodyTop + PAD - scrollOffset; + + if (targetAction != null && targetAction.getType() == MacroActionType.PLACE) { + + BlockPos previewPos = null; + try { + AutismChatField fx = textFields.get("blockPos_0"); + AutismChatField fy = textFields.get("blockPos_1"); + AutismChatField fz = textFields.get("blockPos_2"); + if (fx != null && fy != null && fz != null) { + String sx = fx.getText().strip(); + String sy = fy.getText().strip(); + String sz = fz.getText().strip(); + if (!sx.isEmpty() && !sy.isEmpty() && !sz.isEmpty()) { + int xPos = Integer.parseInt(sx); + int yPos = Integer.parseInt(sy); + int zPos = Integer.parseInt(sz); + previewPos = new BlockPos(xPos, yPos, zPos); + } + } + } catch (NumberFormatException ignored) { + previewPos = null; + } + if (previewPos != null) { + AutismInstaBreakRenderer.setTarget(previewPos, 0xFFFF3B3B); + } + + Identifier placeFont = theme.fontFor(UiTone.BODY); + UiText.draw(context, textRenderer, "Item", placeFont, + AutismColors.textSecondary(), x, y + 2, false); + y += 13; + renderPlaceItemRow(context, x, y, w, mouseX, mouseY, delta); + y += 16 + 4; + y = renderEditorHint(context, x, y, w, + "Name:any Slot:exact None:held"); + y += ROW_GAP; + + renderInlineToggle(context, placeFont, "place_waitForItem", "Wait for Item", x, y, w, mouseX, mouseY); + y += 18; + renderInlineToggle(context, placeFont, "place_silentSwitch", "Silent Switch", x, y, w, mouseX, mouseY); + y += 18; + } + + for (FieldDef field : schema.fields()) { + if (field.type() == FieldType.STRING_LIST) continue; + if (isGuiWaitAfterKey(field.key())) continue; + if (!isFieldVisible(field)) continue; + if (targetAction != null && targetAction.getType() == MacroActionType.PLACE + && "itemName".equals(field.key())) continue; + renderRow(context, field, x, y, w, mouseX, mouseY, delta); + y += rowH(field) + ROW_GAP; + } + + for (FieldDef field : schema.fields()) { + if (field.type() != FieldType.STRING_LIST) continue; + if (isGuiWaitAfterKey(field.key())) continue; + if (!isFieldVisible(field)) continue; + if (targetAction != null && targetAction.getType() == MacroActionType.PLACE + && "itemName".equals(field.key())) continue; + renderRow(context, field, x, y, w, mouseX, mouseY, delta); + y += rowH(field) + ROW_GAP; + } + + if (targetAction != null && targetAction.getType() == MacroActionType.PACKET) { + renderPacketActionButtons(context, x, y, w, mouseX, mouseY); + y += 52; + } + if (targetAction != null && targetAction.getType() == MacroActionType.SEND_PACKET) { + renderSendPacketButtons(context, x, y, w, mouseX, mouseY); + y += 52; + } + if (targetAction != null && targetAction.getType() == MacroActionType.DELAY_PACKETS) { + renderDelayPacketsPresetButtons(context, x, y, w, mouseX, mouseY); + } + + } finally { + UiScissorStack.global().pop(context); + } + + if (needsScroll) { + int sbX = panelX + panelW - SCROLLBAR_W - 1; + drawScrollbar(context, sbX, bodyTop, contentAreaH, totalContentH, contentAreaH, 1, scrollOffset); + final int capSbY = bodyTop, capSbH = contentAreaH; + scrollDragRegions.add(new ScrollDragRegion(sbX, bodyTop, SCROLLBAR_W, contentAreaH, my -> { + int rel = Math.max(0, Math.min(capSbH, my - capSbY)); + scrollOffset = Math.max(0, Math.min(maxScroll, rel * maxScroll / Math.max(1, capSbH))); + })); + } + } + + renderFooter(context, bodyBtm - FOOTER_H, mouseX, mouseY); + } + + private void renderItemPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + int headerBtnW = 44; + + UiText.draw(ctx, textRenderer, + "Items / Exact Slots (" + itemAction.itemNames.size() + ")", font, + AutismColors.textSecondary(), x, cy + 2, false); + boolean canClearAll = !itemAction.itemNames.isEmpty(); + int clearX = x + w - headerBtnW; + renderOverlayButton(ctx, clearX, cy, headerBtnW, 14, "Clear", CompactOverlayButton.Variant.DANGER, canClearAll, mx, my, () -> { + itemAction.itemNames.clear(); + itemAction.itemTimes.clear(); + itemAction.itemActionIdx.clear(); + itemAction.itemButtons.clear(); + itemAction.itemSearchScopes.clear(); + itemAction.stackAmountModes.clear(); + clearItemEditSelection(); + rebuildItemFields(); + }); + cy += 14; + + int selAreaH = SEL_LIST_MAX_VIS * SEL_ITEM_H; + int sbX = x + w - SCROLLBAR_W; + + DirectScrollViewport itemViewport = getOrCreateViewport(selectedScrollViewports, "_item_entries", + x, cy, w, selAreaH, SEL_ITEM_H, SCROLLBAR_W); + itemViewport.setContentHeight(itemAction.itemNames.size() * SEL_ITEM_H); + + itemViewport.renderScrollbar(ctx, mx, my); + + autismclient.util.AutismDropAction[] ACTIONS = autismclient.util.AutismDropAction.values(); + int sbGap = SCROLLBAR_W + 2; + int delW = 13; + int itemW = w - sbGap - delW - 2; + + if (!itemAction.itemNames.isEmpty()) { + itemViewport.beginRender(ctx, theme.borderSoft(), 0x36000000); + int firstVis = itemViewport.getFirstVisibleRow(); + int iy0 = cy - (itemViewport.getScrollOffset() % SEL_ITEM_H); + for (int i = firstVis; i < itemAction.itemNames.size() && i <= itemViewport.getLastVisibleRow(); i++) { + int iy = itemViewport.getRowScreenY(i); + if (iy == Integer.MIN_VALUE) continue; + String entry = itemAction.itemNames.get(i); + int eiActIdx = itemAction.getItemActionIdx(i); + autismclient.util.AutismDropAction eiAct = ACTIONS[eiActIdx]; + int eiBtn = itemAction.getItemButton(i); + boolean selected = i == itemEditIndex; + + ItemTarget entryTarget = targetAt(itemAction.itemTargets, itemAction.itemNames, i); + Component displayName = formatItemTargetText(entryTarget, entry); + boolean rowHovered = mx >= x && mx < x + itemW && my >= iy && my < iy + 13; + + String summaryAct = eiAct.shortName; + String summaryBtn = eiAct == autismclient.util.AutismDropAction.SWAP + ? "H" + Math.max(1, Math.min(9, eiBtn + 1)) + : eiAct == autismclient.util.AutismDropAction.PICKUP_ALL + ? "" + : switch (eiBtn) { case 1 -> "R"; case 2 -> "M"; default -> "L"; }; + int times = itemAction.getItemTime(i); + String summary = " \u2022 " + summaryAct + + (summaryBtn.isBlank() ? "" : " " + summaryBtn) + + (times != 1 ? " \u00d7" + times : ""); + Component rowLabel = Component.empty().append(displayName).append( + Component.literal(summary).withStyle(s -> s.withColor(0xFF888888))); + + MacroTypedListControl.renderRow( + ctx, + textRenderer, + rowLabel, + UiBounds.of(x, iy, itemW, 13), + rowHovered, + selected, + CompactListRenderer.RowTone.NORMAL, + true + ); + + if (iy + 13 > cy && iy < cy + selAreaH) { + final int fi = i; + hitRegions.add(new HitRegion(x, Math.max(cy, iy), itemW, Math.min(iy + 13, cy + selAreaH) - Math.max(cy, iy), () -> toggleItemEditSelection(fi))); + } + + if (iy + 13 > cy && iy < cy + selAreaH) { + int delX = x + itemW + 2; + final int fi = i; + renderIconDeleteButton(ctx, delX, iy, delW, mx, my, () -> { + itemAction.itemNames.remove(fi); + if (fi < itemAction.itemTargets.size()) itemAction.itemTargets.remove(fi); + if (fi < itemAction.itemTimes.size()) itemAction.itemTimes.remove(fi); + if (fi < itemAction.itemActionIdx.size()) itemAction.itemActionIdx.remove(fi); + if (fi < itemAction.itemButtons.size()) itemAction.itemButtons.remove(fi); + if (fi < itemAction.itemSearchScopes.size()) itemAction.itemSearchScopes.remove(fi); + if (fi < itemAction.stackAmountModes.size()) itemAction.stackAmountModes.remove(fi); + if (itemEditIndex == fi) clearItemEditSelection(); + else if (itemEditIndex > fi) itemEditIndex--; + rebuildItemFields(); + DirectScrollViewport vp = selectedScrollViewports.get("_item_entries"); + if (vp != null) vp.scrollBy(-1); + }); + } + } + itemViewport.endRender(ctx); + } else { + CompactListRenderer.drawEmptyState(ctx, textRenderer, "No rows yet. Add an item or exact slot.", x, cy, w - SCROLLBAR_W - 1); + } + cy += selAreaH; + + CompactSurfaces.divider(ctx, x, cy + 2, w, AutismColors.subPanelBorder()); + cy += 6; + + int addPickW = 32; + int addBtnW = 34; + int slotW = 26; + AutismChatField addF = addFields.get("_item_add"); + AutismChatField entrySlotF = textFields.get("item_entrySlot"); + if (addF != null && entrySlotF != null) { + int pickX = x + w - addBtnW - 3 - addPickW; + int plusX = x + w - addBtnW; + int slotX = pickX - 3 - slotW; + addF.setX(x); addF.setY(cy + 1); addF.setWidth(slotX - x - 2); + addF.render(ctx, mx, my, delta); + entrySlotF.setX(slotX); entrySlotF.setY(cy + 1); entrySlotF.setWidth(slotW); + entrySlotF.render(ctx, mx, my, delta); + + boolean capturing = captureSession.isItemSlotCapture("_item_entries"); + renderFieldCaptureButton( + ctx, + pickX, + cy, + addPickW, + 14, + CaptureMode.ITEM_SLOT, + capturing, + true, + mx, + my, + () -> { + toggleItemSlotCapture("_item_entries"); + }); + + String addLbl = itemEditIndex >= 0 ? "New" : "+Add"; + renderOverlayButton(ctx, plusX, cy, addBtnW, 14, addLbl, CompactOverlayButton.Variant.SUCCESS, true, mx, my, () -> { + if (itemEditIndex >= 0) clearItemEditSelection(); + else applyItemEntryEditor(); + }); + } + cy += 16; + cy += 4; + + if (itemEditIndex >= 0 && itemEditIndex < itemAction.itemNames.size()) { + int eiActIdx = itemAction.getItemActionIdx(itemEditIndex); + autismclient.util.AutismDropAction eiAct = ACTIONS[eiActIdx]; + int eiBtn = itemAction.getItemButton(itemEditIndex); + boolean btnActive = eiAct == autismclient.util.AutismDropAction.PICKUP + || eiAct == autismclient.util.AutismDropAction.QUICK_MOVE + || eiAct == autismclient.util.AutismDropAction.SWAP; + final int editIdx = itemEditIndex; + + int editActW = 54; + int editBtnW = 28; + int editTimesW = 28; + int editGap = 3; + renderOverlayButton(ctx, x, cy, editActW, 14, eiAct.shortName, + CompactOverlayButton.Variant.SECONDARY, true, mx, my, + () -> itemAction.cycleItemAction(editIdx), + () -> itemAction.cycleItemActionBackwards(editIdx)); + String btnLbl = eiAct == autismclient.util.AutismDropAction.SWAP + ? "H" + Math.max(1, Math.min(9, eiBtn + 1)) + : eiAct == autismclient.util.AutismDropAction.PICKUP_ALL + ? "All" + : switch (eiBtn) { case 1 -> "R"; case 2 -> "M"; default -> "L"; }; + renderOverlayButton(ctx, x + editActW + editGap, cy, editBtnW, 14, btnLbl, + eiAct == autismclient.util.AutismDropAction.SWAP ? CompactOverlayButton.Variant.PRIMARY : CompactOverlayButton.Variant.GHOST, + btnActive, mx, my, + () -> itemAction.cycleItemButton(editIdx), + () -> itemAction.cycleItemButtonBackwards(editIdx)); + AutismChatField tf = textFields.get("item_times_" + itemEditIndex); + if (tf != null) { tf.setX(x + editActW + editGap + editBtnW + editGap); tf.setY(cy + 1); tf.setWidth(editTimesW); tf.render(ctx, mx, my, delta); } + cy += 16; + + if (isEditingNameOnlyItemTargetingAction()) { + renderItemTargetingControls(ctx, x, cy, w, mx, my); + cy += ROW_H + ROW_GAP; + } + } + + renderGuiWaitRow(ctx, font, "item_waitForGuiBefore", "item_waitForGuiAfter", x, cy, w, mx, my); + cy += ROW_H + ROW_GAP; + + if (toggleStates.getOrDefault("item_waitForGuiBefore", false) + || toggleStates.getOrDefault("item_waitForGuiAfter", false)) { + AutismChatField guiF = textFields.get("item_guiName"); + if (guiF != null) { + int lw = labelWidth(w, "GUI Name", font); + drawLabel(ctx, "GUI Name", x, cy, lw, font); + guiF.setX(controlX(x, lw)); guiF.setY(cy + 2); guiF.setWidth(controlWidth(w, lw)); + guiF.render(ctx, mx, my, delta); + } + cy += ROW_H + ROW_GAP; + } else { + AutismChatField guiF = textFields.get("item_guiName"); + if (guiF != null) guiF.setX(-1000); + } + + renderInlineToggle(ctx, font, "item_waitForItem", "Wait for Item", x, cy, w, mx, my); + cy += ROW_H + ROW_GAP; + + renderInlineToggle(ctx, font, "item_useClickDelay", "Delay Clicks", x, cy, w, mx, my); + cy += ROW_H + ROW_GAP; + + if (toggleStates.getOrDefault("item_useClickDelay", false)) { + AutismChatField delayF = textFields.get("item_clickDelayMs"); + if (delayF != null) { + int lw = labelWidth(w, "Delay (ms)", font); + drawLabel(ctx, "Delay (ms)", x, cy, lw, font); + delayF.setX(controlX(x, lw)); delayF.setY(cy + 2); delayF.setWidth(controlWidth(w, lw)); + delayF.render(ctx, mx, my, delta); + } + cy += ROW_H + ROW_GAP; + } else { + AutismChatField delayF = textFields.get("item_clickDelayMs"); + if (delayF != null) delayF.setX(-1000); + } + + } + + private void renderItemTargetingControls(GuiGraphicsExtractor ctx, int x, int y, int w, int mx, int my) { + if (itemAction == null || itemEditIndex < 0 || itemEditIndex >= itemAction.itemNames.size()) return; + + int gap = 4; + int invW = Math.max(68, (w - gap) / 2); + int stackW = Math.max(72, w - invW - gap); + int stackX = x + invW + gap; + autismclient.util.macro.ItemAction.ItemSearchScope scope = itemAction.getItemSearchScope(itemEditIndex); + + renderOverlayButton( + ctx, + x, + y + 2, + invW, + 14, + scope.label, + scope == autismclient.util.macro.ItemAction.ItemSearchScope.BOTH + ? CompactOverlayButton.Variant.SECONDARY + : CompactOverlayButton.Variant.PRIMARY, + true, + mx, + my, + () -> itemAction.cycleItemSearchScope(itemEditIndex, 1), + () -> itemAction.cycleItemSearchScope(itemEditIndex, -1) + ); + + autismclient.util.macro.ItemAction.StackAmountMode mode = itemAction.getStackAmountMode(itemEditIndex); + renderOverlayButton( + ctx, + stackX, + y + 2, + stackW, + 14, + "Stack: " + mode.label, + mode == autismclient.util.macro.ItemAction.StackAmountMode.DEFAULT + ? CompactOverlayButton.Variant.SECONDARY + : CompactOverlayButton.Variant.PRIMARY, + true, + mx, + my, + () -> itemAction.cycleStackAmountMode(itemEditIndex, 1), + () -> itemAction.cycleStackAmountMode(itemEditIndex, -1) + ); + } + + private boolean isEditingNameOnlyItemTargetingAction() { + if (itemAction == null || itemEditIndex < 0 || itemEditIndex >= itemAction.itemNames.size()) return false; + ItemTarget target = targetAt(itemAction.itemTargets, itemAction.itemNames, itemEditIndex); + if (!target.hasIdentity() || target.hasSlot()) return false; + return itemAction.getItemAction(itemEditIndex) != autismclient.util.AutismDropAction.PICKUP_ALL + || !toggleStates.getOrDefault("item_useCursorItemForPickupAll", itemAction.useCursorItemForPickupAll); + } + + private void addItemEntry(ItemTarget target) { + addTargetEntry(itemAction.itemTargets, itemAction.itemNames, target); + while (itemAction.itemTimes.size() < itemAction.itemNames.size()) itemAction.itemTimes.add(1); + while (itemAction.itemActionIdx.size() < itemAction.itemNames.size()) itemAction.itemActionIdx.add(0); + while (itemAction.itemButtons.size() < itemAction.itemNames.size()) itemAction.itemButtons.add(0); + while (itemAction.itemSearchScopes.size() < itemAction.itemNames.size()) itemAction.itemSearchScopes.add(0); + while (itemAction.stackAmountModes.size() < itemAction.itemNames.size()) itemAction.stackAmountModes.add(0); + int idx = itemAction.itemNames.size() - 1; + AutismChatField f = makeField(28); + f.setNumericOnly(true); + f.setText("1"); + textFields.put("item_times_" + idx, f); + } + + private void rebuildItemFields() { + textFields.keySet().removeIf(k -> k.startsWith("item_times_")); + + trimTargetEntries(itemAction.itemTargets, itemAction.itemNames.size()); + while (itemAction.itemTimes.size() > itemAction.itemNames.size()) itemAction.itemTimes.remove(itemAction.itemTimes.size() - 1); + while (itemAction.itemActionIdx.size() > itemAction.itemNames.size()) itemAction.itemActionIdx.remove(itemAction.itemActionIdx.size() - 1); + while (itemAction.itemButtons.size() > itemAction.itemNames.size()) itemAction.itemButtons.remove(itemAction.itemButtons.size() - 1); + while (itemAction.itemSearchScopes.size() > itemAction.itemNames.size()) itemAction.itemSearchScopes.remove(itemAction.itemSearchScopes.size() - 1); + while (itemAction.stackAmountModes.size() > itemAction.itemNames.size()) itemAction.stackAmountModes.remove(itemAction.stackAmountModes.size() - 1); + while (itemAction.itemSearchScopes.size() < itemAction.itemNames.size()) itemAction.itemSearchScopes.add(0); + while (itemAction.stackAmountModes.size() < itemAction.itemNames.size()) itemAction.stackAmountModes.add(0); + for (int i = 0; i < itemAction.itemNames.size(); i++) { + AutismChatField f = makeField(28); + f.setNumericOnly(true); + f.setText(String.valueOf(itemAction.getItemTime(i))); + textFields.put("item_times_" + i, f); + } + } + + private void toggleItemEditSelection(int index) { + if (itemEditIndex == index) { + clearItemEditSelection(); + return; + } + itemEditIndex = index; + syncItemEntryEditorFromSelection(); + } + + private void clearItemEditSelection() { + itemEditIndex = -1; + AutismChatField addF = addFields.get("_item_add"); + suppressItemEntryLiveUpdate = true; + if (addF != null) addF.setText(""); + AutismChatField slotF = textFields.get("item_entrySlot"); + if (slotF != null) slotF.setText(""); + suppressItemEntryLiveUpdate = false; + } + + private void syncItemEntryEditorFromSelection() { + AutismChatField addF = addFields.get("_item_add"); + AutismChatField slotF = textFields.get("item_entrySlot"); + if (addF == null || slotF == null) return; + suppressItemEntryLiveUpdate = true; + if (itemEditIndex < 0 || itemEditIndex >= itemAction.itemNames.size()) { + addF.setText(""); + slotF.setText(""); + suppressItemEntryLiveUpdate = false; + return; + } + ItemTarget target = targetAt(itemAction.itemTargets, itemAction.itemNames, itemEditIndex); + addF.setText(target.editorText()); + slotF.setText(target.hasSlot() ? String.valueOf(target.slot) : ""); + suppressItemEntryLiveUpdate = false; + } + + private void applyItemEntryEditor() { + applyItemEntryEditor(false); + } + + private void handleItemEntryEditorChanged() { + if (suppressItemEntryLiveUpdate || itemAction == null) return; + if (itemEditIndex < 0 || itemEditIndex >= itemAction.itemNames.size()) return; + applyItemEntryEditor(true); + } + + private void applyItemEntryEditor(boolean preserveSelection) { + if (itemAction == null) return; + AutismChatField addF = addFields.get("_item_add"); + AutismChatField slotF = textFields.get("item_entrySlot"); + if (addF == null || slotF == null) return; + String nameText = addF.getText().strip(); + String slotText = slotF.getText().strip(); + ItemTarget target = buildEntryTargetFromEditor(nameText, slotText, targetAt(itemAction.itemTargets, itemAction.itemNames, itemEditIndex)); + String entry = target.toLegacyEntry(); + if (entry == null || entry.isBlank()) return; + + if (itemEditIndex >= 0 && itemEditIndex < itemAction.itemNames.size()) { + if (!containsEntryOtherThan(itemAction.itemNames, entry, itemEditIndex)) { + setTargetAt(itemAction.itemTargets, itemAction.itemNames, itemEditIndex, target); + } + } else if (!itemAction.itemNames.contains(entry)) { + addItemEntry(target); + } + + if (!preserveSelection) { + clearItemEditSelection(); + } + } + + private void applyCapturedItemEntry(ItemTarget rawTarget) { + if (itemAction == null) return; + + ItemTarget target = storeCaptureTarget(rawTarget); + String entry = target == null ? "" : target.toLegacyEntry(); + if (entry.isBlank()) return; + + int targetIndex = itemEditIndex; + if (targetIndex >= 0 && targetIndex < itemAction.itemNames.size()) { + if (!containsEntryOtherThan(itemAction.itemNames, entry, targetIndex)) { + setTargetAt(itemAction.itemTargets, itemAction.itemNames, targetIndex, target.copy()); + } + } else { + targetIndex = itemAction.itemNames.indexOf(entry); + if (targetIndex < 0) { + addItemEntry(target.copy()); + targetIndex = itemAction.itemNames.size() - 1; + } + } + + itemEditIndex = targetIndex; + AutismChatField addF = addFields.get("_item_add"); + if (addF != null) addF.setText(target.editorText()); + } + + private void renderInlineToggle(GuiGraphicsExtractor ctx, Identifier font, String stateKey, String label, + int x, int y, int w, int mx, int my) { + boolean val = toggleStates.getOrDefault(stateKey, false); + int lw = labelWidth(w, label, font, 34); + drawLabel(ctx, label, x, y, lw, font); + int btnW = 34, btnH = 14; + int btnX = x + w - btnW; + renderOverlayToggleButton( + ctx, + btnX, + y + 2, + btnW, + btnH, + val ? "ON" : "OFF", + val, + "macro-inline:" + stateKey, + mx, + my, + () -> toggleStates.put(stateKey, !toggleStates.getOrDefault(stateKey, false)) + ); + } + + private void renderGuiWaitRow(GuiGraphicsExtractor ctx, Identifier font, String beforeKey, String afterKey, + int x, int y, int w, int mx, int my) { + drawLabel(ctx, "GUI Wait", x, y, labelWidth(w, "GUI Wait", font, 90), font); + int btnW = 42; + int gap = 4; + int afterX = x + w - btnW; + int beforeX = afterX - gap - btnW; + renderGuiWaitButton(ctx, beforeKey, "Before", beforeX, y + 2, btnW, mx, my); + renderGuiWaitButton(ctx, afterKey, "After", afterX, y + 2, btnW, mx, my); + } + + private void renderGuiWaitButton(GuiGraphicsExtractor ctx, String key, String label, + int x, int y, int w, int mx, int my) { + boolean val = toggleStates.getOrDefault(key, false); + renderOverlayToggleButton( + ctx, + x, + y, + w, + 14, + label, + val, + "macro-gui-wait:" + key, + mx, + my, + () -> toggleStates.put(key, !toggleStates.getOrDefault(key, false)) + ); + } + + private void renderCraftPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, + int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int removeW = 13; + int maxTogW = 42; + int amountW = 44; + int headerBtnW = 44; + + int cy = bodyTop + PAD; + + UiText.draw(ctx, textRenderer, + "Craft Entries (" + craftEntries.size() + ")", font, + AutismColors.textSecondary(), x, cy + 2, false); + boolean canClearEntries = !craftEntries.isEmpty(); + renderOverlayButton(ctx, x + w - headerBtnW, cy, headerBtnW, 14, "Clear", + CompactOverlayButton.Variant.DANGER, canClearEntries, mx, my, () -> { + craftEntries.clear(); + rebuildCraftFields(); + DirectScrollViewport craftVp = selectedScrollViewports.get("_craft_entries"); + if (craftVp != null) craftVp.jumpTo(0); + }); + cy += 14; + + int selAreaH = SEL_LIST_MAX_VIS * SEL_ITEM_H; + + DirectScrollViewport craftViewport = getOrCreateViewport(selectedScrollViewports, "_craft_entries", + x, cy, w, selAreaH, SEL_ITEM_H, SCROLLBAR_W); + craftViewport.setContentHeight(craftEntries.size() * SEL_ITEM_H); + + craftViewport.renderScrollbar(ctx, mx, my); + + int sbGap = SCROLLBAR_W + 2; + if (!craftEntries.isEmpty()) { + craftViewport.beginRender(ctx, theme.borderSoft(), 0x36000000); + int firstSel = craftViewport.getFirstVisibleRow(); + for (int i = firstSel; i < craftEntries.size() && i <= craftViewport.getLastVisibleRow(); i++) { + int siy = craftViewport.getRowScreenY(i); + if (siy == Integer.MIN_VALUE) continue; + CraftAction.CraftEntry entry = craftEntries.get(i); + boolean useMax = toggleStates.getOrDefault("craft_useMax_" + i, false); + + int removeX = x + w - sbGap - removeW; + final int fi = i; + renderIconDeleteButton(ctx, removeX, siy + 1, removeW, mx, my, () -> { + craftEntries.remove(fi); + rebuildCraftFields(); + DirectScrollViewport vp = selectedScrollViewports.get("_craft_entries"); + if (vp != null) vp.scrollBy(-1); + }); + + int maxX = removeX - 3 - maxTogW; + String mLbl = useMax ? "Max: On" : "Max: Off"; + final int fii = i; + renderOverlayToggleButton( + ctx, + maxX, + siy + 1, + maxTogW, + 13, + mLbl, + useMax, + "macro-craft-use-max:" + fii, + mx, + my, + () -> toggleStates.put("craft_useMax_" + fii, + !toggleStates.getOrDefault("craft_useMax_" + fii, false)) + ); + + if (!useMax) { + int amtX = maxX - 3 - amountW; + AutismChatField af = textFields.get("craft_amount_" + i); + if (af != null) { af.setX(amtX); af.setY(siy + 1); af.setWidth(amountW); af.render(ctx, mx, my, delta); } + } + + int nameW = useMax ? (maxX - 3 - x) : (maxX - 3 - amountW - 3 - x); + boolean rowHovered = mx >= x && mx < x + nameW && my >= siy && my < siy + 13; + MacroTypedListControl.renderRow( + ctx, + textRenderer, + entry.resultNameComponent(), + UiBounds.of(x, siy, Math.max(1, nameW), 13), + rowHovered, + false, + useMax ? CompactListRenderer.RowTone.READY : CompactListRenderer.RowTone.NORMAL, + true + ); + } + craftViewport.endRender(ctx); + } else { + CompactListRenderer.drawEmptyState(ctx, textRenderer, "No craft entries yet.", x, cy, w - SCROLLBAR_W - 1); + } + cy += selAreaH; + + CompactSurfaces.divider(ctx, x, cy + 2, w, AutismColors.subPanelBorder()); + cy += 6; + + int refreshW = 44; + AutismChatField srchF = addFields.get("_craft_search"); + if (srchF != null) { + srchF.setX(x); srchF.setY(cy); srchF.setWidth(w - refreshW - 3); + srchF.render(ctx, mx, my, delta); + } + int rfX = x + w - refreshW; + renderOverlayButton(ctx, rfX, cy, refreshW, 14, "Reload", + CompactOverlayButton.Variant.SECONDARY, true, mx, my, this::refreshCraftRecipes); + cy += 16; + + String query = srchF != null ? srchF.getText() : ""; + if (!query.equals(craftLastQuery)) { + craftFilteredRecipes = AutismCraftingHelper.filterRecipes( + craftAllRecipes != null ? craftAllRecipes : List.of(), query); + craftLastQuery = query; + craftRecipeScrollOffset = 0; + if (craftSelectedRecipe != null + && (craftFilteredRecipes == null || !craftFilteredRecipes.contains(craftSelectedRecipe))) + craftSelectedRecipe = null; + } + List filtered = + craftFilteredRecipes != null ? craftFilteredRecipes : List.of(); + + int recipeListH = CRAFT_LIST_H; + + DirectScrollViewport recipeViewport = getOrCreateViewport(catalogScrollViewports, "_craft_recipe_browser", + x, cy, w, recipeListH, CATALOG_ITEM_H, SCROLLBAR_W); + recipeViewport.setContentHeight(filtered.size() * CATALOG_ITEM_H); + craftRecipeListBounds = new int[]{cy, recipeListH}; + + recipeViewport.renderScrollbar(ctx, mx, my); + + int recW = w - SCROLLBAR_W - 1; + if (filtered.isEmpty()) { + CompactListRenderer.drawEmptyState( + ctx, + textRenderer, + craftAllRecipes == null || craftAllRecipes.isEmpty() + ? "No crafting recipes loaded. Use Reload." + : "No recipes match the search.", + x, + cy, + recW + ); + } else { + recipeViewport.beginRender(ctx, theme.borderSoft(), 0x36000000); + int firstRec = recipeViewport.getFirstVisibleRow(); + for (int i = firstRec; i < filtered.size() && i <= recipeViewport.getLastVisibleRow(); i++) { + int ry = recipeViewport.getRowScreenY(i); + if (ry == Integer.MIN_VALUE) continue; + AutismCraftingHelper.CraftableRecipeOption opt = filtered.get(i); + boolean inList = craftEntries.stream().anyMatch(e -> + (opt.recipeKey != null && opt.recipeKey.equals(e.recipeKey)) + || (opt.recipeId >= 0 && opt.recipeId == e.recipeId)); + boolean hov = !inList && mx >= x && mx < x + recW && my >= ry && my < ry + CATALOG_ITEM_H; + CompactListRenderer.RowTone tone = inList + ? CompactListRenderer.RowTone.READY + : (opt.craftableNow ? CompactListRenderer.RowTone.NORMAL : CompactListRenderer.RowTone.MISSING); + MacroTypedListControl.renderRow(ctx, textRenderer, opt.labelComponent, + UiBounds.of(x, ry, recW, CATALOG_ITEM_H), hov, inList, tone, true); + if (opt.result != null && opt.result.getCount() > 1) { + String cnt = "\u00d7" + opt.result.getCount(); + UiText.draw(ctx, textRenderer, cnt, font, AutismColors.textDim(), + x + recW - uiWidth(font, cnt) - 2, ry + 2, false); + } + final AutismCraftingHelper.CraftableRecipeOption fOpt = opt; + final boolean fInList = inList; + hitRegions.add(new HitRegion(x, ry, recW, CATALOG_ITEM_H, () -> { + if (fInList) { + craftEntries.removeIf(e -> + (fOpt.recipeKey != null && fOpt.recipeKey.equals(e.recipeKey)) + || (fOpt.recipeId >= 0 && fOpt.recipeId == e.recipeId)); + rebuildCraftFields(); + } else { + CraftAction.CraftEntry newEntry = CraftAction.CraftEntry.fromOption(fOpt, 1, false); + craftEntries.add(newEntry); + int idx = craftEntries.size() - 1; + AutismChatField f = makeField(44); + f.setNumericOnly(true); + f.setText("1"); + textFields.put("craft_amount_" + idx, f); + toggleStates.put("craft_useMax_" + idx, false); + } + })); + } + recipeViewport.endRender(ctx); + } + } + + private void refreshCraftRecipes() { + craftAllRecipes = AutismCraftingHelper.getCraftableRecipes(MC); + craftLastQuery = null; + craftSelectedRecipe = null; + craftRecipeScrollOffset = 0; + } + + private void addCraftEntry() { + if (craftSelectedRecipe == null) return; + AutismChatField amtF = textFields.get("_craft_amount"); + int amount = 1; + if (amtF != null && !craftUseMax) { + try { amount = Math.max(1, Integer.parseInt(amtF.getText().strip())); } + catch (NumberFormatException ignored) { } + } + CraftAction.CraftEntry newEntry = CraftAction.CraftEntry.fromOption(craftSelectedRecipe, amount, craftUseMax); + + for (int i = 0; i < craftEntries.size(); i++) { + CraftAction.CraftEntry existing = craftEntries.get(i); + if ((newEntry.recipeKey != null && newEntry.recipeKey.equals(existing.recipeKey)) + || (newEntry.recipeId >= 0 && newEntry.recipeId == existing.recipeId)) { + existing.amount = newEntry.amount; + existing.useMaxAmount = newEntry.useMaxAmount; + toggleStates.put("craft_useMax_" + i, newEntry.useMaxAmount); + AutismChatField f = textFields.get("craft_amount_" + i); + if (f != null) f.setText(String.valueOf(newEntry.amount)); + return; + } + } + + craftEntries.add(newEntry); + int idx = craftEntries.size() - 1; + AutismChatField f = makeField(44); + f.setNumericOnly(true); + f.setText(String.valueOf(newEntry.amount)); + textFields.put("craft_amount_" + idx, f); + toggleStates.put("craft_useMax_" + idx, newEntry.useMaxAmount); + } + + private void rebuildCraftFields() { + textFields.keySet().removeIf(k -> k.startsWith("craft_amount_")); + for (int i = 0; i < craftEntries.size(); i++) { + CraftAction.CraftEntry entry = craftEntries.get(i); + AutismChatField f = makeField(44); + f.setNumericOnly(true); + f.setText(String.valueOf(entry.amount)); + textFields.put("craft_amount_" + i, f); + if (!toggleStates.containsKey("craft_useMax_" + i)) + toggleStates.put("craft_useMax_" + i, entry.useMaxAmount); + } + toggleStates.keySet().removeIf(k -> { + if (!k.startsWith("craft_useMax_")) return false; + try { return Integer.parseInt(k.substring("craft_useMax_".length())) >= craftEntries.size(); } + catch (NumberFormatException e) { return true; } + }); + } + + private void renderDropPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + int headerBtnW = 44; + + UiText.draw(ctx, textRenderer, + "Drop Entries (" + dropAction.itemNames.size() + ")", font, + AutismColors.textSecondary(), x, cy + 2, false); + boolean canClearAll = !dropAction.itemNames.isEmpty(); + int clearX = x + w - headerBtnW; + renderOverlayButton(ctx, clearX, cy, headerBtnW, 14, "Clear", + CompactOverlayButton.Variant.DANGER, canClearAll, mx, my, () -> { + dropAction.itemNames.clear(); + dropAction.itemCounts.clear(); + clearDropEditSelection(); + rebuildDropFields(); + }); + cy += 14; + + int selAreaH = SEL_LIST_MAX_VIS * SEL_ITEM_H; + + DirectScrollViewport dropViewport = getOrCreateViewport(selectedScrollViewports, "_drop_entries", + x, cy, w, selAreaH, SEL_ITEM_H, SCROLLBAR_W); + dropViewport.setContentHeight(dropAction.itemNames.size() * SEL_ITEM_H); + + dropViewport.renderScrollbar(ctx, mx, my); + + int sbGap = SCROLLBAR_W + 2; + int delW = 13; + int dropItemW = w - sbGap - delW - 2; + + if (!dropAction.itemNames.isEmpty()) { + dropViewport.beginRender(ctx, theme.borderSoft(), 0x36000000); + int firstVis = dropViewport.getFirstVisibleRow(); + for (int i = firstVis; i < dropAction.itemNames.size() && i <= dropViewport.getLastVisibleRow(); i++) { + int iy = dropViewport.getRowScreenY(i); + if (iy == Integer.MIN_VALUE) continue; + String entry = dropAction.itemNames.get(i); + boolean selected = i == dropEditIndex; + + ItemTarget entryTarget = targetAt(dropAction.itemTargets, dropAction.itemNames, i); + Component displayName = formatItemTargetText(entryTarget, entry); + + int cnt = i < dropAction.itemCounts.size() ? dropAction.itemCounts.get(i) : 0; + String summary = " \u2022 " + (cnt == 0 ? "all" : "\u00d7" + cnt); + Component rowLabel = Component.empty().append(displayName).append( + Component.literal(summary).withStyle(s -> s.withColor(0xFF888888))); + + boolean rowHovered = mx >= x && mx < x + dropItemW && my >= iy && my < iy + 13; + MacroTypedListControl.renderRow( + ctx, + textRenderer, + rowLabel, + UiBounds.of(x, iy, dropItemW, 13), + rowHovered, + selected, + CompactListRenderer.RowTone.NORMAL, + true + ); + + if (iy + 13 > cy && iy < cy + selAreaH) { + final int fi = i; + hitRegions.add(new HitRegion(x, Math.max(cy, iy), dropItemW, Math.min(iy + 13, cy + selAreaH) - Math.max(cy, iy), () -> toggleDropEditSelection(fi))); + } + + if (iy + 13 > cy && iy < cy + selAreaH) { + int delX = x + dropItemW + 2; + final int fi = i; + renderIconDeleteButton(ctx, delX, iy, delW, mx, my, () -> { + dropAction.itemNames.remove(fi); + if (fi < dropAction.itemTargets.size()) dropAction.itemTargets.remove(fi); + if (fi < dropAction.itemCounts.size()) dropAction.itemCounts.remove(fi); + if (dropEditIndex == fi) clearDropEditSelection(); + else if (dropEditIndex > fi) dropEditIndex--; + rebuildDropFields(); + DirectScrollViewport vp = selectedScrollViewports.get("_drop_entries"); + if (vp != null) vp.scrollBy(-1); + }); + } + } + dropViewport.endRender(ctx); + } else { + CompactListRenderer.drawEmptyState(ctx, textRenderer, "No entries yet. Add an item or exact slot.", x, cy, w - SCROLLBAR_W - 1); + } + cy += selAreaH; + + CompactSurfaces.divider(ctx, x, cy + 2, w, AutismColors.subPanelBorder()); + cy += 6; + + int addPickW = 32; + int addBtnW = 34; + int slotW = 44; + AutismChatField addF = addFields.get("_drop_add"); + AutismChatField entrySlotF = textFields.get("drop_entrySlot"); + if (addF != null && entrySlotF != null) { + int pickX = x + w - addBtnW - 3 - addPickW; + int plusX = x + w - addBtnW; + int slotX = pickX - 3 - slotW; + addF.setX(x); addF.setY(cy + 1); addF.setWidth(slotX - x - 2); + addF.render(ctx, mx, my, delta); + entrySlotF.setX(slotX); entrySlotF.setY(cy + 1); entrySlotF.setWidth(slotW); + entrySlotF.render(ctx, mx, my, delta); + + boolean capturing = captureSession.isItemSlotCapture("_drop_entries"); + renderFieldCaptureButton( + ctx, + pickX, + cy, + addPickW, + 14, + CaptureMode.ITEM_SLOT, + capturing, + true, + mx, + my, + () -> { + toggleItemSlotCapture("_drop_entries"); + }); + + String addLbl = dropEditIndex >= 0 ? "New" : "+Add"; + renderOverlayButton(ctx, plusX, cy, addBtnW, 14, addLbl, + CompactOverlayButton.Variant.SUCCESS, true, mx, my, () -> { + if (dropEditIndex >= 0) clearDropEditSelection(); + else applyDropEntryEditor(); + }); + } + cy += 16; + cy += 4; + boolean editingSelectedDrop = dropEditIndex >= 0 && dropEditIndex < dropAction.itemNames.size(); + + String dropHint = editingSelectedDrop + ? "Editing this row. 0 means drop the full stack from that slot or item." + : "No row selected. The controls below set defaults for new rows you add."; + cy = renderEditorHint(ctx, x, cy, w, dropHint); + + { + boolean dropAllSelected = editingSelectedDrop + ? getDropEntryCount(dropEditIndex) == 0 + : dropAction.mode == autismclient.util.macro.DropAction.DropMode.ALL; + int lw = labelWidth(w, editingSelectedDrop ? "Selected Row" : "Default Mode", font); + drawLabel(ctx, editingSelectedDrop ? "Selected Row" : "Default Mode", x, cy, lw, font); + int ctrlX = controlX(x, lw); + int ctrlW = controlWidth(w, lw); + int leftW = (ctrlW - 2) / 2; + int rightX = ctrlX + leftW + 2; + int rightW = ctrlW - leftW - 2; + renderOverlayButton(ctx, ctrlX, cy + 2, leftW, 14, "Drop All", + dropAllSelected ? CompactOverlayButton.Variant.PRIMARY : CompactOverlayButton.Variant.GHOST, + true, mx, my, () -> { + if (dropEditIndex >= 0 && dropEditIndex < dropAction.itemNames.size()) { + setDropEntryCount(dropEditIndex, 0); + } else { + enumIndices.put("drop_mode", 0); + dropAction.mode = autismclient.util.macro.DropAction.DropMode.ALL; + } + syncDropCountEditorField(); + }); + renderOverlayButton(ctx, rightX, cy + 2, rightW, 14, "Times", + !dropAllSelected ? CompactOverlayButton.Variant.SUCCESS : CompactOverlayButton.Variant.GHOST, + true, mx, my, () -> { + if (dropEditIndex >= 0 && dropEditIndex < dropAction.itemNames.size()) { + setDropEntryCount(dropEditIndex, Math.max(1, getDropEntryCount(dropEditIndex))); + } else { + enumIndices.put("drop_mode", 1); + dropAction.mode = autismclient.util.macro.DropAction.DropMode.TIMES; + } + syncDropCountEditorField(); + }); + } + cy += ROW_H + ROW_GAP; + + AutismChatField cntF = textFields.get("drop_globalCount"); + syncDropCountEditorField(); + if (cntF != null) { + int lw = labelWidth(w, editingSelectedDrop ? "Selected Count" : "Default Count", font); + drawLabel(ctx, editingSelectedDrop ? "Selected Count" : "Default Count", x, cy, lw, font); + cntF.setX(controlX(x, lw)); cntF.setY(cy + 2); cntF.setWidth(controlWidth(w, lw)); + cntF.render(ctx, mx, my, delta); + cy += ROW_H + ROW_GAP; + } + + renderGuiWaitRow(ctx, font, "drop_waitForGuiBefore", "drop_waitForGuiAfter", x, cy, w, mx, my); + cy += ROW_H + ROW_GAP; + + if (toggleStates.getOrDefault("drop_waitForGuiBefore", false) + || toggleStates.getOrDefault("drop_waitForGuiAfter", false)) { + AutismChatField guiF = textFields.get("drop_guiName"); + if (guiF != null) { + int lw = labelWidth(w, "GUI Name", font); + drawLabel(ctx, "GUI Name", x, cy, lw, font); + guiF.setX(controlX(x, lw)); guiF.setY(cy + 2); guiF.setWidth(controlWidth(w, lw)); + guiF.render(ctx, mx, my, delta); + } + cy += ROW_H + ROW_GAP; + } else { + AutismChatField guiF = textFields.get("drop_guiName"); + if (guiF != null) guiF.setX(-1000); + } + + } + + private void addDropEntry(ItemTarget target, int count) { + if (target == null) return; + String entry = target.toLegacyEntry(); + if (entry.isEmpty()) return; + addTargetEntry(dropAction.itemTargets, dropAction.itemNames, target); + int safeCount = Math.max(0, count); + dropAction.itemCounts.add(safeCount); + int idx = dropAction.itemNames.size() - 1; + AutismChatField f = makeField(32); + f.setNumericOnly(true); + f.setText(String.valueOf(safeCount)); + final int fieldIndex = idx; + f.setChangedListener(text -> { + try { + setDropEntryCount(fieldIndex, Math.max(0, Integer.parseInt(text.strip()))); + if (fieldIndex == dropEditIndex) syncDropCountEditorField(); + } catch (NumberFormatException ignored) { } + }); + textFields.put("drop_count_" + idx, f); + } + + private void rebuildDropFields() { + textFields.keySet().removeIf(k -> k.startsWith("drop_count_")); + trimTargetEntries(dropAction.itemTargets, dropAction.itemNames.size()); + while (dropAction.itemCounts.size() > dropAction.itemNames.size()) + dropAction.itemCounts.remove(dropAction.itemCounts.size() - 1); + for (int i = 0; i < dropAction.itemNames.size(); i++) { + AutismChatField f = makeField(32); + f.setNumericOnly(true); + f.setText(String.valueOf(dropAction.itemCounts.get(i))); + final int fieldIndex = i; + f.setChangedListener(text -> { + try { + setDropEntryCount(fieldIndex, Math.max(0, Integer.parseInt(text.strip()))); + if (fieldIndex == dropEditIndex) syncDropCountEditorField(); + } catch (NumberFormatException ignored) { } + }); + textFields.put("drop_count_" + i, f); + } + } + + private void toggleDropEditSelection(int index) { + if (dropEditIndex == index) { + clearDropEditSelection(); + return; + } + dropEditIndex = index; + syncDropEntryEditorFromSelection(); + syncDropCountEditorField(); + } + + private void clearDropEditSelection() { + dropEditIndex = -1; + AutismChatField addF = addFields.get("_drop_add"); + suppressDropEntryLiveUpdate = true; + if (addF != null) addF.setText(""); + AutismChatField slotF = textFields.get("drop_entrySlot"); + if (slotF != null) slotF.setText(""); + suppressDropEntryLiveUpdate = false; + syncDropCountEditorField(); + } + + private void syncDropEntryEditorFromSelection() { + AutismChatField addF = addFields.get("_drop_add"); + AutismChatField slotF = textFields.get("drop_entrySlot"); + if (addF == null || slotF == null) return; + suppressDropEntryLiveUpdate = true; + if (dropEditIndex < 0 || dropEditIndex >= dropAction.itemNames.size()) { + addF.setText(""); + slotF.setText(""); + suppressDropEntryLiveUpdate = false; + return; + } + ItemTarget target = targetAt(dropAction.itemTargets, dropAction.itemNames, dropEditIndex); + addF.setText(target.editorText()); + slotF.setText(target.hasSlot() ? String.valueOf(target.slot) : ""); + suppressDropEntryLiveUpdate = false; + syncDropCountEditorField(); + } + + private void applyDropEntryEditor() { + applyDropEntryEditor(false); + } + + private void handleDropEntryEditorChanged() { + if (suppressDropEntryLiveUpdate || dropAction == null) return; + if (dropEditIndex < 0 || dropEditIndex >= dropAction.itemNames.size()) return; + applyDropEntryEditor(true); + } + + private void applyDropEntryEditor(boolean preserveSelection) { + if (dropAction == null) return; + AutismChatField addF = addFields.get("_drop_add"); + AutismChatField slotF = textFields.get("drop_entrySlot"); + if (addF == null || slotF == null) return; + String nameText = addF.getText().strip(); + String slotText = slotF.getText().strip(); + ItemTarget target = buildEntryTargetFromEditor(nameText, slotText, targetAt(dropAction.itemTargets, dropAction.itemNames, dropEditIndex)); + String entry = target.toLegacyEntry(); + if (entry.isBlank()) return; + + if (dropEditIndex >= 0 && dropEditIndex < dropAction.itemNames.size()) { + if (!containsEntryOtherThan(dropAction.itemNames, entry, dropEditIndex)) { + setTargetAt(dropAction.itemTargets, dropAction.itemNames, dropEditIndex, target); + } + } else if (!dropAction.itemNames.contains(entry)) { + addDropEntry(target, currentDropEditorCount()); + } + + if (!preserveSelection) { + clearDropEditSelection(); + } + } + + private void applyCapturedDropEntry(ItemTarget rawTarget) { + if (dropAction == null) return; + + ItemTarget target = storeCaptureTarget(rawTarget); + String entry = target == null ? "" : target.toLegacyEntry(); + if (entry.isBlank()) return; + + int targetIndex = dropEditIndex; + if (targetIndex >= 0 && targetIndex < dropAction.itemNames.size()) { + if (!containsEntryOtherThan(dropAction.itemNames, entry, targetIndex)) { + setTargetAt(dropAction.itemTargets, dropAction.itemNames, targetIndex, target.copy()); + } + } else { + targetIndex = dropAction.itemNames.indexOf(entry); + if (targetIndex < 0) { + addDropEntry(target.copy(), currentDropEditorCount()); + targetIndex = dropAction.itemNames.size() - 1; + } + } + + dropEditIndex = targetIndex; + syncDropEntryEditorFromSelection(); + syncDropCountEditorField(); + } + + private int currentDropEditorCount() { + AutismChatField globalCountField = textFields.get("drop_globalCount"); + if (dropEditIndex >= 0 && dropEditIndex < dropAction.itemCounts.size()) { + return Math.max(0, dropAction.itemCounts.get(dropEditIndex)); + } + if (enumIndices.getOrDefault("drop_mode", 0) == 0) { + return 0; + } + if (globalCountField != null) { + try { + return Math.max(0, Integer.parseInt(globalCountField.getText().strip())); + } catch (NumberFormatException ignored) { } + } + return Math.max(0, dropAction.dropCount); + } + + private int getDropEntryCount(int index) { + if (dropAction == null || index < 0 || index >= dropAction.itemNames.size()) return 1; + while (dropAction.itemCounts.size() <= index) dropAction.itemCounts.add(1); + return Math.max(0, dropAction.itemCounts.get(index)); + } + + private void setDropEntryCount(int index, int count) { + if (dropAction == null || index < 0 || index >= dropAction.itemNames.size()) return; + while (dropAction.itemCounts.size() <= index) dropAction.itemCounts.add(1); + int safeCount = Math.max(0, count); + dropAction.itemCounts.set(index, safeCount); + AutismChatField rowField = textFields.get("drop_count_" + index); + if (rowField != null) rowField.setText(String.valueOf(safeCount)); + } + + private void syncDropCountEditorField() { + if (dropAction == null) return; + AutismChatField countField = textFields.get("drop_globalCount"); + if (countField == null) return; + + boolean editingSelectedDrop = dropEditIndex >= 0 && dropEditIndex < dropAction.itemNames.size(); + boolean dropAll = editingSelectedDrop + ? getDropEntryCount(dropEditIndex) == 0 + : dropAction.mode == autismclient.util.macro.DropAction.DropMode.ALL; + int displayCount = editingSelectedDrop + ? Math.max(1, getDropEntryCount(dropEditIndex)) + : Math.max(1, dropAction.dropCount); + + suppressDropCountEditorUpdate = true; + countField.setText(String.valueOf(displayCount)); + countField.setEditable(!dropAll); + suppressDropCountEditorUpdate = false; + } + + private void handleDropCountEditorChanged() { + if (suppressDropCountEditorUpdate || dropAction == null) return; + AutismChatField countField = textFields.get("drop_globalCount"); + if (countField == null) return; + + boolean editingSelectedDrop = dropEditIndex >= 0 && dropEditIndex < dropAction.itemNames.size(); + boolean dropAll = editingSelectedDrop + ? getDropEntryCount(dropEditIndex) == 0 + : dropAction.mode == autismclient.util.macro.DropAction.DropMode.ALL; + if (dropAll) return; + + try { + int value = Math.max(1, Integer.parseInt(countField.getText().strip())); + if (editingSelectedDrop) { + setDropEntryCount(dropEditIndex, value); + } else { + dropAction.dropCount = value; + } + } catch (NumberFormatException ignored) { } + } + + private void renderLanStepPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + boolean filterByUser = toggleStates.getOrDefault("lan_filterByUser", false); + + renderInlineToggle(ctx, font, MacroAction.LISTEN_DURING_PREVIOUS_KEY, + "Listen During Previous", x, cy, w, mx, my); + cy += ROW_H + ROW_GAP; + + renderInlineToggle(ctx, font, "lan_filterByUser", "Specific Peers", x, cy, w, mx, my); + cy += ROW_H + ROW_GAP; + + AutismChatField dsF = textFields.get("lan_defaultStep"); + if (dsF != null && (!filterByUser || lanStepEntries.isEmpty())) { + int lw = labelWidth(w, filterByUser ? "Fallback Step" : "Any Peer Step", font); + drawLabel(ctx, filterByUser ? "Fallback Step" : "Any Peer Step", x, cy, lw, font); + dsF.setX(controlX(x, lw)); dsF.setY(cy + 2); dsF.setWidth(controlWidth(w, lw)); + dsF.render(ctx, mx, my, delta); + cy += ROW_H + ROW_GAP; + } + + String summary = !filterByUser + ? "Continue when any LAN peer reaches the target step." + : lanStepEntries.isEmpty() + ? "Add peers below to narrow it down. Until then, it waits for any peer at the fallback step." + : "Each peer below must reach its step before this continues."; + cy = renderEditorHint(ctx, x, cy, w, summary); + + if (!filterByUser) return; + + if (!lanStepEntries.isEmpty()) { + UiText.draw(ctx, textRenderer, + "Peers (" + lanStepEntries.size() + ")", font, + AutismColors.textSecondary(), x, cy + 2, false); + cy += 13; + } + + boolean hasEntries = !lanStepEntries.isEmpty(); + int visibleRows = hasEntries ? Math.min(3, Math.max(1, lanStepEntries.size())) : 1; + int selAreaH = hasEntries ? visibleRows * SEL_ITEM_H : 12; + + DirectScrollViewport lanViewport = null; + if (hasEntries) { + lanViewport = getOrCreateViewport(selectedScrollViewports, "_lan_entries", + x, cy, w, selAreaH, SEL_ITEM_H, SCROLLBAR_W); + lanViewport.setContentHeight(lanStepEntries.size() * SEL_ITEM_H); + } + + if (hasEntries && lanViewport != null) { + lanViewport.renderScrollbar(ctx, mx, my); + } + + int sbGap = SCROLLBAR_W + 2; + int removeW = 13; + int stepW = 40; + int gapPx = 2; + int removeX = x + w - sbGap - removeW; + int stepX = removeX - gapPx - stepW; + int userW = stepX - x - gapPx; + + if (hasEntries && lanViewport != null) { + lanViewport.beginRender(ctx, theme.borderSoft(), 0x36000000); + int firstVis = lanViewport.getFirstVisibleRow(); + for (int i = firstVis; i < lanStepEntries.size() && i <= lanViewport.getLastVisibleRow(); i++) { + int iy = lanViewport.getRowScreenY(i); + if (iy == Integer.MIN_VALUE) continue; + + CompactSurfaces.valueField(ctx, x, iy, stepX - gapPx - x, 13); + + AutismChatField uf = textFields.get("lan_user_" + i); + if (uf != null) { uf.setX(x); uf.setY(iy + 1); uf.setWidth(userW); uf.render(ctx, mx, my, delta); } + + AutismChatField sf = textFields.get("lan_step_" + i); + if (sf != null) { sf.setX(stepX); sf.setY(iy + 1); sf.setWidth(stepW); sf.render(ctx, mx, my, delta); } + + final int fi = i; + renderIconDeleteButton(ctx, removeX, iy + 1, removeW, mx, my, () -> { + lanStepEntries.remove(fi); + rebuildLanStepFields(); + DirectScrollViewport vp = selectedScrollViewports.get("_lan_entries"); + if (vp != null) vp.scrollBy(-1); + }); + } + lanViewport.endRender(ctx); + } else { + CompactListRenderer.drawEmptyState(ctx, textRenderer, "No peer filters yet.", x, cy, w - SCROLLBAR_W - 1); + } + cy += selAreaH; + + CompactSurfaces.divider(ctx, x, cy + 2, w, AutismColors.subPanelBorder()); + cy += 6; + + int addBtnW = 36; + AutismChatField newUF = addFields.get("_lan_user_add"); + AutismChatField newSF = addFields.get("_lan_step_add"); + if (newUF != null && newSF != null) { + int plusX = x + w - addBtnW; + int stepAX = plusX - 3 - stepW; + int userAW = stepAX - x - 2; + newUF.setX(x); newUF.setY(cy + 1); newUF.setWidth(userAW); + newUF.render(ctx, mx, my, delta); + newSF.setX(stepAX); newSF.setY(cy + 1); newSF.setWidth(stepW); + newSF.render(ctx, mx, my, delta); + + renderOverlayButton(ctx, plusX, cy, addBtnW, 14, "+Add", + CompactOverlayButton.Variant.SUCCESS, true, mx, my, () -> { + String uname = newUF.getText().strip(); + int step = 1; + try { step = Math.max(1, Integer.parseInt(newSF.getText().strip())); } catch (NumberFormatException ignored) { } + lanStepEntries.add(new autismclient.util.macro.WaitForLanStepAction.LanStepEntry(uname, step)); + int idx = lanStepEntries.size() - 1; + AutismChatField uf2 = makeField(80); uf2.setText(uname); + textFields.put("lan_user_" + idx, uf2); + AutismChatField sf2 = makeField(40); sf2.setNumericOnly(true); sf2.setText(String.valueOf(step)); + textFields.put("lan_step_" + idx, sf2); + newUF.setText(""); newSF.setText("1"); + }); + } + } + + private void rebuildLanStepFields() { + textFields.keySet().removeIf(k -> k.startsWith("lan_user_") || k.startsWith("lan_step_")); + for (int i = 0; i < lanStepEntries.size(); i++) { + autismclient.util.macro.WaitForLanStepAction.LanStepEntry e = lanStepEntries.get(i); + AutismChatField uf = makeField(80); uf.setText(e.username); + textFields.put("lan_user_" + i, uf); + AutismChatField sf = makeField(40); sf.setNumericOnly(true); sf.setText(String.valueOf(e.step)); + textFields.put("lan_step_" + i, sf); + } + } + + private void renderPacketActionButtons(GuiGraphicsExtractor ctx, int x, int y, int w, int mx, int my) { + Identifier font = theme.fontFor(UiTone.BODY); + int btnH = 14; + int halfW = (w - 4) / 2; + int topY = y + 2; + int bottomY = y + 20; + + String info = buildPacketActionInfo(); + UiText.draw(ctx, textRenderer, + UiText.trimToWidth(textRenderer, info, w, font, -1), + font, AutismColors.textDim(), x, y - 10, false); + + renderActionButton(ctx, x, topY, halfW, btnH, "Queue First", mx, my, () -> { + List queue = AutismSharedState.get().getDelayedPackets(); + if (queue == null || queue.isEmpty()) { + AutismClientMessaging.sendPrefixed("Queue is empty"); + return; + } + setRawPacketActionData(queue.get(0)); + AutismClientMessaging.sendPrefixed("Loaded first queued packet"); + }); + renderActionButton(ctx, x + halfW + 4, topY, halfW, btnH, "Paste Base64", mx, my, () -> { + List pasted = AutismClipboardHelper.pasteFromClipboard(); + if (pasted == null || pasted.isEmpty()) { + AutismClientMessaging.sendPrefixed("Failed to paste packet data"); + return; + } + setRawPacketActionData(pasted.get(0)); + AutismClientMessaging.sendPrefixed("Loaded first pasted packet"); + }); + renderActionButton(ctx, x, bottomY, w, btnH, "Clear Raw Packet", mx, my, () -> { + workingTag.putString("packetData", ""); + AutismClientMessaging.sendPrefixed("Cleared raw packet data"); + }); + } + + private void renderWaitPacketPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + int halfW = (w - 4) / 2; + List c2sTargets = getWaitPacketTargets("C2S"); + List s2cTargets = getWaitPacketTargets("S2C"); + + String summary = c2sTargets.isEmpty() && s2cTargets.isEmpty() + ? "No packets selected. This step will continue on the next packet in either direction." + : "This step continues as soon as any selected C2S or S2C packet arrives."; + cy = renderEditorHint(ctx, x, cy, w, summary); + + renderInlineToggle(ctx, font, MacroAction.LISTEN_DURING_PREVIOUS_KEY, "Listen During Previous", x, cy, w, mx, my); + cy += 18; + cy = renderFieldByKey(ctx, "saveAs", x, cy, w, mx, my, delta); + + renderActionButton(ctx, x, cy, halfW, 14, "Add C2S", mx, my, () -> openWaitPacketSelector(true)); + renderActionButton(ctx, x + halfW + 4, cy, halfW, 14, "Add S2C", mx, my, () -> openWaitPacketSelector(false)); + cy += 18; + + renderActionButton(ctx, x, cy, halfW, 14, "Load Queue", mx, my, this::loadWaitPacketTargetsFromQueue); + renderActionButton(ctx, x + halfW + 4, cy, halfW, 14, "Clear All", mx, my, () -> { + getOrCreateWaitPacketTargets().clear(); + DirectScrollViewport vpC2s = selectedScrollViewports.get("wait_packet_c2s"); + if (vpC2s != null) vpC2s.jumpTo(0); + DirectScrollViewport vpS2c = selectedScrollViewports.get("wait_packet_s2c"); + if (vpS2c != null) vpS2c.jumpTo(0); + }); + cy += 20; + + cy = renderSimpleSelectedList( + ctx, + x, + cy, + w, + mx, + my, + "wait_packet_c2s", + "C2S Packets", + c2sTargets, + this::removeWaitPacketTarget, + this::formatWaitPacketTarget, + ignored -> null, + () -> clearWaitPacketTargets("C2S"), + "No C2S packets selected" + ); + cy += 4; + + renderSimpleSelectedList( + ctx, + x, + cy, + w, + mx, + my, + "wait_packet_s2c", + "S2C Packets", + s2cTargets, + this::removeWaitPacketTarget, + this::formatWaitPacketTarget, + ignored -> null, + () -> clearWaitPacketTargets("S2C"), + "No S2C packets selected" + ); + } + + private void renderWaitPacketMatchPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + if (waitPacketMatchRules == null) waitPacketMatchRules = new ArrayList<>(); + if (waitPacketMatchEditIndex >= waitPacketMatchRules.size()) waitPacketMatchEditIndex = waitPacketMatchRules.isEmpty() ? -1 : 0; + + cy = renderEditorHint(ctx, x, cy, w, "Add a packet, then set field + rule."); + renderInlineToggle(ctx, font, MacroAction.LISTEN_DURING_PREVIOUS_KEY, "Listen During Previous", x, cy, w, mx, my); + cy += 18; + cy = renderFieldByKey(ctx, "saveAs", x, cy, w, mx, my, delta); + + int halfW = (w - 4) / 2; + renderActionButton(ctx, x, cy, halfW, 14, "Add C2S", mx, my, () -> openWaitPacketMatchSelector(true)); + renderActionButton(ctx, x + halfW + 4, cy, halfW, 14, "Add S2C", mx, my, () -> openWaitPacketMatchSelector(false)); + cy += 18; + + renderWaitPacketMatchRuleList(ctx, x, cy, w, mx, my); + cy += 13 + Math.max(1, Math.min(4, Math.max(1, waitPacketMatchRules.size()))) * SEL_ITEM_H + 5; + + if (waitPacketMatchRules.isEmpty()) { + renderEditorHint(ctx, x, cy, w, "No packet rules yet. Add C2S or S2C."); + return; + } + + final WaitPacketMatchAction.Rule rule = waitPacketMatchRules.get(Math.max(0, waitPacketMatchEditIndex)); + + java.util.List dirOpts = new ArrayList<>(); + for (WaitPacketMatchAction.Direction d : WaitPacketMatchAction.Direction.values()) dirOpts.add(d.name()); + cy = renderInlineEnumDropdown(ctx, font, "Direction", "_wpm_dir", dirOpts, rule.direction.ordinal(), x, cy, w, + i -> rule.direction = WaitPacketMatchAction.Direction.values()[i]); + + final Class> packetClass = resolveWaitPacketMatchClass(rule); + final java.util.List fieldNames = new ArrayList<>(WaitPacketMatchAction.packetFieldNames(packetClass)); + java.util.List fieldDisplay = new ArrayList<>(); + fieldDisplay.add("Packet Only"); + fieldDisplay.addAll(fieldNames); + int fieldIdx = (rule.fieldName == null || rule.fieldName.isBlank()) ? 0 : Math.max(0, fieldNames.indexOf(rule.fieldName) + 1); + cy = renderInlineEnumDropdown(ctx, font, "Field", "_wpm_field", fieldDisplay, fieldIdx, x, cy, w, i -> { + rule.fieldName = i <= 0 ? "" : fieldNames.get(i - 1); + if (rule.fieldName.isBlank()) rule.operator = WaitPacketMatchAction.Operator.EXISTS; + java.util.List vo = WaitPacketMatchAction.valueOptions(packetClass, rule.fieldName); + if (!vo.isEmpty() && (rule.value == null || rule.value.isBlank() || !vo.contains(rule.value))) rule.value = vo.get(0); + syncWaitPacketMatchValueField(); + }); + + if (rule.fieldName != null && !rule.fieldName.isBlank()) { + java.util.List opOpts = new ArrayList<>(); + for (WaitPacketMatchAction.Operator o : WaitPacketMatchAction.Operator.values()) opOpts.add(o.name()); + cy = renderInlineEnumDropdown(ctx, font, "Operator", "_wpm_op", opOpts, rule.operator.ordinal(), x, cy, w, + i -> rule.operator = WaitPacketMatchAction.Operator.values()[i]); + + if (rule.operator != WaitPacketMatchAction.Operator.EXISTS) { + java.util.List valueOptions = WaitPacketMatchAction.valueOptions(packetClass, rule.fieldName); + if (!valueOptions.isEmpty()) { + int valIdx = Math.max(0, valueOptions.indexOf(rule.value)); + cy = renderInlineEnumDropdown(ctx, font, "Value", "_wpm_value_dd", valueOptions, valIdx, x, cy, w, i -> { + rule.value = valueOptions.get(i); + syncWaitPacketMatchValueField(); + }); + } else { + AutismChatField valueField = textFields.get("_wpm_value"); + if (valueField != null) { + int lw = labelWidth(w, "Value", font, 72); + drawLabel(ctx, "Value", x, cy, lw, font); + valueField.setX(controlX(x, lw)); + valueField.setY(cy + 1); + valueField.setWidth(controlWidth(w, lw)); + valueField.render(ctx, mx, my, delta); + cy += ROW_H + ROW_GAP; + } + } + } + } + } + + private int renderInlineEnumDropdown(GuiGraphicsExtractor ctx, Identifier font, String label, String cacheKey, + java.util.List options, int selectedIdx, int x, int cy, int w, + java.util.function.IntConsumer onSelect) { + if (options.isEmpty()) return cy; + int lw = labelWidth(w, label, font, 72); + drawLabel(ctx, label, x, cy, lw, font); + int ctrlX = controlX(x, lw); + int ctrlW = controlWidth(w, lw); + int idx = Math.max(0, Math.min(selectedIdx, options.size() - 1)); + final java.util.List opts = options; + final java.util.function.IntConsumer cb = onSelect; + CompactDropdown dd = enumDropdownCache.computeIfAbsent(cacheKey, k -> + new CompactDropdown(ctrlX, cy + 1, ctrlW, 16, opts, idx, cb)); + dd.setBounds(ctrlX, cy + 1, ctrlW, 16).setOptions(opts).setSelectedIndex(idx).setOnSelect(cb); + enumDropdowns.add(dd); + return cy + ROW_H + ROW_GAP; + } + + private void renderWaitPacketMatchRuleList(GuiGraphicsExtractor ctx, int x, int y, int w, int mx, int my) { + Identifier font = theme.fontFor(UiTone.BODY); + UiText.draw(ctx, textRenderer, "Packet Rules (" + waitPacketMatchRules.size() + ")", font, AutismColors.textSecondary(), x, y + 2, false); + renderOverlayButton(ctx, x + w - 44, y, 44, 14, "Clear", CompactOverlayButton.Variant.DANGER, !waitPacketMatchRules.isEmpty(), mx, my, () -> { + waitPacketMatchRules.clear(); + waitPacketMatchEditIndex = -1; + }); + y += 14; + + int rows = Math.max(1, Math.min(4, Math.max(1, waitPacketMatchRules.size()))); + int listH = rows * SEL_ITEM_H; + int delW = 13; + if (waitPacketMatchRules.isEmpty()) { + CompactListRenderer.drawEmptyState(ctx, textRenderer, "No packet rules selected.", x, y, w - SCROLLBAR_W - 1); + return; + } + + DirectScrollViewport viewport = getOrCreateViewport(selectedScrollViewports, "_wpm_rules", + x, y, w, listH, SEL_ITEM_H, SCROLLBAR_W); + viewport.setContentHeight(waitPacketMatchRules.size() * SEL_ITEM_H); + viewport.renderScrollbar(ctx, mx, my); + int rowW = w - SCROLLBAR_W - 1 - delW - 2; + viewport.beginRender(ctx, theme.borderSoft(), 0x36000000); + for (int i = viewport.getFirstVisibleRow(); i < waitPacketMatchRules.size() && i <= viewport.getLastVisibleRow(); i++) { + int iy = viewport.getRowScreenY(i); + if (iy == Integer.MIN_VALUE) continue; + WaitPacketMatchAction.Rule rule = waitPacketMatchRules.get(i); + boolean selected = i == waitPacketMatchEditIndex; + boolean hovered = mx >= x && mx < x + rowW && my >= iy && my < iy + 13; + MacroTypedListControl.renderRow(ctx, textRenderer, formatWaitPacketMatchRule(rule), + UiBounds.of(x, iy, rowW, 13), hovered, selected, CompactListRenderer.RowTone.NORMAL, true); + final int fi = i; + hitRegions.add(new HitRegion(x, iy, rowW, 13, () -> { + syncWaitPacketMatchEditedRule(); + waitPacketMatchEditIndex = fi; + syncWaitPacketMatchValueField(); + })); + renderIconDeleteButton(ctx, x + rowW + 2, iy, delW, mx, my, () -> { + waitPacketMatchRules.remove(fi); + if (waitPacketMatchEditIndex >= waitPacketMatchRules.size()) waitPacketMatchEditIndex = waitPacketMatchRules.size() - 1; + syncWaitPacketMatchValueField(); + }); + } + viewport.endRender(ctx); + } + + private void renderSendPacketPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + + List actionPackets = getWorkingQueuedPackets(); + List queuePackets = AutismSharedState.get().getDelayedPackets(); + if (queuePackets == null) queuePackets = Collections.emptyList(); + final List finalQueuePackets = queuePackets; + + UiText.draw(ctx, textRenderer, + "Action Packets (" + actionPackets.size() + ")", font, + AutismColors.textSecondary(), x, cy + 2, false); + renderOverlayButton(ctx, x + w - 44, cy, 44, 14, "Clear", + CompactOverlayButton.Variant.DANGER, !actionPackets.isEmpty(), mx, my, () -> { + setWorkingQueuedPackets(Collections.emptyList()); + }); + cy += 14; + + cy = renderQueuedPacketList(ctx, x, cy, w, mx, my, delta, + "_send_packet_action", actionPackets, true, packetIndex -> { + List updated = getWorkingQueuedPackets(); + if (packetIndex < 0 || packetIndex >= updated.size()) return; + updated.remove(packetIndex); + setWorkingQueuedPackets(updated); + }); + + CompactSurfaces.divider(ctx, x, cy + 2, w, AutismColors.subPanelBorder()); + cy += 6; + + AutismChatField nameField = textFields.get("customName"); + if (nameField != null) { + int lw = labelWidth(w, "Name", font); + drawLabel(ctx, "Name", x, cy, lw, font); + nameField.setX(controlX(x, lw)); nameField.setY(cy + 2); nameField.setWidth(controlWidth(w, lw)); + nameField.render(ctx, mx, my, delta); + cy += ROW_H + ROW_GAP; + } + + renderGuiWaitRow(ctx, font, "waitForGuiBefore", "waitForGuiAfter", x, cy, w, mx, my); + cy += ROW_H + ROW_GAP; + + if (toggleStates.getOrDefault("waitForGuiBefore", false) + || toggleStates.getOrDefault("waitForGuiAfter", false)) { + AutismChatField guiField = textFields.get("guiName"); + if (guiField != null) { + int lw = labelWidth(w, "GUI Name", font); + drawLabel(ctx, "GUI Name", x, cy, lw, font); + guiField.setX(controlX(x, lw)); guiField.setY(cy + 2); guiField.setWidth(controlWidth(w, lw)); + guiField.render(ctx, mx, my, delta); + cy += ROW_H + ROW_GAP; + } + } else { + AutismChatField guiField = textFields.get("guiName"); + if (guiField != null) guiField.setX(-1000); + } + + cy += 2; + int halfW = (w - 4) / 2; + renderActionButton(ctx, x, cy, halfW, 14, "From Queue", mx, my, () -> { + setWorkingQueuedPackets(finalQueuePackets); + AutismClientMessaging.sendPrefixed("Loaded " + finalQueuePackets.size() + " packets from queue"); + }); + renderActionButton(ctx, x + halfW + 4, cy, halfW, 14, "Paste Base64", mx, my, () -> { + List pasted = AutismClipboardHelper.pasteFromClipboard(); + if (pasted == null || pasted.isEmpty()) { + AutismNotifications.error("Clipboard does not contain packets."); + return; + } + setWorkingQueuedPackets(pasted); + AutismClientMessaging.sendPrefixed("Pasted " + pasted.size() + " packets"); + }); + cy += 18; + renderActionButton(ctx, x, cy, halfW, 14, "Clear", mx, my, () -> { + setWorkingQueuedPackets(Collections.emptyList()); + AutismClientMessaging.sendPrefixed("Cleared packet list"); + }); + renderActionButton(ctx, x + halfW + 4, cy, halfW, 14, "GBreak", mx, my, this::startGBreakCaptureForEditor); + cy += 20; + + CompactSurfaces.divider(ctx, x, cy + 2, w, AutismColors.subPanelBorder()); + cy += 6; + + UiText.draw(ctx, textRenderer, + "Current Queue (" + finalQueuePackets.size() + ")", font, + AutismColors.textSecondary(), x, cy + 2, false); + cy += 14; + + renderQueuedPacketList(ctx, x, cy, w, mx, my, delta, + "_send_packet_queue", finalQueuePackets, false, packetIndex -> { + if (packetIndex < 0 || packetIndex >= finalQueuePackets.size()) return; + List updated = getWorkingQueuedPackets(); + updated.add(finalQueuePackets.get(packetIndex)); + setWorkingQueuedPackets(updated); + }); + } + + private int renderQueuedPacketList(GuiGraphicsExtractor ctx, int x, int y, int w, int mx, int my, float delta, + String listKey, List packets, + boolean removable, java.util.function.IntConsumer rowAction) { + Identifier font = theme.fontFor(UiTone.BODY); + int listH = SEL_LIST_MAX_VIS * SEL_ITEM_H; + + DirectScrollViewport packetViewport = getOrCreateViewport(selectedScrollViewports, listKey, + x, y, w, listH, SEL_ITEM_H, SCROLLBAR_W); + packetViewport.setContentHeight(packets.size() * SEL_ITEM_H); + + packetViewport.renderScrollbar(ctx, mx, my); + + int removeW = removable ? 13 : 0; + int textW = w - SCROLLBAR_W - 2 - (removable ? (removeW + 2) : 0); + if (packets.isEmpty()) { + UiText.draw(ctx, textRenderer, removable ? "(none - use GBreak, queue, or Paste)" : "(queue empty)", + font, AutismColors.textDim(), x, y + 2, false); + return y + listH; + } + + packetViewport.beginRender(ctx, theme.borderSoft(), 0x36000000); + int firstVis = packetViewport.getFirstVisibleRow(); + for (int i = firstVis; i < packets.size() && i <= packetViewport.getLastVisibleRow(); i++) { + int iy = packetViewport.getRowScreenY(i); + if (iy == Integer.MIN_VALUE) continue; + AutismSharedState.QueuedPacket qp = packets.get(i); + String pname = qp != null && qp.packet != null ? AutismPacketNamer.getFriendlyName(qp.packet) : "???"; + String rowText = (i + 1) + ". " + pname + " d=" + (qp != null ? qp.getDelay() : 0); + boolean hovered = mx >= x && mx < x + textW && my >= iy && my < iy + 13; + MacroTypedListControl.renderRow( + ctx, + textRenderer, + Component.literal(rowText), + UiBounds.of(x, iy, textW, 13), + hovered, + false, + CompactListRenderer.RowTone.NORMAL, + false + ); + final int rowIndex = i; + if (!removable) { + hitRegions.add(new HitRegion(x, iy, textW, 13, () -> rowAction.accept(rowIndex))); + } + + if (removable) { + int removeX = x + textW + 2; + renderIconDeleteButton(ctx, removeX, iy, removeW, mx, my, () -> rowAction.accept(rowIndex)); + } + } + packetViewport.endRender(ctx); + return y + listH; + } + + private void renderSendPacketButtons(GuiGraphicsExtractor ctx, int x, int y, int w, int mx, int my) { + Identifier font = theme.fontFor(UiTone.BODY); + int btnH = 14; + int halfW = (w - 4) / 2; + int topY = y + 2; + int bottomY = y + 20; + + String info = buildSendPacketInfo(); + UiText.draw(ctx, textRenderer, + UiText.trimToWidth(textRenderer, info, w, font, -1), + font, AutismColors.textDim(), x, y - 10, false); + + renderActionButton(ctx, x, topY, halfW, btnH, "From Queue", mx, my, () -> { + List queue = AutismSharedState.get().getDelayedPackets(); + setWorkingQueuedPackets(queue); + AutismClientMessaging.sendPrefixed("Loaded " + getWorkingQueuedPackets().size() + " packets from queue"); + }); + renderActionButton(ctx, x + halfW + 4, topY, halfW, btnH, "Paste Base64", mx, my, () -> { + List pasted = AutismClipboardHelper.pasteFromClipboard(); + if (pasted == null || pasted.isEmpty()) { + AutismNotifications.error("Clipboard does not contain packets."); + return; + } + setWorkingQueuedPackets(pasted); + AutismClientMessaging.sendPrefixed("Pasted " + pasted.size() + " packets"); + }); + renderActionButton(ctx, x, bottomY, halfW, btnH, "Clear", mx, my, () -> { + setWorkingQueuedPackets(Collections.emptyList()); + AutismClientMessaging.sendPrefixed("Cleared packet list"); + }); + renderOverlayButton(ctx, x + halfW + 4, bottomY, halfW, btnH, configurationOnly ? "Capture: In Game" : "GBreak", + CompactOverlayButton.Variant.SECONDARY, !configurationOnly, mx, my, () -> { + if (configurationOnly) return; + AutismSharedState.get().startGBreakCapture(() -> MC.execute(() -> { + List captured = AutismSharedState.get().getGBreakCapturedPackets(); + setWorkingQueuedPackets(captured); + AutismClientMessaging.sendPrefixed(captured.isEmpty() + ? "GBreak capture finished with no packet" + : "GBreak packet captured"); + })); + AutismClientMessaging.sendPrefixed("Break a block now to capture the GBreak packet"); + }); + } + + private record PayloadEditorState(String channel, byte[] rawBytes, boolean commandApiRecognized, + int commandApiValue, PayloadContentMode contentMode, String contentText) { + private PayloadEditorState { + rawBytes = rawBytes == null ? new byte[0] : rawBytes.clone(); + contentMode = contentMode == null ? PayloadContentMode.BINARY_REPLAY : contentMode; + contentText = contentText == null ? "" : contentText; + } + + @Override + public byte[] rawBytes() { + return rawBytes.clone(); + } + + } + + private void initializePayloadEditorFields(PayloadAction seedAction) { + payloadEditorModel = AutismPayloadEditorModel.fromAction(seedAction); + PayloadEditorState state = resolvePayloadEditorState(seedAction); + payloadContentMode = state.contentMode(); + payloadContentEdited = false; + payloadRawEdited = false; + payloadChannelEdited = false; + payloadJsonEdited = false; + payloadModeManuallyChanged = false; + payloadAddTypeManuallyChanged = false; + suppressPayloadEditorChange = false; + + AutismChatField channelField = makeField(120); + channelField.setText(state.channel()); + channelField.setPlaceholder(Component.literal("namespace:channel")); + channelField.setChangedListener(text -> { + if (!suppressPayloadEditorChange) { + payloadChannelEdited = true; + if (payloadEditorModel != null) { + payloadEditorModel.channel = text == null || text.isBlank() ? "minecraft:brand" : text.strip(); + syncPayloadPreviewFieldsFromModel(false); + } + autoSelectPayloadControls(); + } + }); + textFields.put("payload_channel", channelField); + + if (seedAction != null) { + seedAction.payloadPhase = payloadEditorModel.phase; + } + AutismChatField contentField = makeField(PAYLOAD_SCRIPT_H); + contentField.setMultiline(true); + contentField.setEnterInsertsNewline(true); + contentField.setSpaceKeyInsertsSpace(true); + contentField.setHoverEffectsEnabled(false); + contentField.setFocusEffectsEnabled(false); + contentField.setBackgroundColorOverride(0x520A090C); + contentField.setMaxLength(32767); + contentField.setPlaceholder(Component.literal("direction = C2S\nphase = PLAY\nchannel = minecraft:brand\n\nwriteMcString = vanilla")); + contentField.setDisplayTextProvider(this::payloadScriptComponent); + contentField.setChangedListener(text -> { + if (!suppressPayloadEditorChange) { + payloadContentEdited = true; + if (payloadEditorModel != null && payloadEditorModel.applyPacketScript(text)) { + syncPayloadQuickFieldsFromModel(false); + syncPayloadPreviewFieldsFromModel(false); + } + autoSelectPayloadControls(); + } + }); + textFields.put("payload_content", contentField); + + AutismChatField hexView = makeField(PAYLOAD_VIEW_H); + hexView.setMultiline(true); + hexView.setEnterInsertsNewline(true); + hexView.setSpaceKeyInsertsSpace(true); + hexView.setHoverEffectsEnabled(false); + hexView.setFocusEffectsEnabled(false); + hexView.setBackgroundColorOverride(0x520A090C); + hexView.setEditable(true); + hexView.setMaxLength(32767); + hexView.setPlaceholder(Component.literal("00 01 02 FF")); + hexView.setDisplayTextProvider(this::payloadHexComponent); + hexView.setChangedListener(text -> { + if (!suppressPayloadEditorChange) syncPayloadModelFromHex(text); + }); + textFields.put("payload_hex_view", hexView); + + AutismChatField utf8View = makeField(PAYLOAD_VIEW_H); + utf8View.setMultiline(true); + utf8View.setEnterInsertsNewline(true); + utf8View.setSpaceKeyInsertsSpace(true); + utf8View.setHoverEffectsEnabled(false); + utf8View.setFocusEffectsEnabled(false); + utf8View.setBackgroundColorOverride(0x520A090C); + utf8View.setEditable(true); + utf8View.setMaxLength(32767); + utf8View.setPlaceholder(Component.literal("Raw UTF-8 text")); + utf8View.setDisplayTextProvider(this::payloadUtf8Component); + utf8View.setChangedListener(text -> { + if (!suppressPayloadEditorChange) syncPayloadModelFromUtf8(text); + }); + textFields.put("payload_utf8_view", utf8View); + + AutismChatField logicalView = makeField(PAYLOAD_VIEW_H); + logicalView.setMultiline(true); + logicalView.setEnterInsertsNewline(true); + logicalView.setSpaceKeyInsertsSpace(true); + logicalView.setHoverEffectsEnabled(false); + logicalView.setFocusEffectsEnabled(false); + logicalView.setBackgroundColorOverride(0x520A090C); + logicalView.setEditable(true); + logicalView.setMaxLength(32767); + logicalView.setPlaceholder(Component.literal("direction = C2S\nphase = PLAY\nchannel = minecraft:brand\nbodyHex = ...")); + logicalView.setDisplayTextProvider(this::payloadLogicalComponent); + logicalView.setChangedListener(text -> { + if (!suppressPayloadEditorChange) syncPayloadModelFromLogical(text); + }); + textFields.put("payload_logical_view", logicalView); + + AutismChatField commandField = makeField(66); + commandField.setNumericOnly(true); + commandField.setText(String.valueOf(payloadEditorModel.commandApiValue)); + commandField.setPlaceholder(Component.literal("value")); + commandField.setChangedListener(text -> { + if (!suppressPayloadEditorChange && payloadEditorModel != null) { + try { + payloadEditorModel.commandApiValue = Integer.parseInt((text == null ? "" : text).strip()); + payloadEditorModel.commandApiRecognized = true; + payloadEditorModel.commandApiOverride = true; + toggleStates.put("payload_command_api", true); + payloadContentEdited = true; + } catch (NumberFormatException ignored) { } + } + }); + textFields.put("payload_command_value", commandField); + toggleStates.put("payload_command_api", payloadEditorModel.commandApiOverride); + + syncPayloadAllFieldsFromModel(true); + AutismPayloadTemplate.Template template = currentPayloadTemplateFromModel(); + AutismPayloadTemplate.EncodingMode suggestedMode = suggestPayloadMode(template.channel(), template.fields(), template.mode()); + enumIndices.put("payload_mode", payloadModeIndex(suggestedMode)); + enumIndices.put("payload_add_type", payloadTypeIndex(suggestPayloadAddType(template.channel(), suggestedMode, template.fields()))); + } + + private PayloadEditorState resolvePayloadEditorState(PayloadAction seedAction) { + PayloadAction action = new PayloadAction(); + if (seedAction != null) { + action.fromTag(seedAction.toTag()); + } + + String channel = action.channel == null ? "" : action.channel.strip(); + byte[] bytes = new byte[0]; + boolean haveBytes = false; + + if (action.payloadData != null && !action.payloadData.isBlank()) { + try { + bytes = AutismPayloadSupport.parsePayloadBytes(action.payloadData); + haveBytes = true; + } catch (Exception ignored) { + bytes = new byte[0]; + } + } + + if (action.payloadJson != null && !action.payloadJson.isBlank()) { + try { + action.payloadJson = AutismPayloadJsonSupport.normalizeJson(action.payloadJson); + AutismPayloadJsonSupport.EncodedPayload encoded = AutismPayloadJsonSupport.encodeAction(action); + if (channel.isBlank() && encoded.channel() != null && !encoded.channel().isBlank()) { + channel = encoded.channel(); + } + if (!haveBytes) { + bytes = encoded.bytes(); + haveBytes = bytes.length > 0 || action.payloadData == null || action.payloadData.isBlank(); + } + } catch (Exception ignored) { } + } + + if (channel.isBlank()) { + channel = "minecraft:brand"; + } + + if (AutismPayloadSupport.isBrandChannel(channel)) { + String brandText = AutismPayloadSupport.decodeMinecraftStringPayload(bytes); + if (brandText != null || bytes.length == 0) { + return new PayloadEditorState(channel, bytes, false, action.commandApiValue, + PayloadContentMode.BRAND_STRING, + brandText != null ? brandText : AutismPayloadSupport.defaultBrandPayloadString()); + } + } + + Integer commandValue = AutismPayloadSupport.tryParseCommandApiValue(null, channel, bytes); + boolean commandRecognized = action.commandApiRecognized || commandValue != null; + int resolvedCommandValue = commandValue != null ? commandValue : action.commandApiValue; + PayloadContentMode mode = PayloadContentMode.BINARY_REPLAY; + String contentText = ""; + if (commandRecognized) { + mode = PayloadContentMode.COMMAND_INT; + contentText = String.valueOf(resolvedCommandValue); + } else { + String readableText = AutismPayloadSupport.decodeLikelyUtf8Text(bytes); + if (!readableText.isBlank() || bytes.length == 0) { + mode = PayloadContentMode.UTF8_TEXT; + contentText = prettifyPayloadText(readableText); + } else { + contentText = "Binary payload (" + bytes.length + " bytes). Safe replay keeps the captured bytes."; + } + } + return new PayloadEditorState(channel, bytes, commandRecognized, resolvedCommandValue, mode, contentText); + } + + private String prettifyPayloadText(String text) { + if (text == null || text.isBlank()) return ""; + String normalized = text.replace("\r\n", "\n").replace('\r', '\n'); + String stripped = normalized.strip(); + if (!(stripped.startsWith("{") || stripped.startsWith("["))) { + return normalized; + } + try { + return PAYLOAD_TEXT_GSON.toJson(JsonParser.parseString(stripped)); + } catch (Throwable ignored) { + return normalized; + } + } + + private void formatPayloadJsonField(boolean syncPreview) { + AutismChatField jsonField = textFields.get("payload_json"); + if (jsonField == null) return; + jsonField.setText(AutismPayloadJsonSupport.normalizeJson(jsonField.getText())); + if (syncPreview) { + syncPayloadPreviewFromJson(true); + } + } + + private void syncPayloadPreviewFromJson(boolean notifyOnError) { + AutismChatField jsonField = textFields.get("payload_json"); + if (jsonField == null) return; + + PayloadAction preview = new PayloadAction(); + if (payloadAction != null) { + preview.fromTag(payloadAction.toTag()); + } + + AutismChatField channelField = textFields.get("payload_channel"); + AutismChatField rawField = textFields.get("payload_data"); + AutismChatField textField = textFields.get("payload_text"); + AutismChatField commandField = textFields.get("payload_command_value"); + + preview.payloadJson = jsonField.getText(); + preview.channel = channelField == null ? preview.channel : channelField.getText().strip(); + preview.payloadData = rawField == null ? preview.payloadData : rawField.getText(); + preview.commandApiRecognized = toggleStates.getOrDefault("payload_command_api", preview.commandApiRecognized); + + if (commandField != null) { + try { + preview.commandApiValue = Integer.parseInt(commandField.getText().strip()); + } catch (NumberFormatException ignored) { } + } + + try { + preview.payloadJson = AutismPayloadJsonSupport.normalizeJson(preview.payloadJson); + AutismPayloadJsonSupport.EncodedPayload encoded = AutismPayloadJsonSupport.encodeAction(preview); + suppressPayloadEditorChange = true; + try { + jsonField.setText(preview.payloadJson); + if (channelField != null) { + channelField.setText(encoded.channel()); + } + if (rawField != null) { + rawField.setText(AutismPayloadSupport.toHex(encoded.bytes())); + } + if (textField != null) { + textField.setText(AutismPayloadSupport.decodeLikelyUtf8Text(encoded.bytes())); + } + payloadChannelEdited = true; + payloadRawEdited = true; + payloadJsonEdited = false; + } finally { + suppressPayloadEditorChange = false; + } + + Integer commandValue = AutismPayloadSupport.tryParseCommandApiValue(null, encoded.channel(), encoded.bytes()); + if (commandValue != null) { + toggleStates.put("payload_command_api", true); + if (commandField != null) { + commandField.setText(String.valueOf(commandValue)); + } + } + } catch (Exception e) { + if (notifyOnError) { + AutismClientMessaging.sendPrefixed("§cCould not rebuild payload from JSON: " + AutismPayloadSupport.safeMessage(e)); + } + } + } + + private void setPayloadFieldsInEditor(List fields) { + removePayloadRowFields(); + List safeFields = fields == null ? List.of() : fields; + payloadFieldCount = safeFields.size(); + if (payloadEditorModel != null) { + payloadEditorModel.bodyFields = new ArrayList<>(safeFields); + payloadEditorModel.applyPacketScript(payloadEditorModel.packetScript()); + syncPayloadAllFieldsFromModel(true); + return; + } + AutismChatField contentField = textFields.get("payload_content"); + if (contentField != null) { + contentField.setText(AutismPayloadTemplate.serializeFields(safeFields)); + } + } + + private void removePayloadRowFields() { + textFields.entrySet().removeIf(entry -> entry.getKey().startsWith("payload_value_")); + enumIndices.entrySet().removeIf(entry -> entry.getKey().startsWith("payload_type_")); + enumDropdownCache.entrySet().removeIf(entry -> entry.getKey().startsWith("payload_type_")); + payloadFieldCount = 0; + } + + private List payloadFieldsFromEditor() { + if (payloadEditorModel != null) return payloadEditorModel.bodyFields == null ? List.of() : payloadEditorModel.bodyFields; + AutismChatField contentField = textFields.get("payload_content"); + return AutismPayloadTemplate.parseFields(contentField == null ? "" : contentField.getText()); + } + + private void autoSelectPayloadControls() { + if (suppressPayloadEditorChange) return; + String channel = payloadEditorChannel(); + List fields = payloadFieldsFromEditor(); + if (!payloadModeManuallyChanged) { + AutismPayloadTemplate.EncodingMode current = PAYLOAD_MODES.get(Math.max(0, + Math.min(enumIndices.getOrDefault("payload_mode", payloadModeIndex(AutismPayloadTemplate.EncodingMode.ADVANCED_MIXED)), PAYLOAD_MODES.size() - 1))); + enumIndices.put("payload_mode", payloadModeIndex(suggestPayloadMode(channel, fields, current))); + } + if (!payloadAddTypeManuallyChanged) { + AutismPayloadTemplate.EncodingMode mode = payloadModeFromEditor(channel); + enumIndices.put("payload_add_type", payloadTypeIndex(suggestPayloadAddType(channel, mode, fields))); + } + } + + private String payloadEditorChannel() { + if (payloadEditorModel != null && payloadEditorModel.channel != null && !payloadEditorModel.channel.isBlank()) { + return payloadEditorModel.channel.strip(); + } + AutismChatField channelField = textFields.get("payload_channel"); + if (channelField != null && !channelField.getText().isBlank()) return channelField.getText().strip(); + return payloadAction != null && payloadAction.channel != null && !payloadAction.channel.isBlank() + ? payloadAction.channel.strip() + : "minecraft:brand"; + } + + private AutismPayloadTemplate.EncodingMode suggestPayloadMode(String channel, List fields, + AutismPayloadTemplate.EncodingMode fallback) { + List safeFields = fields == null ? List.of() : fields; + if (AutismPayloadSupport.isBrandChannel(channel)) return AutismPayloadTemplate.EncodingMode.MINECRAFT_BYTEBUF; + if ("bungeecord:main".equalsIgnoreCase(channel == null ? "" : channel.strip())) return AutismPayloadTemplate.EncodingMode.JAVA_DATA_OUTPUT; + for (AutismPayloadTemplate.Field field : safeFields) { + if (field == null) continue; + switch (field.type()) { + case HEX_BYTES, RAW_BYTES, BYTE_ARRAY -> { + return AutismPayloadTemplate.EncodingMode.MANUAL_HEX; + } + case JAVA_WRITE_UTF, BYTE, UNSIGNED_BYTE, BOOLEAN, SHORT, UNSIGNED_SHORT, CHAR, INT, LONG, FLOAT, DOUBLE -> { + return AutismPayloadTemplate.EncodingMode.JAVA_DATA_OUTPUT; + } + case VAR_INT, VAR_LONG, MINECRAFT_STRING, IDENTIFIER, UUID_FIELD, BLOCK_POS, ENUM_VAR_INT, OPTIONAL_VALUE -> { + return AutismPayloadTemplate.EncodingMode.MINECRAFT_BYTEBUF; + } + case JSON_STRING, TEXT_COMPONENT, NBT, ITEM_STACK -> { + return AutismPayloadTemplate.EncodingMode.JSON_TEXT; + } + case STRING_BYTES, RAW_UTF8_STRING -> { + return AutismPayloadTemplate.EncodingMode.RAW_UTF8; + } + } + } + return fallback == null ? AutismPayloadTemplate.EncodingMode.ADVANCED_MIXED : fallback; + } + + private AutismPayloadTemplate.FieldType suggestPayloadAddType(String channel, AutismPayloadTemplate.EncodingMode mode, + List fields) { + if (AutismPayloadSupport.isBrandChannel(channel)) return AutismPayloadTemplate.FieldType.MINECRAFT_STRING; + if ("bungeecord:main".equalsIgnoreCase(channel == null ? "" : channel.strip())) return AutismPayloadTemplate.FieldType.JAVA_WRITE_UTF; + if (mode == AutismPayloadTemplate.EncodingMode.MANUAL_HEX) return AutismPayloadTemplate.FieldType.HEX_BYTES; + if (mode == AutismPayloadTemplate.EncodingMode.JAVA_DATA_OUTPUT) return AutismPayloadTemplate.FieldType.JAVA_WRITE_UTF; + if (mode == AutismPayloadTemplate.EncodingMode.MINECRAFT_BYTEBUF) return AutismPayloadTemplate.FieldType.MINECRAFT_STRING; + if (mode == AutismPayloadTemplate.EncodingMode.JSON_TEXT) return AutismPayloadTemplate.FieldType.TEXT_COMPONENT; + return AutismPayloadTemplate.FieldType.STRING_BYTES; + } + + private void syncPayloadModelFromHex(String text) { + if (payloadEditorModel == null) return; + if (payloadEditorModel.applyBodyHex(text)) { + payloadContentEdited = true; + syncPayloadAllFieldsFromModel(false); + } + } + + private void syncPayloadModelFromUtf8(String text) { + if (payloadEditorModel == null) return; + payloadEditorModel.applyUtf8(text); + payloadContentEdited = true; + syncPayloadAllFieldsFromModel(false); + } + + private void syncPayloadModelFromLogical(String text) { + if (payloadEditorModel == null) return; + if (payloadEditorModel.applyLogicalText(text)) { + payloadContentEdited = true; + syncPayloadAllFieldsFromModel(false); + } + } + + private void syncPayloadAllFieldsFromModel(boolean force) { + syncPayloadQuickFieldsFromModel(force); + syncPayloadPreviewFieldsFromModel(force); + } + + private void syncPayloadQuickFieldsFromModel(boolean force) { + if (payloadEditorModel == null) return; + suppressPayloadEditorChange = true; + try { + AutismChatField channelField = textFields.get("payload_channel"); + if (channelField != null && (force || !channelField.isFocused())) { + channelField.setText(payloadEditorModel.channel == null ? "" : payloadEditorModel.channel); + } + enumIndices.put("payload_mode", payloadModeIndex(AutismPayloadTemplate.EncodingMode.parse(payloadEditorModel.encodingMode, payloadEditorModel.channel))); + AutismChatField commandField = textFields.get("payload_command_value"); + if (commandField != null && (force || !commandField.isFocused())) { + commandField.setText(String.valueOf(payloadEditorModel.commandApiValue)); + } + toggleStates.put("payload_command_api", payloadEditorModel.commandApiOverride); + } finally { + suppressPayloadEditorChange = false; + } + } + + private void syncPayloadPreviewFieldsFromModel(boolean force) { + if (payloadEditorModel == null) return; + suppressPayloadEditorChange = true; + try { + AutismChatField contentField = textFields.get("payload_content"); + if (contentField != null && (force || !contentField.isFocused())) { + contentField.setText(payloadEditorModel.packetScript()); + } + AutismChatField hexView = textFields.get("payload_hex_view"); + if (hexView != null && (force || !hexView.isFocused())) { + hexView.setText(payloadEditorModel.bodyHexMultiline()); + } + AutismChatField utf8View = textFields.get("payload_utf8_view"); + if (utf8View != null && (force || !utf8View.isFocused())) { + utf8View.setText(payloadEditorModel.utf8View()); + } + AutismChatField logicalView = textFields.get("payload_logical_view"); + if (logicalView != null && (force || !logicalView.isFocused())) { + logicalView.setText(payloadEditorModel.logicalText()); + } + } finally { + suppressPayloadEditorChange = false; + } + } + + private String escapePayloadScriptValue(String text) { + if (text == null || text.isEmpty()) return ""; + return text.replace("\\", "\\\\").replace("\r\n", "\\n").replace("\r", "\\n").replace("\n", "\\n"); + } + + private int payloadTypeIndex(AutismPayloadTemplate.FieldType type) { + int index = PAYLOAD_FIELD_TYPES.indexOf(type); + return index < 0 ? PAYLOAD_FIELD_TYPES.indexOf(AutismPayloadTemplate.FieldType.STRING_BYTES) : index; + } + + private AutismPayloadTemplate.FieldType payloadTypeAt(int row) { + int index = Math.max(0, Math.min(enumIndices.getOrDefault(payloadTypeKey(row), payloadTypeIndex(AutismPayloadTemplate.FieldType.STRING_BYTES)), + PAYLOAD_FIELD_TYPES.size() - 1)); + return PAYLOAD_FIELD_TYPES.get(index); + } + + private String payloadTypeKey(int row) { + return "payload_type_" + row; + } + + private String payloadValueKey(int row) { + return "payload_value_" + row; + } + + private int payloadModeIndex(AutismPayloadTemplate.EncodingMode mode) { + int index = PAYLOAD_MODES.indexOf(mode); + return index < 0 ? PAYLOAD_MODES.indexOf(AutismPayloadTemplate.EncodingMode.ADVANCED_MIXED) : index; + } + + private AutismPayloadTemplate.EncodingMode payloadModeFromEditor(String channel) { + int fallback = payloadModeIndex(AutismPayloadTemplate.EncodingMode.parse(payloadAction == null ? "" : payloadAction.payloadEncodingMode, channel)); + int index = Math.max(0, Math.min(enumIndices.getOrDefault("payload_mode", fallback), PAYLOAD_MODES.size() - 1)); + return PAYLOAD_MODES.get(index); + } + + private void renderCleanPayloadPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + AutismPayloadTemplate.Template template = currentPayloadTemplateFromEditor(); + AutismPayloadTemplate.BuildResult built = template.build(); + + UiText.draw(ctx, textRenderer, "Custom Payload", font, + AutismColors.textSecondary(), x, cy + 2, false); + cy += 14; + + cy = renderPayloadStatus(ctx, x, cy, w); + cy = renderPayloadTabs(ctx, x, cy, w, mx, my); + + int dirLabelW = 18; + int dirW = 38; + int modeLabelW = 28; + UiText.draw(ctx, textRenderer, "Dir", font, AutismColors.textDim(), x, cy + 3, false); + renderOverlayButton(ctx, x + dirLabelW, cy, dirW, 14, template.direction().name(), CompactOverlayButton.Variant.SECONDARY, true, mx, my, () -> { + if (payloadEditorModel != null) { + payloadEditorModel.direction = AutismPayloadTemplate.nextDirectionName(payloadEditorModel.direction); + syncPayloadAllFieldsFromModel(false); + } else if (payloadAction != null) { + payloadAction.payloadDirection = AutismPayloadTemplate.nextDirectionName(payloadAction.payloadDirection); + } + payloadContentEdited = true; + refreshInteractiveLayout(); + }); + int modeLabelX = x + dirLabelW + dirW + 5; + UiText.draw(ctx, textRenderer, "Mode", font, AutismColors.textDim(), modeLabelX, cy + 3, false); + int modeX = modeLabelX + modeLabelW; + renderPayloadModeDropdown(modeX, cy, Math.max(54, x + w - modeX), mx, my, template); + cy += 18; + + AutismChatField channelField = textFields.get("payload_channel"); + if (channelField != null) { + int lw = labelWidth(w, "Channel", font, 64); + drawLabel(ctx, "Channel", x, cy, lw, font); + int ctrlX = controlX(x, lw); + int ctrlW = controlWidth(w, lw); + channelField.setX(ctrlX); + channelField.setY(cy + 2); + channelField.setWidth(ctrlW); + channelField.render(ctx, mx, my, delta); + cy += ROW_H + ROW_GAP; + } + + if (payloadEditorModel != null && payloadEditorModel.commandApiRecognized) { + AutismChatField commandField = textFields.get("payload_command_value"); + if (commandField != null) { + int lw = labelWidth(w, "CommandApi", font, 64); + drawLabel(ctx, "CommandApi", x, cy, lw, font); + int ctrlX = controlX(x, lw); + int ctrlW = controlWidth(w, lw); + int btnW = 58; + int fieldW = Math.max(38, ctrlW - btnW - 3); + commandField.setX(ctrlX); + commandField.setY(cy + 2); + commandField.setWidth(fieldW); + commandField.render(ctx, mx, my, delta); + boolean override = toggleStates.getOrDefault("payload_command_api", payloadEditorModel.commandApiOverride); + renderOverlayButton(ctx, ctrlX + fieldW + 3, cy + 2, btnW, 14, override ? "Override" : "Exact", + override ? CompactOverlayButton.Variant.SUCCESS : CompactOverlayButton.Variant.SECONDARY, + true, mx, my, () -> { + if (payloadEditorModel != null) { + payloadEditorModel.commandApiOverride = !payloadEditorModel.commandApiOverride; + toggleStates.put("payload_command_api", payloadEditorModel.commandApiOverride); + payloadContentEdited = true; + } + refreshInteractiveLayout(); + }); + cy += ROW_H + ROW_GAP; + } + } + + if (payloadTabIndex == 0) { + UiText.draw(ctx, textRenderer, "Packet Script", font, + AutismColors.textSecondary(), x, cy + 2, false); + renderOverlayButton(ctx, x + w - 42, cy, 42, 14, "Clear", CompactOverlayButton.Variant.DANGER, + !payloadFieldsFromEditor().isEmpty(), mx, my, () -> { + AutismChatField contentField = textFields.get("payload_content"); + if (contentField != null) contentField.setText(""); + payloadContentEdited = true; + refreshInteractiveLayout(); + }); + cy += 15; + int addButtonW = 62; + renderPayloadAddDropdown(x, cy, Math.max(54, w - addButtonW - 4), mx, my); + renderOverlayButton(ctx, x + w - addButtonW, cy, addButtonW, 14, "Add", CompactOverlayButton.Variant.SUCCESS, true, mx, my, () -> { + appendPayloadFieldType(enumIndices.getOrDefault("payload_add_type", payloadTypeIndex(AutismPayloadTemplate.FieldType.STRING_BYTES))); + }); + cy += 17; + + AutismChatField contentField = textFields.get("payload_content"); + if (contentField != null) { + contentField.setX(x); + contentField.setY(cy); + contentField.setWidth(w); + contentField.setHeight(PAYLOAD_SCRIPT_H); + contentField.render(ctx, mx, my, delta); + } + cy += PAYLOAD_SCRIPT_H + 4; + } else if (payloadTabIndex == 1) { + syncPayloadPreviewFieldsFromModel(false); + AutismChatField hexView = textFields.get("payload_hex_view"); + if (hexView != null) { + int bytes = payloadEditorModel == null ? built.bytes().length : payloadEditorModel.bodyBytes.length; + UiText.draw(ctx, textRenderer, "Body Hex - payload body only (" + bytes + " bytes)", font, + AutismColors.textSecondary(), x, cy + 2, false); + cy += 14; + hexView.setX(x); + hexView.setY(cy); + hexView.setWidth(w); + hexView.setHeight(PAYLOAD_VIEW_H); + hexView.render(ctx, mx, my, delta); + cy += PAYLOAD_VIEW_H + 4; + } + } else if (payloadTabIndex == 2) { + syncPayloadPreviewFieldsFromModel(false); + AutismChatField utf8View = textFields.get("payload_utf8_view"); + if (utf8View != null) { + UiText.draw(ctx, textRenderer, "UTF-8 / Raw Text Body", font, + AutismColors.textSecondary(), x, cy + 2, false); + cy += 14; + utf8View.setX(x); + utf8View.setY(cy); + utf8View.setWidth(w); + utf8View.setHeight(PAYLOAD_VIEW_H); + utf8View.render(ctx, mx, my, delta); + cy += PAYLOAD_VIEW_H + 4; + } + } else { + syncPayloadPreviewFieldsFromModel(false); + AutismChatField logicalView = textFields.get("payload_logical_view"); + if (logicalView != null) { + UiText.draw(ctx, textRenderer, "Logical Packet - envelope + body", font, + AutismColors.textSecondary(), x, cy + 2, false); + cy += 14; + logicalView.setX(x); + logicalView.setY(cy); + logicalView.setWidth(w); + logicalView.setHeight(PAYLOAD_VIEW_H); + logicalView.render(ctx, mx, my, delta); + cy += PAYLOAD_VIEW_H + 4; + } + } + + int halfW = (w - 4) / 2; + String notice = payloadValidationText(built); + boolean modelBad = payloadEditorModel != null && payloadEditorModel.validationError != null && !payloadEditorModel.validationError.isBlank(); + int noticeColor = modelBad || !built.errors().isEmpty() + ? AutismColors.dangerText() + : (!built.warnings().isEmpty() ? 0xFFFFC857 : AutismColors.textDim()); + UiText.draw(ctx, textRenderer, UiText.trimToWidth(textRenderer, notice, Math.max(10, w), font, noticeColor), + font, noticeColor, x, cy + 2, false); + cy += 14; + + renderOverlayButton(ctx, x, cy, halfW, 16, configurationOnly ? "Send: In Game" : "Send", + CompactOverlayButton.Variant.SUCCESS, !configurationOnly && built.ok() && !modelBad, mx, my, () -> { + if (configurationOnly) return; + try { + PayloadAction action = buildPayloadActionFromEditor(); + action.execute(MC); + } catch (Exception e) { + AutismClientMessaging.sendPrefixed("§cPayload send failed: " + AutismPayloadSupport.safeMessage(e)); + } + }); + renderOverlayButton(ctx, x + halfW + 4, cy, halfW, 16, "Reset", CompactOverlayButton.Variant.SECONDARY, true, mx, my, () -> { + resetPayloadEditorFields(); + refreshInteractiveLayout(); + }); + cy += 20; + + if (isPayloadConfigPhase()) { + cy = renderEditorHint(ctx, x, cy, w, "Config-phase payload — sending may disconnect.", 0xFFE6B450); + } + renderEditorHint(ctx, x, cy, w, payloadEditorHint()); + } + + private int renderPayloadTabs(GuiGraphicsExtractor ctx, int x, int y, int w, int mx, int my) { + String[] tabs = {"Packet", "Body Hex", "UTF-8", "Logical"}; + int gap = 3; + int tabW = Math.max(42, (w - gap * (tabs.length - 1)) / tabs.length); + for (int i = 0; i < tabs.length; i++) { + int tx = x + i * (tabW + gap); + int tw = i == tabs.length - 1 ? Math.max(30, x + w - tx) : tabW; + CompactOverlayButton.Variant variant = payloadTabIndex == i + ? CompactOverlayButton.Variant.SUCCESS + : CompactOverlayButton.Variant.SECONDARY; + final int index = i; + renderOverlayButton(ctx, tx, y, tw, 14, tabs[i], variant, true, mx, my, () -> { + payloadTabIndex = index; + clearPayloadFieldFocus(); + refreshInteractiveLayout(); + }); + } + return y + 18; + } + + private void clearPayloadFieldFocus() { + for (String key : List.of("payload_content", "payload_hex_view", "payload_utf8_view", "payload_logical_view")) { + AutismChatField field = textFields.get(key); + if (field != null) field.setFocused(false); + } + } + + private void renderPayloadAddDropdown(int x, int y, int w, int mx, int my) { + int idx = Math.max(0, Math.min(enumIndices.getOrDefault("payload_add_type", + payloadTypeIndex(suggestPayloadAddType(payloadEditorChannel(), payloadModeFromEditor(payloadEditorChannel()), payloadFieldsFromEditor()))), + PAYLOAD_FIELD_TYPE_LABELS.size() - 1)); + CompactDropdown dd = enumDropdownCache.computeIfAbsent("payload_add_type", key -> + new CompactDropdown(x, y, w, 14, PAYLOAD_FIELD_TYPE_LABELS, idx, newIdx -> { + payloadAddTypeManuallyChanged = true; + enumIndices.put("payload_add_type", newIdx); + })); + dd.setBounds(x, y, w, 14) + .setOptions(PAYLOAD_FIELD_TYPE_LABELS) + .setSelectedIndex(idx) + .setOnSelect(newIdx -> { + payloadAddTypeManuallyChanged = true; + enumIndices.put("payload_add_type", newIdx); + }) + .setButtonLabelOverride(""); + enumDropdowns.add(dd); + } + + private void appendPayloadFieldType(int index) { + if (index < 0 || index >= PAYLOAD_FIELD_TYPES.size()) return; + AutismPayloadTemplate.FieldType type = PAYLOAD_FIELD_TYPES.get(index); + appendPayloadField(type.label() + " = " + type.defaultValue()); + if (!payloadModeManuallyChanged) { + enumIndices.put("payload_mode", payloadModeIndex(suggestPayloadMode(payloadEditorChannel(), + List.of(new AutismPayloadTemplate.Field(type, type.defaultValue(), true)), payloadModeFromEditor(payloadEditorChannel())))); + } + refreshInteractiveLayout(); + } + + private void updatePayloadPreviewFields(AutismPayloadTemplate.BuildResult built) { + AutismChatField hexView = textFields.get("payload_hex_view"); + if (hexView != null && !hexView.isFocused()) { + suppressPayloadEditorChange = true; + try { + hexView.setText(formatPayloadHex(built.bytes())); + } finally { + suppressPayloadEditorChange = false; + } + } + AutismChatField utf8View = textFields.get("payload_utf8_view"); + if (utf8View != null && !utf8View.isFocused()) { + suppressPayloadEditorChange = true; + try { + utf8View.setText(formatPayloadUtf8View(built)); + } finally { + suppressPayloadEditorChange = false; + } + } + } + + private String formatPayloadHex(byte[] bytes) { + if (bytes == null || bytes.length == 0) return ""; + StringBuilder sb = new StringBuilder(bytes.length * 3 + bytes.length / 16 * 10); + for (int i = 0; i < bytes.length; i++) { + if (i > 0) { + sb.append(i % 16 == 0 ? '\n' : ' '); + } + sb.append(String.format(Locale.ROOT, "%02X", bytes[i] & 0xFF)); + } + return sb.toString(); + } + + private String formatPayloadUtf8View(AutismPayloadTemplate.BuildResult built) { + AutismPayloadTemplate.Preview preview = built.preview(); + String fullUtf8 = AutismPayloadSupport.decodeLikelyUtf8Text(built.bytes()); + if (fullUtf8 != null && !fullUtf8.isBlank()) return fullUtf8; + if (preview.utf8() != null && !preview.utf8().isBlank()) return preview.utf8(); + if (preview.minecraftString() != null && !preview.minecraftString().isBlank()) return preview.minecraftString(); + if (preview.javaWriteUtf() != null && !preview.javaWriteUtf().isBlank()) return preview.javaWriteUtf(); + return ""; + } + + private String payloadValidationText(AutismPayloadTemplate.BuildResult built) { + if (payloadEditorModel != null && payloadEditorModel.validationError != null && !payloadEditorModel.validationError.isBlank()) { + return "Fix: " + shortPayloadMessage(payloadEditorModel.validationError); + } + String scriptIssue = payloadScriptIssue(); + if (scriptIssue != null) return "Fix: " + shortPayloadMessage(scriptIssue); + if (payloadTabIndex == 1) { + AutismChatField hexView = textFields.get("payload_hex_view"); + if (hexView != null && hexView.isFocused()) { + try { + parsePayloadHexView(hexView.getText()); + } catch (Exception e) { + return "Bad hex: " + shortPayloadMessage(AutismPayloadSupport.safeMessage(e)); + } + } + } + if (!built.errors().isEmpty()) return "Fix: " + shortPayloadMessage(built.errors().get(0)); + if (!built.warnings().isEmpty()) return "Warn: " + shortPayloadMessage(built.warnings().get(0)); + return "Ready: " + built.bytes().length + " bytes"; + } + + private String shortPayloadMessage(String message) { + String text = message == null ? "invalid payload" : message.replace('\n', ' ').strip(); + return text.length() <= 34 ? text : text.substring(0, 31) + "..."; + } + + private byte[] parsePayloadHexView(String text) { + String value = text == null ? "" : text.strip(); + if (value.isEmpty()) return new byte[0]; + String compact = value.replaceAll("(?i)0x", "").replaceAll("\\s+", ""); + if (compact.isEmpty()) return new byte[0]; + if ((compact.length() & 1) != 0) { + throw new IllegalArgumentException("Hex needs byte pairs"); + } + if (!compact.matches("(?i)[0-9a-f]+")) { + throw new IllegalArgumentException("Only hex digits are allowed here"); + } + byte[] out = new byte[compact.length() / 2]; + for (int i = 0; i < compact.length(); i += 2) { + out[i / 2] = (byte) Integer.parseInt(compact.substring(i, i + 2), 16); + } + return out; + } + + private String readablePayloadUtf8(byte[] bytes) { + String text = AutismPayloadSupport.decodeLikelyUtf8Text(bytes); + if (text == null || text.isBlank()) return null; + for (int i = 0; i < text.length(); i++) { + char chr = text.charAt(i); + if (chr == '\n' || chr == '\r' || chr == '\t') continue; + if (Character.isISOControl(chr) || chr == '\uFFFD') return null; + } + return text; + } + + private String payloadScriptIssue() { + AutismChatField contentField = textFields.get("payload_content"); + if (contentField == null) return null; + String text = contentField.getText(); + if (text == null || text.isBlank()) return null; + String[] lines = text.replace("\r\n", "\n").replace('\r', '\n').split("\n", -1); + for (int i = 0; i < lines.length; i++) { + String raw = lines[i] == null ? "" : lines[i]; + String line = raw.strip(); + if (line.isEmpty() || line.startsWith("#")) continue; + int split = firstPayloadDelimiter(raw); + if (split < 0) return "Line " + (i + 1) + " needs writer = value"; + String typeText = raw.substring(0, split).strip(); + if (isPayloadEnvelopeKey(typeText)) continue; + if (payloadFieldTypeFromToken(typeText) == null) return "Line " + (i + 1) + " unknown writer"; + } + return null; + } + + private Component payloadScriptComponent(String source) { + MutableComponent out = Component.empty(); + String safe = source == null ? "" : source; + String[] lines = safe.replace("\r\n", "\n").replace('\r', '\n').split("\n", -1); + for (int i = 0; i < lines.length; i++) { + if (i > 0) appendPayloadStyled(out, "\n", 0x777777); + String line = lines[i]; + if (line.isEmpty()) continue; + String stripped = line.stripLeading(); + if (stripped.startsWith("#")) { + appendPayloadStyled(out, line, 0x777777); + continue; + } + int split = firstPayloadDelimiter(line); + if (split < 0) { + appendPayloadStyled(out, line, 0xFF7777); + continue; + } + String typePart = line.substring(0, split); + String sep = line.substring(split, split + 1); + String valuePart = line.substring(split + 1); + AutismPayloadTemplate.FieldType type = payloadFieldTypeFromToken(typePart.strip()); + appendPayloadStyled(out, typePart, isPayloadEnvelopeKey(typePart.strip()) ? 0xF92672 : (type == null ? 0xFF7777 : 0x66D9EF)); + appendPayloadStyled(out, sep, 0xAAAAAA); + appendPayloadValueStyled(out, valuePart); + } + return out; + } + + private boolean isPayloadEnvelopeKey(String key) { + if (key == null) return false; + return switch (key.strip().toLowerCase(Locale.ROOT)) { + case "direction", "phase", "channel", "packetid", "packet_id", "packetclass", "packet_class", + "sourceprotocol", "source_protocol", "provenance" -> true; + default -> false; + }; + } + + private Component payloadHexComponent(String source) { + MutableComponent out = Component.empty(); + String safe = source == null ? "" : source; + int hexCount = 0; + for (int i = 0; i < safe.length(); i++) { + char chr = safe.charAt(i); + if (chr == '\n' || Character.isWhitespace(chr)) { + appendPayloadStyled(out, Character.toString(chr), 0x777777); + } else if (isPayloadHexDigit(chr)) { + int color = ((hexCount / 2) % 2 == 0) ? 0xA6E22E : 0x66D9EF; + appendPayloadStyled(out, Character.toString(chr), color); + hexCount++; + } else { + appendPayloadStyled(out, Character.toString(chr), 0xFF7777); + } + } + return out; + } + + private Component payloadUtf8Component(String source) { + MutableComponent out = Component.empty(); + String safe = source == null ? "" : source; + boolean inString = false; + boolean escaped = false; + for (int i = 0; i < safe.length(); i++) { + char chr = safe.charAt(i); + int color; + if (chr == '\n') color = 0x777777; + else if (Character.isWhitespace(chr)) color = 0x777777; + else if (escaped) { + color = 0xAE81FF; + escaped = false; + } else if (chr == '\\') { + color = 0xAE81FF; + escaped = true; + } else if (chr == '"' || chr == '\'') { + color = 0xE6DB74; + inString = !inString; + } else if (inString) color = 0xE6DB74; + else if ("{}[],:=".indexOf(chr) >= 0) color = 0x66D9EF; + else if (Character.isDigit(chr) || chr == '-' || chr == '+') color = 0xAE81FF; + else if (Character.isLetter(chr)) color = 0xA6E22E; + else color = 0xF8F8F2; + appendPayloadStyled(out, Character.toString(chr), color); + } + return out; + } + + private Component payloadLogicalComponent(String source) { + MutableComponent out = Component.empty(); + String safe = source == null ? "" : source; + String[] lines = safe.replace("\r\n", "\n").replace('\r', '\n').split("\n", -1); + for (int i = 0; i < lines.length; i++) { + if (i > 0) appendPayloadStyled(out, "\n", 0x777777); + String line = lines[i]; + int split = firstPayloadDelimiter(line); + if (split < 0) { + appendPayloadStyled(out, line, line.strip().startsWith("#") ? 0x777777 : 0xF8F8F2); + continue; + } + String key = line.substring(0, split); + String sep = line.substring(split, split + 1); + String value = line.substring(split + 1); + appendPayloadStyled(out, key, isPayloadEnvelopeKey(key) || key.toLowerCase(Locale.ROOT).contains("hex") ? 0x66D9EF : 0xA6E22E); + appendPayloadStyled(out, sep, 0xAAAAAA); + if (key.toLowerCase(Locale.ROOT).contains("hex")) { + appendPayloadStyled(out, value, 0xE6DB74); + } else { + appendPayloadValueStyled(out, value); + } + } + return out; + } + + private void appendPayloadValueStyled(MutableComponent out, String valuePart) { + if (valuePart == null || valuePart.isEmpty()) return; + int leading = 0; + while (leading < valuePart.length() && Character.isWhitespace(valuePart.charAt(leading))) leading++; + if (leading > 0) appendPayloadStyled(out, valuePart.substring(0, leading), 0xAAAAAA); + String value = valuePart.substring(leading); + int color = looksNumericPayloadValue(value) ? 0xAE81FF : looksBooleanPayloadValue(value) ? 0xF92672 : 0xE6DB74; + appendPayloadStyled(out, value, color); + } + + private void appendPayloadStyled(MutableComponent out, String text, int color) { + if (text == null || text.isEmpty()) return; + out.append(UiText.literal(text, theme.fontFor(UiTone.BODY), color)); + } + + private int firstPayloadDelimiter(String line) { + if (line == null) return -1; + int eq = line.indexOf('='); + int colon = line.indexOf(':'); + if (eq < 0) return colon; + if (colon < 0) return eq; + return Math.min(eq, colon); + } + + private AutismPayloadTemplate.FieldType payloadFieldTypeFromToken(String token) { + if (token == null || token.isBlank()) return null; + String normalized = token.strip().toUpperCase(Locale.ROOT).replace('-', '_').replace(' ', '_'); + for (AutismPayloadTemplate.FieldType type : AutismPayloadTemplate.FieldType.values()) { + if (type.name().equals(normalized) || type.label().equalsIgnoreCase(token.strip())) return type; + } + if ("UUID".equals(normalized)) return AutismPayloadTemplate.FieldType.UUID_FIELD; + if ("UTF".equals(normalized) || "WRITEUTF".equals(normalized)) return AutismPayloadTemplate.FieldType.JAVA_WRITE_UTF; + if ("MC_STRING".equals(normalized) || "MINECRAFT_STRING".equals(normalized)) return AutismPayloadTemplate.FieldType.MINECRAFT_STRING; + if ("COMPONENT".equals(normalized) || "TEXT_COMPONENT".equals(normalized)) return AutismPayloadTemplate.FieldType.TEXT_COMPONENT; + return null; + } + + private boolean isPayloadHexDigit(char chr) { + return (chr >= '0' && chr <= '9') || (chr >= 'a' && chr <= 'f') || (chr >= 'A' && chr <= 'F'); + } + + private boolean looksNumericPayloadValue(String value) { + String text = value == null ? "" : value.strip(); + return text.matches("-?(0x[0-9a-fA-F]+|\\d+)(\\.\\d+)?"); + } + + private boolean looksBooleanPayloadValue(String value) { + String text = value == null ? "" : value.strip(); + return "true".equalsIgnoreCase(text) || "false".equalsIgnoreCase(text); + } + + private void renderPayloadModeDropdown(int x, int y, int w, int mx, int my, AutismPayloadTemplate.Template template) { + int idx = payloadModeIndex(template == null ? AutismPayloadTemplate.EncodingMode.ADVANCED_MIXED : template.mode()); + CompactDropdown dd = enumDropdownCache.computeIfAbsent("payload_mode", key -> + new CompactDropdown(x, y, w, 14, PAYLOAD_MODE_LABELS, idx, newIdx -> { + if (newIdx >= 0 && newIdx < PAYLOAD_MODES.size()) { + payloadModeManuallyChanged = true; + enumIndices.put("payload_mode", newIdx); + if (payloadAction != null) payloadAction.payloadEncodingMode = PAYLOAD_MODES.get(newIdx).name(); + if (payloadEditorModel != null) { + payloadEditorModel.encodingMode = PAYLOAD_MODES.get(newIdx).name(); + syncPayloadPreviewFieldsFromModel(false); + } + payloadContentEdited = true; + } + })); + dd.setBounds(x, y, w, 14) + .setOptions(PAYLOAD_MODE_LABELS) + .setSelectedIndex(idx) + .setOnSelect(newIdx -> { + if (newIdx >= 0 && newIdx < PAYLOAD_MODES.size()) { + payloadModeManuallyChanged = true; + enumIndices.put("payload_mode", newIdx); + if (payloadAction != null) payloadAction.payloadEncodingMode = PAYLOAD_MODES.get(newIdx).name(); + if (payloadEditorModel != null) { + payloadEditorModel.encodingMode = PAYLOAD_MODES.get(newIdx).name(); + syncPayloadPreviewFieldsFromModel(false); + } + payloadContentEdited = true; + } + }); + enumDropdowns.add(dd); + } + + private int renderPayloadFieldRow(GuiGraphicsExtractor ctx, int x, int y, int w, int row, int mx, int my, float delta) { + int btnH = 14; + int typeW = Math.min(116, Math.max(88, (w - 70) / 2)); + int gap = 3; + int actionW = 19; + int actionsW = actionW * 3 + gap * 2; + int valueX = x + typeW + gap; + int valueW = Math.max(36, w - typeW - gap - actionsW - gap); + renderPayloadTypeDropdown(row, x, y + 2, typeW, mx, my); + + AutismChatField valueField = textFields.get(payloadValueKey(row)); + if (valueField != null) { + AutismPayloadTemplate.FieldType type = payloadTypeAt(row); + valueField.setPlaceholder(Component.literal(type.defaultValue())); + valueField.setX(valueX); + valueField.setY(y + 3); + valueField.setWidth(valueW); + valueField.render(ctx, mx, my, delta); + } + + int ax = valueX + valueW + gap; + renderOverlayButton(ctx, ax, y + 2, actionW, btnH, "Up", CompactOverlayButton.Variant.SECONDARY, row > 0, mx, my, () -> movePayloadField(row, -1)); + renderOverlayButton(ctx, ax + actionW + gap, y + 2, actionW, btnH, "Dn", CompactOverlayButton.Variant.SECONDARY, row < payloadFieldCount - 1, mx, my, () -> movePayloadField(row, 1)); + renderOverlayButton(ctx, ax + (actionW + gap) * 2, y + 2, actionW, btnH, "X", CompactOverlayButton.Variant.DANGER, payloadFieldCount > 1, mx, my, () -> removePayloadField(row)); + return y + PAYLOAD_FIELD_ROW_H; + } + + private void renderPayloadTypeDropdown(int row, int x, int y, int w, int mx, int my) { + String key = payloadTypeKey(row); + int idx = Math.max(0, Math.min(enumIndices.getOrDefault(key, payloadTypeIndex(AutismPayloadTemplate.FieldType.STRING_BYTES)), PAYLOAD_FIELD_TYPE_LABELS.size() - 1)); + CompactDropdown dd = enumDropdownCache.computeIfAbsent(key, cacheKey -> + new CompactDropdown(x, y, w, 14, PAYLOAD_FIELD_TYPE_LABELS, idx, newIdx -> selectPayloadType(row, newIdx))); + dd.setBounds(x, y, w, 14) + .setOptions(PAYLOAD_FIELD_TYPE_LABELS) + .setSelectedIndex(idx) + .setOnSelect(newIdx -> selectPayloadType(row, newIdx)); + enumDropdowns.add(dd); + } + + private void selectPayloadType(int row, int newIdx) { + if (newIdx < 0 || newIdx >= PAYLOAD_FIELD_TYPES.size()) return; + String key = payloadTypeKey(row); + int previous = enumIndices.getOrDefault(key, -1); + enumIndices.put(key, newIdx); + if (previous != newIdx) { + AutismChatField valueField = textFields.get(payloadValueKey(row)); + if (valueField != null && valueField.getText().isBlank()) { + valueField.setText(PAYLOAD_FIELD_TYPES.get(newIdx).defaultValue()); + } + payloadContentEdited = true; + } + } + + private void movePayloadField(int row, int direction) { + List fields = new ArrayList<>(payloadFieldsFromEditor()); + int target = row + direction; + if (row < 0 || row >= fields.size() || target < 0 || target >= fields.size()) return; + Collections.swap(fields, row, target); + setPayloadFieldsInEditor(fields); + payloadContentEdited = true; + refreshInteractiveLayout(); + } + + private void removePayloadField(int row) { + List fields = new ArrayList<>(payloadFieldsFromEditor()); + if (fields.size() <= 1 || row < 0 || row >= fields.size()) return; + fields.remove(row); + setPayloadFieldsInEditor(fields); + payloadContentEdited = true; + refreshInteractiveLayout(); + } + + private AutismPayloadTemplate.Template currentPayloadTemplateFromEditor() { + if (payloadEditorModel != null) return currentPayloadTemplateFromModel(); + PayloadAction action = new PayloadAction(); + if (payloadAction != null) { + action.fromTag(payloadAction.toTag()); + } + AutismChatField channelField = textFields.get("payload_channel"); + if (channelField != null && !channelField.getText().isBlank()) { + action.channel = channelField.getText().strip(); + } + action.payloadPhase = "PLAY"; + action.payloadEncodingMode = payloadModeFromEditor(action.channel).name(); + action.payloadFields = AutismPayloadTemplate.serializeFields(payloadFieldsFromEditor()); + return AutismPayloadTemplate.fromAction(action); + } + + private AutismPayloadTemplate.Template currentPayloadTemplateFromModel() { + return payloadEditorModel == null ? AutismPayloadTemplate.fromAction(new PayloadAction()) : payloadEditorModel.toTemplate(); + } + + private void appendPayloadField(String line) { + AutismChatField contentField = textFields.get("payload_content"); + if (contentField == null || line == null || line.isBlank()) return; + String current = contentField.getText() == null ? "" : contentField.getText().stripTrailing(); + contentField.setText(current.isBlank() ? line : current + "\n" + line); + payloadContentEdited = true; + } + + private void applyPayloadTemplateToEditor(AutismPayloadTemplate.Template template) { + if (template == null) return; + if (payloadAction != null) { + payloadAction.channel = template.channel(); + payloadAction.payloadDirection = template.direction().name(); + payloadAction.payloadPhase = template.phase().name(); + payloadAction.payloadEncodingMode = template.mode().name(); + payloadAction.payloadFields = AutismPayloadTemplate.serializeFields(template.fields()); + } + suppressPayloadEditorChange = true; + try { + if (payloadEditorModel != null) { + payloadEditorModel.channel = template.channel(); + payloadEditorModel.direction = template.direction().name(); + payloadEditorModel.phase = template.phase().name(); + payloadEditorModel.encodingMode = template.mode().name(); + payloadEditorModel.bodyFields = new ArrayList<>(template.fields()); + payloadEditorModel.applyPacketScript(payloadEditorModel.packetScript()); + } + AutismChatField channelField = textFields.get("payload_channel"); + if (channelField != null) channelField.setText(template.channel()); + if (payloadEditorModel == null) setPayloadFieldsInEditor(template.fields()); + else syncPayloadAllFieldsFromModel(true); + } finally { + suppressPayloadEditorChange = false; + } + payloadChannelEdited = true; + payloadContentEdited = true; + refreshInteractiveLayout(); + } + + private int renderPayloadStatus(GuiGraphicsExtractor ctx, int x, int y, int w) { + Identifier font = theme.fontFor(UiTone.BODY); + String status = payloadReplayStatus(); + String transport = payloadEditorModel == null + ? "Encoder: vanilla" + : (payloadEditorModel.direction + " / " + payloadEditorModel.phase + + (payloadEditorModel.packetId >= 0 ? " / id " + payloadEditorModel.packetId : " / id ?")); + UiText.draw(ctx, textRenderer, + UiText.trimToWidth(textRenderer, status, Math.max(10, w), font, AutismColors.textPrimary()), + font, AutismColors.textPrimary(), x, y + 2, false); + y += 11; + UiText.draw(ctx, textRenderer, + UiText.trimToWidth(textRenderer, transport, Math.max(10, w), font, AutismColors.textDim()), + font, AutismColors.textDim(), x, y + 2, false); + return y + 13; + } + + private String payloadReplayStatus() { + if (payloadEditorModel != null) { + String decoded = payloadEditorModel.decodedKind == null ? "payload" : payloadEditorModel.decodedKind; + int bytes = payloadEditorModel.bodyBytes == null ? 0 : payloadEditorModel.bodyBytes.length; + if (payloadContentEdited || payloadChannelEdited) return "Edited: " + bytes + "B " + decoded; + return "Ready: " + bytes + "B " + decoded; + } + if (payloadContentEdited) { + return "Edited: script rebuilds bytes"; + } + if (payloadChannelEdited) { + return "Edited: channel changed"; + } + return "Payload builder ready"; + } + + private String payloadContentLabel() { + return switch (payloadContentMode) { + case COMMAND_INT -> "Payload Value"; + case BRAND_STRING -> "Brand"; + case UTF8_TEXT -> "Payload Component"; + case BINARY_REPLAY -> "Payload"; + }; + } + + private String payloadEditorHint() { + return "Rows run top to bottom."; + } + + private boolean isPayloadConfigPhase() { + if (payloadEditorModel != null && payloadEditorModel.phase != null) { + return payloadEditorModel.phase.toLowerCase(java.util.Locale.ROOT).contains("config"); + } + return payloadAction != null && payloadAction.payloadPhase != null + && payloadAction.payloadPhase.toLowerCase(java.util.Locale.ROOT).contains("config"); + } + + private void resetPayloadEditorFields() { + payloadEditorModel = AutismPayloadEditorModel.fromAction(payloadAction); + PayloadEditorState state = resolvePayloadEditorState(payloadAction); + payloadContentMode = state.contentMode(); + suppressPayloadEditorChange = true; + try { + AutismChatField channelField = textFields.get("payload_channel"); + if (channelField != null) { + channelField.setText(state.channel()); + } + syncPayloadAllFieldsFromModel(true); + payloadChannelEdited = false; + payloadContentEdited = false; + payloadRawEdited = false; + payloadJsonEdited = false; + payloadModeManuallyChanged = false; + payloadAddTypeManuallyChanged = false; + } finally { + suppressPayloadEditorChange = false; + } + autoSelectPayloadControls(); + } + + private PayloadAction buildCleanPayloadActionFromEditor() { + if (payloadEditorModel != null) { + if (payloadEditorModel.validationError != null && !payloadEditorModel.validationError.isBlank()) { + throw new IllegalArgumentException(payloadEditorModel.validationError); + } + PayloadAction action = payloadEditorModel.toAction(payloadAction); + if (action.channel == null || action.channel.isBlank()) action.channel = "minecraft:brand"; + AutismPayloadTemplate.BuildResult built = payloadEditorModel.toTemplate().build(); + if (!built.ok()) throw new IllegalArgumentException(String.join("; ", built.errors())); + action.payloadData = AutismPayloadSupport.toHex(built.bytes()); + return action; + } + PayloadAction action = new PayloadAction(); + if (payloadAction != null) { + action.fromTag(payloadAction.toTag()); + } + action.payloadClassName = ""; + action.commandApiOverride = false; + action.javaSource = ""; + action.payloadScriptEnabled = false; + + AutismChatField channelField = textFields.get("payload_channel"); + if (channelField != null) { + String editorChannel = channelField.getText().strip(); + if (!editorChannel.isBlank()) { + action.channel = editorChannel; + } + } + + action.payloadFields = AutismPayloadTemplate.serializeFields(payloadFieldsFromEditor()); + if (action.payloadDirection == null || action.payloadDirection.isBlank()) action.payloadDirection = "C2S"; + action.payloadPhase = "PLAY"; + action.payloadEncodingMode = payloadModeFromEditor(action.channel).name(); + + AutismPayloadTemplate.Template template = AutismPayloadTemplate.fromAction(action); + AutismPayloadTemplate.BuildResult built = template.build(); + if (!built.ok()) throw new IllegalArgumentException(String.join("; ", built.errors())); + action.channel = template.channel(); + action.payloadDirection = template.direction().name(); + action.payloadPhase = "PLAY"; + action.payloadEncodingMode = template.mode().name(); + action.payloadFields = AutismPayloadTemplate.serializeFields(template.fields()); + action.sourceDirection = action.payloadDirection; + action.sourceProtocol = ""; + action.payloadData = AutismPayloadSupport.toHex(built.bytes()); + action.payloadJson = ""; + action.commandApiRecognized = false; + action.commandApiOverride = false; + + if (action.channel == null || action.channel.isBlank()) { + action.channel = payloadAction != null && payloadAction.channel != null && !payloadAction.channel.isBlank() + ? payloadAction.channel + : "minecraft:brand"; + } + return action; + } + + private void renderPayloadPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + if (payloadAction != null || targetAction != null) { + renderCleanPayloadPanel(ctx, x, bodyTop, w, mx, my, delta); + return; + } + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + + UiText.draw(ctx, textRenderer, "Custom Payload Editor", font, + AutismColors.textSecondary(), x, cy + 2, false); + cy += 13; + + UiText.draw(ctx, textRenderer, "Packet JSON", font, + AutismColors.textSecondary(), x, cy + 2, false); + cy += 13; + + AutismChatField jsonField = textFields.get("payload_json"); + if (jsonField != null) { + jsonField.setX(x); + jsonField.setY(cy); + jsonField.setWidth(w); + jsonField.setHeight(PAYLOAD_JSON_H); + jsonField.render(ctx, mx, my, delta); + cy += PAYLOAD_JSON_H + 4; + } + + int halfW = (w - 4) / 2; + renderActionButton(ctx, x, cy, halfW, 14, "Pretty JSON", mx, my, () -> { + formatPayloadJsonField(false); + refreshInteractiveLayout(); + }); + renderActionButton(ctx, x + halfW + 4, cy, halfW, 14, "Apply JSON", mx, my, () -> { + syncPayloadPreviewFromJson(true); + refreshInteractiveLayout(); + }); + cy += 18; + + AutismChatField channelField = textFields.get("payload_channel"); + if (channelField != null) { + int lw = labelWidth(w, "Channel", font, 92); + drawLabel(ctx, "Channel", x, cy, lw, font); + int ctrlX = controlX(x, lw); + int ctrlW = controlWidth(w, lw); + channelField.setX(ctrlX); + channelField.setY(cy + 2); + channelField.setWidth(ctrlW); + channelField.render(ctx, mx, my, delta); + cy += ROW_H + ROW_GAP; + } + + if (toggleStates.getOrDefault("payload_command_api", false)) { + AutismChatField commandField = textFields.get("payload_command_value"); + if (commandField != null) { + int lw = labelWidth(w, "CommandApi", font, 92); + drawLabel(ctx, "CommandApi", x, cy, lw, font); + int ctrlX = controlX(x, lw); + int ctrlW = controlWidth(w, lw); + int btnW = 30; + int fieldW = Math.max(32, ctrlW - btnW - 2); + commandField.setX(ctrlX); + commandField.setY(cy + 2); + commandField.setWidth(fieldW); + commandField.render(ctx, mx, my, delta); + renderOverlayButton(ctx, ctrlX + fieldW + 2, cy + 2, btnW, 14, "Sync", + CompactOverlayButton.Variant.GHOST, true, mx, my, () -> { + syncPayloadRawFieldFromCommand(); + refreshInteractiveLayout(); + }); + cy += ROW_H + ROW_GAP; + } + } + + UiText.draw(ctx, textRenderer, "UTF-8 Component", font, + AutismColors.textSecondary(), x, cy + 2, false); + cy += 13; + + AutismChatField textField = textFields.get("payload_text"); + if (textField != null) { + textField.setX(x); + textField.setY(cy); + textField.setWidth(w); + textField.setHeight(PAYLOAD_TEXT_H); + textField.render(ctx, mx, my, delta); + cy += PAYLOAD_TEXT_H + 4; + } + + int legacyHalfW = (w - 4) / 2; + renderActionButton(ctx, x, cy, legacyHalfW, 14, "Component -> Hex", mx, my, () -> { + syncPayloadRawFieldFromText(); + refreshInteractiveLayout(); + }); + renderActionButton(ctx, x + legacyHalfW + 4, cy, legacyHalfW, 14, "Hex -> Component", mx, my, () -> { + syncPayloadTextFieldFromRaw(); + refreshInteractiveLayout(); + }); + cy += 18; + + UiText.draw(ctx, textRenderer, "Raw Payload", font, + AutismColors.textSecondary(), x, cy + 2, false); + cy += 13; + + AutismChatField rawField = textFields.get("payload_data"); + if (rawField != null) { + rawField.setX(x); + rawField.setY(cy); + rawField.setWidth(w); + rawField.setHeight(PAYLOAD_RAW_H); + rawField.render(ctx, mx, my, delta); + cy += PAYLOAD_RAW_H + 4; + } + + renderActionButton(ctx, x, cy, halfW, 14, "Parse Int", mx, my, () -> { + syncPayloadCommandFieldFromRaw(); + refreshInteractiveLayout(); + }); + renderActionButton(ctx, x + halfW + 4, cy, halfW, 14, "Normalize", mx, my, () -> { + AutismChatField field = textFields.get("payload_data"); + if (field == null) return; + try { + field.setText(AutismPayloadSupport.toHex(AutismPayloadSupport.parsePayloadBytes(field.getText()))); + } catch (Exception e) { + AutismClientMessaging.sendPrefixed("§cInvalid payload data: " + AutismPayloadSupport.safeMessage(e)); + } + }); + cy += 18; + + renderActionButton(ctx, x, cy, halfW, 14, "Seed From Int", mx, my, () -> { + syncPayloadRawFieldFromCommand(); + refreshInteractiveLayout(); + }); + renderOverlayButton(ctx, x + halfW + 4, cy, halfW, 14, configurationOnly ? "Send: In Game" : "Send Now", + CompactOverlayButton.Variant.SUCCESS, !configurationOnly, mx, my, () -> { + if (configurationOnly) return; + try { + PayloadAction action = buildPayloadActionFromEditor(); + action.execute(MC); + } catch (Exception e) { + AutismClientMessaging.sendPrefixed("§cPayload send failed: " + AutismPayloadSupport.safeMessage(e)); + } + }); + cy += 20; + + UiText.draw(ctx, textRenderer, "Runtime Java", font, + AutismColors.textSecondary(), x, cy + 2, false); + cy += 13; + + AutismChatField javaField = textFields.get("payload_java"); + if (javaField != null) { + javaField.setX(x); + javaField.setY(cy); + javaField.setWidth(w); + javaField.setHeight(PAYLOAD_JAVA_H); + javaField.render(ctx, mx, my, delta); + cy += PAYLOAD_JAVA_H + 4; + } + + renderEditorHint(ctx, x, cy, w, + "Raw replay is exact by default. Use Apply JSON only when you want the JSON view to rebuild the raw bytes."); + } + + private PayloadAction buildPayloadActionFromEditor() { + if (payloadAction != null || targetAction != null) { + return buildCleanPayloadActionFromEditor(); + } + PayloadAction action = new PayloadAction(); + if (payloadAction != null) { + action.fromTag(payloadAction.toTag()); + } + action.payloadClassName = ""; + + AutismChatField jsonField = textFields.get("payload_json"); + if (jsonField != null) { + action.payloadJson = jsonField.getText(); + } + + boolean jsonUsable = false; + AutismPayloadJsonSupport.EncodedPayload jsonEncoded = null; + if (action.payloadJson != null && !action.payloadJson.isBlank()) { + action.payloadJson = AutismPayloadJsonSupport.normalizeJson(action.payloadJson); + try { + jsonEncoded = AutismPayloadJsonSupport.encodeAction(action); + jsonUsable = true; + } catch (Exception ignored) { } + } + + AutismChatField channelField = textFields.get("payload_channel"); + if (channelField != null) { + String editorChannel = channelField.getText().strip(); + if (!editorChannel.isBlank()) { + action.channel = editorChannel; + } + } + + AutismChatField rawField = textFields.get("payload_data"); + if (rawField != null) { + action.payloadData = rawField.getText(); + } + if (action.payloadData == null || action.payloadData.isBlank()) { + AutismChatField textField = textFields.get("payload_text"); + if (textField != null && !textField.getText().isBlank()) { + action.payloadData = AutismPayloadSupport.toHex(textField.getText().getBytes(StandardCharsets.UTF_8)); + } + } + + AutismChatField javaField = textFields.get("payload_java"); + if (javaField != null) { + action.javaSource = javaField.getText(); + } + + action.commandApiRecognized = toggleStates.getOrDefault("payload_command_api", false); + AutismChatField commandField = textFields.get("payload_command_value"); + if (commandField != null) { + try { + action.commandApiValue = Integer.parseInt(commandField.getText().strip()); + } catch (NumberFormatException ignored) { } + } + + if (payloadJsonEdited && jsonUsable && jsonEncoded != null && !payloadRawEdited && !payloadChannelEdited) { + try { + jsonEncoded = AutismPayloadJsonSupport.encodeAction(action); + action.channel = jsonEncoded.channel(); + action.payloadData = AutismPayloadSupport.toHex(jsonEncoded.bytes()); + } catch (Exception ignored) { } + } + + if (action.commandApiRecognized) { + try { + byte[] bytes = AutismPayloadSupport.parsePayloadBytes(action.payloadData); + action.payloadData = AutismPayloadSupport.toHex(AutismPayloadSupport.withCommandApiValue(bytes, action.commandApiValue)); + } catch (Exception ignored) { } + } + + action.payloadClassName = ""; + + if (action.channel == null || action.channel.isBlank()) { + action.channel = payloadAction != null && payloadAction.channel != null && !payloadAction.channel.isBlank() + ? payloadAction.channel + : "minecraft:brand"; + } + return action; + } + + private void syncPayloadCommandFieldFromRaw() { + AutismChatField rawField = textFields.get("payload_data"); + AutismChatField commandField = textFields.get("payload_command_value"); + AutismChatField channelField = textFields.get("payload_channel"); + if (rawField == null || commandField == null) return; + try { + byte[] bytes = AutismPayloadSupport.parsePayloadBytes(rawField.getText()); + Integer value = AutismPayloadSupport.tryParseCommandApiValue(null, + channelField == null ? "" : channelField.getText(), bytes); + if (value == null) { + AutismClientMessaging.sendPrefixed("§cCould not parse a CommandApi integer from the current payload bytes."); + return; + } + toggleStates.put("payload_command_api", true); + commandField.setText(String.valueOf(value)); + } catch (Exception e) { + AutismClientMessaging.sendPrefixed("§cInvalid payload data: " + AutismPayloadSupport.safeMessage(e)); + } + } + + private void syncPayloadRawFieldFromCommand() { + AutismChatField rawField = textFields.get("payload_data"); + AutismChatField commandField = textFields.get("payload_command_value"); + if (rawField == null || commandField == null) return; + try { + byte[] bytes = AutismPayloadSupport.parsePayloadBytes(rawField.getText()); + int value = Integer.parseInt(commandField.getText().strip()); + toggleStates.put("payload_command_api", true); + rawField.setText(AutismPayloadSupport.toHex(AutismPayloadSupport.withCommandApiValue(bytes, value))); + } catch (Exception e) { + AutismClientMessaging.sendPrefixed("§cFailed to sync CommandApi value: " + AutismPayloadSupport.safeMessage(e)); + } + } + + private void syncPayloadTextFieldFromRaw() { + AutismChatField rawField = textFields.get("payload_data"); + AutismChatField textField = textFields.get("payload_text"); + if (rawField == null || textField == null) return; + try { + byte[] bytes = AutismPayloadSupport.parsePayloadBytes(rawField.getText()); + String text = AutismPayloadSupport.decodeLikelyUtf8Text(bytes); + if (text.isBlank()) { + AutismClientMessaging.sendPrefixed("§cThe current payload bytes do not look like readable UTF-8 text."); + return; + } + textField.setText(text); + } catch (Exception e) { + AutismClientMessaging.sendPrefixed("§cInvalid payload data: " + AutismPayloadSupport.safeMessage(e)); + } + } + + private void syncPayloadRawFieldFromText() { + AutismChatField rawField = textFields.get("payload_data"); + AutismChatField textField = textFields.get("payload_text"); + if (rawField == null || textField == null) return; + rawField.setText(AutismPayloadSupport.toHex(textField.getText().getBytes(StandardCharsets.UTF_8))); + } + + private void renderDelayPacketsPresetButtons(GuiGraphicsExtractor ctx, int x, int y, int w, int mx, int my) { + int btnH = 14; + int halfW = (w - 4) / 2; + int x2 = x + halfW + 4; + renderOverlayButton(ctx, x, y + 2, halfW, btnH, "Default", CompactOverlayButton.Variant.SECONDARY, true, mx, my, () -> { + autismclient.util.macro.DelayPacketsAction tmp = new autismclient.util.macro.DelayPacketsAction(); + tmp.applyDefaultPreset(); + stringLists.put("c2sPackets", new ArrayList<>(tmp.c2sPacketNames)); + stringLists.put("s2cPackets", new ArrayList<>(tmp.s2cPacketNames)); + }); + renderOverlayButton(ctx, x2, y + 2, halfW, btnH, "Module", CompactOverlayButton.Variant.PRIMARY, true, mx, my, () -> { + autismclient.util.macro.DelayPacketsAction tmp = new autismclient.util.macro.DelayPacketsAction(); + tmp.applyModulePreset(); + stringLists.put("c2sPackets", new ArrayList<>(tmp.c2sPacketNames)); + stringLists.put("s2cPackets", new ArrayList<>(tmp.s2cPacketNames)); + }); + } + + private CompactOverlayButton renderOverlayButton( + GuiGraphicsExtractor ctx, + int x, + int y, + int w, + int h, + String label, + CompactOverlayButton.Variant variant, + boolean active, + int mx, + int my, + Runnable action + ) { + return renderOverlayButton(ctx, x, y, w, h, label, variant, active, mx, my, action, null, null, null); + } + + private CompactOverlayButton renderOverlayButton( + GuiGraphicsExtractor ctx, + int x, + int y, + int w, + int h, + String label, + CompactOverlayButton.Variant variant, + boolean active, + int mx, + int my, + Runnable action, + Runnable secondaryAction + ) { + return renderOverlayButton(ctx, x, y, w, h, label, variant, active, mx, my, action, secondaryAction, null, null); + } + + private CompactOverlayButton renderOverlayToggleButton( + GuiGraphicsExtractor ctx, + int x, + int y, + int w, + int h, + String label, + boolean toggleState, + String animationKey, + int mx, + int my, + Runnable action + ) { + return renderOverlayButton( + ctx, x, y, w, h, label, + toggleState ? CompactOverlayButton.Variant.SUCCESS : CompactOverlayButton.Variant.DANGER, + true, mx, my, action, null, toggleState, animationKey + ); + } + + private CompactOverlayButton renderOverlayButton( + GuiGraphicsExtractor ctx, + int x, + int y, + int w, + int h, + String label, + CompactOverlayButton.Variant variant, + boolean active, + int mx, + int my, + Runnable action, + Runnable secondaryAction, + Boolean toggleState, + String animationKey + ) { + CompactOverlayButton button = CompactOverlayButton.create( + x, + y, + w, + h, + Component.literal(label), + ignored -> action.run(), + secondaryAction == null ? null : ignored -> secondaryAction.run() + ); + button.setVariant(variant); + if (toggleState != null) { + button.setToggleState(toggleState).setAnimationKey(animationKey); + } + button.active = active; + CompactOverlayButton.renderStyled(ctx, textRenderer, button, mx, my); + if (toggleState == null) { + UiRenderer.outline(ctx, UiBounds.of(x, y, w, h), macroEditorButtonOutline(variant, active)); + } + hitRegions.add(new HitRegion(button, action)); + return button; + } + + private static int macroEditorButtonOutline(CompactOverlayButton.Variant variant, boolean active) { + if (!active) return 0x88402A30; + return switch (variant == null ? CompactOverlayButton.Variant.SECONDARY : variant) { + case SUCCESS -> autismclient.util.AutismTheme.recolor(0xFF35D873, autismclient.util.AutismTheme.Channel.SUCCESS); + case DANGER -> autismclient.util.AutismTheme.recolor(0xFFFF3B3B, autismclient.util.AutismTheme.Channel.DANGER); + case PRIMARY, FILTER_ON -> autismclient.util.AutismTheme.recolor(0xFFFF5B5B, autismclient.util.AutismTheme.Channel.BUTTON); + case GHOST, FILTER_OFF, SECONDARY -> autismclient.util.AutismTheme.recolor(0xFFFF3B3B, autismclient.util.AutismTheme.Channel.OUTLINE); + }; + } + + private CompactOverlayButton renderFieldCaptureButton( + GuiGraphicsExtractor ctx, + int x, + int y, + int w, + int h, + CaptureMode mode, + boolean capturing, + boolean active, + int mx, + int my, + Runnable action + ) { + return renderFieldCaptureButton(ctx, x, y, w, h, mode, capturing, active, mx, my, null, null, action); + } + + private CompactOverlayButton renderFieldCaptureButton( + GuiGraphicsExtractor ctx, + int x, + int y, + int w, + int h, + CaptureMode mode, + boolean capturing, + boolean active, + int mx, + int my, + String idleLabel, + String capturingLabel, + Runnable action + ) { + if (!captureControlAvailable(mode)) return null; + CompactOverlayButton button = MacroCaptureButton.render( + ctx, + textRenderer, + UiBounds.of(x, y, w, h), + mode, + capturing, + active, + mx, + my, + idleLabel, + capturingLabel, + action + ); + hitRegions.add(new HitRegion(button, action)); + return button; + } + + private void renderIconDeleteButton(GuiGraphicsExtractor ctx, int x, int y, int size, int mx, int my, Runnable action) { + boolean hovered = mx >= x && mx < x + size && my >= y && my < y + size; + MacroTypedListControl.renderDelete(ctx, UiBounds.of(x, y, size, size), hovered); + hitRegions.add(new HitRegion(x, y, size, size, (mouseX, mouseY, mouseButton) -> { + if (mouseButton != 0) return false; + action.run(); + return true; + })); + } + + private void renderActionButton(GuiGraphicsExtractor ctx, int x, int y, int w, int h, + String label, int mx, int my, Runnable action) { + renderOverlayButton(ctx, x, y, w, h, label, CompactOverlayButton.Variant.SECONDARY, true, mx, my, action); + } + + private int renderEditorHint(GuiGraphicsExtractor ctx, int x, int y, int w, String text) { + return renderEditorHint(ctx, x, y, w, text, AutismColors.textDim()); + } + + private int renderEditorHint(GuiGraphicsExtractor ctx, int x, int y, int w, String text, int color) { + String hint = formatEditorHint(text); + if (hint.isEmpty()) return y; + Identifier font = theme.fontFor(UiTone.BODY); + List lines = wrapEditorHint(hint, Math.max(10, w), font, color); + int cy = y; + for (String line : lines) { + UiText.draw(ctx, textRenderer, line, font, color, x, cy + 2, false); + cy += EDITOR_HINT_ROW_H; + } + return cy; + } + + private List wrapEditorHint(String hint, int maxWidth, Identifier font, int color) { + if (hint == null || hint.isBlank()) return List.of(); + String safe = hint.trim().replaceAll("\\s+", " "); + if (UiText.width(textRenderer, safe, font, color) <= maxWidth) return List.of(safe); + String[] words = safe.split(" "); + StringBuilder first = new StringBuilder(); + StringBuilder second = new StringBuilder(); + for (String word : words) { + String candidate = first.length() == 0 ? word : first + " " + word; + if (second.length() == 0 && UiText.width(textRenderer, candidate, font, color) <= maxWidth) { + first.setLength(0); + first.append(candidate); + } else { + if (second.length() > 0) second.append(' '); + second.append(word); + } + } + if (second.length() == 0 || first.length() == 0) { + return List.of(UiText.trimToWidth(textRenderer, safe, maxWidth, font, color)); + } + String secondLine = UiText.width(textRenderer, second.toString(), font, color) <= maxWidth + ? second.toString() + : UiText.trimToWidth(textRenderer, second.toString(), maxWidth, font, color); + return List.of(first.toString(), secondLine); + } + + private String formatEditorHint(String text) { + if (text == null) return ""; + String normalized = text.trim().replaceAll("\\s+", " "); + if (normalized.isEmpty()) return ""; + if (normalized.startsWith("Config-phase payload")) return "Config payload may disconnect."; + + String exact = switch (normalized) { + case "Editing this row. 0 means drop the full stack from that slot or item." -> "Editing row. 0 = full stack."; + case "No row selected. The controls below set defaults for new rows you add." -> "No row picked. Controls set new-row defaults."; + case "Continue when any LAN peer reaches the target step." -> "Waits for any LAN peer step."; + case "Add peers below to narrow it down. Until then, it waits for any peer at the fallback step." -> "Add peers below or use fallback."; + case "Each peer below must reach its step before this continues." -> "All listed peers must reach their step."; + case "No packets selected. This step will continue on the next packet in either direction." -> "No filters: next packet continues."; + case "This step continues as soon as any selected C2S or S2C packet arrives." -> "Waits for any chosen packet."; + case "Capture only marks the block. It will not open it." -> "Capture only marks the block."; + case "0,0,0 uses the current container when open, otherwise the closest nearby one." -> "0,0,0 = current or nearest container."; + case "Pick on an item adds the item. Pick on an empty slot adds that exact slot." -> "Filled slot = item. Empty slot = exact slot."; + case "Pick only accepts chest/custom GUI slots here." -> "Pick only works on GUI slots here."; + case "Pick only accepts player inventory slots here." -> "Pick only works in your inventory here."; + case "No payment targets selected yet." -> "No players selected."; + case "Click a scanned name to toggle it, or use All to add the filtered scan results." -> "Click names to toggle, or use All."; + case "The search box also lets you manually add a player by pressing Enter." -> "Press Enter to add a typed player."; + case "Pick modules below, then click the mode chip on each row." -> "Pick modules, then set each mode."; + case "Each row runs with its own Toggle / Enable / Disable setting." -> "Each row keeps its own mode."; + case "Capture View fills in your current yaw and pitch." -> "Capture View fills yaw and pitch."; + case "Wait for Arrival continues only after Baritone finishes." -> "Waits until Baritone arrives."; + case "Simple disconnect. Delay only controls how long to wait before closing the connection." -> "Simple disconnect after the delay."; + case "Sends lag packets, then the selected kick packet. Packet Count controls how hard it pushes." -> "Sends lag, then the kick packet."; + case "Kick Dupe will run the next eligible macro actions inside the lag sandwich, then kick." -> "Runs next actions inside the dupe kick."; + case "Kick Dupe will try to use a bundle, then kick." -> "Tries bundle dupe, then kicks."; + case "Automatically detects teleport/world change and disconnects at the perfect timing for dupe exploits." -> "Auto-disconnects at the perfect dupe timing."; + case "Waits until the current GUI closes." -> "Waits for the GUI to close."; + case "Waits until a GUI opens." -> "Waits for any GUI to open."; + case "Blank pattern waits for any incoming server or plugin message." -> "Blank pattern = any server message."; + case "Blank pattern waits for any incoming chat line." -> "Blank pattern = any chat line."; + case "Regex is on, so the pattern must match with Java regex rules." -> "Regex mode uses Java regex rules."; + case "No modules found right now." -> "No modules found."; + case "Press Scan to load the current server players." -> "Press Scan for players."; + case "Click a row to use that message." -> "Click a row to use it."; + case "Pick target blocks, then choose the stop rule you want." -> "Pick blocks, then choose a stop rule."; + default -> ""; + }; + if (!exact.isEmpty()) return fitEditorHintText(exact); + + normalized = normalized + .replace("Waits until", "Waits for") + .replace("Continue when", "Continues when") + .replace("This step continues as soon as", "Continues when") + .replace("the selected", "chosen") + .replace("the current", "this") + .replace("current ", "") + .replace("number of times", "times") + .replace("the chosen number of times", "times") + .replace("the chosen ticks", "set ticks") + .replace("only after", "after") + .replace("It will not", "Won't") + .replace("selected kick packet", "kick packet") + .replace("Packet Count controls how hard it pushes", "Packet Count controls force") + .replace("the open handler", "the open GUI") + .replace("player inventory", "inventory") + .replace("inventory slot", "slot") + .replace("the matched item into", "it into") + .replace("first matching visible slot", "first visible match") + .replace("contains an item that matches the optional name", "matches the optional item") + .replace("becomes empty", "turns empty") + .replace("reaches the target count", "hits the target count") + .replace("drops below the target count", "drops below the target") + .replace("on the first content or count change in that exact slot", "on the first exact slot change") + .replace("the block under your crosshair", "your target block") + .replace("the entity under your crosshair", "your target entity") + .replace("whatever is under your crosshair", "your target") + .replace("will attack or break", "acts on") + .replace("will interact with", "uses") + .replace("the currently selected hotbar item", "the held item"); + + return fitEditorHintText(normalized); + } + + private void applyEditorPlaceholders() { + if (schema != null) { + for (FieldDef field : schema.fields()) { + switch (field.type()) { + case TEXT, MACRO_SELECT, NUMBER, DECIMAL, SLOT -> applyTextFieldPlaceholder(field.key(), resolveFieldPlaceholder(field)); + case BLOCK_POS -> applyBlockPosPlaceholders(field.key()); + default -> { + } + } + } + } + + applyTextFieldPlaceholder("item_guiName", "Any GUI"); + applyTextFieldPlaceholder("drop_guiName", "Any GUI"); + applyTextFieldPlaceholder("lan_defaultStep", "Any step"); + applyTextFieldPlaceholder("item_entrySlot", "Slot"); + applyTextFieldPlaceholder("place_itemSlot", "Slot"); + applyTextFieldPlaceholder("drop_entrySlot", "Slot #"); + applyTextFieldPlaceholder("_craft_amount", "1"); + applyTextFieldPlaceholder("_lan_step_add", "1"); + applyTextFieldPlaceholder("drop_globalCount", "1"); + applyTextFieldPlaceholder("amountInput", "1k"); + + applyAddFieldPlaceholder("_item_add", "Any item"); + applyAddFieldPlaceholder("_drop_add", "Any item"); + applyAddFieldPlaceholder("_craft_search", "Find recipe"); + applyAddFieldPlaceholder("_lan_user_add", "Peer name"); + applyAddFieldPlaceholder("soundIds", "Find sound"); + applyAddFieldPlaceholder("entityIds", "Find entity"); + applyAddFieldPlaceholder("targetItems", "Item name"); + applyAddFieldPlaceholder("players", "Find player"); + applyAddFieldPlaceholder("_toggle_module_search", "Find module"); + applyAddFieldPlaceholder("_wait_chat_search", "Find chat"); + } + + private void applyTextFieldPlaceholder(String key, String placeholder) { + AutismChatField field = textFields.get(key); + setEditorPlaceholder(field, placeholder); + } + + private void applyAddFieldPlaceholder(String key, String placeholder) { + AutismChatField field = addFields.get(key); + setEditorPlaceholder(field, placeholder); + } + + private void applyBlockPosPlaceholders(String key) { + applyTextFieldPlaceholder(key + "_0", "X"); + applyTextFieldPlaceholder(key + "_1", "Y"); + applyTextFieldPlaceholder(key + "_2", "Z"); + } + + private void setEditorPlaceholder(AutismChatField field, String placeholder) { + if (field == null || placeholder == null || placeholder.isBlank()) return; + field.setPlaceholder(Component.literal(fitEditorGhostText(placeholder))); + } + + private String resolveFieldPlaceholder(FieldDef field) { + if (field == null) return ""; + return switch (field.key()) { + case "guiName", "waitGuiName" -> "Any GUI"; + case "listFilterText" -> "text to match"; + case "listExcludeText" -> "name1, name2"; + case "pattern" -> "Any chat"; + case "message" -> "Type message"; + case "description" -> "Quick note"; + case "customText" -> "Optional text"; + case "customFilePath" -> "File in book-sources/"; + case "characters" -> "1024"; + case "title" -> targetAction != null && targetAction.getType() == MacroActionType.NBT_BOOK ? "Book title" : "Optional title"; + case "guiTitle" -> "Optional title"; + case "customName" -> "Optional name"; + case "commandTemplate" -> "/pay

"; + case "amountInput" -> "1k"; + case "itemName", "fromItemName", "toItemName" -> "Any item"; + case "moduleName" -> "Pick below"; + case "slot", "fromSlot", "toSlot", "slotNumber", "targetSlot" -> "Slot #"; + case "healthThreshold" -> "0-20"; + case "yaw", "pitch" -> "0"; + case "delayMs" -> "0"; + case "delayTicks" -> "0"; + case "clickCount", "useCount", "holdTicks", "packetCount", "maxDistance", "stopSlotsUsed", + "slotsUsedThreshold", "minedCountTarget", "timeoutSeconds", "durationTicks", + "tickOffset", "preGenCount", "revisionOffset", "maxWaitMs", "bufferMs" -> "1"; + default -> switch (field.type()) { + case TEXT, MACRO_SELECT -> fitEditorGhostText(field.label()); + case SLOT -> "Slot #"; + case NUMBER, DECIMAL -> "0"; + default -> ""; + }; + }; + } + + private String fitEditorGhostText(String text) { + String normalized = text == null ? "" : text.trim().replaceAll("\\s+", " "); + if (normalized.length() <= EDITOR_GHOST_MAX_CHARS) return normalized; + int cutoff = normalized.lastIndexOf(' ', EDITOR_GHOST_MAX_CHARS - 3); + if (cutoff < 5) cutoff = EDITOR_GHOST_MAX_CHARS - 3; + return normalized.substring(0, Math.max(1, cutoff)).trim() + "..."; + } + + private String fitEditorHintText(String text) { + + return text == null ? "" : text.trim().replaceAll("\\s+", " "); + } + + private void renderRow(GuiGraphicsExtractor ctx, FieldDef field, int x, int y, int w, + int mx, int my, float delta) { + if (isGuiWaitBeforeKey(field.key())) { + renderGuiWaitRow(ctx, theme.fontFor(UiTone.BODY), field.key(), "waitForGuiAfter", x, y, w, mx, my); + return; + } + if ("safeClickDelayTicks".equals(field.key())) { + renderXCarrySafeDelaySlider(ctx, x, y, w, mx, my); + return; + } + switch (field.type()) { + case TOGGLE -> renderToggle (ctx, field, x, y, w, mx, my); + case NUMBER, + DECIMAL, + TEXT, + MACRO_SELECT, + SLOT -> renderTextField(ctx, field, x, y, w, mx, my, delta); + case ENUM -> renderEnum (ctx, field, x, y, w, mx, my); + case BLOCK_POS -> renderBlockPos (ctx, field, x, y, w, mx, my, delta); + case STRING_LIST -> { + if (isRacePickerList(field)) + renderRacePickerList(ctx, field, x, y, w, mx, my); + else if (field.captureMode() == CaptureMode.BLOCK_CATALOG) + renderStringListCatalog(ctx, field, x, y, w, mx, my, delta); + else + renderStringList(ctx, field, x, y, w, mx, my, delta); + } + case TARGET_SUMMARY -> renderTargetSummary(ctx, field, x, y, w); + case CAPTURE_BUTTON -> renderCaptureButton(ctx, field, x, y, w, mx, my); + case CONDITION -> renderConditionSummary(ctx, field, x, y, w); + } + } + + private void renderConditionSummary(GuiGraphicsExtractor ctx, FieldDef field, int x, int y, int w) { + Identifier font = theme.fontFor(UiTone.BODY); + int lw = labelWidth(w, field.label(), font, 56); + drawLabel(ctx, field.label(), x, y, lw, font); + + String summary = liveConditionSummary(field.key()); + int valX = controlX(x, lw); + int valW = controlWidth(w, lw); + int color = AutismColors.textPrimary(); + String trimmed = UiText.width(textRenderer, summary, font, color) > valW + ? UiText.trimToWidth(textRenderer, summary, Math.max(8, valW - 4), font, color) + : summary; + UiText.draw(ctx, textRenderer, trimmed, font, color, valX, y + 2, false); + } + + private String liveConditionSummary(String conditionKey) { + CompoundTag stored = (workingTag != null && workingTag.get(conditionKey) instanceof CompoundTag c) ? c : null; + boolean hasFlatEditor = getField("cond_kind") != null; + boolean flatEditable = hasFlatEditor; + if (hasFlatEditor && stored != null) { + try { + flatEditable = autismclient.util.macro.MacroCondition.fromTag(stored).simpleLeafOrNull() != null; + } catch (Throwable ignored) { + flatEditable = true; + } + } + if (flatEditable && hasFlatEditor) { + CompoundTag flat = new CompoundTag(); + flat.putString("cond_kind", currentEnumValue("cond_kind")); + flat.putBoolean("cond_negate", toggleStates.getOrDefault("cond_negate", false)); + flat.putString("cond_item", conditionFieldText("cond_item")); + flat.putString("cond_op", currentEnumValue("cond_op")); + flat.putString("cond_value", conditionFieldText("cond_value")); + flat.putString("cond_cmp", currentEnumValue("cond_cmp")); + flat.putInt("cond_amount", conditionFieldInt("cond_amount", 0)); + flat.putInt("cond_slot", conditionFieldInt("cond_slot", 0)); + try { + return autismclient.util.macro.MacroCondition.readFlatLeaf(flat, "cond_").summary(); + } catch (Throwable ignored) { } + } + if (stored != null) { + try { return autismclient.util.macro.MacroCondition.fromTag(stored).summary(); } + catch (Throwable ignored) { } + } + return "always"; + } + + private String conditionFieldText(String key) { + AutismChatField f = textFields.get(key); + return f == null ? "" : f.getText(); + } + + private int conditionFieldInt(String key, int fallback) { + AutismChatField f = textFields.get(key); + if (f == null) return fallback; + try { return Integer.parseInt(f.getText().strip()); } + catch (NumberFormatException ignored) { return fallback; } + } + + private void renderPlaceItemRow(GuiGraphicsExtractor ctx, int x, int y, int w, + int mx, int my, float delta) { + AutismChatField nameF = textFields.get("itemName"); + AutismChatField slotF = textFields.get("place_itemSlot"); + if (nameF == null || slotF == null) return; + + int pickW = 32; + int slotW = 26; + int gap = 3; + int pickX = x + w - pickW; + int slotX = pickX - gap - slotW; + int nameW = Math.max(1, slotX - x - 2); + + nameF.setX(x); + nameF.setY(y + 1); + nameF.setWidth(nameW); + nameF.render(ctx, mx, my, delta); + + slotF.setX(slotX); + slotF.setY(y + 1); + slotF.setWidth(slotW); + slotF.render(ctx, mx, my, delta); + + boolean capt = captureSession.isItemSlotCapture("itemName"); + renderFieldCaptureButton( + ctx, + pickX, + y, + pickW, + 14, + CaptureMode.ITEM_SLOT, + capt, + true, + mx, + my, + () -> toggleItemSlotCapture("itemName") + ); + } + + private void renderTargetSummary(GuiGraphicsExtractor ctx, FieldDef field, int x, int y, int w) { + Identifier font = theme.fontFor(UiTone.BODY); + int lw = labelWidth(w, field.label(), font, 56); + drawLabel(ctx, field.label(), x, y, lw, font); + + String summary = resolvePacketClickTargetSummary(); + int valX = controlX(x, lw); + int valW = controlWidth(w, lw); + int color = summary == null || summary.isEmpty() + ? AutismColors.textSecondary() + : AutismColors.textPrimary(); + String display = (summary == null || summary.isEmpty()) ? "Not captured" : summary; + String trimmed = UiText.width(textRenderer, display, font, color) > valW + ? UiText.trimToWidth(textRenderer, display, Math.max(8, valW - 4), font, color) + : display; + UiText.draw(ctx, textRenderer, trimmed, font, color, valX, y + 2, false); + } + + private void renderCaptureButton(GuiGraphicsExtractor ctx, FieldDef field, int x, int y, int w, int mx, int my) { + Identifier font = theme.fontFor(UiTone.BODY); + int btnW = 60; + int btnH = 14; + int lw = labelWidth(w, field.label(), font, btnW); + drawLabel(ctx, field.label(), x, y, lw, font); + + boolean capturing = field.key().equals(packetClickCapturePendingKey); + int btnX = x + w - btnW; + renderFieldCaptureButton( + ctx, + btnX, + y + 2, + btnW, + btnH, + CaptureMode.PACKET_CLICK_TARGET, + capturing, + true, + mx, + my, + "Re-capture", + "Click slot...", + () -> beginPacketClickCapture(field.key()) + ); + } + + private String resolvePacketClickTargetSummary() { + if (!(targetAction instanceof autismclient.util.macro.PacketClickAction pca)) return null; + if (pca.target == null) return null; + return pca.target.withMode(currentPacketClickMode()).summary(); + } + + private boolean isRacePickerList(FieldDef field) { + return targetAction != null + && targetAction.getType() == MacroActionType.RACE + && field != null + && "raceSteps".equals(field.key()); + } + + private void renderRacePickerList(GuiGraphicsExtractor ctx, FieldDef field, int x, int y, int w, int mx, int my) { + String key = field.key(); + List values = stringLists.computeIfAbsent(key, ignored -> new ArrayList<>()); + Identifier font = theme.fontFor(UiTone.BODY); + + UiText.draw(ctx, textRenderer, field.label() + " (" + values.size() + ")", font, + AutismColors.textSecondary(), x, y + 2, false); + + int addY = y + 13; + int gap = 4; + int btnW = Math.max(60, (w - gap) / 2); + renderOverlayButton(ctx, x, addY, btnW, 14, "+ Condition", CompactOverlayButton.Variant.PRIMARY, + true, mx, my, () -> openRaceStepSelector(values, true)); + renderOverlayButton(ctx, x + btnW + gap, addY, Math.max(60, w - btnW - gap), 14, "+ Action", CompactOverlayButton.Variant.SUCCESS, + true, mx, my, () -> openRaceStepSelector(values, false)); + int listY = addY + 18; + int rowH = 18; + int visibleRows = SEL_LIST_MAX_VIS; + DirectScrollViewport viewport = getOrCreateViewport(selectedScrollViewports, key + "_race", + x, listY, w, visibleRows * rowH, rowH, SCROLLBAR_W); + viewport.setContentHeight(values.size() * rowH); + viewport.renderScrollbar(ctx, mx, my); + + if (values.isEmpty()) { + String hint = "Use +Cond for waits or +Act for batch actions."; + CompactListRenderer.drawEmptyState(ctx, textRenderer, hint, x, listY, w - SCROLLBAR_W - 1); + return; + } + + int buttonW = 14; + int rowGap = 2; + int buttonArea = (buttonW * 3) + (rowGap * 2); + int rowTextW = Math.max(20, w - SCROLLBAR_W - buttonArea - 7); + viewport.beginRender(ctx, theme.borderSoft(), 0x36000000); + int first = viewport.getFirstVisibleRow(); + for (int vi = first; vi < values.size() && vi <= viewport.getLastVisibleRow(); vi++) { + int rowY = viewport.getRowScreenY(vi); + if (rowY == Integer.MIN_VALUE) continue; + String value = values.get(vi); + boolean hovered = mx >= x && mx < x + rowTextW && my >= rowY && my < rowY + rowH; + renderRaceStepRow(ctx, x, rowY, rowTextW, rowH, vi, value, hovered); + int bx = x + rowTextW + 3; + int rowIndex = vi; + renderRaceListSymbolButton(ctx, bx, rowY + 2, buttonW, mx, my, "^", + false, rowIndex > 0, () -> Collections.swap(values, rowIndex, rowIndex - 1)); + bx += buttonW + rowGap; + renderRaceListSymbolButton(ctx, bx, rowY + 2, buttonW, mx, my, "v", + false, rowIndex + 1 < values.size(), () -> Collections.swap(values, rowIndex, rowIndex + 1)); + bx += buttonW + rowGap; + boolean canDelete = raceActionCount(values) > 1 || !isRaceActionStep(value); + renderRaceListSymbolButton(ctx, bx, rowY + 2, buttonW, mx, my, "X", + true, canDelete, () -> { + if (rowIndex >= 0 && rowIndex < values.size() + && (raceActionCount(values) > 1 || !isRaceActionStep(values.get(rowIndex)))) { + values.remove(rowIndex); + } + }); + } + viewport.endRender(ctx); + } + + private void renderRaceStepRow(GuiGraphicsExtractor ctx, int x, int y, int w, int h, int index, String step, boolean hovered) { + String canonical = autismclient.util.macro.RaceAction.canonicalRaceStep(step); + boolean condition = autismclient.util.macro.RaceAction.isConditionStep(canonical); + int bgColor = hovered ? AutismColors.rowHover() : AutismColors.rowNormal(); + CompactSurfaces.tintedRow(ctx, x, y + 1, w, h - 2, bgColor); + int badgeColor = condition ? -30720 : -12268476; + CompactSurfaces.indicator(ctx, x + 1, y + 3, 3, h - 6, badgeColor); + int numberColor = AutismColors.textDim(); + UiText.draw(ctx, textRenderer, String.valueOf(index + 1), theme.fontFor(UiTone.BODY), numberColor, + x + 8, UiSizing.alignTextY(y, h, theme.fontHeight(UiTone.BODY), theme.bodyTextNudge()), false); + String role = condition ? "COND" : "ACT"; + int roleColor = condition ? AutismColors.packetCyan() : AutismColors.textSecondary(); + int roleX = x + 24; + UiText.draw(ctx, textRenderer, role, theme.fontFor(UiTone.LABEL), roleColor, + roleX, UiSizing.alignTextY(y, h, theme.fontHeight(UiTone.LABEL), theme.bodyTextNudge()), false); + String label = raceStepDisplay(step).replaceFirst("^(COND|ACT)\\s+", ""); + int labelX = roleX + 34; + String trimmed = UiText.trimToWidth(textRenderer, label, Math.max(1, x + w - labelX - 4), + theme.fontFor(UiTone.BODY), -1); + UiText.draw(ctx, textRenderer, trimmed, theme.fontFor(UiTone.BODY), -1, + labelX, UiSizing.alignTextY(y, h, theme.fontHeight(UiTone.BODY), theme.bodyTextNudge()), false); + } + + private void renderRaceListSymbolButton(GuiGraphicsExtractor ctx, int x, int y, int size, int mx, int my, + String symbol, boolean danger, boolean active, Runnable action) { + boolean hovered = active && mx >= x && mx < x + size && my >= y && my < y + size; + MacroTypedListControl.renderSymbol(ctx, UiBounds.of(x, y, size, size), symbol, hovered, danger); + hitRegions.add(new HitRegion(x, y, size, size, (mouseX, mouseY, mouseButton) -> { + if (!active || mouseButton != 0) return false; + action.run(); + return true; + })); + } + + private void openRaceStepSelector(List values, boolean condition) { + List options = condition + ? raceSelectorOptions(RACE_CONDITION_CHOICES, "CONDITION") + : raceSelectorOptions(RACE_ACTION_CHOICES, "ACTION"); + raceStepSelectorOverlay.open(condition ? "Condition Selector" : "Action Selector", options, option -> { + if (option == null || option.id() == null || option.id().isBlank()) return; + values.add((condition ? "CONDITION:" : "ACTION:") + option.id()); + refreshInteractiveLayout(); + }); + } + + private List raceSelectorOptions(List choices, String role) { + ArrayList out = new ArrayList<>(); + for (String choice : choices) { + String[] parts = choice == null ? new String[0] : choice.split("/", 2); + String category = parts.length > 1 ? parts[0].trim() : role; + String id = raceChoiceValue(choice); + if (id.isBlank()) continue; + String label = id.replace('_', ' '); + out.add(new RaceStepSelectorOverlay.Option(category, id, label, role)); + } + return out; + } + + private String raceStepDisplay(String step) { + String canonical = autismclient.util.macro.RaceAction.canonicalRaceStep(step); + String type = autismclient.util.macro.RaceAction.stepTypeName(canonical); + return (autismclient.util.macro.RaceAction.isConditionStep(canonical) ? "COND " : "ACT ") + type; + } + + private boolean isRaceActionStep(String step) { + return autismclient.util.macro.RaceAction.isActionStep(autismclient.util.macro.RaceAction.canonicalRaceStep(step)); + } + + private int raceActionCount(List values) { + int count = 0; + if (values != null) { + for (String value : values) { + if (isRaceActionStep(value)) count++; + } + } + return count; + } + + private String raceChoiceValue(String choice) { + if (choice == null) return ""; + int slash = choice.lastIndexOf('/'); + return (slash >= 0 ? choice.substring(slash + 1) : choice).trim(); + } + + private void beginPacketClickCapture(String fieldKey) { + if (!(targetAction instanceof autismclient.util.macro.PacketClickAction)) return; + packetClickCapturePendingKey = fieldKey; + autismclient.util.AutismContainerHold.setPendingCapture(target -> applyPacketClickCapture(target)); + enterCaptureMode(); + } + + private void applyPacketClickCapture(autismclient.util.AutismPacketClick.Target target) { + if (target == null) return; + if (targetAction instanceof autismclient.util.macro.PacketClickAction pca) { + autismclient.util.AutismPacketClick.Mode mode = currentPacketClickMode(); + pca.mode = mode.name(); + pca.setTarget(target.withMode(mode)); + if (workingTag != null) { + workingTag.putString("mode", mode.name()); + workingTag.put("target", target.withMode(mode).toTag()); + } + } + packetClickCapturePendingKey = null; + exitCaptureMode(false, false); + } + + private autismclient.util.AutismPacketClick.Mode currentPacketClickMode() { + FieldDef modeField = fieldByKey("mode"); + if (modeField != null && modeField.type() == FieldType.ENUM && !modeField.enumOptions().isEmpty()) { + int idx = Math.max(0, Math.min(enumIndices.getOrDefault("mode", 0), modeField.enumOptions().size() - 1)); + return autismclient.util.AutismPacketClick.Mode.fromName(modeField.enumOptions().get(idx)); + } + return autismclient.util.AutismPacketClick.Mode.fromName(workingTag == null ? "" : workingTag.getStringOr("mode", "")); + } + + private FieldDef fieldByKey(String key) { + if (schema == null || key == null) return null; + for (FieldDef field : schema.fields()) { + if (key.equals(field.key())) return field; + } + return null; + } + + public boolean wantsPacketClickCapture() { + return packetClickCapturePendingKey != null + && autismclient.util.AutismContainerHold.hasPendingCapture(); + } + + public boolean cancelPacketClickCaptureIfActive() { + if (packetClickCapturePendingKey == null) return false; + autismclient.util.AutismContainerHold.clearPendingCapture(); + packetClickCapturePendingKey = null; + exitCaptureMode(false, false); + return true; + } + + private boolean isGuiWaitBeforeKey(String key) { + return "waitForGuiBefore".equals(key); + } + + private boolean isGuiWaitAfterKey(String key) { + return "waitForGuiAfter".equals(key); + } + + private void renderToggle(GuiGraphicsExtractor ctx, FieldDef field, int x, int y, int w, + int mx, int my) { + String key = field.key(); + boolean val = toggleStates.getOrDefault(key, false); + Identifier font = theme.fontFor(UiTone.BODY); + + int btnW = 34; + int btnH = 14; + int lw = labelWidth(w, field.label(), font, btnW); + drawLabel(ctx, field.label(), x, y, lw, font); + + int btnX = x + w - btnW; + renderOverlayToggleButton( + ctx, + btnX, + y + 2, + btnW, + btnH, + val ? "ON" : "OFF", + val, + "macro-field:" + key, + mx, + my, + () -> { + boolean nowOn = !toggleStates.getOrDefault(key, false); + toggleStates.put(key, nowOn); + if (workingTag != null) { + workingTag.putBoolean(key, nowOn); + } + if (nowOn && field.hasMutualExclusion()) { + for (String other : field.mutuallyExclusiveWith()) { + toggleStates.put(other, false); + if (workingTag != null) { + workingTag.putBoolean(other, false); + } + } + } + }); + } + + private void renderTextField(GuiGraphicsExtractor ctx, FieldDef field, int x, int y, int w, + int mx, int my, float delta) { + String key = field.key(); + AutismChatField tf = textFields.get(key); + if (tf == null) return; + Identifier font = theme.fontFor(UiTone.BODY); + + if (field.type() == FieldType.MACRO_SELECT) { + renderMacroSelector(ctx, field, tf, x, y, w, mx, my); + return; + } + + if (isWaitChatPatternField(field)) { + UiText.draw(ctx, textRenderer, field.label(), font, + AutismColors.textSecondary(), x, y + 2, false); + tf.setX(x); + tf.setY(y + 13); + int variableW = shouldShowVariableButton(field.key()) ? 24 : 0; + tf.setWidth(Math.max(1, w - (variableW > 0 ? variableW + 2 : 0))); + tf.setHeight(WAIT_CHAT_PATTERN_H); + tf.render(ctx, mx, my, delta); + if (variableW > 0) renderVariableDropdown(field, tf, x + w - variableW, y + 13, variableW); + return; + } + + boolean packetPick = field.captureMode() == CaptureMode.PACKET_NAME; + boolean slotPick = field.type() == FieldType.SLOT && worldCaptureAllowed; + boolean itemSlotPick = field.captureMode() == CaptureMode.ITEM_SLOT && worldCaptureAllowed; + boolean menuButtonPick = field.captureMode() == CaptureMode.CUSTOM_MENU_BUTTON; + boolean nbtBookFilePick = targetAction != null + && targetAction.getType() == MacroActionType.NBT_BOOK + && "customFilePath".equals(key); + int lw = labelWidth(w, field.label(), font, itemSlotPick || packetPick || slotPick || menuButtonPick ? 88 : 56); + drawLabel(ctx, field.label(), x, y, lw, font); + + int tfX = controlX(x, lw); + int variableW = shouldShowVariableButton(key) ? 24 : 0; + + if (menuButtonPick) { + + int pickW = 34; + int availableW = Math.max(1, controlWidth(w, lw) - (variableW > 0 ? variableW + 2 : 0)); + int tfW = Math.max(1, availableW - pickW - 2); + tf.setX(tfX); tf.setY(y + 2); tf.setWidth(tfW); + tf.render(ctx, mx, my, delta); + final String fKey = key; + renderFieldCaptureButton(ctx, tfX + tfW + 2, y + 2, pickW, 14, CaptureMode.CUSTOM_MENU_BUTTON, + false, true, mx, my, () -> pickCustomMenuButtonInto(fKey)); + if (variableW > 0) renderVariableDropdown(field, tf, tfX + tfW + pickW + 4, y + 2, variableW); + } else if (nbtBookFilePick) { + int pickW = 30; + int availableW = Math.max(1, controlWidth(w, lw) - (variableW > 0 ? variableW + 2 : 0)); + int tfW = Math.max(1, availableW - pickW - 2); + tf.setX(tfX); + tf.setY(y + 2); + tf.setWidth(tfW); + tf.render(ctx, mx, my, delta); + renderOverlayButton(ctx, tfX + tfW + 2, y + 2, pickW, 14, "Pick", + CompactOverlayButton.Variant.SECONDARY, true, mx, my, () -> pickNbtBookTextFile(tf)); + if (variableW > 0) renderVariableDropdown(field, tf, tfX + tfW + pickW + 4, y + 2, variableW); + } else if (itemSlotPick || packetPick || slotPick) { + + int pickW = 30; + int availableW = Math.max(1, controlWidth(w, lw) - (variableW > 0 ? variableW + 2 : 0)); + int tfW = slotPick + ? Math.max(26, availableW - pickW - 2) + : Math.max(1, availableW - pickW - 2); + tf.setX(tfX); tf.setY(y + 2); tf.setWidth(tfW); + tf.render(ctx, mx, my, delta); + + int pkX = tfX + tfW + 2; + boolean capt = !packetPick && captureSession.isItemSlotCapture(key); + final String fKey = key; + renderFieldCaptureButton( + ctx, + pkX, + y + 2, + pickW, + 14, + packetPick ? CaptureMode.PACKET_NAME : CaptureMode.ITEM_SLOT, + capt, + true, + mx, + my, + () -> { + if (packetPick) { + openPacketNameFieldSelector(fKey); + return; + } + toggleItemSlotCapture(fKey); + } + ); + if (variableW > 0) renderVariableDropdown(field, tf, pkX + pickW + 2, y + 2, variableW); + } else { + int tfW = Math.max(1, controlWidth(w, lw) - (variableW > 0 ? variableW + 2 : 0)); + tf.setX(tfX); tf.setY(y + 2); tf.setWidth(tfW); + tf.render(ctx, mx, my, delta); + if (variableW > 0) renderVariableDropdown(field, tf, tfX + tfW + 2, y + 2, variableW); + } + } + + private void pickCustomMenuButtonInto(String key) { + autismclient.api.custommenu.CustomMenuSnapshot menu = autismclient.util.custommenu.CustomMenuTracker.current(); + if (menu == null) { + AutismNotifications.warning("No custom screen is open to pick a button from."); + return; + } + java.util.List buttons = new ArrayList<>(); + for (autismclient.api.custommenu.CustomMenuButton button : menu.buttons()) { + if (button.serverRelevant() && !button.label().isBlank()) buttons.add(button); + } + if (buttons.isEmpty()) { + AutismNotifications.warning("This screen has no pressable buttons."); + return; + } + AutismChatField tf = textFields.get(key); + String current = tf == null ? "" : tf.getText().trim(); + int next = 0; + for (int i = 0; i < buttons.size(); i++) { + if (buttons.get(i).label().equalsIgnoreCase(current)) { next = (i + 1) % buttons.size(); break; } + } + String label = buttons.get(next).label(); + if (tf != null) tf.setText(label); + AutismNotifications.show("Button set to \"" + label + "\"" + + (buttons.size() > 1 ? " (Pick again to cycle)" : ""), 0xFF57F287); + } + + private void renderVariableDropdown(FieldDef field, AutismChatField textField, int x, int y, int width) { + if (field == null) return; + renderVariableDropdown(field.key(), textField, x, y, width); + } + + private void renderVariableDropdown(String key, AutismChatField textField, int x, int y, int width) { + if (!shouldShowVariableButton(key) || textField == null) return; + String cacheKey = "__vars_" + key; + CompactDropdown dropdown = enumDropdownCache.computeIfAbsent(cacheKey, + ignored -> new CompactDropdown(x, y, width, 14, variableTokens, 0, index -> {})); + dropdown.setBounds(x, y, width, 14) + .setOptions(variableTokens) + .setButtonLabelOverride("{}") + .setOnSelect(index -> { + if (index >= 0 && index < variableTokens.size()) textField.insertText(variableTokens.get(index)); + dropdown.close(); + }); + enumDropdowns.add(dropdown); + } + + private boolean shouldShowVariableButton(String key) { + return targetAction != null + && targetAction.getType() == MacroActionType.SEND_CHAT + && "message".equals(key) + && !variableTokens.isEmpty(); + } + + private static final List DEFAULT_VARIABLE_TOKENS = List.of( + "{user}", "{pos}", "{rot}", "{x}", "{y}", "{z}", + "{uuid}", "{dimension}", "{facing}", "{server}", "{selected_slot}", "{timestamp}" + ); + + private void rebuildVariableTokens() { + java.util.LinkedHashSet tokens = new java.util.LinkedHashSet<>(); + if (variableMacro != null && variableMacro.actions != null) { + int limit = variableActionIndex < 0 ? variableMacro.actions.size() : Math.min(variableActionIndex, variableMacro.actions.size()); + for (int i = limit - 1; i >= 0 && tokens.size() < 4; i--) { + addCaptureValueTokens(tokens, variableMacro.actions.get(i), 4); + } + } + tokens.addAll(DEFAULT_VARIABLE_TOKENS); + variableTokens.clear(); + variableTokens.addAll(tokens); + } + + private static void addCaptureValueTokens(java.util.Set tokens, MacroAction action, int limit) { + if (!(action instanceof autismclient.util.macro.CaptureValueAction capture) || tokens.size() >= limit) return; + java.util.Set names = autismclient.util.macro.MacroCapturePattern.declaredNames(capture.matchMode, capture.pattern); + for (String name : names) { + if (tokens.size() >= limit) return; + tokens.add("{" + name + "}"); + } + if (tokens.size() < limit) { + String root = autismclient.util.macro.MacroVariableContext.cleanRootName(capture.saveAs); + if (!root.isBlank()) tokens.add("{" + root + "}"); + } + } + + private static void addActionVariableTokens(java.util.Set tokens, MacroAction action) { + if (action instanceof autismclient.util.macro.WaitForChatAction chat) { + for (String name : autismclient.util.macro.MacroCapturePattern.declaredNames(chat.effectiveMatchMode(), chat.pattern)) tokens.add("{" + name + "}"); + addStructuredTokens(tokens, chat.saveAs, "sender", "message", "display", "source"); + } else if (action instanceof autismclient.util.macro.WaitForGuiAction gui) { + for (String name : autismclient.util.macro.MacroCapturePattern.declaredNames(gui.matchMode, gui.guiTitle)) tokens.add("{" + name + "}"); + addStructuredTokens(tokens, gui.saveAs, "title", "type"); + } else if (action instanceof autismclient.util.macro.CaptureValueAction capture) { + for (String name : autismclient.util.macro.MacroCapturePattern.declaredNames(capture.matchMode, capture.pattern)) tokens.add("{" + name + "}"); + switch (capture.source) { + case GUI_TITLE -> addStructuredTokens(tokens, capture.saveAs, "title", "type"); + case RECENT_CHAT -> addStructuredTokens(tokens, capture.saveAs, "sender", "message", "display", "source"); + case SCOREBOARD -> addStructuredTokens(tokens, capture.saveAs, "line", "name", "score", "row", "title", "objective"); + case GUI_ITEM, PLAYER_ITEM, CURSOR_ITEM, HELD_ITEM -> addStructuredTokens(tokens, capture.saveAs, "name", "id", "count", "slot", "lore", "lore1"); + } + } else if (action instanceof autismclient.util.macro.SelectSlotAction select && select.outputVariable != null && !select.outputVariable.isBlank()) { + tokens.add("{" + select.outputVariable.trim() + "}"); + } else if (action instanceof autismclient.util.macro.MacroVariablesAction variables) { + for (String name : variables.names) if (name != null && !name.isBlank()) tokens.add("{" + name.trim() + "}"); + } else if (action instanceof autismclient.util.macro.MacroCaptureOutput output) { + String root = output.getSaveAs(); + if (action instanceof autismclient.util.macro.WaitForHealthAction) { + addStructuredTokens(tokens, root, "health", "max", "absorption"); + } else if (action instanceof autismclient.util.macro.WaitForEntityAction) { + addStructuredTokens(tokens, root, "name", "id", "uuid", "x", "y", "z", "distance"); + } else if (action instanceof autismclient.util.macro.WaitForSoundAction) { + addStructuredTokens(tokens, root, "id", "x", "y", "z"); + } else if (action instanceof autismclient.util.macro.WaitForPacketAction + || action instanceof autismclient.util.macro.WaitPacketMatchAction) { + addStructuredTokens(tokens, root, "name", "class", "direction"); + if (action instanceof autismclient.util.macro.WaitPacketMatchAction packetMatch) { + String cleanRoot = autismclient.util.macro.MacroVariableContext.cleanRootName(root); + if (!cleanRoot.isBlank()) { + for (autismclient.util.macro.WaitPacketMatchAction.Rule rule : packetMatch.effectiveRules()) { + if (rule.fieldName != null && !rule.fieldName.isBlank()) { + tokens.add("{" + cleanRoot + "." + rule.fieldName.trim().toLowerCase(Locale.ROOT) + "}"); + } + } + } + } + } else if (action instanceof autismclient.util.macro.WaitGuiTypeAction gui) { + for (String name : autismclient.util.macro.MacroCapturePattern.declaredNames(gui.matchMode, gui.title)) { + tokens.add("{" + name + "}"); + } + addStructuredTokens(tokens, root, "title", "type"); + } else if (action instanceof autismclient.util.macro.WaitPosAction + || action instanceof autismclient.util.macro.WaitForPositionDeltaAction + || action instanceof autismclient.util.macro.WaitForTeleportAction) { + addStructuredTokens(tokens, root, "x", "y", "z", "yaw", "pitch"); + } else if (action instanceof autismclient.util.macro.WaitForWorldChangeAction) { + addStructuredTokens(tokens, root, "id", "name"); + } else if (action instanceof autismclient.util.macro.WaitGamemodeChangeAction) { + addStructuredTokens(tokens, root, "name"); + } else { + addStructuredTokens(tokens, root, "name", "id", "count", "slot", "condition"); + } + } + } + + private static void addStructuredTokens(java.util.Set tokens, String root, String... properties) { + if (root == null || root.isBlank()) return; + String clean = autismclient.util.macro.MacroVariableContext.cleanRootName(root); + if (clean.isBlank()) return; + tokens.add("{" + clean + "}"); + for (String property : properties) tokens.add("{" + clean + "." + property + "}"); + } + + private void renderMacroSelector(GuiGraphicsExtractor ctx, FieldDef field, AutismChatField backingField, + int x, int y, int w, int mx, int my) { + List macros = availableMacroNames(backingField.getText()); + Identifier font = theme.fontFor(UiTone.BODY); + String current = backingField.getText() == null ? "" : backingField.getText(); + if (current.isBlank() && !macros.isEmpty()) { + backingField.setText(macros.get(0)); + current = backingField.getText(); + } + + UiText.draw(ctx, textRenderer, field.label(), font, AutismColors.textSecondary(), x, y + 2, false); + int badgeW = Math.min(150, Math.max(60, w / 2)); + int badgeX = x + w - badgeW; + CompactSurfaces.valueField(ctx, badgeX, y + 1, badgeW, 14); + String selectedLabel = current.isBlank() ? "No macro selected" : current; + String selectedTrimmed = UiText.trimToWidth(textRenderer, selectedLabel, badgeW - 6, font, -1); + UiText.draw(ctx, textRenderer, selectedTrimmed, font, current.isBlank() ? AutismColors.textMuted() : AutismColors.textPrimary(), badgeX + 3, y + 3, false); + + int listY = y + 17; + int listH = MACRO_SELECT_VISIBLE_ROWS * SEL_ITEM_H; + int itemW = w - SCROLLBAR_W - 1; + String viewportKey = "macro_select_" + field.key(); + DirectScrollViewport viewport = getOrCreateViewport(selectedScrollViewports, viewportKey, x, listY, w, listH, SEL_ITEM_H, SCROLLBAR_W); + viewport.setContentHeight(macros.size() * SEL_ITEM_H); + viewport.renderScrollbar(ctx, mx, my); + + if (macros.isEmpty()) { + CompactSurfaces.row(ctx, x, listY, itemW, 13, false, false); + CompactListRenderer.drawEmptyState(ctx, textRenderer, "No saved macros", x, listY, itemW); + return; + } + + viewport.beginRender(ctx, theme.borderSoft(), 0x36000000); + int first = viewport.getFirstVisibleRow(); + for (int i = first; i < macros.size() && i <= viewport.getLastVisibleRow(); i++) { + String macroName = macros.get(i); + int iy = viewport.getRowScreenY(i); + if (iy == Integer.MIN_VALUE) continue; + boolean selected = macroName.equals(current); + boolean hovered = mx >= x && mx < x + itemW && my >= iy && my < iy + SEL_ITEM_H; + MacroTypedListControl.renderRow(ctx, textRenderer, Component.literal(macroName), + UiBounds.of(x, iy, itemW, SEL_ITEM_H), hovered, selected, CompactListRenderer.RowTone.NORMAL, false); + final String selectedMacro = macroName; + hitRegions.add(new HitRegion(x, iy, itemW, SEL_ITEM_H, () -> backingField.setText(selectedMacro))); + } + viewport.endRender(ctx); + } + + private List availableMacroNames(String currentValue) { + AutismMacroManager manager = AutismMacroManager.get(); + long revision = manager.getRevision(); + if (revision != cachedMacroNamesRevision) { + cachedMacroNames.clear(); + for (AutismMacro macro : manager.getAll()) { + if (macro != null && macro.name != null && !macro.name.isBlank()) { + cachedMacroNames.add(macro.name); + } + } + cachedMacroNamesRevision = revision; + } + + if (currentValue == null || currentValue.isBlank() || cachedMacroNames.contains(currentValue)) { + return cachedMacroNames; + } + + macroNamesWithCurrent.clear(); + macroNamesWithCurrent.add(currentValue); + macroNamesWithCurrent.addAll(cachedMacroNames); + return macroNamesWithCurrent; + } + + private boolean isWaitChatPatternField(FieldDef field) { + return field != null + && "pattern".equals(field.key()) + && targetAction != null + && targetAction.getType() == MacroActionType.WAIT_CHAT; + } + + private void renderEnum(GuiGraphicsExtractor ctx, FieldDef field, int x, int y, int w, + int mx, int my) { + String key = field.key(); + List opts = field.enumOptions(); + if (opts.isEmpty()) return; + int idx = Math.min(enumIndices.getOrDefault(key, 0), opts.size() - 1); + Identifier font = theme.fontFor(UiTone.BODY); + + int lw = labelWidth(w, field.label(), font, 72); + drawLabel(ctx, field.label(), x, y, lw, font); + + int ctrlX = controlX(x, lw); + int ctrlW = controlWidth(w, lw); + int ddH = 16; + int variableW = shouldShowVariableButton(key) ? 20 : 0; + int valueW = Math.max(1, ctrlW - (variableW > 0 ? variableW + 2 : 0)); + AutismChatField bindingField = field.dynamic() ? textFields.get(key) : null; + + if (bindingField != null && !bindingField.getText().isBlank()) { + bindingField.setX(ctrlX); + bindingField.setY(y + 2); + bindingField.setWidth(valueW); + bindingField.render(ctx, mx, my, 0.0f); + if (variableW > 0) renderDynamicEnumDropdown(field, bindingField, ctrlX + valueW + 2, y + 2, variableW); + return; + } + + final List capturedOpts = opts; + final String capturedKey = key; + CompactDropdown dd = enumDropdownCache.computeIfAbsent(key, k -> + new CompactDropdown(ctrlX, y + 1, valueW, ddH, capturedOpts, idx, newIdx -> { + if (newIdx >= 0 && newIdx < capturedOpts.size()) enumIndices.put(capturedKey, newIdx); + })); + dd.setBounds(ctrlX, y + 1, valueW, ddH) + .setOptions(opts) + .setSelectedIndex(idx) + .setOnSelect(newIdx -> { + if (newIdx >= 0 && newIdx < capturedOpts.size()) enumIndices.put(capturedKey, newIdx); + }); + enumDropdowns.add(dd); + if (variableW > 0 && bindingField != null) renderDynamicEnumDropdown(field, bindingField, ctrlX + valueW + 2, y + 2, variableW); + } + + private void renderDynamicEnumDropdown(FieldDef field, AutismChatField bindingField, int x, int y, int width) { + List options = new ArrayList<>(); + options.add("Static"); + options.addAll(variableTokens); + String cacheKey = "__enum_vars_" + field.key(); + CompactDropdown dropdown = enumDropdownCache.computeIfAbsent(cacheKey, + ignored -> new CompactDropdown(x, y, width, 14, options, 0, index -> {})); + dropdown.setBounds(x, y, width, 14) + .setOptions(options) + .setButtonLabelOverride("{}") + .setOnSelect(index -> { + if (index <= 0) bindingField.setText(""); + else if (index < options.size()) bindingField.setText(options.get(index)); + dropdown.close(); + }); + enumDropdowns.add(dropdown); + } + + private void renderBlockPos(GuiGraphicsExtractor ctx, FieldDef field, int x, int y, int w, + int mx, int my, float delta) { + String key = field.key(); + Identifier font = theme.fontFor(UiTone.BODY); + String[] axis = {"X", "Y", "Z"}; + boolean hasCapture = field.captureMode() != CaptureMode.NONE + && captureControlAvailable(field.captureMode()); + + int capBtnW = CAPTURE_BTN_W, capBtnH = 14; + int labelW = hasCapture ? w - capBtnW - 4 : w; + UiText.draw(ctx, textRenderer, field.label(), font, + AutismColors.textSecondary(), x, y + 3, false); + + if (hasCapture) { + int cbX = x + labelW + 4; + renderFieldCaptureButton( + ctx, + cbX, + y, + capBtnW, + capBtnH, + field.captureMode(), + false, + true, + mx, + my, + () -> startBlockPosCapture(field) + ); + } + + int fieldW = (w - 4) / 3; + for (int i = 0; i < 3; i++) { + AutismChatField tf = textFields.get(key + "_" + i); + if (tf == null) continue; + int fx = x + i * (fieldW + 2); + int variableW = shouldShowVariableButton(field.key()) ? 18 : 0; + UiText.draw(ctx, textRenderer, axis[i], font, + AutismColors.textDim(), fx, y + ROW_H + 3, false); + tf.setX(fx + 9); tf.setY(y + ROW_H + 1); + tf.setWidth(Math.max(1, fieldW - 9 - (variableW > 0 ? variableW + 2 : 0))); + tf.render(ctx, mx, my, delta); + if (variableW > 0) renderVariableDropdown(field.key() + "_" + axis[i].toLowerCase(Locale.ROOT), tf, + fx + fieldW - variableW, y + ROW_H + 2, variableW); + } + } + + private void pickNbtBookTextFile(AutismChatField field) { + if (field == null) return; + String current = field.getText() == null ? "" : field.getText().trim(); + String selected = org.lwjgl.util.tinyfd.TinyFileDialogs.tinyfd_openFileDialog( + "NBT Book Text File", + current.isBlank() ? null : current, + null, + null, + false + ); + if (selected != null && !selected.isBlank()) field.setText(selected); + } + + private void renderStringList(GuiGraphicsExtractor ctx, FieldDef field, int x, int y, int w, + int mx, int my, float delta) { + String key = field.key(); + List lst = stringLists.getOrDefault(key, Collections.emptyList()); + Identifier font = theme.fontFor(UiTone.BODY); + AutismChatField af = addFields.get(key); + boolean editable = isEditableStringList(key); + boolean xcarryList = isXCarryListKey(key); + int editIdx = editable ? stringListEditIndex.getOrDefault(key, -1) : -1; + + if (editIdx >= lst.size()) { editIdx = -1; stringListEditIndex.put(key, -1); } + String filter = (!editable && af != null) ? af.getText().toLowerCase() : ""; + String emptyHint = getStringListEmptyHint(key); + + List filtered = MacroTypedListControl.refilter( + lst, + stringListFilteredIndices.computeIfAbsent(key, ignored -> new ArrayList<>()), + value -> filter.isEmpty() || value.toLowerCase().contains(filter) + ); + + String sectionLabel = filter.isEmpty() + ? field.label() + " (" + lst.size() + ")" + : field.label() + " (" + filtered.size() + "/" + lst.size() + ")"; + UiText.draw(ctx, textRenderer, sectionLabel, font, + AutismColors.textSecondary(), x, y + 2, false); + + boolean hasCapture = field.captureMode() != CaptureMode.NONE + && captureControlAvailable(field.captureMode()); + boolean hasSlotField = editable && usesMinecraftTextRendering(key); + int btnH = 14; + int addY = y + 13; + MacroTypedListControl.ToolbarLayout toolbar = MacroTypedListControl.toolbar( + UiBounds.of(x, addY, w, MacroCaptureButton.HEIGHT), + hasSlotField, + hasCapture + ); + int slotW = toolbar.slot() == null ? 0 : toolbar.slot().width(); + + AutismChatField slotField = hasSlotField ? textFields.get(key + "_slot") : null; + if (hasSlotField && slotField == null) { + slotField = makeField(slotW); + slotField.setNumericOnly(true); + slotField.setPlaceholder(Component.literal("Slot#")); + textFields.put(key + "_slot", slotField); + } + if (af != null) { + af.setX(toolbar.text().x()); af.setY(toolbar.text().y() + 1); af.setWidth(toolbar.text().width()); + af.render(ctx, mx, my, delta); + } + if (hasSlotField && slotField != null) { + slotField.setX(toolbar.slot().x()); slotField.setY(toolbar.slot().y() + 1); slotField.setWidth(toolbar.slot().width()); + slotField.render(ctx, mx, my, delta); + } + + if (editable && editIdx >= 0 && editIdx < lst.size() && af != null) { + String nameText = af.getText().strip(); + String slotText = hasSlotField && slotField != null ? slotField.getText().strip() : ""; + String entry = buildEntryFromNameAndSlot(nameText, slotText); + if (!entry.isEmpty()) { + String normalized = isXCarryListKey(key) ? normalizeXCarryEntry(entry) + : usesStoreTargetFormatting(key) + ? autismclient.util.macro.StoreItemAction.normalizeTargetEntry(entry) : entry; + if (normalized != null && !normalized.isBlank() && !normalized.equals(lst.get(editIdx))) { + lst.set(editIdx, normalized); + if (usesMinecraftTextRendering(key)) { + editorItemLists.put(key, buildStructuredListTargets(key)); + } + } + } + } + + final AutismChatField fSlotField = slotField; + if (af != null) { + renderOverlayButton(ctx, toolbar.add().x(), toolbar.add().y(), toolbar.add().width(), btnH, "+Add", CompactOverlayButton.Variant.SUCCESS, true, mx, my, () -> { + String nameText = af.getText().strip(); + String slotText = hasSlotField && fSlotField != null ? fSlotField.getText().strip() : ""; + String entry = buildEntryFromNameAndSlot(nameText, slotText); + if (!entry.isEmpty() && addStringListEntry(field, lst, entry)) { + af.setText(""); + if (fSlotField != null) fSlotField.setText(""); + stringListEditIndex.put(key, -1); + } + }); + } + + if (hasCapture) { + boolean isItemSlot = field.captureMode() == CaptureMode.ITEM_SLOT; + boolean capturing = isItemSlot && captureSession.isItemSlotCapture(key); + final String fKey = key; + final FieldDef fField = field; + final List fLst = lst; + renderFieldCaptureButton( + ctx, + toolbar.capture().x(), + toolbar.capture().y(), + toolbar.capture().width(), + btnH, + field.captureMode(), + capturing, + true, + mx, + my, + () -> { + if (isItemSlot) { + toggleItemSlotCapture(fKey); + } else { + startCapture(fField, fLst); + } + }); + } + + int itemsY = addY + btnH + 2; + int selAreaH = SEL_LIST_MAX_VIS * SEL_ITEM_H; + int delW = 13; + int destW = xcarryList ? 62 : 0; + int amountW = xcarryList ? 54 : 0; + if (xcarryList) syncXCarryDestinationCount(lst.size()); + if (xcarryList) { + syncXCarryAmountCount(lst.size()); + if (editIdx >= 0 && editIdx < lst.size()) { + final int selectedXCarryIndex = editIdx; + AutismChatField countField = textFields.get(key + "_xcarry_count"); + if (countField == null) { + countField = makeField(38); + countField.setNumericOnly(true); + countField.setPlaceholder(Component.literal("Count")); + textFields.put(key + "_xcarry_count", countField); + } + + int amountY = itemsY; + UiText.draw(ctx, textRenderer, "Amount", theme.fontFor(UiTone.BODY), + AutismColors.textSecondary(), x, amountY + 3, false); + int modeX = x + 52; + boolean custom = getXCarryAmountMode(editIdx) == autismclient.util.macro.XCarryAction.AmountMode.CUSTOM; + renderOverlayButton(ctx, modeX, amountY, 58, btnH, custom ? "Count" : "FullStk", + CompactOverlayButton.Variant.SECONDARY, true, mx, my, () -> { + boolean nowCustom = getXCarryAmountMode(selectedXCarryIndex) == autismclient.util.macro.XCarryAction.AmountMode.CUSTOM; + setXCarryAmountMode(selectedXCarryIndex, nowCustom + ? autismclient.util.macro.XCarryAction.AmountMode.FULL_STK + : autismclient.util.macro.XCarryAction.AmountMode.CUSTOM); + AutismChatField cf = textFields.get(key + "_xcarry_count"); + if (cf != null) cf.setText(String.valueOf(getXCarryAmount(selectedXCarryIndex))); + }); + if (custom) { + countField.setX(modeX + 62); + countField.setY(amountY + 1); + countField.setWidth(42); + if (countField.getText().isBlank()) countField.setText(String.valueOf(getXCarryAmount(editIdx))); + countField.render(ctx, mx, my, delta); + try { + int parsed = Integer.parseInt(countField.getText().strip()); + setXCarryAmount(selectedXCarryIndex, Math.max(1, parsed)); + } catch (NumberFormatException ignored) { } + } + itemsY = amountY + btnH + 2; + } + } + + DirectScrollViewport strViewport = getOrCreateViewport(selectedScrollViewports, key, + x, itemsY, w, selAreaH, SEL_ITEM_H, SCROLLBAR_W); + strViewport.setContentHeight(filtered.size() * SEL_ITEM_H); + + strViewport.renderScrollbar(ctx, mx, my); + + if (!filtered.isEmpty()) { + int rowAreaW = Math.max(24, w - SCROLLBAR_W - 1 - delW - 2 + - (destW > 0 ? destW + 2 : 0) + - (amountW > 0 ? amountW + 2 : 0)); + strViewport.beginRender(ctx, theme.borderSoft(), 0x36000000); + int firstVi = strViewport.getFirstVisibleRow(); + for (int vi = firstVi; vi < filtered.size() && vi <= strViewport.getLastVisibleRow(); vi++) { + int ri = filtered.get(vi); + int iy = strViewport.getRowScreenY(vi); + if (iy == Integer.MIN_VALUE) continue; + Component displayValue = formatStringListEntryText(key, lst.get(ri), ri); + boolean selected = editable && ri == editIdx; + boolean hovered = mx >= x && mx < x + rowAreaW && my >= iy && my < iy + SEL_ITEM_H; + if (field.captureMode() == CaptureMode.PACKET_NAME) { + int textColor = getPacketRowColor(lst.get(ri), ri, selected); + MacroTypedListControl.renderRowWithColor( + ctx, + textRenderer, + displayValue, + UiBounds.of(x, iy, rowAreaW, SEL_ITEM_H), + hovered, + selected, + textColor, + usesMinecraftTextRendering(key) + ); + } else { + MacroTypedListControl.renderRow( + ctx, + textRenderer, + displayValue, + UiBounds.of(x, iy, rowAreaW, SEL_ITEM_H), + hovered, + selected, + CompactListRenderer.RowTone.NORMAL, + usesMinecraftTextRendering(key) + ); + } + + if (editable) { + final int fri = ri; + final AutismChatField fSlotF2 = hasSlotField ? textFields.get(key + "_slot") : null; + hitRegions.add(new HitRegion(x, iy, rowAreaW, SEL_ITEM_H, () -> { + int curIdx = stringListEditIndex.getOrDefault(key, -1); + if (curIdx == fri) { + stringListEditIndex.put(key, -1); + if (af != null) af.setText(""); + if (fSlotF2 != null) fSlotF2.setText(""); + AutismChatField countField = textFields.get(key + "_xcarry_count"); + if (countField != null) countField.setText(""); + } else { + stringListEditIndex.put(key, fri); + String raw = lst.get(fri); + if (af != null) af.setText(parseHandlerEntryName(raw)); + if (fSlotF2 != null) { + ItemTarget parsed = ItemTarget.fromLegacyEntry(raw); + fSlotF2.setText(parsed.hasSlot() ? String.valueOf(parsed.slot) : ""); + } + AutismChatField countField = textFields.get(key + "_xcarry_count"); + if (countField != null) countField.setText(String.valueOf(getXCarryAmount(fri))); + } + })); + } + + int actionX = x + rowAreaW + 2; + if (xcarryList) { + final int fDestIndex = ri; + int dest = getXCarryDestination(fDestIndex); + int[] destValues = autismclient.util.macro.XCarryAction.destinationValues(); + List destOptions = autismclient.util.macro.XCarryAction.destinationLabels(); + int selectedDestIndex = autismclient.util.macro.XCarryAction.destinationIndex(dest); + String ddKey = key + "_xcarry_dest_" + fDestIndex; + final int ddX = actionX; + final int ddY = iy + 1; + CompactDropdown dd = enumDropdownCache.computeIfAbsent(ddKey, k -> + new CompactDropdown(ddX, ddY, destW, 13, destOptions, selectedDestIndex, newIdx -> { + if (newIdx >= 0 && newIdx < destValues.length) { + setXCarryDestination(fDestIndex, destValues[newIdx]); + } + })); + dd.setBounds(ddX, ddY, destW, 13) + .setOptions(destOptions) + .setSelectedIndex(selectedDestIndex) + .setOnSelect(newIdx -> { + if (newIdx >= 0 && newIdx < destValues.length) { + setXCarryDestination(fDestIndex, destValues[newIdx]); + } + }); + enumDropdowns.add(dd); + actionX += destW + 2; + + final int fAmountIndex = ri; + boolean custom = getXCarryAmountMode(fAmountIndex) == autismclient.util.macro.XCarryAction.AmountMode.CUSTOM; + String amountLabel = custom ? "x" + getXCarryAmount(fAmountIndex) : "FullStk"; + renderOverlayButton(ctx, actionX, iy + 1, amountW, 13, amountLabel, + custom ? CompactOverlayButton.Variant.SUCCESS : CompactOverlayButton.Variant.SECONDARY, + true, mx, my, () -> { + boolean nowCustom = getXCarryAmountMode(fAmountIndex) == autismclient.util.macro.XCarryAction.AmountMode.CUSTOM; + setXCarryAmountMode(fAmountIndex, nowCustom + ? autismclient.util.macro.XCarryAction.AmountMode.FULL_STK + : autismclient.util.macro.XCarryAction.AmountMode.CUSTOM); + stringListEditIndex.put(key, fAmountIndex); + AutismChatField cf = textFields.get(key + "_xcarry_count"); + if (cf != null) cf.setText(String.valueOf(getXCarryAmount(fAmountIndex))); + }); + actionX += amountW + 2; + } + + int delX = actionX; + final int fRi = ri; + renderIconDeleteButton(ctx, delX, iy + 1, delW, mx, my, () -> { + lst.remove(fRi); + if (xcarryList) { + removeXCarryDestination(fRi); + removeXCarryAmount(fRi); + } + if (editable && stringListEditIndex.getOrDefault(key, -1) == fRi) { + stringListEditIndex.put(key, -1); + if (af != null) af.setText(""); + } else if (editable && stringListEditIndex.getOrDefault(key, -1) > fRi) { + stringListEditIndex.put(key, stringListEditIndex.get(key) - 1); + } + DirectScrollViewport vp = selectedScrollViewports.get(key); + if (vp != null) vp.scrollBy(-1); + if (usesMinecraftTextRendering(key)) { + editorItemLists.put(key, buildStructuredListTargets(key)); + } + }); + } + strViewport.endRender(ctx); + } else if (emptyHint != null && !emptyHint.isBlank()) { + int itemW = w - SCROLLBAR_W - 1; + CompactSurfaces.row(ctx, x, itemsY, itemW, 12, false, false); + CompactListRenderer.drawEmptyState(ctx, textRenderer, emptyHint, x, itemsY, itemW); + } + } + + private String getStringListEmptyHint(String key) { + if (isInventoryAuditTargetListKey(key)) { + List selected = stringLists.getOrDefault(key, Collections.emptyList()); + if (selected.isEmpty()) { + return "Add at least one target before running this audit."; + } + } + return null; + } + + private void renderStringListCatalog(GuiGraphicsExtractor ctx, FieldDef field, int x, int y, int w, + int mx, int my, float delta) { + String key = field.key(); + List sel = stringLists.getOrDefault(key, Collections.emptyList()); + Identifier font = theme.fontFor(UiTone.BODY); + AutismChatField af = addFields.get(key); + String filter = (af != null) ? af.getText().toLowerCase() : ""; + + int cy = y; + + UiText.draw(ctx, textRenderer, field.label() + " (" + sel.size() + ")", font, + AutismColors.textSecondary(), x, cy + 2, false); + cy += 13; + + int delW = 13; + int selAreaH = SEL_LIST_MAX_VIS * SEL_ITEM_H; + + DirectScrollViewport catSelViewport = getOrCreateViewport(selectedScrollViewports, key, + x, cy, w, selAreaH, SEL_ITEM_H, SCROLLBAR_W); + catSelViewport.setContentHeight(sel.size() * SEL_ITEM_H); + + catSelViewport.renderScrollbar(ctx, mx, my); + + if (!sel.isEmpty()) { + int delX = x + w - SCROLLBAR_W - 2 - delW; + catSelViewport.beginRender(ctx, theme.borderSoft(), 0x36000000); + int firstSel = catSelViewport.getFirstVisibleRow(); + for (int i = firstSel; i < sel.size() && i <= catSelViewport.getLastVisibleRow(); i++) { + int siy = catSelViewport.getRowScreenY(i); + if (siy == Integer.MIN_VALUE) continue; + String display = AutismRegistryLabels.block(sel.get(i)); + MacroTypedListControl.renderRow( + ctx, + textRenderer, + Component.literal(display), + UiBounds.of(x, siy, delX - x - 1, 13), + mx >= x && mx < delX - 1 && my >= siy && my < siy + 13, + false, + CompactListRenderer.RowTone.NORMAL, + false + ); + final int fi = i; + renderIconDeleteButton(ctx, delX, siy, delW, mx, my, () -> { + sel.remove(fi); + DirectScrollViewport vp = selectedScrollViewports.get(key); + if (vp != null) vp.scrollBy(-1); + }); + } + catSelViewport.endRender(ctx); + } else { + CompactListRenderer.drawEmptyState(ctx, textRenderer, "(none selected)", x, cy, w - SCROLLBAR_W - 1); + } + cy += selAreaH; + + CompactSurfaces.divider(ctx, x, cy + 1, w, AutismColors.subPanelBorder()); + cy += 5; + + if (af != null) { + af.setX(x); af.setY(cy); af.setWidth(w); + af.render(ctx, mx, my, delta); + } + cy += 14; + + int headerH = 15; + int capBtnH2 = 14; + int cbX = x + w - CAPTURE_BTN_W; + int headerTextW = Math.max(24, cbX - x - 4); + String headerLabel = UiText.trimToWidth( + textRenderer, + "Available Blocks", + headerTextW, + font, + AutismColors.textSecondary() + ); + int headerTextY = UiSizing.alignTextY(cy, headerH, theme.fontHeight(UiTone.BODY), theme.bodyTextNudge()); + renderFieldCaptureButton(ctx, cbX, cy, CAPTURE_BTN_W, capBtnH2, field.captureMode(), false, true, mx, my, () -> startCapture(field, sel)); + UiText.draw(ctx, textRenderer, headerLabel, font, AutismColors.textSecondary(), x, headerTextY, false); + cy += headerH + 2; + + List filtered = MacroTypedListControl.refilterValues( + getAllBlockIds(), + catalogFilteredValues.computeIfAbsent(key + "_catalog", ignored -> new ArrayList<>()), + id -> matchesListFilter(filter, id, trimMinecraftPrefix(id), AutismRegistryLabels.block(id)) + ); + + int catItemW = w - SCROLLBAR_W - 1; + + DirectScrollViewport catViewport = getOrCreateViewport(catalogScrollViewports, key, + x, cy, w, CATALOG_LIST_H, CATALOG_ITEM_H, SCROLLBAR_W); + catViewport.setContentHeight(filtered.size() * CATALOG_ITEM_H); + + catViewport.renderScrollbar(ctx, mx, my); + + catViewport.beginRender(ctx, theme.borderSoft(), 0x36000000); + int firstItem = catViewport.getFirstVisibleRow(); + for (int i = firstItem; i < filtered.size() && i <= catViewport.getLastVisibleRow(); i++) { + int iy = catViewport.getRowScreenY(i); + if (iy == Integer.MIN_VALUE) continue; + String id = filtered.get(i); + String display = AutismRegistryLabels.block(id); + boolean already = sel.contains(id); + boolean hov = mx >= x && mx < x + catItemW && my >= iy && my < iy + CATALOG_ITEM_H; + MacroTypedListControl.renderRow( + ctx, + textRenderer, + Component.literal(display), + UiBounds.of(x, iy, catItemW, CATALOG_ITEM_H), + hov, + already, + already ? CompactListRenderer.RowTone.READY : CompactListRenderer.RowTone.NORMAL, + false + ); + if (!already) { + hitRegions.add(new HitRegion(x, iy, catItemW, CATALOG_ITEM_H, () -> { + if (!sel.contains(id)) sel.add(id); + })); + } else { + + hitRegions.add(new HitRegion(x, iy, catItemW, CATALOG_ITEM_H, () -> sel.remove(id))); + } + } + catViewport.endRender(ctx); + } + + private void renderFooter(GuiGraphicsExtractor ctx, int footerY, int mx, int my) { + int btnH = 16; + String variableWarning = variableAvailabilityWarning(); + int btnY = variableWarning.isBlank() ? footerY + (FOOTER_H - btnH) / 2 : footerY + FOOTER_H - btnH - 2; + if (standalonePayloadEditor) { + int closeW = 72; + int closeX = panelX + (panelW - closeW) / 2; + CompactSurfaces.divider(ctx, panelX + PAD, footerY, panelW - (PAD * 2), AutismColors.subPanelBorder()); + renderOverlayButton(ctx, closeX, btnY, closeW, btnH, "Close", CompactOverlayButton.Variant.SECONDARY, true, mx, my, () -> closeEditor(false)); + return; + } + int btnW = payloadAction != null ? 72 : 58; + int gap = 6; + int total = btnW * 2 + gap; + int sx = panelX + (panelW - total) / 2; + + CompactSurfaces.divider(ctx, panelX + PAD, footerY, panelW - (PAD * 2), AutismColors.subPanelBorder()); + + if (!variableWarning.isBlank()) { + Identifier font = theme.fontFor(UiTone.BODY); + String text = UiText.trimToWidth(textRenderer, variableWarning, panelW - PAD * 2, font, -1); + UiText.draw(ctx, textRenderer, text, font, 0xFFFF6B6B, + panelX + Math.max(PAD, (panelW - uiWidth(font, text)) / 2), footerY + 2, false); + } + + renderOverlayButton(ctx, sx, btnY, btnW, btnH, "Cancel", CompactOverlayButton.Variant.SECONDARY, true, mx, my, () -> closeEditor(false)); + + int saveX = sx + btnW + gap; + renderOverlayButton(ctx, saveX, btnY, btnW, btnH, payloadAction != null ? "Save Macro" : "Save", CompactOverlayButton.Variant.PRIMARY, true, mx, my, () -> closeEditor(true)); + } + + private String variableAvailabilityWarning() { + if (variableMacro == null || variableMacro.actions == null || variableActionIndex < 0) return ""; + java.util.Set used = new java.util.LinkedHashSet<>(); + for (AutismChatField field : textFields.values()) collectTemplateRoots(used, field == null ? "" : field.getText()); + for (List values : stringLists.values()) for (String value : values) collectTemplateRoots(used, value); + used.removeAll(currentActionCaptureRoots()); + if (used.isEmpty()) return ""; + used.removeAll(autismclient.util.macro.MacroTemplate.BUILT_IN_NAMES); + if (used.isEmpty()) return ""; + + java.util.Map providerIndex = new java.util.LinkedHashMap<>(); + for (int i = 0; i < variableMacro.actions.size(); i++) { + java.util.LinkedHashSet supplied = new java.util.LinkedHashSet<>(); + addActionVariableTokens(supplied, variableMacro.actions.get(i)); + for (String token : supplied) { + java.util.LinkedHashSet roots = new java.util.LinkedHashSet<>(); + collectTemplateRoots(roots, token); + for (String root : roots) providerIndex.putIfAbsent(root, i); + } + } + for (String root : used) { + Integer provider = providerIndex.get(root); + if (provider == null) return "Value may be missing"; + if (provider >= variableActionIndex) return "Captured later"; + if (isRaceBodyIndex(provider) && !sameRaceBody(provider, variableActionIndex)) return "Race-only value"; + } + return ""; + } + + private java.util.Set currentActionCaptureRoots() { + java.util.LinkedHashSet outputs = new java.util.LinkedHashSet<>(); + if (targetAction instanceof autismclient.util.macro.MacroCaptureOutput captureOutput) { + String root = autismclient.util.macro.MacroVariableContext.cleanRootName(captureOutput.getSaveAs()); + if (!root.isBlank()) outputs.add(root); + } + String pattern = ""; + autismclient.util.macro.MacroCapturePattern.Mode mode = autismclient.util.macro.MacroCapturePattern.Mode.MATCH; + if (targetAction instanceof autismclient.util.macro.WaitForChatAction) { + AutismChatField field = textFields.get("pattern"); + pattern = field == null ? "" : field.getText(); + mode = editorCaptureMode(); + } else if (targetAction instanceof autismclient.util.macro.WaitForGuiAction) { + AutismChatField field = textFields.get("guiTitle"); + pattern = field == null ? "" : field.getText(); + mode = editorCaptureMode(); + } else if (targetAction instanceof autismclient.util.macro.WaitGuiTypeAction) { + AutismChatField field = textFields.get("title"); + pattern = field == null ? "" : field.getText(); + mode = editorCaptureMode(); + } else if (targetAction instanceof autismclient.util.macro.CaptureValueAction) { + AutismChatField field = textFields.get("pattern"); + pattern = field == null ? "" : field.getText(); + mode = editorCaptureMode(); + } + if (mode != autismclient.util.macro.MacroCapturePattern.Mode.MATCH) { + outputs.addAll(autismclient.util.macro.MacroCapturePattern.declaredNames(mode, pattern)); + } + return outputs; + } + + private autismclient.util.macro.MacroCapturePattern.Mode editorCaptureMode() { + try { + return autismclient.util.macro.MacroCapturePattern.Mode.valueOf(currentEnumValue("matchMode")); + } catch (IllegalArgumentException | NullPointerException ignored) { + return autismclient.util.macro.MacroCapturePattern.Mode.MATCH; + } + } + + private static void collectTemplateRoots(java.util.Set out, String text) { + if (out == null || text == null || text.isBlank()) return; + java.util.regex.Matcher matcher = java.util.regex.Pattern + .compile("(?= 0; + } + + private boolean sameRaceBody(int left, int right) { + int leftHeader = raceHeaderFor(left); + return leftHeader >= 0 && leftHeader == raceHeaderFor(right); + } + + private int raceHeaderFor(int index) { + if (variableMacro == null || variableMacro.actions == null || index < 0) return -1; + for (int i = 0; i < Math.min(index, variableMacro.actions.size()); i++) { + MacroAction action = variableMacro.actions.get(i); + if (action instanceof autismclient.util.macro.RaceAction race) { + int end = i + Math.max(0, race.bodyCount); + if (index > i && index <= end) return i; + } + } + return -1; + } + + private void enterCaptureMode() { + clearCaptureToasts(); + captureHiddenOverlays = new ArrayList<>(); + for (IAutismOverlay o : AutismOverlayManager.get().getOverlays()) { + if (o != this && o.isVisible()) { + o.saveLayout(); + captureHiddenOverlays.add(o); + o.setVisible(false); + } + } + saveLayout(); + clearTextFieldFocus(); + restoreVisibleAfterCapture = visible; + visible = false; + AutismSharedState.get().setCaptureMode(true); + } + + private void toggleItemSlotCapture(String key) { + if (!guardWorldCaptureAction()) return; + captureSession.toggleItemSlotCapture( + key, + this::enterItemSlotCaptureMode, + () -> exitCaptureMode(false, false) + ); + } + + private void enterItemSlotCaptureMode() { + Screen current = MC.gui.screen(); + boolean hasSlotScreen = current instanceof AbstractContainerScreen; + autoOpenedInventoryForCapture = false; + enterCaptureMode(); + if (!hasSlotScreen) { + + screenBeforeCapture = current; + autoOpenedInventoryForCapture = true; + MC.execute(() -> MC.gui.setScreen(new InventoryScreen(MC.player))); + } + } + + private void restoreCaptureHiddenOverlays() { + if (captureHiddenOverlays == null) return; + AutismOverlayManager manager = AutismOverlayManager.get(); + for (IAutismOverlay overlay : captureHiddenOverlays) { + manager.register(overlay); + overlay.setVisible(true); + overlay.saveLayout(); + } + captureHiddenOverlays = null; + } + + private void clearCaptureCallbacks(boolean cancelGBreak) { + AutismSharedState state = AutismSharedState.get(); + state.setCaptureCancelCallback(null); + state.setBlockCaptureCallback(null); + state.setDirectionalBlockCaptureCallback(null); + state.setEntityCaptureCallback(null); + state.setAttackCaptureCallback(null); + state.setEntityCaptureSpecific(false); + if (cancelGBreak && state.isGBreakCapturing()) { + state.cancelGBreakCapture(); + } + } + + private void exitCaptureMode(boolean reopenInventory, boolean closeCurrentScreen) { + restoreCaptureHiddenOverlays(); + clearCaptureCallbacks(false); + AutismSharedState.get().setPlaceCaptureActive(false); + AutismSharedState.get().setCaptureMode(false); + visible = restoreVisibleAfterCapture; + restoreVisibleAfterCapture = false; + + hitRegions.clear(); + scrollDragRegions.clear(); + AutismOverlayManager.get().bringToFront(this); + if (autoOpenedInventoryForCapture) { + + Screen restore = screenBeforeCapture; + MC.execute(() -> { + if (MC.gui.screen() instanceof InventoryScreen) { + if (restore != null) MC.gui.setScreen(restore); + } else if (restore == null && MC.gui.screen() == null && MC.player != null) { + MC.gui.setScreen(new InventoryScreen(MC.player)); + } else if (restore != null && MC.gui.screen() == null) { + MC.gui.setScreen(restore); + } + }); + autoOpenedInventoryForCapture = false; + } else if (reopenInventory && screenBeforeCapture != null) { + MC.execute(() -> { if (MC.gui.screen() == null) MC.gui.setScreen(screenBeforeCapture); }); + } else if (reopenInventory && MC.player != null) { + MC.execute(() -> { if (MC.gui.screen() == null) MC.gui.setScreen(new InventoryScreen(MC.player)); }); + } + if (closeCurrentScreen) { + MC.execute(() -> { if (MC.gui.screen() != null) MC.gui.setScreen(null); }); + } + screenBeforeCapture = null; + refreshInteractiveLayout(); + } + + private void closeEditor(boolean save) { + restoreCaptureHiddenOverlays(); + restoreVisibleAfterCapture = false; + clearCaptureCallbacks(true); + AutismSharedState.get().setCaptureMode(false); + clearCaptureToasts(); + + if (targetAction != null && targetAction.getType() == MacroActionType.PLACE) { + AutismInstaBreakRenderer.clear(); + } + + if (save && targetAction != null) { + if (onPreSave != null) onPreSave.run(); + flushToWorkingTag(); + targetAction.fromTag(workingTag); + autismclient.util.macro.MacroDynamicBindings.load(targetAction, workingTag); + if (onSaveCallback != null) onSaveCallback.run(); + } + packetSelectorOverlay.close(); + raceStepSelectorOverlay.close(); + visible = false; + targetAction = null; + multiEditCount = 1; + standalonePayloadEditor = false; + payloadAction = null; + workingTag = null; + schema = null; + itemAction = null; + captureSession.clearItemSlotCapture(); + if (packetClickCapturePendingKey != null) { + autismclient.util.AutismContainerHold.clearPendingCapture(); + packetClickCapturePendingKey = null; + } + enumDropdowns.clear(); + enumDropdownCache.clear(); + craftEntries = null; + craftAllRecipes = null; + craftFilteredRecipes = null; + craftSelectedRecipe = null; + craftRecipeListBounds = null; + dropAction = null; + editorItemFields.clear(); + editorItemLists.clear(); + lanStepEntries = null; + toggleModuleEntries = null; + onPreSave = null; + onSaveCallback = null; + screenBeforeGBreak = null; + screenBeforeCapture = null; + } + + private void clearCaptureToasts() { + captureToasts.clear(); + } + + private void showCaptureToast(String message, int accentColor) { + captureToasts.show(message, accentColor); + } + + public boolean hasAbstractContainerScreenCaptureToasts() { + return captureToasts.hasVisibleToasts(); + } + + public void renderAbstractContainerScreenCaptureToasts(GuiGraphicsExtractor context, int anchorX, int anchorY, int anchorWidth) { + captureToasts.render(UiContexts.overlay(context, textRenderer, anchorX, anchorY), anchorX, anchorY, anchorWidth); + } + + private void flushToWorkingTag() { + if (workingTag == null) return; + + if (itemAction != null) { + if (itemEditIndex >= 0 && itemEditIndex < itemAction.itemNames.size()) { + applyItemEntryEditor(); + } + for (int i = 0; i < itemAction.itemNames.size(); i++) { + AutismChatField tf = textFields.get("item_times_" + i); + if (tf != null) { + try { + while (itemAction.itemTimes.size() <= i) itemAction.itemTimes.add(1); + itemAction.itemTimes.set(i, Math.max(1, Integer.parseInt(tf.getText().strip()))); + } catch (NumberFormatException ignored) { } + } + } + itemAction.waitForGuiBefore = toggleStates.getOrDefault("item_waitForGuiBefore", false); + itemAction.waitForGuiAfter = toggleStates.getOrDefault("item_waitForGuiAfter", false); + itemAction.waitForItem = toggleStates.getOrDefault("item_waitForItem", false); + itemAction.useCursorItemForPickupAll = toggleStates.getOrDefault("item_useCursorItemForPickupAll", true); + itemAction.useClickDelay = toggleStates.getOrDefault("item_useClickDelay", false); + AutismChatField delayF = textFields.get("item_clickDelayMs"); + if (delayF != null) { + try { itemAction.clickDelayMs = Math.max(0, Integer.parseInt(delayF.getText().strip())); } + catch (NumberFormatException ignored) { } + } + AutismChatField guiF = textFields.get("item_guiName"); + if (guiF != null) itemAction.guiName = guiF.getText(); + if (!itemAction.waitForGuiBefore && !itemAction.waitForGuiAfter) itemAction.guiName = ""; + if (!itemAction.itemNames.isEmpty()) { + itemAction.useSlot = false; + itemAction.targetSlot = -1; + itemAction.actionIndex = 0; + itemAction.button = 0; + itemAction.times = 1; + } + workingTag = itemAction.toTag(); + return; + } + + if (craftEntries != null) { + for (int i = 0; i < craftEntries.size(); i++) { + CraftAction.CraftEntry entry = craftEntries.get(i); + AutismChatField af = textFields.get("craft_amount_" + i); + if (af != null) { + try { entry.amount = Math.max(1, Integer.parseInt(af.getText().strip())); } + catch (NumberFormatException ignored) { } + } + entry.useMaxAmount = toggleStates.getOrDefault("craft_useMax_" + i, false); + } + ListTag entryTags = new ListTag(); + for (CraftAction.CraftEntry entry : craftEntries) { + if (entry.hasRecipe()) entryTags.add(entry.toTag()); + } + workingTag.put("entries", entryTags); + return; + } + + if (dropAction != null) { + if (dropEditIndex >= 0 && dropEditIndex < dropAction.itemNames.size()) { + applyDropEntryEditor(); + } + for (int i = 0; i < dropAction.itemNames.size(); i++) { + AutismChatField f = textFields.get("drop_count_" + i); + if (f != null) { + try { dropAction.itemCounts.set(i, Math.max(0, Integer.parseInt(f.getText().strip()))); } + catch (NumberFormatException ignored) { } + } + } + while (dropAction.itemCounts.size() < dropAction.itemNames.size()) dropAction.itemCounts.add(1); + AutismChatField cntF = textFields.get("drop_globalCount"); + if (cntF != null) { try { dropAction.dropCount = Math.max(1, Integer.parseInt(cntF.getText().strip())); } catch (NumberFormatException ignored) { } } + autismclient.util.macro.DropAction.DropMode[] modes = autismclient.util.macro.DropAction.DropMode.values(); + dropAction.mode = modes[Math.min(enumIndices.getOrDefault("drop_mode", 0), modes.length - 1)]; + dropAction.waitForGuiBefore = toggleStates.getOrDefault("drop_waitForGuiBefore", false); + dropAction.waitForGuiAfter = toggleStates.getOrDefault("drop_waitForGuiAfter", false); + dropAction.useHandlerSlots = true; + AutismChatField guiF = textFields.get("drop_guiName"); + if (guiF != null) dropAction.guiName = guiF.getText(); + if (!dropAction.waitForGuiBefore && !dropAction.waitForGuiAfter) dropAction.guiName = ""; + workingTag = dropAction.toTag(); + return; + } + + if (payloadAction != null) { + payloadAction = buildPayloadActionFromEditor(); + workingTag = payloadAction.toTag(); + return; + } + + if (lanStepEntries != null) { + for (int i = 0; i < lanStepEntries.size(); i++) { + autismclient.util.macro.WaitForLanStepAction.LanStepEntry e = lanStepEntries.get(i); + AutismChatField uf = textFields.get("lan_user_" + i); + if (uf != null) e.username = uf.getText(); + AutismChatField sf = textFields.get("lan_step_" + i); + if (sf != null) { try { e.step = Math.max(1, Integer.parseInt(sf.getText().strip())); } catch (NumberFormatException ignored) { } } + } + ListTag entryList = new ListTag(); + for (autismclient.util.macro.WaitForLanStepAction.LanStepEntry e : lanStepEntries) + entryList.add(e.toTag()); + workingTag.put("entries", entryList); + workingTag.putBoolean("filterByUser", toggleStates.getOrDefault("lan_filterByUser", false)); + workingTag.putBoolean(MacroAction.LISTEN_DURING_PREVIOUS_KEY, + toggleStates.getOrDefault(MacroAction.LISTEN_DURING_PREVIOUS_KEY, false)); + AutismChatField dsF = textFields.get("lan_defaultStep"); + if (dsF != null) { try { workingTag.putInt("defaultStep", Math.max(1, Integer.parseInt(dsF.getText().strip()))); } catch (NumberFormatException ignored) { } } + + } + + if (toggleModuleEntries != null) { + ListTag entriesTag = new ListTag(); + for (autismclient.util.macro.ToggleModuleAction.ModuleEntry entry : toggleModuleEntries) { + if (entry != null && entry.moduleName != null && !entry.moduleName.isBlank()) { + entriesTag.add(entry.toTag()); + } + } + workingTag.put("entries", entriesTag); + workingTag.putString("moduleName", ""); + workingTag.putString("toggleMode", autismclient.util.macro.ToggleModuleAction.ToggleMode.TOGGLE.name()); + return; + } + + if (targetAction != null && targetAction.getType() == MacroActionType.WAIT_PACKET) { + List targets = sanitizeWaitPacketTargets(getOrCreateWaitPacketTargets()); + ListTag packetList = new ListTag(); + for (String target : targets) packetList.add(StringTag.valueOf(target)); + workingTag.put("packetNames", packetList); + workingTag.putString("packetName", targets.isEmpty() ? "" : targets.get(0)); + workingTag.putBoolean(MacroAction.LISTEN_DURING_PREVIOUS_KEY, toggleStates.getOrDefault(MacroAction.LISTEN_DURING_PREVIOUS_KEY, false)); + AutismChatField saveAs = textFields.get("saveAs"); + if (saveAs != null) workingTag.putString("saveAs", saveAs.getText()); + return; + } + + if (targetAction != null && targetAction.getType() == MacroActionType.WAIT_PACKET_MATCH) { + syncWaitPacketMatchEditedRule(); + ListTag rules = new ListTag(); + if (waitPacketMatchRules != null) { + for (WaitPacketMatchAction.Rule rule : waitPacketMatchRules) { + if (rule == null) continue; + if ((rule.packetName == null || rule.packetName.isBlank()) && (rule.fieldName == null || rule.fieldName.isBlank())) continue; + rules.add(rule.toTag()); + } + } + workingTag.put("rules", rules); + workingTag.putBoolean(MacroAction.LISTEN_DURING_PREVIOUS_KEY, toggleStates.getOrDefault(MacroAction.LISTEN_DURING_PREVIOUS_KEY, false)); + AutismChatField saveAs = textFields.get("saveAs"); + if (saveAs != null) workingTag.putString("saveAs", saveAs.getText()); + return; + } + + if (schema == null) return; + for (FieldDef field : schema.fields()) { + String key = field.key(); + switch (field.type()) { + + case TOGGLE -> + workingTag.putBoolean(key, toggleStates.getOrDefault(key, false)); + + case NUMBER, SLOT -> { + AutismChatField f = textFields.get(key); + if (f != null) { + String raw = f.getText().strip(); + if (field.dynamic() && raw.contains("{")) putDynamicBinding(key, raw); + else { + removeDynamicBinding(key); + try { workingTag.putInt(key, Integer.parseInt(raw)); } + catch (NumberFormatException ignored) { } + } + } + } + + case DECIMAL -> { + AutismChatField f = textFields.get(key); + if (f != null) { + String raw = f.getText().strip(); + if (field.dynamic() && raw.contains("{")) putDynamicBinding(key, raw); + else { + removeDynamicBinding(key); + try { workingTag.putDouble(key, Double.parseDouble(raw)); } + catch (NumberFormatException ignored) { } + } + } + } + + case TEXT, MACRO_SELECT -> { + AutismChatField f = textFields.get(key); + if (f != null) workingTag.putString(key, f.getText()); + } + + case ENUM -> { + AutismChatField bindingField = field.dynamic() ? textFields.get(key) : null; + String binding = bindingField == null ? "" : bindingField.getText().strip(); + if (field.dynamic() && !binding.isBlank()) { + putDynamicBinding(key, binding); + } else { + removeDynamicBinding(key); + List opts = field.enumOptions(); + if (!opts.isEmpty()) { + int idx = Math.min(enumIndices.getOrDefault(key, 0), opts.size() - 1); + workingTag.putString(key, opts.get(idx)); + } + } + } + + case BLOCK_POS -> { + String[] xyzKeys = field.xyzKeys(); + boolean dbl = field.xyzDouble(); + for (int i = 0; i < 3; i++) { + AutismChatField f = textFields.get(key + "_" + i); + if (f == null) continue; + String t = f.getText().strip(); + if (field.dynamic() && t.contains("{")) { + putDynamicBinding(xyzKeys[i], t); + continue; + } + removeDynamicBinding(xyzKeys[i]); + if (dbl) { + try { workingTag.putDouble(xyzKeys[i], Double.parseDouble(t)); } + catch (NumberFormatException ignored) { } + } else { + try { workingTag.putInt(xyzKeys[i], Integer.parseInt(t)); } + catch (NumberFormatException ignored) { } + } + } + } + + case STRING_LIST -> { + List items = stringLists.getOrDefault(key, Collections.emptyList()); + ListTag nbt = new ListTag(); + for (String s : items) nbt.add(StringTag.valueOf(s)); + workingTag.put(key, nbt); + } + } + } + + rewriteStructuredEditorTargets(); + + if (targetAction instanceof WaitsForGui && !hasGuiWaitEnabled()) { + workingTag.putString("guiName", ""); + workingTag.putString("waitGuiName", ""); + } + + if (targetAction != null && targetAction.getType() == MacroActionType.INVENTORY) { + String mode = currentEnumValue("mode"); + if ("CLOSE".equals(mode)) { + workingTag.putBoolean("waitForGuiBefore", false); + workingTag.putBoolean("waitForGuiAfter", false); + } + workingTag.putString("guiName", ""); + workingTag.putBoolean("sendPacket", !toggleStates.getOrDefault("sendPacket", false)); + } + if (targetAction != null && targetAction.getType() == MacroActionType.WAIT_SLOT_CHANGE) { + + net.minecraft.nbt.ListTag nbtEntries = new net.minecraft.nbt.ListTag(); + if (wscEntries != null) { + for (WaitForSlotChangeAction.WaitEntry e : wscEntries) { + net.minecraft.nbt.CompoundTag ec = new net.minecraft.nbt.CompoundTag(); + ItemTarget target = e.resolvedTarget(); + if (target.hasSlot() || target.hasIdentity()) ec.put("target", target.toTag()); + ec.putString("mode", e.waitMode.name()); + ec.putInt ("count", Math.max(1, e.targetCount)); + nbtEntries.add(ec); + } + } + workingTag.put("entries", nbtEntries); + workingTag.putBoolean(MacroAction.LISTEN_DURING_PREVIOUS_KEY, + toggleStates.getOrDefault(MacroAction.LISTEN_DURING_PREVIOUS_KEY, false)); + } + if (targetAction != null && targetAction.getType() == MacroActionType.USE_ITEM) { + AutismChatField slotField = textFields.get("slot"); + if (slotField == null || slotField.getText() == null || slotField.getText().strip().isEmpty()) { + workingTag.remove("slot"); + } + String mode = workingTag.getStringOr("useMode", "AUTOMATIC"); + if ("CUSTOM_HOLD".equals(mode)) { + workingTag.putInt("useCount", 1); + if (workingTag.getIntOr("holdTicks", 0) <= 0) workingTag.putInt("holdTicks", 20); + } else if (workingTag.getIntOr("useCount", 0) <= 0) { + workingTag.putInt("useCount", 1); + } + } + if (targetAction != null && targetAction.getType() == MacroActionType.NBT_BOOK) { + normalizeNbtBookWorkingTag(); + } + if (targetAction != null && targetAction.getType() == MacroActionType.SWAP_SLOTS) { + boolean fromUseItemName = workingTag.getBooleanOr("fromUseItemName", false); + boolean toUseItemName = workingTag.getBooleanOr("toUseItemName", false); + if (fromUseItemName) workingTag.putInt("fromSlot", -1); + else workingTag.putString("fromItemName", ""); + if (toUseItemName) workingTag.putInt("toSlot", -1); + else workingTag.putString("toItemName", ""); + } + if (targetAction != null && targetAction.getType() == MacroActionType.GO_TO && !workingTag.getBooleanOr("waitForArrival", false)) { + workingTag.putDouble("arrivalRadius", 2.0); + workingTag.putInt("timeoutMs", 60000); + } + if (targetAction != null && targetAction.getType() == MacroActionType.CLICK) { + if (!hasGuiWaitEnabled()) { + workingTag.putString("guiName", ""); + } + if ("MIDDLE".equals(workingTag.getStringOr("clickType", "RIGHT"))) { + workingTag.putString("clickType", "RIGHT"); + } + if (workingTag.getIntOr("clickCount", 0) <= 0) workingTag.putInt("clickCount", 1); + } + if (targetAction != null && targetAction.getType() == MacroActionType.XCARRY) { + workingTag.putInt("safeClickDelayTicks", + autismclient.util.macro.XCarryAction.clampSafeClickDelayTicks( + workingTag.getIntOr("safeClickDelayTicks", 1))); + workingTag.putBoolean("safeClickDelayAfterPickup", + toggleStates.getOrDefault("safeClickDelayAfterPickup", + workingTag.getBooleanOr("safeClickDelayAfterPickup", true))); + workingTag.putBoolean("safeClickDelayBeforeReturn", + toggleStates.getOrDefault("safeClickDelayBeforeReturn", + workingTag.getBooleanOr("safeClickDelayBeforeReturn", true))); + } + if (targetAction != null && targetAction.getType() == MacroActionType.DISCONNECT) { + String mode = workingTag.getStringOr("mode", "DISCONNECT"); + if ("DISCONNECT".equals(mode)) { + workingTag.putBoolean("useNextAction", false); + } else if (workingTag.getIntOr("packetCount", 0) <= 0) { + workingTag.putInt("packetCount", 200); + } + if (!"KICK_DUPE".equals(mode)) { + workingTag.putBoolean("useNextAction", false); + } + } + if (targetAction != null && targetAction.getType() == MacroActionType.BREAK + && !workingTag.getBooleanOr("interact", false)) { + workingTag.putBoolean("runNextSteps", false); + } + if (targetAction != null && targetAction.getType() == MacroActionType.CLOSE_GUI) { + workingTag.putBoolean("sendPacket", !toggleStates.getOrDefault("sendPacket", false)); + } + if (targetAction != null && targetAction.getType() == MacroActionType.SAVE_GUI) { + workingTag.putBoolean("sendPacket", !toggleStates.getOrDefault("sendPacket", false)); + } + if (targetAction != null && targetAction.getType() == MacroActionType.STORE_ITEM) { + workingTag.putBoolean("closeSendPkt", !toggleStates.getOrDefault("closeSendPkt", false)); + } + if (targetAction != null && (targetAction.getType() == MacroActionType.OPEN_CONTAINER + || targetAction.getType() == MacroActionType.INTERACT_ENTITY)) { + List selectedTargets = stringLists.getOrDefault("entityTargets", Collections.emptyList()); + String entityTarget = selectedTargets.isEmpty() ? "" : selectedTargets.get(0); + workingTag.putString("entityTarget", entityTarget); + } + if (targetAction != null && targetAction.getType() == MacroActionType.WAIT_CHAT) { + workingTag.putInt("fuzzyPercent", + autismclient.util.macro.WaitForChatAction.clampFuzzyPercent(getWaitChatFuzzyPercent())); + if (!hasGuiWaitEnabled()) { + workingTag.putString("waitGuiName", ""); + } + } + if (targetAction != null && targetAction.getType() == MacroActionType.PLACE) { + if (!workingTag.getBooleanOr("manualDirection", false)) { + workingTag.remove("direction"); + } + workingTag.putBoolean("waitForItem", toggleStates.getOrDefault("place_waitForItem", true)); + workingTag.putBoolean("silentSwitch", toggleStates.getOrDefault("place_silentSwitch", false)); + } + } + + private void putDynamicBinding(String key, String template) { + if (workingTag == null || key == null || key.isBlank()) return; + CompoundTag bindings = workingTag.get(autismclient.util.macro.MacroDynamicBindings.TAG_KEY) instanceof CompoundTag existing + ? existing : new CompoundTag(); + bindings.putString(key, template == null ? "" : template); + workingTag.put(autismclient.util.macro.MacroDynamicBindings.TAG_KEY, bindings); + } + + private void removeDynamicBinding(String key) { + if (workingTag == null || key == null) return; + if (!(workingTag.get(autismclient.util.macro.MacroDynamicBindings.TAG_KEY) instanceof CompoundTag bindings)) return; + bindings.remove(key); + if (bindings.isEmpty()) workingTag.remove(autismclient.util.macro.MacroDynamicBindings.TAG_KEY); + } + + private void normalizeNbtBookWorkingTag() { + if (workingTag == null) return; + int pages = workingTag.getIntOr("pages", 100); + if (pages <= 0) workingTag.putInt("pages", 100); + int chars = workingTag.getIntOr("characters", 1024); + if (chars <= 0) workingTag.putInt("characters", 1024); + if (!workingTag.contains("sign")) workingTag.putBoolean("sign", true); + if (!workingTag.contains("appendCount")) workingTag.putBoolean("appendCount", true); + String source = currentEnumValue("dataSource"); + if (source == null || source.isBlank()) source = "Random"; + workingTag.putString("dataSource", source); + if ("Random".equals(source)) { + workingTag.putString("customText", ""); + workingTag.putString("customFilePath", ""); + } else if ("Pasted".equals(source)) { + workingTag.putString("customFilePath", ""); + } else if ("File".equals(source)) { + workingTag.putString("customText", ""); + } + } + + @Override + public boolean mouseClicked(double mx, double my, int button) { + if (!visible) return false; + if (packetSelectorOverlay.isVisible()) return packetSelectorOverlay.mouseClicked(mx, my, button); + if (raceStepSelectorOverlay.isVisible()) return raceStepSelectorOverlay.mouseClicked(mx, my, button); + int imx = (int) mx, imy = (int) my; + + if (!enumDropdowns.isEmpty()) { + if (CompactDropdown.mouseClicked(enumDropdowns, mx, my, button)) { + AutismOverlayManager.get().bringToFront(this); + return true; + } + if (CompactDropdown.isMenuOpen(enumDropdowns)) { + return true; + } + } + + if (isOverCloseButton(mx, my, getBounds())) { + closeEditor(false); + return true; + } + if (isOverCollapseButton(mx, my, getBounds())) { + setCollapsed(!collapsed); + return true; + } + if (isOverDragBar(mx, my)) { + dragging = true; + dragOffX = mx - panelX; + dragOffY = my - panelY; + AutismOverlayManager.get().bringToFront(this); + return true; + } + if (!isMouseOver(mx, my)) return false; + if (collapsed) return true; + + AutismOverlayManager.get().bringToFront(this); + + MouseButtonEvent click = new MouseButtonEvent(imx, imy, new MouseButtonInfo(button, 0)); + boolean bodyInputAllowed = bodyInputClip == null || bodyInputClip.contains(imx, imy); + AutismChatField focused = null; + if (bodyInputAllowed) { + for (Map.Entry entry : textFields.entrySet()) { + if (!isPayloadTextFieldVisible(entry.getKey())) continue; + + String baseKey = entry.getKey().replaceAll("_\\d+$", ""); + FieldDef fld = getField(baseKey); + if (fld != null && !isFieldVisible(fld)) continue; + if (entry.getValue().mouseClicked(click, false)) { focused = entry.getValue(); break; } + } + } + if (bodyInputAllowed && focused == null) { + for (Map.Entry entry : addFields.entrySet()) { + FieldDef fld = getField(entry.getKey()); + if (fld != null && !isFieldVisible(fld)) continue; + if (entry.getValue().mouseClicked(click, false)) { focused = entry.getValue(); break; } + } + } + if (focused != null) { + AutismChatField ff = focused; + textFields.values().forEach(f -> f.setFocused(f == ff)); + addFields.values().forEach(f -> f.setFocused(f == ff)); + return true; + } + + clearTextFieldFocus(); + + if (button == 0 && isOverWaitChatFuzzySlider(imx, imy)) { + waitChatFuzzySliderDragging = true; + updateWaitChatFuzzyPercentFromMouse(imx); + return true; + } + if (button == 0 && isOverRotateSmoothnessSlider(imx, imy)) { + rotateSmoothnessSliderDragging = true; + updateRotateSmoothnessFromMouse(imx); + return true; + } + if (button == 0 && isOverXCarrySafeDelaySlider(imx, imy)) { + xcarrySafeDelaySliderDragging = true; + updateXCarrySafeDelayFromMouse(imx); + return true; + } + + if (bodyInputAllowed) { + for (DirectScrollViewport vp : selectedScrollViewports.values()) { + if (vp.isScrollbarHovered(mx, my)) { + vp.mouseClicked(mx, my, button); + return true; + } + } + for (DirectScrollViewport vp : catalogScrollViewports.values()) { + if (vp.isScrollbarHovered(mx, my)) { + vp.mouseClicked(mx, my, button); + return true; + } + } + } + + for (ScrollDragRegion r : scrollDragRegions) { + if (r.contains(imx, imy)) { + activeScrollDragHandler = r.handler(); + activeScrollDragHandler.accept(imy); + return true; + } + } + + for (HitRegion r : hitRegions) { + if (r.contains(imx, imy) && r.fire(mx, my, button)) { + refreshInteractiveLayout(); + return true; + } + } + return true; + } + + private boolean isPayloadTextFieldVisible(String key) { + if ("payload_content".equals(key)) return payloadTabIndex == 0; + if ("payload_hex_view".equals(key)) return payloadTabIndex == 1; + if ("payload_utf8_view".equals(key)) return payloadTabIndex == 2; + if ("payload_logical_view".equals(key)) return payloadTabIndex == 3; + return true; + } + + @Override + public boolean mouseReleased(double mx, double my, int button) { + if (packetSelectorOverlay.isVisible() && packetSelectorOverlay.mouseReleased(mx, my, button)) return true; + if (raceStepSelectorOverlay.isVisible() && raceStepSelectorOverlay.mouseReleased(mx, my, button)) return true; + boolean consumed = false; + + for (DirectScrollViewport vp : selectedScrollViewports.values()) { + if (vp.isScrollbarDragging()) { vp.mouseReleased(); consumed = true; } + } + for (DirectScrollViewport vp : catalogScrollViewports.values()) { + if (vp.isScrollbarDragging()) { vp.mouseReleased(); consumed = true; } + } + + if (activeScrollDragHandler != null) { activeScrollDragHandler = null; consumed = true; } + if (waitChatFuzzySliderDragging) { waitChatFuzzySliderDragging = false; consumed = true; } + if (rotateSmoothnessSliderDragging) { rotateSmoothnessSliderDragging = false; consumed = true; } + if (xcarrySafeDelaySliderDragging) { xcarrySafeDelaySliderDragging = false; consumed = true; } + if (dragging) { dragging = false; consumed = true; } + if (CompactDropdown.mouseReleased(enumDropdowns)) return true; + for (Map.Entry entry : textFields.entrySet()) { + if (!isPayloadTextFieldVisible(entry.getKey())) continue; + if (entry.getValue().mouseReleased(mx, my, button)) consumed = true; + } + for (AutismChatField field : addFields.values()) { + if (field.mouseReleased(mx, my, button)) consumed = true; + } + return consumed; + } + + @Override + public boolean mouseDragged(double mx, double my, int button, double dx, double dy) { + if (packetSelectorOverlay.isVisible() && packetSelectorOverlay.mouseDragged(mx, my, button, dx, dy)) return true; + if (raceStepSelectorOverlay.isVisible() && raceStepSelectorOverlay.mouseDragged(mx, my, button, dx, dy)) return true; + if (CompactDropdown.mouseDragged(enumDropdowns, mx, my, button)) return true; + if (waitChatFuzzySliderDragging) { + updateWaitChatFuzzyPercentFromMouse((int) mx); + return true; + } + if (rotateSmoothnessSliderDragging) { + updateRotateSmoothnessFromMouse((int) mx); + return true; + } + if (xcarrySafeDelaySliderDragging) { + updateXCarrySafeDelayFromMouse((int) mx); + return true; + } + if (dragging) { + panelX = (int)(mx - dragOffX); + panelY = (int)(my - dragOffY); + AutismWindowLayout c = clampToScreen(this); + panelX = c.x; panelY = c.y; + return true; + } + + for (Map.Entry entry : textFields.entrySet()) { + if (!isPayloadTextFieldVisible(entry.getKey())) continue; + if (entry.getValue().mouseDragged(mx, my, button, dx, dy)) return true; + } + for (AutismChatField field : addFields.values()) { + if (field.mouseDragged(mx, my, button, dx, dy)) return true; + } + + for (DirectScrollViewport vp : selectedScrollViewports.values()) { + if (vp.isScrollbarDragging()) { vp.mouseDragged(mx, my); return true; } + } + for (DirectScrollViewport vp : catalogScrollViewports.values()) { + if (vp.isScrollbarDragging()) { vp.mouseDragged(mx, my); return true; } + } + + if (activeScrollDragHandler != null) { + activeScrollDragHandler.accept((int) my); + return true; + } + return false; + } + + @Override + public boolean mouseScrolled(double mx, double my, double amount) { + if (packetSelectorOverlay.isVisible()) return packetSelectorOverlay.mouseScrolled(mx, my, amount); + if (raceStepSelectorOverlay.isVisible()) return raceStepSelectorOverlay.mouseScrolled(mx, my, amount); + if (!visible || !isMouseOver(mx, my)) return false; + + if (!enumDropdowns.isEmpty() + && (CompactDropdown.isMenuOpen(enumDropdowns) + || CompactDropdown.isInsideOpenMenu(enumDropdowns, mx, my))) { + if (CompactDropdown.mouseScrolled(enumDropdowns, mx, my, amount)) return true; + } + + boolean bodyScrollAllowed = bodyInputClip == null || bodyInputClip.contains((int) mx, (int) my); + if (bodyScrollAllowed) { + for (Map.Entry entry : textFields.entrySet()) { + if (!isPayloadTextFieldVisible(entry.getKey())) continue; + if (entry.getValue().mouseScrolled(mx, my, amount)) return true; + } + for (AutismChatField field : addFields.values()) { + if (field.mouseScrolled(mx, my, amount)) return true; + } + + for (Map.Entry entry : selectedScrollViewports.entrySet()) { + DirectScrollViewport vp = entry.getValue(); + if (vp.contains(mx, my)) { + vp.mouseScrolled(mx, my, amount); + return true; + } + } + + for (Map.Entry entry : catalogScrollViewports.entrySet()) { + DirectScrollViewport vp = entry.getValue(); + if (vp.contains(mx, my)) { + vp.mouseScrolled(mx, my, amount); + return true; + } + } + } + + if (craftRecipeListBounds != null + && my >= craftRecipeListBounds[0] + && my < craftRecipeListBounds[0] + craftRecipeListBounds[1]) { + craftRecipeScrollOffset = Math.max(0, craftRecipeScrollOffset - (int)(amount * CATALOG_ITEM_H)); + return true; + } + + scrollOffset = Math.max(0, scrollOffset - (int)(amount * 12)); + return true; + } + + @Override + public boolean keyPressed(int keyCode, int scanCode, int modifiers) { + if (!visible) return false; + if (packetSelectorOverlay.isVisible()) return packetSelectorOverlay.keyPressed(keyCode, scanCode, modifiers); + if (raceStepSelectorOverlay.isVisible()) return raceStepSelectorOverlay.keyPressed(keyCode, scanCode, modifiers); + if (CompactDropdown.isMenuOpen(enumDropdowns)) { + if (keyCode == GLFW.GLFW_KEY_ESCAPE || keyCode == GLFW.GLFW_KEY_ENTER) { + CompactDropdown.closeOpenMenu(enumDropdowns); + } + return true; + } + if (keyCode == GLFW.GLFW_KEY_ESCAPE) { + if (cancelCaptureIfActive()) return true; + if (hasTextFieldFocused()) { clearTextFieldFocus(); return true; } + closeEditor(false); + return true; + } + KeyEvent ki = new KeyEvent(keyCode, scanCode, modifiers); + + for (AutismChatField f : textFields.values()) { + if (f.isFocused()) return f.keyPressed(ki); + } + for (AutismChatField f : addFields.values()) { + if (f.isFocused()) return f.keyPressed(ki); + } + return false; + } + + @Override + public boolean charTyped(char chr, int modifiers) { + if (!visible) return false; + if (packetSelectorOverlay.isVisible()) return packetSelectorOverlay.charTyped(chr, modifiers); + if (raceStepSelectorOverlay.isVisible()) return raceStepSelectorOverlay.charTyped(chr, modifiers); + CharacterEvent ci = new CharacterEvent(chr); + for (AutismChatField f : textFields.values()) { + if (f.isFocused() && f.charTyped(ci)) return true; + } + for (AutismChatField f : addFields.values()) { + if (f.isFocused() && f.charTyped(ci)) return true; + } + return false; + } + + private boolean isFieldVisible(FieldDef field) { + if (field == null) return false; + if ("safeClickDelayTicks".equals(field.key())) { + return isXCarrySafeClickTimingVisible(); + } + if ("safeClickDelayAfterPickup".equals(field.key()) || "safeClickDelayBeforeReturn".equals(field.key())) { + return isXCarrySafeClickTimingVisible(); + } + if (isGuiNameField(field.key()) && targetAction instanceof WaitsForGui) { + return hasGuiWaitEnabled(); + } + if (targetAction != null && targetAction.getType() == MacroActionType.INVENTORY) { + String mode = currentEnumValue("mode"); + if ("waitForGuiBefore".equals(field.key()) || "waitForGuiAfter".equals(field.key())) { + return "OPEN".equals(mode); + } + if ("sendPacket".equals(field.key())) { + return "CLOSE".equals(mode); + } + } + if (targetAction != null && targetAction.getType() == MacroActionType.WAIT_ENTITY) { + String checkMode = currentEnumValue("checkMode"); + if ("centerOnPlayer".equals(field.key()) + || "radius".equals(field.key()) + || "mustBeLookingAt".equals(field.key())) { + return "RADIUS".equals(checkMode) || ("NEARBY".equals(checkMode) && !"mustBeLookingAt".equals(field.key())); + } + if ("pos".equals(field.key())) { + return ("RADIUS".equals(checkMode) || "NEARBY".equals(checkMode)) && !toggleStates.getOrDefault("centerOnPlayer", false); + } + } + + if (targetAction != null && targetAction.getType() == MacroActionType.INVENTORY_AUDIT) { + String mode = currentEnumValue("mode"); + String openMode = currentEnumValue("openMode"); + boolean isDupeMode = "DUPE".equals(mode) || "DUPE_SPAM".equals(mode); + boolean isDupeSpam = "DUPE_SPAM".equals(mode); + + if ("targetItems".equals(field.key())) { + return isDupeMode; + } + + if ("openCommand".equals(field.key())) { + return isDupeMode && "COMMAND".equals(openMode); + } + + if ("containerPos".equals(field.key())) { + return isDupeMode && "CONTAINER".equals(openMode); + } + + if ("spamCount".equals(field.key()) || "spamDelayMs".equals(field.key())) { + return isDupeSpam; + } + + if ("openMode".equals(field.key()) || + "dupeVector".equals(field.key()) || + "iterations".equals(field.key()) || + "maxTransferAttempts".equals(field.key()) || + "transferRetryDelayMs".equals(field.key())) { + return isDupeMode; + } + } + + if (targetAction != null && targetAction.getType() == MacroActionType.PACKET_GATE + && "DISABLE_GATE".equals(currentEnumValue("mode"))) { + String key = field.key(); + return "mode".equals(key) || "gateId".equals(key) || "flushOnDisable".equals(key); + } + + if (targetAction != null && (targetAction.getType() == MacroActionType.FPS + || targetAction.getType() == MacroActionType.SPING)) { + String endMode = currentEnumValue("endMode"); + boolean timeout = endMode.isEmpty() || "TIMEOUT".equals(endMode); + boolean steps = "STEPS".equals(endMode); + boolean useTicks = toggleStates.getOrDefault("useTicks", false); + String key = field.key(); + if ("stepCount".equals(key)) return steps; + if ("useTicks".equals(key)) return timeout; + if ("durationMs".equals(key)) return timeout && !useTicks; + if ("durationTicks".equals(key)) return timeout && useTicks; + if ("continueNextActions".equals(key)) return timeout; + } + if (targetAction != null && targetAction.getType() == MacroActionType.CAPTURE_VALUE) { + String key = field.key(); + if ("listFilterText".equals(key) || "listStripPrefix".equals(key) || "listPickPosition".equals(key)) { + String source = currentEnumValue("source"); + if (!"COMMAND_AUTOFILL".equals(source) && !"TABLIST".equals(source)) return false; + String filter = currentEnumValue("listFilter"); + if ("listFilterText".equals(key)) return !"NONE".equals(filter); + if ("listStripPrefix".equals(key)) return "PREFIX".equals(filter) || "SUFFIX".equals(filter); + return "POSITION".equals(currentEnumValue("listSelection")); + } + } + + if (!field.hasShowWhen()) return true; + boolean cond; + if (field.showWhenValue() != null && !field.showWhenValue().isEmpty()) { + String currentValue = currentEnumValue(field.showWhenKey()); + cond = false; + for (String allowed : field.showWhenValue().split("\\|")) { + if (allowed.equals(currentValue)) { + cond = true; + break; + } + } + } else { + cond = toggleStates.getOrDefault(field.showWhenKey(), false); + } + boolean visible = field.showWhenInverted() ? !cond : cond; + + if (visible && !field.showWhenInverted()) { + FieldDef dep = getField(field.showWhenKey()); + if (dep != null && !isFieldVisible(dep)) visible = false; + } + return visible; + } + + private boolean isXCarrySafeClickTimingVisible() { + return targetAction != null + && targetAction.getType() == MacroActionType.XCARRY + && "PUT_IN".equals(currentEnumValue("mode")) + && "SAFE_CLICK".equals(currentEnumValue("transferMode")); + } + + private boolean isGuiNameField(String key) { + return "guiName".equals(key) || "waitGuiName".equals(key); + } + + private boolean hasGuiWaitEnabled() { + return toggleStates.getOrDefault("waitForGuiBefore", false) + || toggleStates.getOrDefault("waitForGuiAfter", false) + || toggleStates.getOrDefault("waitForGui", false); + } + + private String currentEnumValue(String key) { + if (schema == null) return ""; + for (FieldDef field : schema.fields()) { + if (!field.key().equals(key) || field.type() != FieldType.ENUM) continue; + List opts = field.enumOptions(); + if (opts.isEmpty()) return ""; + int idx = Math.min(enumIndices.getOrDefault(key, 0), opts.size() - 1); + return opts.get(idx); + } + return ""; + } + + private void prepareWorkingTagForEditor(MacroAction action) { + if (action == null || workingTag == null) return; + + if (action instanceof autismclient.util.macro.SelectSlotAction selectSlotAction) { + primeStructuredField("itemName", selectSlotAction.itemTarget, selectSlotAction.itemName, null); + } + if (action instanceof autismclient.util.macro.UseItemAction useItemAction) { + primeStructuredField("itemName", useItemAction.itemTarget, useItemAction.itemName, "slot"); + if (useItemAction.slot >= 0) workingTag.putInt("slot", useItemAction.slot); + } + if (action instanceof autismclient.util.macro.WaitForCooldownAction waitForCooldownAction) { + primeStructuredField("itemName", waitForCooldownAction.itemTarget, waitForCooldownAction.itemName, null); + } + if (action instanceof autismclient.util.macro.CloseGuiAction closeGuiAction) { + primeStructuredField("itemName", closeGuiAction.itemTarget, closeGuiAction.itemName, "targetSlot"); + } + if (action instanceof autismclient.util.macro.SwapSlotsAction swapSlotsAction) { + primeStructuredField("fromItemName", swapSlotsAction.fromItemTarget, swapSlotsAction.fromItemName, null); + primeStructuredField("toItemName", swapSlotsAction.toItemTarget, swapSlotsAction.toItemName, null); + } + if (action instanceof autismclient.util.macro.StoreItemAction storeItemAction) { + primeStructuredList("targetItems", storeItemAction.itemTargets, storeItemAction.targetItems); + } + if (action instanceof autismclient.util.macro.XCarryAction xCarryAction) { + primeStructuredList("entries", xCarryAction.entryTargets, xCarryAction.entries); + workingTag.putInt("safeClickDelayTicks", + autismclient.util.macro.XCarryAction.clampSafeClickDelayTicks(xCarryAction.safeClickDelayTicks)); + workingTag.putBoolean("safeClickDelayAfterPickup", xCarryAction.safeClickDelayAfterPickup); + workingTag.putBoolean("safeClickDelayBeforeReturn", xCarryAction.safeClickDelayBeforeReturn); + ListTag destinations = new ListTag(); + xCarryAction.resizeDestinations(xCarryAction.entries.size()); + xCarryAction.resizeAmountSettings(xCarryAction.entries.size()); + ListTag amountModes = new ListTag(); + ListTag amounts = new ListTag(); + for (int i = 0; i < xCarryAction.entries.size(); i++) { + destinations.add(StringTag.valueOf(String.valueOf(xCarryAction.destinationFor(i)))); + amountModes.add(StringTag.valueOf(xCarryAction.amountModeFor(i).name())); + amounts.add(StringTag.valueOf(String.valueOf(xCarryAction.amountFor(i)))); + } + workingTag.put("entryDestinations", destinations); + workingTag.put("entryAmountModes", amountModes); + workingTag.put("entryAmounts", amounts); + } + if (action instanceof autismclient.util.macro.InventoryAuditAction inventoryAuditAction) { + primeStructuredList("targetItems", inventoryAuditAction.itemTargets, inventoryAuditAction.targetItems); + } + if (action instanceof autismclient.util.macro.PlaceAction placeAction) { + primeStructuredField("itemName", placeAction.itemTarget, placeAction.itemName, null); + normalizePlaceWorkingTag(); + } + } + + private void normalizePlaceWorkingTag() { + if (workingTag == null) return; + workingTag.remove("slot"); + if (!workingTag.getBooleanOr("manualDirection", false)) { + workingTag.remove("direction"); + } + } + + private ItemTarget buildPlaceItemTarget() { + AutismChatField nameF = textFields.get("itemName"); + AutismChatField slotF = textFields.get("place_itemSlot"); + return buildEntryTargetFromEditor( + nameF == null ? "" : nameF.getText(), + slotF == null ? "" : slotF.getText(), + editorItemFields.get("itemName") + ); + } + + private void syncPlaceItemEditorFields() { + if (targetAction == null || targetAction.getType() != MacroActionType.PLACE) return; + ItemTarget target = buildPlaceItemTarget(); + if (target.hasSlot() || target.hasIdentity()) { + editorItemFields.put("itemName", target.copy()); + } else { + editorItemFields.remove("itemName"); + } + } + + private void primeStructuredField(String key, ItemTarget source, String legacyValue, String slotKey) { + ItemTarget resolved = resolveEditorTarget(source, legacyValue); + if (!resolved.hasSlot() && !resolved.hasIdentity()) return; + + editorItemFields.put(key, resolved.copy()); + workingTag.putString(key, resolved.editorText()); + if (slotKey != null && resolved.hasSlot()) { + workingTag.putInt(slotKey, resolved.slot); + } + } + + private void refreshItemTextDisplayProviders() { + bindStructuredItemFieldDisplay("itemName"); + bindStructuredItemFieldDisplay("fromItemName"); + bindStructuredItemFieldDisplay("toItemName"); + bindTransientItemEditorDisplay("_item_add"); + bindTransientItemEditorDisplay("_drop_add"); + bindTransientItemEditorDisplay("_wsc_add"); + bindTransientItemEditorDisplay("targetItems"); + } + + private void bindStructuredItemFieldDisplay(String key) { + AutismChatField field = textFields.get(key); + if (field == null) return; + field.setDisplayTextProvider(value -> resolveStructuredItemFieldDisplay(key, value)); + } + + private void bindTransientItemEditorDisplay(String key) { + AutismChatField field = addFields.get(key); + if (field == null) return; + field.setDisplayTextProvider(value -> resolveTransientItemEditorDisplay(key, value)); + } + + private Component resolveStructuredItemFieldDisplay(String key, String value) { + return richItemFieldDisplay(editorItemFields.get(key), value); + } + + private Component resolveTransientItemEditorDisplay(String key, String value) { + return switch (key) { + case "_item_add" -> richItemFieldDisplay( + itemAction != null && itemEditIndex >= 0 && itemEditIndex < itemAction.itemNames.size() + ? targetAt(itemAction.itemTargets, itemAction.itemNames, itemEditIndex) + : null, + value + ); + case "_drop_add" -> richItemFieldDisplay( + dropAction != null && dropEditIndex >= 0 && dropEditIndex < dropAction.itemNames.size() + ? targetAt(dropAction.itemTargets, dropAction.itemNames, dropEditIndex) + : null, + value + ); + case "_wsc_add" -> richItemFieldDisplay( + wscEntries != null && wscEditIndex >= 0 && wscEditIndex < wscEntries.size() + ? wscEntries.get(wscEditIndex).resolvedTarget() + : null, + value + ); + case "targetItems" -> richItemFieldDisplay(resolveSelectedTargetItemsEditorTarget(), value); + default -> null; + }; + } + + private ItemTarget resolveSelectedTargetItemsEditorTarget() { + int storeIndex = stringListEditIndex.getOrDefault("store_items_selected", -1); + int auditIndex = stringListEditIndex.getOrDefault("audit_items_selected", -1); + int index = storeIndex >= 0 ? storeIndex : auditIndex; + if (index < 0) return null; + List targets = buildStructuredListTargets("targetItems"); + if (index >= 0 && index < targets.size()) { + ItemTarget target = targets.get(index); + if (target != null && (target.hasSlot() || target.hasIdentity())) return target; + } + return null; + } + + private Component richItemFieldDisplay(ItemTarget target, String value) { + if (target == null) return null; + Component rich = target.editorComponent(value); + if (rich == null) return null; + String safeValue = value == null ? "" : value; + return safeValue.equals(rich.getString()) ? rich.copy() : null; + } + + private void primeStructuredList(String key, List source, List legacyValues) { + List resolved = copyEditorTargets(source, legacyValues); + if (resolved.isEmpty()) return; + + editorItemLists.put(key, ItemTarget.copyList(resolved)); + ListTag listTag = new ListTag(); + for (ItemTarget target : resolved) { + if (target == null) continue; + String entry = target.toLegacyEntry(); + if (!entry.isBlank()) listTag.add(StringTag.valueOf(entry)); + } + workingTag.put(key, listTag); + } + + private ItemTarget resolveEditorTarget(ItemTarget source, String legacyValue) { + if (source != null && (source.hasSlot() || source.hasIdentity())) return source.copy(); + return ItemTarget.fromLegacyEntry(legacyValue); + } + + private List copyEditorTargets(List source, List legacyValues) { + List resolved = ItemTarget.copyList(source); + if (!resolved.isEmpty()) return resolved; + + List parsed = new ArrayList<>(); + if (legacyValues == null) return parsed; + for (String legacyValue : legacyValues) { + ItemTarget target = ItemTarget.fromLegacyEntry(legacyValue); + if (target.hasSlot() || target.hasIdentity()) parsed.add(target); + } + return parsed; + } + + private ItemTarget buildStructuredFieldTarget(String key, String slotKey) { + AutismChatField valueField = textFields.get(key); + String text = valueField == null ? "" : valueField.getText().strip(); + ItemTarget previous = editorItemFields.get(key); + int slot = -1; + boolean slotDriven = false; + if (slotKey != null) { + AutismChatField slotField = textFields.get(slotKey); + slot = slotField == null ? -1 : parseHandlerSlotField(slotField.getText(), -1); + slotDriven = true; + } else if (previous != null && previous.hasSlot()) { + slot = previous.slot; + } + + if (text.isEmpty() && (!slotDriven || slot < 0)) { + return new ItemTarget(); + } + + if (previous != null && text.equals(previous.editorText())) { + ItemTarget preserved = previous.copy(); + if (slotDriven) preserved.slot = slot; + return preserved; + } + + if (previous != null && previous.hasRichText() && !text.isEmpty()) { + ItemTarget preserved = previous.withEditedRichDisplay(text); + if (slot >= 0) preserved.slot = slot; + else if (slotDriven) preserved.slot = -1; + return preserved; + } + + String raw; + if (slot >= 0 && !text.isEmpty()) raw = "#" + slot + "|" + text; + else if (slot >= 0) raw = "#" + slot; + else raw = text; + return ItemTarget.fromLegacyEntry(raw); + } + + private List buildStructuredListTargets(String key) { + List values = stringLists.getOrDefault(key, Collections.emptyList()); + List previous = editorItemLists.getOrDefault(key, Collections.emptyList()); + boolean[] used = new boolean[previous.size()]; + List rebuilt = new ArrayList<>(); + for (String value : values) { + String entry = value == null ? "" : value.strip(); + if (entry.isEmpty()) continue; + + ItemTarget preserved = null; + for (int i = 0; i < previous.size(); i++) { + ItemTarget candidate = previous.get(i); + if (used[i] || candidate == null) continue; + if (entry.equals(candidate.toLegacyEntry())) { + preserved = candidate.copy(); + used[i] = true; + break; + } + } + if (preserved == null) preserved = ItemTarget.fromLegacyEntry(entry); + if (isXCarryListKey(key) && preserved.hasIdentity()) preserved.slot = -1; + if (preserved.hasSlot() || preserved.hasIdentity()) rebuilt.add(preserved); + } + editorItemLists.put(key, ItemTarget.copyList(rebuilt)); + return rebuilt; + } + + private void rewriteStructuredEditorTargets() { + if (targetAction == null || workingTag == null) return; + + if (targetAction instanceof autismclient.util.macro.SelectSlotAction) { + writeStructuredField("itemName", buildStructuredFieldTarget("itemName", null)); + } + if (targetAction instanceof autismclient.util.macro.UseItemAction) { + writeStructuredField("itemName", buildStructuredFieldTarget("itemName", "slot")); + } + if (targetAction instanceof autismclient.util.macro.WaitForCooldownAction) { + writeStructuredField("itemName", buildStructuredFieldTarget("itemName", null)); + } + if (targetAction instanceof autismclient.util.macro.CloseGuiAction) { + writeStructuredField("itemName", buildStructuredFieldTarget("itemName", "targetSlot")); + } + if (targetAction instanceof autismclient.util.macro.SwapSlotsAction) { + writeStructuredField("fromItemName", buildStructuredFieldTarget("fromItemName", null)); + writeStructuredField("toItemName", buildStructuredFieldTarget("toItemName", null)); + } + if (targetAction instanceof autismclient.util.macro.PlaceAction) { + writeStructuredField("itemName", buildPlaceItemTarget()); + workingTag.remove("slot"); + } + if (targetAction instanceof autismclient.util.macro.StoreItemAction) { + writeStructuredList("targetItems", buildStructuredListTargets("targetItems")); + } + if (targetAction instanceof autismclient.util.macro.XCarryAction) { + writeStructuredList("entries", buildStructuredListTargets("entries")); + int count = stringLists.getOrDefault("entries", Collections.emptyList()).size(); + syncXCarryDestinationCount(count); + syncXCarryAmountCount(count); + } + if (targetAction instanceof autismclient.util.macro.InventoryAuditAction) { + writeStructuredList("targetItems", buildStructuredListTargets("targetItems")); + } + } + + private void writeStructuredField(String key, ItemTarget target) { + if (target == null || (!target.hasSlot() && !target.hasIdentity())) { + workingTag.remove(key); + editorItemFields.remove(key); + return; + } + workingTag.put(key, target.toTag()); + editorItemFields.put(key, target.copy()); + } + + private void writeStructuredList(String key, List targets) { + workingTag.put(key, ItemTarget.toTagList(targets)); + } + + private void refreshInteractiveLayout() { + hitRegions.clear(); + scrollDragRegions.clear(); + int neededH = HEADER_HEIGHT + PAD + computeContentH() + FOOTER_H + PAD; + int minH = currentMinPanelHeight(); + int maxH = Math.max(minH, AutismUiScale.getVirtualScreenHeight() * 4 / 5); + panelH = Math.max(minH, Math.min(maxH, neededH)); + AutismWindowLayout clamped = clampToScreen(this, new AutismWindowLayout(panelX, panelY, panelW, panelH, visible, collapsed)); + panelX = clamped.x; + panelY = clamped.y; + panelW = clamped.width; + panelH = clamped.height; + } + + private void toggleWscEditSelection(int index) { + if (wscEditIndex == index) { + wscEditIndex = -1; + clearWscEditorFields(); + } else { + wscEditIndex = index; + if (wscEntries != null && index < wscEntries.size()) { + syncWscEditorFromEntry(wscEntries.get(index)); + } + } + } + + private void syncWscEditorFromEntry(WaitForSlotChangeAction.WaitEntry e) { + AutismChatField addF = addFields.get("_wsc_add"); + AutismChatField slotF = textFields.get("wsc_slot"); + AutismChatField countF = textFields.get("wsc_count"); + if (addF == null || slotF == null) return; + suppressWscLiveUpdate = true; + ItemTarget target = e.resolvedTarget(); + addF.setText(target.editorText()); + slotF.setText(target.hasSlot() ? String.valueOf(target.slot) : ""); + if (countF != null) countF.setText(String.valueOf(Math.max(1, e.targetCount))); + suppressWscLiveUpdate = false; + } + + private void clearWscEditorFields() { + AutismChatField addF = addFields.get("_wsc_add"); + AutismChatField slotF = textFields.get("wsc_slot"); + AutismChatField countF = textFields.get("wsc_count"); + suppressWscLiveUpdate = true; + if (addF != null) addF.setText(""); + if (slotF != null) slotF.setText(""); + if (countF != null) countF.setText(""); + suppressWscLiveUpdate = false; + } + + private void handleWscEntryEditorChanged() { + if (suppressWscLiveUpdate || wscEntries == null) return; + if (wscEditIndex < 0 || wscEditIndex >= wscEntries.size()) return; + AutismChatField addF = addFields.get("_wsc_add"); + AutismChatField slotF = textFields.get("wsc_slot"); + if (addF == null || slotF == null) return; + String nameText = addF.getText().strip(); + String slotText = slotF.getText().strip(); + WaitForSlotChangeAction.WaitEntry entry = wscEntries.get(wscEditIndex); + ItemTarget target = buildEntryTargetFromEditor(nameText, slotText, entry.resolvedTarget()); + String rawTarget = target.toLegacyEntry(); + String norm = rawTarget.isEmpty() ? "" : + autismclient.util.macro.StoreItemAction.normalizeTargetEntry(rawTarget); + if (norm == null) norm = ""; + if (!wscTargetExistsOtherThan(norm, wscEditIndex)) { + entry.target = norm; + entry.itemTarget = target; + } + } + + private void handleWscCountChanged() { + if (suppressWscLiveUpdate || wscEntries == null) return; + AutismChatField countF = textFields.get("wsc_count"); + if (countF == null) return; + int count; + try { count = Integer.parseInt(countF.getText().strip()); } + catch (NumberFormatException ignored) { return; } + count = Math.max(1, count); + if (wscEditIndex >= 0 && wscEditIndex < wscEntries.size()) { + wscEntries.get(wscEditIndex).targetCount = count; + } else { + wscAddCount = count; + } + } + + private void applyWscAddEntry(AutismChatField addF, AutismChatField slotF) { + if (wscEntries == null) return; + String nameText = addF.getText().strip(); + String slotText = slotF.getText().strip(); + ItemTarget target = buildEntryTargetFromEditor(nameText, slotText, null); + String rawTarget = target.toLegacyEntry(); + String norm = rawTarget.isEmpty() ? "" : + autismclient.util.macro.StoreItemAction.normalizeTargetEntry(rawTarget); + if (norm == null) norm = ""; + if (!wscTargetExists(norm)) { + WaitForSlotChangeAction.WaitEntry entry = new WaitForSlotChangeAction.WaitEntry(norm, wscAddMode, wscAddCount); + entry.itemTarget = target; + entry.target = norm; + wscEntries.add(entry); + addF.setText(""); + slotF.setText(""); + } + } + + private boolean wscTargetExists(String normTarget) { + if (wscEntries == null) return false; + for (WaitForSlotChangeAction.WaitEntry e : wscEntries) { + if (e.target.equals(normTarget)) return true; + } + return false; + } + + private boolean wscTargetExistsOtherThan(String normTarget, int ignoreIdx) { + if (wscEntries == null) return false; + for (int i = 0; i < wscEntries.size(); i++) { + if (i != ignoreIdx && wscEntries.get(i).target.equals(normTarget)) return true; + } + return false; + } + + private boolean isWaitSlotChangeEntryKey(String key) { + return targetAction != null + && targetAction.getType() == MacroActionType.WAIT_SLOT_CHANGE + && "targetEntries".equals(key); + } + + private boolean isStoreItemTargetListKey(String key) { + return targetAction != null + && targetAction.getType() == MacroActionType.STORE_ITEM + && "targetItems".equals(key); + } + + private boolean isInventoryAuditTargetListKey(String key) { + return targetAction != null + && targetAction.getType() == MacroActionType.INVENTORY_AUDIT + && "targetItems".equals(key); + } + + private boolean usesStoreTargetFormatting(String key) { + return isStoreItemTargetListKey(key) || isInventoryAuditTargetListKey(key); + } + + private String buildHandlerEntryFromEditor(String nameText, String slotText) { + String trimmedName = nameText == null ? "" : nameText.trim(); + int slot = parseHandlerSlotField(slotText, -1); + if (!trimmedName.isEmpty() && slot >= 0) return "#" + slot + "|" + trimmedName; + if (!trimmedName.isEmpty()) return trimmedName; + return slot >= 0 ? "#" + slot : null; + } + + private ItemTarget captureItemTarget(net.minecraft.world.inventory.Slot slot, String itemName, String registryId, int visibleSlot) { + if (slot != null && slot.getItem() != null && !slot.getItem().isEmpty()) { + return ItemTarget.capture(slot.getItem(), visibleSlot); + } + if (visibleSlot >= 0) return ItemTarget.slotOnly(visibleSlot); + String fallback = registryId != null && !registryId.isBlank() + ? registryId.trim() + : (itemName == null ? "" : itemName.trim()); + return ItemTarget.fromLegacyEntry(fallback); + } + + private static ItemTarget stripSlotFromTarget(ItemTarget target) { + if (target == null) return new ItemTarget(); + if (!target.hasSlot()) return target; + ItemTarget copy = target.copy(); + copy.slot = -1; + return copy; + } + + private static ItemTarget storeCaptureTarget(ItemTarget target) { + if (target == null) return new ItemTarget(); + if (target.hasIdentity()) return stripSlotFromTarget(target); + return target.copy(); + } + + private ItemTarget buildEntryTargetFromEditor(String nameText, String slotText, ItemTarget previous) { + String trimmedName = nameText == null ? "" : nameText.strip(); + int slot = parseHandlerSlotField(slotText, -1); + if (trimmedName.isEmpty() && slot < 0) return new ItemTarget(); + + if (previous != null && trimmedName.equals(previous.editorText())) { + ItemTarget kept = previous.copy(); + kept.slot = slot; + return kept; + } + + if (previous != null && previous.hasRichText() && !trimmedName.isEmpty()) { + ItemTarget preserved = previous.withEditedRichDisplay(trimmedName); + preserved.slot = slot; + return preserved; + } + + String raw; + if (slot >= 0 && !trimmedName.isEmpty()) raw = "#" + slot + "|" + trimmedName; + else if (slot >= 0) raw = "#" + slot; + else raw = trimmedName; + return ItemTarget.fromLegacyEntry(raw); + } + + private ItemTarget targetAt(List targets, List legacyEntries, int index) { + if (targets != null && index >= 0 && index < targets.size()) { + ItemTarget target = targets.get(index); + if (target != null && (target.hasSlot() || target.hasIdentity())) return target; + } + if (legacyEntries != null && index >= 0 && index < legacyEntries.size()) { + return ItemTarget.fromLegacyEntry(legacyEntries.get(index)); + } + return new ItemTarget(); + } + + private void preserveCapturedListTarget(String key, List entries, ItemTarget capturedTarget) { + if (key == null || entries == null || capturedTarget == null) return; + String normalized = capturedTarget.toLegacyEntry(); + if (usesStoreTargetFormatting(key) || isWaitSlotChangeEntryKey(key)) { + normalized = autismclient.util.macro.StoreItemAction.normalizeTargetEntry(normalized); + } else if (isXCarryListKey(key)) { + normalized = normalizeXCarryEntry(normalized); + } + if (normalized == null || normalized.isBlank()) return; + + int index = entries.indexOf(normalized); + if (index < 0) return; + + List targets = buildStructuredListTargets(key); + while (targets.size() < entries.size()) { + targets.add(new ItemTarget()); + } + ItemTarget stored = isXCarryListKey(key) ? stripSlotFromTarget(capturedTarget) : capturedTarget.copy(); + if (!normalized.equals(stored.toLegacyEntry())) { + ItemTarget normalizedTarget = ItemTarget.fromLegacyEntry(normalized); + stored.slot = normalizedTarget.slot; + if (!normalizedTarget.hasSlot() && !stored.hasIdentity()) { + stored = normalizedTarget; + } + } + targets.set(index, stored); + editorItemLists.put(key, ItemTarget.copyList(targets)); + } + + private void setTargetAt(List targets, List legacyEntries, int index, ItemTarget target) { + if (targets == null || legacyEntries == null || index < 0) return; + while (targets.size() <= index) targets.add(new ItemTarget()); + while (legacyEntries.size() <= index) legacyEntries.add(""); + ItemTarget stored = target == null ? new ItemTarget() : target; + targets.set(index, stored); + legacyEntries.set(index, stored.toLegacyEntry()); + } + + private void addTargetEntry(List targets, List legacyEntries, ItemTarget target) { + if (targets == null || legacyEntries == null || target == null) return; + targets.add(target); + legacyEntries.add(target.toLegacyEntry()); + } + + private void trimTargetEntries(List targets, int size) { + if (targets == null) return; + while (targets.size() > size) targets.remove(targets.size() - 1); + while (targets.size() < size) targets.add(new ItemTarget()); + } + + private boolean isEditableStringList(String key) { + return isXCarryListKey(key) || isStoreItemTargetListKey(key) + || isInventoryAuditTargetListKey(key) || isWaitSlotChangeEntryKey(key); + } + + private boolean isXCarryListKey(String key) { + return targetAction != null + && targetAction.getType() == MacroActionType.XCARRY + && "entries".equals(key); + } + + private boolean isOpenContainerEntityListKey(String key) { + return targetAction != null + && (targetAction.getType() == MacroActionType.OPEN_CONTAINER + || targetAction.getType() == MacroActionType.INTERACT_ENTITY) + && "entityTargets".equals(key); + } + + private boolean isReplaceOnCaptureEntityKey(String key) { + return false; + } + + private CaptureListAddResult tryAddCapturedStoreItemEntry(net.minecraft.world.inventory.Slot slot, + String itemName, + String registryId, + int visibleSlot, + List entries) { + if (slot == null || visibleSlot < 0) { + return new CaptureListAddResult(false, "Could not read that slot", CAPTURE_TOAST_ERROR); + } + + String mode = currentEnumValue("mode"); + boolean playerInventorySlot = autismclient.util.AutismInventoryHelper.isInventorySlot(MC, slot); + if ("LOOT".equals(mode) && playerInventorySlot) { + return new CaptureListAddResult(false, "Steal only accepts chest/custom GUI slots", CAPTURE_TOAST_ERROR); + } + if ("STORE".equals(mode) && !playerInventorySlot) { + return new CaptureListAddResult(false, "Store only accepts player inventory slots", CAPTURE_TOAST_ERROR); + } + + String rawEntry = storeCaptureTarget(captureItemTarget(slot, itemName, registryId, visibleSlot)).toLegacyEntry(); + return tryAddCapturedStringListEntry(findField("targetItems"), "targetItems", entries, rawEntry); + } + + private String normalizeXCarryEntry(String raw) { + if (raw == null) return null; + String trimmed = raw.trim(); + if (trimmed.isEmpty()) return null; + ItemTarget parsed = ItemTarget.fromLegacyEntry(trimmed); + if (parsed.hasIdentity()) { + parsed.slot = -1; + String entry = parsed.toLegacyEntry(); + return entry == null || entry.isBlank() ? null : entry; + } + if (!trimmed.startsWith("#") && trimmed.matches("\\d+")) { + trimmed = "#" + trimmed; + } + return autismclient.util.macro.XCarryAction.normalizeEntry(trimmed); + } + + private boolean addStringListEntry(FieldDef field, List entries, String rawEntry) { + if (entries == null || rawEntry == null) return false; + String entry = rawEntry.strip(); + if (entry.isEmpty()) return false; + + if (field != null && isXCarryListKey(field.key())) { + entry = normalizeXCarryEntry(entry); + if (entry == null) return false; + int limit = currentXCarryEntryLimit(); + if (entries.size() >= limit) { + AutismClientMessaging.sendPrefixed(xCarryLimitMessage(limit)); + return false; + } + entries.add(entry); + syncXCarryDestinationCount(entries.size()); + syncXCarryAmountCount(entries.size()); + return true; + } + + if (field != null && isOpenContainerEntityListKey(field.key())) { + if (entry.isBlank()) return false; + if (!entries.contains(entry)) entries.add(entry); + return true; + } + + if (field != null && (usesStoreTargetFormatting(field.key()) || isWaitSlotChangeEntryKey(field.key()))) { + entry = autismclient.util.macro.StoreItemAction.normalizeTargetEntry(entry); + if (entry == null || entry.isBlank() || entries.contains(entry)) return false; + entries.add(entry); + return true; + } + + if (field != null && "players".equals(field.key())) { + if (containsIgnoreCase(entries, entry)) return false; + entries.add(entry); + return true; + } + + entries.add(entry); + return true; + } + + private CaptureListAddResult tryAddCapturedStringListEntry(FieldDef field, String key, List entries, String rawEntry) { + if (entries == null) return null; + String entry = rawEntry == null ? "" : rawEntry.strip(); + if (entry.isEmpty()) { + return new CaptureListAddResult(false, "Nothing to add from that slot", CAPTURE_TOAST_ERROR); + } + + if (field != null && isXCarryListKey(field.key())) { + entry = normalizeXCarryEntry(entry); + if (entry == null || entry.isBlank()) { + return new CaptureListAddResult(false, "Could not read that XCarry entry", CAPTURE_TOAST_ERROR); + } + String formatted = formatStringListEntry(key, entry); + int limit = currentXCarryEntryLimit(); + if (entries.size() >= limit) { + return new CaptureListAddResult(false, xCarryLimitMessage(limit), CAPTURE_TOAST_ERROR); + } + entries.add(entry); + syncXCarryDestinationCount(entries.size()); + syncXCarryAmountCount(entries.size()); + return new CaptureListAddResult(true, "Added " + formatted, CAPTURE_TOAST_SUCCESS); + } + + if (field != null && (usesStoreTargetFormatting(field.key()) || isWaitSlotChangeEntryKey(field.key()))) { + entry = autismclient.util.macro.StoreItemAction.normalizeTargetEntry(entry); + if (entry == null || entry.isBlank()) { + return new CaptureListAddResult(false, "Could not read that slot target", CAPTURE_TOAST_ERROR); + } + } + + String formatted = formatStringListEntry(key, entry); + if (entries.contains(entry)) { + return new CaptureListAddResult(false, "Already added " + formatted, CAPTURE_TOAST_ERROR); + } + entries.add(entry); + return new CaptureListAddResult(true, "Added " + formatted, CAPTURE_TOAST_SUCCESS); + } + + private String formatStringListEntry(String key, String entry) { + if (isXCarryListKey(key)) { + String formatted = autismclient.util.macro.XCarryAction.formatEntry(entry); + if (!formatted.isEmpty()) return formatted; + } + if (usesStoreTargetFormatting(key) || isWaitSlotChangeEntryKey(key)) { + return autismclient.util.macro.StoreItemAction.formatTargetEntry(entry); + } + if (isOpenContainerEntityListKey(key)) { + return formatEntityEntry(entry); + } + return entry == null ? "" : entry; + } + + private int currentXCarryEntryLimit() { + return autismclient.util.macro.XCarryAction.MAX_ENTRIES; + } + + private String xCarryLimitMessage(int limit) { + return "XCarry limit reached: " + limit + " entries max (5 craft + 4 armor + offhand + cursor)"; + } + + private void syncXCarryDestinationCount(int count) { + if (workingTag == null) return; + ListTag list = workingTag.getList("entryDestinations").orElse(new ListTag()); + while (list.size() < count) list.add(StringTag.valueOf(String.valueOf(autismclient.util.macro.XCarryAction.DEST_AUTO))); + while (list.size() > count) list.remove(list.size() - 1); + workingTag.put("entryDestinations", list); + } + + private void syncXCarryAmountCount(int count) { + if (workingTag == null) return; + ListTag modes = workingTag.getList("entryAmountModes").orElse(new ListTag()); + while (modes.size() < count) modes.add(StringTag.valueOf(autismclient.util.macro.XCarryAction.AmountMode.FULL_STK.name())); + while (modes.size() > count) modes.remove(modes.size() - 1); + workingTag.put("entryAmountModes", modes); + + ListTag amounts = workingTag.getList("entryAmounts").orElse(new ListTag()); + while (amounts.size() < count) amounts.add(StringTag.valueOf("1")); + while (amounts.size() > count) amounts.remove(amounts.size() - 1); + workingTag.put("entryAmounts", amounts); + } + + private int getXCarryDestination(int index) { + if (workingTag == null || index < 0) return autismclient.util.macro.XCarryAction.DEST_AUTO; + ListTag list = workingTag.getList("entryDestinations").orElse(new ListTag()); + if (index >= list.size()) return autismclient.util.macro.XCarryAction.DEST_AUTO; + try { + return Integer.parseInt(list.get(index).asString().orElse(String.valueOf(autismclient.util.macro.XCarryAction.DEST_AUTO))); + } catch (Exception ignored) { + return autismclient.util.macro.XCarryAction.DEST_AUTO; + } + } + + private void setXCarryDestination(int index, int destination) { + if (workingTag == null || index < 0) return; + syncXCarryDestinationCount(Math.max(index + 1, stringLists.getOrDefault("entries", Collections.emptyList()).size())); + ListTag list = workingTag.getList("entryDestinations").orElse(new ListTag()); + if (index >= list.size()) return; + list.set(index, StringTag.valueOf(String.valueOf(destination))); + workingTag.put("entryDestinations", list); + } + + private void removeXCarryDestination(int index) { + if (workingTag == null || index < 0) return; + ListTag list = workingTag.getList("entryDestinations").orElse(new ListTag()); + if (index >= 0 && index < list.size()) list.remove(index); + workingTag.put("entryDestinations", list); + } + + private autismclient.util.macro.XCarryAction.AmountMode getXCarryAmountMode(int index) { + if (workingTag == null || index < 0) return autismclient.util.macro.XCarryAction.AmountMode.FULL_STK; + ListTag list = workingTag.getList("entryAmountModes").orElse(new ListTag()); + if (index >= list.size()) return autismclient.util.macro.XCarryAction.AmountMode.FULL_STK; + try { + return autismclient.util.macro.XCarryAction.AmountMode.valueOf( + list.get(index).asString().orElse(autismclient.util.macro.XCarryAction.AmountMode.FULL_STK.name())); + } catch (IllegalArgumentException ignored) { + return autismclient.util.macro.XCarryAction.AmountMode.FULL_STK; + } + } + + private void setXCarryAmountMode(int index, autismclient.util.macro.XCarryAction.AmountMode mode) { + if (workingTag == null || index < 0) return; + syncXCarryAmountCount(Math.max(index + 1, stringLists.getOrDefault("entries", Collections.emptyList()).size())); + ListTag list = workingTag.getList("entryAmountModes").orElse(new ListTag()); + list.set(index, StringTag.valueOf((mode == null ? autismclient.util.macro.XCarryAction.AmountMode.FULL_STK : mode).name())); + workingTag.put("entryAmountModes", list); + } + + private int getXCarryAmount(int index) { + if (workingTag == null || index < 0) return 1; + ListTag list = workingTag.getList("entryAmounts").orElse(new ListTag()); + if (index >= list.size()) return 1; + try { + return Math.max(1, Integer.parseInt(list.get(index).asString().orElse("1"))); + } catch (NumberFormatException ignored) { + return 1; + } + } + + private void setXCarryAmount(int index, int amount) { + if (workingTag == null || index < 0) return; + syncXCarryAmountCount(Math.max(index + 1, stringLists.getOrDefault("entries", Collections.emptyList()).size())); + ListTag list = workingTag.getList("entryAmounts").orElse(new ListTag()); + list.set(index, StringTag.valueOf(String.valueOf(Math.max(1, amount)))); + workingTag.put("entryAmounts", list); + } + + private void removeXCarryAmount(int index) { + if (workingTag == null || index < 0) return; + ListTag modes = workingTag.getList("entryAmountModes").orElse(new ListTag()); + if (index >= 0 && index < modes.size()) modes.remove(index); + workingTag.put("entryAmountModes", modes); + ListTag amounts = workingTag.getList("entryAmounts").orElse(new ListTag()); + if (index >= 0 && index < amounts.size()) amounts.remove(index); + workingTag.put("entryAmounts", amounts); + } + + private Component formatStringListEntryText(String key, String entry, int index) { + if (usesMinecraftTextRendering(key)) { + ItemTarget target = resolveStructuredListTarget(key, index, entry); + return formatItemTargetText(target, formatStringListEntry(key, entry)); + } + return Component.literal(formatStringListEntry(key, entry)); + } + + private int getPacketRowColor(String entry, int index, boolean selected) { + if (selected) return autismclient.util.AutismColors.packetRowSelectedText(); + Class> packetClass = autismclient.util.AutismPacketRegistry.getPacket(entry); + if (packetClass == null) return theme.color(autismclient.gui.vanillaui.components.UiTone.BODY); + boolean c2s = autismclient.util.AutismPacketRegistry.getC2SPackets().contains(packetClass); + return autismclient.util.AutismColors.packetRowText(c2s, index); + } + + private ItemTarget resolveStructuredListTarget(String key, int index, String entry) { + List targets = buildStructuredListTargets(key); + if (index >= 0 && index < targets.size()) { + ItemTarget target = targets.get(index); + if (target != null && (target.hasSlot() || target.hasIdentity())) return target.copy(); + } + ItemTarget parsed = ItemTarget.fromLegacyEntry(entry); + return (parsed.hasSlot() || parsed.hasIdentity()) ? parsed : null; + } + + private boolean usesMinecraftTextRendering(String key) { + return usesStoreTargetFormatting(key) || isXCarryListKey(key); + } + + private Component formatItemTargetText(ItemTarget target, String fallback) { + String safeFallback = fallback == null ? "" : fallback; + if (target == null) return Component.literal(safeFallback); + + boolean hasSlot = target.hasSlot(); + boolean hasIdentity = target.hasIdentity(); + if (hasSlot && hasIdentity) { + return Component.literal(target.slot + ": ").append(target.listComponent().copy()); + } + if (hasSlot) { + return Component.literal("#" + target.slot); + } + if (hasIdentity) { + Component display = target.listComponent(); + if (display != null && !display.getString().isBlank()) return display.copy(); + } + return Component.literal(safeFallback); + } + + private static String buildEntryFromNameAndSlot(String name, String slotText) { + String n = name == null ? "" : name.strip(); + int slot = -1; + if (slotText != null && !slotText.isBlank()) { + try { slot = Integer.parseInt(slotText.replaceAll("[^0-9]", "")); } + catch (NumberFormatException ignored) { } + } + if (slot >= 0 && !n.isEmpty()) return "#" + slot + "|" + n; + if (slot >= 0) return "#" + slot; + return n; + } + + private String parseHandlerEntryName(String entry) { + if (entry == null || entry.isBlank()) return ""; + if (!entry.startsWith("#")) return entry; + int separator = entry.indexOf('|'); + return separator >= 0 && separator + 1 < entry.length() ? entry.substring(separator + 1).trim() : ""; + } + + private int parseHandlerSlotField(String text, int fallback) { + String raw = text == null ? "" : text.trim(); + if (raw.isEmpty()) return fallback; + String cleaned = raw.replaceAll("[^0-9]", ""); + if (cleaned.isEmpty()) return fallback; + try { + int slot = Integer.parseInt(cleaned); + return slot < 0 ? fallback : slot; + } catch (NumberFormatException ignored) { + return fallback; + } + } + + private int parseSlotEntryValue(String entry) { + if (entry == null || !entry.startsWith("#")) return -1; + try { + int separator = entry.indexOf('|'); + String raw = separator >= 0 ? entry.substring(1, separator) : entry.substring(1); + return Integer.parseInt(raw); + } catch (NumberFormatException ignored) { + return -1; + } + } + + private boolean containsEntryOtherThan(List entries, String entry, int ignoreIndex) { + for (int i = 0; i < entries.size(); i++) { + if (i != ignoreIndex && entries.get(i).equals(entry)) return true; + } + return false; + } + + private List getWorkingQueuedPackets() { + if (workingTag == null) return new ArrayList<>(); + SendPacketAction action = new SendPacketAction(); + action.fromTag(workingTag); + return new ArrayList<>(action.packets); + } + + private void setWorkingQueuedPackets(List packets) { + if (workingTag == null) return; + net.minecraft.nbt.ListTag packetList = new net.minecraft.nbt.ListTag(); + if (packets != null) { + for (AutismSharedState.QueuedPacket qp : packets) { + CompoundTag packetTag = AutismClipboardHelper.serializeQueuedPacket(qp); + if (packetTag != null) packetList.add(packetTag); + } + } + workingTag.put("packets", packetList); + } + + private String buildSendPacketInfo() { + List packets = getWorkingQueuedPackets(); + if (packets.isEmpty()) return "Packets: 0"; + + String autoName = ""; + for (AutismSharedState.QueuedPacket qp : packets) { + if (qp != null && qp.packet != null) { + autoName = AutismPacketNamer.getFriendlyName(qp.packet); + break; + } + } + if (autoName.isEmpty()) return "Packets: " + packets.size(); + return packets.size() == 1 ? "Packets: 1 - " + autoName : "Packets: " + packets.size() + " - " + autoName; + } + + private void setRawPacketActionData(AutismSharedState.QueuedPacket packet) { + if (workingTag == null || packet == null) return; + List single = java.util.Collections.singletonList(packet); + String base64 = AutismClipboardHelper.serializeQueueToBase64(single); + if (base64 == null || base64.isBlank()) return; + workingTag.putString("packetData", base64); + if (!workingTag.contains("description") || workingTag.getStringOr("description", "").isBlank()) { + String name = packet.packet != null ? AutismPacketNamer.getFriendlyName(packet.packet) : "Packet"; + workingTag.putString("description", name); + } + } + + private String buildPacketActionInfo() { + if (workingTag == null) return "Raw Packet: empty"; + String packetData = workingTag.getStringOr("packetData", ""); + if (packetData == null || packetData.isBlank()) return "Raw Packet: empty"; + String description = workingTag.getStringOr("description", ""); + return description == null || description.isBlank() ? "Raw Packet: loaded" : "Raw Packet: " + description; + } + + private void startGBreakCaptureForEditor() { + if (!guardWorldCaptureAction()) return; + AutismSharedState state = AutismSharedState.get(); + screenBeforeGBreak = MC.gui.screen(); + enterCaptureMode(); + state.setCaptureCancelCallback(() -> { + state.cancelGBreakCapture(); + if (screenBeforeGBreak != null) { + MC.gui.setScreen(screenBeforeGBreak); + screenBeforeGBreak = null; + } + exitCaptureMode(false, false); + }); + MC.execute(() -> { if (MC.gui.screen() != null) MC.gui.setScreen(null); }); + AutismClientMessaging.sendPrefixed("GBreak: Break a block to capture the insta-break packet"); + state.startGBreakCapture(() -> MC.execute(() -> { + List captured = AutismSharedState.get().getGBreakCapturedPackets(); + if (!captured.isEmpty()) { + setWorkingQueuedPackets(java.util.Collections.singletonList(captured.get(0))); + workingTag.putString("customName", "GBreak"); + AutismChatField customNameField = textFields.get("customName"); + if (customNameField != null) customNameField.setText("GBreak"); + AutismClientMessaging.sendPrefixed("GBreak packet captured"); + } else { + AutismClientMessaging.sendPrefixed("GBreak capture finished with no packet"); + } + + if (screenBeforeGBreak != null) { + MC.gui.setScreen(screenBeforeGBreak); + screenBeforeGBreak = null; + } + exitCaptureMode(false, false); + AutismOverlayManager.get().bringToFront(this); + })); + } + + private void startLookAtEntityCapture() { + if (!guardWorldCaptureAction()) return; + if (!(targetAction instanceof autismclient.util.macro.LookAtBlockAction)) return; + Screen previousScreen = MC.gui.screen(); + enterCaptureMode(); + AutismSharedState state = AutismSharedState.get(); + state.setCaptureCancelCallback(() -> { + if (previousScreen != null) MC.gui.setScreen(previousScreen); + state.setEntityCaptureCallback(null); + exitCaptureMode(false, false); + }); + MC.execute(() -> { if (MC.gui.screen() != null) MC.gui.setScreen(null); }); + state.setEntityCaptureSpecific(entitySpecificCaptureMode); + state.setEntityCaptureCallback(payload -> MC.execute(() -> { + List selected = stringLists.get("entityIds"); + if (selected != null && payload != null && !payload.isBlank()) { + if (entitySpecificCaptureMode) { + selected.removeIf(existing -> existing.startsWith(entitySpecificEntryPrefix(payload))); + } + if (!selected.contains(payload)) selected.add(payload); + } + if (previousScreen != null) MC.gui.setScreen(previousScreen); + exitCaptureMode(false, false); + AutismOverlayManager.get().bringToFront(this); + })); + } + + private void renderWaitSoundPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + + cy = renderFieldByKey(ctx, "waitForGuiBefore", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "waitForGuiAfter", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "waitGuiName", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "checkDistance", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "maxDistance", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "saveAs", x, cy, w, mx, my, delta); + + List selected = stringLists.getOrDefault("soundIds", Collections.emptyList()); + cy = renderSimpleSelectedList(ctx, x, cy, w, mx, my, "wait_sound_selected", "Sounds", selected, value -> { + selected.remove(value); + DirectScrollViewport vp = selectedScrollViewports.get("wait_sound_selected"); + if (vp != null) vp.scrollBy(-1); + }, AutismRegistryLabels::sound, "(any sound - add to filter)"); + + AutismChatField search = addFields.get("soundIds"); + if (search != null) { + search.setX(x); + search.setY(cy + 1); + search.setWidth(w); + search.render(ctx, mx, my, delta); + } + cy += 18; + + String filter = search != null ? search.getText().trim().toLowerCase() : ""; + List filtered = filterRegistryValues("wait_sound_search", getAllSoundIds(), filter, AutismRegistryLabels::sound); + renderSearchRegistryList( + ctx, + x, + cy, + w, + mx, + my, + "wait_sound_search", + filtered, + 6, + value -> { + if (selected.contains(value)) selected.remove(value); + else selected.add(value); + }, + selected::contains, + AutismRegistryLabels::sound + ); + } + + private void renderWaitEntityPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + + cy = renderFieldByKey(ctx, "checkMode", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "radius", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "centerOnPlayer", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "pos", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "mustBeLookingAt", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "saveAs", x, cy, w, mx, my, delta); + + List selected = stringLists.getOrDefault("entityIds", Collections.emptyList()); + cy = renderSimpleSelectedList(ctx, x, cy, w, mx, my, "wait_entity_selected", "Entities", selected, selected::remove, + this::formatEntityEntry, "(any entity - add type or specific)"); + + AutismChatField search = addFields.get("entityIds"); + int searchW = w - 66; + if (search != null) { + search.setX(x); + search.setY(cy + 1); + search.setWidth(searchW); + search.render(ctx, mx, my, delta); + } + int modeX = x + searchW + 2; + String modeLabel = entitySpecificCaptureMode ? "[Spec]" : "[Type]"; + renderActionButton(ctx, modeX, cy, 30, 14, modeLabel, mx, my, () -> entitySpecificCaptureMode = !entitySpecificCaptureMode); + renderActionButton(ctx, modeX + 34, cy, 32, 14, "CAP", mx, my, this::startWaitEntityCapture); + cy += 18; + + String filter = search != null ? search.getText().trim().toLowerCase() : ""; + List filtered = filterRegistryValues("wait_entity_search", getAllEntityIds(), filter, AutismRegistryLabels::entity); + renderSearchRegistryList( + ctx, + x, + cy, + w, + mx, + my, + "wait_entity_search", + filtered, + 4, + value -> { + if (selected.contains(value)) selected.remove(value); + else selected.add(value); + }, + selected::contains, + AutismRegistryLabels::entity + ); + cy += 4 + 4 * CATALOG_ITEM_H + 10; + + UiText.draw(ctx, textRenderer, "Nearby Entities", font, AutismColors.textSecondary(), x, cy + 2, false); + cy += 13; + List nearbyEntries = getNearbyEntityEntries(); + renderSearchRegistryList( + ctx, + x, + cy, + w, + mx, + my, + "wait_entity_nearby", + nearbyEntries, + 3, + value -> { + String stored = entitySpecificCaptureMode ? value : extractEntityTypeFromNearbyEntry(value); + if (stored.isBlank()) return; + if (entitySpecificCaptureMode) { + boolean removed = selected.removeIf(existing -> existing.startsWith(entitySpecificEntryPrefix(stored))); + if (!removed) selected.add(stored); + } else if (selected.contains(stored)) { + selected.remove(stored); + } else { + selected.add(stored); + } + }, + value -> { + String stored = entitySpecificCaptureMode ? value : extractEntityTypeFromNearbyEntry(value); + return entitySpecificCaptureMode + ? selected.stream().anyMatch(existing -> existing.startsWith(entitySpecificEntryPrefix(stored))) + : selected.contains(stored); + }, + this::formatNearbyEntityEntry + ); + } + + private void renderOpenContainerPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + + cy = renderFieldByKey(ctx, "targetMode", x, cy, w, mx, my, delta); + String targetMode = currentEnumValue("targetMode"); + if ("ENTITY".equals(targetMode)) { + cy = renderFieldByKey(ctx, "entityTargets", x, cy, w, mx, my, delta); + } else if ("BLOCK".equals(targetMode)) { + cy = renderFieldByKey(ctx, "pos", x, cy, w, mx, my, delta); + } + cy = renderFieldByKey(ctx, "waitForGuiBefore", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "waitForGuiAfter", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "guiName", x, cy, w, mx, my, delta); + if ("ENTITY".equals(targetMode)) { + String hint = "Pick captures exact entities. Last Target reuses the most recent interaction target."; + cy = renderEditorHint(ctx, x, cy, w, hint); + List selected = stringLists.getOrDefault("entityTargets", Collections.emptyList()); + cy += 13; + List nearbyEntries = getNearbyEntityEntries(); + renderSearchRegistryList( + ctx, + x, + cy, + w, + mx, + my, + "open_container_entity_nearby", + nearbyEntries, + 3, + value -> { + if (selected.contains(value)) selected.remove(value); + else selected.add(value); + }, + selected::contains, + this::formatNearbyEntityEntry + ); + } else if ("LAST_TARGET".equals(targetMode)) { + renderEditorHint(ctx, x, cy, w, "Uses the last block or entity container you actually opened."); + } else { + cy = renderEditorHint(ctx, x, cy, w, "Capture only marks the block. It will not open it."); + renderNearbyContainerList(ctx, x, cy, w, mx, my, "open_container_nearby", "pos"); + } + } + + private void renderNearbyContainerList(GuiGraphicsExtractor ctx, int x, int y, int w, int mx, int my, + String listKey, String fieldKey) { + Identifier font = theme.fontFor(UiTone.BODY); + UiText.draw(ctx, textRenderer, "Nearby Containers", font, AutismColors.textSecondary(), x, y + 2, false); + y += 14; + List nearbyContainers = getNearbyContainerPositions(); + renderSearchRegistryList( + ctx, + x, + y, + w, + mx, + my, + listKey, + nearbyContainers, + CONTAINER_LIST_VISIBLE_ROWS, + pos -> fillBlockPosField(fieldKey, pos), + pos -> isCurrentBlockPosField(fieldKey, pos), + this::formatContainerEntry + ); + } + + private void renderStoreItemPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + int cy = bodyTop + PAD; + + cy = renderFieldByKey(ctx, "mode", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "allItems", x, cy, w, mx, my, delta); + + List selected = stringLists.getOrDefault("targetItems", Collections.emptyList()); + if (!toggleStates.getOrDefault("allItems", false)) { + cy = renderSimpleSelectedList(ctx, x, cy, w, mx, my, "store_items_selected", "Target Items", selected, + selected::remove, autismclient.util.macro.StoreItemAction::formatTargetEntry, + value -> formatStringListEntryText("targetItems", value, selected.indexOf(value)), + selected::clear, + "(nothing selected - search, type #slot, or capture)", true); + + int storeEditIdx = stringListEditIndex.getOrDefault("store_items_selected", -1); + boolean storeEditing = storeEditIdx >= 0 && storeEditIdx < selected.size(); + AutismChatField search = addFields.get("targetItems"); + int pickW = 32; + int addBtnW = 34; + int slotW = 44; + int capBtnX = x + w - pickW; + int addBtnX = capBtnX - 3 - addBtnW; + int slotX = addBtnX - 2 - slotW; + int nameW = slotX - x - 2; + + AutismChatField storeSlotF = textFields.get("store_slot"); + if (storeSlotF == null) { + storeSlotF = makeField(slotW); + storeSlotF.setNumericOnly(true); + storeSlotF.setPlaceholder(Component.literal("Slot#")); + textFields.put("store_slot", storeSlotF); + } + + String pendingText = stringListEditPendingText.remove("store_items_selected"); + if (pendingText != null) { + if (search != null) search.setText(parseHandlerEntryName(pendingText)); + ItemTarget parsed = ItemTarget.fromLegacyEntry(pendingText); + storeSlotF.setText(parsed.hasSlot() ? String.valueOf(parsed.slot) : ""); + } + + if (search != null) { + search.setX(x); search.setY(cy + 1); search.setWidth(nameW); + search.render(ctx, mx, my, delta); + } + storeSlotF.setX(slotX); storeSlotF.setY(cy + 1); storeSlotF.setWidth(slotW); + storeSlotF.render(ctx, mx, my, delta); + + if (storeEditing && search != null) { + String nameText = search.getText().strip(); + String slotText = storeSlotF.getText().strip(); + String entry = buildEntryFromNameAndSlot(nameText, slotText); + if (!entry.isEmpty()) { + String normalized = autismclient.util.macro.StoreItemAction.normalizeTargetEntry(entry); + if (normalized != null && !normalized.isBlank() && !normalized.equals(selected.get(storeEditIdx))) { + selected.set(storeEditIdx, normalized); + editorItemLists.put("targetItems", buildStructuredListTargets("targetItems")); + } + } + } + + final AutismChatField fStoreSlotF = storeSlotF; + renderOverlayButton(ctx, addBtnX, cy, addBtnW, 14, "+Add", CompactOverlayButton.Variant.SUCCESS, true, mx, my, () -> { + if (search == null) return; + String nameText = search.getText().strip(); + String slotText = fStoreSlotF.getText().strip(); + String entry = buildEntryFromNameAndSlot(nameText, slotText); + if (!entry.isEmpty()) { + String normalized = autismclient.util.macro.StoreItemAction.normalizeTargetEntry(entry); + if (normalized != null && !normalized.isBlank() && !selected.contains(normalized)) { + selected.add(normalized); + editorItemLists.put("targetItems", buildStructuredListTargets("targetItems")); + } + search.setText(""); + fStoreSlotF.setText(""); + stringListEditIndex.put("store_items_selected", -1); + } + }); + boolean capturing = captureSession.isItemSlotCapture("targetItems"); + renderFieldCaptureButton(ctx, capBtnX, cy, pickW, 14, CaptureMode.ITEM_SLOT, capturing, + true, mx, my, () -> toggleItemSlotCapture("targetItems")); + cy += 18; + + String filter = search != null ? search.getText().trim().toLowerCase() : ""; + List filtered = filterRegistryValues("store_items_search", getAllItemIds(), filter, AutismRegistryLabels::item); + renderSearchRegistryList( + ctx, + x, + cy, + w, + mx, + my, + "store_items_search", + filtered, + 6, + value -> { + if (selected.contains(value)) selected.remove(value); + else selected.add(value); + stringListEditIndex.put("store_items_selected", -1); + editorItemLists.put("targetItems", buildStructuredListTargets("targetItems")); + }, + selected::contains, + AutismRegistryLabels::item + ); + cy += 6 * CATALOG_ITEM_H + 4; + + cy = renderEditorHint(ctx, x, cy, w, "Pick on an item adds the item. Pick on an empty slot adds that exact slot."); + + String modeHint = "LOOT".equals(currentEnumValue("mode")) + ? "Pick only accepts chest/custom GUI slots here." + : "Pick only accepts player inventory slots here."; + cy = renderEditorHint(ctx, x, cy, w, modeHint); + } + + cy = renderFieldByKey(ctx, "persistent", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "delayTicks", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "closeAfter", x, cy, w, mx, my, delta); + renderFieldByKey(ctx, "closeSendPkt", x, cy, w, mx, my, delta); + } + + private void renderInventoryAuditPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + int cy = bodyTop + PAD; + + cy = renderFieldByKey(ctx, "mode", x, cy, w, mx, my, delta); + + List selected = stringLists.getOrDefault("targetItems", Collections.emptyList()); + FieldDef targetItemsField = getField("targetItems"); + if (targetItemsField != null && isFieldVisible(targetItemsField)) { + String emptyLabel = getStringListEmptyHint("targetItems"); + if (emptyLabel == null || emptyLabel.isBlank()) emptyLabel = "(nothing selected)"; + boolean multipleStacks = toggleStates.getOrDefault("multipleStacks", false); + int listTop = cy; + + cy = renderSimpleSelectedList(ctx, x, cy, w, mx, my, "audit_items_selected", "Targets", selected, + selected::remove, autismclient.util.macro.StoreItemAction::formatTargetEntry, + value -> formatStringListEntryText("targetItems", value, selected.indexOf(value)), + selected::clear, + emptyLabel, + true); + + int multiBtnW = 96; + int clearBtnW = 44; + int multiBtnX = x + w - clearBtnW - 3 - multiBtnW; + renderOverlayToggleButton(ctx, multiBtnX, listTop, multiBtnW, 14, "Multiple Stacks", + multipleStacks, "macro-audit:multiple-stacks", + mx, my, () -> toggleStates.put("multipleStacks", !toggleStates.getOrDefault("multipleStacks", false))); + + int auditEditIdx = stringListEditIndex.getOrDefault("audit_items_selected", -1); + boolean auditEditing = auditEditIdx >= 0 && auditEditIdx < selected.size(); + AutismChatField search = addFields.get("targetItems"); + int pickW = 32; + int addBtnW = 34; + int slotW = 26; + int pickX = x + w - addBtnW - 3 - pickW; + int addBtnX = x + w - addBtnW; + int slotX = pickX - 3 - slotW; + int nameW = slotX - x - 2; + + AutismChatField auditSlotF = textFields.get("audit_slot"); + if (auditSlotF == null) { + auditSlotF = makeField(slotW); + auditSlotF.setNumericOnly(true); + auditSlotF.setPlaceholder(Component.literal("Slot")); + textFields.put("audit_slot", auditSlotF); + } + + String pendingText = stringListEditPendingText.remove("audit_items_selected"); + if (pendingText != null) { + if (search != null) search.setText(parseHandlerEntryName(pendingText)); + ItemTarget parsed = ItemTarget.fromLegacyEntry(pendingText); + auditSlotF.setText(parsed.hasSlot() ? String.valueOf(parsed.slot) : ""); + } + + if (search != null) { + search.setX(x); search.setY(cy + 1); search.setWidth(nameW); + search.render(ctx, mx, my, delta); + } + auditSlotF.setX(slotX); auditSlotF.setY(cy + 1); auditSlotF.setWidth(slotW); + auditSlotF.render(ctx, mx, my, delta); + + if (auditEditing && search != null) { + String nameText = search.getText().strip(); + String slotText = auditSlotF.getText().strip(); + String entry = buildEntryFromNameAndSlot(nameText, slotText); + if (!entry.isEmpty()) { + String normalized = autismclient.util.macro.StoreItemAction.normalizeTargetEntry(entry); + if (normalized != null && !normalized.isBlank() && !normalized.equals(selected.get(auditEditIdx))) { + selected.set(auditEditIdx, normalized); + editorItemLists.put("targetItems", buildStructuredListTargets("targetItems")); + } + } + } + + final AutismChatField fAuditSlotF = auditSlotF; + boolean capturing = captureSession.isItemSlotCapture("targetItems"); + renderFieldCaptureButton(ctx, pickX, cy, pickW, 14, CaptureMode.ITEM_SLOT, capturing, + true, mx, my, () -> toggleItemSlotCapture("targetItems")); + + String addLabel = auditEditing ? "New" : "+Add"; + renderOverlayButton(ctx, addBtnX, cy, addBtnW, 14, addLabel, CompactOverlayButton.Variant.SUCCESS, true, mx, my, () -> { + if (search == null) return; + if (stringListEditIndex.getOrDefault("audit_items_selected", -1) >= 0) { + stringListEditIndex.put("audit_items_selected", -1); + stringListEditPendingText.put("audit_items_selected", ""); + search.setText(""); + fAuditSlotF.setText(""); + return; + } + + String nameText = search.getText().strip(); + String slotText = fAuditSlotF.getText().strip(); + String entry = buildEntryFromNameAndSlot(nameText, slotText); + if (!entry.isEmpty()) { + String normalized = autismclient.util.macro.StoreItemAction.normalizeTargetEntry(entry); + if (normalized != null && !normalized.isBlank() && !selected.contains(normalized)) { + selected.add(normalized); + editorItemLists.put("targetItems", buildStructuredListTargets("targetItems")); + } + search.setText(""); + fAuditSlotF.setText(""); + stringListEditIndex.put("audit_items_selected", -1); + stringListEditPendingText.put("audit_items_selected", ""); + } + }); + cy += 18; + } + + cy = renderFieldByKey(ctx, "openMode", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "openCommand", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "containerPos", x, cy, w, mx, my, delta); + if ("CONTAINER".equals(currentEnumValue("openMode"))) { + cy = renderEditorHint(ctx, x, cy, w, "Capture stores the clicked block position. Nearby also includes likely server-handled GUI blocks."); + renderNearbyContainerList(ctx, x, cy, w, mx, my, "inventory_audit_nearby", "containerPos"); + cy += CONTAINER_LIST_VISIBLE_ROWS * CATALOG_ITEM_H + 17; + } + cy = renderFieldByKey(ctx, "dupeVector", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "iterations", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "maxTransferAttempts", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "transferRetryDelayMs", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "spamCount", x, cy, w, mx, my, delta); + renderFieldByKey(ctx, "spamDelayMs", x, cy, w, mx, my, delta); + } + + private void renderPayPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + int cy = bodyTop + PAD; + + cy = renderFieldByKey(ctx, "commandTemplate", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "amountInput", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "divideEnabled", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "delayEnabled", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "delayMs", x, cy, w, mx, my, delta); + + List selected = stringLists.getOrDefault("players", Collections.emptyList()); + cy = renderSimpleSelectedList(ctx, x, cy, w, mx, my, "pay_players_selected", "Players", selected, + value -> removeStringIgnoreCase(selected, value), value -> value, ignored -> null, selected::clear, + "(scan the server or add one manually)"); + + AutismChatField search = addFields.get("players"); + int scanW = 34; + int allW = 28; + int searchW = Math.max(1, w - scanW - allW - 4); + if (search != null) { + search.setX(x); + search.setY(cy + 1); + search.setWidth(searchW); + search.render(ctx, mx, my, delta); + } + int scanX = x + searchW + 2; + int allX = scanX + scanW + 2; + renderActionButton(ctx, scanX, cy, scanW, 14, "Scan", mx, my, this::refreshPayScannedPlayers); + renderActionButton(ctx, allX, cy, allW, 14, "All", mx, my, () -> addFilteredPayPlayers( + selected, search != null ? search.getText() : "" + )); + cy += 18; + + String query = search != null ? search.getText() : ""; + if (!payPlayerScanPerformed) { + renderRegistryPlaceholder(ctx, x, cy, w, "pay_players_scan", 1, "Press Scan to load the current server players."); + cy += CATALOG_ITEM_H + 4; + } else { + cy = renderPayGroupedList(ctx, x, cy, w, mx, my, selected, query) + 4; + } + + AutismChatField amountField = textFields.get("amountInput"); + long amount = autismclient.util.macro.PayAction.parseAmount(amountField != null ? amountField.getText() : ""); + boolean divide = toggleStates.getOrDefault("divideEnabled", false); + int count = selected.size(); + String summary; + if (count == 0) { + summary = "No players selected."; + } else if (divide) { + long[] dist = autismclient.util.macro.PayAction.distribute(amount, count); + String per = dist[0] == dist[count - 1] + ? autismclient.util.macro.PayAction.formatAmount(dist[0]) + : autismclient.util.macro.PayAction.formatAmount(dist[count - 1]) + "-" + autismclient.util.macro.PayAction.formatAmount(dist[0]); + summary = "Splits " + autismclient.util.macro.PayAction.formatAmount(amount) + " among " + count + " (" + per + " each)."; + } else { + summary = "Pays " + count + " x " + autismclient.util.macro.PayAction.formatAmount(amount) + + " (" + autismclient.util.macro.PayAction.formatAmount(amount * (long) count) + " total)."; + } + cy = renderEditorHint(ctx, x, cy, w, summary); + + String hint = payPlayerScanPerformed + ? "Click a name to add it. Click a rank header to add/remove everyone in that rank; All adds all." + : "Scan to list players by rank. Type a name then Enter to add it manually."; + renderEditorHint(ctx, x, cy, w, hint); + } + + private record PayRow(boolean header, String prefix, String name, List members) { + static PayRow header(String prefix, List members) { return new PayRow(true, prefix, null, members); } + static PayRow player(String prefix, String name) { return new PayRow(false, prefix, name, null); } + } + + private List buildPayRows(String query) { + Map> byPrefix = new LinkedHashMap<>(); + for (String name : filterEntries(payScannedPlayers, query)) { + byPrefix.computeIfAbsent(payPrefixFor(name), ignored -> new ArrayList<>()).add(name); + } + List order = new ArrayList<>(byPrefix.keySet()); + order.sort((a, b) -> { + boolean ab = a.isBlank(); + boolean bb = b.isBlank(); + if (ab != bb) return ab ? 1 : -1; + return a.compareToIgnoreCase(b); + }); + List rows = new ArrayList<>(); + for (String prefix : order) { + List names = byPrefix.get(prefix); + names.sort(String.CASE_INSENSITIVE_ORDER); + rows.add(PayRow.header(prefix, names)); + for (String name : names) rows.add(PayRow.player(prefix, name)); + } + return rows; + } + + private int renderPayGroupedList(GuiGraphicsExtractor ctx, int x, int y, int w, int mx, int my, List selected, String query) { + int rowH = CATALOG_ITEM_H; + List entries = buildPayRows(query); + if (entries.isEmpty()) { + CompactSurfaces.row(ctx, x, y, w, 12, false, false); + CompactListRenderer.drawEmptyState(ctx, textRenderer, "No players found", x, y, w); + return y + rowH; + } + + int clipTop = bodyInputClip != null ? bodyInputClip.y() : Integer.MIN_VALUE; + int clipBottom = bodyInputClip != null ? bodyInputClip.bottom() : Integer.MAX_VALUE; + Identifier font = theme.fontFor(UiTone.BODY); + int iy = y; + for (PayRow row : entries) { + if (iy + rowH > clipTop && iy < clipBottom) { + if (row.header()) { + List members = row.members(); + int selCount = (int) members.stream().filter(m -> containsIgnoreCase(selected, m)).count(); + boolean allSel = selCount == members.size() && selCount > 0; + UiText.fill(ctx, x, iy, x + w, iy + rowH - 1, 0x44000000); + UiText.fill(ctx, x, iy, x + 2, iy + rowH - 1, allSel ? 0xFF4E8E5A : 0xFF8E2E39); + int headerColor = allSel ? 0xFF9CE0A8 : 0xFFE7B0B8; + int baseY = iy + Math.max(1, (rowH - 8) / 2); + String marker = allSel ? "✓ " : "+ "; + String counter = " (" + selCount + "/" + members.size() + ")"; + int markerW = textRenderer.width(marker); + int counterW = textRenderer.width(counter); + int rankMaxW = Math.max(8, w - 12 - markerW - counterW); + int cx = x + 6; + UiText.draw(ctx, textRenderer, marker, font, headerColor, cx, baseY, false); + cx += markerW; + + Component styled = row.prefix().isBlank() ? null : payPrefixComponents.get(row.prefix()); + if (styled != null && textRenderer.width(styled) <= rankMaxW) { + ctx.text(textRenderer, styled, cx, baseY, 0xFFFFFFFF, false); + cx += textRenderer.width(styled); + } else { + String fallback = row.prefix().isBlank() ? "No rank" : row.prefix(); + int fallbackColor = row.prefix().isBlank() ? headerColor : 0xFFFFFFFF; + fallback = UiText.trimToWidth(textRenderer, fallback, rankMaxW, font, fallbackColor); + UiText.draw(ctx, textRenderer, fallback, font, fallbackColor, cx, baseY, false); + cx += textRenderer.width(fallback); + } + UiText.draw(ctx, textRenderer, counter, font, headerColor, cx, baseY, false); + final List targetMembers = members; + hitRegions.add(new HitRegion(x, iy, w, rowH, () -> togglePayRankSelection(selected, targetMembers))); + } else { + boolean sel = containsIgnoreCase(selected, row.name()); + boolean hovered = mx >= x && mx < x + w && my >= iy && my < iy + rowH; + String label = UiText.trimToWidth(textRenderer, " " + row.name(), w - 6, font, AutismColors.textSecondary()); + MacroTypedListControl.renderRow(ctx, textRenderer, Component.literal(label), + UiBounds.of(x, iy, w, rowH), hovered, sel, + sel ? CompactListRenderer.RowTone.READY : CompactListRenderer.RowTone.NORMAL, false); + final String name = row.name(); + hitRegions.add(new HitRegion(x, iy, w, rowH, () -> togglePayPlayerSelection(selected, name))); + } + } + iy += rowH; + } + return iy; + } + + private void renderToggleModulePanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + List selected = + toggleModuleEntries != null ? toggleModuleEntries : Collections.emptyList(); + + UiText.draw(ctx, textRenderer, "Module Actions (" + selected.size() + ")", font, AutismColors.textSecondary(), x, cy + 2, false); + boolean canClear = !selected.isEmpty(); + int clearX = x + w - 44; + renderOverlayButton(ctx, clearX, cy, 44, 14, "Clear", + CompactOverlayButton.Variant.DANGER, canClear, mx, my, () -> { + selected.clear(); + DirectScrollViewport vp = selectedScrollViewports.get("toggle_module_selected"); + if (vp != null) vp.jumpTo(0); + }); + cy += 14; + + int listH = 4 * SEL_ITEM_H; + int itemW = w - SCROLLBAR_W - 1; + + DirectScrollViewport toggleViewport = getOrCreateViewport(selectedScrollViewports, "toggle_module_selected", + x, cy, w, listH, SEL_ITEM_H, SCROLLBAR_W); + toggleViewport.setContentHeight(selected.size() * SEL_ITEM_H); + + toggleViewport.renderScrollbar(ctx, mx, my); + + if (selected.isEmpty()) { + CompactListRenderer.drawEmptyState(ctx, textRenderer, "Pick modules below.", x, cy, itemW); + } else { + toggleViewport.beginRender(ctx, theme.borderSoft(), 0x36000000); + int first = toggleViewport.getFirstVisibleRow(); + for (int i = first; i < selected.size() && i <= toggleViewport.getLastVisibleRow(); i++) { + int iy = toggleViewport.getRowScreenY(i); + if (iy == Integer.MIN_VALUE) continue; + autismclient.util.macro.ToggleModuleAction.ModuleEntry entry = selected.get(i); + int removeW = 13; + int modeW = 52; + int rowW = itemW - removeW - modeW - 4; + boolean hovered = mx >= x && mx < x + rowW && my >= iy + 1 && my < iy + 14; + MacroTypedListControl.renderRow( + ctx, + textRenderer, + Component.literal(entry.moduleName), + UiBounds.of(x, iy + 1, rowW, 13), + hovered, + false, + CompactListRenderer.RowTone.NORMAL, + false + ); + + int modeX = x + rowW + 2; + String modeLabel = formatToggleModeShort(entry.toggleMode); + final int entryIndex = i; + renderOverlayButton(ctx, modeX, iy + 1, modeW, 13, modeLabel, + entry.toggleMode == autismclient.util.macro.ToggleModuleAction.ToggleMode.ENABLE + ? CompactOverlayButton.Variant.SUCCESS + : (entry.toggleMode == autismclient.util.macro.ToggleModuleAction.ToggleMode.DISABLE + ? CompactOverlayButton.Variant.DANGER + : CompactOverlayButton.Variant.GHOST), + true, mx, my, + () -> cycleToggleModuleEntryMode(entryIndex, 1), + () -> cycleToggleModuleEntryMode(entryIndex, -1)); + + int removeX = modeX + modeW + 2; + renderIconDeleteButton(ctx, removeX, iy + 1, removeW, mx, my, () -> { + if (entryIndex >= 0 && entryIndex < selected.size()) { + selected.remove(entryIndex); + DirectScrollViewport vp = selectedScrollViewports.get("toggle_module_selected"); + if (vp != null) vp.scrollBy(-1); + } + }); + } + toggleViewport.endRender(ctx); + } + cy += listH + 4; + + AutismChatField search = addFields.get("_toggle_module_search"); + int refreshW = 52; + int addW = 40; + int searchW = Math.max(1, w - refreshW - addW - 4); + if (search != null) { + search.setX(x); + search.setY(cy + 1); + search.setWidth(searchW); + search.render(ctx, mx, my, delta); + } + int refreshX = x + searchW + 2; + int addX = refreshX + refreshW + 2; + renderActionButton(ctx, refreshX, cy, refreshW, 14, "Refresh", mx, my, this::refreshMeteorModuleNames); + renderActionButton(ctx, addX, cy, addW, 14, "+Add", mx, my, () -> addFirstFilteredModule(search != null ? search.getText() : "")); + cy += 18; + + String query = search != null ? search.getText() : ""; + List filteredAutism = filterEntries("toggle_module_autism_registry", autismModuleNames, query); + List filteredMeteor = filterEntries("toggle_module_meteor_registry", meteorModuleNames, query); + boolean hasExternalModules = !meteorModuleNames.isEmpty(); + if (autismModuleNames.isEmpty() && meteorModuleNames.isEmpty()) { + renderRegistryPlaceholder(ctx, x, cy, w, "toggle_module_registry_empty", 6, "No modules found right now."); + cy += 6 * CATALOG_ITEM_H + 4; + } else { + cy = renderToggleModuleCatalogSection(ctx, x, cy, w, mx, my, + "AUTISM Modules", "toggle_module_autism_registry", + autismModuleNames, filteredAutism, hasExternalModules ? 3 : 6, selected); + if (hasExternalModules) { + cy = renderToggleModuleCatalogSection(ctx, x, cy, w, mx, my, + "Meteor Modules", "toggle_module_meteor_registry", + meteorModuleNames, filteredMeteor, 3, selected); + } + } + + String hint = selected.isEmpty() + ? "Pick modules below, then click the mode chip on each row." + : "Each row runs with its own Toggle / Enable / Disable setting."; + renderEditorHint(ctx, x, cy, w, hint); + } + + private int renderToggleModuleCatalogSection(GuiGraphicsExtractor ctx, int x, int y, int w, int mx, int my, + String title, String listKey, List source, + List filtered, + int visibleRows, + List selected) { + Identifier font = theme.fontFor(UiTone.BODY); + UiText.draw(ctx, textRenderer, title, font, AutismColors.textSecondary(), x, y + 1, false); + y += 12; + if (source == null || source.isEmpty()) { + renderRegistryPlaceholder(ctx, x, y, w, listKey, visibleRows, "No modules found right now."); + } else { + renderSearchRegistryList(ctx, x, y, w, mx, my, listKey, filtered, visibleRows, + this::addToggleModuleEntry, + value -> containsModuleEntry(selected, value), + value -> value); + } + return y + visibleRows * CATALOG_ITEM_H + 4; + } + + private void renderRegistryPlaceholder(GuiGraphicsExtractor ctx, int x, int y, int w, String listKey, int visibleRows, String message) { + int listH = visibleRows * CATALOG_ITEM_H; + int itemW = w - SCROLLBAR_W - 1; + CompactSurfaces.row(ctx, x, y, itemW, 12, false, false); + CompactListRenderer.drawEmptyState(ctx, textRenderer, formatEditorHint(message), x, y, itemW); + } + + private void refreshPayScannedPlayers() { + payScannedPlayers.clear(); + payPlayerPrefixes.clear(); + payPrefixComponents.clear(); + payPlayerScanPerformed = true; + DirectScrollViewport vp = catalogScrollViewports.get("pay_players_scan"); + if (vp != null) vp.jumpTo(0); + + for (autismclient.util.AutismPlayerScanner.ScannedPlayer player : autismclient.util.AutismPlayerScanner.scan(MC)) { + if (player == null || player.name() == null || player.name().isBlank()) continue; + if (containsIgnoreCase(payScannedPlayers, player.name())) continue; + payScannedPlayers.add(player.name()); + if (player.hasPrefix()) { + payPlayerPrefixes.put(player.name().toLowerCase(Locale.ROOT), player.prefix()); + + if (player.prefixComponent() != null) { + payPrefixComponents.putIfAbsent(player.prefix(), player.prefixComponent()); + } + } + } + payScannedPlayers.sort(String::compareToIgnoreCase); + } + + private String payPrefixFor(String name) { + return name == null ? "" : payPlayerPrefixes.getOrDefault(name.toLowerCase(Locale.ROOT), ""); + } + + private void togglePayRankSelection(List selected, List members) { + if (selected == null || members == null || members.isEmpty()) return; + boolean allSelected = members.stream().allMatch(m -> containsIgnoreCase(selected, m)); + if (allSelected) { + for (String m : members) removeStringIgnoreCase(selected, m); + } else { + for (String m : members) { + if (!containsIgnoreCase(selected, m)) selected.add(m); + } + } + } + + private void refreshMeteorModuleNames() { + autismModuleNames.clear(); + meteorModuleNames.clear(); + DirectScrollViewport autismVp = catalogScrollViewports.get("toggle_module_autism_registry"); + if (autismVp != null) autismVp.jumpTo(0); + DirectScrollViewport meteorVp = catalogScrollViewports.get("toggle_module_meteor_registry"); + if (meteorVp != null) meteorVp.jumpTo(0); + DirectScrollViewport emptyVp = catalogScrollViewports.get("toggle_module_registry_empty"); + if (emptyVp != null) emptyVp.jumpTo(0); + for (String moduleName : autismclient.util.AutismCompatManager.getAutismModuleNames()) { + if (moduleName != null && !moduleName.isBlank() && !containsIgnoreCase(autismModuleNames, moduleName)) { + autismModuleNames.add(moduleName); + } + } + for (String moduleName : autismclient.util.AutismCompatManager.getMeteorOnlyModuleNames()) { + if (moduleName != null && !moduleName.isBlank() && !containsIgnoreCase(meteorModuleNames, moduleName)) { + meteorModuleNames.add(moduleName); + } + } + autismModuleNames.sort(String::compareToIgnoreCase); + meteorModuleNames.sort(String::compareToIgnoreCase); + } + + private List filterEntries(List source, String query) { + return filterEntries(null, source, query); + } + + private List filterRegistryValues(String cacheKey, List source, String query, + Function labeler) { + String filter = query == null ? "" : query.trim().toLowerCase(Locale.ROOT); + List target = catalogFilteredValues.computeIfAbsent(cacheKey, ignored -> new ArrayList<>()); + return MacroTypedListControl.refilterValues(source, target, + id -> id != null && matchesListFilter(filter, id, trimMinecraftPrefix(id), labeler.apply(id))); + } + + private List filterEntries(String cacheKey, List source, String query) { + if (source == null || source.isEmpty()) return Collections.emptyList(); + String filter = query == null ? "" : query.trim().toLowerCase(Locale.ROOT); + List target = cacheKey == null + ? new ArrayList<>() + : catalogFilteredValues.computeIfAbsent(cacheKey, ignored -> new ArrayList<>()); + return MacroTypedListControl.refilterValues(source, target, + value -> value != null && (filter.isEmpty() || value.toLowerCase(Locale.ROOT).contains(filter))); + } + + private void addFilteredPayPlayers(List selected, String query) { + if (selected == null) return; + for (String player : filterEntries(payScannedPlayers, query)) { + if (!containsIgnoreCase(selected, player)) selected.add(player); + } + } + + private void togglePayPlayerSelection(List selected, String player) { + if (selected == null || player == null || player.isBlank()) return; + if (containsIgnoreCase(selected, player)) removeStringIgnoreCase(selected, player); + else selected.add(player); + } + + private boolean containsIgnoreCase(List values, String target) { + if (values == null || target == null) return false; + for (String value : values) { + if (value != null && value.equalsIgnoreCase(target)) return true; + } + return false; + } + + private void removeStringIgnoreCase(List values, String target) { + if (values == null || target == null) return; + values.removeIf(value -> value != null && value.equalsIgnoreCase(target)); + } + + private void addFirstFilteredModule(String query) { + List filtered = filterEntries(autismModuleNames, query); + if (filtered.isEmpty()) filtered = filterEntries(meteorModuleNames, query); + if (!filtered.isEmpty()) addToggleModuleEntry(filtered.get(0)); + } + + private void addToggleModuleEntry(String moduleName) { + if (toggleModuleEntries == null || moduleName == null || moduleName.isBlank() || containsModuleEntry(toggleModuleEntries, moduleName)) return; + toggleModuleEntries.add(new autismclient.util.macro.ToggleModuleAction.ModuleEntry(moduleName, autismclient.util.macro.ToggleModuleAction.ToggleMode.TOGGLE)); + } + + private boolean containsModuleEntry(List entries, String moduleName) { + if (entries == null || moduleName == null) return false; + for (autismclient.util.macro.ToggleModuleAction.ModuleEntry entry : entries) { + if (entry != null && entry.moduleName != null && entry.moduleName.equalsIgnoreCase(moduleName)) return true; + } + return false; + } + + private void cycleToggleModuleEntryMode(int index, int direction) { + if (toggleModuleEntries == null || index < 0 || index >= toggleModuleEntries.size()) return; + autismclient.util.macro.ToggleModuleAction.ModuleEntry entry = toggleModuleEntries.get(index); + autismclient.util.macro.ToggleModuleAction.ToggleMode[] modes = autismclient.util.macro.ToggleModuleAction.ToggleMode.values(); + int next = (entry.toggleMode.ordinal() + (direction < 0 ? -1 : 1)) % modes.length; + if (next < 0) next += modes.length; + entry.toggleMode = modes[next]; + } + + private String formatToggleModeShort(autismclient.util.macro.ToggleModuleAction.ToggleMode mode) { + return switch (mode) { + case ENABLE -> "Enable"; + case DISABLE -> "Disable"; + default -> "Toggle"; + }; + } + + private void renderWaitSlotChangePanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + int headerBtnW = 44; + + renderInlineToggle(ctx, font, MacroAction.LISTEN_DURING_PREVIOUS_KEY, + "Listen During Previous", x, cy, w, mx, my); + cy += ROW_H + ROW_GAP; + cy = renderFieldByKey(ctx, "saveAs", x, cy, w, mx, my, delta); + + List entries = + wscEntries != null ? wscEntries : new ArrayList<>(); + if (wscEditIndex >= entries.size()) wscEditIndex = -1; + + UiText.draw(ctx, textRenderer, + "Items / Slots (" + entries.size() + ")", font, + AutismColors.textSecondary(), x, cy + 2, false); + boolean canClear = !entries.isEmpty(); + int clearX = x + w - headerBtnW; + renderOverlayButton(ctx, clearX, cy, headerBtnW, 14, "Clear", + CompactOverlayButton.Variant.DANGER, canClear, mx, my, () -> { + entries.clear(); wscEditIndex = -1; clearWscEditorFields(); + }); + cy += 14; + + int delW = 13; + int rowW = w - SCROLLBAR_W - 1 - delW - 2; + + int selAreaH = SEL_LIST_MAX_VIS * SEL_ITEM_H; + + DirectScrollViewport wscViewport = getOrCreateViewport(selectedScrollViewports, "_wsc_entries", + x, cy, w, selAreaH, SEL_ITEM_H, SCROLLBAR_W); + wscViewport.setContentHeight(entries.size() * SEL_ITEM_H); + + wscViewport.renderScrollbar(ctx, mx, my); + + if (!entries.isEmpty()) { + wscViewport.beginRender(ctx, theme.borderSoft(), 0x36000000); + int firstVis = wscViewport.getFirstVisibleRow(); + for (int i = firstVis; i < entries.size() && i <= wscViewport.getLastVisibleRow(); i++) { + int iy = wscViewport.getRowScreenY(i); + if (iy == Integer.MIN_VALUE) continue; + boolean selected = (i == wscEditIndex); + WaitForSlotChangeAction.WaitEntry e = entries.get(i); + + Component targetDisp = formatItemTargetText(e.resolvedTarget(), "(any slot)"); + String modeSummary = " \u2022 " + e.modeLabel(); + Component rowLabel = Component.empty().append(targetDisp).append( + Component.literal(modeSummary).withStyle(s -> s.withColor(0xFF888888))); + boolean rowHovered = mx >= x && mx < x + rowW && my >= iy && my < iy + 13; + MacroTypedListControl.renderRow( + ctx, + textRenderer, + rowLabel, + UiBounds.of(x, iy, rowW, 13), + rowHovered, + selected, + CompactListRenderer.RowTone.NORMAL, + true + ); + + final int fi = i; + if (iy + 13 > cy && iy < cy + selAreaH) { + hitRegions.add(new HitRegion(x, Math.max(cy, iy), rowW, Math.min(iy + 13, cy + selAreaH) - Math.max(cy, iy), () -> toggleWscEditSelection(fi))); + } + + int delX = x + rowW + 2; + renderIconDeleteButton(ctx, delX, iy, delW, mx, my, () -> { + if (wscEditIndex == fi) { wscEditIndex = -1; clearWscEditorFields(); } + else if (wscEditIndex > fi) wscEditIndex--; + entries.remove(fi); + DirectScrollViewport vp = selectedScrollViewports.get("_wsc_entries"); + if (vp != null) vp.scrollBy(-1); + }); + } + wscViewport.endRender(ctx); + } else { + CompactListRenderer.drawEmptyState(ctx, textRenderer, "No entries yet. Add an item or slot below.", x, cy, w - SCROLLBAR_W - 1); + } + cy += selAreaH; + + CompactSurfaces.divider(ctx, x, cy + 2, w, AutismColors.subPanelBorder()); + cy += 6; + + AutismChatField wscAddF = addFields.get("_wsc_add"); + AutismChatField wscSlotF = textFields.get("wsc_slot"); + if (wscAddF != null && wscSlotF != null) { + int pickW = 32; + int slotW = 44; + int pickX = x + w - pickW; + int slotX = pickX - 2 - slotW; + wscAddF.setX(x); wscAddF.setY(cy + 1); wscAddF.setWidth(slotX - x - 2); + wscSlotF.setX(slotX); wscSlotF.setY(cy + 1); wscSlotF.setWidth(slotW); + wscAddF.render(ctx, mx, my, delta); + wscSlotF.render(ctx, mx, my, delta); + + boolean capturing = captureSession.isItemSlotCapture("_wsc_entries"); + renderFieldCaptureButton(ctx, pickX, cy, pickW, 14, CaptureMode.ITEM_SLOT, capturing, + true, mx, my, () -> toggleItemSlotCapture("_wsc_entries")); + } + cy += 16; + + { + boolean editing = wscEditIndex >= 0 && wscEditIndex < entries.size(); + WaitForSlotChangeAction.WaitMode curMode = + editing ? entries.get(wscEditIndex).waitMode : wscAddMode; + int curCount = editing ? entries.get(wscEditIndex).targetCount : wscAddCount; + + int addBtnW = 34; + int cntW = 36; + int modBtnW = w - addBtnW - 2 - cntW - 2; + + String modeFull = curMode.name().replace("_", " "); + renderOverlayButton(ctx, x, cy, modBtnW, 14, modeFull, + CompactOverlayButton.Variant.GHOST, true, mx, my, () -> { + WaitForSlotChangeAction.WaitMode[] modes = WaitForSlotChangeAction.WaitMode.values(); + if (wscEditIndex >= 0 && wscEditIndex < entries.size()) { + entries.get(wscEditIndex).cycleMode(); + } else { + wscAddMode = modes[(wscAddMode.ordinal() + 1) % modes.length]; + } + }, () -> { + WaitForSlotChangeAction.WaitMode[] modes = WaitForSlotChangeAction.WaitMode.values(); + if (wscEditIndex >= 0 && wscEditIndex < entries.size()) { + entries.get(wscEditIndex).cycleModeBackwards(); + } else { + wscAddMode = modes[(wscAddMode.ordinal() - 1 + modes.length) % modes.length]; + } + }); + + int cntX = x + modBtnW + 2; + AutismChatField countF = textFields.get("wsc_count"); + boolean countRelevant = curMode == WaitForSlotChangeAction.WaitMode.COUNT_AT_LEAST + || curMode == WaitForSlotChangeAction.WaitMode.COUNT_BELOW; + if (countF != null) { + if (countRelevant) { + countF.setX(cntX); countF.setY(cy + 1); countF.setWidth(cntW); + if (!countF.isFocused() && !suppressWscLiveUpdate) { + suppressWscLiveUpdate = true; + countF.setText(String.valueOf(curCount)); + suppressWscLiveUpdate = false; + } + countF.render(ctx, mx, my, delta); + } else { + CompactSurfaces.valueField(ctx, cntX, cy, cntW, 14); + fillBorder(ctx, cntX, cy, cntW, 14, 0xFF2A1A1A); + UiText.draw(ctx, textRenderer, "-", font, AutismColors.textDim(), + cntX + (cntW - uiWidth(font, "-")) / 2, cy + 3, false); + } + } + + int plusX = cntX + cntW + 2; + renderOverlayButton(ctx, plusX, cy, addBtnW, 14, "+Add", + CompactOverlayButton.Variant.SUCCESS, true, mx, my, () -> { + if (wscAddF != null && wscSlotF != null) { + applyWscAddEntry(wscAddF, wscSlotF); + wscEditIndex = -1; + clearWscEditorFields(); + } + }); + } + cy += 16; + + renderEditorHint(ctx, x, cy, w, + wscEditIndex >= 0 ? "Editing selected row. Use Mode below to cycle. ALL entries must match." + : "Click a row to edit. ALL entries must match before proceeding."); + } + + private void renderUseItemPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + + cy = renderUseItemTargetRow(ctx, x, cy, w, mx, my, delta); + int btnW = (w - 4) / 2; + renderActionButton(ctx, x, cy, btnW, 14, "Use Held", mx, my, this::fillUseItemFromHeld); + renderActionButton(ctx, x + btnW + 4, cy, btnW, 14, "Use Current", mx, my, () -> { + AutismChatField field = textFields.get("itemName"); + if (field != null) field.setText(""); + AutismChatField slotField = textFields.get("slot"); + if (slotField != null) slotField.setText(""); + editorItemFields.remove("itemName"); + }); + cy += 18; + + cy = renderFieldByKey(ctx, "useMode", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "waitForFinish", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "sneak", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "holdTicks", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "useCount", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "waitForGui", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "guiName", x, cy, w, mx, my, delta); + + String itemTarget = currentUseItemTargetLabel(); + String mode = currentEnumValue("useMode"); + String hint = "CUSTOM_HOLD".equals(mode) + ? "Hold-uses " + itemTarget + " for the set ticks." + : "Uses " + itemTarget + " for the set count."; + renderEditorHint(ctx, x, cy, w, hint); + } + + private int renderUseItemTargetRow(GuiGraphicsExtractor ctx, int x, int y, int w, int mx, int my, float delta) { + FieldDef itemFieldDef = getField("itemName"); + AutismChatField itemField = textFields.get("itemName"); + AutismChatField slotField = textFields.get("slot"); + if (itemFieldDef == null || itemField == null || slotField == null) { + int cy = renderFieldByKey(ctx, "itemName", x, y, w, mx, my, delta); + return renderFieldByKey(ctx, "slot", x, cy, w, mx, my, delta); + } + + Identifier font = theme.fontFor(UiTone.BODY); + int labelW = labelWidth(w, itemFieldDef.label(), font, 88); + drawLabel(ctx, itemFieldDef.label(), x, y, labelW, font); + + int controlX = controlX(x, labelW); + int controlW = Math.max(1, controlWidth(w, labelW)); + int pickW = 30; + int slotW = 34; + int gap = 2; + int itemW = Math.max(1, controlW - pickW - slotW - gap * 2); + + itemField.setX(controlX); + itemField.setY(y + 2); + itemField.setWidth(itemW); + itemField.render(ctx, mx, my, delta); + + int slotX = controlX + itemW + gap; + slotField.setX(slotX); + slotField.setY(y + 2); + slotField.setWidth(slotW); + slotField.render(ctx, mx, my, delta); + + int pickX = slotX + slotW + gap; + boolean capturing = captureSession.isItemSlotCapture("itemName"); + renderFieldCaptureButton( + ctx, + pickX, + y + 2, + pickW, + 14, + CaptureMode.ITEM_SLOT, + capturing, + true, + mx, + my, + () -> toggleItemSlotCapture("itemName") + ); + + return y + ROW_H + ROW_GAP; + } + + private void renderRotatePanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + int cy = bodyTop + PAD; + + cy = renderFieldByKey(ctx, "yaw", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "pitch", x, cy, w, mx, my, delta); + renderActionButton(ctx, x, cy, w, 14, "Capture View", mx, my, this::fillRotateFromCurrentView); + cy += 18; + cy = renderFieldByKey(ctx, "smooth", x, cy, w, mx, my, delta); + if (toggleStates.getOrDefault("smooth", false)) { + cy = renderRotateSmoothnessSlider(ctx, x, cy, w, mx, my); + } else { + rotateSmoothnessSliderDragging = false; + clearRotateSmoothnessSliderBounds(); + } + cy = renderFieldByKey(ctx, "waitForCompletion", x, cy, w, mx, my, delta); + renderEditorHint(ctx, x, cy, w, + toggleStates.getOrDefault("smooth", false) + ? "Capture View fills in your current yaw and pitch. Smoothness 1 is faster, 10 is slower." + : "Capture View fills in your current yaw and pitch."); + } + + private void renderLookAtPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + int cy = bodyTop + PAD; + + cy = renderFieldByKey(ctx, "targetMode", x, cy, w, mx, my, delta); + String mode = currentEnumValue("targetMode"); + if ("BLOCK".equals(mode)) { + cy = renderFieldByKey(ctx, "searchRadius", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "blockIds", x, cy, w, mx, my, delta); + } else if ("ENTITY".equals(mode)) { + cy = renderFieldByKey(ctx, "searchRadius", x, cy, w, mx, my, delta); + cy = renderLookAtEntitySelector(ctx, x, cy, w, mx, my, delta); + } else { + cy = renderFieldByKey(ctx, "blockPos", x, cy, w, mx, my, delta); + } + + cy = renderFieldByKey(ctx, "smooth", x, cy, w, mx, my, delta); + if (toggleStates.getOrDefault("smooth", false)) { + cy = renderRotateSmoothnessSlider(ctx, x, cy, w, mx, my); + } else { + rotateSmoothnessSliderDragging = false; + clearRotateSmoothnessSliderBounds(); + } + cy = renderFieldByKey(ctx, "waitForCompletion", x, cy, w, mx, my, delta); + + String hint = switch (mode) { + case "BLOCK" -> "Search blocks and it faces the nearest matching block in range."; + case "ENTITY" -> "Pick entity types or specific captures and it faces the nearest match in range."; + default -> "Pick a specific block position to face."; + }; + if (toggleStates.getOrDefault("smooth", false)) hint += " Smoothness 1 is faster, 10 is slower."; + renderEditorHint(ctx, x, cy, w, hint); + } + + private int renderLookAtEntitySelector(GuiGraphicsExtractor ctx, int x, int y, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = y; + + List selected = stringLists.getOrDefault("entityIds", Collections.emptyList()); + cy = renderSimpleSelectedList(ctx, x, cy, w, mx, my, "look_at_entity_selected", "Entities", selected, selected::remove, + this::formatEntityEntry, "(add entity types or specific captures)"); + + AutismChatField search = addFields.get("entityIds"); + int searchW = w - 66; + if (search != null) { + search.setX(x); + search.setY(cy + 1); + search.setWidth(searchW); + search.render(ctx, mx, my, delta); + } + int modeX = x + searchW + 2; + String modeLabel = entitySpecificCaptureMode ? "[Spec]" : "[Type]"; + renderActionButton(ctx, modeX, cy, 30, 14, modeLabel, mx, my, () -> entitySpecificCaptureMode = !entitySpecificCaptureMode); + renderActionButton(ctx, modeX + 34, cy, 32, 14, "CAP", mx, my, this::startLookAtEntityCapture); + cy += 18; + + String filter = search != null ? search.getText().trim().toLowerCase() : ""; + List filtered = filterRegistryValues("look_at_entity_search", getAllEntityIds(), filter, AutismRegistryLabels::entity); + renderSearchRegistryList( + ctx, + x, + cy, + w, + mx, + my, + "look_at_entity_search", + filtered, + 4, + value -> { + if (selected.contains(value)) selected.remove(value); + else selected.add(value); + }, + selected::contains, + AutismRegistryLabels::entity + ); + cy += 4 + 4 * CATALOG_ITEM_H + 10; + + UiText.draw(ctx, textRenderer, "Nearby Entities", font, AutismColors.textSecondary(), x, cy + 2, false); + cy += 13; + List nearbyEntries = getNearbyEntityEntries(); + renderSearchRegistryList( + ctx, + x, + cy, + w, + mx, + my, + "look_at_entity_nearby", + nearbyEntries, + 3, + value -> { + String stored = entitySpecificCaptureMode ? value : extractEntityTypeFromNearbyEntry(value); + if (stored.isBlank()) return; + if (entitySpecificCaptureMode) { + boolean removed = selected.removeIf(existing -> existing.startsWith(entitySpecificEntryPrefix(stored))); + if (!removed) selected.add(stored); + } else if (selected.contains(stored)) { + selected.remove(stored); + } else { + selected.add(stored); + } + }, + value -> { + String stored = entitySpecificCaptureMode ? value : extractEntityTypeFromNearbyEntry(value); + return entitySpecificCaptureMode + ? selected.stream().anyMatch(existing -> existing.startsWith(entitySpecificEntryPrefix(stored))) + : selected.contains(stored); + }, + this::formatNearbyEntityEntry + ); + return cy + 3 * CATALOG_ITEM_H + 4; + } + + private void renderGoToPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + FieldDef posField = getField("pos"); + if (posField != null) { + cy = renderBlockPosWithoutCapture(ctx, posField, x, cy, w, mx, my, delta); + } + renderActionButton(ctx, x, cy, w, 14, "Capture Here", mx, my, this::fillGoToFromPlayer); + cy += 18; + cy = renderFieldByKey(ctx, "waitForArrival", x, cy, w, mx, my, delta); + renderEditorHint(ctx, x, cy, w, "Wait for Arrival continues only after Baritone finishes."); + } + + private void renderSwapSlotsPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + + UiText.draw(ctx, textRenderer, "From", font, AutismColors.textSecondary(), x, cy + 2, false); + renderActionButton(ctx, x + w - 68, cy, 68, 14, "Flip Ends", mx, my, this::swapSwapSlotEndpoints); + cy += 16; + cy = renderFieldByKey(ctx, "fromUseItemName", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "fromItemName", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "fromSlot", x, cy, w, mx, my, delta); + + CompactSurfaces.divider(ctx, x, cy + 2, w, AutismColors.subPanelBorder()); + cy += 8; + + UiText.draw(ctx, textRenderer, "To", font, AutismColors.textSecondary(), x, cy + 2, false); + cy += 16; + cy = renderFieldByKey(ctx, "toUseItemName", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "toItemName", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "toSlot", x, cy, w, mx, my, delta); + + renderEditorHint(ctx, x, cy, w, buildSwapSlotsSummary()); + } + + private void renderClickPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + + cy = renderFieldByKey(ctx, "clickType", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "clickCount", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "waitForGuiBefore", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "waitForGuiAfter", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "guiName", x, cy, w, mx, my, delta); + + renderEditorHint(ctx, x, cy, w, buildClickSummary()); + } + + private void renderDisconnectPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + + cy = renderFieldByKey(ctx, "mode", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "delayMs", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "lagMethod", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "kickMethod", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "packetCount", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "useNextAction", x, cy, w, mx, my, delta); + + cy = renderFieldByKey(ctx, "trigger", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "tolerance", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "bufferMs", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "timeoutSec", x, cy, w, mx, my, delta); + + String mode = currentEnumValue("mode"); + String hint = switch (mode) { + case "DISCONNECT" -> "Simple disconnect. Delay only controls how long to wait before closing the connection."; + case "KICK" -> "Sends lag packets, then the selected kick packet. Packet Count controls how hard it pushes."; + case "AUTO_DISCONNECT" -> "Auto-disconnects at the perfect dupe timing."; + case "KICK_DUPE" -> toggleStates.getOrDefault("useNextAction", false) + ? "Kick Dupe will run the next eligible macro actions inside the lag sandwich, then kick." + : "Kick Dupe will try to use a bundle, then kick."; + default -> "Unknown mode"; + }; + renderEditorHint(ctx, x, cy, w, hint, "DISCONNECT".equals(mode) ? AutismColors.textDim() : 0xFFFFB36B); + } + + private void renderWaitGuiPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + + cy = renderFieldByKey(ctx, "waitMode", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "guiType", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "matchMode", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "guiTitle", x, cy, w, mx, my, delta); + cy = renderCapturePatternBuilder(ctx, textFields.get("guiTitle"), x, cy, w, mx, my); + cy = renderFieldByKey(ctx, "saveAs", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "timeoutMs", x, cy, w, mx, my, delta); + + String mode = currentEnumValue("waitMode"); + String guiType = currentEnumValue("guiType"); + String hint = "CLOSE".equals(mode) + ? "Waits until the matching " + guiType + " GUI closes." + : "Waits until a matching " + guiType + " GUI opens."; + renderEditorHint(ctx, x, cy, w, hint); + } + + private void renderSelectSlotPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + + cy = renderFieldByKey(ctx, "itemName", x, cy, w, mx, my, delta); + + int btnW = (w - 4) / 2; + renderActionButton(ctx, x, cy, btnW, 14, "Held", mx, my, this::fillSelectSlotFromHeld); + renderActionButton(ctx, x + btnW + 4, cy, btnW, 14, "Use Slot Only", mx, my, this::clearSelectSlotItemName); + cy += 18; + + UiText.draw(ctx, textRenderer, "Fallback Hotbar Slot", font, AutismColors.textSecondary(), x, cy + 2, false); + cy += 12; + + cy = renderSelectSlotHotbarPicker(ctx, x, cy, w, mx, my); + cy = renderFieldByKey(ctx, "strategy", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "outputVariable", x, cy, w, mx, my, delta); + + renderEditorHint(ctx, x, cy, w, buildSelectSlotSummary()); + } + + private int renderSelectSlotHotbarPicker(GuiGraphicsExtractor ctx, int x, int y, int w, int mx, int my) { + Identifier font = theme.fontFor(UiTone.BODY); + int selectedSlot = getSelectSlotHotbarIndex(); + int slotGap = 2; + int cellW = Math.max(16, Math.min(24, (w - slotGap * 8) / 9)); + int totalW = cellW * 9 + slotGap * 8; + int startX = x + Math.max(0, (w - totalW) / 2); + + for (int slot = 0; slot < 9; slot++) { + int sx = startX + slot * (cellW + slotGap); + boolean selected = selectedSlot == slot; + String label = String.valueOf(slot + 1); + final int clickedSlot = slot; + renderOverlayButton(ctx, sx, y, cellW, 14, label, + selected ? CompactOverlayButton.Variant.PRIMARY : CompactOverlayButton.Variant.GHOST, + true, mx, my, () -> setSelectSlotHotbarIndex(clickedSlot)); + } + + return y + 18; + } + + private void renderWaitCooldownPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + + cy = renderFieldByKey(ctx, "itemName", x, cy, w, mx, my, delta); + + int halfW = (w - 4) / 2; + renderActionButton(ctx, x, cy, halfW, 14, currentWaitCooldownHandLabel(), mx, my, this::toggleWaitCooldownHand); + renderActionButton(ctx, x + halfW + 4, cy, halfW, 14, "Capture Held", mx, my, this::fillWaitCooldownFromHeld); + cy += 18; + + renderActionButton(ctx, x, cy, Math.min(130, w), 14, "Use InteractionHand Item", mx, my, this::clearWaitCooldownItemName); + cy += 18; + + renderEditorHint(ctx, x, cy, w, buildWaitCooldownSummary()); + } + + private void renderWaitInventoryPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + int cy = bodyTop + PAD; + cy = renderFieldByKey(ctx, MacroAction.LISTEN_DURING_PREVIOUS_KEY, x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "condition", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "itemName", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "count", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "slot", x, cy, w, mx, my, delta); + if (isFieldVisible(getField("slot"))) { + int third = (w - 4) / 3; + renderActionButton(ctx, x, cy, third, 14, "Selected", mx, my, this::fillWaitInventorySelectedSlot); + boolean capturing = captureSession.isItemSlotCapture("wait_inventory_slot"); + renderFieldCaptureButton(ctx, x + third + 2, cy, third, 14, CaptureMode.ITEM_SLOT, capturing, + true, mx, my, "Pick Slot", "Done", this::toggleWaitInventorySlotCapture); + renderActionButton(ctx, x + (third + 2) * 2, cy, w - (third + 2) * 2, 14, "Slot 0", mx, my, () -> setWaitInventorySlot(0)); + cy += 18; + } + cy = renderFieldByKey(ctx, "timeoutMs", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "saveAs", x, cy, w, mx, my, delta); + renderEditorHint(ctx, x, cy, w, "Use Pick Slot when a GUI is open, or Selected for hotbar waits."); + } + + private void renderCaptureValuePanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int w, int mx, int my, float delta) { + int cy = bodyTop + PAD; + cy = renderFieldByKey(ctx, "source", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "autofillCommand", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "autofillTimeoutMs", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "autofillCacheList", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "itemFilter", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "slot", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "itemText", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "saveAs", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "listSelection", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "listPickPosition", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "listFilter", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "listFilterText", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "listExcludeText", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "listStripPrefix", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "excludeSelf", x, cy, w, mx, my, delta); + if ("RECENT_CHAT".equals(currentEnumValue("source"))) { + cy = renderCaptureRecentChatPicker(ctx, x, cy, w, mx, my); + } else if ("SCOREBOARD".equals(currentEnumValue("source"))) { + cy = renderCaptureScoreboardPicker(ctx, x, cy, w, mx, my); + } else if ("TABLIST".equals(currentEnumValue("source"))) { + cy = renderCaptureTablistMatches(ctx, x, cy, w, mx, my); + } + cy = renderFieldByKey(ctx, "exampleText", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "selectedText", x, cy, w, mx, my, delta); + + autismclient.util.macro.CaptureValueAction draft = captureValueDraft(); + String primaryName = captureValuePrimaryName(draft); + String token = primaryName.isBlank() ? "" : "{" + primaryName + "}"; + boolean exampleCapture = draft.source == autismclient.util.macro.CaptureValueAction.Source.RECENT_CHAT + || draft.source == autismclient.util.macro.CaptureValueAction.Source.GUI_TITLE + || draft.source == autismclient.util.macro.CaptureValueAction.Source.SCOREBOARD; + boolean immediatePreview = !draft.waitForTrigger + && (draft.source == autismclient.util.macro.CaptureValueAction.Source.RECENT_CHAT + || draft.source == autismclient.util.macro.CaptureValueAction.Source.GUI_TITLE + || draft.source == autismclient.util.macro.CaptureValueAction.Source.SCOREBOARD); + autismclient.util.macro.CaptureValueAction.Preview preview = immediatePreview + ? draft.preview(MC) + : exampleCapture ? draft.previewExample() : draft.preview(MC); + String previewText = preview.success() ? preview.value(primaryName) : preview.message(); + if (preview.success() && previewText.isBlank()) previewText = preview.sourceText(); + if (exampleCapture && draft.selectedText.isBlank()) { + previewText = "Enter the changing part above"; + } else if (exampleCapture && draft.pattern.isBlank()) { + previewText = "Capture This is not in Example"; + } + + cy = renderCaptureCopyField(ctx, "Use Later", "_capture_token", token, x, cy, w, mx, my, + "Variable copied."); + cy = renderCaptureCopyField(ctx, "Preview Now", "_capture_preview", previewText, x, cy, w, mx, my, + "Preview copied."); + cy = renderFieldByKey(ctx, "normalizeNumbers", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "numberModifier", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "numberModifierAmount", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "waitForTrigger", x, cy, w, mx, my, delta); + String behaviorHint; + if (draft.source == autismclient.util.macro.CaptureValueAction.Source.COMMAND_AUTOFILL) { + behaviorHint = "Asks server when run."; + } else if (draft.source == autismclient.util.macro.CaptureValueAction.Source.TABLIST) { + behaviorHint = draft.waitForTrigger + ? "Waits for matching player." + : "Picks an online player."; + } else { + behaviorHint = draft.waitForTrigger + ? draft.source == autismclient.util.macro.CaptureValueAction.Source.SCOREBOARD + ? "Waits for row change." + : "Waits for next match." + : draft.source == autismclient.util.macro.CaptureValueAction.Source.RECENT_CHAT + || draft.source == autismclient.util.macro.CaptureValueAction.Source.GUI_TITLE + ? "Uses newest saved match." + : "Reads current value now."; + } + renderEditorHint(ctx, x, cy, w, behaviorHint); + } + + private int renderCaptureRecentChatPicker(GuiGraphicsExtractor ctx, int x, int y, int w, int mx, int my) { + List history = + autismclient.util.macro.MacroExecutor.getRecentChatMessages().stream() + .limit(CAPTURE_CHAT_HISTORY_LIMIT) + .toList(); + Identifier font = theme.fontFor(UiTone.BODY); + UiText.draw(ctx, textRenderer, "Recent Chat - click to fill", font, + AutismColors.textSecondary(), x, y + 2, false); + y += 13; + int listH = captureChatHistoryListHeight(history.size()); + renderRecentChatHistoryList(ctx, x, y, w, listH, mx, my, history, + "capture_value_recent", CAPTURE_CHAT_VISIBLE_ROWS, this::applyCaptureValueChatHistoryEntry); + return y + listH + ROW_GAP; + } + + private void applyCaptureValueChatHistoryEntry(autismclient.util.macro.MacroExecutor.RecentChatMessage entry) { + if (entry == null) return; + String text = formatWaitChatHistoryEntry(entry); + String suggested = autismclient.util.macro.CaptureValueAction.suggestDynamicPart(text); + AutismChatField exampleField = textFields.get("exampleText"); + AutismChatField selectedField = textFields.get("selectedText"); + suppressCaptureValueAutoPattern = true; + if (exampleField != null) exampleField.setText(text); + if (selectedField != null) selectedField.setText(suggested); + suppressCaptureValueAutoPattern = false; + refreshCaptureValueAutoPattern(); + } + + private int renderCaptureScoreboardPicker(GuiGraphicsExtractor ctx, int x, int y, int w, int mx, int my) { + List lines = + autismclient.util.macro.CaptureValueAction.scoreboardLines(MC); + Identifier font = theme.fontFor(UiTone.BODY); + String title = lines.isEmpty() || lines.get(0).objectiveTitle().isBlank() + ? "Scoreboard - select a row" + : "Scoreboard - " + lines.get(0).objectiveTitle(); + UiText.draw(ctx, textRenderer, + UiText.trimToWidth(textRenderer, title, w, font, -1), + font, AutismColors.textSecondary(), x, y + 2, false); + y += 13; + int listH = lines.isEmpty() ? 24 + : Math.min(CAPTURE_SCOREBOARD_VISIBLE_ROWS, lines.size()) * CAPTURE_SCOREBOARD_ROW_H; + int itemW = Math.max(1, w - SCROLLBAR_W - 1); + DirectScrollViewport viewport = getOrCreateViewport(selectedScrollViewports, "capture_value_scoreboard", + x, y, w, listH, CAPTURE_SCOREBOARD_ROW_H, SCROLLBAR_W); + viewport.setContentHeight(lines.size() * CAPTURE_SCOREBOARD_ROW_H); + viewport.renderScrollbar(ctx, mx, my); + if (lines.isEmpty()) { + CompactSurfaces.row(ctx, x, y, itemW, 24, false, false); + UiText.draw(ctx, textRenderer, "No sidebar scoreboard.", font, + AutismColors.textDim(), x + 3, y + 7, false); + return y + 24 + ROW_GAP; + } + + String selectedKey = editorFieldText("scoreboardRow", ""); + viewport.beginRender(ctx, theme.borderSoft(), 0x36000000); + int first = viewport.getFirstVisibleRow(); + for (int i = first; i < lines.size() && i <= viewport.getLastVisibleRow(); i++) { + int rowY = viewport.getRowScreenY(i); + if (rowY == Integer.MIN_VALUE) continue; + var line = lines.get(i); + boolean selected = line.key().equals(selectedKey); + boolean hovered = mx >= x && mx < x + itemW && my >= rowY && my < rowY + CAPTURE_SCOREBOARD_ROW_H; + CompactSurfaces.row(ctx, x, rowY, itemW, CAPTURE_SCOREBOARD_ROW_H, hovered, selected); + CompactSurfaces.indicator(ctx, x, rowY + 2, 3, CAPTURE_SCOREBOARD_ROW_H - 4, + selected ? 0xFF35D873 : 0xFFCC7A22); + String rowLabel = "Row " + (line.row() + 1); + UiText.draw(ctx, textRenderer, rowLabel, font, AutismColors.textDim(), x + 6, rowY + 2, false); + UiText.draw(ctx, textRenderer, + UiText.trimToWidth(textRenderer, line.text(), Math.max(20, itemW - 10), font, -1), + font, AutismColors.textPrimary(), x + 6, rowY + 11, false); + final var selectedLine = line; + hitRegions.add(new HitRegion(x, rowY, itemW, CAPTURE_SCOREBOARD_ROW_H, + () -> applyCaptureValueScoreboardLine(selectedLine))); + } + viewport.endRender(ctx); + return y + listH + ROW_GAP; + } + + private java.util.List captureTablistNamesCache; + private long captureTablistNamesAtMs; + + private java.util.List captureTablistNames() { + long now = System.currentTimeMillis(); + if (captureTablistNamesCache == null || now - captureTablistNamesAtMs > CAPTURE_TABLIST_SCAN_TTL_MS) { + java.util.List players = + autismclient.util.AutismPlayerScanner.scan(MC); + java.util.List names = new java.util.ArrayList<>(players.size()); + for (autismclient.util.AutismPlayerScanner.ScannedPlayer player : players) names.add(player.name()); + captureTablistNamesCache = names; + captureTablistNamesAtMs = now; + } + return captureTablistNamesCache; + } + + private java.util.List captureTablistAllNames(autismclient.util.macro.CaptureValueAction draft) { + java.util.List names = new java.util.ArrayList<>(captureTablistNames()); + if (!draft.excludeSelf && MC.player != null && MC.player.getGameProfile() != null) { + names.add(MC.player.getGameProfile().name()); + names.sort(String.CASE_INSENSITIVE_ORDER); + } + return names; + } + + private int captureTablistMatchCount() { + autismclient.util.macro.CaptureValueAction draft = captureValueDraft(); + return draft.filterCandidates(captureTablistAllNames(draft)).size(); + } + + private int renderCaptureTablistMatches(GuiGraphicsExtractor ctx, int x, int y, int w, int mx, int my) { + autismclient.util.macro.CaptureValueAction draft = captureValueDraft(); + java.util.List names = captureTablistAllNames(draft); + java.util.List pool = draft.filterCandidates(names); + Identifier font = theme.fontFor(UiTone.BODY); + UiText.draw(ctx, textRenderer, "Matches (" + pool.size() + " of " + names.size() + ")", font, + AutismColors.textSecondary(), x, y + 2, false); + y += 13; + int listH = pool.isEmpty() ? 24 + : Math.min(CAPTURE_TABLIST_VISIBLE_ROWS, pool.size()) * CAPTURE_TABLIST_ROW_H; + int itemW = Math.max(1, w - SCROLLBAR_W - 1); + DirectScrollViewport viewport = getOrCreateViewport(selectedScrollViewports, "capture_value_tablist", + x, y, w, listH, CAPTURE_TABLIST_ROW_H, SCROLLBAR_W); + viewport.setContentHeight(pool.size() * CAPTURE_TABLIST_ROW_H); + viewport.renderScrollbar(ctx, mx, my); + if (pool.isEmpty()) { + CompactSurfaces.row(ctx, x, y, itemW, 24, false, false); + UiText.draw(ctx, textRenderer, "No matching players.", font, + AutismColors.textDim(), x + 3, y + 7, false); + return y + 24 + ROW_GAP; + } + viewport.beginRender(ctx, theme.borderSoft(), 0x36000000); + int first = viewport.getFirstVisibleRow(); + for (int i = first; i < pool.size() && i <= viewport.getLastVisibleRow(); i++) { + int rowY = viewport.getRowScreenY(i); + if (rowY == Integer.MIN_VALUE) continue; + String name = pool.get(i); + boolean hovered = mx >= x && mx < x + itemW && my >= rowY && my < rowY + CAPTURE_TABLIST_ROW_H; + CompactSurfaces.row(ctx, x, rowY, itemW, CAPTURE_TABLIST_ROW_H, hovered, false); + UiText.draw(ctx, textRenderer, + UiText.trimToWidth(textRenderer, name, Math.max(20, itemW - 10), font, -1), + font, AutismColors.textPrimary(), x + 6, rowY + 3, false); + hitRegions.add(new HitRegion(x, rowY, itemW, CAPTURE_TABLIST_ROW_H, + () -> copyCaptureEditorValue(name, "Name copied."))); + } + viewport.endRender(ctx); + return y + listH + ROW_GAP; + } + + private void applyCaptureValueScoreboardLine(autismclient.util.macro.CaptureValueAction.ScoreboardLine line) { + if (line == null) return; + AutismChatField rowField = textFields.get("scoreboardRow"); + AutismChatField rowIndexField = textFields.get("scoreboardRowIndex"); + AutismChatField objectiveField = textFields.get("scoreboardObjective"); + AutismChatField exampleField = textFields.get("exampleText"); + AutismChatField selectedField = textFields.get("selectedText"); + String suggested = autismclient.util.macro.CaptureValueAction.suggestDynamicPart(line.text()); + suppressCaptureValueAutoPattern = true; + if (rowField != null) rowField.setText(line.key()); + if (rowIndexField != null) rowIndexField.setText(Integer.toString(line.row())); + if (objectiveField != null) objectiveField.setText(line.objective()); + if (exampleField != null) exampleField.setText(line.text()); + if (selectedField != null) selectedField.setText(suggested); + suppressCaptureValueAutoPattern = false; + refreshCaptureValueAutoPattern(); + } + + private void refreshCaptureValueAutoPattern() { + if (suppressCaptureValueAutoPattern || !(targetAction instanceof autismclient.util.macro.CaptureValueAction)) return; + String example = editorFieldText("exampleText", ""); + String selected = editorFieldText("selectedText", ""); + String variable = editorFieldText("saveAs", "value"); + if (workingTag != null) { + workingTag.putString("exampleText", example); + workingTag.putString("selectedText", selected); + } + if (example.isBlank() || selected.isBlank()) { + AutismChatField patternField = textFields.get("pattern"); + if (patternField != null) patternField.setText(""); + if (workingTag != null) workingTag.putString("pattern", ""); + return; + } + String generated = autismclient.util.macro.CaptureValueAction.buildCapturePattern(example, selected, variable); + AutismChatField patternField = textFields.get("pattern"); + if (patternField != null) patternField.setText(generated); + if (workingTag != null) { + workingTag.putString("pattern", generated); + } + if (!generated.isBlank()) { + enumIndices.put("matchMode", 1); + if (workingTag != null) workingTag.putString("matchMode", "CAPTURE"); + } + } + + private int captureChatHistoryListHeight(int count) { + if (count <= 0) return 24; + return Math.min(CAPTURE_CHAT_VISIBLE_ROWS, Math.min(CAPTURE_CHAT_HISTORY_LIMIT, count)) * WAIT_CHAT_ROW_H; + } + + private void clipHitRegions(int fromIndex, UiBounds clip) { + if (clip == null) return; + for (int i = hitRegions.size() - 1; i >= Math.max(0, fromIndex); i--) { + HitRegion region = hitRegions.get(i); + int left = Math.max(region.x, clip.x()); + int top = Math.max(region.y, clip.y()); + int right = Math.min(region.x + region.w, clip.right()); + int bottom = Math.min(region.y + region.h, clip.bottom()); + if (right <= left || bottom <= top) { + hitRegions.remove(i); + } else if (left != region.x || top != region.y || right != region.x + region.w || bottom != region.y + region.h) { + hitRegions.set(i, new HitRegion(left, top, right - left, bottom - top, region.action)); + } + } + } + + private int renderCaptureCopyField(GuiGraphicsExtractor ctx, String label, String fieldKey, String value, + int x, int y, int w, int mx, int my, String copiedMessage) { + Identifier font = theme.fontFor(UiTone.BODY); + UiText.draw(ctx, textRenderer, label, font, AutismColors.textSecondary(), x, y + 2, false); + y += 12; + int buttonW = Math.min(52, Math.max(40, w / 4)); + AutismChatField field = addFields.get(fieldKey); + if (field != null) { + String safe = value == null ? "" : value; + if (!safe.equals(field.getText())) field.setText(safe); + field.setX(x); + field.setY(y); + field.setWidth(Math.max(1, w - buttonW - 4)); + field.setHeight(14); + field.render(ctx, mx, my, frameDelta); + } + String copied = value == null ? "" : value; + renderActionButton(ctx, x + w - buttonW, y, buttonW, 14, "Copy", mx, my, + () -> copyCaptureEditorValue(copied, copiedMessage)); + return y + 18; + } + + private void copyCaptureEditorValue(String value, String message) { + if (value == null || value.isBlank()) { + AutismNotifications.warning("Nothing to copy."); + return; + } + MC.keyboardHandler.setClipboard(value); + AutismNotifications.copied(message); + } + + private autismclient.util.macro.CaptureValueAction captureValueDraft() { + autismclient.util.macro.CaptureValueAction draft = new autismclient.util.macro.CaptureValueAction(); + try { + draft.source = autismclient.util.macro.CaptureValueAction.Source.valueOf(currentEnumValue("source")); + } catch (IllegalArgumentException | NullPointerException ignored) { } + try { + draft.matchMode = autismclient.util.macro.MacroCapturePattern.Mode.valueOf(currentEnumValue("matchMode")); + } catch (IllegalArgumentException | NullPointerException ignored) { } + try { + draft.itemText = autismclient.util.macro.CaptureValueAction.ItemText.valueOf(currentEnumValue("itemText")); + } catch (IllegalArgumentException | NullPointerException ignored) { } + draft.saveAs = editorFieldText("saveAs", "value"); + draft.pattern = editorFieldText("pattern", ""); + draft.exampleText = editorFieldText("exampleText", ""); + draft.selectedText = editorFieldText("selectedText", ""); + draft.itemFilter = editorFieldText("itemFilter", ""); + draft.scoreboardRow = editorFieldText("scoreboardRow", ""); + draft.scoreboardObjective = editorFieldText("scoreboardObjective", ""); + try { + draft.scoreboardRowIndex = Integer.parseInt(editorFieldText("scoreboardRowIndex", "-1").trim()); + } catch (NumberFormatException ignored) { + draft.scoreboardRowIndex = -1; + } + draft.normalizeNumbers = workingTag != null && workingTag.getBooleanOr("normalizeNumbers", false); + try { + draft.numberModifier = autismclient.util.macro.CaptureValueAction.NumberModifier.valueOf( + currentEnumValue("numberModifier")); + } catch (IllegalArgumentException | NullPointerException ignored) { } + try { + draft.numberModifierAmount = Double.parseDouble(editorFieldText("numberModifierAmount", "1").trim()); + } catch (NumberFormatException ignored) { + draft.numberModifierAmount = Double.NaN; + } + draft.waitForTrigger = toggleStates.getOrDefault("waitForTrigger", + workingTag == null || workingTag.getBooleanOr("waitForTrigger", true)); + try { + draft.slot = Integer.parseInt(editorFieldText("slot", "-1").trim()); + } catch (NumberFormatException ignored) { + draft.slot = -1; + } + draft.autofillCommand = editorFieldText("autofillCommand", ""); + try { + draft.autofillTimeoutMs = Integer.parseInt(editorFieldText("autofillTimeoutMs", "5000").trim()); + } catch (NumberFormatException ignored) { + draft.autofillTimeoutMs = 5000; + } + draft.autofillCacheList = toggleStates.getOrDefault("autofillCacheList", + workingTag != null && workingTag.getBooleanOr("autofillCacheList", false)); + try { + draft.listSelection = autismclient.util.macro.CaptureListSelector.Selection.valueOf(currentEnumValue("listSelection")); + } catch (IllegalArgumentException | NullPointerException ignored) { } + try { + draft.listFilter = autismclient.util.macro.CaptureListSelector.Filter.valueOf(currentEnumValue("listFilter")); + } catch (IllegalArgumentException | NullPointerException ignored) { } + draft.listFilterText = editorFieldText("listFilterText", ""); + draft.listExcludeText = editorFieldText("listExcludeText", ""); + try { + draft.listPickPosition = Integer.parseInt(editorFieldText("listPickPosition", "1").trim()); + } catch (NumberFormatException ignored) { + draft.listPickPosition = 1; + } + draft.listStripPrefix = toggleStates.getOrDefault("listStripPrefix", + workingTag != null && workingTag.getBooleanOr("listStripPrefix", false)); + draft.excludeSelf = toggleStates.getOrDefault("excludeSelf", + workingTag == null || workingTag.getBooleanOr("excludeSelf", true)); + return draft; + } + + private String captureValuePrimaryName(autismclient.util.macro.CaptureValueAction draft) { + if (draft == null) return ""; + + boolean listSource = draft.source == autismclient.util.macro.CaptureValueAction.Source.COMMAND_AUTOFILL + || draft.source == autismclient.util.macro.CaptureValueAction.Source.TABLIST; + if (!listSource) { + java.util.Set captured = autismclient.util.macro.MacroCapturePattern.declaredNames(draft.matchMode, draft.pattern); + if (!captured.isEmpty()) return captured.iterator().next(); + } + return autismclient.util.macro.MacroVariableContext.cleanRootName(draft.saveAs); + } + + private String editorFieldText(String key, String fallback) { + AutismChatField field = textFields.get(key); + return field == null ? fallback : field.getText(); + } + + private void fillWaitInventorySelectedSlot() { + if (MC.player == null) return; + setWaitInventorySlot(MC.player.getInventory().getSelectedSlot()); + } + + private void setWaitInventorySlot(int slot) { + AutismChatField field = textFields.get("slot"); + if (field != null) field.setText(String.valueOf(Math.max(0, slot))); + } + + private void toggleWaitInventorySlotCapture() { + toggleItemSlotCapture("wait_inventory_slot"); + } + + private void renderWaitChatPanel(GuiGraphicsExtractor ctx, int x, int bodyTop, int contentBottom, int w, int mx, int my, float delta) { + Identifier font = theme.fontFor(UiTone.BODY); + int cy = bodyTop + PAD; + + cy = renderFieldByKey(ctx, "pattern", x, cy, w, mx, my, delta); + cy = renderCapturePatternBuilder(ctx, textFields.get("pattern"), x, cy, w, mx, my); + cy = renderFieldByKey(ctx, "matchMode", x, cy, w, mx, my, delta); + String matchMode = currentEnumValue("matchMode"); + if ("MATCH".equals(matchMode)) { + cy = renderWaitChatFuzzySlider(ctx, x, cy, w, mx, my); + } else { + waitChatFuzzySliderDragging = false; + clearWaitChatFuzzySliderBounds(); + } + cy = renderFieldByKey(ctx, "saveAs", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "timeoutMs", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "waitForGuiBefore", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "waitForGuiAfter", x, cy, w, mx, my, delta); + cy = renderFieldByKey(ctx, "waitGuiName", x, cy, w, mx, my, delta); + + String pattern = textFields.containsKey("pattern") ? textFields.get("pattern").getText().trim() : ""; + int fuzzyPercent = getWaitChatFuzzyPercent(); + String hint = pattern.isEmpty() + ? "Blank pattern = any chat line." + : ("REGEX".equals(matchMode) ? "Named groups save values." + : "CAPTURE".equals(matchMode) ? "Use {name} to capture." + : "Fuzzy match: " + fuzzyPercent + "%."); + cy = renderEditorHint(ctx, x, cy, w, hint); + + AutismChatField searchField = addFields.get("_wait_chat_search"); + if (searchField != null) { + searchField.setX(x); + searchField.setY(cy); + searchField.setWidth(w); + searchField.render(ctx, mx, my, delta); + cy += 18; + } + + List history = filterWaitChatHistory(); + UiText.draw(ctx, textRenderer, "Recent Messages (" + history.size() + ")", + font, AutismColors.textSecondary(), x, cy + 2, false); + UiText.draw(ctx, textRenderer, + UiText.trimToWidth(textRenderer, formatEditorHint("Click a row to use that message."), Math.max(20, w - 122), font, -1), + font, AutismColors.textDim(), x + 118, cy + 2, false); + cy += 13; + int availableListHeight = Math.max(24, contentBottom - cy - PAD); + renderWaitChatHistoryList(ctx, x, cy, w, availableListHeight, mx, my, history); + } + + private int renderCapturePatternBuilder(GuiGraphicsExtractor ctx, AutismChatField patternField, + int x, int y, int w, int mx, int my) { + AutismChatField nameField = addFields.get("_capture_name"); + if (nameField == null || patternField == null) return y; + int buttonW = 48; + nameField.setX(x); + nameField.setY(y + 1); + nameField.setWidth(Math.max(1, w - buttonW - 3)); + nameField.setHeight(14); + nameField.render(ctx, mx, my, 0.0f); + renderActionButton(ctx, x + w - buttonW, y + 1, buttonW, 14, "Capture", mx, my, () -> { + String name = autismclient.util.macro.MacroVariableContext.cleanRootName(nameField.getText()); + if (name.isBlank()) return; + patternField.insertText("{" + name + "}"); + enumIndices.put("matchMode", 1); + workingTag.putString("matchMode", "CAPTURE"); + workingTag.putString("patternJson", ""); + }); + return y + 18; + } + + private int renderWaitChatFuzzySlider(GuiGraphicsExtractor ctx, int x, int y, int w, int mx, int my) { + Identifier font = theme.fontFor(UiTone.BODY); + int percent = getWaitChatFuzzyPercent(); + UiText.draw(ctx, textRenderer, "Match Strength", font, AutismColors.textSecondary(), x, y + 2, false); + String label = percent + "%"; + UiText.draw(ctx, textRenderer, label, font, AutismColors.textDim(), + x + w - uiWidth(font, label), y + 2, false); + y += 13; + + int sliderW = w; + int sliderH = 14; + int trackH = 4; + int trackY = y + (sliderH - trackH) / 2; + waitChatFuzzySliderX = x; + waitChatFuzzySliderY = y; + waitChatFuzzySliderW = sliderW; + waitChatFuzzySliderH = sliderH; + + UiRenderer.frame(ctx, UiBounds.of(x, y, sliderW, sliderH), 0xFF0D0D18, AutismColors.subPanelBorder()); + UiRenderer.rect(ctx, UiBounds.of(x + 1, trackY, sliderW - 2, trackH), 0xFF150C0C); + + int[] steps = {40, 50, 60, 70, 80, 90, 100}; + int knobIndex = Math.max(0, Math.min(6, (percent - 40) / 10)); + int knobCenterX = x + Math.round((sliderW - 1) * (knobIndex / 6.0f)); + UiRenderer.rect(ctx, UiBounds.of(x + 1, trackY, knobCenterX - x - 1, trackH), 0xFF345C86); + + for (int i = 0; i < steps.length; i++) { + int step = steps[i]; + int cx = x + Math.round((sliderW - 1) * (i / 6.0f)); + int tickColor = step <= percent ? 0xFF9DCEFF : 0xFF5A4040; + UiRenderer.rect(ctx, UiBounds.of(cx, y + 2, 1, sliderH - 4), tickColor); + } + + int knobW = 16; + int knobX = Math.max(x, Math.min(x + sliderW - knobW, knobCenterX - knobW / 2)); + boolean hovered = isOverWaitChatFuzzySlider(mx, my); + int knobFill = waitChatFuzzySliderDragging ? 0xFF274A6D : (hovered ? 0xFF2A4462 : 0xFF223B56); + int knobBorder = waitChatFuzzySliderDragging ? 0xFFA5D5FF : 0xFF88BBFF; + UiRenderer.frame(ctx, UiBounds.of(knobX, y, knobW, sliderH), knobFill, knobBorder); + return y + sliderH + ROW_GAP; + } + + private int getWaitChatFuzzyPercent() { + AutismChatField field = textFields.get("fuzzyPercent"); + if (field == null) return 100; + try { + return autismclient.util.macro.WaitForChatAction.clampFuzzyPercent(Integer.parseInt(field.getText().trim())); + } catch (NumberFormatException ignored) { + return 100; + } + } + + private void setWaitChatFuzzyPercent(int percent) { + AutismChatField field = textFields.get("fuzzyPercent"); + if (field != null) field.setText(String.valueOf(autismclient.util.macro.WaitForChatAction.clampFuzzyPercent(percent))); + } + + private void clearWaitChatFuzzySliderBounds() { + waitChatFuzzySliderX = -1; + waitChatFuzzySliderY = -1; + waitChatFuzzySliderW = 0; + waitChatFuzzySliderH = 0; + } + + private boolean isOverWaitChatFuzzySlider(int mx, int my) { + return waitChatFuzzySliderW > 0 + && waitChatFuzzySliderH > 0 + && mx >= waitChatFuzzySliderX + && mx < waitChatFuzzySliderX + waitChatFuzzySliderW + && my >= waitChatFuzzySliderY + && my < waitChatFuzzySliderY + waitChatFuzzySliderH; + } + + private void updateWaitChatFuzzyPercentFromMouse(int mouseX) { + if (waitChatFuzzySliderW <= 1) return; + float normalized = (mouseX - waitChatFuzzySliderX) / (float) (waitChatFuzzySliderW - 1); + normalized = Math.max(0.0f, Math.min(1.0f, normalized)); + int stepIndex = Math.round(normalized * 6.0f); + setWaitChatFuzzyPercent(40 + stepIndex * 10); + } + + private int renderRotateSmoothnessSlider(GuiGraphicsExtractor ctx, int x, int y, int w, int mx, int my) { + Identifier font = theme.fontFor(UiTone.BODY); + int smoothness = getRotateSmoothness(); + UiText.draw(ctx, textRenderer, "Smoothness", font, AutismColors.textSecondary(), x, y + 2, false); + String label = smoothness + " / 10"; + UiText.draw(ctx, textRenderer, label, font, AutismColors.textDim(), + x + w - uiWidth(font, label), y + 2, false); + y += 13; + + int sliderW = w; + int sliderH = 14; + int trackH = 4; + int trackY = y + (sliderH - trackH) / 2; + rotateSmoothnessSliderX = x; + rotateSmoothnessSliderY = y; + rotateSmoothnessSliderW = sliderW; + rotateSmoothnessSliderH = sliderH; + + UiRenderer.frame(ctx, UiBounds.of(x, y, sliderW, sliderH), 0xFF0D0D18, AutismColors.subPanelBorder()); + UiRenderer.rect(ctx, UiBounds.of(x + 1, trackY, sliderW - 2, trackH), 0xFF150C0C); + + int knobIndex = Math.max(0, Math.min(9, smoothness - 1)); + int knobCenterX = x + Math.round((sliderW - 1) * (knobIndex / 9.0f)); + UiRenderer.rect(ctx, UiBounds.of(x + 1, trackY, knobCenterX - x - 1, trackH), 0xFF345C86); + + for (int i = 0; i < 10; i++) { + int cx = x + Math.round((sliderW - 1) * (i / 9.0f)); + int tickColor = i <= knobIndex ? 0xFF9DCEFF : 0xFF5A4040; + UiRenderer.rect(ctx, UiBounds.of(cx, y + 2, 1, sliderH - 4), tickColor); + } + + int knobW = 16; + int knobX = Math.max(x, Math.min(x + sliderW - knobW, knobCenterX - knobW / 2)); + boolean hovered = isOverRotateSmoothnessSlider(mx, my); + int knobFill = rotateSmoothnessSliderDragging ? 0xFF274A6D : (hovered ? 0xFF2A4462 : 0xFF223B56); + int knobBorder = rotateSmoothnessSliderDragging ? 0xFFA5D5FF : 0xFF88BBFF; + UiRenderer.frame(ctx, UiBounds.of(knobX, y, knobW, sliderH), knobFill, knobBorder); + return y + sliderH + ROW_GAP; + } + + private int getRotateSmoothness() { + AutismChatField field = textFields.get("smoothness"); + if (field == null) return 9; + try { + return autismclient.util.macro.RotateAction.clampSmoothness(Integer.parseInt(field.getText().trim())); + } catch (NumberFormatException ignored) { + return 9; + } + } + + private void setRotateSmoothness(int smoothness) { + AutismChatField field = textFields.get("smoothness"); + if (field != null) field.setText(String.valueOf(autismclient.util.macro.RotateAction.clampSmoothness(smoothness))); + } + + private void clearRotateSmoothnessSliderBounds() { + rotateSmoothnessSliderX = -1; + rotateSmoothnessSliderY = -1; + rotateSmoothnessSliderW = 0; + rotateSmoothnessSliderH = 0; + } + + private boolean isOverRotateSmoothnessSlider(int mx, int my) { + return rotateSmoothnessSliderW > 0 + && rotateSmoothnessSliderH > 0 + && mx >= rotateSmoothnessSliderX + && mx < rotateSmoothnessSliderX + rotateSmoothnessSliderW + && my >= rotateSmoothnessSliderY + && my < rotateSmoothnessSliderY + rotateSmoothnessSliderH; + } + + private void updateRotateSmoothnessFromMouse(int mouseX) { + if (rotateSmoothnessSliderW <= 1) return; + float normalized = (mouseX - rotateSmoothnessSliderX) / (float) (rotateSmoothnessSliderW - 1); + normalized = Math.max(0.0f, Math.min(1.0f, normalized)); + int stepIndex = Math.round(normalized * 9.0f); + setRotateSmoothness(1 + stepIndex); + } + + private int renderXCarrySafeDelaySlider(GuiGraphicsExtractor ctx, int x, int y, int w, int mx, int my) { + Identifier font = theme.fontFor(UiTone.BODY); + int delay = getXCarrySafeDelayTicks(); + UiText.draw(ctx, textRenderer, "Safe Delay", font, AutismColors.textSecondary(), x, y + 2, false); + String label = delay + "t"; + UiText.draw(ctx, textRenderer, label, font, AutismColors.textDim(), + x + w - uiWidth(font, label), y + 2, false); + y += 13; + + int sliderW = w; + int sliderH = 14; + int trackH = 4; + int trackY = y + (sliderH - trackH) / 2; + xcarrySafeDelaySliderX = x; + xcarrySafeDelaySliderY = y; + xcarrySafeDelaySliderW = sliderW; + xcarrySafeDelaySliderH = sliderH; + + UiRenderer.frame(ctx, UiBounds.of(x, y, sliderW, sliderH), 0xFF0D0D18, AutismColors.subPanelBorder()); + UiRenderer.rect(ctx, UiBounds.of(x + 1, trackY, sliderW - 2, trackH), 0xFF150C0C); + + int knobIndex = Math.max(0, Math.min(10, delay)); + int knobCenterX = x + Math.round((sliderW - 1) * (knobIndex / 10.0f)); + UiRenderer.rect(ctx, UiBounds.of(x + 1, trackY, knobCenterX - x - 1, trackH), 0xFF6A2D2D); + + for (int i = 0; i <= 10; i++) { + int cx = x + Math.round((sliderW - 1) * (i / 10.0f)); + int tickColor = i <= knobIndex ? 0xFFFF8A8A : 0xFF5A4040; + UiRenderer.rect(ctx, UiBounds.of(cx, y + 2, 1, sliderH - 4), tickColor); + } + + int knobW = 16; + int knobX = Math.max(x, Math.min(x + sliderW - knobW, knobCenterX - knobW / 2)); + boolean hovered = isOverXCarrySafeDelaySlider(mx, my); + int knobFill = xcarrySafeDelaySliderDragging ? 0xFF5C2424 : (hovered ? 0xFF4C2424 : 0xFF351B1B); + int knobBorder = xcarrySafeDelaySliderDragging ? 0xFFFFB0B0 : 0xFFFF7777; + UiRenderer.frame(ctx, UiBounds.of(knobX, y, knobW, sliderH), knobFill, knobBorder); + return y + sliderH + ROW_GAP; + } + + private int getXCarrySafeDelayTicks() { + AutismChatField field = textFields.get("safeClickDelayTicks"); + if (field == null) return 1; + try { + return autismclient.util.macro.XCarryAction.clampSafeClickDelayTicks(Integer.parseInt(field.getText().trim())); + } catch (NumberFormatException ignored) { + return 1; + } + } + + private void setXCarrySafeDelayTicks(int ticks) { + AutismChatField field = textFields.get("safeClickDelayTicks"); + if (field != null) { + field.setText(String.valueOf(autismclient.util.macro.XCarryAction.clampSafeClickDelayTicks(ticks))); + } + } + + private void clearXCarrySafeDelaySliderBounds() { + xcarrySafeDelaySliderX = -1; + xcarrySafeDelaySliderY = -1; + xcarrySafeDelaySliderW = 0; + xcarrySafeDelaySliderH = 0; + } + + private boolean isOverXCarrySafeDelaySlider(int mx, int my) { + return xcarrySafeDelaySliderW > 0 + && xcarrySafeDelaySliderH > 0 + && mx >= xcarrySafeDelaySliderX + && mx < xcarrySafeDelaySliderX + xcarrySafeDelaySliderW + && my >= xcarrySafeDelaySliderY + && my < xcarrySafeDelaySliderY + xcarrySafeDelaySliderH; + } + + private void updateXCarrySafeDelayFromMouse(int mouseX) { + if (xcarrySafeDelaySliderW <= 1) return; + float normalized = (mouseX - xcarrySafeDelaySliderX) / (float) (xcarrySafeDelaySliderW - 1); + normalized = Math.max(0.0f, Math.min(1.0f, normalized)); + int stepIndex = Math.round(normalized * 10.0f); + setXCarrySafeDelayTicks(stepIndex); + } + + private void applyWaitChatHistoryEntry(autismclient.util.macro.MacroExecutor.RecentChatMessage entry) { + AutismChatField field = textFields.get("pattern"); + if (field != null && entry != null) { + Component patternComponent = entry.displayComponent() != null + ? entry.displayComponent().copy() + : Component.literal(formatWaitChatHistoryEntry(entry)); + setWaitChatPatternField(field, patternComponent); + enumIndices.put("matchMode", 0); + workingTag.putString("matchMode", "MATCH"); + } + } + + private void setWaitChatPatternField(AutismChatField field, Component component) { + if (field == null) return; + Component safeComponent = component != null ? component.copy() : Component.empty(); + String visibleText = safeComponent.getString(); + workingTag.putString("pattern", visibleText); + workingTag.putString("patternJson", + autismclient.util.macro.MacroExecutor.serializeTextComponent(safeComponent)); + suppressWaitChatPatternSync = true; + field.setText(visibleText); + suppressWaitChatPatternSync = false; + } + + private Component getWaitChatPatternComponent(String fallbackValue) { + Component exact = autismclient.util.macro.MacroExecutor.deserializeTextComponent( + workingTag != null ? workingTag.getStringOr("patternJson", "") : ""); + if (exact != null) return exact.copy(); + return Component.literal(fallbackValue == null ? "" : fallbackValue); + } + + private Component rebuildWaitChatPatternComponent(Component previousComponent, String editedValue) { + String safeValue = editedValue == null ? "" : editedValue; + if (previousComponent == null) return Component.literal(safeValue); + + String previousValue = previousComponent.getString(); + if (previousValue.equals(safeValue)) return previousComponent.copy(); + if (safeValue.isEmpty()) return Component.empty(); + if (previousValue.isEmpty()) return Component.literal(safeValue); + + List