diff --git a/.github/workflows/build-main.yml b/.github/workflows/build-main.yml index be8c822..9eb8ed5 100644 --- a/.github/workflows/build-main.yml +++ b/.github/workflows/build-main.yml @@ -13,22 +13,12 @@ jobs: steps: - uses: actions/checkout@v2 - - name: Cache local Maven repository - uses: actions/cache@v2 - env: - cache-name: cache-m2 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-build-${{ env.cache-name }} - restore-keys: | - ${{ runner.os }}-build-${{ env.cache-name }}- - ${{ runner.os }}-build- - ${{ runner.os }}- - name: Set up Java - uses: actions/setup-java@v2 + uses: actions/setup-java@v3 with: java-version: '8' distribution: 'zulu' + cache: 'maven' - name: Set up CI environment run: .github/setup.sh - name: Execute the build diff --git a/.github/workflows/build-pr.yml b/.github/workflows/build-pr.yml index d92dcf7..c350d34 100644 --- a/.github/workflows/build-pr.yml +++ b/.github/workflows/build-pr.yml @@ -11,22 +11,12 @@ jobs: steps: - uses: actions/checkout@v2 - - name: Cache local Maven repository - uses: actions/cache@v2 - env: - cache-name: cache-m2 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-build-${{ env.cache-name }} - restore-keys: | - ${{ runner.os }}-build-${{ env.cache-name }}- - ${{ runner.os }}-build- - ${{ runner.os }}- - name: Set up Java - uses: actions/setup-java@v2 + uses: actions/setup-java@v3 with: java-version: '8' distribution: 'zulu' + cache: 'maven' - name: Set up CI environment run: .github/setup.sh - name: Execute the build diff --git a/LICENSE b/LICENSE deleted file mode 100644 index f288702..0000000 --- a/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - 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/LICENSE.txt b/LICENSE.txt index 94a9ed0..46680d0 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,674 +1,24 @@ - 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 -. +Copyright (c) 2020 - 2024, SciJava developers. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/README.md b/README.md index 4b4da6e..6db8c88 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,2 @@ -[![](https://github.com/fiji/jython-autocompletion/actions/workflows/build-main.yml/badge.svg)](https://github.com/fiji/jython-autocompletion/actions/workflows/build-main.yml) +[![](https://github.com/scijava/jython-autocompletion/actions/workflows/build-main.yml/badge.svg)](https://github.com/scijava/jython-autocompletion/actions/workflows/build-main.yml) diff --git a/pom.xml b/pom.xml index 1f643c7..6fa1074 100644 --- a/pom.xml +++ b/pom.xml @@ -1,29 +1,28 @@ - + 4.0.0 org.scijava pom-scijava - 31.1.0 + 37.0.0 - jython-autocompletion - 0.0.3-SNAPSHOT + script-editor-jython + 1.1.1-SNAPSHOT - Jython Autocompletion - Autocompletion for the jython language in the Script Editor - https://github.com/fiji/jython-autocompletion + Jython Script Editor plugin + Jython language support for SciJava Script Editor. + https://github.com/scijava/script-editor-jython 2020 - Fiji - https://fiji.sc + SciJava + https://scijava.org - GNU General Public License v3+ - http://www.gnu.org/licenses/gpl.html + Simplified BSD License repo @@ -32,7 +31,7 @@ acardona Albert Cardona - https://imagej.net/User:Albertcardona + https://imagej.net/people/acardona lead developer @@ -42,10 +41,10 @@ maintainer - + tferr Tiago Ferreira - https://imagej.net/User:Tiago + https://imagej.net/people/tferr developer debugger @@ -54,84 +53,114 @@ haesleinhuepf Robert Haase - https://imagej.net/User:Haesleinhuepf + https://imagej.net/people/haesleinhuepf developer debugger + + ctrueden + Curtis Rueden + https://imagej.net/people/ctrueden + + maintainer + + Jan Eglinger + https://imagej.net/people/imagejan imagejan + + Jonathan Hale + Squareys + + + Karl Duderstadt + https://imagej.net/people/karlduderstadt + karlduderstadt + Image.sc Forum - https://forum.image.sc/tags/jython + https://forum.image.sc/tag/script-editor - scm:git:git://github.com/fiji/jython-autocompletion - scm:git:git@github.com:fiji/jython-autocompletion + scm:git:git://github.com/scijava/script-editor-jython + scm:git:git@github.com:scijava/script-editor-jython HEAD - https://github.com/fiji/jython-autocompletion + https://github.com/scijava/script-editor-jython GitHub Issues - https://github.com/fiji/jython-autocompletion/issues + https://github.com/scijava/script-editor-jython/issues GitHub Actions - https://github.com/fiji/jython-autocompletion/actions + https://github.com/scijava/script-editor-jython/actions - org.fiji.jython.autocompletion - gpl_v3 - Albert Cardona + org.scijava.jython.autocompletion + bsd_2 + SciJava developers. sign,deploy-to-scijava - - 0.5.12 - 3.5.2 - - - none - - - scijava.public - https://maven.scijava.org/content/groups/public - - - org.scijava script-editor + + org.scijava + scijava-common + + com.fifesoft autocomplete + + com.fifesoft + languagesupport + + + com.fifesoft + rsyntaxtextarea + org.antlr antlr-runtime - ${antlr-runtime.version} org.python jython-slim + + + + org.scijava + scripting-jython + runtime + + + + scijava.public + https://maven.scijava.org/content/groups/public + + diff --git a/src/main/java/sc/fiji/jython/autocompletion/ClassDotAutocompletions.java b/src/main/java/org/scijava/plugins/scripteditor/jython/ClassDotAutocompletions.java similarity index 52% rename from src/main/java/sc/fiji/jython/autocompletion/ClassDotAutocompletions.java rename to src/main/java/org/scijava/plugins/scripteditor/jython/ClassDotAutocompletions.java index f2b9f38..1f457d2 100644 --- a/src/main/java/sc/fiji/jython/autocompletion/ClassDotAutocompletions.java +++ b/src/main/java/org/scijava/plugins/scripteditor/jython/ClassDotAutocompletions.java @@ -1,25 +1,32 @@ /*- * #%L - * Autocompletion for the jython language in the Script Editor + * Jython language support for SciJava Script Editor. * %% - * Copyright (C) 2020 - 2022 Albert Cardona + * Copyright (C) 2020 - 2024 SciJava developers. * %% - * 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. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: * - * 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. + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * . + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. * #L% */ -package sc.fiji.jython.autocompletion; +package org.scijava.plugins.scripteditor.jython; import java.util.ArrayList; import java.util.List; @@ -30,6 +37,14 @@ public class ClassDotAutocompletions extends DefVarDotAutocompletions { final List superclassNames; // List of superclasses final ListdotAutocompletions; // List of class methods and fields + /** + * + * @param fnName + * @param superclassNames + * @param argumentNames + * @param dotAutocompletions + * @param class_scope + */ public ClassDotAutocompletions(final String fnName, List superclassNames, final List argumentNames, final List dotAutocompletions, final Scope class_scope) { super(fnName, null, argumentNames, class_scope); @@ -45,7 +60,7 @@ public List get() { if (fm.isEmpty()) { // Maybe it's a python class // get them all via the org.python.indexer.Indexer and Builtins classes, see StaticDotAutocompletions - System.out.println("Don't know yet how to handle class " + className); + JythonDev.print("Don't know yet how to handle class " + className); } ac.addAll(fm); } @@ -57,7 +72,10 @@ public void put(final CompletionText entry) { this.dotAutocompletions.add(entry); } - /** Make this be cda plus its own dotAutocompletions. */ + /** Make this be cda plus its own dotAutocompletions. + * + * @param cda + */ public void mutateIntoPlus(final ClassDotAutocompletions cda) { this.className = cda.className; diff --git a/src/main/java/org/scijava/plugins/scripteditor/jython/ConstructorAutocompletions.java b/src/main/java/org/scijava/plugins/scripteditor/jython/ConstructorAutocompletions.java new file mode 100644 index 0000000..ae6f944 --- /dev/null +++ b/src/main/java/org/scijava/plugins/scripteditor/jython/ConstructorAutocompletions.java @@ -0,0 +1,52 @@ +/*- + * #%L + * Jython language support for SciJava Script Editor. + * %% + * Copyright (C) 2020 - 2024 SciJava developers. + * %% + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * #L% + */ +package org.scijava.plugins.scripteditor.jython; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.scijava.ui.swing.script.autocompletion.CompletionText; + +public class ConstructorAutocompletions implements DotAutocompletions +{ + private final Class c; + + public ConstructorAutocompletions(final Class c) { + this.c = c; + } + + @Override + public List get() { + return Arrays.asList(this.c.getConstructors()).stream() + .map(cons -> new CompletionText(c.getSimpleName(), c, cons)) + .collect(Collectors.toList()); + } + +} diff --git a/src/main/java/org/scijava/plugins/scripteditor/jython/CustomFunctionCompletion.java b/src/main/java/org/scijava/plugins/scripteditor/jython/CustomFunctionCompletion.java new file mode 100644 index 0000000..4ceb58a --- /dev/null +++ b/src/main/java/org/scijava/plugins/scripteditor/jython/CustomFunctionCompletion.java @@ -0,0 +1,126 @@ +/*- + * #%L + * Jython language support for SciJava Script Editor. + * %% + * Copyright (C) 2020 - 2024 SciJava developers. + * %% + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * #L% + */ +package org.scijava.plugins.scripteditor.jython; + +import org.fife.ui.autocomplete.Completion; +import org.fife.ui.autocomplete.CompletionProvider; +import org.fife.ui.autocomplete.FunctionCompletion; +import org.fife.ui.autocomplete.VariableCompletion; + +public class CustomFunctionCompletion extends FunctionCompletion +{ + public CustomFunctionCompletion( + final CompletionProvider provider, + final String name, + final String returnType) { + super(provider, name, returnType); + } + + @Override + public String getName() { + return super.getName() + "()"; // for listing with fields and methods + } + + protected String getSuperName() { + return super.getName(); + } + + @Override + public String getDefinitionString() { + StringBuilder sb = new StringBuilder(); + + // Add the return type if applicable (C macros like NULL have no type). + String type = getType(); + if (type!=null) { + sb.append(type).append(' '); + } + + // Add the item being described's name. + sb.append(super.getName()); // without parentheses: will be added below with arguments inside + + // Add parameters for functions. + CompletionProvider provider = getProvider(); + char start = provider.getParameterListStart(); + if (start!=0) { + sb.append(start); + } + for (int i=0; i argumentNames; + Scope scope; + + public DefVarDotAutocompletions(final String fnName, final String returnClassName, final List argumentNames, final Scope scope) { + super(returnClassName); + this.fnName = fnName; + this.argumentNames = argumentNames; + this.scope = scope; + } + + public List getArgumentNames() { + return this.argumentNames; + } + + @Override + public String toString() { + return "DefVarAutocompletions:" + + " Class: " + super.className + + " Arguments: " + String.join(", ", this.argumentNames); + } +} diff --git a/src/main/java/org/scijava/plugins/scripteditor/jython/DotAutocompletions.java b/src/main/java/org/scijava/plugins/scripteditor/jython/DotAutocompletions.java new file mode 100644 index 0000000..6367f41 --- /dev/null +++ b/src/main/java/org/scijava/plugins/scripteditor/jython/DotAutocompletions.java @@ -0,0 +1,124 @@ +/*- + * #%L + * Jython language support for SciJava Script Editor. + * %% + * Copyright (C) 2020 - 2024 SciJava developers. + * %% + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * #L% + */ +package org.scijava.plugins.scripteditor.jython; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Stream; + +import org.scijava.ui.swing.script.autocompletion.CompletionText; + +public interface DotAutocompletions { + + static public final DotAutocompletions EMPTY = new EmptyDotAutocompletions(); + + default public String getClassname() { + return null; + } + + default public String getSummary() { + return null; + } + + public List get(); + + default public Stream getStream() { + return get().stream(); + } + + static public List getPublicFieldsAndMethods(final String className) { + final List ac = new ArrayList<>(); + if (null != className) { + try { + final Class c = Class.forName(className); + for (final Field f: c.getFields()) + ac.add(new CompletionText(f.getName(), c, f)); + for (final Method m: c.getMethods()) + ac.add(new CompletionText(m.getName() + "()", c, m)); // TODO could do a parameter-driven autocompletion + } catch (final Exception e) { + JythonDev.print("Could not load class " + className, e); + } + } + return ac; + } + + + /** Collect static fields and static methods from {@code c} into {@code ac}. + * + * @param c + * @param ac + */ + static public void staticFieldsAndStaticMethodsInto(final Class c, final List ac) { + for (final Field f: c.getDeclaredFields()) + if (Modifier.isStatic(f.getModifiers())) + ac.add(new CompletionText(f.getName(), c, f)); + for (final Method m: c.getDeclaredMethods()) + if (Modifier.isStatic(m.getModifiers())) + ac.add(new CompletionText(m.getName() + "()", c, m)); + } + + /** Collect non-static fields and non-static methods of class {@code c} into {@code ac}. + * + * @param c + * @param ac + */ + static public void fieldsAndMethodsInto(final Class c, final List ac) { + for (final Field f: c.getDeclaredFields()) + if (!Modifier.isStatic(f.getModifiers())) + ac.add(new CompletionText(f.getName(), c, f)); + for (final Method m: c.getDeclaredMethods()) + if (!Modifier.isStatic(m.getModifiers())) + ac.add(new CompletionText(m.getName() + "()", c, m)); + } + + static public Stream staticFieldsAndStaticMethodsStream(final Class c, final boolean staticFields, final boolean staticMethods) { + return Stream.concat( + Arrays.stream(c.getDeclaredFields()) + .filter(f -> Modifier.isStatic(f.getModifiers())) + .map(f -> new CompletionText(f.getName(), c, f)), + Arrays.stream(c.getDeclaredMethods()) + .filter(m -> Modifier.isStatic(m.getModifiers())) + .map(m -> new CompletionText(m.getName(), c, m))); + } + + static public Stream fieldsAndMethodsStream(final Class c, final boolean staticFields, final boolean staticMethods) { + return Stream.concat( + Arrays.stream(c.getFields()) + .filter(f -> !Modifier.isStatic(f.getModifiers())) + .map(f -> new CompletionText(f.getName(), c, f)), + Arrays.stream(c.getMethods()) + .filter(m -> !Modifier.isStatic(m.getModifiers())) + .map(m -> new CompletionText(m.getName(), c, m))); + } + +} diff --git a/src/main/java/org/scijava/plugins/scripteditor/jython/EmptyDotAutocompletions.java b/src/main/java/org/scijava/plugins/scripteditor/jython/EmptyDotAutocompletions.java new file mode 100644 index 0000000..2f3ecd2 --- /dev/null +++ b/src/main/java/org/scijava/plugins/scripteditor/jython/EmptyDotAutocompletions.java @@ -0,0 +1,46 @@ +/*- + * #%L + * Jython language support for SciJava Script Editor. + * %% + * Copyright (C) 2020 - 2024 SciJava developers. + * %% + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * #L% + */ +package org.scijava.plugins.scripteditor.jython; + +import java.util.Collections; +import java.util.List; + +import org.scijava.ui.swing.script.autocompletion.CompletionText; + +public class EmptyDotAutocompletions implements DotAutocompletions { + @Override + public List get() { + return Collections.emptyList(); + } + + @Override + public String toString() { + return "EMPTY"; + } +} diff --git a/src/main/java/org/scijava/plugins/scripteditor/jython/JythonAutoCompletion.java b/src/main/java/org/scijava/plugins/scripteditor/jython/JythonAutoCompletion.java new file mode 100644 index 0000000..a9d2ba3 --- /dev/null +++ b/src/main/java/org/scijava/plugins/scripteditor/jython/JythonAutoCompletion.java @@ -0,0 +1,176 @@ +/*- + * #%L + * Jython language support for SciJava Script Editor. + * %% + * Copyright (C) 2020 - 2024 SciJava developers. + * %% + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * #L% + */ +package org.scijava.plugins.scripteditor.jython; + +import java.util.HashMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.swing.text.BadLocationException; + +import org.fife.ui.autocomplete.AutoCompletion; +import org.fife.ui.autocomplete.Completion; +import org.fife.ui.autocomplete.CompletionProvider; +import org.scijava.ui.swing.script.EditorPane; +import org.scijava.ui.swing.script.autocompletion.ImportCompletion; + +public class JythonAutoCompletion extends AutoCompletion { + + public JythonAutoCompletion(final CompletionProvider provider) { + super(provider); + this.setParameterAssistanceEnabled(true); + this.setShowDescWindow(true); + } + + static private final Pattern importPattern = Pattern.compile("^(from[ \\t]+([a-zA-Z_][a-zA-Z0-9._]*)[ \\t]+|)import[ \\t]+([a-zA-Z_][a-zA-Z0-9_]*[ \\ta-zA-Z0-9_,]*)[ \\t]*([\\\\]*|)[ \\t]*(#.*|)$"), + tripleQuotePattern = Pattern.compile("\"\"\""), + variableDeclarationPattern = Pattern.compile("([a-zA-Z_][a-zA-Z0-9._]*)[ \\t]*=[ \\t]*([A-Z_][a-zA-Z0-9._]*)(?:\\()"); // E.g., in 'imp=ImagePlus()' group1: imp; group2: ImagePlus + + static public class Import { + final public String className, + alias; // same as simple class name, or the alias from "as " + final public int lineNumber; + + public Import(final String className, final String alias, final int lineNumber) { + this.className = className; + this.alias = null != alias ? alias : className.substring(className.lastIndexOf('.') + 1); + this.lineNumber = lineNumber; + } + + // E.g. handle "ImageJFunctions as IL" -> ["ImageJFunctions", "as", "IL"] + public Import(final String packageName, final String[] parts, final int lineNumber) { + this(packageName + "." + parts[0], 3 == parts.length ? parts[2] : null, lineNumber); + } + } + + static public final String findClassAliasOfVariable(final String variable, String inputText) { + final String[] lines = inputText.split("\n"); + for (int i = 0; i < lines.length; ++i) { + final String line = lines[i]; + final Matcher matcher = variableDeclarationPattern.matcher(line); + if (matcher.find()) { + // a line containing a variable declaration +// System.out.println("Queried variable: " + variable); +// System.out.println("Hit: line #" + i + ": " + line); +// System.out.println("Matcher g1: " + matcher.group(1)); +// System.out.println("Matcher g2: " + matcher.group(2)); + if (variable.equals(matcher.group(1))) { + return matcher.group(2); + } + } + } + return null; + } + + static public final HashMap findImportedClasses(final String text) { + final HashMap importedClasses = new HashMap<>(); + String packageName = ""; + boolean endingBackslash = false; + boolean insideTripleQuotes = false; + + // Scan the whole file for imports + final String[] lines = text.split("\n"); + for (int i=0; i -1) importLine = importLine.substring(0, backslash); + else { + final int sharp = importLine.lastIndexOf('#'); + if (sharp > -1) importLine = importLine.substring(0, sharp); + } + for (final String simpleClassName : importLine.split(",")) { + final Import im = new Import(packageName, simpleClassName.trim().split("\\s"), i); + importedClasses.put(im.alias, im); + } + endingBackslash = -1 != backslash; // otherwise there is another line with classes of the same package + continue; + } + final Matcher m = importPattern.matcher(line); + if (m.find()) { + packageName = null == m.group(2) ? "" : m.group(2); + for (final String simpleClassName : m.group(3).split(",")) { + final Import im = new Import(packageName, simpleClassName.trim().split("\\s"), i); + importedClasses.put(im.alias, im); + } + endingBackslash = null != m.group(4) && m.group(4).length() > 0 && '\\' == m.group(4).charAt(0); + } + } + + return importedClasses; + } + + @Override + protected void insertCompletion(final Completion c, final boolean typedParamListStartChar) { + if (c instanceof ImportCompletion) { + final EditorPane editor = (EditorPane) super.getTextComponent(); + editor.beginAtomicEdit(); + try { + super.insertCompletion(c, typedParamListStartChar); + final ImportCompletion cc = (ImportCompletion)c; + final HashMap importedClasses = findImportedClasses(editor.getText()); + // Insert import statement after the last import, if not there already + for (final Import im : importedClasses.values()) { + if (im.className.contentEquals(cc.getClassName())) + return; // don't insert + } + try { + final int insertAtLine = 0 == importedClasses.size() ? 0 + : importedClasses.values().stream().map(im -> im.lineNumber).reduce(Math::max).get(); + editor.insert(cc.getImportStatement() + "\n", editor.getLineStartOffset(0 == insertAtLine ? 0 : insertAtLine + 1)); + } catch (BadLocationException e) { + e.printStackTrace(); + } + } finally { + editor.endAtomicEdit(); + } + } else { + super.insertCompletion(c, typedParamListStartChar); + } + } +} diff --git a/src/main/java/sc/fiji/jython/autocompletion/JythonAutoCompletions.java b/src/main/java/org/scijava/plugins/scripteditor/jython/JythonAutoCompletions.java similarity index 53% rename from src/main/java/sc/fiji/jython/autocompletion/JythonAutoCompletions.java rename to src/main/java/org/scijava/plugins/scripteditor/jython/JythonAutoCompletions.java index 9c0b15b..0d51e24 100644 --- a/src/main/java/sc/fiji/jython/autocompletion/JythonAutoCompletions.java +++ b/src/main/java/org/scijava/plugins/scripteditor/jython/JythonAutoCompletions.java @@ -1,28 +1,37 @@ /*- * #%L - * Autocompletion for the jython language in the Script Editor + * Jython language support for SciJava Script Editor. * %% - * Copyright (C) 2020 - 2022 Albert Cardona + * Copyright (C) 2020 - 2024 SciJava developers. * %% - * 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. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: * - * 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. + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * . + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. * #L% */ -package sc.fiji.jython.autocompletion; +package org.scijava.plugins.scripteditor.jython; import java.io.File; import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.Parameter; import java.nio.file.FileVisitOption; import java.nio.file.Files; import java.nio.file.Path; @@ -30,6 +39,7 @@ import java.util.Collections; import java.util.Comparator; import java.util.List; +import java.util.Map; import java.util.function.Function; import java.util.jar.JarEntry; import java.util.jar.JarFile; @@ -37,22 +47,22 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; +import javax.swing.text.JTextComponent; + import org.fife.ui.autocomplete.BasicCompletion; import org.fife.ui.autocomplete.Completion; import org.fife.ui.autocomplete.CompletionProvider; +import org.fife.ui.autocomplete.FunctionCompletion; +import org.fife.ui.autocomplete.ParameterChoicesProvider; +import org.fife.ui.autocomplete.ParameterizedCompletion; import org.python.indexer.types.NModuleType; -import org.scijava.ui.swing.script.autocompletion.AutoCompletionListener; -import org.scijava.ui.swing.script.autocompletion.JythonAutocompletionProvider; +import org.scijava.ui.swing.script.autocompletion.CompletionText; -public class JythonAutoCompletions implements AutoCompletionListener -{ - static { - // Register as listener for jython autocompletions - JythonAutocompletionProvider.addAutoCompletionListener(new JythonAutoCompletions()); - } +public class JythonAutoCompletions { static private final Pattern assign = Pattern.compile("^([ \\t]*)(([a-zA-Z_][a-zA-Z0-9_ \\t,]*)[ \\t]+=[ \\t]+(.*))$"), - nameToken = Pattern.compile("^(.*?[ \\t]+|)([a-zA-Z_][a-zA-Z0-9_]+)$"), + nameToken = Pattern.compile("^(.*?[ \\t,\\[=\\(]+)([a-zA-Z_][a-zA-Z0-9_]+)$"), + invocation = Pattern.compile("^(.*?[ \\t]+|)([a-zA-Z_][a-zA-Z0-9_]+\\()$"), dotNameToken = Pattern.compile("^(.*?[ \\t]+|)([a-zA-Z0-9_\\.\\[\\](){}]+)\\.([a-zA-Z0-9_]*)$"), endingCode = Pattern.compile("^([ \\t]*)[^#]*?(.*?)[ \\t]*:[ \\t]*(#.*|)[\\n]*$"), sysPathAppend = Pattern.compile("sys.path.append[ \\t]*[(][ \\t]*['\"](.*?)['\"][ \\t]*[)]"), // fragile to line breaks in e.g. .append @@ -82,7 +92,7 @@ public List apply(final Path filepath) { .collect(Collectors.toList()); return modules; } catch (Exception e) { - e.printStackTrace(); + JythonDev.print("Failed to load jython module", e); } finally { if (null != jar) try { jar.close(); } catch (Exception ee) {} } @@ -90,7 +100,7 @@ public List apply(final Path filepath) { } }).findFirst().orElse(Collections.emptyList()); } catch (IOException e) { - e.printStackTrace(); + JythonDev.print("Cannot find jython-slim-*.jar file", e); } finally { jython_jar_modules = ls; } @@ -99,17 +109,16 @@ public List apply(final Path filepath) { public JythonAutoCompletions() {} - @Override - public List completionsFor(final CompletionProvider provider, String codeWithoutLastLine, final String lastLine, final String alreadyEnteredText) { + public List completionsFor(final JythonAutocompletionProvider provider, String codeWithoutLastLine, final String lastLine, final String alreadyEnteredText) { // Replacing of text will start at crop, given the already entered text that is considered for replacement final int crop = lastLine.length() - alreadyEnteredText.length(); // Query the lastLine to find out what needs autocompletion - // Preconditions 1: can't expand when ending with any of: "()[]{},; " + // Preconditions 1: can't expand when ending with any of: "[]{},; " final char lastChar = lastLine.charAt(lastLine.length() -1); - if (0 == lastLine.length() || "()[]{},; ".indexOf(lastChar) > -1) + if (0 == lastLine.length() || "[]{},; ".indexOf(lastChar) > -1) return Collections.emptyList(); // Preconditions 2: codeWithoutLastLine has to be valid @@ -117,14 +126,14 @@ public List completionsFor(final CompletionProvider provider, String // so that the ParserFacade can work boolean add_pass = false; if (codeWithoutLastLine.endsWith("\n")) { - JythonScriptParser.print("codeWithoutLastLine ends with line break"); + JythonDev.printTrace("codeWithoutLastLine ends with line break"); final int priorLineBreak = codeWithoutLastLine.lastIndexOf('\n', codeWithoutLastLine.length() - 2); final String endingLine = codeWithoutLastLine.substring(priorLineBreak + 1); final Matcher me = endingCode.matcher(endingLine); if (me.find()) { codeWithoutLastLine = codeWithoutLastLine.substring(0, priorLineBreak + 1) + me.group(1) + me.group(2); add_pass = true; - JythonScriptParser.print("changed code to: \n" + codeWithoutLastLine + "\n###"); + JythonDev.printTrace("changed code to: \n" + codeWithoutLastLine + "\n###"); } } @@ -136,10 +145,9 @@ public List completionsFor(final CompletionProvider provider, String if (path.exists() && path.isDirectory() && !Scope.indexer.getLoadPath().stream().filter(s -> path.equals(new File(s))).findFirst().isPresent()) Scope.indexer.addPath(path.getAbsolutePath()); } - JythonScriptParser.print("PYTHONPATH:\n" + String.join("\n", Scope.indexer.getLoadPath())); + JythonDev.printTrace("PYTHONPATH:\n" + String.join("\n", Scope.indexer.getLoadPath())); } catch (Exception e) { - System.out.println("Failed to add path from sys.path.append expression."); - e.printStackTrace(); + JythonDev.print("Failed to add path from sys.path.append expression.", e); } // Situations to autocomplete: @@ -171,7 +179,7 @@ public List completionsFor(final CompletionProvider provider, String : s.substring(dir.length(), s.length() -3)) // remove ending ".py" .replace('/', '.')); } catch (IOException e) { - e.printStackTrace(); + JythonDev.print("Failed to read jython module file.", e); } return null; }).flatMap(Function.identity()) @@ -216,10 +224,57 @@ public List completionsFor(final CompletionProvider provider, String } final Matcher m1 = nameToken.matcher(lastLine); + /* if (m1.find()) return JythonScriptParser.parseAST(codeWithoutLastLine).getLast().findStartsWith(m1.group(2)).stream() .map(s -> new BasicCompletion(provider, (lastLine + s.substring(m1.group(2).length())).substring(crop))) .collect(Collectors.toList()); + */ + + if (m1.find()) { + final Scope scope = JythonScriptParser.parseAST(codeWithoutLastLine).getLast(); + // Handle argument suggestions for constructors and functions + provider.setParameterChoicesProvider(new CustomParameterChoicesProvider(provider, scope)); + final Map names = scope.findStartsWith2(m1.group(2)); + final ArrayList completions = new ArrayList<>(); + for (final Map.Entry e : names.entrySet()) { + final String classname = e.getValue(); + // Add a constructor parameterized completion + if (null != classname) { + try { + final Class c = Class.forName(classname); + for (final Constructor constructor : c.getConstructors()) { + completions.add(makeDotCompletion( + crop > -1 && crop < m1.group(1).length() ? m1.group(1).substring(crop) : "", + m1.group(2), new CompletionText(e.getKey(), c, constructor), provider)); + } + } catch (ClassNotFoundException cnfe) { + JythonDev.printTrace("Can't load class: " + classname); + } + } + // Add the simple classname completion + completions.add(new BasicCompletion(provider, (lastLine + e.getKey().substring(m1.group(2).length())).substring(crop))); + } + return completions; + } + + JythonDev.printTrace("invocation.matcher:"); + final Matcher m1c = invocation.matcher(lastLine); + if (m1c.find()) { + final String name = m1c.group(2).substring(0, m1c.group(2).length() -1); + JythonDev.printTrace(" name: " + name); + final Scope scope = JythonScriptParser.parseAST(codeWithoutLastLine).getLast(); + final DotAutocompletions da = scope.find(name, DotAutocompletions.EMPTY); + provider.setParameterChoicesProvider(new CustomParameterChoicesProvider(provider, scope)); + JythonDev.print(da); + if (da instanceof ConstructorAutocompletions) { + JythonDev.printTrace("da is a ConstructorAutocompletions"); + return da.get().stream() + .map(ct -> makeDotCompletion("", name, ct, provider)) // TODO pre is wrong: see below for hints + .collect(Collectors.toList()); + } + // TODO and functions + } final Matcher m2 = dotNameToken.matcher(lastLine); if (m2.find()) { @@ -245,20 +300,26 @@ public List completionsFor(final CompletionProvider provider, String String suffix = ""; if (add_pass) { add_pass = false; // don't - JythonScriptParser.print("Removed ' pass'"); + JythonDev.printTrace("Removed ' pass'"); suffix = ":\n "; } varName = "____GRAB____"; // an injected var to capture the returned class code = codeWithoutLastLine + (add_pass ? ": pass" : "") + suffix + lastLine.substring(0, start) + varName + " = " + lastLine.substring(start, lastLine.length() - 1 - seed.length()); - JythonScriptParser.print("codeWithoutLastLine:\n" + codeWithoutLastLine); + JythonDev.printTrace("codeWithoutLastLine:\n" + codeWithoutLastLine); } - final DotAutocompletions da = JythonScriptParser.parseAST(code).getLast().find(varName, DotAutocompletions.EMPTY); + final Scope scope = JythonScriptParser.parseAST(code); + final DotAutocompletions da = scope.getLast().find(varName, DotAutocompletions.EMPTY); final String fullPre = lastLine.substring(crop); final String pre = fullPre.substring(0, fullPre.lastIndexOf(seed)); final String lowerCaseSeed = seed.toLowerCase(); + + // Depends on scope + provider.setParameterChoicesProvider(new CustomParameterChoicesProvider(provider, scope)); + List list = da.get().stream() .filter(s -> s.getReplacementText().toLowerCase().contains(lowerCaseSeed)) - .map(s -> s.getCompletion(provider, pre + s.getReplacementText(), s.getReplacementText().startsWith(seed) ? 1 : 0)) + //.map(s -> s.getCompletion(provider, pre + s.getReplacementText(), s.getReplacementText().startsWith(seed) ? 1 : 0)) + .map(s -> makeDotCompletion(pre, lowerCaseSeed, s, provider)) .collect(Collectors.toList()); sortCompletions(list, seed); return list; @@ -266,6 +327,79 @@ public List completionsFor(final CompletionProvider provider, String return Collections.emptyList(); } + + protected static Completion makeDotCompletion(final String pre, final String seed, final CompletionText ct, final CompletionProvider provider) { + final List ps = ct.getMethodArgs(); + if (null != ps && null != ct.getReturnType()) { // ) && !ps.isEmpty()) { + JythonDev.printTrace("using FunctionCompletion: ps is " + ps.stream().map(Parameter::toString).collect(Collectors.joining(", ", "[", "]"))); + String text = ct.getReplacementText(); + if (text.endsWith("()")) text = text.substring(0, text.length() -2); // remove trailing parentheses + final FunctionCompletion fc = new CustomFunctionCompletion( + provider, + pre + text, + ct.getReturnType()); + fc.setReturnValueDescription(ct.getReturnType()); + fc.setShortDescription(ct.getSummary()); // CompletionText.getDescription returns null + //fc.setSummary(ct.getSummary()); // useless: later, FunctionCompletion doesn't use the summary from its superclass + final ArrayList params = new ArrayList<>(); + for (int i=0; i getParameterChoices(JTextComponent tc, + org.fife.ui.autocomplete.ParameterizedCompletion.Parameter param) { + final Object typeObj = param.getTypeObject(); + Class clazz = null; + if (null != typeObj && typeObj instanceof Class) { + clazz = (Class)typeObj; + JythonDev.printTrace("class: " + clazz + ", " + clazz.getCanonicalName()); + } + switch (param.getType()) { + case "int": clazz = Integer.class; break; + case "long": clazz = Long.class; break; + case "float": clazz = Float.class; break; + case "double": clazz = Double.class; break; + case "boolean": clazz = Boolean.class; break; + case "char": clazz = Character.class; break; + case "short": clazz = Short.class; break; + case "byte": clazz = Byte.class; break; + } + if (null != clazz) try { + JythonDev.printTrace("type is: " + param.getType()); + JythonDev.printTrace("class is: " + clazz.getCanonicalName()); + final List bc = scope + .findVarsByType(param.getType(), clazz) + .map(varName -> new BasicCompletion(provider, varName)) + .collect(Collectors.toList()); + for (int i=0; i asCompletionList(final Stream stream, final String pre) { + return stream + .map((s) -> new BasicCompletion(JythonAutocompletionProvider.this, pre + s)) + .collect(Collectors.toList()); + } + + @Override + public List getCompletionsImpl(final JTextComponent comp) { + final ArrayList completions = new ArrayList<>(); + String currentLine, + codeWithoutLastLine, + alreadyEnteredText = this.getAlreadyEnteredText(comp); + try { + codeWithoutLastLine = comp.getText(0, comp.getCaretPosition()); + final int lastLineBreak = codeWithoutLastLine.lastIndexOf("\n") + 1; + currentLine = codeWithoutLastLine.substring(lastLineBreak); // up to the caret position + codeWithoutLastLine = codeWithoutLastLine.substring(0, lastLineBreak); + } catch (BadLocationException e1) { + e1.printStackTrace(); + return completions; + } + // Completions provided by listeners (e.g. for methods and fields and variables and builtins from jython-autocompletion package) + try { + final List cs = autoCompletions.completionsFor(this, codeWithoutLastLine, currentLine, alreadyEnteredText); + if (cs != null) completions.addAll(cs); + } + catch (Exception e) { + JythonDev.print("Failed to get autocompletions from " + autoCompletions); + JythonDev.printError(e); + } + // Java class discovery for completions with auto-imports + completions.addAll(getCompletions(alreadyEnteredText)); + return completions; + } + + /** Completions to discover (autocomplete imports) and auto-import java classes. */ + public List getCompletions(final String text) { + // don't block + if (!ClassUtil.isCacheReady()) return Collections.emptyList(); + + // E.g. "from ij" to expand to a package name and class like ij or ij.gui or ij.plugin + final Matcher m1 = fromImport.matcher(text); + if (m1.find()) + return asCompletionList(ClassUtil.findClassNamesContaining(m1.group(3)).map(formatter::singleToImportStatement), ""); + + final Matcher m1f = fastImport.matcher(text); + if (m1f.find()) + return asCompletionList(ClassUtil.findClassNamesForPackage(m1f.group(2)).map(formatter::singleToImportStatement), ""); + + // E.g. "from ij.gui import Roi, Po" to expand to PolygonRoi, PointRoi for Jython + final Matcher m2 = importStatement.matcher(text); + if (m2.find()) { + final String packageName = m2.group(3); + String className = m2.group(4); // incomplete or empty, or multiple separated by commas with the last one incomplete or empty + + JythonDev.print("m2 matches className: " + className); + final String[] bycomma = className.split(","); + String precomma = ""; + if (bycomma.length > 1) { + className = bycomma[bycomma.length -1].trim(); // last one + for (int i=0; i stream; + if (className.length() > 0) + stream = ClassUtil.findClassNamesStartingWith(null == packageName ? className : packageName + "." + className); + else + stream = ClassUtil.findClassNamesForPackage(packageName); + // Simple class names + stream = stream.map((s) -> s.substring(Math.max(0, s.lastIndexOf('.') + 1))); + return asCompletionList(stream, m2.group(1) + precomma); + } + + final Matcher m3 = simpleClassName.matcher(text); + if (m3.find()) { + // Side effect: insert the import at the top of the file if necessary + //return asCompletionList(ClassUtil.findSimpleClassNamesStartingWith(m3.group(2)).stream(), m3.group(1)); + return ClassUtil.findSimpleClassNamesStartingWith(m3.group(2)).stream() + .map(className -> new ImportCompletionImpl(JythonAutocompletionProvider.this, + m3.group(1) + className.substring(className.lastIndexOf('.') + 1), + className, + formatter.singleToImportStatement(className))) + .collect(Collectors.toList()); + } + + + /* Covered by listener from jython-completions + + final Matcher m4 = staticMethodOrField.matcher(text); + try { + + String simpleClassName; + String methodOrFieldSeed; + String pre; + boolean isStatic; + + if (m4.find()) { + + // a call to a static class + pre = m4.group(1); + simpleClassName = m4.group(3); // expected complete, e.g. ImagePlus + methodOrFieldSeed = m4.group(4).toLowerCase(); // incomplete: e.g. "GR", a string to search for in the class declared fields or methods + isStatic = true; + + } else { + + // a call to an instantiated class + final String[] varAndSeed = getVariableAnSeedAtCaretLocation(); + if (varAndSeed == null) return Collections.emptyList(); + + simpleClassName = JythonAutoCompletion.findClassAliasOfVariable(varAndSeed[0], text_area.getText()); + if (simpleClassName == null) return Collections.emptyList(); + + pre = varAndSeed[0] + "."; + methodOrFieldSeed = varAndSeed[1]; + isStatic = false; + +// System.out.println("simpleClassName: " + simpleClassName); +// System.out.println("methodOrFieldSeed: " + methodOrFieldSeed); + + } + + // Retrieve all methods and fields, if the seed is empty + final boolean includeAll = methodOrFieldSeed.trim().isEmpty(); + + // Scan the script, parse the imports, find first one matching + final Import im = JythonAutoCompletion.findImportedClasses(text_area.getText()).get(simpleClassName); + if (null != im) { + try { + final Class c = Class.forName(im.className); + final ArrayList completions = new ArrayList<>(); + for (final Field f: c.getFields()) { + if (isStatic == Modifier.isStatic(f.getModifiers()) && + (includeAll || f.getName().toLowerCase().contains(methodOrFieldSeed))) + completions.add(ClassUtil.getCompletion(this, pre, f, c)); + } + for (final Method m: c.getMethods()) { + if (isStatic == Modifier.isStatic(m.getModifiers()) && + (includeAll || m.getName().toLowerCase().contains(methodOrFieldSeed))) + completions.add(ClassUtil.getCompletion(this, pre, m, c)); + } + + Collections.sort(completions, new Comparator() { + int prefix1Index = Integer.MAX_VALUE; + int prefix2Index = Integer.MAX_VALUE; + @Override + public int compare(final Completion o1, final Completion o2) { + prefix1Index = Integer.MAX_VALUE; + prefix2Index = Integer.MAX_VALUE; + if (o1.getReplacementText().startsWith(pre)) + prefix1Index = 0; + if (o2.getReplacementText().startsWith(pre)) + prefix2Index = 0; + if (prefix1Index == prefix2Index) + return o1.compareTo(o2); + else + return prefix1Index - prefix2Index; + } + }); + + return completions; + } catch (final ClassNotFoundException ignored) { + return ClassUtil.classUnavailableCompletions(this, simpleClassName + "."); + } + } + } catch (final Exception e) { + e.printStackTrace(); + } + + */ + + return Collections.emptyList(); + } + + @SuppressWarnings("unused") + private String[] getVariableAnSeedAtCaretLocation() { + try { + final int caretOffset = text_area.getCaretPosition(); + final int lineNumber = text_area.getLineOfOffset(caretOffset); + final int startOffset = text_area.getLineStartOffset(lineNumber); + final String lineUpToCaret = text_area.getText(startOffset, caretOffset - startOffset); + final String[] words = lineUpToCaret.split("\\s+"); + final String[] varAndSeed = words[words.length - 1].split("\\."); + return (varAndSeed.length == 2) ? varAndSeed : new String[] { varAndSeed[varAndSeed.length - 1], "" }; + } catch (final BadLocationException e) { + JythonDev.printError(e); + } + return null; + } + +} diff --git a/src/main/java/org/scijava/plugins/scripteditor/jython/JythonDev.java b/src/main/java/org/scijava/plugins/scripteditor/jython/JythonDev.java new file mode 100644 index 0000000..dec8aa5 --- /dev/null +++ b/src/main/java/org/scijava/plugins/scripteditor/jython/JythonDev.java @@ -0,0 +1,65 @@ +/*- + * #%L + * Jython language support for SciJava Script Editor. + * %% + * Copyright (C) 2020 - 2024 SciJava developers. + * %% + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * #L% + */ +package org.scijava.plugins.scripteditor.jython; + +public class JythonDev +{ + static public int SILENT = 0, + MESSAGES = 1, + ERRORS = 2; + + /** Adjust value to see debugging information, including: + * SILENT: nothing is printed at all. + * MESSAGES: prints light messages indicating some internals and the kinds of errors. + * ERRORS: prints everything including exceptions. + */ + static public int debug = MESSAGES; + + static public final void print(Object s) { + if (debug >= MESSAGES) System.out.println(s); + } + + static public final void printError(Throwable e) { + if (debug >= ERRORS) e.printStackTrace(); + } + + static public final void printTrace(Object s) { + if (debug >= ERRORS) System.out.println(s); + } + + static public final void print(Object s, Throwable e) { + if (debug >= ERRORS) { + System.out.println(s); + e.printStackTrace(); + } else if (debug >= MESSAGES) { + System.out.println(s.toString() + " :: " + e.getMessage()); + } + } + +} diff --git a/src/main/java/org/scijava/plugins/scripteditor/jython/JythonImportFormat.java b/src/main/java/org/scijava/plugins/scripteditor/jython/JythonImportFormat.java new file mode 100644 index 0000000..b63c473 --- /dev/null +++ b/src/main/java/org/scijava/plugins/scripteditor/jython/JythonImportFormat.java @@ -0,0 +1,47 @@ +/*- + * #%L + * Jython language support for SciJava Script Editor. + * %% + * Copyright (C) 2020 - 2024 SciJava developers. + * %% + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * #L% + */ +package org.scijava.plugins.scripteditor.jython; + +import org.scijava.ui.swing.script.autocompletion.ImportFormat; + +public class JythonImportFormat implements ImportFormat +{ + @Override + public final String singleToImportStatement(final String className) { + final int idot = className.lastIndexOf('.'); + if (-1 == idot) + return "import " + className; + return dualToImportStatement(className.substring(0, idot), className.substring(idot + 1)); + } + + @Override + public String dualToImportStatement(final String packageName, final String simpleClassName) { + return "from " + packageName + " import " + simpleClassName; + } +} diff --git a/src/main/java/org/scijava/plugins/scripteditor/jython/JythonLanguageSupportPlugin.java b/src/main/java/org/scijava/plugins/scripteditor/jython/JythonLanguageSupportPlugin.java new file mode 100644 index 0000000..cb944e2 --- /dev/null +++ b/src/main/java/org/scijava/plugins/scripteditor/jython/JythonLanguageSupportPlugin.java @@ -0,0 +1,90 @@ +/*- + * #%L + * Jython language support for SciJava Script Editor. + * %% + * Copyright (C) 2020 - 2024 SciJava developers. + * %% + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * #L% + */ +package org.scijava.plugins.scripteditor.jython; + +import org.fife.rsta.ac.AbstractLanguageSupport; +import org.fife.ui.autocomplete.AutoCompletion; +import org.fife.ui.autocomplete.CompletionProvider; +import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; +import org.scijava.Priority; +import org.scijava.plugin.Plugin; +import org.scijava.ui.swing.script.LanguageSupportPlugin; +import org.scijava.ui.swing.script.LanguageSupportService; + +/** + * {@link LanguageSupportPlugin} for the jython language. + * + * @author Albert Cardona + * + * @see LanguageSupportService + */ +@Plugin(type = LanguageSupportPlugin.class, priority = Priority.HIGH) +public class JythonLanguageSupportPlugin extends AbstractLanguageSupport implements LanguageSupportPlugin +{ + + private AutoCompletion ac; + private RSyntaxTextArea text_area; + + public JythonLanguageSupportPlugin() { + setAutoCompleteEnabled(true); + setParameterAssistanceEnabled(true); + setShowDescWindow(true); + } + + @Override + public String getLanguageName() { + return "Python (Jython)"; + } + + @Override + public void install(final RSyntaxTextArea textArea) { + this.text_area = textArea; + this.ac = this.createAutoCompletion(null); + this.ac.setParameterAssistanceEnabled(true); + this.ac.install(textArea); + // store upstream + super.installImpl(textArea, this.ac); + } + + @Override + public void uninstall(final RSyntaxTextArea textArea) { + if (textArea == this.text_area) { + super.uninstallImpl(textArea); // will call this.acp.uninstall(); + } + } + + /** + * Ignores the argument. + */ + @Override + protected AutoCompletion createAutoCompletion(CompletionProvider p) { + return new JythonAutoCompletion(new JythonAutocompletionProvider(text_area, new JythonImportFormat())); + } + +} diff --git a/src/main/java/sc/fiji/jython/autocompletion/JythonScriptParser.java b/src/main/java/org/scijava/plugins/scripteditor/jython/JythonScriptParser.java similarity index 73% rename from src/main/java/sc/fiji/jython/autocompletion/JythonScriptParser.java rename to src/main/java/org/scijava/plugins/scripteditor/jython/JythonScriptParser.java index 8aa41ee..59d2de5 100644 --- a/src/main/java/sc/fiji/jython/autocompletion/JythonScriptParser.java +++ b/src/main/java/org/scijava/plugins/scripteditor/jython/JythonScriptParser.java @@ -1,25 +1,32 @@ /*- * #%L - * Autocompletion for the jython language in the Script Editor + * Jython language support for SciJava Script Editor. * %% - * Copyright (C) 2020 - 2022 Albert Cardona + * Copyright (C) 2020 - 2024 SciJava developers. * %% - * 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. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: * - * 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. + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * . + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. * #L% */ -package sc.fiji.jython.autocompletion; +package org.scijava.plugins.scripteditor.jython; import java.lang.reflect.Method; import java.util.ArrayList; @@ -33,6 +40,7 @@ import org.python.antlr.PythonTree; import org.python.antlr.ast.Assign; import org.python.antlr.ast.Attribute; +import org.python.antlr.ast.BinOp; import org.python.antlr.ast.Call; import org.python.antlr.ast.ClassDef; import org.python.antlr.ast.Expr; @@ -44,6 +52,7 @@ import org.python.antlr.ast.Name; import org.python.antlr.ast.Num; import org.python.antlr.ast.Return; +import org.python.antlr.ast.Str; import org.python.antlr.ast.TryExcept; import org.python.antlr.ast.TryFinally; import org.python.antlr.ast.Tuple; @@ -57,29 +66,30 @@ import org.python.core.CompileMode; import org.python.core.CompilerFlags; import org.python.core.ParserFacade; +import org.python.core.PyFloat; import org.python.core.PyInteger; import org.python.core.PyObject; import org.python.indexer.types.NModuleType; import org.scijava.ui.swing.script.autocompletion.CompletionText; -public class JythonScriptParser { - - /** Controls whether debugging statements print to stdout. */ - static public boolean DEBUG = false; - +public class JythonScriptParser +{ /** * Parse valid jython code. * - * @return The top-level {@code Scope}, which is empty (see {@code {@link Scope#isEmpty()}) when the code has errors and can't be parsed by {@code ParserFacade#parse(String, CompileMode, String, CompilerFlags)}. + * @param code + * + * @return The top-level {@link Scope}, which is empty (see {@link Scope#isEmpty()}) when the code has errors and can't be parsed by {@link ParserFacade#parse(String, CompileMode, String, CompilerFlags)}. */ static public Scope parseAST(final String code) { // The code includes from beginning of the file until the point at which an autocompletion is requested. // Therefore, remove the last line, which would fail to parse because it is incomplete try { final mod m = ParserFacade.parse(code, CompileMode.exec, "", new CompilerFlags()); - return parseNode(m.getChildren(), null, null); + final Scope scope = parseNode(m.getChildren(), null, null); + return null == scope ? new Scope(null) : scope; } catch (Throwable t) { - t.printStackTrace(); + JythonDev.printError(t); return new Scope(null); } } @@ -94,7 +104,7 @@ static public Scope parseAST(final String code) { * @return A new {@code Scope} containing {@code DotAutocompletions} to represent each statement. */ static public Scope parseNode(final List children, final Scope parent, final String className) { - if (null == children) return parent; + if (null == children) return parent; // will return null if parent is null final Scope scope = new Scope(parent, className); parseNode(scope, children, className); return scope; @@ -103,7 +113,7 @@ static public Scope parseNode(final List children, final Scope paren static public void parseNode(final Scope scope, final List children, final String className) { for (final PythonTree child : children) { - print(child.getClass()); + JythonDev.printTrace(child.getClass()); if (child instanceof ImportFrom) scope.imports.putAll(parseImportFromStatement( (ImportFrom)child )); @@ -122,7 +132,7 @@ else if (child instanceof If || child instanceof For || child instanceof While // no new scope in if/for/while/with/try/ statements in python parseNode(scope, child.getChildren(), null); else - print("IGNORING child: " + child + " -- " + (null != child.getChildren() ? + JythonDev.printTrace("IGNORING child: " + child + " -- " + (null != child.getChildren() ? String.join("::", child.getChildren().stream().map(c -> c.toString()).collect(Collectors.toList())) : "")); } @@ -130,7 +140,7 @@ else if (child instanceof If || child instanceof For || child instanceof While static public void parseExpr(final Expr child, final Scope scope) { // child.getText() shows child is the base - print("Expr: " + child.getText() + ", " + child.getInternalValue() + ", " + child.getValue() + ", children: " + String.join(", ", child.getChildren().stream().map(PythonTree::toString).collect(Collectors.toList()))); + JythonDev.printTrace("Expr: " + child.getText() + ", " + child.getInternalValue() + ", " + child.getValue() + ", children: " + String.join(", ", child.getChildren().stream().map(PythonTree::toString).collect(Collectors.toList()))); } /** @@ -161,6 +171,15 @@ static public Map parseImportStatement(final Import return classes; } + static private DotAutocompletions maybeStaticToDot(final PythonTree node, final DotAutocompletions da) { + JythonDev.printTrace("children count:" + node.getChildCount() + ", children: " + (null != node.getChildren() ? node.getChildren().stream().map(c -> c.toString()).collect(Collectors.toList()) : "")); + if (node.getChildCount() > 0 && da instanceof StaticDotAutocompletions) { + // It's a right expression (a constructor invocation assigned to a variable on the left) so the left is an instance of the class + return new VarDotAutocompletions(da.getClassname()); + } + return da; + } + /** * Parse an assignment (an equal sign) to find out the class of the left side (the variable) * by asking the right side about what it is or returns. @@ -180,17 +199,17 @@ static public Map parseAssignStatement(final Assign for (int i=0; i parseAssignStatement(final Assign * Adds a child Scope to the given parent Scope, and also a variable to the parent scope * with no class, just for the function name. Then populates the child scope. * - * @fn - * @parent + * @param fn + * @param parent */ static public void parseFunctionDef(final FunctionDef fn, final Scope parent) { // Get the function name @@ -287,7 +306,7 @@ static public void parseClassDef(final ClassDef c, final Scope parent) { for (final expr e: c.getInternalBases()) { final DotAutocompletions da = parent.find(e.getText(), null); if (null == da || null == da.getClassname()) - print("Could not find completions and className for " + e.getText()); + JythonDev.print("Could not find completions and className for " + e.getText()); else superclassNames.add(da.getClassname()); } @@ -324,6 +343,7 @@ static public void parseClassDef(final ClassDef c, final Scope parent) { /** Discover the class returned by the right statement in an assignment. * * @param right + * @param scope */ static public DotAutocompletions parseRight(final PyObject right, final Scope scope) { if (right instanceof Name) { @@ -336,8 +356,12 @@ static public DotAutocompletions parseRight(final PyObject right, final Scope sc if (right instanceof Num) { // e.g. return 10 // e.g. n = 42 - final Class c = ((Num)right).getInternalN().getClass() == PyInteger.class ? Long.TYPE : Double.TYPE; - return new VarDotAutocompletions(c.toString()); + final Class c = ((Num)right).getInternalN().getClass() == PyInteger.class ? Long.TYPE : Double.TYPE; // TODO this creates trouble for Scope.findVarsByType and would be perhaps easier as Long and Double (non-primitive). + return new VarDotAutocompletions(c.toString()); // becomes "long" or "double" + } + if (right instanceof Str) { + // Literal String + return new VarDotAutocompletions(String.class.getCanonicalName()); } if (right instanceof Attribute) { // e.g. a field or a method @@ -355,7 +379,7 @@ static public DotAutocompletions parseRight(final PyObject right, final Scope sc return new VarDotAutocompletions(m.getReturnType().getName()); return new VarDotAutocompletions(c.getField(name).getType().getName()); } catch (Exception e) { - print("Could not find method or field " + name + " in class " + className); + JythonDev.print("Could not find method or field " + name + " in class " + className, e); } // Could also be a python module, e.g. attempting to autocomplete "os.path." try { @@ -363,7 +387,7 @@ static public DotAutocompletions parseRight(final PyObject right, final Scope sc if (null != module) return new StaticDotAutocompletions(className + "." + name); } catch (Exception e) { - print("Not a python module: " + className + "." + name); + JythonDev.printTrace("Not a python module: " + className + "." + name); } } if (right instanceof Call) { @@ -376,11 +400,33 @@ static public DotAutocompletions parseRight(final PyObject right, final Scope sc final Yield yield = (Yield)right; return parseRight(yield.getValue(), scope); } + if (right instanceof BinOp) { + // e.g., division, multiplication, addition, subtraction + // What actual type is returned, I don't know: python allows operator overloading. + final BinOp binop = (BinOp)right; + // Weak attempt at finding out what is it (will not succeed if neither is a number) + // TODO this should be done recursively + JythonDev.printTrace("BinOp: weak attempt at finding out what kind of number it returns."); + // First, check if any is a number + final Class typeL = binop.getLeft().isNumberType() ? ((Num)binop.getLeft()).getInternalN().getClass() : null, + typeR = binop.getRight().isNumberType() ? ((Num)binop.getRight()).getInternalN().getClass() : null; + if (null != typeL || null != typeR) { + // If both are integers + if (typeL == PyInteger.class && typeR == PyInteger.class) + return new VarDotAutocompletions(Long.class.toString()); // long + // If any is a float + if (typeL == PyFloat.class || typeR == PyFloat.class) + return new VarDotAutocompletions(Double.class.toString()); // double + } + // Go by whatever left is, or if empty, whatever right is: no guarantee to be correct, but can be correct often + final DotAutocompletions da = parseRight(binop.getLeft(), scope); + if (da != DotAutocompletions.EMPTY) + return da; + return parseRight(binop.getRight(), scope); + } + + JythonDev.printTrace("Unsupported 'right' is: " + right + " " + (right != null ? right.getClass() : "")); return DotAutocompletions.EMPTY; } - - static public final void print(Object s) { - if (DEBUG) System.out.println(s); - } } diff --git a/src/main/java/org/scijava/plugins/scripteditor/jython/JythonScriptSyntaxHighlighter.java b/src/main/java/org/scijava/plugins/scripteditor/jython/JythonScriptSyntaxHighlighter.java new file mode 100644 index 0000000..da40922 --- /dev/null +++ b/src/main/java/org/scijava/plugins/scripteditor/jython/JythonScriptSyntaxHighlighter.java @@ -0,0 +1,46 @@ +/* + * #%L + * Jython language support for SciJava Script Editor. + * %% + * Copyright (C) 2020 - 2024 SciJava developers. + * %% + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * #L% + */ + +package org.scijava.plugins.scripteditor.jython; + +import org.fife.ui.rsyntaxtextarea.modes.PythonTokenMaker; +import org.scijava.plugin.Plugin; +import org.scijava.ui.swing.script.SyntaxHighlighter; + +/** + * SyntaxHighlighter for Python (Jython). + * + * @author Karl Duderstadt + */ +@Plugin(type = SyntaxHighlighter.class, name = "python-(jython)") +public class JythonScriptSyntaxHighlighter extends PythonTokenMaker implements +SyntaxHighlighter +{ + // Everything implemented in PythonTokenMaker +} diff --git a/src/main/java/sc/fiji/jython/autocompletion/Scope.java b/src/main/java/org/scijava/plugins/scripteditor/jython/Scope.java similarity index 56% rename from src/main/java/sc/fiji/jython/autocompletion/Scope.java rename to src/main/java/org/scijava/plugins/scripteditor/jython/Scope.java index c1363db..933db4d 100644 --- a/src/main/java/sc/fiji/jython/autocompletion/Scope.java +++ b/src/main/java/org/scijava/plugins/scripteditor/jython/Scope.java @@ -1,25 +1,32 @@ /*- * #%L - * Autocompletion for the jython language in the Script Editor + * Jython language support for SciJava Script Editor. * %% - * Copyright (C) 2020 - 2022 Albert Cardona + * Copyright (C) 2020 - 2024 SciJava developers. * %% - * 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. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: * - * 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. + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * . + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. * #L% */ -package sc.fiji.jython.autocompletion; +package org.scijava.plugins.scripteditor.jython; import java.io.File; import java.nio.file.FileSystems; @@ -34,12 +41,14 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import java.util.stream.Stream; import org.python.indexer.Indexer; import org.python.indexer.types.NModuleType; import org.scijava.ui.swing.script.autocompletion.CompletionText; + public class Scope { final Scope parent; final String className; // if any @@ -71,7 +80,7 @@ public void run() { return; } if (keys.containsKey(key)) { - System.out.println("Python module at:\n" + keys.get(key) + "\n ... was updated. Clearing indexer cache."); + JythonDev.print("Python module at:\n" + keys.get(key) + "\n ... was updated. Clearing indexer cache."); // One of the files changed: unload all, given that parent modules would have been loaded as well // and it gets complicated quickly to find out which need to be reloaded and which don't. keys.clear(); @@ -85,7 +94,7 @@ public void run() { module_watcher.setPriority(Thread.NORM_PRIORITY); module_watcher.start(); } catch (Exception e ){ - System.out.println("Failed to start filesystem watcher service for python modules"); + JythonDev.print("Failed to start filesystem watcher service for python modules", e); } } @@ -105,8 +114,7 @@ static NModuleType loadPythonModule(final String qname) { mod = indexer.loadModule(qname); if (null == mod) return null; } catch (Exception e) { - System.out.println("Could not load python module named " + qname); - e.printStackTrace(); + JythonDev.print("Could not load python module named " + qname, e); return null; } try { @@ -121,12 +129,10 @@ static NModuleType loadPythonModule(final String qname) { StandardWatchEventKinds.ENTRY_DELETE); keys.put(key, path); } else { - System.out.println("Python module " + qname + " doesn't have an associated file path."); + JythonDev.print("Python module " + qname + " doesn't have an associated file path."); } } catch (Exception e) { - System.out.println("Could not load python module named " + qname); - System.out.println(e.getMessage()); - e.printStackTrace(); + JythonDev.print("Could not load python module named " + qname, e); } return mod; } @@ -190,6 +196,93 @@ public List findStartsWith(final String name) { return completions; } + /** Return a table of names vs classnames, with classnames being null for python builtins. + * + * @param name + * @return + */ + public Map findStartsWith2(final String name) { + final Map completions = new HashMap<>(); + Scope scope = this; + while (null != scope) { + for (final Map.Entry e: scope.vars.entrySet()) { + if (e.getKey().startsWith(name)) completions.put(e.getKey(), e.getValue().getClassname()); + } + for (final Map.Entry e: scope.imports.entrySet()) { + if (e.getKey().startsWith(name)) completions.put(e.getKey(), e.getValue().getClassname()); + } + for (String builtinName: indexer.getBindings().keySet()) { + if (builtinName.startsWith("__builtin__.")) + builtinName = builtinName.substring(12); // without the "__builtin__." prefix + if (builtinName.startsWith(name)) completions.put(builtinName, null); + } + scope = scope.parent; + } + return completions; + } + + + /** Find vars by type, recursively upstream the nested scopes, listing first those of the innermost scope. + * + * @param clazz + */ + public Stream findVarsByType(final String type, final Class clazz) { + Stream varNames = new ArrayList().stream(); + Scope scope = this; + JythonDev.printTrace("Scope.findVarsByType: searching for type " + type + " and class " + clazz.getCanonicalName()); + while (null != scope) { + varNames = Stream.concat(varNames, + scope.vars.entrySet().stream() + .filter(e -> { + try { + JythonDev.printTrace("Scope.findVarsByType, testing: " + e.getKey() + " :: " + e.getValue() + " with class " + e.getValue().getClassname()); + if (e.getKey().startsWith("____")) return false; // injected variables in JythonAutoCompletions.completionsFor + final String classname = e.getValue().getClassname(); + if (null == classname) return false; + if (type.equals(classname)) { + JythonDev.printTrace("type == classname: " + type); + return true; + } + // Handle compatible numeric arguments + if (Number.class.isAssignableFrom(clazz)) { + // Python only has long or float + if (classname.equals("float")) { + return true; // all numeric types will fit + } + if (classname.equals("long")) { + // or "long", but that was exact-matched earlier + return type.equals("int") + || type.equals("short") + || type.equals("byte") + || clazz.isAssignableFrom(Long.class) + || clazz.isAssignableFrom(Integer.class) + || clazz.isAssignableFrom(Short.class) + || clazz.isAssignableFrom(Byte.class); + } + } + // Fix class when it's a primitive number + Class c = null; + switch (classname) { + case "long": c = Long.class; break; + case "float": c = Float.class; break; + default: c = Class.forName(classname); + } + // Search for subclass or interface + return clazz.isAssignableFrom(c); + + // TODO: search for methods of non-matching classes that return a matching type + + } catch (ClassNotFoundException e1) { + JythonDev.print("Cannot load class " + e.getValue(), e1); + } + return false; + }) + .map(e -> e.getKey())); + scope = scope.parent; + } + return varNames; + } + public HashMap getImports() { final HashMap imports = new HashMap<>(this.imports); diff --git a/src/main/java/sc/fiji/jython/autocompletion/StaticDotAutocompletions.java b/src/main/java/org/scijava/plugins/scripteditor/jython/StaticDotAutocompletions.java similarity index 53% rename from src/main/java/sc/fiji/jython/autocompletion/StaticDotAutocompletions.java rename to src/main/java/org/scijava/plugins/scripteditor/jython/StaticDotAutocompletions.java index 55d11d3..69ba534 100644 --- a/src/main/java/sc/fiji/jython/autocompletion/StaticDotAutocompletions.java +++ b/src/main/java/org/scijava/plugins/scripteditor/jython/StaticDotAutocompletions.java @@ -1,29 +1,33 @@ /*- * #%L - * Autocompletion for the jython language in the Script Editor + * Jython language support for SciJava Script Editor. * %% - * Copyright (C) 2020 - 2022 Albert Cardona + * Copyright (C) 2020 - 2024 SciJava developers. * %% - * 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. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: * - * 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. + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * . + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. * #L% */ -package sc.fiji.jython.autocompletion; +package org.scijava.plugins.scripteditor.jython; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -50,7 +54,7 @@ public List get() { try { // Check first if it's a python module final NModuleType module = Scope.loadPythonModule(this.className); // Scope.indexer.getBuiltinModule(this.className); - System.out.println("module is: " + module); + JythonDev.printTrace("module is: " + module); if (null != module) { module.getTable().keySet().forEach( m -> ac.add(new CompletionText(m))); // Not need to remove: a file system watcher will do so when the module file is updated or deleted. @@ -61,7 +65,7 @@ public List get() { } // Or a java class: try { - fieldsAndStaticMethodsInto(Class.forName(this.className), ac); + DotAutocompletions.staticFieldsAndStaticMethodsInto(Class.forName(this.className), ac); return ac; } catch (ClassNotFoundException cnfe) { msg += "\nCannot find java class " + this.className; @@ -77,7 +81,7 @@ public List get() { .map(m -> m.getReturnType()) .distinct() .collect(Collectors.toList())) { - fieldsAndMethodsInto(r, ac); + DotAutocompletions.fieldsAndMethodsInto(r, ac); } return ac; } catch (ClassNotFoundException cnfe) { @@ -85,33 +89,14 @@ public List get() { } if (null != msg) { - System.out.println(msg); + JythonDev.print(msg); } } catch (Exception e) { - if (null != msg) System.out.println(msg); - e.printStackTrace(); + JythonDev.print(msg, e); } } return ac; } - - private void fieldsAndStaticMethodsInto(final Class c, final List ac) { - for (final Field f: c.getDeclaredFields()) - if (Modifier.isStatic(f.getModifiers())) - ac.add(new CompletionText(f.getName(), c, f)); - for (final Method m: c.getDeclaredMethods()) - if (Modifier.isStatic(m.getModifiers())) - ac.add(new CompletionText(m.getName() + "()", c, m)); // TODO could do a parameter-driven autocompletion - } - - private void fieldsAndMethodsInto(final Class c, final List ac) { - for (final Field f: c.getDeclaredFields()) - if (!Modifier.isStatic(f.getModifiers())) - ac.add(new CompletionText(f.getName(), c, f)); - for (final Method m: c.getDeclaredMethods()) - if (!Modifier.isStatic(m.getModifiers())) - ac.add(new CompletionText(m.getName() + "()", c, m)); // TODO could do a parameter-driven autocompletion - } @Override public String toString() { diff --git a/src/main/java/org/scijava/plugins/scripteditor/jython/VarDotAutocompletions.java b/src/main/java/org/scijava/plugins/scripteditor/jython/VarDotAutocompletions.java new file mode 100644 index 0000000..abd5c0c --- /dev/null +++ b/src/main/java/org/scijava/plugins/scripteditor/jython/VarDotAutocompletions.java @@ -0,0 +1,78 @@ +/*- + * #%L + * Jython language support for SciJava Script Editor. + * %% + * Copyright (C) 2020 - 2024 SciJava developers. + * %% + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * #L% + */ +package org.scijava.plugins.scripteditor.jython; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Stream; + +import org.scijava.ui.swing.script.autocompletion.CompletionText; + +public class VarDotAutocompletions implements DotAutocompletions { + String className; + public VarDotAutocompletions(final String className) { + this.className = className; + } + @Override + public String getClassname() { + return this.className; + } + @Override + public List get() { + final List ac = new ArrayList<>(); + if (null != className) { + try { + final Class c = Class.forName(className); + DotAutocompletions.fieldsAndMethodsInto(c, ac); + } catch (final Exception e) { + JythonDev.print("Could not load class " + className, e); + } + } + return ac; + } + + @Override + public Stream getStream() { + try { + final Class c = Class.forName(this.className); + return Stream.concat( + Arrays.stream(c.getFields()).map(f -> new CompletionText(f.getName(), c, f)), + Arrays.stream(c.getMethods()).map(m -> new CompletionText(m.getName(), c, m))); + } catch (final Exception e) { + JythonDev.print("Could not load class " + className, e); + } + return Stream.empty(); + } + + @Override + public String toString() { + return "VarDotAutocompletions: " + this.className; + } +} diff --git a/src/main/java/sc/fiji/jython/autocompletion/DefVarDotAutocompletions.java b/src/main/java/sc/fiji/jython/autocompletion/DefVarDotAutocompletions.java deleted file mode 100644 index 5392690..0000000 --- a/src/main/java/sc/fiji/jython/autocompletion/DefVarDotAutocompletions.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * #%L - * Autocompletion for the jython language in the Script Editor - * %% - * Copyright (C) 2020 - 2022 Albert Cardona - * %% - * 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 - * . - * #L% - */ -package sc.fiji.jython.autocompletion; - -import java.util.List; - -public class DefVarDotAutocompletions extends VarDotAutocompletions { - - String fnName; - final List argumentNames; - Scope scope; - - public DefVarDotAutocompletions(final String fnName, final String returnClassName, final List argumentNames, final Scope scope) { - super(returnClassName); - this.fnName = fnName; - this.argumentNames = argumentNames; - this.scope = scope; - } - - public List getArgumentNames() { - return this.argumentNames; - } - - @Override - public String toString() { - return "DefVarAutocompletions:" + - " Class: " + super.className + - " Arguments: " + String.join(", ", this.argumentNames); - } -} diff --git a/src/main/java/sc/fiji/jython/autocompletion/DotAutocompletions.java b/src/main/java/sc/fiji/jython/autocompletion/DotAutocompletions.java deleted file mode 100644 index 153b4b7..0000000 --- a/src/main/java/sc/fiji/jython/autocompletion/DotAutocompletions.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * #%L - * Autocompletion for the jython language in the Script Editor - * %% - * Copyright (C) 2020 - 2022 Albert Cardona - * %% - * 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 - * . - * #L% - */ -package sc.fiji.jython.autocompletion; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -import org.scijava.ui.swing.script.autocompletion.CompletionText; - -public interface DotAutocompletions { - - static public final DotAutocompletions EMPTY = new EmptyDotAutocompletions(); - - default public String getClassname() { - return null; - } - - default public String getSummary() { - return null; - } - - public List get(); - - static public List getPublicFieldsAndMethods(final String className) { - final List ac = new ArrayList<>(); - if (null != className) { - try { - final Class c = Class.forName(className); - for (final Field f: c.getFields()) - ac.add(new CompletionText(f.getName(), c, f)); - for (final Method m: c.getMethods()) - ac.add(new CompletionText(m.getName() + "()", c, m)); // TODO could do a parameter-driven autocompletion - } catch (final Exception e) { - System.out.println("Could not load class " + className + " :: " + e.getMessage()); - } - } - return ac; - } - -} diff --git a/src/main/java/sc/fiji/jython/autocompletion/EmptyDotAutocompletions.java b/src/main/java/sc/fiji/jython/autocompletion/EmptyDotAutocompletions.java deleted file mode 100644 index 82de42e..0000000 --- a/src/main/java/sc/fiji/jython/autocompletion/EmptyDotAutocompletions.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * #%L - * Autocompletion for the jython language in the Script Editor - * %% - * Copyright (C) 2020 - 2022 Albert Cardona - * %% - * 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 - * . - * #L% - */ -package sc.fiji.jython.autocompletion; - -import java.util.Collections; -import java.util.List; - -import org.scijava.ui.swing.script.autocompletion.CompletionText; - -public class EmptyDotAutocompletions implements DotAutocompletions { - @Override - public List get() { - return Collections.emptyList(); - } - - @Override - public String toString() { - return "EMPTY"; - } -} diff --git a/src/main/java/sc/fiji/jython/autocompletion/VarDotAutocompletions.java b/src/main/java/sc/fiji/jython/autocompletion/VarDotAutocompletions.java deleted file mode 100644 index 40ca9db..0000000 --- a/src/main/java/sc/fiji/jython/autocompletion/VarDotAutocompletions.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * #%L - * Autocompletion for the jython language in the Script Editor - * %% - * Copyright (C) 2020 - 2022 Albert Cardona - * %% - * 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 - * . - * #L% - */ -package sc.fiji.jython.autocompletion; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -import org.scijava.ui.swing.script.autocompletion.CompletionText; - -public class VarDotAutocompletions implements DotAutocompletions { - String className; - public VarDotAutocompletions(final String className) { - this.className = className; - } - @Override - public String getClassname() { - return this.className; - } - @Override - public List get() { - final List ac = new ArrayList<>(); - if (null != this.className) { - try { - final Class c = Class.forName(this.className); - for (final Field f: c.getFields()) - ac.add(new CompletionText(f.getName(), c, f)); - for (final Method m: c.getMethods()) - ac.add(new CompletionText(m.getName() + "()", c, m)); // TODO could do a parameter-driven autocompletion - } catch (Exception e) { - e.printStackTrace(); - } - } - return ac; - } - - @Override - public String toString() { - return "VarDotAutocompletions: " + this.className; - } -} diff --git a/src/test/java/org/scijava/plugins/scripteditor/jython/JythonScriptEditorTestDrive.java b/src/test/java/org/scijava/plugins/scripteditor/jython/JythonScriptEditorTestDrive.java new file mode 100644 index 0000000..df3ef1d --- /dev/null +++ b/src/test/java/org/scijava/plugins/scripteditor/jython/JythonScriptEditorTestDrive.java @@ -0,0 +1,43 @@ +/* + * #%L + * Jython language support for SciJava Script Editor. + * %% + * Copyright (C) 2020 - 2024 SciJava developers. + * %% + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * #L% + */ + +package org.scijava.plugins.scripteditor.jython; + +import org.scijava.ui.swing.script.Main; + +/** + * Interactive test for Jython in the Script Editor. + * + * @author Curtis Rueden + */ +public class JythonScriptEditorTestDrive { + public static void main(String[] args) throws Exception { + Main.launch("Python"); + } +} diff --git a/src/test/java/sc/fiji/jython/autocompletion/JythoScriptParserTest.java b/src/test/java/org/scijava/plugins/scripteditor/jython/JythonScriptParserTest.java similarity index 63% rename from src/test/java/sc/fiji/jython/autocompletion/JythoScriptParserTest.java rename to src/test/java/org/scijava/plugins/scripteditor/jython/JythonScriptParserTest.java index 07e831c..c1ebf91 100644 --- a/src/test/java/sc/fiji/jython/autocompletion/JythoScriptParserTest.java +++ b/src/test/java/org/scijava/plugins/scripteditor/jython/JythonScriptParserTest.java @@ -1,27 +1,36 @@ /*- * #%L - * Autocompletion for the jython language in the Script Editor + * Jython language support for SciJava Script Editor. * %% - * Copyright (C) 2020 - 2022 Albert Cardona + * Copyright (C) 2020 - 2024 SciJava developers. * %% - * 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. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: * - * 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. + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * . + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. * #L% */ -package sc.fiji.jython.autocompletion; +package org.scijava.plugins.scripteditor.jython; -public class JythoScriptParserTest { +import org.scijava.plugins.scripteditor.jython.JythonScriptParser; + +public class JythonScriptParserTest { static public String testCode = String.join("\n", "from os import path", @@ -104,7 +113,6 @@ public class JythoScriptParserTest { static public final void main(String[] args) { try { final String code = testCode3; - JythonScriptParser.DEBUG = true; final int lastLineBreak = code.lastIndexOf("\n"); final String codeToParse = -1 == lastLineBreak ? code : code.substring(0, lastLineBreak); JythonScriptParser.parseAST(codeToParse).print("");