pax_global_header00006660000000000000000000000064136371074560014526gustar00rootroot0000000000000052 comment=95f4574aca39c110b76c6b423ecb5add279aadb2 jfreesvg-4.1/000077500000000000000000000000001363710745600132055ustar00rootroot00000000000000jfreesvg-4.1/.gitignore000066400000000000000000000001121363710745600151670ustar00rootroot00000000000000target javadoc distribution *.class # Package Files # *.jar *.war *.ear jfreesvg-4.1/LICENSE000066400000000000000000001045151363710745600142200ustar00rootroot00000000000000 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-4.1/README.md000066400000000000000000000207421363710745600144710ustar00rootroot00000000000000JFreeSVG ======== Version 4.1, by David Gilbert, 26 March 2020. (C)opyright 2013-2020, by Object Refinery Limited. 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](http://www.jfree.org/jfreesvg/javadoc/doc-files/SVGTimeSeriesChartDemo1.svg) The home page for the project is: http://www.jfree.org/jfreesvg/ 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 4.1 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 Build ----- You can build `JFreeSVG` from sources using Maven: mvn clean install 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). If you prefer not to be bound by the terms of the GPLv3, you can purchase an alternative license from Object Refinery Limited (please e-mail info@object-refinery.com for details, or check the JFreeSVG home page). 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. Change History -------------- Version 4.1 (26 March 2020) - correction of fix for encoding of images (bug#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. Contact / Questions ------------------- If you have any questions or feedback about JFreeSVG, please post in the forum: http://www.jfree.org/forum/viewforum.php?f=32 ...or send an e-mail to david.gilbert@object-refinery.com. jfreesvg-4.1/pom.xml000066400000000000000000000127411363710745600145270ustar00rootroot00000000000000 4.0.0 org.jfree org.jfree.svg 4.1 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 junit junit 4.12 test org.apache.maven.plugins maven-compiler-plugin 3.8.1 11 11 -Xlint:unchecked ${project.build.sourceEncoding} org.apache.maven.plugins maven-javadoc-plugin 3.1.1 true true ossrh https://oss.sonatype.org/content/repositories/snapshots release org.apache.maven.plugins maven-gpg-plugin 1.5 sign-artifacts verify sign org.sonatype.plugins nexus-staging-maven-plugin 1.6.7 true ossrh https://oss.sonatype.org/ false org.apache.maven.plugins maven-javadoc-plugin 3.1.1 true true attach-javadoc jar org.apache.maven.plugins maven-source-plugin 3.2.0 attach-sources jar-no-fork jfreesvg-4.1/src/000077500000000000000000000000001363710745600137745ustar00rootroot00000000000000jfreesvg-4.1/src/main/000077500000000000000000000000001363710745600147205ustar00rootroot00000000000000jfreesvg-4.1/src/main/java/000077500000000000000000000000001363710745600156415ustar00rootroot00000000000000jfreesvg-4.1/src/main/java/module-info.java000066400000000000000000000001521363710745600207200ustar00rootroot00000000000000module org.jfree.svg { requires java.desktop; requires java.logging; exports org.jfree.svg; } jfreesvg-4.1/src/main/java/org/000077500000000000000000000000001363710745600164305ustar00rootroot00000000000000jfreesvg-4.1/src/main/java/org/jfree/000077500000000000000000000000001363710745600175235ustar00rootroot00000000000000jfreesvg-4.1/src/main/java/org/jfree/svg/000077500000000000000000000000001363710745600203225ustar00rootroot00000000000000jfreesvg-4.1/src/main/java/org/jfree/svg/FontMapper.java000066400000000000000000000037331363710745600232460ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-2020, by Object Refinery Limited. 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 object that can (optionally) translate one font family name to an * alternative. A {@code FontMapper} is assigned to an * {@link SVGGraphics2D} instance. The default implementation will map * Java logical font names to the equivalent SVG generic font names. * * @since 1.5 */ public interface FontMapper { /** * Maps the specified font family name to an alternative, or else returns * the same family name. * * @param family the font family name ({@code null} not permitted). * * @return The same font family name or an alternative (never {@code null}). */ String mapFont(String family); } jfreesvg-4.1/src/main/java/org/jfree/svg/ImageElement.java000066400000000000000000000061301363710745600235210ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-2020, by Object Refinery Limited. 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-4.1/src/main/java/org/jfree/svg/MeetOrSlice.java000066400000000000000000000033341363710745600233430ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-2020, by Object Refinery Limited. 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-4.1/src/main/java/org/jfree/svg/PreserveAspectRatio.java000066400000000000000000000043531363710745600251240ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-2020, by Object Refinery Limited. 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-4.1/src/main/java/org/jfree/svg/SVGGraphics2D.java000066400000000000000000003225221363710745600235010ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-2020, by Object Refinery Limited. 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.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.text.DecimalFormat; import java.text.DecimalFormatSymbols; 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.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: *
    *
  • 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;
  • * *
  • 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);
  • * *
  • there are settings to control the number of decimal places used to * write the coordinates for geometrical elements (default 2dp) and transform * matrices (default 6dp). These defaults may change in a future release.
  • * *
  • 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. We auto-populate 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-"; private final int width; private final int height; private final SVGUnits units; /** * The shape rendering property to set for the SVG element. Permitted * values are "auto", "crispEdges", "geometricPrecision" and * "optimizeSpeed". */ private String shapeRendering = "auto"; /** * The text rendering property for the SVG element. Permitted values * are "auto", "optimizeSpeed", "optimizeLegibility" and * "geometricPrecision". */ private String textRendering = "auto"; /** 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 number of decimal places to use when writing the matrix values * for transformations. */ private int transformDP; /** * The decimal formatter for transform matrices. */ private DecimalFormat transformFormat; /** * The number of decimal places to use when writing coordinates for * geometrical shapes. */ private int geometryDP; /** * The decimal formatter for coordinates of geometrical shapes. */ private DecimalFormat geometryFormat; /** The buffer that accumulates the SVG output. */ private 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. */ private String defsKeyPrefix = ""; /** * 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 #KEY_IMAGE_HREF} hint. */ private String filePrefix; /** * The filename suffix for images that are referenced rather than * embedded but don't have an {@code href} supplied via the * {@link #KEY_IMAGE_HREF} hint. */ private String fileSuffix; /** * 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(); 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; /** * 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); /** Maps font family names to alternates (or leaves them unchanged). */ private FontMapper fontMapper; /** The background color, used by clearRect(). */ private Color background = Color.BLACK; /** A hidden image used for font metrics. */ private BufferedImage fmImage; 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. */ 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 lazily instantiated in draw/fillArc and then * subsequently reused to avoid creating a lot of garbage. */ private Arc2D arc; /** * 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. */ private String gradientPaintRef = null; /** * 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(int width, int 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. * * @since 3.2 */ public SVGGraphics2D(int width, int height, SVGUnits units) { this(width, height, units, new StringBuilder()); } /** * Creates a new instance with the specified width and height that will * populate the supplied StringBuilder instance. This constructor is * used by the {@link #create()} method, but won't normally be called * directly by user code. * * @param width the width of the SVG element. * @param height the height of the SVG element. * @param sb the string builder ({@code null} not permitted). * * @since 2.0 */ public SVGGraphics2D(int width, int height, StringBuilder sb) { this(width, height, null, sb); } /** * Creates a new instance with the specified width and height that will * populate the supplied StringBuilder instance. This constructor is * used by the {@link #create()} method, but won't normally be called * directly by user code. * * @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 above ({@code null} * permitted). * @param sb the string builder ({@code null} not permitted). * * @since 3.2 */ public SVGGraphics2D(int width, int height, SVGUnits units, StringBuilder sb) { this.width = width; this.height = height; this.units = units; this.shapeRendering = "auto"; this.textRendering = "auto"; this.defsKeyPrefix = "_" + String.valueOf(System.nanoTime()); this.clip = null; this.imageElements = new ArrayList<>(); this.filePrefix = "image-"; this.fileSuffix = ".png"; this.font = new Font("SansSerif", Font.PLAIN, 12); this.fontMapper = new StandardFontMapper(); this.zeroStrokeWidth = 0.1; this.sb = sb; this.hints = new RenderingHints(SVGHints.KEY_IMAGE_HANDLING, SVGHints.VALUE_IMAGE_HANDLING_EMBED); // force the formatters to use a '.' for the decimal point DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setDecimalSeparator('.'); this.transformFormat = new DecimalFormat("0.######", dfs); this.geometryFormat = new DecimalFormat("0.##", dfs); 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(SVGGraphics2D parent) { this(parent.width, parent.height, parent.units, parent.sb); this.shapeRendering = parent.shapeRendering; this.textRendering = parent.textRendering; this.fontMapper = parent.fontMapper; getRenderingHints().add(parent.hints); this.checkStrokeControlHint = parent.checkStrokeControlHint; setTransformDP(parent.transformDP); setGeometryDP(parent.geometryDP); 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 int 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 int 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 value of the 'shape-rendering' property that will be * written to the SVG element. The default value is "auto". * * @return The shape rendering property. * * @since 2.0 */ public String getShapeRendering() { return this.shapeRendering; } /** * Sets the value of the 'shape-rendering' property that will be written to * the SVG element. Permitted values are "auto", "crispEdges", * "geometricPrecision", "inherit" and "optimizeSpeed". * * @param value the new value. * * @since 2.0 */ public void setShapeRendering(String value) { if (!value.equals("auto") && !value.equals("crispEdges") && !value.equals("geometricPrecision") && !value.equals("optimizeSpeed")) { throw new IllegalArgumentException("Unrecognised value: " + value); } this.shapeRendering = value; } /** * Returns the value of the 'text-rendering' property that will be * written to the SVG element. The default value is "auto". * * @return The text rendering property. * * @since 2.0 */ public String getTextRendering() { return this.textRendering; } /** * Sets the value of the 'text-rendering' property that will be written to * the SVG element. Permitted values are "auto", "optimizeSpeed", * "optimizeLegibility" and "geometricPrecision". * * @param value the new value. * * @since 2.0 */ public void setTextRendering(String value) { if (!value.equals("auto") && !value.equals("optimizeSpeed") && !value.equals("optimizeLegibility") && !value.equals("geometricPrecision")) { throw new IllegalArgumentException("Unrecognised value: " + value); } this.textRendering = value; } /** * 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 number of decimal places used to write the transformation * matrices in the SVG output. The default value is 6. *

