pax_global_header00006660000000000000000000000064146357431740014530gustar00rootroot0000000000000052 comment=b47aa93ed40cecbfa0e6ddce2ffcaeb6e2729793 jfreesvg-5.0.6/000077500000000000000000000000001463574317400133535ustar00rootroot00000000000000jfreesvg-5.0.6/.github/000077500000000000000000000000001463574317400147135ustar00rootroot00000000000000jfreesvg-5.0.6/.github/FUNDING.yml000066400000000000000000000000771463574317400165340ustar00rootroot00000000000000# These are supported funding model platforms github: [jfree] jfreesvg-5.0.6/.github/workflows/000077500000000000000000000000001463574317400167505ustar00rootroot00000000000000jfreesvg-5.0.6/.github/workflows/ci.yaml000066400000000000000000000010201463574317400202200ustar00rootroot00000000000000--- name: Java CI on: [push] jobs: test: runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, macOS-latest, windows-latest] java: [11, 17, 21] fail-fast: false max-parallel: 4 name: Test JDK ${{ matrix.java }}, ${{ matrix.os }} steps: - uses: actions/checkout@v1 - name: Set up JDK uses: actions/setup-java@v1 with: java-version: ${{ matrix.java }} - name: Test with Maven run: mvn test -B --file pom.xml ... jfreesvg-5.0.6/.gitignore000066400000000000000000000001231463574317400153370ustar00rootroot00000000000000target distribution .idea *.class **/.DS_Store # Package Files # *.jar *.war *.ear jfreesvg-5.0.6/LICENSE000066400000000000000000001045151463574317400143660ustar00rootroot00000000000000 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 . jfreesvg-5.0.6/README.md000066400000000000000000000250101463574317400146300ustar00rootroot00000000000000JFreeSVG ======== Version 5.0.6, by David Gilbert, 23 June 2024. (C)opyright 2013-present, by David Gilbert. All rights reserved. [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.jfree/org.jfree.svg/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.jfree/org.jfree.svg) Overview -------- **JFreeSVG** is a graphics library for the Java(tm) platform that allows you to generate content in SVG format using the standard Java2D drawing API (`Graphics2D`). JFreeSVG is light-weight, fast, and has no dependencies other than the Java runtime (11 or later). ![Sample from JFreeChart](https://raw.githubusercontent.com/jfree/jfreesvg/master/src/main/javadoc/doc-files/FlowPlotDemo2.svg) Getting Started --------------- The Javadocs for the `SVGGraphics2D` class gives examples for typical usage, and if you are already familiar with the Java2D APIs, then all you need to do is add the JFreeSVG dependency and start coding. Oracle provides tutorials for Java2D here: - http://docs.oracle.com/javase/tutorial/2d/ There are some demonstration applications in the [JFree-Demos](https://github.com/jfree/jfree-demos) project at GitHub. Include ------- JFreeSVG is published to the Central Repository. You can include it in your projects with the following dependency: org.jfree org.jfree.svg 5.0.6 JFreeSVG is a modular library with the module name `org.jfree.svg`. To use JFreeSVG with Java 8, you can use the following (note the different artifact ID): org.jfree jfreesvg 3.4.3 Build ----- You can build `JFreeSVG` from sources using Maven: mvn clean verify To generate the Javadocs: mvn clean compile javadoc:javadoc Testing ------- `JFreeSVG` is being tested using [Graphics2D Tester](https://github.com/jfree/graphics2d-tester) and produces the output shown below. There are several areas that still need work: - the compositing rules in `AlphaComposite` are not implemented - font metrics are approximated ![jfreesvg](https://github.com/jfree/jfreesvg/assets/1835893/d7d6f741-8005-49c5-bc4c-fff112a33cef) License ------- JFreeSVG is free software under the terms of the GNU General Public License version 3 (GPLv3) or later. The license file is included in this distribution (gpl-3.0.txt). Please note that JFreeSVG is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Please refer to the license for details. If you prefer not to be bound by the terms of the GPLv3, you can obtain an alternative license by sponsoring the JFree project: - https://github.com/sponsors/jfree Change History -------------- Version 5.0.6 (23 June 2024) - fix issue with `LinearGradientPaint` and `RadialGradientPaint` reference generation - minor code transformations suggested by the Datadog Static Analyzer and SonarLint - update Maven and JUnit dependencies Version 5.0.5 (19 February 2023) - fixed `drawArc()` and `fillArc()` - update Maven and JUnit dependencies Version 5.0.4 (9 January 2023) - minor code transformations - unit test fix - update Maven and JUnit dependencies Version 5.0.3 (22 June 2022) - remove duplicate calls to `getClipPathRef()` - update Maven plugin dependencies Version 5.0.2 (7 November 2021) - add support for `TextAttribute.TRACKING` - clarified Javadocs for `SVGHints.KEY_BEGIN_GROUP` Version 5.0.1 (4 August 2021) - handle cycle methods for `GradientPaint` and `RadialGradientPaint`; - fix output for filled `Ellipse2D`. Version 5.0 (12 June 2021) - replaced `geometryDP` and `transformDP` attributes with function references ([#35](https://github.com/jfree/jfreesvg/issues/35)); - fixed issue with `RyuDouble` ([#39](https://github.com/jfree/jfreesvg/issues/39)); - changed SVG `width` and `height` attributes from `int` to `double` ([#37](https://github.com/jfree/jfreesvg/issues/37)); - changed `ViewBox` dimension attributes from `int` to `double`; - updated `draw(Shape)` and `fill(Shape)` methods for more compact output; - fixed miter limit ([#36](https://github.com/jfree/jfreesvg/issues/36) and [#38](https://github.com/jfree/jfreesvg/issues/38)); - fixed font family name issue ([#27](https://github.com/jfree/jfreesvg/issues/27)); - added more JUnit tests; - updated JUnit test dependency to version 5.7.2. Version 4.2 (10 January 2021) - replace `NumberFormat` with Ryu algorithm for performance gains ([#30](https://github.com/jfree/jfreesvg/pull/30)); - add winding rule to path data if required ([#25](https://github.com/jfree/jfreesvg/issues/25)); - migrated to JUnit 5. Version 4.1 (26 March 2020) - correction of fix for encoding of images ([#21](https://github.com/jfree/jfreesvg/issues/21)). Version 4.0 (27 February 2020) - created a module for JFreeSVG: `org.jfree.svg`; - increased the minimum required Java version to 11; - changed the Maven artifact ID to match the module name; - removed 'graphics2d' from the package names; - fix `drawArc()` and `fillArc()` methods to draw pie arcs; - use `java.util.Base64` instead of `javax.xml.bind.DatatypeConverter`. Version 3.4 (10 February 2019) - added attribute for font size units override; - added automatic module name (`org.jfree.jfreesvg`); - omit transformation if it is the identity transform; - fixed `drawString()` method for empty string; - fixed `drawImage()` method for `null` `ImageOp`. Version 3.3 (7 November 2017) - the default `DEFS` key prefix should not begin with a number; - transferred demo code to the [JFree-Demos](https://github.com/jfree/jfree-demos) project to streamline the distribution process. Version 3.2 (9 October 2016) - added facility to specify `units` for `width` and `height` attributes; - added option to suppress `width` and `height` from SVG element; - add option to include `viewBox` and associated parameters in the SVG element; - fixed `NullPointerException` in `drawImage(Image, AffineTransform, ImageObserver)` (bug #6); - copy `fontMapper` in `create()` method (bug #5). Version 3.1 (30 April 2016) - use fractional metrics for `FontMetrics`; - use `ellipse` element to draw/fill `Ellipse2D` instances; - handle alpha in gradient paints. Version 3.0 (8 June 2015) - added handling for `BasicStroke` cap, join and miterlimit; - added ZIP option when writing SVG to files; - added demo for exporting Swing UIs to SVG; - removed `CanvasGraphics2D` implementation; - fixed handling of `PathIterator.SEG_CLOSE`; - fixed y-coordinate bug in `drawImage()`; - added workaround for `ClassCastException` when exporting Swing UIs on MacOSX with Nimbus L&F. Version 2.1 (4 August 2014) - fixed bug with element end tag for JFreeChart; - fixed compilation error in demos. Version 2.0 (30 July 2014) - added configurable text-rendering and shape-rendering properties to the SVG element; - observe `KEY_STROKE_CONTROL` rendering hints; - fixed `create()` method so that Swing components can be rendered correctly; - modified the font render context info to fix glyph positioning for text drawn as vector graphics; - write colors using `rgb()` rather than `rgba()`, and write the alpha value to separate opacity attribute; - changed the license from AGPLv3 to GPLv3. Version 1.9 (6 May 2014) - added `defsKeyPrefix` attribute to allow unique ids for DEFS when generating multiple SVG elements for use in a single HTML page; - added support for `LinearGradientPaint` and improved existing `GradientPaint` handling; - added `KEY_ELEMENT_TITLE` rendering hint; - added support for arbitrary key, value pairs in the `KEY_START_GROUP` handler; - added `zeroStrokeWidth` attribute to allow configuration of handling for `BasicStroke` with zero width (which the Java specification states should be "rendered as the thinnest possible line"); - fixed a bug in the `drawImage(Image, int, int, int, int, int, int, int, int, ImageObserver)` method. Version 1.8 (11 April 2014) - added additional `KEY_BEGIN_GROUP` options, plus special integration support for Orson Charts; - added special handling for shape drawing when the `Stroke` is not an instance of `BasicStroke`; - explicitly set encoding to UTF-8 for `SVGUtils.writeToSVG()` and `SVGUtils.writeToHTML()`. Version 1.7 (25 February 2014) - added `SVGHints.KEY_BEGIN_GROUP` and `SVGHints.KEY_END_GROUP` to allow grouping of SVG output; - fix `drawString()` to include id if `SVGHints.KEY_ELEMENT_ID` is set; - fix transparent colors issue; - fixed minor issue with meta tag in HTML output file. Version 1.6 (18 December 2013) - fixed a minor packaging error in version 1.5. Version 1.5 (18 December 2013) - added `FontMapper` to ensure that Java logical font names map to the equivalent SVG generic font names; - added `SVGHints.KEY_IMAGE_HREF` to allow image references to be specified; - added `SVGHints.KEY_ELEMENT_ID` to allow an element id to be supplied for the next element to be written; - fixed a bug for special characters in `drawString()`; - fixed a bug with coordinate formatting in certain locales. Version 1.4 (24 October 2013) - `getSVGFontStyle()` now specifies font-size units as required by the SVG standard. Fixes a bug that is visible when the SVG output is rendered in FireFox (which is more strict about the standard than other browsers); - added text-rendering attribute to the SVG text element generated by the `drawString()` method; - added new key and values to `SVGHint` to configure the value of the text-rendering attribute. Version 1.3 (24 September 2013) - implemented `getDeviceConfiguration()` method; - fixed clipping bug with transforms applied after clip is set; - fixed bug with `setClip(null)`; - fixed "not well-formed" parsing issue for Firefox; - set `preserveAspectRatio` attribute for images; Version 1.2 (13 September 2013) - added SVG and XLINK namespaces to SVG element; - fixed capitalisation of `linearGradient` element, to pass W3C validator; - added support for Java2D's `RadialGradientPaint`; - added `SVGUtils.writeToSVG()` method; - added new demo `SVGTimeSeriesChartDemo1.java`. Version 1.1 (4 September 2013) - reimplemented `drawString(AttributedCharacterIterator, float, float)` using `TextLayout` and modified `drawGlyphVector()` to fill rather than stroke shapes (for `SVG/CanvasGraphics2D`); - removed the PDF code (to a separate project, **OrsonPDF**); - fixed clipping bug in `SVGGraphics2D`; - added `geomDP` and `transformDP` attributes to `CanvasGraphics2D` to control number of decimal places for numbers written to script; Version 1.0 (31 July 2013) - Initial public release. jfreesvg-5.0.6/pom.xml000066400000000000000000000157001463574317400146730ustar00rootroot00000000000000 4.0.0 org.jfree org.jfree.svg 5.0.6 jar JFreeSVG http://www.jfree.org/jfreesvg A fast, lightweight Java library for creating SVG output. GNU General Public License (GPL) http://www.gnu.org/licenses/gpl.txt repo https://github.com/jfree/jfreesvg scm:git:git://github.com/jfree/jfreesvg.git scm:git:git@github.com:jfree/jfreesvg.git dave@jfree.org David Gilbert https://github.com/jfree UTF-8 org.junit.jupiter junit-jupiter-api 5.10.2 test org.junit.jupiter junit-jupiter-engine 5.10.2 test org.apache.maven.plugins maven-clean-plugin 3.3.2 org.apache.maven.plugins maven-resources-plugin 3.3.1 ${project.build.sourceEncoding} org.apache.maven.plugins maven-compiler-plugin 3.13.0 11 11 -Xlint:unchecked ${project.build.sourceEncoding} org.apache.maven.plugins maven-jar-plugin 3.4.1 org.apache.maven.plugins maven-javadoc-plugin 3.6.3 true true maven-surefire-plugin 3.2.5 maven-failsafe-plugin 3.2.5 org.apache.maven.plugins maven-install-plugin 3.1.2 ossrh https://oss.sonatype.org/content/repositories/snapshots release org.apache.maven.plugins maven-gpg-plugin 3.2.4 sign-artifacts verify sign org.sonatype.plugins nexus-staging-maven-plugin 1.7.0 true ossrh https://oss.sonatype.org/ false org.apache.maven.plugins maven-javadoc-plugin 3.7.0 true true attach-javadoc jar org.apache.maven.plugins maven-source-plugin 3.3.1 attach-sources jar-no-fork jfreesvg-5.0.6/src/000077500000000000000000000000001463574317400141425ustar00rootroot00000000000000jfreesvg-5.0.6/src/main/000077500000000000000000000000001463574317400150665ustar00rootroot00000000000000jfreesvg-5.0.6/src/main/java/000077500000000000000000000000001463574317400160075ustar00rootroot00000000000000jfreesvg-5.0.6/src/main/java/module-info.java000066400000000000000000000012301463574317400210640ustar00rootroot00000000000000/** * JFreeSVG is a Java module that enables the generation of Scalable Vector Graphics (SVG) output via the * standard Java2D API. For example, the following chart is created with JFreeChart and rendered with JFreeSVG: *

* FlowPlotDemo2.svg *

* The project is hosted at GitHub: https://github.com/jfree/jfreesvg. * @see https://jfree.github.io/jfreechart-and-opencsv/ */ module org.jfree.svg { requires java.desktop; requires java.logging; exports org.jfree.svg; } jfreesvg-5.0.6/src/main/java/org/000077500000000000000000000000001463574317400165765ustar00rootroot00000000000000jfreesvg-5.0.6/src/main/java/org/jfree/000077500000000000000000000000001463574317400176715ustar00rootroot00000000000000jfreesvg-5.0.6/src/main/java/org/jfree/svg/000077500000000000000000000000001463574317400204705ustar00rootroot00000000000000jfreesvg-5.0.6/src/main/java/org/jfree/svg/ImageElement.java000066400000000000000000000061211463574317400236670ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-present, by David Gilbert. All rights reserved. * * Project Info: http://www.jfree.org/jfreesvg/index.html * * 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 . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * JFreeSVG home page: * * http://www.jfree.org/jfreesvg * */ package org.jfree.svg; import java.awt.Image; import org.jfree.svg.util.Args; /** * A {@code (String, Image)} pair that links together a reference ID and * the source image. This is used internally by {@link SVGGraphics2D} to track * images as they are rendered. This is important when images are not embedded * in the SVG output, in which case you may need to generate corresponding * image files for the images (see also {@link SVGGraphics2D#getSVGImages()}). */ public final class ImageElement { /** The filename specified in the href. */ private final String href; /** The image. */ private final Image image; /** * Creates a new instance. * * @param href the href ({@code null} not permitted). * @param image the image ({@code null} not permitted). */ public ImageElement(String href, Image image) { Args.nullNotPermitted(href, "href"); Args.nullNotPermitted(image, "image"); this.href = href; this.image = image; } /** * Returns the reference ID that was specified in the constructor. * * @return The href (never {@code null}). */ public String getHref() { return href; } /** * Returns the image that was specified in the constructor. * * @return The image (never {@code null}). */ public Image getImage() { return image; } /** * Returns a string representation of this object, primarily for debugging * purposes. * * @return A string. */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("ImageElement["); sb.append(this.href).append(", ").append(this.image); sb.append("]"); return sb.toString(); } } jfreesvg-5.0.6/src/main/java/org/jfree/svg/MeetOrSlice.java000066400000000000000000000033251463574317400235110ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-present, by David Gilbert. All rights reserved. * * Project Info: http://www.jfree.org/jfreesvg/index.html * * 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 . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * JFreeSVG home page: * * http://www.jfree.org/jfreesvg * */ package org.jfree.svg; /** * An enumeration of the values for the {@code meetOrSlice} attribute. * * @since 3.2 */ public enum MeetOrSlice { /** Value 'meet'. */ MEET("meet"), /** Value 'slice'. */ SLICE("slice"); private final String label; MeetOrSlice(String label) { this.label = label; } @Override public String toString() { return this.label; } } jfreesvg-5.0.6/src/main/java/org/jfree/svg/PreserveAspectRatio.java000066400000000000000000000043441463574317400252720ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-present, by David Gilbert. All rights reserved. * * Project Info: http://www.jfree.org/jfreesvg/index.html * * 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 . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * JFreeSVG home page: * * http://www.jfree.org/jfreesvg * */ package org.jfree.svg; /** * An enumeration of the values for the {@code preserveAspectRatio} attribute. * * @since 3.2 */ public enum PreserveAspectRatio { /** Value 'none'. */ NONE("none"), /** Value 'xMinYMin'. */ XMIN_YMIN("xMinYMin"), /** Value 'xMinYMid'. */ XMIN_YMID("xMinYMid"), /** Value 'xMinYMax'. */ XMIN_YMAX("xMinYMax"), /** Value 'xMidYMin'. */ XMID_YMIN("xMidYMin"), /** Value 'xMidYMid'. */ XMID_YMID("xMidYMid"), /** Value 'xMidYMax'. */ XMID_YMAX("xMidYMax"), /** Value 'xMaxYMin'. */ XMAX_YMIN("xMaxYMin"), /** Value 'xMaxYMid'. */ XMAX_YMID("xMaxYMid"), /** Value 'xMaxYMax'. */ XMAX_YMAX("xMaxYMax"); private final String label; PreserveAspectRatio(String label) { this.label = label; } @Override public String toString() { return this.label; } } jfreesvg-5.0.6/src/main/java/org/jfree/svg/SVGGraphics2D.java000066400000000000000000003171631463574317400236540ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-present, by David Gilbert. All rights reserved. * * Project Info: http://www.jfree.org/jfreesvg/index.html * * 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 . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * JFreeSVG home page: * * http://www.jfree.org/jfreesvg */ package org.jfree.svg; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.FontMetrics; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.Image; import java.awt.LinearGradientPaint; import java.awt.MultipleGradientPaint.CycleMethod; import java.awt.Paint; import java.awt.RadialGradientPaint; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.font.FontRenderContext; import java.awt.font.GlyphVector; import java.awt.font.TextAttribute; import java.awt.font.TextLayout; import java.awt.geom.AffineTransform; import java.awt.geom.Arc2D; import java.awt.geom.Area; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Path2D; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.awt.image.BufferedImageOp; import java.awt.image.ImageObserver; import java.awt.image.RenderedImage; import java.awt.image.renderable.RenderableImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.text.AttributedCharacterIterator; import java.text.AttributedCharacterIterator.Attribute; import java.text.AttributedString; import java.util.ArrayList; import java.util.Base64; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.function.DoubleFunction; import java.util.function.Function; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import org.jfree.svg.util.Args; import org.jfree.svg.util.GradientPaintKey; import org.jfree.svg.util.GraphicsUtils; import org.jfree.svg.util.LinearGradientPaintKey; import org.jfree.svg.util.RadialGradientPaintKey; /** *

