diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..00a51af --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# These are explicitly windows files and should use crlf +*.bat text eol=crlf + diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml new file mode 100644 index 0000000..c0e17e9 --- /dev/null +++ b/.github/workflows/gradle.yml @@ -0,0 +1,43 @@ +name: Java CI + +on: [push] + +jobs: + build: + strategy: + matrix: + os: [ubuntu-latest] + runs-on: ${{ matrix.os }} + + steps: + - uses: actions/checkout@v1 + + - uses: actions/cache@v1 + with: + path: ~/.gradle/caches + key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }} + restore-keys: | + ${{ runner.os }}-gradle- + + - name: Set up JDK 1.8 + uses: actions/setup-java@v1 + with: + java-version: 1.11 + + - name: Build with Gradle + run: ./gradlew build + + - name: Create update4j configuration + run: ./gradlew generateUpdateConfig + + - name: Deploy to Github Pages + uses: JamesIves/github-pages-deploy-action@releases/v3 + with: + ACCESS_TOKEN: ${{ secrets.ACCESS_TOKEN }} + # Need to create a personal access token until this is resolved: + # https://github.community/t5/GitHub-Actions/Github-action-not-triggering-gh-pages-upon-push/m-p/31266/highlight/true#M743 + #GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + BASE_BRANCH: master # The branch the action should deploy from. + BRANCH: gh-pages # The branch the action should deploy to. + FOLDER: build/pages # The folder the action should deploy. + \ No newline at end of file diff --git a/.gitignore b/.gitignore index 3b01403..fdac8cf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,23 @@ -*.properties +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build + +# TeaseAI files +Themes/ +log/ +Personalities/* +Images/* +Logs/* +TeaseAI.properties + +# IntelliJ .idea *.iml -out -target + +# Eclipse .settings .project .classpath -.git -Personalities/* -Images/* -Logs/* \ No newline at end of file +bin/ \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /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/META-INF/MANIFEST.MF b/META-INF/MANIFEST.MF deleted file mode 100644 index 63d0c3f..0000000 --- a/META-INF/MANIFEST.MF +++ /dev/null @@ -1,3 +0,0 @@ -Manifest-Version: 1.0 -Main-Class: me.goddragon.teaseai.TeaseAI - diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..6b62695 --- /dev/null +++ b/build.gradle @@ -0,0 +1,81 @@ +plugins { + // Apply the java plugin to add support for Java + id 'java' + + // Apply the application plugin to add support for building a CLI application. + id 'application' + + id 'org.openjfx.javafxplugin' version '0.0.8' + + id 'maven-publish' + + id 'com.palantir.git-version' version '0.12.2' +} + +java { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 +} + +javafx { + version = "13" + modules = [ 'javafx.controls', 'javafx.fxml', 'javafx.media', 'javafx.swing' ] +} + +repositories { + jcenter() + + // Used to import EstimAPI from Github + maven { url "https://jitpack.io" } +} + +dependencies { + // This dependency is used by the application. + implementation 'com.google.guava:guava:28.0-jre' + implementation 'com.google.code.gson:gson:2.8.6' + implementation group: 'de.dfki.mary', name: 'voice-cmu-slt-hsmm', version: '5.2' + + // https://mvnrepository.com/artifact/de.dfki.mary/voice-dfki-prudence-hsmm + implementation group: 'de.dfki.mary', name: 'voice-dfki-prudence-hsmm', version: '5.2' + + + // jsoup HTML parser library @ https://jsoup.org/ + implementation 'org.jsoup:jsoup:1.12.1' + + // https://mvnrepository.com/artifact/org.json/json + implementation group: 'org.json', name: 'json', version: '20190722' + // TODO Update to commons-configuration2? + // https://mvnrepository.com/artifact/commons-configuration/commons-configuration + implementation group: 'commons-configuration', name: 'commons-configuration', version: '1.10' + + implementation 'com.github.GodDragoner:EstimAPI:master-SNAPSHOT' + + // Use JUnit test framework + testImplementation 'junit:junit:4.12' +} + +configurations.all { + resolutionStrategy { + // Force newer groovy version (required by voice-dfki-prudence-hsmm) because older one fails with module resolution in update4j. + force 'org.codehaus.groovy:groovy-all:2.5.8' + } +} + +application { + // Define the main class for the application. + mainClassName = 'me.goddragon.teaseai.Main' +} + +version gitVersion() + +publishing { + publications { + maven(MavenPublication) { + groupId = 'com.github.GodDragoner' + artifactId = 'TeaseAIJava' + from components.java + } + } +} + +apply plugin: 'me.goddragon.updater' \ No newline at end of file diff --git a/buildSrc/.gitattributes b/buildSrc/.gitattributes new file mode 100644 index 0000000..00a51af --- /dev/null +++ b/buildSrc/.gitattributes @@ -0,0 +1,6 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# These are explicitly windows files and should use crlf +*.bat text eol=crlf + diff --git a/buildSrc/.gitignore b/buildSrc/.gitignore new file mode 100644 index 0000000..1b6985c --- /dev/null +++ b/buildSrc/.gitignore @@ -0,0 +1,5 @@ +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle new file mode 100644 index 0000000..a072915 --- /dev/null +++ b/buildSrc/build.gradle @@ -0,0 +1,15 @@ +description = "Exposes gradle buildSrc for IDE support" + +apply plugin: "groovy" + +repositories { + mavenLocal() + mavenCentral() +} + +dependencies { + implementation gradleApi() + implementation localGroovy() + + implementation group: 'org.update4j', name: 'update4j', version: '1.4.4' +} diff --git a/buildSrc/src/main/java/me/goddragon/updater/GitHubRepository.java b/buildSrc/src/main/java/me/goddragon/updater/GitHubRepository.java new file mode 100644 index 0000000..074ee96 --- /dev/null +++ b/buildSrc/src/main/java/me/goddragon/updater/GitHubRepository.java @@ -0,0 +1,43 @@ +package me.goddragon.updater; + +public class GitHubRepository { + private final String owner; + private final String repository; + + public GitHubRepository(String owner, String repository) { + super(); + this.owner = owner; + this.repository = repository; + } + + public String getOwner() { + return owner; + } + + public String getRepository() { + return repository; + } + + private static String getActionString() { + String actionString = System.getenv("GITHUB_REPOSITORY"); + + if(actionString == null) { + throw new RuntimeException("This task is only available on Github Actions!"); + } + + return actionString; + } + + public static GitHubRepository fromActionsString() { + + String[] parts = getActionString().split("/", 2); + String owner = parts[0]; + String repository = parts[1]; + return new GitHubRepository(owner, repository); + } + + public String getPagesUrl(String file) { + return String.format("https://%s.github.io/%s/%s", + this.owner, this.repository, file); + } +} diff --git a/buildSrc/src/main/java/me/goddragon/updater/Update4JPlugin.java b/buildSrc/src/main/java/me/goddragon/updater/Update4JPlugin.java new file mode 100644 index 0000000..4808d10 --- /dev/null +++ b/buildSrc/src/main/java/me/goddragon/updater/Update4JPlugin.java @@ -0,0 +1,10 @@ +package me.goddragon.updater; + +import org.gradle.api.Plugin; +import org.gradle.api.Project; + +public class Update4JPlugin implements Plugin { + public void apply(Project project) { + project.getTasks().create("generateUpdateConfig", Update4JTask.class).dependsOn("jar"); + } +} diff --git a/buildSrc/src/main/java/me/goddragon/updater/Update4JTask.java b/buildSrc/src/main/java/me/goddragon/updater/Update4JTask.java new file mode 100644 index 0000000..3f4bc47 --- /dev/null +++ b/buildSrc/src/main/java/me/goddragon/updater/Update4JTask.java @@ -0,0 +1,190 @@ +package me.goddragon.updater; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Set; + +import org.gradle.api.DefaultTask; +import org.gradle.api.artifacts.ModuleVersionIdentifier; +import org.gradle.api.artifacts.ResolvedArtifact; +import org.gradle.api.artifacts.repositories.UrlArtifactRepository; +import org.gradle.api.file.RegularFile; +import org.gradle.api.provider.Provider; +import org.gradle.api.tasks.TaskAction; +import org.gradle.jvm.tasks.Jar; +import org.update4j.Configuration; +import org.update4j.Configuration.Builder; +import org.update4j.FileMetadata; +import org.update4j.OS; + +public class Update4JTask extends DefaultTask { + @TaskAction + void generateManifest() throws IOException { + Builder builder = Configuration.builder(); + builder.basePath("${user.dir}/TeaseAI"); + builder.property("default.launcher.main.class", "me.goddragon.teaseai.Main"); + + File ghPagesRelease = getProject().file("build/pages/releases/"); + ghPagesRelease.mkdirs(); + + // Remove old releases + for(File file : ghPagesRelease.listFiles()) { + file.delete(); + } + + addMainJar(builder); + appendDeps(builder); + + File configFile = getProject().file("build/pages/releases/update.xml"); + + try(FileWriter writer = new FileWriter(configFile)) { + builder.build().write(writer); + } + } + + + + private void addMainJar(Builder builder) throws IOException { + File mainJar = getMainJarFile(); + + String uri = GitHubRepository.fromActionsString().getPagesUrl("releases/" + mainJar.getName()); + + File target = getProject().file("build/pages/releases/" + mainJar.getName()); + + Files.copy(mainJar.toPath(), target.toPath()); + + builder.file(FileMetadata + .readFrom(mainJar.getAbsolutePath()) + .uri(uri) + .classpath() + ); + } + + private File getMainJarFile() { + final Jar jarTask = (Jar) getProject().getTasks().getByName("jar"); + final Provider archiveName = jarTask.getArchiveFileName(); + final RegularFile file = jarTask.getDestinationDirectory().file(archiveName).get(); + return file.getAsFile(); + } + + private void appendDeps(Builder builder) throws IOException { + Set artifacts = getProject().getConfigurations().getByName("runtimeClasspath") + .getResolvedConfiguration().getResolvedArtifacts(); + + String[] repos = getRepositoryUrls(); + + for (ResolvedArtifact artifact : artifacts) { + + addOtherOSFiles(repos, artifact, builder); + + String url = getArtifactUrl(repos, artifact); + + builder.file( + FileMetadata.readFrom(artifact.getFile().getAbsolutePath()) + .uri(url) + .osFromFilename() + .classpath() + ); + } + } + + private URI toURI(String url) { + try { + return new URI(url); + } catch (URISyntaxException e) { + // Should never happen, these urls are generated by this class. + throw new RuntimeException(e); + } + } + + private void addOtherOSFiles(String[] repos, ResolvedArtifact artifact, Builder builder) throws IOException { + OS[] osClassifiers = { OS.LINUX, OS.WINDOWS, OS.MAC }; + String classifier = artifact.getClassifier(); + + if(classifier != null && OS.fromShortName(classifier) == OS.CURRENT) { + for(OS os : osClassifiers) { + if(os == OS.CURRENT) { + continue; + } + + String url = getArtifactUrl(repos, artifact, os.getShortName()); + String filename = Paths.get(toURI(url).getPath()).getFileName().toString(); + + File outputFile = getProject() + .file("build/otherOS/" + os.getShortName() + "/" + filename + ".jar"); + + outputFile.getParentFile().mkdirs(); + + ReadableByteChannel readableByteChannel = Channels.newChannel(new URL(url).openStream()); + try(FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) { + fileOutputStream.getChannel() + .transferFrom(readableByteChannel, 0, Long.MAX_VALUE); + } + + builder.file(FileMetadata.readFrom(outputFile.getPath()) + .uri(url) + .os(os) + .classpath()); + } + } + } + + private String[] getRepositoryUrls() { + return getProject().getRepositories().stream() + .filter(repository -> repository instanceof UrlArtifactRepository) + .map(repository -> (UrlArtifactRepository) repository) + .map(repository -> repository.getUrl().toString()) + .toArray(String[]::new); + + } + + private String getArtifactUrl(String[] repositories, ResolvedArtifact artifact) { + return getArtifactUrl(repositories, artifact, artifact.getClassifier()); + } + + private String getArtifactUrl(String[] repositories, ResolvedArtifact artifact, String classifierOverwrite) { + for (String repoUrl : repositories) { + ModuleVersionIdentifier dependency = artifact.getModuleVersion().getId(); + + String group = dependency.getGroup().replace('.', '/'); + String name = dependency.getName(); + String version = dependency.getVersion(); + + String classifier = ""; + + if (classifierOverwrite != null) { + classifier = "-" + classifierOverwrite; + } + + String jarUrl = String.format("%s/%s/%s/%s/%s-%s%s.jar", repoUrl, group, name, version, name, version, + classifier); + + if (exists(jarUrl)) { + return jarUrl; + } + } + + throw new RuntimeException("Artifact not found in any repository"); + } + + private boolean exists(String url) { + try { + HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); + con.setRequestMethod("HEAD"); + + return con.getResponseCode() == HttpURLConnection.HTTP_OK; + } catch (Exception e) { + return false; + } + } +} diff --git a/buildSrc/src/main/resources/META-INF/gradle-plugins/me.goddragon.updater.properties b/buildSrc/src/main/resources/META-INF/gradle-plugins/me.goddragon.updater.properties new file mode 100644 index 0000000..2fe2981 --- /dev/null +++ b/buildSrc/src/main/resources/META-INF/gradle-plugins/me.goddragon.updater.properties @@ -0,0 +1 @@ +implementation-class=me.goddragon.updater.Update4JPlugin diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..cc4fdc2 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..6ce793f --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.0-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..2fe81a7 --- /dev/null +++ b/gradlew @@ -0,0 +1,183 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or 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. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# 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"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# 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 + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# 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" + which java >/dev/null 2>&1 || 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 + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9618d8d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,100 @@ +@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 + +@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=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@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%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="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! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/jitpack.yml b/jitpack.yml new file mode 100644 index 0000000..46c8529 --- /dev/null +++ b/jitpack.yml @@ -0,0 +1,2 @@ +jdk: + - openjdk11 \ No newline at end of file diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..b5648dc --- /dev/null +++ b/settings.gradle @@ -0,0 +1,14 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * + * Detailed information about configuring a multi-project build in Gradle can be found + * in the user manual at https://docs.gradle.org/6.0/userguide/multi_project_builds.html + */ + +rootProject.name = 'TeaseAIJava' + +include "buildSrc" + +rootProject.children.find{ it.name == "buildSrc" }.name = "myproject-build-src" \ No newline at end of file diff --git a/src/TAJUpdater.jar b/src/TAJUpdater.jar deleted file mode 100644 index 7fcd3aa..0000000 Binary files a/src/TAJUpdater.jar and /dev/null differ diff --git a/src/main/java/me/goddragon/teaseai/Main.java b/src/main/java/me/goddragon/teaseai/Main.java new file mode 100644 index 0000000..785b616 --- /dev/null +++ b/src/main/java/me/goddragon/teaseai/Main.java @@ -0,0 +1,95 @@ +package me.goddragon.teaseai; + +import me.goddragon.teaseai.utils.FileUtils; +import me.goddragon.teaseai.utils.TeaseLogger; +import me.goddragon.teaseai.utils.ZipUtils; +import me.goddragon.teaseai.utils.update.UpdateHandler; + +import javax.swing.*; +import java.io.*; +import java.lang.management.ManagementFactory; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.file.Paths; +import java.util.logging.Level; + +public class Main { + + public static double JAVA_VERSION = getJavaVersion(); + public static String OPERATING_SYSTEM = System.getProperty("os.name").toLowerCase(); + + public static void main(String[] args) { + TeaseAI.main(args); + } + + + private static File getJavaFXLibFolder() { + File currentDir = Paths.get(System.getProperty("user.dir")).toFile(); + + for (File file : currentDir.listFiles()) { + if (file.isDirectory()) { + for (File dirFile : file.listFiles()) { + //Check if we have found the right lib folder containing the files we expect it to contain + if (dirFile.isDirectory() && dirFile.getName().equals("lib") && FileUtils.folderContains(dirFile, "javafx.base.jar")) { + //libFolder = dirFile; + return dirFile; + } + } + } + } + + return null; + } + + public static void restart() { + try { + Process process = Runtime.getRuntime().exec(new String[]{"java", "--module-path=" + getJavaFXLibFolder().getPath(), "--add-modules=javafx.controls,javafx.fxml,javafx.base,javafx.media,javafx.graphics,javafx.swing,javafx.web", "-jar", "TeaseAI.jar"}); + + /*BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream())); + String line; + while ((line = input.readLine()) != null) { + System.out.println(line); + } + + input.close();*/ + } catch (IOException e) { + e.printStackTrace(); + } + + System.exit(0); + } + + public static boolean isWindows() { + return (OPERATING_SYSTEM.indexOf("win") >= 0); + } + + public static boolean isMac() { + return (OPERATING_SYSTEM.indexOf("mac") >= 0); + } + + public static boolean isUnix() { + return (OPERATING_SYSTEM.indexOf("nix") >= 0 || OPERATING_SYSTEM.indexOf("nux") >= 0 || OPERATING_SYSTEM.indexOf("aix") > 0); + } + + public static boolean isSolaris() { + return (OPERATING_SYSTEM.indexOf("sunos") >= 0); + } + + public static String getOS() { + if (isWindows()) { + return "win"; + } else if (isMac()) { + return "osx"; + } else if (isUnix()) { + return "uni"; + } else if (isSolaris()) { + return "sol"; + } else { + return "err"; + } + } + + static double getJavaVersion() { + return Double.parseDouble(System.getProperty("java.specification.version")); + } +} diff --git a/src/me/goddragon/teaseai/TeaseAI.java b/src/main/java/me/goddragon/teaseai/TeaseAI.java similarity index 55% rename from src/me/goddragon/teaseai/TeaseAI.java rename to src/main/java/me/goddragon/teaseai/TeaseAI.java index 7c1d9d2..6319561 100644 --- a/src/me/goddragon/teaseai/TeaseAI.java +++ b/src/main/java/me/goddragon/teaseai/TeaseAI.java @@ -1,316 +1,417 @@ -package me.goddragon.teaseai; - -import javafx.application.Application; -import javafx.application.Platform; -import javafx.concurrent.Task; -import javafx.fxml.FXMLLoader; -import javafx.scene.Parent; -import javafx.scene.Scene; -import javafx.scene.control.Alert; -import javafx.scene.text.Font; -import javafx.stage.Stage; -import me.goddragon.teaseai.api.chat.ChatHandler; -import me.goddragon.teaseai.api.chat.TypeSpeed; -import me.goddragon.teaseai.api.chat.response.Response; -import me.goddragon.teaseai.api.chat.response.ResponseHandler; -import me.goddragon.teaseai.api.config.ConfigHandler; -import me.goddragon.teaseai.api.config.ConfigValue; -import me.goddragon.teaseai.api.media.MediaCollection; -import me.goddragon.teaseai.api.media.MediaFetishType; -import me.goddragon.teaseai.api.media.MediaHandler; -import me.goddragon.teaseai.api.runnable.TeaseRunnableHandler; -import me.goddragon.teaseai.api.scripts.personality.Personality; -import me.goddragon.teaseai.api.scripts.personality.PersonalityManager; -import me.goddragon.teaseai.api.session.Session; -import me.goddragon.teaseai.api.session.StrokeHandler; -import me.goddragon.teaseai.gui.ProgressForm; -import me.goddragon.teaseai.gui.StartupProgressPane; -import me.goddragon.teaseai.gui.main.MainGuiController; -import me.goddragon.teaseai.utils.TeaseLogger; -import me.goddragon.teaseai.utils.update.UpdateHandler; - -import java.io.IOException; -import java.util.logging.Level; - -/** - * Created by GodDragon on 21.03.2018. - */ -public class TeaseAI extends Application { - - public static final String VERSION = "1.0.16"; - public static final String UPDATE_FOLDER = "Updates"; - - public static double JAVA_VERSION = getJavaVersion(); - - public static TeaseAI application; - private ConfigHandler configHandler = new ConfigHandler("TeaseAI.properties"); - private MediaCollection mediaCollection; - private MainGuiController controller; - private Thread mainThread; - private Stage primaryStage; - public Thread scriptThread; - - public StartupProgressPane startupProgressPane; - private Scene mainScene; - - public final ConfigValue PREFERRED_SESSION_DURATION = new ConfigValue("preferredSessionDuration", "60", configHandler); - public final ConfigValue CHAT_TEXT_SIZE = new ConfigValue("chatTextSize", Font.getDefault().getSize(), configHandler); - public final ConfigValue DEFAULT_TYPE_SPEED = new ConfigValue("defaultTypeSpeed", TypeSpeed.MEDIUM, configHandler); - public final ConfigValue LAST_SELECTED_PERSONALITY = new ConfigValue("lastSelectedPersonality", "null", configHandler); - public final ConfigValue TEASE_AI_PROPERTIES_LINK = new ConfigValue("teaseAIPropertiesLink", "https://gist.githubusercontent.com/GodDragoner/6c7193903cb0695ff891e8468ad279cd/raw/TeaseAI.properties", configHandler); - - private Session session; - - @Override - public void start(Stage primaryStage) throws Exception { - if(JAVA_VERSION < 10) { - Alert alert = new Alert(Alert.AlertType.ERROR); - alert.setTitle("Old Java Version Detected"); - alert.setHeaderText(null); - alert.setContentText("You are using java version " + JAVA_VERSION + " which is not supported. Please use Java 10 or higher. This program will close now."); - alert.showAndWait(); - return; - } - - TeaseLogger.getLogger().log(Level.INFO, "Launching TAJ " + VERSION); - - //Will allow us to use ecma6 language - System.setProperty("nashorn.args", "--language=es6"); - - this.application = this; - this.mainThread = Thread.currentThread(); - this.primaryStage = primaryStage; - this.startupProgressPane = new StartupProgressPane(); - - //Load config values first - configHandler.loadConfig(); - - ProgressForm progressForm = new ProgressForm("Checking for TAJ update..."); - Task task = new Task() { - @Override - public Void call() throws InterruptedException { - UpdateHandler.getHandler().checkForUpdate(); - - progressForm.setNameSync("Checking personalities..."); - PersonalityManager.getManager().setProgressUpdate((workDone, totalWork) -> - updateProgress(workDone, totalWork)); - - PersonalityManager.getManager().loadPersonalities(); - - progressForm.setNameSync("Finishing startup..."); - - TeaseAI.application.runOnUIThread(new Runnable() { - @Override - public void run() { - try { - TeaseAI.application.finishedCheckup(); - } catch (IOException e) { - e.printStackTrace(); - } - } - }); - - return null; - } - }; - - progressForm.bindProgressBar(task); - startupProgressPane.addProgressBar(progressForm); - startupProgressPane.show(); - - task.setOnSucceeded(event -> startupProgressPane.getDialogStage().close()); - - Thread thread = new Thread(task); - thread.start(); - } - - public static void main(String[] args) { - launch(args); - } - - public void finishedCheckup() throws IOException { - startupProgressPane.close(); - - FXMLLoader loader = new FXMLLoader(getClass().getResource("gui/main/main.fxml")); - controller = new MainGuiController(primaryStage); - loader.setController(controller); - Parent root = loader.load(); - primaryStage.setTitle("Tease-AI " + VERSION); - mainScene = new Scene(root, 1480, 720); - primaryStage.setScene(mainScene); - primaryStage.show(); - controller.initiate(); - - primaryStage.setOnCloseRequest(event -> { - try { - System.exit(0); - } catch (Exception e) { - e.printStackTrace(); - } - }); - - //Load values to add the config values - MediaFetishType.values(); - - ChatHandler.getHandler().load(); - - this.mediaCollection = new MediaCollection(); - - PersonalityManager.getManager().addPersonalitiesToGUI(); - - initializeNewSession(); - - controller.loadDomInfo(); - } - - public boolean checkForNewResponses() { - if (Thread.currentThread() != scriptThread) { - throw new IllegalStateException("Can only check for new responses on the script thread"); - } - - Response queuedResponse = ResponseHandler.getHandler().getLatestQueuedResponse(); - if (queuedResponse != null) { - ResponseHandler.getHandler().removeQueuedResponse(queuedResponse); - return queuedResponse.trigger(); - } - - return false; - } - - public void runOnUIThread(Runnable runnable) { - //If we are not on the main thread, run it later on it - if (Thread.currentThread() != mainThread) { - Platform.runLater(runnable); - } else { - //We can safely run the runnable because we are on the main thread - runnable.run(); - } - } - - public void waitPossibleScripThread(long timeoutMillis) { - waitThread(timeoutMillis); - - //Let's check whether we are supposed to force the session to end - if(Thread.currentThread() == scriptThread) { - session.checkForForcedEnd(); - } - } - - public void sleepPossibleScripThread(long sleepMillis) { - sleepPossibleScripThread(sleepMillis, false); - } - - public void sleepPossibleScripThread(long sleepMillis, boolean runnablesOnly) { - if(Thread.currentThread() != scriptThread) { - sleepThread(sleepMillis); - } else { - long startedAt = System.currentTimeMillis(); - long millisPerInterval = 100; - while(startedAt + sleepMillis > System.currentTimeMillis()) { - sleepThread(millisPerInterval); - - //Check for new stuff - if(!runnablesOnly) { - //Only check if the session already started - if(session.isStarted()) { - session.checkForInteraction(); - } - } else { - TeaseRunnableHandler.getHandler().checkRunnables(); - } - } - } - } - - public void sleepScripThread(long sleepMillis) { - if(Thread.currentThread() != scriptThread) { - TeaseLogger.getLogger().log(Level.SEVERE, "Tried to sleep script thread from other thread."); - return; - } - - sleepThread(sleepMillis); - } - - public void waitScriptThread(long timeoutMillis) { - if(Thread.currentThread() != scriptThread) { - TeaseLogger.getLogger().log(Level.SEVERE, "Tried to wait script thread from other thread."); - return; - } - - waitThread(timeoutMillis); - } - - public void waitThread() { - waitThread(0); - } - - public void waitThread(long timeoutMillis) { - synchronized (Thread.currentThread()) { - try { - Thread.currentThread().wait(timeoutMillis); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - public void sleepThread(long sleepMillis) { - synchronized (Thread.currentThread()) { - try { - Thread.sleep(sleepMillis); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - public MainGuiController getController() { - return controller; - } - - public void initializeNewSession() { - this.session = new Session(); - - //End everything such as metronome and stroking - StrokeHandler.getHandler().setEdging(false); - StrokeHandler.getHandler().setOnEdge(false); - StrokeHandler.getHandler().stopMetronome(); - - //Show no picture - MediaHandler.getHandler().showPicture(null); - - session.setActivePersonality((Personality) controller.getPersonalityChoiceBox().getSelectionModel().getSelectedItem()); - - //Reset the temporary variables - session.getActivePersonality().getVariableHandler().clearTemporaryVariables(); - } - - public Thread getScriptThread() { - return scriptThread; - } - - public Thread getMainThread() { - return mainThread; - } - - public ConfigHandler getConfigHandler() { - return configHandler; - } - - public MediaCollection getMediaCollection() { - return mediaCollection; - } - - public Session getSession() { - return session; - } - - public Scene getScene() { - return mainScene; - } - - - static double getJavaVersion() { - return Double.parseDouble(System.getProperty("java.specification.version")); - } -} +package me.goddragon.teaseai; + +import javafx.application.Application; +import javafx.application.Platform; +import javafx.concurrent.Task; +import javafx.fxml.FXMLLoader; +import javafx.scene.Parent; +import javafx.scene.Scene; +import javafx.scene.control.Alert; +import javafx.scene.text.Font; +import javafx.stage.Stage; +import me.goddragon.teaseai.api.chat.ChatHandler; +import me.goddragon.teaseai.api.chat.TypeSpeed; +import me.goddragon.teaseai.api.chat.response.Response; +import me.goddragon.teaseai.api.chat.response.ResponseHandler; +import me.goddragon.teaseai.api.config.ConfigHandler; +import me.goddragon.teaseai.api.config.ConfigValue; +import me.goddragon.teaseai.api.config.PersonalitiesSettingsHandler; +import me.goddragon.teaseai.api.media.MediaCollection; +import me.goddragon.teaseai.api.media.MediaFetishType; +import me.goddragon.teaseai.api.media.MediaHandler; +import me.goddragon.teaseai.api.runnable.TeaseRunnableHandler; +import me.goddragon.teaseai.api.scripts.personality.Personality; +import me.goddragon.teaseai.api.scripts.personality.PersonalityManager; +import me.goddragon.teaseai.api.session.Session; +import me.goddragon.teaseai.api.session.StrokeHandler; +import me.goddragon.teaseai.api.statistics.StatisticsManager; +import me.goddragon.teaseai.gui.ProgressForm; +import me.goddragon.teaseai.gui.StartupProgressPane; +import me.goddragon.teaseai.gui.main.MainGuiController; +import me.goddragon.teaseai.gui.settings.AppearanceSettings; +import me.goddragon.teaseai.utils.TeaseLogger; +import me.goddragon.teaseai.utils.update.JFXUpdater; +import me.goddragon.teaseai.utils.update.UpdateHandler; + +import java.io.IOException; +import java.util.List; +import java.util.logging.Level; + +/** + * Created by GodDragon on 21.03.2018. + */ +public class TeaseAI extends Application { + + + public static final String VERSION = "1.2"; + public static final String UPDATE_FOLDER = "Updates"; + + public static TeaseAI application; + private ConfigHandler configHandler = new ConfigHandler("TeaseAI.properties"); + private MediaCollection mediaCollection; + private MainGuiController controller; + private Thread mainThread; + private Stage primaryStage; + private Thread scriptThread; + + public StartupProgressPane startupProgressPane; + private Scene mainScene; + + public final ConfigValue PREFERRED_SESSION_DURATION = new ConfigValue("preferredSessionDuration", "60", configHandler); + public final ConfigValue CHAT_TEXT_SIZE = new ConfigValue("chatTextSize", Font.getDefault().getSize(), configHandler); + public final ConfigValue DEFAULT_TYPE_SPEED = new ConfigValue("defaultTypeSpeed", TypeSpeed.MEDIUM, configHandler); + public final ConfigValue LAST_SELECTED_PERSONALITY = new ConfigValue("lastSelectedPersonality", "null", configHandler); + public final ConfigValue TEASE_AI_PROPERTIES_LINK = new ConfigValue("teaseAIPropertiesLink", UpdateHandler.TEASE_AI_PROPERTIES_DEFAULT_LINK, configHandler); + public final ConfigValue TEXT_TO_SPEECH = new ConfigValue("texttospeech", 2, configHandler); + public final ConfigValue DEBUG_MODE = new ConfigValue("debugmode", false, configHandler); + public final ConfigValue ESTIM_ENABLED = new ConfigValue("estimEnabled", false, configHandler); + public final ConfigValue ESTIM_DEVICE_PATH = new ConfigValue("estimDevicePath", "", configHandler); + public final ConfigValue ESTIM_METRONOME = new ConfigValue("estimMetronome", false, configHandler); + public final ConfigValue ESTIM_METRONOME_USER_CONTROLS_POWER = new ConfigValue("estimMetronomeUserControlsPower", true, configHandler); + public final ConfigValue ESTIM_METRONOME_ENABLED_MODES = new ConfigValue("estimMetronomeEnabledModes", "CONTINUOUS,TRAINING,FLO,SQUEEZE,PULSE,THROB,THRUST,TWIST,B_SPLIT,MILK,CYCLE,WAVE,STEP,BOUNCE,A_SPLIT,WATERFALL,RANDOM", configHandler); + public final ConfigValue ESTIM_METRONOME_BPM_MIN = new ConfigValue("estimMetronomeBpmMin", "0", configHandler); + public final ConfigValue ESTIM_METRONOME_BPM_MAX = new ConfigValue("estimMetronomeBpmMax", "180", configHandler); + public final ConfigValue ESTIM_CHANNEL_A_MIN = new ConfigValue("estimChannelAMin", "1", configHandler); + public final ConfigValue ESTIM_CHANNEL_A_MAX = new ConfigValue("estimChannelAMax", "10", configHandler); + public final ConfigValue ESTIM_CHANNEL_B_MIN = new ConfigValue("estimChannelBMin", "1", configHandler); + public final ConfigValue ESTIM_CHANNEL_B_MAX = new ConfigValue("estimChannelBMax", "10", configHandler); + public final ConfigValue ESTIM_CHANNEL_C_MIN = new ConfigValue("estimChannelCMin", "1", configHandler); + public final ConfigValue ESTIM_CHANNEL_C_MAX = new ConfigValue("estimChannelCMax", "99", configHandler); + public final ConfigValue ESTIM_CHANNEL_D_MIN = new ConfigValue("estimChannelDMin", "1", configHandler); + public final ConfigValue ESTIM_CHANNEL_D_MAX = new ConfigValue("estimChannelDMax", "99", configHandler); + + + private Session session; + public boolean TextToSpeechEnabled = false; + private boolean responsesDisabled = false; + + + @Override + public void start(Stage primaryStage) throws Exception { + if (Main.JAVA_VERSION < 10) { + Alert alert = new Alert(Alert.AlertType.ERROR); + alert.setTitle("Old Java Version Detected"); + alert.setHeaderText(null); + alert.setContentText("You are using java version " + Main.JAVA_VERSION + " which is not supported. Please use Java 10 or higher. This program will close now."); + alert.showAndWait(); + return; + } + + TeaseLogger.getLogger().log(Level.INFO, "Launching TAJ " + VERSION); + + //Will allow us to use ecma6 language + System.setProperty("nashorn.args", "--language=es6"); + + this.application = this; + this.mainThread = Thread.currentThread(); + this.primaryStage = primaryStage; + this.startupProgressPane = new StartupProgressPane(); + + //Load config values first + configHandler.loadConfig(); + + UpdateHandler.TEASE_AI_PROPERTIES_DEFAULT_LINK = TEASE_AI_PROPERTIES_LINK.getValue(); + + ProgressForm progressForm = new ProgressForm("Checking for TAJ update..."); + Task task = new Task() { + @Override + public Void call() throws InterruptedException { + JFXUpdater.getUpdater().checkForUpdate(); + + progressForm.setNameSync("Checking personalities..."); + PersonalityManager.getManager().setProgressUpdate((workDone, totalWork) -> + updateProgress(workDone, totalWork)); + + PersonalityManager.getManager().loadPersonalities(); + + TeaseAI.application.runOnUIThread(new Runnable() { + @Override + public void run() { + try { + TeaseAI.application.finishedCheckup(progressForm); + } catch (IOException e) { + e.printStackTrace(); + } + } + }); + + return null; + } + }; + + progressForm.bindProgressBar(task); + startupProgressPane.addProgressBar(progressForm); + startupProgressPane.show(); + + new PersonalitiesSettingsHandler(); + //task.setOnSucceeded(event -> startupProgressPane.getDialogStage().close()); + + Thread thread = new Thread(task); + thread.start(); + if (TEXT_TO_SPEECH.getInt() == 1) { + setTTS(true); + } + } + + public static void main(String[] args) { + launch(args); + } + + public void finishedCheckup(ProgressForm progressForm) throws IOException { + //startupProgressPane.close(); + + progressForm.setNameSync("Setting up GUI..."); + + FXMLLoader loader = new FXMLLoader(getClass().getResource("gui/main/main.fxml")); + controller = new MainGuiController(primaryStage); + loader.setController(controller); + Parent root = loader.load(); + primaryStage.setTitle("Tease-AI " + VERSION); + mainScene = new Scene(root, 1480, 720); + + //So we can apply our themes to all relevant GUIs at once + controller.addMainScene(mainScene); + + primaryStage.setScene(mainScene); + controller.initiate(); + + primaryStage.setOnCloseRequest(event -> { + try { + System.exit(0); + } catch (Exception e) { + e.printStackTrace(); + } + }); + + Task task = new Task() { + @Override + public Void call() { + //Load values to add the config values + MediaFetishType.values(); + + progressForm.setNameSync("Loading picture sets..."); + + PersonalityManager.getManager().setProgressUpdate((workDone, totalWork) -> + updateProgress(workDone, totalWork)); + + ChatHandler.getHandler().load(); + + progressForm.setNameSync("Finishing startup..."); + + TeaseAI.application.runOnUIThread(new Runnable() { + @Override + public void run() { + primaryStage.show(); + + TeaseAI.this.mediaCollection = new MediaCollection(); + + PersonalityManager.getManager().addPersonalitiesToGUI(); + + initializeNewSession(); + + controller.loadDomInfo(); + + //Load theme last so everything is setup + AppearanceSettings.loadSelectedTheme(); + + //Reload lazy sub because it is somehow messed up + TeaseAI.application.getController().getLazySubController().clear(); + TeaseAI.application.getController().getLazySubController().createDefaults(); + } + }); + + return null; + } + }; + + progressForm.bindProgressBar(task); + task.setOnSucceeded(event -> startupProgressPane.getDialogStage().close()); + Thread thread = new Thread(task); + thread.start(); + //startupProgressPane.addProgressBar(progressForm); + } + + public boolean checkForNewResponses() { + if (!Thread.currentThread().equals(getScriptThread())) { + throw new IllegalStateException("Can only check for new responses on the script thread"); + } + + //This way we will handle ALL queued responses in this session but any further queued responses will be done too + List queued = (List) ResponseHandler.getHandler().getQueuedResponse().clone(); + ResponseHandler.getHandler().getQueuedResponse().clear(); + + //Repeat for all queued responses + while (!queued.isEmpty()) { + Response queuedResponse = queued.get(0); + queued.remove(0); + + if (queuedResponse != null) { + ResponseHandler.getHandler().removeQueuedResponse(queuedResponse); + if ((queuedResponse.isIgnoreDisabledResponses() || !responsesDisabled)) { + if (queuedResponse.trigger()) { + return true; + } + } + } else { + break; + } + } + + return false; + } + + public void runOnUIThread(Runnable runnable) { + //If we are not on the main thread, run it later on it + if (Thread.currentThread() != mainThread) { + Platform.runLater(runnable); + } else { + //We can safely run the runnable because we are on the main thread + runnable.run(); + } + } + + public void waitPossibleScripThread(long timeoutMillis) { + waitThread(timeoutMillis); + + //Let's check whether we are supposed to force the session to end + if (Thread.currentThread() == getScriptThread()) { + session.checkForForcedEnd(); + } + } + + public void sleepPossibleScripThread(long sleepMillis) { + sleepPossibleScripThread(sleepMillis, false); + } + + public void sleepPossibleScripThread(long sleepMillis, boolean runnablesOnly) { + if (Thread.currentThread() != getScriptThread()) { + sleepThread(sleepMillis); + } else { + long startedAt = System.currentTimeMillis(); + long millisPerInterval = 100; + while (startedAt + sleepMillis > System.currentTimeMillis()) { + sleepThread(millisPerInterval); + + //Check for new stuff + if (!runnablesOnly) { + //Only check if the session already started + if (session.isStarted()) { + session.checkForInteraction(); + } + } else { + TeaseRunnableHandler.getHandler().checkRunnables(); + } + } + } + } + + public void sleepScripThread(long sleepMillis) { + if (Thread.currentThread() != getScriptThread()) { + TeaseLogger.getLogger().log(Level.SEVERE, "Tried to sleep script thread from other thread."); + return; + } + + sleepThread(sleepMillis); + } + + public void waitScriptThread(long timeoutMillis) { + if (Thread.currentThread() != getScriptThread()) { + TeaseLogger.getLogger().log(Level.SEVERE, "Tried to wait script thread from other thread."); + return; + } + + waitThread(timeoutMillis); + } + + public void waitThread() { + waitThread(0); + } + + public void waitThread(long timeoutMillis) { + synchronized (Thread.currentThread()) { + try { + Thread.currentThread().wait(timeoutMillis); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + public void sleepThread(long sleepMillis) { + synchronized (Thread.currentThread()) { + try { + Thread.sleep(sleepMillis); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + public MainGuiController getController() { + return controller; + } + + public void initializeNewSession() { + this.session = new Session(); + + this.session.statisticsManager = new StatisticsManager(); + + //End everything such as metronome and stroking + StrokeHandler.getHandler().setEdging(false); + StrokeHandler.getHandler().stopMetronome(); + + //Show no picture + MediaHandler.getHandler().showPicture(null); + + session.setActivePersonality((Personality) controller.getPersonalityChoiceBox().getSelectionModel().getSelectedItem()); + + //Reset the temporary variables + session.getActivePersonality().getVariableHandler().clearTemporaryVariables(); + AppearanceSettings.loadSelectedTheme(); + } + + public void setTTS(boolean value) { + TextToSpeechEnabled = value; + } + + public void setScriptThread(Thread scriptThread) { + this.scriptThread = scriptThread; + System.out.println("Set script thread!"); + } + + public Thread getScriptThread() { + return scriptThread; + } + + public Thread getMainThread() { + return mainThread; + } + + public ConfigHandler getConfigHandler() { + return configHandler; + } + + public MediaCollection getMediaCollection() { + return mediaCollection; + } + + public Session getSession() { + return session; + } + + public Scene getScene() { + return mainScene; + } + + public boolean isResponsesDisabled() { + return responsesDisabled; + } + + public void setResponsesDisabled(boolean responsesDisabled) { + this.responsesDisabled = responsesDisabled; + } + + public static TeaseAI getApplication() { + return application; + } +} diff --git a/src/me/goddragon/teaseai/api/chat/Answer.java b/src/main/java/me/goddragon/teaseai/api/chat/Answer.java similarity index 87% rename from src/me/goddragon/teaseai/api/chat/Answer.java rename to src/main/java/me/goddragon/teaseai/api/chat/Answer.java index 3a1cdc0..dd70ab9 100644 --- a/src/me/goddragon/teaseai/api/chat/Answer.java +++ b/src/main/java/me/goddragon/teaseai/api/chat/Answer.java @@ -15,17 +15,18 @@ public class Answer { private long startedAt; private boolean timeout = false; - public Answer() {} + public Answer() { + } public Answer(long timeoutSeconds) { - this.millisTimeout = timeoutSeconds*1000; + this.millisTimeout = timeoutSeconds * 1000; } public void addOption(String optionMessage) { addOption(optionMessage, optionMessage); } - public void addOption(String optionName, String optionMessage) { + public static void addOption(String optionName, String optionMessage) { TeaseAI.application.runOnUIThread(new Runnable() { @Override public void run() { @@ -48,6 +49,8 @@ public void loop() { this.answer = null; this.timeout = false; + TeaseAI.application.setResponsesDisabled(true); + startedAt = System.currentTimeMillis(); TeaseAI.application.waitPossibleScripThread(millisTimeout); checkTimeout(); @@ -127,7 +130,8 @@ public boolean isInteger() { try { Integer.parseInt(answer); return true; - } catch (NumberFormatException ex) {} + } catch (NumberFormatException ex) { + } return false; } @@ -136,7 +140,8 @@ public boolean isInt() { try { Integer.parseInt(answer); return true; - } catch (NumberFormatException ex) {} + } catch (NumberFormatException ex) { + } return false; } @@ -145,7 +150,8 @@ public boolean isDouble() { try { Double.parseDouble(answer); return true; - } catch (NumberFormatException ex) {} + } catch (NumberFormatException ex) { + } return false; } @@ -157,7 +163,8 @@ public int getInteger() { public int getInt() { try { return Integer.parseInt(answer); - } catch (NumberFormatException ex) {} + } catch (NumberFormatException ex) { + } return 0; } @@ -165,7 +172,8 @@ public int getInt() { public double getDouble() { try { return Double.parseDouble(answer); - } catch (NumberFormatException ex) {} + } catch (NumberFormatException ex) { + } return 0; } @@ -175,7 +183,7 @@ public long getMillisTimeout() { } public void setTimeoutSeconds(long timeoutSeconds) { - this.millisTimeout = timeoutSeconds*1000; + this.millisTimeout = timeoutSeconds * 1000; } public void setMillisTimeout(long millisTimeout) { @@ -195,7 +203,7 @@ public void setStartedAt(long startedAt) { } public void checkTimeout() { - if(System.currentTimeMillis() - startedAt >= millisTimeout - 100 && millisTimeout > 0) { + if (System.currentTimeMillis() - startedAt >= millisTimeout - 100 && millisTimeout > 0) { timeout = true; } } diff --git a/src/me/goddragon/teaseai/api/chat/ChatHandler.java b/src/main/java/me/goddragon/teaseai/api/chat/ChatHandler.java similarity index 79% rename from src/me/goddragon/teaseai/api/chat/ChatHandler.java rename to src/main/java/me/goddragon/teaseai/api/chat/ChatHandler.java index 30bd5c0..10dce22 100644 --- a/src/me/goddragon/teaseai/api/chat/ChatHandler.java +++ b/src/main/java/me/goddragon/teaseai/api/chat/ChatHandler.java @@ -1,368 +1,417 @@ -package me.goddragon.teaseai.api.chat; - -import javafx.collections.ListChangeListener; -import javafx.scene.Node; -import javafx.scene.control.ScrollPane; -import javafx.scene.text.Text; -import javafx.scene.text.TextFlow; -import me.goddragon.teaseai.TeaseAI; -import me.goddragon.teaseai.utils.TeaseLogger; - -import java.util.*; -import java.util.logging.Level; - -/** - * Created by GodDragon on 22.03.2018. - */ -public class ChatHandler { - - public static final int SUB_SENDER_ID = 0; - public static final int MAIN_DOM_SENDER_ID = 1; - - private static ChatHandler handler = new ChatHandler(); - private TypeSpeed typeSpeed = TypeSpeed.valueOf(TeaseAI.application.DEFAULT_TYPE_SPEED.getValue()); - - /** - * Millis waited after each message by default - */ - private long messagePauseMillis = 1000; - - /** - * Millis waited after each message per character by default - */ - private long perMessageCharacterPauseMillis = 100; - - /** - * Is the default pause after each message calculated based on each message or one default value - */ - private boolean pausePerMessageCharacter = true; - - private HashMap senders = new HashMap<>(); - - /** - * Holds all messages that are only temporary displayed - */ - private Collection temporaryMessages = new HashSet<>(); - - private Answer currentCallback = null; - - private ChatParticipant currentDom = null; - - public ChatHandler() { - TextFlow textFlow = TeaseAI.application.getController().getChatWindow(); - ScrollPane textContainer = TeaseAI.application.getController().getChatScrollPane(); - textFlow.getChildren().addListener( - (ListChangeListener) ((change) -> { - textFlow.layout(); - textContainer.layout(); - textContainer.setVvalue(1.0f); - })); - textContainer.setContent(textFlow); - - //Initial space in chat - addText(new Text(" ")); - } - - public void load() { - registerSender(new ChatParticipant(0, SenderType.SUB, new Contact("sub", "Sub Name"))); - Contact dommeContact = new Contact("dom", "Dom Name"); - registerSender(new ChatParticipant(1, SenderType.DOM, dommeContact)); - registerSender(new ChatParticipant(2, SenderType.DOM, new Contact("dommeFriend1", "Emma"))); - registerSender(new ChatParticipant(3, SenderType.DOM, new Contact("dommeFriend2", "Staicy"))); - registerSender(new ChatParticipant(4, SenderType.DOM, new Contact("dommeFriend3", "Amara"))); - } - - public void registerSender(ChatParticipant chatSender) { - senders.put(chatSender.getId(), chatSender); - } - - public ChatParticipant getParticipantByName(String name) { - for (ChatParticipant sender : senders.values()) { - if (sender.getName().equalsIgnoreCase(name)) { - return sender; - } - } - - throw new IllegalArgumentException("Chat participant with name " + name + " does not exist."); - } - - public ChatParticipant getParticipantById(int id) { - if (!senders.containsKey(id)) { - TeaseLogger.getLogger().log(Level.SEVERE, "Chat participant with id " + id + " does not exist."); - return null; - } - - return senders.get(id); - } - - public ChatParticipant getSubParticipant() { - return getParticipantById(SUB_SENDER_ID); - } - - public ChatParticipant getMainDomParticipant() { - return getParticipantById(MAIN_DOM_SENDER_ID); - } - - public ChatParticipant getSelectedSender() { - return currentDom != null? currentDom : getMainDomParticipant(); - } - - public void addText(String message) { - addText(new Text(message)); - } - - public void addText(Text text) { - addText(text, false); - } - - public void addText(Text text, boolean temporary) { - TextFlow textFlow = TeaseAI.application.getController().getChatWindow(); - - TeaseAI.application.runOnUIThread(new Runnable() { - @Override - public void run() { - if(!textFlow.getChildren().contains(text)) { - if(!temporary) { - removeAllTemporaryMessages(); - } - - textFlow.getChildren().add(text); - - if(!temporary) { - addAllTemporaryMessages(); - } - } else { - TeaseLogger.getLogger().log(Level.SEVERE, "Tried to add same text instance multiple times."); - } - } - }); - - if(!temporary) { - TeaseLogger.getLogger().log(Level.FINE, text.getText()); - } - } - - public void addText(Text... text) { - TextFlow textFlow = TeaseAI.application.getController().getChatWindow(); - - TeaseAI.application.runOnUIThread(new Runnable() { - @Override - public void run() { - removeAllTemporaryMessages(); - - textFlow.getChildren().addAll(text); - - addAllTemporaryMessages(); - } - }); - - String resultingText = ""; - for(Text textPiece : text) { - resultingText += textPiece.getText(); - } - - TeaseLogger.getLogger().log(Level.FINE, resultingText); - } - - public void addLine(String message) { - addLine(new Text(message)); - } - - public void addLine(Text text) { - TextFlow textFlow = TeaseAI.application.getController().getChatWindow(); - - TeaseAI.application.runOnUIThread(new Runnable() { - @Override - public void run() { - if(!textFlow.getChildren().contains(text)) { - removeAllTemporaryMessages(); - textFlow.getChildren().add(text); - nextRow(); - addAllTemporaryMessages(); - } else { - TeaseLogger.getLogger().log(Level.SEVERE, "Tried to add same text instance multiple times."); - } - } - }); - - TeaseLogger.getLogger().log(Level.FINE, text.getText()); - } - - public void addLine(Text... text) { - addLine(Arrays.asList(text)); - } - - public void addLine(List text) { - TextFlow textFlow = TeaseAI.application.getController().getChatWindow(); - TeaseAI.application.runOnUIThread(new Runnable() { - @Override - public void run() { - removeAllTemporaryMessages(); - - textFlow.getChildren().addAll(text); - nextRow(); - - addAllTemporaryMessages(); - } - }); - - String resultingText = ""; - for(Text textPiece : text) { - resultingText += textPiece.getText(); - } - - TeaseLogger.getLogger().log(Level.FINE, resultingText); - } - - public void addTemporaryMessage(Text text) { - addText(text, true); - synchronized (temporaryMessages) { - temporaryMessages.add(text); - } - } - - public void removeTemporaryMessage(Text text) { - TeaseAI.application.runOnUIThread(new Runnable() { - @Override - public void run() { - TeaseAI.application.getController().getChatWindow().getChildren().remove(text); - } - }); - - synchronized (temporaryMessages) { - temporaryMessages.remove(text); - } - } - - public void removeAllTemporaryMessages() { - synchronized (temporaryMessages) { - for (Text text : temporaryMessages) { - TeaseAI.application.getController().getChatWindow().getChildren().remove(text); - } - } - } - - public void addAllTemporaryMessages() { - TextFlow textFlow = TeaseAI.application.getController().getChatWindow(); - - synchronized (temporaryMessages) { - for (Text text : temporaryMessages) { - //Only add it if it is not yet existent - if (!textFlow.getChildren().contains(text)) { - TeaseAI.application.getController().getChatWindow().getChildren().add(text); - } - } - } - } - - public void removeLatestLine() { - removeLine(TeaseAI.application.getController().getChatWindow().getChildren().size() - 1); - } - - public void removeLine(int index) { - TextFlow textFlow = TeaseAI.application.getController().getChatWindow(); - - if (index > textFlow.getChildren().size() - 1) { - throw new IndexOutOfBoundsException("There are no " + (index + 1) + " rows of chat thus we were unable to remove the line."); - } - - TeaseAI.application.runOnUIThread(new Runnable() { - @Override - public void run() { - textFlow.getChildren().remove(index); - } - }); - } - - public void onSubMessage(String message) { - if (currentCallback != null && currentCallback.getAnswer() == null) { - currentCallback.setAnswer(message); - - - //Wake the script thread, the user might want some response - synchronized (TeaseAI.application.getScriptThread()) { - TeaseAI.application.getScriptThread().notify(); - } - } - } - - public long getMillisToPause(String message) { - if (!pausePerMessageCharacter) { - return messagePauseMillis; - } else { - return perMessageCharacterPauseMillis * message.trim().length(); - } - } - - public Collection getParticipants() { - return senders.values(); - } - - public Answer getCurrentCallback() { - return currentCallback; - } - - public TypeSpeed getTypeSpeed() { - return typeSpeed; - } - - public void setCurrentCallback(Answer currentCallback) { - this.currentCallback = currentCallback; - } - - public long getMessagePauseMillis() { - return messagePauseMillis; - } - - public void setMessagePauseMillis(long messagePauseMillis) { - this.messagePauseMillis = messagePauseMillis; - } - - public void setDefaultWaitSeconds(int seconds) { - setMessagePauseMillis(seconds * 1000); - } - - public long getPerMessageCharacterPauseMillis() { - return perMessageCharacterPauseMillis; - } - - public void setPerMessageCharacterPauseMillis(long perMessageCharacterPauseMillis) { - this.perMessageCharacterPauseMillis = perMessageCharacterPauseMillis; - } - - public void setPerMessageCharacterPauseSeconds(long perMessageCharacterPauseSeconds) { - setPerMessageCharacterPauseMillis(perMessageCharacterPauseSeconds * 1000); - } - - public boolean isPausePerMessageCharacter() { - return pausePerMessageCharacter; - } - - public void setPausePerMessageCharacter(boolean pausePerMessageCharacter) { - this.pausePerMessageCharacter = pausePerMessageCharacter; - } - - public void nextRow() { - addText("\n "); - } - - public ChatParticipant getCurrentDom() { - return currentDom; - } - - public void setCurrentDom(ChatParticipant currentDom) { - this.currentDom = currentDom; - } - - public static ChatHandler getHandler() { - return handler; - } - - public HashMap getSenders() { - return senders; - } - - public static void setHandler(ChatHandler handler) { - ChatHandler.handler = handler; - } -} +package me.goddragon.teaseai.api.chat; + +import javafx.collections.ListChangeListener; +import javafx.scene.Node; +import javafx.scene.control.ScrollPane; +import javafx.scene.paint.Color; +import javafx.scene.text.Text; +import javafx.scene.text.TextFlow; +import me.goddragon.teaseai.TeaseAI; +import me.goddragon.teaseai.api.scripts.personality.PersonalityManager; +import me.goddragon.teaseai.api.texttospeech.TextToSpeech; +import me.goddragon.teaseai.utils.TeaseLogger; + +import java.util.*; +import java.util.logging.Level; + +/** + * Created by GodDragon on 22.03.2018. + */ +public class ChatHandler { + + public static final int SUB_SENDER_ID = 0; + public static final int MAIN_DOM_SENDER_ID = 1; + + private static ChatHandler handler = new ChatHandler(); + + private TypeSpeed typeSpeed = TypeSpeed.valueOf(TeaseAI.application.DEFAULT_TYPE_SPEED.getValue()); + + private Color defaultChatColor = Color.BLACK; + + private Color dateColor; + /** + * Millis waited after each message by default + */ + private long messagePauseMillis = 1000; + + /** + * Millis waited after each message per character by default + */ + private long perMessageCharacterPauseMillis = 100; + + /** + * Is the default pause after each message calculated based on each message or one default value + */ + private boolean pausePerMessageCharacter = true; + + private HashMap senders = new HashMap<>(); + + /** + * Holds all messages that are only temporary displayed + */ + private Collection temporaryMessages = new HashSet<>(); + + private Answer currentCallback = null; + + private ChatParticipant currentDom = null; + private TextToSpeech textToSpeech; + + public ChatHandler() { + this.dateColor = Color.DARKGRAY; + + TextFlow textFlow = TeaseAI.application.getController().getChatWindow(); + ScrollPane textContainer = TeaseAI.application.getController().getChatScrollPane(); + textFlow.getChildren().addListener( + (ListChangeListener) ((change) -> { + textFlow.layout(); + textContainer.layout(); + textContainer.setVvalue(1.0f); + })); + textContainer.setContent(textFlow); + + //Initial space in chat + // TODO Can this be done later? Can lead to NoClassDef error when ctor isn't finished when runnable runs + addText(new Text(" ")); + textToSpeech = new TextToSpeech(); + textToSpeech.setVoice("dfki-prudence-hsmm"); + } + + public void load() { + PersonalityManager.getManager().getProgressUpdate().accept(0, 5); + + registerSender(new ChatParticipant(0, SenderType.SUB, new Contact("sub", "Sub Name")).setNameColor(Color.DARKCYAN)); + PersonalityManager.getManager().getProgressUpdate().accept(1, 5); + + Contact dommeContact = new Contact("dom", "Dom Name"); + registerSender(new ChatParticipant(1, SenderType.DOM, dommeContact).setNameColor(Color.RED)); + PersonalityManager.getManager().getProgressUpdate().accept(2, 5); + + registerSender(new ChatParticipant(2, SenderType.DOM, new Contact("dommeFriend1", "Emma")).setNameColor(Color.ORANGE)); + PersonalityManager.getManager().getProgressUpdate().accept(3, 5); + + registerSender(new ChatParticipant(3, SenderType.DOM, new Contact("dommeFriend2", "Staicy")).setNameColor(Color.LIGHTGREEN)); + PersonalityManager.getManager().getProgressUpdate().accept(4, 5); + + registerSender(new ChatParticipant(4, SenderType.DOM, new Contact("dommeFriend3", "Amara")).setNameColor(Color.MEDIUMVIOLETRED)); + PersonalityManager.getManager().getProgressUpdate().accept(5, 5); + } + + public void registerSender(ChatParticipant chatSender) { + senders.put(chatSender.getId(), chatSender); + } + + public ChatParticipant getParticipantByName(String name) { + for (ChatParticipant sender : senders.values()) { + if (sender.getName().equalsIgnoreCase(name)) { + return sender; + } + } + + throw new IllegalArgumentException("Chat participant with name " + name + " does not exist."); + } + + public ChatParticipant getParticipantById(int id) { + if (!senders.containsKey(id)) { + TeaseLogger.getLogger().log(Level.SEVERE, "Chat participant with id " + id + " does not exist."); + return null; + } + + return senders.get(id); + } + + public ChatParticipant getSubParticipant() { + return getParticipantById(SUB_SENDER_ID); + } + + public ChatParticipant getMainDomParticipant() { + return getParticipantById(MAIN_DOM_SENDER_ID); + } + + public ChatParticipant getSelectedSender() { + return currentDom != null ? currentDom : getMainDomParticipant(); + } + + public void addText(String message) { + addText(new Text(message)); + } + + public void addText(Text text) { + addText(text, false); + } + + public void addText(Text text, boolean temporary) { + TextFlow textFlow = TeaseAI.application.getController().getChatWindow(); + + TeaseAI.application.runOnUIThread(new Runnable() { + @Override + public void run() { + if (!textFlow.getChildren().contains(text)) { + if (!temporary) { + removeAllTemporaryMessages(); + } + + textFlow.getChildren().add(text); + + if (!temporary) { + addAllTemporaryMessages(); + } + } else { + TeaseLogger.getLogger().log(Level.SEVERE, "Tried to add same text instance multiple times."); + } + } + }); + + if (!temporary) { + TeaseLogger.getLogger().log(Level.FINE, text.getText()); + } + } + + public void addText(Text... text) { + TextFlow textFlow = TeaseAI.application.getController().getChatWindow(); + + TeaseAI.application.runOnUIThread(new Runnable() { + @Override + public void run() { + removeAllTemporaryMessages(); + + textFlow.getChildren().addAll(text); + + addAllTemporaryMessages(); + } + }); + + String resultingText = ""; + for (Text textPiece : text) { + resultingText += textPiece.getText(); + } + + TeaseLogger.getLogger().log(Level.FINE, resultingText); + } + + public void addLine(String message) { + addLine(new Text(message)); + } + + public void addLine(Text text) { + TextFlow textFlow = TeaseAI.application.getController().getChatWindow(); + + TeaseAI.application.runOnUIThread(new Runnable() { + @Override + public void run() { + if (!textFlow.getChildren().contains(text)) { + textToSpeech.speak(text.getText(), 1.0f, false, true); + removeAllTemporaryMessages(); + textFlow.getChildren().add(text); + nextRow(); + addAllTemporaryMessages(); + } else { + TeaseLogger.getLogger().log(Level.SEVERE, "Tried to add same text instance multiple times."); + } + } + }); + + TeaseLogger.getLogger().log(Level.FINE, text.getText()); + } + + public void addLine(Text... text) { + addLine(Arrays.asList(text)); + } + + public void addLine(List text) { + TextFlow textFlow = TeaseAI.application.getController().getChatWindow(); + TeaseAI.application.runOnUIThread(new Runnable() { + @Override + public void run() { + removeAllTemporaryMessages(); + /*for (Text t: text) + { + if (t.getText() != null) + { + textToSpeech.speak(t.getText(), 1.0f, false, false); + } + }*/ + textFlow.getChildren().addAll(text); + nextRow(); + + addAllTemporaryMessages(); + } + }); + + String resultingText = ""; + for (Text textPiece : text) { + resultingText += textPiece.getText(); + } + + TeaseLogger.getLogger().log(Level.FINE, resultingText); + } + + public void addTemporaryMessage(Text text) { + addText(text, true); + synchronized (temporaryMessages) { + temporaryMessages.add(text); + } + } + + public void removeTemporaryMessage(Text text) { + TeaseAI.application.runOnUIThread(new Runnable() { + @Override + public void run() { + TeaseAI.application.getController().getChatWindow().getChildren().remove(text); + } + }); + + synchronized (temporaryMessages) { + temporaryMessages.remove(text); + } + } + + public void removeAllTemporaryMessages() { + synchronized (temporaryMessages) { + for (Text text : temporaryMessages) { + TeaseAI.application.getController().getChatWindow().getChildren().remove(text); + } + } + } + + public void addAllTemporaryMessages() { + TextFlow textFlow = TeaseAI.application.getController().getChatWindow(); + + synchronized (temporaryMessages) { + for (Text text : temporaryMessages) { + //Only add it if it is not yet existent + if (!textFlow.getChildren().contains(text)) { + TeaseAI.application.getController().getChatWindow().getChildren().add(text); + } + } + } + } + + public void removeLatestLine() { + removeLine(TeaseAI.application.getController().getChatWindow().getChildren().size() - 1); + } + + public void removeLine(int index) { + TextFlow textFlow = TeaseAI.application.getController().getChatWindow(); + + if (index > textFlow.getChildren().size() - 1) { + throw new IndexOutOfBoundsException("There are no " + (index + 1) + " rows of chat thus we were unable to remove the line."); + } + + TeaseAI.application.runOnUIThread(new Runnable() { + @Override + public void run() { + textFlow.getChildren().remove(index); + } + }); + } + + public void onSubMessage(String message) { + TeaseAI.application.setResponsesDisabled(false); + + if (currentCallback != null && currentCallback.getAnswer() == null) { + currentCallback.setAnswer(message); + + //Wake the script thread, the user might want some response + synchronized (TeaseAI.application.getScriptThread()) { + TeaseAI.application.getScriptThread().notify(); + } + } + } + + public long getMillisToPause(String message) { + if (!pausePerMessageCharacter) { + return messagePauseMillis; + } else { + return perMessageCharacterPauseMillis * message.trim().length(); + } + } + + public Collection getParticipants() { + return senders.values(); + } + + public Answer getCurrentCallback() { + return currentCallback; + } + + public TypeSpeed getTypeSpeed() { + return typeSpeed; + } + + public void setCurrentCallback(Answer currentCallback) { + this.currentCallback = currentCallback; + } + + public long getMessagePauseMillis() { + return messagePauseMillis; + } + + public void setMessagePauseMillis(long messagePauseMillis) { + this.messagePauseMillis = messagePauseMillis; + } + + public void setDefaultWaitSeconds(int seconds) { + setMessagePauseMillis(seconds * 1000); + } + + public long getPerMessageCharacterPauseMillis() { + return perMessageCharacterPauseMillis; + } + + public void setPerMessageCharacterPauseMillis(long perMessageCharacterPauseMillis) { + this.perMessageCharacterPauseMillis = perMessageCharacterPauseMillis; + } + + public void setPerMessageCharacterPauseSeconds(long perMessageCharacterPauseSeconds) { + setPerMessageCharacterPauseMillis(perMessageCharacterPauseSeconds * 1000); + } + + public boolean isPausePerMessageCharacter() { + return pausePerMessageCharacter; + } + + public void setPausePerMessageCharacter(boolean pausePerMessageCharacter) { + this.pausePerMessageCharacter = pausePerMessageCharacter; + } + + public void nextRow() { + addText("\n "); + } + + public ChatParticipant getCurrentDom() { + return currentDom; + } + + public void setCurrentDom(ChatParticipant currentDom) { + this.currentDom = currentDom; + } + + public static ChatHandler getHandler() { + return handler; + } + + public HashMap getSenders() { + return senders; + } + + public Color getDefaultChatColor() { + return defaultChatColor; + } + + public Color getDateColor() { + return dateColor; + } + + public void setDateColor(Color newColor) { + this.dateColor = newColor; + } + + public void setDefaultChatColor(Color newColor) { + this.defaultChatColor = newColor; + } + + public static void setHandler(ChatHandler handler) { + ChatHandler.handler = handler; + } + +} diff --git a/src/me/goddragon/teaseai/api/chat/ChatParticipant.java b/src/main/java/me/goddragon/teaseai/api/chat/ChatParticipant.java similarity index 71% rename from src/me/goddragon/teaseai/api/chat/ChatParticipant.java rename to src/main/java/me/goddragon/teaseai/api/chat/ChatParticipant.java index 8a8c077..a8655cd 100644 --- a/src/me/goddragon/teaseai/api/chat/ChatParticipant.java +++ b/src/main/java/me/goddragon/teaseai/api/chat/ChatParticipant.java @@ -1,363 +1,386 @@ -package me.goddragon.teaseai.api.chat; - -import javafx.scene.paint.Color; -import javafx.scene.text.Font; -import javafx.scene.text.FontWeight; -import javafx.scene.text.Text; -import me.goddragon.teaseai.TeaseAI; -import me.goddragon.teaseai.api.chat.response.Response; -import me.goddragon.teaseai.api.chat.response.ResponseHandler; -import me.goddragon.teaseai.api.chat.vocabulary.VocabularyHandler; -import me.goddragon.teaseai.api.media.MediaHandler; -import me.goddragon.teaseai.api.picture.PictureSet; -import me.goddragon.teaseai.api.picture.TaggedPicture; -import me.goddragon.teaseai.api.session.Session; -import me.goddragon.teaseai.utils.RandomUtils; -import me.goddragon.teaseai.utils.TeaseLogger; - -import java.io.File; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.logging.Level; - -/** - * Created by GodDragon on 22.03.2018. - */ -public class ChatParticipant { - - private static int latestId = 0; - - private int id; - private String name; - private Contact contact; - private SenderType type; - private boolean active = false; - private TypeSpeed typeSpeed; - private Color chatColor; - - private PictureSet pictureSet; - - public ChatParticipant(SenderType type, Contact contact) { - this(latestId + 1, type, contact); - } - - public ChatParticipant(String name, SenderType type) { - this(latestId + 1, name, type, null); - } - - public ChatParticipant(int id, SenderType type, Contact contact) { - this(id, contact.NAME.getValue(), type, contact); - } - - public ChatParticipant(int id, String name, SenderType type, Contact contact) { - this.id = id; - - //Update the latest id - latestId = Math.max(id, latestId); - - this.name = name; - this.type = type; - this.contact = contact; - this.typeSpeed = ChatHandler.getHandler().getTypeSpeed(); - - switch (id) { - case 0: - chatColor = Color.DARKCYAN; - break; - case 1: - chatColor = Color.RED; - break; - case 2: - chatColor = Color.ORANGE; - break; - case 3: - chatColor = Color.LIGHTGREEN; - break; - case 4: - chatColor = Color.MEDIUMVIOLETRED; - break; - case 5: - chatColor = Color.TEAL; - break; - default: - chatColor = Color.SALMON; - break; - } - - if (type == SenderType.SUB) { - active = true; - } - - choosePictureSet(); - } - - public ChatParticipant(int id, String name, SenderType type, Color chatColor, Contact contact) { - this.id = id; - this.name = name; - this.type = type; - this.chatColor = chatColor; - - if (type == SenderType.SUB) { - active = true; - } - - choosePictureSet(); - } - - public void sendJoin() { - sendInteract("joined"); - } - - public void sendLeave() { - sendInteract("left"); - } - - public void sendInteract(String type) { - Text nameText = new Text(name + " "); - nameText.setFont(Font.font(null, FontWeight.BOLD, TeaseAI.application.CHAT_TEXT_SIZE.getDouble() + 2)); - nameText.setFill(chatColor); - - Text messageText = new Text(type + " the chat room."); - messageText.setFill(Color.AQUA); - messageText.setFont(Font.font(null, FontWeight.BOLD, TeaseAI.application.CHAT_TEXT_SIZE.getDouble() + 2)); - - ChatHandler.getHandler().addLine(nameText, messageText); - } - - public void sendMessage(String message) { - sendMessage(message, ChatHandler.getHandler().getMillisToPause(message)); - } - - public void sendMessage(String message, int secondsToWait) { - sendMessage(message, secondsToWait * 1000L); - } - - public void sendMessage(String message, long millisToWait) { - //We need to wait BEFORE we replace the vocabularies. Otherwise any code triggered by the vocab will execute before the message is send - startTyping(message); - - //Replace all vocabularies - message = VocabularyHandler.getHandler().replaceAllVocabularies(message); - - Text messageText = new Text(message); - messageText.setFont(Font.font(null, FontWeight.NORMAL, TeaseAI.application.CHAT_TEXT_SIZE.getDouble())); - - sendMessage(message, messageText, millisToWait); - } - - public void sendMessage(String rawMessage, Text message, long millisToWait) { - sendMessage(rawMessage, millisToWait, message); - } - - public void sendMessage(String rawMessage, long millisToWait, Text... messages) { - sendMessage(rawMessage, millisToWait, Arrays.asList(messages)); - } - - public void sendMessage(String rawMessage, long millisToWait, List messages) { - DateFormat dateFormat = new SimpleDateFormat("hh:mm a"); - - Text dateText = new Text(dateFormat.format(new Date()) + " "); - dateText.setFill(Color.DARKGRAY); - dateText.setFont(Font.font(null, FontWeight.MEDIUM, TeaseAI.application.CHAT_TEXT_SIZE.getDouble())); - Text text = new Text(name + ": "); - - text.setFill(chatColor); - - text.setFont(Font.font(null, FontWeight.BOLD, TeaseAI.application.CHAT_TEXT_SIZE.getDouble() + 1)); - //Check whether we can find a response fitting right now - if (type == SenderType.SUB) { - Response response = ResponseHandler.getHandler().checkMessageForResponse(rawMessage); - if (response != null) { - //Set the message of the response so we know what triggered it later on - response.setMessage(rawMessage); - - //Queue the response so we can call it later - ResponseHandler.getHandler().addQueuedResponse(response); - } - } else { - //If the dom sends a message we will check for queued responses that need to be handle before continuing - - //This should always run on the script thread but maybe I am stupid so we will catch this here - if (Thread.currentThread() != TeaseAI.application.getScriptThread()) { - throw new IllegalStateException("Dom can only send messages on the script thread"); - } - - Response queuedResponse = ResponseHandler.getHandler().getLatestQueuedResponse(); - if (queuedResponse != null) { - ResponseHandler.getHandler().removeQueuedResponse(queuedResponse); - - //If this returns true the trigger was successful and we won't send the current message that was supposed to be sent - if (queuedResponse.trigger()) { - return; - } - } - } - - List lineMessages = new ArrayList<>(); - lineMessages.add(dateText); - lineMessages.add(text); - lineMessages.addAll(messages); - ChatHandler.getHandler().addLine(lineMessages); - - if (type != SenderType.SUB && !MediaHandler.getHandler().isImagesLocked() && pictureSet != null) { - Session session = TeaseAI.application.getSession(); - TaggedPicture taggedPicture = session.getActivePersonality().getPictureSelector().getPicture(session, this); - if (taggedPicture != null) { - MediaHandler.getHandler().showPicture(session.getActivePersonality().getPictureSelector().getPicture(session, this).getFile()); - } - } - - //Wait some time after this message before continuing (only if it is not the sub who send the message) - if (millisToWait > 0 && type != SenderType.SUB) { - TeaseAI.application.sleepPossibleScripThread(millisToWait); - } - } - - public Answer sendInput(String message) { - return sendInput(message, 0); - } - - public Answer sendInput(String message, int timeoutSeconds) { - return sendInput(message, new Answer(timeoutSeconds)); - } - - public Answer sendInput(String message, Answer answer) { - //No waiting here because we will wait later on anyway - sendMessage(message, 0); - - ChatHandler.getHandler().setCurrentCallback(answer); - - //Reset timeout (normally the answer is a new object, but we don't know whether they might reuse an old answer) - answer.setTimeout(false); - - //Reset the latest answer message - answer.setAnswer(null); - answer.setStartedAt(System.currentTimeMillis()); - - //Wait for answer - TeaseAI.application.waitPossibleScripThread(answer.getMillisTimeout()); - answer.checkTimeout(); - - return answer; - } - - private void startTyping(String message) { - if (type == SenderType.SUB) { - return; - } - - long millisToWait = typeSpeed.getTypeDuration(message); - - if (millisToWait > 0) { - Text text = new Text(name + " is typing..."); - text.setFill(Color.AQUA); - text.setFont(Font.font(null, FontWeight.BOLD, TeaseAI.application.CHAT_TEXT_SIZE.getDouble() + 2)); - ChatHandler.getHandler().addTemporaryMessage(text); - - TeaseAI.application.sleepPossibleScripThread(millisToWait, true); - - ChatHandler.getHandler().removeTemporaryMessage(text); - } - } - - public int getId() { - return id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public SenderType getType() { - return type; - } - - public void setType(SenderType type) { - this.type = type; - } - - public boolean isActive() { - return active; - } - - public void setActive(boolean active) { - if (type == SenderType.SUB) { - throw new IllegalStateException("Sub cannot be inactive in chat"); - } - - this.active = active; - } - - public TypeSpeed getTypeSpeed() { - return typeSpeed; - } - - public void setTypeSpeed(TypeSpeed typeSpeed) { - this.typeSpeed = typeSpeed; - } - - public Color getChatColor() { - return chatColor; - } - - public void setChatColor(Color chatColor) { - this.chatColor = chatColor; - } - - public Contact getContact() { - return contact; - } - - public void choosePictureSet() { - File imageFolder = contact == null? null : contact.getImageFolder(); - if (imageFolder == null || !imageFolder.exists()) { - return; - } - - List pictureSets = new ArrayList<>(); - for (File file : imageFolder.listFiles((current, name) -> new File(current, name).isDirectory())) { - PictureSet pictureSet = new PictureSet(file); - - //No pictures => ignore the set - if(pictureSet.getTaggedPictures().isEmpty()) { - continue; - } - - pictureSets.add(pictureSet); - } - - this.pictureSet = null; - TeaseLogger.getLogger().log(Level.INFO, "Loaded " + pictureSets.size() + " picture sets for " + name); - - if (!pictureSets.isEmpty()) { - int loops = 0; - while (this.pictureSet == null && loops < 20) { - PictureSet pictureSet = pictureSets.get(RandomUtils.randInt(0, pictureSets.size() - 1)); - - if (!pictureSet.getTaggedPictures().isEmpty()) { - this.pictureSet = pictureSet; - } - - loops++; - } - } - } - - public PictureSet getPictureSet() { - return pictureSet; - } - - public void setPictureSet(PictureSet pictureSet) { - this.pictureSet = pictureSet; - } - - @Override - public String toString() { - return name; - } -} +package me.goddragon.teaseai.api.chat; + +import javafx.scene.paint.Color; +import javafx.scene.text.Font; +import javafx.scene.text.FontWeight; +import javafx.scene.text.Text; +import me.goddragon.teaseai.TeaseAI; +import me.goddragon.teaseai.api.chat.response.Response; +import me.goddragon.teaseai.api.chat.response.ResponseHandler; +import me.goddragon.teaseai.api.chat.vocabulary.VocabularyHandler; +import me.goddragon.teaseai.api.media.MediaHandler; +import me.goddragon.teaseai.api.picture.PictureSet; +import me.goddragon.teaseai.api.picture.TaggedPicture; +import me.goddragon.teaseai.api.session.Session; +import me.goddragon.teaseai.api.texttospeech.TextToSpeech; +import me.goddragon.teaseai.utils.RandomUtils; +import me.goddragon.teaseai.utils.StringUtils; +import me.goddragon.teaseai.utils.TeaseLogger; + +import java.io.File; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.logging.Level; + +/** + * Created by GodDragon on 22.03.2018. + */ +public class ChatParticipant { + + private static int latestId = 0; + + private int id; + private String name; + private Contact contact; + private SenderType type; + private boolean active = false; + private TypeSpeed typeSpeed; + + private PictureSet pictureSet; + + private Color nameColor = Color.BLACK; + private TextToSpeech textToSpeech; + + public ChatParticipant(SenderType type, Contact contact) { + this(latestId + 1, type, contact); + } + + public ChatParticipant(String name, SenderType type) { + this(latestId + 1, name, type, null); + } + + public ChatParticipant(int id, SenderType type, Contact contact) { + this(id, contact.NAME.getValue(), type, contact); + } + + public ChatParticipant(int id, String name, SenderType type, Contact contact) { + this.id = id; + + //Update the latest id + latestId = Math.max(id, latestId); + + this.name = name; + this.type = type; + this.contact = contact; + this.typeSpeed = ChatHandler.getHandler().getTypeSpeed(); + + if (type == SenderType.SUB) { + active = true; + } + + choosePictureSet(); + textToSpeech = new TextToSpeech(); + textToSpeech.setVoice("dfki-prudence-hsmm"); + } + + public void sendJoin() { + sendInteract("joined"); + } + + public void sendLeave() { + sendInteract("left"); + } + + public void sendInteract(String type) { + Text nameText = new Text(name + " "); + nameText.setFont(Font.font(null, FontWeight.BOLD, TeaseAI.application.CHAT_TEXT_SIZE.getDouble() + 2)); + nameText.setFill(this.nameColor); + + Text messageText = new Text(type + " the chat room."); + messageText.setFill(Color.AQUA); + messageText.setFont(Font.font(null, FontWeight.BOLD, TeaseAI.application.CHAT_TEXT_SIZE.getDouble() + 2)); + + ChatHandler.getHandler().addLine(nameText, messageText); + } + + public void customMessage(String message, long delay, boolean showTyping) { + if (delay == -1) { + delay = ChatHandler.getHandler().getMillisToPause(message); + } + + message = VocabularyHandler.getHandler().replaceAllVocabularies(message); + + if (showTyping) { + startTyping(message); + } + + sendMessage(message, delay, StringUtils.processString(message)); + } + + public void sendMessage(String message) { + sendMessage(message, ChatHandler.getHandler().getMillisToPause(message)); + } + + public void sendMessage(String message, int secondsToWait) { + sendMessage(message, secondsToWait * 1000L); + } + + public void sendMessage(String message, long millisToWait) { + //We need to wait BEFORE we replace the vocabularies. Otherwise any code triggered by the vocab will execute before the message is send + startTyping(message); + + //Replace all vocabularies + message = VocabularyHandler.getHandler().replaceAllVocabularies(message); + + Text messageText = new Text(message); + messageText.setFont(Font.font(null, FontWeight.NORMAL, TeaseAI.application.CHAT_TEXT_SIZE.getDouble())); + messageText.setFill(ChatHandler.getHandler().getDefaultChatColor()); + + sendMessage(message, messageText, millisToWait); + } + + public void sendMessage(String rawMessage, Text message, long millisToWait) { + sendMessage(rawMessage, millisToWait, message); + } + + public void sendMessage(String rawMessage, long millisToWait, Text... messages) { + sendMessage(rawMessage, millisToWait, Arrays.asList(messages)); + } + + public void sendMessage(String rawMessage, long millisToWait, List messages) { + DateFormat dateFormat = new SimpleDateFormat("hh:mm a"); + + Text dateText = new Text(dateFormat.format(new Date()) + " "); + dateText.setFill(ChatHandler.getHandler().getDateColor()); + dateText.setFont(Font.font(null, FontWeight.MEDIUM, TeaseAI.application.CHAT_TEXT_SIZE.getDouble())); + Text text = new Text(name + ": "); + + text.setFill(this.nameColor); + + text.setFont(Font.font(null, FontWeight.BOLD, TeaseAI.application.CHAT_TEXT_SIZE.getDouble() + 1)); + //Check whether we can find a response fitting right now + if (this.type == SenderType.SUB ) { + Collection responses = ResponseHandler.getHandler().checkMessageForResponse(rawMessage); + + if (!responses.isEmpty()) { + for (Response response : responses) { + //Set the message of the response so we know what triggered it later on + response.setMessage(rawMessage); + + //Queue the response so we can call it later + ResponseHandler.getHandler().addQueuedResponse(response); + } + } + } else { + //If the dom sends a message we will check for queued responses that need to be handle before continuing + + //This should always run on the script thread but maybe I am stupid so we will catch this here + if (Thread.currentThread() != TeaseAI.application.getScriptThread()) { + throw new IllegalStateException("Dom can only send messages on the script thread"); + } + + + if (TeaseAI.getApplication().checkForNewResponses()) { + //If this returns true the trigger was successful and we won't send the current message that was supposed to be sent + return; + } + + /* + Response queuedResponse = ResponseHandler.getHandler().getLatestQueuedResponse(); + if (queuedResponse != null) { + ResponseHandler.getHandler().removeQueuedResponse(queuedResponse); + + + if (queuedResponse.trigger()) { + return; + } + }*/ + } + + List lineMessages = new ArrayList<>(); + lineMessages.add(dateText); + lineMessages.add(text); + + if (TeaseAI.application.TextToSpeechEnabled && id != 0) { + String toSpeak = ""; + + for (Text text2 : messages) { + toSpeak += text2.getText(); + } + + textToSpeech.speak(toSpeak, 1.0f, true, false); + } + + lineMessages.addAll(messages); + ChatHandler.getHandler().addLine(lineMessages); + + //TeaseLogger.getLogger().log(Level.INFO, "Current PictureSet:" + pictureSet); + if (type != SenderType.SUB && !MediaHandler.getHandler().isImagesLocked() && pictureSet != null) { + Session session = TeaseAI.application.getSession(); + TaggedPicture taggedPicture = session.getActivePersonality().getPictureSelector().getPicture(session, this); + if (taggedPicture != null) { + MediaHandler.getHandler().showPicture(taggedPicture.getFile()); + } + } + + //Wait some time after this message before continuing (only if it is not the sub who send the message) + if (millisToWait > 0 && type != SenderType.SUB) { + TeaseAI.application.sleepPossibleScripThread(millisToWait); + } + } + + public Answer sendInput(String message) { + return sendInput(message, 0); + } + + public Answer sendInput(String message, int timeoutSeconds) { + return sendInput(message, new Answer(timeoutSeconds)); + } + + public Answer sendInput(String message, Answer answer) { + //No waiting here because we will wait later on anyway + sendMessage(message, 0); + + ChatHandler.getHandler().setCurrentCallback(answer); + + //Reset timeout (normally the answer is a new object, but we don't know whether they might reuse an old answer) + answer.setTimeout(false); + + //Reset the latest answer message + answer.setAnswer(null); + answer.setStartedAt(System.currentTimeMillis()); + + //Wait for answer + TeaseAI.application.waitPossibleScripThread(answer.getMillisTimeout()); + answer.checkTimeout(); + + return answer; + } + + public Answer sendInput(String rawMessage, long timeoutSeconds) { + customMessage(rawMessage, 0,true); + Answer answer = new Answer(timeoutSeconds); + ChatHandler.getHandler().setCurrentCallback(answer); + + //Reset the latest answer message + answer.setAnswer(null); + answer.setStartedAt(System.currentTimeMillis()); + + //Wait for answer + TeaseAI.application.waitPossibleScripThread(answer.getMillisTimeout()); + answer.checkTimeout(); + + return answer; + } + + private void startTyping(String message) { + if (type == SenderType.SUB) { + return; + } + + long millisToWait = typeSpeed.getTypeDuration(message); + + if (millisToWait > 0) { + Text text = new Text(name + " is typing..."); + text.setFill(Color.AQUA); + text.setFont(Font.font(null, FontWeight.BOLD, TeaseAI.application.CHAT_TEXT_SIZE.getDouble() + 2)); + ChatHandler.getHandler().addTemporaryMessage(text); + + TeaseAI.application.sleepPossibleScripThread(millisToWait, true); + + ChatHandler.getHandler().removeTemporaryMessage(text); + } + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public SenderType getType() { + return type; + } + + public void setType(SenderType type) { + this.type = type; + } + + public boolean isActive() { + return active; + } + + public void setActive(boolean active) { + if (type == SenderType.SUB) { + throw new IllegalStateException("Sub cannot be inactive in chat"); + } + + this.active = active; + } + + public TypeSpeed getTypeSpeed() { + return typeSpeed; + } + + public void setTypeSpeed(TypeSpeed typeSpeed) { + this.typeSpeed = typeSpeed; + } + + public Contact getContact() { + return contact; + } + + public void choosePictureSet() { + File imageFolder = contact == null ? null : contact.getImageFolder(); + if (imageFolder == null || !imageFolder.exists()) { + return; + } + + List pictureSets = new ArrayList<>(); + for (File file : imageFolder.listFiles((current, name) -> new File(current, name).isDirectory())) { + PictureSet pictureSet = new PictureSet(file); + + //No pictures => ignore the set + if (pictureSet.getTaggedPictures().isEmpty() && pictureSet.getPicturesInFolder().length == 0) { + continue; + } + + pictureSets.add(pictureSet); + } + + this.pictureSet = null; + TeaseLogger.getLogger().log(Level.INFO, "Loaded " + pictureSets.size() + " picture sets for " + name); + + if (!pictureSets.isEmpty()) { + int loops = 0; + while (this.pictureSet == null && loops < 20) { + PictureSet pictureSet = pictureSets.get(RandomUtils.randInt(0, pictureSets.size() - 1)); + if (!pictureSet.getTaggedPictures().isEmpty() || pictureSet.getPicturesInFolder().length > 0) { + this.pictureSet = pictureSet; + } + + loops++; + } + } + } + + public PictureSet getPictureSet() { + return pictureSet; + } + + public void setPictureSet(PictureSet pictureSet) { + this.pictureSet = pictureSet; + } + + + public ChatParticipant setNameColor(Color nameColor) { + this.nameColor = nameColor; + return this; + } + + public Color getNameColor() { + return nameColor; + } + + @Override + public String toString() { + return name; + } +} diff --git a/src/me/goddragon/teaseai/api/chat/Contact.java b/src/main/java/me/goddragon/teaseai/api/chat/Contact.java similarity index 90% rename from src/me/goddragon/teaseai/api/chat/Contact.java rename to src/main/java/me/goddragon/teaseai/api/chat/Contact.java index 5d83739..9e9fbd0 100644 --- a/src/me/goddragon/teaseai/api/chat/Contact.java +++ b/src/main/java/me/goddragon/teaseai/api/chat/Contact.java @@ -31,7 +31,7 @@ public void save() { } public File getImageFolder() { - if(IMAGE_SET_PATH.getValue().equalsIgnoreCase("null")) { + if (IMAGE_SET_PATH.getValue().equalsIgnoreCase("null")) { return null; } @@ -39,7 +39,7 @@ public File getImageFolder() { } public File getImage() { - if(IMAGE_PATH.getValue().equalsIgnoreCase("null")) { + if (IMAGE_PATH.getValue().equalsIgnoreCase("null")) { return null; } diff --git a/src/me/goddragon/teaseai/api/chat/MessageBuilder.java b/src/main/java/me/goddragon/teaseai/api/chat/MessageBuilder.java similarity index 98% rename from src/me/goddragon/teaseai/api/chat/MessageBuilder.java rename to src/main/java/me/goddragon/teaseai/api/chat/MessageBuilder.java index d09dcfd..ee5abe3 100644 --- a/src/me/goddragon/teaseai/api/chat/MessageBuilder.java +++ b/src/main/java/me/goddragon/teaseai/api/chat/MessageBuilder.java @@ -91,7 +91,7 @@ public MessageBuilder append(String text) { public String getRawText() { String raw = ""; - for(Text text : texts) { + for (Text text : texts) { raw += text.getText(); } diff --git a/src/me/goddragon/teaseai/api/chat/SenderType.java b/src/main/java/me/goddragon/teaseai/api/chat/SenderType.java similarity index 79% rename from src/me/goddragon/teaseai/api/chat/SenderType.java rename to src/main/java/me/goddragon/teaseai/api/chat/SenderType.java index 036cdef..8ad60ac 100644 --- a/src/me/goddragon/teaseai/api/chat/SenderType.java +++ b/src/main/java/me/goddragon/teaseai/api/chat/SenderType.java @@ -3,7 +3,7 @@ /** * Created by GodDragon on 22.03.2018. */ -public enum SenderType { +public enum SenderType { DOM, SUB } diff --git a/src/me/goddragon/teaseai/api/chat/TypeSpeed.java b/src/main/java/me/goddragon/teaseai/api/chat/TypeSpeed.java similarity index 87% rename from src/me/goddragon/teaseai/api/chat/TypeSpeed.java rename to src/main/java/me/goddragon/teaseai/api/chat/TypeSpeed.java index 1223bb5..5dab017 100644 --- a/src/me/goddragon/teaseai/api/chat/TypeSpeed.java +++ b/src/main/java/me/goddragon/teaseai/api/chat/TypeSpeed.java @@ -14,6 +14,6 @@ public enum TypeSpeed { } public long getTypeDuration(String message) { - return message.trim().length()*millisPerLetter; + return message.trim().length() * millisPerLetter; } } diff --git a/src/me/goddragon/teaseai/api/chat/response/Response.java b/src/main/java/me/goddragon/teaseai/api/chat/response/Response.java similarity index 71% rename from src/me/goddragon/teaseai/api/chat/response/Response.java rename to src/main/java/me/goddragon/teaseai/api/chat/response/Response.java index 81124b7..590e215 100644 --- a/src/me/goddragon/teaseai/api/chat/response/Response.java +++ b/src/main/java/me/goddragon/teaseai/api/chat/response/Response.java @@ -3,6 +3,7 @@ import java.util.Collection; import java.util.HashSet; import java.util.regex.Pattern; +import java.util.stream.Collectors; /** * Created by GodDragon on 24.03.2018. @@ -16,18 +17,19 @@ public abstract class Response { private String message; private boolean disabled = false; + private boolean ignoreDisabledResponses = false; public Response() { } public Response(String... indicators) { - for(String indicator : indicators) { + for (String indicator : indicators) { addIndicator(indicator); } } public Response(Pattern... patterns) { - for(Pattern pattern : patterns) { + for (Pattern pattern : patterns) { this.regexPatterns.add(pattern); } } @@ -39,8 +41,8 @@ public boolean checkPattern(Pattern pattern, String message) { } public boolean checkPatterns(String message) { - for(Pattern pattern : regexPatterns) { - if(checkPattern(pattern, message)) { + for (Pattern pattern : regexPatterns) { + if (checkPattern(pattern, message)) { return true; } } @@ -50,8 +52,8 @@ public boolean checkPatterns(String message) { public boolean containsLike(String message) { message = message.toLowerCase(); - for(String indicator : lowerCaseIndicators) { - if(message.contains(indicator)) { + for (String indicator : lowerCaseIndicators) { + if (message.contains(indicator)) { return true; } } @@ -60,8 +62,8 @@ public boolean containsLike(String message) { } public boolean containsEqual(String message) { - for(String indicator : indicators) { - if(message.contains(indicator)) { + for (String indicator : indicators) { + if (message.contains(indicator)) { return true; } } @@ -76,13 +78,13 @@ public void addIndicator(String indicator) { } public void addIndicators(String... indicators) { - for(String indicator : indicators) { + for (String indicator : indicators) { addIndicator(indicator); } } public void addRegexPatterns(String... patterns) { - for(String pattern : patterns) { + for (String pattern : patterns) { addRegexPatterns(Pattern.compile(pattern)); } } @@ -92,7 +94,7 @@ public void addRegexPattern(Pattern pattern) { } public void addRegexPatterns(Pattern... patterns) { - for(Pattern pattern : patterns) { + for (Pattern pattern : patterns) { addRegexPattern(pattern); } } @@ -120,4 +122,17 @@ public String getMessage() { public void setMessage(String message) { this.message = message; } + + public boolean isIgnoreDisabledResponses() { + return ignoreDisabledResponses; + } + + public void setIgnoreDisabledResponses(boolean ignoreDisabledResponses) { + this.ignoreDisabledResponses = ignoreDisabledResponses; + } + + @Override + public String toString() { + return getIndicators().stream().map(Object::toString).collect(Collectors.joining(",")); + } } diff --git a/src/me/goddragon/teaseai/api/chat/response/ResponseHandler.java b/src/main/java/me/goddragon/teaseai/api/chat/response/ResponseHandler.java similarity index 80% rename from src/me/goddragon/teaseai/api/chat/response/ResponseHandler.java rename to src/main/java/me/goddragon/teaseai/api/chat/response/ResponseHandler.java index 3def975..0a0f24c 100644 --- a/src/me/goddragon/teaseai/api/chat/response/ResponseHandler.java +++ b/src/main/java/me/goddragon/teaseai/api/chat/response/ResponseHandler.java @@ -1,5 +1,6 @@ package me.goddragon.teaseai.api.chat.response; +import me.goddragon.teaseai.TeaseAI; import me.goddragon.teaseai.api.scripts.ScriptHandler; import me.goddragon.teaseai.api.scripts.personality.Personality; import me.goddragon.teaseai.utils.StringUtils; @@ -13,7 +14,6 @@ import java.io.FileReader; import java.util.ArrayList; import java.util.Collection; -import java.util.HashSet; import java.util.List; import java.util.logging.Level; @@ -24,12 +24,14 @@ public class ResponseHandler { private static ResponseHandler handler = new ResponseHandler(); - private final Collection responses = new HashSet<>(); + private final Collection responses = new ArrayList<>(); - private final List queuedResponse = new ArrayList<>(); + private final ArrayList queuedResponse = new ArrayList<>(); private Response currentLoadingResponse; + private boolean lockedQueuedResponse = false; + public void loadResponsesFromPersonality(Personality personality) { responses.clear(); @@ -47,12 +49,13 @@ public boolean trigger() { ScriptEngine engine = ScriptHandler.getHandler().getEngine(); String responseName = file.getName().substring(0, file.getName().length() - 3); String functionName = StringUtils.decapitalize(responseName) + "Response"; + try { - Invocable invocable = (Invocable) engine; + Invocable invocable = (Invocable) engine; Object result = invocable.invokeFunction(functionName, getMessage()); - if(result instanceof Boolean) { + if (result instanceof Boolean) { return (Boolean) result; } return false; @@ -60,7 +63,7 @@ public boolean trigger() { TeaseLogger.getLogger().log(Level.SEVERE, "Error while handling file '" + e.getFileName() + "' in line " + e.getLineNumber() + "\n" + "Error: " + e.getMessage(), false); } catch (NoSuchMethodException e) { - TeaseLogger.getLogger().log(Level.SEVERE, "Response '" + responseName + " is missing the function to trigger it. Create the function '" + functionName + "(message)' for this to work." , false); + TeaseLogger.getLogger().log(Level.SEVERE, "Response '" + responseName + " is missing the function to trigger it. Create the function '" + functionName + "(message)' for this to work.", false); } return false; } @@ -85,7 +88,7 @@ public boolean trigger() { public void registerResponse(Response response) { synchronized (responses) { - if(!responses.contains(response)) { + if (!responses.contains(response)) { responses.add(response); } } @@ -109,32 +112,46 @@ public void removeQueuedResponse(Response response) { } } + public ArrayList getQueuedResponse() { + return queuedResponse; + } + public Response getLatestQueuedResponse() { synchronized (queuedResponse) { if (!queuedResponse.isEmpty()) { - return queuedResponse.get(queuedResponse.size() - 1); + return queuedResponse.get(0); } } return null; } - public Response checkMessageForResponse(String message) { + public Collection checkMessageForResponse(String message) { + List responses = new ArrayList<>(); + synchronized (responses) { - for (Response response : responses) { - if (response.containsLike(message) && !response.isDisabled()) { - return response; + for (Response response : this.responses) { + if (response.containsLike(message) && !response.isDisabled() && (response.isIgnoreDisabledResponses() || !TeaseAI.application.isResponsesDisabled())) { + responses.add(response); } } } - return null; + return responses; } public Response getCurrentLoadingResponse() { return currentLoadingResponse; } + public boolean isLockedQueuedResponse() { + return lockedQueuedResponse; + } + + public void setLockedQueuedResponse(boolean lockedQueuedResponse) { + this.lockedQueuedResponse = lockedQueuedResponse; + } + public static ResponseHandler getHandler() { return handler; } diff --git a/src/me/goddragon/teaseai/api/chat/vocabulary/RunableVocabulary.java b/src/main/java/me/goddragon/teaseai/api/chat/vocabulary/RunableVocabulary.java similarity index 94% rename from src/me/goddragon/teaseai/api/chat/vocabulary/RunableVocabulary.java rename to src/main/java/me/goddragon/teaseai/api/chat/vocabulary/RunableVocabulary.java index af2fc51..aa70c4f 100644 --- a/src/me/goddragon/teaseai/api/chat/vocabulary/RunableVocabulary.java +++ b/src/main/java/me/goddragon/teaseai/api/chat/vocabulary/RunableVocabulary.java @@ -54,9 +54,9 @@ public String toString() { TeaseLogger.getLogger().log(Level.SEVERE, "Error while handling file '" + e.getFileName() + "' in line " + e.getLineNumber() + "\n" + "Error: " + e.getMessage(), false); } catch (NoSuchMethodException e) { - TeaseLogger.getLogger().log(Level.SEVERE, "Vocabulary '" + responseName + " is missing the function to trigger it. Create the function '" + getFunctionName() + "()' for this to work." , false); - } catch(NullPointerException ex) { - TeaseLogger.getLogger().log(Level.SEVERE, "Vocabulary '" + responseName + "' returned null!" , false); + TeaseLogger.getLogger().log(Level.SEVERE, "Vocabulary '" + responseName + " is missing the function to trigger it. Create the function '" + getFunctionName() + "()' for this to work.", false); + } catch (NullPointerException ex) { + TeaseLogger.getLogger().log(Level.SEVERE, "Vocabulary '" + responseName + "' returned null!", false); } return '!' + name + '!'; diff --git a/src/me/goddragon/teaseai/api/chat/vocabulary/Vocabulary.java b/src/main/java/me/goddragon/teaseai/api/chat/vocabulary/Vocabulary.java similarity index 94% rename from src/me/goddragon/teaseai/api/chat/vocabulary/Vocabulary.java rename to src/main/java/me/goddragon/teaseai/api/chat/vocabulary/Vocabulary.java index 62a2e68..0603b89 100644 --- a/src/me/goddragon/teaseai/api/chat/vocabulary/Vocabulary.java +++ b/src/main/java/me/goddragon/teaseai/api/chat/vocabulary/Vocabulary.java @@ -12,7 +12,7 @@ public class Vocabulary { private HashMap synonyms = new HashMap<>(); public Vocabulary(Object... synonyms) { - for(Object object : synonyms) { + for (Object object : synonyms) { this.synonyms.put(object, 1D); } } diff --git a/src/me/goddragon/teaseai/api/chat/vocabulary/VocabularyHandler.java b/src/main/java/me/goddragon/teaseai/api/chat/vocabulary/VocabularyHandler.java similarity index 95% rename from src/me/goddragon/teaseai/api/chat/vocabulary/VocabularyHandler.java rename to src/main/java/me/goddragon/teaseai/api/chat/vocabulary/VocabularyHandler.java index ca041c2..1407f7b 100644 --- a/src/me/goddragon/teaseai/api/chat/vocabulary/VocabularyHandler.java +++ b/src/main/java/me/goddragon/teaseai/api/chat/vocabulary/VocabularyHandler.java @@ -59,7 +59,7 @@ public void loadVocabulariesFromPersonality(Personality personality) { synonym = split[0]; try { chance = Double.parseDouble(split[1]); - } catch(NumberFormatException ex) { + } catch (NumberFormatException ex) { TeaseLogger.getLogger().log(Level.SEVERE, "Malformed vocabulary '" + file.getName() + "'. Found ; but didn't find valid chance in string " + strLine); } } @@ -70,7 +70,7 @@ public void loadVocabulariesFromPersonality(Personality personality) { //Close the input stream br.close(); - if(vocabulary != null) { + if (vocabulary != null) { //Remove .txt extension registerVocabulary(file.getName().substring(0, file.getName().length() - 4), vocabulary); } @@ -78,8 +78,8 @@ public void loadVocabulariesFromPersonality(Personality personality) { } catch (IOException e) { e.printStackTrace(); } - } else if(file.getName().endsWith(".js")) { - String name = file.getName().substring(0, file.getName().length() - 3); + } else if (file.getName().endsWith(".js")) { + String name = file.getName().substring(0, file.getName().length() - 3); RunableVocabulary runableVocabulary = new RunableVocabulary(name, file); registerVocabulary(name, runableVocabulary); diff --git a/src/main/java/me/goddragon/teaseai/api/config/CheckBoxComponent.java b/src/main/java/me/goddragon/teaseai/api/config/CheckBoxComponent.java new file mode 100644 index 0000000..32e5902 --- /dev/null +++ b/src/main/java/me/goddragon/teaseai/api/config/CheckBoxComponent.java @@ -0,0 +1,40 @@ +package me.goddragon.teaseai.api.config; + +import javafx.beans.value.ChangeListener; +import javafx.beans.value.ObservableValue; +import javafx.scene.control.CheckBox; + +public class CheckBoxComponent extends VariableBasedComponent { + + private CheckBox checkBox; + + public CheckBoxComponent(PersonalityVariable variable, String settingString) { + super(settingString, variable.getDescription(), variable); + setUp(); + } + + public CheckBoxComponent(PersonalityVariable variable, String settingString, String description) { + super(settingString, description, variable); + setUp(); + } + + private void setUp() { + this.checkBox = new CheckBox(); + + if (variable.getValue() == Boolean.TRUE) { + checkBox.setSelected(true); + } + + checkBox.selectedProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) { + if (checkBox.isSelected()) { + variable.setValue(true); + } else { + variable.setValue(false); + } + } + }); + this.setting = checkBox; + } +} diff --git a/src/me/goddragon/teaseai/api/config/ConfigHandler.java b/src/main/java/me/goddragon/teaseai/api/config/ConfigHandler.java similarity index 86% rename from src/me/goddragon/teaseai/api/config/ConfigHandler.java rename to src/main/java/me/goddragon/teaseai/api/config/ConfigHandler.java index 0ca39fe..fbee771 100644 --- a/src/me/goddragon/teaseai/api/config/ConfigHandler.java +++ b/src/main/java/me/goddragon/teaseai/api/config/ConfigHandler.java @@ -31,12 +31,13 @@ public void loadConfig() { InputStream input = null; try { //Do we want to fetch it from a file or url? - if(isConfig()) { + if (isConfig()) { File config = new File(configName); if (!config.exists()) { try { config.createNewFile(); } catch (IOException e) { + e.printStackTrace(); TeaseLogger.getLogger().log(Level.SEVERE, "Failed to load config.", e); } } @@ -52,7 +53,7 @@ public void loadConfig() { properties.clear(); properties.load(input); - for(ConfigValue configValue : configValues) { + for (ConfigValue configValue : configValues) { //Fetch the value from the config/create default configValue.getValue(); } @@ -69,15 +70,19 @@ public void loadConfig() { } //Only save when we are not dealing an url - if(isConfig()) { + if (isConfig()) { reloadAllValues(); saveConfig(); } } + public File getConfigFile() { + return new File(configName); + } + public void saveConfig() { - if(!isConfig()) { + if (!isConfig()) { TeaseLogger.getLogger().log(Level.SEVERE, "Can't save a config to an url. URL: '" + url.toString() + "'."); return; } @@ -92,11 +97,16 @@ public void saveConfig() { } public void reloadAllValues() { - for(ConfigValue configValue : configValues) { + for (ConfigValue configValue : configValues) { configValue.reloadValue(); } } + public void changeConfigName(String configName) { + getConfigFile().renameTo(new File(configName)); + this.configName = configName; + } + public boolean isURL() { return url != null; } diff --git a/src/me/goddragon/teaseai/api/config/ConfigValue.java b/src/main/java/me/goddragon/teaseai/api/config/ConfigValue.java similarity index 92% rename from src/me/goddragon/teaseai/api/config/ConfigValue.java rename to src/main/java/me/goddragon/teaseai/api/config/ConfigValue.java index b57b3c3..4b0d0a9 100644 --- a/src/me/goddragon/teaseai/api/config/ConfigValue.java +++ b/src/main/java/me/goddragon/teaseai/api/config/ConfigValue.java @@ -20,12 +20,12 @@ public ConfigValue(String name, Object defaultValue, ConfigHandler configHandler public ConfigValue setValue(String value) { this.value = value; - configHandler.getProperties().setProperty(name, value.toString()); + configHandler.getProperties().setProperty(name, value); return this; } public String getValue() { - if(value != null) { + if (value != null) { return value; } @@ -36,7 +36,7 @@ public String getValue() { createDefault(); - if(configHandler.isConfig()) { + if (configHandler.isConfig()) { save(); } diff --git a/src/main/java/me/goddragon/teaseai/api/config/DoubleSpinnerComponent.java b/src/main/java/me/goddragon/teaseai/api/config/DoubleSpinnerComponent.java new file mode 100644 index 0000000..60a1dd2 --- /dev/null +++ b/src/main/java/me/goddragon/teaseai/api/config/DoubleSpinnerComponent.java @@ -0,0 +1,61 @@ +package me.goddragon.teaseai.api.config; + +import javafx.scene.control.Spinner; +import javafx.scene.control.SpinnerValueFactory; +import javafx.scene.control.TextFormatter; +import javafx.util.converter.DoubleStringConverter; + +import java.text.NumberFormat; + +public class DoubleSpinnerComponent extends SpinnerComponent { + private Spinner spinner; + private final double min; + private final double max; + + public DoubleSpinnerComponent(PersonalityVariable variable, String settingString, double min, double max) { + super(settingString, variable.getDescription(), variable); + this.min = min; + this.max = max; + + setUp(); + } + + public DoubleSpinnerComponent(PersonalityVariable variable, String settingString, double min, double max, String description) { + super(settingString, description, variable); + this.min = min; + this.max = max; + + setUp(); + } + + private void setUp() { + double startingValue = min; + + if (variable.getValue() instanceof Integer) { + startingValue = (Integer) variable.getValue(); + } else { + try { + startingValue = Integer.parseInt((String) variable.getValue()); + } catch (NumberFormatException ex) { + handleMissAssignedValue("Double"); + } + } + + //spinner = new Spinner<>(min, max, startingValue); + + spinner = new Spinner<>(min, max, startingValue); + + NumberFormat format = NumberFormat.getNumberInstance(); + + TextFormatter priceFormatter = new TextFormatter<>(new DoubleStringConverter(), startingValue, getFilter(format)); + + spinner.setValueFactory(new SpinnerValueFactory.DoubleSpinnerValueFactory(min, max, startingValue)); + spinner.setEditable(true); + spinner.getEditor().setTextFormatter(priceFormatter); + spinner.getValueFactory().setValue(startingValue); + + spinner.valueProperty().addListener((observable, oldValue, newValue) -> variable.setValue(newValue)); + + this.setting = spinner; + } +} diff --git a/src/main/java/me/goddragon/teaseai/api/config/GUISettingComponent.java b/src/main/java/me/goddragon/teaseai/api/config/GUISettingComponent.java new file mode 100644 index 0000000..bed6764 --- /dev/null +++ b/src/main/java/me/goddragon/teaseai/api/config/GUISettingComponent.java @@ -0,0 +1,60 @@ +package me.goddragon.teaseai.api.config; + +import javafx.scene.Node; +import javafx.scene.control.Label; +import javafx.scene.control.Tooltip; +import javafx.stage.PopupWindow; +import javafx.util.Duration; + +public abstract class GUISettingComponent { + + protected Label settingLabel; + protected String description; + protected Node setting; + protected int columnNumber = -1; + + + public GUISettingComponent(String settingString, int columnNumber) { + this(settingString); + this.columnNumber = columnNumber; + } + + public GUISettingComponent(String settingString) { + settingString += ":"; + settingLabel = new Label(settingString); + } + + public GUISettingComponent(String settingString, String description, int columnNumber) { + this(settingString, description); + this.columnNumber = columnNumber; + } + + public GUISettingComponent(String settingString, String description) { + this(settingString); + this.description = description; + //Tooltip.install(settingLabel, makeBubble(new Tooltip(this.description))); + settingLabel.setTooltip(makeBubble(new Tooltip(this.description))); + } + + private Tooltip makeBubble(Tooltip tooltip) { + tooltip.setStyle("-fx-font-size: 14px;"); + tooltip.setMaxWidth(300); + tooltip.setWrapText(true); + tooltip.setAnchorLocation(PopupWindow.AnchorLocation.WINDOW_BOTTOM_LEFT); + tooltip.setShowDelay(new Duration(100)); + + return tooltip; + } + + public Label getLabel() { + return settingLabel; + } + + public Node getSetting() { + return setting; + } + + public int getColumnID() { + return columnNumber; + } +} diff --git a/src/main/java/me/goddragon/teaseai/api/config/IntegerSpinnerComponent.java b/src/main/java/me/goddragon/teaseai/api/config/IntegerSpinnerComponent.java new file mode 100644 index 0000000..4215f37 --- /dev/null +++ b/src/main/java/me/goddragon/teaseai/api/config/IntegerSpinnerComponent.java @@ -0,0 +1,62 @@ +package me.goddragon.teaseai.api.config; + +import javafx.scene.control.Spinner; +import javafx.scene.control.SpinnerValueFactory; +import javafx.scene.control.TextFormatter; +import javafx.util.converter.IntegerStringConverter; + +import java.text.NumberFormat; + +public class IntegerSpinnerComponent extends SpinnerComponent { + private Spinner spinner; + private final int min; + private final int max; + + public IntegerSpinnerComponent(PersonalityVariable variable, String settingString, int min, int max) { + super(settingString, variable.getDescription(), variable); + this.min = min; + this.max = max; + + setUp(); + } + + public IntegerSpinnerComponent(PersonalityVariable variable, String settingString, int min, int max, String description) { + super(settingString, description, variable); + this.min = min; + this.max = max; + + setUp(); + } + + private void setUp() { + int startingValue = min; + + if (variable.getValue() instanceof Integer) { + startingValue = (Integer) variable.getValue(); + } else { + try { + startingValue = Integer.parseInt((String) variable.getValue()); + } catch (NumberFormatException ex) { + handleMissAssignedValue("Integer"); + } + } + + //spinner = new Spinner<>(min, max, startingValue); + + spinner = new Spinner<>(min, max, startingValue); + + NumberFormat format = NumberFormat.getIntegerInstance(); + + TextFormatter valueFormatter = new TextFormatter<>(new IntegerStringConverter(), startingValue, getFilter(format)); + + spinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(min, max, startingValue)); + spinner.setEditable(true); + spinner.getEditor().setTextFormatter(valueFormatter); + spinner.getValueFactory().setValue(startingValue); + + spinner.valueProperty().addListener((observable, oldValue, newValue) -> variable.setValue(newValue)); + + this.setting = spinner; + } + +} diff --git a/src/main/java/me/goddragon/teaseai/api/config/OptionsListComponent.java b/src/main/java/me/goddragon/teaseai/api/config/OptionsListComponent.java new file mode 100644 index 0000000..554dfe5 --- /dev/null +++ b/src/main/java/me/goddragon/teaseai/api/config/OptionsListComponent.java @@ -0,0 +1,49 @@ +package me.goddragon.teaseai.api.config; + +import javafx.beans.value.ChangeListener; +import javafx.beans.value.ObservableValue; +import javafx.collections.FXCollections; +import javafx.scene.control.ChoiceBox; +import me.goddragon.teaseai.utils.TeaseLogger; + +import java.util.ArrayList; +import java.util.logging.Level; + +public class OptionsListComponent extends VariableBasedComponent { + private ArrayList options; + private ChoiceBox choiceBox; + + public OptionsListComponent(PersonalityVariable variable, String settingString, ArrayList options) { + super(settingString, variable.getDescription(), variable); + this.options = options; + setUp(); + } + + public OptionsListComponent(PersonalityVariable variable, String settingString, ArrayList options, String description) { + super(settingString, description, variable); + this.options = options; + setUp(); + } + + private void setUp() { + choiceBox = new ChoiceBox<>(FXCollections.observableArrayList(options)); + String toSet = ""; + for (String thisString : options) { + if (variable.getValue().equals(thisString)) { + toSet = thisString; + } + } + if (!toSet.equals("")) { + choiceBox.getSelectionModel().select(toSet); + } else { + TeaseLogger.getLogger().log(Level.WARNING, "Current value " + variable.getValue() + " of variable " + variable.getConfigName() + " does not match any of its possible options"); + } + choiceBox.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observableValue, Number number, Number number2) { + variable.setValue(choiceBox.getItems().get((Integer) number2)); + } + }); + this.setting = choiceBox; + } +} diff --git a/src/main/java/me/goddragon/teaseai/api/config/PersonalitiesSettingsHandler.java b/src/main/java/me/goddragon/teaseai/api/config/PersonalitiesSettingsHandler.java new file mode 100644 index 0000000..66922b8 --- /dev/null +++ b/src/main/java/me/goddragon/teaseai/api/config/PersonalitiesSettingsHandler.java @@ -0,0 +1,60 @@ +package me.goddragon.teaseai.api.config; + +import javafx.scene.control.Tab; + +import java.util.ArrayList; +import java.util.HashSet; + +public class PersonalitiesSettingsHandler { + private static HashSet addedComponents; + private static PersonalitiesSettingsHandler thisHandler; + private static ArrayList personalitySettingsHandlers; + private static ArrayList personalityTabsToAdd; + + public PersonalitiesSettingsHandler() { + thisHandler = this; + personalitySettingsHandlers = new ArrayList<>(); + personalityTabsToAdd = new ArrayList<>(); + addedComponents = new HashSet<>(); + } + + public static PersonalitiesSettingsHandler getHandler() { + return thisHandler; + } + + public void addPersonalitySettingsHandler(PersonalitySettingsHandler handler) { + personalitySettingsHandlers.add(handler); + } + + public Tab addPersonalityTab(String personalityName) { + Tab newTab = new Tab(personalityName); + personalityTabsToAdd.add(newTab); + return newTab; + } + + public void addGuiComponent(PersonalityVariable comp) { + if (addedComponents.contains(comp)) { + throw new IllegalArgumentException("Gui component added that has already been added. Check if it has been added first!"); + } else { + addedComponents.add(comp); + } + } + + public boolean hasComponent(PersonalityVariable comp) { + boolean equivalentVar = false; + for (PersonalityVariable var : addedComponents) { + if (var.equals(comp)) { + equivalentVar = true; + } + } + return addedComponents.contains(comp) || equivalentVar; + } + + public ArrayList getTabsToAdd() { + return personalityTabsToAdd; + } + + public ArrayList getSettingsHandlers() { + return personalitySettingsHandlers; + } +} diff --git a/src/main/java/me/goddragon/teaseai/api/config/PersonalitySettingsHandler.java b/src/main/java/me/goddragon/teaseai/api/config/PersonalitySettingsHandler.java new file mode 100644 index 0000000..f51d44e --- /dev/null +++ b/src/main/java/me/goddragon/teaseai/api/config/PersonalitySettingsHandler.java @@ -0,0 +1,117 @@ +package me.goddragon.teaseai.api.config; + +import javafx.beans.value.ChangeListener; +import javafx.beans.value.ObservableValue; +import javafx.geometry.Orientation; +import javafx.geometry.Pos; +import javafx.scene.control.Label; +import javafx.scene.control.ListView; +import javafx.scene.control.Tab; +import javafx.scene.layout.AnchorPane; +import javafx.scene.layout.ColumnConstraints; +import javafx.scene.layout.GridPane; +import javafx.scene.layout.RowConstraints; + +import java.util.ArrayList; + +public class PersonalitySettingsHandler { + private ArrayList settingsPanels; + + private Tab PersonalityTab; + + private String personalityName; + + private GridPane personalityGridPane; + + private ListView @@ -331,9 +431,9 @@ - + - + @@ -369,16 +469,14 @@ - -