* Note that there is a separate attribute to control the number of decimal * places for geometrical elements in the output (see * {@link #getGeometryDP()}). * * @return The number of decimal places. * * @see #setTransformDP(int) */ public int getTransformDP() { return this.transformDP; } /** * Sets the number of decimal places used to write the transformation * matrices in the SVG output. Values in the range 1 to 10 will be used * to configure a formatter to that number of decimal places, for all other * values we revert to the normal {@code String} conversion of * {@code double} primitives (approximately 16 decimals places). *

* Note that there is a separate attribute to control the number of decimal * places for geometrical elements in the output (see * {@link #setGeometryDP(int)}). * * @param dp the number of decimal places (normally 1 to 10). * * @see #getTransformDP() */ public void setTransformDP(int dp) { this.transformDP = dp; if (dp < 1 || dp > 10) { this.transformFormat = null; return; } DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setDecimalSeparator('.'); this.transformFormat = new DecimalFormat("0." + "##########".substring(0, dp), dfs); } /** * Returns the number of decimal places used to write the coordinates * of geometrical shapes. The default value is 2. *

* Note that there is a separate attribute to control the number of decimal * places for transform matrices in the output (see * {@link #getTransformDP()}). * * @return The number of decimal places. */ public int getGeometryDP() { return this.geometryDP; } /** * Sets the number of decimal places used to write the coordinates of * geometrical shapes in the SVG output. Values in the range 1 to 10 will * be used to configure a formatter to that number of decimal places, for * all other values we revert to the normal String conversion of double * primitives (approximately 16 decimals places). *

* Note that there is a separate attribute to control the number of decimal * places for transform matrices in the output (see * {@link #setTransformDP(int)}). * * @param dp the number of decimal places (normally 1 to 10). */ public void setGeometryDP(int dp) { this.geometryDP = dp; if (dp < 1 || dp > 10) { this.geometryFormat = null; return; } DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setDecimalSeparator('.'); this.geometryFormat = new DecimalFormat("0." + "##########".substring(0, dp), dfs); } /** * 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(this.width, 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 fontMapper} object ({@link #getFontMapper()}) 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); String ref = this.gradientPaints.get(key); if (ref == null) { int count = this.gradientPaints.keySet().size(); String id = this.defsKeyPrefix + "gp" + count; this.elementIDs.add(id); this.gradientPaints.put(key, id); this.gradientPaintRef = id; } else { this.gradientPaintRef = ref; } } else if (paint instanceof LinearGradientPaint) { LinearGradientPaint lgp = (LinearGradientPaint) paint; LinearGradientPaintKey key = new LinearGradientPaintKey(lgp); String ref = this.linearGradientPaints.get(key); if (ref == null) { int count = this.linearGradientPaints.keySet().size(); String id = this.defsKeyPrefix + "lgp" + count; this.elementIDs.add(id); this.linearGradientPaints.put(key, id); this.gradientPaintRef = id; } } else if (paint instanceof RadialGradientPaint) { RadialGradientPaint rgp = (RadialGradientPaint) paint; RadialGradientPaintKey key = new RadialGradientPaintKey(rgp); String ref = this.radialGradientPaints.get(key); if (ref == null) { int count = this.radialGradientPaints.keySet().size(); String id = this.defsKeyPrefix + "rgp" + count; this.elementIDs.add(id); this.radialGradientPaints.put(key, id); this.gradientPaintRef = 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("\n"); } 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 sb the string builder ({@code null} not permitted). */ private void appendOptionalElementIDFromHint(StringBuilder sb) { 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); } this.sb.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("d=\""); float[] coords = new float[6]; boolean first = true; PathIterator iterator = path.getPathIterator(null); while (!iterator.isDone()) { int type = iterator.currentSegment(coords); if (!first) { b.append(" "); } first = false; 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. * * @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()) .append(";"); if (!strokeCap.equals(DEFAULT_STROKE_CAP)) { b.append("stroke-linecap: ").append(strokeCap).append(";"); } if (!strokeJoin.equals(DEFAULT_STROKE_JOIN)) { b.append("stroke-linejoin: ").append(strokeJoin).append(";"); } 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]); } b.append(";"); } if (this.checkStrokeControlHint) { Object hint = getRenderingHint(RenderingHints.KEY_STROKE_CONTROL); if (RenderingHints.VALUE_STROKE_NORMALIZE.equals(hint) && !this.shapeRendering.equals("crispEdges")) { b.append("shape-rendering:crispEdges;"); } if (RenderingHints.VALUE_STROKE_PURE.equals(hint) && !this.shapeRendering.equals("geometricPrecision")) { 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()).append("; "); b.append("fill-opacity: ").append(getColorAlpha() * getAlpha()); 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 font mapper (an object that optionally maps font family * names to alternates). The default mapper will convert Java logical * font names to the equivalent SVG generic font name, and leave all other * font names unchanged. * * @return The font mapper (never {@code null}). * * @see #setFontMapper(org.jfree.svg.FontMapper) * @since 1.5 */ public FontMapper getFontMapper() { return this.fontMapper; } /** * Sets the font mapper. * * @param mapper the font mapper ({@code null} not permitted). * * @since 1.5 */ public void setFontMapper(FontMapper mapper) { Args.nullNotPermitted(mapper, "mapper"); this.fontMapper = mapper; } /** * 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.fontMapper.mapFont(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;"); } 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; } private String transformDP(double d) { if (this.transformFormat != null) { return transformFormat.format(d); } else { return String.valueOf(d); } } private String geomDP(double d) { if (this.geometryFormat != null) { return geometryFormat.format(d); } else { return String.valueOf(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, but there is an open bug report (since 2004) * that suggests this is wrong: *

* * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6206189 * * @param s the clip shape ({@code null} not permitted). */ @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) { setArc(x, y, width, height, startAngle, arcAngle); 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) { setArc(x, y, width, height, startAngle, arcAngle); 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 or // referenced... Object hint = getRenderingHint(SVGHints.KEY_IMAGE_HANDLING); if (SVGHints.VALUE_IMAGE_HANDLING_EMBED.equals(hint)) { this.sb.append("\n"); return true; } else { // here for SVGHints.VALUE_IMAGE_HANDLING_REFERENCE 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... 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("\n"); 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) { Paint saved = getPaint(); setPaint(bgcolor); fillRect(x, y, w, h); setPaint(saved); return drawImage(img, x, y, w, h, observer); } /** * 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("\n"); StringBuilder defs = new StringBuilder(""); for (GradientPaintKey key : this.gradientPaints.keySet()) { defs.append(getLinearGradientElement(this.gradientPaints.get(key), key.getPaint())); defs.append("\n"); } for (LinearGradientPaintKey key : this.linearGradientPaints.keySet()) { defs.append(getLinearGradientElement( this.linearGradientPaints.get(key), key.getPaint())); defs.append("\n"); } for (RadialGradientPaintKey key : this.radialGradientPaints.keySet()) { defs.append(getRadialGradientElement( this.radialGradientPaints.get(key), key.getPaint())); defs.append("\n"); } for (int i = 0; i < this.clipPaths.size(); i++) { StringBuilder b = new StringBuilder(""); b.append(""); b.append("").append("\n"); defs.append(b.toString()); } defs.append("\n"); svg.append(defs); svg.append(this.sb); svg.append(""); return svg.toString(); } /** * 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 Arc2D} object that is used by * {@link #drawArc(int, int, int, int, int, int)} and * {@link #fillArc(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 startAngle the start angle in degrees, 0 = 3 o'clock. * @param arcAngle the angle (anticlockwise) in degrees. */ private void setArc(int x, int y, int width, int height, int startAngle, int arcAngle) { if (this.arc == null) { this.arc = new Arc2D.Double(x, y, width, height, startAngle, arcAngle, Arc2D.PIE); } else { this.arc.setArc(x, y, width, height, startAngle, arcAngle, Arc2D.PIE); } } /** * 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-4.1/src/main/java/org/jfree/svg/SVGGraphicsConfiguration.java000066400000000000000000000133731363710745600260440ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-2020, by Object Refinery Limited. 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-4.1/src/main/java/org/jfree/svg/SVGGraphicsDevice.java000066400000000000000000000053361363710745600244340ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-2020, by Object Refinery Limited. 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; 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-4.1/src/main/java/org/jfree/svg/SVGHints.java000066400000000000000000000477701363710745600226510ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-2020, by Object Refinery Limited. 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 an id equal to the hint value (which must * be an instance of String). 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 the id for * the new group. 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 e) { return null; } catch (NoSuchFieldException ex) { return null; } catch (SecurityException ex) { return null; } catch (IllegalArgumentException ex) { return null; } catch (IllegalAccessException ex) { 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 return val == null || val instanceof String; case 3: // KEY_ELEMENT_ID return val == null || val instanceof String; 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-4.1/src/main/java/org/jfree/svg/SVGUnits.java000066400000000000000000000037431363710745600226560ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-2020, by Object Refinery Limited. 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-4.1/src/main/java/org/jfree/svg/SVGUtils.java000066400000000000000000000150001363710745600226410ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-2020, by Object Refinery Limited. 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.util.logging.Level; import java.util.logging.Logger; import java.util.zip.GZIPOutputStream; import org.jfree.svg.util.Args; /** * 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, "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, "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); } } } } jfreesvg-4.1/src/main/java/org/jfree/svg/StandardFontMapper.java000066400000000000000000000071531363710745600247270ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-2020, by Object Refinery Limited. 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 org.jfree.svg.util.Args; /** * A default implementation of the {@link FontMapper} interface. This * implementation will map the Java logical fonts to equivalent SVG generic * fonts. You can add your own mappings if you need to. * * @since 1.5 */ public class StandardFontMapper implements FontMapper { /** Storage for the alternates. */ private final Map alternates; /** * Creates a new instance with mappings for the Java logical fonts. */ public StandardFontMapper() { 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 mapped (alternate) font family name. * * @param family the font family ({@code null} not permitted). * * @return The alternate font family name (possibly {@code null}). */ public String get(String family) { Args.nullNotPermitted(family, "family"); return this.alternates.get(family); } /** * Adds a font family mapping (if the specified alternate is * {@code null} it has the effect of clearing any existing mapping). * * @param family the font family name ({@code null} not permitted). * @param alternate the alternate ({@code null} permitted). */ public void put(String family, String alternate) { Args.nullNotPermitted(family, "family"); this.alternates.put(family, alternate); } /** * Maps the specified font family name to an alternative, or else returns * the same family name. * * @param family the font family name ({@code null} not permitted). * * @return The same font family name or an alternative (never {@code null}). */ @Override public String mapFont(String family) { Args.nullNotPermitted(family, "family"); String alternate = this.alternates.get(family); if (alternate != null) { return alternate; } return family; } } jfreesvg-4.1/src/main/java/org/jfree/svg/ViewBox.java000066400000000000000000000045341363710745600225560ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-2020, by Object Refinery Limited. 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; /** * Represents a view box in SVG. * * @since 3.2 */ public class ViewBox { private final int minX; private final int minY; private final int width; private final int 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(int minX, int minY, int width, int height) { this.minX = minX; this.minY = minY; this.width = width; this.height = height; } /** * Returns a string containing the view box coordinates and dimensions. * * @return A string containing the view box coordinates and dimensions. */ public String valueStr() { return new StringBuilder().append(this.minX).append(" ") .append(this.minY).append(" ").append(this.width).append(" ") .append(this.height).toString(); } } jfreesvg-4.1/src/main/java/org/jfree/svg/package-info.java000066400000000000000000000002561363710745600235140ustar00rootroot00000000000000/** * Contains {@link org.jfree.svg.SVGGraphics2D} and supporting classes that allow * Java2D rendering to Scalable Vector Graphics (SVG) format. */ package org.jfree.svg;jfreesvg-4.1/src/main/java/org/jfree/svg/util/000077500000000000000000000000001363710745600212775ustar00rootroot00000000000000jfreesvg-4.1/src/main/java/org/jfree/svg/util/Args.java000066400000000000000000000064371363710745600230500ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-2020, by Object Refinery Limited. 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 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-4.1/src/main/java/org/jfree/svg/util/GradientPaintKey.java000066400000000000000000000076301363710745600253520ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-2020, by Object Refinery Limited. 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-4.1/src/main/java/org/jfree/svg/util/GraphicsUtils.java000066400000000000000000000136331363710745600247310ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-2020, by Object Refinery Limited. 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 (int i = 0; i < keys.length; i++) { properties.put(keys[i], img.getProperty(keys[i])); } } BufferedImage result = new BufferedImage(cm, raster, isAlphaPremultiplied, properties); img.copyData(raster); return result; } } jfreesvg-4.1/src/main/java/org/jfree/svg/util/LinearGradientPaintKey.java000066400000000000000000000074201363710745600265020ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-2020, by Object Refinery Limited. 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 LinearGradientPaint)) { return false; } LinearGradientPaint that = (LinearGradientPaint) obj; 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-4.1/src/main/java/org/jfree/svg/util/RadialGradientPaintKey.java000066400000000000000000000075121363710745600264660ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-2020, by Object Refinery Limited. 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 RadialGradientPaint)) { return false; } RadialGradientPaint that = (RadialGradientPaint) obj; 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-4.1/src/main/java/org/jfree/svg/util/package-info.java000066400000000000000000000002341363710745600244650ustar00rootroot00000000000000/** * An internal package for the JFreeSVG library. This package * contains utility and other supporting classes. */ package org.jfree.svg.util;jfreesvg-4.1/src/test/000077500000000000000000000000001363710745600147535ustar00rootroot00000000000000jfreesvg-4.1/src/test/java/000077500000000000000000000000001363710745600156745ustar00rootroot00000000000000jfreesvg-4.1/src/test/java/org/000077500000000000000000000000001363710745600164635ustar00rootroot00000000000000jfreesvg-4.1/src/test/java/org/jfree/000077500000000000000000000000001363710745600175565ustar00rootroot00000000000000jfreesvg-4.1/src/test/java/org/jfree/svg/000077500000000000000000000000001363710745600203555ustar00rootroot00000000000000jfreesvg-4.1/src/test/java/org/jfree/svg/TestSVGGraphics2D.java000066400000000000000000000663271363710745600244040ustar00rootroot00000000000000/* =================================================== * JFreeSVG : an SVG library for the Java(tm) platform * =================================================== * * (C)opyright 2013-2020, by Object Refinery Limited. 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.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; 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.jfree.svg.SVGGraphics2D; import org.jfree.svg.SVGHints; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; /** * 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). */ public class TestSVGGraphics2D { private Graphics2D g2; @Before public void setUp() { // 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(); // Test SVGGraphics2D... this.g2 = new SVGGraphics2D(10, 20); } /** * Checks that the default transform is an identity transform. */ @Test public 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 public 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 public 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); //Assert.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 public 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 public 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 public 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 public 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 public 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 public 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 public 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 public 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 public 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 public void checkGetClipSafety() { Rectangle2D r = new Rectangle2D.Double(0, 0, 1, 1); this.g2.setClip(r); Shape s = this.g2.getClip(); assertFalse(r == s); Shape s2 = this.g2.getClip(); assertFalse(s == s2); } /** * The default user clip should be null. */ @Test public void checkDefaultClip() { assertNull("Default user clip should be null.", g2.getClip()); } /** * Checks that getClipBounds() is returning an integer approximation of * the bounds. */ @Test public 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 public 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 public 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()); } @Test public 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 public 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 public 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 public 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 public 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? Switching off the test for now. */ @Test @Ignore public 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()); } /** * A simple check for a call to clipRect(). */ @Test public 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 public 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 public 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 public 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 public 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 public 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()); assertTrue(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 public 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 public 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()); } @Test public 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 public 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 public void checkSetBackground() { this.g2.setBackground(Color.CYAN); assertEquals(Color.CYAN, this.g2.getBackground()); assertFalse(Color.CYAN.equals(this.g2.getColor())); assertFalse(Color.CYAN.equals(this.g2.getPaint())); } /** * The behaviour of the reference implementation has been observed as * allowing null (this is inconsistent with the behaviour of setColor()). */ @Test public void checkSetBackgroundNull() { this.g2.setBackground(Color.RED); this.g2.setBackground(null); assertEquals(null, 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 public 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 public void checkSetCompositeNull() { try { this.g2.setComposite(null); fail("Expected an IllegalArgumentException."); } catch (IllegalArgumentException e) { // this exception is expected in the test } } @Test public 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 public 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 public 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 public void checkGetRenderingHintWithNullKey() { assertNull(this.g2.getRenderingHint(null)); } /** * Check setting a hint with a value that doesn't match the key. */ @Test public 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 public 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 public void checkSetRenderingHintsNull() { try { this.g2.setRenderingHints(null); fail("NullPointerException expected."); } catch (NullPointerException e) { // this is expected } } @Test public 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 public 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 public 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 public 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 NullPointerException. */ @Test public void drawGlyphVectorNull() { try { g2.drawGlyphVector(null, 10, 10); fail("Expecting a NullPointerException."); } catch (NullPointerException e) { // expected } } /** * Check the shear() method. */ @Test public 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 public 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 public 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 public 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 public 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 public 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)); } /** * A test to check whether setting a transform on the Graphics2D affects * the results of text measurements performed via getFontMetrics(). */ @Test public 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 public 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 public void drawRenderedImageWithNullImage() { g2.drawRenderedImage(null, AffineTransform.getTranslateInstance(0, 0)); assertTrue(true); // won't get here if there's an exception above } }