* A {@code Graphics2D} implementation that creates SVG output. After * rendering the graphics via the {@code SVGGraphics2D}, you can retrieve * an SVG element (see {@link #getSVGElement()}) or an SVG document (see * {@link #getSVGDocument()}) containing your content. *

* Usage
*

* Using the {@code SVGGraphics2D} class is straightforward. First, * create an instance specifying the height and width of the SVG element that * will be created. Then, use standard Java2D API calls to draw content * into the element. Finally, retrieve the SVG element that has been * accumulated. For example: *

*
{@code SVGGraphics2D g2 = new SVGGraphics2D(300, 200);
 * g2.setPaint(Color.RED);
 * g2.draw(new Rectangle(10, 10, 280, 180));
 * String svgElement = g2.getSVGElement();}
*

* For the content generation step, you can make use of third party libraries, * such as JFreeChart and * Orson Charts, that * render output using standard Java2D API calls. *

* Rendering Hints
*

* The {@code SVGGraphics2D} supports a couple of custom rendering hints - * for details, refer to the {@link SVGHints} class documentation. Also see * the examples in this blog post: * * Orson Charts 3D / Enhanced SVG Export. *

* Other Notes
* Some additional notes: *
    *
  • by default, JFreeSVG uses a fast conversion of numerical values to * strings for the SVG output (the 'RyuDouble' implementation). If you * prefer a different approach (for example, controlling the number of * decimal places in the output to reduce the file size) you can set your * own functions for converting numerical values - see the * {@link #setGeomDoubleConverter(DoubleFunction)} and * {@link #setTransformDoubleConverter(DoubleFunction)} methods.
  • * *
  • the {@link #getFontMetrics(java.awt.Font)} and * {@link #getFontRenderContext()} methods return values that come from an * internal {@code BufferedImage}, this is a short-cut and we don't know * if there are any negative consequences (if you know of any, please let us * know and we'll add the info here or find a way to fix it);
  • * *
  • Images are supported, but for methods with an {@code ImageObserver} * parameter note that the observer is ignored completely. In any case, using * images that are not fully loaded already would not be a good idea in the * context of generating SVG data/files;
  • * *
  • when an HTML page contains multiple SVG elements, the items within * the DEFS element for each SVG element must have IDs that are unique across * all SVG elements in the page. JFreeSVG auto-populates the * {@code defsKeyPrefix} attribute to help ensure that unique IDs are * generated.
  • *
* *

* For some demos showing how to use this class, look at the JFree-Demos project * at GitHub: https://github.com/jfree/jfree-demos. *

*/ public final class SVGGraphics2D extends Graphics2D { /** The prefix for keys used to identify clip paths. */ private static final String CLIP_KEY_PREFIX = "clip-"; /** The width of the SVG. */ private final double width; /** The height of the SVG. */ private final double height; /** * Units for the width and height of the SVG, if null then no * unit information is written in the SVG output. This is set via * the class constructors. */ private final SVGUnits units; /** The font size units. */ private SVGUnits fontSizeUnits = SVGUnits.PX; /** Rendering hints (see SVGHints). */ private final RenderingHints hints; /** * A flag that controls whether or not the KEY_STROKE_CONTROL hint is * checked. */ private boolean checkStrokeControlHint = true; /** * The function used to convert double values to strings when writing * matrix values for transforms in the SVG output. */ private DoubleFunction transformDoubleConverter; /** * The function used to convert double values to strings for the geometry * coordinates in the SVG output. */ private DoubleFunction geomDoubleConverter; /** The buffer that accumulates the SVG output. */ private final StringBuilder sb; /** * A prefix for the keys used in the DEFS element. This can be used to * ensure that the keys are unique when creating more than one SVG element * for a single HTML page. */ String defsKeyPrefix = "_" + System.nanoTime(); /** * A map of all the gradients used, and the corresponding id. When * generating the SVG file, all the gradient paints used must be defined * in the defs element. */ private Map gradientPaints = new HashMap<>(); /** * A map of all the linear gradients used, and the corresponding id. When * generating the SVG file, all the linear gradient paints used must be * defined in the defs element. */ private Map linearGradientPaints = new HashMap<>(); /** * A map of all the radial gradients used, and the corresponding id. When * generating the SVG file, all the radial gradient paints used must be * defined in the defs element. */ private Map radialGradientPaints = new HashMap<>(); /** * A list of the registered clip regions. These will be written to the * DEFS element. */ private List clipPaths = new ArrayList<>(); /** * The filename prefix for images that are referenced rather than * embedded but don't have an {@code href} supplied via the * {@link SVGHints#KEY_IMAGE_HREF} hint. */ private String filePrefix = "image-"; /** * The filename suffix for images that are referenced rather than * embedded but don't have an {@code href} supplied via the * {@link SVGHints#KEY_IMAGE_HREF} hint. */ private String fileSuffix = ".png"; /** * A list of images that are referenced but not embedded in the SVG. * After the SVG is generated, the caller can make use of this list to * write PNG files if they don't already exist. */ private List imageElements; /** The user clip (can be null). */ private Shape clip; /** The reference for the current clip. */ private String clipRef; /** The current transform. */ private AffineTransform transform = new AffineTransform(); /** The paint used to draw or fill shapes and text. */ private Paint paint = Color.BLACK; private Color color = Color.BLACK; private Composite composite = AlphaComposite.getInstance( AlphaComposite.SRC_OVER, 1.0f); /** The current stroke. */ private Stroke stroke = new BasicStroke(1.0f); /** * The width of the SVG stroke to use when the user supplies a * BasicStroke with a width of 0.0 (in this case the Java specification * says "If width is set to 0.0f, the stroke is rendered as the thinnest * possible line for the target device and the antialias hint setting.") */ private double zeroStrokeWidth; /** The last font that was set. */ private Font font = new Font("SansSerif", Font.PLAIN, 12); /** * The font render context. The fractional metrics flag solves the glyph * positioning issue identified by Christoph Nahr: * http://news.kynosarges.org/2014/06/28/glyph-positioning-in-jfreesvg-orsonpdf/ */ private final FontRenderContext fontRenderContext = new FontRenderContext( null, false, true); /** * Generates the SVG font from the Java font family name (this function * provides a hook for custom output formatting (for example putting quotes * around the font family name - see issue #27) and font substitutions. */ private Function fontFunction; /** The background color, used by clearRect(). */ private Color background = Color.BLACK; /** An internal image used for font metrics. */ private BufferedImage fmImage; /** * The graphics target for the internal image that is used for font * metrics. */ private Graphics2D fmImageG2D; /** * An instance that is lazily instantiated in drawLine and then * subsequently reused to avoid creating a lot of garbage. */ private Line2D line; /** * An instance that is lazily instantiated in fillRect and then * subsequently reused to avoid creating a lot of garbage. */ private Rectangle2D rect; /** * An instance that is lazily instantiated in draw/fillRoundRect and then * subsequently reused to avoid creating a lot of garbage. */ private RoundRectangle2D roundRect; /** * An instance that is lazily instantiated in draw/fillOval and then * subsequently reused to avoid creating a lot of garbage. */ private Ellipse2D oval; /** * An instance that is reused in draw/fillArc to avoid creating a lot of garbage. */ private final Arc2D arc = new Arc2D.Double(); /** * If the current paint is an instance of {@link GradientPaint}, this * field will contain the reference id that is used in the DEFS element * for that linear gradient. */ String gradientPaintRef; /** * The device configuration (this is lazily instantiated in the * getDeviceConfiguration() method). */ private GraphicsConfiguration deviceConfiguration; /** A set of element IDs. */ private final Set elementIDs; /** * Creates a new instance with the specified width and height. * * @param width the width of the SVG element. * @param height the height of the SVG element. */ public SVGGraphics2D(double width, double height) { this(width, height, null, new StringBuilder()); } /** * Creates a new instance with the specified width and height in the given * units. * * @param width the width of the SVG element. * @param height the height of the SVG element. * @param units the units for the width and height ({@code null} permitted). * * @since 3.2 */ public SVGGraphics2D(double width, double height, SVGUnits units) { this(width, height, units, new StringBuilder()); } /** * Creates a new instance with the specified width and height that will * populate the supplied {@code StringBuilder} instance. * * @param width the width of the SVG element. * @param height the height of the SVG element. * @param units the units for the width and height ({@code null} permitted). * @param sb the string builder ({@code null} not permitted). * * @since 3.2 */ public SVGGraphics2D(double width, double height, SVGUnits units, StringBuilder sb) { super(); Args.requireFinitePositive(width, "width"); Args.requireFinitePositive(height, "height"); Args.nullNotPermitted(sb, "sb"); this.width = width; this.height = height; this.units = units; this.geomDoubleConverter = SVGUtils::doubleToString; this.transformDoubleConverter = SVGUtils::doubleToString; this.imageElements = new ArrayList<>(); this.fontFunction = new StandardFontFunction(); this.zeroStrokeWidth = 0.1; this.sb = sb; this.hints = new RenderingHints(SVGHints.KEY_IMAGE_HANDLING, SVGHints.VALUE_IMAGE_HANDLING_EMBED); this.elementIDs = new HashSet<>(); } /** * Creates a new instance that is a child of the supplied parent. * * @param parent the parent ({@code null} not permitted). */ private SVGGraphics2D(final SVGGraphics2D parent) { this(parent.width, parent.height, parent.units, parent.sb); this.fontFunction = parent.fontFunction; getRenderingHints().add(parent.hints); this.checkStrokeControlHint = parent.checkStrokeControlHint; this.transformDoubleConverter = parent.transformDoubleConverter; this.geomDoubleConverter = parent.geomDoubleConverter; this.defsKeyPrefix = parent.defsKeyPrefix; this.gradientPaints = parent.gradientPaints; this.linearGradientPaints = parent.linearGradientPaints; this.radialGradientPaints = parent.radialGradientPaints; this.clipPaths = parent.clipPaths; this.filePrefix = parent.filePrefix; this.fileSuffix = parent.fileSuffix; this.imageElements = parent.imageElements; this.zeroStrokeWidth = parent.zeroStrokeWidth; } /** * Returns the width for the SVG element, specified in the constructor. * This value will be written to the SVG element returned by the * {@link #getSVGElement()} method. * * @return The width for the SVG element. */ public double getWidth() { return this.width; } /** * Returns the height for the SVG element, specified in the constructor. * This value will be written to the SVG element returned by the * {@link #getSVGElement()} method. * * @return The height for the SVG element. */ public double getHeight() { return this.height; } /** * Returns the units for the width and height of the SVG element's * viewport, as specified in the constructor. The default value is * {@code null}). * * @return The units (possibly {@code null}). * * @since 3.2 */ public SVGUnits getUnits() { return this.units; } /** * Returns the flag that controls whether or not this object will observe * the {@code KEY_STROKE_CONTROL} rendering hint. The default value is * {@code true}. * * @return A boolean. * * @see #setCheckStrokeControlHint(boolean) * @since 2.0 */ public boolean getCheckStrokeControlHint() { return this.checkStrokeControlHint; } /** * Sets the flag that controls whether or not this object will observe * the {@code KEY_STROKE_CONTROL} rendering hint. When enabled (the * default), a hint to normalise strokes will write a {@code stroke-style} * attribute with the value {@code crispEdges}. * * @param check the new flag value. * * @see #getCheckStrokeControlHint() * @since 2.0 */ public void setCheckStrokeControlHint(boolean check) { this.checkStrokeControlHint = check; } /** * Returns the prefix used for all keys in the DEFS element. The default * value is {@code "_"+ String.valueOf(System.nanoTime())}. * * @return The prefix string (never {@code null}). * * @since 1.9 */ public String getDefsKeyPrefix() { return this.defsKeyPrefix; } /** * Sets the prefix that will be used for all keys in the DEFS element. * If required, this must be set immediately after construction (before any * content generation methods have been called). * * @param prefix the prefix ({@code null} not permitted). * * @since 1.9 */ public void setDefsKeyPrefix(String prefix) { Args.nullNotPermitted(prefix, "prefix"); this.defsKeyPrefix = prefix; } /** * Returns the double-to-string function that is used when writing * coordinates for geometrical shapes in the SVG output. The default * function uses the Ryu algorithm for speed (see class description for * more details). * * @return The double-to-string function (never {@code null}). * * @since 5.0 */ public DoubleFunction getGeomDoubleConverter() { return this.geomDoubleConverter; } /** * Sets the double-to-string function that is used when writing coordinates * for geometrical shapes in the SVG output. The default converter * optimises for speed when generating the SVG and should cover normal * usage. However, this method provides the ability to substitute * an alternative function (for example, one that favours output size * over speed of generation). * * @param converter the convertor function ({@code null} not permitted). * * @see #setTransformDoubleConverter(java.util.function.DoubleFunction) * * @since 5.0 */ public void setGeomDoubleConverter(DoubleFunction converter) { Args.nullNotPermitted(converter, "converter"); this.geomDoubleConverter = converter; } /** * Returns the double-to-string function that is used when writing * values for matrix transformations in the SVG output. * * @return The double-to-string function (never {@code null}). * * @since 5.0 */ public DoubleFunction getTransformDoubleConverter() { return this.transformDoubleConverter; } /** * Sets the double-to-string function that is used when writing coordinates * for matrix transformations in the SVG output. The default converter * optimises for speed when generating the SVG and should cover normal * usage. However this method provides the ability to substitute * an alternative function (for example, one that favours output size * over speed of generation). * * @param converter the convertor function ({@code null} not permitted). * * @see #setGeomDoubleConverter(java.util.function.DoubleFunction) * * @since 5.0 */ public void setTransformDoubleConverter(DoubleFunction converter) { Args.nullNotPermitted(converter, "converter"); this.transformDoubleConverter = converter; } /** * Returns the prefix used to generate a filename for an image that is * referenced from, rather than embedded in, the SVG element. * * @return The file prefix (never {@code null}). * * @since 1.5 */ public String getFilePrefix() { return this.filePrefix; } /** * Sets the prefix used to generate a filename for any image that is * referenced from the SVG element. * * @param prefix the new prefix ({@code null} not permitted). * * @since 1.5 */ public void setFilePrefix(String prefix) { Args.nullNotPermitted(prefix, "prefix"); this.filePrefix = prefix; } /** * Returns the suffix used to generate a filename for an image that is * referenced from, rather than embedded in, the SVG element. * * @return The file suffix (never {@code null}). * * @since 1.5 */ public String getFileSuffix() { return this.fileSuffix; } /** * Sets the suffix used to generate a filename for any image that is * referenced from the SVG element. * * @param suffix the new prefix ({@code null} not permitted). * * @since 1.5 */ public void setFileSuffix(String suffix) { Args.nullNotPermitted(suffix, "suffix"); this.fileSuffix = suffix; } /** * Returns the width to use for the SVG stroke when the AWT stroke * specified has a zero width (the default value is {@code 0.1}). In * the Java specification for {@code BasicStroke} it states "If width * is set to 0.0f, the stroke is rendered as the thinnest possible * line for the target device and the antialias hint setting." We don't * have a means to implement that accurately since we must specify a fixed * width. * * @return The width. * * @since 1.9 */ public double getZeroStrokeWidth() { return this.zeroStrokeWidth; } /** * Sets the width to use for the SVG stroke when the current AWT stroke * has a width of 0.0. * * @param width the new width (must be 0 or greater). * * @since 1.9 */ public void setZeroStrokeWidth(double width) { if (width < 0.0) { throw new IllegalArgumentException("Width cannot be negative."); } this.zeroStrokeWidth = width; } /** * Returns the device configuration associated with this * {@code Graphics2D}. * * @return The graphics configuration. */ @Override public GraphicsConfiguration getDeviceConfiguration() { if (this.deviceConfiguration == null) { this.deviceConfiguration = new SVGGraphicsConfiguration( (int) Math.ceil(this.width), (int) Math.ceil(this.height)); } return this.deviceConfiguration; } /** * Creates a new graphics object that is a copy of this graphics object * (except that it has not accumulated the drawing operations). Not sure * yet when or why this would be useful when creating SVG output. Note * that the {@code fontFunction} object ({@link #getFontFunction()}) is * shared between the existing instance and the new one. * * @return A new graphics object. */ @Override public Graphics create() { SVGGraphics2D copy = new SVGGraphics2D(this); copy.setRenderingHints(getRenderingHints()); copy.setTransform(getTransform()); copy.setClip(getClip()); copy.setPaint(getPaint()); copy.setColor(getColor()); copy.setComposite(getComposite()); copy.setStroke(getStroke()); copy.setFont(getFont()); copy.setBackground(getBackground()); copy.setFilePrefix(getFilePrefix()); copy.setFileSuffix(getFileSuffix()); return copy; } /** * Returns the paint used to draw or fill shapes (or text). The default * value is {@link Color#BLACK}. * * @return The paint (never {@code null}). * * @see #setPaint(java.awt.Paint) */ @Override public Paint getPaint() { return this.paint; } /** * Sets the paint used to draw or fill shapes (or text). If * {@code paint} is an instance of {@code Color}, this method will * also update the current color attribute (see {@link #getColor()}). If * you pass {@code null} to this method, it does nothing (in * accordance with the JDK specification). * * @param paint the paint ({@code null} is permitted but ignored). * * @see #getPaint() */ @Override public void setPaint(Paint paint) { if (paint == null) { return; } this.paint = paint; this.gradientPaintRef = null; if (paint instanceof Color) { setColor((Color) paint); } else if (paint instanceof GradientPaint) { GradientPaint gp = (GradientPaint) paint; GradientPaintKey key = new GradientPaintKey(gp); this.gradientPaintRef = this.gradientPaints.computeIfAbsent(key, k -> { int count = this.gradientPaints.keySet().size(); String id = this.defsKeyPrefix + "gp" + count; this.elementIDs.add(id); return id; }); } else if (paint instanceof LinearGradientPaint) { LinearGradientPaint lgp = (LinearGradientPaint) paint; LinearGradientPaintKey key = new LinearGradientPaintKey(lgp); this.gradientPaintRef = this.linearGradientPaints.computeIfAbsent(key, k -> { int count = this.linearGradientPaints.keySet().size(); String id = this.defsKeyPrefix + "lgp" + count; this.elementIDs.add(id); return id; }); } else if (paint instanceof RadialGradientPaint) { RadialGradientPaint rgp = (RadialGradientPaint) paint; RadialGradientPaintKey key = new RadialGradientPaintKey(rgp); this.gradientPaintRef = this.radialGradientPaints.computeIfAbsent(key, k -> { int count = this.radialGradientPaints.keySet().size(); String id = this.defsKeyPrefix + "rgp" + count; this.elementIDs.add(id); return id; }); } } /** * Returns the foreground color. This method exists for backwards * compatibility in AWT, you should use the {@link #getPaint()} method. * * @return The foreground color (never {@code null}). * * @see #getPaint() */ @Override public Color getColor() { return this.color; } /** * Sets the foreground color. This method exists for backwards * compatibility in AWT, you should use the * {@link #setPaint(java.awt.Paint)} method. * * @param c the color ({@code null} permitted but ignored). * * @see #setPaint(java.awt.Paint) */ @Override public void setColor(Color c) { if (c == null) { return; } this.color = c; this.paint = c; } /** * Returns the background color. The default value is {@link Color#BLACK}. * This is used by the {@link #clearRect(int, int, int, int)} method. * * @return The background color (possibly {@code null}). * * @see #setBackground(java.awt.Color) */ @Override public Color getBackground() { return this.background; } /** * Sets the background color. This is used by the * {@link #clearRect(int, int, int, int)} method. The reference * implementation allows {@code null} for the background color, so * we allow that too (but for that case, the clearRect method will do * nothing). * * @param color the color ({@code null} permitted). * * @see #getBackground() */ @Override public void setBackground(Color color) { this.background = color; } /** * Returns the current composite. * * @return The current composite (never {@code null}). * * @see #setComposite(java.awt.Composite) */ @Override public Composite getComposite() { return this.composite; } /** * Sets the composite (only {@code AlphaComposite} is handled). * * @param comp the composite ({@code null} not permitted). * * @see #getComposite() */ @Override public void setComposite(Composite comp) { if (comp == null) { throw new IllegalArgumentException("Null 'comp' argument."); } this.composite = comp; } /** * Returns the current stroke (used when drawing shapes). * * @return The current stroke (never {@code null}). * * @see #setStroke(java.awt.Stroke) */ @Override public Stroke getStroke() { return this.stroke; } /** * Sets the stroke that will be used to draw shapes. * * @param s the stroke ({@code null} not permitted). * * @see #getStroke() */ @Override public void setStroke(Stroke s) { if (s == null) { throw new IllegalArgumentException("Null 's' argument."); } this.stroke = s; } /** * Returns the current value for the specified hint. See the * {@link SVGHints} class for information about the hints that can be * used with {@code SVGGraphics2D}. * * @param hintKey the hint key ({@code null} permitted, but the * result will be {@code null} also). * * @return The current value for the specified hint * (possibly {@code null}). * * @see #setRenderingHint(java.awt.RenderingHints.Key, java.lang.Object) */ @Override public Object getRenderingHint(RenderingHints.Key hintKey) { return this.hints.get(hintKey); } /** * Sets the value for a hint. See the {@link SVGHints} class for * information about the hints that can be used with this implementation. * * @param hintKey the hint key ({@code null} not permitted). * @param hintValue the hint value. * * @see #getRenderingHint(java.awt.RenderingHints.Key) */ @Override public void setRenderingHint(RenderingHints.Key hintKey, Object hintValue) { if (hintKey == null) { throw new NullPointerException("Null 'hintKey' not permitted."); } // KEY_BEGIN_GROUP and KEY_END_GROUP are handled as special cases that // never get stored in the hints map... if (SVGHints.isBeginGroupKey(hintKey)) { String groupId = null; String ref = null; List otherKeysAndValues = null; if (hintValue instanceof String) { groupId = (String) hintValue; } else if (hintValue instanceof Map) { Map hintValueMap = (Map) hintValue; groupId = (String) hintValueMap.get("id"); ref = (String) hintValueMap.get("ref"); for (final Object obj: hintValueMap.entrySet()) { final Entry e = (Entry) obj; final Object key = e.getKey(); if ("id".equals(key) || "ref".equals(key)) { continue; } if (otherKeysAndValues == null) { otherKeysAndValues = new ArrayList<>(); } otherKeysAndValues.add(e); } } this.sb.append(""); } else if (SVGHints.isEndGroupKey(hintKey)) { this.sb.append(""); } else if (SVGHints.isElementTitleKey(hintKey) && (hintValue != null)) { this.sb.append(""); this.sb.append(SVGUtils.escapeForXML(String.valueOf(hintValue))); this.sb.append(""); } else { this.hints.put(hintKey, hintValue); } } /** * Returns a copy of the rendering hints. Modifying the returned copy * will have no impact on the state of this {@code Graphics2D} instance. * * @return The rendering hints (never {@code null}). * * @see #setRenderingHints(java.util.Map) */ @Override public RenderingHints getRenderingHints() { return (RenderingHints) this.hints.clone(); } /** * Sets the rendering hints to the specified collection. * * @param hints the new set of hints ({@code null} not permitted). * * @see #getRenderingHints() */ @Override public void setRenderingHints(Map hints) { this.hints.clear(); addRenderingHints(hints); } /** * Adds all the supplied rendering hints. * * @param hints the hints ({@code null} not permitted). */ @Override public void addRenderingHints(Map hints) { this.hints.putAll(hints); } /** * A utility method that appends an optional element id if one is * specified via the rendering hints. * * @param builder the string builder ({@code null} not permitted). */ private void appendOptionalElementIDFromHint(StringBuilder builder) { String elementID = (String) this.hints.get(SVGHints.KEY_ELEMENT_ID); if (elementID != null) { this.hints.put(SVGHints.KEY_ELEMENT_ID, null); // clear it if (this.elementIDs.contains(elementID)) { throw new IllegalStateException("The element id " + elementID + " is already used."); } else { this.elementIDs.add(elementID); } builder.append(" id='").append(elementID).append('\''); } } /** * Draws the specified shape with the current {@code paint} and * {@code stroke}. There is direct handling for {@code Line2D}, * {@code Rectangle2D}, {@code Ellipse2D} and {@code Path2D}. All other * shapes are mapped to a {@code GeneralPath} and then drawn (effectively * as {@code Path2D} objects). * * @param s the shape ({@code null} not permitted). * * @see #fill(java.awt.Shape) */ @Override public void draw(Shape s) { // if the current stroke is not a BasicStroke then it is handled as // a special case if (!(this.stroke instanceof BasicStroke)) { fill(this.stroke.createStrokedShape(s)); return; } if (s instanceof Line2D) { Line2D l = (Line2D) s; this.sb.append(""); } else if (s instanceof Rectangle2D) { Rectangle2D r = (Rectangle2D) s; this.sb.append(""); } else if (s instanceof Ellipse2D) { Ellipse2D e = (Ellipse2D) s; this.sb.append(""); } else if (s instanceof Path2D) { Path2D path = (Path2D) s; this.sb.append(""); this.sb.append(""); this.sb.append(""); } else { draw(new GeneralPath(s)); // handled as a Path2D next time through } } /** * Fills the specified shape with the current {@code paint}. There is * direct handling for {@code Rectangle2D}, {@code Ellipse2D} and * {@code Path2D}. All other shapes are mapped to a {@code GeneralPath} * and then filled. * * @param s the shape ({@code null} not permitted). * * @see #draw(java.awt.Shape) */ @Override public void fill(Shape s) { if (s instanceof Rectangle2D) { Rectangle2D r = (Rectangle2D) s; if (r.isEmpty()) { return; } this.sb.append(""); } else if (s instanceof Ellipse2D) { Ellipse2D e = (Ellipse2D) s; this.sb.append(""); } else if (s instanceof Path2D) { Path2D path = (Path2D) s; this.sb.append("'); this.sb.append(""); this.sb.append(""); } else { fill(new GeneralPath(s)); // handled as a Path2D next time through } } /** * Creates an SVG path string for the supplied Java2D path. * * @param path the path ({@code null} not permitted). * * @return An SVG path string. */ private String getSVGPathData(Path2D path) { StringBuilder b = new StringBuilder(); if (path.getWindingRule() == Path2D.WIND_EVEN_ODD) { b.append("fill-rule='evenodd' "); } b.append("d='"); float[] coords = new float[6]; PathIterator iterator = path.getPathIterator(null); while (!iterator.isDone()) { int type = iterator.currentSegment(coords); switch (type) { case (PathIterator.SEG_MOVETO): b.append('M').append(geomDP(coords[0])).append(',') .append(geomDP(coords[1])); break; case (PathIterator.SEG_LINETO): b.append('L').append(geomDP(coords[0])).append(',') .append(geomDP(coords[1])); break; case (PathIterator.SEG_QUADTO): b.append('Q').append(geomDP(coords[0])) .append(',').append(geomDP(coords[1])) .append(',').append(geomDP(coords[2])) .append(',').append(geomDP(coords[3])); break; case (PathIterator.SEG_CUBICTO): b.append('C').append(geomDP(coords[0])).append(',') .append(geomDP(coords[1])).append(',') .append(geomDP(coords[2])).append(',') .append(geomDP(coords[3])).append(',') .append(geomDP(coords[4])).append(',') .append(geomDP(coords[5])); break; case (PathIterator.SEG_CLOSE): b.append('Z'); break; default: break; } iterator.next(); } return b.append('\'').toString(); } /** * Returns the current alpha (transparency) in the range 0.0 to 1.0. * If the current composite is an {@link AlphaComposite} we read the alpha * value from there, otherwise this method returns 1.0. * * @return The current alpha (transparency) in the range 0.0 to 1.0. */ private float getAlpha() { float alpha = 1.0f; if (this.composite instanceof AlphaComposite) { AlphaComposite ac = (AlphaComposite) this.composite; alpha = ac.getAlpha(); } return alpha; } /** * Returns an SVG color string based on the current paint. To handle * {@code GradientPaint} we rely on the {@code setPaint()} method * having set the {@code gradientPaintRef} attribute. * * @return An SVG color string. */ private String svgColorStr() { String result = "black;"; if (this.paint instanceof Color) { return rgbColorStr((Color) this.paint); } else if (this.paint instanceof GradientPaint || this.paint instanceof LinearGradientPaint || this.paint instanceof RadialGradientPaint) { return "url(#" + this.gradientPaintRef + ")"; } return result; } /** * Returns the SVG RGB color string for the specified color. * * @param c the color ({@code null} not permitted). * * @return The SVG RGB color string. */ private String rgbColorStr(Color c) { StringBuilder b = new StringBuilder("rgb("); b.append(c.getRed()).append(",").append(c.getGreen()).append(",") .append(c.getBlue()).append(")"); return b.toString(); } /** * Returns a string representing the specified color in RGBA format. * * @param c the color ({@code null} not permitted). * * @return The SVG RGBA color string. */ private String rgbaColorStr(Color c) { StringBuilder b = new StringBuilder("rgba("); double alphaPercent = c.getAlpha() / 255.0; b.append(c.getRed()).append(',').append(c.getGreen()).append(',') .append(c.getBlue()); b.append(',').append(transformDP(alphaPercent)); b.append(')'); return b.toString(); } private static final String DEFAULT_STROKE_CAP = "butt"; private static final String DEFAULT_STROKE_JOIN = "miter"; private static final float DEFAULT_MITER_LIMIT = 4.0f; /** * Returns a stroke style string based on the current stroke and * alpha settings. Implementation note: the last attribute in the string * will not have a semicolon after it. * * @return A stroke style string. */ private String strokeStyle() { double strokeWidth = 1.0f; String strokeCap = DEFAULT_STROKE_CAP; String strokeJoin = DEFAULT_STROKE_JOIN; float miterLimit = DEFAULT_MITER_LIMIT; float[] dashArray = new float[0]; if (this.stroke instanceof BasicStroke) { BasicStroke bs = (BasicStroke) this.stroke; strokeWidth = bs.getLineWidth() > 0.0 ? bs.getLineWidth() : this.zeroStrokeWidth; switch (bs.getEndCap()) { case BasicStroke.CAP_ROUND: strokeCap = "round"; break; case BasicStroke.CAP_SQUARE: strokeCap = "square"; break; case BasicStroke.CAP_BUTT: default: // already set to "butt" } switch (bs.getLineJoin()) { case BasicStroke.JOIN_BEVEL: strokeJoin = "bevel"; break; case BasicStroke.JOIN_ROUND: strokeJoin = "round"; break; case BasicStroke.JOIN_MITER: default: // already set to "miter" } miterLimit = bs.getMiterLimit(); dashArray = bs.getDashArray(); } StringBuilder b = new StringBuilder(); b.append("stroke-width:").append(strokeWidth).append(";"); b.append("stroke:").append(svgColorStr()).append(";"); b.append("stroke-opacity:").append(getColorAlpha() * getAlpha()); if (!strokeCap.equals(DEFAULT_STROKE_CAP)) { b.append(";stroke-linecap:").append(strokeCap); } if (!strokeJoin.equals(DEFAULT_STROKE_JOIN)) { b.append(";stroke-linejoin:").append(strokeJoin); } if (Math.abs(DEFAULT_MITER_LIMIT - miterLimit) > 0.001) { b.append(";stroke-miterlimit:").append(geomDP(miterLimit)); } if (dashArray != null && dashArray.length != 0) { b.append(";stroke-dasharray:"); for (int i = 0; i < dashArray.length; i++) { if (i != 0) { b.append(","); } b.append(dashArray[i]); } } if (this.checkStrokeControlHint) { Object hint = getRenderingHint(RenderingHints.KEY_STROKE_CONTROL); if (RenderingHints.VALUE_STROKE_NORMALIZE.equals(hint)) { b.append(";shape-rendering:crispEdges"); } if (RenderingHints.VALUE_STROKE_PURE.equals(hint)) { b.append(";shape-rendering:geometricPrecision"); } } return b.toString(); } /** * Returns the alpha value of the current {@code paint}, or {@code 1.0f} if * it is not an instance of {@code Color}. * * @return The alpha value (in the range {@code 0.0} to {@code 1.0}). */ private float getColorAlpha() { if (this.paint instanceof Color) { Color c = (Color) this.paint; return c.getAlpha() / 255.0f; } return 1f; } /** * Returns a fill style string based on the current paint and * alpha settings. * * @return A fill style string. */ private String getSVGFillStyle() { StringBuilder b = new StringBuilder(); b.append("fill:").append(svgColorStr()); double opacity = getColorAlpha() * getAlpha(); if (opacity < 1.0) { b.append(';').append("fill-opacity:").append(opacity); } return b.toString(); } /** * Returns the current font used for drawing text. * * @return The current font (never {@code null}). * * @see #setFont(java.awt.Font) */ @Override public Font getFont() { return this.font; } /** * Sets the font to be used for drawing text. * * @param font the font ({@code null} is permitted but ignored). * * @see #getFont() */ @Override public void setFont(Font font) { if (font == null) { return; } this.font = font; } /** * Returns the function that generates SVG font references from a supplied * Java font family name. The default function will convert Java logical * font names to the equivalent SVG generic font name, pass-through all * other font names unchanged, and surround the result in single quotes. * * @return The font mapper (never {@code null}). * * @see #setFontFunction(java.util.function.Function) * @since 5.0 */ public Function getFontFunction() { return this.fontFunction; } /** * Sets the font function that is used to generate SVG font references from * Java font family names. * * @param fontFunction the font mapper ({@code null} not permitted). * * @since 5.0 */ public void setFontFunction(Function fontFunction) { Args.nullNotPermitted(fontFunction, "fontFunction"); this.fontFunction = fontFunction; } /** * Returns the font size units. The default value is {@code SVGUnits.PX}. * * @return The font size units. * * @since 3.4 */ public SVGUnits getFontSizeUnits() { return this.fontSizeUnits; } /** * Sets the font size units. In general, if this method is used it should * be called immediately after the {@code SVGGraphics2D} instance is * created and before any content is generated. * * @param fontSizeUnits the font size units ({@code null} not permitted). * * @since 3.4 */ public void setFontSizeUnits(SVGUnits fontSizeUnits) { Args.nullNotPermitted(fontSizeUnits, "fontSizeUnits"); this.fontSizeUnits = fontSizeUnits; } /** * Returns a string containing font style info. * * @return A string containing font style info. */ private String getSVGFontStyle() { StringBuilder b = new StringBuilder(); b.append("fill: ").append(svgColorStr()).append("; "); b.append("fill-opacity: ").append(getColorAlpha() * getAlpha()) .append("; "); String fontFamily = this.fontFunction.apply(this.font.getFamily()); b.append("font-family: ").append(fontFamily).append("; "); b.append("font-size: ").append(this.font.getSize()).append(this.fontSizeUnits).append(";"); if (this.font.isBold()) { b.append(" font-weight: bold;"); } if (this.font.isItalic()) { b.append(" font-style: italic;"); } Object tracking = this.font.getAttributes().get(TextAttribute.TRACKING); if (tracking instanceof Number) { double spacing = ((Number) tracking).doubleValue() * this.font.getSize(); if (Math.abs(spacing) > 0.000001) { // not zero b.append(" letter-spacing: ").append(geomDP(spacing)).append(';'); } } return b.toString(); } /** * Returns the font metrics for the specified font. * * @param f the font. * * @return The font metrics. */ @Override public FontMetrics getFontMetrics(Font f) { if (this.fmImage == null) { this.fmImage = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB); this.fmImageG2D = this.fmImage.createGraphics(); this.fmImageG2D.setRenderingHint( RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); } return this.fmImageG2D.getFontMetrics(f); } /** * Returns the font render context. * * @return The font render context (never {@code null}). */ @Override public FontRenderContext getFontRenderContext() { return this.fontRenderContext; } /** * Draws a string at {@code (x, y)}. The start of the text at the * baseline level will be aligned with the {@code (x, y)} point. *

* Note that you can make use of the {@link SVGHints#KEY_TEXT_RENDERING} * hint when drawing strings (this is completely optional though). * * @param str the string ({@code null} not permitted). * @param x the x-coordinate. * @param y the y-coordinate. * * @see #drawString(java.lang.String, float, float) */ @Override public void drawString(String str, int x, int y) { drawString(str, (float) x, (float) y); } /** * Draws a string at {@code (x, y)}. The start of the text at the * baseline level will be aligned with the {@code (x, y)} point. *

* Note that you can make use of the {@link SVGHints#KEY_TEXT_RENDERING} * hint when drawing strings (this is completely optional though). * * @param str the string ({@code null} not permitted). * @param x the x-coordinate. * @param y the y-coordinate. */ @Override public void drawString(String str, float x, float y) { if (str == null) { throw new NullPointerException("Null 'str' argument."); } if (str.isEmpty()) { return; } if (!SVGHints.VALUE_DRAW_STRING_TYPE_VECTOR.equals( this.hints.get(SVGHints.KEY_DRAW_STRING_TYPE))) { this.sb.append(""); this.sb.append(""); this.sb.append(SVGUtils.escapeForXML(str)).append(""); this.sb.append(""); } else { AttributedString as = new AttributedString(str, this.font.getAttributes()); drawString(as.getIterator(), x, y); } } /** * Draws a string of attributed characters at {@code (x, y)}. The * call is delegated to * {@link #drawString(AttributedCharacterIterator, float, float)}. * * @param iterator an iterator for the characters. * @param x the x-coordinate. * @param y the x-coordinate. */ @Override public void drawString(AttributedCharacterIterator iterator, int x, int y) { drawString(iterator, (float) x, (float) y); } /** * Draws a string of attributed characters at {@code (x, y)}. * * @param iterator an iterator over the characters ({@code null} not * permitted). * @param x the x-coordinate. * @param y the y-coordinate. */ @Override public void drawString(AttributedCharacterIterator iterator, float x, float y) { Set s = iterator.getAllAttributeKeys(); if (!s.isEmpty()) { TextLayout layout = new TextLayout(iterator, getFontRenderContext()); layout.draw(this, x, y); } else { StringBuilder strb = new StringBuilder(); iterator.first(); for (int i = iterator.getBeginIndex(); i < iterator.getEndIndex(); i++) { strb.append(iterator.current()); iterator.next(); } drawString(strb.toString(), x, y); } } /** * Draws the specified glyph vector at the location {@code (x, y)}. * * @param g the glyph vector ({@code null} not permitted). * @param x the x-coordinate. * @param y the y-coordinate. */ @Override public void drawGlyphVector(GlyphVector g, float x, float y) { fill(g.getOutline(x, y)); } /** * Applies the translation {@code (tx, ty)}. This call is delegated * to {@link #translate(double, double)}. * * @param tx the x-translation. * @param ty the y-translation. * * @see #translate(double, double) */ @Override public void translate(int tx, int ty) { translate((double) tx, (double) ty); } /** * Applies the translation {@code (tx, ty)}. * * @param tx the x-translation. * @param ty the y-translation. */ @Override public void translate(double tx, double ty) { AffineTransform t = getTransform(); t.translate(tx, ty); setTransform(t); } /** * Applies a rotation (anti-clockwise) about {@code (0, 0)}. * * @param theta the rotation angle (in radians). */ @Override public void rotate(double theta) { AffineTransform t = getTransform(); t.rotate(theta); setTransform(t); } /** * Applies a rotation (anti-clockwise) about {@code (x, y)}. * * @param theta the rotation angle (in radians). * @param x the x-coordinate. * @param y the y-coordinate. */ @Override public void rotate(double theta, double x, double y) { translate(x, y); rotate(theta); translate(-x, -y); } /** * Applies a scale transformation. * * @param sx the x-scaling factor. * @param sy the y-scaling factor. */ @Override public void scale(double sx, double sy) { AffineTransform t = getTransform(); t.scale(sx, sy); setTransform(t); } /** * Applies a shear transformation. This is equivalent to the following * call to the {@code transform} method: *

*
  • * {@code transform(AffineTransform.getShearInstance(shx, shy));} *
* * @param shx the x-shear factor. * @param shy the y-shear factor. */ @Override public void shear(double shx, double shy) { transform(AffineTransform.getShearInstance(shx, shy)); } /** * Applies this transform to the existing transform by concatenating it. * * @param t the transform ({@code null} not permitted). */ @Override public void transform(AffineTransform t) { AffineTransform tx = getTransform(); tx.concatenate(t); setTransform(tx); } /** * Returns a copy of the current transform. * * @return A copy of the current transform (never {@code null}). * * @see #setTransform(java.awt.geom.AffineTransform) */ @Override public AffineTransform getTransform() { return (AffineTransform) this.transform.clone(); } /** * Sets the transform. * * @param t the new transform ({@code null} permitted, resets to the * identity transform). * * @see #getTransform() */ @Override public void setTransform(AffineTransform t) { if (t == null) { this.transform = new AffineTransform(); } else { this.transform = new AffineTransform(t); } this.clipRef = null; } /** * Returns {@code true} if the rectangle (in device space) intersects * with the shape (the interior, if {@code onStroke} is {@code false}, * otherwise the stroked outline of the shape). * * @param rect a rectangle (in device space). * @param s the shape. * @param onStroke test the stroked outline only? * * @return A boolean. */ @Override public boolean hit(Rectangle rect, Shape s, boolean onStroke) { Shape ts; if (onStroke) { ts = this.transform.createTransformedShape( this.stroke.createStrokedShape(s)); } else { ts = this.transform.createTransformedShape(s); } if (!rect.getBounds2D().intersects(ts.getBounds2D())) { return false; } Area a1 = new Area(rect); Area a2 = new Area(ts); a1.intersect(a2); return !a1.isEmpty(); } /** * Does nothing in this {@code SVGGraphics2D} implementation. */ @Override public void setPaintMode() { // do nothing } /** * Does nothing in this {@code SVGGraphics2D} implementation. * * @param c ignored */ @Override public void setXORMode(Color c) { // do nothing } /** * Returns the bounds of the user clipping region. * * @return The clip bounds (possibly {@code null}). * * @see #getClip() */ @Override public Rectangle getClipBounds() { if (this.clip == null) { return null; } return getClip().getBounds(); } /** * Returns the user clipping region. The initial default value is * {@code null}. * * @return The user clipping region (possibly {@code null}). * * @see #setClip(java.awt.Shape) */ @Override public Shape getClip() { if (this.clip == null) { return null; } AffineTransform inv; try { inv = this.transform.createInverse(); return inv.createTransformedShape(this.clip); } catch (NoninvertibleTransformException ex) { return null; } } /** * Sets the user clipping region. * * @param shape the new user clipping region ({@code null} permitted). * * @see #getClip() */ @Override public void setClip(Shape shape) { // null is handled fine here... this.clip = this.transform.createTransformedShape(shape); this.clipRef = null; } /** * Registers the clip so that we can later write out all the clip * definitions in the DEFS element. * * @param clip the clip (ignored if {@code null}) */ private String registerClip(Shape clip) { if (clip == null) { this.clipRef = null; return null; } // generate the path String pathStr = getSVGPathData(new Path2D.Double(clip)); int index = this.clipPaths.indexOf(pathStr); if (index < 0) { this.clipPaths.add(pathStr); index = this.clipPaths.size() - 1; } return this.defsKeyPrefix + CLIP_KEY_PREFIX + index; } /** * Returns a string representation of the specified number for use in the * SVG output. * * @param d the number. * * @return A string representation of the number. */ private String transformDP(final double d) { return this.transformDoubleConverter.apply(d); } /** * Returns a string representation of the specified number for use in the * SVG output. * * @param d the number. * * @return A string representation of the number. */ private String geomDP(final double d) { return this.geomDoubleConverter.apply(d); } private String getSVGTransform(AffineTransform t) { StringBuilder b = new StringBuilder("matrix("); b.append(transformDP(t.getScaleX())).append(","); b.append(transformDP(t.getShearY())).append(","); b.append(transformDP(t.getShearX())).append(","); b.append(transformDP(t.getScaleY())).append(","); b.append(transformDP(t.getTranslateX())).append(","); b.append(transformDP(t.getTranslateY())).append(")"); return b.toString(); } /** * Clips to the intersection of the current clipping region and the * specified shape. * * According to the Oracle API specification, this method will accept a * {@code null} argument, however there is a bug report (opened in 2004 * and fixed in 2021) that describes the passing of {@code null} as * "not recommended": *

* * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6206189 * * @param s the clip shape ({@code null} not recommended). */ @Override public void clip(Shape s) { if (s instanceof Line2D) { s = s.getBounds2D(); } if (this.clip == null) { setClip(s); return; } Shape ts = this.transform.createTransformedShape(s); if (!ts.intersects(this.clip.getBounds2D())) { setClip(new Rectangle2D.Double()); } else { Area a1 = new Area(ts); Area a2 = new Area(this.clip); a1.intersect(a2); this.clip = new Path2D.Double(a1); } this.clipRef = null; } /** * Clips to the intersection of the current clipping region and the * specified rectangle. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. */ @Override public void clipRect(int x, int y, int width, int height) { setRect(x, y, width, height); clip(this.rect); } /** * Sets the user clipping region to the specified rectangle. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. * * @see #getClip() */ @Override public void setClip(int x, int y, int width, int height) { setRect(x, y, width, height); setClip(this.rect); } /** * Draws a line from {@code (x1, y1)} to {@code (x2, y2)} using * the current {@code paint} and {@code stroke}. * * @param x1 the x-coordinate of the start point. * @param y1 the y-coordinate of the start point. * @param x2 the x-coordinate of the end point. * @param y2 the x-coordinate of the end point. */ @Override public void drawLine(int x1, int y1, int x2, int y2) { if (this.line == null) { this.line = new Line2D.Double(x1, y1, x2, y2); } else { this.line.setLine(x1, y1, x2, y2); } draw(this.line); } /** * Fills the specified rectangle with the current {@code paint}. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the rectangle width. * @param height the rectangle height. */ @Override public void fillRect(int x, int y, int width, int height) { setRect(x, y, width, height); fill(this.rect); } /** * Clears the specified rectangle by filling it with the current * background color. If the background color is {@code null}, this * method will do nothing. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. * * @see #getBackground() */ @Override public void clearRect(int x, int y, int width, int height) { if (getBackground() == null) { return; // we can't do anything } Paint saved = getPaint(); setPaint(getBackground()); fillRect(x, y, width, height); setPaint(saved); } /** * Draws a rectangle with rounded corners using the current * {@code paint} and {@code stroke}. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. * @param arcWidth the arc-width. * @param arcHeight the arc-height. * * @see #fillRoundRect(int, int, int, int, int, int) */ @Override public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { setRoundRect(x, y, width, height, arcWidth, arcHeight); draw(this.roundRect); } /** * Fills a rectangle with rounded corners using the current {@code paint}. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. * @param arcWidth the arc-width. * @param arcHeight the arc-height. * * @see #drawRoundRect(int, int, int, int, int, int) */ @Override public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { setRoundRect(x, y, width, height, arcWidth, arcHeight); fill(this.roundRect); } /** * Draws an oval framed by the rectangle {@code (x, y, width, height)} * using the current {@code paint} and {@code stroke}. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. * * @see #fillOval(int, int, int, int) */ @Override public void drawOval(int x, int y, int width, int height) { setOval(x, y, width, height); draw(this.oval); } /** * Fills an oval framed by the rectangle {@code (x, y, width, height)}. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. * * @see #drawOval(int, int, int, int) */ @Override public void fillOval(int x, int y, int width, int height) { setOval(x, y, width, height); fill(this.oval); } /** * Draws an arc contained within the rectangle * {@code (x, y, width, height)}, starting at {@code startAngle} * and continuing through {@code arcAngle} degrees using * the current {@code paint} and {@code stroke}. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. * @param startAngle the start angle in degrees, 0 = 3 o'clock. * @param arcAngle the angle (anticlockwise) in degrees. * * @see #fillArc(int, int, int, int, int, int) */ @Override public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) { this.arc.setArc(x, y, width, height, startAngle, arcAngle, Arc2D.OPEN); draw(this.arc); } /** * Fills an arc contained within the rectangle * {@code (x, y, width, height)}, starting at {@code startAngle} * and continuing through {@code arcAngle} degrees, using * the current {@code paint}. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. * @param startAngle the start angle in degrees, 0 = 3 o'clock. * @param arcAngle the angle (anticlockwise) in degrees. * * @see #drawArc(int, int, int, int, int, int) */ @Override public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) { this.arc.setArc(x, y, width, height, startAngle, arcAngle, Arc2D.PIE); fill(this.arc); } /** * Draws the specified multi-segment line using the current * {@code paint} and {@code stroke}. * * @param xPoints the x-points. * @param yPoints the y-points. * @param nPoints the number of points to use for the polyline. */ @Override public void drawPolyline(int[] xPoints, int[] yPoints, int nPoints) { GeneralPath p = GraphicsUtils.createPolygon(xPoints, yPoints, nPoints, false); draw(p); } /** * Draws the specified polygon using the current {@code paint} and * {@code stroke}. * * @param xPoints the x-points. * @param yPoints the y-points. * @param nPoints the number of points to use for the polygon. * * @see #fillPolygon(int[], int[], int) */ @Override public void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) { GeneralPath p = GraphicsUtils.createPolygon(xPoints, yPoints, nPoints, true); draw(p); } /** * Fills the specified polygon using the current {@code paint}. * * @param xPoints the x-points. * @param yPoints the y-points. * @param nPoints the number of points to use for the polygon. * * @see #drawPolygon(int[], int[], int) */ @Override public void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) { GeneralPath p = GraphicsUtils.createPolygon(xPoints, yPoints, nPoints, true); fill(p); } /** * Returns the bytes representing a PNG format image. * * @param img the image to encode ({@code null} not permitted). * * @return The bytes representing a PNG format image. */ private byte[] getPNGBytes(Image img) { Args.nullNotPermitted(img, "img"); RenderedImage ri; if (img instanceof RenderedImage) { ri = (RenderedImage) img; } else { BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = bi.createGraphics(); g2.drawImage(img, 0, 0, null); ri = bi; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(ri, "png", baos); } catch (IOException ex) { Logger.getLogger(SVGGraphics2D.class.getName()).log(Level.SEVERE, "IOException while writing PNG data.", ex); } return baos.toByteArray(); } /** * Draws an image at the location {@code (x, y)}. Note that the * {@code observer} is ignored. * * @param img the image ({@code null} permitted...method will do nothing). * @param x the x-coordinate. * @param y the y-coordinate. * @param observer ignored. * * @return {@code true} if there is no more drawing to be done. */ @Override public boolean drawImage(Image img, int x, int y, ImageObserver observer) { if (img == null) { return true; } int w = img.getWidth(observer); if (w < 0) { return false; } int h = img.getHeight(observer); if (h < 0) { return false; } return drawImage(img, x, y, w, h, observer); } /** * Draws the image into the rectangle defined by {@code (x, y, w, h)}. * Note that the {@code observer} is ignored (it is not useful in this * context). * * @param img the image ({@code null} permitted...draws nothing). * @param x the x-coordinate. * @param y the y-coordinate. * @param w the width. * @param h the height. * @param observer ignored. * * @return {@code true} if there is no more drawing to be done. */ @Override public boolean drawImage(Image img, int x, int y, int w, int h, ImageObserver observer) { if (img == null) { return true; } // the rendering hints control whether the image is embedded // (the default) or referenced... Object hint = getRenderingHint(SVGHints.KEY_IMAGE_HANDLING); if (SVGHints.VALUE_IMAGE_HANDLING_REFERENCE.equals(hint)) { // non-default case, hint was set by caller int count = this.imageElements.size(); String href = (String) this.hints.get(SVGHints.KEY_IMAGE_HREF); if (href == null) { href = this.filePrefix + count + this.fileSuffix; } else { // KEY_IMAGE_HREF value is for a single use, so clear it... this.hints.put(SVGHints.KEY_IMAGE_HREF, null); } ImageElement imageElement = new ImageElement(href, img); this.imageElements.add(imageElement); // write an SVG element for the img this.sb.append(""); return true; } else { // default to SVGHints.VALUE_IMAGE_HANDLING_EMBED this.sb.append(""); return true; } } /** * Draws an image at the location {@code (x, y)}. Note that the * {@code observer} is ignored. * * @param img the image ({@code null} permitted...draws nothing). * @param x the x-coordinate. * @param y the y-coordinate. * @param bgcolor the background color ({@code null} permitted). * @param observer ignored. * * @return {@code true} if there is no more drawing to be done. */ @Override public boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer) { if (img == null) { return true; } int w = img.getWidth(null); if (w < 0) { return false; } int h = img.getHeight(null); if (h < 0) { return false; } return drawImage(img, x, y, w, h, bgcolor, observer); } /** * Draws an image to the rectangle {@code (x, y, w, h)} (scaling it if * required), first filling the background with the specified color. Note * that the {@code observer} is ignored. * * @param img the image. * @param x the x-coordinate. * @param y the y-coordinate. * @param w the width. * @param h the height. * @param bgcolor the background color ({@code null} permitted). * @param observer ignored. * * @return {@code true} if the image is drawn. */ @Override public boolean drawImage(Image img, int x, int y, int w, int h, Color bgcolor, ImageObserver observer) { this.sb.append("'); Paint saved = getPaint(); setPaint(bgcolor); fillRect(x, y, w, h); setPaint(saved); boolean result = drawImage(img, x, y, w, h, observer); this.sb.append(""); return result; } /** * Draws part of an image (defined by the source rectangle * {@code (sx1, sy1, sx2, sy2)}) into the destination rectangle * {@code (dx1, dy1, dx2, dy2)}. Note that the {@code observer} is ignored. * * @param img the image. * @param dx1 the x-coordinate for the top left of the destination. * @param dy1 the y-coordinate for the top left of the destination. * @param dx2 the x-coordinate for the bottom right of the destination. * @param dy2 the y-coordinate for the bottom right of the destination. * @param sx1 the x-coordinate for the top left of the source. * @param sy1 the y-coordinate for the top left of the source. * @param sx2 the x-coordinate for the bottom right of the source. * @param sy2 the y-coordinate for the bottom right of the source. * * @return {@code true} if the image is drawn. */ @Override public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer) { int w = dx2 - dx1; int h = dy2 - dy1; BufferedImage img2 = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = img2.createGraphics(); g2.drawImage(img, 0, 0, w, h, sx1, sy1, sx2, sy2, null); return drawImage(img2, dx1, dy1, null); } /** * Draws part of an image (defined by the source rectangle * {@code (sx1, sy1, sx2, sy2)}) into the destination rectangle * {@code (dx1, dy1, dx2, dy2)}. The destination rectangle is first * cleared by filling it with the specified {@code bgcolor}. Note that * the {@code observer} is ignored. * * @param img the image. * @param dx1 the x-coordinate for the top left of the destination. * @param dy1 the y-coordinate for the top left of the destination. * @param dx2 the x-coordinate for the bottom right of the destination. * @param dy2 the y-coordinate for the bottom right of the destination. * @param sx1 the x-coordinate for the top left of the source. * @param sy1 the y-coordinate for the top left of the source. * @param sx2 the x-coordinate for the bottom right of the source. * @param sy2 the y-coordinate for the bottom right of the source. * @param bgcolor the background color ({@code null} permitted). * @param observer ignored. * * @return {@code true} if the image is drawn. */ @Override public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer) { Paint saved = getPaint(); setPaint(bgcolor); fillRect(dx1, dy1, dx2 - dx1, dy2 - dy1); setPaint(saved); return drawImage(img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, observer); } /** * Draws the rendered image. If {@code img} is {@code null} this method * does nothing. * * @param img the image ({@code null} permitted). * @param xform the transform. */ @Override public void drawRenderedImage(RenderedImage img, AffineTransform xform) { if (img == null) { return; } BufferedImage bi = GraphicsUtils.convertRenderedImage(img); drawImage(bi, xform, null); } /** * Draws the renderable image. * * @param img the renderable image. * @param xform the transform. */ @Override public void drawRenderableImage(RenderableImage img, AffineTransform xform) { RenderedImage ri = img.createDefaultRendering(); drawRenderedImage(ri, xform); } /** * Draws an image with the specified transform. Note that the * {@code observer} is ignored. * * @param img the image. * @param xform the transform ({@code null} permitted). * @param obs the image observer (ignored). * * @return {@code true} if the image is drawn. */ @Override public boolean drawImage(Image img, AffineTransform xform, ImageObserver obs) { AffineTransform savedTransform = getTransform(); if (xform != null) { transform(xform); } boolean result = drawImage(img, 0, 0, obs); if (xform != null) { setTransform(savedTransform); } return result; } /** * Draws the image resulting from applying the {@code BufferedImageOp} * to the specified image at the location {@code (x, y)}. * * @param img the image. * @param op the operation ({@code null} permitted). * @param x the x-coordinate. * @param y the y-coordinate. */ @Override public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) { BufferedImage imageToDraw = img; if (op != null) { imageToDraw = op.filter(img, null); } drawImage(imageToDraw, new AffineTransform(1f, 0f, 0f, 1f, x, y), null); } /** * This method does nothing. The operation assumes that the output is in * bitmap form, which is not the case for SVG, so we silently ignore * this method call. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width of the area. * @param height the height of the area. * @param dx the delta x. * @param dy the delta y. */ @Override public void copyArea(int x, int y, int width, int height, int dx, int dy) { // do nothing, this operation is silently ignored. } /** * This method does nothing, there are no resources to dispose. */ @Override public void dispose() { // nothing to do } /** * Returns the SVG element that has been generated by calls to this * {@code Graphics2D} implementation. * * @return The SVG element. */ public String getSVGElement() { return getSVGElement(null); } /** * Returns the SVG element that has been generated by calls to this * {@code Graphics2D} implementation, giving it the specified {@code id}. * If {@code id} is {@code null}, the element will have no {@code id} * attribute. * * @param id the element id ({@code null} permitted). * * @return A string containing the SVG element. * * @since 1.8 */ public String getSVGElement(String id) { return getSVGElement(id, true, null, null, null); } /** * Returns the SVG element that has been generated by calls to this * {@code Graphics2D} implementation, giving it the specified {@code id}. * If {@code id} is {@code null}, the element will have no {@code id} * attribute. This method also allows for a {@code viewBox} to be defined, * along with the settings that handle scaling. * * @param id the element id ({@code null} permitted). * @param includeDimensions include the width and height attributes? * @param viewBox the view box specification (if {@code null} then no * {@code viewBox} attribute will be defined). * @param preserveAspectRatio the value of the {@code preserveAspectRatio} * attribute (if {@code null} then not attribute will be defined). * @param meetOrSlice the value of the meetOrSlice attribute. * * @return A string containing the SVG element. * * @since 3.2 */ public String getSVGElement(String id, boolean includeDimensions, ViewBox viewBox, PreserveAspectRatio preserveAspectRatio, MeetOrSlice meetOrSlice) { StringBuilder svg = new StringBuilder("'); // only need to write DEFS if there is something to include if (isDefsOutputRequired()) { StringBuilder defs = new StringBuilder(""); for (var entry : this.gradientPaints.entrySet()) { defs.append(getLinearGradientElement(entry.getValue(), entry.getKey().getPaint())); } for (var entry : this.linearGradientPaints.entrySet()) { defs.append(getLinearGradientElement(entry.getValue(), entry.getKey().getPaint())); } for (var entry : this.radialGradientPaints.entrySet()) { defs.append(getRadialGradientElement(entry.getValue(), entry.getKey().getPaint())); } for (int i = 0; i < this.clipPaths.size(); i++) { StringBuilder b = new StringBuilder(""); b.append(""); b.append(""); defs.append(b); } defs.append(""); svg.append(defs); } svg.append(this.sb); svg.append(""); return svg.toString(); } /** * Returns {@code true} if there are items that need to be written to the * DEFS element, and {@code false} otherwise. * * @return A boolean. */ private boolean isDefsOutputRequired() { return !(this.gradientPaints.isEmpty() && this.linearGradientPaints.isEmpty() && this.radialGradientPaints.isEmpty() && this.clipPaths.isEmpty()); } /** * Returns an SVG document (this contains the content returned by the * {@link #getSVGElement()} method, prepended with the required document * header). * * @return An SVG document. */ public String getSVGDocument() { StringBuilder b = new StringBuilder(); b.append("\n"); b.append("\n"); b.append(getSVGElement()); return b.append("\n").toString(); } /** * Returns the list of image elements that have been referenced in the * SVG output but not embedded. If the image files don't already exist, * you can use this list as the basis for creating the image files. * * @return The list of image elements. * * @see SVGHints#KEY_IMAGE_HANDLING */ public List getSVGImages() { return this.imageElements; } /** * Returns a new set containing the element IDs that have been used in * output so far. * * @return The element IDs. * * @since 1.5 */ public Set getElementIDs() { return new HashSet<>(this.elementIDs); } /** * Returns an element to represent a linear gradient. All the linear * gradients that are used get written to the DEFS element in the SVG. * * @param id the reference id. * @param paint the gradient. * * @return The SVG element. */ private String getLinearGradientElement(String id, GradientPaint paint) { StringBuilder b = new StringBuilder("'); Color c1 = paint.getColor1(); b.append(""); Color c2 = paint.getColor2(); b.append(""); return b.append("").toString(); } /** * Returns an element to represent a linear gradient. All the linear * gradients that are used get written to the DEFS element in the SVG. * * @param id the reference id. * @param paint the gradient. * * @return The SVG element. */ private String getLinearGradientElement(String id, LinearGradientPaint paint) { StringBuilder b = new StringBuilder(""); for (int i = 0; i < paint.getFractions().length; i++) { Color c = paint.getColors()[i]; float fraction = paint.getFractions()[i]; b.append(""); } return b.append("").toString(); } /** * Returns an element to represent a radial gradient. All the radial * gradients that are used get written to the DEFS element in the SVG. * * @param id the reference id. * @param rgp the radial gradient. * * @return The SVG element. */ private String getRadialGradientElement(String id, RadialGradientPaint rgp) { StringBuilder b = new StringBuilder("'); Color[] colors = rgp.getColors(); float[] fractions = rgp.getFractions(); for (int i = 0; i < colors.length; i++) { Color c = colors[i]; float f = fractions[i]; b.append(""); } return b.append("").toString(); } /** * Returns a clip path reference for the current user clip. This is * written out on all SVG elements that draw or fill shapes or text. * * @return A clip path reference. */ private String getClipPathRef() { if (this.clip == null) { return ""; } if (this.clipRef == null) { this.clipRef = registerClip(getClip()); } StringBuilder b = new StringBuilder(); b.append("clip-path='url(#").append(this.clipRef).append(")'"); return b.toString(); } /** * Sets the attributes of the reusable {@link Rectangle2D} object that is * used by the {@link SVGGraphics2D#drawRect(int, int, int, int)} and * {@link SVGGraphics2D#fillRect(int, int, int, int)} methods. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. */ private void setRect(int x, int y, int width, int height) { if (this.rect == null) { this.rect = new Rectangle2D.Double(x, y, width, height); } else { this.rect.setRect(x, y, width, height); } } /** * Sets the attributes of the reusable {@link RoundRectangle2D} object that * is used by the {@link #drawRoundRect(int, int, int, int, int, int)} and * {@link #fillRoundRect(int, int, int, int, int, int)} methods. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. * @param arcWidth the arc width. * @param arcHeight the arc height. */ private void setRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { if (this.roundRect == null) { this.roundRect = new RoundRectangle2D.Double(x, y, width, height, arcWidth, arcHeight); } else { this.roundRect.setRoundRect(x, y, width, height, arcWidth, arcHeight); } } /** * Sets the attributes of the reusable {@link Ellipse2D} object that is * used by the {@link #drawOval(int, int, int, int)} and * {@link #fillOval(int, int, int, int)} methods. * * @param x the x-coordinate. * @param y the y-coordinate. * @param width the width. * @param height the height. */ private void setOval(int x, int y, int width, int height) { if (this.oval == null) { this.oval = new Ellipse2D.Double(x, y, width, height); } else { this.oval.setFrame(x, y, width, height); } } } jfreesvg-5.0.6/src/main/java/org/jfree/svg/SVGGraphicsConfiguration.java000066400000000000000000000133641463574317400262120ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-present, by David Gilbert. All rights reserved. * * Project Info: http://www.jfree.org/jfreesvg/index.html * * 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 . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * JFreeSVG home page: * * http://www.jfree.org/jfreesvg * */ package org.jfree.svg; import java.awt.AWTException; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.ImageCapabilities; import java.awt.Rectangle; import java.awt.Transparency; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.DirectColorModel; import java.awt.image.VolatileImage; import java.awt.image.WritableRaster; /** * A graphics configuration for the {@link SVGGraphics2D} class. */ public class SVGGraphicsConfiguration extends GraphicsConfiguration { private GraphicsDevice device; private final int width; private final int height; /** * Creates a new instance. * * @param width the width of the bounds. * @param height the height of the bounds. */ public SVGGraphicsConfiguration(int width, int height) { super(); this.width = width; this.height = height; } /** * Returns the graphics device that this configuration is associated with. * * @return The graphics device (never {@code null}). */ @Override public GraphicsDevice getDevice() { if (this.device == null) { this.device = new SVGGraphicsDevice("JFreeSVG-GraphicsDevice", this); } return this.device; } /** * Returns the color model for this configuration. * * @return The color model. */ @Override public ColorModel getColorModel() { return getColorModel(Transparency.TRANSLUCENT); } /** * Returns the color model for the specified transparency type, or * {@code null}. * * @param transparency the transparency type. * * @return A color model (possibly {@code null}). */ @Override public ColorModel getColorModel(int transparency) { switch (transparency) { case Transparency.TRANSLUCENT: return ColorModel.getRGBdefault(); case Transparency.OPAQUE: return new DirectColorModel(32, 0x00ff0000, 0x0000ff00, 0x000000ff); default: return null; } } /** * Returns the default transform. * * @return The default transform. */ @Override public AffineTransform getDefaultTransform() { return new AffineTransform(); } /** * Returns the normalizing transform. * * @return The normalizing transform. */ @Override public AffineTransform getNormalizingTransform() { return new AffineTransform(); } /** * Returns the bounds for this configuration. * * @return The bounds. */ @Override public Rectangle getBounds() { return new Rectangle(this.width, this.height); } /** * Creates a compatible image. This override is only here to provide * support for Java 6 because from Java 7 onwards the super class has a * non-abstract implementation for this method. * * @param width the width. * @param height the height. * * @return A compatible image. */ @Override public BufferedImage createCompatibleImage(int width, int height) { ColorModel model = getColorModel(); WritableRaster raster = model.createCompatibleWritableRaster(width, height); return new BufferedImage(model, raster, model.isAlphaPremultiplied(), null); } private BufferedImage img; private GraphicsConfiguration gc; /** * Returns a volatile image. This method is a workaround for a * ClassCastException that occurs on MacOSX when exporting a Swing UI * that uses the Nimbus Look and Feel to SVG. * * @param width the image width. * @param height the image height. * @param caps the image capabilities. * @param transparency the transparency. * * @return The volatile image. * * @throws AWTException if there is a problem creating the image. */ @Override public VolatileImage createCompatibleVolatileImage(int width, int height, ImageCapabilities caps, int transparency) throws AWTException { if (img == null) { img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); gc = img.createGraphics().getDeviceConfiguration(); } return gc.createCompatibleVolatileImage(width, height, caps, transparency); } }jfreesvg-5.0.6/src/main/java/org/jfree/svg/SVGGraphicsDevice.java000066400000000000000000000053451463574317400246020ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-present, by David Gilbert. All rights reserved. * * Project Info: http://www.jfree.org/jfreesvg/index.html * * 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 . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * JFreeSVG home page: * * http://www.jfree.org/jfreesvg * */ package org.jfree.svg; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; /** * A graphics device for JFreeSVG. */ public class SVGGraphicsDevice extends GraphicsDevice { private final String id; private final GraphicsConfiguration defaultConfig; /** * Creates a new instance. * * @param id the id. * @param defaultConfig the default configuration. */ public SVGGraphicsDevice(String id, GraphicsConfiguration defaultConfig) { this.id = id; this.defaultConfig = defaultConfig; } /** * Returns the device type. * * @return The device type. */ @Override public int getType() { return GraphicsDevice.TYPE_PRINTER; } /** * Returns the id string. * * @return The id string. */ @Override public String getIDstring() { return this.id; } /** * Returns all configurations for this device. * * @return All configurations for this device. */ @Override public GraphicsConfiguration[] getConfigurations() { return new GraphicsConfiguration[] { getDefaultConfiguration() }; } /** * Returns the default configuration for this device. * * @return The default configuration for this device. */ @Override public GraphicsConfiguration getDefaultConfiguration() { return this.defaultConfig; } } jfreesvg-5.0.6/src/main/java/org/jfree/svg/SVGHints.java000066400000000000000000000500661463574317400230070ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-present, by David Gilbert. All rights reserved. * * Project Info: http://www.jfree.org/jfreesvg/index.html * * 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 . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * JFreeSVG home page: * * http://www.jfree.org/jfreesvg */ package org.jfree.svg; import java.awt.RenderingHints; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; /** * Defines the rendering hints that can be used with the {@link SVGGraphics2D} * class. The supported hints are:
*

    *
  • {@link #KEY_IMAGE_HANDLING} that controls how images are handled * (embedded in the SVG, or referenced externally);
  • *
  • {@link #KEY_IMAGE_HREF} that allows the caller to specify the image * href attribute for the next image;
  • *
  • {@link #KEY_TEXT_RENDERING} that allows configuration of the preferred * value of the SVG {@code text-rendering} attribute in text elements;
  • *
  • {@link #KEY_ELEMENT_ID} that allows the caller to specify the element * ID for the next element;
  • *
  • {@link #KEY_BEGIN_GROUP} tells the {@code SVGGraphics2D} instance * to start a new group element with attributes controlled by the hint value * (which may be a {@code String} for the group ID or, more generally, a * {@code Map} containing arbitrary attribute values). Any other * {@code Graphics2D} implementation will ignore this hint;
  • *
  • {@link #KEY_END_GROUP} tells the {@code SVGGraphics2D} instance * to end a group element. The hint value is ignored. The caller assumes * responsibility for balancing the number of {@code KEY_BEGIN_GROUP} and * {@code KEY_END_GROUP} hints. Any other {@code Graphics2D} * implementation will ignore this hint.
  • *
* */ public final class SVGHints { private SVGHints() { // no need to instantiate this } /** * The key for the hint that controls whether images are embedded in the * SVG or referenced externally. Valid hint values are * {@link #VALUE_IMAGE_HANDLING_EMBED} and * {@link #VALUE_IMAGE_HANDLING_REFERENCE}. */ public static final SVGHints.Key KEY_IMAGE_HANDLING = new SVGHints.Key(0); /** * Hint value for {@code KEY_IMAGE_HANDLING} to specify that images * should be embedded in the SVG output using PNG data {@code Base64} * encoded. */ public static final Object VALUE_IMAGE_HANDLING_EMBED = "VALUE_IMAGE_HANDLING_EMBED"; /** * Hint value for {@code KEY_IMAGE_HANDLING} to say that images should * be referenced externally. */ public static final Object VALUE_IMAGE_HANDLING_REFERENCE = "VALUE_IMAGE_HANDLING_REFERENCE"; /** * The key for a hint that permits configuration of the text-rendering * attribute in SVG text elements */ public static final SVGHints.Key KEY_TEXT_RENDERING = new SVGHints.Key(1); /** * Hint value for {@code KEY_TEXT_RENDERING} to set the * {@code text-rendering} attribute in SVG text elements to 'auto'. */ public static final String VALUE_TEXT_RENDERING_AUTO = "auto"; /** * Hint value for {@code KEY_TEXT_RENDERING} to set the * {@code text-rendering} attribute in SVG text elements to * 'optimizeSpeed'. */ public static final String VALUE_TEXT_RENDERING_SPEED = "optimizeSpeed"; /** * Hint value for {@code KEY_TEXT_RENDERING} to set the * {@code text-rendering} attribute in SVG text elements to * 'optimizeLegibility'. */ public static final String VALUE_TEXT_RENDERING_LEGIBILITY = "optimizeLegibility"; /** * Hint value for {@code KEY_TEXT_RENDERING} to set the * {@code text-rendering} attribute in SVG text elements to * 'geometricPrecision'. */ public static final String VALUE_TEXT_RENDERING_PRECISION = "geometricPrecision"; /** * Hint value for {@code KEY_TEXT_RENDERING} to set the * {@code text-rendering} attribute in SVG text elements to * 'inherit'. */ public static final String VALUE_TEXT_RENDERING_INHERIT = "inherit"; /** * Hint key to supply string to be used as the href for an image that is * referenced rather than embedded. The value associated with the key * should be a string and will be used for the next image element written * to the SVG output (and then the hint will be cleared). * * @since 1.5 */ public static final SVGHints.Key KEY_IMAGE_HREF = new SVGHints.Key(2); /** * Hint key to supply an element id for the next element generated. * * @since 1.5 */ public static final SVGHints.Key KEY_ELEMENT_ID = new SVGHints.Key(3); /** * Hint key that informs the {@code SVGGraphics2D} that the caller * would like to begin a new group element. The hint value is either: * *
    *
  • a {@code String} that will be used as the value of the * {@code id} attribute for the group; or
  • *
  • a {@code Map} instance containing arbitrary attribute values for the * group (usually including an {@code id}).
  • *
* After opening the new group the hint is cleared and it is the caller's * responsibility to close the group later using * {@link SVGHints#KEY_END_GROUP}. Groups can be nested. * * @since 1.7 */ public static final SVGHints.Key KEY_BEGIN_GROUP = new SVGHints.Key(4); /** * Hint key that informs the {@code SVGGraphics2D} that the caller * would like to close a previously opened group element. The hint * value is ignored. * * @since 1.7 */ public static final SVGHints.Key KEY_END_GROUP = new SVGHints.Key(5); /** * Hint key that informs the {@code SVGGraphics2D} that the caller * would like to add a title element to the output (with the hint value * being a string containing the title text). * * @since 1.9 */ public static final SVGHints.Key KEY_ELEMENT_TITLE = new SVGHints.Key(6); /** * The key for the hint that controls whether strings are rendered as * characters or vector graphics (implemented using {@code TextLayout}). * The latter will result in larger output files but avoids problems with * fonts not being available for the viewer. Valid hint values are * {@link #VALUE_DRAW_STRING_TYPE_STANDARD} and * {@link #VALUE_DRAW_STRING_TYPE_VECTOR}. * * @since 2.0 */ public static final SVGHints.Key KEY_DRAW_STRING_TYPE = new SVGHints.Key(7); /** * Hint value for {@code KEY_DRAW_STRING_TYPE} to specify that strings * should be written to the output using standard SVG text elements. * * @since 2.0 */ public static final Object VALUE_DRAW_STRING_TYPE_STANDARD = "VALUE_DRAW_STRING_TYPE_STANDARD"; /** * Hint value for {@code KEY_DRAW_STRING_TYPE} to say that strings * should be written to the output using vector graphics primitives. * * @since 2.0 */ public static final Object VALUE_DRAW_STRING_TYPE_VECTOR = "VALUE_DRAW_STRING_TYPE_VECTOR"; /** * A list of keys that are treated as synonyms for KEY_BEGIN_GROUP * (the list does not include KEY_BEGIN_GROUP itself). */ private static final List beginGroupKeys; /** * A list of keys that are treated as synonyms for KEY_END_GROUP * (the list does not include KEY_END_GROUP itself). */ private static final List endGroupKeys; /** * A list of keys that are treated as synonyms for KEY_ELEMENT_TITLE * (the list does not include KEY_ELEMENT_TITLE itself). */ private static final List elementTitleKeys; static { beginGroupKeys = new ArrayList<>(); endGroupKeys = new ArrayList<>(); elementTitleKeys = new ArrayList<>(); if (isOrsonChartsOnClasspath()) { beginGroupKeys.add(getOrsonChartsBeginElementKey()); endGroupKeys.add(getOrsonChartsEndElementKey()); elementTitleKeys.add(getOrsonChartsElementTitleKey()); } if (isJFreeChartOnClasspath()) { beginGroupKeys.add(getJFreeChartBeginElementKey()); endGroupKeys.add(getJFreeChartEndElementKey()); } } /** * Creates and returns a list of keys that are synonymous with * {@link #KEY_BEGIN_GROUP}. * * @return A list (never {@code null}). * * @since 1.8 */ public static List getBeginGroupKeys() { return new ArrayList<>(beginGroupKeys); } /** * Adds a key to the list of keys that are synonyms for * {@link SVGHints#KEY_BEGIN_GROUP}. * * @param key the key ({@code null} not permitted). * * @since 1.8 */ public static void addBeginGroupKey(RenderingHints.Key key) { beginGroupKeys.add(key); } /** * Removes a key from the list of keys that are synonyms for * {@link SVGHints#KEY_BEGIN_GROUP}. * * @param key the key ({@code null} not permitted). * * @since 1.8 */ public static void removeBeginGroupKey(RenderingHints.Key key) { beginGroupKeys.remove(key); } /** * Clears the list of keys that are treated as synonyms for * {@link SVGHints#KEY_BEGIN_GROUP}. * * @since 1.8 */ public static void clearBeginGroupKeys() { beginGroupKeys.clear(); } /** * Returns {@code true} if this key is equivalent to * {@link #KEY_BEGIN_GROUP}, and {@code false} otherwise. The purpose * of this method is to allow certain keys from external packages (such as * JFreeChart and Orson Charts) to use their own keys to drive the * behaviour of {@code SVGHints.KEY_BEGIN_GROUP}. This has two benefits: * (1) it avoids the necessity to make JFreeSVG a direct dependency, and * (2) it makes the grouping behaviour generic from the point of view of * the external package, rather than SVG-specific. * * @param key the key ({@code null} not permitted) * * @return A boolean. * * @since 1.8 */ public static boolean isBeginGroupKey(RenderingHints.Key key) { return SVGHints.KEY_BEGIN_GROUP.equals(key) || beginGroupKeys.contains(key); } /** * Creates and returns a list of keys that are synonymous with * {@link #KEY_END_GROUP}. * * @return A list (never {@code null}). * * @since 1.8 */ public static List getEndGroupKeys() { return new ArrayList<>(endGroupKeys); } /** * Adds a key to the list of keys that are synonyms for * {@link SVGHints#KEY_END_GROUP}. * * @param key the key ({@code null} not permitted). * * @since 1.8 */ public static void addEndGroupKey(RenderingHints.Key key) { endGroupKeys.add(key); } /** * Removes a key from the list of keys that are synonyms for * {@link SVGHints#KEY_END_GROUP}. * * @param key the key ({@code null} not permitted). * * @since 1.8 */ public static void removeEndGroupKey(RenderingHints.Key key) { endGroupKeys.remove(key); } /** * Clears the list of keys that are treated as synonyms for * {@link SVGHints#KEY_END_GROUP}. * * @since 1.8 */ public static void clearEndGroupKeys() { endGroupKeys.clear(); } /** * Returns {@code true} if this key is equivalent to * {@link #KEY_END_GROUP}, and {@code false} otherwise. The purpose * of this method is to allow certain keys from external packages (such as * JFreeChart and Orson Charts) to use their own keys to drive the * behaviour of {@code SVGHints.KEY_END_GROUP}. This has two benefits: * (1) it avoids the necessity to make JFreeSVG a direct dependency, and * (2) it makes the grouping behaviour generic from the point of view of * the external package, rather than SVG-specific. * * @param key the key ({@code null} not permitted). * * @return A boolean. * * @since 1.8 */ public static boolean isEndGroupKey(RenderingHints.Key key) { return SVGHints.KEY_END_GROUP.equals(key) || endGroupKeys.contains(key); } /** * Creates and returns a list of keys that are synonymous with * {@link #KEY_ELEMENT_TITLE}. * * @return A list (never {@code null}). * * @since 1.9 */ public static List getElementTitleKeys() { return new ArrayList<>(elementTitleKeys); } /** * Adds a key to the list of keys that are synonyms for * {@link SVGHints#KEY_ELEMENT_TITLE}. * * @param key the key ({@code null} not permitted). * * @since 1.9 */ public static void addElementTitleKey(RenderingHints.Key key) { elementTitleKeys.add(key); } /** * Removes a key from the list of keys that are synonyms for * {@link SVGHints#KEY_ELEMENT_TITLE}. * * @param key the key ({@code null} not permitted). * * @since 1.9 */ public static void removeElementTitleKey(RenderingHints.Key key) { elementTitleKeys.remove(key); } /** * Clears the list of keys that are treated as synonyms for * {@link SVGHints#KEY_ELEMENT_TITLE}. * * @since 1.9 */ public static void clearElementTitleKeys() { elementTitleKeys.clear(); } /** * Returns {@code true} if this key is equivalent to * {@link #KEY_ELEMENT_TITLE}, and {@code false} otherwise. The * purpose of this method is to allow certain keys from external packages * (such as JFreeChart and Orson Charts) to use their own keys to drive the * behaviour of {@code SVGHints.KEY_ELEMENT_TITLE}. This has two benefits: * (1) it avoids the necessity to make JFreeSVG a direct dependency, and * (2) it makes the element title behaviour generic from the point of view * of the external package, rather than SVG-specific. * * @param key the key ({@code null} not permitted) * * @return A boolean. * * @since 1.9 */ public static boolean isElementTitleKey(RenderingHints.Key key) { return SVGHints.KEY_ELEMENT_TITLE.equals(key) || elementTitleKeys.contains(key); } /** * Returns {@code true} if Orson Charts (version 1.3 or later) is on * the classpath, and {@code false} otherwise. This method is used to * auto-register keys from Orson Charts that should translate to the * behaviour of {@link SVGHints#KEY_BEGIN_GROUP} and * {@link SVGHints#KEY_END_GROUP}. *

* The Orson Charts library can be found at * http://www.object-refinery.com/orsoncharts/ * * @return A boolean. * * @since 1.8 */ private static boolean isOrsonChartsOnClasspath() { return (getOrsonChartsBeginElementKey() != null); } /** * Returns {@code true} if JFreeChart (1.0.18 or later) is on * the classpath, and {@code false} otherwise. This method is used to * auto-register keys from JFreeChart that should translate to the * behaviour of {@link SVGHints#KEY_BEGIN_GROUP} and * {@link SVGHints#KEY_END_GROUP}. * *

The JFreeChart library can be found at * http://www.jfree.org/jfreechart/. * * @return A boolean. * * @since 2.0 */ private static boolean isJFreeChartOnClasspath() { return (getJFreeChartBeginElementKey() != null); } private static RenderingHints.Key fetchKey(String className, String fieldName) { Class hintsClass; try { hintsClass = Class.forName(className); Field f = hintsClass.getDeclaredField(fieldName); return (RenderingHints.Key) f.get(null); } catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { return null; } } private static RenderingHints.Key getOrsonChartsBeginElementKey() { return fetchKey("com.orsoncharts.Chart3DHints", "KEY_BEGIN_ELEMENT"); } private static RenderingHints.Key getOrsonChartsEndElementKey() { return fetchKey("com.orsoncharts.Chart3DHints", "KEY_END_ELEMENT"); } private static RenderingHints.Key getOrsonChartsElementTitleKey() { return fetchKey("com.orsoncharts.Chart3DHints", "KEY_ELEMENT_TITLE"); } private static RenderingHints.Key getJFreeChartBeginElementKey() { return fetchKey("org.jfree.chart.ChartHints", "KEY_BEGIN_ELEMENT"); } private static RenderingHints.Key getJFreeChartEndElementKey() { return fetchKey("org.jfree.chart.ChartHints", "KEY_END_ELEMENT"); } /** * A key for hints used by the {@link SVGGraphics2D} class. */ public static class Key extends RenderingHints.Key { /** * Creates a new instance. * * @param privateKey the private key. */ public Key(int privateKey) { super(privateKey); } /** * Returns {@code true} if {@code val} is a value that is * compatible with this key, and {@code false} otherwise. * * @param val the value. * * @return A boolean. */ @Override public boolean isCompatibleValue(Object val) { switch (intKey()) { case 0: return VALUE_IMAGE_HANDLING_EMBED.equals(val) || VALUE_IMAGE_HANDLING_REFERENCE.equals(val); case 1: return VALUE_TEXT_RENDERING_AUTO.equals(val) || VALUE_TEXT_RENDERING_INHERIT.equals(val) || VALUE_TEXT_RENDERING_LEGIBILITY.equals(val) || VALUE_TEXT_RENDERING_PRECISION.equals(val) || VALUE_TEXT_RENDERING_SPEED.equals(val); case 2: // KEY_IMAGE:URL case 3: // KEY_ELEMENT_ID case 4: // KEY_BEGIN_GROUP return val == null || val instanceof String; case 5: // KEY_END_GROUP return true; // the value is ignored case 6: // KEY_ELEMENT_TITLE return val instanceof String; case 7: return val == null || VALUE_DRAW_STRING_TYPE_STANDARD.equals(val) || VALUE_DRAW_STRING_TYPE_VECTOR.equals(val); default: throw new RuntimeException("Not possible!"); } } } } jfreesvg-5.0.6/src/main/java/org/jfree/svg/SVGUnits.java000066400000000000000000000037341463574317400230240ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-present, by David Gilbert. All rights reserved. * * Project Info: http://www.jfree.org/jfreesvg/index.html * * 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 . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * JFreeSVG home page: * * http://www.jfree.org/jfreesvg * */ package org.jfree.svg; /** * An enumeration of the values for SVG units. * * @since 3.2 */ public enum SVGUnits { /** The font size. */ EM("em"), /** Height of character 'x'. */ EX("ex"), /** Pixels in user space coordinates. */ PX("px"), /** Points (1/72 inch). */ PT("pt"), /** Picas (1/6 inch). */ PC("pc"), /** Centimeters. */ CM("cm"), /** Millimeters. */ MM("mm"), /** Inches. */ IN("in"); private final String label; SVGUnits(String label) { this.label = label; } @Override public String toString() { return this.label; } } jfreesvg-5.0.6/src/main/java/org/jfree/svg/SVGUtils.java000066400000000000000000000170161463574317400230200ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-present, by David Gilbert. All rights reserved. * * Project Info: http://www.jfree.org/jfreesvg/index.html * * 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 . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * JFreeSVG home page: * * http://www.jfree.org/jfreesvg * */ package org.jfree.svg; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.util.function.DoubleFunction; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.GZIPOutputStream; import org.jfree.svg.util.Args; import org.jfree.svg.util.DoubleConverter; import org.jfree.svg.util.RyuDouble; /** * Utility methods related to the {@link SVGGraphics2D} implementation. */ public class SVGUtils { private SVGUtils() { // no need to instantiate this } /** * Returns a new string where any special characters in the source string * have been encoded. * * @param source the source string ({@code null} not permitted). * * @return A new string with special characters escaped for XML. * * @since 1.5 */ public static String escapeForXML(String source) { Args.nullNotPermitted(source, "source"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < source.length(); i++) { char c = source.charAt(i); switch (c) { case '<' : { sb.append("<"); break; } case '>' : { sb.append(">"); break; } case '&' : { String next = source.substring(i, Math.min(i + 6, source.length())); if (next.startsWith("<") || next.startsWith(">") || next.startsWith("&") || next.startsWith("'") || next.startsWith(""")) { sb.append(c); } else { sb.append("&"); } break; } case '\'' : { sb.append("'"); break; } case '\"' : { sb.append("""); break; } default : sb.append(c); } } return sb.toString(); } /** * Writes a file containing the SVG element. * * @param file the file ({@code null} not permitted). * @param svgElement the SVG element ({@code null} not permitted). * * @throws IOException if there is an I/O problem. * * @since 1.2 */ public static void writeToSVG(File file, String svgElement) throws IOException { writeToSVG(file, svgElement, false); } /** * Writes a file containing the SVG element. * * @param file the file ({@code null} not permitted). * @param svgElement the SVG element ({@code null} not permitted). * @param zip compress the output. * * @throws IOException if there is an I/O problem. * * @since 3.0 */ public static void writeToSVG(File file, String svgElement, boolean zip) throws IOException { BufferedWriter writer = null; try { OutputStream os = new FileOutputStream(file); if (zip) { os = new GZIPOutputStream(os); } OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8); writer = new BufferedWriter(osw); writer.write("\n"); writer.write(svgElement + "\n"); writer.flush(); } finally { try { if (writer != null) { writer.close(); } } catch (IOException ex) { throw new RuntimeException(ex); } } } /** * Writes an HTML file containing an SVG element. * * @param file the file. * @param title the title. * @param svgElement the SVG element. * * @throws IOException if there is an I/O problem. */ public static void writeToHTML(File file, String title, String svgElement) throws IOException { BufferedWriter writer = null; try { FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8); writer = new BufferedWriter(osw); writer.write("\n"); writer.write("\n"); writer.write("\n"); writer.write("" + title + "\n"); writer.write("\n"); writer.write("\n"); writer.write("\n"); writer.write(svgElement + "\n"); writer.write("\n"); writer.write("\n"); writer.flush(); } finally { try { if (writer != null) { writer.close(); } } catch (IOException ex) { Logger.getLogger(SVGUtils.class.getName()).log(Level.SEVERE, null, ex); } } } /** * Returns a string representing the specified double value. Internally * this method is using the code from: https://github.com/ulfjack/ryu which * is optimised for speed. * * @param d the value. * * @return A string representation of the double. * * @since 5.0 */ public static String doubleToString(double d) { return RyuDouble.doubleToString(d); } /** * Returns a double-to-string function that limits the output to a * specific number of decimal places (in the range 1 to 10). * * @param dp the decimal places (required in the range 1 to 10). * * @return The converter. * * @since 5.0 */ public static DoubleFunction createDoubleConverter(int dp) { return new DoubleConverter(dp); } } jfreesvg-5.0.6/src/main/java/org/jfree/svg/StandardFontFunction.java000066400000000000000000000103631463574317400254330ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-present, by David Gilbert. All rights reserved. * * Project Info: http://www.jfree.org/jfreesvg/index.html * * 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 . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * JFreeSVG home page: * * http://www.jfree.org/jfreesvg * */ package org.jfree.svg; import java.awt.Font; import java.util.HashMap; import java.util.Map; import java.util.function.Function; import org.jfree.svg.util.Args; /** * The standard function used in JFreeSVG to create font references for the * SVG output. This implementation will substitute SVG generic font names * for the Java logical fonts. Methods are provided for adding more font * substitutions if you require them. This function will also surround the * font name with single-quotes, which addresses issue #27. * * @since 5.0 */ public class StandardFontFunction implements Function { /** A map of substitute font family names. */ private final Map alternates; /** * Creates a new instance with mappings for the Java logical fonts. */ public StandardFontFunction() { this.alternates = new HashMap<>(); this.alternates.put(Font.DIALOG, "sans-serif"); this.alternates.put(Font.DIALOG_INPUT, "monospace"); this.alternates.put(Font.SANS_SERIF, "sans-serif"); this.alternates.put(Font.SERIF, "serif"); this.alternates.put(Font.MONOSPACED, "monospace"); } /** * Returns the (substitute) SVG font family name for the specified Java font * family name, or {@code null} if there is no substitute. * * @param family the Java font family name ({@code null} not permitted). * * @return The substitute SVG font family name, or {@code null}. */ public String get(String family) { Args.nullNotPermitted(family, "family"); return this.alternates.get(family); } /** * Adds a substitute font family name (to be used in the SVG output) for * the given Java font family name. If the specified alternate is * {@code null} it has the effect of clearing any existing substitution. * * @param family the Java font family name ({@code null} not permitted). * @param substitute the font family name to substitute in the SVG * output ({@code null} permitted). */ public void put(String family, String substitute) { Args.nullNotPermitted(family, "family"); this.alternates.put(family, substitute); } /** * Returns the SVG font reference for the supplied (Java) font family * name. This implementation provides substitute names for the Java * logical fonts. Other Java font family names are not changed, but all * font family names are surrounded in single quotes for the SVG output. * * @param family the font family name ({@code null} not permitted). * * @return The SVG font reference (never {@code null}). */ @Override public String apply(String family) { Args.nullNotPermitted(family, "family"); String alternate = this.alternates.get(family); if (alternate == null) { alternate = "\"" + family + "\""; } return alternate; } } jfreesvg-5.0.6/src/main/java/org/jfree/svg/ViewBox.java000066400000000000000000000050671463574317400227260ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-present, by David Gilbert. All rights reserved. * * Project Info: http://www.jfree.org/jfreesvg/index.html * * 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 . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * JFreeSVG home page: * * http://www.jfree.org/jfreesvg * */ package org.jfree.svg; import java.util.function.DoubleFunction; /** * Represents a view box in SVG. * * @since 3.2 */ public class ViewBox { private final double minX; private final double minY; private final double width; private final double height; /** * Creates a new instance with the specified dimensions. * * @param minX the x coordinate. * @param minY the y coordinate. * @param width the width. * @param height the height. */ public ViewBox(double minX, double minY, double width, double height) { this.minX = minX; this.minY = minY; this.width = width; this.height = height; } /** * Returns a string containing the view box coordinates and dimensions. * * @param df the converter function ({@code null} not permitted). * * @return A string containing the view box coordinates and dimensions. */ public String valueStr(DoubleFunction df) { return new StringBuilder().append(df.apply(this.minX)).append(' ') .append(df.apply(this.minY)).append(' ') .append(df.apply(this.width)).append(' ') .append(df.apply(this.height)).toString(); } } jfreesvg-5.0.6/src/main/java/org/jfree/svg/package-info.java000066400000000000000000000002561463574317400236620ustar00rootroot00000000000000/** * Contains {@link org.jfree.svg.SVGGraphics2D} and supporting classes that allow * Java2D rendering to Scalable Vector Graphics (SVG) format. */ package org.jfree.svg;jfreesvg-5.0.6/src/main/java/org/jfree/svg/util/000077500000000000000000000000001463574317400214455ustar00rootroot00000000000000jfreesvg-5.0.6/src/main/java/org/jfree/svg/util/Args.java000066400000000000000000000112411463574317400232030ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-present, by David Gilbert. All rights reserved. * * Project Info: http://www.jfree.org/jfreesvg/index.html * * 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 . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * JFreeSVG home page: * * http://www.jfree.org/jfreesvg * */ package org.jfree.svg.util; /** * A utility class that performs checks for method argument validity. */ public class Args { private Args() { // no need to instantiate this } /** * Checks that an argument is non-{@code null} and throws an * {@code IllegalArgumentException} otherwise. * * @param obj the object to check for {@code null}. * @param ref the text name for the parameter (to include in the exception * message). */ public static void nullNotPermitted(Object obj, String ref) { if (obj == null) { throw new IllegalArgumentException("Null '" + ref + "' argument."); } } /** * Checks that the value falls within the specified range and, if it does * not, throws an {@code IllegalArgumentException}. * * @param value the value. * @param name the parameter name. * @param lowerBound the lower bound of the permitted range. * @param upperBound the upper bound fo the permitted range. */ public static void requireInRange(int value, String name, int lowerBound, int upperBound) { if (value < lowerBound || value > upperBound) { throw new IllegalArgumentException("Require '" + name + "' (" + value + ") to be in the range " + lowerBound + " to " + upperBound); } } /** * Checks that an argument is a finite positive value and throws an * {@code IllegalArgumentException} otherwise. * * @param d the value to check. * @param ref the text name for the parameter (to include in the exception * message). */ public static void requireFinitePositive(double d, String ref) { if (d <= 0.0) { throw new IllegalArgumentException("Require positive value for '" + ref + "' argument."); } if (!Double.isFinite(d)) { throw new IllegalArgumentException("Require finite value for '" + ref + "' argument."); } } /** * Checks an array to ensure it has the correct length and throws an * {@code IllegalArgumentException} if it does not. * * @param length the required length. * @param array the array to check. * @param ref the text name of the array parameter (to include in the * exception message). */ public static void arrayMustHaveLength(int length, boolean[] array, String ref) { nullNotPermitted(array, "array"); if (array.length != length) { throw new IllegalArgumentException("Array '" + ref + "' requires length " + length); } } /** * Checks an array to ensure it has the correct length and throws an * {@code IllegalArgumentException} if it does not. * * @param length the required length. * @param array the array to check ({@code null} not permitted). * @param ref the text name of the array parameter (to include in the * exception message). */ public static void arrayMustHaveLength(int length, double[] array, String ref) { nullNotPermitted(array, "array"); if (array.length != length) { throw new IllegalArgumentException("Array '" + ref + "' requires length " + length); } } } jfreesvg-5.0.6/src/main/java/org/jfree/svg/util/DoubleConverter.java000066400000000000000000000047041463574317400254170ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-present, by David Gilbert. All rights reserved. * * Project Info: http://www.jfree.org/jfreesvg/index.html * * 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 . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * JFreeSVG home page: * * http://www.jfree.org/jfreesvg */ package org.jfree.svg.util; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; import java.util.function.DoubleFunction; /** * A function that converts double values to a string representation with * a maximum number of decimal places. */ public class DoubleConverter implements DoubleFunction { private final DecimalFormat formatter; /** * Creates a new function that converts double values to strings with * the maximum number of decimal places as specified. * * @param dp the max decimal places (in the range 1 to 10). */ public DoubleConverter(int dp) { Args.requireInRange(dp, "dp", 1, 10); DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(Locale.US); this.formatter = new DecimalFormat("0." + "##########".substring(0, dp), dfs); } /** * Returns a string representation of the specified value. * * @param value the value. * * @return A string representation of the specified value. */ @Override public String apply(double value) { return this.formatter.format(value); } } jfreesvg-5.0.6/src/main/java/org/jfree/svg/util/GradientPaintKey.java000066400000000000000000000076211463574317400255200ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-present, by David Gilbert. All rights reserved. * * Project Info: http://www.jfree.org/jfreesvg/index.html * * 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 . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * JFreeSVG home page: * * http://www.jfree.org/jfreesvg * */ package org.jfree.svg.util; import java.awt.GradientPaint; /** * A wrapper for a {@code GradientPaint} that can be used as the key for * a {@code Map} (including a {@code HashMap}). This class is used * internally by {@code SVGGraphics2D} to track and re-use gradient * definitions. {@code GradientPaint} itself does not implement the * equals() and hashCode() methods, so it doesn't make a good key for a * {@code Map}. */ public final class GradientPaintKey { private final GradientPaint paint; /** * Creates a new instance based on the specified {@code paint}. * * @param paint the paint ({@code null} not permitted). */ public GradientPaintKey(GradientPaint paint) { Args.nullNotPermitted(paint, "paint"); this.paint = paint; } /** * Returns the {@code GradientPaint} that was supplied to the * constructor. * * @return The {@code GradientPaint} (never {@code null}). */ public GradientPaint getPaint() { return this.paint; } /** * Checks this instance for equality with an arbitrary object. * * @param obj the object to test against ({@code null} permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof GradientPaintKey)) { return false; } GradientPaintKey that = (GradientPaintKey) obj; GradientPaint thisGP = this.paint; GradientPaint thatGP = that.getPaint(); if (!thisGP.getColor1().equals(thatGP.getColor1())) { return false; } if (!thisGP.getColor2().equals(thatGP.getColor2())) { return false; } if (!thisGP.getPoint1().equals(thatGP.getPoint1())) { return false; } if (!thisGP.getPoint2().equals(thatGP.getPoint2())) { return false; } if (thisGP.getTransparency() != thatGP.getTransparency()) { return false; } if (thisGP.isCyclic() != thatGP.isCyclic()) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.paint.getPoint1().hashCode(); hash = 47 * hash + this.paint.getPoint2().hashCode(); hash = 47 * hash + this.paint.getColor1().hashCode(); hash = 47 * hash + this.paint.getColor2().hashCode(); return hash; } } jfreesvg-5.0.6/src/main/java/org/jfree/svg/util/GraphicsUtils.java000066400000000000000000000135761463574317400251050ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-present, by David Gilbert. All rights reserved. * * Project Info: http://www.jfree.org/jfreesvg/index.html * * 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 . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * JFreeSVG home page: * * http://www.jfree.org/jfreesvg * */ package org.jfree.svg.util; import java.awt.Polygon; import java.awt.Shape; import java.awt.geom.Arc2D; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Path2D; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.RenderedImage; import java.awt.image.WritableRaster; import java.util.Hashtable; /** * A collection of static utility methods for shapes and images. */ public final class GraphicsUtils { private GraphicsUtils() { // no need to instantiate this } /** * Returns a shape that is (more or less) equivalent to the supplied shape. * For some known shape implementations ({@code Line2D}, * {@code Rectangle2D}, {@code RoundRectangle2D}, {@code Arc2D}, * {@code Ellipse2D}, and {@code Polygon}) the copy will be an instance of * that class. For other shapes, a {@code Path2D} containing the outline * of the shape is returned. * * @param shape the shape ({@code null} not permitted). * * @return A copy of the shape or shape outline (never {@code null}). */ public static Shape copyOf(Shape shape) { Args.nullNotPermitted(shape, "shape"); if (shape instanceof Line2D) { Line2D l = (Line2D) shape; return new Line2D.Double(l.getX1(), l.getY1(), l.getX2(), l.getY2()); } if (shape instanceof Rectangle2D) { Rectangle2D r = (Rectangle2D) shape; return new Rectangle2D.Double(r.getX(), r.getY(), r.getWidth(), r.getHeight()); } if (shape instanceof RoundRectangle2D) { RoundRectangle2D rr = (RoundRectangle2D) shape; return new RoundRectangle2D.Double(rr.getX(), rr.getY(), rr.getWidth(), rr.getHeight(), rr.getArcWidth(), rr.getArcHeight()); } if (shape instanceof Arc2D) { Arc2D arc = (Arc2D) shape; return new Arc2D.Double(arc.getX(), arc.getY(), arc.getWidth(), arc.getHeight(), arc.getAngleStart(), arc.getAngleExtent(), arc.getArcType()); } if (shape instanceof Ellipse2D) { Ellipse2D ell = (Ellipse2D) shape; return new Ellipse2D.Double(ell.getX(), ell.getY(), ell.getWidth(), ell.getHeight()); } if (shape instanceof Polygon) { Polygon p = (Polygon) shape; return new Polygon(p.xpoints, p.ypoints, p.npoints); } return new Path2D.Double(shape); } /** * Creates a polygon from the specified {@code x} and {@code y} coordinate * arrays. * * @param xPoints the x-points. * @param yPoints the y-points. * @param nPoints the number of points to use for the polyline. * @param close closed? * * @return A polygon. */ public static GeneralPath createPolygon(int[] xPoints, int[] yPoints, int nPoints, boolean close) { GeneralPath p = new GeneralPath(); p.moveTo(xPoints[0], yPoints[0]); for (int i = 1; i < nPoints; i++) { p.lineTo(xPoints[i], yPoints[i]); } if (close) { p.closePath(); } return p; } /** * Converts a rendered image to a {@code BufferedImage}. This utility * method has come from a forum post by Jim Moore at: *

* * http://www.jguru.com/faq/view.jsp?EID=114602 * * @param img the rendered image ({@code null} not permitted). * * @return A buffered image. */ public static BufferedImage convertRenderedImage(RenderedImage img) { Args.nullNotPermitted(img, "img"); if (img instanceof BufferedImage) { return (BufferedImage) img; } ColorModel cm = img.getColorModel(); int width = img.getWidth(); int height = img.getHeight(); WritableRaster raster = cm.createCompatibleWritableRaster(width, height); boolean isAlphaPremultiplied = cm.isAlphaPremultiplied(); Hashtable properties = new Hashtable(); String[] keys = img.getPropertyNames(); if (keys != null) { for (String key : keys) { properties.put(key, img.getProperty(key)); } } BufferedImage result = new BufferedImage(cm, raster, isAlphaPremultiplied, properties); img.copyData(raster); return result; } } jfreesvg-5.0.6/src/main/java/org/jfree/svg/util/LinearGradientPaintKey.java000066400000000000000000000074271463574317400266570ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-present, by David Gilbert. All rights reserved. * * Project Info: http://www.jfree.org/jfreesvg/index.html * * 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 . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * JFreeSVG home page: * * http://www.jfree.org/jfreesvg * */ package org.jfree.svg.util; import java.awt.LinearGradientPaint; import java.util.Arrays; /** * A wrapper for a {@code LinearGradientPaint} that can be used as the key * for a {@code Map} (including a {@code HashMap}). This class is * used internally by {@code SVGGraphics2D} to track and re-use gradient * definitions. {@code LinearGradientPaint} itself does not implement the * {@code equals()} and {@code hashCode()} methods, so it doesn't make a good * key for a {@code Map}. * * @since 1.9 */ public class LinearGradientPaintKey { private final LinearGradientPaint paint; /** * Creates a new instance. * * @param lgp the linear gradient paint ({@code null} not permitted). */ public LinearGradientPaintKey(LinearGradientPaint lgp) { Args.nullNotPermitted(lgp, "lgp"); this.paint = lgp; } /** * Returns the {@code LinearGradientPaint} that was supplied to the * constructor. * * @return The {@code LinearGradientPaint} (never {@code null}). */ public LinearGradientPaint getPaint() { return this.paint; } /** * Tests this instance for equality with an arbitrary object. * * @param obj the object to test ({@code null} permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (! (obj instanceof LinearGradientPaintKey)) { return false; } LinearGradientPaint that = ((LinearGradientPaintKey) obj).paint; if (!this.paint.getStartPoint().equals(that.getStartPoint())) { return false; } if (!this.paint.getEndPoint().equals(that.getEndPoint())) { return false; } if (!Arrays.equals(this.paint.getColors(), that.getColors())) { return false; } if (!Arrays.equals(this.paint.getFractions(), that.getFractions())) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.paint.getStartPoint().hashCode(); hash = 47 * hash + this.paint.getEndPoint().hashCode(); hash = 47 * hash + Arrays.hashCode(this.paint.getColors()); hash = 47 * hash + Arrays.hashCode(this.paint.getFractions()); return hash; } } jfreesvg-5.0.6/src/main/java/org/jfree/svg/util/RadialGradientPaintKey.java000066400000000000000000000075211463574317400266340ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-present, by David Gilbert. All rights reserved. * * Project Info: http://www.jfree.org/jfreesvg/index.html * * 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 . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * JFreeSVG home page: * * http://www.jfree.org/jfreesvg * */ package org.jfree.svg.util; import java.awt.RadialGradientPaint; import java.util.Arrays; /** * A wrapper for a {@code RadialGradientPaint} that can be used as the key * for a {@code Map} (including a {@code HashMap}). This class is * used internally by {@code SVGGraphics2D} to track and re-use gradient * definitions. {@code GradientPaint} itself does not implement the * {@code equals()} and {@code hashCode()} methods, so it doesn't make a good * key for a {@code Map}. */ public class RadialGradientPaintKey { private final RadialGradientPaint paint; /** * Creates a new instance. * * @param rgp the radial gradient paint ({@code null} not permitted). */ public RadialGradientPaintKey(RadialGradientPaint rgp) { Args.nullNotPermitted(rgp, "rgp"); this.paint = rgp; } /** * Returns the {@code RadialGradientPaint} that was supplied to the * constructor. * * @return The {@code RadialGradientPaint} (never {@code null}). */ public RadialGradientPaint getPaint() { return this.paint; } /** * Tests this instance for equality with an arbitrary object. * * @param obj the object to test ({@code null} permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (! (obj instanceof RadialGradientPaintKey)) { return false; } RadialGradientPaint that = ((RadialGradientPaintKey) obj).paint; if (!this.paint.getCenterPoint().equals(that.getCenterPoint())) { return false; } if (!this.paint.getFocusPoint().equals(that.getCenterPoint())) { return false; } if (!Arrays.equals(this.paint.getColors(), that.getColors())) { return false; } if (!Arrays.equals(this.paint.getFractions(), that.getFractions())) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.paint.getCenterPoint().hashCode(); hash = 47 * hash + this.paint.getFocusPoint().hashCode(); hash = 47 * hash + Float.floatToIntBits(this.paint.getRadius()); hash = 47 * hash + Arrays.hashCode(this.paint.getColors()); hash = 47 * hash + Arrays.hashCode(this.paint.getFractions()); return hash; } } jfreesvg-5.0.6/src/main/java/org/jfree/svg/util/RoundingMode.java000066400000000000000000000022231463574317400247010ustar00rootroot00000000000000// Copyright 2018 Ulf Adams // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.jfree.svg.util; public enum RoundingMode { CONSERVATIVE { @Override public boolean acceptUpperBound(boolean even) { return false; } @Override public boolean acceptLowerBound(boolean even) { return false; } }, ROUND_EVEN { @Override public boolean acceptUpperBound(boolean even) { return even; } @Override public boolean acceptLowerBound(boolean even) { return even; } }; public abstract boolean acceptUpperBound(boolean even); public abstract boolean acceptLowerBound(boolean even); }jfreesvg-5.0.6/src/main/java/org/jfree/svg/util/RyuDouble.java000066400000000000000000000421451463574317400242300ustar00rootroot00000000000000// Copyright 2018 Ulf Adams // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.jfree.svg.util; import java.math.BigInteger; /** * An implementation of Ryu for double. */ public final class RyuDouble { private static boolean DEBUG = false; private static final int DOUBLE_MANTISSA_BITS = 52; private static final long DOUBLE_MANTISSA_MASK = (1L << DOUBLE_MANTISSA_BITS) - 1; private static final int DOUBLE_EXPONENT_BITS = 11; private static final int DOUBLE_EXPONENT_MASK = (1 << DOUBLE_EXPONENT_BITS) - 1; private static final int DOUBLE_EXPONENT_BIAS = (1 << (DOUBLE_EXPONENT_BITS - 1)) - 1; private static final int POS_TABLE_SIZE = 326; private static final int NEG_TABLE_SIZE = 291; // Only for debugging. private static final BigInteger[] POW5 = new BigInteger[POS_TABLE_SIZE]; private static final BigInteger[] POW5_INV = new BigInteger[NEG_TABLE_SIZE]; private static final int POW5_BITCOUNT = 121; // max 3*31 = 124 private static final int POW5_QUARTER_BITCOUNT = 31; private static final int[][] POW5_SPLIT = new int[POS_TABLE_SIZE][4]; private static final int POW5_INV_BITCOUNT = 122; // max 3*31 = 124 private static final int POW5_INV_QUARTER_BITCOUNT = 31; private static final int[][] POW5_INV_SPLIT = new int[NEG_TABLE_SIZE][4]; static { BigInteger mask = BigInteger.valueOf(1).shiftLeft(POW5_QUARTER_BITCOUNT).subtract(BigInteger.ONE); BigInteger invMask = BigInteger.valueOf(1).shiftLeft(POW5_INV_QUARTER_BITCOUNT).subtract(BigInteger.ONE); for (int i = 0; i < Math.max(POW5.length, POW5_INV.length); i++) { BigInteger pow = BigInteger.valueOf(5).pow(i); int pow5len = pow.bitLength(); int expectedPow5Bits = pow5bits(i); if (expectedPow5Bits != pow5len) { throw new IllegalStateException(pow5len + " != " + expectedPow5Bits); } if (i < POW5.length) { POW5[i] = pow; } if (i < POW5_SPLIT.length) { for (int j = 0; j < 4; j++) { POW5_SPLIT[i][j] = pow .shiftRight(pow5len - POW5_BITCOUNT + (3 - j) * POW5_QUARTER_BITCOUNT) .and(mask) .intValueExact(); } } if (i < POW5_INV_SPLIT.length) { // We want floor(log_2 5^q) here, which is pow5len - 1. int j = pow5len - 1 + POW5_INV_BITCOUNT; BigInteger inv = BigInteger.ONE.shiftLeft(j).divide(pow).add(BigInteger.ONE); POW5_INV[i] = inv; for (int k = 0; k < 4; k++) { if (k == 0) { POW5_INV_SPLIT[i][k] = inv.shiftRight((3 - k) * POW5_INV_QUARTER_BITCOUNT).intValueExact(); } else { POW5_INV_SPLIT[i][k] = inv.shiftRight((3 - k) * POW5_INV_QUARTER_BITCOUNT).and(invMask).intValueExact(); } } } } } public static String doubleToString(double value) { return doubleToString(value, RoundingMode.ROUND_EVEN); } public static String doubleToString(double value, RoundingMode roundingMode) { // Step 1: Decode the floating point number, and unify normalized and subnormal cases. // First, handle all the trivial cases. if (Double.isNaN(value)) return "NaN"; if (value == Double.POSITIVE_INFINITY) return "Infinity"; if (value == Double.NEGATIVE_INFINITY) return "-Infinity"; long bits = Double.doubleToLongBits(value); if (bits == 0) return "0.0"; if (bits == 0x8000000000000000L) return "-0.0"; // Otherwise extract the mantissa and exponent bits and run the full algorithm. int ieeeExponent = (int) ((bits >>> DOUBLE_MANTISSA_BITS) & DOUBLE_EXPONENT_MASK); long ieeeMantissa = bits & DOUBLE_MANTISSA_MASK; int e2; long m2; if (ieeeExponent == 0) { // Denormal number - no implicit leading 1, and the exponent is 1, not 0. e2 = 1 - DOUBLE_EXPONENT_BIAS - DOUBLE_MANTISSA_BITS; m2 = ieeeMantissa; } else { // Add implicit leading 1. e2 = ieeeExponent - DOUBLE_EXPONENT_BIAS - DOUBLE_MANTISSA_BITS; m2 = ieeeMantissa | (1L << DOUBLE_MANTISSA_BITS); } boolean sign = bits < 0; if (DEBUG) { System.out.println("IN=" + Long.toBinaryString(bits)); System.out.println(" S=" + (sign ? "-" : "+") + " E=" + e2 + " M=" + m2); } // Step 2: Determine the interval of legal decimal representations. boolean even = (m2 & 1) == 0; final long mv = 4 * m2; final long mp = 4 * m2 + 2; final int mmShift = ((m2 != (1L << DOUBLE_MANTISSA_BITS)) || (ieeeExponent <= 1)) ? 1 : 0; final long mm = 4 * m2 - 1 - mmShift; e2 -= 2; if (DEBUG) { String sv, sp, sm; int e10; if (e2 >= 0) { sv = BigInteger.valueOf(mv).shiftLeft(e2).toString(); sp = BigInteger.valueOf(mp).shiftLeft(e2).toString(); sm = BigInteger.valueOf(mm).shiftLeft(e2).toString(); e10 = 0; } else { BigInteger factor = BigInteger.valueOf(5).pow(-e2); sv = BigInteger.valueOf(mv).multiply(factor).toString(); sp = BigInteger.valueOf(mp).multiply(factor).toString(); sm = BigInteger.valueOf(mm).multiply(factor).toString(); e10 = e2; } e10 += sp.length() - 1; System.out.println("E =" + e10); System.out.println("d+=" + sp); System.out.println("d =" + sv); System.out.println("d-=" + sm); System.out.println("e2=" + e2); } // Step 3: Convert to a decimal power base using 128-bit arithmetic. // -1077 = 1 - 1023 - 53 - 2 <= e_2 - 2 <= 2046 - 1023 - 53 - 2 = 968 long dv, dp, dm; final int e10; boolean dmIsTrailingZeros = false, dvIsTrailingZeros = false; if (e2 >= 0) { final int q = Math.max(0, ((e2 * 78913) >>> 18) - 1); // k = constant + floor(log_2(5^q)) final int k = POW5_INV_BITCOUNT + pow5bits(q) - 1; final int i = -e2 + q + k; dv = mulPow5InvDivPow2(mv, q, i); dp = mulPow5InvDivPow2(mp, q, i); dm = mulPow5InvDivPow2(mm, q, i); e10 = q; if (DEBUG) { System.out.println(mv + " * 2^" + e2); System.out.println("V+=" + dp); System.out.println("V =" + dv); System.out.println("V-=" + dm); } if (DEBUG) { long exact = POW5_INV[q] .multiply(BigInteger.valueOf(mv)) .shiftRight(-e2 + q + k).longValueExact(); System.out.println(exact + " " + POW5_INV[q].bitCount()); if (dv != exact) { throw new IllegalStateException(); } } if (q <= 21) { if (mv % 5 == 0) { dvIsTrailingZeros = multipleOfPowerOf5(mv, q); } else if (roundingMode.acceptUpperBound(even)) { dmIsTrailingZeros = multipleOfPowerOf5(mm, q); } else if (multipleOfPowerOf5(mp, q)) { dp--; } } } else { final int q = Math.max(0, ((-e2 * 732923) >>> 20) - 1); final int i = -e2 - q; final int k = pow5bits(i) - POW5_BITCOUNT; final int j = q - k; dv = mulPow5divPow2(mv, i, j); dp = mulPow5divPow2(mp, i, j); dm = mulPow5divPow2(mm, i, j); e10 = q + e2; if (DEBUG) { System.out.println(mv + " * 5^" + (-e2) + " / 10^" + q); } if (q <= 1) { dvIsTrailingZeros = true; if (roundingMode.acceptUpperBound(even)) { dmIsTrailingZeros = mmShift == 1; } else { dp--; } } else if (q < 63) { dvIsTrailingZeros = (mv & ((1L << (q - 1)) - 1)) == 0; } } if (DEBUG) { System.out.println("d+=" + dp); System.out.println("d =" + dv); System.out.println("d-=" + dm); System.out.println("e10=" + e10); System.out.println("d-10=" + dmIsTrailingZeros); System.out.println("d =" + dvIsTrailingZeros); System.out.println("Accept upper=" + roundingMode.acceptUpperBound(even)); System.out.println("Accept lower=" + roundingMode.acceptLowerBound(even)); } // Step 4: Find the shortest decimal representation in the interval of legal representations. // // We do some extra work here in order to follow Float/Double.toString semantics. In particular, // that requires printing in scientific format if and only if the exponent is between -3 and 7, // and it requires printing at least two decimal digits. // // Above, we moved the decimal dot all the way to the right, so now we need to count digits to // figure out the correct exponent for scientific notation. final int vplength = decimalLength(dp); int exp = e10 + vplength - 1; // Double.toString semantics requires using scientific notation if and only if outside this range. boolean scientificNotation = !((exp >= -3) && (exp < 7)); int removed = 0; int lastRemovedDigit = 0; long output; if (dmIsTrailingZeros || dvIsTrailingZeros) { while (dp / 10 > dm / 10) { if ((dp < 100) && scientificNotation) { // Double.toString semantics requires printing at least two digits. break; } dmIsTrailingZeros &= dm % 10 == 0; dvIsTrailingZeros &= lastRemovedDigit == 0; lastRemovedDigit = (int) (dv % 10); dp /= 10; dv /= 10; dm /= 10; removed++; } if (dmIsTrailingZeros && roundingMode.acceptLowerBound(even)) { while (dm % 10 == 0) { if ((dp < 100) && scientificNotation) { // Double.toString semantics requires printing at least two digits. break; } dvIsTrailingZeros &= lastRemovedDigit == 0; lastRemovedDigit = (int) (dv % 10); dp /= 10; dv /= 10; dm /= 10; removed++; } } if (dvIsTrailingZeros && (lastRemovedDigit == 5) && (dv % 2 == 0)) { // Round even if the exact numbers is .....50..0. lastRemovedDigit = 4; } output = dv + ((dv == dm && !(dmIsTrailingZeros && roundingMode.acceptLowerBound(even))) || (lastRemovedDigit >= 5) ? 1 : 0); } else { while (dp / 10 > dm / 10) { if ((dp < 100) && scientificNotation) { // Double.toString semantics requires printing at least two digits. break; } lastRemovedDigit = (int) (dv % 10); dp /= 10; dv /= 10; dm /= 10; removed++; } output = dv + ((dv == dm || (lastRemovedDigit >= 5)) ? 1 : 0); } int olength = vplength - removed; if (DEBUG) { System.out.println("LAST_REMOVED_DIGIT=" + lastRemovedDigit); System.out.println("VP=" + dp); System.out.println("VR=" + dv); System.out.println("VM=" + dm); System.out.println("O=" + output); System.out.println("OLEN=" + olength); System.out.println("EXP=" + exp); } // Step 5: Print the decimal representation. // We follow Double.toString semantics here. char[] result = new char[24]; int index = 0; if (sign) { result[index++] = '-'; } // Values in the interval [1E-3, 1E7) are special. if (scientificNotation) { // Print in the format x.xxxxxE-yy. for (int i = 0; i < olength - 1; i++) { int c = (int) (output % 10); output /= 10; result[index + olength - i] = (char) ('0' + c); } result[index] = (char) ('0' + output % 10); result[index + 1] = '.'; index += olength + 1; if (olength == 1) { result[index++] = '0'; } // Print 'E', the exponent sign, and the exponent, which has at most three digits. result[index++] = 'E'; if (exp < 0) { result[index++] = '-'; exp = -exp; } if (exp >= 100) { result[index++] = (char) ('0' + exp / 100); exp %= 100; result[index++] = (char) ('0' + exp / 10); } else if (exp >= 10) { result[index++] = (char) ('0' + exp / 10); } result[index++] = (char) ('0' + exp % 10); return new String(result, 0, index); } else { // Otherwise follow the Java spec for values in the interval [1E-3, 1E7). if (exp < 0) { // Decimal dot is before any of the digits. result[index++] = '0'; result[index++] = '.'; for (int i = -1; i > exp; i--) { result[index++] = '0'; } int current = index; for (int i = 0; i < olength; i++) { result[current + olength - i - 1] = (char) ('0' + output % 10); output /= 10; index++; } } else if (exp + 1 >= olength) { // Decimal dot is after any of the digits. for (int i = 0; i < olength; i++) { result[index + olength - i - 1] = (char) ('0' + output % 10); output /= 10; } index += olength; for (int i = olength; i < exp + 1; i++) { result[index++] = '0'; } result[index++] = '.'; result[index++] = '0'; } else { // Decimal dot is somewhere between the digits. int current = index + 1; for (int i = 0; i < olength; i++) { if (olength - i - 1 == exp) { result[current + olength - i - 1] = '.'; current--; } result[current + olength - i - 1] = (char) ('0' + output % 10); output /= 10; } index += olength + 1; } return new String(result, 0, index); } } private static int pow5bits(int e) { return ((e * 1217359) >>> 19) + 1; } private static int decimalLength(long v) { if (v >= 1000000000000000000L) return 19; if (v >= 100000000000000000L) return 18; if (v >= 10000000000000000L) return 17; if (v >= 1000000000000000L) return 16; if (v >= 100000000000000L) return 15; if (v >= 10000000000000L) return 14; if (v >= 1000000000000L) return 13; if (v >= 100000000000L) return 12; if (v >= 10000000000L) return 11; if (v >= 1000000000L) return 10; if (v >= 100000000L) return 9; if (v >= 10000000L) return 8; if (v >= 1000000L) return 7; if (v >= 100000L) return 6; if (v >= 10000L) return 5; if (v >= 1000L) return 4; if (v >= 100L) return 3; if (v >= 10L) return 2; return 1; } private static boolean multipleOfPowerOf5(long value, int q) { return pow5Factor(value) >= q; } private static int pow5Factor(long value) { // We want to find the largest power of 5 that divides value. if ((value % 5) != 0) return 0; if ((value % 25) != 0) return 1; if ((value % 125) != 0) return 2; if ((value % 625) != 0) return 3; int count = 4; value /= 625; while (value > 0) { if (value % 5 != 0) { return count; } value /= 5; count++; } throw new IllegalArgumentException("" + value); } /** * Compute the high digits of m * 5^p / 10^q = m * 5^(p - q) / 2^q = m * 5^i / 2^j, with q chosen * such that m * 5^i / 2^j has sufficiently many decimal digits to represent the original floating * point number. */ private static long mulPow5divPow2(long m, int i, int j) { // m has at most 55 bits. long mHigh = m >>> 31; long mLow = m & 0x7fffffff; long bits13 = mHigh * POW5_SPLIT[i][0]; // 124 long bits03 = mLow * POW5_SPLIT[i][0]; // 93 long bits12 = mHigh * POW5_SPLIT[i][1]; // 93 long bits02 = mLow * POW5_SPLIT[i][1]; // 62 long bits11 = mHigh * POW5_SPLIT[i][2]; // 62 long bits01 = mLow * POW5_SPLIT[i][2]; // 31 long bits10 = mHigh * POW5_SPLIT[i][3]; // 31 long bits00 = mLow * POW5_SPLIT[i][3]; // 0 int actualShift = j - 3 * 31 - 21; if (actualShift < 0) { throw new IllegalArgumentException("" + actualShift); } return (((((( ((bits00 >>> 31) + bits01 + bits10) >>> 31) + bits02 + bits11) >>> 31) + bits03 + bits12) >>> 21) + (bits13 << 10)) >>> actualShift; } /** * Compute the high digits of m / 5^i / 2^j such that the result is accurate to at least 9 * decimal digits. i and j are already chosen appropriately. */ private static long mulPow5InvDivPow2(long m, int i, int j) { // m has at most 55 bits. long mHigh = m >>> 31; long mLow = m & 0x7fffffff; long bits13 = mHigh * POW5_INV_SPLIT[i][0]; long bits03 = mLow * POW5_INV_SPLIT[i][0]; long bits12 = mHigh * POW5_INV_SPLIT[i][1]; long bits02 = mLow * POW5_INV_SPLIT[i][1]; long bits11 = mHigh * POW5_INV_SPLIT[i][2]; long bits01 = mLow * POW5_INV_SPLIT[i][2]; long bits10 = mHigh * POW5_INV_SPLIT[i][3]; long bits00 = mLow * POW5_INV_SPLIT[i][3]; int actualShift = j - 3 * 31 - 21; if (actualShift < 0) { throw new IllegalArgumentException("" + actualShift); } return (((((( ((bits00 >>> 31) + bits01 + bits10) >>> 31) + bits02 + bits11) >>> 31) + bits03 + bits12) >>> 21) + (bits13 << 10)) >>> actualShift; } }jfreesvg-5.0.6/src/main/java/org/jfree/svg/util/package-info.java000066400000000000000000000002341463574317400246330ustar00rootroot00000000000000/** * An internal package for the JFreeSVG library. This package * contains utility and other supporting classes. */ package org.jfree.svg.util;jfreesvg-5.0.6/src/main/javadoc/000077500000000000000000000000001463574317400164755ustar00rootroot00000000000000jfreesvg-5.0.6/src/main/javadoc/doc-files/000077500000000000000000000000001463574317400203425ustar00rootroot00000000000000jfreesvg-5.0.6/src/main/javadoc/doc-files/FlowPlotDemo2.svg000066400000000000000000000440461463574317400235300ustar00rootroot00000000000000 Selected NZ Exports Sept 2020Source: https://statisticsnz.shinyapps.io/trade_dashboard/BeveragesUSADairyTravelMeatServicesOther GoodsUnited KingdomWoodChinaAustraliaFruit & NutsGoods jfreesvg-5.0.6/src/test/000077500000000000000000000000001463574317400151215ustar00rootroot00000000000000jfreesvg-5.0.6/src/test/java/000077500000000000000000000000001463574317400160425ustar00rootroot00000000000000jfreesvg-5.0.6/src/test/java/org/000077500000000000000000000000001463574317400166315ustar00rootroot00000000000000jfreesvg-5.0.6/src/test/java/org/jfree/000077500000000000000000000000001463574317400177245ustar00rootroot00000000000000jfreesvg-5.0.6/src/test/java/org/jfree/svg/000077500000000000000000000000001463574317400205235ustar00rootroot00000000000000jfreesvg-5.0.6/src/test/java/org/jfree/svg/TestDoubleConversion.java000066400000000000000000000173361463574317400255200ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-present, by David Gilbert. All rights reserved. * * Project Info: http://www.jfree.org/jfreesvg/index.html * * 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 . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * JFreeSVG home page: * * http://www.jfree.org/jfreesvg * */ package org.jfree.svg; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Locale; import org.junit.jupiter.api.Test; import java.util.function.DoubleFunction; /** * A range of tests to sanity check the double to string conversions performed * by JFreeSVG. */ public class TestDoubleConversion { /** Default conversion in Java standard library. */ private final DoubleFunction d2s = Double::toString; /** Fast 'Ryu' algorithm. */ private final DoubleFunction ryu = SVGUtils::doubleToString; /** Uses DecimalFormat to limit output to max 2dp. */ private final DoubleFunction dp2 = SVGUtils.createDoubleConverter(2); /** Uses DecimalFormat to limit output to max 6dp. */ private final DoubleFunction dp6 = SVGUtils.createDoubleConverter(6); @Test public void testGeneral() { double value = 1; assertEquals("1.0", d2s.apply(value)); assertEquals("1.0", ryu.apply(value)); assertEquals("1", dp2.apply(value)); assertEquals("1", dp6.apply(value)); value = -1; assertEquals("-1.0", d2s.apply(value)); assertEquals("-1.0", ryu.apply(value)); assertEquals("-1", dp2.apply(value)); assertEquals("-1", dp6.apply(value)); value = 1234.5678912345; assertEquals("1234.5678912345", d2s.apply(value)); assertEquals("1234.5678912345", ryu.apply(value)); assertEquals("1234.57", dp2.apply(value)); assertEquals("1234.567891", dp6.apply(value)); value = -1234.5678912345; assertEquals("-1234.5678912345", d2s.apply(value)); assertEquals("-1234.5678912345", ryu.apply(value)); assertEquals("-1234.57", dp2.apply(value)); assertEquals("-1234.567891", dp6.apply(value)); value = 1500; assertEquals("1500.0", d2s.apply(value)); assertEquals("1500.0", ryu.apply(value)); assertEquals("1500", dp2.apply(value)); assertEquals("1500", dp6.apply(value)); value = -1500; assertEquals("-1500.0", d2s.apply(value)); assertEquals("-1500.0", ryu.apply(value)); assertEquals("-1500", dp2.apply(value)); assertEquals("-1500", dp6.apply(value)); } @Test public void testNaN() { double value = Double.NaN; assertEquals("NaN", d2s.apply(value)); assertEquals("NaN", ryu.apply(value)); assertEquals("NaN", dp2.apply(value)); assertEquals("NaN", dp6.apply(value)); } @Test public void testPositiveInfinity() { double value = Double.POSITIVE_INFINITY; assertEquals("Infinity", d2s.apply(value)); assertEquals("Infinity", ryu.apply(value)); assertEquals("∞", dp2.apply(value)); assertEquals("∞", dp6.apply(value)); } @Test public void testNegativeInfinity() { double value = Double.NEGATIVE_INFINITY; assertEquals("-Infinity", d2s.apply(value)); assertEquals("-Infinity", ryu.apply(value)); assertEquals("-∞", dp2.apply(value)); assertEquals("-∞", dp6.apply(value)); } @Test public void testMaxValue() { double value = Double.MAX_VALUE; assertEquals("1.7976931348623157E308", d2s.apply(value)); assertEquals("1.7976931348623157E308", ryu.apply(value)); assertEquals("179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", dp2.apply(value)); assertEquals("179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", dp6.apply(value)); } @Test public void testMinValue() { double value = Double.MIN_VALUE; assertEquals("4.9E-324", d2s.apply(value)); assertEquals("4.9E-324", ryu.apply(value)); assertEquals("0", dp2.apply(value)); assertEquals("0", dp6.apply(value)); } @Test public void testDP() { double value = 0.1234567898765; assertEquals("0.1234567898765", d2s.apply(value)); assertEquals("0.1234567898765", ryu.apply(value)); assertEquals("0.12", dp2.apply(value)); assertEquals("0.123457", dp6.apply(value)); value = -0.1234567898765; assertEquals("-0.1234567898765", d2s.apply(value)); assertEquals("-0.1234567898765", ryu.apply(value)); assertEquals("-0.12", dp2.apply(value)); assertEquals("-0.123457", dp6.apply(value)); } @Test public void test10DP() { DoubleFunction dp10 = SVGUtils.createDoubleConverter(10); double value = 0.1234567898765; assertEquals("0.1234567899", dp10.apply(value)); value = -0.1234567898765; assertEquals("-0.1234567899", dp10.apply(value)); } /** * The goal of this test is to check that the formatting is not impacted * by the locale. */ @Test public void testLocale() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.FRANCE); DoubleFunction df4 = SVGUtils.createDoubleConverter(4); DoubleFunction df6 = SVGUtils.createDoubleConverter(6); double value = 1; assertEquals("1.0", d2s.apply(value)); assertEquals("1.0", ryu.apply(value)); assertEquals("1", df4.apply(value)); assertEquals("1", df6.apply(value)); value = -1; assertEquals("-1.0", d2s.apply(value)); assertEquals("-1.0", ryu.apply(value)); assertEquals("-1", df4.apply(value)); assertEquals("-1", df6.apply(value)); value = 1500; assertEquals("1500.0", d2s.apply(value)); assertEquals("1500.0", ryu.apply(value)); assertEquals("1500", df4.apply(value)); assertEquals("1500", df6.apply(value)); value = -1500; assertEquals("-1500.0", d2s.apply(value)); assertEquals("-1500.0", ryu.apply(value)); assertEquals("-1500", df4.apply(value)); assertEquals("-1500", df6.apply(value)); Locale.setDefault(saved); } } jfreesvg-5.0.6/src/test/java/org/jfree/svg/TestGeneral.java000066400000000000000000001063401463574317400236070ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-present, by David Gilbert. All rights reserved. * * Project Info: http://www.jfree.org/jfreesvg/index.html * * 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 . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * JFreeSVG home page: * * http://www.jfree.org/jfreesvg * */ package org.jfree.svg; import java.awt.*; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import java.awt.geom.*; import java.awt.image.BufferedImage; import org.junit.jupiter.api.Test; /** * Some general tests that check the SVG output generated. */ public class TestGeneral { /** * Check that the SVG document generates as expected. */ @Test public void checkGetSVGDocument() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setPaint(Color.BLUE); g2.fill(new Rectangle(10, 20, 30, 40)); assertEquals("\n" + "\n" + "\n", g2.getSVGDocument()); } /** * Check that the optional ID is written correctly whether it is null or non-null. */ @Test public void checkGetSVGElementWithID() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setPaint(Color.BLUE); g2.fill(new Rectangle(10, 20, 30, 40)); assertEquals("" + "", g2.getSVGElement("ID1")); assertEquals("" + "", g2.getSVGElement(null)); } /** * Check that the width and height are written correctly whether or not units are specified. */ @Test public void checkGetSVGElementWithSVGUnits() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100, SVGUnits.PX); g2.setPaint(Color.BLUE); g2.fill(new Rectangle(10, 20, 30, 40)); assertEquals("" + "", g2.getSVGElement(null)); } /** * Check that a ViewBox is written correctly in the output. */ @Test public void checkGetSVGElementWithViewBox() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setPaint(Color.BLUE); g2.fill(new Rectangle(10, 20, 30, 40)); ViewBox viewBox = new ViewBox(30, 50, 100, 125); assertEquals("" + "", g2.getSVGElement(null, true, viewBox, null, null)); } /** * Check that a ViewBox is written correctly in the output. */ @Test public void checkGetSVGElementWithViewBoxAndPreserveAspectRatio() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setPaint(Color.BLUE); g2.fill(new Rectangle(10, 20, 30, 40)); ViewBox viewBox = new ViewBox(30, 50, 100, 125); assertEquals("" + "", g2.getSVGElement(null, true, viewBox, PreserveAspectRatio.XMAX_YMAX, null)); } /** * Check that a simple SVG document does not include a DEFS element if * there is no gradient paint and no user clipping. */ @Test public void checkDefsNotRequired() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setPaint(Color.BLUE); g2.fill(new Rectangle(10, 20, 30, 40)); assertFalse(g2.getSVGElement().contains("")); } @Test public void checkDrawPath2D() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 3.0f)); Path2D path = new Path2D.Double(); path.moveTo(10.0, 20.0); path.lineTo(30.0, 40.0); g2.draw(path); assertEquals("" + "", g2.getSVGElement()); } @Test public void checkDrawPath2DWithElementID() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 3.0f)); Path2D path = new Path2D.Double(); path.moveTo(10.0, 20.0); path.lineTo(30.0, 40.0); g2.setRenderingHint(SVGHints.KEY_ELEMENT_ID, "UNIQUE_ELEMENT_ID_1"); g2.draw(path); assertEquals("" + "", g2.getSVGElement()); } @Test public void checkDrawPath2DWithTransform() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 3.0f)); g2.setTransform(AffineTransform.getTranslateInstance(2.0, 3.0)); Path2D path = new Path2D.Double(); path.moveTo(10.0, 20.0); path.lineTo(30.0, 40.0); g2.draw(path); assertEquals("" + "", g2.getSVGElement()); } /** * Checks that the clip is correctly applied when drawing a Path2D. */ @Test public void checkDrawPath2DWithClip() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setDefsKeyPrefix("PRE"); g2.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 3.0f)); g2.clip(new Rectangle(10, 15, 20, 25)); Path2D path = new Path2D.Double(); path.moveTo(10.0, 20.0); path.lineTo(30.0, 40.0); g2.draw(path); assertEquals("" + "" + "", g2.getSVGElement()); } @Test public void checkFillPath2D() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setPaint(Color.BLUE); Path2D path = new Path2D.Double(); path.moveTo(10.0, 20.0); path.lineTo(30.0, 40.0); g2.fill(path); assertEquals("" + "", g2.getSVGElement()); } @Test public void checkFillPath2DWithElementID() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setPaint(Color.BLUE); Path2D path = new Path2D.Double(); path.moveTo(10.0, 20.0); path.lineTo(30.0, 40.0); g2.setRenderingHint(SVGHints.KEY_ELEMENT_ID, "UNIQUE_ELEMENT_ID_1"); g2.fill(path); assertEquals("" + "", g2.getSVGElement()); } @Test public void checkFillPath2DWithTransform() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setPaint(Color.RED); g2.setTransform(AffineTransform.getScaleInstance(2.0, 3.0)); Path2D path = new Path2D.Double(); path.moveTo(10.0, 20.0); path.lineTo(30.0, 40.0); g2.fill(path); assertEquals("" + "", g2.getSVGElement()); } @Test public void checkFillPath2DWithClip() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setDefsKeyPrefix("DEF"); g2.setPaint(Color.RED); g2.clip(new Rectangle(10, 11, 12, 13)); Path2D path = new Path2D.Double(); path.moveTo(10.0, 20.0); path.lineTo(30.0, 40.0); g2.fill(path); assertEquals("" + "" + "", g2.getSVGElement()); } @Test public void checkDrawLine2D() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 3.0f)); Line2D line = new Line2D.Double(10.0, 20.0, 30.0, 40.0); g2.draw(line); assertEquals("" + "", g2.getSVGElement()); } @Test public void checkDrawLine2DWithElementID() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 3.0f)); Line2D line = new Line2D.Double(10.0, 20.0, 30.0, 40.0); g2.setRenderingHint(SVGHints.KEY_ELEMENT_ID, "UNIQUE_ELEMENT_ID_1"); g2.draw(line); assertEquals("" + "", g2.getSVGElement()); } @Test public void checkDrawLine2DWithTransform() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 3.0f)); g2.setTransform(AffineTransform.getScaleInstance(2.0, 3.0)); Line2D line = new Line2D.Double(10.0, 20.0, 30.0, 40.0); g2.draw(line); assertEquals("" + "", g2.getSVGElement()); } @Test public void checkDrawLine2DWithTransformAndClip() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setDefsKeyPrefix("PRE"); g2.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 3.0f)); g2.setTransform(AffineTransform.getScaleInstance(2.0, 3.0)); g2.clip(new Rectangle(10, 11, 12, 13)); Line2D line = new Line2D.Double(10.0, 20.0, 30.0, 40.0); g2.draw(line); assertEquals("" + "" + "", g2.getSVGElement()); } @Test public void checkDrawRectangle2D() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 3.0f)); Rectangle2D rect = new Rectangle2D.Double(10.0, 20.0, 30.0, 40.0); g2.draw(rect); assertEquals("" + "", g2.getSVGElement()); } @Test public void checkDrawRectangle2DWithElementID() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 3.0f)); Rectangle2D rect = new Rectangle2D.Double(10.0, 20.0, 30.0, 40.0); g2.setRenderingHint(SVGHints.KEY_ELEMENT_ID, "UNIQUE_ELEMENT_ID_1"); g2.draw(rect); assertNull(g2.getRenderingHint(SVGHints.KEY_ELEMENT_ID)); // should be cleared after call assertEquals("" + "", g2.getSVGElement()); } @Test public void checkDrawRectangle2DWithTransform() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 3.0f)); g2.setTransform(AffineTransform.getScaleInstance(2.0, 3.0)); Rectangle2D rect = new Rectangle2D.Double(10.0, 20.0, 30.0, 40.0); g2.draw(rect); assertEquals("" + "", g2.getSVGElement()); } @Test public void checkDrawRectangle2DWithClip() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setDefsKeyPrefix("PRE"); g2.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 3.0f)); g2.clip(new Rectangle(10, 15, 20, 25)); Rectangle2D rect = new Rectangle2D.Double(10.0, 20.0, 30.0, 40.0); g2.draw(rect); assertEquals("" + "" + "", g2.getSVGElement()); } /** * Checks the output when drawing an Ellipse2D. */ @Test public void checkDrawEllipse2D() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 3.0f)); Ellipse2D ellipse = new Ellipse2D.Double(10.0, 20.0, 30.0, 40.0); g2.draw(ellipse); assertEquals("" + "", g2.getSVGElement()); } @Test public void checkDrawEllipse2DWithElementID() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 3.0f)); Ellipse2D ellipse = new Ellipse2D.Double(10.0, 20.0, 30.0, 40.0); g2.setRenderingHint(SVGHints.KEY_ELEMENT_ID, "UNIQUE_ELEMENT_ID_1"); g2.draw(ellipse); assertEquals("" + "", g2.getSVGElement()); } @Test public void checkDrawEllipse2DWithTransform() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 3.0f)); g2.setTransform(AffineTransform.getScaleInstance(2.0, 3.0)); Ellipse2D ellipse = new Ellipse2D.Double(10.0, 20.0, 30.0, 40.0); g2.draw(ellipse); assertEquals("" + "", g2.getSVGElement()); } @Test public void checkDrawEllipse2DWithClip() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setDefsKeyPrefix("DEF"); g2.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 3.0f)); g2.clip(new Rectangle(10, 15, 20, 25)); Ellipse2D ellipse = new Ellipse2D.Double(10.0, 20.0, 30.0, 40.0); g2.draw(ellipse); assertEquals("" + "" + "", g2.getSVGElement()); } /** * Checks the output when filling an Ellipse2D. */ @Test public void checkFillEllipse2D() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setPaint(Color.DARK_GRAY); Ellipse2D ellipse = new Ellipse2D.Double(10.0, 20.0, 30.0, 40.0); g2.fill(ellipse); assertEquals("", g2.getSVGElement()); } /** * Checks the output when filling an Ellipse2D and specifying * an element ID. */ @Test public void checkFillEllipse2DWithElementID() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setPaint(Color.DARK_GRAY); Ellipse2D ellipse = new Ellipse2D.Double(10.0, 20.0, 30.0, 40.0); g2.setRenderingHint(SVGHints.KEY_ELEMENT_ID, "UNIQUE_ELEMENT_ID_1"); g2.fill(ellipse); assertEquals("", g2.getSVGElement()); } @Test public void checkFillRectangle2D() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setPaint(Color.GREEN); Rectangle2D rect = new Rectangle2D.Double(10.0, 20.0, 30.0, 40.0); g2.fill(rect); assertEquals("" + "", g2.getSVGElement()); } @Test public void checkFillRectangle2DWithElementID() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setPaint(Color.GREEN); Rectangle2D rect = new Rectangle2D.Double(10.0, 20.0, 30.0, 40.0); g2.setRenderingHint(SVGHints.KEY_ELEMENT_ID, "UNIQUE_ELEMENT_ID_1"); g2.fill(rect); assertEquals("" + "", g2.getSVGElement()); } /** * Check the fill rectangle output with a non-default alpha value. */ @Test public void checkFillRectangle2DWithAlpha() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setPaint(Color.GREEN); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f)); Rectangle2D rect = new Rectangle2D.Double(10.0, 20.0, 30.0, 40.0); g2.fill(rect); assertEquals("" + "", g2.getSVGElement()); } /** * Check the fill rectangle output with a clip setting. */ @Test public void checkFillRectangle2DWithClip() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setDefsKeyPrefix("DEF"); g2.setPaint(Color.GREEN); g2.clip(new Rectangle(10, 11, 12, 13)); Rectangle2D rect = new Rectangle2D.Double(10.0, 20.0, 30.0, 40.0); g2.fill(rect); assertEquals("" + "" + "", g2.getSVGElement()); } /** * Check the fill rectangle output with a transform. */ @Test public void checkFillRectangle2DWithTransform() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setTransform(AffineTransform.getRotateInstance(Math.PI)); g2.setPaint(Color.GREEN); Rectangle2D rect = new Rectangle2D.Double(10.0, 20.0, 30.0, 40.0); g2.fill(rect); assertEquals("" + "", g2.getSVGElement()); } @Test public void checkFillRectangle2DWithGradientPaint() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setDefsKeyPrefix("DEFS_PREFIX"); g2.setPaint(new GradientPaint(1.0f, 2.0f, Color.RED, 3.0f, 4.0f, Color.GREEN)); Rectangle2D rect = new Rectangle2D.Double(10.0, 20.0, 30.0, 40.0); g2.fill(rect); assertEquals("", g2.getSVGElement()); } @Test public void checkFillRectangle2DWithLinearGradientPaint() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setDefsKeyPrefix("DEFS_PREFIX"); Point2D start = new Point2D.Float(0, 0); Point2D end = new Point2D.Float(50, 50); float[] dist = {0.0f, 0.2f, 1.0f}; Color[] colors = {Color.RED, Color.WHITE, Color.BLUE}; g2.setPaint(new LinearGradientPaint(start, end, dist, colors)); Rectangle2D rect = new Rectangle2D.Double(10.0, 20.0, 30.0, 40.0); g2.fill(rect); assertEquals("", g2.getSVGElement()); } @Test public void checkFillRectangle2DWithRadialGradientPaint() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setDefsKeyPrefix("DEFS_PREFIX"); Point2D center = new Point2D.Float(50, 50); float radius = 25; float[] dist = {0.0f, 0.2f, 1.0f}; Color[] colors = {Color.RED, Color.WHITE, Color.BLUE}; g2.setPaint(new RadialGradientPaint(center, radius, dist, colors)); Rectangle2D rect = new Rectangle2D.Double(10.0, 20.0, 30.0, 40.0); g2.fill(rect); assertEquals("", g2.getSVGElement()); } /** * Check the output for drawing a string. */ @Test public void checkDrawString() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setPaint(Color.GREEN); g2.drawString("ABC", 10, 20); assertEquals("" + "ABC", g2.getSVGElement()); } /** * Check the output for drawing a string. */ @Test public void checkDrawStringWithElementID() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setPaint(Color.GREEN); g2.setRenderingHint(SVGHints.KEY_ELEMENT_ID, "UNIQUE_ELEMENT_ID_1"); g2.drawString("ABC", 10, 20); assertEquals("" + "ABC", g2.getSVGElement()); } private static Image createImage() { BufferedImage image = new BufferedImage(3, 5, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); g2.setColor(Color.RED); g2.fillRect(0, 0, 3, 5); return image; } /** * Check the output for drawing an image. */ @Test public void checkDrawImage() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.drawImage(createImage(), 10, 20, Color.YELLOW, null); assertEquals("", g2.getSVGElement()); } /** * Check the output for drawing an image. */ @Test public void checkDrawImageWithElementID() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setRenderingHint(SVGHints.KEY_ELEMENT_ID, "UNIQUE_ELEMENT_ID_1"); g2.drawImage(createImage(), 10, 20, Color.YELLOW, null); assertEquals("", g2.getSVGElement()); } @Test public void checkDrawImageWithClip() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setDefsKeyPrefix("PRE"); g2.clipRect(10, 20, 30, 40); g2.drawImage(createImage(), 10, 20, Color.YELLOW, null); assertEquals("", g2.getSVGElement()); } /** * Check the output for drawing an image with a transform applied. */ @Test public void checkDrawImageWithTransform() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setTransform(AffineTransform.getTranslateInstance(11.1, 22.2)); g2.drawImage(createImage(), 10, 20, Color.YELLOW, null); assertEquals("", g2.getSVGElement()); } /** * Check the output for drawing an image. */ @Test public void checkDrawImageWithReferenceHint() { SVGGraphics2D g2 = new SVGGraphics2D(200, 100); g2.setRenderingHint(SVGHints.KEY_IMAGE_HANDLING, SVGHints.VALUE_IMAGE_HANDLING_REFERENCE); g2.drawImage(createImage(), 10, 20, Color.YELLOW, null); assertEquals("", g2.getSVGElement()); } } jfreesvg-5.0.6/src/test/java/org/jfree/svg/TestSVGGraphics2D.java000066400000000000000000001030411463574317400245330ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-present, by David Gilbert. All rights reserved. * * Project Info: http://www.jfree.org/jfreesvg/index.html * * 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 . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * JFreeSVG home page: * * http://www.jfree.org/jfreesvg * */ package org.jfree.svg; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.BeforeEach; import static org.junit.jupiter.api.Assertions.*; /** * Some tests for a Graphics2D implementation. All tests should pass with the * Graphics2D instance from a BufferedImage (which we can treat as a reference * implementation). */ class TestSVGGraphics2D { /** * Change this to true to test against a reference Graphics2D * implementation from the JDK. This is useful to verify that the tests * are correct. */ private static final boolean TEST_REFERENCE_IMPLEMENTATION = false; private Graphics2D g2; @BeforeEach public void setUp() { if (TEST_REFERENCE_IMPLEMENTATION) { // to test a reference implementation, use this Graphics2D from a // BufferedImage in the JDK BufferedImage img = new BufferedImage(10, 20, BufferedImage.TYPE_INT_ARGB); this.g2 = img.createGraphics(); } else { // Test SVGGraphics2D... this.g2 = new SVGGraphics2D(10.0, 20.0); } } /** * Checks that the default transform is an identity transform. */ @Test void checkDefaultTransform() { assertEquals(new AffineTransform(), g2.getTransform()); } /** * Modifying the transform returned by the Graphics2D should not affect * the state of the Graphics2D. In order for that to happen, the method * should be returning a copy of the actual transform object. */ @Test void checkGetTransformSafety() { AffineTransform t = g2.getTransform(); t.rotate(Math.PI); assertNotEquals(t, g2.getTransform()); assertEquals(new AffineTransform(), g2.getTransform()); } /** * A basic check that setTransform() does indeed update the transform. */ @Test void setTransform() { AffineTransform t = new AffineTransform(1, 2, 3, 4, 5, 6); g2.setTransform(t); assertEquals(t, g2.getTransform()); t.setTransform(6, 5, 4, 3, 2, 1); g2.setTransform(t); assertEquals(t, g2.getTransform()); // in spite of the docs saying that null is accepted this gives // a NullPointerException with SunGraphics2D. //g2.setTransform(null); //assertEquals(new AffineTransform(), g2.getTransform()); } /** * When calling setTransform() the caller passes in an AffineTransform * instance. If the caller retains a reference to the AffineTransform * and subsequently modifies it, we don't want the Graphics2D object to * be affected...so it should be making an internal copy of the * AffineTransform. */ @Test void checkSetTransformSafety() { AffineTransform t = AffineTransform.getTranslateInstance(1.0, 2.0); g2.setTransform(t); assertEquals(t, g2.getTransform()); t.setToRotation(Math.PI); assertNotEquals(t, g2.getTransform()); } @Test void checkSetNonInvertibleTransform() { AffineTransform t = AffineTransform.getScaleInstance(0.0, 0.0); g2.setTransform(t); assertEquals(t, g2.getTransform()); // after setting the clip, we cannot retrieve it while the transform // is non-invertible... Rectangle2D clip = new Rectangle2D.Double(1, 2, 3, 4); g2.setClip(clip); assertNull(g2.getClip()); g2.setTransform(new AffineTransform()); assertEquals(new Rectangle2D.Double(0, 0, 0, 0), g2.getClip().getBounds2D()); } /** * A check for a call to transform() with a rotation, that follows a * translation. */ @Test void checkTransform() { AffineTransform t = new AffineTransform(); this.g2.setTransform(t); this.g2.translate(30, 30); AffineTransform rt = AffineTransform.getRotateInstance(Math.PI / 2.0, 300, 200); this.g2.transform(rt); t = this.g2.getTransform(); assertEquals(0, t.getScaleX(), EPSILON); assertEquals(0, t.getScaleY(), EPSILON); assertEquals(-1.0, t.getShearX(), EPSILON); assertEquals(1.0, t.getShearY(), EPSILON); assertEquals(530.0, t.getTranslateX(), EPSILON); assertEquals(-70, t.getTranslateY(), EPSILON); } @Test void checkTransformNull() { try { this.g2.transform(null); fail("Expected a NullPointerException."); } catch (NullPointerException e) { // this exception is expected } } /** * Basic checks for the scale(x, y) method. */ @Test void scale() { g2.scale(0.5, 2.0); assertEquals(AffineTransform.getScaleInstance(0.5, 2.0), g2.getTransform()); g2.scale(2.0, -1.0); assertEquals(AffineTransform.getScaleInstance(1.0, -2.0), g2.getTransform()); } /** * Checks that a call to scale(x, y) on top of an existing translation * gives the correct values. */ @Test void translateFollowedByScale() { g2.translate(2, 3); assertEquals(AffineTransform.getTranslateInstance(2.0, 3.0), g2.getTransform()); g2.scale(10, 20); assertEquals(new AffineTransform(10.0, 0.0, 0.0, 20.0, 2.0, 3.0), g2.getTransform()); } /** * Checks that a call to translate(x, y) on top of an existing scale * gives the correct values. */ @Test void scaleFollowedByTranslate() { g2.scale(2, 2); assertEquals(AffineTransform.getScaleInstance(2.0, 2.0), g2.getTransform()); g2.translate(10, 20); assertEquals(new AffineTransform(2.0, 0.0, 0.0, 2.0, 20.0, 40.0), g2.getTransform()); } private static final double EPSILON = 0.000000001; @Test void scaleFollowedByRotate() { g2.scale(2, 2); assertEquals(AffineTransform.getScaleInstance(2.0, 2.0), g2.getTransform()); g2.rotate(Math.PI / 3); AffineTransform t = g2.getTransform(); assertEquals(1.0, t.getScaleX(), EPSILON); assertEquals(1.0, t.getScaleY(), EPSILON); assertEquals(-1.7320508075688772, t.getShearX(), EPSILON); assertEquals(1.7320508075688772, t.getShearY(), EPSILON); assertEquals(0.0, t.getTranslateX(), EPSILON); assertEquals(0.0, t.getTranslateY(), EPSILON); } @Test void rotateFollowedByScale() { g2.rotate(Math.PI); assertEquals(AffineTransform.getRotateInstance(Math.PI), g2.getTransform()); g2.scale(2.0, 2.0); assertEquals(new AffineTransform(-2.0, 0.0, 0.0, -2.0, 0.0, 0.0), g2.getTransform()); } /** * Checks that the getClip() method returns a different object than what * was passed to setClip(), and that multiple calls to getClip() return * a new object each time. */ @Test void checkGetClipSafety() { Rectangle2D r = new Rectangle2D.Double(0, 0, 1, 1); this.g2.setClip(r); Shape s = this.g2.getClip(); assertNotSame(r, s); Shape s2 = this.g2.getClip(); assertNotSame(s, s2); } /** * The default user clip should be {@code null}. */ @Test void checkDefaultClip() { assertNull(g2.getClip(), "Default user clip should be null."); } /** * Checks that getClipBounds() is returning an integer approximation of * the bounds. */ @Test void checkGetClipBounds() { Rectangle2D r = new Rectangle2D.Double(0.25, 0.25, 0.5, 0.5); this.g2.setClip(r); assertEquals(new Rectangle(0, 0, 1, 1), this.g2.getClipBounds()); } /** * Checks that getClipBounds() returns {@code null} when the clip is * {@code null}. */ @Test void checkGetClipBoundsWhenClipIsNull() { this.g2.setClip(null); assertNull(this.g2.getClipBounds()); } /** * Simple check that the clip() methods creates an intersection with the * existing clip region. */ @Test void checkClip() { Rectangle2D r = new Rectangle2D.Double(1.0, 1.0, 3.0, 3.0); this.g2.setClip(r); this.g2.clip(new Rectangle2D.Double(0.0, 0.0, 2.0, 2.0)); assertEquals(new Rectangle2D.Double(1.0, 1.0, 1.0, 1.0), this.g2.getClip().getBounds2D()); } /** * Check that if the user clip is non-intersecting with the existing clip, then * the clip is empty. */ @Test void checkNonIntersectingClip() { Rectangle2D r = new Rectangle2D.Double(1.0, 1.0, 3.0, 3.0); this.g2.setClip(r); this.g2.clip(new Rectangle2D.Double(5.0, 5.0, 1.0, 1.0)); assertTrue(this.g2.getClip().getBounds2D().isEmpty()); } /** * After applying a scale transformation, getClip() will return a * modified clip. */ @Test void checkClipAfterScaling() { Rectangle2D r = new Rectangle2D.Double(1, 2, 3, 0.5); this.g2.setClip(r); assertEquals(r, this.g2.getClip().getBounds2D()); this.g2.scale(0.5, 2.0); assertEquals(new Rectangle2D.Double(2, 1, 6, 0.25), this.g2.getClip().getBounds2D()); // check that we get a good intersection when clipping after the // scaling has been done... r = new Rectangle2D.Double(3, 0, 2, 2); this.g2.clip(r); assertEquals(new Rectangle2D.Double(3, 1, 2, 0.25), this.g2.getClip().getBounds2D()); } /** * Translating will change the existing clip. */ @Test void checkClipAfterTranslate() { Rectangle2D clip = new Rectangle2D.Double(0.0, 0.0, 1.0, 1.0); this.g2.setClip(clip); assertEquals(clip, this.g2.getClip().getBounds2D()); this.g2.translate(1.0, 2.0); assertEquals(new Rectangle(-1, -2, 1 ,1), this.g2.getClip().getBounds2D()); } @Test void checkSetClipAfterTranslate() { this.g2.translate(1.0, 2.0); this.g2.setClip(0, 0, 1, 1); assertEquals(new Rectangle(0, 0, 1, 1), this.g2.getClip().getBounds()); this.g2.translate(1.0, 2.0); assertEquals(new Rectangle(-1, -2, 1, 1), this.g2.getClip().getBounds()); } /** * Transforming will change the reported clipping shape. */ @Test void checkClipAfterTransform() { Rectangle2D clip = new Rectangle2D.Double(0, 0, 1, 1); this.g2.setClip(clip); assertEquals(clip, this.g2.getClip().getBounds2D()); this.g2.transform(AffineTransform.getRotateInstance(Math.PI)); assertEquals(new Rectangle(-1, -1, 1 ,1), this.g2.getClip().getBounds2D()); this.g2.setTransform(new AffineTransform()); assertEquals(clip, this.g2.getClip().getBounds2D()); } /** * Clipping with a line makes no sense, but the API allows it so we should * not fail. In fact, running with a JDK Graphics2D (from a BufferedImage) * it seems that the bounding rectangle of the line is used for clipping... * does that make sense? Matching the behaviour for now. */ @Test void checkClipWithLine2D() { Rectangle2D r = new Rectangle2D.Double(1.0, 1.0, 3.0, 3.0); this.g2.setClip(r); this.g2.clip(new Line2D.Double(1.0, 2.0, 3.0, 4.0)); assertEquals(new Rectangle2D.Double(1.0, 2.0, 2.0, 2.0), this.g2.getClip().getBounds2D()); //assertTrue(this.g2.getClip().getBounds2D().isEmpty()); } /** * Clipping with a null argument is "not recommended" according to the * latest API docs (https://bugs.java.com/bugdatabase/view_bug.do?bug_id=6206189). */ @Test void checkClipWithNullArgument() { // when there is a current clip set, a null pointer exception is expected this.g2.setClip(new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0)); assertThrows(NullPointerException.class, () -> this.g2.clip(null)); this.g2.setClip(null); try { this.g2.clip(null); } catch (Exception e) { fail("No exception expected."); } } /** * A simple check for a call to clipRect(). */ @Test void checkClipRect() { Rectangle2D clip = new Rectangle2D.Double(0, 0, 5, 5); this.g2.setClip(clip); this.g2.clipRect(2, 1, 4, 2); assertEquals(new Rectangle(2, 1, 3, 2), g2.getClip().getBounds2D()); } @Test void checkClipRectParams() { Rectangle2D clip = new Rectangle2D.Double(0, 0, 5, 5); this.g2.setClip(clip); // negative width this.g2.clipRect(2, 1, -4, 2); assertTrue(this.g2.getClip().getBounds2D().isEmpty()); // negative height this.g2.setClip(clip); this.g2.clipRect(2, 1, 4, -2); assertTrue(this.g2.getClip().getBounds2D().isEmpty()); } @Test void checkDrawStringWithNullString() { try { g2.drawString((String) null, 1, 2); fail("There should be a NullPointerException."); } catch (NullPointerException e) { // this exception is expected } try { g2.drawString((String) null, 1.0f, 2.0f); fail("There should be a NullPointerException."); } catch (NullPointerException e) { // this exception is expected } } @Test void checkDrawStringWithEmptyString() { // this should not cause any exception g2.setRenderingHint(SVGHints.KEY_DRAW_STRING_TYPE, SVGHints.VALUE_DRAW_STRING_TYPE_VECTOR); g2.drawString("", 1, 2); g2.setRenderingHint(SVGHints.KEY_DRAW_STRING_TYPE, null); g2.drawString("", 1, 2); } /** * Some checks for the create() method. */ @Test void checkCreate() { this.g2.setClip(new Rectangle(1, 2, 3, 4)); Graphics2D copy = (Graphics2D) g2.create(); assertEquals(copy.getBackground(), g2.getBackground()); assertEquals(copy.getClip().getBounds2D(), g2.getClip().getBounds2D()); assertEquals(copy.getColor(), g2.getColor()); assertEquals(copy.getComposite(), g2.getComposite()); assertEquals(copy.getFont(), g2.getFont()); assertEquals(copy.getRenderingHints(), g2.getRenderingHints()); assertEquals(copy.getStroke(), g2.getStroke()); assertEquals(copy.getTransform(), g2.getTransform()); } /** * The setPaint() method allows a very minor state leakage in the sense * that it is possible to modify a GradientPaint externally after a call * to the setPaint() method and have it impact the state of the * Graphics2D implementation. Avoiding this would require cloning the * Paint object, but there is no good way to do that for an arbitrary * Paint instance. */ @Test void checkSetPaintSafety() { Point2D pt1 = new Point2D.Double(1.0, 2.0); Point2D pt2 = new Point2D.Double(3.0, 4.0); GradientPaint gp = new GradientPaint(pt1, Color.RED, pt2, Color.BLUE); this.g2.setPaint(gp); assertEquals(gp, this.g2.getPaint()); assertSame(gp, this.g2.getPaint()); pt1.setLocation(7.0, 7.0); assertEquals(gp, this.g2.getPaint()); } /** * According to the Javadocs, setting the paint to null should have no * impact on the current paint (that is, the call is silently ignored). */ @Test void checkSetPaintNull() { this.g2.setPaint(Color.RED); // this next call should have no impact this.g2.setPaint(null); assertEquals(Color.RED, this.g2.getPaint()); } /** * Passing a Color to setPaint() also updates the color, but not the * background color. */ @Test void checkSetPaintAlsoUpdatesColorButNotBackground() { Color existingBackground = this.g2.getBackground(); this.g2.setPaint(Color.MAGENTA); assertEquals(Color.MAGENTA, this.g2.getPaint()); assertEquals(Color.MAGENTA, this.g2.getColor()); assertEquals(existingBackground, this.g2.getBackground()); } /** * If setPaint() is called with an argument that is not an instance of * Color, then the existing color remains unchanged. */ @Test void checkSetPaintDoesNotUpdateColor() { GradientPaint gp = new GradientPaint(1.0f, 2.0f, Color.RED, 3.0f, 4.0f, Color.BLUE); this.g2.setColor(Color.MAGENTA); this.g2.setPaint(gp); assertEquals(gp, this.g2.getPaint()); assertEquals(Color.MAGENTA, this.g2.getColor()); } /** * Verifies that setting the old AWT color attribute also updates the * Java2D paint attribute. * * @see #checkSetPaintAlsoUpdatesColorButNotBackground() */ @Test void checkSetColorAlsoUpdatesPaint() { this.g2.setColor(Color.MAGENTA); assertEquals(Color.MAGENTA, this.g2.getPaint()); assertEquals(Color.MAGENTA, this.g2.getColor()); } /** * The behaviour of the reference implementation has been observed as * ignoring null. This matches the documented behaviour of the * setPaint() method. */ @Test void checkSetColorNull() { this.g2.setColor(Color.RED); this.g2.setColor(null); assertEquals(Color.RED, this.g2.getColor()); } /** * Setting the background color does not change the color or paint. */ @Test void checkSetBackground() { this.g2.setBackground(Color.CYAN); assertEquals(Color.CYAN, this.g2.getBackground()); assertNotEquals(Color.CYAN, this.g2.getColor()); assertNotEquals(Color.CYAN, this.g2.getPaint()); } /** * The behaviour of the reference implementation has been observed as * allowing null (this is inconsistent with the behaviour of setColor()). */ @Test void checkSetBackgroundNull() { this.g2.setBackground(Color.RED); this.g2.setBackground(null); assertNull(this.g2.getBackground()); } /** * Since the setBackground() method is allowing null, we should ensure * that the clearRect() method doesn't fail in this case. With no * background color, the clearRect() method should be a no-op but there * is no easy way to test for that. */ @Test void checkClearRectWithNullBackground() { this.g2.setBackground(null); this.g2.clearRect(1, 2, 3, 4); //no exceptions and we're good } /** * In the reference implementation, setting a null composite has been * observed to throw an IllegalArgumentException. */ @Test void checkSetCompositeNull() { try { this.g2.setComposite(null); fail("Expected an IllegalArgumentException."); } catch (IllegalArgumentException e) { // this exception is expected in the test } } @Test void checkSetStrokeNull() { try { this.g2.setStroke(null); fail("Expected an IllegalArgumentException."); } catch (IllegalArgumentException e) { // this exception is expected in the test } } /** * Basic check of set then get. */ @Test void checkSetRenderingHint() { this.g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); assertEquals(RenderingHints.VALUE_STROKE_PURE, this.g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL)); } /** * The reference implementation has been observed to throw a * NullPointerException when the key is null. */ @Test void checkSetRenderingHintWithNullKey() { try { this.g2.setRenderingHint(null, "XYZ"); fail("NullPointerException is expected here."); } catch (NullPointerException e) { // this is expected } } /** * The reference implementation has been observed to accept a null key * and return null in that case. */ @Test void checkGetRenderingHintWithNullKey() { assertNull(this.g2.getRenderingHint(null)); } /** * Check setting a hint with a value that doesn't match the key. */ @Test void checkSetRenderingHintWithInconsistentValue() { try { this.g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_ANTIALIAS_DEFAULT); fail("Expected an IllegalArgumentException."); } catch (IllegalArgumentException e) { // we expect this exception } } /** * A call to getRenderingHints() is returning a copy of the hints, so * changing it will not affect the state of the Graphics2D instance. */ @Test void checkGetRenderingHintsSafety() { this.g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); RenderingHints hints = this.g2.getRenderingHints(); hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); assertEquals(RenderingHints.VALUE_ANTIALIAS_OFF, this.g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING)); } @Test void checkSetRenderingHintsNull() { try { this.g2.setRenderingHints(null); fail("NullPointerException expected."); } catch (NullPointerException e) { // this is expected } } @Test void checkHit() { Shape shape = new Rectangle2D.Double(0.0, 0.0, 1.0, 1.0); Rectangle r = new Rectangle(2, 2, 2, 2); assertFalse(this.g2.hit(r, shape, false)); this.g2.scale(3.0, 3.0); assertTrue(this.g2.hit(r, shape, false)); } @Test void checkHitForOutline() { Shape shape = new Rectangle2D.Double(0.0, 0.0, 3.0, 3.0); Rectangle r = new Rectangle(1, 1, 1, 1); assertFalse(this.g2.hit(r, shape, true)); this.g2.scale(0.5, 0.5); // now the rectangle is entirely inside the shape, but does not touch // the outline... assertTrue(this.g2.hit(r, shape, true)); } /** * We have observed in the reference implementation that setting the font * to null does not change the current font setting. */ @Test void checkSetFontNull() { Font f = new Font("Serif", Font.PLAIN, 8); this.g2.setFont(f); assertEquals(f, this.g2.getFont()); this.g2.setFont(null); assertEquals(f, this.g2.getFont()); } @Test void checkDefaultStroke() { BasicStroke s = (BasicStroke) this.g2.getStroke(); assertEquals(BasicStroke.CAP_SQUARE, s.getEndCap()); assertEquals(1.0f, s.getLineWidth(), EPSILON); assertEquals(BasicStroke.JOIN_MITER, s.getLineJoin()); } /** * Check that a null GlyphVector throws a {@code NullPointerException}. */ @Test void drawGlyphVectorNull() { try { g2.drawGlyphVector(null, 10, 10); fail("Expecting a NullPointerException."); } catch (NullPointerException e) { // expected } } /** * Check the shear() method. */ @Test void shear() { g2.setTransform(new AffineTransform()); g2.shear(2.0, 3.0); assertEquals(new AffineTransform(1, 3, 2, 1, 0, 0), g2.getTransform()); } /** * Checks a translate() followed by a shear(). */ @Test void shearFollowingTranslate() { g2.setTransform(new AffineTransform()); g2.translate(10.0, 20.0); g2.shear(2.0, 3.0); assertEquals(new AffineTransform(1, 3, 2, 1, 10, 20), g2.getTransform()); } @Test void drawImageWithNullBackground() { Image img = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB); g2.drawImage(img, 10, 10, null, null); assertTrue(true); // won't get here if there's an exception above } /** * https://github.com/jfree/jfreesvg/issues/6 */ @Test void drawImageWithNullTransform() { Image img = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB); g2.drawImage(img, null, null); assertTrue(true); // won't get here if there's an exception above } @Test void drawImageWithNullImage() { // API docs say method does nothing if img is null // still seems to return true assertTrue(g2.drawImage(null, 10, 20, null)); assertTrue(g2.drawImage(null, 10, 20, 30, 40, null)); assertTrue(g2.drawImage(null, 10, 20, Color.YELLOW, null)); assertTrue(g2.drawImage(null, 1, 2, 3, 4, Color.RED, null)); assertTrue(g2.drawImage(null, 1, 2, 3, 4, 5, 6, 7, 8, null)); assertTrue(g2.drawImage(null, 1, 2, 3, 4, 5, 6, 7, 8, Color.RED, null)); } @Test void drawImageWithNegativeDimensions() { Image img = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB); assertTrue(g2.drawImage(img, 1, 2, -10, 10, null)); assertTrue(g2.drawImage(img, 1, 2, 10, -10, null)); } /** * Check that the color is not changed by setting a clip. In some * implementations the clip is saved/restored as part of the overall * graphics state so clipping can impact other attributes. */ @Test void checkColorAfterSetClip() { this.g2.setColor(Color.RED); assertEquals(Color.RED, this.g2.getColor()); this.g2.setClip(0, 0, 10, 10); assertEquals(Color.RED, this.g2.getColor()); this.g2.setColor(Color.BLUE); assertEquals(Color.BLUE, this.g2.getColor()); this.g2.setClip(0, 0, 20, 20); assertEquals(Color.BLUE, this.g2.getColor()); } /** * See https://github.com/jfree/fxgraphics2d/issues/6 */ @Test void checkFontAfterSetClip() { this.g2.setFont(new Font(Font.DIALOG, Font.BOLD, 12)); assertEquals(new Font(Font.DIALOG, Font.BOLD, 12), this.g2.getFont()); this.g2.setClip(0, 0, 10, 10); assertEquals(new Font(Font.DIALOG, Font.BOLD, 12), this.g2.getFont()); this.g2.setFont(new Font(Font.DIALOG, Font.BOLD, 24)); assertEquals(new Font(Font.DIALOG, Font.BOLD, 24), this.g2.getFont()); this.g2.setClip(0, 0, 20, 20); assertEquals(new Font(Font.DIALOG, Font.BOLD, 24), this.g2.getFont()); } /** * See https://github.com/jfree/fxgraphics2d/issues/6 */ @Test void checkStrokeAfterSetClip() { this.g2.setStroke(new BasicStroke(1.0f)); assertEquals(new BasicStroke(1.0f), this.g2.getStroke()); this.g2.setClip(0, 0, 10, 10); assertEquals(new BasicStroke(1.0f), this.g2.getStroke()); this.g2.setStroke(new BasicStroke(2.0f)); assertEquals(new BasicStroke(2.0f), this.g2.getStroke()); this.g2.setClip(0, 0, 20, 20); assertEquals(new BasicStroke(2.0f), this.g2.getStroke()); } /** * A test to check whether setting a transform on the Graphics2D affects * the results of text measurements performed via getFontMetrics(). */ @Test void testGetFontMetrics() { Font f = new Font(Font.SANS_SERIF, Font.PLAIN, 10); FontMetrics fm = this.g2.getFontMetrics(f); int w = fm.stringWidth("ABC"); Rectangle2D bounds = fm.getStringBounds("ABC", this.g2); // after scaling, the string width is not changed this.g2.setTransform(AffineTransform.getScaleInstance(3.0, 2.0)); fm = this.g2.getFontMetrics(f); assertEquals(w, fm.stringWidth("ABC")); assertEquals(bounds.getWidth(), fm.getStringBounds("ABC", this.g2).getWidth(), EPSILON); } @Test void drawImageWithNullImageOp() { BufferedImage img = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB); g2.drawImage(img, null, 2, 3); assertTrue(true); // won't get here if there's an exception above } /** * API docs say the method does nothing when called with a null image. */ @Test void drawRenderedImageWithNullImage() { g2.drawRenderedImage(null, AffineTransform.getTranslateInstance(0, 0)); assertTrue(true); // won't get here if there's an exception above } /** * Filling and/or stroking a Rectangle2D with a negative width will not display anything but * should not throw an exception. */ @Test void fillOrStrokeRectangleWithNegativeWidthMustNotFail() { g2.draw(new Rectangle2D.Double(0, 0, 0, 10)); g2.draw(new Rectangle2D.Double(0, 0, -10, 10)); g2.fill(new Rectangle2D.Double(0, 0, 0, 10)); g2.fill(new Rectangle2D.Double(0, 0, -10, 10)); assertTrue(true); // won't get here if there's an exception above } /** * Filling and/or stroking a Rectangle2D with a negative height will not display anything but * should not throw an exception. */ @Test void fillOrStrokeRectangleWithNegativeHeightMustNotFail() { g2.draw(new Rectangle2D.Double(0, 0, 0, 10)); g2.draw(new Rectangle2D.Double(0, 0, 10, -10)); g2.fill(new Rectangle2D.Double(0, 0, 0, 10)); g2.fill(new Rectangle2D.Double(0, 0, 10, -10)); assertTrue(true); // won't get here if there's an exception above } @Test void checkClipAfterCreate() { this.g2.setClip(10, 20, 30, 40); assertEquals(new Rectangle(10, 20, 30, 40), g2.getClip().getBounds2D()); Graphics2D g2copy = (Graphics2D) this.g2.create(); g2copy.clipRect(11, 21, 10, 10); assertEquals(new Rectangle(11, 21, 10, 10), g2copy.getClip().getBounds2D()); g2copy.dispose(); assertEquals(new Rectangle(10, 20, 30, 40), g2.getClip().getBounds2D()); } @Test void checkGradientPaintRefGeneration() { if (!(this.g2 instanceof SVGGraphics2D)) return; SVGGraphics2D svg2 = (SVGGraphics2D) this.g2; GradientPaint gp0 = new GradientPaint(1.0f, 2.0f, Color.RED, 3.0f, 4.0f, Color.BLUE); svg2.setPaint(gp0); assertEquals(svg2.defsKeyPrefix + "gp0", svg2.gradientPaintRef); GradientPaint gp1 = new GradientPaint(1.0f, 2.0f, Color.YELLOW, 3.0f, 4.0f, Color.GREEN); svg2.setPaint(gp1); assertEquals(svg2.defsKeyPrefix + "gp1", svg2.gradientPaintRef); svg2.setPaint(gp0); assertEquals(svg2.defsKeyPrefix + "gp0", svg2.gradientPaintRef); } @Test void checkLinearGradientPaintRefGeneration() { if (!(this.g2 instanceof SVGGraphics2D)) return; SVGGraphics2D svg2 = (SVGGraphics2D) this.g2; var lgp0 = new LinearGradientPaint(1.0f, 2.0f,3.0f, 4.0f, new float[] { 0.0f, 0.5f, 1.0f }, new Color[] { Color.RED, Color.BLUE, Color.GREEN }); svg2.setPaint(lgp0); assertEquals(svg2.defsKeyPrefix + "lgp0", svg2.gradientPaintRef); var lgp1 = new LinearGradientPaint(1.0f, 2.0f,3.0f, 4.0f, new float[] { 0.0f, 0.5f, 1.0f }, new Color[] { Color.YELLOW, Color.CYAN, Color.GRAY }); svg2.setPaint(lgp1); assertEquals(svg2.defsKeyPrefix + "lgp1", svg2.gradientPaintRef); svg2.setPaint(lgp0); assertEquals(svg2.defsKeyPrefix + "lgp0", svg2.gradientPaintRef); } @Test void checkRadialGradientPaintRefGeneration() { if (!(this.g2 instanceof SVGGraphics2D)) return; SVGGraphics2D svg2 = (SVGGraphics2D) this.g2; var rgp0 = new RadialGradientPaint(1.0f, 2.0f, 3.0f, new float[] { 0.0f, 0.5f, 1.0f }, new Color[] { Color.RED, Color.BLUE, Color.GREEN }); svg2.setPaint(rgp0); assertEquals(svg2.defsKeyPrefix + "rgp0", svg2.gradientPaintRef); var rgp1 = new RadialGradientPaint(1.0f, 2.0f, 4.0f, new float[] { 0.0f, 0.5f, 1.0f }, new Color[] { Color.YELLOW, Color.CYAN, Color.GRAY }); svg2.setPaint(rgp1); assertEquals(svg2.defsKeyPrefix + "rgp1", svg2.gradientPaintRef); svg2.setPaint(rgp0); assertEquals(svg2.defsKeyPrefix + "rgp0", svg2.gradientPaintRef); } } jfreesvg-5.0.6/src/test/java/org/jfree/svg/util/000077500000000000000000000000001463574317400215005ustar00rootroot00000000000000jfreesvg-5.0.6/src/test/java/org/jfree/svg/util/ArgsTest.java000066400000000000000000000036721463574317400241070ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-present, by David Gilbert. All rights reserved. * * Project Info: http://www.jfree.org/jfreesvg/index.html * * 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 . * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * If you do not wish to be bound by the terms of the GPL, an alternative * commercial license can be purchased. For details, please see visit the * JFreeSVG home page: * * http://www.jfree.org/jfreesvg * */ package org.jfree.svg.util; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertThrows; /** * Tests for the Args utility class. */ public class ArgsTest { /** * Checks for the requireFinitePositive() method. */ @Test public void checkRequireFinitePositive() { assertThrows(IllegalArgumentException.class, () -> Args.requireFinitePositive(0.0, "d")); assertThrows(IllegalArgumentException.class, () -> Args.requireFinitePositive(Double.NEGATIVE_INFINITY, "d")); assertThrows(IllegalArgumentException.class, () -> Args.requireFinitePositive(Double.NaN, "d")); } }