libcobra-java-0.98.4.orig/0000755000175000017500000000000011134672336015213 5ustar twernertwernerlibcobra-java-0.98.4.orig/lib/0000755000175000017500000000000011134672336015761 5ustar twernertwernerlibcobra-java-0.98.4.orig/COBRA-README.txt0000644000175000017500000000033110630211126017514 0ustar twernertwernerPlease see http://html.xamjwg.org/cobra.jsp for additional information on this toolkit. See the LICENSE.txt file for Cobra licensing and the COBRA-ACK.txt file for licensing information on Cobra dependencies. libcobra-java-0.98.4.orig/COBRA-ACK.txt0000644000175000017500000000166210743401044017172 0ustar twernertwernerThe following externals are used by this project: * [http://www.mozilla.org/rhino/] Rhino - Javascript for Java (MPL/GPL) We are using Rhino to process Javascript embedded in HTML documents. Rhino binaries (js.jar under the lib directory) are redistributed unmodified. We use Rhino 1.6R5 which is released under a dual MPL/GPL license. Note that the GPL license is applicable in this case, as that is the license that is compatible with the LGPL. Users should observe the GPL license of Rhino. * [http://cssparser.sourceforge.net/] Cssparser (LGPL) We use it to parse CSS code. We distribute its source code (modified) with Cobra. It is also available in CVS in module XAMJ_Project/cssparser. * [http://w3c.org] W3C DOM Java Bindings (W3C Software Copyright Notice and License) We implement these DOM interfaces. Source redistributed unmodified. See package org.w3c.dom.html2. libcobra-java-0.98.4.orig/LICENSE.txt0000644000175000017500000006343710603777472017062 0ustar twernertwerner GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Cobra is an HTML Toolkit for Java Copyright (C) 2007 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Website: http://xamjwg.orglibcobra-java-0.98.4.orig/src/0000755000175000017500000000000011134672336016002 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/0000755000175000017500000000000010641432632016564 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/lobobrowser/0000755000175000017500000000000010641432704021123 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/lobobrowser/html/0000755000175000017500000000000011125630302022057 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/lobobrowser/html/AbstractHtmlRendererContext.java0000644000175000017500000001070011126720504030351 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html; import java.awt.event.MouseEvent; import java.net.URL; import org.w3c.dom.html2.HTMLCollection; import org.w3c.dom.html2.HTMLElement; import org.w3c.dom.html2.HTMLLinkElement; /** * Abstract implementation of the {@link HtmlRendererContext} interface with * blank methods, provided for developer convenience. */ public abstract class AbstractHtmlRendererContext implements HtmlRendererContext { public void alert(String message) { } public void back() { } public void blur() { } public void close() { } public boolean confirm(String message) { return false; } public BrowserFrame createBrowserFrame() { return null; } public void focus() { } public String getDefaultStatus() { return null; } public HTMLCollection getFrames() { return null; } public HtmlObject getHtmlObject(HTMLElement element) { return null; } public String getName() { return null; } public HtmlRendererContext getOpener() { return null; } public HtmlRendererContext getParent() { return null; } public String getStatus() { return null; } public HtmlRendererContext getTop() { return null; } public UserAgentContext getUserAgentContext() { return null; } /** * Returns false unless overridden. */ public boolean isClosed() { return false; } /** * Returns true unless overridden. */ public boolean isImageLoadingEnabled() { return true; } /** * Returns false unless overridden. */ public boolean isVisitedLink(HTMLLinkElement link) { return false; } public void linkClicked(HTMLElement linkNode, URL url, String target) { } public void navigate(URL url, String target) { } /** * Returns true unless overridden. */ public boolean onContextMenu(HTMLElement element, MouseEvent event) { return true; } public void onMouseOut(HTMLElement element, MouseEvent event) { } public void onMouseOver(HTMLElement element, MouseEvent event) { } public HtmlRendererContext open(String absoluteUrl, String windowName, String windowFeatures, boolean replace) { return null; } public HtmlRendererContext open(URL url, String windowName, String windowFeatures, boolean replace) { return null; } public String prompt(String message, String inputDefault) { return null; } public void reload() { } public void scroll(int x, int y) { } public void setDefaultStatus(String value) { } public void setOpener(HtmlRendererContext opener) { } public void setStatus(String message) { } public void submitForm(String method, URL action, String target, String enctype, FormInput[] formInputs) { } /** * Returns true unless overridden. */ public boolean onDoubleClick(HTMLElement element, MouseEvent event) { return true; } /** * Returns true unless overridden. */ public boolean onMouseClick(HTMLElement element, MouseEvent event) { return true; } public void scrollBy(int x, int y) { } public void resizeBy(int byWidth, int byHeight) { } public void resizeTo(int width, int height) { } public void forward() { } public String getCurrentURL() { return null; } public int getHistoryLength() { return 0; } public String getNextURL() { return null; } public String getPreviousURL() { return null; } public void goToHistoryURL(String url) { } public void moveInHistory(int offset) { } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/BrowserFrame.java0000644000175000017500000000444711134671040025335 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 29, 2006 */ package org.lobobrowser.html; import java.awt.Component; import java.net.URL; import org.w3c.dom.*; /** * The BrowserFrame interface represents a browser frame. * A simple implementation of this interface is * provided in {@link org.lobobrowser.html.test.SimpleBrowserFrame}. */ public interface BrowserFrame { /** * Gets the component that renders the frame. * This can be a {@link org.lobobrowser.html.gui.HtmlPanel}. */ public Component getComponent(); /** * Loads a URL in the frame. */ public void loadURL(URL url); /** * Gets the content document. */ public Document getContentDocument(); /** * Gets the {@link HtmlRendererContext} of the frame. */ public HtmlRendererContext getHtmlRendererContext(); /** * Sets the default margin insets of the browser frame. * @param insets The margin insets. */ public void setDefaultMarginInsets(java.awt.Insets insets); /** * Sets the default horizontal overflow of the browser frame. * @param overflowX See constants in {@link org.lobobrowser.html.style.RenderState}. */ public void setDefaultOverflowX(int overflowX); /** * Sets the default vertical overflow of the browser frame. * @param overflowY See constants in {@link org.lobobrowser.html.style.RenderState}. */ public void setDefaultOverflowY(int overflowY); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/FormInput.java0000644000175000017500000000722210750307714024663 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 15, 2006 */ package org.lobobrowser.html; /** * The FormInput class contains the state * of an HTML form input item. */ public class FormInput { //private final InputStream inputStream; //private final String charset; public static final FormInput[] EMPTY_ARRAY = new FormInput[0]; private final String name; private final String textValue; private final java.io.File fileValue; /** * Constructs a FormInput * with a text value. * @param name The name of the input. * @param value The value of the input. */ public FormInput(String name, String value) { super(); this.name = name; this.textValue = value; this.fileValue = null; } /** * Constructs a FormInput * with a file value. * @param name The name of the input. * @param value The value of the input. */ public FormInput(String name, java.io.File value) { this.name = name; this.textValue = null; this.fileValue = value; } /** * Gets the name of the input. */ public String getName() { return this.name; } /** * Returns true if the form input holds a text value. */ public boolean isText() { return this.textValue != null; } /** * Returns true if the form input holds a file value. */ public boolean isFile() { return this.fileValue != null; } /** * Gets the text value of the form input. * If the form input does not hold a text value, * this method should not be called. * @see #isText() */ public String getTextValue() { return this.textValue; } /** * Gets the file value of the form input. * If the form input does not hold a file * value, this method should not be called. * @see #isFile() */ public java.io.File getFileValue() { return this.fileValue; } /** * Always returns UTF-8. * @deprecated The method is implemented only to provide some backward compatibility. */ public String getCharset() { return "UTF-8"; } /** * Gets data as an input stream. The caller * is responsible for closing the stream. * @deprecated Call either {@link #getTextValue()} or {@link #getFileValue()} instead. */ public java.io.InputStream getInputStream() throws java.io.IOException { if(this.isText()) { return new java.io.ByteArrayInputStream(this.getTextValue().getBytes("UTF-8")); } else if(this.isFile()) { return new java.io.FileInputStream(this.getFileValue()); } else { return null; } } /** * Shows a string representation of the FormInput * that may be useful in debugging. * @see #getTextValue() */ public String toString() { return "FormInput[name=" + this.name + ",textValue=" + this.textValue + "]"; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/HtmlObject.java0000644000175000017500000000121610641432374024770 0ustar twernertwernerpackage org.lobobrowser.html; import java.awt.*; /** * This interface should be implemented to provide * OBJECT, EMBED or APPLET functionality. */ public interface HtmlObject { public Component getComponent(); public void suspend(); public void resume(); public void destroy(); /** * Called as the object is layed out, either * the first time it's layed out or whenever * the DOM changes. This is where the object * should reset its state based on element * children or attributes and possibly change * its preferred size if appropriate. */ public void reset(int availableWidth, int availableHeight); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/HtmlRendererContext.java0000644000175000017500000002507611126720412026677 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Aug 28, 2005 */ package org.lobobrowser.html; import java.net.URL; import org.w3c.dom.html2.*; /** * The HtmlRendererContext interface must be implemented * in order to use the Cobra HTML renderer. An instance of this interface * will be called back whenever the renderer needs to perform an action that * it is not designed to know how to perform on its own, e.g. opening a browser window * or a context menu. In many ways this * interface parallers the Javascript Window class (which * in reality represents a browser frame, not a window). *

* A simple implementation of this interface is provided in * {@link org.lobobrowser.html.test.SimpleHtmlRendererContext SimpleHtmlRendererContext}. * @see org.lobobrowser.html.gui.HtmlPanel#setDocument(org.w3c.dom.Document, HtmlRendererContext) */ public interface HtmlRendererContext { /** * Navigates to the location given. Implementations should * retrieve the URL content, parse it and render it. * @param url The destination URL. * @param target Same as the target attribute in the HTML anchor tag, i.e. _top, _blank, etc. */ public void navigate(URL url, String target); /** * Performs a link click. Implementations should * invoke {@link #navigate(URL, String)}. * @param linkNode The HTML node that was clicked. * @param url The destination URL. * @param target Same as the target attribute in the HTML anchor tag, i.e. _top, _blank, etc. */ public void linkClicked(org.w3c.dom.html2.HTMLElement linkNode, URL url, String target); /** * Gets a collection of frames from the document * currently in the context. */ public HTMLCollection getFrames(); /** * Submits a HTML form. Note that when the the method is "GET", parameters * are still expected to be part of formInputs. * @param method The request method, GET or POST. * @param action The destination URL. * @param target Same as the target attribute in the FORM tag, i.e. _blank, _top, etc. * @param enctype The encoding type. * @param formInputs An array of {@link org.lobobrowser.html.FormInput} instances. */ public void submitForm(String method, URL action, String target, String enctype, FormInput[] formInputs); /** * Creates a {@link org.lobobrowser.html.BrowserFrame} instance. */ public BrowserFrame createBrowserFrame(); /** * Gets the user agent context. */ public UserAgentContext getUserAgentContext(); /** * Gets a HtmlObject instance that implements * a OBJECT tag from HTML. * @param element The DOM element for the object, which may * either represent an OBJECT, EMBED or an APPLET tag. * @return Implementations of this method must return null * if they have any problems producing a HtmlObject instance. * This is particularly true of OBJECT tags, where inner HTML of * the tag must be rendered if the OBJECT content cannot be handled. */ public HtmlObject getHtmlObject(org.w3c.dom.html2.HTMLElement element); /** * This method is called when a visual element is right-clicked. * @param element The narrowest element enclosing the mouse location. * @param event The mouse event. * @return The method should return true to continue propagating the event, * or false to stop propagating it. */ public boolean onContextMenu(org.w3c.dom.html2.HTMLElement element, java.awt.event.MouseEvent event); /** * This method is called when there's a mouse click on an element. * @param element The narrowest element enclosing the mouse location. * @param event The mouse event. * @return The method should return true to continue propagating the event, * or false to stop propagating it. */ public boolean onMouseClick(org.w3c.dom.html2.HTMLElement element, java.awt.event.MouseEvent event); /** * This method is called when there's a mouse double-click on an element. * @param element The narrowest element enclosing the mouse location. * @param event The mouse event. * @return The method should return true to continue propagating the event, * or false to stop propagating it. */ public boolean onDoubleClick(org.w3c.dom.html2.HTMLElement element, java.awt.event.MouseEvent event); /** * This method is called when the mouse first hovers over an element. * @param element The element that the mouse has just entered. * @param event The mouse event. */ public void onMouseOver(org.w3c.dom.html2.HTMLElement element, java.awt.event.MouseEvent event); /** * This method is called when the mouse no longer hovers a given element. * @param element The element that the mouse has just exited. * @param event The mouse event. */ public void onMouseOut(org.w3c.dom.html2.HTMLElement element, java.awt.event.MouseEvent event); /** * This method should return true if and only if image loading * needs to be enabled. */ public boolean isImageLoadingEnabled(); //------ Methods useful for Window implementation: /** * Opens an alert dialog. * @param message Message shown by the dialog. */ public void alert(String message); /** * Goes to the previous page in the browser's history. */ public void back(); /** * Relinquishes focus. */ public void blur(); /** * Closes the browser window, provided this * is allowed for the current context. */ public void close(); /** * Opens a confirmation dialog. * @param message The message shown by the confirmation dialog. * @return True if the user selects YES. */ public boolean confirm(String message); /** * Requests focus for the current window. */ public void focus(); /** * Opens a separate browser window and renders a URL. * @param absoluteUrl The URL to be rendered. * @param windowName The name of the new window. * @param windowFeatures The features of the new window (same as in Javascript open method). * @param replace * @return A new {@link org.lobobrowser.html.HtmlRendererContext} instance. * @deprecated Use {@link #open(URL, String, String, boolean)} instead. */ public HtmlRendererContext open(String absoluteUrl, String windowName, String windowFeatures, boolean replace); /** * Opens a separate browser window and renders a URL. * @param url The URL to be rendered. * @param windowName The name of the new window. * @param windowFeatures The features of the new window (same as in Javascript open method). * @param replace * @return A new {@link org.lobobrowser.html.HtmlRendererContext} instance. */ public HtmlRendererContext open(java.net.URL url, String windowName, String windowFeatures, boolean replace); /** * Shows a prompt dialog. * @param message The message shown by the dialog. * @param inputDefault The default input value. * @return The user's input value. */ public String prompt(String message, String inputDefault); /** * Scrolls the client area. * @param x Document's x coordinate. * @param y Document's y coordinate. */ public void scroll(int x, int y); /** * Scrolls the client area. * @param x Horizontal pixels to scroll. * @param y Vertical pixels to scroll. */ public void scrollBy(int x, int y); /** * Resizes the window. * @param width The new width. * @param height The new height. */ public void resizeTo(int width, int height); /** * Resizes the window. * @param byWidth The number of pixels to resize the width by. * @param byHeight The number of pixels to resize the height by. */ public void resizeBy(int byWidth, int byHeight); /** * Gets a value indicating if the window is closed. */ public boolean isClosed(); public String getDefaultStatus(); public void setDefaultStatus(String value); /** * Gets the window name. */ public String getName(); /** * Gets the parent of the frame/window in the current context. */ public HtmlRendererContext getParent(); /** * Gets the opener of the frame/window in the current context. */ public HtmlRendererContext getOpener(); /** * Sets the context that opened the current frame/window. * @param opener A {@link org.lobobrowser.html.HtmlRendererContext}. */ public void setOpener(HtmlRendererContext opener); /** * Gets the window status text. */ public String getStatus(); /** * Sets the window status text. * @param message A string. */ public void setStatus(String message); /** * Gets the top-most browser frame/window. */ public HtmlRendererContext getTop(); /** * It should return true if the link provided has been visited. */ public boolean isVisitedLink(HTMLLinkElement link); /** * Reloads the current document. */ public void reload(); /** * Gets the number of pages in the history list. */ public int getHistoryLength(); /** * Gets the current URL in history. */ public String getCurrentURL(); /** * Gets the next URL in the history. */ public String getNextURL(); /** * Gets the previous URL in the history. */ public String getPreviousURL(); /** * Goes forward one page. */ public void forward(); /** * Navigates the history according to the given offset. * @param offset A positive or negative number. -1 is * equivalent to {@link #back()}. +1 is * equivalent to {@link #forward()}. */ public void moveInHistory(int offset); /** * Navigates to a URL in the history list. */ public void goToHistoryURL(String url); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/HttpRequest.java0000644000175000017500000001306010771510712025222 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Nov 13, 2005 */ package org.lobobrowser.html; import java.awt.Image; import java.net.URL; import org.w3c.dom.Document; /** * The HttpRequest interface should * be implemented to provide web request capabilities. It is * used a similar manner to XMLHttpRequest in * Javascript (AJAX). Normally, a listener will be added * by calling {@link #addReadyStateChangeListener(ReadyStateChangeListener)}, * the method {@link #open(String, URL, boolean, String, String) open} * will be called, and finally, {@link #send(String)} will be called to * complete the request. * @see UserAgentContext#createHttpRequest() */ public interface HttpRequest { /** * The uninitialized request state. */ public static final int STATE_UNINITIALIZED = 0; /** * The loading request state. The open method * has been called, but a response has not been received yet. */ public static final int STATE_LOADING = 1; /** * The loaded request state. Headers and status are now available. */ public static final int STATE_LOADED = 2; /** * The interactive request state. Downloading response. */ public static final int STATE_INTERACTIVE = 3; /** * The complete request state. All operations are finished. */ public static final int STATE_COMPLETE = 4; /** * Gets the state of the request, a value * between 0 and 4. * @return A value corresponding to one of the STATE* constants in this class. */ public int getReadyState(); /** * Gets the request response as text. */ public String getResponseText(); /** * Gets the request response as an XML DOM. */ public Document getResponseXML(); /** * Gets the request response as an AWT image. */ public Image getResponseImage(); /** * Gets the request response bytes. */ public byte[] getResponseBytes(); /** * Gets the status of the response. Note that this * can be 0 for file requests in addition to 200 * for successful HTTP requests. */ public int getStatus(); /** * Gets the status text of the request, e.g. "OK" for 200. */ public String getStatusText(); /** * Aborts an ongoing request. */ public void abort(); /** * Gets a string with all the response headers. */ public String getAllResponseHeaders(); /** * Gets a response header value. * @param headerName The name of the header. */ public String getResponseHeader(String headerName); /** * Starts an asynchronous request. * @param method The request method. * @param url The destination URL. */ public void open(String method, String url) throws java.io.IOException; /** * Opens an asynchronous request. * @param method The request method. * @param url The destination URL. */ public void open(String method, URL url) throws java.io.IOException; /** * Opens an request. * @param method The request method. * @param url The destination URL. * @param asyncFlag Whether the request is asynchronous. */ public void open(String method, URL url, boolean asyncFlag) throws java.io.IOException; /** * Opens a request. * @param method The request method. * @param url The destination URL. * @param asyncFlag Whether the request should be asynchronous. */ public void open(String method, String url, boolean asyncFlag) throws java.io.IOException; /** * Opens a request. * @param method The request method. * @param url The destination URL. * @param asyncFlag Whether the request should be asynchronous. * @param userName The HTTP authentication user name. */ public void open(String method, java.net.URL url, boolean asyncFlag, String userName) throws java.io.IOException; /** * Opens a request. * @param method The request method. * @param url The destination URL. * @param asyncFlag Whether the request should be asynchronous. * @param userName The HTTP authentication user name. * @param password The HTTP authentication password. */ public void open(String method, java.net.URL url, boolean asyncFlag, String userName, String password) throws java.io.IOException; /** * Sends POST content if any. * @param content POST content or null for GET requests. * @throws java.io.IOException */ public void send(String content) throws java.io.IOException; /** * Adds a listener of ReadyState changes. The listener should be invoked * even in the case of errors. * @param listener An instanceof of {@link org.lobobrowser.html.ReadyStateChangeListener} */ public void addReadyStateChangeListener(ReadyStateChangeListener listener); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/ReadyStateChangeListener.java0000644000175000017500000000267310726473510027627 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Nov 13, 2005 */ package org.lobobrowser.html; import java.util.EventListener; /** * The ReadyStateChangeListener interface * is implemented to receive ReadyState change events * from {@link org.lobobrowser.html.HttpRequest}. * @see org.lobobrowser.html.HttpRequest#addReadyStateChangeListener(ReadyStateChangeListener) * @author J. H. S. */ public interface ReadyStateChangeListener extends EventListener { /** * This method is called when the ReadyState changes. */ public void readyStateChanged(); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/UserAgentContext.java0000644000175000017500000000630711125726656026214 0ustar twernertwernerpackage org.lobobrowser.html; /** * Provides information about the user agent (browser) driving * the parser and/or renderer. *

* A simple implementation of this interface is provided in * {@link org.lobobrowser.html.test.SimpleUserAgentContext}. * @see HtmlRendererContext#getUserAgentContext() * @see org.lobobrowser.html.parser.DocumentBuilderImpl#DocumentBuilderImpl(UserAgentContext) */ public interface UserAgentContext { /** * Creates an instance of {@link org.lobobrowser.html.HttpRequest} which * can be used by the renderer to load images, scripts, external style sheets, * and implement the Javascript XMLHttpRequest class (AJAX). */ public HttpRequest createHttpRequest(); /** * Gets browser "code" name. */ public String getAppCodeName(); /** * Gets browser application name. */ public String getAppName(); /** * Gets browser application version. */ public String getAppVersion(); /** * Gets browser application minor version. */ public String getAppMinorVersion(); /** * Gets browser language code. See ISO 639-1 codes. */ public String getBrowserLanguage(); /** * Returns a boolean value indicating whether cookies are * enabled in the user agent. This value is used for reporting * purposes only. */ public boolean isCookieEnabled(); /** * Returns a boolean value indicating whether scripting * is enabled in the user agent. If this value is false, * the parser will not process scripts and Javascript element * attributes will have no effect. */ public boolean isScriptingEnabled(); /** * Returns a boolean value indicating whether * remote (non-inline) CSS documents should be loaded. */ public boolean isExternalCSSEnabled(); /** * Gets the name of the user's operating system. */ public String getPlatform(); /** * Should return the string used in * the User-Agent header. */ public String getUserAgent(); /** * Method used to implement Javascript document.cookie property. */ public String getCookie(java.net.URL url); /** * Method used to implement document.cookie property. * @param cookieSpec Specification of cookies, as they * would appear in the Set-Cookie * header value of HTTP. */ public void setCookie(java.net.URL url, String cookieSpec); /** * Gets the security policy for scripting. Return null * if JavaScript code is trusted. */ public java.security.Policy getSecurityPolicy(); /** * Gets the scripting optimization level, which is a value * equivalent to Rhino's optimization level. */ public int getScriptingOptimizationLevel(); /** * Returns true if the current media matches the name provided. * @param mediaName Media name, which * may be screen, tty, etc. (See HTML Specification). */ public boolean isMedia(String mediaName); public String getVendor(); public String getProduct(); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/0000755000175000017500000000000011125630302023520 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/AttrImpl.java0000644000175000017500000000533310726473500026136 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Sep 10, 2005 */ package org.lobobrowser.html.domimpl; import org.w3c.dom.*; public class AttrImpl extends NodeImpl implements Attr { private String name; private String value; private boolean specified; private Element ownerElement; private boolean isId; /** * @param name * @param value */ public AttrImpl(String name, String value, boolean specified, Element owner, boolean isId) { super(); this.name = name; this.value = value; this.specified = specified; this.ownerElement = owner; this.isId = isId; } /** * @param name */ public AttrImpl(String name) { super(); this.name = name; this.value = ""; this.specified = false; this.ownerElement = null; this.isId = false; } public String getLocalName() { return this.name; } public String getNodeName() { return this.name; } public String getNodeValue() throws DOMException { return this.value; } public void setNodeValue(String nodeValue) throws DOMException { this.value = nodeValue; } public short getNodeType() { return Node.ATTRIBUTE_NODE; } public String getName() { return this.name; } public boolean getSpecified() { return this.specified; } public String getValue() { return this.value; } public void setValue(String value) throws DOMException { this.value = value; } public Element getOwnerElement() { return this.ownerElement; } public TypeInfo getSchemaTypeInfo() { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Namespaces not supported"); } public boolean isId() { return this.isId; } public void setId(boolean value) { this.isId = value; } protected Node createSimilarNode() { return new AttrImpl(this.name, this.value, this.specified, this.ownerElement, this.isId); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/CDataSectionImpl.java0000644000175000017500000000273010726473510027524 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Sep 4, 2005 */ package org.lobobrowser.html.domimpl; import org.w3c.dom.*; public class CDataSectionImpl extends TextImpl implements CDATASection { public CDataSectionImpl() { super(); } public CDataSectionImpl(String text) { super(text); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.NodeImpl#getnodeName() */ public String getNodeName() { return "#cdata-section"; } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.NodeImpl#getnodeType() */ public short getNodeType() { return Node.CDATA_SECTION_NODE; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/CharacterDataImpl.java0000644000175000017500000000705410763031256027713 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Sep 3, 2005 */ package org.lobobrowser.html.domimpl; import org.w3c.dom.*; public abstract class CharacterDataImpl extends NodeImpl implements CharacterData { protected volatile String text; public CharacterDataImpl() { super(); } public CharacterDataImpl(String text) { this.text = text; } public String getClassName() { return "HTMLCharacterData"; } public String getTextContent() throws DOMException { return this.text; } public void setTextContent(String textContent) throws DOMException { this.text = textContent; if(!this.notificationsSuspended) { this.informInvalid(); } } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.NodeImpl#cloneNode(boolean) */ public Node cloneNode(boolean deep) { CharacterDataImpl newNode = (CharacterDataImpl) super.cloneNode(deep); newNode.setData(this.getData()); return newNode; } public void appendData(String arg) throws DOMException { this.text += arg; if(!this.notificationsSuspended) { this.informInvalid(); } } public void deleteData(int offset, int count) throws DOMException { StringBuffer buffer = new StringBuffer(this.text); StringBuffer result = buffer.delete(offset, offset + count); this.text = result.toString(); if(!this.notificationsSuspended) { this.informInvalid(); } } public String getData() throws DOMException { return this.text; } public int getLength() { return this.text.length(); } public void insertData(int offset, String arg) throws DOMException { StringBuffer buffer = new StringBuffer(this.text); StringBuffer result = buffer.insert(offset, arg); this.text = result.toString(); if(!this.notificationsSuspended) { this.informInvalid(); } } public void replaceData(int offset, int count, String arg) throws DOMException { StringBuffer buffer = new StringBuffer(this.text); StringBuffer result = buffer.replace(offset, offset + count, arg); this.text = result.toString(); if(!this.notificationsSuspended) { this.informInvalid(); } } public void setData(String data) throws DOMException { this.text = data; if(!this.notificationsSuspended) { this.informInvalid(); } } public String substringData(int offset, int count) throws DOMException { return this.text.substring(offset, offset + count); } public String toString() { String someText = this.text; int length = someText.length(); if(someText != null && someText.length() > 32) { someText = someText.substring(0, 29) + "..."; } return this.getNodeName() + "[length=" + length + ",text=" + someText + "]"; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/ChildHTMLCollection.java0000644000175000017500000000361610726473504030134 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Dec 3, 2005 */ package org.lobobrowser.html.domimpl; import org.lobobrowser.js.*; import org.w3c.dom.Node; import org.w3c.dom.html2.HTMLCollection; public class ChildHTMLCollection extends AbstractScriptableDelegate implements HTMLCollection { private final NodeImpl rootNode; /** * @param node */ public ChildHTMLCollection(NodeImpl node) { super(); rootNode = node; } public int getLength() { return this.rootNode.getChildCount(); } public Node item(int index) { return this.rootNode.getChildAtIndex(index); } public Node namedItem(String name) { org.w3c.dom.Document doc = this.rootNode.getOwnerDocument(); if(doc == null) { return null; } //TODO: This might get elements that are not descendents. Node node = (Node) doc.getElementById(name); if(node != null && node.getParentNode() == this.rootNode) { return node; } return null; } public int indexOf(Node node) { return this.rootNode.getChildIndex(node); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/CommentImpl.java0000644000175000017500000000320010726473476026631 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 9, 2005 */ package org.lobobrowser.html.domimpl; import org.w3c.dom.Comment; import org.w3c.dom.DOMException; import org.w3c.dom.Node; public class CommentImpl extends CharacterDataImpl implements Comment { public CommentImpl(String text) { super(text); } public String getLocalName() { return null; } public String getNodeName() { return "#comment"; } public String getNodeValue() throws DOMException { return this.getTextContent(); } public void setNodeValue(String nodeValue) throws DOMException { this.setTextContent(nodeValue); } public short getNodeType() { return Node.COMMENT_NODE; } protected Node createSimilarNode() { return new CommentImpl(this.text); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/DOMConfigurationImpl.java0000644000175000017500000000340210726473502030370 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 9, 2005 */ package org.lobobrowser.html.domimpl; import java.util.*; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.DOMException; import org.w3c.dom.DOMStringList; public class DOMConfigurationImpl implements DOMConfiguration { private final Map parameters = new HashMap(); public DOMConfigurationImpl() { super(); } public void setParameter(String name, Object value) throws DOMException { synchronized(this) { this.parameters.put(name, value); } } public Object getParameter(String name) throws DOMException { synchronized(this) { return this.parameters.get(name); } } public boolean canSetParameter(String name, Object value) { //TODO return true; } public DOMStringList getParameterNames() { synchronized(this) { return new DOMStringListImpl(parameters.keySet()); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/DOMImplementationImpl.java0000644000175000017500000000377710726473506030571 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 15, 2005 */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.*; import org.w3c.dom.DOMException; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; public class DOMImplementationImpl implements DOMImplementation { private final UserAgentContext context; public DOMImplementationImpl(UserAgentContext context) { this.context = context; } public boolean hasFeature(String feature, String version) { return "HTML".equals(feature) && "2.0".compareTo(version) <= 0; } public DocumentType createDocumentType(String qualifiedName, String publicId, String systemId) throws DOMException { return new DocumentTypeImpl(qualifiedName, publicId, systemId); } public Document createDocument(String namespaceURI, String qualifiedName, DocumentType doctype) throws DOMException { return new HTMLDocumentImpl(this.context); } public Object getFeature(String feature, String version) { if("HTML".equals(feature) && "2.0".compareTo(version) <= 0) { return this; } else { return null; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/DOMStringListImpl.java0000644000175000017500000000307110726473504027667 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 9, 2005 */ package org.lobobrowser.html.domimpl; import org.w3c.dom.DOMStringList; import java.util.*; public class DOMStringListImpl implements DOMStringList { private final List sourceList; public DOMStringListImpl(Collection sourceList) { List list = new ArrayList(); list.addAll(sourceList); this.sourceList = list; } public String item(int index) { try { return (String) this.sourceList.get(index); } catch(IndexOutOfBoundsException iob) { return null; } } public int getLength() { return this.sourceList.size(); } public boolean contains(String str) { return this.sourceList.contains(str); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/DescendentHTMLCollection.java0000644000175000017500000001454211123247206031153 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Dec 3, 2005 */ package org.lobobrowser.html.domimpl; import java.util.*; import java.lang.ref.*; import org.lobobrowser.js.*; import org.lobobrowser.util.*; import org.w3c.dom.Node; import org.w3c.dom.html2.HTMLCollection; public class DescendentHTMLCollection extends AbstractScriptableDelegate implements HTMLCollection { private final NodeImpl rootNode; private final NodeFilter nodeFilter; private final Object treeLock; private final boolean nestIntoMatchingNodes; public DescendentHTMLCollection(NodeImpl node, NodeFilter filter, Object treeLock) { this(node, filter, treeLock, true); } /** * @param node * @param filter */ public DescendentHTMLCollection(NodeImpl node, NodeFilter filter, Object treeLock, boolean nestMatchingNodes) { rootNode = node; nodeFilter = filter; this.treeLock = treeLock; this.nestIntoMatchingNodes = nestMatchingNodes; HTMLDocumentImpl document = (HTMLDocumentImpl) node.getOwnerDocument(); document.addDocumentNotificationListener(new LocalNotificationListener(document, this)); } private Map itemsByName = null; private List itemsByIndex = null; private void ensurePopulatedImpl() { if(this.itemsByName == null) { ArrayList descendents = this.rootNode.getDescendents(this.nodeFilter, this.nestIntoMatchingNodes); this.itemsByIndex = descendents == null ? Collections.EMPTY_LIST : descendents; int size = descendents == null ? 0 : descendents.size(); Map itemsByName = new HashMap(size * 3 / 2); this.itemsByName = itemsByName; for(int i = 0; i < size; i++) { Object descNode = descendents.get(i); if(descNode instanceof ElementImpl) { ElementImpl element = (ElementImpl) descNode; String id = element.getId(); if(id != null && id.length() != 0) { itemsByName.put(id, element); } String name = element.getAttribute("name"); if(name != null && name.length() != 0 && !name.equals(id)) { itemsByName.put(name, element); } } } } } private void invalidate() { synchronized(this.treeLock) { this.itemsByName = null; this.itemsByIndex = null; } } private boolean isValid() { synchronized(this.treeLock) { return this.itemsByName != null && this.itemsByIndex != null; } } public int getLength() { synchronized(this.treeLock) { this.ensurePopulatedImpl(); return this.itemsByIndex.size(); } } public Node item(int index) { synchronized(this.treeLock) { this.ensurePopulatedImpl(); try { return (Node) this.itemsByIndex.get(index); } catch(java.lang.IndexOutOfBoundsException iob) { return null; } } } public Node namedItem(String name) { synchronized(this.treeLock) { this.ensurePopulatedImpl(); return (Node) this.itemsByName.get(name); } } public int indexOf(Node node) { synchronized(this.treeLock) { this.ensurePopulatedImpl(); return this.itemsByIndex.indexOf(node); } } // private final class NodeCounter implements NodeVisitor { // private int count = 0; // // public final void visit(Node node) { // if(nodeFilter.accept(node)) { // this.count++; // throw new SkipVisitorException(); // } // } // // public int getCount() { // return this.count; // } // } // // private final class NodeScanner implements NodeVisitor { // private int count = 0; // private Node foundNode = null; // private final int targetIndex; // // public NodeScanner(int idx) { // this.targetIndex = idx; // } // // public final void visit(Node node) { // if(nodeFilter.accept(node)) { // if(this.count == this.targetIndex) { // this.foundNode = node; // throw new StopVisitorException(); // } // this.count++; // throw new SkipVisitorException(); // } // } // // public Node getNode() { // return this.foundNode; // } // } // // private final class NodeScanner2 implements NodeVisitor { // private int count = 0; // private int foundIndex = -1; // private final Node targetNode; // // public NodeScanner2(Node node) { // this.targetNode = node; // } // // public final void visit(Node node) { // if(nodeFilter.accept(node)) { // if(node == this.targetNode) { // this.foundIndex = this.count; // throw new StopVisitorException(); // } // this.count++; // throw new SkipVisitorException(); // } // } // // public int getIndex() { // return this.foundIndex; // } // } private static class LocalNotificationListener extends DocumentNotificationAdapter { // Needs to be a static class with a weak reference to // the collection object. private final HTMLDocumentImpl document; private final WeakReference collectionRef; public LocalNotificationListener(final HTMLDocumentImpl document, final DescendentHTMLCollection collection) { super(); this.document = document; this.collectionRef = new WeakReference(collection); } public void structureInvalidated(NodeImpl node) { DescendentHTMLCollection collection = (DescendentHTMLCollection) this.collectionRef.get(); if(collection == null) { // Gone! this.document.removeDocumentNotificationListener(this); return; } if(collection.isValid()) { if(Nodes.isSameOrAncestorOf(collection.rootNode, node)) { collection.invalidate(); } } } public void nodeLoaded(NodeImpl node) { this.structureInvalidated(node); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/DocumentFragmentImpl.java0000644000175000017500000000317110726473504030470 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 9, 2005 */ package org.lobobrowser.html.domimpl; import org.w3c.dom.DOMException; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Node; public class DocumentFragmentImpl extends NodeImpl implements DocumentFragment { public DocumentFragmentImpl() { super(); } public String getLocalName() { return null; } public String getNodeName() { return "#document-fragment"; } public String getNodeValue() throws DOMException { return null; } public void setNodeValue(String nodeValue) throws DOMException { } public short getNodeType() { return org.w3c.dom.Node.DOCUMENT_FRAGMENT_NODE; } protected Node createSimilarNode() { return new DocumentFragmentImpl(); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/DocumentNotificationAdapter.java0000644000175000017500000000306210764534434032033 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.domimpl; /** * An abstract implementation of {@link DocumentNotificationListener} * with blank methods, provided for convenience. */ public abstract class DocumentNotificationAdapter implements DocumentNotificationListener { public void allInvalidated() { } public void externalScriptLoading(NodeImpl node) { } public void invalidated(NodeImpl node) { } public void lookInvalidated(NodeImpl node) { } public void nodeLoaded(NodeImpl node) { } public void positionInvalidated(NodeImpl node) { } public void sizeInvalidated(NodeImpl node) { } public void structureInvalidated(NodeImpl node) { } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/DocumentNotificationListener.java0000644000175000017500000000307310764534256032244 0ustar twernertwernerpackage org.lobobrowser.html.domimpl; /** * A listener of document changes. */ public interface DocumentNotificationListener { /** * Called if a property related to the node's * size has changed. * @param node */ public void sizeInvalidated(NodeImpl node); /** * Called if something such as a color or * decoration has changed. This would be * something which does not affect the * rendered size. * @param node */ public void lookInvalidated(NodeImpl node); /** * Changed if the position of the node in a * parent has changed. * @param node */ public void positionInvalidated(NodeImpl node); /** * This is called when the node has changed, but * it is unclear if it's a size change or a look * change. Typically, a node attribute has changed, * but the set of child nodes has not changed. * @param node */ public void invalidated(NodeImpl node); /** * Called when the node (with all its contents) is first * created by the parser. * @param node */ public void nodeLoaded(NodeImpl node); /** * The children of the node might have changed. * @param node */ public void structureInvalidated(NodeImpl node); /** * Called when a external script (a SCRIPT tag with a src attribute) * is about to start loading. * @param node */ public void externalScriptLoading(NodeImpl node); /** * This is called when the whole document * is potentially invalid, e.g. when a new * style sheet has been added. */ public void allInvalidated(); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/DocumentTypeImpl.java0000644000175000017500000000460110726473510027642 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 15, 2005 */ package org.lobobrowser.html.domimpl; import org.w3c.dom.DOMException; import org.w3c.dom.DocumentType; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; public class DocumentTypeImpl extends NodeImpl implements DocumentType { private final String qualifiedName; private final String publicId; private final String systemId; public DocumentTypeImpl(String qname, String publicId, String systemId) { super(); this.qualifiedName = qname; this.publicId = publicId; this.systemId = systemId; } public String getLocalName() { return null; } public String getNodeName() { return this.getName(); } public String getNodeValue() throws DOMException { return null; } public void setNodeValue(String nodeValue) throws DOMException { // nop } public short getNodeType() { return org.w3c.dom.Node.DOCUMENT_TYPE_NODE; } public String getName() { return this.qualifiedName; } public NamedNodeMap getEntities() { //TODO: DOCTYPE declared entities return null; } public NamedNodeMap getNotations() { //TODO: DOCTYPE notations return null; } public String getPublicId() { return this.publicId; } public String getSystemId() { return this.systemId; } public String getInternalSubset() { //TODO: DOCTYPE internal subset return null; } protected Node createSimilarNode() { return new DocumentTypeImpl(this.qualifiedName, this.publicId, this.systemId); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/ElementFactory.java0000644000175000017500000001234311047522134027315 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 8, 2005 */ package org.lobobrowser.html.domimpl; import java.util.*; import org.w3c.dom.html2.*; import org.w3c.dom.*; class ElementFactory { private final Map builders = new HashMap(80); private ElementFactory() { // This sets up builders for each known element tag. Map builders = this.builders; builders.put("HTML", new HTMLElementBuilder.Html()); builders.put("TITLE", new HTMLElementBuilder.Title()); builders.put("BASE", new HTMLElementBuilder.Base()); HTMLElementBuilder div = new HTMLElementBuilder.Div(); builders.put("DIV", div); builders.put("DL", div); builders.put("BODY", new HTMLElementBuilder.Body()); builders.put("CENTER", new HTMLElementBuilder.Center()); builders.put("CAPTION", new HTMLElementBuilder.Center()); builders.put("PRE", new HTMLElementBuilder.Pre()); builders.put("P", new HTMLElementBuilder.P()); HTMLElementBuilder bq = new HTMLElementBuilder.Blockquote(); builders.put("BLOCKQUOTE", bq); builders.put("DD", bq); builders.put("SPAN", new HTMLElementBuilder.Span()); builders.put("SCRIPT", new HTMLElementBuilder.Script()); builders.put("IMG", new HTMLElementBuilder.Img()); builders.put("STYLE", new HTMLElementBuilder.Style()); builders.put("LINK", new HTMLElementBuilder.Link()); builders.put("A", new HTMLElementBuilder.Anchor()); builders.put("ANCHOR", new HTMLElementBuilder.Anchor()); builders.put("TABLE", new HTMLElementBuilder.Table()); builders.put("TD", new HTMLElementBuilder.Td()); builders.put("TH", new HTMLElementBuilder.Th()); builders.put("TR", new HTMLElementBuilder.Tr()); builders.put("FORM", new HTMLElementBuilder.Form()); builders.put("INPUT", new HTMLElementBuilder.Input()); builders.put("BUTTON", new HTMLElementBuilder.Button()); builders.put("TEXTAREA", new HTMLElementBuilder.Textarea()); builders.put("SELECT", new HTMLElementBuilder.Select()); builders.put("OPTION", new HTMLElementBuilder.Option()); builders.put("FRAMESET", new HTMLElementBuilder.Frameset()); builders.put("FRAME", new HTMLElementBuilder.Frame()); builders.put("IFRAME", new HTMLElementBuilder.IFrame()); builders.put("UL", new HTMLElementBuilder.Ul()); builders.put("OL", new HTMLElementBuilder.Ol()); builders.put("LI", new HTMLElementBuilder.Li()); builders.put("HR", new HTMLElementBuilder.Hr()); builders.put("BR", new HTMLElementBuilder.Br()); builders.put("OBJECT", new HTMLElementBuilder.HtmlObject()); builders.put("APPLET", new HTMLElementBuilder.Applet()); builders.put("EMBED", new HTMLElementBuilder.NonStandard()); builders.put("FONT", new HTMLElementBuilder.Font()); builders.put("BASEFONT", new HTMLElementBuilder.BaseFont()); builders.put("TT", new HTMLElementBuilder.Tt()); builders.put("CODE", new HTMLElementBuilder.Code()); builders.put("SMALL", new HTMLElementBuilder.Small()); builders.put("BIG", new HTMLElementBuilder.Big()); builders.put("B", new HTMLElementBuilder.Strong()); builders.put("STRONG", new HTMLElementBuilder.Strong()); builders.put("U", new HTMLElementBuilder.Underline()); builders.put("STRIKE", new HTMLElementBuilder.Strike()); builders.put("SUP", new HTMLElementBuilder.Sup()); builders.put("SUB", new HTMLElementBuilder.Sub()); HTMLElementBuilder em = new HTMLElementBuilder.Em(); builders.put("I", em); builders.put("EM", em); builders.put("CITE", em); HTMLElementBuilder heading = new HTMLElementBuilder.Heading(); builders.put("H1", heading); builders.put("H2", heading); builders.put("H3", heading); builders.put("H4", heading); builders.put("H5", heading); builders.put("H6", heading); } private static ElementFactory instance = new ElementFactory(); public static ElementFactory getInstance() { return instance; } public final HTMLElement createElement(HTMLDocumentImpl document, String name) throws DOMException { String normalName = name.toUpperCase(); // No need to synchronize; read-only map at this point. HTMLElementBuilder builder = (HTMLElementBuilder) this.builders.get(normalName); if(builder == null) { //TODO: IE would assume name is html text here? HTMLElementImpl element = new HTMLElementImpl(name); element.setOwnerDocument(document); return element; } else { return builder.create(document, name); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/ElementFilter.java0000644000175000017500000000245410726473506027150 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Dec 3, 2005 */ package org.lobobrowser.html.domimpl; import org.w3c.dom.Node; public final class ElementFilter implements NodeFilter { private final String elementName; /** * @param name */ public ElementFilter(String name) { super(); elementName = name; } public final boolean accept(Node node) { return this.elementName.equalsIgnoreCase(node.getNodeName()); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/ElementImpl.java0000644000175000017500000003352411055031236026610 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 29, 2005 */ package org.lobobrowser.html.domimpl; import java.util.*; import org.lobobrowser.util.*; import org.w3c.dom.Attr; import org.w3c.dom.DOMException; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.TypeInfo; import org.w3c.dom.Text; import org.w3c.dom.Comment; public class ElementImpl extends NodeImpl implements Element { private final String name; public ElementImpl(String name) { super(); this.name = name; } protected Map attributes; /* * (non-Javadoc) * * @see org.xamjwg.html.domimpl.NodeImpl#getattributes() */ public NamedNodeMap getAttributes() { synchronized(this) { Map attrs = this.attributes; if (attrs == null) { attrs = new HashMap(); this.attributes = attrs; } return new NamedNodeMapImpl(this, this.attributes); } } public boolean hasAttributes() { synchronized(this) { Map attrs = this.attributes; return attrs == null ? false : !attrs.isEmpty(); } } public boolean equalAttributes(Node arg) { if (arg instanceof ElementImpl) { synchronized(this) { Map attrs1 = this.attributes; if (attrs1 == null) { attrs1 = Collections.EMPTY_MAP; } Map attrs2 = ((ElementImpl) arg).attributes; if (attrs2 == null) { attrs2 = Collections.EMPTY_MAP; } return Objects.equals(attrs1, attrs2); } } else { return false; } } private String id; public String getId() { String id = this.id; return id == null ? "" : id; } public void setId(String id) { this.setAttribute("id", id); } //private String title; public String getTitle() { return this.getAttribute("title"); } public void setTitle(String title) { this.setAttribute("title", title); } public String getLang() { return this.getAttribute("lang"); } public void setLang(String lang) { this.setAttribute("lang", lang); } public String getDir() { return this.getAttribute("dir"); } public void setDir(String dir) { this.setAttribute("dir", dir); } public final String getAttribute(String name) { String normalName = this.normalizeAttributeName(name); synchronized(this) { Map attributes = this.attributes; return attributes == null ? null : (String) attributes .get(normalName); } } private Attr getAttr(String normalName, String value) { // TODO: "specified" attributes return new AttrImpl(normalName, value, true, this, "id" .equals(normalName)); } public Attr getAttributeNode(String name) { String normalName = this.normalizeAttributeName(name); synchronized(this) { Map attributes = this.attributes; String value = attributes == null ? null : (String) attributes .get(normalName); return value == null ? null : this.getAttr(normalName, value); } } public Attr getAttributeNodeNS(String namespaceURI, String localName) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Namespaces not supported"); } public String getAttributeNS(String namespaceURI, String localName) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Namespaces not supported"); } protected static boolean isTagName(Node node, String name) { return node.getNodeName().equalsIgnoreCase(name); } public NodeList getElementsByTagName(String name) { boolean matchesAll = "*".equals(name); List descendents = new LinkedList(); synchronized(this.treeLock) { ArrayList nl = this.nodeList; if(nl != null) { Iterator i = nl.iterator(); while (i.hasNext()) { Object child = i.next(); if (child instanceof Element) { Element childElement = (Element) child; if (matchesAll || isTagName(childElement, name)) { descendents.add(child); } NodeList sublist = childElement.getElementsByTagName(name); int length = sublist.getLength(); for (int idx = 0; idx < length; idx++) { descendents.add(sublist.item(idx)); } } } } } return new NodeListImpl(descendents); } public NodeList getElementsByTagNameNS(String namespaceURI, String localName) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Namespaces not supported"); } public TypeInfo getSchemaTypeInfo() { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Namespaces not supported"); } public String getTagName() { return this.getNodeName(); } public boolean hasAttribute(String name) { String normalName = this.normalizeAttributeName(name); synchronized(this) { Map attributes = this.attributes; return attributes == null ? false : attributes .containsKey(normalName); } } public boolean hasAttributeNS(String namespaceURI, String localName) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Namespaces not supported"); } public void removeAttribute(String name) throws DOMException { String normalName = this.normalizeAttributeName(name); synchronized(this) { Map attributes = this.attributes; if (attributes == null) { return; } attributes.remove(normalName); } } public Attr removeAttributeNode(Attr oldAttr) throws DOMException { String normalName = this.normalizeAttributeName(oldAttr.getName()); synchronized(this) { Map attributes = this.attributes; if (attributes == null) { return null; } String oldValue = (String) attributes.remove(normalName); // TODO: "specified" attributes return oldValue == null ? null : this.getAttr(normalName, oldValue); } } public void removeAttributeNS(String namespaceURI, String localName) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Namespaces not supported"); } protected void assignAttributeField(String normalName, String value) { // Note: overriders assume that processing here is only done after // checking attribute names, i.e. they may not call the super // implementation if an attribute is already taken care of. boolean isName = false; if ("id".equals(normalName) || (isName = "name".equals(normalName))) { // Note that the value of name is used // as an ID, but the value of ID is not // used as a name. if(!isName) { this.id = value; } HTMLDocumentImpl document = (HTMLDocumentImpl) this.document; if (document != null) { //// Do not remove old ID. Consider scenario where both //// name and ID are provided in an element. // if (oldId != null) { // document.removeElementById(oldId); // } document.setElementById(value, this); if(isName) { String oldName = this.getAttribute("name"); if(oldName != null) { document.removeNamedItem(oldName); } document.setNamedItem(value, this); } } } } protected final String normalizeAttributeName(String name) { return name.toLowerCase(); } public void setAttribute(String name, String value) throws DOMException { String normalName = this.normalizeAttributeName(name); synchronized(this) { Map attribs = this.attributes; if (attribs == null) { attribs = new HashMap(2); this.attributes = attribs; } attribs.put(normalName, value); } this.assignAttributeField(normalName, value); } /** * Fast method to set attributes. It is not thread safe. * Calling thread should hold a treeLock. */ public void setAttributeImpl(String name, String value) throws DOMException { String normalName = this.normalizeAttributeName(name); Map attribs = this.attributes; if (attribs == null) { attribs = new HashMap(2); this.attributes = attribs; } this.assignAttributeField(normalName, value); attribs.put(normalName, value); } public Attr setAttributeNode(Attr newAttr) throws DOMException { String normalName = this.normalizeAttributeName(newAttr.getName()); String value = newAttr.getValue(); synchronized(this) { if (this.attributes == null) { this.attributes = new HashMap(); } this.attributes.put(normalName, value); // this.setIdAttribute(normalName, newAttr.isId()); } this.assignAttributeField(normalName, value); return newAttr; } public Attr setAttributeNodeNS(Attr newAttr) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Namespaces not supported"); } public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Namespaces not supported"); } public void setIdAttribute(String name, boolean isId) throws DOMException { String normalName = this.normalizeAttributeName(name); if (!"id".equals(normalName)) { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "IdAttribute can't be anything other than ID"); } } public void setIdAttributeNode(Attr idAttr, boolean isId) throws DOMException { String normalName = this.normalizeAttributeName(idAttr.getName()); if (!"id".equals(normalName)) { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "IdAttribute can't be anything other than ID"); } } public void setIdAttributeNS(String namespaceURI, String localName, boolean isId) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Namespaces not supported"); } /* * (non-Javadoc) * * @see org.xamjwg.html.domimpl.NodeImpl#getLocalName() */ public String getLocalName() { return this.getNodeName(); } /* * (non-Javadoc) * * @see org.xamjwg.html.domimpl.NodeImpl#getNodeName() */ public String getNodeName() { return this.name; } /* * (non-Javadoc) * * @see org.xamjwg.html.domimpl.NodeImpl#getNodeType() */ public short getNodeType() { return Node.ELEMENT_NODE; } /* * (non-Javadoc) * * @see org.xamjwg.html.domimpl.NodeImpl#getNodeValue() */ public String getNodeValue() throws DOMException { return null; } /* * (non-Javadoc) * * @see org.xamjwg.html.domimpl.NodeImpl#setNodeValue(java.lang.String) */ public void setNodeValue(String nodeValue) throws DOMException { // nop } /** * Gets inner text of the element, possibly including text in comments. * This can be used to get Javascript code out of a SCRIPT element. * * @param includeComment */ protected String getRawInnerText(boolean includeComment) { synchronized(this.treeLock) { ArrayList nl = this.nodeList; if(nl != null) { Iterator i = nl.iterator(); StringBuffer sb = null; while (i.hasNext()) { Object node = i.next(); if (node instanceof Text) { Text tn = (Text) node; String txt = tn.getNodeValue(); if (!"".equals(txt)) { if (sb == null) { sb = new StringBuffer(); } sb.append(txt); } } else if (node instanceof ElementImpl) { ElementImpl en = (ElementImpl) node; String txt = en.getRawInnerText(includeComment); if (!"".equals(txt)) { if (sb == null) { sb = new StringBuffer(); } sb.append(txt); } } else if (includeComment && node instanceof Comment) { Comment cn = (Comment) node; String txt = cn.getNodeValue(); if (!"".equals(txt)) { if (sb == null) { sb = new StringBuffer(); } sb.append(txt); } } } return sb == null ? "" : sb.toString(); } else { return ""; } } } public String toString() { StringBuffer sb = new StringBuffer(); sb.append(this.getNodeName()); sb.append(" ["); NamedNodeMap attribs = this.getAttributes(); int length = attribs.getLength(); for (int i = 0; i < length; i++) { Attr attr = (Attr) attribs.item(i); sb.append(attr.getNodeName()); sb.append('='); sb.append(attr.getNodeValue()); if (i + 1 < length) { sb.append(','); } } sb.append("]"); return sb.toString(); } public void setInnerText(String newText) { org.w3c.dom.Document document = this.document; if(document == null) { this.warn("setInnerText(): Element " + this + " does not belong to a document."); return; } synchronized(this.treeLock) { ArrayList nl = this.nodeList; if (nl != null) { nl.clear(); } } // Create node and call appendChild outside of synchronized block. Node textNode = document.createTextNode(newText); this.appendChild(textNode); } protected Node createSimilarNode() { HTMLDocumentImpl doc = (HTMLDocumentImpl) this.document; return doc == null ? null : doc.createElement(this.getTagName()); } protected String htmlEncodeChildText(String text) { if(org.lobobrowser.html.parser.HtmlParser.isDecodeEntities(this.name)) { return Strings.strictHtmlEncode(text, false); } else { return text; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/FilteredNodeListImpl.java0000644000175000017500000000410210726473504030421 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 9, 2005 */ package org.lobobrowser.html.domimpl; import org.lobobrowser.js.*; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.util.*; class FilteredNodeListImpl extends AbstractScriptableDelegate implements NodeList { private final Collection sourceNodeList; private final NodeFilter filter; private final Object lock; /** * @param filter * @param list */ public FilteredNodeListImpl(NodeFilter filter, Collection list, Object lock) { super(); this.filter = filter; sourceNodeList = list; this.lock = lock; } public Node item(int index) { synchronized(this.lock) { int count = 0; Iterator i = this.sourceNodeList.iterator(); while(i.hasNext()) { Node node = (Node) i.next(); if(this.filter.accept(node)) { if(count == index) { return node; } count++; } } return null; } } public int getLength() { synchronized(this.lock) { int count = 0; Iterator i = this.sourceNodeList.iterator(); while(i.hasNext()) { Node node = (Node) i.next(); if(this.filter.accept(node)) { count++; } } return count; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/FrameNode.java0000644000175000017500000000036510641432430026233 0ustar twernertwernerpackage org.lobobrowser.html.domimpl; import org.lobobrowser.html.*; /** * Tag interface for frame nodes. */ public interface FrameNode { public BrowserFrame getBrowserFrame(); public void setBrowserFrame(BrowserFrame frame); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLAbstractUIElement.java0000644000175000017500000001346011130421054030365 0ustar twernertwernerpackage org.lobobrowser.html.domimpl; import org.lobobrowser.html.*; import org.lobobrowser.html.js.Executor; import org.lobobrowser.js.*; import org.mozilla.javascript.*; import org.w3c.dom.*; import java.util.*; import java.util.logging.Level; /** * Implements common functionality of most elements. */ public class HTMLAbstractUIElement extends HTMLElementImpl { private Function onfocus, onblur, onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup, oncontextmenu; public HTMLAbstractUIElement(String name) { super(name); } public Function getOnblur() { return this.getEventFunction(onblur, "onblur"); } public void setOnblur(Function onblur) { this.onblur = onblur; } public Function getOnclick() { return this.getEventFunction(onclick, "onclick"); } public void setOnclick(Function onclick) { this.onclick = onclick; } public Function getOndblclick() { return this.getEventFunction(ondblclick, "ondblclick"); } public void setOndblclick(Function ondblclick) { this.ondblclick = ondblclick; } public Function getOnfocus() { return this.getEventFunction(onfocus, "onfocus"); } public void setOnfocus(Function onfocus) { this.onfocus = onfocus; } public Function getOnkeydown() { return this.getEventFunction(onkeydown, "onkeydown"); } public void setOnkeydown(Function onkeydown) { this.onkeydown = onkeydown; } public Function getOnkeypress() { return this.getEventFunction(onkeypress, "onkeypress"); } public void setOnkeypress(Function onkeypress) { this.onkeypress = onkeypress; } public Function getOnkeyup() { return this.getEventFunction(onkeyup, "onkeyup"); } public void setOnkeyup(Function onkeyup) { this.onkeyup = onkeyup; } public Function getOnmousedown() { return this.getEventFunction(onmousedown, "onmousedown"); } public void setOnmousedown(Function onmousedown) { this.onmousedown = onmousedown; } public Function getOnmousemove() { return this.getEventFunction(onmousemove, "onmousemove"); } public void setOnmousemove(Function onmousemove) { this.onmousemove = onmousemove; } public Function getOnmouseout() { return this.getEventFunction(onmouseout, "onmouseout"); } public void setOnmouseout(Function onmouseout) { this.onmouseout = onmouseout; } public Function getOnmouseover() { return this.getEventFunction(onmouseover, "onmouseover"); } public void setOnmouseover(Function onmouseover) { this.onmouseover = onmouseover; } public Function getOnmouseup() { return this.getEventFunction(onmouseup, "onmouseup"); } public void setOnmouseup(Function onmouseup) { this.onmouseup = onmouseup; } public Function getOncontextmenu() { return this.getEventFunction(oncontextmenu, "oncontextmenu"); } public void setOncontextmenu(Function oncontextmenu) { this.oncontextmenu = oncontextmenu; } public void focus() { UINode node = this.getUINode(); if(node != null) { node.focus(); } } public void blur() { UINode node = this.getUINode(); if(node != null) { node.blur(); } } private Map functionByAttribute = null; protected Function getEventFunction(Function varValue, String attributeName) { if(varValue != null) { return varValue; } String normalAttributeName = this.normalizeAttributeName(attributeName); synchronized(this) { Map fba = this.functionByAttribute; Function f = fba == null ? null : (Function) fba.get(normalAttributeName); if(f != null) { return f; } UserAgentContext uac = this.getUserAgentContext(); if(uac == null) { throw new IllegalStateException("No user agent context."); } if(uac.isScriptingEnabled()) { String attributeValue = this.getAttribute(attributeName); if(attributeValue == null || attributeValue.length() == 0) { f = null; } else { String functionCode = "function " + normalAttributeName + "_" + System.identityHashCode(this) + "() { " + attributeValue + " }"; Document doc = this.document; if(doc == null) { throw new IllegalStateException("Element does not belong to a document."); } Context ctx = Executor.createContext(this.getDocumentURL(), uac); try { Scriptable scope = (Scriptable) doc.getUserData(Executor.SCOPE_KEY); if(scope == null) { throw new IllegalStateException("Scriptable (scope) instance was expected to be keyed as UserData to document using " + Executor.SCOPE_KEY); } Scriptable thisScope = (Scriptable) JavaScript.getInstance().getJavascriptObject(this, scope); try { //TODO: Get right line number for script. //TODO: Optimize this in case it's called multiple times? Is that done? f = ctx.compileFunction(thisScope, functionCode, this.getTagName() + "[" + this.getId() + "]." + attributeName, 1, null); } catch(EcmaError ecmaError) { logger.log(Level.WARNING, "Javascript error at " + ecmaError.getSourceName() + ":" + ecmaError.getLineNumber() + ": " + ecmaError.getMessage(), ecmaError); f = null; } catch(Throwable err) { logger.log(Level.WARNING, "Unable to evaluate Javascript code", err); f = null; } } finally { Context.exit(); } } if(fba == null) { fba = new HashMap(1); this.functionByAttribute = fba; } fba.put(normalAttributeName, f); } return f; } } protected void assignAttributeField(String normalName, String value) { super.assignAttributeField(normalName, value); if(normalName.startsWith("on")) { synchronized(this) { Map fba = this.functionByAttribute; if(fba != null) { fba.remove(normalName); } } } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLAppletElementImpl.java0000644000175000017500000000372210641432432030443 0ustar twernertwernerpackage org.lobobrowser.html.domimpl; import org.w3c.dom.html.HTMLAppletElement; public class HTMLAppletElementImpl extends HTMLAbstractUIElement implements HTMLAppletElement { public HTMLAppletElementImpl(String name) { super(name); } public String getAlign() { return this.getAttribute("align"); } public String getAlt() { return this.getAttribute("alt"); } public String getArchive() { return this.getAttribute("archive"); } public String getCode() { return this.getAttribute("code"); } public String getCodeBase() { return this.getAttribute("codebase"); } public String getHeight() { return this.getAttribute("height"); } public String getHspace() { return this.getAttribute("hspace"); } public String getName() { return this.getAttribute("name"); } public String getObject() { return this.getAttribute("object"); } public String getVspace() { return this.getAttribute("vspace"); } public String getWidth() { return this.getAttribute("width"); } public void setAlign(String align) { this.setAttribute("align", align); } public void setAlt(String alt) { this.setAttribute("alt", alt); } public void setArchive(String archive) { this.setAttribute("archive", archive); } public void setCode(String code) { this.setAttribute("code", code); } public void setCodeBase(String codeBase) { this.setAttribute("codebase", codeBase); } public void setHeight(String height) { this.setAttribute("height", height); } public void setHspace(String hspace) { this.setAttribute("hspace", hspace); } public void setName(String name) { this.setAttribute("name", name); } public void setObject(String object) { this.setAttribute("object", object); } public void setVspace(String vspace) { this.setAttribute("vspace", vspace); } public void setWidth(String width) { this.setAttribute("width", width); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLBRElementImpl.java0000644000175000017500000000100710641432432027513 0ustar twernertwernerpackage org.lobobrowser.html.domimpl; import org.w3c.dom.html2.HTMLBRElement; public class HTMLBRElementImpl extends HTMLElementImpl implements HTMLBRElement { public HTMLBRElementImpl(String name) { super(name); } public String getClear() { return this.getAttribute("clear"); } public void setClear(String clear) { this.setAttribute("clear", clear); } protected void appendInnerTextImpl(StringBuffer buffer) { buffer.append("\r\n"); super.appendInnerTextImpl(buffer); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLBaseElementImpl.java0000644000175000017500000000311610726473504030076 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.domimpl; import org.w3c.dom.UserDataHandler; public class HTMLBaseElementImpl extends HTMLElementImpl { public HTMLBaseElementImpl(String name) { super(name, true); } public Object setUserData(String key, Object data, UserDataHandler handler) { if(org.lobobrowser.html.parser.HtmlParser.MODIFYING_KEY.equals(key) && data != Boolean.TRUE) { this.processBaseTag(); } return super.setUserData(key, data, handler); } private final void processBaseTag() { HTMLDocumentImpl doc = (HTMLDocumentImpl) this.document; if(doc != null) { doc.setBaseURI(this.getAttribute("href")); doc.setDefaultTarget(this.getAttribute("target")); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLBaseFontElementImpl.java0000644000175000017500000000635511134546340030726 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.*; import org.lobobrowser.util.gui.ColorFactory; import org.w3c.dom.html2.HTMLBaseFontElement; public class HTMLBaseFontElementImpl extends HTMLAbstractUIElement implements HTMLBaseFontElement { public HTMLBaseFontElementImpl(String name) { super(name); } public String getColor() { return this.getAttribute("color"); } public String getFace() { return this.getAttribute("face"); } public void setColor(String color) { this.setAttribute("color", color); } public void setFace(String face) { this.setAttribute("face", face); } public int getSize() { try { return Integer.parseInt(this.getAttribute("size")); } catch(Exception thrown) { this.warn("getSize(): Unable to parse size attribute in " + this + ".", thrown); return 0; } } public void setSize(int size) { this.setAttribute("size", String.valueOf(size)); } protected RenderState createRenderState(RenderState prevRenderState) { String size = this.getAttribute("size"); if(size != null) { int fontNumber = HtmlValues.getFontNumberOldStyle(size, prevRenderState); float fontSize = HtmlValues.getFontSize(fontNumber); prevRenderState = new BaseFontRenderState(prevRenderState, fontNumber); } return super.createRenderState(prevRenderState); } protected AbstractCSS2Properties createDefaultStyleSheet() { String fontFamily = this.getAttribute("face"); String color = this.getAttribute("color"); String size = this.getAttribute("size"); ModelNode parentModelNode = this.getParentModelNode(); RenderState parentRS = parentModelNode == null ? null : parentModelNode.getRenderState(); String fontSize = null; if(parentRS != null) { int fontNumber = HtmlValues.getFontNumberOldStyle(size, parentRS); fontSize = HtmlValues.getFontSizeSpec(fontNumber); } ComputedCSS2Properties css = new ComputedCSS2Properties(this); if(fontSize != null) { css.internalSetLC("font-size", fontSize); } if(fontFamily != null) { css.internalSetLC("font-family", fontFamily); } if(color != null) { css.internalSetLC("color", color); } return css; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLBaseInputElement.java0000644000175000017500000002026010772245354030274 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 15, 2006 */ package org.lobobrowser.html.domimpl; import java.util.ArrayList; import org.lobobrowser.html.FormInput; import org.lobobrowser.html.js.Executor; import org.mozilla.javascript.Function; import org.w3c.dom.Node; import org.w3c.dom.html2.HTMLFormElement; public abstract class HTMLBaseInputElement extends HTMLAbstractUIElement { public HTMLBaseInputElement(String name) { super(name); } protected InputContext inputContext; protected String deferredValue; public void setInputContext(InputContext ic) { String dv = null; synchronized(this) { this.inputContext = ic; if(ic != null) { dv = this.deferredValue; } } if(dv != null) { ic.setValue(dv); } } public String getDefaultValue() { return this.getAttribute("defaultValue"); } public void setDefaultValue(String defaultValue) { this.setAttribute("defaultValue", defaultValue); } public HTMLFormElement getForm() { Node parent = this.getParentNode(); while(parent != null && !(parent instanceof HTMLFormElement)) { parent = parent.getParentNode(); } return (HTMLFormElement) parent; } public void submitForm(FormInput[] extraFormInputs) { HTMLFormElementImpl form = (HTMLFormElementImpl) this.getForm(); if(form != null) { form.submit(extraFormInputs); } } public void resetForm() { HTMLFormElement form = this.getForm(); if (form != null) { form.reset(); } } public String getAccept() { return this.getAttribute("accept"); } public void setAccept(String accept) { this.setAttribute("accept", accept); } public String getAccessKey() { return this.getAttribute("accessKey"); } public void setAccessKey(String accessKey) { this.setAttribute("accessKey", accessKey); } public String getAlign() { return this.getAttribute("align"); } public void setAlign(String align) { this.setAttribute("align", align); } public String getAlt() { return this.getAttribute("alit"); } public void setAlt(String alt) { this.setAttribute("alt", alt); } public boolean getDisabled() { InputContext ic = this.inputContext; return ic == null ? false : ic.getDisabled(); } public void setDisabled(boolean disabled) { InputContext ic = this.inputContext; if(ic != null) { ic.setDisabled(disabled); } } public String getName() { //TODO: Should this return valid of "id"? return this.getAttribute("name"); } public void setName(String name) { this.setAttribute("name", name); } public boolean getReadOnly() { InputContext ic = this.inputContext; return ic == null ? false : ic.getReadOnly(); } public void setReadOnly(boolean readOnly) { InputContext ic = this.inputContext; if(ic != null) { ic.setReadOnly(readOnly); } } public int getTabIndex() { InputContext ic = this.inputContext; return ic == null ? 0 : ic.getTabIndex(); } public void setTabIndex(int tabIndex) { InputContext ic = this.inputContext; if(ic != null) { ic.setTabIndex(tabIndex); } } public String getValue() { InputContext ic = this.inputContext; if(ic != null) { //Note: Per HTML Spec, setValue does not set attribute. return ic.getValue(); } else { String dv = this.deferredValue; if(dv != null) { return dv; } else { String val = this.getAttribute("value"); return val == null ? "" : val; } } } protected java.io.File getFileValue() { InputContext ic = this.inputContext; if(ic != null) { return ic.getFileValue(); } else { return null; } } public void setValue(String value) { InputContext ic = null; synchronized(this) { ic = this.inputContext; if(ic == null) { this.deferredValue = value; } } if(ic != null) { ic.setValue(value); } } public void blur() { InputContext ic = this.inputContext; if(ic != null) { ic.blur(); } } public void focus() { InputContext ic = this.inputContext; if(ic != null) { ic.focus(); } } public void select() { InputContext ic = this.inputContext; if(ic != null) { ic.select(); } } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.HTMLElementImpl#assignAttributeField(java.lang.String, java.lang.String) */ protected void assignAttributeField(String normalName, String value) { if("value".equals(normalName)) { InputContext ic = this.inputContext; if(ic != null) { ic.setValue(value); } } else if("src".equals(normalName)) { this.loadImage(value); } else { super.assignAttributeField(normalName, value); } } private Function onload; public Function getOnload() { return this.getEventFunction(this.onload, "onload"); } public void setOnload(Function onload) { this.onload = onload; } private java.awt.Image image = null; private String imageSrc; private void loadImage(String src) { HTMLDocumentImpl document = (HTMLDocumentImpl) this.document; if(document != null) { synchronized(this.imageListeners) { this.imageSrc = src; this.image = null; } if(src != null) { document.loadImage(src, new LocalImageListener(src)); } } } public final java.awt.Image getImage() { synchronized(this.imageListeners) { return this.image; } } private final ArrayList imageListeners = new ArrayList(1); /** * Adds a listener of image loading events. * The listener gets called right away if there's already * an image. * @param listener */ public void addImageListener(ImageListener listener) { ArrayList l = this.imageListeners; java.awt.Image currentImage; synchronized(l) { currentImage = this.image; l.add(listener); } if(currentImage != null) { // Call listener right away if there's already an // image; holding no locks. listener.imageLoaded(new ImageEvent(this, currentImage)); // Should not call onload handler here. That's taken // care of otherwise. } } public void removeImageListener(ImageListener listener) { ArrayList l = this.imageListeners; synchronized(l) { l.remove(l); } } void resetInput() { InputContext ic = this.inputContext; if(ic != null) { ic.resetInput(); } } private void dispatchEvent(String expectedImgSrc, ImageEvent event) { ArrayList l = this.imageListeners; ImageListener[] listenerArray; synchronized(l) { if(!expectedImgSrc.equals(this.imageSrc)) { return; } this.image = event.image; // Get array of listeners while holding lock. listenerArray = (ImageListener[]) l.toArray(ImageListener.EMPTY_ARRAY); } int llength = listenerArray.length; for(int i = 0; i < llength; i++) { // Inform listener, holding no lock. listenerArray[i].imageLoaded(event); } Function onload = this.getOnload(); if(onload != null) { //TODO: onload event object? Executor.executeFunction(HTMLBaseInputElement.this, onload, null); } } private class LocalImageListener implements ImageListener { private final String expectedImgSrc; public LocalImageListener(String imgSrc) { this.expectedImgSrc = imgSrc; } public void imageLoaded(ImageEvent event) { dispatchEvent(this.expectedImgSrc, event); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLBlockQuoteElementImpl.java0000644000175000017500000000236111134376672031277 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.*; public class HTMLBlockQuoteElementImpl extends HTMLAbstractUIElement { public HTMLBlockQuoteElementImpl(String name) { super(name); } protected RenderState createRenderState(RenderState prevRenderState) { return new BlockQuoteRenderState(prevRenderState, this); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLBodyElementImpl.java0000644000175000017500000000671010726473504030124 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 8, 2005 */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.*; import org.mozilla.javascript.Function; import org.w3c.dom.Document; import org.w3c.dom.html2.*; public class HTMLBodyElementImpl extends HTMLAbstractUIElement implements HTMLBodyElement { public HTMLBodyElementImpl(String name) { super(name); } void setOwnerDocument(Document value, boolean deep) { super.setOwnerDocument(value, deep); if(value instanceof HTMLDocument) { ((HTMLDocument) value).setBody(this); } } void setOwnerDocument(Document value) { super.setOwnerDocument(value); if(value instanceof HTMLDocument) { ((HTMLDocument) value).setBody(this); } } public String getALink() { return this.getAttribute("alink"); } public void setALink(String aLink) { this.setAttribute("alink", aLink); } public String getBackground() { return this.getAttribute("background"); } public void setBackground(String background) { this.setAttribute("background", background); } public String getBgColor() { return this.getAttribute("bgcolor"); } public void setBgColor(String bgColor) { this.setAttribute("bgcolor", bgColor); } public String getLink() { return this.getAttribute("link"); } public void setLink(String link) { this.setAttribute("link", link); } public String getText() { return this.getAttribute("text"); } public void setText(String text) { this.setAttribute("text", text); } public String getVLink() { return this.getAttribute("vlink"); } public void setVLink(String vLink) { this.setAttribute("vlink", vLink); } protected RenderState createRenderState(RenderState prevRenderState) { return new BodyRenderState(prevRenderState, this); } public Function getOnload() { Object document = this.document; if(document instanceof HTMLDocumentImpl) { return ((HTMLDocumentImpl) document).getOnloadHandler(); } else { return null; } } public void setOnload(Function onload) { Object document = this.document; if(document instanceof HTMLDocumentImpl) { //Note that body.onload overrides //Window.onload. ((HTMLDocumentImpl) document).setOnloadHandler(onload); } } protected void assignAttributeField(String normalName, String value) { if("onload".equals(normalName)) { Function onload = this.getEventFunction(null, normalName); if(onload != null) { this.setOnload(onload); } } else { super.assignAttributeField(normalName, value); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLButtonElementImpl.java0000644000175000017500000000206510726473506030503 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.domimpl; public class HTMLButtonElementImpl extends HTMLBaseInputElement { public HTMLButtonElementImpl(String name) { super(name); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLCenterElementImpl.java0000644000175000017500000000244510726473504030450 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.*; public class HTMLCenterElementImpl extends HTMLAbstractUIElement { public HTMLCenterElementImpl(String name) { super(name); } protected RenderState createRenderState(RenderState prevRenderState) { prevRenderState = new AlignXRenderState(prevRenderState, 50); return new BlockRenderState(prevRenderState, this); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLDivElementImpl.java0000644000175000017500000000374311111755164027746 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.*; import org.w3c.dom.html2.HTMLDivElement; public class HTMLDivElementImpl extends HTMLAbstractUIElement implements HTMLDivElement { public HTMLDivElementImpl(String name) { super(name); } public String getAlign() { return this.getAttribute("align"); } public void setAlign(String align) { this.setAttribute("align", align); } protected RenderState createRenderState(RenderState prevRenderState) { return new BlockRenderState(prevRenderState, this); } protected void appendInnerTextImpl(StringBuffer buffer) { int length = buffer.length(); int lineBreaks; if(length == 0) { lineBreaks = 2; } else { int start = length - 2; if (start < 0) { start = 0; } lineBreaks = 0; for(int i = start; i < length; i++) { char ch = buffer.charAt(i); if(ch == '\n') { lineBreaks++; } } } for(int i = 0; i < 1 - lineBreaks; i++) { buffer.append("\r\n"); } super.appendInnerTextImpl(buffer); buffer.append("\r\n"); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLDocumentImpl.java0000644000175000017500000011101411067635334027465 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Sep 3, 2005 */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.*; import org.lobobrowser.html.io.*; import org.lobobrowser.html.js.*; import org.lobobrowser.html.parser.HtmlParser; import org.lobobrowser.html.style.*; import org.lobobrowser.util.*; import org.lobobrowser.util.io.EmptyReader; import org.w3c.dom.*; import org.w3c.dom.css.CSSStyleSheet; import org.w3c.dom.views.*; import org.w3c.dom.html2.*; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.mozilla.javascript.Function; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.logging.*; import java.security.*; /** * Implementation of the W3C HTMLDocument interface. */ public class HTMLDocumentImpl extends NodeImpl implements HTMLDocument, DocumentView { private static final Logger logger = Logger.getLogger(HTMLDocumentImpl.class.getName()); private final ElementFactory factory; private final HtmlRendererContext rcontext; private final UserAgentContext ucontext; private final Window window; private final Map elementsById = new WeakValueHashMap(); private String documentURI; private java.net.URL documentURL; private WritableLineReader reader; public HTMLDocumentImpl(HtmlRendererContext rcontext) { this(rcontext.getUserAgentContext(), rcontext, null, null); } public HTMLDocumentImpl(UserAgentContext ucontext) { this(ucontext, null, null, null); } public HTMLDocumentImpl(final UserAgentContext ucontext, final HtmlRendererContext rcontext, WritableLineReader reader, String documentURI) { this.factory = ElementFactory.getInstance(); this.rcontext = rcontext; this.ucontext = ucontext; this.reader = reader; this.documentURI = documentURI; try { java.net.URL docURL = new java.net.URL(documentURI); SecurityManager sm = System.getSecurityManager(); if(sm != null) { // Do not allow creation of HTMLDocumentImpl if there's // no permission to connect to the host of the URL. // This is so that cookies cannot be written arbitrarily // with setCookie() method. sm.checkPermission(new java.net.SocketPermission(docURL.getHost(), "connect")); } this.documentURL = docURL; this.domain = docURL.getHost(); } catch(java.net.MalformedURLException mfu) { logger.warning("HTMLDocumentImpl(): Document URI [" + documentURI + "] is malformed."); } this.document = this; // Get Window object Window window; if(rcontext != null) { window = Window.getWindow(rcontext); } else { // Plain parsers may use Javascript too. window = new Window(null, ucontext); } // Window must be retained or it will be garbage collected. this.window = window; window.setDocument(this); // Set up Javascript scope this.setUserData(Executor.SCOPE_KEY, window.getWindowScope(), null); } private Set locales; /** * Gets an immutable set of locales previously set for this document. */ public Set getLocales() { return locales; } /** * Sets the locales of the document. This helps * determine whether specific fonts can display text * in the languages of all the locales. * @param locales An immutable set of java.util.Locale instances. */ public void setLocales(Set locales) { this.locales = locales; } String getDocumentHost() { URL docUrl = this.documentURL; return docUrl == null ? null : docUrl.getHost(); } public URL getDocumentURL() { //TODO: Security considerations? return this.documentURL; } /** * Caller should synchronize on document. */ void setElementById(String id, Element element) { synchronized(this) { this.elementsById.put(id, element); } } void removeElementById(String id) { synchronized(this) { this.elementsById.remove(id); } } private volatile String baseURI; /* (non-Javadoc) * @see org.xamjwg.html.domimpl.NodeImpl#getbaseURI() */ public String getBaseURI() { String buri = this.baseURI; return buri == null ? this.documentURI : buri; } public void setBaseURI(String value) { this.baseURI = value; } private String defaultTarget; public String getDefaultTarget() { return this.defaultTarget; } public void setDefaultTarget(String value) { this.defaultTarget = value; } public AbstractView getDefaultView() { return this.window; } public String getTextContent() throws DOMException { return null; } public void setTextContent(String textContent) throws DOMException { // NOP, per spec } private String title; public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } private String referrer; public String getReferrer() { return this.referrer; } public void setReferrer(String value) { this.referrer = value; } private String domain; public String getDomain() { return this.domain; } public void setDomain(String domain) { String oldDomain = this.domain; if(oldDomain != null && Domains.isValidCookieDomain(domain, oldDomain)) { this.domain = domain; } else { throw new SecurityException("Cannot set domain to '" + domain + "' when current domain is '" + oldDomain + "'"); } } public HTMLElement getBody() { synchronized(this) { return this.body; } } private HTMLCollection images; private HTMLCollection applets; private HTMLCollection links; private HTMLCollection forms; private HTMLCollection anchors; private HTMLCollection frames; public HTMLCollection getImages() { synchronized(this) { if(this.images == null) { this.images = new DescendentHTMLCollection(this, new ImageFilter(), this.treeLock); } return this.images; } } public HTMLCollection getApplets() { synchronized(this) { if(this.applets == null) { //TODO: Should include OBJECTs that are applets? this.applets = new DescendentHTMLCollection(this, new AppletFilter(), this.treeLock); } return this.applets; } } public HTMLCollection getLinks() { synchronized(this) { if(this.links == null) { this.links = new DescendentHTMLCollection(this, new LinkFilter(), this.treeLock); } return this.links; } } public HTMLCollection getForms() { synchronized(this) { if(this.forms == null) { this.forms = new DescendentHTMLCollection(this, new FormFilter(), this.treeLock); } return this.forms; } } public HTMLCollection getFrames() { synchronized(this) { if(this.frames == null) { this.frames = new DescendentHTMLCollection(this, new FrameFilter(), this.treeLock); } return this.frames; } } public HTMLCollection getAnchors() { synchronized(this) { if(this.anchors == null) { this.anchors = new DescendentHTMLCollection(this, new AnchorFilter(), this.treeLock); } return this.anchors; } } public String getCookie() { SecurityManager sm = System.getSecurityManager(); if(sm != null) { return (String) AccessController.doPrivileged(new PrivilegedAction() { // Justification: A caller (e.g. Google Analytics script) // might want to get cookies from the parent document. // If the caller has access to the document, it appears // they should be able to get cookies on that document. // Note that this Document instance cannot be created // with an arbitrary URL. // TODO: Security: Review rationale. public Object run() { return ucontext.getCookie(documentURL); } }); } else { return this.ucontext.getCookie(this.documentURL); } } public void setCookie(final String cookie) throws DOMException { SecurityManager sm = System.getSecurityManager(); if(sm != null) { AccessController.doPrivileged(new PrivilegedAction() { // Justification: A caller (e.g. Google Analytics script) // might want to set cookies on the parent document. // If the caller has access to the document, it appears // they should be able to set cookies on that document. // Note that this Document instance cannot be created // with an arbitrary URL. public Object run() { ucontext.setCookie(documentURL, cookie); return null; } }); } else { this.ucontext.setCookie(this.documentURL, cookie); } } public void open() { synchronized(this.treeLock) { if(this.reader != null) { if(this.reader instanceof LocalWritableLineReader) { try { this.reader.close(); } catch(IOException ioe) { //ignore } this.reader = null; } else { // Already open, return. // Do not close http/file documents in progress. return; } } this.removeAllChildrenImpl(); this.reader = new LocalWritableLineReader(new EmptyReader()); } } /** * Loads the document from the reader provided when the * current instance of HTMLDocumentImpl was constructed. * It then closes the reader. * @throws IOException * @throws SAXException * @throws UnsupportedEncodingException */ public void load() throws IOException,SAXException,UnsupportedEncodingException { this.load(true); } public void load(boolean closeReader) throws IOException,SAXException,UnsupportedEncodingException { WritableLineReader reader; synchronized(this.treeLock) { this.removeAllChildrenImpl(); this.setTitle(null); this.setBaseURI(null); this.setDefaultTarget(null); this.styleSheets.clear(); this.styleSheetAggregator = null; reader = this.reader; } if(reader != null) { try { ErrorHandler errorHandler = new LocalErrorHandler(); String systemId = this.documentURI; String publicId = systemId; HtmlParser parser = new HtmlParser(this.ucontext, this, errorHandler, publicId, systemId); parser.parse(reader); } finally { if(closeReader) { try { reader.close(); } catch(Exception err) { logger.log(Level.WARNING,"load(): Unable to close stream", err); } synchronized(this.treeLock) { this.reader = null; } } } } } public void close() { synchronized(this.treeLock) { if(this.reader instanceof LocalWritableLineReader) { try { this.reader.close(); } catch(java.io.IOException ioe) { // ignore } this.reader = null; } else { // do nothing - could be parsing document off the web. } //TODO: cause it to render } } public void write(String text) { synchronized(this.treeLock) { if(this.reader != null) { try { // This can end up in openBufferChanged this.reader.write(text); } catch(IOException ioe) { //ignore } } } } public void writeln(String text) { synchronized(this.treeLock) { if(this.reader != null) { try { // This can end up in openBufferChanged this.reader.write(text + "\r\n"); } catch(IOException ioe) { //ignore } } } } private void openBufferChanged(String text) { // Assumed to execute in a lock // Assumed that text is not broken up HTML. ErrorHandler errorHandler = new LocalErrorHandler(); String systemId = this.documentURI; String publicId = systemId; HtmlParser parser = new HtmlParser(this.ucontext, this, errorHandler, publicId, systemId); StringReader strReader = new StringReader(text); try { // This sets up another Javascript scope Window. Does it matter? parser.parse(strReader); } catch(Exception err) { this.warn("Unable to parse written HTML text. BaseURI=[" + this.getBaseURI() + "].", err); } } /** * Gets the collection of elements whose name * attribute is elementName. */ public NodeList getElementsByName(String elementName) { return this.getNodeList(new ElementNameFilter(elementName)); } private DocumentType doctype; public DocumentType getDoctype() { return this.doctype; } public void setDoctype(DocumentType doctype) { this.doctype = doctype; } public Element getDocumentElement() { synchronized(this.treeLock) { ArrayList nl = this.nodeList; if(nl != null) { Iterator i = nl.iterator(); while(i.hasNext()) { Object node = i.next(); if(node instanceof Element) { return (Element) node; } } } return null; } } public Element createElement(String tagName) throws DOMException { return this.factory.createElement(this, tagName); } /* (non-Javadoc) * @see org.w3c.dom.Document#createDocumentFragment() */ public DocumentFragment createDocumentFragment() { //TODO: According to documentation, when a document //fragment is added to a node, its children are added, //not itself. DocumentFragmentImpl node = new DocumentFragmentImpl(); node.setOwnerDocument(this); return node; } public Text createTextNode(String data) { TextImpl node = new TextImpl(data); node.setOwnerDocument(this); return node; } public Comment createComment(String data) { CommentImpl node = new CommentImpl(data); node.setOwnerDocument(this); return node; } public CDATASection createCDATASection(String data) throws DOMException { CDataSectionImpl node = new CDataSectionImpl(data); node.setOwnerDocument(this); return node; } public ProcessingInstruction createProcessingInstruction( String target, String data) throws DOMException { HTMLProcessingInstruction node = new HTMLProcessingInstruction(target, data); node.setOwnerDocument(this); return node; } public Attr createAttribute(String name) throws DOMException { return new AttrImpl(name); } public EntityReference createEntityReference(String name) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "HTML document"); } /** * Gets all elements that match the given tag name. * @param tagname The element tag name or an asterisk * character (*) to match all elements. */ public NodeList getElementsByTagName(String tagname) { if("*".equals(tagname)) { return this.getNodeList(new ElementFilter()); } else { return this.getNodeList(new TagNameFilter(tagname)); } } public Node importNode(Node importedNode, boolean deep) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Not implemented"); } public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "HTML document"); } public Attr createAttributeNS(String namespaceURI, String qualifiedName) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "HTML document"); } public NodeList getElementsByTagNameNS(String namespaceURI, String localName) { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "HTML document"); } public Element getElementById(String elementId) { Element element; synchronized(this) { element = (Element) this.elementsById.get(elementId); } return element; } private final Map elementsByName = new HashMap(0); public Element namedItem(String name) { Element element; synchronized(this) { element = (Element) this.elementsByName.get(name); } return element; } void setNamedItem(String name, Element element) { synchronized(this) { this.elementsByName.put(name, element); } } void removeNamedItem(String name) { synchronized(this) { this.elementsByName.remove(name); } } private String inputEncoding; public String getInputEncoding() { return this.inputEncoding; } private String xmlEncoding; public String getXmlEncoding() { return this.xmlEncoding; } private boolean xmlStandalone; public boolean getXmlStandalone() { return this.xmlStandalone; } public void setXmlStandalone(boolean xmlStandalone) throws DOMException { this.xmlStandalone = xmlStandalone; } private String xmlVersion = null; public String getXmlVersion() { return this.xmlVersion; } public void setXmlVersion(String xmlVersion) throws DOMException { this.xmlVersion = xmlVersion; } private boolean strictErrorChecking = true; public boolean getStrictErrorChecking() { return this.strictErrorChecking; } public void setStrictErrorChecking(boolean strictErrorChecking) { this.strictErrorChecking = strictErrorChecking; } public String getDocumentURI() { return this.documentURI; } public void setDocumentURI(String documentURI) { //TODO: Security considerations? Chaging documentURL? this.documentURI = documentURI; } public Node adoptNode(Node source) throws DOMException { if(source instanceof NodeImpl) { NodeImpl node = (NodeImpl) source; node.setOwnerDocument(this, true); return node; } else { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Invalid Node implementation"); } } private DOMConfiguration domConfig; public DOMConfiguration getDomConfig() { synchronized(this) { if(this.domConfig == null) { this.domConfig = new DOMConfigurationImpl(); } return this.domConfig; } } public void normalizeDocument() { //TODO: Normalization options from domConfig synchronized(this.treeLock) { this.visitImpl(new NodeVisitor() { public void visit(Node node) { node.normalize(); } }); } } public Node renameNode(Node n, String namespaceURI, String qualifiedName) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "No renaming"); } private DOMImplementation domImplementation; /* (non-Javadoc) * @see org.w3c.dom.Document#getImplementation() */ public DOMImplementation getImplementation() { synchronized(this) { if(this.domImplementation == null) { this.domImplementation = new DOMImplementationImpl(this.ucontext); } return this.domImplementation; } } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.NodeImpl#getLocalName() */ public String getLocalName() { // Always null for document return null; } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.NodeImpl#getNodeName() */ public String getNodeName() { return "#document"; } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.NodeImpl#getNodeType() */ public short getNodeType() { return Node.DOCUMENT_NODE; } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.NodeImpl#getNodeValue() */ public String getNodeValue() throws DOMException { // Always null for document return null; } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.NodeImpl#setNodeValue(java.lang.String) */ public void setNodeValue(String nodeValue) throws DOMException { throw new DOMException(DOMException.INVALID_MODIFICATION_ERR, "Cannot set node value of document"); } public final HtmlRendererContext getHtmlRendererContext() { return this.rcontext; } public UserAgentContext getUserAgentContext() { return this.ucontext; } public final URL getFullURL(String uri) { try { String baseURI = this.getBaseURI(); URL documentURL = baseURI == null ? null : new URL(baseURI); return Urls.createURL(documentURL, uri); } catch(MalformedURLException mfu) { // Try agan, without the baseURI. try { return new URL(uri); } catch(MalformedURLException mfu2) { logger.log(Level.WARNING,"Unable to create URL for URI=[" + uri + "], with base=[" + this.getBaseURI() + "].", mfu); return null; } } } public final Location getLocation() { return this.window.getLocation(); } public void setLocation(String location) { this.getLocation().setHref(location); } public String getURL() { return this.documentURI; } private HTMLElement body; public void setBody(HTMLElement body) { synchronized(this) { this.body = body; } } private final Collection styleSheets = new CSSStyleSheetList(); public class CSSStyleSheetList extends ArrayList { public int getLength(){ return this.size(); } public CSSStyleSheet item(int index){ return (CSSStyleSheet) get(index); } } final void addStyleSheet(CSSStyleSheet ss) { synchronized(this.treeLock) { this.styleSheets.add(ss); this.styleSheetAggregator = null; // Need to invalidate all children up to // this point. this.forgetRenderState(); //TODO: this might be ineffcient. ArrayList nl = this.nodeList; if(nl != null) { Iterator i = nl.iterator(); while(i.hasNext()) { Object node = i.next(); if(node instanceof HTMLElementImpl) { ((HTMLElementImpl) node).forgetStyle(true); } } } } this.allInvalidated(); } public void allInvalidated(boolean forgetRenderStates) { if(forgetRenderStates) { synchronized(this.treeLock) { this.styleSheetAggregator = null; // Need to invalidate all children up to // this point. this.forgetRenderState(); //TODO: this might be ineffcient. ArrayList nl = this.nodeList; if(nl != null) { Iterator i = nl.iterator(); while(i.hasNext()) { Object node = i.next(); if(node instanceof HTMLElementImpl) { ((HTMLElementImpl) node).forgetStyle(true); } } } } } this.allInvalidated(); } public Collection getStyleSheets(){ return this.styleSheets; } private StyleSheetAggregator styleSheetAggregator = null; final StyleSheetAggregator getStyleSheetAggregator() { synchronized(this.treeLock) { StyleSheetAggregator ssa = this.styleSheetAggregator; if(ssa == null) { ssa = new StyleSheetAggregator(this); try { ssa.addStyleSheets(this.styleSheets); } catch(MalformedURLException mfu) { logger.log(Level.WARNING,"getStyleSheetAggregator()", mfu); } this.styleSheetAggregator = ssa; } return ssa; } } private final ArrayList documentNotificationListeners = new ArrayList(1); /** * Adds a document notification listener, which is informed about * changes to the document. * @param listener An instance of {@link DocumentNotificationListener}. */ public void addDocumentNotificationListener(DocumentNotificationListener listener) { ArrayList listenersList = this.documentNotificationListeners; synchronized(listenersList) { listenersList.add(listener); } } public void removeDocumentNotificationListener(DocumentNotificationListener listener) { ArrayList listenersList = this.documentNotificationListeners; synchronized(listenersList) { listenersList.remove(listener); } } public void sizeInvalidated(NodeImpl node) { ArrayList listenersList = this.documentNotificationListeners; int size; synchronized(listenersList) { size = listenersList.size(); } // Traverse list outside synchronized block. // (Shouldn't call listener methods in synchronized block. // Deadlock is possible). But assume list could have // been changed. for(int i = 0; i < size; i++) { try { DocumentNotificationListener dnl = (DocumentNotificationListener) listenersList.get(i); dnl.sizeInvalidated(node); } catch(IndexOutOfBoundsException iob) { // ignore } } } /** * Called if something such as a color or * decoration has changed. This would be * something which does not affect the * rendered size, and can be revalidated * with a simple repaint. * @param node */ public void lookInvalidated(NodeImpl node) { ArrayList listenersList = this.documentNotificationListeners; int size; synchronized(listenersList) { size = listenersList.size(); } // Traverse list outside synchronized block. // (Shouldn't call listener methods in synchronized block. // Deadlock is possible). But assume list could have // been changed. for(int i = 0; i < size; i++) { try { DocumentNotificationListener dnl = (DocumentNotificationListener) listenersList.get(i); dnl.lookInvalidated(node); } catch(IndexOutOfBoundsException iob) { // ignore } } } /** * Changed if the position of the node in a * parent has changed. * @param node */ public void positionInParentInvalidated(NodeImpl node) { ArrayList listenersList = this.documentNotificationListeners; int size; synchronized(listenersList) { size = listenersList.size(); } // Traverse list outside synchronized block. // (Shouldn't call listener methods in synchronized block. // Deadlock is possible). But assume list could have // been changed. for(int i = 0; i < size; i++) { try { DocumentNotificationListener dnl = (DocumentNotificationListener) listenersList.get(i); dnl.positionInvalidated(node); } catch(IndexOutOfBoundsException iob) { // ignore } } } /** * This is called when the node has changed, but * it is unclear if it's a size change or a look * change. An attribute change should trigger this. * @param node */ public void invalidated(NodeImpl node) { ArrayList listenersList = this.documentNotificationListeners; int size; synchronized(listenersList) { size = listenersList.size(); } // Traverse list outside synchronized block. // (Shouldn't call listener methods in synchronized block. // Deadlock is possible). But assume list could have // been changed. for(int i = 0; i < size; i++) { try { DocumentNotificationListener dnl = (DocumentNotificationListener) listenersList.get(i); dnl.invalidated(node); } catch(IndexOutOfBoundsException iob) { // ignore } } } /** * This is called when children of the node might * have changed. * @param node */ public void structureInvalidated(NodeImpl node) { ArrayList listenersList = this.documentNotificationListeners; int size; synchronized(listenersList) { size = listenersList.size(); } // Traverse list outside synchronized block. // (Shouldn't call listener methods in synchronized block. // Deadlock is possible). But assume list could have // been changed. for(int i = 0; i < size; i++) { try { DocumentNotificationListener dnl = (DocumentNotificationListener) listenersList.get(i); dnl.structureInvalidated(node); } catch(IndexOutOfBoundsException iob) { // ignore } } } public void nodeLoaded(NodeImpl node) { ArrayList listenersList = this.documentNotificationListeners; int size; synchronized(listenersList) { size = listenersList.size(); } // Traverse list outside synchronized block. // (Shouldn't call listener methods in synchronized block. // Deadlock is possible). But assume list could have // been changed. for(int i = 0; i < size; i++) { try { DocumentNotificationListener dnl = (DocumentNotificationListener) listenersList.get(i); dnl.nodeLoaded(node); } catch(IndexOutOfBoundsException iob) { // ignore } } } public void externalScriptLoading(NodeImpl node) { ArrayList listenersList = this.documentNotificationListeners; int size; synchronized(listenersList) { size = listenersList.size(); } // Traverse list outside synchronized block. // (Shouldn't call listener methods in synchronized block. // Deadlock is possible). But assume list could have // been changed. for(int i = 0; i < size; i++) { try { DocumentNotificationListener dnl = (DocumentNotificationListener) listenersList.get(i); dnl.externalScriptLoading(node); } catch(IndexOutOfBoundsException iob) { // ignore } } } /** * Informs listeners that the whole document has been * invalidated. */ public void allInvalidated() { ArrayList listenersList = this.documentNotificationListeners; int size; synchronized(listenersList) { size = listenersList.size(); } // Traverse list outside synchronized block. // (Shouldn't call listener methods in synchronized block. // Deadlock is possible). But assume list could have // been changed. for(int i = 0; i < size; i++) { try { DocumentNotificationListener dnl = (DocumentNotificationListener) listenersList.get(i); dnl.allInvalidated(); } catch(IndexOutOfBoundsException iob) { // ignore } } } protected RenderState createRenderState(RenderState prevRenderState) { return new StyleSheetRenderState(this); } private final Map imageInfos = new HashMap(4); private final ImageEvent BLANK_IMAGE_EVENT = new ImageEvent(this, null); /** * Loads images asynchronously such that they are shared if loaded * simultaneously from the same URI. * Informs the listener immediately if an image is already known. * @param relativeUri * @param imageListener */ protected void loadImage(String relativeUri, ImageListener imageListener) { HtmlRendererContext rcontext = this.getHtmlRendererContext(); if(rcontext == null || !rcontext.isImageLoadingEnabled()) { // Ignore image loading when there's no renderer context. // Consider Cobra users who are only using the parser. imageListener.imageLoaded(BLANK_IMAGE_EVENT); return; } final URL url = this.getFullURL(relativeUri); if(url == null) { imageListener.imageLoaded(BLANK_IMAGE_EVENT); return; } final String urlText = url.toExternalForm(); final Map map = this.imageInfos; ImageEvent event = null; synchronized(map) { ImageInfo info = (ImageInfo) map.get(urlText); if(info != null) { if(info.loaded) { // TODO: This can't really happen because ImageInfo // is removed right after image is loaded. event = info.imageEvent; } else { info.addListener(imageListener); } } else { UserAgentContext uac = rcontext.getUserAgentContext(); final HttpRequest httpRequest = uac.createHttpRequest(); final ImageInfo newInfo = new ImageInfo(); map.put(urlText, newInfo); newInfo.addListener(imageListener); httpRequest.addReadyStateChangeListener(new ReadyStateChangeListener() { public void readyStateChanged() { if(httpRequest.getReadyState() == HttpRequest.STATE_COMPLETE) { java.awt.Image newImage = httpRequest.getResponseImage(); ImageEvent newEvent = newImage == null ? null : new ImageEvent(HTMLDocumentImpl.this, newImage); ImageListener[] listeners; synchronized(map) { newInfo.imageEvent = newEvent; newInfo.loaded = true; listeners = newEvent == null ? null : newInfo.getListeners(); // Must remove from map in the locked block // that got the listeners. Otherwise a new // listener might miss the event?? map.remove(urlText); } if(listeners != null) { int llength = listeners.length; for(int i = 0; i < llength; i++) { // Call holding no locks listeners[i].imageLoaded(newEvent); } } } } }); SecurityManager sm = System.getSecurityManager(); if(sm == null) { try { httpRequest.open("GET", url, true); httpRequest.send(null); } catch(java.io.IOException thrown) { logger.log(Level.WARNING, "loadImage()", thrown); } } else { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { // Code might have restrictions on accessing // items from elsewhere. try { httpRequest.open("GET", url, true); httpRequest.send(null); } catch(java.io.IOException thrown) { logger.log(Level.WARNING, "loadImage()", thrown); } return null; } }); } } } if(event != null) { // Call holding no locks. imageListener.imageLoaded(event); } } private Function onloadHandler; public Function getOnloadHandler() { return onloadHandler; } public void setOnloadHandler(Function onloadHandler) { this.onloadHandler = onloadHandler; } public Object setUserData(String key, Object data, UserDataHandler handler) { Function onloadHandler = this.onloadHandler; if(onloadHandler != null) { if(org.lobobrowser.html.parser.HtmlParser.MODIFYING_KEY.equals(key) && data == Boolean.FALSE) { //TODO: onload event object? Executor.executeFunction(this, onloadHandler, null); } } return super.setUserData(key, data, handler); } protected Node createSimilarNode() { return new HTMLDocumentImpl(this.ucontext, this.rcontext, this.reader, this.documentURI); } private static class ImageInfo { // Access to this class is synchronized on imageInfos. public ImageEvent imageEvent; public boolean loaded; private ArrayList listeners = new ArrayList(1); void addListener(ImageListener listener) { this.listeners.add(listener); } ImageListener[] getListeners() { return (ImageListener[]) this.listeners.toArray(ImageListener.EMPTY_ARRAY); } } private class ImageFilter implements NodeFilter { public boolean accept(Node node) { return "IMG".equalsIgnoreCase(node.getNodeName()); } } private class AppletFilter implements NodeFilter { public boolean accept(Node node) { //TODO: "OBJECT" elements that are applets too. return "APPLET".equalsIgnoreCase(node.getNodeName()); } } private class LinkFilter implements NodeFilter { public boolean accept(Node node) { return node instanceof HTMLLinkElement; } } private class AnchorFilter implements NodeFilter { public boolean accept(Node node) { String nodeName = node.getNodeName(); return "A".equalsIgnoreCase(nodeName) || "ANCHOR".equalsIgnoreCase(nodeName); } } private class FormFilter implements NodeFilter { public boolean accept(Node node) { String nodeName = node.getNodeName(); return "FORM".equalsIgnoreCase(nodeName); } } private class FrameFilter implements NodeFilter { public boolean accept(Node node) { return node instanceof org.w3c.dom.html2.HTMLFrameElement || node instanceof org.w3c.dom.html2.HTMLIFrameElement; } } // private class BodyFilter implements NodeFilter { // public boolean accept(Node node) { // return node instanceof org.w3c.dom.html2.HTMLBodyElement; // } // } private class ElementNameFilter implements NodeFilter { private final String name; public ElementNameFilter(String name) { this.name = name; } public boolean accept(Node node) { //TODO: Case sensitive? return (node instanceof Element) && this.name.equals(((Element) node).getAttribute("name")); } } private class ElementFilter implements NodeFilter { public ElementFilter() { } public boolean accept(Node node) { return node instanceof Element; } } private class TagNameFilter implements NodeFilter { private final String name; public TagNameFilter(String name) { this.name = name; } public boolean accept(Node node) { if(!(node instanceof Element)) { return false; } String n = this.name; return n.equalsIgnoreCase(((Element) node).getTagName()); } } /** * Tag class that also notifies document * when text is written to an open buffer. * @author J. H. S. */ private class LocalWritableLineReader extends WritableLineReader { /** * @param reader */ public LocalWritableLineReader(LineNumberReader reader) { super(reader); } /** * @param reader */ public LocalWritableLineReader(Reader reader) { super(reader); } public void write(String text) throws IOException { super.write(text); if("".equals(text)) { openBufferChanged(text); } } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLElementBuilder.java0000644000175000017500000002206411047522134027762 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 8, 2005 */ package org.lobobrowser.html.domimpl; import org.w3c.dom.html2.*; public abstract class HTMLElementBuilder { public final HTMLElement create(HTMLDocument document, String name) { HTMLElementImpl element = this.build(name); element.setOwnerDocument(document); return element; } protected abstract HTMLElementImpl build(String name); public static class Html extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLHtmlElementImpl(name); } } public static class Title extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLTitleElementImpl(name); } } public static class Base extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLBaseElementImpl(name); } } public static class Body extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLBodyElementImpl(name); } } public static class Span extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLSpanElementImpl(name); } } public static class Script extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLScriptElementImpl(name); } } public static class Img extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLImageElementImpl(name); } } public static class Style extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLStyleElementImpl(name); } } public static class Table extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLTableElementImpl(name); } } public static class Td extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLTableCellElementImpl(name); } } public static class Th extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLTableHeadElementImpl(name); } } public static class Tr extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLTableRowElementImpl(name); } } public static class Link extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLLinkElementImpl(name); } } public static class Anchor extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLLinkElementImpl(name); } } public static class Form extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLFormElementImpl(name); } } public static class Input extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLInputElementImpl(name); } } public static class Button extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLButtonElementImpl(name); } } public static class Textarea extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLTextAreaElementImpl(name); } } public static class Select extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLSelectElementImpl(name); } } public static class Option extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLOptionElementImpl(name); } } public static class Frameset extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLFrameSetElementImpl(name); } } public static class Frame extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLFrameElementImpl(name); } } public static class Ul extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLUListElementImpl(name); } } public static class Ol extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLOListElementImpl(name); } } public static class Li extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLLIElementImpl(name); } } public static class Pre extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLPreElementImpl(name); } } public static class Div extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLDivElementImpl(name); } } public static class Blockquote extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLBlockQuoteElementImpl(name); } } public static class Hr extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLHRElementImpl(name); } } public static class Br extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLBRElementImpl(name); } } public static class P extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLPElementImpl(name); } } public static class GenericMarkup extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLGenericMarkupElement(name); } } public static class HtmlObject extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLObjectElementImpl(name); } } public static class Applet extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLAppletElementImpl(name); } } public static class IFrame extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLIFrameElementImpl(name); } } public static class BaseFont extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLBaseFontElementImpl(name); } } public static class Font extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLFontElementImpl(name); } } public static class Tt extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLMonospacedElementImpl(name); } } public static class Code extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLMonospacedElementImpl(name); } } public static class Heading extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLHeadingElementImpl(name); } } public static class Small extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLFontSizeChangeElementImpl(name, -1); } } public static class Big extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLFontSizeChangeElementImpl(name, +1); } } public static class Em extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLEmElementImpl(name); } } public static class Strong extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLStrongElementImpl(name); } } public static class Underline extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLUnderlineElementImpl(name); } } public static class Strike extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLStrikeElementImpl(name); } } public static class Center extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLCenterElementImpl(name); } } public static class NonStandard extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLNonStandardElement(name); } } public static class Sup extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLSuperscriptElementImpl(name,1); } } public static class Sub extends HTMLElementBuilder { public HTMLElementImpl build(String name) { return new HTMLSuperscriptElementImpl(name,-1); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLElementImpl.java0000644000175000017500000005720011134547602027301 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Sep 3, 2005 */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.FormInput; import org.lobobrowser.html.parser.HtmlParser; import org.lobobrowser.html.style.*; import org.lobobrowser.util.*; import org.w3c.css.sac.InputSource; import org.w3c.dom.*; import org.w3c.dom.css.CSSStyleDeclaration; import org.w3c.dom.html2.*; import com.steadystate.css.parser.CSSOMParser; import java.io.*; import java.util.*; import java.util.logging.*; public class HTMLElementImpl extends ElementImpl implements HTMLElement, CSS2PropertiesContext { private final boolean noStyleSheet; public HTMLElementImpl(String name, boolean noStyleSheet) { super(name); this.noStyleSheet = noStyleSheet; } public HTMLElementImpl(String name) { super(name); this.noStyleSheet = false; } private volatile AbstractCSS2Properties currentStyleDeclarationState; private volatile AbstractCSS2Properties localStyleDeclarationState; protected final void forgetLocalStyle() { synchronized(this) { this.currentStyleDeclarationState = null; this.localStyleDeclarationState = null; this.computedStyles = null; } } protected final void forgetStyle(boolean deep) { //TODO: OPTIMIZATION: If we had a ComputedStyle map in //window (Mozilla model) the map could be cleared in one shot. synchronized(this) { this.currentStyleDeclarationState = null; this.computedStyles = null; this.isHoverStyle = null; this.hasHoverStyleByElement = null; if(deep) { java.util.ArrayList nl = this.nodeList; if(nl != null) { Iterator i = nl.iterator(); while(i.hasNext()) { Object node = i.next(); if(node instanceof HTMLElementImpl) { ((HTMLElementImpl) node).forgetStyle(deep); } } } } } } /** * Gets the style object associated with the element. * It may return null only if the type of element does not handle stylesheets. */ public AbstractCSS2Properties getCurrentStyle() { AbstractCSS2Properties sds; synchronized(this) { sds = this.currentStyleDeclarationState; if(sds != null) { return sds; } } // Can't do the following in synchronized block (reverse locking order with document). // First, add declarations from stylesheet sds = this.createDefaultStyleSheet(); sds = this.addStyleSheetDeclarations(sds, this.getPseudoNames()); // Now add local style if any. AbstractCSS2Properties localStyle = this.getStyle(); if(sds == null) { sds = new ComputedCSS2Properties(this); sds.setLocalStyleProperties(localStyle); } else { sds.setLocalStyleProperties(localStyle); } synchronized(this) { // Check if style properties were set while outside // the synchronized block (can happen). AbstractCSS2Properties setProps = this.currentStyleDeclarationState; if(setProps != null) { return setProps; } this.currentStyleDeclarationState = sds; return sds; } } /** * Gets the local style object associated with the element. The properties * object returned only includes properties from the local style attribute. * It may return null only if the type of element does not handle stylesheets. */ public AbstractCSS2Properties getStyle() { AbstractCSS2Properties sds; synchronized(this) { sds = this.localStyleDeclarationState; if(sds != null) { return sds; } sds = new LocalCSS2Properties(this); // Add any declarations in style attribute (last takes precedence). String style = this.getAttribute("style"); if(style != null && style.length() != 0) { CSSOMParser parser = new CSSOMParser(); InputSource inputSource = this.getCssInputSourceForDecl(style); try { CSSStyleDeclaration sd = parser.parseStyleDeclaration(inputSource); sds.addStyleDeclaration(sd); } catch(Exception err) { String id = this.getId(); String withId = id == null ? "" : " with ID '" + id + "'"; this.warn("Unable to parse style attribute value for element " + this.getTagName() + withId + " in " + this.getDocumentURL() + ".", err); } } this.localStyleDeclarationState = sds; } // Synchronization note: Make sure getStyle() does not return multiple values. return sds; } protected AbstractCSS2Properties createDefaultStyleSheet() { // Override to provide element defaults. return null; } private Map computedStyles; public AbstractCSS2Properties getComputedStyle(String pseudoElement) { if(pseudoElement == null) { pseudoElement = ""; } synchronized(this) { Map cs = this.computedStyles; if(cs != null) { AbstractCSS2Properties sds = (AbstractCSS2Properties) cs.get(pseudoElement); if(sds != null) { return sds; } } } // Can't do the following in synchronized block (reverse locking order with document). // First, add declarations from stylesheet Set pes = pseudoElement.length() == 0 ? null : Collections.singleton(pseudoElement); AbstractCSS2Properties sds = this.createDefaultStyleSheet(); sds = this.addStyleSheetDeclarations(sds, pes); // Now add local style if any. AbstractCSS2Properties localStyle = this.getStyle(); if(sds == null) { sds = new ComputedCSS2Properties(this); sds.setLocalStyleProperties(localStyle); } else { sds.setLocalStyleProperties(localStyle); } synchronized(this) { // Check if style properties were set while outside // the synchronized block (can happen). We need to // return instance already set for consistency. Map cs = this.computedStyles; if(cs == null) { cs = new HashMap(2); this.computedStyles = cs; } else { AbstractCSS2Properties sds2 = (AbstractCSS2Properties) cs.get(pseudoElement); if(sds2 != null) { return sds2; } } cs.put(pseudoElement, sds); } return sds; } public void setStyle(Object value) { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Cannot set style property"); } public void setCurrentStyle(Object value) { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Cannot set currentStyle property"); } public String getClassName() { String className = this.getAttribute("class"); // Blank required instead of null. return className == null ? "" : className; } public void setClassName(String className) { this.setAttribute("class", className); } public String getCharset() { return this.getAttribute("charset"); } public void setCharset(String charset) { this.setAttribute("charset", charset); } public void warn(String message, Throwable err) { logger.log(Level.WARNING, message, err); } public void warn(String message) { logger.log(Level.WARNING, message); } protected int getAttributeAsInt(String name, int defaultValue) { String value = this.getAttribute(name); try { return Integer.parseInt(value); } catch(Exception err) { this.warn("Bad integer", err); return defaultValue; } } public boolean getAttributeAsBoolean(String name) { return this.getAttribute(name) != null; } protected void assignAttributeField(String normalName, String value) { if(!this.notificationsSuspended) { this.informInvalidAttibute(normalName); } else { if("style".equals(normalName)) { this.forgetLocalStyle(); } } super.assignAttributeField(normalName, value); } protected final InputSource getCssInputSourceForDecl(String text) { java.io.Reader reader = new StringReader("{" + text + "}"); InputSource is = new InputSource(reader); return is; } /** * Adds style sheet declarations applicable * to this element. * A properties object is created if necessary * when the one passed is null. * @param style */ protected final AbstractCSS2Properties addStyleSheetDeclarations(AbstractCSS2Properties style, Set pseudoNames) { Node pn = this.parentNode; if(pn == null) { // do later return style; } String classNames = this.getClassName(); if(classNames != null && classNames.length() != 0) { String id = this.getId(); String elementName = this.getTagName(); String[] classNameArray = Strings.split(classNames); for(int i = classNameArray.length; --i >= 0;) { String className = classNameArray[i]; Collection sds = this.findStyleDeclarations(elementName, id, className, pseudoNames); if(sds != null) { Iterator sdsi = sds.iterator(); while(sdsi.hasNext()) { CSSStyleDeclaration sd = (CSSStyleDeclaration) sdsi.next(); if(style == null) { style = new ComputedCSS2Properties(this); } style.addStyleDeclaration(sd); } } } } else { String id = this.getId(); String elementName = this.getTagName(); Collection sds = this.findStyleDeclarations(elementName, id, null, pseudoNames); if(sds != null) { Iterator sdsi = sds.iterator(); while(sdsi.hasNext()) { CSSStyleDeclaration sd = (CSSStyleDeclaration) sdsi.next(); if(style == null) { style = new ComputedCSS2Properties(this); } style.addStyleDeclaration(sd); } } } return style; } private boolean isMouseOver = false; public void setMouseOver(boolean mouseOver) { if(this.isMouseOver != mouseOver) { // Change isMouseOver field before checking to invalidate. this.isMouseOver = mouseOver; // Check if descendents are affected (e.g. div:hover a { ... } ) this.invalidateDescendentsForHover(); if(this.hasHoverStyle()) { //TODO: OPTIMIZATION: In some cases it should be much //better to simply invalidate the "look" of the node. this.informInvalid(); } } } private void invalidateDescendentsForHover() { synchronized(this.treeLock) { this.invalidateDescendentsForHoverImpl(this); } } private void invalidateDescendentsForHoverImpl(HTMLElementImpl ancestor) { ArrayList nodeList = this.nodeList; if(nodeList != null) { int size = nodeList.size(); for(int i = 0; i < size; i++) { Object node = nodeList.get(i); if(node instanceof HTMLElementImpl) { HTMLElementImpl descendent = (HTMLElementImpl) node; if(descendent.hasHoverStyle(ancestor)) { descendent.informInvalid(); } descendent.invalidateDescendentsForHoverImpl(ancestor); } } } } private Boolean isHoverStyle = null; private Map hasHoverStyleByElement = null; private boolean hasHoverStyle() { Boolean ihs; synchronized(this) { ihs = this.isHoverStyle; if(ihs != null) { return ihs.booleanValue(); } } HTMLDocumentImpl doc = (HTMLDocumentImpl) this.document; if(doc == null) { ihs = Boolean.FALSE; } else { StyleSheetAggregator ssa = doc.getStyleSheetAggregator(); String id = this.getId(); String elementName = this.getTagName(); String classNames = this.getClassName(); String[] classNameArray = null; if(classNames != null && classNames.length() != 0) { classNameArray = Strings.split(classNames); } ihs = Boolean.valueOf(ssa.affectedByPseudoNameInAncestor(this, this, elementName, id, classNameArray, "hover")); } synchronized(this) { this.isHoverStyle = ihs; } return ihs.booleanValue(); } private boolean hasHoverStyle(HTMLElementImpl ancestor) { Map ihs; synchronized(this) { ihs = this.hasHoverStyleByElement; if(ihs != null) { Boolean f = (Boolean) ihs.get(ancestor); if(f != null) { return f.booleanValue(); } } } Boolean hhs; HTMLDocumentImpl doc = (HTMLDocumentImpl) this.document; if(doc == null) { hhs = Boolean.FALSE; } else { StyleSheetAggregator ssa = doc.getStyleSheetAggregator(); String id = this.getId(); String elementName = this.getTagName(); String classNames = this.getClassName(); String[] classNameArray = null; if(classNames != null && classNames.length() != 0) { classNameArray = Strings.split(classNames); } hhs = Boolean.valueOf(ssa.affectedByPseudoNameInAncestor(this, ancestor, elementName, id, classNameArray, "hover")); } synchronized(this) { ihs = this.hasHoverStyleByElement; if(ihs == null) { ihs = new HashMap(2); this.hasHoverStyleByElement = ihs; } ihs.put(ancestor, hhs); } return hhs.booleanValue(); } /** * Gets the pseudo-element lowercase names currently * applicable to this element. Method must return * null if there are no such * pseudo-elements. */ public Set getPseudoNames() { Set pnset = null; if(this.isMouseOver) { if(pnset == null) { pnset = new HashSet(1); } pnset.add("hover"); } return pnset; } protected final Collection findStyleDeclarations(String elementName, String id, String className, Set pseudoNames) { HTMLDocumentImpl doc = (HTMLDocumentImpl) this.document; if(doc == null) { return null; } StyleSheetAggregator ssa = doc.getStyleSheetAggregator(); return ssa.getActiveStyleDeclarations(this, elementName, id, className, pseudoNames); } public void informInvalid() { // This is called when an attribute or child changes. this.forgetStyle(false); super.informInvalid(); } public void informInvalidAttibute(String normalName) { // This is called when an attribute changes while // the element is allowing notifications. if("style".equals(normalName)) { this.forgetLocalStyle(); } else if("id".equals(normalName) || "class".equals(normalName)) { this.forgetStyle(false); } // Call super implementation of informValid(). super.informInvalid(); } /** * Gets form input due to the current element. It should * return null except when the element is a form input element. */ protected FormInput[] getFormInputs() { // Override in input elements return null; } private boolean classMatch(String classTL) { String classNames = this.getClassName(); if(classNames == null || classNames.length() == 0) { return classTL == null; } StringTokenizer tok = new StringTokenizer(classNames, " \t\r\n"); while(tok.hasMoreTokens()) { String token = tok.nextToken(); if(token.toLowerCase().equals(classTL)) { return true; } } return false; } /** * Get an ancestor that matches the element tag name given and the * style class given. * @param elementTL An tag name in lowercase or an asterisk (*). * @param classTL A class name in lowercase. */ public HTMLElementImpl getAncestorWithClass(String elementTL, String classTL) { Object nodeObj = this.getParentNode(); if(nodeObj instanceof HTMLElementImpl) { HTMLElementImpl parentElement = (HTMLElementImpl) nodeObj; String pelementTL = parentElement.getTagName().toLowerCase(); if(("*".equals(elementTL) || elementTL.equals(pelementTL)) && parentElement.classMatch(classTL)) { return parentElement; } return parentElement.getAncestorWithClass(elementTL, classTL); } else { return null; } } public HTMLElementImpl getParentWithClass(String elementTL, String classTL) { Object nodeObj = this.getParentNode(); if(nodeObj instanceof HTMLElementImpl) { HTMLElementImpl parentElement = (HTMLElementImpl) nodeObj; String pelementTL = parentElement.getTagName().toLowerCase(); if(("*".equals(elementTL) || elementTL.equals(pelementTL)) && parentElement.classMatch(classTL)) { return parentElement; } } return null; } public HTMLElementImpl getPreceedingSiblingElement() { Node parentNode = this.getParentNode(); if(parentNode == null) { return null; } NodeList childNodes = parentNode.getChildNodes(); if(childNodes == null) { return null; } int length = childNodes.getLength(); HTMLElementImpl priorElement = null; for(int i = 0; i < length; i++) { Node child = childNodes.item(i); if(child == this) { return priorElement; } if(child instanceof HTMLElementImpl) { priorElement = (HTMLElementImpl) child; } } return null; } public HTMLElementImpl getPreceedingSiblingWithClass(String elementTL, String classTL) { HTMLElementImpl psibling = this.getPreceedingSiblingElement(); if(psibling != null) { String pelementTL = psibling.getTagName().toLowerCase(); if(("*".equals(elementTL) || elementTL.equals(pelementTL)) && psibling.classMatch(classTL)) { return psibling; } } return null; } public HTMLElementImpl getAncestorWithId(String elementTL, String idTL) { Object nodeObj = this.getParentNode(); if(nodeObj instanceof HTMLElementImpl) { HTMLElementImpl parentElement = (HTMLElementImpl) nodeObj; String pelementTL = parentElement.getTagName().toLowerCase(); String pid = parentElement.getId(); String pidTL = pid == null ? null : pid.toLowerCase(); if(("*".equals(elementTL) || elementTL.equals(pelementTL)) && idTL.equals(pidTL)) { return parentElement; } return parentElement.getAncestorWithId(elementTL, idTL); } else { return null; } } public HTMLElementImpl getParentWithId(String elementTL, String idTL) { Object nodeObj = this.getParentNode(); if(nodeObj instanceof HTMLElementImpl) { HTMLElementImpl parentElement = (HTMLElementImpl) nodeObj; String pelementTL = parentElement.getTagName().toLowerCase(); String pid = parentElement.getId(); String pidTL = pid == null ? null : pid.toLowerCase(); if(("*".equals(elementTL) || elementTL.equals(pelementTL)) && idTL.equals(pidTL)) { return parentElement; } } return null; } public HTMLElementImpl getPreceedingSiblingWithId(String elementTL, String idTL) { HTMLElementImpl psibling = this.getPreceedingSiblingElement(); if(psibling != null) { String pelementTL = psibling.getTagName().toLowerCase(); String pid = psibling.getId(); String pidTL = pid == null ? null : pid.toLowerCase(); if(("*".equals(elementTL) || elementTL.equals(pelementTL)) && idTL.equals(pidTL)) { return psibling; } } return null; } public HTMLElementImpl getAncestor(String elementTL) { Object nodeObj = this.getParentNode(); if(nodeObj instanceof HTMLElementImpl) { HTMLElementImpl parentElement = (HTMLElementImpl) nodeObj; if("*".equals(elementTL)) { return parentElement; } String pelementTL = parentElement.getTagName().toLowerCase(); if(elementTL.equals(pelementTL)) { return parentElement; } return parentElement.getAncestor(elementTL); } else { return null; } } public HTMLElementImpl getParent(String elementTL) { Object nodeObj = this.getParentNode(); if(nodeObj instanceof HTMLElementImpl) { HTMLElementImpl parentElement = (HTMLElementImpl) nodeObj; if("*".equals(elementTL)) { return parentElement; } String pelementTL = parentElement.getTagName().toLowerCase(); if(elementTL.equals(pelementTL)) { return parentElement; } } return null; } public HTMLElementImpl getPreceedingSibling(String elementTL) { HTMLElementImpl psibling = this.getPreceedingSiblingElement(); if(psibling != null) { if("*".equals(elementTL)) { return psibling; } String pelementTL = psibling.getTagName().toLowerCase(); if(elementTL.equals(pelementTL)) { return psibling; } } return null; } protected Object getAncestorForJavaClass(Class javaClass) { Object nodeObj = this.getParentNode(); if(nodeObj == null || javaClass.isInstance(nodeObj)) { return nodeObj; } else if(nodeObj instanceof HTMLElementImpl) { return ((HTMLElementImpl) nodeObj).getAncestorForJavaClass(javaClass); } else { return null; } } public void setInnerHTML(String newHtml) { HTMLDocumentImpl document = (HTMLDocumentImpl) this.document; if(document == null) { this.warn("setInnerHTML(): Element " + this + " does not belong to a document."); return; } HtmlParser parser = new HtmlParser(document.getUserAgentContext(), document, null, null, null); synchronized(this) { ArrayList nl = this.nodeList; if (nl != null) { nl.clear(); } } // Should not synchronize around parser probably. try { Reader reader = new StringReader(newHtml); try { parser.parse(reader, this); } finally { reader.close(); } } catch(Exception thrown) { this.warn("setInnerHTML(): Error setting inner HTML.", thrown); } } public String getOuterHTML() { StringBuffer buffer = new StringBuffer(); synchronized(this) { this.appendOuterHTMLImpl(buffer); } return buffer.toString(); } protected void appendOuterHTMLImpl(StringBuffer buffer) { String tagName = this.getTagName(); buffer.append('<'); buffer.append(tagName); Map attributes = this.attributes; if(attributes != null) { Iterator i = attributes.entrySet().iterator(); while(i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); String value = (String) entry.getValue(); if(value != null) { buffer.append(' '); buffer.append(entry.getKey()); buffer.append("=\""); buffer.append(Strings.strictHtmlEncode(value, true)); buffer.append("\""); } } } ArrayList nl = this.nodeList; if(nl == null || nl.size() == 0) { buffer.append("/>"); return; } buffer.append('>'); this.appendInnerHTMLImpl(buffer); buffer.append("'); } protected RenderState createRenderState(RenderState prevRenderState) { // Overrides NodeImpl method // Called in synchronized block already return new StyleSheetRenderState(prevRenderState, this); } public int getOffsetTop() { //TODO: Sometimes this can be called while parsing, and //browsers generally give the right answer. UINode uiNode = this.getUINode(); return uiNode == null ? 0 : uiNode.getBoundsRelativeToBlock().y; } public int getOffsetLeft() { UINode uiNode = this.getUINode(); return uiNode == null ? 0 : uiNode.getBoundsRelativeToBlock().x; } public int getOffsetWidth() { UINode uiNode = this.getUINode(); return uiNode == null ? 0 : uiNode.getBoundsRelativeToBlock().width; } public int getOffsetHeight() { UINode uiNode = this.getUINode(); return uiNode == null ? 0 : uiNode.getBoundsRelativeToBlock().height; } public AbstractCSS2Properties getParentStyle() { Object parent = this.parentNode; if(parent instanceof HTMLElementImpl) { return ((HTMLElementImpl) parent).getCurrentStyle(); } return null; } public String getDocumentBaseURI() { HTMLDocumentImpl doc = (HTMLDocumentImpl) this.document; if(doc != null) { return doc.getBaseURI(); } else { return null; } } public String toString() { return super.toString() + "[currentStyle=" + this.getCurrentStyle() + "]"; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLEmElementImpl.java0000644000175000017500000000253610726473512027571 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.*; /** * Element used for I, EM and CITE. */ public class HTMLEmElementImpl extends HTMLAbstractUIElement { public HTMLEmElementImpl(String name) { super(name); } protected RenderState createRenderState(RenderState prevRenderState) { prevRenderState = new FontStyleRenderState(prevRenderState, java.awt.Font.ITALIC); return super.createRenderState(prevRenderState); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLFontElementImpl.java0000644000175000017500000000624511134556006030131 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.AbstractCSS2Properties; import org.lobobrowser.html.style.BaseFontRenderState; import org.lobobrowser.html.style.ColorRenderState; import org.lobobrowser.html.style.ComputedCSS2Properties; import org.lobobrowser.html.style.FontNameRenderState; import org.lobobrowser.html.style.HtmlValues; import org.lobobrowser.html.style.RenderState; import org.lobobrowser.util.gui.ColorFactory; import org.w3c.dom.html2.HTMLFontElement; public class HTMLFontElementImpl extends HTMLAbstractUIElement implements HTMLFontElement { public HTMLFontElementImpl(String name) { super(name); } public String getColor() { return this.getAttribute("color"); } public String getFace() { return this.getAttribute("face"); } public String getSize() { return this.getAttribute("size"); } public void setColor(String color) { this.setAttribute("color", color); } public void setFace(String face) { this.setAttribute("face", face); } public void setSize(String size) { this.setAttribute("size", size); } protected RenderState createRenderState(RenderState prevRenderState) { return super.createRenderState(prevRenderState); } protected AbstractCSS2Properties createDefaultStyleSheet() { String fontFamily = this.getAttribute("face"); String color = this.getAttribute("color"); String size = this.getAttribute("size"); String fontSize = null; if(size != null) { ModelNode parentModelNode = this.getParentModelNode(); RenderState parentRS = parentModelNode == null ? null : parentModelNode.getRenderState(); if(parentRS != null) { int fontNumber = HtmlValues.getFontNumberOldStyle(size, parentRS); fontSize = HtmlValues.getFontSizeSpec(fontNumber); } } ComputedCSS2Properties css = new ComputedCSS2Properties(this); if(fontSize != null) { css.internalSetLC("font-size", fontSize); } if(fontFamily != null) { css.internalSetLC("font-family", fontFamily); } if(color != null) { css.internalSetLC("color", color); } return css; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLFontSizeChangeElementImpl.java0000644000175000017500000000376611134547262032103 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.*; /** * This element is used for SMALL and BIG. */ public class HTMLFontSizeChangeElementImpl extends HTMLAbstractUIElement { private final int fontChange; public HTMLFontSizeChangeElementImpl(String name, int fontChange) { super(name); this.fontChange = fontChange; } protected RenderState createRenderState(RenderState prevRenderState) { return super.createRenderState(prevRenderState); } protected AbstractCSS2Properties createDefaultStyleSheet() { ModelNode parentModelNode = this.getParentModelNode(); RenderState parentRS = parentModelNode == null ? null : parentModelNode.getRenderState(); String fontSize = null; int prevFontSize = parentRS != null ? parentRS.getFont().getSize() : HtmlValues.DEFAULT_FONT_SIZE_INT; int newFontSize = prevFontSize + (this.fontChange * 2); fontSize = newFontSize + "px"; ComputedCSS2Properties css = new ComputedCSS2Properties(this); css.internalSetLC("font-size", fontSize); return css; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLFormElementImpl.java0000644000175000017500000001453010763034036030123 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 14, 2006 */ package org.lobobrowser.html.domimpl; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.html2.HTMLCollection; import org.w3c.dom.html2.HTMLFormElement; import org.lobobrowser.html.FormInput; import org.lobobrowser.html.HtmlRendererContext; import org.lobobrowser.html.js.*; import org.mozilla.javascript.*; public class HTMLFormElementImpl extends HTMLAbstractUIElement implements HTMLFormElement { public HTMLFormElementImpl(String name) { super(name); } public HTMLFormElementImpl() { super("FORM"); } public Object namedItem(final String name) { try { //TODO: This could use document.namedItem. this.visit(new NodeVisitor() { public void visit(Node node) { if(HTMLFormElementImpl.isInput(node)) { if(name.equals(((Element) node).getAttribute("name"))) { throw new StopVisitorException(node); } } } }); } catch(StopVisitorException sve) { return sve.getTag(); } return null; } public Object item(final int index) { try { this.visit(new NodeVisitor() { private int current = 0; public void visit(Node node) { if(HTMLFormElementImpl.isInput(node)) { if(this.current == index) { throw new StopVisitorException(node); } this.current++; } } }); } catch(StopVisitorException sve) { return sve.getTag(); } return null; } private HTMLCollection elements; public HTMLCollection getElements() { HTMLCollection elements = this.elements; if(elements == null) { elements = new DescendentHTMLCollection(this, new InputFilter(), this.treeLock, false); this.elements = elements; } return elements; } public int getLength() { return this.getElements().getLength(); } public String getName() { return this.getAttribute("name"); } public void setName(String name) { this.setAttribute("name", name); } public String getAcceptCharset() { return this.getAttribute("acceptCharset"); } public void setAcceptCharset(String acceptCharset) { this.setAttribute("acceptCharset", acceptCharset); } public String getAction() { return this.getAttribute("action"); } public void setAction(String action) { this.setAttribute("action", action); } public String getEnctype() { return this.getAttribute("enctype"); } public void setEnctype(String enctype) { this.setAttribute("enctype", enctype); } public String getMethod() { String method = this.getAttribute("method"); if(method == null) { method = "GET"; } return method; } public void setMethod(String method) { this.setAttribute("method", method); } public String getTarget() { return this.getAttribute("target"); } public void setTarget(String target) { this.setAttribute("target", target); } public void submit() { this.submit(null); } private Function onsubmit; public void setOnsubmit(Function value) { this.onsubmit = value; } public Function getOnsubmit() { return this.getEventFunction(this.onsubmit, "onsubmit"); } /** * This method should be called when form submission is * done by a submit button. * @param extraFormInputs Any additional form inputs that * need to be submitted, e.g. the submit button parameter. */ public final void submit(final FormInput[] extraFormInputs) { Function onsubmit = this.getOnsubmit(); if(onsubmit != null) { //TODO: onsubmit event object? if(!Executor.executeFunction(this, onsubmit, null)) { return; } } HtmlRendererContext context = this.getHtmlRendererContext(); if(context != null) { final ArrayList formInputs = new ArrayList(); if(extraFormInputs != null) { for(int i = 0; i < extraFormInputs.length; i++) { formInputs.add(extraFormInputs[i]); } } this.visit(new NodeVisitor() { public void visit(Node node) { if(node instanceof HTMLElementImpl) { FormInput[] fis = ((HTMLElementImpl) node).getFormInputs(); if(fis != null) { for(int i = 0; i < fis.length; i++) { FormInput fi = fis[i]; if(fi.getName() == null) { throw new IllegalStateException("Form input does not have a name: " + node); } formInputs.add(fi); } } } } }); FormInput[] fia = (FormInput[]) formInputs.toArray(FormInput.EMPTY_ARRAY); String href = this.getAction(); if(href == null) { href = this.getBaseURI(); } try { URL url = this.getFullURL(href); context.submitForm(this.getMethod(), url, this.getTarget(), this.getEnctype(), fia); } catch(MalformedURLException mfu) { this.warn("submit()", mfu); } } } public void reset() { this.visit(new NodeVisitor() { public void visit(Node node) { if(node instanceof HTMLBaseInputElement) { ((HTMLBaseInputElement) node).resetInput(); } } }); } static boolean isInput(Node node) { String name = node.getNodeName().toLowerCase(); return name.equals("input") || name.equals("textarea") || name.equals("select"); } private class InputFilter implements NodeFilter { /* (non-Javadoc) * @see org.xamjwg.html.domimpl.NodeFilter#accept(org.w3c.dom.Node) */ public boolean accept(Node node) { return HTMLFormElementImpl.isInput(node); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLFrameElementImpl.java0000644000175000017500000000655610726473510030266 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 28, 2006 */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.BrowserFrame; import org.lobobrowser.html.js.*; import org.w3c.dom.Document; import org.w3c.dom.html2.HTMLFrameElement; public class HTMLFrameElementImpl extends HTMLElementImpl implements HTMLFrameElement, FrameNode { private volatile BrowserFrame browserFrame; public HTMLFrameElementImpl(String name, boolean noStyleSheet) { super(name, noStyleSheet); } public HTMLFrameElementImpl(String name) { super(name); } public void setBrowserFrame(BrowserFrame frame) { this.browserFrame = frame; } public BrowserFrame getBrowserFrame() { return this.browserFrame; } public String getFrameBorder() { return this.getAttribute("frameBorder"); } public void setFrameBorder(String frameBorder) { this.setAttribute("frameBorder", frameBorder); } public String getLongDesc() { return this.getAttribute("longdesc"); } public void setLongDesc(String longDesc) { this.setAttribute("longdesc", longDesc); } public String getMarginHeight() { return this.getAttribute("marginHeight"); } public void setMarginHeight(String marginHeight) { this.setAttribute("marginHeight", marginHeight); } public String getMarginWidth() { return this.getAttribute("marginWidth"); } public void setMarginWidth(String marginWidth) { this.setAttribute("marginWidth", marginWidth); } public String getName() { return this.getAttribute("name"); } public void setName(String name) { this.setAttribute("name", name); } private boolean noResize; public boolean getNoResize() { return this.noResize; } public void setNoResize(boolean noResize) { this.noResize = noResize; } public String getScrolling() { return this.getAttribute("scrolling"); } public void setScrolling(String scrolling) { this.setAttribute("scrolling", scrolling); } public String getSrc() { return this.getAttribute("src"); } public void setSrc(String src) { this.setAttribute("src", src); } public Document getContentDocument() { BrowserFrame frame = this.browserFrame; if(frame == null) { // Not loaded yet return null; } return frame.getContentDocument(); } public Window getContentWindow() { BrowserFrame frame = this.browserFrame; if(frame == null) { // Not loaded yet return null; } return Window.getWindow(frame.getHtmlRendererContext()); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLFrameSetElementImpl.java0000644000175000017500000000310410726473506030731 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 28, 2006 */ package org.lobobrowser.html.domimpl; import org.w3c.dom.html2.HTMLFrameSetElement; public class HTMLFrameSetElementImpl extends HTMLElementImpl implements HTMLFrameSetElement { public HTMLFrameSetElementImpl(String name, boolean noStyleSheet) { super(name, noStyleSheet); } public HTMLFrameSetElementImpl(String name) { super(name); } public String getCols() { return this.getAttribute("cols"); } public void setCols(String cols) { this.setAttribute("cols", cols); } public String getRows() { return this.getAttribute("rows"); } public void setRows(String rows) { this.setAttribute("rows", rows); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLGenericMarkupElement.java0000644000175000017500000000027010641432430031121 0ustar twernertwernerpackage org.lobobrowser.html.domimpl; public class HTMLGenericMarkupElement extends HTMLAbstractUIElement { public HTMLGenericMarkupElement(String name) { super(name); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLHRElementImpl.java0000644000175000017500000000162510641432432027527 0ustar twernertwernerpackage org.lobobrowser.html.domimpl; import org.w3c.dom.html2.HTMLHRElement; public class HTMLHRElementImpl extends HTMLAbstractUIElement implements HTMLHRElement { public HTMLHRElementImpl(String name) { super(name); } public String getAlign() { return this.getAttribute("align"); } public boolean getNoShade() { return "noshade".equalsIgnoreCase(this.getAttribute("noshade")); } public String getSize() { return this.getAttribute("size"); } public String getWidth() { return this.getAttribute("width"); } public void setAlign(String align) { this.setAttribute("align", align); } public void setNoShade(boolean noShade) { this.setAttribute("noshade", noShade ? "noshade" : null); } public void setSize(String size) { this.setAttribute("size", size); } public void setWidth(String width) { this.setAttribute("width", width); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLHeadingElementImpl.java0000644000175000017500000000717011134441044030553 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.*; import org.w3c.dom.html2.HTMLHeadingElement; public class HTMLHeadingElementImpl extends HTMLAbstractUIElement implements HTMLHeadingElement { public HTMLHeadingElementImpl(String name) { super(name); } public String getAlign() { return this.getAttribute("align"); } public void setAlign(String align) { this.setAttribute("align", align); } private final float getHeadingFontSize() { String tagName = this.getTagName(); try { int lastCharValue = tagName.charAt(1) - '0'; switch(lastCharValue) { case 1: return 24.0f; case 2: return 18.0f; case 3: return 15.0f; case 4: return 12.0f; case 5: return 10.0f; case 6: return 8.0f; } } catch(Exception thrown) { this.warn("getHeadingFontSize(): Bad heading tag: " + this.getTagName(), thrown); } return 14.0f; } private final String getHeadingFontSizeText() { String tagName = this.getTagName(); try { int lastCharValue = tagName.charAt(1) - '0'; switch(lastCharValue) { case 1: return "24pt"; case 2: return "18pt"; case 3: return "13.55pt"; case 4: return "12pt"; case 5: return "10pt"; case 6: return "7.55pt"; } } catch(Exception thrown) { this.warn("getHeadingFontSizeText(): Bad heading tag: " + this.getTagName(), thrown); } return "14px"; } protected RenderState createRenderState(RenderState prevRenderState) { float fontSize = this.getHeadingFontSize(); //(can't put a RenderState in the middle - messes up "em" sizes). //prevRenderState = new FontSizeRenderState(prevRenderState, fontSize, java.awt.Font.BOLD); return new HeadingRenderState(prevRenderState, this); } protected void appendInnerTextImpl(StringBuffer buffer) { int length = buffer.length(); int lineBreaks; if(length == 0) { lineBreaks = 2; } else { int start = length - 4; if (start < 0) { start = 0; } lineBreaks = 0; for(int i = start; i < length; i++) { char ch = buffer.charAt(i); if(ch == '\n') { lineBreaks++; } } } for(int i = 0; i < 2 - lineBreaks; i++) { buffer.append("\r\n"); } super.appendInnerTextImpl(buffer); buffer.append("\r\n\r\n"); } protected AbstractCSS2Properties createDefaultStyleSheet() { ComputedCSS2Properties css = new ComputedCSS2Properties(this); css.internalSetLC("font-size", this.getHeadingFontSizeText()); css.internalSetLC("font-weight", "bolder"); return css; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLHtmlElementImpl.java0000644000175000017500000000261210726473504030130 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 8, 2005 */ package org.lobobrowser.html.domimpl; import org.w3c.dom.html2.HTMLHtmlElement; public class HTMLHtmlElementImpl extends HTMLElementImpl implements HTMLHtmlElement { public HTMLHtmlElementImpl() { super("HTML", true); } public HTMLHtmlElementImpl(String name) { super(name, true); } public String getVersion() { return this.getAttribute("version"); } public void setVersion(String version) { this.setAttribute("version", version); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLIFrameElementImpl.java0000644000175000017500000000715111130344650030357 0ustar twernertwernerpackage org.lobobrowser.html.domimpl; import org.lobobrowser.html.*; import org.lobobrowser.html.js.Window; import org.lobobrowser.html.style.*; import org.lobobrowser.util.gui.ColorFactory; import org.w3c.dom.Document; import org.w3c.dom.html2.HTMLIFrameElement; public class HTMLIFrameElementImpl extends HTMLAbstractUIElement implements HTMLIFrameElement, FrameNode { private volatile BrowserFrame browserFrame; public HTMLIFrameElementImpl(String name) { super(name); } public void setBrowserFrame(BrowserFrame frame) { this.browserFrame = frame; if(frame != null) { String src = this.getAttribute("src"); if(src != null) { try { frame.loadURL(this.getFullURL(src)); } catch(java.net.MalformedURLException mfu) { this.warn("setBrowserFrame(): Unable to navigate to src.", mfu); } } } } public BrowserFrame getBrowserFrame() { return this.browserFrame; } public String getAlign() { return this.getAttribute("align"); } public Document getContentDocument() { //TODO: Domain-based security BrowserFrame frame = this.browserFrame; if(frame == null) { // Not loaded yet return null; } return frame.getContentDocument(); } public Window getContentWindow() { BrowserFrame frame = this.browserFrame; if(frame == null) { // Not loaded yet return null; } return Window.getWindow(frame.getHtmlRendererContext()); } public String getFrameBorder() { return this.getAttribute("frameborder"); } public String getHeight() { return this.getAttribute("height"); } public String getLongDesc() { return this.getAttribute("longdesc"); } public String getMarginHeight() { return this.getAttribute("marginheight"); } public String getMarginWidth() { return this.getAttribute("marginwidth"); } public String getName() { return this.getAttribute("name"); } public String getScrolling() { return this.getAttribute("scrolling"); } public String getSrc() { return this.getAttribute("src"); } public String getWidth() { return this.getAttribute("width"); } public void setAlign(String align) { this.setAttribute("align", align); } public void setFrameBorder(String frameBorder) { this.setAttribute("frameborder", frameBorder); } public void setHeight(String height) { this.setAttribute("height", height); } public void setLongDesc(String longDesc) { this.setAttribute("longdesc", longDesc); } public void setMarginHeight(String marginHeight) { this.setAttribute("marginHeight", marginHeight); } public void setMarginWidth(String marginWidth) { this.setAttribute("marginWidth", marginWidth); } public void setName(String name) { this.setAttribute("name", name); } public void setScrolling(String scrolling) { this.setAttribute("scrolling", scrolling); } public void setSrc(String src) { this.setAttribute("src", src); } public void setWidth(String width) { this.setAttribute("width", width); } protected void assignAttributeField(String normalName, String value) { if("src".equals(normalName)) { BrowserFrame frame = this.browserFrame; if(frame != null) { try { frame.loadURL(this.getFullURL(value)); } catch(java.net.MalformedURLException mfu) { this.warn("assignAttributeField(): Unable to navigate to src.", mfu); } } } else { super.assignAttributeField(normalName, value); } } protected RenderState createRenderState(RenderState prevRenderState) { return new IFrameRenderState(prevRenderState, this); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLImageElementImpl.java0000644000175000017500000001454510726473510030253 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Nov 19, 2005 */ package org.lobobrowser.html.domimpl; import java.util.*; import org.lobobrowser.html.js.*; import org.lobobrowser.html.style.*; import org.mozilla.javascript.Function; import org.w3c.dom.html2.HTMLImageElement; public class HTMLImageElementImpl extends HTMLAbstractUIElement implements HTMLImageElement { public HTMLImageElementImpl() { super("IMG"); } public HTMLImageElementImpl(String name) { super(name); } public String getName() { return this.getAttribute("name"); } public void setName(String name) { this.setAttribute("name", name); } public String getAlign() { return this.getAttribute("align"); } public void setAlign(String align) { this.setAttribute("align", align); } public String getAlt() { return this.getAttribute("alt"); } public void setAlt(String alt) { this.setAttribute("alt", alt); } public String getBorder() { return this.getAttribute("border"); } public void setBorder(String border) { this.setAttribute("border", border); } public int getHeight() { UINode r = this.uiNode; return r == null ? 0 : r.getBounds().height; } public void setHeight(int height) { this.setAttribute("height", String.valueOf(height)); } public int getHspace() { return this.getAttributeAsInt("hspace", 0); } public void setHspace(int hspace) { this.setAttribute("hspace", String.valueOf("hspace")); } public boolean getIsMap() { return this.getAttributeAsBoolean("isMap"); } public void setIsMap(boolean isMap) { this.setAttribute("isMap", isMap ? "isMap" : null); } public String getLongDesc() { return this.getAttribute("longDesc"); } public void setLongDesc(String longDesc) { this.setAttribute("longDesc", longDesc); } public String getSrc() { return this.getAttribute("src"); } /** * Sets the image URI and starts to load the image. * Note that an HtmlRendererContext should be available * to the HTML document for images to be loaded. */ public void setSrc(String src) { this.setAttribute("src", src); } public String getUseMap() { return this.getAttribute("useMap"); } public void setUseMap(String useMap) { this.setAttribute("useMap", useMap); } public int getVspace() { return this.getAttributeAsInt("vspace", 0); } public void setVspace(int vspace) { this.setAttribute("vspace", String.valueOf(vspace)); } public int getWidth() { UINode r = this.uiNode; return r == null ? 0 : r.getBounds().width; } public void setWidth(int width) { this.setAttribute("width", String.valueOf(width)); } protected void assignAttributeField(String normalName, String value) { super.assignAttributeField(normalName, value); if("src".equals(normalName)) { this.loadImage(value); } } private Function onload; public Function getOnload() { return this.getEventFunction(this.onload, "onload"); } public void setOnload(Function onload) { this.onload = onload; } private java.awt.Image image = null; private String imageSrc; private void loadImage(String src) { HTMLDocumentImpl document = (HTMLDocumentImpl) this.document; if(document != null) { synchronized(this.listeners) { this.imageSrc = src; this.image = null; } if(src != null) { document.loadImage(src, new LocalImageListener(src)); } } } public final java.awt.Image getImage() { synchronized(this.listeners) { return this.image; } } private final ArrayList listeners = new ArrayList(1); /** * Adds a listener of image loading events. * The listener gets called right away if there's already * an image. * @param listener */ public void addImageListener(ImageListener listener) { ArrayList l = this.listeners; java.awt.Image currentImage; synchronized(l) { currentImage = this.image; l.add(listener); } if(currentImage != null) { // Call listener right away if there's already an // image; holding no locks. listener.imageLoaded(new ImageEvent(this, currentImage)); // Should not call onload handler here. That's taken // care of otherwise. } } public void removeImageListener(ImageListener listener) { ArrayList l = this.listeners; synchronized(l) { l.remove(l); } } private void dispatchEvent(String expectedImgSrc, ImageEvent event) { ArrayList l = this.listeners; ImageListener[] listenerArray; synchronized(l) { if(!expectedImgSrc.equals(this.imageSrc)) { return; } this.image = event.image; // Get array of listeners while holding lock. listenerArray = (ImageListener[]) l.toArray(ImageListener.EMPTY_ARRAY); } int llength = listenerArray.length; for(int i = 0; i < llength; i++) { // Inform listener, holding no lock. listenerArray[i].imageLoaded(event); } Function onload = this.getOnload(); if(onload != null) { //TODO: onload event object? Executor.executeFunction(HTMLImageElementImpl.this, onload, null); } } protected RenderState createRenderState(RenderState prevRenderState) { return new ImageRenderState(prevRenderState, this); } private class LocalImageListener implements ImageListener { private final String expectedImgSrc; public LocalImageListener(String imgSrc) { this.expectedImgSrc = imgSrc; } public void imageLoaded(ImageEvent event) { dispatchEvent(this.expectedImgSrc, event); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLInputElementImpl.java0000644000175000017500000001207110726473510030320 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 15, 2006 */ package org.lobobrowser.html.domimpl; import java.util.logging.*; import org.lobobrowser.html.FormInput; import org.w3c.dom.html2.*; public class HTMLInputElementImpl extends HTMLBaseInputElement implements HTMLInputElement { public HTMLInputElementImpl(String name) { super(name); } private boolean defaultChecked; public boolean getDefaultChecked() { return this.defaultChecked; } public void setDefaultChecked(boolean defaultChecked) { this.defaultChecked = defaultChecked; } public boolean getChecked() { InputContext ic = this.inputContext; if(ic == null) { return this.getAttributeAsBoolean("checked"); } else { return ic.getChecked(); } } public void setChecked(boolean checked) { InputContext ic = this.inputContext; if(ic != null) { ic.setChecked(checked); } } public int getMaxLength() { InputContext ic = this.inputContext; return ic == null ? 0 : ic.getMaxLength(); } public void setMaxLength(int maxLength) { InputContext ic = this.inputContext; if(ic != null) { ic.setMaxLength(maxLength); } } public int getSize() { InputContext ic = this.inputContext; return ic == null ? 0 : ic.getControlSize(); } public void setSize(int size) { InputContext ic = this.inputContext; if(ic != null) { ic.setControlSize(size); } } public String getSrc() { return this.getAttribute("src"); } public void setSrc(String src) { this.setAttribute("src", src); } /** * Gets input type in lowercase. */ public String getType() { String type = this.getAttribute("type"); return type == null ? null : type.toLowerCase(); } public void setType(String type) { this.setAttribute("type", type); } public String getUseMap() { return this.getAttribute("usemap"); } public void setUseMap(String useMap) { this.setAttribute("usemap", useMap); } public void click() { InputContext ic = this.inputContext; if(ic != null) { ic.click(); } } public boolean isSubmittableWithEnterKey() { String type = this.getType(); return (type == null || "".equals(type) || "text".equals(type) || "password".equals(type)); } public boolean isSubmittableWithPress() { String type = this.getType(); return "submit".equals(type) || "image".equals(type); } public boolean isSubmitInput() { String type = this.getType(); return "submit".equals(type); } public boolean isImageInput() { String type = this.getType(); return "image".equals(type); } public boolean isResetInput() { String type = this.getType(); return "reset".equals(type); } void resetInput() { InputContext ic = this.inputContext; if(ic != null) { ic.resetInput(); } } protected FormInput[] getFormInputs() { String type = this.getType(); String name = this.getName(); if(name == null) { return null; } if(type == null) { return new FormInput[] { new FormInput(name, this.getValue()) }; } else { if("text".equals(type) || "password".equals(type) || "hidden".equals(type) || "".equals(type)) { return new FormInput[] { new FormInput(name, this.getValue()) }; } else if("submit".equals(type)) { // It's done as an "extra" form input return null; } else if("radio".equals(type) || "checkbox".equals(type)) { if(this.getChecked()) { String value = this.getValue(); if(value == null || value.length() == 0) { value = "on"; } return new FormInput[] { new FormInput(name, value) }; } else { return null; } } else if("image".equals(type)) { // It's done as an "extra" form input return null; } else if("file".equals(type)) { java.io.File file = this.getFileValue(); if(file == null) { if(logger.isLoggable(Level.INFO)) { logger.info("getFormInputs(): File input named " + name + " has null file."); } return null; } else { return new FormInput[] { new FormInput(name, file) }; } } else { return null; } } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLLIElementImpl.java0000644000175000017500000000350610726473506027535 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Feb 12, 2006 */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.*; import org.w3c.dom.html2.HTMLLIElement; public class HTMLLIElementImpl extends HTMLAbstractUIElement implements HTMLLIElement { public HTMLLIElementImpl(String name) { super(name); } public String getType() { return this.getAttribute("type"); } public void setType(String type) { this.setAttribute("type", type); } public int getValue() { String valueText = this.getAttribute("value"); if(valueText == null) { return 0; } try { return Integer.parseInt(valueText); } catch(NumberFormatException nfe) { return 0; } } public void setValue(int value) { this.setAttribute("value", String.valueOf(value)); } protected RenderState createRenderState(RenderState prevRenderState) { return new DisplayRenderState(prevRenderState, this, RenderState.DISPLAY_LIST_ITEM); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLLinkElementImpl.java0000644000175000017500000002014711126723430030113 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.domimpl; import java.net.MalformedURLException; import java.net.URL; import org.w3c.dom.UserDataHandler; import org.w3c.dom.css.CSSStyleSheet; import org.w3c.dom.html2.*; import org.lobobrowser.html.*; import org.lobobrowser.html.style.*; import org.lobobrowser.util.gui.*; import com.steadystate.css.dom.*; import java.util.logging.*; public class HTMLLinkElementImpl extends HTMLAbstractUIElement implements HTMLLinkElement { private static final Logger logger = Logger.getLogger(HTMLLinkElementImpl.class.getName()); private static final boolean loggableInfo = logger.isLoggable(Level.INFO); private CSSStyleSheet styleSheet; public HTMLLinkElementImpl(String name) { super(name); } private boolean disabled; public boolean getDisabled() { return this.disabled; } public void setDisabled(boolean disabled) { this.disabled = disabled; CSSStyleSheet sheet = this.styleSheet; if(sheet != null) { sheet.setDisabled(disabled); } } public String getHref() { String href = this.getAttribute("href"); return href == null ? "" : href; } public void setHref(String href) { this.setAttribute("href", href); } public String getHreflang() { return this.getAttribute("hreflang"); } public void setHreflang(String hreflang) { this.setAttribute("hreflang", hreflang); } public String getMedia() { return this.getAttribute("media"); } public void setMedia(String media) { this.setAttribute("media", media); } public String getRel() { return this.getAttribute("rel"); } public void setRel(String rel) { this.setAttribute("rel", rel); } public String getRev() { return this.getAttribute("rev"); } public void setRev(String rev) { this.setAttribute("rev", rev); } public String getTarget() { String target = this.getAttribute("target"); if(target != null) { return target; } HTMLDocumentImpl doc = (HTMLDocumentImpl) this.document; return doc == null ? null : doc.getDefaultTarget(); } public void setTarget(String target) { this.setAttribute("target", target); } public String getType() { return this.getAttribute("type"); } public void setType(String type) { this.setAttribute("type", type); } public Object setUserData(String key, Object data, UserDataHandler handler) { if(org.lobobrowser.html.parser.HtmlParser.MODIFYING_KEY.equals(key) && data != Boolean.TRUE) { this.processLink(); } else if(com.steadystate.css.dom.CSSStyleSheetImpl.KEY_DISABLED_CHANGED.equals(key)) { this.informDocumentInvalid(); } return super.setUserData(key, data, handler); } /** * If the LINK refers to a stylesheet document, this method * loads and parses it. */ protected void processLink() { this.styleSheet = null; String rel = this.getAttribute("rel"); if(rel != null) { String cleanRel = rel.trim().toLowerCase(); boolean isStyleSheet = cleanRel.equals("stylesheet"); boolean isAltStyleSheet = cleanRel.equals("alternate stylesheet"); if(isStyleSheet || isAltStyleSheet) { UserAgentContext uacontext = this.getUserAgentContext(); if(uacontext.isExternalCSSEnabled()) { String media = this.getMedia(); if(CSSUtilities.matchesMedia(media, uacontext)) { HTMLDocumentImpl doc = (HTMLDocumentImpl) this.getOwnerDocument(); try { boolean liflag = loggableInfo; long time1 = liflag ? System.currentTimeMillis() : 0; try { CSSStyleSheet sheet = CSSUtilities.parse(this, this.getHref(), doc, doc.getBaseURI(), false); if(sheet != null) { this.styleSheet = sheet; if(sheet instanceof CSSStyleSheetImpl) { CSSStyleSheetImpl sheetImpl = (CSSStyleSheetImpl) sheet; if(isAltStyleSheet) { sheetImpl.setDisabledOnly(true); } else { sheetImpl.setDisabledOnly(this.disabled); } } else { if(isAltStyleSheet) { sheet.setDisabled(true); } else { sheet.setDisabled(this.disabled); } } doc.addStyleSheet(sheet); } } finally { if(liflag) { long time2 = System.currentTimeMillis(); logger.info("processLink(): Loaded and parsed CSS (or attempted to) at URI=[" + this.getHref() + "] in " + (time2 - time1) + " ms."); } } } catch(MalformedURLException mfe) { this.warn("Will not parse CSS. URI=[" + this.getHref() + "] with BaseURI=[" + doc.getBaseURI() + "] does not appear to be a valid URI."); } catch(Throwable err) { this.warn("Unable to parse CSS. URI=[" + this.getHref() + "].", err); } } } } } } public String getAbsoluteHref() { HtmlRendererContext rcontext = this.getHtmlRendererContext(); if(rcontext != null) { String href = this.getHref(); if(href != null && href.length() > 0) { String target = this.getTarget(); try { URL url = this.getFullURL(href); return url == null ? null : url.toExternalForm(); } catch(MalformedURLException mfu) { this.warn("Malformed URI: [" + href + "].", mfu); } } } return null; } public void navigate() { if(this.disabled) { return; } HtmlRendererContext rcontext = this.getHtmlRendererContext(); if(rcontext != null) { String href = this.getHref(); if(href != null && href.length() > 0) { String target = this.getTarget(); try { URL url = this.getFullURL(href); if(url == null) { this.warn("Unable to resolve URI: [" + href + "]."); } else { rcontext.linkClicked(this, url, target); } } catch(MalformedURLException mfu) { this.warn("Malformed URI: [" + href + "].", mfu); } } } } private java.awt.Color getLinkColor() { HTMLDocument doc = (HTMLDocument) this.document; if(doc != null) { HTMLBodyElement body = (HTMLBodyElement) doc.getBody(); if(body != null) { String vlink = body.getVLink(); String link = body.getLink(); if(vlink != null || link != null) { HtmlRendererContext rcontext = this.getHtmlRendererContext(); if(rcontext != null) { boolean visited = rcontext.isVisitedLink(this); String colorText = visited ? vlink : link; if(colorText != null) { return ColorFactory.getInstance().getColor(colorText); } } } } } return java.awt.Color.BLUE; } protected RenderState createRenderState(RenderState prevRenderState) { if(this.hasAttribute("href")) { prevRenderState = new TextDecorationRenderState(prevRenderState, RenderState.MASK_TEXTDECORATION_UNDERLINE); prevRenderState = new ColorRenderState(prevRenderState, this.getLinkColor()); } return super.createRenderState(prevRenderState); } public String toString() { // Javascript code often depends on this being exactly href. See js9.html. // To change, perhaps add method to AbstractScriptableDelegate. return this.getHref(); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLMonospacedElementImpl.java0000644000175000017500000000254310726473500031313 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.*; /** * Element used for TT and CODE. */ public class HTMLMonospacedElementImpl extends HTMLAbstractUIElement { public HTMLMonospacedElementImpl(String name) { super(name); } protected RenderState createRenderState(RenderState prevRenderState) { prevRenderState = new FontNameRenderState(prevRenderState, "Monospaced"); return super.createRenderState(prevRenderState); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLNonStandardElement.java0000644000175000017500000000042710641432430030604 0ustar twernertwernerpackage org.lobobrowser.html.domimpl; public class HTMLNonStandardElement extends HTMLElementImpl { public HTMLNonStandardElement(String name, boolean noStyleSheet) { super(name, noStyleSheet); } public HTMLNonStandardElement(String name) { super(name); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLOListElementImpl.java0000644000175000017500000000406111134376520030250 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Feb 12, 2006 */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.*; import org.w3c.dom.html2.HTMLOListElement; public class HTMLOListElementImpl extends HTMLAbstractUIElement implements HTMLOListElement { public HTMLOListElementImpl(String name) { super(name); } public boolean getCompact() { String compactText = this.getAttribute("compact"); return "compact".equalsIgnoreCase(compactText); } public void setCompact(boolean compact) { this.setAttribute("compact", compact ? "compact" : null); } public int getStart() { String startText = this.getAttribute("start"); if(startText == null) { return 1; } try { return Integer.parseInt(startText); } catch(NumberFormatException nfe) { return 1; } } public void setStart(int start) { this.setAttribute("start", String.valueOf(start)); } public String getType() { return this.getAttribute("type"); } public void setType(String type) { this.setAttribute("type", type); } protected RenderState createRenderState(RenderState prevRenderState) { return new ListRenderState(prevRenderState, this); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLObjectElementImpl.java0000644000175000017500000000747110641432430030427 0ustar twernertwernerpackage org.lobobrowser.html.domimpl; import org.w3c.dom.Document; import org.w3c.dom.html2.HTMLFormElement; import org.w3c.dom.html2.HTMLObjectElement; public class HTMLObjectElementImpl extends HTMLAbstractUIElement implements HTMLObjectElement { public HTMLObjectElementImpl(String name) { super(name); } public String getAlign() { return this.getAttribute("align"); } public String getAlt() { return this.getAttribute("alt"); } public String getArchive() { return this.getAttribute("archive"); } public String getCode() { return this.getAttribute("code"); } public String getCodeBase() { return this.getAttribute("codebase"); } public String getHeight() { return this.getAttribute("height"); } public String getName() { return this.getAttribute("name"); } public String getObject() { return this.getAttribute("object"); } public String getWidth() { return this.getAttribute("width"); } public void setAlign(String align) { this.setAttribute("align", align); } public void setAlt(String alt) { this.setAttribute("alt", alt); } public void setArchive(String archive) { this.setAttribute("archive", archive); } public void setCode(String code) { this.setAttribute("code", code); } public void setCodeBase(String codeBase) { this.setAttribute("codebase", codeBase); } public void setHeight(String height) { this.setAttribute("height", height); } public void setName(String name) { this.setAttribute("name", name); } public void setObject(String object) { this.setAttribute("object", object); } public void setWidth(String width) { this.setAttribute("width", width); } public String getBorder() { return this.getAttribute("border"); } public String getCodeType() { return this.getAttribute("codetype"); } public Document getContentDocument() { return this.getOwnerDocument(); } public String getData() { return this.getAttribute("data"); } public boolean getDeclare() { return "declare".equalsIgnoreCase(this.getAttribute("declare")); } public HTMLFormElement getForm() { return (HTMLFormElement) this.getAncestorForJavaClass(HTMLFormElement.class); } public int getHspace() { try { return Integer.parseInt(this.getAttribute("hspace")); } catch(Exception err) { return 0; } } public String getStandby() { return this.getAttribute("standby"); } public int getTabIndex() { try { return Integer.parseInt(this.getAttribute("tabindex")); } catch(Exception err) { return 0; } } public String getType() { return this.getAttribute("type"); } public String getUseMap() { return this.getAttribute("usemap"); } public int getVspace() { try { return Integer.parseInt(this.getAttribute("vspace")); } catch(Exception err) { return 0; } } public void setBorder(String border) { this.setAttribute("border", border); } public void setCodeType(String codeType) { this.setAttribute("codetype", codeType); } public void setData(String data) { this.setAttribute("data", data); } public void setDeclare(boolean declare) { this.setAttribute("declare", declare ? "declare" : null); } public void setHspace(int hspace) { this.setAttribute("hspace", String.valueOf(hspace)); } public void setStandby(String standby) { this.setAttribute("standby", standby); } public void setTabIndex(int tabIndex) { this.setAttribute("tabindex", String.valueOf(tabIndex)); } public void setType(String type) { this.setAttribute("type", type); } public void setUseMap(String useMap) { this.setAttribute("usemap", useMap); } public void setVspace(int vspace) { this.setAttribute("vspace", String.valueOf(vspace)); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLOptionElementImpl.java0000644000175000017500000000462011125506242030463 0ustar twernertwernerpackage org.lobobrowser.html.domimpl; import org.w3c.dom.html2.*; public class HTMLOptionElementImpl extends HTMLElementImpl implements HTMLOptionElement { public HTMLOptionElementImpl(String name) { super(name, true); } public boolean getDefaultSelected() { return this.getAttributeAsBoolean("selected"); } public boolean getDisabled() { return false; } public HTMLFormElement getForm() { return this.getForm(); } public int getIndex() { Object parent = this.getParentNode(); if(parent instanceof HTMLSelectElement) { HTMLOptionsCollectionImpl options = (HTMLOptionsCollectionImpl) ((HTMLSelectElement) parent).getOptions(); return options.indexOf(this); } else { return -1; } } public String getLabel() { return this.getAttribute("label"); } public boolean getSelected() { return this.selected; } public String getText() { return this.getRawInnerText(false); } public void setText(String value) { this.setTextContent(value); } public String getValue() { return this.getAttribute("value"); } public void setDefaultSelected(boolean defaultSelected) { this.setAttribute("selected", defaultSelected ? "selected" : null); } public void setDisabled(boolean disabled) { //TODO Unsupported } public void setLabel(String label) { this.setAttribute("label", label); } private boolean selected; void setSelectedImpl(boolean selected) { this.selected = selected; } public void setSelected(boolean selected) { boolean changed = selected != this.selected; this.selected = selected; // Changing the option state changes the selected index. Object parent = this.getParentNode(); if(parent instanceof HTMLSelectElementImpl) { HTMLSelectElementImpl parentSelect = ((HTMLSelectElementImpl) parent); if(changed || parentSelect.getSelectedIndex() == -1) { if(selected) { parentSelect.setSelectedIndexImpl(this.getIndex()); } else { int currentIndex = parentSelect.getSelectedIndex(); if(currentIndex != -1 && currentIndex == this.getIndex()) { parentSelect.setSelectedIndexImpl(-1); } } } } } public void setValue(String value) { this.setAttribute("value", value); } public String toString() { return "HTMLOptionElementImpl[text=" + this.getText() + ",selected=" + this.getSelected() + "]"; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLOptionsCollectionImpl.java0000644000175000017500000000132410763033610031347 0ustar twernertwernerpackage org.lobobrowser.html.domimpl; import org.w3c.dom.DOMException; import org.w3c.dom.Node; import org.w3c.dom.html2.*; public class HTMLOptionsCollectionImpl extends DescendentHTMLCollection implements HTMLOptionsCollection { public static final NodeFilter OPTION_FILTER = new OptionFilter(); public HTMLOptionsCollectionImpl(HTMLElementImpl selectElement) { super(selectElement, OPTION_FILTER, selectElement.treeLock, false); } public void setLength(int length) throws DOMException { throw new UnsupportedOperationException(); } private static class OptionFilter implements NodeFilter { public boolean accept(Node node) { return node instanceof HTMLOptionElement; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLPElementImpl.java0000644000175000017500000000215311134376350027416 0ustar twernertwernerpackage org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.*; import org.w3c.dom.html2.HTMLParagraphElement; public class HTMLPElementImpl extends HTMLAbstractUIElement implements HTMLParagraphElement { public HTMLPElementImpl(String name) { super(name); } public String getAlign() { return this.getAttribute("align"); } public void setAlign(String align) { this.setAttribute("align", align); } protected void appendInnerTextImpl(StringBuffer buffer) { int length = buffer.length(); int lineBreaks; if(length == 0) { lineBreaks = 2; } else { int start = length - 4; if (start < 0) { start = 0; } lineBreaks = 0; for(int i = start; i < length; i++) { char ch = buffer.charAt(i); if(ch == '\n') { lineBreaks++; } } } for(int i = 0; i < 2 - lineBreaks; i++) { buffer.append("\r\n"); } super.appendInnerTextImpl(buffer); buffer.append("\r\n\r\n"); } protected RenderState createRenderState(RenderState prevRenderState) { return new ParagraphRenderState(prevRenderState, this); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLPreElementImpl.java0000644000175000017500000000322410726473504027752 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Feb 12, 2006 */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.*; import org.w3c.dom.html2.HTMLPreElement; public class HTMLPreElementImpl extends HTMLAbstractUIElement implements HTMLPreElement { public HTMLPreElementImpl(String name) { super(name); } public int getWidth() { String widthText = this.getAttribute("width"); if(widthText == null) { return 0; } try { return Integer.parseInt(widthText); } catch(NumberFormatException nfe) { return 0; } } public void setWidth(int width) { this.setAttribute("width", String.valueOf(width)); } protected RenderState createRenderState(RenderState prevRenderState) { return new PreRenderState(prevRenderState, this); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLProcessingInstruction.java0000644000175000017500000000305710764510266031451 0ustar twernertwerner/* * HtmlProcessingInstruction.java * Selima Prague FBI Project * 5th-March-2008 */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.domimpl.NodeImpl; import org.w3c.dom.DOMException; import org.w3c.dom.Node; import org.w3c.dom.ProcessingInstruction; /** * HTML DOM object representing processing instruction as per HTML 4.0 specification. * * @author vitek */ public class HTMLProcessingInstruction extends NodeImpl implements ProcessingInstruction, Cloneable { String target; String data; public HTMLProcessingInstruction(String target,String data) { this.target = target; this.data = data; } protected Node createSimilarNode() { return (Node) clone(); } public String getLocalName() { return target; } public String getNodeName() { return target; } public short getNodeType() { return Node.PROCESSING_INSTRUCTION_NODE; } public String getNodeValue() throws DOMException { return data; } public void setNodeValue(String nodeValue) throws DOMException { this.data = nodeValue; } public String getData() { return data; } public String getTarget() { return target; } public void setData(String data) throws DOMException { this.data = data; } public Object clone() { try { return (HTMLProcessingInstruction) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } } public String toString() { return ""; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLScriptElementImpl.java0000644000175000017500000001457511130421122030456 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 8, 2005 */ package org.lobobrowser.html.domimpl; import org.w3c.dom.Document; import org.w3c.dom.UserDataHandler; import org.w3c.dom.html2.HTMLScriptElement; import org.lobobrowser.html.*; import org.lobobrowser.html.js.Executor; import org.mozilla.javascript.*; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.logging.*; public class HTMLScriptElementImpl extends HTMLElementImpl implements HTMLScriptElement { private static final Logger logger = Logger.getLogger(HTMLScriptElementImpl.class.getName()); private static final boolean loggableInfo = logger.isLoggable(Level.INFO); public HTMLScriptElementImpl() { super("SCRIPT", true); } public HTMLScriptElementImpl(String name) { super(name, true); } private String text; public String getText() { String t = this.text; if(t == null) { return this.getRawInnerText(true); } else { return t; } } public void setText(String text) { this.text = text; } public String getHtmlFor() { return this.getAttribute("htmlFor"); } public void setHtmlFor(String htmlFor) { this.setAttribute("htmlFor", htmlFor); } public String getEvent() { return this.getAttribute("event"); } public void setEvent(String event) { this.setAttribute("event", event); } private boolean defer; public boolean getDefer() { return this.defer; } public void setDefer(boolean defer) { this.defer = defer; } public String getSrc() { return this.getAttribute("src"); } public void setSrc(String src) { this.setAttribute("src", src); } public String getType() { return this.getAttribute("type"); } public void setType(String type) { this.setAttribute("type", type); } public Object setUserData(String key, Object data, UserDataHandler handler) { if(org.lobobrowser.html.parser.HtmlParser.MODIFYING_KEY.equals(key) && data != Boolean.TRUE) { this.processScript(); } return super.setUserData(key, data, handler); } protected final void processScript() { UserAgentContext bcontext = this.getUserAgentContext(); if(bcontext == null) { throw new IllegalStateException("No user agent context."); } if(bcontext.isScriptingEnabled()) { String text; final String scriptURI; int baseLineNumber; String src = this.getSrc(); Document doc = this.document; if(!(doc instanceof HTMLDocumentImpl)) { throw new IllegalStateException("no valid document"); } boolean liflag = loggableInfo; if(src == null) { text = this.getText(); scriptURI = doc.getBaseURI(); baseLineNumber = 1; //TODO: Line number of inner text?? } else { this.informExternalScriptLoading(); java.net.URL scriptURL = ((HTMLDocumentImpl) doc).getFullURL(src); scriptURI = scriptURL == null ? src : scriptURL.toExternalForm(); long time1 = liflag ? System.currentTimeMillis() : 0; try { final HttpRequest request = bcontext.createHttpRequest(); // Perform a synchronous request SecurityManager sm = System.getSecurityManager(); if(sm == null) { try { request.open("GET", scriptURI, false); request.send(null); } catch(java.io.IOException thrown) { logger.log(Level.WARNING, "processScript()", thrown); } } else { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { // Code might have restrictions on accessing // items from elsewhere. try { request.open("GET", scriptURI, false); request.send(null); } catch(java.io.IOException thrown) { logger.log(Level.WARNING, "processScript()", thrown); } return null; } }); } int status = request.getStatus(); if(status != 200 && status != 0) { this.warn("Script at [" + scriptURI + "] failed to load; HTTP status: " + status + "."); return; } text = request.getResponseText(); } finally { if(liflag) { long time2 = System.currentTimeMillis(); logger.info("processScript(): Loaded external Javascript from URI=[" + scriptURI + "] in " + (time2 - time1) + " ms."); } } baseLineNumber = 1; } Context ctx = Executor.createContext(this.getDocumentURL(), bcontext); try { Scriptable scope = (Scriptable) doc.getUserData(Executor.SCOPE_KEY); if(scope == null) { throw new IllegalStateException("Scriptable (scope) instance was expected to be keyed as UserData to document using " + Executor.SCOPE_KEY); } try { long time1 = liflag ? System.currentTimeMillis() : 0; if(text == null) { throw new java.lang.IllegalStateException("Script source is null: " + this + "."); } ctx.evaluateString(scope, text, scriptURI, baseLineNumber, null); if(liflag) { long time2 = System.currentTimeMillis(); logger.info("addNotify(): Evaluated (or attempted to evaluate) Javascript in " + (time2 - time1) + " ms."); } } catch(EcmaError ecmaError) { logger.log(Level.WARNING, "Javascript error at " + ecmaError.getSourceName() + ":" + ecmaError.getLineNumber() + ": " + ecmaError.getMessage(), ecmaError); } catch(Throwable err) { logger.log(Level.WARNING, "Unable to evaluate Javascript code", err); } } finally { Context.exit(); } } } protected void appendInnerTextImpl(StringBuffer buffer) { // nop } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLSelectElementImpl.java0000644000175000017500000000771510773452512030452 0ustar twernertwernerpackage org.lobobrowser.html.domimpl; import java.util.*; import org.lobobrowser.html.FormInput; import org.mozilla.javascript.*; import org.w3c.dom.DOMException; import org.w3c.dom.html2.HTMLElement; import org.w3c.dom.html2.HTMLOptionsCollection; import org.w3c.dom.html2.HTMLSelectElement; public class HTMLSelectElementImpl extends HTMLBaseInputElement implements HTMLSelectElement { public HTMLSelectElementImpl(String name) { super(name); } public void add(HTMLElement element, HTMLElement before) throws DOMException { this.insertBefore(element, before); } public int getLength() { return this.getOptions().getLength(); } private Boolean multipleState = null; public boolean getMultiple() { Boolean m = this.multipleState; if(m != null) { return m.booleanValue(); } return this.getAttributeAsBoolean("multiple"); } private HTMLOptionsCollection options; public HTMLOptionsCollection getOptions() { synchronized(this) { if(this.options == null) { this.options = new HTMLOptionsCollectionImpl(this); } return this.options; } } public int getSelectedIndex() { InputContext ic = this.inputContext; if(ic != null) { return ic.getSelectedIndex(); } else { return this.deferredSelectedIndex; } } public int getSize() { InputContext ic = this.inputContext; if(ic != null) { return ic.getVisibleSize(); } else { return 0; } } public String getType() { return this.getMultiple() ? "select-multiple" : "select-one"; } public void remove(int index) { try { this.removeChild(this.getOptions().item(index)); } catch(DOMException de) { this.warn("remove(): Unable to remove option at index " + index + ".", de); } } public void setLength(int length) throws DOMException { this.getOptions().setLength(length); } public void setMultiple(boolean multiple) { boolean prevMultiple = this.getMultiple(); this.multipleState = Boolean.valueOf(multiple); if(prevMultiple != multiple) { this.informLayoutInvalid(); } } private int deferredSelectedIndex = -1; public void setSelectedIndex(int selectedIndex) { this.setSelectedIndexImpl(selectedIndex); HTMLOptionsCollection options = this.getOptions(); int length = options.getLength(); for(int i = 0; i < length; i++) { HTMLOptionElementImpl option = (HTMLOptionElementImpl) options.item(i); option.setSelectedImpl(i == selectedIndex); } } void setSelectedIndexImpl(int selectedIndex) { InputContext ic = this.inputContext; if(ic != null) { ic.setSelectedIndex(selectedIndex); } else { this.deferredSelectedIndex = selectedIndex; } } public void setSize(int size) { InputContext ic = this.inputContext; if(ic != null) { ic.setVisibleSize(size); } } protected FormInput[] getFormInputs() { // Needs to be overriden for forms to submit. InputContext ic = this.inputContext; String[] values = ic == null ? null : ic.getValues(); if(values == null) { String value = this.getValue(); values = value == null ? null : new String[] { value }; if(values == null) { return null; } } String name = this.getName(); if(name == null) { return null; } ArrayList formInputs = new ArrayList(); for(int i = 0; i < values.length; i++) { formInputs.add(new FormInput(name, values[i])); } return (FormInput[]) formInputs.toArray(FormInput.EMPTY_ARRAY); } public void resetInput() { InputContext ic = this.inputContext; if(ic != null) { ic.resetInput(); } } public void setInputContext(InputContext ic) { super.setInputContext(ic); if(ic != null) { ic.setSelectedIndex(this.deferredSelectedIndex); } } private Function onchange; public Function getOnchange() { return this.getEventFunction(this.onchange, "onchange"); } public void setOnchange(Function value) { this.onchange = value; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLSpanElementImpl.java0000644000175000017500000000222610726473510030123 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 8, 2005 */ package org.lobobrowser.html.domimpl; import org.w3c.dom.html2.HTMLElement; public class HTMLSpanElementImpl extends HTMLAbstractUIElement implements HTMLElement { public HTMLSpanElementImpl(String name) { super(name); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLStrikeElementImpl.java0000644000175000017500000000257310726473500030467 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.*; /** * Element used for STRIKE. */ public class HTMLStrikeElementImpl extends HTMLAbstractUIElement { public HTMLStrikeElementImpl(String name) { super(name); } protected RenderState createRenderState(RenderState prevRenderState) { prevRenderState = new TextDecorationRenderState(prevRenderState, RenderState.MASK_TEXTDECORATION_LINE_THROUGH); return super.createRenderState(prevRenderState); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLStrongElementImpl.java0000644000175000017500000000254210726473502030500 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.*; /** * Element used for B and STRONG. */ public class HTMLStrongElementImpl extends HTMLAbstractUIElement { public HTMLStrongElementImpl(String name) { super(name); } protected RenderState createRenderState(RenderState prevRenderState) { prevRenderState = new FontStyleRenderState(prevRenderState, java.awt.Font.BOLD); return super.createRenderState(prevRenderState); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLStyleElementImpl.java0000644000175000017500000000717311107761130030320 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Nov 27, 2005 */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.CSSUtilities; import org.w3c.css.sac.InputSource; import org.w3c.dom.UserDataHandler; import org.w3c.dom.css.CSSStyleSheet; import org.w3c.dom.html2.HTMLStyleElement; import com.steadystate.css.dom.CSSStyleSheetImpl; import com.steadystate.css.parser.CSSOMParser; public class HTMLStyleElementImpl extends HTMLElementImpl implements HTMLStyleElement { private CSSStyleSheet styleSheet; public HTMLStyleElementImpl() { super("STYLE", true); } public HTMLStyleElementImpl(String name) { super(name, true); } private boolean disabled; public boolean getDisabled() { return this.disabled; } public void setDisabled(boolean disabled) { this.disabled = disabled; CSSStyleSheet sheet = this.styleSheet; if(sheet != null) { sheet.setDisabled(disabled); } } public String getMedia() { return this.getAttribute("media"); } public void setMedia(String media) { this.setAttribute("media", media); } public String getType() { return this.getAttribute("type"); } public void setType(String type) { this.setAttribute("type", type); } public Object setUserData(String key, Object data, UserDataHandler handler) { if(org.lobobrowser.html.parser.HtmlParser.MODIFYING_KEY.equals(key) && data != Boolean.TRUE) { this.processStyle(); } else if(com.steadystate.css.dom.CSSStyleSheetImpl.KEY_DISABLED_CHANGED.equals(key)) { this.informDocumentInvalid(); } return super.setUserData(key, data, handler); } protected void processStyle() { this.styleSheet = null; if(CSSUtilities.matchesMedia(this.getMedia(), this.getUserAgentContext())) { String text = this.getRawInnerText(true); if(text != null && !"".equals(text)) { String processedText = CSSUtilities.preProcessCss(text); HTMLDocumentImpl doc = (HTMLDocumentImpl) this.getOwnerDocument(); CSSOMParser parser = new CSSOMParser(); String baseURI = doc.getBaseURI(); InputSource is = CSSUtilities.getCssInputSourceForStyleSheet(processedText, baseURI); try { CSSStyleSheetImpl sheet = (CSSStyleSheetImpl) parser.parseStyleSheet(is); sheet.setOwnerNode(this); sheet.setHref(baseURI); doc.addStyleSheet(sheet); this.styleSheet = sheet; if(sheet instanceof CSSStyleSheetImpl) { CSSStyleSheetImpl sheetImpl = (CSSStyleSheetImpl) sheet; sheetImpl.setDisabledOnly(this.disabled); } else { sheet.setDisabled(this.disabled); } } catch(Throwable err) { this.warn("Unable to parse style sheet", err); } } } } protected void appendInnerTextImpl(StringBuffer buffer) { // nop } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLSuperscriptElementImpl.java0000644000175000017500000000131011047522352031532 0ustar twernertwernerpackage org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.FontStyleRenderState; import org.lobobrowser.html.style.RenderState; /** * Element used for SUB */ public class HTMLSuperscriptElementImpl extends HTMLAbstractUIElement { private int superscript; public HTMLSuperscriptElementImpl(String name, int superscript) { super(name); this.superscript = superscript; } protected RenderState createRenderState(RenderState prevRenderState) { prevRenderState = FontStyleRenderState.createSuperscriptFontStyleRenderState(prevRenderState, new Integer(this.superscript)); return super.createRenderState(prevRenderState); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLTableCellElementImpl.java0000644000175000017500000001004310726473500031044 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Dec 4, 2005 */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.*; import org.w3c.dom.html2.HTMLTableCellElement; public class HTMLTableCellElementImpl extends HTMLAbstractUIElement implements HTMLTableCellElement { public HTMLTableCellElementImpl(String name) { super(name); } public int getCellIndex() { // TODO Cell index in row return 0; } public String getAbbr() { return this.getAttribute("abbr"); } public void setAbbr(String abbr) { this.setAttribute("abbr", abbr); } public String getAlign() { return this.getAttribute("align"); } public void setAlign(String align) { this.setAttribute("align", align); } public String getAxis() { return this.getAttribute("axis"); } public void setAxis(String axis) { this.setAttribute("axis", axis); } public String getBgColor() { return this.getAttribute("bgcolor"); } public void setBgColor(String bgColor) { this.setAttribute("bgcolor", bgColor); } public String getCh() { return this.getAttribute("ch"); } public void setCh(String ch) { this.setAttribute("ch", ch); } public String getChOff() { return this.getAttribute("choff"); } public void setChOff(String chOff) { this.setAttribute("choff", chOff); } public int getColSpan() { String colSpanText = this.getAttribute("colspan"); if(colSpanText == null) { return 1; } else { try { return Integer.parseInt(colSpanText); } catch(NumberFormatException nfe) { return 1; } } } public void setColSpan(int colSpan) { this.setAttribute("colspan", String.valueOf(colSpan)); } public String getHeaders() { return this.getAttribute("headers"); } public void setHeaders(String headers) { this.setAttribute("headers", headers); } public String getHeight() { return this.getAttribute("height"); } public void setHeight(String height) { this.setAttribute("height", height); } public boolean getNoWrap() { return "nowrap".equalsIgnoreCase(this.getAttribute("nowrap")); } public void setNoWrap(boolean noWrap) { this.setAttribute("nowrap", noWrap ? "nowrap" : null); } public int getRowSpan() { String rowSpanText = this.getAttribute("rowspan"); if(rowSpanText == null) { return 1; } else { try { return Integer.parseInt(rowSpanText); } catch(NumberFormatException nfe) { return 1; } } } public void setRowSpan(int rowSpan) { this.setAttribute("rowspan", String.valueOf(rowSpan)); } public String getScope() { return this.getAttribute("scope"); } public void setScope(String scope) { this.setAttribute("scope", scope); } public String getVAlign() { return this.getAttribute("valign"); } public void setVAlign(String vAlign) { this.setAttribute("valign", vAlign); } public String getWidth() { return this.getAttribute("width"); } public void setWidth(String width) { this.setAttribute("width", width); } protected RenderState createRenderState(RenderState prevRenderState) { return new TableCellRenderState(prevRenderState, this); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLTableElementImpl.java0000644000175000017500000001670210763034072030252 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Dec 3, 2005 */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.*; import org.w3c.dom.DOMException; import org.w3c.dom.Node; import org.w3c.dom.html2.HTMLCollection; import org.w3c.dom.html2.HTMLElement; import org.w3c.dom.html2.HTMLTableCaptionElement; import org.w3c.dom.html2.HTMLTableElement; import org.w3c.dom.html2.HTMLTableSectionElement; import java.util.*; public class HTMLTableElementImpl extends HTMLAbstractUIElement implements HTMLTableElement { public HTMLTableElementImpl() { super("TABLE"); } public HTMLTableElementImpl(String name) { super(name); } private HTMLTableCaptionElement caption; public HTMLTableCaptionElement getCaption() { return this.caption; } public void setCaption(HTMLTableCaptionElement caption) throws DOMException { this.caption = caption; } private HTMLTableSectionElement thead; public HTMLTableSectionElement getTHead() { return this.thead; } public void setTHead(HTMLTableSectionElement tHead) throws DOMException { this.thead = tHead; } private HTMLTableSectionElement tfoot; public HTMLTableSectionElement getTFoot() { return this.tfoot; } public void setTFoot(HTMLTableSectionElement tFoot) throws DOMException { this.tfoot = tFoot; } public HTMLCollection getRows() { return new DescendentHTMLCollection(this, new ElementFilter("TR"), this.treeLock, false); } public HTMLCollection getTBodies() { return new DescendentHTMLCollection(this, new ElementFilter("TBODY"), this.treeLock, false); } public String getAlign() { return this.getAttribute("align"); } public void setAlign(String align) { this.setAttribute("align", align); } public String getBgColor() { return this.getAttribute("bgcolor"); } public void setBgColor(String bgColor) { this.setAttribute("bgcolor", bgColor); } public String getBorder() { return this.getAttribute("border"); } public void setBorder(String border) { this.setAttribute("border", border); } public String getCellPadding() { return this.getAttribute("cellpadding"); } public void setCellPadding(String cellPadding) { this.setAttribute("cellpadding", cellPadding); } public String getCellSpacing() { return this.getAttribute("cellspacing"); } public void setCellSpacing(String cellSpacing) { this.setAttribute("cellspacing", cellSpacing); } public String getFrame() { return this.getAttribute("frame"); } public void setFrame(String frame) { this.setAttribute("frame", frame); } public String getRules() { return this.getAttribute("rules"); } public void setRules(String rules) { this.setAttribute("rules", rules); } public String getSummary() { return this.getAttribute("summary"); } public void setSummary(String summary) { this.setAttribute("summary", summary); } public String getWidth() { return this.getAttribute("width"); } public void setWidth(String width) { this.setAttribute("width", width); } /* (non-Javadoc) * @see org.xamjwg.html.renderer.RenderableContext#getHeightLength() */ public HtmlLength getHeightLength(int availHeight) { try { AbstractCSS2Properties props = this.getCurrentStyle(); String heightText = props == null ? null : props.getHeight(); if(heightText == null) { return new HtmlLength(this.getAttribute("height")); } else { return new HtmlLength(HtmlValues.getPixelSize(heightText, this.getRenderState(), 0, availHeight)); } } catch(Exception err) { return null; } } /* (non-Javadoc) * @see org.xamjwg.html.renderer.RenderableContext#getWidthLength() */ public HtmlLength getWidthLength(int availWidth) { try { AbstractCSS2Properties props = this.getCurrentStyle(); String widthText = props == null ? null : props.getWidth(); if(widthText == null) { return new HtmlLength(this.getAttribute("width")); } else { return new HtmlLength(HtmlValues.getPixelSize(widthText, this.getRenderState(), 0, availWidth)); } } catch(Exception err) { return null; } } public HTMLElement createTHead() { org.w3c.dom.Document doc = this.document; return doc == null ? null : (HTMLElement) doc.createElement("thead"); } public void deleteTHead() { this.removeChildren(new ElementFilter("THEAD")); } public HTMLElement createTFoot() { org.w3c.dom.Document doc = this.document; return doc == null ? null : (HTMLElement) doc.createElement("tfoot"); } public void deleteTFoot() { this.removeChildren(new ElementFilter("TFOOT")); } public HTMLElement createCaption() { org.w3c.dom.Document doc = this.document; return doc == null ? null : (HTMLElement) doc.createElement("caption"); } public void deleteCaption() { this.removeChildren(new ElementFilter("CAPTION")); } /** * Inserts a row at the index given. If index is -1, * the row is appended as the last row. */ public HTMLElement insertRow(int index) throws DOMException { org.w3c.dom.Document doc = this.document; if(doc == null) { throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, "Orphan element"); } HTMLElement rowElement = (HTMLElement) doc.createElement("TR"); synchronized(this.treeLock) { if(index == -1) { this.appendChild(rowElement); return rowElement; } ArrayList nl = this.nodeList; if(nl != null) { int size = nl.size(); int trcount = 0; for(int i = 0; i < size; i++) { Node node = (Node) nl.get(i); if("TR".equalsIgnoreCase(node.getNodeName())) { if(trcount == index) { this.insertAt(rowElement, i); return rowElement; } trcount++; } } } else { this.appendChild(rowElement); return rowElement; } } throw new DOMException(DOMException.INDEX_SIZE_ERR, "Index out of range"); } public void deleteRow(int index) throws DOMException { synchronized(this.treeLock) { ArrayList nl = this.nodeList; if(nl != null) { int size = nl.size(); int trcount = 0; for(int i = 0; i < size; i++) { Node node = (Node) nl.get(i); if("TR".equalsIgnoreCase(node.getNodeName())) { if(trcount == index) { this.removeChildAt(i); return; } trcount++; } } } } throw new DOMException(DOMException.INDEX_SIZE_ERR, "Index out of range"); } protected RenderState createRenderState(RenderState prevRenderState) { return new TableRenderState(prevRenderState, this); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLTableHeadElementImpl.java0000644000175000017500000000264410726473504031042 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.FontStyleRenderState; import org.lobobrowser.html.style.RenderState; /** * Element used for TH. */ public class HTMLTableHeadElementImpl extends HTMLTableCellElementImpl { public HTMLTableHeadElementImpl(String name) { super(name); } protected RenderState createRenderState(RenderState prevRenderState) { prevRenderState = new FontStyleRenderState(prevRenderState, java.awt.Font.BOLD); return super.createRenderState(prevRenderState); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLTableRowElementImpl.java0000644000175000017500000001205011123426710030725 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Dec 4, 2005 */ package org.lobobrowser.html.domimpl; import java.util.ArrayList; import org.w3c.dom.DOMException; import org.w3c.dom.Node; import org.w3c.dom.html2.HTMLCollection; import org.w3c.dom.html2.HTMLElement; import org.w3c.dom.html2.HTMLTableRowElement; public class HTMLTableRowElementImpl extends HTMLElementImpl implements HTMLTableRowElement { public HTMLTableRowElementImpl(String name) { super(name, true); } public HTMLTableRowElementImpl() { super("TR", true); } public int getRowIndex() { NodeImpl parent = (NodeImpl) this.getParentNode(); if(parent == null) { return -1; } try { parent.visit(new NodeVisitor() { private int count = 0; public void visit(Node node) { if(node instanceof HTMLTableRowElementImpl) { if(HTMLTableRowElementImpl.this == node) { throw new StopVisitorException(new Integer(this.count)); } this.count++; } } }); } catch(StopVisitorException sve) { return ((Integer) sve.getTag()).intValue(); } return -1; } public int getSectionRowIndex() { // TODO Auto-generated method stub return 0; } public HTMLCollection getCells() { NodeFilter filter = new NodeFilter() { public boolean accept(Node node) { return node instanceof HTMLTableCellElementImpl; } }; return new DescendentHTMLCollection(this, filter, this.treeLock, false); } public String getAlign() { return this.getAttribute("align"); } public void setAlign(String align) { this.setAttribute("align", align); } public String getBgColor() { return this.getAttribute("bgcolor"); } public void setBgColor(String bgColor) { this.setAttribute("bgcolor", bgColor); } public String getCh() { return this.getAttribute("ch"); } public void setCh(String ch) { this.setAttribute("ch", ch); } public String getChOff() { return this.getAttribute("choff"); } public void setChOff(String chOff) { this.setAttribute("choff", chOff); } public String getVAlign() { return this.getAttribute("valign"); } public void setVAlign(String vAlign) { this.setAttribute("valign", vAlign); } /** * Inserts a TH element at the specified index. *

* Note: This method is non-standard. * @param index The cell index to insert at. * @return The element that was inserted. * @throws DOMException When the index is out of range. */ public HTMLElement insertHeader(int index) throws DOMException { return this.insertCell(index, "TH"); } public HTMLElement insertCell(int index) throws DOMException { return this.insertCell(index, "TD"); } private HTMLElement insertCell(int index, String tagName) throws DOMException { org.w3c.dom.Document doc = this.document; if(doc == null) { throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, "Orphan element"); } HTMLElement cellElement = (HTMLElement) doc.createElement(tagName); synchronized(this.treeLock) { if(index == -1) { this.appendChild(cellElement); return cellElement; } ArrayList nl = this.nodeList; if(nl != null) { int size = nl.size(); int trcount = 0; for(int i = 0; i < size; i++) { Node node = (Node) nl.get(i); if(node instanceof org.w3c.dom.html2.HTMLTableCellElement) { if(trcount == index) { this.insertAt(cellElement, i); return cellElement; } trcount++; } } } else { this.appendChild(cellElement); return cellElement; } } throw new DOMException(DOMException.INDEX_SIZE_ERR, "Index out of range"); } public void deleteCell(int index) throws DOMException { synchronized(this.treeLock) { ArrayList nl = this.nodeList; if(nl != null) { int size = nl.size(); int trcount = 0; for(int i = 0; i < size; i++) { Node node = (Node) nl.get(i); if(node instanceof org.w3c.dom.html2.HTMLTableCellElement) { if(trcount == index) { this.removeChildAt(index); } trcount++; } } } } throw new DOMException(DOMException.INDEX_SIZE_ERR, "Index out of range"); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLTextAreaElementImpl.java0000644000175000017500000000476310726473510030747 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 15, 2006 */ package org.lobobrowser.html.domimpl; import java.io.UnsupportedEncodingException; import org.lobobrowser.html.FormInput; import org.w3c.dom.html2.HTMLFormElement; import org.w3c.dom.html2.HTMLTextAreaElement; public class HTMLTextAreaElementImpl extends HTMLBaseInputElement implements HTMLTextAreaElement { public HTMLTextAreaElementImpl(String name) { super(name); } public HTMLTextAreaElementImpl() { super("TEXTAREA"); } protected FormInput[] getFormInputs() { String name = this.getName(); if(name == null) { return null; } return new FormInput[] { new FormInput(name, this.getValue()) }; } /* (non-Javadoc) * @see org.w3c.dom.html2.HTMLTextAreaElement#getCols() */ public int getCols() { InputContext ic = this.inputContext; return ic == null ? 0 : ic.getCols(); } /* (non-Javadoc) * @see org.w3c.dom.html2.HTMLTextAreaElement#getRows() */ public int getRows() { InputContext ic = this.inputContext; return ic == null ? 0 : ic.getRows(); } /* (non-Javadoc) * @see org.w3c.dom.html2.HTMLTextAreaElement#getType() */ public String getType() { return "textarea"; } /* (non-Javadoc) * @see org.w3c.dom.html2.HTMLTextAreaElement#setCols(int) */ public void setCols(int cols) { InputContext ic = this.inputContext; if(ic != null) { ic.setCols(cols); } } /* (non-Javadoc) * @see org.w3c.dom.html2.HTMLTextAreaElement#setRows(int) */ public void setRows(int rows) { InputContext ic = this.inputContext; if(ic != null) { ic.setRows(rows); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLTitleElementImpl.java0000644000175000017500000000311010726473506030301 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.domimpl; import org.w3c.dom.*; public class HTMLTitleElementImpl extends HTMLElementImpl { public HTMLTitleElementImpl(String name) { super(name, true); } public Object setUserData(String key, Object data, UserDataHandler handler) { if(org.lobobrowser.html.parser.HtmlParser.MODIFYING_KEY.equals(key) && data == Boolean.FALSE) { Document document = this.document; if(document instanceof HTMLDocumentImpl) { String textContent = this.getTextContent(); String title = textContent == null ? null : textContent.trim(); ((HTMLDocumentImpl) document).setTitle(title); } } return super.setUserData(key, data, handler); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLUListElementImpl.java0000644000175000017500000000334611134376542030267 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Feb 12, 2006 */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.*; import org.w3c.dom.html2.HTMLUListElement; public class HTMLUListElementImpl extends HTMLAbstractUIElement implements HTMLUListElement { public HTMLUListElementImpl(String name) { super(name); } public boolean getCompact() { String compactText = this.getAttribute("compact"); return "compact".equalsIgnoreCase(compactText); } public void setCompact(boolean compact) { this.setAttribute("compact", compact ? "compact" : null); } public String getType() { return this.getAttribute("type"); } public void setType(String type) { this.setAttribute("type", type); } protected RenderState createRenderState(RenderState prevRenderState) { return new ListRenderState(prevRenderState, this); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/HTMLUnderlineElementImpl.java0000644000175000017500000000257110726473502031153 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.domimpl; import org.lobobrowser.html.style.*; /** * Element used for U. */ public class HTMLUnderlineElementImpl extends HTMLAbstractUIElement { public HTMLUnderlineElementImpl(String name) { super(name); } protected RenderState createRenderState(RenderState prevRenderState) { prevRenderState = new TextDecorationRenderState(prevRenderState, RenderState.MASK_TEXTDECORATION_UNDERLINE); return super.createRenderState(prevRenderState); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/ImageEvent.java0000644000175000017500000000222010726473510026417 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.domimpl; import java.util.EventObject; public class ImageEvent extends EventObject { public final java.awt.Image image; public ImageEvent(Object source, java.awt.Image image) { super(source); this.image = image; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/ImageListener.java0000644000175000017500000000215110726473510027126 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.domimpl; public interface ImageListener extends java.util.EventListener { public static final ImageListener[] EMPTY_ARRAY = new ImageListener[0]; public void imageLoaded(ImageEvent event); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/InputContext.java0000644000175000017500000000376210773432746027063 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 15, 2006 */ package org.lobobrowser.html.domimpl; public interface InputContext { public boolean getChecked(); public void setChecked(boolean checked); public boolean getDisabled(); public void setDisabled(boolean disabled); public int getMaxLength(); public void setMaxLength(int maxLength); public String getName(); public void setName(String name); public boolean getReadOnly(); public void setReadOnly(boolean readOnly); public int getControlSize(); public void setControlSize(int size); public int getTabIndex(); public void setTabIndex(int tabIndex); public String getValue(); public String[] getValues(); public void setValue(String value); public void blur(); public void focus(); public void select(); public void click(); public int getRows(); public int getCols(); public void setRows(int rows); public void setCols(int cols); public int getSelectedIndex(); public void setSelectedIndex(int value); public int getVisibleSize(); public void setVisibleSize(int value); public java.io.File getFileValue(); public void resetInput(); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/LocalErrorHandler.java0000644000175000017500000000340010726473510027736 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 22, 2005 */ package org.lobobrowser.html.domimpl; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import java.util.logging.*; class LocalErrorHandler implements ErrorHandler { private static final Logger logger = Logger.getLogger(LocalErrorHandler.class.getName()); /** * @param context */ public LocalErrorHandler() { } public void warning(SAXParseException exception) throws SAXException { logger.log(Level.WARNING,exception.getMessage(), exception.getCause()); } public void error(SAXParseException exception) throws SAXException { logger.log(Level.SEVERE,exception.getMessage(), exception.getCause()); } public void fatalError(SAXParseException exception) throws SAXException { logger.log(Level.SEVERE,exception.getMessage(), exception.getCause()); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/ModelNode.java0000644000175000017500000000346310726473500026252 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 23, 2005 */ package org.lobobrowser.html.domimpl; import java.net.MalformedURLException; import org.lobobrowser.html.style.*; /** * A generic node interface. The idea is that implementors could * be W3C nodes or not. */ public interface ModelNode { //There shouldn't be any references to GUI components here. //Events are processed by controller in renderer package. public java.net.URL getFullURL(String spec) throws MalformedURLException; public void warn(String message, Throwable err); public boolean isEqualOrDescendentOf(ModelNode otherNode); public ModelNode getParentModelNode(); public RenderState getRenderState(); /** * Sets a document item. A radio button, for example, * can use this to set button group state. * @param name * @param value */ public void setDocumentItem(String name, Object value); public Object getDocumentItem(String name); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/NamedNodeMapImpl.java0000644000175000017500000000607510726473510027521 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Sep 3, 2005 */ package org.lobobrowser.html.domimpl; import org.lobobrowser.js.*; import org.w3c.dom.*; import java.util.*; public class NamedNodeMapImpl extends AbstractScriptableDelegate implements NamedNodeMap { //Note: class must be public for reflection to work. private final Map attributes = new HashMap(); private final ArrayList attributeList = new ArrayList(); public NamedNodeMapImpl(Element owner, Map attribs) { Iterator i = attribs.entrySet().iterator(); while(i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); String name = (String) entry.getKey(); String value = (String) entry.getValue(); //TODO: "specified" attributes Attr attr = new AttrImpl(name, value, true, owner, "ID".equals(name)); this.attributes.put(name, attr); this.attributeList.add(attr); } } public int getLength() { return this.attributeList.size(); } public Node getNamedItem(String name) { return (Node) this.attributes.get(name); } /** * @param name */ public Node namedItem(String name) { // Method needed for Javascript indexing. return this.getNamedItem(name); } public Node getNamedItemNS(String namespaceURI, String localName) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "No namespace support"); } public Node item(int index) { try { return (Node) this.attributeList.get(index); } catch(IndexOutOfBoundsException iob) { return null; } } public Node removeNamedItem(String name) throws DOMException { return (Node) this.attributes.remove(name); } public Node removeNamedItemNS(String namespaceURI, String localName) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "No namespace support"); } public Node setNamedItem(Node arg) throws DOMException { Object prevValue = this.attributes.put(arg.getNodeName(), arg); if(prevValue != null) { this.attributeList.remove(prevValue); } this.attributeList.add(arg); return arg; } public Node setNamedItemNS(Node arg) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "No namespace support"); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/NodeFilter.java0000644000175000017500000000206010726473510026430 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 8, 2005 */ package org.lobobrowser.html.domimpl; import org.w3c.dom.*; public interface NodeFilter { public boolean accept(Node node); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/NodeImpl.java0000644000175000017500000007624011067635342026121 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Sep 3, 2005 */ package org.lobobrowser.html.domimpl; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.logging.*; import org.lobobrowser.html.*; import org.lobobrowser.html.style.*; import org.lobobrowser.js.*; import org.lobobrowser.util.*; import org.w3c.dom.*; public abstract class NodeImpl extends AbstractScriptableDelegate implements Node, ModelNode { private static final NodeImpl[] EMPTY_ARRAY = new NodeImpl[0]; private static final RenderState INVALID_RENDER_STATE = new StyleSheetRenderState(null); protected static final Logger logger = Logger.getLogger(NodeImpl.class.getName()); protected UINode uiNode; protected ArrayList nodeList; protected volatile Document document; /** * A tree lock is less deadlock-prone than * a node-level lock. This is assigned in * setOwnerDocument. */ protected volatile Object treeLock = this; public NodeImpl() { super(); } public void setUINode(UINode uiNode) { // Called in GUI thread always. this.uiNode = uiNode; } public UINode getUINode() { // Called in GUI thread always. return this.uiNode; } /** * Tries to get a UINode associated with the current node. * Failing that, it tries ancestors recursively. This method * will return the closest block-level renderer node, if any. */ public UINode findUINode() { // Called in GUI thread always. UINode uiNode = this.uiNode; if(uiNode != null) { return uiNode; } NodeImpl parentNode = (NodeImpl) this.getParentNode(); return parentNode == null ? null : parentNode.findUINode(); } public Node appendChild(Node newChild) throws DOMException { synchronized(this.treeLock) { ArrayList nl = this.nodeList; if(nl == null) { nl = new ArrayList(3); this.nodeList = nl; } nl.add(newChild); if(newChild instanceof NodeImpl) { ((NodeImpl) newChild).setParentImpl(this); } } if(!this.notificationsSuspended) { this.informStructureInvalid(); } return newChild; } protected void removeAllChildren() { synchronized(this.treeLock) { this.removeAllChildrenImpl(); } } protected void removeAllChildrenImpl() { synchronized(this.treeLock) { ArrayList nl = this.nodeList; if(nl != null) { nl.clear(); //this.nodeList = null; } } if(!this.notificationsSuspended) { this.informStructureInvalid(); } } protected NodeList getNodeList(NodeFilter filter) { Collection collection = new ArrayList(); synchronized(this.treeLock) { this.appendChildrenToCollectionImpl(filter, collection); } return new NodeListImpl(collection); } public NodeImpl[] getChildrenArray() { ArrayList nl = this.nodeList; synchronized(this.treeLock) { return nl == null ? null : (NodeImpl[]) nl.toArray(NodeImpl.EMPTY_ARRAY); } } int getChildCount() { ArrayList nl = this.nodeList; synchronized(this.treeLock) { return nl == null ? 0 : nl.size(); } } private ChildHTMLCollection childrenCollection; public ChildHTMLCollection getChildren() { // Method required by JavaScript synchronized(this) { ChildHTMLCollection collection = this.childrenCollection; if(collection == null) { collection = new ChildHTMLCollection(this); this.childrenCollection = collection; } return collection; } } /** * Creates an ArrayList of descendent nodes that * the given filter condition. */ public ArrayList getDescendents(NodeFilter filter, boolean nestIntoMatchingNodes) { ArrayList al = new ArrayList(); synchronized(this.treeLock) { this.extractDescendentsArrayImpl(filter, al, nestIntoMatchingNodes); } return al; } /** * Extracts all descendents that match the filter, except those * descendents of nodes that match the filter. * @param filter * @param al */ private void extractDescendentsArrayImpl(NodeFilter filter, ArrayList al, boolean nestIntoMatchingNodes) { ArrayList nl = this.nodeList; if(nl != null) { Iterator i = nl.iterator(); while(i.hasNext()) { NodeImpl n = (NodeImpl) i.next(); if(filter.accept(n)) { al.add(n); if(nestIntoMatchingNodes) { n.extractDescendentsArrayImpl(filter, al, nestIntoMatchingNodes); } } else if(n.getNodeType() == Node.ELEMENT_NODE) { n.extractDescendentsArrayImpl(filter, al, nestIntoMatchingNodes); } } } } private void appendChildrenToCollectionImpl(NodeFilter filter, Collection collection) { ArrayList nl = this.nodeList; if(nl != null) { Iterator i = nl.iterator(); while(i.hasNext()) { NodeImpl node = (NodeImpl) i.next(); if(filter.accept(node)) { collection.add(node); } node.appendChildrenToCollectionImpl(filter, collection); } } } /** * Should create a node with some cloned properties, like the node name, * but not attributes or children. */ protected abstract Node createSimilarNode(); public Node cloneNode(boolean deep) { try { Node newNode = this.createSimilarNode(); NodeList children = this.getChildNodes(); int length = children.getLength(); for(int i = 0; i < length; i++) { Node child = (Node) children.item(i); Node newChild = deep ? child.cloneNode(deep) : child; newNode.appendChild(newChild); } if(newNode instanceof Element) { Element elem = (Element) newNode; NamedNodeMap nnmap = this.getAttributes(); if(nnmap != null) { int nnlength = nnmap.getLength(); for(int i = 0; i < nnlength; i++) { Attr attr = (Attr) nnmap.item(i); elem.setAttributeNode((Attr) attr.cloneNode(true)); } } } synchronized(this){ if (userDataHandlers != null && userData != null) { for(Iterator handlers = userDataHandlers.entrySet().iterator();handlers.hasNext();){ Map.Entry entry = (Map.Entry) handlers.next(); UserDataHandler handler = (UserDataHandler)entry.getValue(); handler.handle(UserDataHandler.NODE_CLONED,(String) entry.getKey(),userData.get(entry.getKey()), this, newNode); } } } return newNode; } catch(Exception err) { throw new IllegalStateException(err.getMessage()); } } private int getNodeIndex() { NodeImpl parent = (NodeImpl) this.getParentNode(); return parent == null ? -1 : parent.getChildIndex(this); } int getChildIndex(Node child) { synchronized(this.treeLock) { ArrayList nl = this.nodeList; return nl == null ? -1 : nl.indexOf(child); } } Node getChildAtIndex(int index) { synchronized(this.treeLock) { ArrayList nl = this.nodeList; try { return nl == null ? null : (Node) nl.get(index); } catch(IndexOutOfBoundsException iob) { this.warn("getChildAtIndex(): Bad index=" + index + " for node=" + this + "."); return null; } } } private boolean isAncestorOf(Node other) { NodeImpl parent = (NodeImpl) other.getParentNode(); if(parent == this) { return true; } else if(parent == null) { return false; } else { return this.isAncestorOf(parent); } } public short compareDocumentPosition(Node other) throws DOMException { Node parent = this.getParentNode(); if(!(other instanceof NodeImpl)) { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Unknwon node implementation"); } if(parent != null && parent == other.getParentNode()) { int thisIndex = this.getNodeIndex(); int otherIndex = ((NodeImpl) other).getNodeIndex(); if(thisIndex == -1 || otherIndex == -1) { return Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC; } if(thisIndex < otherIndex) { return Node.DOCUMENT_POSITION_FOLLOWING; } else { return Node.DOCUMENT_POSITION_PRECEDING; } } else if(this.isAncestorOf(other)) { return Node.DOCUMENT_POSITION_CONTAINED_BY; } else if(((NodeImpl) other).isAncestorOf(this)) { return Node.DOCUMENT_POSITION_CONTAINS; } else { return Node.DOCUMENT_POSITION_DISCONNECTED; } } public NamedNodeMap getAttributes() { return null; } public Document getOwnerDocument() { return this.document; } void setOwnerDocument(Document value) { this.document = value; this.treeLock = value == null ? this : (Object) value; } void setOwnerDocument(Document value, boolean deep) { this.document = value; this.treeLock = value == null ? this : (Object) value; if(deep) { synchronized(this.treeLock) { ArrayList nl = this.nodeList; if(nl != null) { Iterator i = nl.iterator(); while(i.hasNext()) { NodeImpl child = (NodeImpl) i.next(); child.setOwnerDocument(value, deep); } } } } } void visitImpl(NodeVisitor visitor) { try { visitor.visit(this); } catch(SkipVisitorException sve) { return; } catch(StopVisitorException sve) { throw sve; } ArrayList nl = this.nodeList; if(nl != null) { Iterator i = nl.iterator(); while(i.hasNext()) { NodeImpl child = (NodeImpl) i.next(); try { // Call with child's synchronization child.visit(visitor); } catch(StopVisitorException sve) { throw sve; } } } } void visit(NodeVisitor visitor) { synchronized(this.treeLock) { this.visitImpl(visitor); } } public Node insertBefore(Node newChild, Node refChild) throws DOMException { synchronized(this.treeLock) { ArrayList nl = this.nodeList; int idx = nl == null ? -1 : nl.indexOf(refChild); if(idx == -1) { throw new DOMException(DOMException.NOT_FOUND_ERR, "refChild not found"); } nl.add(idx, newChild); if(newChild instanceof NodeImpl) { ((NodeImpl) newChild).setParentImpl(this); } } if(!this.notificationsSuspended) { this.informStructureInvalid(); } return newChild; } protected Node insertAt(Node newChild, int idx) throws DOMException { synchronized(this.treeLock) { ArrayList nl = this.nodeList; if(nl == null) { nl = new ArrayList(); this.nodeList = nl; } nl.add(idx, newChild); if(newChild instanceof NodeImpl) { ((NodeImpl) newChild).setParentImpl(this); } } if(!this.notificationsSuspended) { this.informStructureInvalid(); } return newChild; } public Node replaceChild(Node newChild, Node oldChild) throws DOMException { synchronized(this.treeLock) { ArrayList nl = this.nodeList; int idx = nl == null ? -1 : nl.indexOf(oldChild); if(idx == -1) { throw new DOMException(DOMException.NOT_FOUND_ERR, "oldChild not found"); } nl.set(idx, newChild); } if(!this.notificationsSuspended) { this.informStructureInvalid(); } return newChild; } public Node removeChild(Node oldChild) throws DOMException { synchronized(this.treeLock) { ArrayList nl = this.nodeList; if(nl == null || !nl.remove(oldChild)) { throw new DOMException(DOMException.NOT_FOUND_ERR, "oldChild not found"); } } if(!this.notificationsSuspended) { this.informStructureInvalid(); } return oldChild; } public Node removeChildAt(int index) throws DOMException { try { synchronized(this.treeLock) { ArrayList nl = this.nodeList; if(nl == null) { throw new DOMException(DOMException.INDEX_SIZE_ERR, "Empty list of children"); } Node n = (Node) nl.remove(index); if (n == null) { throw new DOMException(DOMException.INDEX_SIZE_ERR, "No node with that index"); } return n; } } finally { if(!this.notificationsSuspended) { this.informStructureInvalid(); } } } public boolean hasChildNodes() { synchronized(this.treeLock) { ArrayList nl = this.nodeList; return nl != null && !nl.isEmpty(); } } public String getBaseURI() { Document document = this.document; return document == null ? null : document.getBaseURI(); } public NodeList getChildNodes() { synchronized(this.treeLock) { ArrayList nl = this.nodeList; return new NodeListImpl(nl == null ? Collections.EMPTY_LIST : nl); } } public Node getFirstChild() { synchronized(this.treeLock) { ArrayList nl = this.nodeList; try { return nl == null ? null : (Node) nl.get(0); } catch(IndexOutOfBoundsException iob) { return null; } } } public Node getLastChild() { synchronized(this.treeLock) { ArrayList nl = this.nodeList; try { return nl == null ? null : (Node) nl.get(nl.size() - 1); } catch(IndexOutOfBoundsException iob) { return null; } } } private Node getPreviousTo(Node node) { synchronized(this.treeLock) { ArrayList nl = this.nodeList; int idx = nl == null ? -1 : nl.indexOf(node); if(idx == -1) { throw new DOMException(DOMException.NOT_FOUND_ERR, "node not found"); } try { return (Node) nl.get(idx-1); } catch(IndexOutOfBoundsException iob) { return null; } } } private Node getNextTo(Node node) { synchronized(this.treeLock) { ArrayList nl = this.nodeList; int idx = nl == null ? -1 : nl.indexOf(node); if(idx == -1) { throw new DOMException(DOMException.NOT_FOUND_ERR, "node not found"); } try { return (Node) nl.get(idx+1); } catch(IndexOutOfBoundsException iob) { return null; } } } public Node getPreviousSibling() { NodeImpl parent = (NodeImpl) this.getParentNode(); return parent == null ? null : parent.getPreviousTo(this); } public Node getNextSibling() { NodeImpl parent = (NodeImpl) this.getParentNode(); return parent == null ? null : parent.getNextTo(this); } public Object getFeature(String feature, String version) { //TODO What should this do? return null; } private Map userData; //TODO: Inform handlers on cloning, etc. private Map userDataHandlers; protected volatile boolean notificationsSuspended = false; public Object setUserData(String key, Object data, UserDataHandler handler) { if(org.lobobrowser.html.parser.HtmlParser.MODIFYING_KEY.equals(key)) { boolean ns = (Boolean.TRUE == data); this.notificationsSuspended = ns; if(!ns) { this.informNodeLoaded(); } } //here we spent some effort preventing our maps from growing too much synchronized(this) { if(handler != null) { if(this.userDataHandlers == null) { this.userDataHandlers = new HashMap(); } else if (handler == null){ this.userDataHandlers.remove(key); } if (handler != null) this.userDataHandlers.put(key,handler); } Map userData = this.userData; if (data != null){ if(userData == null) { userData = new HashMap(); this.userData = userData; } return userData.put(key, data); } else if (userData != null) return userData.remove(key); else return null; } } public Object getUserData(String key) { synchronized(this) { Map ud = this.userData; return ud == null ? null : ud.get(key); } } public abstract String getLocalName(); public boolean hasAttributes() { return false; } public String getNamespaceURI() { return null; } public abstract String getNodeName(); public abstract String getNodeValue() throws DOMException; private volatile String prefix; public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) throws DOMException { this.prefix = prefix; } public abstract void setNodeValue(String nodeValue) throws DOMException; public abstract short getNodeType(); /** * Gets the text content of this node * and its descendents. */ public String getTextContent() throws DOMException { StringBuffer sb = new StringBuffer(); synchronized(this.treeLock) { ArrayList nl = this.nodeList; if(nl != null) { Iterator i = nl.iterator(); while(i.hasNext()) { Node node = (Node) i.next(); short type = node.getNodeType(); switch(type) { case Node.CDATA_SECTION_NODE: case Node.TEXT_NODE: case Node.ELEMENT_NODE: String textContent = node.getTextContent(); if(textContent != null) { sb.append(textContent); } break; default: break; } } } } return sb.toString(); } public void setTextContent(String textContent) throws DOMException { synchronized(this.treeLock) { this.removeChildrenImpl(new TextFilter()); if(textContent != null && !"".equals(textContent)) { TextImpl t = new TextImpl(textContent); t.setOwnerDocument(this.document); t.setParentImpl(this); ArrayList nl = this.nodeList; if(nl == null) { nl = new ArrayList(); this.nodeList = nl; } nl.add(t); } } if(!this.notificationsSuspended) { this.informStructureInvalid(); } } protected void removeChildren(NodeFilter filter) { synchronized(this.treeLock) { this.removeChildrenImpl(filter); } if(!this.notificationsSuspended) { this.informStructureInvalid(); } } protected void removeChildrenImpl(NodeFilter filter) { ArrayList nl = this.nodeList; if(nl != null) { int len = nl.size(); for(int i = len; --i >= 0;) { Node node = (Node) nl.get(i); if(filter.accept(node)) { nl.remove(i); } } } } public Node insertAfter(Node newChild, Node refChild) { synchronized(this.treeLock) { ArrayList nl = this.nodeList; int idx = nl == null ? -1 : nl.indexOf(refChild); if(idx == -1) { throw new DOMException(DOMException.NOT_FOUND_ERR, "refChild not found"); } nl.add(idx+1, newChild); if(newChild instanceof NodeImpl) { ((NodeImpl) newChild).setParentImpl(this); } } if(!this.notificationsSuspended) { this.informStructureInvalid(); } return newChild; } public Text replaceAdjacentTextNodes(Text node, String textContent) { try { synchronized(this.treeLock) { ArrayList nl = this.nodeList; if(nl == null) { throw new DOMException(DOMException.NOT_FOUND_ERR, "Node not a child"); } int idx = nl.indexOf(node); if(idx == -1) { throw new DOMException(DOMException.NOT_FOUND_ERR, "Node not a child"); } int firstIdx = idx; List toDelete = new LinkedList(); for(int adjIdx = idx; --adjIdx >= 0;) { Object child = this.nodeList.get(adjIdx); if(child instanceof Text) { firstIdx = adjIdx; toDelete.add(child); } } int length = this.nodeList.size(); for(int adjIdx = idx; ++adjIdx < length;) { Object child = this.nodeList.get(adjIdx); if(child instanceof Text) { toDelete.add(child); } } this.nodeList.removeAll(toDelete); TextImpl textNode = new TextImpl(textContent); textNode.setOwnerDocument(this.document); textNode.setParentImpl(this); this.nodeList.add(firstIdx, textNode); return textNode; } } finally { if(!this.notificationsSuspended) { this.informStructureInvalid(); } } } public Text replaceAdjacentTextNodes(Text node) { try { synchronized(this.treeLock) { ArrayList nl = this.nodeList; if(nl == null) { throw new DOMException(DOMException.NOT_FOUND_ERR, "Node not a child"); } int idx = nl.indexOf(node); if(idx == -1) { throw new DOMException(DOMException.NOT_FOUND_ERR, "Node not a child"); } StringBuffer textBuffer = new StringBuffer(); int firstIdx = idx; List toDelete = new LinkedList(); for(int adjIdx = idx; --adjIdx >= 0;) { Object child = this.nodeList.get(adjIdx); if(child instanceof Text) { firstIdx = adjIdx; toDelete.add(child); textBuffer.append(((Text) child).getNodeValue()); } } int length = this.nodeList.size(); for(int adjIdx = idx; ++adjIdx < length;) { Object child = this.nodeList.get(adjIdx); if(child instanceof Text) { toDelete.add(child); textBuffer.append(((Text) child).getNodeValue()); } } this.nodeList.removeAll(toDelete); TextImpl textNode = new TextImpl(textBuffer.toString()); textNode.setOwnerDocument(this.document); textNode.setParentImpl(this); this.nodeList.add(firstIdx, textNode); return textNode; } } finally { if(!this.notificationsSuspended) { this.informStructureInvalid(); } } } protected volatile Node parentNode; public Node getParentNode() { // Should it be synchronized? Could have side-effects. return this.parentNode; } public boolean isSameNode(Node other) { return this == other; } public boolean isSupported(String feature, String version) { return ("HTML".equals(feature) && version.compareTo("4.01") <= 0); } public String lookupNamespaceURI(String prefix) { return null; } public boolean equalAttributes(Node arg) { return false; } public boolean isEqualNode(Node arg) { return arg instanceof NodeImpl && this.getNodeType() == arg.getNodeType() && Objects.equals(this.getNodeName(), arg.getNodeName()) && Objects.equals(this.getNodeValue(), arg.getNodeValue()) && Objects.equals(this.getLocalName(), arg.getLocalName()) && Objects.equals(this.nodeList, ((NodeImpl) arg).nodeList) && this.equalAttributes(arg); } public boolean isDefaultNamespace(String namespaceURI) { return namespaceURI == null; } public String lookupPrefix(String namespaceURI) { return null; } public void normalize() { synchronized(this.treeLock) { ArrayList nl = this.nodeList; if(nl != null) { Iterator i = nl.iterator(); List textNodes = new LinkedList(); boolean prevText = false; while(i.hasNext()) { Node child = (Node) i.next(); if(child.getNodeType() == Node.TEXT_NODE) { if(!prevText) { prevText = true; textNodes.add(child); } } else { prevText = false; } } i = textNodes.iterator(); while(i.hasNext()) { Text text = (Text) i.next(); this.replaceAdjacentTextNodes(text); } } } if(!this.notificationsSuspended) { this.informStructureInvalid(); } } public String toString() { return this.getNodeName(); } public UserAgentContext getUserAgentContext() { Object doc = this.document; if(doc instanceof HTMLDocumentImpl) { return ((HTMLDocumentImpl) doc).getUserAgentContext(); } else { return null; } } public HtmlRendererContext getHtmlRendererContext() { Object doc = this.document; if(doc instanceof HTMLDocumentImpl) { return ((HTMLDocumentImpl) doc).getHtmlRendererContext(); } else { return null; } } final void setParentImpl(Node parent) { // Call holding treeLock. this.parentNode = parent; } //----- ModelNode implementation /* (non-Javadoc) * @see org.xamjwg.html.renderer.RenderableContext#getAlignmentX() */ public float getAlignmentX() { //TODO: Removable method? return 0.5f; } /* (non-Javadoc) * @see org.xamjwg.html.renderer.RenderableContext#getAlignmentY() */ public float getAlignmentY() { return 0.5f; } /* (non-Javadoc) * @see org.xamjwg.html.renderer.RenderableContext#getFullURL(java.lang.String) */ public URL getFullURL(String spec) throws MalformedURLException { Object doc = this.document; if(doc instanceof HTMLDocumentImpl) { return ((HTMLDocumentImpl) doc).getFullURL(spec); } else { return new java.net.URL(spec); } } public URL getDocumentURL() { Object doc = this.document; if(doc instanceof HTMLDocumentImpl) { return ((HTMLDocumentImpl) doc).getDocumentURL(); } else { return null; } } /* (non-Javadoc) * @see org.xamjwg.html.renderer.RenderableContext#getDocumentItem(java.lang.String) */ public Object getDocumentItem(String name) { org.w3c.dom.Document document = this.document; return document == null ? null : document.getUserData(name); } /* (non-Javadoc) * @see org.xamjwg.html.renderer.RenderableContext#setDocumentItem(java.lang.String, java.lang.Object) */ public void setDocumentItem(String name, Object value) { org.w3c.dom.Document document = this.document; if(document == null) { return; } document.setUserData(name, value, null); } /* (non-Javadoc) * @see org.xamjwg.html.renderer.RenderableContext#isEqualOrDescendentOf(org.xamjwg.html.renderer.RenderableContext) */ public final boolean isEqualOrDescendentOf(ModelNode otherContext) { if(otherContext == this) { return true; } Object parent = this.getParentNode(); if(parent instanceof HTMLElementImpl) { return ((HTMLElementImpl) parent).isEqualOrDescendentOf(otherContext); } else { return false; } } public final ModelNode getParentModelNode() { return (ModelNode) this.parentNode; } public void warn(String message, Throwable err) { logger.log(Level.WARNING, message, err); } public void warn(String message) { logger.log(Level.WARNING, message); } public void informSizeInvalid() { HTMLDocumentImpl doc = (HTMLDocumentImpl) this.document; if(doc != null) { doc.sizeInvalidated(this); } } public void informLookInvalid() { this.forgetRenderState(); HTMLDocumentImpl doc = (HTMLDocumentImpl) this.document; if(doc != null) { doc.lookInvalidated(this); } } public void informPositionInvalid() { HTMLDocumentImpl doc = (HTMLDocumentImpl) this.document; if(doc != null) { doc.positionInParentInvalidated(this); } } public void informInvalid() { // This is called when an attribute or child changes. this.forgetRenderState(); HTMLDocumentImpl doc = (HTMLDocumentImpl) this.document; if(doc != null) { doc.invalidated(this); } } public void informStructureInvalid() { // This is called when an attribute or child changes. this.forgetRenderState(); HTMLDocumentImpl doc = (HTMLDocumentImpl) this.document; if(doc != null) { doc.structureInvalidated(this); } } protected void informNodeLoaded() { // This is called when an attribute or child changes. this.forgetRenderState(); HTMLDocumentImpl doc = (HTMLDocumentImpl) this.document; if(doc != null) { doc.nodeLoaded(this); } } protected void informExternalScriptLoading() { // This is called when an attribute or child changes. this.forgetRenderState(); HTMLDocumentImpl doc = (HTMLDocumentImpl) this.document; if(doc != null) { doc.externalScriptLoading(this); } } public void informLayoutInvalid() { // This is called by the style properties object. this.forgetRenderState(); HTMLDocumentImpl doc = (HTMLDocumentImpl) this.document; if(doc != null) { doc.invalidated(this); } } public void informDocumentInvalid() { // This is called when an attribute or child changes. HTMLDocumentImpl doc = (HTMLDocumentImpl) this.document; if(doc != null) { doc.allInvalidated(true); } } private RenderState renderState = INVALID_RENDER_STATE; public RenderState getRenderState() { // Generally called from the GUI thread, except for // offset properties. RenderState rs; synchronized(this.treeLock) { rs = this.renderState; if(rs != INVALID_RENDER_STATE) { return rs; } Object parent = this.parentNode; if(parent != null || this instanceof Document) { RenderState prs = this.getParentRenderState(parent); rs = this.createRenderState(prs); this.renderState = rs; return rs; } else { // Return null without caching. // Scenario is possible due to Javascript. return null; } } } protected final RenderState getParentRenderState(Object parent) { if(parent instanceof NodeImpl) { return ((NodeImpl) parent).getRenderState(); } else { return null; } } protected RenderState createRenderState(RenderState prevRenderState) { return prevRenderState; } protected void forgetRenderState() { synchronized(this.treeLock) { if(this.renderState != INVALID_RENDER_STATE) { this.renderState = INVALID_RENDER_STATE; // Note that getRenderState() "validates" // ancestor states as well. java.util.ArrayList nl = this.nodeList; if(nl != null) { Iterator i = nl.iterator(); while(i.hasNext()) { ((NodeImpl) i.next()).forgetRenderState(); } } } } } public String getInnerHTML() { StringBuffer buffer = new StringBuffer(); synchronized(this) { this.appendInnerHTMLImpl(buffer); } return buffer.toString(); } protected void appendInnerHTMLImpl(StringBuffer buffer) { ArrayList nl = this.nodeList; int size; if (nl != null && (size = nl.size()) > 0) { for (int i = 0; i < size; i++) { Node child = (Node) nl.get(i); if (child instanceof HTMLElementImpl) { ((HTMLElementImpl) child).appendOuterHTMLImpl(buffer); } else if(child instanceof Comment) { buffer.append(""); } else if (child instanceof Text) { String text = ((Text) child).getTextContent(); String encText = this.htmlEncodeChildText(text); buffer.append(encText); } else if (child instanceof ProcessingInstruction) { buffer.append(child.toString()); } } } } protected String htmlEncodeChildText(String text) { return Strings.strictHtmlEncode(text, false); } /** * Attempts to convert the subtree starting at this point to a close text * representation. BR elements are converted to line breaks, and so forth. */ public String getInnerText() { StringBuffer buffer = new StringBuffer(); synchronized(this.treeLock) { this.appendInnerTextImpl(buffer); } return buffer.toString(); } protected void appendInnerTextImpl(StringBuffer buffer) { ArrayList nl = this.nodeList; if (nl == null) { return; } int size = nl.size(); if (size == 0) { return; } for (int i = 0; i < size; i++) { Node child = (Node) nl.get(i); if (child instanceof ElementImpl) { ((ElementImpl) child).appendInnerTextImpl(buffer); } if(child instanceof Comment) { // skip } else if (child instanceof Text) { buffer.append(((Text) child).getTextContent()); } } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/NodeListImpl.java0000644000175000017500000000304310726473506026747 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Sep 3, 2005 */ package org.lobobrowser.html.domimpl; import org.lobobrowser.js.*; import org.w3c.dom.*; import java.util.*; public class NodeListImpl extends AbstractScriptableDelegate implements NodeList { //Note: class must be public for reflection to work. private final ArrayList nodeList = new ArrayList(); public NodeListImpl(Collection collection) { super(); nodeList.addAll(collection); } public int getLength() { return this.nodeList.size(); } public Node item(int index) { try { return (Node) this.nodeList.get(index); } catch(IndexOutOfBoundsException iob) { return null; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/NodeVisitor.java0000644000175000017500000000227210726473510026647 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 9, 2005 */ package org.lobobrowser.html.domimpl; public interface NodeVisitor { /** * Visits a node. The call should be * expected to occur in a synchronized * block. The lock will be node-dependent. * @param node */ public void visit(org.w3c.dom.Node node); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/SkipVisitorException.java0000644000175000017500000000246110726473510030547 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Dec 3, 2005 */ package org.lobobrowser.html.domimpl; class SkipVisitorException extends RuntimeException { public SkipVisitorException() { super(); } public SkipVisitorException(String message) { super(message); } public SkipVisitorException(String message, Throwable cause) { super(message, cause); } public SkipVisitorException(Throwable cause) { super(cause); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/StopVisitorException.java0000644000175000017500000000303710726473510030566 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Dec 3, 2005 */ package org.lobobrowser.html.domimpl; class StopVisitorException extends RuntimeException { private final Object tag; public StopVisitorException() { super(); this.tag = null; } public StopVisitorException(String message) { super(message); this.tag = null; } public StopVisitorException(String message, Throwable cause) { super(message, cause); this.tag = null; } public StopVisitorException(Throwable cause) { super(cause); this.tag = null; } public StopVisitorException(Object tag) { this.tag = tag; } public final Object getTag() { return this.tag; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/TextFilter.java0000644000175000017500000000224110726473476026503 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Nov 13, 2005 */ package org.lobobrowser.html.domimpl; import org.w3c.dom.Node; public class TextFilter implements NodeFilter { public TextFilter() { super(); } public boolean accept(Node node) { return node instanceof org.w3c.dom.Text; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/TextImpl.java0000644000175000017500000000776110726473502026161 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Sep 4, 2005 */ package org.lobobrowser.html.domimpl; import org.w3c.dom.*; import org.lobobrowser.util.*; public class TextImpl extends CharacterDataImpl implements Text { public TextImpl() { this(""); } public TextImpl(String text) { this.text = text; } /* (non-Javadoc) * @see org.w3c.dom.html2.Text#isElementContentWhitespace() */ public boolean isElementContentWhitespace() { String t = this.text; return t == null || t.trim().equals(""); } /* (non-Javadoc) * @see org.w3c.dom.html2.Text#replaceWholeText(java.lang.String) */ public Text replaceWholeText(String content) throws DOMException { NodeImpl parent = (NodeImpl) this.getParentNode(); if(parent == null) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Text node has no parent"); } return parent.replaceAdjacentTextNodes(this, content); } /* (non-Javadoc) * @see org.w3c.dom.html2.Text#splitText(int) */ public Text splitText(int offset) throws DOMException { NodeImpl parent = (NodeImpl) this.getParentNode(); if(parent == null) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Text node has no parent"); } String t = this.text; if(offset < 0 || offset > t.length()) { throw new DOMException(DOMException.INDEX_SIZE_ERR, "Bad offset: " + offset); } String content1 = t.substring(0, offset); String content2 = t.substring(offset); this.text = content1; TextImpl newNode = new TextImpl(content2); newNode.setOwnerDocument(this.document); return (Text) parent.insertAfter(newNode, this); } /* (non-Javadoc) * @see org.w3c.dom.html2.Text#getwholeText() */ public String getWholeText() { NodeImpl parent = (NodeImpl) this.getParentNode(); if(parent == null) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Text node has no parent"); } return parent.getTextContent(); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.NodeImpl#getlocalName() */ public String getLocalName() { return null; } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.NodeImpl#getnodeName() */ public String getNodeName() { return "#text"; } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.NodeImpl#getnodeType() */ public short getNodeType() { return Node.TEXT_NODE; } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.NodeImpl#getnodeValue() */ public String getNodeValue() throws DOMException { return this.text; } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.NodeImpl#setnodeValue(java.lang.String) */ public void setNodeValue(String nodeValue) throws DOMException { this.text = nodeValue; } public void setTextContent(String textContent) throws DOMException { this.text = textContent; } protected Node createSimilarNode() { return new TextImpl(this.text); } public String toString() { String text = this.text; int textLength = text == null ? 0 : text.length(); return "#text[length=" + textLength + ",value=\"" + Strings.truncate(text, 64) + "\",renderState=" + this.getRenderState() + "]"; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/UINode.java0000644000175000017500000000262511050517260025517 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 14, 2006 */ package org.lobobrowser.html.domimpl; import java.awt.Rectangle; /** * A UI node abstraction that is used to send notifications * back to the UI and to obtain information the DOM needs * from the UI (such as image dimensions). */ public interface UINode { /** * Called * @param modelNode */ public void repaint(ModelNode modelNode); public Rectangle getBounds(); public Rectangle getBoundsRelativeToBlock(); public void focus(); public void blur(); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/domimpl/package.html0000644000175000017500000000012110741125662026006 0ustar twernertwernerContains an implementation of the W3C HTML DOM Level 2 interfaces. libcobra-java-0.98.4.orig/src/org/lobobrowser/html/gui/0000755000175000017500000000000011133557554022663 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/lobobrowser/html/gui/DocumentNotification.java0000644000175000017500000000103710641432450027642 0ustar twernertwernerpackage org.lobobrowser.html.gui; import org.lobobrowser.html.domimpl.*; class DocumentNotification { public static final int LOOK = 0; public static final int POSITION = 1; public static final int SIZE = 2; public static final int GENERIC = 3; public final int type; public final NodeImpl node; public DocumentNotification(int type, NodeImpl node) { this.type = type; this.node = node; } public String toString() { return "DocumentNotification[type=" + this.type + ",node=" + this.node + "]"; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/gui/FrameSetPanel.java0000644000175000017500000002223510726473476026227 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 29, 2006 */ package org.lobobrowser.html.gui; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.StringTokenizer; import javax.swing.*; import java.util.logging.*; import org.lobobrowser.html.*; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.html.renderer.NodeRenderer; import org.lobobrowser.html.style.HtmlLength; import org.lobobrowser.util.gui.WrapperLayout; /** * A Swing panel used to render FRAMESETs only. It is * used by {@link HtmlPanel} when a document is determined * to be a FRAMESET. * @see HtmlPanel * @see HtmlBlockPanel */ public class FrameSetPanel extends JComponent implements NodeRenderer { private static final Logger logger = Logger.getLogger(FrameSetPanel.class.getName()); public FrameSetPanel() { super(); this.setLayout(WrapperLayout.getInstance()); //TODO: This should be a temporary preferred size this.setPreferredSize(new Dimension(600, 400)); } private HtmlLength[] getLengths(String spec) { if(spec == null) { return new HtmlLength[] { new HtmlLength("1*") }; } StringTokenizer tok = new StringTokenizer(spec, ","); ArrayList lengths = new ArrayList(); while(tok.hasMoreTokens()) { String token = tok.nextToken().trim(); try { lengths.add(new HtmlLength(token)); } catch(Exception err) { logger.warning("Frame rows or cols value [" + spec + "] is invalid."); } } return (HtmlLength[]) lengths.toArray(HtmlLength.EMPTY_ARRAY); } private HTMLElementImpl[] getSubFrames(HTMLElementImpl parent) { NodeImpl[] children = parent.getChildrenArray(); ArrayList subFrames = new ArrayList(); for(int i = 0; i < children.length; i++) { NodeImpl child = children[i]; if(child instanceof HTMLElementImpl) { String nodeName = child.getNodeName(); if("FRAME".equalsIgnoreCase(nodeName) || "FRAMESET".equalsIgnoreCase(nodeName)) { subFrames.add(child); } } } return (HTMLElementImpl[]) subFrames.toArray(new HTMLElementImpl[0]); } private HTMLElementImpl rootNode; /** * Sets the FRAMESET node and invalidates the component * so it can be rendered immediately in the GUI thread. */ public void setRootNode(NodeImpl node) { // Method expected to be called in the GUI thread. if(!(node instanceof HTMLElementImpl)) { throw new IllegalArgumentException("node=" + node); } HTMLElementImpl element = (HTMLElementImpl) node; this.rootNode = element; HtmlRendererContext context = element.getHtmlRendererContext(); this.htmlContext = context; this.domInvalid = true; this.invalidate(); this.validateAll(); this.repaint(); } protected void validateAll() { Component toValidate = this; for(;;) { Container parent = toValidate.getParent(); if(parent == null || parent.isValid()) { break; } toValidate = parent; } toValidate.validate(); } public final void processDocumentNotifications(DocumentNotification[] notifications) { // Called in the GUI thread. if(notifications.length > 0) { // Not very efficient, but it will do. this.domInvalid = true; this.invalidate(); if(this.isVisible()) { this.validate(); this.repaint(); } } } private HtmlRendererContext htmlContext; private Component[] frameComponents; private boolean domInvalid = true; public void setBounds(int x, int y, int w, int h) { super.setBounds(x, y, w, h); } /** * This method is invoked by AWT in the GUI thread * to lay out the component. This implementation * is an override. */ public void doLayout() { if(this.domInvalid) { this.domInvalid = false; this.removeAll(); HtmlRendererContext context = this.htmlContext; if(context != null) { HTMLElementImpl element = (HTMLElementImpl) this.rootNode; String rows = element.getAttribute("rows"); String cols = element.getAttribute("cols"); HtmlLength[] rowLengths = this.getLengths(rows); HtmlLength[] colLengths = this.getLengths(cols); HTMLElementImpl[] subframes = this.getSubFrames(element); Component[] frameComponents = new Component[subframes.length]; this.frameComponents = frameComponents; for(int i = 0; i < subframes.length; i++) { HTMLElementImpl frameElement = subframes[i]; if(frameElement != null && "FRAMESET".equalsIgnoreCase(frameElement.getTagName())) { FrameSetPanel fsp = new FrameSetPanel(); fsp.setRootNode(frameElement); frameComponents[i] = fsp; } else { if(frameElement instanceof FrameNode) { BrowserFrame frame = context.createBrowserFrame(); ((FrameNode) frameElement).setBrowserFrame(frame); String src = frameElement.getAttribute("src"); if(src != null) { java.net.URL url; try { url = frameElement.getFullURL(src); if(url != null) { frame.loadURL(url); } } catch(MalformedURLException mfu) { logger.warning("Frame URI=[" + src + "] is malformed."); } } frameComponents[i] = frame.getComponent(); } else { frameComponents[i] = new JPanel(); } } } HtmlLength[] rhl = rowLengths; HtmlLength[] chl = colLengths; Component[] fc = this.frameComponents; if(rhl != null && chl != null && fc != null) { Dimension size = this.getSize(); Insets insets = this.getInsets(); int width = size.width - insets.left - insets.right; int height = size.height - insets.left - insets.right; int[] absColLengths = this.getAbsoluteLengths(chl, width); int[] absRowLengths = this.getAbsoluteLengths(rhl, height); this.add(this.getSplitPane(this.htmlContext, absColLengths, 0, absColLengths.length, absRowLengths, 0, absRowLengths.length, fc)); } } } super.doLayout(); } private int[] getAbsoluteLengths(HtmlLength[] htmlLengths, int totalSize) { int[] absLengths = new int[htmlLengths.length]; int totalSizeNonMulti = 0; int sumMulti = 0; for(int i = 0; i < htmlLengths.length; i++) { HtmlLength htmlLength = htmlLengths[i]; int lengthType = htmlLength.getLengthType(); if(lengthType == HtmlLength.PIXELS) { int absLength = htmlLength.getRawValue(); totalSizeNonMulti += absLength; absLengths[i] = absLength; } else if(lengthType == HtmlLength.LENGTH) { int absLength = htmlLength.getLength(totalSize); totalSizeNonMulti += absLength; absLengths[i] = absLength; } else { sumMulti += htmlLength.getRawValue(); } } int remaining = totalSize - totalSizeNonMulti; if(remaining > 0 && sumMulti > 0) { for(int i = 0; i < htmlLengths.length; i++) { HtmlLength htmlLength = htmlLengths[i]; if(htmlLength.getLengthType() == HtmlLength.MULTI_LENGTH) { int absLength = (remaining * htmlLength.getRawValue()) / sumMulti; absLengths[i] = absLength; } } } return absLengths; } private Component getSplitPane(HtmlRendererContext context, int[] colLengths, int firstCol, int numCols, int[] rowLengths, int firstRow, int numRows, Component[] frameComponents) { if(numCols == 1) { int frameindex = colLengths.length * firstRow + firstCol; Component topComponent = frameindex < frameComponents.length ? frameComponents[frameindex] : null; if(numRows == 1) { return topComponent; } else { Component bottomComponent = this.getSplitPane(context, colLengths, firstCol, numCols, rowLengths, firstRow + 1, numRows - 1, frameComponents); JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topComponent, bottomComponent); sp.setDividerLocation(rowLengths[firstRow]); return sp; } } else { Component rightComponent = this.getSplitPane(context, colLengths, firstCol + 1, numCols - 1, rowLengths, firstRow, numRows, frameComponents); Component leftComponent = this.getSplitPane(context, colLengths, firstCol, 1, rowLengths, firstRow, numRows, frameComponents); JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftComponent, rightComponent); sp.setDividerLocation(colLengths[firstCol]); return sp; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/gui/HtmlBlockPanel.java0000644000175000017500000006660211133557552026375 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 16, 2005 */ package org.lobobrowser.html.gui; import java.awt.*; import java.awt.event.*; import java.awt.datatransfer.*; import javax.swing.*; import org.lobobrowser.html.*; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.html.renderer.*; import org.lobobrowser.html.style.RenderState; import org.lobobrowser.util.*; import org.lobobrowser.util.gui.ColorFactory; import org.w3c.dom.*; import java.util.logging.*; import java.util.*; /** * A Swing component that renders a HTML block, given * by a DOM root or an internal element, typically a DIV. * This component cannot render FRAMESETs. HtmlBlockPanel * is used by {@link HtmlPanel} whenever the DOM * is determined not to be a FRAMESET. * @see HtmlPanel * @see FrameSetPanel * @author J. H. S. */ public class HtmlBlockPanel extends JComponent implements NodeRenderer, RenderableContainer, ClipboardOwner { private static final Logger logger = Logger.getLogger(HtmlBlockPanel.class.getName()); private static final boolean loggableInfo = logger.isLoggable(Level.INFO); protected final FrameContext frameContext; protected final UserAgentContext ucontext; protected final HtmlRendererContext rcontext; protected RenderableSpot startSelection; protected RenderableSpot endSelection; protected RBlock rblock; protected int preferredWidth = -1; protected Insets defaultMarginInsets = null; //protected Insets defaultPaddingInsets = null; protected int defaultOverflowX = RenderState.OVERFLOW_AUTO; protected int defaultOverflowY = RenderState.OVERFLOW_SCROLL; public HtmlBlockPanel(UserAgentContext pcontext, HtmlRendererContext rcontext, FrameContext frameContext) { this(ColorFactory.TRANSPARENT, false, pcontext, rcontext, frameContext); } public HtmlBlockPanel(Color background, boolean opaque, UserAgentContext pcontext, HtmlRendererContext rcontext, FrameContext frameContext) { this.setLayout(null); this.setAutoscrolls(true); this.frameContext = frameContext; this.ucontext = pcontext; this.rcontext = rcontext; this.setOpaque(opaque); this.setBackground(background); ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if("copy".equals(command)) { copy(); } } }; if(!GraphicsEnvironment.isHeadless()) { this.registerKeyboardAction(actionListener, "copy", KeyStroke.getKeyStroke(KeyEvent.VK_COPY, 0), JComponent.WHEN_FOCUSED); this.registerKeyboardAction(actionListener, "copy", KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), JComponent.WHEN_FOCUSED); } this.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { onMouseClick(e); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { onMouseExited(e); } public void mousePressed(MouseEvent e) { onMousePressed(e); } public void mouseReleased(MouseEvent e) { onMouseReleased(e); } }); this.addMouseMotionListener(new MouseMotionListener() { /* (non-Javadoc) * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent) */ public void mouseDragged(MouseEvent e) { onMouseDragged(e); } /* (non-Javadoc) * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent) */ public void mouseMoved(MouseEvent arg0) { onMouseMoved(arg0); } }); this.addMouseWheelListener(new MouseWheelListener() { public void mouseWheelMoved(MouseWheelEvent e) { onMouseWheelMoved(e); } }); } /** * Scrolls the body area to the given location. *

* This method should be called from the GUI thread. * @param bounds The bounds in the scrollable block area that should * become visible. * @param xIfNeeded If this parameter is true, scrolling will only occur if the * requested bounds are not currently visible horizontally. * @param yIfNeeded If this parameter is true, scrolling will only occur if the * requested bounds are not currently visible vertically. */ public void scrollTo(Rectangle bounds, boolean xIfNeeded, boolean yIfNeeded) { RBlock block = this.rblock; if(block != null) { block.scrollTo(bounds, xIfNeeded, yIfNeeded); } } public void scrollBy(int xOffset, int yOffset) { RBlock block = this.rblock; if(block != null) { if(xOffset != 0) { block.scrollBy(JScrollBar.HORIZONTAL, xOffset); } if(yOffset != 0) { block.scrollBy(JScrollBar.VERTICAL, yOffset); } } } /** * Scrolls the body area to the node given, if it is * part of the current document. *

* This method should be called from the GUI thread. * @param node A DOM node. */ public void scrollTo(Node node) { Rectangle bounds = this.getNodeBounds(node, true); if(bounds == null) { return; } this.scrollTo(bounds, true, false); } /** * Gets the rectangular bounds of the given node. *

* This method should be called from the GUI thread. * @param node A node in the current document. * @param relativeToScrollable Whether the bounds should be relative to the * scrollable body area. Otherwise, they are * relative to the root block (which is the * essentially the same as being relative to this * HtmlBlockPanel minus Swing * borders). */ public Rectangle getNodeBounds(Node node, boolean relativeToScrollable) { RBlock block = this.rblock; if(block == null) { return null; } // Find UINode first Node currentNode = node; UINode uiNode = null; while(currentNode != null) { if(currentNode instanceof HTMLElementImpl) { HTMLElementImpl element = (HTMLElementImpl) currentNode; uiNode = element.getUINode(); if(uiNode != null) { break; } } currentNode = currentNode.getParentNode(); } if(uiNode == null) { return null; } RCollection relativeTo = relativeToScrollable ? (RCollection) block.getRBlockViewport() : (RCollection) block; if(node == currentNode) { BoundableRenderable br = (BoundableRenderable) uiNode; Point guiPoint = br.getOriginRelativeTo(relativeTo); Dimension size = br.getSize(); return new Rectangle(guiPoint, size); } else { return this.scanNodeBounds((RCollection) uiNode, node, relativeTo); } } /** * Gets an aggregate of the bounds of renderer leaf nodes. */ private Rectangle scanNodeBounds(RCollection root, Node node, RCollection relativeTo) { Iterator i = root.getRenderables(); Rectangle resultBounds = null; BoundableRenderable prevBoundable = null; if(i != null) { while(i.hasNext()) { Renderable r = (Renderable) i.next(); Rectangle subBounds = null; if(r instanceof RCollection) { RCollection rc = (RCollection) r; prevBoundable = rc; subBounds = this.scanNodeBounds(rc, node, relativeTo); } else if(r instanceof BoundableRenderable) { BoundableRenderable br = (BoundableRenderable) r; prevBoundable = br; if(Nodes.isSameOrAncestorOf(node, (Node) r.getModelNode())) { Point origin = br.getOriginRelativeTo(relativeTo); Dimension size = br.getSize(); subBounds = new Rectangle(origin, size); } } else { // This would have to be a RStyleChanger. We rely on these // when the target node has blank content. if(Nodes.isSameOrAncestorOf(node, (Node) r.getModelNode())) { int xInRoot = prevBoundable == null ? 0 : prevBoundable.getX() + prevBoundable.getWidth(); Point rootOrigin = root.getOriginRelativeTo(relativeTo); subBounds = new Rectangle(rootOrigin.x + xInRoot, rootOrigin.y, 0, root.getHeight()); } } if(subBounds != null) { if(resultBounds == null) { resultBounds = subBounds; } else { resultBounds = subBounds.union(resultBounds); } } } } return resultBounds; } public BoundableRenderable getRootRenderable() { return this.rblock; } /** * Allows {@link #getPreferredSize()} to render the HTML block * in order to determine the preferred size of this component. * Note that getPreferredSize() is a potentially time-consuming * operation if the preferred width is set. * @param width The preferred blocked width. Use -1 to unset. */ public void setPreferredWidth(int width) { this.preferredWidth = width; } /** * If the preferred size has been set with {@link #setPreferredSize(Dimension)}, * then that size is returned. Otherwise a preferred size is calculated by * rendering the HTML DOM, provided one is available and a preferred width other * than -1 has been set with {@link #setPreferredWidth(int)}. * An arbitrary preferred size is returned in other scenarios. */ public Dimension getPreferredSize() { // Expected to be invoked in the GUI thread. if(this.isPreferredSizeSet()) { return super.getPreferredSize(); } final int pw = this.preferredWidth; if(pw != -1) { final RBlock block = this.rblock; if(block != null) { // Layout should always be done in the GUI thread. if(EventQueue.isDispatchThread()) { block.layout(pw, 0, false, false, RenderState.OVERFLOW_VISIBLE, RenderState.OVERFLOW_VISIBLE, true); } else { try { EventQueue.invokeAndWait(new Runnable() { public void run() { block.layout(pw, 0, false, false, RenderState.OVERFLOW_VISIBLE, RenderState.OVERFLOW_VISIBLE, true); } }); } catch(Exception err) { logger.log(Level.SEVERE, "Unable to do preferred size layout.", err); } } // Adjust for permanent vertical scrollbar. int newPw = Math.max(block.width + block.getVScrollBarWidth(), pw); return new Dimension(newPw, block.height); } } return new Dimension(600, 400); } public void finalize() throws Throwable { super.finalize(); } public boolean copy() { String selection = HtmlBlockPanel.this.getSelectionText(); if(selection != null) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(new StringSelection(selection), HtmlBlockPanel.this); return true; } else { return false; } } // public void setDefaultPaddingInsets(Insets insets) { // this.defaultPaddingInsets = insets; // RBlock block = this.rblock; // if(block != null) { // block.setDefaultPaddingInsets(insets); // } // } public int getFirstLineHeight() { RBlock block = this.rblock; return block == null ? 0 : block.getFirstLineHeight(); } public void setSelectionEnd(RenderableSpot rpoint) { this.endSelection = rpoint; } public void setSelectionStart(RenderableSpot rpoint) { this.startSelection = rpoint; } public boolean isSelectionAvailable() { RenderableSpot start = this.startSelection; RenderableSpot end = this.endSelection; return start != null && end != null && !start.equals(end); } public org.w3c.dom.Node getSelectionNode() { RenderableSpot start = this.startSelection; RenderableSpot end = this.endSelection; if(start != null && end != null) { return Nodes.getCommonAncestor((Node) start.renderable.getModelNode(), (Node) end.renderable.getModelNode()); } else { return null; } } /** * Sets the root node to render. This method should * be invoked in the GUI dispatch thread. */ public void setRootNode(NodeImpl node) { if(node != null) { RBlock block = new RBlock(node, 0, this.ucontext, this.rcontext, this.frameContext, this); block.setDefaultMarginInsets(this.defaultMarginInsets); //block.setDefaultPaddingInsets(this.defaultPaddingInsets); block.setDefaultOverflowX(this.defaultOverflowX); block.setDefaultOverflowY(this.defaultOverflowY); node.setUINode(block); this.rblock = block; } else { this.rblock = null; } this.invalidate(); this.validateAll(); this.repaint(); } protected void validateAll() { Component toValidate = this; for(;;) { Container parent = toValidate.getParent(); if(parent == null || parent.isValid()) { break; } toValidate = parent; } toValidate.validate(); } protected void revalidatePanel() { // Called in the GUI thread. this.invalidate(); this.validate(); //TODO: Could be paintImmediately. this.repaint(); } public NodeImpl getRootNode() { RBlock block = this.rblock; return block == null ? null : (NodeImpl) block.getModelNode(); } private void onMouseClick(MouseEvent event) { // Rely on AWT mouse-click only for double-clicks RBlock block = this.rblock; if(block != null) { int button = event.getButton(); int clickCount = event.getClickCount(); if(button == MouseEvent.BUTTON1 && clickCount > 1) { //TODO: Double-click must be revised. It generates //a single click via mouse release. Point point = event.getPoint(); block.onDoubleClick(event, point.x, point.y); } else if(button == MouseEvent.BUTTON3 && clickCount == 1) { block.onRightClick(event, event.getX(), event.getY()); } } } private BoundableRenderable mousePressTarget; private void onMousePressed(MouseEvent event) { this.requestFocus(); RBlock block = this.rblock; if(block != null) { Point point = event.getPoint(); this.mousePressTarget = block; int rx = point.x; int ry = point.y; block.onMousePressed(event, point.x, point.y); RenderableSpot rp = block.getLowestRenderableSpot(rx, ry); if(rp != null) { this.frameContext.resetSelection(rp); } else { this.frameContext.resetSelection(null); } } } private void onMouseReleased(MouseEvent event) { RBlock block = this.rblock; if(block != null) { Point point = event.getPoint(); int rx = point.x; int ry = point.y; if(event.getButton() == MouseEvent.BUTTON1) { // TODO: This will be raised twice on a double-click. block.onMouseClick(event, rx, ry); } block.onMouseReleased(event, rx, ry); BoundableRenderable oldTarget = this.mousePressTarget; if(oldTarget != null) { this.mousePressTarget = null; if(oldTarget != block) { oldTarget.onMouseDisarmed(event); } } } else { this.mousePressTarget = null; } } private void onMouseExited(MouseEvent event) { BoundableRenderable oldTarget = this.mousePressTarget; if(oldTarget != null) { this.mousePressTarget = null; oldTarget.onMouseDisarmed(event); } } private void onMouseWheelMoved(MouseWheelEvent mwe) { RBlock block = this.rblock; if(block != null) { switch(mwe.getScrollType()) { case MouseWheelEvent.WHEEL_UNIT_SCROLL: int units = mwe.getWheelRotation() * mwe.getScrollAmount(); block.scrollByUnits(JScrollBar.VERTICAL, units); break; } } } private void onMouseDragged(MouseEvent event) { RBlock block = this.rblock; if(block != null) { Point point = event.getPoint(); RenderableSpot rp = block.getLowestRenderableSpot(point.x, point.y); if(rp != null) { this.frameContext.expandSelection(rp); } block.ensureVisible(point); } } private void onMouseMoved(MouseEvent event) { RBlock block = this.rblock; if(block != null) { Point point = event.getPoint(); block.onMouseMoved(event, point.x, point.y, false, null); } } /* (non-Javadoc) * @see javax.swing.JComponent#paintComponent(java.awt.Graphics) */ //protected void paintComponent(Graphics g) { public void paint(Graphics g) { // We go against Sun's advice and override // paint() instead of paintComponent(). Scrollbars // do not repaint correctly if we use // paintComponent. if(this.isOpaque()) { // Background not painted by default in JComponent. Rectangle clipBounds = g.getClipBounds(); g.setColor(this.getBackground()); g.fillRect(clipBounds.x, clipBounds.y, clipBounds.width, clipBounds.height); } if(g instanceof Graphics2D) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } RBlock block = this.rblock; if(block != null) { boolean liflag = loggableInfo; long time1 = liflag ? System.currentTimeMillis() : 0; block.paint(g); if(liflag) { long time2 = System.currentTimeMillis(); Node rootNode = this.getRootNode(); String uri = rootNode instanceof Document ? ((Document) rootNode).getDocumentURI() : ""; logger.info("paintComponent(): URI=[" + uri + "]. Block paint elapsed: " + (time2 - time1) + " ms."); } // Paint FrameContext selection RenderableSpot start = this.startSelection; RenderableSpot end = this.endSelection; if(start != null && end != null && !start.equals(end)) { block.paintSelection(g, false, start, end); } } } public void doLayout() { try { Dimension size = this.getSize(); boolean liflag = loggableInfo; long time1 = 0; if(liflag) { time1 = System.currentTimeMillis(); } this.clearComponents(); RBlock block = this.rblock; if(block != null) { ModelNode rootNode = block.getModelNode(); block.layout(size.width, size.height, true, true, null, false); //Only set origin block.setOrigin(0, 0); block.updateWidgetBounds(0, 0); this.updateGUIComponents(); if(liflag) { long time2 = System.currentTimeMillis(); String uri = rootNode instanceof Document ? ((Document) rootNode).getDocumentURI() : ""; logger.info("doLayout(): URI=[" + uri + "]. Block layout elapsed: " + (time2 - time1) + " ms. Component count: " + this.getComponentCount() + "."); } } else { if(this.getComponentCount() > 0) { this.removeAll(); } } } catch(Throwable thrown) { logger.log(Level.SEVERE, "Unexpected error in layout engine. Document is " + this.getRootNode(), thrown); } } /** * Implementation of UINode.repaint(). */ public void repaint(ModelNode modelNode) { //this.rblock.invalidateRenderStyle(); this.repaint(); } public String getSelectionText() { RenderableSpot start = this.startSelection; RenderableSpot end = this.endSelection; if(start != null && end != null) { StringBuffer buffer = new StringBuffer(); this.rblock.extractSelectionText(buffer, false, start, end); return buffer.toString(); } else { return null; } } public boolean hasSelection() { RenderableSpot start = this.startSelection; RenderableSpot end = this.endSelection; if(start != null && end != null && !start.equals(end)) { return true; } else { return false; } } protected void paintChildren(Graphics g) { // Overridding with NOP. For various reasons, // the regular mechanism for painting children // needs to be handled by Cobra. } public Color getPaintedBackgroundColor() { return this.isOpaque() ? this.getBackground() : null; } /* (non-Javadoc) * @see java.awt.datatransfer.ClipboardOwner#lostOwnership(java.awt.datatransfer.Clipboard, java.awt.datatransfer.Transferable) */ public void lostOwnership(Clipboard arg0, Transferable arg1) { } public void relayout() { // Expected to be called in the GUI thread. // Renderable branch should be invalidated at this // point, but this GUI component not necessarily. this.revalidatePanel(); } public void invalidateLayoutUpTree() { // Called when renderable branch is invalidated. // We shouldn't do anything here. Changes in renderer // tree do not have any bearing on validity of GUI // component. } public void updateAllWidgetBounds() { this.rblock.updateWidgetBounds(0, 0); } public Point getGUIPoint(int clientX, int clientY) { // This is the GUI! return new Point(clientX, clientY); } public void focus() { this.grabFocus(); } private boolean processingDocumentNotification = false; void processDocumentNotifications(DocumentNotification[] notifications) { // Called in the GUI thread. if(this.processingDocumentNotification) { // This should not be possible. Even if // Javascript modifies the DOM during // parsing, this should be executed in // the GUI thread, not the parser thread. throw new IllegalStateException("Recursive"); } this.processingDocumentNotification = true; try { //Note: It may be assumed that usually only generic //notifications come in batches. Other types //of noitifications probably come one by one. boolean topLayout = false; java.util.ArrayList repainters = null; int length = notifications.length; for(int i = 0; i < length; i++) { DocumentNotification dn = notifications[i]; int type = dn.type; switch(type) { case DocumentNotification.GENERIC: case DocumentNotification.SIZE: { NodeImpl node = dn.node; if(node == null) { // This is all-invalidate (new style sheet) if(loggableInfo) { logger.info("processDocumentNotifications(): Calling invalidateLayoutDeep()."); } this.rblock.invalidateLayoutDeep(); //this.rblock.invalidateRenderStyle(); } else { UINode uiNode = node.findUINode(); if(uiNode != null) { RElement relement = (RElement) uiNode; relement.invalidateLayoutUpTree(); // if(type == DocumentNotification.GENERIC) { // relement.invalidateRenderStyle(); // } } else { if(loggableInfo) { logger.info("processDocumentNotifications(): Unable to find UINode for " + node); } } } topLayout = true; break; } case DocumentNotification.POSITION: { //TODO: Could be more efficient. NodeImpl node = dn.node; NodeImpl parent = (NodeImpl) node.getParentNode(); if(parent != null) { UINode uiNode = parent.findUINode(); if(uiNode != null) { RElement relement = (RElement) uiNode; relement.invalidateLayoutUpTree(); } } topLayout = true; break; } case DocumentNotification.LOOK: { NodeImpl node = dn.node; UINode uiNode = node.findUINode(); if(uiNode != null) { if(repainters == null) { repainters = new ArrayList(1); } RElement relement = (RElement) uiNode; //relement.invalidateRenderStyle(); repainters.add(relement); } break; } default: break; } } if(topLayout) { this.revalidatePanel(); } else { if(repainters != null) { Iterator i = repainters.iterator(); while(i.hasNext()) { RElement element = (RElement) i.next(); element.repaint(); } } } } finally { this.processingDocumentNotification = false; } } public void addDelayedPair(DelayedPair pair) { // NOP } public RenderableContainer getParentContainer() { return null; } public Collection getDelayedPairs() { return null; } public void clearDelayedPairs() { } private Set components; private void clearComponents() { Set c = this.components; if(c != null) { c.clear(); } } public Component addComponent(Component component) { Set c = this.components; if(c == null) { c = new HashSet(); this.components = c; } if(c.add(component)) { return component; } else { return null; } } private void updateGUIComponents() { // We use this method, instead of removing all components and // adding them back, because removal of components can cause // them to lose focus. Set c = this.components; if(c == null) { if(this.getComponentCount() != 0) { this.removeAll(); } } else { // Remove children not in the set. Set workingSet = new HashSet(); workingSet.addAll(c); int count = this.getComponentCount(); for(int i = 0; i < count;) { Component component = this.getComponent(i); if(!c.contains(component)) { this.remove(i); count = this.getComponentCount(); } else { i++; workingSet.remove(component); } } // Add components in set that were not previously children. Iterator wsi = workingSet.iterator(); while(wsi.hasNext()) { Component component = (Component) wsi.next(); this.add(component); } } } public Insets getDefaultMarginInsets() { return defaultMarginInsets; } /** * Sets the default margin insets. Note that in the root block, * the margin behaves like padding. * @param defaultMarginInsets The default margin insets. */ public void setDefaultMarginInsets(Insets defaultMarginInsets) { if(!Objects.equals(this.defaultMarginInsets, defaultMarginInsets)) { this.defaultMarginInsets = defaultMarginInsets; RBlock block = this.rblock; if(block != null) { block.setDefaultMarginInsets(defaultMarginInsets); block.relayoutIfValid(); } } } // public Insets getDefaultPaddingInsets() { // return defaultPaddingInsets; // } // public int getDefaultOverflowX() { return defaultOverflowX; } public void setDefaultOverflowX(int defaultOverflowX) { if(defaultOverflowX != this.defaultOverflowX) { this.defaultOverflowX = defaultOverflowX; RBlock block = this.rblock; if(block != null) { block.setDefaultOverflowX(defaultOverflowX); block.relayoutIfValid(); } } } public int getDefaultOverflowY() { return defaultOverflowY; } public void setDefaultOverflowY(int defaultOverflowY) { if(this.defaultOverflowY != defaultOverflowY) { this.defaultOverflowY = defaultOverflowY; RBlock block = this.rblock; if(block != null) { block.setDefaultOverflowY(defaultOverflowY); block.relayoutIfValid(); } } } }libcobra-java-0.98.4.orig/src/org/lobobrowser/html/gui/HtmlPanel.java0000644000175000017500000006075711134671124025420 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Nov 19, 2005 */ package org.lobobrowser.html.gui; import java.awt.*; import java.awt.event.ActionEvent; import java.util.*; import java.io.*; import javax.swing.*; import org.lobobrowser.html.*; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.html.parser.*; import org.lobobrowser.html.renderer.*; import org.lobobrowser.html.style.RenderState; import org.lobobrowser.util.EventDispatch2; import org.lobobrowser.util.gui.WrapperLayout; import org.w3c.dom.Document; import org.w3c.dom.Text; import org.w3c.dom.html2.*; /** * The HtmlPanel class is a Swing * component that can render a HTML DOM. It uses * either {@link HtmlBlockPanel} or {@link FrameSetPanel} * internally, depending on whether the document * is determined to be a FRAMESET or not. *

* Invoke method {@link #setDocument(Document, HtmlRendererContext)} * in order to schedule a document for rendering. */ public class HtmlPanel extends JComponent implements FrameContext { private final EventDispatch2 selectionDispatch = new SelectionDispatch(); private final javax.swing.Timer notificationTimer; private final DocumentNotificationListener notificationListener; private final Runnable notificationImmediateAction; private static final int NOTIF_TIMER_DELAY = 300; private volatile boolean isFrameSet = false; private volatile NodeRenderer nodeRenderer = null; private volatile NodeImpl rootNode; private volatile int preferredWidth = -1; private volatile Insets defaultMarginInsets = new Insets(8, 8, 8, 8); private volatile int defaultOverflowX = RenderState.OVERFLOW_AUTO; private volatile int defaultOverflowY = RenderState.OVERFLOW_SCROLL; protected volatile HtmlBlockPanel htmlBlockPanel; protected volatile FrameSetPanel frameSetPanel; /** * Constructs an HtmlPanel. */ public HtmlPanel() { super(); this.setLayout(WrapperLayout.getInstance()); this.setOpaque(false); this.notificationTimer = new javax.swing.Timer(NOTIF_TIMER_DELAY, new NotificationTimerAction()); this.notificationTimer.setRepeats(false); this.notificationListener = new LocalDocumentNotificationListener(); this.notificationImmediateAction = new Runnable() { public void run() { processNotifications(); } }; } /** * Sets a preferred width that serves as a hint in calculating * the preferred size of the HtmlPanel. Note that * the preferred size can only be calculated when a document is * available, and it will vary during incremental rendering. *

* This method currently does not have any effect when the * document is a FRAMESET. *

* Note also that setting the preferred width (to a value other * than -1) will negatively impact performance. * * @param width The preferred width, or -1 to unset. */ public void setPreferredWidth(int width) { this.preferredWidth = width; HtmlBlockPanel htmlBlock = this.htmlBlockPanel; if(htmlBlock != null) { htmlBlock.setPreferredWidth(width); } } /** * If the current document is not a FRAMESET, * this method scrolls the body area to the given location. *

* This method should be called from the GUI thread. * @param bounds The bounds in the scrollable block area that should * become visible. * @param xIfNeeded If this parameter is true, scrolling will only occur if the * requested bounds are not currently visible horizontally. * @param yIfNeeded If this parameter is true, scrolling will only occur if the * requested bounds are not currently visible vertically. */ public void scrollTo(Rectangle bounds, boolean xIfNeeded, boolean yIfNeeded) { HtmlBlockPanel htmlBlock = this.htmlBlockPanel; if(htmlBlock != null) { htmlBlock.scrollTo(bounds, xIfNeeded, yIfNeeded); } } /** * Scrolls the body area to the node given, if it is * part of the current document. *

* This method should be called from the GUI thread. * @param node A DOM node. */ public void scrollTo(org.w3c.dom.Node node) { HtmlBlockPanel htmlBlock = this.htmlBlockPanel; if(htmlBlock != null) { htmlBlock.scrollTo(node); } } /** * Gets the root Renderable of * the HTML block. It returns null * for FRAMESETs. */ public BoundableRenderable getBlockRenderable() { HtmlBlockPanel htmlBlock = this.htmlBlockPanel; return htmlBlock == null ? null : htmlBlock.getRootRenderable(); } /** * Gets an instance of {@link FrameSetPanel} in case * the currently rendered page is a FRAMESET. *

* Note: This method should be invoked in the GUI thread. * @return A FrameSetPanel instance or null * if the document currently rendered is not a FRAMESET. */ public FrameSetPanel getFrameSetPanel() { int componentCount = this.getComponentCount(); if(componentCount == 0) { return null; } Object c = this.getComponent(0); if(c instanceof FrameSetPanel) { return (FrameSetPanel) c; } return null; } private void setUpAsBlock(UserAgentContext ucontext, HtmlRendererContext rcontext) { HtmlBlockPanel shp = this.createHtmlBlockPanel(ucontext, rcontext); shp.setPreferredWidth(this.preferredWidth); shp.setDefaultMarginInsets(this.defaultMarginInsets); shp.setDefaultOverflowX(this.defaultOverflowX); shp.setDefaultOverflowY(this.defaultOverflowY); this.htmlBlockPanel = shp; this.frameSetPanel = null; this.removeAll(); this.add(shp); this.nodeRenderer = shp; } private void setUpFrameSet(NodeImpl fsrn) { this.isFrameSet = true; this.htmlBlockPanel = null; FrameSetPanel fsp = this.createFrameSetPanel(); this.frameSetPanel = fsp; this.nodeRenderer = fsp; this.removeAll(); this.add(fsp); fsp.setRootNode(fsrn); } /** * Method invoked internally to create a {@link HtmlBlockPanel}. * It is made available so it can be overridden. */ protected HtmlBlockPanel createHtmlBlockPanel(UserAgentContext ucontext, HtmlRendererContext rcontext) { return new HtmlBlockPanel(java.awt.Color.WHITE, true, ucontext, rcontext, this); } /** * Method invoked internally to create a {@link FrameSetPanel}. * It is made available so it can be overridden. */ protected FrameSetPanel createFrameSetPanel() { return new FrameSetPanel(); } /** * Scrolls the document such that x and y coordinates * are placed in the upper-left corner of the panel. *

* This method may be called outside of the GUI Thread. * @param x The x coordinate. * @param y The y coordinate. */ public void scroll(final int x, final int y) { if(EventQueue.isDispatchThread()) { this.scrollImpl(x, y); } else { EventQueue.invokeLater(new Runnable() { public void run() { scrollImpl(x, y); } }); } } public void scrollBy(final int x, final int y) { if(EventQueue.isDispatchThread()) { this.scrollByImpl(x, y); } else { EventQueue.invokeLater(new Runnable() { public void run() { scrollByImpl(x, y); } }); } } private void scrollImpl(int x, int y) { this.scrollTo(new Rectangle(x, y, 16, 16), false, false); } private void scrollByImpl(int xOffset, int yOffset) { HtmlBlockPanel bp = this.htmlBlockPanel; if(bp != null) { bp.scrollBy(xOffset, yOffset); } } /** * Clears the current document if any. * If called outside the GUI thread, the operation * will be scheduled to be performed in the GUI * thread. */ public void clearDocument() { if(java.awt.EventQueue.isDispatchThread()) { this.clearDocumentImpl(); } else { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { HtmlPanel.this.clearDocumentImpl(); } }); } } private void clearDocumentImpl() { HTMLDocumentImpl prevDocument = (HTMLDocumentImpl) this.rootNode; if(prevDocument != null) { prevDocument.removeDocumentNotificationListener(this.notificationListener); } NodeRenderer nr = this.nodeRenderer; if(nr != null) { nr.setRootNode(null); } this.rootNode = null; this.htmlBlockPanel = null; this.nodeRenderer = null; this.isFrameSet = false; this.removeAll(); this.revalidate(); this.repaint(); } /** * Sets an HTML DOM node and invalidates the component so it is * rendered as soon as possible in the GUI thread. *

* If this method is called from a thread that is not the GUI * dispatch thread, the document is scheduled to be set later. * Note that {@link #setPreferredWidth(int) preferred size} * calculations should be done in the GUI dispatch thread for * this reason. * @param node This should * normally be a Document instance obtained with * {@link org.lobobrowser.html.parser.DocumentBuilderImpl}. *

* @param rcontext A renderer context. * @see org.lobobrowser.html.parser.DocumentBuilderImpl#parse(org.xml.sax.InputSource) * @see org.lobobrowser.html.test.SimpleHtmlRendererContext */ public void setDocument(final Document node, final HtmlRendererContext rcontext) { if(java.awt.EventQueue.isDispatchThread()) { this.setDocumentImpl(node, rcontext); } else { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { HtmlPanel.this.setDocumentImpl(node, rcontext); } }); } } /** * Scrolls to the element identified by the given ID in * the current document. *

* If this method is invoked outside the GUI thread, * the operation is scheduled to be performed as soon * as possible in the GUI thread. * @param nameOrId The name or ID of the element in the document. */ public void scrollToElement(final String nameOrId) { if(EventQueue.isDispatchThread()) { this.scrollToElementImpl(nameOrId); } else { EventQueue.invokeLater(new Runnable() { public void run() { scrollToElementImpl(nameOrId); } }); } } private void scrollToElementImpl(String nameOrId) { NodeImpl node = this.rootNode; if(node instanceof HTMLDocumentImpl) { HTMLDocumentImpl doc = (HTMLDocumentImpl) node; org.w3c.dom.Element element = doc.getElementById(nameOrId); if(element != null) { this.scrollTo(element); } } } private void setDocumentImpl(Document node, HtmlRendererContext rcontext) { // Expected to be called in the GUI thread. if(!(node instanceof HTMLDocumentImpl)) { throw new IllegalArgumentException("Only nodes of type HTMLDocumentImpl are currently supported. Use DocumentBuilderImpl."); } HTMLDocumentImpl prevDocument = (HTMLDocumentImpl) this.rootNode; if(prevDocument != null) { prevDocument.removeDocumentNotificationListener(this.notificationListener); } HTMLDocumentImpl nodeImpl = (HTMLDocumentImpl) node; nodeImpl.addDocumentNotificationListener(this.notificationListener); this.rootNode = nodeImpl; NodeImpl fsrn = this.getFrameSetRootNode(nodeImpl); boolean newIfs = fsrn != null; if(newIfs != this.isFrameSet || this.getComponentCount() == 0) { this.isFrameSet = newIfs; if(newIfs) { this.setUpFrameSet(fsrn); } else { this.setUpAsBlock(rcontext.getUserAgentContext(), rcontext); } } NodeRenderer nr = this.nodeRenderer; if(nr != null) { // These subcomponents should take care // of revalidation. if(newIfs) { nr.setRootNode(fsrn); } else { nr.setRootNode(nodeImpl); } } else { this.invalidate(); this.validate(); this.repaint(); } } /** * Renders HTML given as a string. * @param htmlSource The HTML source code. * @param uri A base URI used to resolve item URIs. * @param rcontext The {@link HtmlRendererContext} instance. * @see org.lobobrowser.html.test.SimpleHtmlRendererContext * @see #setDocument(Document, HtmlRendererContext) */ public void setHtml(String htmlSource, String uri, HtmlRendererContext rcontext) { try { DocumentBuilderImpl builder = new DocumentBuilderImpl(rcontext.getUserAgentContext(), rcontext); Reader reader = new StringReader(htmlSource); try { InputSourceImpl is = new InputSourceImpl(reader, uri); Document document = builder.parse(is); this.setDocument(document, rcontext); } finally { reader.close(); } } catch(java.io.IOException ioe) { throw new IllegalStateException("Unexpected condition.", ioe); } catch(org.xml.sax.SAXException se) { throw new IllegalStateException("Unexpected condition.", se); } } /** * Gets the HTML DOM node currently rendered if any. */ public NodeImpl getRootNode() { return this.rootNode; } private boolean resetIfFrameSet() { NodeImpl nodeImpl = this.rootNode; NodeImpl fsrn = this.getFrameSetRootNode(nodeImpl); boolean newIfs = fsrn != null; if(newIfs != this.isFrameSet || this.getComponentCount() == 0) { this.isFrameSet = newIfs; if(newIfs) { this.setUpFrameSet(fsrn); NodeRenderer nr = this.nodeRenderer; nr.setRootNode(fsrn); // Set proper bounds and repaint. this.validate(); this.repaint(); return true; } } return false; } private NodeImpl getFrameSetRootNode(NodeImpl node) { if(node instanceof Document) { ElementImpl element = (ElementImpl) ((Document) node).getDocumentElement(); if(element != null && "HTML".equalsIgnoreCase(element.getTagName())) { return this.getFrameSet(element); } else { return this.getFrameSet(node); } } else { return null; } } private NodeImpl getFrameSet(NodeImpl node) { NodeImpl[] children = node.getChildrenArray(); if(children == null) { return null; } int length = children.length; NodeImpl frameSet = null; for(int i = 0; i < length; i++) { NodeImpl child = children[i]; if(child instanceof Text) { // Ignore } else if(child instanceof ElementImpl) { String tagName = child.getNodeName(); if("HEAD".equalsIgnoreCase(tagName) || "NOFRAMES".equalsIgnoreCase(tagName) || "TITLE".equalsIgnoreCase(tagName) || "META".equalsIgnoreCase(tagName) || "SCRIPT".equalsIgnoreCase(tagName) || "NOSCRIPT".equalsIgnoreCase(tagName)) { // ignore it } else if("FRAMESET".equalsIgnoreCase(tagName)) { frameSet = child; break; } else { if(this.hasSomeHtml((ElementImpl) child)) { return null; } } } } return frameSet; } private boolean hasSomeHtml(ElementImpl element) { String tagName = element.getTagName(); if("HEAD".equalsIgnoreCase(tagName) || "TITLE".equalsIgnoreCase(tagName) || "META".equalsIgnoreCase(tagName)) { return false; } NodeImpl[] children = element.getChildrenArray(); if(children != null) { int length = children.length; for(int i = 0; i < length; i++) { NodeImpl child = children[i]; if(child instanceof Text) { String textContent = ((Text) child).getTextContent(); if(textContent != null && !"".equals(textContent.trim())) { return false; } } else if(child instanceof ElementImpl) { if(this.hasSomeHtml((ElementImpl) child)) { return false; } } } } return true; } /** * Internal method used to expand the selection to the given point. *

* Note: This method should be invoked in the GUI thread. */ public void expandSelection(RenderableSpot rpoint) { HtmlBlockPanel block = this.htmlBlockPanel; if(block != null) { block.setSelectionEnd(rpoint); block.repaint(); this.selectionDispatch.fireEvent(new SelectionChangeEvent(this, block.isSelectionAvailable())); } } /** * Internal method used to reset the selection so that * it is empty at the given point. This is what is called * when the user clicks on a point in the document. *

* Note: This method should be invoked in the GUI thread. */ public void resetSelection(RenderableSpot rpoint) { HtmlBlockPanel block = this.htmlBlockPanel; if(block != null) { block.setSelectionStart(rpoint); block.setSelectionEnd(rpoint); block.repaint(); } this.selectionDispatch.fireEvent(new SelectionChangeEvent(this, false)); } /** * Gets the selection text. *

* Note: This method should be invoked in the GUI thread. */ public String getSelectionText() { HtmlBlockPanel block = this.htmlBlockPanel; if(block == null) { return null; } else { return block.getSelectionText(); } } /** * Gets a DOM node enclosing the selection. The node returned should * be the inner-most node that encloses both selection start and end * points. Note that the selection end point may be just outside of * the selection. *

* Note: This method should be invoked in the GUI thread. * @return A node enclosing the current selection, or null * if there is no such node. It also returns null * for FRAMESETs. */ public org.w3c.dom.Node getSelectionNode() { HtmlBlockPanel block = this.htmlBlockPanel; if(block == null) { return null; } else { return block.getSelectionNode(); } } /** * Returns true only if the current block has a selection. * This method has no effect in FRAMESETs at the moment. */ public boolean hasSelection() { HtmlBlockPanel block = this.htmlBlockPanel; if(block == null) { return false; } else { return block.hasSelection(); } } /** * Copies the current selection, if any, into the clipboard. * This method has no effect in FRAMESETs at the moment. */ public boolean copy() { HtmlBlockPanel block = this.htmlBlockPanel; if(block != null) { return block.copy(); } else { return false; } } /** * Adds listener of selection changes. Note that it does * not have any effect on FRAMESETs. * @param listener An instance of {@link SelectionChangeListener}. */ public void addSelectionChangeListener(SelectionChangeListener listener) { this.selectionDispatch.addListener(listener); } /** * Removes a listener of selection changes that was * previously added. */ public void removeSelectionChangeListener(SelectionChangeListener listener) { this.selectionDispatch.removeListener(listener); } /** * Sets the default margin insets. Note that in the root block, * the margin behaves like padding. *

* This method has no effect on FRAMESETs. * @param insets The default margin insets. */ public void setDefaultMarginInsets(Insets insets) { this.defaultMarginInsets = insets; HtmlBlockPanel block = this.htmlBlockPanel; if(block != null) { block.setDefaultMarginInsets(insets); } } /** * Sets the default horizontal overflow. *

* This method has no effect on FRAMESETs. * @param overflow See {@link org.lobobrowser.html.style.RenderState}. */ public void setDefaultOverflowX(int overflow) { this.defaultOverflowX = overflow; HtmlBlockPanel block = this.htmlBlockPanel; if(block != null) { block.setDefaultOverflowX(overflow); } } /** * Sets the default vertical overflow. *

* This method has no effect on FRAMESETs. * @param overflow See {@link org.lobobrowser.html.style.RenderState}. */ public void setDefaultOverflowY(int overflow) { this.defaultOverflowY = overflow; HtmlBlockPanel block = this.htmlBlockPanel; if(block != null) { block.setDefaultOverflowY(overflow); } } private ArrayList notifications = new ArrayList(1); private void addNotification(DocumentNotification notification) { // This can be called in a random thread. ArrayList notifs = this.notifications; synchronized(notifs) { notifs.add(notification); } if(EventQueue.isDispatchThread()) { // In this case we want the notification to be processed // immediately. However, we don't want potential recursions // to occur when a Javascript property is set in the GUI thread. // Additionally, many property values may be set in one // event block. EventQueue.invokeLater(this.notificationImmediateAction); } else { this.notificationTimer.restart(); } } /** * Invalidates the layout of the given node and schedules it * to be layed out later. Multiple invalidations may be * processed in a single document layout. */ public void delayedRelayout(NodeImpl node) { ArrayList notifs = this.notifications; synchronized(notifs) { notifs.add(new DocumentNotification(DocumentNotification.SIZE, node)); } this.notificationTimer.restart(); } private void processNotifications() { // This is called in the GUI thread. ArrayList notifs = this.notifications; DocumentNotification[] notifsArray; synchronized(notifs) { int size = notifs.size(); if(size == 0) { return; } notifsArray = new DocumentNotification[size]; notifsArray = (DocumentNotification[]) notifs.toArray(notifsArray); notifs.clear(); } int length = notifsArray.length; for(int i = 0; i < length; i++) { DocumentNotification dn = notifsArray[i]; if(dn.node instanceof HTMLFrameSetElement && this.htmlBlockPanel != null) { if(this.resetIfFrameSet()) { // Revalidation already taken care of. return; } } } HtmlBlockPanel blockPanel = this.htmlBlockPanel; if(blockPanel != null) { blockPanel.processDocumentNotifications(notifsArray); } FrameSetPanel frameSetPanel = this.frameSetPanel; if(frameSetPanel != null) { frameSetPanel.processDocumentNotifications(notifsArray); } } private class SelectionDispatch extends EventDispatch2 { /* (non-Javadoc) * @see org.xamjwg.util.EventDispatch2#dispatchEvent(java.util.EventListener, java.util.EventObject) */ protected void dispatchEvent(EventListener listener, EventObject event) { ((SelectionChangeListener) listener).selectionChanged((SelectionChangeEvent) event); } } private class LocalDocumentNotificationListener implements DocumentNotificationListener { public void allInvalidated() { HtmlPanel.this.addNotification(new DocumentNotification(DocumentNotification.GENERIC, null)); } public void invalidated(NodeImpl node) { HtmlPanel.this.addNotification(new DocumentNotification(DocumentNotification.GENERIC, node)); } public void lookInvalidated(NodeImpl node) { HtmlPanel.this.addNotification(new DocumentNotification(DocumentNotification.LOOK, node)); } public void positionInvalidated(NodeImpl node) { HtmlPanel.this.addNotification(new DocumentNotification(DocumentNotification.POSITION, node)); } public void sizeInvalidated(NodeImpl node) { HtmlPanel.this.addNotification(new DocumentNotification(DocumentNotification.SIZE, node)); } public void externalScriptLoading(NodeImpl node) { // Ignorable here. } public void nodeLoaded(NodeImpl node) { HtmlPanel.this.addNotification(new DocumentNotification(DocumentNotification.GENERIC, node)); } public void structureInvalidated(NodeImpl node) { HtmlPanel.this.addNotification(new DocumentNotification(DocumentNotification.GENERIC, node)); } } private class NotificationTimerAction implements java.awt.event.ActionListener { public void actionPerformed(ActionEvent e) { HtmlPanel.this.processNotifications(); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/gui/SelectionChangeEvent.java0000644000175000017500000000250310726473510027557 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.gui; import java.util.EventObject; /** * Event associated with {@link SelectionChangeListener}. */ public class SelectionChangeEvent extends EventObject { private final boolean hasSelection; public SelectionChangeEvent(Object source, boolean hasSelection) { super(source); this.hasSelection = hasSelection; } public boolean isSelectionAvailable() { return this.hasSelection; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/gui/SelectionChangeListener.java0000644000175000017500000000264110726473506030273 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.gui; import java.util.EventListener; /** * Receives selection change events. * @author J. H. S. * @see org.lobobrowser.html.gui.HtmlPanel#addSelectionChangeListener(SelectionChangeListener) */ public interface SelectionChangeListener extends EventListener { /** * Receives a selection change event. This method * may be assumed to execute in the GUI thread. * @param event A {@link SelectionChangeEvent} instance. */ public void selectionChanged(SelectionChangeEvent event); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/gui/package.html0000644000175000017500000000020410712365564025140 0ustar twernertwernerContains Java Swing components that render a HTML DOM. libcobra-java-0.98.4.orig/src/org/lobobrowser/html/io/0000755000175000017500000000000011125630302022466 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/lobobrowser/html/io/WritableLineReader.java0000644000175000017500000000555010726473500027055 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Nov 13, 2005 */ package org.lobobrowser.html.io; import java.io.*; public class WritableLineReader extends LineNumberReader { private final Reader delegate; public WritableLineReader(Reader reader, int bufferSize) { super(reader, bufferSize); this.delegate = reader; } public WritableLineReader(Reader reader) { super(reader); this.delegate = reader; } /* * Note: Not implicitly thread safe. */ public int read() throws IOException { StringBuffer sb = this.writeBuffer; if(sb != null && sb.length() > 0) { char ch = sb.charAt(0); sb.deleteCharAt(0); if(sb.length() == 0) { this.writeBuffer = null; } return (int) ch; } return super.read(); } /* (non-Javadoc) * Note: Not implicitly thread safe. * @see java.io.Reader#read(byte[], int, int) */ public int read(char[] b, int off, int len) throws IOException { StringBuffer sb = this.writeBuffer; if(sb != null && sb.length() > 0) { int srcEnd = Math.min(sb.length(), len); sb.getChars(0, srcEnd, b, off); sb.delete(0, srcEnd); if(sb.length() == 0) { this.writeBuffer = null; } return srcEnd; } return super.read(b, off, len); } public boolean ready() throws IOException { StringBuffer sb = this.writeBuffer; if(sb != null && sb.length() > 0) { return true; } return super.ready(); } /* (non-Javadoc) * Note: Not implicitly thread safe. * @see java.io.Reader#close() */ public void close() throws IOException { this.writeBuffer = null; super.close(); } private StringBuffer writeBuffer = null; /** * Note: Not implicitly thread safe. * @param text * @throws IOException */ public void write(String text) throws IOException { // Document overrides this to know that new data is coming. StringBuffer sb = this.writeBuffer; if(sb == null) { sb = new StringBuffer(); this.writeBuffer = sb; } sb.append(text); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/js/0000755000175000017500000000000011134560176022506 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/lobobrowser/html/js/Event.java0000644000175000017500000001074010773115022024426 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.js; import org.w3c.dom.html2.*; import java.awt.event.*; import org.lobobrowser.js.*; public class Event extends AbstractScriptableDelegate { private boolean cancelBubble; private HTMLElement fromElement, toElement; private int leafX, leafY; private boolean returnValue; private HTMLElement srcElement; private String type; private final java.awt.event.InputEvent inputEvent; public Event(String type, HTMLElement srcElement, java.awt.event.InputEvent mouseEvent, int leafX, int leafY) { this.type = type; this.srcElement = srcElement; this.leafX = leafX; this.leafY = leafY; this.inputEvent = mouseEvent; } public Event(String type, HTMLElement srcElement, java.awt.event.KeyEvent keyEvent) { this.type = type; this.srcElement = srcElement; this.inputEvent = keyEvent; } public Event(String type, HTMLElement srcElement) { this.type = type; this.srcElement = srcElement; this.inputEvent = null; } public boolean getAltKey() { InputEvent ie = this.inputEvent; return ie == null ? false : ie.isAltDown(); } public boolean getShiftKey() { InputEvent ie = this.inputEvent; return ie == null ? false : ie.isShiftDown(); } public boolean getCtrlKey() { InputEvent ie = this.inputEvent; return ie == null ? false : ie.isControlDown(); } public int getButton() { InputEvent ie = this.inputEvent; if(ie instanceof MouseEvent) { return ((MouseEvent) ie).getButton(); } else { return 0; } } public boolean isCancelBubble() { return cancelBubble; } public void setCancelBubble(boolean cancelBubble) { this.cancelBubble = cancelBubble; } public String getType() { return type; } public void setType(String type) { this.type = type; } public int getClientX() { InputEvent ie = this.inputEvent; if(ie instanceof MouseEvent) { return ((MouseEvent) ie).getX(); } else { return 0; } } public int getClientY() { InputEvent ie = this.inputEvent; if(ie instanceof MouseEvent) { return ((MouseEvent) ie).getY(); } else { return 0; } } public int getKeyCode() { InputEvent ie = this.inputEvent; if(ie instanceof KeyEvent) { return ((KeyEvent) ie).getKeyCode(); } else { return 0; } } // public int getOffsetX() { // // Despite advertising that it returns an element-relative offset, // // IE doesn't do this. // //TODO: Must be relative to top viewport. // return this.getClientX() - 2; // } // // public int getOffsetY() { // // Despite advertising that it returns an element-relative offset, // // IE doesn't do this. // //TODO: Must be relative to top viewport. // return this.getClientY() - 2; // } public boolean isReturnValue() { return returnValue; } public void setReturnValue(boolean returnValue) { this.returnValue = returnValue; } public HTMLElement getSrcElement() { return srcElement; } public void setSrcElement(HTMLElement srcElement) { this.srcElement = srcElement; } public HTMLElement getFromElement() { return fromElement; } public void setFromElement(HTMLElement fromElement) { this.fromElement = fromElement; } public HTMLElement getToElement() { return toElement; } public void setToElement(HTMLElement toElement) { this.toElement = toElement; } public int getLeafX() { return leafX; } public void setLeafX(int leafX) { this.leafX = leafX; } public int getLeafY() { return leafY; } public void setLeafY(int leafY) { this.leafY = leafY; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/js/Executor.java0000644000175000017500000001017010751150732025143 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.js; import org.lobobrowser.html.*; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.js.JavaScript; import org.mozilla.javascript.*; import org.w3c.dom.Document; import java.util.logging.*; public class Executor { private static final Logger logger = Logger.getLogger(Executor.class.getName()); /** * This method should be invoked instead of Context.enter. * @param codeSource * @param ucontext */ public static Context createContext(java.net.URL codeSource, UserAgentContext ucontext) { Context prev = Context.getCurrentContext(); Context ctx = Context.enter(); ctx.setOptimizationLevel(ucontext.getScriptingOptimizationLevel()); if(prev == null) { // If there was a previous context, this one must be nested. // We still need to create a context because of exit() but // we cannot set a new security controller. ctx.setSecurityController(new SecurityControllerImpl(codeSource, ucontext.getSecurityPolicy())); } return ctx; } public static boolean executeFunction(NodeImpl element, Function f, Event event) { return Executor.executeFunction(element, element, f, event); } public static boolean executeFunction(NodeImpl element, Object thisObject, Function f, Event event) { Document doc = element.getOwnerDocument(); if(doc == null) { throw new IllegalStateException("Element does not belong to a document."); } Context ctx = createContext(element.getDocumentURL(), element.getUserAgentContext()); try { Scriptable scope = (Scriptable) doc.getUserData(Executor.SCOPE_KEY); if(scope == null) { throw new IllegalStateException("Scriptable (scope) instance was expected to be keyed as UserData to document using " + Executor.SCOPE_KEY); } JavaScript js = JavaScript.getInstance(); Scriptable thisScope = (Scriptable) js.getJavascriptObject(thisObject, scope); try { Scriptable eventScriptable = (Scriptable) js.getJavascriptObject(event, thisScope); ScriptableObject.defineProperty(thisScope, "event", eventScriptable, ScriptableObject.READONLY); Object result = f.call(ctx, thisScope, thisScope, new Object[0]); if(!(result instanceof Boolean)) { return true; } return ((Boolean) result).booleanValue(); } catch(Throwable thrown) { logger.log(Level.WARNING, "executeFunction(): There was an error in Javascript code.", thrown); return true; } } finally { Context.exit(); } } public static boolean executeFunction(Scriptable thisScope, Function f, java.net.URL codeSource, UserAgentContext ucontext) { Context ctx = createContext(codeSource, ucontext); try { try { Object result = f.call(ctx, thisScope, thisScope, new Object[0]); if(!(result instanceof Boolean)) { return true; } return ((Boolean) result).booleanValue(); } catch(Throwable err) { logger.log(Level.WARNING, "executeFunction(): Unable to execute Javascript function " + f.getClassName() + ".", err); return true; } } finally { Context.exit(); } } /** * A document UserData key used * to map Javascript scope in the HTML document. */ public static final String SCOPE_KEY = "cobra.js.scope"; } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/js/FilteredObjectList.java0000644000175000017500000000400410726473500027070 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 9, 2005 */ package org.lobobrowser.html.js; import java.util.*; import org.lobobrowser.js.*; public class FilteredObjectList extends AbstractScriptableDelegate { private final Collection sourceNodeList; private final ObjectFilter filter; private final Object lock; /** * @param filter * @param list */ public FilteredObjectList(ObjectFilter filter, Collection list, Object lock) { super(); this.filter = filter; sourceNodeList = list; this.lock = lock; } public Object item(int index) { synchronized(this.lock) { int count = 0; Iterator i = this.sourceNodeList.iterator(); while(i.hasNext()) { Object node = (Object) i.next(); if(this.filter.accept(node)) { if(count == index) { return node; } count++; } } return null; } } public int getLength() { synchronized(this.lock) { int count = 0; Iterator i = this.sourceNodeList.iterator(); while(i.hasNext()) { Object node = (Object) i.next(); if(this.filter.accept(node)) { count++; } } return count; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/js/History.java0000644000175000017500000000531511127104412025003 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.js; import org.lobobrowser.html.*; import org.lobobrowser.js.AbstractScriptableDelegate; public class History extends AbstractScriptableDelegate { private final Window window; History(Window window) { this.window = window; } public String getCurrent() { HtmlRendererContext ctx = this.window.getHtmlRendererContext(); return ctx != null ? ctx.getCurrentURL() : null; } public String getNext() { HtmlRendererContext ctx = this.window.getHtmlRendererContext(); return ctx != null ? ctx.getNextURL() : null; } public String getPrevious() { HtmlRendererContext ctx = this.window.getHtmlRendererContext(); return ctx != null ? ctx.getPreviousURL() : null; } public int getLength() { HtmlRendererContext ctx = this.window.getHtmlRendererContext(); return ctx != null ? ctx.getHistoryLength() : 0; } public void back() { HtmlRendererContext ctx = this.window.getHtmlRendererContext(); if(ctx != null) { ctx.back(); } } public void forward() { HtmlRendererContext ctx = this.window.getHtmlRendererContext(); if(ctx != null) { ctx.forward(); } } public void go(int offset) { HtmlRendererContext ctx = this.window.getHtmlRendererContext(); if(ctx != null) { ctx.moveInHistory(offset); } } public void go(String url) { HtmlRendererContext ctx = this.window.getHtmlRendererContext(); if(ctx != null) { ctx.goToHistoryURL(url); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/js/Location.java0000644000175000017500000000644411126716716025135 0ustar twernertwernerpackage org.lobobrowser.html.js; import org.lobobrowser.html.*; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.js.*; import org.w3c.dom.Document; import java.net.*; import java.util.logging.*; public class Location extends AbstractScriptableDelegate { private static final Logger logger = Logger.getLogger(Location.class.getName()); private final Window window; Location(final Window window) { this.window = window; } private URL getURL() { URL url; try { Document document = this.window.getDocumentNode(); url = document == null ? null : new URL(document.getDocumentURI()); } catch(java.net.MalformedURLException mfu) { url = null; } return url; } public String getHash() { URL url = this.getURL(); return url == null ? null : url.getRef(); } public String getHost() { URL url = this.getURL(); if(url == null) { return null; } return url.getHost() + (url.getPort() == -1 ? "" : ":" + url.getPort()); } public String getHostname() { URL url = this.getURL(); if(url == null) { return null; } return url.getHost(); } public String getPathname() { URL url = this.getURL(); return url == null ? null : url.getPath(); } public String getPort() { URL url = this.getURL(); if(url == null) { return null; } int port = url.getPort(); return port == -1 ? null : String.valueOf(port); } public String getProtocol() { URL url = this.getURL(); if(url == null) { return null; } return url.getProtocol() + ":"; } public String getSearch() { URL url = this.getURL(); String query = url == null ? null : url.getQuery(); // Javascript requires "?" in its search string. return query == null ? "" : "?" + query; } private String target; public String getTarget() { return this.target; } public void setTarget(String value) { this.target = value; } public String getHref() { Document document = this.window.getDocumentNode(); return document == null ? null : document.getDocumentURI(); } public void setHref(String uri) { HtmlRendererContext rcontext = this.window.getHtmlRendererContext(); if(rcontext != null) { try { URL url; Document document = this.window.getDocumentNode(); if(document instanceof HTMLDocumentImpl) { HTMLDocumentImpl docImpl = (HTMLDocumentImpl) document; url = docImpl.getFullURL(uri); } else { url = new URL(uri); } rcontext.navigate(url, this.target); } catch(java.net.MalformedURLException mfu) { logger.log(Level.WARNING, "setHref(): Malformed location: [" + uri + "].", mfu); } } } public void reload() { //TODO: This is not really reload. Document document = this.window.getDocumentNode(); if(document instanceof HTMLDocumentImpl) { HTMLDocumentImpl docImpl = (HTMLDocumentImpl) document; HtmlRendererContext rcontext = docImpl.getHtmlRendererContext(); if(rcontext != null) { rcontext.reload(); } else { docImpl.warn("reload(): No renderer context in Location's document."); } } } public void replace(String href) { this.setHref(href); } public String toString() { // This needs to be href. Callers // rely on that. return this.getHref(); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/js/Navigator.java0000644000175000017500000000465611126716726025323 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.js; import org.lobobrowser.html.*; import org.lobobrowser.js.*; public class Navigator extends AbstractScriptableDelegate { private final UserAgentContext context; /** * @param context */ Navigator(UserAgentContext context) { super(); this.context = context; } public String getAppCodeName() { return this.context.getAppCodeName(); } public String getAppName() { return this.context.getAppName(); } public String getAppVersion() { return this.context.getAppVersion(); } public String getAppMinorVersion() { return this.context.getAppMinorVersion(); } public String getPlatform() { return this.context.getPlatform(); } public String getUserAgent() { return this.context.getUserAgent(); } public String getVendor() { return this.context.getVendor(); } public String getProduct() { return this.context.getProduct(); } public boolean javaEnabled() { // True always? return true; } private MimeTypesCollection mimeTypes; public MimeTypesCollection getMimeTypes() { synchronized(this) { MimeTypesCollection mt = this.mimeTypes; if(mt == null) { mt = new MimeTypesCollection(); this.mimeTypes = mt; } return mt; } } public class MimeTypesCollection { // Class must be public to allow JavaScript access public int getLength() { return 0; } public Object item(int index) { return null; } public Object namedItem(String name) { return null; } } }libcobra-java-0.98.4.orig/src/org/lobobrowser/html/js/ObjectFilter.java0000644000175000017500000000203110726473506025727 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Nov 12, 2005 */ package org.lobobrowser.html.js; public interface ObjectFilter { public boolean accept(Object target); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/js/Screen.java0000644000175000017500000000305611126716752024600 0ustar twernertwernerpackage org.lobobrowser.html.js; import java.awt.*; import org.lobobrowser.js.*; public class Screen extends AbstractScriptableDelegate { private final GraphicsEnvironment graphicsEnvironment; private final GraphicsDevice graphicsDevice; /** * @param context */ Screen() { super(); if (GraphicsEnvironment.isHeadless()) { this.graphicsEnvironment = null; this.graphicsDevice = null; } else { this.graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment(); this.graphicsDevice = this.graphicsEnvironment.getDefaultScreenDevice(); } } public int getHeight() { GraphicsDevice gd = this.graphicsDevice; return gd == null ? 0 : gd.getDisplayMode().getHeight(); } public int getPixelDepth() { return this.getColorDepth(); } public int getWidth() { GraphicsEnvironment ge = this.graphicsEnvironment; if(ge == null) { return 0; } GraphicsDevice gd = ge.getDefaultScreenDevice(); return gd.getDisplayMode().getWidth(); } public int getAvailHeight() { GraphicsEnvironment ge = this.graphicsEnvironment; if(ge == null) { return 0; } return ge.getMaximumWindowBounds().height; } public int getAvailWidth() { GraphicsEnvironment ge = this.graphicsEnvironment; if(ge == null) { return 0; } return ge.getMaximumWindowBounds().width; } public int getColorDepth() { GraphicsDevice gd = this.graphicsDevice; if(gd == null) { return 0; } return gd.getDisplayMode().getBitDepth(); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/js/SecurityControllerImpl.java0000644000175000017500000000542610726473500030055 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.js; import org.mozilla.javascript.*; import java.security.*; public class SecurityControllerImpl extends SecurityController { private final java.net.URL url; private final java.security.Policy policy; private final CodeSource codesource; public SecurityControllerImpl(java.net.URL url, Policy policy) { this.url = url; this.policy = policy; this.codesource = new CodeSource(this.url, (java.security.cert.Certificate[]) null); } public Object callWithDomain(Object securityDomain, final Context ctx, final Callable callable, final Scriptable scope, final Scriptable thisObj, final Object[] args) { if(securityDomain == null) { return callable.call(ctx, scope, thisObj, args); } else { PrivilegedAction action = new PrivilegedAction() { public Object run() { return callable.call(ctx, scope, thisObj, args); } }; AccessControlContext acctx = new AccessControlContext(new ProtectionDomain[] { (ProtectionDomain) securityDomain }); return AccessController.doPrivileged(action, acctx); } } public GeneratedClassLoader createClassLoader(ClassLoader parent, Object staticDomain) { return new LocalSecureClassLoader(parent); } public Object getDynamicSecurityDomain(Object securityDomain) { Policy policy = this.policy; if(policy == null) { return null; } else { PermissionCollection permissions = this.policy.getPermissions(codesource); return new ProtectionDomain(codesource, permissions); } } private class LocalSecureClassLoader extends SecureClassLoader implements GeneratedClassLoader { public LocalSecureClassLoader(ClassLoader parent) { super(parent); } public Class defineClass(String name, byte[] b) { return this.defineClass(name, b, 0, b.length, codesource); } public void linkClass(Class clazz) { super.resolveClass(clazz); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/js/Window.java0000644000175000017500000006263611134561070024627 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Nov 12, 2005 */ package org.lobobrowser.html.js; import java.util.*; import java.lang.ref.*; import javax.swing.Timer; import java.awt.event.*; import java.util.logging.*; import org.lobobrowser.html.*; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.js.*; import org.lobobrowser.util.ID; import org.mozilla.javascript.Context; import org.mozilla.javascript.Function; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; import org.w3c.dom.Document; import org.w3c.dom.html2.*; import org.w3c.dom.views.*; import org.w3c.dom.css.*; public class Window extends AbstractScriptableDelegate implements AbstractView { private static final Logger logger = Logger.getLogger(Window.class.getName()); private static final Map CONTEXT_WINDOWS = new WeakHashMap(); //private static final JavaClassWrapper IMAGE_WRAPPER = JavaClassWrapperFactory.getInstance().getClassWrapper(Image.class); private static final JavaClassWrapper XMLHTTPREQUEST_WRAPPER = JavaClassWrapperFactory.getInstance().getClassWrapper(XMLHttpRequest.class); private static int timerIdCounter = 0; private final HtmlRendererContext rcontext; private final UserAgentContext uaContext; private Navigator navigator; private Screen screen; private Location location; private Map taskMap; private volatile HTMLDocumentImpl document; public Window(HtmlRendererContext rcontext, UserAgentContext uaContext) { //TODO: Probably need to create a new Window instance //for every document. Sharing of Window state between //different documents is not correct. this.rcontext = rcontext; this.uaContext = uaContext; } private static int generateTimerID() { synchronized(logger) { return timerIdCounter++; } } public HtmlRendererContext getHtmlRendererContext() { return this.rcontext; } public UserAgentContext getUserAgentContext() { return this.uaContext; } private void clearState() { Scriptable s = this.getWindowScope(); if(s != null) { Object[] ids = s.getIds(); for(int i = 0; i < ids.length; i++) { Object id = ids[i]; if(id instanceof String) { s.delete((String) id); } else if(id instanceof Integer) { s.delete(((Integer) id).intValue()); } } } } public void setDocument(HTMLDocumentImpl document) { Document prevDocument = this.document; if(prevDocument != document) { // Should clearing of the state be done // when window "unloads"? if(prevDocument != null) { // Only clearing when the previous document was not null // because state might have been set on the window before // the very first document is added. this.clearState(); } this.initWindowScope(document); this.forgetAllTasks(); Function onunload = this.onunload; if(onunload != null) { HTMLDocumentImpl oldDoc = (HTMLDocumentImpl) this.document; Executor.executeFunction(this.getWindowScope(), onunload, oldDoc.getDocumentURL(), this.uaContext); this.onunload = null; } this.document = document; } } public DocumentView getDocument() { return this.document; } public Document getDocumentNode() { return this.document; } private void putAndStartTask(Integer timeoutID, Timer timer, Object retained) { TaskWrapper oldTaskWrapper = null; synchronized(this) { Map taskMap = this.taskMap; if(taskMap == null) { taskMap = new HashMap(4); this.taskMap = taskMap; } else { oldTaskWrapper = (TaskWrapper) taskMap.get(timeoutID); } taskMap.put(timeoutID, new TaskWrapper(timer, retained)); } // Do this outside synchronized block, just in case. if(oldTaskWrapper != null) { oldTaskWrapper.timer.stop(); } timer.start(); } private void forgetTask(Integer timeoutID, boolean cancel) { TaskWrapper oldTimer = null; synchronized(this) { Map taskMap = this.taskMap; if(taskMap != null) { oldTimer = (TaskWrapper) taskMap.remove(timeoutID); } } if(oldTimer != null && cancel) { oldTimer.timer.stop(); } } private void forgetAllTasks() { TaskWrapper[] oldTaskWrappers = null; synchronized(this) { Map taskMap = this.taskMap; if(taskMap != null) { oldTaskWrappers = (TaskWrapper[]) taskMap.values().toArray(new TaskWrapper[0]); this.taskMap = null; } } if(oldTaskWrappers != null) { for(int i = 0; i < oldTaskWrappers.length; i++) { TaskWrapper taskWrapper = oldTaskWrappers[i]; taskWrapper.timer.stop(); } } } // private Timer getTask(Long timeoutID) { // synchronized(this) { // Map taskMap = this.taskMap; // if(taskMap != null) { // return (Timer) taskMap.get(timeoutID); // } // } // return null; // } /** * @param aFunction * Javascript function to invoke on each loop. * @param aTimeInMs * Time in millisecund between each loop. * @return Return the timer ID to use as reference * @see Window.setInterval interface * definition * @todo Make proper and refactore with {@link Window#setTimeout(Function, double)}. */ public int setInterval(final Function aFunction, final double aTimeInMs) { if (aTimeInMs > Integer.MAX_VALUE || aTimeInMs < 0) { throw new IllegalArgumentException("Timeout value " + aTimeInMs + " is not supported."); } final int timeID = generateTimerID(); final Integer timeIDInt = new Integer(timeID); ActionListener task = new FunctionTimerTask(this, timeIDInt, aFunction, false); int t = (int) aTimeInMs; if(t < 1) { t = 1; } Timer timer = new Timer(t, task); timer.setRepeats(true); // The only difference with setTimeout this.putAndStartTask(timeIDInt, timer, aFunction); return timeID; } /** * @param aExpression * Javascript expression to invoke on each loop. * @param aTimeInMs * Time in millisecund between each loop. * @return Return the timer ID to use as reference * @see Window.setInterval interface * definition * @todo Make proper and refactore with {@link Window#setTimeout(String, double)}. */ public int setInterval(final String aExpression, double aTimeInMs) { if (aTimeInMs > Integer.MAX_VALUE || aTimeInMs < 0) { throw new IllegalArgumentException("Timeout value " + aTimeInMs + " is not supported."); } final int timeID = generateTimerID(); final Integer timeIDInt = new Integer(timeID); ActionListener task = new ExpressionTimerTask(this, timeIDInt, aExpression, false); int t = (int) aTimeInMs; if(t < 1) { t = 1; } Timer timer = new Timer(t, task); timer.setRepeats(false); // The only difference with setTimeout this.putAndStartTask(timeIDInt, timer, null); return timeID; } /** * @param aTimerID * Timer ID to stop. * @see Window.clearInterval interface Definition */ public void clearInterval(int aTimerID) { Integer key = new Integer(aTimerID); this.forgetTask(key, true); } public void alert(String message) { if(this.rcontext != null) { this.rcontext.alert(message); } } public void back() { HtmlRendererContext rcontext = this.rcontext; if(rcontext != null) { rcontext.back(); } } public void blur() { HtmlRendererContext rcontext = this.rcontext; if(rcontext != null) { rcontext.blur(); } } public void clearTimeout(int timeoutID) { Integer key = new Integer(timeoutID); this.forgetTask(key, true); } public void close() { HtmlRendererContext rcontext = this.rcontext; if(rcontext != null) { rcontext.close(); } } public boolean confirm(String message) { HtmlRendererContext rcontext = this.rcontext; if(rcontext != null) { return rcontext.confirm(message); } else { return false; } } public Object eval(String javascript) { HTMLDocumentImpl document = (HTMLDocumentImpl) this.document; if(document == null) { throw new IllegalStateException("Cannot evaluate if document is not set."); } Context ctx = Executor.createContext(document.getDocumentURL(), this.uaContext); try { Scriptable scope = this.getWindowScope(); if(scope == null) { throw new IllegalStateException("Scriptable (scope) instance was expected to be keyed as UserData to document using " + Executor.SCOPE_KEY); } String scriptURI = "window.eval"; if(logger.isLoggable(Level.INFO)) { logger.info("eval(): javascript follows...\r\n" + javascript); } return ctx.evaluateString(scope, javascript, scriptURI, 1, null); } finally { Context.exit(); } } public void focus() { HtmlRendererContext rcontext = this.rcontext; if(rcontext != null) { rcontext.focus(); } } private void initWindowScope(final Document doc) { // Special Javascript class: XMLHttpRequest final Scriptable ws = this.getWindowScope(); JavaInstantiator xi = new JavaInstantiator() { public Object newInstance() { Document d = doc; if(d == null) { throw new IllegalStateException("Cannot perform operation when document is unset."); } HTMLDocumentImpl hd; try { hd = (HTMLDocumentImpl) d; } catch(ClassCastException err) { throw new IllegalStateException("Cannot perform operation with documents of type " + d.getClass().getName() + "."); } return new XMLHttpRequest(uaContext, hd.getDocumentURL(), ws); } }; Function xmlHttpRequestC = JavaObjectWrapper.getConstructor("XMLHttpRequest", XMLHTTPREQUEST_WRAPPER, ws, xi); ScriptableObject.defineProperty(ws, "XMLHttpRequest", xmlHttpRequestC, ScriptableObject.READONLY); // HTML element classes this.defineElementClass(ws, doc, "Image", "img", HTMLImageElementImpl.class); this.defineElementClass(ws, doc, "Script", "script", HTMLScriptElementImpl.class); this.defineElementClass(ws, doc, "IFrame", "iframe", HTMLIFrameElementImpl.class); this.defineElementClass(ws, doc, "Option", "option", HTMLOptionElementImpl.class); this.defineElementClass(ws, doc, "Select", "select", HTMLSelectElementImpl.class); } private ScriptableObject windowScope; public Scriptable getWindowScope() { synchronized(this) { ScriptableObject windowScope = this.windowScope; if(windowScope != null) { return windowScope; } // Context.enter() OK in this particular case. Context ctx = Context.enter(); try { // Window scope needs to be top-most scope. windowScope = (ScriptableObject) JavaScript.getInstance().getJavascriptObject(this, null); ctx.initStandardObjects(windowScope); this.windowScope = windowScope; return windowScope; } finally { Context.exit(); } } } private final void defineElementClass(Scriptable scope, final Document document, final String jsClassName, final String elementName, Class javaClass) { JavaInstantiator ji = new JavaInstantiator() { public Object newInstance() { Document d = document; if(d == null) { throw new IllegalStateException("Document not set in current context."); } return d.createElement(elementName); } }; JavaClassWrapper classWrapper = JavaClassWrapperFactory.getInstance().getClassWrapper(javaClass); Function constructorFunction = JavaObjectWrapper.getConstructor(jsClassName, classWrapper, scope, ji); ScriptableObject.defineProperty(scope, jsClassName, constructorFunction, ScriptableObject.READONLY); } public static Window getWindow(HtmlRendererContext rcontext) { if(rcontext == null) { return null; } synchronized(CONTEXT_WINDOWS) { Reference wref = (Reference) CONTEXT_WINDOWS.get(rcontext); if(wref != null) { Window window = (Window) wref.get(); if(window != null) { return window; } } Window window = new Window(rcontext, rcontext.getUserAgentContext()); CONTEXT_WINDOWS.put(rcontext, new WeakReference(window)); return window; } } public Window open(String relativeUrl, String windowName, String windowFeatures, boolean replace) { HtmlRendererContext rcontext = this.rcontext; if(rcontext != null) { java.net.URL url; Object document = this.document; if(document instanceof HTMLDocumentImpl) { url = ((HTMLDocumentImpl) document).getFullURL(relativeUrl); } else { try { url = new java.net.URL(relativeUrl); } catch(java.net.MalformedURLException mfu) { throw new IllegalArgumentException("Malformed URI: " + relativeUrl); } } HtmlRendererContext newContext = rcontext.open(url, windowName, windowFeatures, replace); return getWindow(newContext); } else { return null; } } public Window open(String url) { return this.open(url, "window:" + String.valueOf(ID.generateLong())); } public Window open(String url, String windowName) { return this.open(url, windowName, "", false); } public Window open(String url, String windowName, String windowFeatures) { return this.open(url, windowName, windowFeatures, false); } public String prompt(String message) { return this.prompt(message, ""); } public String prompt(String message, int inputDefault) { return this.prompt(message, String.valueOf(inputDefault)); } public String prompt(String message, String inputDefault) { HtmlRendererContext rcontext = this.rcontext; if(rcontext != null) { return rcontext.prompt(message, inputDefault); } else { return null; } } public void scrollTo(int x, int y) { HtmlRendererContext rcontext = this.rcontext; if(rcontext != null) { rcontext.scroll(x, y); } } public void scrollBy(int x, int y) { HtmlRendererContext rcontext = this.rcontext; if(rcontext != null) { rcontext.scrollBy(x, y); } } public void resizeTo(int width, int height) { HtmlRendererContext rcontext = this.rcontext; if(rcontext != null) { rcontext.resizeTo(width, height); } } public void resizeBy(int byWidth, int byHeight) { HtmlRendererContext rcontext = this.rcontext; if(rcontext != null) { rcontext.resizeBy(byWidth, byHeight); } } public int setTimeout(final String expr, double millis) { if(millis > Integer.MAX_VALUE || millis < 0) { throw new IllegalArgumentException("Timeout value " + millis + " is not supported."); } final int timeID = generateTimerID(); final Integer timeIDInt = new Integer(timeID); ActionListener task = new ExpressionTimerTask(this, timeIDInt, expr, true); int t = (int) millis; if(t < 1) { t = 1; } Timer timer = new Timer(t, task); timer.setRepeats(false); this.putAndStartTask(timeIDInt, timer, null); return timeID; } public int setTimeout(final Function function, double millis) { if(millis > Integer.MAX_VALUE || millis < 0) { throw new IllegalArgumentException("Timeout value " + millis + " is not supported."); } final int timeID = generateTimerID(); final Integer timeIDInt = new Integer(timeID); ActionListener task = new FunctionTimerTask(this, timeIDInt, function, true); int t = (int) millis; if(t < 1) { t = 1; } Timer timer = new Timer(t, task); timer.setRepeats(false); this.putAndStartTask(timeIDInt, timer, function); return timeID; } public boolean isClosed() { HtmlRendererContext rcontext = this.rcontext; if(rcontext != null) { return rcontext.isClosed(); } else { return false; } } public String getDefaultStatus() { HtmlRendererContext rcontext = this.rcontext; if(rcontext != null) { return rcontext.getDefaultStatus(); } else { return null; } } public HTMLCollection getFrames() { Document doc = this.document; if(doc instanceof HTMLDocumentImpl) { return ((HTMLDocumentImpl) doc).getFrames(); } return null; } private int length; private boolean lengthSet = false; /** * Gets the number of frames. */ public int getLength() { if(this.lengthSet) { return this.length; } else { HTMLCollection frames = this.getFrames(); return frames == null ? 0 : frames.getLength(); } } public void setLength(int length) { this.lengthSet = true; this.length = length; } public String getName() { HtmlRendererContext rcontext = this.rcontext; if(rcontext != null) { return rcontext.getName(); } else { return null; } } public Window getParent() { HtmlRendererContext rcontext = this.rcontext; if(rcontext != null) { return Window.getWindow(rcontext.getParent()); } else { return null; } } public Window getOpener() { HtmlRendererContext rcontext = this.rcontext; if(rcontext != null) { return Window.getWindow(rcontext.getOpener()); } else { return null; } } public void setOpener(Window opener) { HtmlRendererContext rcontext = this.rcontext; if(rcontext != null) { if(opener == null) { rcontext.setOpener(null); } else { rcontext.setOpener(opener.rcontext); } } } public Window getSelf() { return this; } public String getStatus() { HtmlRendererContext rcontext = this.rcontext; if(rcontext != null) { return rcontext.getStatus(); } else { return null; } } public void setStatus(String message) { HtmlRendererContext rcontext = this.rcontext; if(rcontext != null) { rcontext.setStatus(message); } } public Window getTop() { HtmlRendererContext rcontext = this.rcontext; if(rcontext != null) { return Window.getWindow(rcontext.getTop()); } else { return null; } } public Window getWindow() { return this; } public Navigator getNavigator() { synchronized(this) { Navigator nav = this.navigator; if(nav == null) { nav = new Navigator(this.uaContext); this.navigator = nav; } return nav; } } public Screen getScreen() { synchronized(this) { Screen nav = this.screen; if(nav == null) { nav = new Screen(); this.screen = nav; } return nav; } } public Location getLocation() { synchronized(this) { Location location = this.location; if(location == null) { location = new Location(this); this.location = location; } return location; } } public void setLocation(String location) { this.getLocation().setHref(location); } private History history; public History getHistory() { synchronized(this) { History history = this.history; if(history == null) { history = new History(this); this.history = history; } return history; } } public CSS2Properties getComputedStyle(HTMLElement element, String pseudoElement) { if(element instanceof HTMLElementImpl) { return ((HTMLElementImpl) element).getComputedStyle(pseudoElement); } else { throw new java.lang.IllegalArgumentException("Element implementation unknown: " + element); } } public Function getOnload() { Document doc = this.document; if(doc instanceof HTMLDocumentImpl) { return ((HTMLDocumentImpl) doc).getOnloadHandler(); } else { return null; } } public void setOnload(Function onload) { //Note that body.onload overrides //window.onload. Document doc = this.document; if(doc instanceof HTMLDocumentImpl) { ((HTMLDocumentImpl) doc).setOnloadHandler(onload); } } private Function onunload; public Function getOnunload() { return onunload; } public void setOnunload(Function onunload) { this.onunload = onunload; } public org.w3c.dom.Node namedItem(String name) { // Bug 1928758: Element IDs are named objects in context. HTMLDocumentImpl doc = this.document; if(doc == null) { return null; } org.w3c.dom.Node node = doc.getElementById(name); if(node != null) { return node; } return null; } public void forceGC() { System.gc(); } private static abstract class WeakWindowTask implements ActionListener { private final WeakReference windowRef; public WeakWindowTask(Window window) { this.windowRef = new WeakReference(window); } protected Window getWindow() { WeakReference ref = this.windowRef; return ref == null ? null : (Window) ref.get(); } } private static class FunctionTimerTask extends WeakWindowTask { // Implemented as a static WeakWindowTask to allow the Window // to get garbage collected, especially in infinite loop // scenarios. private final Integer timeIDInt; private final WeakReference functionRef; private final boolean removeTask; public FunctionTimerTask(Window window, Integer timeIDInt, Function function, boolean removeTask) { super(window); this.timeIDInt = timeIDInt; this.functionRef = new WeakReference(function); this.removeTask = removeTask; } public void actionPerformed(ActionEvent e) { // This executes in the GUI thread and that's good. try { Window window = this.getWindow(); if(window == null) { if(logger.isLoggable(Level.INFO)) { logger.info("actionPerformed(): Window is no longer available."); } return; } if(this.removeTask) { window.forgetTask(this.timeIDInt, false); } HTMLDocumentImpl doc = (HTMLDocumentImpl) window.getDocument(); if(doc == null) { throw new IllegalStateException("Cannot perform operation when document is unset."); } Function function = (Function) this.functionRef.get(); if(function == null) { throw new IllegalStateException("Cannot perform operation. Function is no longer available."); } Executor.executeFunction(window.getWindowScope(), function, doc.getDocumentURL(), window.getUserAgentContext()); } catch(Throwable err) { logger.log(Level.WARNING, "actionPerformed()", err); } } } private static class ExpressionTimerTask extends WeakWindowTask { // Implemented as a static WeakWindowTask to allow the Window // to get garbage collected, especially in infinite loop // scenarios. private final Integer timeIDInt; private final String expression; private final boolean removeTask; public ExpressionTimerTask(Window window, Integer timeIDInt, String expression, boolean removeTask) { super(window); this.timeIDInt = timeIDInt; this.expression = expression; this.removeTask = removeTask; } public void actionPerformed(ActionEvent e) { // This executes in the GUI thread and that's good. try { Window window = this.getWindow(); if(window == null) { if(logger.isLoggable(Level.INFO)) { logger.info("actionPerformed(): Window is no longer available."); } return; } if(this.removeTask) { window.forgetTask(this.timeIDInt, false); } HTMLDocumentImpl doc = (HTMLDocumentImpl) window.getDocument(); if(doc == null) { throw new IllegalStateException("Cannot perform operation when document is unset."); } window.eval(this.expression); } catch(Throwable err) { logger.log(Level.WARNING, "actionPerformed()", err); } } } private static class TaskWrapper { public final Timer timer; private final Object retained; public TaskWrapper(Timer timer, Object retained) { super(); this.timer = timer; this.retained = retained; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/js/XMLHttpRequest.java0000644000175000017500000000733210753354760026235 0ustar twernertwernerpackage org.lobobrowser.html.js; import java.net.*; import org.w3c.dom.Document; import org.lobobrowser.html.*; import org.lobobrowser.util.*; import org.lobobrowser.js.*; import org.mozilla.javascript.*; import java.util.logging.*; public class XMLHttpRequest extends AbstractScriptableDelegate { //TODO: See reference: http://www.xulplanet.com/references/objref/XMLHttpRequest.html private static final Logger logger = Logger.getLogger(XMLHttpRequest.class.getName()); private final HttpRequest request; private final UserAgentContext pcontext; private final Scriptable scope; private final java.net.URL codeSource; public XMLHttpRequest(UserAgentContext pcontext, java.net.URL codeSource, Scriptable scope) { this.request = pcontext.createHttpRequest(); this.pcontext = pcontext; this.scope = scope; this.codeSource = codeSource; } public void abort() { request.abort(); } public String getAllResponseHeaders() { return request.getAllResponseHeaders(); } public int getReadyState() { return request.getReadyState(); } public byte[] getResponseBytes() { return request.getResponseBytes(); } public String getResponseHeader(String headerName) { return request.getResponseHeader(headerName); } public String getResponseText() { return request.getResponseText(); } public Document getResponseXML() { return request.getResponseXML(); } public int getStatus() { return request.getStatus(); } public String getStatusText() { return request.getStatusText(); } private URL getFullURL(String relativeUrl) throws java.net.MalformedURLException { return Urls.createURL(this.codeSource, relativeUrl); } public void open(String method, String url, boolean asyncFlag, String userName, String password) throws java.io.IOException { request.open(method, this.getFullURL(url), asyncFlag, userName, password); } public void open(String method, String url, boolean asyncFlag, String userName) throws java.io.IOException { request.open(method, this.getFullURL(url), asyncFlag, userName); } public void open(String method, String url, boolean asyncFlag) throws java.io.IOException { request.open(method, this.getFullURL(url), asyncFlag); } public void open(String method, String url) throws java.io.IOException { request.open(method, this.getFullURL(url)); } public void send(String content) throws java.io.IOException { request.send(content); } private Function onreadystatechange; private boolean listenerAdded; public Function getOnreadystatechange() { synchronized(this) { return this.onreadystatechange; } } public void setOnreadystatechange(final Function value) { synchronized(this) { this.onreadystatechange = value; if(value != null && !this.listenerAdded) { this.request.addReadyStateChangeListener(new ReadyStateChangeListener() { public void readyStateChanged() { // Not called in GUI thread to ensure consistency of readyState. executeReadyStateChange(); } }); this.listenerAdded = true; } } } private void executeReadyStateChange() { // Not called in GUI thread to ensure consistency of readyState. try { Function f = XMLHttpRequest.this.getOnreadystatechange(); if(f != null) { Context ctx = Executor.createContext(this.codeSource, this.pcontext); try { Scriptable newScope = (Scriptable) JavaScript.getInstance().getJavascriptObject(XMLHttpRequest.this, this.scope); f.call(ctx, newScope, newScope, new Object[0]); } finally { Context.exit(); } } } catch(Exception err) { logger.log(Level.WARNING, "Error processing ready state change.", err); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/package.html0000644000175000017500000000014510445351614024352 0ustar twernertwernerContext interfaces that need to be implemented in order to use the parser and renderer.libcobra-java-0.98.4.orig/src/org/lobobrowser/html/parser/0000755000175000017500000000000011125630300023351 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/lobobrowser/html/parser/DocumentBuilderImpl.java0000644000175000017500000001446711056277150030154 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 15, 2005 */ package org.lobobrowser.html.parser; import java.io.*; import javax.xml.parsers.DocumentBuilder; import java.util.logging.*; import org.lobobrowser.html.*; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.html.io.*; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * The DocumentBuilderImpl class is an HTML * DOM parser that implements the * standard W3C DocumentBuilder interface. * @author J. H. S. */ public class DocumentBuilderImpl extends DocumentBuilder { private static final Logger logger = Logger.getLogger(DocumentBuilderImpl.class.getName()); private EntityResolver resolver; private ErrorHandler errorHandler; private final UserAgentContext bcontext; private final HtmlRendererContext rcontext; /** * Constructs a DocumentBuilderImpl. This constructor * should be used when only the parsing functionality (without rendering) * is required. * @param context An instance of {@link org.lobobrowser.html.UserAgentContext}, * which may be an instance of {@link org.lobobrowser.html.test.SimpleUserAgentContext}. */ public DocumentBuilderImpl(UserAgentContext context) { this.rcontext = null; this.bcontext = context; } /** * Constructs a DocumentBuilderImpl. This constructor * should be used when rendering is expected. * @param ucontext An instance of {@link org.lobobrowser.html.UserAgentContext}, * which may be an instance of {@link org.lobobrowser.html.test.SimpleUserAgentContext}. * @param rcontext An instance of {@link org.lobobrowser.html.HtmlRendererContext}, * which may be an instance of {@link org.lobobrowser.html.test.SimpleHtmlRendererContext}. */ public DocumentBuilderImpl(UserAgentContext ucontext, HtmlRendererContext rcontext) { this.rcontext = rcontext; this.bcontext = ucontext; } /** * Constructs a DocumentBuilderImpl. This constructor * should be used when rendering is expected. * @param rcontext An instance of {@link org.lobobrowser.html.HtmlRendererContext}, * which may be an instance of {@link org.lobobrowser.html.test.SimpleHtmlRendererContext}. */ public DocumentBuilderImpl(HtmlRendererContext rcontext) { this.rcontext = rcontext; this.bcontext = rcontext.getUserAgentContext(); } /** * Parses an HTML document. Note that this method will read the entire * input source before returning a Document instance. * @param is The input source, which may be an instance of * {@link org.lobobrowser.html.parser.InputSourceImpl}. * @see #createDocument(InputSource) */ public Document parse(InputSource is) throws org.xml.sax.SAXException, IOException { HTMLDocumentImpl document = (HTMLDocumentImpl) this.createDocument(is); document.load(); return document; } /** * Creates a document without parsing the input provided, so * the document object can be used for incremental rendering. * @param is The input source, which may be an instance of * {@link org.lobobrowser.html.parser.InputSourceImpl}. The input * source must provide either an input stream or a reader. * @see HTMLDocumentImpl#load() */ public Document createDocument(InputSource is) throws SAXException, IOException { String encoding = is.getEncoding(); String charset = encoding; if(charset == null) { charset = "US-ASCII"; } String uri = is.getSystemId(); if(uri == null) { logger.warning("parse(): InputSource has no SystemId (URI); document item URLs will not be resolvable."); } WritableLineReader wis; Reader reader = is.getCharacterStream(); if(reader != null) { wis = new WritableLineReader(reader); } else { InputStream in = is.getByteStream(); if(in != null) { wis = new WritableLineReader(new InputStreamReader(in, charset)); } else if(uri != null) { // To comply with the InputSource documentation, we need // to do this: java.net.URLConnection connection = new java.net.URL(uri).openConnection(); in = connection.getInputStream(); if(encoding == null) { charset = org.lobobrowser.util.Urls.getCharset(connection); } wis = new WritableLineReader(new InputStreamReader(in, charset)); } else { throw new IllegalArgumentException("The InputSource must have either a reader, an input stream or a URI."); } } HTMLDocumentImpl document = new HTMLDocumentImpl(this.bcontext, this.rcontext, wis, uri); return document; } public boolean isNamespaceAware() { return false; } public boolean isValidating() { return false; } public void setEntityResolver(EntityResolver er) { this.resolver = er; } public void setErrorHandler(ErrorHandler eh) { this.errorHandler = eh; } public Document newDocument() { return new HTMLDocumentImpl(this.bcontext); } private DOMImplementation domImplementation; public DOMImplementation getDOMImplementation() { synchronized(this) { if(this.domImplementation == null) { this.domImplementation = new DOMImplementationImpl(this.bcontext); } return this.domImplementation; } } public ErrorHandler getErrorHandler() { return errorHandler; } public EntityResolver getResolver() { return resolver; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/parser/ElementInfo.java0000644000175000017500000000447311000443542026433 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 23, 2005 */ package org.lobobrowser.html.parser; import java.util.Set; class ElementInfo { public final int endElementType; public final boolean childElementOk; public final Set stopTags; public final boolean noScriptElement; public final boolean decodeEntities; public static final int END_ELEMENT_FORBIDDEN = 0; public static final int END_ELEMENT_OPTIONAL = 1; public static final int END_ELEMENT_REQUIRED = 2; /** * @param ok * @param type */ public ElementInfo(boolean ok, int type) { this.childElementOk = ok; this.endElementType = type; this.stopTags = null; this.noScriptElement = false; this.decodeEntities = true; } /** * @param ok * @param type */ public ElementInfo(boolean ok, int type, Set stopTags) { this.childElementOk = ok; this.endElementType = type; this.stopTags = stopTags; this.noScriptElement = false; this.decodeEntities = true; } public ElementInfo(boolean ok, int type, Set stopTags, boolean noScriptElement) { this.childElementOk = ok; this.endElementType = type; this.stopTags = stopTags; this.noScriptElement = noScriptElement; this.decodeEntities = true; } public ElementInfo(boolean ok, int type, boolean decodeEntities) { this.childElementOk = ok; this.endElementType = type; this.stopTags = null; this.noScriptElement = false; this.decodeEntities = decodeEntities; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/parser/HtmlParser.java0000644000175000017500000013761011067637014026323 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Aug 28, 2005 */ package org.lobobrowser.html.parser; import java.io.*; import java.util.*; import java.util.logging.*; import org.w3c.dom.Node; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.DOMException; import org.xml.sax.ErrorHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.lobobrowser.html.*; import org.lobobrowser.html.io.*; /** * The HtmlParser class is an HTML DOM parser. * This parser provides the functionality for * the standard DOM parser implementation {@link org.lobobrowser.html.parser.DocumentBuilderImpl}. * This parser class may be used directly when a different DOM * implementation is preferred. */ public class HtmlParser { private static final Logger logger = Logger.getLogger(HtmlParser.class.getName()); private final Document document; private final UserAgentContext ucontext; private final ErrorHandler errorHandler; private final String publicId; private final String systemId; private static final Map ENTITIES = new HashMap(256); private static final Map ELEMENT_INFOS = new HashMap(35); /** * A node UserData key used to tell * nodes that their content may be about to be * modified. Elements could use this to temporarily * suspend notifications. The value set * will be either Boolean.TRUE or * Boolean.FALSE. */ public static final String MODIFYING_KEY = "cobra.suspend"; static { Map entities = ENTITIES; entities.put("amp", new Character('&')); entities.put("lt", new Character('<')); entities.put("gt", new Character('>')); entities.put("quot", new Character('"')); entities.put("nbsp", new Character((char) 160)); entities.put("lsquo", new Character('\u2018')); entities.put("rsquo", new Character('\u2019')); entities.put("frasl", new Character((char) 47)); entities.put("ndash", new Character((char) 8211)); entities.put("mdash", new Character((char) 8212)); entities.put("iexcl", new Character((char) 161)); entities.put("cent", new Character((char) 162)); entities.put("pound", new Character((char) 163)); entities.put("curren", new Character((char) 164)); entities.put("yen", new Character((char) 165)); entities.put("brvbar", new Character((char) 166)); entities.put("brkbar", new Character((char) 166)); entities.put("sect", new Character((char) 167)); entities.put("uml", new Character((char) 168)); entities.put("die", new Character((char) 168)); entities.put("copy", new Character((char) 169)); entities.put("ordf", new Character((char) 170)); entities.put("laquo", new Character((char) 171)); entities.put("not", new Character((char) 172)); entities.put("shy", new Character((char) 173)); entities.put("reg", new Character((char) 174)); entities.put("macr", new Character((char) 175)); entities.put("hibar", new Character((char) 175)); entities.put("deg", new Character((char) 176)); entities.put("plusmn", new Character((char) 177)); entities.put("sup2", new Character((char) 178)); entities.put("sup3", new Character((char) 179)); entities.put("acute", new Character((char) 180)); entities.put("micro", new Character((char) 181)); entities.put("para", new Character((char) 182)); entities.put("middot", new Character((char) 183)); entities.put("cedil", new Character((char) 184)); entities.put("sup1", new Character((char) 185)); entities.put("ordm", new Character((char) 186)); entities.put("raquo", new Character((char) 187)); entities.put("frac14", new Character((char) 188)); entities.put("frac12", new Character((char) 189)); entities.put("frac34", new Character((char) 190)); entities.put("iquest", new Character((char) 191)); entities.put("Agrave", new Character((char) 192)); entities.put("Aacute", new Character((char) 193)); entities.put("Acirc", new Character((char) 194)); entities.put("Atilde", new Character((char) 195)); entities.put("Auml", new Character((char) 196)); entities.put("Aring", new Character((char) 197)); entities.put("AElig", new Character((char) 198)); entities.put("Ccedil", new Character((char) 199)); entities.put("Egrave", new Character((char) 200)); entities.put("Eacute", new Character((char) 201)); entities.put("Ecirc", new Character((char) 202)); entities.put("Euml", new Character((char) 203)); entities.put("Igrave", new Character((char) 204)); entities.put("Iacute", new Character((char) 205)); entities.put("Icirc", new Character((char) 206)); entities.put("Iuml", new Character((char) 207)); entities.put("ETH", new Character((char) 208)); entities.put("Ntilde", new Character((char) 209)); entities.put("Ograve", new Character((char) 210)); entities.put("Oacute", new Character((char) 211)); entities.put("Ocirc", new Character((char) 212)); entities.put("Otilde", new Character((char) 213)); entities.put("Ouml", new Character((char) 214)); entities.put("times", new Character((char) 215)); entities.put("Oslash", new Character((char) 216)); entities.put("Ugrave", new Character((char) 217)); entities.put("Uacute", new Character((char) 218)); entities.put("Ucirc", new Character((char) 219)); entities.put("Uuml", new Character((char) 220)); entities.put("Yacute", new Character((char) 221)); entities.put("THORN", new Character((char) 222)); entities.put("szlig", new Character((char) 223)); entities.put("agrave", new Character((char) 224)); entities.put("aacute", new Character((char) 225)); entities.put("acirc", new Character((char) 226)); entities.put("atilde", new Character((char) 227)); entities.put("auml", new Character((char) 228)); entities.put("aring", new Character((char) 229)); entities.put("aelig", new Character((char) 230)); entities.put("ccedil", new Character((char) 231)); entities.put("egrave", new Character((char) 232)); entities.put("eacute", new Character((char) 233)); entities.put("ecirc", new Character((char) 234)); entities.put("euml", new Character((char) 235)); entities.put("igrave", new Character((char) 236)); entities.put("iacute", new Character((char) 237)); entities.put("icirc", new Character((char) 238)); entities.put("iuml", new Character((char) 239)); entities.put("eth", new Character((char) 240)); entities.put("ntilde", new Character((char) 241)); entities.put("ograve", new Character((char) 242)); entities.put("oacute", new Character((char) 243)); entities.put("ocirc", new Character((char) 244)); entities.put("otilde", new Character((char) 245)); entities.put("ouml", new Character((char) 246)); entities.put("divide", new Character((char) 247)); entities.put("oslash", new Character((char) 248)); entities.put("ugrave", new Character((char) 249)); entities.put("uacute", new Character((char) 250)); entities.put("ucirc", new Character((char) 251)); entities.put("uuml", new Character((char) 252)); entities.put("yacute", new Character((char) 253)); entities.put("thorn", new Character((char) 254)); entities.put("yuml", new Character((char) 255)); //symbols from http://de.selfhtml.org/html/referenz/zeichen.htm //greek letters entities.put("Alpha", new Character((char) 913)); entities.put("Beta", new Character((char) 914)); entities.put("Gamma", new Character((char) 915)); entities.put("Delta", new Character((char) 916)); entities.put("Epsilon", new Character((char) 917)); entities.put("Zeta", new Character((char) 918)); entities.put("Eta", new Character((char) 919)); entities.put("Theta", new Character((char) 920)); entities.put("Iota", new Character((char) 921)); entities.put("Kappa", new Character((char) 922)); entities.put("Lambda", new Character((char) 923)); entities.put("Mu", new Character((char) 924)); entities.put("Nu", new Character((char) 925)); entities.put("Xi", new Character((char) 926)); entities.put("Omicron", new Character((char) 927)); entities.put("Pi", new Character((char) 928)); entities.put("Rho", new Character((char) 929)); entities.put("Sigma", new Character((char) 930)); entities.put("Sigmaf", new Character((char) 931)); entities.put("Tau", new Character((char) 932)); entities.put("Upsilon", new Character((char) 933)); entities.put("Phi", new Character((char) 934)); entities.put("Chi", new Character((char) 935)); entities.put("Psi", new Character((char) 936)); entities.put("Omega", new Character((char) 937)); entities.put("alpha", new Character((char) 945)); entities.put("beta", new Character((char) 946)); entities.put("gamma", new Character((char) 947)); entities.put("delta", new Character((char) 948)); entities.put("epsilon", new Character((char) 949)); entities.put("zeta", new Character((char) 950)); entities.put("eta", new Character((char) 951)); entities.put("theta", new Character((char) 952)); entities.put("iota", new Character((char) 953)); entities.put("kappa", new Character((char) 954)); entities.put("lambda", new Character((char) 955)); entities.put("mu", new Character((char) 956)); entities.put("nu", new Character((char) 957)); entities.put("xi", new Character((char) 958)); entities.put("omicron", new Character((char) 959)); entities.put("pi", new Character((char) 960)); entities.put("rho", new Character((char) 961)); entities.put("sigma", new Character((char) 962)); entities.put("sigmaf", new Character((char) 963)); entities.put("tau", new Character((char) 964)); entities.put("upsilon", new Character((char) 965)); entities.put("phi", new Character((char) 966)); entities.put("chi", new Character((char) 967)); entities.put("psi", new Character((char) 968)); entities.put("omega", new Character((char) 969)); entities.put("thetasym", new Character((char) 977)); entities.put("upsih", new Character((char) 978)); entities.put("piv", new Character((char) 982)); //math symbols entities.put("forall", new Character((char) 8704)); entities.put("part", new Character((char) 8706)); entities.put("exist", new Character((char) 8707)); entities.put("empty", new Character((char) 8709)); entities.put("nabla", new Character((char) 8711)); entities.put("isin", new Character((char) 8712)); entities.put("notin", new Character((char) 8713)); entities.put("ni", new Character((char) 8715)); entities.put("prod", new Character((char) 8719)); entities.put("sum", new Character((char) 8721)); entities.put("minus", new Character((char) 8722)); entities.put("lowast", new Character((char) 8727)); entities.put("radic", new Character((char) 8730)); entities.put("prop", new Character((char) 8733)); entities.put("infin", new Character((char) 8734)); entities.put("ang", new Character((char) 8736)); entities.put("and", new Character((char) 8743)); entities.put("or", new Character((char) 8744)); entities.put("cap", new Character((char) 8745)); entities.put("cup", new Character((char) 8746)); entities.put("int", new Character((char) 8747)); entities.put("there4", new Character((char) 8756)); entities.put("sim", new Character((char) 8764)); entities.put("cong", new Character((char) 8773)); entities.put("asymp", new Character((char) 8776)); entities.put("ne", new Character((char) 8800)); entities.put("equiv", new Character((char) 8801)); entities.put("le", new Character((char) 8804)); entities.put("ge", new Character((char) 8805)); entities.put("sub", new Character((char) 8834)); entities.put("sup", new Character((char) 8835)); entities.put("nsub", new Character((char) 8836)); entities.put("sube", new Character((char) 8838)); entities.put("supe", new Character((char) 8839)); entities.put("oplus", new Character((char) 8853)); entities.put("otimes", new Character((char) 8855)); entities.put("perp", new Character((char) 8869)); entities.put("sdot", new Character((char) 8901)); entities.put("loz", new Character((char) 9674)); //technical symbols entities.put("lceil", new Character((char) 8968)); entities.put("rceil", new Character((char) 8969)); entities.put("lfloor", new Character((char) 8970)); entities.put("rfloor", new Character((char) 8971)); entities.put("lang", new Character((char) 9001)); entities.put("rang", new Character((char) 9002)); //arrow symbols entities.put("larr", new Character((char) 8592)); entities.put("uarr", new Character((char) 8593)); entities.put("rarr", new Character((char) 8594)); entities.put("darr", new Character((char) 8595)); entities.put("harr", new Character((char) 8596)); entities.put("crarr", new Character((char) 8629)); entities.put("lArr", new Character((char) 8656)); entities.put("uArr", new Character((char) 8657)); entities.put("rArr", new Character((char) 8658)); entities.put("dArr", new Character((char) 8659)); entities.put("hArr", new Character((char) 8960)); //divers symbols entities.put("bull", new Character((char) 8226)); entities.put("prime", new Character((char) 8242)); entities.put("Prime", new Character((char) 8243)); entities.put("oline", new Character((char) 8254)); entities.put("weierp", new Character((char) 8472)); entities.put("image", new Character((char) 8465)); entities.put("real", new Character((char) 8476)); entities.put("trade", new Character((char) 8482)); entities.put("euro", new Character((char) 8364)); entities.put("alefsym", new Character((char) 8501)); entities.put("spades", new Character((char) 9824)); entities.put("clubs", new Character((char) 9827)); entities.put("hearts", new Character((char) 9829)); entities.put("diams", new Character((char) 9830)); //ext lat symbols entities.put("OElig", new Character((char) 338)); entities.put("oelig", new Character((char) 339)); entities.put("Scaron", new Character((char) 352)); entities.put("scaron", new Character((char) 353)); entities.put("fnof", new Character((char) 402)); //interpunction entities.put("ensp", new Character((char) 8194)); entities.put("emsp", new Character((char) 8195)); entities.put("thinsp", new Character((char) 8201)); entities.put("zwnj", new Character((char) 8204)); entities.put("zwj", new Character((char) 8205)); entities.put("lrm", new Character((char) 8206)); entities.put("rlm", new Character((char) 8207)); entities.put("sbquo", new Character((char) 8218)); entities.put("ldquo", new Character((char) 8220)); entities.put("rdquo", new Character((char) 8221)); entities.put("bdquo", new Character((char) 8222)); entities.put("dagger", new Character((char) 8224)); entities.put("Dagger", new Character((char) 8225)); entities.put("hellip", new Character((char) 8230)); entities.put("permil", new Character((char) 8240)); entities.put("lsaquo", new Character((char) 8249)); entities.put("rsaquo", new Character((char) 8250)); //diacrit symb entities.put("circ", new Character((char) 710)); entities.put("tilde", new Character((char) 732)); Map elementInfos = ELEMENT_INFOS; elementInfos.put("NOSCRIPT", new ElementInfo(true, ElementInfo.END_ELEMENT_REQUIRED, null, true)); ElementInfo optionalEndElement = new ElementInfo(true, ElementInfo.END_ELEMENT_OPTIONAL); ElementInfo forbiddenEndElement = new ElementInfo(false, ElementInfo.END_ELEMENT_FORBIDDEN); ElementInfo onlyTextDE = new ElementInfo(false, ElementInfo.END_ELEMENT_REQUIRED, true); ElementInfo onlyText = new ElementInfo(false, ElementInfo.END_ELEMENT_REQUIRED, false); Set tableCellStopElements = new HashSet(); tableCellStopElements.add("TH"); tableCellStopElements.add("TD"); tableCellStopElements.add("TR"); ElementInfo tableCellElement = new ElementInfo(true, ElementInfo.END_ELEMENT_OPTIONAL, tableCellStopElements); Set headStopElements = new HashSet(); headStopElements.add("BODY"); headStopElements.add("DIV"); headStopElements.add("SPAN"); headStopElements.add("TABLE"); ElementInfo headElement = new ElementInfo(true, ElementInfo.END_ELEMENT_OPTIONAL, headStopElements); Set optionStopElements = new HashSet(); optionStopElements.add("OPTION"); optionStopElements.add("SELECT"); ElementInfo optionElement = new ElementInfo(true, ElementInfo.END_ELEMENT_OPTIONAL, optionStopElements); Set paragraphStopElements = new HashSet(); paragraphStopElements.add("P"); paragraphStopElements.add("DIV"); paragraphStopElements.add("TABLE"); paragraphStopElements.add("PRE"); paragraphStopElements.add("UL"); paragraphStopElements.add("OL"); ElementInfo paragraphElement = new ElementInfo(true, ElementInfo.END_ELEMENT_OPTIONAL, paragraphStopElements); // Set liStopElements = new HashSet(); // liStopElements.add("LI"); // liStopElements.add("UL"); // liStopElements.add("OL"); elementInfos.put("SCRIPT", onlyText); elementInfos.put("STYLE", onlyText); elementInfos.put("TEXTAREA", onlyTextDE); elementInfos.put("IMG", forbiddenEndElement); elementInfos.put("META", forbiddenEndElement); elementInfos.put("LINK", forbiddenEndElement); elementInfos.put("BASE", forbiddenEndElement); elementInfos.put("INPUT", forbiddenEndElement); elementInfos.put("FRAME", forbiddenEndElement); elementInfos.put("BR", forbiddenEndElement); elementInfos.put("HR", forbiddenEndElement); elementInfos.put("EMBED", forbiddenEndElement); elementInfos.put("SPACER", forbiddenEndElement); elementInfos.put("P", paragraphElement); elementInfos.put("LI", optionalEndElement); elementInfos.put("DT", optionalEndElement); elementInfos.put("DD", optionalEndElement); elementInfos.put("TR", optionalEndElement); elementInfos.put("TH", tableCellElement); elementInfos.put("TD", tableCellElement); elementInfos.put("HEAD", headElement); elementInfos.put("OPTION", optionElement); // Note: The specification states anchors have // a required end element, but browsers generally behave // as if it's optional. elementInfos.put("A", optionalEndElement); elementInfos.put("ANCHOR", optionalEndElement); //TODO: Keep adding tags here } /** * Constructs a HtmlParser. * @param document A W3C Document instance. * @param errorHandler The error handler. * @param publicId The public ID of the document. * @param systemId The system ID of the document. * @deprecated UserAgentContext should be passed in constructor. */ public HtmlParser(Document document, ErrorHandler errorHandler, String publicId, String systemId) { this.ucontext = null; this.document = document; this.errorHandler = errorHandler; this.publicId = publicId; this.systemId = systemId; } /** * Constructs a HtmlParser. * @param ucontext The user agent context. * @param document An W3C Document instance. * @param errorHandler The error handler. * @param publicId The public ID of the document. * @param systemId The system ID of the document. */ public HtmlParser(UserAgentContext ucontext, Document document, ErrorHandler errorHandler, String publicId, String systemId) { this.ucontext = ucontext; this.document = document; this.errorHandler = errorHandler; this.publicId = publicId; this.systemId = systemId; } /** * Constructs a HtmlParser. * @param ucontext The user agent context. * @param document A W3C Document instance. */ public HtmlParser(UserAgentContext ucontext, Document document) { this.ucontext = ucontext; this.document = document; this.errorHandler = null; this.publicId = null; this.systemId = null; } public static boolean isDecodeEntities(String elementName) { ElementInfo einfo = (ElementInfo) ELEMENT_INFOS.get(elementName.toUpperCase()); return einfo == null ? true : einfo.decodeEntities; } /** * Parses HTML from an input stream, assuming * the character set is ISO-8859-1. * @param in The input stream. * @throws IOException Thrown when there are errors reading the stream. * @throws SAXException Thrown when there are parse errors. */ public void parse(InputStream in) throws IOException,SAXException,UnsupportedEncodingException { this.parse(in, "ISO-8859-1"); } /** * Parses HTML from an input stream, using the given character set. * @param in The input stream. * @param charset The character set. * @throws IOException Thrown when there's an error reading from the stream. * @throws SAXException Thrown when there is a parser error. * @throws UnsupportedEncodingException Thrown if the character set is not supported. */ public void parse(InputStream in, String charset) throws IOException,SAXException,UnsupportedEncodingException { WritableLineReader reader = new WritableLineReader(new InputStreamReader(in, charset)); this.parse(reader); } /** * Parses HTML given by a Reader. This method appends * nodes to the document provided to the parser. * @param reader An instance of Reader. * @throws IOException Thrown if there are errors reading the input stream. * @throws SAXException Thrown if there are parse errors. */ public void parse(Reader reader) throws IOException, SAXException { this.parse(new LineNumberReader(reader)); } public void parse(LineNumberReader reader) throws IOException, SAXException { Document doc = this.document; this.parse(reader, doc); } /** * This method may be used when the DOM should be built under * a given node, such as when innerHTML is used * in Javascript. * @param reader A document reader. * @param parent The root node for the parsed DOM. * @throws IOException * @throws SAXException */ public void parse(Reader reader, Node parent) throws IOException, SAXException { this.parse(new LineNumberReader(reader), parent); } /** * This method may be used when the DOM should be built under * a given node, such as when innerHTML is used * in Javascript. * @param reader A LineNumberReader for the document. * @param parent The root node for the parsed DOM. * @throws IOException * @throws SAXException */ public void parse(LineNumberReader reader, Node parent) throws IOException, SAXException { // Note: Parser does not clear document. It could be used incrementally. try { parent.setUserData(MODIFYING_KEY, Boolean.TRUE, null); try { while(this.parseToken(parent, reader, null, new LinkedList()) != TOKEN_EOD) {;} } catch(StopException se) { throw new SAXException("Unexpected flow exception", se); } } finally { parent.setUserData(MODIFYING_KEY, Boolean.FALSE, null); } } private static final int TOKEN_EOD = 0; private static final int TOKEN_COMMENT = 1; private static final int TOKEN_TEXT = 2; private static final int TOKEN_BEGIN_ELEMENT = 3; private static final int TOKEN_END_ELEMENT = 4; private static final int TOKEN_FULL_ELEMENT = 5; private static final int TOKEN_BAD = 6; private String normalLastTag = null; private boolean justReadTagBegin = false; private boolean justReadTagEnd = false; /** * Only set when readAttribute returns false. */ private boolean justReadEmptyElement = false; /** * Parses text followed by one element. * @param parent * @param reader * @param stopAtTagUC If this tag is encountered, the method throws StopException. * @param stopTags If tags in this set are encountered, the method throws StopException. * @return * @throws IOException * @throws StopException * @throws SAXException */ private final int parseToken(Node parent, LineNumberReader reader, Set stopTags, LinkedList ancestors) throws IOException, StopException, SAXException { Document doc = this.document; StringBuffer textSb = this.readUpToTagBegin(reader); if(textSb == null) { return TOKEN_EOD; } if(textSb.length() != 0) { //int textLine = reader.getLineNumber(); StringBuffer decText = this.entityDecode(textSb); Node textNode = doc.createTextNode(decText.toString()); try { parent.appendChild(textNode); } catch(DOMException de) { if(parent.getNodeType() != Node.DOCUMENT_NODE || de.code != DOMException.HIERARCHY_REQUEST_ERR) { logger.log(Level.WARNING, "parseToken(): Unable to append child to " + parent + ".", de); } } } if(this.justReadTagBegin) { String tag = this.readTag(parent, reader); if(tag == null) { return TOKEN_EOD; } String normalTag = tag.toUpperCase(); try { if(tag.startsWith("!")) { if("!--".equals(tag)) { //int commentLine = reader.getLineNumber(); StringBuffer comment = this.passEndOfComment(reader); StringBuffer decText = this.entityDecode(comment); parent.appendChild(doc.createComment(decText.toString())); return TOKEN_COMMENT; } else { //TODO: DOCTYPE node this.passEndOfTag(reader); return TOKEN_BAD; } } else if(tag.startsWith("/")) { tag = tag.substring(1); normalTag = normalTag.substring(1); this.passEndOfTag(reader); return TOKEN_END_ELEMENT; } else if (tag.startsWith("?")) { tag = tag.substring(1); StringBuffer data = readProcessingInstruction(reader); parent.appendChild(doc.createProcessingInstruction(tag, data.toString())); return TOKEN_FULL_ELEMENT; } else { Element element = doc.createElement(tag); element.setUserData(MODIFYING_KEY, Boolean.TRUE, null); try { if(!this.justReadTagEnd) { while(this.readAttribute(reader, element)) {;} } if(stopTags != null && stopTags.contains(normalTag)) { // Throw before appending to parent. // After attributes are set. // After MODIFYING_KEY is set. throw new StopException(element); } // Add element to parent before children are added. // This is necessary for incremental rendering. parent.appendChild(element); if(!this.justReadEmptyElement) { ElementInfo einfo = (ElementInfo) ELEMENT_INFOS.get(normalTag); int endTagType = einfo == null ? ElementInfo.END_ELEMENT_REQUIRED : einfo.endElementType; if(endTagType != ElementInfo.END_ELEMENT_FORBIDDEN) { boolean childrenOk = einfo == null ? true : einfo.childElementOk; Set newStopSet = einfo == null ? null : einfo.stopTags; if(newStopSet == null) { if(endTagType == ElementInfo.END_ELEMENT_OPTIONAL) { newStopSet = Collections.singleton(normalTag); } } if(stopTags != null) { if(newStopSet != null) { Set newStopSet2 = new HashSet(); newStopSet2.addAll(stopTags); newStopSet2.addAll(newStopSet); newStopSet = newStopSet2; } else { newStopSet = endTagType == ElementInfo.END_ELEMENT_REQUIRED ? null : stopTags; } } ancestors.addFirst(normalTag); try { for(;;) { try { int token; if(einfo != null && einfo.noScriptElement) { UserAgentContext ucontext = this.ucontext; if(ucontext == null || ucontext.isScriptingEnabled()) { token = this.parseForEndTag(parent, reader, tag, false, einfo.decodeEntities); } else { token = this.parseToken(element, reader, newStopSet, ancestors); } } else { token = childrenOk ? this.parseToken(element, reader, newStopSet, ancestors) : this.parseForEndTag(element, reader, tag, true, einfo.decodeEntities); } if(token == TOKEN_END_ELEMENT) { String normalLastTag = this.normalLastTag; if(normalTag.equals(normalLastTag)) { return TOKEN_FULL_ELEMENT; } else { ElementInfo closeTagInfo = (ElementInfo) ELEMENT_INFOS.get(normalLastTag); if(closeTagInfo == null || closeTagInfo.endElementType != ElementInfo.END_ELEMENT_FORBIDDEN) { //TODO: Rather inefficient algorithm, but it's probably executed infrequently? Iterator i = ancestors.iterator(); if(i.hasNext()) { i.next(); while(i.hasNext()) { String normalAncestorTag = (String) i.next(); if(normalLastTag.equals(normalAncestorTag)) { normalTag = normalLastTag; return TOKEN_END_ELEMENT; } } } } //TODO: Working here } } else if(token == TOKEN_EOD) { return TOKEN_EOD; } } catch(StopException se) { // newElement does not have a parent. Element newElement = se.getElement(); tag = newElement.getTagName(); normalTag = tag.toUpperCase(); // If a subelement throws StopException with // a tag matching the current stop tag, the exception // is rethrown (e.g. blahblah) if(stopTags != null && stopTags.contains(normalTag)) { throw se; } einfo = (ElementInfo) ELEMENT_INFOS.get(normalTag); endTagType = einfo == null ? ElementInfo.END_ELEMENT_REQUIRED : einfo.endElementType; childrenOk = einfo == null ? true : einfo.childElementOk; newStopSet = einfo == null ? null : einfo.stopTags; if(newStopSet == null) { if(endTagType == ElementInfo.END_ELEMENT_OPTIONAL) { newStopSet = Collections.singleton(normalTag); } } if(stopTags != null && newStopSet != null) { Set newStopSet2 = new HashSet(); newStopSet2.addAll(stopTags); newStopSet2.addAll(newStopSet); newStopSet = newStopSet2; } ancestors.removeFirst(); ancestors.addFirst(normalTag); //Switch element element.setUserData(MODIFYING_KEY, Boolean.FALSE, null); //newElement should have been suspended. element = newElement; // Add to parent parent.appendChild(element); if(this.justReadEmptyElement) { return TOKEN_BEGIN_ELEMENT; } } } } finally { ancestors.removeFirst(); } } } return TOKEN_BEGIN_ELEMENT; } finally { // This can inform elements to continue with notifications. // It can also cause Javascript to get processed. element.setUserData(MODIFYING_KEY, Boolean.FALSE, null); } } } finally { this.normalLastTag = normalTag; } } else { this.normalLastTag = null; return TOKEN_TEXT; } } /** * Reads text until the beginning of the next tag. * Leaves the reader offset past the opening angle bracket. * Returns null only on EOF. */ private final StringBuffer readUpToTagBegin(LineNumberReader reader) throws IOException, SAXException{ StringBuffer sb = null; int intCh; while((intCh = reader.read()) != -1) { char ch = (char) intCh; if(ch == '<') { this.justReadTagBegin = true; this.justReadTagEnd = false; this.justReadEmptyElement = false; if(sb == null) { sb = new StringBuffer(0); } return sb; } if(sb == null) { sb = new StringBuffer(); } sb.append(ch); } this.justReadTagBegin = false; this.justReadTagEnd = false; this.justReadEmptyElement = false; return sb; } /** * Assumes that the content is completely made up of text, * and parses until an ending tag is found. * @param parent * @param reader * @param tagName * @return * @throws IOException */ private final int parseForEndTag(Node parent, LineNumberReader reader, String tagName, boolean addTextNode, boolean decodeEntities) throws IOException, SAXException { Document doc = this.document; int intCh; StringBuffer sb = new StringBuffer(); while((intCh = reader.read()) != -1) { char ch = (char) intCh; if(ch == '<') { intCh = reader.read(); if(intCh != -1) { ch = (char) intCh; if(ch == '/') { StringBuffer tempBuffer = new StringBuffer(); INNER: while((intCh = reader.read()) != -1) { ch = (char) intCh; if(ch == '>') { String thisTag = tempBuffer.toString().trim(); if(thisTag.equalsIgnoreCase(tagName)) { this.justReadTagBegin = false; this.justReadTagEnd = true; this.justReadEmptyElement = false; this.normalLastTag = thisTag.toUpperCase(); if(addTextNode) { if(decodeEntities) { sb = this.entityDecode(sb); } String text = sb.toString(); if(text.length() != 0) { Node textNode = doc.createTextNode(text); parent.appendChild(textNode); } } return HtmlParser.TOKEN_END_ELEMENT; } else { break INNER; } } else { tempBuffer.append(ch); } } sb.append("') { this.justReadTagEnd = true; this.justReadTagBegin = false; this.justReadEmptyElement = lastCharSlash; String tag = sb.toString(); return tag; } else if (ch == '/') { lastCharSlash = true; } else { if(lastCharSlash) { sb.append('/'); } lastCharSlash = false; sb.append(ch); } chInt = reader.read(); if(chInt == -1) { break; } ch = (char) chInt; } } } if(sb.length() > 0) { this.justReadTagEnd = false; this.justReadTagBegin = false; this.justReadEmptyElement = false; } String tag = sb.toString(); return tag; } private final StringBuffer passEndOfComment(LineNumberReader reader) throws IOException { if(this.justReadTagEnd) { return new StringBuffer(0); } StringBuffer sb = new StringBuffer(); OUTER: for(;;) { int chInt = reader.read(); if(chInt == -1) { break OUTER; } char ch = (char) chInt; if(ch == '-') { chInt = reader.read(); if(chInt == -1) { sb.append(ch); break OUTER; } ch = (char) chInt; if(ch == '-') { StringBuffer extra = null; INNER: for(;;) { chInt = reader.read(); if(chInt == -1) { if(extra != null) { sb.append(extra.toString()); } break OUTER; } ch = (char) chInt; if(ch == '>') { this.justReadTagBegin = false; this.justReadTagEnd = true; return sb; } else if(ch == '-') { // Allow any number of dashes at the end if(extra == null) { extra = new StringBuffer(); extra.append("--"); } extra.append("-"); } else if(Character.isWhitespace(ch)) { if(extra == null) { extra = new StringBuffer(); extra.append("--"); } extra.append(ch); } else { if(extra != null) { sb.append(extra.toString()); } sb.append(ch); break INNER; } } } else { sb.append('-'); sb.append(ch); } } else { sb.append(ch); } } if(sb.length() > 0) { this.justReadTagBegin = false; this.justReadTagEnd = false; } return sb; } private final void passEndOfTag(Reader reader) throws IOException { if(this.justReadTagEnd) { return; } boolean readSomething = false; for(;;) { int chInt = reader.read(); if(chInt == -1) { break; } readSomething = true; char ch = (char) chInt; if(ch == '>') { this.justReadTagEnd = true; this.justReadTagBegin = false; return; } } if(readSomething) { this.justReadTagBegin = false; this.justReadTagEnd = false; } } private final StringBuffer readProcessingInstruction(LineNumberReader reader) throws IOException { StringBuffer pidata = new StringBuffer(); if(this.justReadTagEnd) { return pidata; } int ch; for(ch = reader.read();ch != -1 && ch != '>'; ch = reader.read()) { pidata.append((char)ch); } this.justReadTagBegin = false; this.justReadTagEnd = ch != -1; return pidata; } private final boolean readAttribute(LineNumberReader reader, Element element) throws IOException, SAXException { if(this.justReadTagEnd) { return false; } // Read attribute name up to '=' character. // May read several attribute names without explicit values. StringBuffer attributeName = null; boolean blankFound = false; boolean lastCharSlash = false; for(;;) { int chInt = reader.read(); if(chInt == -1) { if(attributeName != null && attributeName.length() != 0) { String attributeNameStr = attributeName.toString(); element.setAttribute(attributeNameStr, attributeNameStr); attributeName.setLength(0); } this.justReadTagBegin = false; this.justReadTagEnd = false; this.justReadEmptyElement = false; return false; } char ch = (char) chInt; if(ch == '=') { lastCharSlash = false; blankFound = false; break; } else if(ch == '>') { if(attributeName != null && attributeName.length() != 0) { String attributeNameStr = attributeName.toString(); element.setAttribute(attributeNameStr, attributeNameStr); } this.justReadTagBegin = false; this.justReadTagEnd = true; this.justReadEmptyElement = lastCharSlash; return false; } else if(ch == '/') { blankFound = true; lastCharSlash = true; } else if(Character.isWhitespace(ch)) { lastCharSlash = false; blankFound = true; } else { lastCharSlash = false; if(blankFound) { blankFound = false; if(attributeName != null && attributeName.length() != 0) { String attributeNameStr = attributeName.toString(); element.setAttribute(attributeNameStr, attributeNameStr); attributeName.setLength(0); } } if(attributeName == null) { attributeName = new StringBuffer(6); } attributeName.append(ch); } } // Read blanks up to open quote or first non-blank. StringBuffer attributeValue = null; int openQuote = -1; for(;;) { int chInt = reader.read(); if(chInt == -1) { break; } char ch = (char) chInt; if(ch == '>') { if(attributeName != null && attributeName.length() != 0) { String attributeNameStr = attributeName.toString(); element.setAttribute(attributeNameStr, attributeNameStr); } this.justReadTagBegin = false; this.justReadTagEnd = true; this.justReadEmptyElement = lastCharSlash; return false; } else if(ch == '/') { lastCharSlash = true; } else if(Character.isWhitespace(ch)) { lastCharSlash = false; } else { lastCharSlash = false; if(ch == '"') { openQuote = '"'; } else if(ch == '\'') { openQuote = '\''; } else { openQuote = -1; if(attributeValue == null) { attributeValue = new StringBuffer(6); } attributeValue.append(ch); } break; } } // Read attribute value for(;;) { int chInt = reader.read(); if(chInt == -1) { break; } char ch = (char) chInt; if(openQuote != -1 && ch == openQuote) { lastCharSlash = false; if(attributeName != null) { String attributeNameStr = attributeName.toString(); if(attributeValue == null) { // Quotes are closed. There's a distinction // between blank values and null in HTML, as // processed by major browsers. element.setAttribute(attributeNameStr, ""); } else { StringBuffer actualAttributeValue = this.entityDecode(attributeValue); element.setAttribute(attributeNameStr, actualAttributeValue.toString()); } } this.justReadTagBegin = false; this.justReadTagEnd = false; return true; } else if(openQuote == -1 && ch == '>') { if(attributeName != null) { String attributeNameStr = attributeName.toString(); if(attributeValue == null) { element.setAttribute(attributeNameStr, null); } else { StringBuffer actualAttributeValue = this.entityDecode(attributeValue); element.setAttribute(attributeNameStr, actualAttributeValue.toString()); } } this.justReadTagBegin = false; this.justReadTagEnd = true; this.justReadEmptyElement = lastCharSlash; return false; } else if(openQuote == -1 && Character.isWhitespace(ch)) { lastCharSlash = false; if(attributeName != null) { String attributeNameStr = attributeName.toString(); if(attributeValue == null) { element.setAttribute(attributeNameStr, null); } else { StringBuffer actualAttributeValue = this.entityDecode(attributeValue); element.setAttribute(attributeNameStr, actualAttributeValue.toString()); } } this.justReadTagBegin = false; this.justReadTagEnd = false; return true; } else { if(attributeValue == null) { attributeValue = new StringBuffer(6); } if(lastCharSlash) { attributeValue.append('/'); } lastCharSlash = false; attributeValue.append(ch); } } this.justReadTagBegin = false; this.justReadTagEnd = false; if(attributeName != null) { String attributeNameStr = attributeName.toString(); if(attributeValue == null) { element.setAttribute(attributeNameStr, null); } else { StringBuffer actualAttributeValue = this.entityDecode(attributeValue); element.setAttribute(attributeNameStr, actualAttributeValue.toString()); } } return false; } private final StringBuffer entityDecode(StringBuffer rawText) throws org.xml.sax.SAXException { int startIdx = 0; StringBuffer sb = null; for(;;) { int ampIdx = rawText.indexOf("&", startIdx); if(ampIdx == -1) { if(sb == null) { return rawText; } else { sb.append(rawText.substring(startIdx)); return sb; } } if(sb == null) { sb = new StringBuffer(); } sb.append(rawText.substring(startIdx, ampIdx)); int colonIdx = rawText.indexOf(";", ampIdx); if(colonIdx == -1) { sb.append('&'); startIdx = ampIdx+1; continue; } String spec = rawText.substring(ampIdx+1, colonIdx); if(spec.startsWith("#")) { String number = spec.substring(1).toLowerCase(); int decimal; try { if(number.startsWith("x")) { decimal = Integer.parseInt(number.substring(1), 16); } else { decimal = Integer.parseInt(number); } } catch(NumberFormatException nfe) { logger.log(Level.WARNING, "entityDecode()", nfe); decimal = 0; } sb.append((char) decimal); } else { int chInt = this.getEntityChar(spec); if(chInt == -1) { sb.append('&'); sb.append(spec); sb.append(';'); } else { sb.append((char) chInt); } } startIdx = colonIdx+1; } } private final Locator getLocator(int lineNumber, int columnNumber) { return new LocatorImpl(this.publicId, this.systemId, lineNumber, columnNumber); } private final int getEntityChar(String spec) { //TODO: Declared entities Character c = (Character) ENTITIES.get(spec); if(c == null) { String specTL = spec.toLowerCase(); c = (Character) ENTITIES.get(specTL); if(c == null) { return -1; } } return (int) c.charValue(); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/parser/InputSourceImpl.java0000644000175000017500000000603010766167640027343 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 22, 2005 */ package org.lobobrowser.html.parser; import java.io.InputStream; import java.io.Reader; import org.xml.sax.InputSource; /** * The InputSourceImpl class implements * the InputSource interface. * @author J. H. S. */ public class InputSourceImpl extends InputSource { /** * Constructs an InputSourceImpl. * @deprecated Use a constructor that takes either a stream or a reader. */ public InputSourceImpl() { super(); } /** * Constructs an InputSourceImpl. *

* It is valid to use this constructor, but it * is generally recommended that callers use * one of the constructors that take a reader * or an input stream instead. * @param uri The URI (or systemID) of the document. */ public InputSourceImpl(String uri) { super(uri); } /** * Constructs an InputSourceImpl. * @param byteStream The input stream where content can be read. * @deprecated Use constructor with uri parameter. */ public InputSourceImpl(InputStream byteStream) { super(byteStream); } /** * Constructs an InputSourceImpl. * @param characterStream The Reader where characters can be read. * @deprecated Use constructor with uri parameter. */ public InputSourceImpl(Reader characterStream) { super(characterStream); } /** * Constructs an InputSourceImpl. * @param characterStream The Reader where characters can be read. * @param uri The URI of the document. */ public InputSourceImpl(Reader characterStream, String uri) { super(characterStream); this.setSystemId(uri); } /** * Constructs an InputSourceImpl. * @param byteStream The input stream where content can be read. * @param uri The URI that identifies the content. * @param charset The character set of the input stream. */ public InputSourceImpl(InputStream byteStream, String uri, String charset) { super(byteStream); this.setEncoding(charset); this.setSystemId(uri); this.setPublicId(uri); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/parser/LocatorImpl.java0000644000175000017500000000325210726473500026460 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 16, 2005 */ package org.lobobrowser.html.parser; import org.xml.sax.Locator; class LocatorImpl implements Locator { private final String publicId; private final String systemId; private final int lineNumber; private final int columnNumber; /** * @param pid * @param sid * @param lnumber * @param cnumber */ public LocatorImpl(String pid, String sid, int lnumber, int cnumber) { super(); publicId = pid; systemId = sid; lineNumber = lnumber; columnNumber = cnumber; } public String getPublicId() { return this.publicId; } public String getSystemId() { return this.systemId; } public int getLineNumber() { return this.lineNumber; } public int getColumnNumber() { return this.columnNumber; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/parser/StopException.java0000644000175000017500000000236410726473500027042 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 23, 2005 */ package org.lobobrowser.html.parser; import org.w3c.dom.Element; class StopException extends Exception { private final Element element; /** * @param element */ public StopException(Element element) { super(); this.element = element; } public Element getElement() { return this.element; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/parser/package.html0000644000175000017500000000015310712365602025644 0ustar twernertwernerContains HTML parser classes. libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/0000755000175000017500000000000011132567050023674 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/BaseBoundableRenderable.java0000644000175000017500000002226411130406144031211 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 17, 2005 */ package org.lobobrowser.html.renderer; import java.awt.*; import java.awt.event.MouseEvent; import org.lobobrowser.html.domimpl.*; import java.util.logging.*; /** * @author J. H. S. */ abstract class BaseBoundableRenderable extends BaseRenderable implements BoundableRenderable { protected static final Logger logger = Logger.getLogger(BaseBoundableRenderable.class.getName()); protected static final Color SELECTION_COLOR = Color.BLUE; protected static final Color SELECTION_XOR = Color.LIGHT_GRAY; //protected final Rectangle bounds = new Rectangle(); protected final RenderableContainer container; protected final ModelNode modelNode; public int x, y, width, height; /** * Starts as true because ancestors could be invalidated. */ protected boolean layoutUpTreeCanBeInvalidated = true; public void markLayoutValid() { this.layoutUpTreeCanBeInvalidated = true; } public BaseBoundableRenderable(RenderableContainer container, ModelNode modelNode) { this.container = container; this.modelNode = modelNode; } public java.awt.Point getGUIPoint(int clientX, int clientY) { Renderable parent = this.getParent(); if(parent instanceof BoundableRenderable) { return ((BoundableRenderable) parent).getGUIPoint(clientX + this.x, clientY + this.y); } else if(parent == null) { return this.container.getGUIPoint(clientX + this.x, clientY + this.y); } else { throw new IllegalStateException("parent=" + parent); } } public Point getRenderablePoint(int guiX, int guiY) { Renderable parent = this.getParent(); if(parent instanceof BoundableRenderable) { return ((BoundableRenderable) parent).getRenderablePoint(guiX - this.x, guiY - this.y); } else if(parent == null) { return new Point(guiX - this.x, guiY - this.y); } else { throw new IllegalStateException("parent=" + parent); } } public int getHeight() { return height; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getX() { return x; } public int getY() { return y; } public boolean contains(int x, int y) { return x >= this.x && y >= this.y && x < this.x + this.width && y < this.y + this.height; } public Rectangle getBounds() { return new Rectangle(this.x, this.y, this.width, this.height); } public Dimension getSize() { return new Dimension(this.width, this.height); } public ModelNode getModelNode() { return this.modelNode; } // /* (non-Javadoc) // * @see net.sourceforge.xamj.domimpl.markup.Renderable#getBounds() // */ // public Rectangle getBounds() { // return this.bounds; // } // public void setBounds(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public void setHeight(int height) { this.height = height; } public void setOrigin(int x, int y) { this.x = x; this.y = y; } protected abstract void invalidateLayoutLocal(); /** * Invalidates this Renderable and its parent (i.e. all * ancestors). */ public final void invalidateLayoutUpTree() { if(this.layoutUpTreeCanBeInvalidated) { this.layoutUpTreeCanBeInvalidated = false; this.invalidateLayoutLocal(); // Try original parent first. RCollection parent = this.originalParent; if(parent == null) { parent = this.parent; if(parent == null) { // Has to be top block RenderableContainer rc = this.container; if(rc != null) { rc.invalidateLayoutUpTree(); } } else { parent.invalidateLayoutUpTree(); } } else { parent.invalidateLayoutUpTree(); } } else { } } protected boolean isValid() { return this.layoutUpTreeCanBeInvalidated; } private final void relayoutImpl(boolean invalidateLocal, boolean onlyIfValid) { if(onlyIfValid && !this.layoutUpTreeCanBeInvalidated) { return; } if(invalidateLocal) { this.invalidateLayoutUpTree(); } Renderable parent = this.parent; if(parent instanceof BaseBoundableRenderable) { ((BaseBoundableRenderable) parent).relayoutImpl(false, false); } else if(parent == null) { // Has to be top RBlock. this.container.relayout(); } else { if(logger.isLoggable(Level.INFO)) { logger.warning("relayout(): Don't know how to relayout " + this + ", parent being " + parent); } } } /** * Invalidates the current Renderable (which invalidates its ancestors) * and then requests the top level GUI container to do the layout and repaint. * It's safe to call this method outside the GUI thread. */ public void relayout() { if(EventQueue.isDispatchThread()) { this.relayoutImpl(true, false); } else { EventQueue.invokeLater(new Runnable() { public void run() { relayoutImpl(true, false); } }); } } public void relayoutIfValid() { if(EventQueue.isDispatchThread()) { this.relayoutImpl(true, true); } else { EventQueue.invokeLater(new Runnable() { public void run() { relayoutImpl(true, true); } }); } } /** * Parent for graphics coordinates. */ protected RCollection parent; public void setParent(RCollection parent) { this.parent = parent; } public RCollection getParent() { return this.parent; } /** * Parent for invalidation. */ protected RCollection originalParent; public void setOriginalParent(RCollection origParent) { this.originalParent = origParent; } /** * This is the parent based on the original element hierarchy. */ public RCollection getOriginalParent() { return this.originalParent; } public RCollection getOriginalOrCurrentParent() { RCollection origParent = this.originalParent; if(origParent == null) { return this.parent; } return origParent; } public void repaint(int x, int y, int width, int height) { Renderable parent = this.parent; if(parent instanceof BoundableRenderable) { ((BoundableRenderable) parent).repaint(x + this.x, y + this.y, width, height); } else if(parent == null) { // Has to be top RBlock. this.container.repaint(x, y, width, height); } else { if(logger.isLoggable(Level.INFO)) { logger.warning("repaint(): Don't know how to repaint " + this + ", parent being " + parent); } } } public void repaint() { this.repaint(0, 0, this.width, this.height); } public Color getBlockBackgroundColor() { return this.container.getPaintedBackgroundColor(); } public final void paintTranslated(Graphics g) { int x = this.x; int y = this.y; g.translate(x, y); try { this.paint(g); } finally { g.translate(-x, -y); } } protected final java.awt.Point translateDescendentPoint(BoundableRenderable descendent, int x, int y) { while(descendent != this) { if(descendent == null) { throw new IllegalStateException("Not descendent"); } x += descendent.getX(); y += descendent.getY(); // Coordinates are always relative to actual parent? descendent = descendent.getParent(); } return new Point(x, y); } public void onMouseOut(MouseEvent event, int x, int y, ModelNode limit) { if(this.isContainedByNode()) { HtmlController.getInstance().onMouseOut(this.modelNode, event, x, y, limit); } } public void onMouseMoved(MouseEvent event, int x, int y, boolean triggerEvent, ModelNode limit) { if(triggerEvent) { if(this.isContainedByNode()) { HtmlController.getInstance().onMouseOver(this.modelNode, event, x, y, limit); } } } public Point getOrigin() { return new Point(this.x, this.y); } public Point getOriginRelativeTo(RCollection ancestor) { int x = this.x; int y = this.y; RCollection parent = this.parent; for(;;) { if(parent == null) { throw new java.lang.IllegalArgumentException("Not an ancestor: " + ancestor); } if(parent == ancestor) { return new Point(x, y); } x += parent.getX(); y += parent.getY(); parent = parent.getParent(); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/BaseControl.java0000644000175000017500000000453710773730560026773 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 23, 2005 */ package org.lobobrowser.html.renderer; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import javax.swing.*; import org.lobobrowser.html.domimpl.*; import java.util.logging.*; abstract class BaseControl extends JComponent implements UIControl { private static final Logger logger = Logger.getLogger(BaseControl.class.getName()); protected static final Dimension ZERO_DIMENSION = new Dimension(0, 0); protected final HTMLElementImpl controlElement; protected RUIControl ruicontrol; /** * @param context */ public BaseControl(HTMLElementImpl modelNode) { this.controlElement = modelNode; } public Component getComponent() { return this; } public void setRUIControl(RUIControl ruicontrol) { this.ruicontrol = ruicontrol; } public int getVAlign() { return RElement.VALIGN_BASELINE; } /** * Method invoked when image changes size. * It's expected to be called outside the GUI thread. */ protected void invalidateAndRepaint() { RUIControl rc = this.ruicontrol; if(rc == null) { logger.severe("invalidateAndPaint(): RUIControl not set."); return; } if(rc.isValid()) { rc.relayout(); } } /* (non-Javadoc) * @see org.xamjwg.html.renderer.UIControl#getBackgroundColor() */ public Color getBackgroundColor() { return this.getBackground(); } public void reset(int availWidth, int availHeight) { } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/BaseElementRenderable.java0000644000175000017500000010015011134665416030713 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; import java.awt.*; import java.awt.image.ImageObserver; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.logging.Level; import org.lobobrowser.util.Strings; import org.lobobrowser.util.gui.*; import org.lobobrowser.html.HttpRequest; import org.lobobrowser.html.ReadyStateChangeListener; import org.lobobrowser.html.UserAgentContext; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.html.style.*; import org.lobobrowser.util.gui.ColorFactory; import org.w3c.dom.css.CSS2Properties; abstract class BaseElementRenderable extends BaseRCollection implements RElement, RenderableContainer, java.awt.image.ImageObserver { protected static final Integer INVALID_SIZE = new Integer(Integer.MIN_VALUE); /** * A collection of all GUI components * added by descendents. */ private Collection guiComponents = null; /** * A list of absolute positioned or * float parent-child pairs. */ protected Collection delayedPairs = null; // protected boolean renderStyleCanBeInvalidated = true; /** * Background color which may be different to * that from RenderState in the case of a Document node. */ protected Color backgroundColor; protected volatile Image backgroundImage; protected int zIndex; protected Color borderTopColor; protected Color borderLeftColor; protected Color borderBottomColor; protected Color borderRightColor; protected Insets borderInsets; protected Insets marginInsets; protected Insets paddingInsets; protected BorderInfo borderInfo; protected java.net.URL lastBackgroundImageUri; protected Insets defaultMarginInsets = null; protected Insets defaultPaddingInsets = null; protected int overflowX; protected int overflowY; protected final UserAgentContext userAgentContext; public BaseElementRenderable(RenderableContainer container, ModelNode modelNode, UserAgentContext ucontext) { super(container, modelNode); this.userAgentContext = ucontext; } public void setDefaultPaddingInsets(Insets insets) { this.defaultPaddingInsets = insets; } public void setDefaultMarginInsets(Insets insets) { this.defaultMarginInsets = insets; } public float getAlignmentX() { return 0.0f; } public float getAlignmentY() { return 0.0f; } protected boolean layoutDeepCanBeInvalidated = false; /** * Invalidates this Renderable and all * descendents. This is only used in special * cases, such as when a new style sheet is * added. */ public final void invalidateLayoutDeep() { if(this.layoutDeepCanBeInvalidated) { this.layoutDeepCanBeInvalidated = false; this.invalidateLayoutLocal(); Iterator i = this.getRenderables(); if(i != null) { while(i.hasNext()) { Object r = i.next(); if(r instanceof RCollection) { ((RCollection) r).invalidateLayoutDeep(); } } } } } protected void invalidateLayoutLocal() { RenderState rs = this.modelNode.getRenderState(); if(rs != null) { rs.invalidate(); } this.overflowX = RenderState.OVERFLOW_NONE; this.overflowY = RenderState.OVERFLOW_NONE; this.declaredWidth = INVALID_SIZE; this.declaredHeight = INVALID_SIZE; this.lastAvailHeightForDeclared = -1; this.lastAvailWidthForDeclared = -1; } private Integer declaredWidth = INVALID_SIZE; private Integer declaredHeight = INVALID_SIZE; private int lastAvailWidthForDeclared = -1; private int lastAvailHeightForDeclared = -1; protected Integer getDeclaredWidth(RenderState renderState, int actualAvailWidth) { Integer dw = this.declaredWidth; if(dw == INVALID_SIZE || actualAvailWidth != this.lastAvailWidthForDeclared) { this.lastAvailWidthForDeclared = actualAvailWidth; int dwInt = this.getDeclaredWidthImpl(renderState, actualAvailWidth); dw = dwInt == -1 ? null : new Integer(dwInt); this.declaredWidth = dw; } return dw; } public final boolean hasDeclaredWidth() { Integer dw = this.declaredWidth; if(dw == INVALID_SIZE) { Object rootNode = this.modelNode; if(rootNode instanceof HTMLElementImpl) { HTMLElementImpl element = (HTMLElementImpl) rootNode; CSS2Properties props = element.getCurrentStyle(); if(props == null) { return false; } return !Strings.isBlank(props.getWidth()); } return false; } return dw != null; } private final int getDeclaredWidthImpl(RenderState renderState, int availWidth) { Object rootNode = this.modelNode; if(rootNode instanceof HTMLElementImpl) { HTMLElementImpl element = (HTMLElementImpl) rootNode; CSS2Properties props = element.getCurrentStyle(); if(props == null) { return -1; } String widthText = props.getWidth(); if(widthText == null || "".equals(widthText)) { return -1; } return HtmlValues.getPixelSize(widthText, renderState, -1, availWidth); } else { return -1; } } protected Integer getDeclaredHeight(RenderState renderState, int actualAvailHeight) { Integer dh = this.declaredHeight; if(dh == INVALID_SIZE || actualAvailHeight != this.lastAvailHeightForDeclared) { this.lastAvailHeightForDeclared = actualAvailHeight; int dhInt = this.getDeclaredHeightImpl(renderState, actualAvailHeight); dh = dhInt == -1 ? null : new Integer(dhInt); this.declaredHeight = dh; } return dh; } protected int getDeclaredHeightImpl(RenderState renderState, int availHeight) { Object rootNode = this.modelNode; if(rootNode instanceof HTMLElementImpl) { HTMLElementImpl element = (HTMLElementImpl) rootNode; CSS2Properties props = element.getCurrentStyle(); if(props == null) { return -1; } String heightText = props.getHeight(); if(heightText == null || "".equals(heightText)) { return -1; } return HtmlValues.getPixelSize(heightText, renderState, -1, availHeight); } else { return -1; } } /** * All overriders should call super implementation. */ public void paint(Graphics g) { } /** * Lays out children, and deals with "valid" state. Override doLayout method * instead of this one. */ public final void layout(int availWidth, int availHeight, boolean sizeOnly) { // Must call doLayout regardless of validity state. try { this.doLayout(availWidth, availHeight, sizeOnly); } finally { this.layoutUpTreeCanBeInvalidated = true; this.layoutDeepCanBeInvalidated = true; } } protected abstract void doLayout(int availWidth, int availHeight, boolean sizeOnly); protected final void sendGUIComponentsToParent() { // Ensures that parent has all the components // below this renderer node. (Parent expected to have removed them). Collection gc = this.guiComponents; int count = 0; if(gc != null) { RenderableContainer rc = this.container; Iterator i = gc.iterator(); while(i.hasNext()) { count++; rc.addComponent((Component) i.next()); } } } protected final void clearGUIComponents() { Collection gc = this.guiComponents; if(gc != null) { gc.clear(); } } /* (non-Javadoc) * @see org.xamjwg.html.renderer.RenderableContainer#add(java.awt.Component) */ public Component addComponent(Component component) { // Expected to be called in GUI thread. // Adds only in local collection. // Does not remove from parent. // Sending components to parent is done // by sendGUIComponentsToParent(). Collection gc = this.guiComponents; if(gc == null) { gc = new HashSet(1); this.guiComponents = gc; } gc.add(component); return component; } public void updateAllWidgetBounds() { this.container.updateAllWidgetBounds(); } /** * Updates widget bounds below this node only. * Should not be called during general rendering. */ public void updateWidgetBounds() { java.awt.Point guiPoint = this.getGUIPoint(0, 0); this.updateWidgetBounds(guiPoint.x, guiPoint.y); } public Rectangle getBoundsRelativeToBlock() { RCollection parent = this; int x = 0, y = 0; while(parent != null) { x += parent.getX(); y += parent.getY(); parent = parent.getParent(); if(parent instanceof RElement) { break; } } return new Rectangle(x, y, this.getWidth(), this.getHeight()); } protected void clearStyle(boolean isRootBlock) { this.borderInfo = null; this.borderInsets = null; this.borderTopColor = null; this.borderLeftColor = null; this.borderBottomColor = null; this.borderRightColor = null; this.zIndex = 0; this.backgroundColor = null; this.backgroundImage = null; this.lastBackgroundImageUri = null; this.overflowX = RenderState.OVERFLOW_VISIBLE; this.overflowY = RenderState.OVERFLOW_VISIBLE; if(isRootBlock) { // The margin of the root block behaves like extra padding. Insets insets1 = this.defaultMarginInsets; Insets insets2 = this.defaultPaddingInsets; Insets finalInsets = insets1 == null ? null : new Insets(insets1.top, insets1.left, insets1.bottom, insets1.right); if(insets2 != null) { if(finalInsets == null) { finalInsets = new Insets(insets2.top, insets2.left, insets2.bottom, insets2.right); } else { finalInsets.top += insets2.top; finalInsets.bottom += insets2.bottom; finalInsets.left += insets2.left; finalInsets.right += insets2.right; } } this.marginInsets = null; this.paddingInsets = finalInsets; } else { this.marginInsets = this.defaultMarginInsets; this.paddingInsets = this.defaultPaddingInsets; } } protected void applyStyle(int availWidth, int availHeight) { //TODO: Can be optimized if there's no style? //TODO: There's part of this that doesn't depend on availWidth // and availHeight, so it doesn't need to be redone on // every resize. //Note: Overridden by tables and lists. Object rootNode = this.modelNode; HTMLElementImpl rootElement; boolean isRootBlock; if(rootNode instanceof HTMLDocumentImpl) { isRootBlock = true; HTMLDocumentImpl doc = (HTMLDocumentImpl) rootNode; // Need to get BODY tag, for bgcolor, etc. rootElement = (HTMLElementImpl) doc.getBody(); } else { isRootBlock = false; rootElement = (HTMLElementImpl) rootNode; } if(rootElement == null) { this.clearStyle(isRootBlock); return; } RenderState rs = rootElement.getRenderState(); if(rs == null) { throw new IllegalStateException("Element without render state: " + rootElement + "; parent=" + rootElement.getParentNode()); } BackgroundInfo binfo = rs.getBackgroundInfo(); this.backgroundColor = binfo == null ? null : binfo.backgroundColor; java.net.URL backgroundImageUri = binfo == null ? null : binfo.backgroundImage; if (backgroundImageUri == null) { this.backgroundImage = null; this.lastBackgroundImageUri = null; } else if(!backgroundImageUri.equals(this.lastBackgroundImageUri)) { this.lastBackgroundImageUri = backgroundImageUri; this.loadBackgroundImage(backgroundImageUri); } AbstractCSS2Properties props = rootElement.getCurrentStyle(); if(props == null) { this.clearStyle(isRootBlock); } else { BorderInfo borderInfo = rs.getBorderInfo(); this.borderInfo = borderInfo; HtmlInsets binsets = borderInfo == null ? null : borderInfo.insets; HtmlInsets minsets = rs.getMarginInsets(); HtmlInsets pinsets = rs.getPaddingInsets(); Insets defaultMarginInsets = this.defaultMarginInsets; int dmleft = 0, dmright = 0, dmtop = 0, dmbottom = 0; if(defaultMarginInsets != null) { dmleft = defaultMarginInsets.left; dmright = defaultMarginInsets.right; dmtop = defaultMarginInsets.top; dmbottom = defaultMarginInsets.bottom; } Insets defaultPaddingInsets = this.defaultPaddingInsets; int dpleft = 0, dpright = 0, dptop = 0, dpbottom = 0; if(defaultPaddingInsets != null) { dpleft = defaultPaddingInsets.left; dpright = defaultPaddingInsets.right; dptop = defaultPaddingInsets.top; dpbottom = defaultPaddingInsets.bottom; } Insets borderInsets = binsets == null ? null : binsets.getAWTInsets(0, 0, 0, 0, availWidth, availHeight, 0, 0); if(borderInsets == null) { borderInsets = RBlockViewport.ZERO_INSETS; } Insets paddingInsets = pinsets == null ? defaultPaddingInsets : pinsets.getAWTInsets(dptop, dpleft, dpbottom, dpright, availWidth, availHeight, 0, 0); if(paddingInsets == null) { paddingInsets = RBlockViewport.ZERO_INSETS; } Insets tentativeMarginInsets = minsets == null ? defaultMarginInsets : minsets.getAWTInsets(dmtop, dmleft, dmbottom, dmright, availWidth, availHeight, 0, 0); if(tentativeMarginInsets == null) { tentativeMarginInsets = RBlockViewport.ZERO_INSETS; } int actualAvailWidth = availWidth - paddingInsets.left - paddingInsets.right - borderInsets.left - borderInsets.right - tentativeMarginInsets.left - tentativeMarginInsets.right; int actualAvailHeight = availHeight - paddingInsets.top - paddingInsets.bottom - borderInsets.top - borderInsets.bottom - tentativeMarginInsets.top - tentativeMarginInsets.bottom; Integer declaredWidth = this.getDeclaredWidth(rs, actualAvailWidth); Integer declaredHeight = this.getDeclaredHeight(rs, actualAvailHeight); int autoMarginX = 0, autoMarginY = 0; if(declaredWidth != null) { autoMarginX = (availWidth - declaredWidth.intValue() - (borderInsets == null ? 0 : borderInsets.left - borderInsets.right) - (paddingInsets == null ? 0 : paddingInsets.left - paddingInsets.right)) / 2; } if(declaredHeight != null) { autoMarginY = (availHeight - declaredHeight.intValue() - (borderInsets == null ? 0 : borderInsets.top - borderInsets.bottom) - (paddingInsets == null ? 0 : paddingInsets.top - paddingInsets.bottom)) / 2; } this.borderInsets = borderInsets; if(isRootBlock) { // In the root block, the margin behaves like an extra padding. Insets regularMarginInsets = (autoMarginX == 0 && autoMarginY == 0) ? tentativeMarginInsets : (minsets == null ? defaultMarginInsets : minsets.getAWTInsets(dmtop, dmleft, dmbottom, dmright, availWidth, availHeight, autoMarginX, autoMarginY)); if(paddingInsets == null) { paddingInsets = RBlockViewport.ZERO_INSETS; } if(regularMarginInsets == null) { regularMarginInsets = RBlockViewport.ZERO_INSETS; } this.marginInsets = null; this.paddingInsets = new Insets( paddingInsets.top + regularMarginInsets.top, paddingInsets.left + regularMarginInsets.left, paddingInsets.bottom + regularMarginInsets.bottom, paddingInsets.right + regularMarginInsets.right); } else { this.paddingInsets = paddingInsets; this.marginInsets = (autoMarginX == 0 && autoMarginY == 0) ? tentativeMarginInsets : (minsets == null ? defaultMarginInsets : minsets.getAWTInsets(dmtop, dmleft, dmbottom, dmright, availWidth, availHeight, autoMarginX, autoMarginY)); } if(borderInfo != null) { this.borderTopColor = borderInfo.topColor; this.borderLeftColor = borderInfo.leftColor; this.borderBottomColor = borderInfo.bottomColor; this.borderRightColor = borderInfo.rightColor; } else { this.borderTopColor = null; this.borderLeftColor = null; this.borderBottomColor = null; this.borderRightColor = null; } String zIndex = props.getZIndex(); if(zIndex != null) { try { this.zIndex = Integer.parseInt(zIndex); } catch(NumberFormatException err) { logger.log(Level.WARNING, "Unable to parse z-index [" + zIndex + "] in element " + this.modelNode + ".", err); this.zIndex = 0; } } else { this.zIndex = 0; } this.overflowX = rs.getOverflowX(); this.overflowY = rs.getOverflowY(); } // Check if background image needs to be loaded } protected void loadBackgroundImage(final java.net.URL imageURL) { ModelNode rc = this.modelNode; UserAgentContext ctx = this.userAgentContext; if(ctx != null) { final HttpRequest request = ctx.createHttpRequest(); request.addReadyStateChangeListener(new ReadyStateChangeListener() { public void readyStateChanged() { int readyState = request.getReadyState(); if(readyState == HttpRequest.STATE_COMPLETE) { int status = request.getStatus(); if(status == 200 || status == 0) { Image img = request.getResponseImage(); BaseElementRenderable.this.backgroundImage = img; // Cause observer to be called int w = img.getWidth(BaseElementRenderable.this); int h = img.getHeight(BaseElementRenderable.this); // Maybe image already done... if(w != -1 && h != -1) { BaseElementRenderable.this.repaint(); } } } } }); SecurityManager sm = System.getSecurityManager(); if(sm == null) { try { request.open("GET", imageURL); request.send(null); } catch(java.io.IOException thrown) { logger.log(Level.WARNING, "loadBackgroundImage()", thrown); } } else { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { // Code might have restrictions on accessing // items from elsewhere. try { request.open("GET", imageURL); request.send(null); } catch(java.io.IOException thrown) { logger.log(Level.WARNING, "loadBackgroundImage()", thrown); } return null; } }); } } } public int getZIndex() { return this.zIndex; } private Color getBorderTopColor() { Color c = this.borderTopColor; return c == null ? Color.black : c; } private Color getBorderLeftColor() { Color c = this.borderLeftColor; return c == null ? Color.black : c; } private Color getBorderBottomColor() { Color c = this.borderBottomColor; return c == null ? Color.black : c; } private Color getBorderRightColor() { Color c = this.borderRightColor; return c == null ? Color.black : c; } protected void prePaint(java.awt.Graphics g) { int startWidth = this.width; int startHeight = this.height; int totalWidth = startWidth; int totalHeight = startHeight; int startX = 0; int startY = 0; ModelNode node = this.modelNode; RenderState rs = node.getRenderState(); Insets marginInsets = this.marginInsets; if(marginInsets != null) { totalWidth -= (marginInsets.left + marginInsets.right); totalHeight -= (marginInsets.top + marginInsets.bottom); startX += marginInsets.left; startY += marginInsets.top; } Insets borderInsets = this.borderInsets; if(borderInsets != null) { int btop = borderInsets.top; int bleft = borderInsets.left; int bright = borderInsets.right; int bbottom = borderInsets.bottom; int newTotalWidth = totalWidth - (bleft + bright); int newTotalHeight = totalHeight - (btop + bbottom); int newStartX = startX + bleft; int newStartY = startY + btop; Rectangle clientRegion = new Rectangle(newStartX, newStartY, newTotalWidth, newTotalHeight); // Paint borders if the clip bounds are not contained // by the content area. Rectangle clipBounds = g.getClipBounds(); if(!clientRegion.contains(clipBounds)) { BorderInfo borderInfo = this.borderInfo; if(btop > 0) { g.setColor(this.getBorderTopColor()); int borderStyle = borderInfo == null ? HtmlValues.BORDER_STYLE_SOLID : borderInfo.topStyle; for(int i = 0; i < btop; i++) { int leftOffset = (i * bleft) / btop; int rightOffset = (i * bright) / btop; if(borderStyle == HtmlValues.BORDER_STYLE_DASHED) { GUITasks.drawDashed(g, startX + leftOffset, startY + i, startX + totalWidth - rightOffset - 1, startY + i, 10 + btop, 6); } else { g.drawLine(startX + leftOffset, startY + i, startX + totalWidth - rightOffset - 1, startY + i); } } } if(bright > 0) { int borderStyle = borderInfo == null ? HtmlValues.BORDER_STYLE_SOLID : borderInfo.rightStyle; g.setColor(this.getBorderRightColor()); int lastX = startX + totalWidth - 1; for(int i = 0; i < bright; i++) { int topOffset = (i * btop) / bright; int bottomOffset = (i * bbottom) / bright; if(borderStyle == HtmlValues.BORDER_STYLE_DASHED) { GUITasks.drawDashed(g, lastX - i, startY + topOffset, lastX - i, startY + totalHeight - bottomOffset - 1, 10 + bright, 6); } else { g.drawLine(lastX - i, startY + topOffset, lastX - i, startY + totalHeight - bottomOffset - 1); } } } if(bbottom > 0) { int borderStyle = borderInfo == null ? HtmlValues.BORDER_STYLE_SOLID : borderInfo.bottomStyle; g.setColor(this.getBorderBottomColor()); int lastY = startY + totalHeight - 1; for(int i = 0; i < bbottom; i++) { int leftOffset = (i * bleft) / bbottom; int rightOffset = (i * bright) / bbottom; if(borderStyle == HtmlValues.BORDER_STYLE_DASHED) { GUITasks.drawDashed(g, startX + leftOffset, lastY - i, startX + totalWidth - rightOffset - 1, lastY - i, 10 + bbottom, 6); } else { g.drawLine(startX + leftOffset, lastY - i, startX + totalWidth - rightOffset - 1, lastY - i); } } } if(bleft > 0) { int borderStyle = borderInfo == null ? HtmlValues.BORDER_STYLE_SOLID : borderInfo.leftStyle; g.setColor(this.getBorderLeftColor()); for(int i = 0; i < bleft; i++) { int topOffset = (i * btop) / bleft; int bottomOffset = (i * bbottom) / bleft; if(borderStyle == HtmlValues.BORDER_STYLE_DASHED) { GUITasks.drawDashed(g, startX + i, startY + topOffset, startX + i, startY + totalHeight - bottomOffset - 1, 10 + bleft, 6); } else { g.drawLine(startX + i, startY + topOffset, startX + i, startY + totalHeight - bottomOffset - 1); } } } } // Adjust client area border totalWidth = newTotalWidth; totalHeight = newTotalHeight; startX = newStartX; startY = newStartY; } // Using clientG (clipped below) beyond this point. Graphics clientG = g.create(startX, startY, totalWidth, totalHeight); try { Rectangle bkgBounds = null; if(node != null) { Color bkg = this.backgroundColor; if(bkg != null && bkg.getAlpha() > 0) { clientG.setColor(bkg); bkgBounds = clientG.getClipBounds(); clientG.fillRect(bkgBounds.x, bkgBounds.y, bkgBounds.width, bkgBounds.height); } BackgroundInfo binfo = rs == null ? null : rs.getBackgroundInfo(); Image image = this.backgroundImage; if(image != null) { if(bkgBounds == null) { bkgBounds = clientG.getClipBounds(); } int w = image.getWidth(this); int h = image.getHeight(this); if(w != -1 && h != -1) { switch(binfo == null ? BackgroundInfo.BR_REPEAT : binfo.backgroundRepeat) { case BackgroundInfo.BR_NO_REPEAT: { int imageX; if(binfo.backgroundXPositionAbsolute) { imageX = binfo.backgroundXPosition; } else { imageX = (binfo.backgroundXPosition * (totalWidth - w)) / 100; } int imageY; if(binfo.backgroundYPositionAbsolute) { imageY = binfo.backgroundYPosition; } else { imageY =(binfo.backgroundYPosition * (totalHeight - h)) / 100; } clientG.drawImage(image, imageX, imageY, w, h, this); break; } case BackgroundInfo.BR_REPEAT_X: { int imageY; if(binfo.backgroundYPositionAbsolute) { imageY = binfo.backgroundYPosition; } else { imageY = (binfo.backgroundYPosition * (totalHeight - h)) / 100; } // Modulate starting x. int x = (bkgBounds.x / w) * w; int topX = bkgBounds.x + bkgBounds.width; for(; x < topX; x += w) { clientG.drawImage(image, x, imageY, w, h, this); } break; } case BackgroundInfo.BR_REPEAT_Y: { int imageX; if(binfo.backgroundXPositionAbsolute) { imageX = binfo.backgroundXPosition; } else { imageX = (binfo.backgroundXPosition * (totalWidth - w)) / 100; } // Modulate starting y. int y = (bkgBounds.y / h) * h; int topY = bkgBounds.y + bkgBounds.height; for(; y < topY; y += h) { clientG.drawImage(image, imageX, y, w, h, this); } break; } default: { // Modulate starting x and y. int baseX = (bkgBounds.x / w) * w; int baseY = (bkgBounds.y / h) * h; int topX = bkgBounds.x + bkgBounds.width; int topY = bkgBounds.y + bkgBounds.height; // Replacing this: for(int x = baseX; x < topX; x += w) { for(int y = baseY; y < topY; y += h) { clientG.drawImage(image, x, y, w, h, this); } } break; } } } } } } finally { clientG.dispose(); } } public boolean imageUpdate(Image img, int infoflags, int x, int y, int w, int h) { // This is so that a loading image doesn't cause // too many repaint events. if((infoflags & ImageObserver.ALLBITS) != 0 || (infoflags & ImageObserver.FRAMEBITS) != 0) { this.repaint(); } return true; } protected static final int SCROLL_BAR_THICKNESS = 16; /** * Gets insets of content area. It includes margin, borders * and scrollbars, but not padding. */ public Insets getInsets(boolean hscroll, boolean vscroll) { RenderState rs = this.modelNode.getRenderState(); Insets mi = this.marginInsets; Insets bi = this.borderInsets; int top = 0; int bottom = 0; int left = 0; int right = 0; if(mi != null) { top += mi.top; left += mi.left; bottom += mi.bottom; right += mi.right; } if(bi != null) { top += bi.top; left += bi.left; bottom += bi.bottom; right += bi.right; } if(hscroll) { bottom += SCROLL_BAR_THICKNESS; } if(vscroll) { right += SCROLL_BAR_THICKNESS; } return new Insets(top, left, bottom, right); } protected final void sendDelayedPairsToParent() { // Ensures that parent has all the components // below this renderer node. (Parent expected to have removed them). Collection gc = this.delayedPairs; if(gc != null) { RenderableContainer rc = this.container; Iterator i = gc.iterator(); while(i.hasNext()) { DelayedPair pair = (DelayedPair) i.next(); if(pair.targetParent != this) { rc.addDelayedPair(pair); } } } } public final void clearDelayedPairs() { Collection gc = this.delayedPairs; if(gc != null) { gc.clear(); } } public final Collection getDelayedPairs() { return this.delayedPairs; } /* (non-Javadoc) * @see org.xamjwg.html.renderer.RenderableContainer#add(java.awt.Component) */ public void addDelayedPair(DelayedPair pair) { // Expected to be called in GUI thread. // Adds only in local collection. // Does not remove from parent. // Sending components to parent is done // by sendDelayedPairsToParent(). Collection gc = this.delayedPairs; if(gc == null) { // Sequence is important. //TODO: But possibly added multiple //times in table layout? gc = new java.util.LinkedList(); this.delayedPairs = gc; } gc.add(pair); } public RenderableContainer getParentContainer() { return this.container; } public boolean isContainedByNode() { return true; } public int getCollapsibleMarginBottom() { int cm; Insets paddingInsets = this.paddingInsets; if(paddingInsets != null && paddingInsets.bottom > 0) { cm = 0; } else { Insets borderInsets = this.borderInsets; if(borderInsets != null && borderInsets.bottom > 0) { cm = 0; } else { cm = this.getMarginBottom(); } } if(this.isMarginBoundary()) { RenderState rs = this.modelNode.getRenderState(); if(rs != null) { FontMetrics fm = rs.getFontMetrics(); int fontHeight = fm.getHeight(); if(fontHeight > cm) { cm = fontHeight; } } } return cm; } protected boolean isMarginBoundary() { return (this.overflowY != RenderState.OVERFLOW_VISIBLE && this.overflowX != RenderState.OVERFLOW_NONE) || this.modelNode instanceof HTMLDocumentImpl; } public int getCollapsibleMarginTop() { int cm; Insets paddingInsets = this.paddingInsets; if(paddingInsets != null && paddingInsets.top > 0) { cm = 0; } else { Insets borderInsets = this.borderInsets; if(borderInsets != null && borderInsets.top > 0) { cm = 0; } else { cm = this.getMarginTop(); } } if(this.isMarginBoundary()) { RenderState rs = this.modelNode.getRenderState(); if(rs != null) { FontMetrics fm = rs.getFontMetrics(); int fontHeight = fm.getHeight(); if(fontHeight > cm) { cm = fontHeight; } } } return cm; } public int getMarginBottom() { Insets marginInsets = this.marginInsets; return marginInsets == null ? 0 : marginInsets.bottom; } public int getMarginLeft() { Insets marginInsets = this.marginInsets; return marginInsets == null ? 0 : marginInsets.left; } public int getMarginRight() { Insets marginInsets = this.marginInsets; return marginInsets == null ? 0 : marginInsets.right; } public int getMarginTop() { Insets marginInsets = this.marginInsets; return marginInsets == null ? 0 : marginInsets.top; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/BaseInputControl.java0000644000175000017500000001317610773730006030005 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 15, 2006 */ package org.lobobrowser.html.renderer; import java.awt.Graphics; import java.io.File; import org.lobobrowser.html.domimpl.*; abstract class BaseInputControl extends BaseControl implements InputContext { protected String value; public BaseInputControl(HTMLBaseInputElement modelNode) { super(modelNode); this.setOpaque(false); } public void reset(int availWidth, int availHeight) { super.reset(availWidth, availHeight); String sizeText = this.controlElement.getAttribute("size"); if(sizeText != null) { try { this.size = Integer.parseInt(sizeText); } catch(NumberFormatException nfe) { // ignore } } } public int getVAlign() { return RElement.VALIGN_ABSBOTTOM; } protected int size = -1; /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#blur() */ public void blur() { } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#click() */ public void click() { } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#focus() */ public void focus() { this.requestFocus(); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#getChecked() */ public boolean getChecked() { return false; } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#getDisabled() */ public boolean getDisabled() { return !this.isEnabled(); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#getMaxLength() */ public int getMaxLength() { return 0; } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#getReadOnly() */ public boolean getReadOnly() { return false; } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#getTabIndex() */ public int getTabIndex() { return 0; } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#getValue() */ public String getValue() { return this.value; } /** * Returns null. It should be * overridden by controls that support multiple values. */ public String[] getValues() { return null; } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#select() */ public void select() { } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#setChecked(boolean) */ public void setChecked(boolean checked) { } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#setDisabled(boolean) */ public void setDisabled(boolean disabled) { this.setEnabled(!disabled); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#setMaxLength(int) */ public void setMaxLength(int maxLength) { } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#setReadOnly(boolean) */ public void setReadOnly(boolean readOnly) { } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#setSize(int) */ public void setControlSize(int size) { this.size = size; this.invalidate(); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#setTabIndex(int) */ public void setTabIndex(int tabIndex) { } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#setValue(java.lang.String) */ public void setValue(String value) { this.value = value; } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#getTextSize() */ public int getControlSize() { return this.size; } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#getCols() */ public int getCols() { return 0; } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#getRows() */ public int getRows() { return 0; } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#setCols(int) */ public void setCols(int cols) { } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#setRows(int) */ public void setRows(int rows) { } /* (non-Javadoc) * @see org.xamjwg.html.renderer.UIControl#paintSelection(java.awt.Graphics, boolean, org.xamjwg.html.renderer.RenderablePoint, org.xamjwg.html.renderer.RenderablePoint) */ public boolean paintSelection(Graphics g, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { return inSelection; } public boolean getMultiple() { // For selects return false; } public int getSelectedIndex() { // For selects return -1; } public int getVisibleSize() { // For selects return 0; } public void setMultiple(boolean value) { // For selects } public void setSelectedIndex(int value) { // For selects } public void setVisibleSize(int value) { // For selects } public File getFileValue() { // For file inputs return null; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/BaseInputTextControl.java0000644000175000017500000001217710764503030030645 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 15, 2006 */ package org.lobobrowser.html.renderer; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Insets; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.JTextComponent; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.util.gui.WrapperLayout; abstract class BaseInputTextControl extends BaseInputControl { private static final float DEFAULT_FONT_SIZE = 14.0f; protected final JTextComponent widget; public BaseInputTextControl(final HTMLBaseInputElement modelNode) { super(modelNode); this.setLayout(WrapperLayout.getInstance()); JTextComponent widget = this.createTextField(); Font font = widget.getFont(); widget.setFont(font.deriveFont(DEFAULT_FONT_SIZE)); widget.setDocument(new LimitedDocument()); //Note: Value attribute cannot be set in reset() method. //Otherwise, layout revalidation causes typed values to //be lost (including revalidation due to hover.) ElementImpl element = this.controlElement; String value = element.getAttribute("value"); widget.setText(value); this.widget = widget; this.add(widget); } public void reset(int availWidth, int availHeight) { super.reset(availWidth, availHeight); String maxLengthText = this.controlElement.getAttribute("maxlength"); if(maxLengthText != null) { try { this.maxLength = Integer.parseInt(maxLengthText); } catch(NumberFormatException nfe) { // ignore } } } protected abstract JTextComponent createTextField(); private int maxLength = -1; /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#getMaxLength() */ public int getMaxLength() { return this.maxLength; } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#getReadOnly() */ public boolean getReadOnly() { return !this.widget.isEditable(); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#getValue() */ public String getValue() { return this.widget.getText(); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#select() */ public void select() { this.widget.selectAll(); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#setDisabled(boolean) */ public void setDisabled(boolean disabled) { super.setDisabled(disabled); this.widget.setEnabled(!disabled); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#setMaxLength(int) */ public void setMaxLength(int maxLength) { this.maxLength = maxLength; } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#setReadOnly(boolean) */ public void setReadOnly(boolean readOnly) { this.widget.setEditable(!readOnly); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#setValue(java.lang.String) */ public void setValue(String value) { this.widget.setText(value); } public java.awt.Dimension getPreferredSize() { int size = this.size; JTextComponent widget = this.widget; FontMetrics fm = widget.getFontMetrics(widget.getFont()); Insets insets = widget.getInsets(); int pw, ph; if(size == -1) { pw = 100; } else { pw = insets.left + insets.right + fm.charWidth('0') * size; } ph = fm.getHeight() + insets.top + insets.bottom; return new java.awt.Dimension(pw, ph); } public void resetInput() { this.widget.setText(""); } /** * Implements maxlength functionality. */ private class LimitedDocument extends javax.swing.text.PlainDocument { /* (non-Javadoc) * @see javax.swing.text.PlainDocument#insertString(int, java.lang.String, javax.swing.text.AttributeSet) */ public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { int max = BaseInputTextControl.this.maxLength; if(max != -1) { int docLength = this.getLength(); if(docLength >= max) { return; } int strLen = str.length(); if(docLength + strLen > max) { String shorterStr = str.substring(0, max - docLength); super.insertString(offs, shorterStr, a); } else { super.insertString(offs, str, a); } } else { super.insertString(offs, str, a); } } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/BaseRCollection.java0000644000175000017500000002223010740131372027544 0ustar twernertwernerpackage org.lobobrowser.html.renderer; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.util.Iterator; import org.lobobrowser.html.domimpl.ModelNode; abstract class BaseRCollection extends BaseBoundableRenderable implements RCollection { public BaseRCollection(RenderableContainer container, ModelNode modelNode) { super(container, modelNode); } public void focus() { this.container.focus(); //TODO: Plus local focus } public void blur() { RCollection parent = this.parent; if(parent != null) { parent.focus(); } else { //TODO: Remove local focus } } /** * Updates bounds of all descendent's GUI components, * based on root bounds. */ public void updateWidgetBounds(int guiX, int guiY) { Iterator i = this.getRenderables(); if(i != null) { while(i.hasNext()) { Object r = i.next(); if(r instanceof RCollection) { // RUIControl is a RCollection too. RCollection rc = (RCollection) r; rc.updateWidgetBounds(guiX + rc.getX(), guiY + rc.getY()); } } } } private boolean checkStartSelection(Rectangle bounds, Point selectionPoint) { if(bounds.y > selectionPoint.y) { return true; } else if(selectionPoint.y >= bounds.y && selectionPoint.y < bounds.y + bounds.height && bounds.x > selectionPoint.x) { return true; } else { return false; } } private boolean checkEndSelection(Rectangle bounds, Point selectionPoint) { if(bounds.y > selectionPoint.y) { return true; } else if(selectionPoint.y >= bounds.y && selectionPoint.y < bounds.y + bounds.height && selectionPoint.x < bounds.x) { return true; } else { return false; } } public boolean paintSelection(Graphics g, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { // TODO: Does this work with renderables that are absolutely positioned? Point checkPoint1 = null; Point checkPoint2 = null; if(!inSelection) { boolean isStart = startPoint.renderable == this; boolean isEnd = endPoint.renderable == this; if(isStart && isEnd) { checkPoint1 = startPoint.getPoint(); checkPoint2 = endPoint.getPoint(); } else if(isStart) { checkPoint1 = startPoint.getPoint(); } else if(isEnd) { checkPoint1 = endPoint.getPoint(); } } else { if(startPoint.renderable == this) { checkPoint1 = startPoint.getPoint(); } else if(endPoint.renderable == this) { checkPoint1 = endPoint.getPoint(); } } Iterator i = this.getRenderables(); if(i != null) { while(i.hasNext()) { Object robj = i.next(); if(robj instanceof BoundableRenderable) { BoundableRenderable renderable = (BoundableRenderable) robj; Rectangle bounds = renderable.getBounds(); if(!inSelection) { if(checkPoint1 != null && this.checkStartSelection(bounds, checkPoint1)) { if(checkPoint2 != null) { checkPoint1 = checkPoint2; checkPoint2 = null; } else { checkPoint1 = null; } inSelection = true; } else if(checkPoint2 != null && this.checkStartSelection(bounds, checkPoint2)) { checkPoint1 = null; checkPoint2 = null; inSelection = true; } } else if(inSelection && checkPoint1 != null && this.checkEndSelection(bounds, checkPoint1)) { return false; } int offsetX = bounds.x; int offsetY = bounds.y; g.translate(offsetX, offsetY); try { boolean newInSelection = renderable.paintSelection(g, inSelection, startPoint, endPoint); if(inSelection && !newInSelection) { return false; } inSelection = newInSelection; } finally { g.translate(-offsetX, -offsetY); } } } } if(inSelection && checkPoint1 != null) { return false; } else if(!inSelection && (checkPoint1 != null || checkPoint2 != null) && !(checkPoint1 != null && checkPoint2 != null)) { // Has to have started not being in selection, // but we must start selecting without having // selected anything in the block then. return true; } return inSelection; } public boolean extractSelectionText(StringBuffer buffer, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { Point checkPoint1 = null; Point checkPoint2 = null; if(!inSelection) { boolean isStart = startPoint.renderable == this; boolean isEnd = endPoint.renderable == this; if(isStart && isEnd) { checkPoint1 = startPoint.getPoint(); checkPoint2 = endPoint.getPoint(); } else if(isStart) { checkPoint1 = startPoint.getPoint(); } else if(isEnd) { checkPoint1 = endPoint.getPoint(); } } else { if(startPoint.renderable == this) { checkPoint1 = startPoint.getPoint(); } else if(endPoint.renderable == this) { checkPoint1 = endPoint.getPoint(); } } Iterator i = this.getRenderables(); if(i != null) { while(i.hasNext()) { Object robj = i.next(); if(robj instanceof BoundableRenderable) { BoundableRenderable renderable = (BoundableRenderable) robj; if(!inSelection) { Rectangle bounds = renderable.getBounds(); if(checkPoint1 != null && this.checkStartSelection(bounds, checkPoint1)) { if(checkPoint2 != null) { checkPoint1 = checkPoint2; checkPoint2 = null; } else { checkPoint1 = null; } inSelection = true; } else if(checkPoint2 != null && this.checkStartSelection(bounds, checkPoint2)) { checkPoint1 = null; checkPoint2 = null; inSelection = true; } } else if(inSelection && checkPoint1 != null && this.checkEndSelection(renderable.getBounds(), checkPoint1)) { return false; } boolean newInSelection = renderable.extractSelectionText(buffer, inSelection, startPoint, endPoint); if(inSelection && !newInSelection) { return false; } inSelection = newInSelection; } } } if(inSelection && checkPoint1 != null) { return false; } else if(!inSelection && (checkPoint1 != null || checkPoint2 != null) && !(checkPoint1 != null && checkPoint2 != null)) { // Has to have started not being in selection, // but we must start selecting without having // selected anything in the block then. return true; } return inSelection; } public void invalidateLayoutDeep() { //TODO: May be pretty inefficient in RLine's //if it's true that non-layable components //are not in RLine's anymore. this.invalidateLayoutLocal(); Iterator renderables = this.getRenderables(); if(renderables != null) { while(renderables.hasNext()) { Object r = renderables.next(); if(r instanceof RCollection) { ((RCollection) r).invalidateLayoutDeep(); } } } } private BoundableRenderable renderableWithMouse = null; public void onMouseMoved(MouseEvent event, int x, int y, boolean triggerEvent, ModelNode limit) { super.onMouseMoved(event, x, y, triggerEvent, limit); BoundableRenderable oldRenderable = this.renderableWithMouse; Renderable r = this.getRenderable(x, y); BoundableRenderable newRenderable = r instanceof BoundableRenderable ? (BoundableRenderable) r : null; ModelNode newLimit; if(this.isContainedByNode()) { newLimit = this.modelNode; } else { newLimit = limit; } boolean changed = oldRenderable != newRenderable; if(changed) { if(oldRenderable != null) { oldRenderable.onMouseOut(event, x - oldRenderable.getX(), y - oldRenderable.getY(), newLimit); } this.renderableWithMouse = newRenderable; } // Must recurse always if(newRenderable != null) { newRenderable.onMouseMoved(event, x - newRenderable.getX(), y - newRenderable.getY(), changed, newLimit); } } public void onMouseOut(MouseEvent event, int x, int y, ModelNode limit) { super.onMouseOut(event, x, y, limit); BoundableRenderable oldRenderable = this.renderableWithMouse; if(oldRenderable != null) { this.renderableWithMouse = null; ModelNode newLimit; if(this.isContainedByNode()) { newLimit = this.modelNode; } else { newLimit = limit; } oldRenderable.onMouseOut(event, x - oldRenderable.getX(), y - oldRenderable.getY(), newLimit); } } public BoundableRenderable getRenderable(int x, int y) { Iterator i = this.getRenderables(); if(i != null) { while(i.hasNext()) { Object r = i.next(); if(r instanceof BoundableRenderable) { BoundableRenderable br = (BoundableRenderable) r; int bx = br.getX(); int by = br.getY(); if(y >= by && y < by + br.getHeight() && x >= bx && x < bx + br.getWidth()) { return br; } } } } return null; } public boolean onRightClick(MouseEvent event, int x, int y) { BoundableRenderable br = this.getRenderable(x, y); if(br == null) { return HtmlController.getInstance().onContextMenu(this.modelNode, event, x, y); } else { return br.onRightClick(event, x - br.getX(), y - br.getY()); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/BaseRListElement.java0000644000175000017500000000623111127641550027705 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; import org.lobobrowser.html.HtmlRendererContext; import org.lobobrowser.html.UserAgentContext; import org.lobobrowser.html.domimpl.HTMLElementImpl; import org.lobobrowser.html.domimpl.NodeImpl; import org.lobobrowser.html.style.AbstractCSS2Properties; import org.lobobrowser.html.style.HtmlValues; import org.lobobrowser.html.style.ListStyle; class BaseRListElement extends RBlock { protected static final String DEFAULT_COUNTER_NAME = "$cobra.counter"; protected ListStyle listStyle = null; public BaseRListElement(NodeImpl modelNode, int listNesting, UserAgentContext pcontext, HtmlRendererContext rcontext, FrameContext frameContext, RenderableContainer parentContainer) { super(modelNode, listNesting, pcontext, rcontext, frameContext, parentContainer); } protected void applyStyle(int availWidth, int availHeight) { this.listStyle = null; super.applyStyle(availWidth, availHeight); Object rootNode = this.modelNode; if(!(rootNode instanceof HTMLElementImpl)) { return; } HTMLElementImpl rootElement = (HTMLElementImpl) rootNode; AbstractCSS2Properties props = rootElement.getCurrentStyle(); if(props == null) { return; } ListStyle listStyle = null; String listStyleText = props.getListStyle(); if(listStyleText != null) { listStyle = HtmlValues.getListStyle(listStyleText); } String listStyleTypeText = props.getListStyleType(); if(listStyleTypeText != null) { int listType = HtmlValues.getListStyleType(listStyleTypeText); if(listType != ListStyle.TYPE_UNSET) { if(listStyle == null) { listStyle = new ListStyle(); } listStyle.type = listType; } } if(listStyle == null || listStyle.type == ListStyle.TYPE_UNSET) { String typeAttributeText = rootElement.getAttribute("type"); if(typeAttributeText != null) { int newStyleType = HtmlValues.getListStyleTypeDeprecated(typeAttributeText); if(newStyleType != ListStyle.TYPE_UNSET) { if(listStyle == null) { listStyle = new ListStyle(); this.listStyle = listStyle; } listStyle.type = newStyleType; } } } this.listStyle = listStyle; } public String toString() { return "BaseRListElement[node=" + this.modelNode + "]"; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/BaseRenderable.java0000644000175000017500000000046110724771324027405 0ustar twernertwernerpackage org.lobobrowser.html.renderer; abstract class BaseRenderable implements Renderable { private int ordinal = 0; public int getOrdinal() { return this.ordinal; } public int getZIndex() { return 0; } public void setOrdinal(int ordinal) { this.ordinal = ordinal; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/BoundableRenderable.java0000644000175000017500000001065410762532154030431 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; import java.awt.*; import java.awt.event.*; import org.lobobrowser.html.domimpl.ModelNode; /** * A renderer node with well-defined bounds. Most renderer nodes * implement this interface. */ public interface BoundableRenderable extends Renderable { public ModelNode getModelNode(); public Rectangle getBounds(); public Dimension getSize(); public Point getOrigin(); public Point getOriginRelativeTo(RCollection ancestor); /** * Gets the parent where the renderable is rendered. */ public RCollection getParent(); public void setOriginalParent(RCollection origParent); /** * Gets the parent set with {@link #setOriginalParent(RCollection)}. * It represents the parent where the renderable would have * been originally rendered according to the DOM. This will * be non-null only if {@link #getParent()} is not the parent * where this renderable would have been originally rendered. */ public RCollection getOriginalParent(); /** * Returns {@link #getOriginalParent()} if not null. Otherwise * it returns {@link #getParent()}. */ public RCollection getOriginalOrCurrentParent(); public void setBounds(int x, int y, int with, int height); public void setOrigin(int x, int y); public void setX(int x); public void setY(int y); public int getX(); public int getY(); public int getHeight(); public int getWidth(); public void setHeight(int height); public void setWidth(int width); public RenderableSpot getLowestRenderableSpot(int x, int y); public Point getRenderablePoint(int guiX, int guiY); public void repaint(); /** * Returns false if the event is consumed. True to propagate further. */ public boolean onMousePressed(MouseEvent event, int x, int y); public boolean onMouseReleased(MouseEvent event, int x, int y); public boolean onMouseDisarmed(MouseEvent event); public boolean onMouseClick(MouseEvent event, int x, int y); public boolean onDoubleClick(MouseEvent event, int x, int y); public boolean onRightClick(MouseEvent event, int x, int y); public void onMouseMoved(MouseEvent event, int x, int y, boolean triggerEvent, ModelNode limit); public void onMouseOut(MouseEvent event, int x, int y, ModelNode limit); /** * Returns true if the renderable is fully contained by its modelNode, but * said modelNode does not fully contain an ancestor renderable. */ public boolean isContainedByNode(); /** * Asks the Renderable to paint the selection between two * points. Nothing will be done if the points are outside * the Renderable. * @param g * @param inSelection * @param startPoint * @param endPoint * @return True iff it's in selection when finished painting. */ public boolean paintSelection(Graphics g, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint); /** * Paints by either creating a new clipped graphics context corresponding * to the bounds of the Renderable, or by translating the origin. * @param g Parent's Graphics context. */ public void paintTranslated(Graphics g); public boolean extractSelectionText(StringBuffer buffer, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint); public void repaint(int x, int y, int width, int height); public void relayout(); public void setParent(RCollection parent); public java.awt.Point getGUIPoint(int clientX, int clientY); public int getOrdinal(); public void setOrdinal(int ordinal); public int getZIndex(); public void invalidateLayoutUpTree(); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/BrokenComponent.java0000644000175000017500000000077010641432550027646 0ustar twernertwernerpackage org.lobobrowser.html.renderer; import java.awt.*; class BrokenComponent extends Component { public Dimension getPreferredSize() { return new Dimension(10, 10); } public void update(Graphics g) { this.paint(g); } public void paint(Graphics g) { g.setColor(Color.RED); Dimension size = this.getSize(); g.drawRect(0, 0, size.width, size.height); g.drawLine(0, 0, size.width - 1, size.height - 1); g.drawLine(size.width - 1, 0, 0, size.height - 1); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/BrowserFrameUIControl.java0000644000175000017500000001211011130405462030723 0ustar twernertwernerpackage org.lobobrowser.html.renderer; import java.awt.*; import org.lobobrowser.html.*; import org.lobobrowser.html.style.*; import org.lobobrowser.html.domimpl.*; import org.w3c.dom.html2.*; class BrowserFrameUIControl implements UIControl { //private final BrowserFrame browserFrame; private final Component component; private final HTMLElement element; private final BrowserFrame browserFrame; private RUIControl ruiControl; public BrowserFrameUIControl(HTMLElement element, BrowserFrame browserFrame) { this.component = browserFrame.getComponent(); this.browserFrame = browserFrame; this.element = element; } public int getVAlign() { return RElement.VALIGN_BASELINE; } public float getAlignmentY() { return 0; } public Color getBackgroundColor() { return this.component.getBackground(); } public Component getComponent() { return this.component; } private int availWidth; private int availHeight; public void reset(int availWidth, int availHeight) { this.availWidth = availWidth; this.availHeight = availHeight; RUIControl ruiControl = this.ruiControl; if(ruiControl != null) { ModelNode node = ruiControl.getModelNode(); HTMLElement element = (HTMLElement) node; RenderState renderState = node.getRenderState(); HtmlInsets insets = null; String marginwidth = element.getAttribute("marginwidth"); String marginheight = element.getAttribute("marginheight"); if(marginwidth != null && marginwidth.length() != 0) { if(insets == null) { insets = new HtmlInsets(); } marginwidth = marginwidth.trim(); if(marginwidth.endsWith("%")) { int value; try { value = Integer.parseInt(marginwidth.substring(0, marginwidth.length() - 1)); } catch(NumberFormatException nfe) { value = 0; } insets.left = value; insets.right = value; insets.leftType = HtmlInsets.TYPE_PERCENT; insets.rightType = HtmlInsets.TYPE_PERCENT; } else { int value; try { value = Integer.parseInt(marginwidth); } catch(NumberFormatException nfe) { value = 0; } insets.left = value; insets.right = value; insets.leftType = HtmlInsets.TYPE_PIXELS; insets.rightType = HtmlInsets.TYPE_PIXELS; } } if(marginheight != null && marginheight.length() != 0) { if(insets == null) { insets = new HtmlInsets(); } marginheight = marginheight.trim(); if(marginheight.endsWith("%")) { int value; try { value = Integer.parseInt(marginheight.substring(0, marginheight.length() - 1)); } catch(NumberFormatException nfe) { value = 0; } insets.top = value; insets.bottom = value; insets.topType = HtmlInsets.TYPE_PERCENT; insets.bottomType = HtmlInsets.TYPE_PERCENT; } else { int value; try { value = Integer.parseInt(marginheight); } catch(NumberFormatException nfe) { value = 0; } insets.top = value; insets.bottom = value; insets.topType = HtmlInsets.TYPE_PIXELS; insets.bottomType = HtmlInsets.TYPE_PIXELS; } } Insets awtMarginInsets = insets == null ? null : insets.getSimpleAWTInsets(availWidth, availHeight); int overflowX = renderState.getOverflowX(); int overflowY = renderState.getOverflowY(); if(awtMarginInsets != null) { this.browserFrame.setDefaultMarginInsets(awtMarginInsets); } if(overflowX != RenderState.OVERFLOW_NONE) { this.browserFrame.setDefaultOverflowX(overflowX); } if(overflowY != RenderState.OVERFLOW_NONE) { this.browserFrame.setDefaultOverflowY(overflowY); } } } public Dimension getPreferredSize() { int width = HtmlValues.getOldSyntaxPixelSize(element.getAttribute("width"), this.availWidth, 100); int height = HtmlValues.getOldSyntaxPixelSize(element.getAttribute("height"), this.availHeight, 100); return new Dimension(width, height); } public void invalidate() { this.component.invalidate(); } public void paint(Graphics g) { // We actually have to paint it. this.component.paint(g); } public boolean paintSelection(Graphics g, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { // Selection does not cross in here? return false; } public void setBounds(int x, int y, int width, int height) { this.component.setBounds(x, y, width, height); } public void setRUIControl(RUIControl ruicontrol) { this.ruiControl = ruicontrol; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/CombinedFloatingBounds.java0000644000175000017500000000547611131102370031117 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; import org.lobobrowser.util.Objects; class CombinedFloatingBounds implements FloatingBounds { private final FloatingBounds floatBounds1; private final FloatingBounds floatBounds2; public CombinedFloatingBounds(final FloatingBounds floatBounds1, final FloatingBounds floatBounds2) { super(); this.floatBounds1 = floatBounds1; this.floatBounds2 = floatBounds2; } public int getClearY(int y) { return Math.max(this.floatBounds1.getClearY(y), this.floatBounds2.getClearY(y)); } public int getFirstClearY(int y) { return Math.max(this.floatBounds1.getFirstClearY(y), this.floatBounds2.getFirstClearY(y)); } public int getLeft(int y) { return Math.max(this.floatBounds1.getLeft(y), this.floatBounds2.getLeft(y)); } public int getLeftClearY(int y) { return Math.max(this.floatBounds1.getLeftClearY(y), this.floatBounds2.getLeftClearY(y)); } public int getMaxY() { return Math.max(this.floatBounds1.getMaxY(), this.floatBounds2.getMaxY()); } public int getRight(int y) { return Math.max(this.floatBounds1.getRight(y), this.floatBounds2.getRight(y)); } public int getRightClearY(int y) { return Math.max(this.floatBounds1.getRightClearY(y), this.floatBounds2.getRightClearY(y)); } public boolean equals(Object obj) { // Important for layout caching. if(!(obj instanceof CombinedFloatingBounds)) { return false; } CombinedFloatingBounds other = (CombinedFloatingBounds) obj; return Objects.equals(other.floatBounds1, this.floatBounds1) && Objects.equals(other.floatBounds2, this.floatBounds2); } public int hashCode() { FloatingBounds fbounds1 = this.floatBounds1; FloatingBounds fbounds2 = this.floatBounds2; return (fbounds1 == null ? 0 : fbounds1.hashCode()) ^ (fbounds2 == null ? 0 : fbounds2.hashCode()); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/DelayedPair.java0000644000175000017500000000244210764536740026740 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; public class DelayedPair { public final RenderableContainer targetParent; public final BoundableRenderable child; public final int x; public final int y; public DelayedPair(final RenderableContainer parent, final BoundableRenderable child, int x, int y) { super(); this.targetParent = parent; this.child = child; this.x = x; this.y = y; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/ExportableFloat.java0000644000175000017500000000270011132567334027636 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; public class ExportableFloat { public static final ExportableFloat[] EMPTY_ARRAY = new ExportableFloat[0]; public final BoundableRenderable element; public final boolean leftFloat; public final int origX; public final int origY; public ExportableFloat(BoundableRenderable element, boolean leftFloat, int origX, int origY) { super(); this.element = element; this.leftFloat = leftFloat; this.origX = origX; this.origY = origY; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/ExportedRenderable.java0000644000175000017500000000301110726473506030322 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; class ExportedRenderable { public final RBlockViewport originalTarget; public final BoundableRenderable renderable; /** * Coordinates in original target, for aligned blocks. */ public final int x, y; /** * -1 (left), 0, or +1 (right). */ public final int alignment; public ExportedRenderable(final RBlockViewport originalTarget, final BoundableRenderable renderable, final int x, final int y, final int alignment) { super(); this.originalTarget = originalTarget; this.x = x; this.y = y; this.alignment = alignment; this.renderable = renderable; } }libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/FloatingBounds.java0000644000175000017500000000301110726473506027462 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; interface FloatingBounds { /** * The offset from the left at the given Y, not counting insets. */ public int getLeft(int y); /** * The offset from the right at the given Y, not counting insets. */ public int getRight(int y); /** * The Y at which the float clears starting at the given Y. */ public int getClearY(int y); /** * The Y at which the first float clears. It does * not recurse to check other floats. */ public int getFirstClearY(int y); public int getLeftClearY(int y); public int getRightClearY(int y); public int getMaxY(); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/FloatingBoundsSource.java0000644000175000017500000000204010764537060030642 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; interface FloatingBoundsSource { public FloatingBounds getChildBlockFloatingBounds(int apparentBlockWidth); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/FloatingInfo.java0000644000175000017500000000235111132567160027121 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; public class FloatingInfo { public final int shiftX, shiftY; public final ExportableFloat[] floats; public FloatingInfo(int shiftX, int shiftY, ExportableFloat[] floats) { super(); this.shiftX = shiftX; this.shiftY = shiftY; this.floats = floats; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/FloatingViewportBounds.java0000644000175000017500000001067311131106336031217 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; class FloatingViewportBounds implements FloatingBounds { private final FloatingBounds prevBounds; private final boolean leftFloat; private final int y; private final int offsetFromBorder; private final int height; /** * * @param prevBounds * @param leftFloat * @param y * @param offsetFromBorder Width of floating box, including padding insets. * @param height */ public FloatingViewportBounds(FloatingBounds prevBounds, boolean leftFloat, int y, int offsetFromBorder, int height) { this.prevBounds = prevBounds; this.leftFloat = leftFloat; this.y = y; this.offsetFromBorder = offsetFromBorder; this.height = height; } public int getLeft(int y) { int left = 0; if(this.leftFloat && y >= this.y && y < this.y + height) { left = this.offsetFromBorder; } FloatingBounds prev = this.prevBounds; if(prev != null) { int newLeft = prev.getLeft(y); if(newLeft > left) { left = newLeft; } } return left; } /** * The offset from the right edge, not counting padding. */ public int getRight(int y) { int right = 0; if(!this.leftFloat && y >= this.y && y < this.y + this.height) { right = this.offsetFromBorder; } FloatingBounds prev = this.prevBounds; if(prev != null) { int newRight = prev.getRight(y); if(newRight > right) { right = newRight; } } return right; } public int getClearY(int y) { int cleary = Math.max(y, this.y + this.height); FloatingBounds prev = this.prevBounds; if(prev != null) { int pcy = prev.getClearY(y); if(pcy > cleary) { cleary = pcy; } } return cleary; } public int getFirstClearY(int y) { int clearY = y; FloatingBounds prev = this.prevBounds; if(prev != null) { int prevClearY = prev.getFirstClearY(y); if(prevClearY != y) { clearY = prevClearY; } } if(clearY == y && y >= this.y && y < this.y + this.height) { clearY = this.y + this.height; } return clearY; } public int getLeftClearY(int y) { int cleary; if(this.leftFloat) { cleary = Math.max(y, this.y + this.height); } else { cleary = y; } FloatingBounds prev = this.prevBounds; if(prev != null) { int pcy = prev.getLeftClearY(y); if(pcy > cleary) { cleary = pcy; } } return cleary; } public int getRightClearY(int y) { int cleary; if(!this.leftFloat) { cleary = Math.max(y, this.y + this.height); } else { cleary = y; } FloatingBounds prev = this.prevBounds; if(prev != null) { int pcy = prev.getLeftClearY(y); if(pcy > cleary) { cleary = pcy; } } return cleary; } public int getMaxY() { int maxY = this.y + this.height; FloatingBounds prev = this.prevBounds; if(prev != null) { int prevMaxY = prev.getMaxY(); if(prevMaxY > maxY) { maxY = prevMaxY; } } return maxY; } public boolean equals(Object other) { // Important for layout caching. if(other == this) { return true; } if(!(other instanceof FloatingViewportBounds)) { return false; } FloatingViewportBounds olm = (FloatingViewportBounds) other; return olm.leftFloat == this.leftFloat && olm.y == this.y && olm.height == this.height && olm.offsetFromBorder == this.offsetFromBorder && org.lobobrowser.util.Objects.equals(olm.prevBounds, this.prevBounds); } public int hashCode() { return (this.leftFloat ? 1 : 0) ^ this.y ^ this.height ^ this.offsetFromBorder; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/FrameContext.java0000644000175000017500000000243310726473502027146 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; import org.lobobrowser.html.domimpl.*; /** * Provides direct access to the GUI component where the * document is rendered, typically a browser frame of some sort. */ public interface FrameContext { public void resetSelection(RenderableSpot rpoint); public void expandSelection(RenderableSpot rpoint); public void delayedRelayout(NodeImpl node); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/HrControl.java0000644000175000017500000000365610726473506026475 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Nov 19, 2005 */ package org.lobobrowser.html.renderer; import java.awt.*; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.html.style.RenderState; class HrControl extends BaseControl { public HrControl(HTMLElementImpl modelNode) { super(modelNode); } public void paintComponent(Graphics g) { super.paintComponent(g); Dimension size = this.getSize(); int offset = 8; int x = offset; int y = size.height / 2 - 1; int width = size.width - offset * 2; g.setColor(Color.black); g.drawRect(x, y, width, 2); } public boolean paintSelection(Graphics g, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { return inSelection; } private int availWidth; public void reset(int availWidth, int availHeight) { this.availWidth = availWidth; } public Dimension getPreferredSize() { RenderState rs = this.controlElement.getRenderState(); FontMetrics fm = rs.getFontMetrics(); return new Dimension(this.availWidth, fm.getHeight()); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/HtmlController.java0000644000175000017500000002354510773374154027533 0ustar twernertwernerpackage org.lobobrowser.html.renderer; import org.lobobrowser.html.*; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.html.js.*; import org.mozilla.javascript.*; import java.util.logging.*; import java.awt.event.*; class HtmlController { private static final Logger logger = Logger.getLogger(HtmlController.class.getName()); private static final HtmlController instance = new HtmlController(); static HtmlController getInstance() { return instance; } /** * @return True to propagate further and false if the event was consumed. */ public boolean onEnterPressed(ModelNode node, InputEvent event) { if(node instanceof HTMLInputElementImpl) { HTMLInputElementImpl hie = (HTMLInputElementImpl) node; if(hie.isSubmittableWithEnterKey()) { hie.submitForm(null); return false; } } // No propagation return false; } /** * @return True to propagate further and false if the event was consumed. */ public boolean onMouseClick(ModelNode node, MouseEvent event, int x, int y) { if(logger.isLoggable(Level.INFO)) { logger.info("onMouseClick(): node=" + node + ",class=" + node.getClass().getName()); } if(node instanceof HTMLAbstractUIElement) { HTMLAbstractUIElement uiElement = (HTMLAbstractUIElement) node; Function f = uiElement.getOnclick(); if(f != null) { Event jsEvent = new Event("click", uiElement, event, x, y); if(!Executor.executeFunction(uiElement, f, jsEvent)) { return false; } } HtmlRendererContext rcontext = uiElement.getHtmlRendererContext(); if(rcontext != null) { if(!rcontext.onMouseClick(uiElement, event)) { return false; } } } if(node instanceof HTMLLinkElementImpl) { ((HTMLLinkElementImpl) node).navigate(); return false; } else if(node instanceof HTMLButtonElementImpl) { HTMLButtonElementImpl button = (HTMLButtonElementImpl) node; String rawType = button.getAttribute("type"); String type; if(rawType == null) { type = "submit"; } else { type = rawType.trim().toLowerCase(); } if("submit".equals(type)) { FormInput[] formInputs; String name = button.getName(); if(name == null) { formInputs = null; } else { formInputs = new FormInput[] { new FormInput(name, button.getValue()) }; } button.submitForm(formInputs); } else if("reset".equals(type)) { button.resetForm(); } else { // NOP for "button"! } return false; } ModelNode parent = node.getParentModelNode(); if(parent == null) { return true; } return this.onMouseClick(parent, event, x, y); } public boolean onContextMenu(ModelNode node, MouseEvent event, int x, int y) { if(logger.isLoggable(Level.INFO)) { logger.info("onContextMenu(): node=" + node + ",class=" + node.getClass().getName()); } if(node instanceof HTMLAbstractUIElement) { HTMLAbstractUIElement uiElement = (HTMLAbstractUIElement) node; Function f = uiElement.getOncontextmenu(); if(f != null) { Event jsEvent = new Event("contextmenu", uiElement, event, x, y); if(!Executor.executeFunction(uiElement, f, jsEvent)) { return false; } } HtmlRendererContext rcontext = uiElement.getHtmlRendererContext(); if(rcontext != null) { // Needs to be done after Javascript, so the script // is able to prevent it. if(!rcontext.onContextMenu(uiElement, event)) { return false; } } } ModelNode parent = node.getParentModelNode(); if(parent == null) { return true; } return this.onContextMenu(parent, event, x, y); } public void onMouseOver(ModelNode node, MouseEvent event, int x, int y, ModelNode limit) { while(node != null) { if(node == limit) { break; } if(node instanceof HTMLAbstractUIElement) { HTMLAbstractUIElement uiElement = (HTMLAbstractUIElement) node; uiElement.setMouseOver(true); Function f = uiElement.getOnmouseover(); if(f != null) { Event jsEvent = new Event("mouseover", uiElement, event, x, y); Executor.executeFunction(uiElement, f, jsEvent); } HtmlRendererContext rcontext = uiElement.getHtmlRendererContext(); if(rcontext != null) { rcontext.onMouseOver(uiElement, event); } } node = node.getParentModelNode(); } } public void onMouseOut(ModelNode node, MouseEvent event, int x, int y, ModelNode limit) { while(node != null) { if(node == limit) { break; } if(node instanceof HTMLAbstractUIElement) { HTMLAbstractUIElement uiElement = (HTMLAbstractUIElement) node; uiElement.setMouseOver(false); Function f = uiElement.getOnmouseout(); if(f != null) { Event jsEvent = new Event("mouseout", uiElement, event, x, y); Executor.executeFunction(uiElement, f, jsEvent); } HtmlRendererContext rcontext = uiElement.getHtmlRendererContext(); if(rcontext != null) { rcontext.onMouseOut(uiElement, event); } } node = node.getParentModelNode(); } } /** * @return True to propagate further, false if consumed. */ public boolean onDoubleClick(ModelNode node, MouseEvent event, int x, int y) { if(logger.isLoggable(Level.INFO)) { logger.info("onDoubleClick(): node=" + node + ",class=" + node.getClass().getName()); } if(node instanceof HTMLAbstractUIElement) { HTMLAbstractUIElement uiElement = (HTMLAbstractUIElement) node; Function f = uiElement.getOndblclick(); if(f != null) { Event jsEvent = new Event("dblclick", uiElement, event, x, y); if(!Executor.executeFunction(uiElement, f, jsEvent)) { return false; } } HtmlRendererContext rcontext = uiElement.getHtmlRendererContext(); if(rcontext != null) { if(!rcontext.onDoubleClick(uiElement, event)) { return false; } } } ModelNode parent = node.getParentModelNode(); if(parent == null) { return true; } return this.onDoubleClick(parent, event, x, y); } /** * @return True to propagate further, false if consumed. */ public boolean onMouseDisarmed(ModelNode node, MouseEvent event) { if(node instanceof HTMLLinkElementImpl) { ((HTMLLinkElementImpl) node).getCurrentStyle().setOverlayColor(null); return false; } ModelNode parent = node.getParentModelNode(); if(parent == null) { return true; } return this.onMouseDisarmed(parent, event); } /** * @return True to propagate further, false if consumed. */ public boolean onMouseDown(ModelNode node, MouseEvent event, int x, int y) { boolean pass = true; if(node instanceof HTMLAbstractUIElement) { HTMLAbstractUIElement uiElement = (HTMLAbstractUIElement) node; Function f = uiElement.getOnmousedown(); if(f != null) { Event jsEvent = new Event("mousedown", uiElement, event, x, y); pass = Executor.executeFunction(uiElement, f, jsEvent); } } if(node instanceof HTMLLinkElementImpl) { ((HTMLLinkElementImpl) node).getCurrentStyle().setOverlayColor("#9090FF80"); return false; } if(!pass) { return false; } ModelNode parent = node.getParentModelNode(); if(parent == null) { return true; } return this.onMouseDown(parent, event, x, y); } /** * @return True to propagate further, false if consumed. */ public boolean onMouseUp(ModelNode node, MouseEvent event, int x, int y) { boolean pass = true; if(node instanceof HTMLAbstractUIElement) { HTMLAbstractUIElement uiElement = (HTMLAbstractUIElement) node; Function f = uiElement.getOnmouseup(); if(f != null) { Event jsEvent = new Event("mouseup", uiElement, event, x, y); pass = Executor.executeFunction(uiElement, f, jsEvent); } } if(node instanceof HTMLLinkElementImpl) { ((HTMLLinkElementImpl) node).getCurrentStyle().setOverlayColor(null); return false; } if(!pass) { return false; } ModelNode parent = node.getParentModelNode(); if(parent == null) { return true; } return this.onMouseUp(parent, event, x, y); } /** * @param node The node generating the event. * @param x For images only, x coordinate of mouse click. * @param y For images only, y coordinate of mouse click. * @return True to propagate further, false if consumed. */ public boolean onPressed(ModelNode node, InputEvent event, int x, int y) { if(node instanceof HTMLAbstractUIElement) { HTMLAbstractUIElement uiElement = (HTMLAbstractUIElement) node; Function f = uiElement.getOnclick(); if(f != null) { Event jsEvent = new Event("click", uiElement, event, x, y); if(!Executor.executeFunction(uiElement, f, jsEvent)) { return false; } } } if(node instanceof HTMLInputElementImpl) { HTMLInputElementImpl hie = (HTMLInputElementImpl) node; if(hie.isSubmitInput()) { FormInput[] formInputs; String name = hie.getName(); if(name == null) { formInputs = null; } else { formInputs = new FormInput[] { new FormInput(name, hie.getValue()) }; } hie.submitForm(formInputs); } else if(hie.isImageInput()) { String name = hie.getName(); String prefix = name == null ? "" : name + "."; FormInput[] extraFormInputs = new FormInput[] { new FormInput(prefix + "x", String.valueOf(x)), new FormInput(prefix + "y", String.valueOf(y)) }; hie.submitForm(extraFormInputs); } else if(hie.isResetInput()) { hie.resetForm(); } } // No propagate return false; } public boolean onChange(ModelNode node) { if(node instanceof HTMLSelectElementImpl) { HTMLSelectElementImpl uiElement = (HTMLSelectElementImpl) node; Function f = uiElement.getOnchange(); if(f != null) { Event jsEvent = new Event("change", uiElement); if(!Executor.executeFunction(uiElement, f, jsEvent)) { return false; } } } // No propagate return false; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/ImgControl.java0000644000175000017500000001427311130347154026622 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Nov 19, 2005 */ package org.lobobrowser.html.renderer; import java.awt.*; import java.awt.image.ImageObserver; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.html.style.HtmlValues; class ImgControl extends BaseControl implements ImageListener { private volatile Image image; //private final UserAgentContext browserContext; private String lastSrc; public ImgControl(HTMLImageElementImpl modelNode) { super(modelNode); //this.browserContext = pcontext; modelNode.addImageListener(this); } public void paintComponent(Graphics g) { super.paintComponent(g); Dimension size = this.getSize(); Insets insets = this.getInsets(); synchronized(this) {} Image image = this.image; if(image != null) { g.drawImage(image, insets.left, insets.top, size.width - insets.left - insets.right, size.height - insets.top - insets.bottom, this); } else { //TODO: alt } } private int valign = RElement.VALIGN_BASELINE; private Dimension preferredSize; private int declaredWidth; private int declaredHeight; public void reset(int availWidth, int availHeight) { // Expected in the GUI thread. HTMLElementImpl element = this.controlElement; int dw = HtmlValues.getOldSyntaxPixelSize(element.getAttribute("width"), availWidth, -1); int dh = HtmlValues.getOldSyntaxPixelSize(element.getAttribute("height"), availHeight, -1); this.declaredWidth = dw; this.declaredHeight = dh; this.preferredSize = this.createPreferredSize(dw, dh); int valign; String alignText = element.getAttribute("align"); if(alignText == null) { valign = RElement.VALIGN_BASELINE; } else { alignText = alignText.toLowerCase().trim(); if("middle".equals(alignText)) { valign = RElement.VALIGN_MIDDLE; } else if("absmiddle".equals(alignText)) { valign = RElement.VALIGN_ABSMIDDLE; } else if("top".equals(alignText)) { valign = RElement.VALIGN_TOP; } else if("bottom".equals(alignText)) { valign = RElement.VALIGN_BOTTOM; } else if("baseline".equals(alignText)) { valign = RElement.VALIGN_BASELINE; } else if("absbottom".equals(alignText)) { valign = RElement.VALIGN_ABSBOTTOM; } else { valign = RElement.VALIGN_BASELINE; } } this.valign = valign; } public int getVAlign() { return this.valign; } public Dimension getPreferredSize() { Dimension ps = this.preferredSize; return ps == null ? new Dimension(0, 0) : ps; } public Dimension createPreferredSize(int dw, int dh) { Image img = this.image; if(dw == -1) { if(dh != -1) { int iw = img == null ? -1 : img.getWidth(this); int ih = img == null ? -1 : img.getHeight(this); if(ih == 0) { dw = iw == -1 ? 0 : iw; } else if(iw == -1 || ih == -1) { dw = 0; } else { dw = dh * iw / ih; } } else { dw = img == null ? -1 : img.getWidth(this); if(dw == -1) { dw = 0; } } } if(dh == -1) { if(dw != -1) { int iw = img == null ? -1 : img.getWidth(this); int ih = img == null ? -1 : img.getHeight(this); if(iw == 0) { dh = ih == -1 ? 0 : ih; } else if(iw == -1 || ih == -1) { dh = 0; } else { dh = dw * ih / iw; } } else { dh = img == null ? -1 : img.getHeight(this); if(dh == -1) { dh = 0; } } } return new Dimension(dw, dh); } private final boolean checkPreferredSizeChange() { Dimension newPs = this.createPreferredSize(this.declaredWidth, this.declaredHeight); Dimension ps = this.preferredSize; if(ps == null) { return true; } if(ps.width != newPs.width || ps.height != newPs.height) { this.preferredSize = newPs; return true; } else { return false; } } /* (non-Javadoc) * @see java.awt.Component#imageUpdate(java.awt.Image, int, int, int, int, int) */ public boolean imageUpdate(Image img, int infoflags, int x, int y, final int w, final int h) { if((infoflags & ImageObserver.ALLBITS) != 0 || (infoflags & ImageObserver.FRAMEBITS) != 0) { EventQueue.invokeLater(new Runnable() { public void run() { if(!checkPreferredSizeChange()) { repaint(); } else { ruicontrol.preferredSizeInvalidated(); } } }); } return true; } /* (non-Javadoc) * @see java.awt.Component#imageUpdate(java.awt.Image, int, int, int, int, int) */ public void imageUpdate(Image img, final int w, final int h) { EventQueue.invokeLater(new Runnable() { public void run() { if(!checkPreferredSizeChange()) { repaint(); } else { ruicontrol.preferredSizeInvalidated(); } } }); } public boolean paintSelection(Graphics g, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { return inSelection; } public void imageLoaded(ImageEvent event) { // Implementation of ImageListener. Invoked in a request thread most likely. Image image = event.image; this.image = image; int width = image.getWidth(this); int height = image.getHeight(this); if(width != -1 && height != -1) { this.imageUpdate(image, width, height); } } public String toString() { return "ImgControl[src=" + this.lastSrc + "]"; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/InputButtonControl.java0000644000175000017500000000615510773730722030412 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 15, 2006 */ package org.lobobrowser.html.renderer; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.util.gui.WrapperLayout; import javax.swing.*; class InputButtonControl extends BaseInputControl { private final JButton widget; public InputButtonControl(final HTMLBaseInputElement modelNode) { super(modelNode); this.setLayout(WrapperLayout.getInstance()); JButton widget = new JButton(); widget.setContentAreaFilled(false); this.widget = widget; this.add(widget); widget.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { HtmlController.getInstance().onPressed(InputButtonControl.this.controlElement, null, 0, 0); } }); } public void reset(int availWidth, int availHeight) { super.reset(availWidth, availHeight); RUIControl ruiControl = this.ruicontrol; JButton button = this.widget; button.setContentAreaFilled(!ruiControl.hasBackground()); java.awt.Color foregroundColor = ruiControl.getForegroundColor(); if(foregroundColor != null) { button.setForeground(foregroundColor); } HTMLInputElementImpl element = (HTMLInputElementImpl) this.controlElement; String text = element.getAttribute("value"); if(text == null || text.length() == 0) { String type = element.getType(); if("submit".equalsIgnoreCase(type)) { text = "Submit Query"; } else if("reset".equalsIgnoreCase(type)) { text = "Reset"; } else { text = ""; } } button.setText(text); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#click() */ public void click() { this.widget.doClick(); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#getValue() */ public String getValue() { return this.widget.getText(); } public void setDisabled(boolean disabled) { super.setDisabled(disabled); this.widget.setEnabled(!disabled); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#setValue(java.lang.String) */ public void setValue(String value) { this.widget.setText(value); } public void resetInput() { // nop } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/InputCheckboxControl.java0000644000175000017500000000522311067636200030651 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 15, 2006 */ package org.lobobrowser.html.renderer; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.util.gui.WrapperLayout; import javax.swing.*; class InputCheckboxControl extends BaseInputControl { private final JCheckBox widget; public InputCheckboxControl(HTMLBaseInputElement modelNode) { super(modelNode); this.setLayout(WrapperLayout.getInstance()); JCheckBox checkBox = new JCheckBox(); checkBox.setOpaque(false); this.widget = checkBox; //Note: Value attribute cannot be set in reset() method. //Otherwise, layout revalidation causes typed values to //be lost (including revalidation due to hover.) checkBox.setSelected(this.controlElement.getAttributeAsBoolean("checked")); this.add(checkBox); } public void reset(int availWidth, int availHeight) { super.reset(availWidth, availHeight); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#click() */ public void click() { this.widget.doClick(); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#getChecked() */ public boolean getChecked() { return this.widget.isSelected(); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#setChecked(boolean) */ public void setChecked(boolean checked) { this.widget.setSelected(checked); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#setDisabled(boolean) */ public void setDisabled(boolean disabled) { super.setDisabled(disabled); this.widget.setEnabled(!disabled); } public void resetInput() { this.widget.setSelected(this.controlElement.getAttributeAsBoolean("checked")); } public String getValue() { return this.controlElement.getAttribute("value"); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/InputFileControl.java0000644000175000017500000000536110726473504030014 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; import java.awt.event.ActionEvent; import org.lobobrowser.html.domimpl.*; import javax.swing.*; import java.io.*; public class InputFileControl extends BaseInputControl { private final JTextField textField = new JTextField(); private final JButton browseButton = new JButton(); public InputFileControl(HTMLBaseInputElement modelNode) { super(modelNode); this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); JButton browseButton = this.browseButton; browseButton.setAction(new BrowseAction()); browseButton.setText("Browse"); java.awt.Dimension ps = this.textField.getPreferredSize(); this.textField.setPreferredSize(new java.awt.Dimension(128, ps.height)); this.textField.setEditable(false); this.add(this.textField); this.add(Box.createHorizontalStrut(4)); this.add(browseButton); } public String getValue() { // This is the way browsers behave, even // though this value is not submitted. return this.textField.getText(); } public void setDisabled(boolean disabled) { this.browseButton.setEnabled(!disabled); } public void setValue(String value) { // nop - security } private File fileValue; private void setFileValue(File file) { this.fileValue = file; if(file == null) { this.textField.setText(""); } else { this.textField.setText(file.getAbsolutePath()); } } public File getFileValue() { return this.fileValue; } public void resetInput() { this.setFileValue(null); } private class BrowseAction extends AbstractAction { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); if(chooser.showOpenDialog(InputFileControl.this) == JFileChooser.APPROVE_OPTION) { setFileValue(chooser.getSelectedFile()); } else { setFileValue(null); } } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/InputImageControl.java0000644000175000017500000001554510726473500030160 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Image; import java.awt.Insets; import java.awt.image.ImageObserver; import java.awt.event.*; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.html.style.HtmlValues; import org.lobobrowser.util.gui.*; class InputImageControl extends BaseInputControl implements ImageListener { //private JButton button; private boolean mouseBeingPressed; public InputImageControl(final HTMLBaseInputElement modelNode) { super(modelNode); this.setLayout(WrapperLayout.getInstance()); // JButton button = new LocalButton(); // this.button = button; // button.setMargin(RBlockViewport.ZERO_INSETS); // button.setBorder(null); // this.add(button); modelNode.addImageListener(this); this.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { mouseBeingPressed = true; repaint(); } // public void mouseExited(MouseEvent e) { // mouseBeingPressed = false; // repaint(); // } public void mouseReleased(MouseEvent e) { mouseBeingPressed = false; repaint(); HtmlController.getInstance().onPressed(modelNode, e, e.getX(), e.getY()); } }); } private int valign = RElement.VALIGN_BASELINE; private Dimension preferredSize; private int declaredWidth; private int declaredHeight; private Image image; public void reset(int availWidth, int availHeight) { super.reset(availWidth, availHeight); HTMLElementImpl element = this.controlElement; int dw = HtmlValues.getOldSyntaxPixelSize(element.getAttribute("width"), availWidth, -1); int dh = HtmlValues.getOldSyntaxPixelSize(element.getAttribute("height"), availHeight, -1); this.declaredWidth = dw; this.declaredHeight = dh; this.preferredSize = this.createPreferredSize(dw, dh); int valign; String alignText = element.getAttribute("align"); if(alignText == null) { valign = RElement.VALIGN_BASELINE; } else { alignText = alignText.toLowerCase().trim(); if("middle".equals(alignText)) { valign = RElement.VALIGN_MIDDLE; } else if("absmiddle".equals(alignText)) { valign = RElement.VALIGN_ABSMIDDLE; } else if("top".equals(alignText)) { valign = RElement.VALIGN_TOP; } else if("bottom".equals(alignText)) { valign = RElement.VALIGN_BOTTOM; } else if("baseline".equals(alignText)) { valign = RElement.VALIGN_BASELINE; } else if("absbottom".equals(alignText)) { valign = RElement.VALIGN_ABSBOTTOM; } else { valign = RElement.VALIGN_BASELINE; } } this.valign = valign; } public int getVAlign() { return this.valign; } public void paintComponent(Graphics g) { super.paintComponent(g); Dimension size = this.getSize(); Insets insets = this.getInsets(); synchronized(this) {} Image image = this.image; if(image != null) { g.drawImage(image, insets.left, insets.top, size.width - insets.left - insets.right, size.height - insets.top - insets.bottom, this); } else { //TODO: alt } if(this.mouseBeingPressed) { Color over = new Color(255, 100, 100, 64); if(over != null) { Color oldColor = g.getColor(); try { g.setColor(over); g.fillRect(0, 0, size.width, size.height); } finally { g.setColor(oldColor); } } } } public Dimension getPreferredSize() { Dimension ps = this.preferredSize; return ps == null ? new Dimension(0, 0) : ps; } public Dimension createPreferredSize(int dw, int dh) { Image img = this.image; if(dw == -1) { dw = img == null ? -1 : img.getWidth(this); if(dw == -1) { dw = 0; } } if(dh == -1) { dh = img == null ? -1 : img.getHeight(this); if(dh == -1) { dh = 0; } } return new Dimension(dw, dh); } private final boolean checkPreferredSizeChange() { Dimension newPs = this.createPreferredSize(this.declaredWidth, this.declaredHeight); Dimension ps = this.preferredSize; if(ps == null) { return true; } if(ps.width != newPs.width || ps.height != newPs.height) { this.preferredSize = newPs; return true; } else { return false; } } /* (non-Javadoc) * @see java.awt.Component#imageUpdate(java.awt.Image, int, int, int, int, int) */ public boolean imageUpdate(Image img, int infoflags, int x, int y, final int w, final int h) { if((infoflags & ImageObserver.ALLBITS) != 0 || (infoflags & ImageObserver.FRAMEBITS) != 0) { EventQueue.invokeLater(new Runnable() { public void run() { if(!checkPreferredSizeChange()) { repaint(); } else { ruicontrol.preferredSizeInvalidated(); } } }); } return true; } /* (non-Javadoc) * @see java.awt.Component#imageUpdate(java.awt.Image, int, int, int, int, int) */ public void imageUpdate(Image img, final int w, final int h) { EventQueue.invokeLater(new Runnable() { public void run() { if(!checkPreferredSizeChange()) { repaint(); } else { ruicontrol.preferredSizeInvalidated(); } } }); } public boolean paintSelection(Graphics g, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { return inSelection; } public void imageLoaded(ImageEvent event) { // Implementation of ImageListener. Invoked in a request thread most likely. Image image = event.image; // ImageIcon imageIcon = new ImageIcon(image); // this.button.setIcon(imageIcon); this.image = image; int width = image.getWidth(this); int height = image.getHeight(this); if(width != -1 && height != -1) { this.imageUpdate(image, width, height); } } public void resetInput() { // NOP } // private static class LocalButton extends JButton { // public void revalidate() { // // ignore // } // // public void repaint() { // // ignore // } // } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/InputPasswordControl.java0000644000175000017500000000265210726473506030741 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 15, 2006 */ package org.lobobrowser.html.renderer; import javax.swing.JPasswordField; import javax.swing.text.JTextComponent; import org.lobobrowser.html.domimpl.*; class InputPasswordControl extends InputTextControl { public InputPasswordControl(final HTMLBaseInputElement modelNode) { super(modelNode); } /* (non-Javadoc) * @see org.xamjwg.html.renderer.InputTextControl#createTextField(java.lang.String) */ protected JTextComponent createTextField() { return new JPasswordField(); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/InputRadioControl.java0000644000175000017500000000634711067636244030201 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 15, 2006 */ package org.lobobrowser.html.renderer; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.util.gui.WrapperLayout; import javax.swing.*; class InputRadioControl extends BaseInputControl { private final JRadioButton widget; public InputRadioControl(HTMLBaseInputElement modelNode) { super(modelNode); this.setLayout(WrapperLayout.getInstance()); JRadioButton radio = new JRadioButton(); radio.setOpaque(false); this.widget = radio; //Note: Value attribute cannot be set in reset() method. //Otherwise, layout revalidation causes typed values to //be lost (including revalidation due to hover.) HTMLElementImpl controlElement = this.controlElement; String name = controlElement.getAttribute("name"); ButtonGroup prevGroup = this.buttonGroup; if(prevGroup != null) { prevGroup.remove(radio); } if(name != null) { String key = "cobra.radio.group." + name; ButtonGroup group = (ButtonGroup) controlElement.getDocumentItem(key); if(group == null) { group = new ButtonGroup(); controlElement.setDocumentItem(key, group); } group.add(radio); this.buttonGroup = group; } else { this.buttonGroup = null; } radio.setSelected(controlElement.getAttributeAsBoolean("checked")); this.add(radio); } private ButtonGroup buttonGroup; public void reset(int availWidth, int availHeight) { super.reset(availWidth, availHeight); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#click() */ public void click() { this.widget.doClick(); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#getChecked() */ public boolean getChecked() { return this.widget.isSelected(); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#setChecked(boolean) */ public void setChecked(boolean checked) { this.widget.setSelected(checked); } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.InputContext#setDisabled(boolean) */ public void setDisabled(boolean disabled) { super.setDisabled(disabled); this.widget.setEnabled(!disabled); } public void resetInput() { this.widget.setSelected(this.controlElement.getAttributeAsBoolean("checked")); } public String getValue() { return this.controlElement.getAttribute("value"); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/InputSelectControl.java0000644000175000017500000002501010773452630030344 0ustar twernertwernerpackage org.lobobrowser.html.renderer; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import java.awt.event.*; import java.util.*; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.util.gui.WrapperLayout; import org.w3c.dom.html2.*; class InputSelectControl extends BaseInputControl { private final JComboBox comboBox; private final JList list; private final DefaultListModel listModel; private boolean inSelectionEvent; public InputSelectControl(final HTMLBaseInputElement modelNode) { super(modelNode); this.setLayout(WrapperLayout.getInstance()); final JComboBox comboBox = new JComboBox(); comboBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { OptionItem item = (OptionItem) e.getItem(); if(item != null) { switch(e.getStateChange()) { case ItemEvent.SELECTED: if(!suspendSelections) { // In this case it's better to change the // selected index. We don't want multiple selections. inSelectionEvent = true; try { int selectedIndex = comboBox.getSelectedIndex(); HTMLSelectElementImpl selectElement = (HTMLSelectElementImpl) modelNode; selectElement.setSelectedIndex(selectedIndex); } finally { inSelectionEvent = false; } HtmlController.getInstance().onChange(modelNode); } break; case ItemEvent.DESELECTED: // Ignore deselection here. It must necessarily // be followed by combo-box selection. If we deselect, that // changes the state of the control. break; } } } }); final DefaultListModel listModel = new DefaultListModel(); final JList list = new JList(listModel); this.listModel = listModel; list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); list.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if(!e.getValueIsAdjusting() && !suspendSelections) { boolean changed = false; inSelectionEvent = true; try { int modelSize = listModel.getSize(); for(int i = 0; i < modelSize; i++) { OptionItem item = (OptionItem) listModel.get(i); if(item != null) { boolean oldIsSelected = item.isSelected(); boolean newIsSelected = list.isSelectedIndex(i); if(oldIsSelected != newIsSelected) { changed = true; item.setSelected(newIsSelected); } } } } finally { inSelectionEvent = false; } if(changed) { HtmlController.getInstance().onChange(modelNode); } } } }); //Note: Value attribute cannot be set in reset() method. //Otherwise, layout revalidation causes typed values to //be lost (including revalidation due to hover.) this.comboBox = comboBox; this.list = list; this.resetItemList(); } private static final int STATE_NONE = 0; private static final int STATE_COMBO = 1; private static final int STATE_LIST = 2; private int state = STATE_NONE; private boolean suspendSelections = false; private void resetItemList() { HTMLSelectElementImpl selectElement = (HTMLSelectElementImpl) this.controlElement; boolean isMultiple = selectElement.getMultiple(); if(isMultiple && this.state != STATE_LIST) { this.state = STATE_LIST; this.removeAll(); JScrollPane scrollPane = new JScrollPane(this.list); this.add(scrollPane); } else if(!isMultiple && this.state != STATE_COMBO) { this.state = STATE_COMBO; this.removeAll(); this.add(this.comboBox); } this.suspendSelections = true; try { HTMLOptionsCollection optionElements = selectElement.getOptions(); if(this.state == STATE_COMBO) { JComboBox comboBox = this.comboBox; // First determine current selected option HTMLOptionElement priorSelectedOption = null; int priorIndex = selectElement.getSelectedIndex(); if(priorIndex != -1) { int numOptions = optionElements.getLength(); for(int index = 0; index < numOptions; index++) { HTMLOptionElement option = (HTMLOptionElement) optionElements.item(index); if(index == priorIndex) { priorSelectedOption = option; } } } comboBox.removeAllItems(); OptionItem defaultItem = null; OptionItem selectedItem = null; OptionItem firstItem = null; int numOptions = optionElements.getLength(); for(int index = 0; index < numOptions; index++) { HTMLOptionElement option = (HTMLOptionElement) optionElements.item(index); if(option != null) { OptionItem item = new OptionItem(option); if(firstItem == null) { firstItem = item; comboBox.addItem(item); // Undo automatic selection that occurs // when adding the first item. // This might set the deferred index as well. selectElement.setSelectedIndex(-1); if(priorSelectedOption != null) { priorSelectedOption.setSelected(true); } } else { comboBox.addItem(item); } if(option.getSelected()) { selectedItem = item; } if(option.getDefaultSelected()) { defaultItem = item; } } } if(selectedItem != null) { comboBox.setSelectedItem(selectedItem); } else if(defaultItem != null) { comboBox.setSelectedItem(defaultItem); } else if(firstItem != null) { comboBox.setSelectedItem(firstItem); } } else { JList list = this.list; Collection defaultSelectedIndexes = null; Collection selectedIndexes = null; OptionItem firstItem = null; DefaultListModel listModel = this.listModel; listModel.clear(); int numOptions = optionElements.getLength(); for(int index = 0; index < numOptions; index++) { HTMLOptionElement option = (HTMLOptionElement) optionElements.item(index); OptionItem item = new OptionItem(option); if(firstItem == null) { firstItem = item; listModel.addElement(item); // Do not select first item automatically. list.setSelectedIndex(-1); } else { listModel.addElement(item); } if(option.getSelected()) { if(selectedIndexes == null) { selectedIndexes = new LinkedList(); } selectedIndexes.add(new Integer(index)); } if(option.getDefaultSelected()) { if(defaultSelectedIndexes == null) { defaultSelectedIndexes = new LinkedList(); } defaultSelectedIndexes.add(new Integer(index)); } } if(selectedIndexes != null && selectedIndexes.size() != 0) { Iterator sii = selectedIndexes.iterator(); while(sii.hasNext()) { Integer si = (Integer) sii.next(); list.addSelectionInterval(si.intValue(), si.intValue()); } } else if(defaultSelectedIndexes != null && defaultSelectedIndexes.size() != 0) { Iterator sii = defaultSelectedIndexes.iterator(); while(sii.hasNext()) { Integer si = (Integer) sii.next(); list.addSelectionInterval(si.intValue(), si.intValue()); } } } } finally { this.suspendSelections = false; } } public void reset(int availWidth, int availHeight) { super.reset(availWidth, availHeight); // Need to do this here in case element was incomplete // when first rendered. this.resetItemList(); } public String getValue() { if(this.state == STATE_COMBO) { OptionItem item = (OptionItem) this.comboBox.getSelectedItem(); return item == null ? null : item.getValue(); } else { OptionItem item = (OptionItem) this.list.getSelectedValue(); return item == null ? null : item.getValue(); } } private int selectedIndex = -1; public int getSelectedIndex() { return this.selectedIndex; } public void setSelectedIndex(int value) { this.selectedIndex = value; boolean prevSuspend = this.suspendSelections; this.suspendSelections = true; // Note that neither IE nor FireFox generate selection // events when the selection is changed programmatically. try { if(!this.inSelectionEvent) { if(this.state == STATE_COMBO) { JComboBox comboBox = this.comboBox; if(comboBox.getSelectedIndex() != value) { // This check is done to avoid an infinite recursion // on ItemListener. int size = comboBox.getItemCount(); if(value < size) { comboBox.setSelectedIndex(value); } } } else { JList list = this.list; int[] selectedIndices = list.getSelectedIndices(); if(selectedIndices == null || selectedIndices.length != 1 || selectedIndices[0] != value) { // This check is done to avoid an infinite recursion // on ItemListener. int size = this.listModel.getSize(); if(value < size) { list.setSelectedIndex(value); } } } } } finally { this.suspendSelections = prevSuspend; } } public int getVisibleSize() { return this.comboBox.getMaximumRowCount(); } public void setVisibleSize(int value) { this.comboBox.setMaximumRowCount(value); } public void resetInput() { this.list.setSelectedIndex(-1); this.comboBox.setSelectedIndex(-1); } public String[] getValues() { if(this.state == STATE_COMBO) { OptionItem item = (OptionItem) this.comboBox.getSelectedItem(); return item == null ? null : new String[] { item.getValue() }; } else { Object[] values = this.list.getSelectedValues(); if(values == null) { return null; } ArrayList al = new ArrayList(); for(int i = 0; i < values.length; i++) { OptionItem item = (OptionItem) values[i]; al.add(item.getValue()); } return (String[]) al.toArray(new String[0]); } } private static class OptionItem { private final HTMLOptionElement option; private final String caption; public OptionItem(HTMLOptionElement option) { this.option = option; String label = option.getLabel(); if(label == null) { this.caption = option.getText(); } else { this.caption = label; } } public void setSelected(boolean value) { this.option.setSelected(value); } public boolean isSelected() { return this.option.getSelected(); } public String toString() { return this.caption; } public String getValue() { String value = this.option.getValue(); if(value == null) { value = this.option.getText(); } return value; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/InputTextAreaControl.java0000644000175000017500000001124210761010746030637 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 15, 2006 */ package org.lobobrowser.html.renderer; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Insets; import javax.swing.*; import javax.swing.text.JTextComponent; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.util.gui.WrapperLayout; class InputTextAreaControl extends BaseInputControl { private final JTextComponent widget; public InputTextAreaControl(HTMLBaseInputElement modelNode) { super(modelNode); this.setLayout(WrapperLayout.getInstance()); JTextComponent widget = this.createTextField(); this.widget = widget; this.add(new JScrollPane(widget)); //Note: Value attribute cannot be set in reset() method. //Otherwise, layout revalidation causes typed values to //be lost (including revalidation due to hover.) ElementImpl element = this.controlElement; String value = element.getTextContent(); ((JTextArea) widget).setLineWrap(true); widget.setText(value); } public void reset(int availWidth, int availHeight) { super.reset(availWidth, availHeight); ElementImpl element = this.controlElement; String colsStr = element.getAttribute("cols"); if(colsStr != null) { try { this.setCols(Integer.parseInt(colsStr)); } catch(NumberFormatException nfe) { // ignore } } String rowsStr = element.getAttribute("rows"); if(rowsStr != null) { try { this.setRows(Integer.parseInt(rowsStr)); } catch(NumberFormatException nfe) { // ignore } } } protected JTextComponent createTextField() { return new JTextArea(); } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BaseInputControl#getCols() */ public int getCols() { return this.cols; } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BaseInputControl#getRows() */ public int getRows() { return this.rows; } private int cols = -1; private int rows = -1; /* (non-Javadoc) * @see org.xamjwg.html.renderer.BaseInputControl#setCols(int) */ public void setCols(int cols) { if(cols != this.cols) { this.cols = cols; this.invalidate(); } } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BaseInputControl#setRows(int) */ public void setRows(int rows) { if(rows != this.rows) { this.rows = rows; this.invalidate(); } } public java.awt.Dimension getPreferredSize() { int pw; int cols = this.cols; if(cols == -1) { pw = 100; } else { Font f = this.widget.getFont(); FontMetrics fm = this.widget.getFontMetrics(f); Insets insets = this.widget.getInsets(); pw = insets.left + insets.right + fm.charWidth('*') * cols; } int ph; int rows = this.rows; if(rows == -1) { ph = 100; } else { Font f = this.widget.getFont(); FontMetrics fm = this.widget.getFontMetrics(f); Insets insets = this.widget.getInsets(); ph = insets.top + insets.bottom + fm.getHeight() * rows; } return new java.awt.Dimension(pw, ph); } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BaseInputControl#getReadOnly() */ public boolean getReadOnly() { return !this.widget.isEditable(); } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BaseInputControl#getValue() */ public String getValue() { String text = this.widget.getText(); return org.lobobrowser.util.Strings.getCRLFString(text); } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BaseInputControl#setReadOnly(boolean) */ public void setReadOnly(boolean readOnly) { this.widget.setEditable(readOnly); } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BaseInputControl#setValue(java.lang.String) */ public void setValue(String value) { this.widget.setText(value); } public void resetInput() { this.widget.setText(""); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/InputTextControl.java0000644000175000017500000000334710764503050030053 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 15, 2006 */ package org.lobobrowser.html.renderer; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import org.lobobrowser.html.domimpl.*; import javax.swing.*; import javax.swing.text.JTextComponent; class InputTextControl extends BaseInputTextControl { public InputTextControl(final HTMLBaseInputElement modelNode) { super(modelNode); JTextField w = (JTextField) this.widget; w.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { HtmlController.getInstance().onEnterPressed(modelNode, null); } }); } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BaseInputTextControl#createTextField(java.lang.String) */ protected JTextComponent createTextField() { return new JTextField(); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/LineBreak.java0000644000175000017500000000351310726473506026407 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; import org.lobobrowser.html.domimpl.*; public class LineBreak { public static final int NONE = 0; public static final int LEFT = 1; public static final int RIGHT = 2; public static final int ALL = 3; private final int breakType; private final ModelNode newLineNode; public LineBreak(final int breakType, ModelNode newLineNode) { super(); this.breakType = breakType; this.newLineNode = newLineNode; } public int getBreakType() { return this.breakType; } public ModelNode getModelNode() { return this.newLineNode; } public static int getBreakType(String clearAttr) { if(clearAttr == null) { return NONE; } else if("all".equalsIgnoreCase(clearAttr)) { return ALL; } else if("left".equalsIgnoreCase(clearAttr)) { return LEFT; } else if("right".equalsIgnoreCase(clearAttr)) { return RIGHT; } else { return NONE; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/LineMargin.java0000644000175000017500000000377310726473506026610 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; class LineMargin { private final int clearX; private final int clearY; private final LineMargin next; public LineMargin(LineMargin next, int cleary, int totalXOffset) { super(); this.next = next; this.clearY = cleary; this.clearX = totalXOffset; } public int getClearY() { return clearY; } public LineMargin getNext() { return next; } public int getOffset() { return clearX; } public boolean equals(Object other) { if(!(other instanceof LineMargin)) { return false; } LineMargin olm = (LineMargin) other; return olm.clearX == this.clearX && olm.clearY == this.clearY && org.lobobrowser.util.Objects.equals(olm.next, this.next); } public LineMargin translated(int yoffset, int xoffset) { int newClearY = this.clearY - yoffset; int newOffsetX = this.clearX - xoffset; if(newOffsetX < 0) { newOffsetX = 0; } LineMargin oldNext = this.next; LineMargin newNext = oldNext == null ? null : oldNext.translated(yoffset, xoffset); return new LineMargin(newNext, newClearY, newOffsetX); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/MarkupLayout.java0000644000175000017500000000232010726473506027203 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Nov 6, 2005 */ package org.lobobrowser.html.renderer; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import org.lobobrowser.html.domimpl.HTMLElementImpl; interface MarkupLayout { public void layoutMarkup(RBlockViewport bodyLayout, HTMLElementImpl markupElement); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/MarkupUtilities.java0000644000175000017500000002207010726473510027700 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 16, 2005 */ package org.lobobrowser.html.renderer; import java.awt.*; import org.lobobrowser.util.Diagnostics; //import java.util.logging.*; /** * @author J. H. S. */ class MarkupUtilities { //private static final Logger logger = Logger.getLogger(MarkupUtilities.class); // public static final int MODE_ABOVE_OR_AT = 0; // public static final int MODE_BELOW_OR_AT = 1; // public static final int MODE_LEFT_OR_AT = 0; // public static final int MODE_RIGHT_OR_AT = 1; /** * */ private MarkupUtilities() { super(); } public static BoundableRenderable findRenderable(Renderable[] renderables, Point point, boolean vertical) { return findRenderable(renderables, point, 0, renderables.length, vertical); } public static BoundableRenderable findRenderable(Renderable[] renderables, int x, int y, boolean vertical) { return findRenderable(renderables, x, y, 0, renderables.length, vertical); } private static BoundableRenderable findRenderable(Renderable[] renderables, Point point, int firstIndex, int length, boolean vertical) { return findRenderable(renderables, point.x, point.y, firstIndex, length, vertical); } private static BoundableRenderable findRenderable(Renderable[] renderables, int x, int y, int firstIndex, int length, boolean vertical) { if(length == 0) { return null; } if(length == 1) { Renderable r = renderables[firstIndex]; if(!(r instanceof BoundableRenderable)) { return null; } BoundableRenderable br = (BoundableRenderable) r; Rectangle rbounds = br.getBounds(); return rbounds.contains(x, y) ? br : null; } else { int middleIndex = firstIndex + length / 2; Renderable r = renderables[middleIndex]; Rectangle rbounds; if(r instanceof BoundableRenderable) { rbounds = ((BoundableRenderable) r).getBounds(); } else { BoundableRenderable rleft = findRenderable(renderables, x, y, firstIndex, middleIndex - firstIndex, vertical); if(rleft != null) { return rleft; } return findRenderable(renderables, x, y, middleIndex + 1, length - (middleIndex - firstIndex + 1), vertical); } if(rbounds.contains(x, y)) { return (BoundableRenderable) r; } if(vertical) { if(y < rbounds.y) { return findRenderable(renderables, x, y, firstIndex, middleIndex - firstIndex, vertical); } else { return findRenderable(renderables, x, y, middleIndex + 1, length - (middleIndex - firstIndex + 1), vertical); } } else { if(x < rbounds.x) { return findRenderable(renderables, x, y, firstIndex, middleIndex - firstIndex, vertical); } else { return findRenderable(renderables, x, y, middleIndex + 1, length - (middleIndex - firstIndex + 1), vertical); } } } } public static Range findRenderables(Renderable[] renderables, Rectangle clipArea, boolean vertical) { return findRenderables(renderables, clipArea, 0, renderables.length, vertical); } private static Range findRenderables(Renderable[] renderables, Rectangle clipArea, int firstIndex, int length, boolean vertical) { if(length == 0) { return new Range(0, 0); } int offset1 = findFirstIndex(renderables, clipArea, firstIndex, length, vertical); int offset2 = findLastIndex(renderables, clipArea, firstIndex, length, vertical); if(offset1 == -1 && offset2 == -1) { //if(logger.isLoggable(Level.INFO))logger.info("findRenderables(): Range not found for clipArea=" + clipArea + ",length=" + length); //for(int i = firstIndex; i < length; i++) { //logger.info("findRenderables(): renderable.bounds=" + renderables[i].getBounds()); //} return new Range(0, 0); } if(offset1 == -1) { offset1 = firstIndex; } if(offset2 == -1) { offset2 = firstIndex + length - 1; } return new Range(offset1, offset2 - offset1 + 1); } private static int findFirstIndex(Renderable[] renderables, Rectangle clipArea, int index, int length, boolean vertical) { Diagnostics.Assert(length > 0, "length=" + length); if(length == 1) { Renderable r = renderables[index]; Rectangle rbounds; if(r instanceof BoundableRenderable) { rbounds = ((BoundableRenderable) r).getBounds(); } else { return -1; } if(intersects(rbounds, clipArea, vertical)) { return index; } else { return -1; } } else { int middleIndex = index + length / 2; Renderable r = renderables[middleIndex]; Rectangle rbounds; if(r instanceof BoundableRenderable) { rbounds = ((BoundableRenderable) r).getBounds(); } else { int leftIndex = findFirstIndex(renderables, clipArea, index, middleIndex - index, vertical); if(leftIndex != -1) { return leftIndex; } return findFirstIndex(renderables, clipArea, middleIndex + 1, length - (middleIndex - index + 1), vertical); } if(vertical) { if(rbounds.y + rbounds.height < clipArea.y) { int newLen = length - (middleIndex - index + 1); return newLen == 0 ? -1 : findFirstIndex(renderables, clipArea, middleIndex + 1, newLen, vertical); } else { int newLen = middleIndex - index; int resultIdx = newLen == 0 ? -1 : findFirstIndex(renderables, clipArea, index, newLen, vertical); if(resultIdx == -1) { if(intersects(clipArea, rbounds, vertical)) { return middleIndex; } } return resultIdx; } } else { if(rbounds.x + rbounds.width < clipArea.x) { return findFirstIndex(renderables, clipArea, middleIndex + 1, length - (middleIndex - index), vertical); } else { int resultIdx = findFirstIndex(renderables, clipArea, index, middleIndex - index, vertical); if(resultIdx == -1) { if(intersects(clipArea, rbounds, vertical)) { return middleIndex; } } return resultIdx; } } } } private static int findLastIndex(Renderable[] renderables, Rectangle clipArea, int index, int length, boolean vertical) { Diagnostics.Assert(length > 0, "length<=0"); if(length == 1) { Renderable r = renderables[index]; Rectangle rbounds; if(r instanceof BoundableRenderable) { rbounds = ((BoundableRenderable) r).getBounds(); } else { return -1; } if(intersects(clipArea, rbounds, vertical)) { return index; } else { return -1; } } else { int middleIndex = index + length / 2; Renderable r = renderables[middleIndex]; Rectangle rbounds; if(r instanceof BoundableRenderable) { rbounds = ((BoundableRenderable) r).getBounds(); } else { int rightIndex = findLastIndex(renderables, clipArea, middleIndex + 1, length - (middleIndex - index + 1), vertical); if(rightIndex != -1) { return rightIndex; } return findLastIndex(renderables, clipArea, index, middleIndex - index, vertical); } if(vertical) { if(rbounds.y > clipArea.y + clipArea.height) { return findLastIndex(renderables, clipArea, index, middleIndex - index, vertical); } else { int newLen = length - (middleIndex - index + 1); int resultIdx = newLen == 0 ? -1 : findLastIndex(renderables, clipArea, middleIndex + 1, newLen, vertical); if(resultIdx == -1) { if(intersects(clipArea, rbounds, vertical)) { return middleIndex; } } return resultIdx; } } else { if(rbounds.x > clipArea.x + clipArea.width) { return findLastIndex(renderables, clipArea, index, middleIndex - index, vertical); } else { int resultIdx = findLastIndex(renderables, clipArea, middleIndex + 1, length - (middleIndex - index + 1), vertical); if(resultIdx == -1) { if(intersects(clipArea, rbounds, vertical)) { return middleIndex; } } return resultIdx; } } } } private static boolean intersects(Rectangle rect1, Rectangle rect2, boolean vertical) { if(vertical) { return !( (rect1.y > rect2.y + rect2.height) || (rect2.y > rect1.y + rect1.height) ); } else { return !( (rect1.x > rect2.x + rect2.width) || (rect2.x > rect1.x + rect1.width) ); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/NodeRenderer.java0000644000175000017500000000212210726473476027130 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 29, 2006 */ package org.lobobrowser.html.renderer; import org.lobobrowser.html.domimpl.NodeImpl; public interface NodeRenderer { public void setRootNode(NodeImpl node); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/OverflowException.java0000644000175000017500000000244710726473502030236 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 23, 2005 */ package org.lobobrowser.html.renderer; import java.util.*; /** * @author J. H. S. */ class OverflowException extends Exception { private final Collection renderables; /** * */ public OverflowException(Collection renderables) { super(); this.renderables = renderables; } public Collection getRenderables() { return this.renderables; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/ParentFloatingBoundsSource.java0000644000175000017500000000505511131106514032006 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; import org.lobobrowser.util.Objects; public class ParentFloatingBoundsSource implements FloatingBoundsSource { private final int blockShiftRight; private final int expectedBlockWidth; private final int newX; private final int newY; private final FloatingBounds floatBounds; public ParentFloatingBoundsSource(int blockShiftRight, int expectedWidth, int newX, int newY, FloatingBounds floatBounds) { super(); this.blockShiftRight = blockShiftRight; this.expectedBlockWidth = expectedWidth; this.newX = newX; this.newY = newY; this.floatBounds = floatBounds; } public FloatingBounds getChildBlockFloatingBounds(int apparentBlockWidth) { int actualRightShift = this.blockShiftRight + (this.expectedBlockWidth - apparentBlockWidth); return new ShiftedFloatingBounds(this.floatBounds, -this.newX, -actualRightShift, -this.newY); } public boolean equals(Object obj) { // Important for layout caching. if(!(obj instanceof ParentFloatingBoundsSource)) { return false; } ParentFloatingBoundsSource other = (ParentFloatingBoundsSource) obj; return this.blockShiftRight == other.blockShiftRight && this.expectedBlockWidth == other.expectedBlockWidth && this.newX == other.newX && this.newY == other.newY && Objects.equals(this.floatBounds, other.floatBounds); } public int hashCode() { return this.newX ^ this.newY ^ this.blockShiftRight ^ this.expectedBlockWidth; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/PositionedRenderable.java0000644000175000017500000000273211131332670030641 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; class PositionedRenderable { public static final PositionedRenderable[] EMPTY_ARRAY = new PositionedRenderable[0]; public final BoundableRenderable renderable; public final boolean verticalAlignable; public final int ordinal; public final boolean isFloat; public PositionedRenderable(final BoundableRenderable renderable, final boolean verticalAlignable, int ordinal, boolean isFloat) { super(); this.renderable = renderable; this.verticalAlignable = verticalAlignable; this.ordinal = ordinal; this.isFloat = isFloat; } }libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/RBlank.java0000644000175000017500000001332410726473510025720 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on May 21, 2005 */ package org.lobobrowser.html.renderer; import java.awt.*; import java.awt.event.MouseEvent; import org.lobobrowser.html.domimpl.ModelNode; import org.lobobrowser.html.style.RenderState; final class RBlank extends BaseBoundableRenderable { //TODO: Is there a need for RBlank's at all? public final int ascentPlusLeading; private final FontMetrics fontMetrics; public RBlank(ModelNode me, FontMetrics fm, RenderableContainer container, int ascentPlusLeading, int width, int height) { super(container, me); this.fontMetrics = fm; this.ascentPlusLeading = ascentPlusLeading; // Dimensions set when constructed. this.width = width; this.height = height; } protected void invalidateLayoutLocal() { } public boolean onMouseClick(java.awt.event.MouseEvent event, int x, int y) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onMouseClick(me, event, x, y); } else { return true; } } public boolean onDoubleClick(java.awt.event.MouseEvent event, int x, int y) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onDoubleClick(me, event, x, y); } else { return true; } } public boolean onMousePressed(java.awt.event.MouseEvent event, int x, int y) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onMouseDown(me, event, x, y); } else { return true; } } public boolean onMouseReleased(java.awt.event.MouseEvent event, int x, int y) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onMouseUp(me, event, x, y); } else { return true; } } public boolean onMouseDisarmed(java.awt.event.MouseEvent event) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onMouseDisarmed(me, event); } else { return true; } } /* (non-Javadoc) * @see net.sourceforge.xamj.domimpl.markup.Renderable#paint(java.awt.Graphics) */ public final void paint(Graphics g) { RenderState rs = this.modelNode.getRenderState(); Color bkg = rs.getTextBackgroundColor(); if(bkg != null) { Color oldColor = g.getColor(); try { g.setColor(bkg); g.fillRect(0, 0, this.width, this.height); } finally { g.setColor(oldColor); } } int td = rs.getTextDecorationMask(); if(td != 0) { if((td & RenderState.MASK_TEXTDECORATION_UNDERLINE) != 0) { int lineOffset = this.ascentPlusLeading + 2; g.drawLine(0, lineOffset, this.width, lineOffset); } if ((td & RenderState.MASK_TEXTDECORATION_LINE_THROUGH) != 0) { FontMetrics fm = this.fontMetrics; int lineOffset = fm.getLeading() + (fm.getAscent() + fm.getDescent()) / 2; g.drawLine(0, lineOffset, this.width, lineOffset); } if ((td & RenderState.MASK_TEXTDECORATION_OVERLINE) != 0) { int lineOffset = this.fontMetrics.getLeading(); g.drawLine(0, lineOffset, this.width, lineOffset); } if ((td & RenderState.MASK_TEXTDECORATION_BLINK) != 0) { //TODO } } Color over = rs.getOverlayColor(); if(over != null) { Color oldColor = g.getColor(); try { g.setColor(over); g.fillRect(0, 0, width, height); } finally { g.setColor(oldColor); } } } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BoundableRenderable#paintSelection(java.awt.Graphics, boolean, org.xamjwg.html.renderer.RenderablePoint, org.xamjwg.html.renderer.RenderablePoint) */ public boolean paintSelection(Graphics g, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { if(this == startPoint.renderable || this == endPoint.renderable) { if(inSelection) { return false; } } else if(!inSelection) { return false; } g.setColor(SELECTION_COLOR); g.setXORMode(SELECTION_XOR); g.fillRect(0, 0, this.width, this.height); g.setPaintMode(); return true; } public boolean extractSelectionText(StringBuffer buffer, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { if(this == startPoint.renderable || this == endPoint.renderable) { if(inSelection) { return false; } } else if(!inSelection) { return false; } buffer.append(' '); return true; } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BoundableRenderable#getRenderable(int, int) */ public RenderableSpot getLowestRenderableSpot(int x, int y) { return new RenderableSpot(this, x, y); } public boolean isContainedByNode() { return true; } public boolean onRightClick(MouseEvent event, int x, int y) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onContextMenu(me, event, x, y); } else { return true; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/RBlock.java0000644000175000017500000015765611134667316025747 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 16, 2005 */ package org.lobobrowser.html.renderer; import java.util.*; import java.util.logging.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.awt.image.ImageObserver; import org.lobobrowser.html.*; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.html.style.*; import org.lobobrowser.util.*; import org.w3c.dom.Node; /** * Represents a HTML block in a rendered document, typically * a DIV. The root renderer node is of this type as well. *

* Immediately below an RBlock you will find a node of * type {@link RBlockViewport}. */ public class RBlock extends BaseElementRenderable implements RenderableContainer, ImageObserver { protected static final Logger logger = Logger.getLogger(RBlock.class.getName()); private static final boolean loggableInfo = logger.isLoggable(Level.INFO); private static final int MAX_CACHE_SIZE = 10; protected final FrameContext frameContext; protected final int listNesting; protected final HtmlRendererContext rendererContext; protected final RBlockViewport bodyLayout; protected final Map cachedLayout = new Hashtable(5); protected RenderableSpot startSelection; protected RenderableSpot endSelection; protected JScrollBar vScrollBar; protected JScrollBar hScrollBar; protected boolean hasHScrollBar = false; protected boolean hasVScrollBar = false; // Validation-dependent variables... // private Dimension layoutSize = null; protected int defaultOverflowX = RenderState.OVERFLOW_NONE; protected int defaultOverflowY = RenderState.OVERFLOW_NONE; private LayoutValue lastLayoutValue = null; private LayoutKey lastLayoutKey = null; public RBlock(NodeImpl modelNode, int listNesting, UserAgentContext pcontext, HtmlRendererContext rcontext, FrameContext frameContext, RenderableContainer parentContainer) { super(parentContainer, modelNode, pcontext); this.listNesting = listNesting; this.frameContext = frameContext; this.rendererContext = rcontext; RBlockViewport bl = new RBlockViewport(modelNode, this, this .getViewportListNesting(listNesting), pcontext, rcontext, frameContext, this); this.bodyLayout = bl; bl.setOriginalParent(this); // Initialize origin of RBlockViewport to be as far top-left as // possible. // This will be corrected on first layout. bl.setX(Short.MAX_VALUE); bl.setY(Short.MAX_VALUE); } /** * Gets the width the vertical scrollbar has when shown. */ public int getVScrollBarWidth() { return SCROLL_BAR_THICKNESS; } public void finalize() throws Throwable { super.finalize(); } public int getVAlign() { // Not used return VALIGN_BASELINE; } public void ensureVisible(Point point) { RBlockViewport bodyLayout = this.bodyLayout; if (bodyLayout != null) { boolean hscroll = this.hasHScrollBar; boolean vscroll = this.hasVScrollBar; int origX = bodyLayout.x; int origY = bodyLayout.y; Insets insets = this.getInsets(hscroll, vscroll); if (hscroll) { if (point.x < insets.left) { bodyLayout.x += (insets.left - point.x); } else if (point.x > this.width - insets.right) { bodyLayout.x -= (point.x - this.width + insets.right); } } if (vscroll) { if (point.y < insets.top) { bodyLayout.y += (insets.top - point.y); } else if (point.y > this.height - insets.bottom) { bodyLayout.y -= (point.y - this.height + insets.bottom); } } if (hscroll || vscroll) { this.correctViewportOrigin(insets, this.width, this.height); if (origX != bodyLayout.x || origY != bodyLayout.y) { this.resetScrollBars(null); // TODO: This could be paintImmediately. this.repaint(); } } } } private JScrollBar getHScrollBar() { JScrollBar sb = this.hScrollBar; if (sb == null) { // Should never go back to null sb = new JScrollBar(JScrollBar.HORIZONTAL); sb.addAdjustmentListener(new LocalAdjustmentListener( JScrollBar.HORIZONTAL)); this.hScrollBar = sb; } return sb; } private JScrollBar getVScrollBar() { JScrollBar sb = this.vScrollBar; if (sb == null) { // Should never go back to null sb = new JScrollBar(JScrollBar.VERTICAL); sb.addAdjustmentListener(new LocalAdjustmentListener( JScrollBar.VERTICAL)); this.vScrollBar = sb; } return sb; } // public final boolean couldBeScrollable() { // int overflow = this.getOverflow(); // return overflow != OVERFLOW_NONE // && (overflow == OVERFLOW_SCROLL // || overflow == OVERFLOW_VERTICAL || overflow == OVERFLOW_AUTO); // } // public final boolean isOverflowVisibleX() { int overflow = this.overflowX; return overflow == RenderState.OVERFLOW_NONE || overflow == RenderState.OVERFLOW_VISIBLE; } public final boolean isOverflowVisibleY() { int overflow = this.overflowY; return overflow == RenderState.OVERFLOW_NONE || overflow == RenderState.OVERFLOW_VISIBLE; } public int getFirstLineHeight() { return this.bodyLayout.getFirstLineHeight(); } public int getFirstBaselineOffset() { return this.bodyLayout.getFirstBaselineOffset(); } public void setSelectionEnd(RenderableSpot rpoint) { this.endSelection = rpoint; } public void setSelectionStart(RenderableSpot rpoint) { this.startSelection = rpoint; } public int getViewportListNesting(int blockNesting) { return blockNesting; } public void paint(Graphics g) { RenderState rs = this.modelNode.getRenderState(); if (rs != null && rs.getVisibility() != RenderState.VISIBILITY_VISIBLE) { // Just don't paint it. return; } boolean linfo = loggableInfo; long time1 = linfo ? System.currentTimeMillis() : 0; this.prePaint(g); long time2 = linfo ? System.currentTimeMillis() : 0; long time3 = 0; try { Insets insets = this.getInsets(this.hasHScrollBar, this.hasVScrollBar); RBlockViewport bodyLayout = this.bodyLayout; if (bodyLayout != null) { int overflowX = this.overflowX; int overflowY = this.overflowY; if ((overflowX == RenderState.OVERFLOW_NONE || overflowX == RenderState.OVERFLOW_VISIBLE) && (overflowY == RenderState.OVERFLOW_NONE || overflowY == RenderState.OVERFLOW_VISIBLE)) { // Simply translate. int bx = bodyLayout.x; int by = bodyLayout.y; g.translate(bx, by); try { bodyLayout.paint(g); } finally { g.translate(-bx, -by); } } else { // Clip when there potential scrolling or hidden overflow // was requested. Graphics newG = g.create(insets.left, insets.top, this.width - insets.left - insets.right, this.height - insets.top - insets.bottom); try { // Second, translate newG.translate(bodyLayout.x - insets.left, bodyLayout.y - insets.top); // Third, paint in clipped + translated region. bodyLayout.paint(newG); } finally { newG.dispose(); } } if (linfo) { time3 = System.currentTimeMillis(); } } else { // nop } // Paint FrameContext selection. // This is only done by root RBlock. RenderableSpot start = this.startSelection; RenderableSpot end = this.endSelection; boolean inSelection = false; if (start != null && end != null && !start.equals(end)) { this.paintSelection(g, inSelection, start, end); } // Must paint scrollbars too. JScrollBar hsb = this.hScrollBar; if (hsb != null) { Graphics sbg = g.create(insets.left, this.height - insets.bottom, this.width - insets.left - insets.right, SCROLL_BAR_THICKNESS); try { hsb.paint(sbg); } finally { sbg.dispose(); } } JScrollBar vsb = this.vScrollBar; if (vsb != null) { Graphics sbg = g.create(this.width - insets.right, insets.top, SCROLL_BAR_THICKNESS, this.height - insets.top - insets.bottom); try { vsb.paint(sbg); } finally { sbg.dispose(); } } } finally { // Must always call super implementation super.paint(g); } if (linfo) { long time4 = System.currentTimeMillis(); if (time4 - time1 > 100) { logger.info("paint(): Elapsed: " + (time4 - time1) + " ms. Prepaint: " + (time2 - time1) + " ms. Viewport: " + (time3 - time2) + " ms. RBlock: " + this + "."); } } } public final void layout(int availWidth, int availHeight, boolean expandWidth, boolean expandHeight, int defaultOverflowX, int defaultOverflowY, boolean sizeOnly) { this.layout(availWidth, availHeight, expandWidth, expandHeight, null, defaultOverflowX, defaultOverflowY, sizeOnly); } public final void layout(int availWidth, int availHeight, boolean expandWidth, boolean expandHeight, FloatingBoundsSource floatBoundsSource, boolean sizeOnly) { this.layout(availWidth, availHeight, expandWidth, expandHeight, floatBoundsSource, this.defaultOverflowX, this.defaultOverflowY, sizeOnly); } public final void layout(int availWidth, int availHeight, boolean expandWidth, boolean expandHeight, FloatingBoundsSource floatBoundsSource, int defaultOverflowX, int defaultOverflowY, boolean sizeOnly) { try { this.doLayout(availWidth, availHeight, expandWidth, expandHeight, floatBoundsSource, defaultOverflowX, defaultOverflowY, sizeOnly); } finally { this.layoutUpTreeCanBeInvalidated = true; this.layoutDeepCanBeInvalidated = true; // this.renderStyleCanBeInvalidated = true; } } public final void doLayout(int availWidth, int availHeight, boolean sizeOnly) { // This is an override of an abstract method. this.doLayout(availWidth, availHeight, true, false, null, this.defaultOverflowX, this.defaultOverflowY, sizeOnly); } /** * Lays out and sets dimensions only if RBlock is invalid (or never before * layed out), if the parameters passed differ from the last layout, or if * the current font differs from the font for the last layout. * * @param availWidth * @param availHeight */ public void doLayout(int availWidth, int availHeight, boolean expandWidth, boolean expandHeight, FloatingBoundsSource floatBoundsSource, int defaultOverflowX, int defaultOverflowY, boolean sizeOnly) { // Expected to be invoked in the GUI thread. RenderState renderState = this.modelNode.getRenderState(); Font font = renderState == null ? null : renderState.getFont(); int whiteSpace = renderState == null ? RenderState.WS_NORMAL : renderState.getWhiteSpace(); LayoutKey key = new LayoutKey(availWidth, availHeight, expandWidth, expandHeight, floatBoundsSource, defaultOverflowX, defaultOverflowY, whiteSpace, font); Map cachedLayout = this.cachedLayout; LayoutValue value; if(sizeOnly) { value = (LayoutValue) cachedLayout.get(key); } else { if(Objects.equals(key, this.lastLayoutKey)) { value = this.lastLayoutValue; } else { value = null; } } if(value == null) { value = this.forceLayout(renderState, availWidth, availHeight, expandWidth, expandHeight, floatBoundsSource, defaultOverflowX, defaultOverflowY, sizeOnly); if(sizeOnly) { this.lastLayoutKey = null; this.lastLayoutValue = null; if(cachedLayout.size() > MAX_CACHE_SIZE) { // Unlikely, but we should keep it bounded. cachedLayout.clear(); } cachedLayout.put(key, value); } else { this.lastLayoutKey = key; this.lastLayoutValue = value; } } this.width = value.width; this.height = value.height; this.hasHScrollBar = value.hasHScrollBar; this.hasVScrollBar = value.hasVScrollBar; // Even if we didn't do layout, the parent is // expected to have removed its GUI components. this.sendGUIComponentsToParent(); // Even if we didn't do layout, the parent is // expected to have removed its delayed pairs. this.sendDelayedPairsToParent(); } private final boolean correctViewportOrigin(Insets insets, int blockWidth, int blockHeight) { RBlockViewport bodyLayout = this.bodyLayout; int viewPortX = bodyLayout.x; int viewPortY = bodyLayout.y; boolean corrected = false; if (viewPortX > insets.left) { bodyLayout.x = insets.left; corrected = true; } else if (viewPortX < blockWidth - insets.right - bodyLayout.width) { bodyLayout.x = Math.min(insets.left, blockWidth - insets.right - bodyLayout.width); corrected = true; } if (viewPortY > insets.top) { bodyLayout.y = insets.top; corrected = true; } else if (viewPortY < blockHeight - insets.bottom - bodyLayout.height) { bodyLayout.y = Math.min(insets.top, blockHeight - insets.bottom - bodyLayout.height); corrected = true; } return corrected; } /** * Lays out the block without checking for prior dimensions. * * @param declaredWidth The declared width of the block. * @param declaredHeight The declared height of the block. * @param tentativeWidth Presumed width of the whole block (with margins). * @param tentativeHeight * @return */ private final LayoutValue forceLayout(RenderState renderState, int availWidth, int availHeight, boolean expandWidth, boolean expandHeight, FloatingBoundsSource blockFloatBoundsSource, int defaultOverflowX, int defaultOverflowY, boolean sizeOnly) { // Expected to be invoked in the GUI thread. // TODO: Not necessary to do full layout if only expandWidth or // expandHeight change (specifically in tables). RenderState rs = renderState; if (rs == null) { rs = new BlockRenderState(null); } // // Clear adjust() cache. // this.cachedAdjust.clear(); // We reprocess the rendering state. // Probably doesn't need to be done in its entirety every time. this.applyStyle(availWidth, availHeight); RBlockViewport bodyLayout = this.bodyLayout; NodeImpl node = (NodeImpl) this.modelNode; if (node == null || bodyLayout == null) { Insets insets = this.getInsets(false, false); return new LayoutValue(insets.left + insets.right, insets.bottom + insets.top, false, false); } Insets paddingInsets = this.paddingInsets; if (paddingInsets == null) { paddingInsets = RBlockViewport.ZERO_INSETS; } Insets borderInsets = this.borderInsets; if(borderInsets == null) { borderInsets = RBlockViewport.ZERO_INSETS; } Insets marginInsets = this.marginInsets; if(marginInsets == null) { marginInsets = RBlockViewport.ZERO_INSETS; } int paddingTotalWidth = paddingInsets.left + paddingInsets.right; int paddingTotalHeight = paddingInsets.top + paddingInsets.bottom; int overflowX = this.overflowX; if (overflowX == RenderState.OVERFLOW_NONE) { overflowX = defaultOverflowX; } int overflowY = this.overflowY; if (overflowY == RenderState.OVERFLOW_NONE) { overflowY = defaultOverflowY; } boolean vauto = overflowY == RenderState.OVERFLOW_AUTO; boolean hscroll = overflowX == RenderState.OVERFLOW_SCROLL; boolean hauto = overflowX == RenderState.OVERFLOW_AUTO; boolean vscroll = overflowY == RenderState.OVERFLOW_SCROLL; Insets insets = this.getInsets(hscroll, vscroll); int insetsTotalWidth = insets.left + insets.right; int insetsTotalHeight = insets.top + insets.bottom; int actualAvailWidth = availWidth - paddingTotalWidth - insetsTotalWidth; int actualAvailHeight = availWidth - paddingTotalHeight - insetsTotalHeight; Integer dw = this.getDeclaredWidth(renderState, actualAvailWidth); Integer dh = this.getDeclaredHeight(renderState, actualAvailHeight); int declaredWidth = -1; int declaredHeight = -1; if (dw != null) { declaredWidth = dw.intValue(); } if (dh != null) { declaredHeight = dh.intValue(); } // Remove all GUI components previously added by descendents // The RBlockViewport.layout() method is expected to add all of them // back. this.clearGUIComponents(); int tentativeWidth; int tentativeHeight; // Step # 1: If there's no declared width and no width // expansion has been requested, do a preliminary layout // assuming that the scrollable region has width=0 and // there's no wrapping. tentativeWidth = declaredWidth == -1 ? availWidth : declaredWidth + insetsTotalWidth + paddingTotalWidth; tentativeHeight = declaredHeight == -1 ? availHeight : declaredHeight + insetsTotalHeight + paddingTotalHeight; if(declaredWidth == -1 && !expandWidth && availWidth > insetsTotalWidth + paddingTotalWidth) { RenderThreadState state = RenderThreadState.getState(); boolean prevOverrideNoWrap = state.overrideNoWrap; if(!prevOverrideNoWrap) { state.overrideNoWrap = true; try { int desiredViewportWidth = paddingTotalWidth; int desiredViewportHeight = paddingTotalHeight; bodyLayout.layout(desiredViewportWidth, desiredViewportHeight, paddingInsets, -1, null, true); // If we find that the viewport is not as wide as we // presumed, then we'll use that as a new tentative width. if(bodyLayout.width + insetsTotalWidth < tentativeWidth) { tentativeWidth = bodyLayout.width + insetsTotalWidth; tentativeHeight = bodyLayout.height + insetsTotalHeight; } } finally { state.overrideNoWrap = false; } } } // Step # 2: Do a layout with the tentativeWidth (adjusted if Step # 1 was done), // but in case overflow-y is "auto", then we check for possible overflow. FloatingBounds viewportFloatBounds = null; FloatingBounds blockFloatBounds = null; if (blockFloatBoundsSource != null) { blockFloatBounds = blockFloatBoundsSource.getChildBlockFloatingBounds(tentativeWidth); viewportFloatBounds = new ShiftedFloatingBounds( blockFloatBounds, -insets.left, -insets.right, -insets.top); } int desiredViewportWidth = tentativeWidth - insetsTotalWidth; int desiredViewportHeight = tentativeHeight - insets.top - insets.bottom; int maxY = vauto ? (declaredHeight == -1 ? -1 : declaredHeight + paddingInsets.top) : -1; boolean needToAddVScroll = false; try { bodyLayout.layout(desiredViewportWidth, desiredViewportHeight, paddingInsets, maxY, viewportFloatBounds, sizeOnly); } catch(SizeExceededException see) { // Getting this exception means that we need to add a vertical scrollbar. // Wee need to relayout and adjust insets and widths for scrollbar. vscroll = true; insets = this.getInsets(hscroll, vscroll); insetsTotalWidth = insets.left + insets.right; actualAvailWidth = availWidth - paddingTotalWidth - insetsTotalWidth; dw = this.getDeclaredWidth(renderState, actualAvailWidth); declaredWidth = dw == null ? -1 : dw.intValue(); desiredViewportWidth = tentativeWidth - insetsTotalWidth; if (blockFloatBounds != null) { viewportFloatBounds = new ShiftedFloatingBounds( blockFloatBounds, -insets.left, -insets.right, -insets.top); } bodyLayout.layout(desiredViewportWidth, desiredViewportHeight, paddingInsets, -1, viewportFloatBounds, sizeOnly); } int bodyWidth = bodyLayout.width; int bodyHeight = bodyLayout.height; int prelimBlockWidth = bodyWidth + insetsTotalWidth; int prelimBlockHeight = bodyHeight + insetsTotalHeight; int adjDeclaredWidth = declaredWidth == -1 ? -1 : declaredWidth + insets.left + insets.right + paddingInsets.left + paddingInsets.right; int adjDeclaredHeight = declaredHeight == -1 ? -1 : declaredHeight + insets.top + insets.bottom + paddingInsets.top + paddingInsets.bottom; // Adjust insets and other dimensions base on overflow-y=auto. if (hauto && ((adjDeclaredWidth != -1 && prelimBlockWidth > adjDeclaredWidth) || (prelimBlockWidth > tentativeWidth))) { hscroll = true; insets = this.getInsets(hscroll, vscroll); insetsTotalHeight = insets.top + insets.bottom; prelimBlockHeight = bodyHeight + insetsTotalHeight; } boolean visibleX = overflowX == RenderState.OVERFLOW_VISIBLE || overflowX == RenderState.OVERFLOW_NONE; boolean visibleY = overflowY == RenderState.OVERFLOW_VISIBLE || overflowY == RenderState.OVERFLOW_NONE; int resultingWidth; int resultingHeight; if (adjDeclaredWidth == -1) { resultingWidth = expandWidth ? Math.max(prelimBlockWidth, tentativeWidth) : prelimBlockWidth; if (hscroll && resultingWidth > tentativeWidth) { resultingWidth = Math.max(tentativeWidth, SCROLL_BAR_THICKNESS); } } else { resultingWidth = visibleX ? Math.max(prelimBlockWidth, adjDeclaredWidth) : adjDeclaredWidth; } if(!sizeOnly) { // Align horizontally now. This may change canvas height. int alignmentXPercent = rs.getAlignXPercent(); if (alignmentXPercent > 0) { // TODO: OPTIMIZATION: alignment should not be done in table cell // sizing determination. int canvasWidth = Math.max(bodyLayout.width, resultingWidth - insets.left - insets.right); // Alignment is done afterwards because canvas dimensions might have // changed. bodyLayout.alignX(alignmentXPercent, canvasWidth, paddingInsets); } } if (adjDeclaredHeight == -1) { resultingHeight = expandHeight ? Math.max(prelimBlockHeight, tentativeHeight) : prelimBlockHeight; if (vscroll && resultingHeight > tentativeHeight) { resultingHeight = Math.max(tentativeHeight, SCROLL_BAR_THICKNESS); } } else { resultingHeight = visibleY ? Math.max(prelimBlockHeight, adjDeclaredHeight) : adjDeclaredHeight; } if(!sizeOnly) { // Align vertically now int alignmentYPercent = rs.getAlignYPercent(); if (alignmentYPercent > 0) { // TODO: OPTIMIZATION: alignment should not be done in table cell // sizing determination. int canvasHeight = Math.max(bodyLayout.height, resultingHeight - insets.top - insets.bottom); // Alignment is done afterwards because canvas dimensions might have // changed. bodyLayout.alignY(alignmentYPercent, canvasHeight, paddingInsets); } } if (vscroll) { JScrollBar sb = this.getVScrollBar(); this.addComponent(sb); // Bounds set by updateWidgetBounds } if (hscroll) { JScrollBar sb = this.getHScrollBar(); this.addComponent(sb); // Bounds set by updateWidgetBounds } if (hscroll || vscroll) { // In this case, viewport origin should not be reset. // We don't want to cause the document to scroll back // up while rendering. this.correctViewportOrigin(insets, resultingWidth, resultingHeight); // Now reset the scrollbar state. Depends // on block width and height. this.width = resultingWidth; this.height = resultingHeight; this.resetScrollBars(rs); } else { bodyLayout.x = insets.left; bodyLayout.y = insets.top; } return new LayoutValue(resultingWidth, resultingHeight, hscroll, vscroll); } // /** // * Adjustment step which must be done after layout. This will expand blocks // * that need to be expanded and relayout blocks with relative sizes // * accordingly. // * // * @param availWidth // * @param availHeight // * @param expandWidth // * @param expandHeight // */ // public void adjust(int availWidth, int availHeight, boolean expandWidth, // boolean expandHeight, FloatingBoundsSource floatBoundsSource, boolean useDeclaredSize) { // RenderState renderState = this.modelNode.getRenderState(); // Font font = renderState == null ? null : renderState.getFont(); // int whiteSpace = renderState == null ? RenderState.WS_NORMAL : renderState.getWhiteSpace(); // int tentativeWidth; // if(useDeclaredSize && floatBoundsSource != null) { // Integer declaredWidth = this.getDeclaredWidth(renderState, availWidth); // Insets insets = this.getInsets(this.hasHScrollBar, this.hasVScrollBar); // Insets paddingInsets = this.paddingInsets; // int hinsets = insets.left + insets.right + (paddingInsets == null ? 0 : paddingInsets.left + paddingInsets.right); // tentativeWidth = declaredWidth == null ? availWidth : declaredWidth.intValue() + hinsets; // } // else { // // Assuming that we don't care about this if // // floatBoundsSource == null. // tentativeWidth = availWidth; // } // FloatingBounds blockFloatBounds = floatBoundsSource == null ? null : floatBoundsSource.getChildBlockFloatingBounds(tentativeWidth); // LayoutKey layoutKey = new LayoutKey(availWidth, availHeight, blockFloatBounds, this.defaultOverflowX, this.defaultOverflowY, whiteSpace, font, expandWidth, expandHeight, useDeclaredSize); // LayoutValue layoutValue = (LayoutValue) this.cachedAdjust.get(layoutKey); // // Expected to be invoked in the GUI thread. // if (layoutValue == null) { // layoutValue = this.forceAdjust(renderState, availWidth, availHeight, // expandWidth, expandHeight, blockFloatBounds, this.defaultOverflowX, this.defaultOverflowY, useDeclaredSize); // this.cachedAdjust.put(layoutKey, layoutValue); // } // // // We send GUI components up in adjust() in case new ones were added. // this.sendGUIComponentsToParent(); // // No sending delayed pairs here. // this.width = layoutValue.width; // this.height = layoutValue.height; // this.hasHScrollBar = layoutValue.hasHScrollBar; // this.hasVScrollBar = layoutValue.hasVScrollBar; // } // // /** // * This adjustment step needs to be performed after layout. In this case, // * the dimensions previously obtained in the layout are assumed to be the // * desired dimensions of the block. // *

// * When we first layout a block, we don't know its final width and height. // * It could be wider or narrower than originally assumed. // * Consider elements embedded in the block that have widths and heights // * specified by a percentage. // */ // public void adjust() { // // Expected to be invoked in the GUI thread. // this.adjust(this.width, this.height, true, true, null, false); // } // // /** // * // * @param renderState // * @param tentativeWidth // * The tentative or max width that will be tried. // * @param tentativeHeight // * The tentative or max height that will be tried. // * @param adjDeclaredWidth // * The declared width plus margins. // * @param adjDeclaredHeight // * The declared height plus margins. // * @param floatBounds // * Float bounds that need to be passed to the viewport. // * @param defaultOverflow // */ // private final LayoutValue forceAdjust(RenderState renderState, int availWidth, int availHeight, // boolean expandWidth, boolean expandHeight, // FloatingBounds blockFloatBounds, int defaultOverflowX, int defaultOverflowY, boolean useDeclaredSize) { // // Expected to be invoked in the GUI thread. // RenderState rs = renderState; // if (rs == null) { // rs = new BlockRenderState(null); // } // RBlockViewport bodyLayout = this.bodyLayout; // NodeImpl node = (NodeImpl) this.modelNode; // if (node == null || bodyLayout == null) { // Insets insets = this.getInsets(false, false); // return new LayoutValue(insets.left + insets.right, insets.bottom + insets.top, false, false); // } // // // No clearing of GUI components here // // int overflowX = this.overflowX; // if (overflowX == RenderState.OVERFLOW_NONE) { // overflowX = defaultOverflowX; // } // int overflowY = this.overflowY; // if (overflowY == RenderState.OVERFLOW_NONE) { // overflowY = defaultOverflowY; // } // boolean autoY = overflowY == RenderState.OVERFLOW_AUTO; // boolean hscroll = overflowX == RenderState.OVERFLOW_SCROLL; // boolean hauto = overflowX == RenderState.OVERFLOW_AUTO; // boolean vscroll = overflowY == RenderState.OVERFLOW_SCROLL; // Insets paddingInsets = this.paddingInsets; // if (paddingInsets == null) { // paddingInsets = RBlockViewport.ZERO_INSETS; // } // Insets borderInsets = this.borderInsets; // if(borderInsets == null) { // borderInsets = RBlockViewport.ZERO_INSETS; // } // Insets marginInsets = this.marginInsets; // if(marginInsets == null) { // marginInsets = RBlockViewport.ZERO_INSETS; // } // // // Calculate presumed size of block. // int tentativeWidth; // int tentativeHeight; // int declaredWidth = -1; // int declaredHeight = -1; // if(useDeclaredSize) { // Integer dw = this.getDeclaredWidth(renderState, availWidth); // Integer dh = this.getDeclaredHeight(renderState, availHeight); // if (dw != null) { // declaredWidth = dw.intValue(); // } // if (dh != null) { // declaredHeight = dh.intValue(); // } // } // if(declaredWidth == -1) { // tentativeWidth = availWidth; // } // else { // tentativeWidth = declaredWidth + paddingInsets.left + paddingInsets.right + borderInsets.left + borderInsets.right + marginInsets.left + marginInsets.right; // } // if(declaredHeight == -1) { // tentativeHeight = availHeight; // } // else { // tentativeHeight = declaredHeight + paddingInsets.top + paddingInsets.bottom + borderInsets.top + borderInsets.bottom + marginInsets.top + marginInsets.bottom; // } // Insets insets = null; // for (int tries = (autoY ? 0 : 1); tries < 2; tries++) { // try { // insets = this.getInsets(hscroll, vscroll); // int desiredViewportWidth = tentativeWidth - insets.left // - insets.right; // int desiredViewportHeight = tentativeHeight - insets.top // - insets.bottom; // FloatingBounds viewportFloatBounds = null; // if (blockFloatBounds != null) { // viewportFloatBounds = new ShiftedFloatingBounds( // blockFloatBounds, -insets.left, -insets.right, // -insets.top); // } // bodyLayout.adjust(desiredViewportWidth, desiredViewportHeight, // paddingInsets, viewportFloatBounds); // break; // } catch (SizeExceededException hee) { // if (tries != 0) { // throw new IllegalStateException("tries=" + tries + ",autoY=" // + autoY); // } // vscroll = true; // } // } // // Dimension size = bodyLayout.getSize(); // // Dimension rblockSize = new Dimension(size.width + insets.left + // // insets.right, size.height + insets.top + insets.bottom); // int rblockWidth = bodyLayout.width + insets.left + insets.right; // int adjDeclaredWidth = declaredWidth == -1 ? -1 : declaredWidth + insets.left + insets.right + paddingInsets.left + paddingInsets.right; // int adjDeclaredHeight = declaredHeight == -1 ? -1 : declaredHeight + insets.top + insets.bottom + paddingInsets.top + paddingInsets.bottom; // if (hauto // && !hscroll // && ((adjDeclaredWidth != -1 && rblockWidth > adjDeclaredWidth) || (rblockWidth > tentativeWidth))) { // hscroll = true; // insets = this.getInsets(hscroll, vscroll); // rblockWidth = bodyLayout.width + insets.left + insets.right; // } // // Calculate resulting width. // boolean visibleX = overflowX == RenderState.OVERFLOW_VISIBLE || overflowX == RenderState.OVERFLOW_NONE; // boolean visibleY = overflowY == RenderState.OVERFLOW_VISIBLE || overflowY == RenderState.OVERFLOW_NONE; // int resultingWidth; // if (adjDeclaredWidth == -1) { // resultingWidth = rblockWidth; // if (hscroll && resultingWidth > tentativeWidth) { // resultingWidth = Math.max(tentativeWidth, SCROLL_BAR_THICKNESS); // } else if (expandWidth && resultingWidth < tentativeWidth) { // resultingWidth = tentativeWidth; // } // } else { // resultingWidth = visibleX ? Math.max(rblockWidth, adjDeclaredWidth) // : adjDeclaredWidth; // } // // Align horizontally now. This may change canvas height. // int alignmentXPercent = rs.getAlignXPercent(); // if (alignmentXPercent > 0) { // // TODO: OPTIMIZATION: alignment should not be done in table cell // // sizing determination. // int canvasWidth = Math.max(bodyLayout.width, resultingWidth // - insets.left - insets.right); // // Alignment is done afterwards because canvas dimensions might have // // changed. // bodyLayout.alignX(alignmentXPercent, canvasWidth, paddingInsets); // } // // int resultingHeight; // int rblockHeight = bodyLayout.height + insets.top + insets.bottom; // if (autoY // && !vscroll // && ((adjDeclaredHeight != -1 && rblockHeight > adjDeclaredHeight) || (rblockHeight > tentativeHeight))) { // vscroll = true; // insets = this.getInsets(hscroll, vscroll); // rblockHeight = bodyLayout.height + insets.top + insets.bottom; // } // if (adjDeclaredHeight == -1) { // resultingHeight = rblockHeight; // if (vscroll && resultingHeight > tentativeHeight) { // resultingHeight = Math.max(tentativeHeight, // SCROLL_BAR_THICKNESS); // } else if (expandHeight && resultingHeight < tentativeHeight) { // resultingHeight = tentativeHeight; // } // } else { // resultingHeight = visibleY ? Math.max(rblockHeight, // adjDeclaredHeight) : adjDeclaredHeight; // } // // // Align vertically now // int alignmentYPercent = rs.getAlignYPercent(); // if (alignmentYPercent > 0) { // // TODO: OPTIMIZATION: alignment should not be done in table cell // // sizing determination. // int canvasHeight = Math.max(bodyLayout.height, resultingHeight // - insets.top - insets.bottom); // // Alignment is done afterwards because canvas dimensions might have // // changed. // bodyLayout.alignY(alignmentYPercent, canvasHeight, paddingInsets); // } // // if (vscroll) { // JScrollBar sb = this.getVScrollBar(); // this.addComponent(sb); // // Bounds set by updateWidgetBounds // } // if (hscroll) { // JScrollBar sb = this.getHScrollBar(); // this.addComponent(sb); // // Bounds set by updateWidgetBounds // } // // if (hscroll || vscroll) { // // In this case, viewport origin should not be changed. // // We don't want to cause the document to scroll back // // up while rendering. // this.correctViewportOrigin(insets, resultingWidth, resultingHeight); // // Depends on width, height and origin // this.resetScrollBars(rs); // } else { // bodyLayout.x = insets.left; // bodyLayout.y = insets.top; // } // return new LayoutValue(resultingWidth, resultingHeight, hscroll, vscroll); // } private int getVUnitIncrement(RenderState renderState) { if (renderState != null) { return renderState.getFontMetrics().getHeight(); } else { return new BlockRenderState(null).getFontMetrics().getHeight(); } } private boolean resettingScrollBars = false; /** * Changes scroll bar state to match viewport origin. */ private void resetScrollBars(RenderState renderState) { // Expected to be called only in the GUI thread. this.resettingScrollBars = true; try { RBlockViewport bodyLayout = this.bodyLayout; if (bodyLayout != null) { Insets insets = this.getInsets(this.hasHScrollBar, this.hasVScrollBar); JScrollBar vsb = this.vScrollBar; if (vsb != null) { int newValue = insets.top - bodyLayout.y; int newExtent = this.height - insets.top - insets.bottom; int newMin = 0; int newMax = bodyLayout.height; vsb.setValues(newValue, newExtent, newMin, newMax); vsb.setUnitIncrement(this.getVUnitIncrement(renderState)); vsb.setBlockIncrement(newExtent); } JScrollBar hsb = this.hScrollBar; if (hsb != null) { int newValue = insets.left - bodyLayout.x; int newExtent = this.width - insets.left - insets.right; int newMin = 0; int newMax = bodyLayout.width; hsb.setValues(newValue, newExtent, newMin, newMax); } } } finally { this.resettingScrollBars = false; } } /* * (non-Javadoc) * * @see org.xamjwg.html.renderer.UIControl#paintSelection(java.awt.Graphics, * boolean, org.xamjwg.html.renderer.RenderablePoint, * org.xamjwg.html.renderer.RenderablePoint) */ public boolean paintSelection(Graphics g, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { Graphics newG = g.create(); try { Insets insets = this.getInsets(this.hasHScrollBar, this.hasVScrollBar); // Just clip, don't translate. newG.clipRect(insets.left, insets.top, this.width - insets.left - insets.right, this.height - insets.top - insets.bottom); return super .paintSelection(newG, inSelection, startPoint, endPoint); } finally { newG.dispose(); } // boolean endSelectionLater = false; // if(inSelection) { // if(startPoint.renderable == this || endPoint.renderable == this) { // return false; // } // } // else { // if(startPoint.renderable == this || endPoint.renderable == this) { // // This can only occur if the selection point // // is on the margin or border or the block. // inSelection = true; // if(startPoint.renderable == this && endPoint.renderable == this) { // // Start and end selection points on margin or border. // endSelectionLater = true; // } // } // } // RBlockViewport bodyLayout = this.bodyLayout; // if(bodyLayout != null) { // Insets insets = this.getInsets(this.hasHScrollBar, // this.hasVScrollBar); // Graphics newG = g.create(insets.left, insets.top, this.width - // insets.left - insets.right, this.height - insets.top - // insets.bottom); // try { // newG.translate(bodyLayout.x - insets.left, bodyLayout.y - // insets.top); // boolean newInSelection = bodyLayout.paintSelection(newG, inSelection, // startPoint, endPoint); // if(endSelectionLater) { // return false; // } // return newInSelection; // } finally { // newG.dispose(); // } // } // else { // return inSelection; // } } /* * (non-Javadoc) * * @see org.xamjwg.html.renderer.BoundableRenderable#getRenderablePoint(int, * int) */ public RenderableSpot getLowestRenderableSpot(int x, int y) { RBlockViewport bodyLayout = this.bodyLayout; if (bodyLayout != null) { Insets insets = this.getInsets(this.hasHScrollBar, this.hasVScrollBar); if (x > insets.left && x < this.width - insets.right && y > insets.top && y < this.height - insets.bottom) { return bodyLayout.getLowestRenderableSpot(x - bodyLayout.x, y - bodyLayout.y); } else { return new RenderableSpot(this, x, y); } } else { return new RenderableSpot(this, x, y); } } /** * RBlocks should only be invalidated if one of their properties change, or * if a descendent changes, or if a style property of an ancestor is such * that it could produce layout changes in this RBlock. */ public void invalidateLayoutLocal() { super.invalidateLayoutLocal(); this.cachedLayout.clear(); this.lastLayoutKey = null; this.lastLayoutValue = null; JScrollBar hScrollBar = this.hScrollBar; if(hScrollBar != null) { // Necessary hScrollBar.invalidate(); } JScrollBar vScrollBar = this.vScrollBar; if(vScrollBar != null) { // Necessary vScrollBar.invalidate(); } } protected void clearStyle(boolean isRootBlock) { super.clearStyle(isRootBlock); this.overflowX = this.defaultOverflowX; this.overflowY = this.defaultOverflowY; } /* * (non-Javadoc) * * @see org.xamjwg.html.renderer.BoundableRenderable#onMouseClick(java.awt.event.MouseEvent, * int, int) */ public boolean onMouseClick(MouseEvent event, int x, int y) { RBlockViewport bodyLayout = this.bodyLayout; if (bodyLayout != null) { if (!bodyLayout.onMouseClick(event, x - bodyLayout.x, y - bodyLayout.y)) { return false; } } if (!HtmlController.getInstance().onMouseClick(this.modelNode, event, x, y)) { return false; } if (this.backgroundColor != null) { return false; } return true; } public boolean onDoubleClick(MouseEvent event, int x, int y) { RBlockViewport bodyLayout = this.bodyLayout; if (bodyLayout != null) { if (!bodyLayout.onDoubleClick(event, x - bodyLayout.x, y - bodyLayout.y)) { return false; } } if (this.backgroundColor != null) { return false; } return true; } /* * (non-Javadoc) * * @see org.xamjwg.html.renderer.BoundableRenderable#onMouseDisarmed(java.awt.event.MouseEvent) */ public boolean onMouseDisarmed(MouseEvent event) { BoundableRenderable br = this.armedRenderable; if (br != null) { try { return br.onMouseDisarmed(event); } finally { this.armedRenderable = null; } } else { return true; } } private BoundableRenderable armedRenderable; /* * (non-Javadoc) * * @see org.xamjwg.html.renderer.BoundableRenderable#onMousePressed(java.awt.event.MouseEvent, * int, int) */ public boolean onMousePressed(MouseEvent event, int x, int y) { RBlockViewport bodyLayout = this.bodyLayout; if (bodyLayout != null) { int newX = x - bodyLayout.x; int newY = y - bodyLayout.y; if (bodyLayout.contains(newX, newY)) { this.armedRenderable = bodyLayout; if (!bodyLayout.onMousePressed(event, newX, newY)) { return false; } } else { this.armedRenderable = null; } } else { this.armedRenderable = null; } if (!HtmlController.getInstance().onMouseDown(this.modelNode, event, x, y)) { return false; } if (this.backgroundColor != null) { return false; } return true; } /* * (non-Javadoc) * * @see org.xamjwg.html.renderer.BoundableRenderable#onMouseReleased(java.awt.event.MouseEvent, * int, int) */ public boolean onMouseReleased(MouseEvent event, int x, int y) { RBlockViewport bodyLayout = this.bodyLayout; if (bodyLayout != null) { int newX = x - bodyLayout.x; int newY = y - bodyLayout.y; if (bodyLayout.contains(newX, newY)) { this.armedRenderable = null; if (!bodyLayout.onMouseReleased(event, newX, newY)) { return false; } } else { BoundableRenderable br = this.armedRenderable; if (br != null) { br.onMouseDisarmed(event); } } } if (!HtmlController.getInstance() .onMouseUp(this.modelNode, event, x, y)) { return false; } if (this.backgroundColor != null) { return false; } return true; } public Color getPaintedBackgroundColor() { return this.backgroundColor; } /* * (non-Javadoc) * * @see org.xamjwg.html.renderer.RCollection#getRenderables() */ public Iterator getRenderables() { final RBlockViewport bodyLayout = this.bodyLayout; return new Iterator() { private RBlockViewport bl = bodyLayout; public boolean hasNext() { return bl != null; } public Object next() { if (bl == null) { throw new NoSuchElementException(); } try { return bl; } finally { bl = null; } } public void remove() { throw new UnsupportedOperationException(); } }; } /* * (non-Javadoc) * * @see org.xamjwg.html.domimpl.ContainingBlockContext#repaint(org.xamjwg.html.domimpl.RenderableContext) */ public void repaint(ModelNode modelNode) { // this.invalidateRenderStyle(); this.repaint(); } // public boolean extractSelectionText(StringBuffer buffer, boolean // inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { // RBlockViewport bodyLayout = this.bodyLayout; // if(bodyLayout != null) { // inSelection = inSelection ? endPoint.renderable != this : // startPoint.renderable == this; // return bodyLayout.extractSelectionText(buffer, inSelection, startPoint, // endPoint); // } // else { // return inSelection; // } // } public void updateWidgetBounds(int guiX, int guiY) { super.updateWidgetBounds(guiX, guiY); boolean hscroll = this.hasHScrollBar; boolean vscroll = this.hasVScrollBar; if (hscroll || vscroll) { Insets insets = this.getInsets(hscroll, vscroll); if (hscroll) { JScrollBar hsb = this.hScrollBar; if (hsb != null) { hsb.setBounds(guiX + insets.left, guiY + this.height - insets.bottom, this.width - insets.left - insets.right, SCROLL_BAR_THICKNESS); } } if (vscroll) { JScrollBar vsb = this.vScrollBar; if (vsb != null) { vsb.setBounds(guiX + this.width - insets.right, guiY + insets.top, SCROLL_BAR_THICKNESS, this.height - insets.top - insets.bottom); } } } } public void scrollHorizontalTo(int newX) { RBlockViewport bodyLayout = this.bodyLayout; if (bodyLayout != null) { Insets insets = this.getInsets(this.hasHScrollBar, this.hasVScrollBar); int viewPortX = newX; if (viewPortX > insets.left) { bodyLayout.x = insets.left; } else if (viewPortX < this.width - insets.right - bodyLayout.width) { bodyLayout.x = Math.min(insets.left, this.width - insets.right - bodyLayout.width); } else { bodyLayout.x = viewPortX; } this.resetScrollBars(null); this.updateWidgetBounds(); this.repaint(); } } public void scrollVerticalTo(int newY) { RBlockViewport bodyLayout = this.bodyLayout; if (bodyLayout != null) { Insets insets = this.getInsets(this.hasHScrollBar, this.hasVScrollBar); int viewPortY = newY; if (viewPortY > insets.top) { bodyLayout.y = insets.top; } else if (viewPortY < this.height - insets.bottom - bodyLayout.height) { bodyLayout.y = Math.min(insets.top, this.height - insets.bottom - bodyLayout.height); } else { bodyLayout.y = viewPortY; } this.resetScrollBars(null); this.updateWidgetBounds(); this.repaint(); } } public void scrollByUnits(int orientation, int units) { int offset = orientation == JScrollBar.VERTICAL ? this .getVUnitIncrement(null) * units : units; this.scrollBy(orientation, offset); } public void scrollBy(int orientation, int offset) { RBlockViewport bodyLayout = this.bodyLayout; if (bodyLayout != null) { switch (orientation) { case JScrollBar.HORIZONTAL: this.scrollHorizontalTo(bodyLayout.x - offset); break; case JScrollBar.VERTICAL: this.scrollVerticalTo(bodyLayout.y - offset); break; } } } /** * Scrolls the viewport's origin to the given location, or * as close to it as possible. *

* This method should be invoked in the GUI thread. * @param bounds The bounds of the scrollable area that should become visible. * @param xIfNeeded If this parameter is true the x coordinate * is changed only if the horizontal bounds are not currently visible. * @param yIfNeeded If this parameter is true the y coordinate * is changed only if the vertical bounds are not currently visible. */ public void scrollTo(Rectangle bounds, boolean xIfNeeded, boolean yIfNeeded) { boolean hscroll = this.hasHScrollBar; boolean vscroll = this.hasVScrollBar; if(hscroll || vscroll) { RBlockViewport bv = this.bodyLayout; Insets insets = this.getInsets(hscroll, vscroll); int vpheight = this.height - insets.top - insets.bottom; int vpwidth = this.width - insets.left - insets.right; int tentativeX = insets.left - bounds.x; int tentativeY = insets.top - bounds.y; boolean needCorrection = false; if(!(xIfNeeded && tentativeX <= bv.x && -tentativeX + bv.x + bounds.width <= vpwidth)) { bv.setX(tentativeX); needCorrection = true; } if(!(yIfNeeded && tentativeY <= bv.y && -tentativeY + bv.y + bounds.height <= vpheight)) { bv.setY(tentativeY); needCorrection = true; } if(needCorrection) { this.correctViewportOrigin(insets, this.width, this.height); } } } private void scrollToSBValue(int orientation, int value) { Insets insets = this.getInsets(this.hasHScrollBar, this.hasVScrollBar); switch (orientation) { case JScrollBar.HORIZONTAL: int xOrigin = insets.left - value; this.scrollHorizontalTo(xOrigin); break; case JScrollBar.VERTICAL: int yOrigin = insets.top - value; this.scrollVerticalTo(yOrigin); break; } } public RBlockViewport getRBlockViewport() { return this.bodyLayout; } public boolean extractSelectionText(StringBuffer buffer, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { boolean result = super.extractSelectionText(buffer, inSelection, startPoint, endPoint); String br = System.getProperty("line.separator"); if(inSelection) { buffer.insert(0, br); } if(result) { buffer.append(br); } return result; } public String toString() { return "RBlock[node=" + this.modelNode + "]"; } // public FloatingBounds getExportableFloatingBounds() { // RBlockViewport viewport = this.bodyLayout; // FloatingBounds viewportBounds = viewport.getExportableFloatingBounds(); // if (viewportBounds == null) { // return null; // } // Insets insets = this.getInsets(this.hasHScrollBar, this.hasVScrollBar); // return new ShiftedFloatingBounds(viewportBounds, insets.left, // insets.right, viewport.y); // } public FloatingInfo getExportableFloatingInfo() { FloatingInfo info = this.bodyLayout.getExportableFloatingInfo(); if(info == null) { return null; } Insets insets = this.getInsets(this.hasHScrollBar, this.hasVScrollBar); return new FloatingInfo(info.shiftX + insets.left, info.shiftY + insets.top, info.floats); } private class LocalAdjustmentListener implements AdjustmentListener { private final int orientation; public LocalAdjustmentListener(int orientation) { this.orientation = orientation; } public void adjustmentValueChanged(AdjustmentEvent e) { if (RBlock.this.resettingScrollBars) { return; } switch (e.getAdjustmentType()) { case AdjustmentEvent.UNIT_INCREMENT: // fall through case AdjustmentEvent.UNIT_DECREMENT: // fall through case AdjustmentEvent.BLOCK_INCREMENT: // fall through case AdjustmentEvent.BLOCK_DECREMENT: // fall through case AdjustmentEvent.TRACK: { int value = e.getValue(); RBlock.this.scrollToSBValue(this.orientation, value); break; } } } } private static class BodyFilter implements NodeFilter { public boolean accept(Node node) { return node instanceof org.w3c.dom.html2.HTMLBodyElement; } } public int getDefaultOverflowX() { return defaultOverflowX; } public int getDefaultOverflowY() { return defaultOverflowY; } public void setDefaultOverflowX(int defaultOverflowX) { this.defaultOverflowX = defaultOverflowX; } public void setDefaultOverflowY(int defaultOverflowY) { this.defaultOverflowY = defaultOverflowY; } private static class LayoutKey { public final int availWidth; public final int availHeight; public final FloatingBoundsSource floatBoundsSource; public final int defaultOverflowX; public final int defaultOverflowY; public final int whitespace; public final Font font; public final boolean expandWidth; public final boolean expandHeight; public final boolean useDeclaredSize; public LayoutKey(int availWidth, int availHeight, boolean expandWidth, boolean expandHeight, FloatingBoundsSource floatBoundsSource, int defaultOverflowX, int defaultOverflowY, int whitespace, Font font) { super(); this.availWidth = availWidth; this.availHeight = availHeight; this.floatBoundsSource = floatBoundsSource; this.defaultOverflowX = defaultOverflowX; this.defaultOverflowY = defaultOverflowY; this.whitespace = whitespace; this.font = font; this.expandWidth = expandWidth; this.expandHeight = expandHeight; this.useDeclaredSize = true; } public boolean equals(Object obj) { if(obj == this) { return true; } if(!(obj instanceof LayoutKey)) { return false; } LayoutKey other = (LayoutKey) obj; return other.availWidth == this.availWidth && other.availHeight == this.availHeight && other.defaultOverflowX == this.defaultOverflowX && other.defaultOverflowY == this.defaultOverflowY && other.whitespace == this.whitespace && other.expandWidth == this.expandWidth && other.expandHeight == this.expandHeight && other.useDeclaredSize == this.useDeclaredSize && Objects.equals(other.font, this.font) && Objects.equals(other.floatBoundsSource, this.floatBoundsSource); } public int hashCode() { Font font = this.font; return (this.availWidth * 1000 + this.availHeight) ^ (font == null ? 0 : font.hashCode()) ^ (this.expandWidth ? 2 : 0) ^ (this.expandHeight ? 1 : 0); } } private static class LayoutValue { public final int width; public final int height; public final boolean hasHScrollBar; public final boolean hasVScrollBar; public LayoutValue(int width, int height, boolean hasHScrollBar, boolean hasVScrollBar) { this.width = width; this.height = height; this.hasHScrollBar = hasHScrollBar; this.hasVScrollBar = hasVScrollBar; } } }libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/RBlockViewport.java0000644000175000017500000027434111134646434027474 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 16, 2005 */ package org.lobobrowser.html.renderer; import java.awt.*; import java.awt.event.MouseEvent; import java.util.*; import org.lobobrowser.html.*; import org.lobobrowser.html.style.*; import org.lobobrowser.html.domimpl.*; import org.w3c.dom.*; import java.util.logging.*; /** * A substantial portion of the HTML rendering logic of the package can * be found in this class. * This class is in charge of laying out the DOM subtree of a node, * usually on behalf of an RBlock. * It creates a renderer subtree consisting of RLine's or RBlock's. RLine's in * turn contain RWord's and so on. * This class also happens to be used as an RBlock scrollable viewport. * @author J. H. S. */ public class RBlockViewport extends BaseRCollection { // GENERAL NOTES // An RBlockViewport basically consists of two collections: // seqRenderables and positionedRenderables. The seqRenderables // collection is a sequential list of RLine's and RBlock's // that is amenable to a binary search by Y position. The // positionedRenderables collection is a z-index ordered // collection meant for blocks with position=absolute and such. // // HOW FLOATS WORK // Float boxes are scheduled to be added on the next available line. // Line layout is bounded by the current floatBounds. // When a float is placed with placeFloat(), an absolutely positioned // box is added. Whether the float height expands the RBlockViewport // height is determined by isFloatLimit(). // // FloatingBounds are inherited by sub-boxes, but the bounds are // shifted. // // The RBlockViewport also publishes a collection of "exporatable // floating bounds." These are float boxes that go beyond the bounds // of the RBlockViewport, so ancestor blocks can obtain them to adjust // their own bounds. public static final Insets ZERO_INSETS = new Insets(0, 0, 0, 0); private static final Logger logger = Logger.getLogger(RBlockViewport.class.getName()); //private final ArrayList awtComponents = new ArrayList(); private final RenderableContainer container; private final int listNesting; private final UserAgentContext userAgentContext; private final HtmlRendererContext rendererContext; private final FrameContext frameContext; private SortedSet positionedRenderables; private ArrayList seqRenderables = null; private ArrayList exportableFloats = null; // private Collection exportedRenderables; private RLine currentLine; private int maxX; private int maxY; //private int availHeight; private int desiredWidth; // includes insets private int desiredHeight; // includes insets private int availContentHeight; // does not include insets private int availContentWidth; // does not include insets private int yLimit; private int positionedOrdinal; private int currentCollapsibleMargin; private Insets paddingInsets; private boolean overrideNoWrap; private FloatingBounds floatBounds = null; private boolean sizeOnly; private BoundableRenderable lastSeqBlock; private static final Map elementLayout = new HashMap(70); private static final MarkupLayout miscLayout = new MiscLayout(); static { Map el = elementLayout; EmLayout em = new EmLayout(); el.put("I", em); el.put("EM", em); el.put("CITE", em); el.put("H1", new HLayout(24)); el.put("H2", new HLayout(18)); el.put("H3", new HLayout(15)); el.put("H4", new HLayout(12)); el.put("H5", new HLayout(10)); el.put("H6", new HLayout(8)); StrongLayout strong = new StrongLayout(); el.put("B", strong); el.put("STRONG", strong); el.put("TH", strong); el.put("U", new ULayout()); el.put("STRIKE", new StrikeLayout()); el.put("BR", new BrLayout()); el.put("P", new PLayout()); el.put("NOSCRIPT", new NoScriptLayout()); NopLayout nop = new NopLayout(); el.put("SCRIPT", nop); el.put("HEAD", nop); el.put("TITLE", nop); el.put("META", nop); el.put("STYLE", nop); el.put("LINK", nop); el.put("IMG", new ImgLayout()); el.put("TABLE", new TableLayout()); ChildrenLayout children = new ChildrenLayout(); el.put("HTML", children); AnchorLayout anchor = new AnchorLayout(); el.put("A", anchor); el.put("ANCHOR", anchor); el.put("INPUT", new InputLayout2()); el.put("TEXTAREA", new TextAreaLayout2()); el.put("SELECT", new SelectLayout()); ListItemLayout list = new ListItemLayout(); el.put("UL", list); el.put("OL", list); el.put("LI", list); CommonBlockLayout cbl = new CommonBlockLayout(); el.put("PRE", cbl); el.put("CENTER", cbl); el.put("CAPTION", cbl); DivLayout div = new DivLayout(); el.put("DIV", div); el.put("BODY", div); el.put("DL", div); el.put("DT", div); BlockQuoteLayout bq = new BlockQuoteLayout(); el.put("BLOCKQUOTE", bq); el.put("DD", bq); el.put("HR", new HrLayout()); el.put("SPAN", new SpanLayout()); ObjectLayout ol = new ObjectLayout(false, true); el.put("OBJECT", new ObjectLayout(true, true)); el.put("APPLET", ol); el.put("EMBED", ol); el.put("IFRAME", new IFrameLayout()); } /** * Constructs an HtmlBlockLayout. * @param container This is usually going to be an RBlock. * @param listNesting The nesting level for lists. This is zero except inside a list. * @param pcontext The HTMLParserContext instance. * @param frameContext This is usually going to be HtmlBlock, an object where text selections are contained. * @param parent This is usually going to be the parent of container. */ public RBlockViewport(ModelNode modelNode, RenderableContainer container, int listNesting, UserAgentContext pcontext, HtmlRendererContext rcontext, FrameContext frameContext, RCollection parent) { super(container, modelNode); this.parent = parent; this.userAgentContext = pcontext; this.rendererContext = rcontext; this.frameContext = frameContext; this.container = container; this.listNesting = listNesting; // Layout here can always be "invalidated" this.layoutUpTreeCanBeInvalidated = true; } public void invalidateLayoutLocal() { // Workaround for fact that RBlockViewport does not // get validated or invalidated. this.layoutUpTreeCanBeInvalidated = true; } public int getAvailContentWidth() { return this.availContentWidth; } private int initCollapsibleMargin() { Object parent = this.parent; if(!(parent instanceof RBlock)) { return 0; } RBlock parentBlock = (RBlock) parent; return parentBlock.getCollapsibleMarginTop(); } /** * Builds the layout/renderer tree from scratch. * Note: Returned dimension needs to be actual size needed for rendered content, * not the available container size. This is relied upon by table layout. * @param yLimit If other than -1, layout will throw SizeExceededException * in the event that the layout goes beyond this y-coordinate point. */ public void layout(int desiredWidth, int desiredHeight, Insets paddingInsets, int yLimit, FloatingBounds floatBounds, boolean sizeOnly) { // Expected in GUI thread. It's possible it may be invoked during pack() // outside of the GUI thread. if(!EventQueue.isDispatchThread() && logger.isLoggable(Level.INFO)) { logger.warning("layout(): Invoked outside GUI dispatch thread."); } RenderableContainer container = this.container; this.paddingInsets = paddingInsets; this.yLimit = yLimit; this.desiredHeight = desiredHeight; this.desiredWidth = desiredWidth; this.floatBounds = floatBounds; this.isFloatLimit = null; this.pendingFloats = null; this.sizeOnly = sizeOnly; this.lastSeqBlock = null; this.currentCollapsibleMargin = this.initCollapsibleMargin(); // maxX and maxY should not be reset by layoutPass. this.maxX = paddingInsets.left; this.maxY = paddingInsets.top; int availw = desiredWidth - paddingInsets.left - paddingInsets.right; if(availw < 0) { availw = 0; } int availh = desiredHeight - paddingInsets.top - paddingInsets.bottom; if(availh == 0) { availh = 0; } this.availContentHeight = availh; this.availContentWidth = availw; // New floating algorithm. this.layoutPass((NodeImpl) this.modelNode); Collection delayedPairs = container.getDelayedPairs(); if(delayedPairs != null && delayedPairs.size() > 0) { // Add positioned renderables that belong here Iterator i = delayedPairs.iterator(); while(i.hasNext()) { DelayedPair pair = (DelayedPair) i.next(); if(pair.targetParent == container) { this.importDelayedPair(pair); } } } // Compute maxY according to last block. int maxY = this.maxY; int maxYWholeBlock = maxY; BoundableRenderable lastSeqBlock = this.lastSeqBlock; if(lastSeqBlock != null) { int effBlockHeight = this.getEffectiveBlockHeight(lastSeqBlock); if(lastSeqBlock.getY() + effBlockHeight > maxY) { this.maxY = maxY = lastSeqBlock.getY() + effBlockHeight; maxYWholeBlock = lastSeqBlock.getY() + lastSeqBlock.getHeight(); } } // See if line should increase maxY. Empty // lines shouldn't, except in cases where // there was a BR. RLine lastLine = this.currentLine; Rectangle lastBounds = lastLine.getBounds(); if(lastBounds.height > 0 || lastBounds.y > maxYWholeBlock) { int lastTopX = lastBounds.x + lastBounds.width; if(lastTopX > this.maxX) { this.maxX = lastTopX; } int lastTopY = lastBounds.y + lastBounds.height; if(lastTopY > maxY) { this.maxY = maxY = lastTopY; } } // Check positioned renderables for maxX and maxY SortedSet posRenderables = this.positionedRenderables; if(posRenderables != null) { boolean isFloatLimit = this.isFloatLimit(); Iterator i = posRenderables.iterator(); while(i.hasNext()) { PositionedRenderable pr = (PositionedRenderable) i.next(); BoundableRenderable br = pr.renderable; if(br.getX() + br.getWidth() > this.maxX) { this.maxX = br.getX() + br.getWidth(); } if(isFloatLimit || !pr.isFloat) { if(br.getY() + br.getHeight() > maxY) { this.maxY = maxY = br.getY() + br.getHeight(); } } } } this.width = paddingInsets.right + this.maxX; this.height = paddingInsets.bottom + maxY; } private void layoutPass(NodeImpl rootNode) { RenderableContainer container = this.container; container.clearDelayedPairs(); this.positionedOrdinal = 0; // Remove sequential renderables... this.seqRenderables = null; // Remove other renderables... this.positionedRenderables = null; // Remove exporatable floats... this.exportableFloats = null; // Call addLine after setting margins this.currentLine = this.addLine(rootNode, null, this.paddingInsets.top); // Start laying out... // The parent is expected to have set the RenderState already. this.layoutChildren(rootNode); // This adds last-line floats. this.lineDone(this.currentLine); } /** * Applies any horizonal aLignment. It may adjust height if necessary. * @param canvasWidth The new width of the viewport. It could be * different to the previously calculated width. * @param paddingInsets */ public void alignX(int alignXPercent, int canvasWidth, Insets paddingInsets) { int prevMaxY = this.maxY; // Horizontal alignment if(alignXPercent > 0) { ArrayList renderables = this.seqRenderables; if(renderables != null) { Insets insets = this.paddingInsets; FloatingBounds floatBounds = this.floatBounds; int numRenderables = renderables.size(); int yoffset = 0; // This may get adjusted due to blocks and floats. for(int i = 0; i < numRenderables; i++) { Object r = renderables.get(i); if(r instanceof BoundableRenderable) { BoundableRenderable seqRenderable = (BoundableRenderable) r; int y = seqRenderable.getY(); int newY; if(yoffset > 0) { newY = y + yoffset; seqRenderable.setY(newY); if(newY + seqRenderable.getHeight() > this.maxY) { this.maxY = newY + seqRenderable.getHeight(); } } else { newY = y; } boolean isVisibleBlock = seqRenderable instanceof RBlock && ((RBlock) seqRenderable).isOverflowVisibleX(); int leftOffset = isVisibleBlock ? insets.left : this.fetchLeftOffset(y); int rightOffset = isVisibleBlock ? insets.right : this.fetchRightOffset(y); int actualAvailWidth = canvasWidth - leftOffset - rightOffset; int difference = actualAvailWidth - seqRenderable.getWidth(); if(difference > 0) { // The difference check means that only // blocks with a declared width would get adjusted? int shift = (difference * alignXPercent) / 100; // if(floatBounds != null && isVisibleBlock) { // RBlock block = (RBlock) seqRenderable; // // Block needs to layed out again. Contents need // // to shift because of float. // final int expectedWidth = availContentWidth; // final int blockShiftRight = insets.right; // final int newX = leftOffset; // FloatingBoundsSource floatBoundsSource = new ParentFloatingBoundsSource(blockShiftRight, expectedWidth, newX, newY, floatBounds); // block.layout(actualAvailWidth, this.availContentHeight, true, false, floatBoundsSource); // } if(!isVisibleBlock) { int newX = leftOffset + shift; seqRenderable.setX(newX); } } } } } } if(prevMaxY != this.maxY) { this.height += (this.maxY - prevMaxY); } } /** * Applies vertical alignment. * @param canvasHeight * @param paddingInsets */ public void alignY(int alignYPercent, int canvasHeight, Insets paddingInsets) { int prevMaxY = this.maxY; if(alignYPercent > 0) { int availContentHeight = canvasHeight - paddingInsets.top - paddingInsets.bottom; int usedHeight = this.maxY - paddingInsets.top; int difference = availContentHeight - usedHeight; if(difference > 0) { int shift = (difference * alignYPercent) / 100; ArrayList rlist = this.seqRenderables; if(rlist != null) { // Try sequential renderables first. Iterator renderables = rlist.iterator(); while(renderables.hasNext()) { Object r = renderables.next(); if(r instanceof BoundableRenderable) { BoundableRenderable line = (BoundableRenderable) r; int newY = line.getY() + shift; line.setY(newY); if(newY + line.getHeight() > this.maxY) { this.maxY = newY + line.getHeight(); } } } } // Now other renderables, but only those that can be // vertically aligned Set others = this.positionedRenderables; if(others != null) { Iterator i2 = others.iterator(); while(i2.hasNext()) { PositionedRenderable pr = (PositionedRenderable) i2.next(); if(pr.verticalAlignable) { BoundableRenderable br = pr.renderable; int newY = br.getY() + shift; br.setY(newY); if(newY + br.getHeight() > this.maxY) { this.maxY = newY + br.getHeight(); } } } } } } if(prevMaxY != this.maxY) { this.height += (this.maxY - prevMaxY); } } // /** // * // * @param block A block needing readjustment due to horizontal alignment. // * @return // */ // private int readjustBlock(RBlock block, final int newX, final int newY, final FloatingBounds floatBounds) { // final int rightInsets = this.paddingInsets.right; // final int expectedWidth = this.desiredWidth - rightInsets - newX; // final int blockShiftRight = rightInsets; // final int prevHeight = block.height; // FloatingBoundsSource floatBoundsSource = new FloatingBoundsSource() { // public FloatingBounds getChildBlockFloatingBounds(int apparentBlockWidth) { // int actualRightShift = blockShiftRight + (expectedWidth - apparentBlockWidth); // return new ShiftedFloatingBounds(floatBounds, -newX, -actualRightShift, -newY); // } // }; // block.adjust(expectedWidth, this.availContentHeight, true, false, floatBoundsSource, true); // return block.height - prevHeight; // } // private RLine addLine(ModelNode startNode, RLine prevLine, int newLineY) { // lineDone must be called before we try to // get float bounds. this.lineDone(prevLine); this.checkY(newLineY); int leftOffset = this.fetchLeftOffset(newLineY); int newX = leftOffset; int newMaxWidth = this.desiredWidth - this.fetchRightOffset(newLineY) - leftOffset; RLine rline; boolean initialAllowOverflow; if(prevLine == null) { // Note: Assumes that prevLine == null means it's the first line. RenderState rs = this.modelNode.getRenderState(); initialAllowOverflow = rs == null ? false : rs.getWhiteSpace() == RenderState.WS_NOWRAP; // Text indentation only applies to the first line in the block. int textIndent = rs == null ? 0 : rs.getTextIndent(this.availContentWidth); if(textIndent != 0) { newX += textIndent; // Line width also changes! newMaxWidth += (leftOffset - newX); } } else { int prevLineHeight = prevLine.getHeight(); if(prevLineHeight > 0) { this.currentCollapsibleMargin = 0; } initialAllowOverflow = prevLine.isAllowOverflow(); if(prevLine.x + prevLine.width > this.maxX) { this.maxX = prevLine.x + prevLine.width; } } rline = new RLine(startNode, this.container, newX, newLineY, newMaxWidth, 0, initialAllowOverflow); rline.setParent(this); ArrayList sr = this.seqRenderables; if(sr == null) { sr = new ArrayList(1); this.seqRenderables = sr; } sr.add(rline); this.currentLine = rline; return rline; } private void layoutMarkup(NodeImpl node) { // This is the "inline" layout of an element. // The difference with layoutChildren is that this // method checks for padding and margin insets. RenderState rs = node.getRenderState(); Insets marginInsets = null; Insets paddingInsets = null; if(rs != null) { HtmlInsets mi = rs.getMarginInsets(); marginInsets = mi == null ? null : mi.getSimpleAWTInsets(this.availContentWidth, this.availContentHeight); HtmlInsets pi = rs.getPaddingInsets(); paddingInsets = pi == null ? null : pi.getSimpleAWTInsets(this.availContentWidth, this.availContentHeight); } int leftSpacing = 0; int rightSpacing = 0; if(marginInsets != null) { leftSpacing += marginInsets.left; rightSpacing += marginInsets.right; } if(paddingInsets != null) { leftSpacing += paddingInsets.left; rightSpacing += paddingInsets.right; } if(leftSpacing > 0) { RLine line = this.currentLine; line.addSpacing(new RSpacing(node, this.container, leftSpacing, line.height)); } this.layoutChildren( node); if(rightSpacing > 0) { RLine line = this.currentLine; line.addSpacing(new RSpacing(node, this.container, rightSpacing, line.height)); } } private void layoutChildren(NodeImpl node) { NodeImpl[] childrenArray = node.getChildrenArray(); if(childrenArray != null) { int length = childrenArray.length; for(int i = 0; i < length; i++) { NodeImpl child = childrenArray[i]; short nodeType = child.getNodeType(); if(nodeType == Node.TEXT_NODE) { this.layoutText( child); } else if(nodeType == Node.ELEMENT_NODE) { // Note that scanning for node bounds (anchor location) // depends on there being a style changer for inline elements. this.currentLine.addStyleChanger(new RStyleChanger(child)); String nodeName = child.getNodeName().toUpperCase(); MarkupLayout ml = (MarkupLayout) elementLayout.get(nodeName); if(ml == null) { ml = miscLayout; } ml.layoutMarkup(this, (HTMLElementImpl) child); this.currentLine.addStyleChanger(new RStyleChanger(node)); } else if(nodeType == Node.COMMENT_NODE || nodeType == Node.PROCESSING_INSTRUCTION_NODE) { // ignore } else { throw new IllegalStateException("Unknown node: " + child); } } } } private final void positionRBlock(HTMLElementImpl markupElement, RBlock renderable) { if(!this.addElsewhereIfPositioned( renderable, markupElement, false, true, false)) { int availContentHeight = this.availContentHeight; RLine line = this.currentLine; // Inform line done before layout so floats are considered. this.lineDone(line); Insets paddingInsets = this.paddingInsets; int newLineY = line == null ? paddingInsets.top : line.y + line.height; //int leftOffset = this.fetchLeftOffset(newLineY); //int rightOffset = this.fetchRightOffset(newLineY); // Float offsets are ignored with block. int availContentWidth = this.availContentWidth; final int expectedWidth = availContentWidth; final int blockShiftRight = paddingInsets.right; final int newX = paddingInsets.left; final int newY = newLineY; FloatingBounds floatBounds = this.floatBounds; FloatingBoundsSource floatBoundsSource = floatBounds == null ? null : new ParentFloatingBoundsSource(blockShiftRight, expectedWidth, newX, newY, floatBounds); renderable.layout(availContentWidth, availContentHeight, true, false, floatBoundsSource, this.sizeOnly); this.addAsSeqBlock(renderable, false, false, false, false); // Calculate new floating bounds after block has been put in place. FloatingInfo floatingInfo = renderable.getExportableFloatingInfo(); if(floatingInfo != null) { this.importFloatingInfo(floatingInfo, renderable); } // Now add line, after float is set. this.addLineAfterBlock(renderable, false); } } private final void positionRElement(HTMLElementImpl markupElement, RElement renderable, boolean usesAlignAttribute, boolean obeysFloats, boolean alignCenterAttribute) { if(!this.addElsewhereIfPositioned( renderable, markupElement, usesAlignAttribute, true, true)) { int availContentWidth = this.availContentWidth; int availContentHeight = this.availContentHeight; RLine line = this.currentLine; // Inform line done before layout so floats are considered. this.lineDone(line); if(obeysFloats) { int newLineY = line == null ? this.paddingInsets.top : line.y + line.height; int leftOffset = this.fetchLeftOffset(newLineY); int rightOffset = this.fetchRightOffset(newLineY); availContentWidth = this.desiredWidth - leftOffset - rightOffset; } renderable.layout(availContentWidth, availContentHeight, this.sizeOnly); boolean centerBlock = false; if(alignCenterAttribute) { String align = markupElement.getAttribute("align"); centerBlock = align != null && align.equalsIgnoreCase("center"); } this.addAsSeqBlock(renderable, obeysFloats, false, true, centerBlock); } } private final void layoutRBlock(HTMLElementImpl markupElement) { RBlock renderable = (RBlock) markupElement.getUINode(); if(renderable == null) { renderable = new RBlock(markupElement, this.listNesting, this.userAgentContext, this.rendererContext, this.frameContext, this.container); markupElement.setUINode(renderable); } renderable.setOriginalParent(this); this.positionRBlock( markupElement, renderable); } private final void layoutRTable(HTMLElementImpl markupElement) { RElement renderable = (RElement) markupElement.getUINode(); if(renderable == null) { renderable = new RTable(markupElement, this.userAgentContext, this.rendererContext, this.frameContext, container); markupElement.setUINode((UINode) renderable); } renderable.setOriginalParent(this); this.positionRElement(markupElement, renderable, markupElement instanceof HTMLTableElementImpl, true, true); } private final void layoutListItem(HTMLElementImpl markupElement) { RListItem renderable = (RListItem) markupElement.getUINode(); if(renderable == null) { renderable = new RListItem(markupElement, this.listNesting, this.userAgentContext, this.rendererContext, this.frameContext, this.container, null); markupElement.setUINode(renderable); } renderable.setOriginalParent(this); this.positionRBlock( markupElement, renderable); } private final void layoutList(HTMLElementImpl markupElement) { RList renderable = (RList) markupElement.getUINode(); if(renderable == null) { renderable = new RList(markupElement, this.listNesting, this.userAgentContext, this.rendererContext, this.frameContext, this.container, null); markupElement.setUINode(renderable); } renderable.setOriginalParent(this); this.positionRBlock( markupElement, renderable); } // private void addParagraphBreak(ModelNode startNode) { // // This needs to get replaced with paragraph collapsing // this.addLineBreak(startNode, LineBreak.NONE); // this.addLineBreak(startNode, LineBreak.NONE); // } private void addLineBreak(ModelNode startNode, int breakType) { RLine line = this.currentLine; if(line == null) { Insets insets = this.paddingInsets; this.addLine(startNode, null, insets.top); line = this.currentLine; } if(line.getHeight() == 0) { RenderState rs = startNode.getRenderState(); int fontHeight = rs.getFontMetrics().getHeight(); line.setHeight(fontHeight); } line.setLineBreak(new LineBreak(breakType, startNode)); int newLineY; FloatingBounds fb = this.floatBounds; if(breakType == LineBreak.NONE || fb == null) { newLineY = line == null ? this.paddingInsets.top : line.y + line.height; } else { int prevY = line == null ? this.paddingInsets.top : line.y + line.height; switch(breakType) { case LineBreak.LEFT: newLineY = fb.getLeftClearY(prevY); break; case LineBreak.RIGHT: newLineY = fb.getRightClearY(prevY); break; default: newLineY = fb.getClearY(prevY); break; } } this.currentLine = this.addLine(startNode, line, newLineY); } private boolean addElsewhereIfFloat(BoundableRenderable renderable, HTMLElementImpl element, boolean usesAlignAttribute, AbstractCSS2Properties style, boolean layout) { // "static" handled here String align = null; if(style != null) { align = style.getFloat(); if(align != null && align.length() == 0) { align = null; } } if(align == null && usesAlignAttribute) { align = element.getAttribute("align"); } if(align != null) { if("left".equalsIgnoreCase(align)) { this.layoutFloat(renderable, layout, true); return true; } else if("right".equalsIgnoreCase(align)) { this.layoutFloat(renderable, layout, false); return true; } else { // fall through } } return false; } // final RBlockViewport getParentViewport(ExportedRenderable er) { // if(er.alignment == 0) { // return this.getParentViewport(); // } // else { // return this.getParentViewportForAlign(); // } // } // // final boolean isImportable(ExportedRenderable er) { // if(er.alignment == 0) { // return this.positionsAbsolutes(); // } // else { // return this.getParentViewportForAlign() == null; // } // } final RBlockViewport getParentViewport() { // Use originalParent, which for one, is not going to be null during layout. RCollection parent = this.getOriginalOrCurrentParent(); while(parent != null && !(parent instanceof RBlockViewport)) { parent = parent.getOriginalOrCurrentParent(); } return (RBlockViewport) parent; } // final RBlockViewport getParentViewportForAlign() { // // Use originalParent, which for one, is not going to be null during layout. // Object parent = this.getOriginalOrCurrentParent(); // if(parent instanceof RBlock) { // RBlock block = (RBlock) parent; // if(!block.couldBeScrollable()) { // parent = ((BaseElementRenderable) parent).getOriginalOrCurrentParent(); // if(parent instanceof RBlockViewport) { // return (RBlockViewport) parent; // } // } // } // return null; // } // private static int getPosition(HTMLElementImpl element) { RenderState rs = element.getRenderState(); return rs == null ? RenderState.POSITION_STATIC : rs.getPosition(); } /** * Checks for position and float attributes. * @param container * @param containerSize * @param insets * @param renderable * @param element * @param usesAlignAttribute * @return True if it was added elsewhere. */ private boolean addElsewhereIfPositioned(RElement renderable, HTMLElementImpl element, boolean usesAlignAttribute, boolean layoutIfPositioned, boolean obeysFloats) { // At this point block already has bounds. AbstractCSS2Properties style = element.getCurrentStyle(); int position = getPosition(element); boolean absolute = position == RenderState.POSITION_ABSOLUTE; boolean relative = position == RenderState.POSITION_RELATIVE; if(absolute || relative) { if(layoutIfPositioned) { // Presumes the method will return true. if(renderable instanceof RBlock) { RBlock block = (RBlock) renderable; FloatingBoundsSource inheritedFloatBoundsSource = null; if(relative) { Insets paddingInsets = this.paddingInsets; RLine line = this.currentLine; // Inform line done before layout so floats are considered. this.lineDone(line); int newY = line == null ? paddingInsets.top : line.y + line.height; final int expectedWidth = this.availContentWidth; final int blockShiftRight = paddingInsets.right; final int newX = paddingInsets.left; FloatingBounds floatBounds = this.floatBounds; inheritedFloatBoundsSource = floatBounds == null ? null : new ParentFloatingBoundsSource(blockShiftRight, expectedWidth, newX, newY, floatBounds); } block.layout(this.availContentWidth, this.availContentHeight, false, false, inheritedFloatBoundsSource, this.sizeOnly); } else { renderable.layout(this.availContentWidth, this.availContentHeight, this.sizeOnly); } } RenderState rs = element.getRenderState(); String leftText = style.getLeft(); RLine line = this.currentLine; int lineBottomY = line == null ? 0 : line.getY() + line.getHeight(); int newLeft; if(leftText != null) { newLeft = HtmlValues.getPixelSize(leftText, rs, 0, this.availContentWidth); } else { String rightText = style.getRight(); if(rightText != null) { int right = HtmlValues.getPixelSize(rightText, rs, 0, this.availContentWidth); newLeft = this.desiredWidth - right - renderable.getWidth(); // If right==0 and renderable.width is larger than the parent's width, // the expected behavior is for newLeft to be negative. } else { newLeft = 0; } } int newTop = relative ? 0 : lineBottomY; String topText = style.getTop(); if(topText != null) { newTop = HtmlValues.getPixelSize(topText, rs, newTop, this.availContentHeight); } else { String bottomText = style.getBottom(); if(bottomText != null) { int bottom = HtmlValues.getPixelSize(bottomText, rs, 0, this.availContentHeight); newTop = this.desiredHeight - bottom - renderable.getHeight(); if(!relative && newTop < 0) { newTop = 0; } } } if(relative) { // First, try to add normally. RRelative rrel = new RRelative(this.container, element, renderable, newLeft, newTop); rrel.assignDimension(); if(!this.addElsewhereIfFloat(rrel, element, usesAlignAttribute, style, true)) { boolean centerBlock = false; if(renderable instanceof RTable) { String align = element.getAttribute("align"); centerBlock = align != null && align.equalsIgnoreCase("center"); } this.addAsSeqBlock(rrel, obeysFloats, true, true, centerBlock); // Need to import float boxes from relative, after // the box's origin has been set. FloatingInfo floatingInfo = rrel.getExportableFloatingInfo(); if(floatingInfo != null) { this.importFloatingInfo(floatingInfo, rrel); } } else { // Adjust size of RRelative again - float might have been adjusted. rrel.assignDimension(); } } else { // Schedule as delayed pair. Will be positioned after // everything else. this.scheduleAbsDelayedPair(renderable, newLeft, newTop); // Does not affect bounds of this viewport yet. return true; } int newBottomY = renderable.getY() + renderable.getHeight(); this.checkY(newBottomY); if(newBottomY > this.maxY) { this.maxY = newBottomY; } return true; } else { if(this.addElsewhereIfFloat( renderable, element, usesAlignAttribute, style, layoutIfPositioned)) { return true; } } return false; } /** * Checks property 'float' and in some cases attribute 'align'. */ private void addRenderableToLineCheckStyle(RElement renderable, HTMLElementImpl element, boolean usesAlignAttribute) { if(this.addElsewhereIfPositioned( renderable, element, usesAlignAttribute, true, true)) { return; } renderable.layout(this.availContentWidth, this.availContentHeight, this.sizeOnly); this.addRenderableToLine(renderable); } private void addRenderableToLine(Renderable renderable) { //this.skipLineBreakBefore = false; RenderState rs = renderable.getModelNode().getRenderState(); RLine line = this.currentLine; int liney = line.y; boolean emptyLine = line.isEmpty(); FloatingBounds floatBounds = this.floatBounds; int cleary; if(floatBounds != null) { cleary = floatBounds.getFirstClearY(liney); } else { cleary = liney + line.height; } try { line.add(renderable); // Check if the line goes into the float. if(floatBounds != null && cleary > liney) { int rightOffset = this.fetchRightOffset(liney); int topLineX = this.desiredWidth - rightOffset; if(line.getX() + line.getWidth() > topLineX) { // Shift line down to clear area line.setY(cleary); } } } catch(OverflowException oe) { int nextY = emptyLine ? cleary : liney + line.height; this.addLine(renderable.getModelNode(), line, nextY); Collection renderables = oe.getRenderables(); Iterator i = renderables.iterator(); while(i.hasNext()) { Renderable r = (Renderable) i.next(); this.addRenderableToLine(r); } } if(renderable instanceof RUIControl) { this.container.addComponent(((RUIControl) renderable).widget.getComponent()); } } private void addWordToLine(RWord renderable) { //this.skipLineBreakBefore = false; RLine line = this.currentLine; int liney = line.y; boolean emptyLine = line.isEmpty(); FloatingBounds floatBounds = this.floatBounds; int cleary; if(floatBounds != null) { cleary = floatBounds.getFirstClearY(liney); } else { cleary = liney + line.height; } try { line.addWord(renderable); // Check if the line goes into the float. if(floatBounds != null && cleary > liney) { int rightOffset = this.fetchRightOffset(liney); int topLineX = this.desiredWidth - rightOffset; if(line.getX() + line.getWidth() > topLineX) { // Shift line down to clear area line.setY(cleary); } } } catch(OverflowException oe) { int nextY = emptyLine ? cleary : liney + line.height; this.addLine(renderable.getModelNode(), line, nextY); Collection renderables = oe.getRenderables(); Iterator i = renderables.iterator(); while(i.hasNext()) { Renderable r = (Renderable) i.next(); this.addRenderableToLine(r); } } } private void addAsSeqBlockCheckStyle(RElement block, HTMLElementImpl element, boolean usesAlignAttribute) { if(this.addElsewhereIfPositioned(block, element, usesAlignAttribute, false, true)) { return; } this.addAsSeqBlock(block); } private void addAsSeqBlock(RElement block) { this.addAsSeqBlock(block, true, true, true, false); } private int getNewBlockY(BoundableRenderable newBlock, int expectedY) { // Assumes the previous block is not a line with height > 0. if(!(newBlock instanceof RElement)) { return expectedY; } RElement block = (RElement) newBlock; int ccm = this.currentCollapsibleMargin; int topMargin = block.getMarginTop(); if(topMargin == 0 && ccm == 0) { return expectedY; } return expectedY - Math.min(topMargin, ccm); } private int getEffectiveBlockHeight(BoundableRenderable block) { // Assumes block is the last one in the sequence. if(!(block instanceof RElement)) { return block.getHeight(); } RCollection parent = this.getParent(); if(!(parent instanceof RElement)) { return block.getHeight(); } int blockMarginBottom = ((RElement) block).getMarginBottom(); int parentMarginBottom = ((RElement) parent).getCollapsibleMarginBottom(); return block.getHeight() - Math.min(blockMarginBottom, parentMarginBottom); } private void addAsSeqBlock(BoundableRenderable block, boolean obeysFloats, boolean informLineDone, boolean addLine, boolean centerBlock) { Insets insets = this.paddingInsets; int insetsl = insets.left; ArrayList sr = this.seqRenderables; if(sr == null) { sr = new ArrayList(1); this.seqRenderables = sr; } RLine prevLine = this.currentLine; boolean initialAllowOverflow; if(prevLine != null) { initialAllowOverflow = prevLine.isAllowOverflow(); if(informLineDone) { this.lineDone(prevLine); } if(prevLine.x + prevLine.width > this.maxX) { this.maxX = prevLine.x + prevLine.width; } // Check height only with floats. } else { initialAllowOverflow = false; } int prevLineHeight = prevLine == null ? 0 : prevLine.height; int newLineY = prevLine == null ? insets.top : prevLine.y + prevLineHeight; int blockX; int blockY = prevLineHeight == 0 ? this.getNewBlockY(block, newLineY) : newLineY; int blockWidth = block.getWidth(); if(obeysFloats) { //TODO: execution of fetchLeftOffset done twice with positionRElement. FloatingBounds floatBounds = this.floatBounds; int actualAvailWidth; if(floatBounds != null) { int blockOffset = this.fetchLeftOffset(newLineY); blockX = blockOffset; int rightOffset = this.fetchRightOffset(newLineY); actualAvailWidth = this.desiredWidth - rightOffset - blockOffset; if(blockWidth > actualAvailWidth) { blockY = floatBounds.getClearY(newLineY); } } else { actualAvailWidth = this.availContentWidth; blockX = insetsl; } if(centerBlock) { int roomX = actualAvailWidth - blockWidth; if(roomX > 0) { blockX += (roomX / 2); } } } else { //Block does not obey alignment margins blockX = insetsl; } block.setOrigin(blockX, blockY); sr.add(block); block.setParent(this); if(blockX + blockWidth > this.maxX) { this.maxX = blockX + blockWidth; } this.lastSeqBlock = block; this.currentCollapsibleMargin = block instanceof RElement ? ((RElement) block).getMarginBottom() : 0; if(addLine) { newLineY = blockY + block.getHeight(); this.checkY(newLineY); int leftOffset = this.fetchLeftOffset(newLineY); int newX = leftOffset; int newMaxWidth = this.desiredWidth - this.fetchRightOffset(newLineY) - leftOffset; ModelNode lineNode = block.getModelNode().getParentModelNode(); RLine newLine = new RLine(lineNode, this.container, newX, newLineY, newMaxWidth, 0, initialAllowOverflow); newLine.setParent(this); sr.add(newLine); this.currentLine = newLine; } } private void addLineAfterBlock(RBlock block, boolean informLineDone) { ArrayList sr = this.seqRenderables; if(sr == null) { sr = new ArrayList(1); this.seqRenderables = sr; } RLine prevLine = this.currentLine; boolean initialAllowOverflow; if(prevLine != null) { initialAllowOverflow = prevLine.isAllowOverflow(); if(informLineDone) { this.lineDone(prevLine); } if(prevLine.x + prevLine.width > this.maxX) { this.maxX = prevLine.x + prevLine.width; } // Check height only with floats. } else { initialAllowOverflow = false; } ModelNode lineNode = block.getModelNode().getParentModelNode(); int newLineY = block.getY() + block.getHeight(); this.checkY(newLineY); int leftOffset = this.fetchLeftOffset(newLineY); int newX = leftOffset; int newMaxWidth = this.desiredWidth - this.fetchRightOffset(newLineY) - leftOffset; RLine newLine = new RLine(lineNode, this.container, newX, newLineY, newMaxWidth, 0, initialAllowOverflow); newLine.setParent(this); sr.add(newLine); this.currentLine = newLine; } private void layoutText(NodeImpl textNode) { RenderState renderState = textNode.getRenderState(); if(renderState == null) { throw new IllegalStateException("RenderState is null for node " + textNode + " with parent " + textNode.getParentNode()); } FontMetrics fm = renderState.getFontMetrics(); int descent = fm.getDescent(); int ascentPlusLeading = fm.getAscent() + fm.getLeading(); int wordHeight = fm.getHeight(); int blankWidth = fm.charWidth(' '); int whiteSpace = this.overrideNoWrap ? RenderState.WS_NOWRAP : renderState.getWhiteSpace(); int textTransform = renderState.getTextTransform(); String text = textNode.getNodeValue(); if(whiteSpace != RenderState.WS_PRE) { boolean prevAllowOverflow = this.currentLine.isAllowOverflow(); boolean allowOverflow = whiteSpace == RenderState.WS_NOWRAP; this.currentLine.setAllowOverflow(allowOverflow); try { int length = text.length(); boolean firstWord = true; StringBuffer word = new StringBuffer(12); for(int i = 0; i < length; i++) { char ch = text.charAt(i); if(Character.isWhitespace(ch)) { if(firstWord) { firstWord = false; } int wlen = word.length(); if(wlen > 0) { RWord rword = new RWord(textNode, word.toString(), container, fm, descent, ascentPlusLeading, wordHeight, textTransform); this.addWordToLine(rword); word.delete(0, wlen); } RLine line = this.currentLine; if(line.width > 0) { RBlank rblank = new RBlank(textNode, fm, container, ascentPlusLeading, blankWidth, wordHeight); line.addBlank(rblank); } for(i++; i < length; i++) { ch = text.charAt(i); if(!Character.isWhitespace(ch)) { word.append(ch); break; } } } else { word.append(ch); } } if(word.length() > 0) { RWord rword = new RWord(textNode, word.toString(), container, fm, descent, ascentPlusLeading, wordHeight, textTransform); this.addWordToLine(rword); } } finally { this.currentLine.setAllowOverflow(prevAllowOverflow); } } else { int length = text.length(); boolean lastCharSlashR = false; StringBuffer line = new StringBuffer(); for(int i = 0; i < length; i++) { char ch = text.charAt(i); switch(ch) { case '\r': lastCharSlashR = true; break; case '\n': int llen = line.length(); if(llen > 0) { RWord rword = new RWord(textNode, line.toString(), container, fm, descent, ascentPlusLeading, wordHeight, textTransform); this.addWordToLine(rword); line.delete(0, line.length()); } RLine prevLine = this.currentLine; prevLine.setLineBreak(new LineBreak(LineBreak.NONE, textNode)); this.addLine(textNode, prevLine, prevLine.y + prevLine.height); break; default: if(lastCharSlashR) { line.append('\r'); lastCharSlashR = false; } line.append(ch); break; } } if(line.length() > 0) { RWord rword = new RWord(textNode, line.toString(), container, fm, descent, ascentPlusLeading, wordHeight, textTransform); this.addWordToLine(rword); } } } /** * * @param others An ordered collection. * @param seqRenderables * @param destination */ private void populateZIndexGroups(Collection others, Collection seqRenderables, ArrayList destination) { this.populateZIndexGroups(others, seqRenderables == null ? null : seqRenderables.iterator(), destination); } /** * * @param others An ordered collection. * @param seqRenderablesIterator * @param destination */ private void populateZIndexGroups(Collection others, Iterator seqRenderablesIterator, ArrayList destination) { // First, others with z-index < 0 Iterator i1 = others.iterator(); Renderable pending = null; while(i1.hasNext()) { PositionedRenderable pr = (PositionedRenderable) i1.next(); BoundableRenderable r = pr.renderable; if(r.getZIndex() >= 0) { pending = r; break; } destination.add(r); } // Second, sequential renderables Iterator i2 = seqRenderablesIterator; if(i2 != null) { while(i2.hasNext()) { destination.add(i2.next()); } } // Third, other renderables with z-index >= 0. if(pending != null) { destination.add(pending); while(i1.hasNext()) { PositionedRenderable pr = (PositionedRenderable) i1.next(); Renderable r = pr.renderable; destination.add(r); } } } public Renderable[] getRenderablesArray() { SortedSet others = this.positionedRenderables; int othersSize = others == null ? 0 : others.size(); if(othersSize == 0) { ArrayList sr = this.seqRenderables; return sr == null ? Renderable.EMPTY_ARRAY : (Renderable[]) sr.toArray(Renderable.EMPTY_ARRAY); } else { ArrayList allRenderables = new ArrayList(); this.populateZIndexGroups(others, this.seqRenderables, allRenderables); return (Renderable[]) allRenderables.toArray(Renderable.EMPTY_ARRAY); } } public Iterator getRenderables() { SortedSet others = this.positionedRenderables; if(others == null || others.size() == 0) { ArrayList sr = this.seqRenderables; return sr == null ? null : sr.iterator(); } else { ArrayList allRenderables = new ArrayList(); this.populateZIndexGroups(others, this.seqRenderables, allRenderables); return allRenderables.iterator(); } } public Iterator getRenderables(Rectangle clipBounds) { if(!EventQueue.isDispatchThread() && logger.isLoggable(Level.INFO)) { logger.warning("getRenderables(): Invoked outside GUI dispatch thread."); } ArrayList sr = this.seqRenderables; Iterator baseIterator = null; if(sr != null) { Renderable[] array = (Renderable[]) sr.toArray(Renderable.EMPTY_ARRAY); Range range = MarkupUtilities.findRenderables(array, clipBounds, true); baseIterator = org.lobobrowser.util.ArrayUtilities.iterator(array, range.offset, range.length); } SortedSet others = this.positionedRenderables; if(others == null || others.size() == 0) { return baseIterator; } else { ArrayList matches = new ArrayList(); // ArrayList "matches" keeps the order from "others". Iterator i = others.iterator(); while(i.hasNext()) { PositionedRenderable pr = (PositionedRenderable) i.next(); Object r = pr.renderable; if(r instanceof BoundableRenderable) { BoundableRenderable br = (BoundableRenderable) r; Rectangle rbounds = br.getBounds(); if(clipBounds.intersects(rbounds)) { matches.add(pr); } } } if(matches.size() == 0) { return baseIterator; } else { ArrayList destination = new ArrayList(); this.populateZIndexGroups(matches, baseIterator, destination); return destination.iterator(); } } } public BoundableRenderable getRenderable(int x, int y) { Iterator i = this.getRenderables(x, y); return i == null ? null : (i.hasNext() ? (BoundableRenderable) i.next() : null); } public BoundableRenderable getRenderable(java.awt.Point point) { return this.getRenderable(point.x, point.y); } public Iterator getRenderables(java.awt.Point point) { return this.getRenderables(point.x, point.y); } public Iterator getRenderables(int pointx, int pointy) { if(!EventQueue.isDispatchThread() && logger.isLoggable(Level.INFO)) { logger.warning("getRenderable(): Invoked outside GUI dispatch thread."); } Collection result = null; SortedSet others = this.positionedRenderables; int size = others == null ? 0 : others.size(); PositionedRenderable[] otherArray = size == 0 ? null : (PositionedRenderable[]) others.toArray(PositionedRenderable.EMPTY_ARRAY); // Try to find in other renderables with z-index >= 0 first. int index = 0; if(size != 0) { int px = pointx; int py = pointy; // Must go in reverse order for(index = size; --index >= 0;) { PositionedRenderable pr = otherArray[index]; BoundableRenderable r = pr.renderable; if(r.getZIndex() < 0) { break; } if(r instanceof BoundableRenderable) { BoundableRenderable br = (BoundableRenderable) r; Rectangle rbounds = br.getBounds(); if(rbounds.contains(px, py)) { if(result == null) { result = new LinkedList(); } result.add(br); } } } } // Now do a "binary" search on sequential renderables. ArrayList sr = this.seqRenderables; if(sr != null) { Renderable[] array = (Renderable[]) sr.toArray(Renderable.EMPTY_ARRAY); BoundableRenderable found = MarkupUtilities.findRenderable(array, pointx, pointy, true); if(found != null) { if(result == null) { result = new LinkedList(); } result.add(found); } } // Finally, try to find it in renderables with z-index < 0. if(size != 0) { int px = pointx; int py = pointy; // Must go in reverse order for(; index >= 0; index--) { PositionedRenderable pr = otherArray[index]; Renderable r = pr.renderable; if(r instanceof BoundableRenderable) { BoundableRenderable br = (BoundableRenderable) r; Rectangle rbounds = br.getBounds(); if(rbounds.contains(px, py)) { if(result == null) { result = new LinkedList(); } result.add(br); } } } } return result == null ? null : result.iterator(); } private RElement setupNewUIControl(RenderableContainer container, HTMLElementImpl element, UIControl control) { RElement renderable = new RUIControl(element, control, container, this.frameContext, this.userAgentContext); element.setUINode((UINode) renderable); return renderable; } private final void addAlignableAsBlock(HTMLElementImpl markupElement, RElement renderable) { //TODO: Get rid of this method? // At this point block already has bounds. boolean regularAdd = false; String align = markupElement.getAttribute("align"); if(align != null) { if("left".equalsIgnoreCase(align)) { this.layoutFloat(renderable, false, true); } else if("right".equalsIgnoreCase(align)) { this.layoutFloat(renderable, false, false); } else { regularAdd = true; } } else { regularAdd = true; } if(regularAdd) { this.addAsSeqBlock(renderable); } } private final void layoutHr(HTMLElementImpl markupElement) { RElement renderable = (RElement) markupElement.getUINode(); if(renderable == null) { renderable = this.setupNewUIControl(container, markupElement, new HrControl(markupElement)); } renderable.layout(this.availContentWidth, this.availContentHeight, this.sizeOnly); this.addAlignableAsBlock( markupElement, renderable); } private final BaseInputControl createInputControl(HTMLBaseInputElement markupElement) { String type = markupElement.getAttribute("type"); if(type == null) { return new InputTextControl(markupElement); } type = type.toLowerCase(); if("text".equals(type) || type.length() == 0) { return new InputTextControl(markupElement); } else if("hidden".equals(type)) { return null; } else if("submit".equals(type)) { return new InputButtonControl(markupElement); } else if("password".equals(type)) { return new InputPasswordControl(markupElement); } else if("radio".equals(type)) { return new InputRadioControl(markupElement); } else if("checkbox".equals(type)) { return new InputCheckboxControl(markupElement); } else if("image".equals(type)) { return new InputImageControl(markupElement); } else if("reset".equals(type)) { return new InputButtonControl(markupElement); } else if("button".equals(type)) { return new InputButtonControl(markupElement); } else if("file".equals(type)) { return new InputFileControl(markupElement); } else { return null; } } /** * Gets offset from the left due to floats. It includes padding. */ private final int fetchLeftOffset(int newLineY) { Insets paddingInsets = this.paddingInsets; FloatingBounds floatBounds = this.floatBounds; if(floatBounds == null) { return paddingInsets.left; } int left = floatBounds.getLeft(newLineY); if(left < paddingInsets.left) { return paddingInsets.left; } return left; } /** * Gets offset from the right due to floats. It includes padding. */ private final int fetchRightOffset(int newLineY) { Insets paddingInsets = this.paddingInsets; FloatingBounds floatBounds = this.floatBounds; if(floatBounds == null) { return paddingInsets.right; } int right = floatBounds.getRight(newLineY); if(right < paddingInsets.right) { return paddingInsets.right; } return right; } private static final SizeExceededException SEE = new SizeExceededException(); private final void checkY(int y) { if(this.yLimit != -1 && y > this.yLimit) { throw SEE; } } private final void layoutFloat(BoundableRenderable renderable, boolean layout, boolean leftFloat) { renderable.setOriginalParent(this); if(layout) { int availWidth = this.availContentWidth; int availHeight = this.availContentHeight; if(renderable instanceof RBlock) { RBlock block = (RBlock) renderable; // Float boxes don't inherit float bounds? block.layout(availWidth, availHeight, false, false, null, this.sizeOnly); } else if(renderable instanceof RElement) { RElement e = (RElement) renderable; e.layout(availWidth, availHeight, this.sizeOnly); } } RFloatInfo floatInfo = new RFloatInfo(renderable.getModelNode(), renderable, leftFloat); this.currentLine.simplyAdd(floatInfo); this.scheduleFloat(floatInfo); } private void scheduleAbsDelayedPair(BoundableRenderable renderable, int x, int y) { // It gets reimported in the local // viewport if it turns out it can't be exported up. RenderableContainer container = this.container; for(;;) { if(container instanceof Renderable) { Object node = ((Renderable) container).getModelNode(); if(node instanceof HTMLElementImpl) { HTMLElementImpl element = (HTMLElementImpl) node; int position = getPosition(element); if(position != RenderState.POSITION_STATIC) { break; } RenderableContainer newContainer = container.getParentContainer(); if(newContainer == null) { break; } container = newContainer; } else { break; } } else { break; } } DelayedPair pair = new DelayedPair(container, renderable, x, y); this.container.addDelayedPair(pair); } void importDelayedPair(DelayedPair pair) { BoundableRenderable r = pair.child; r.setOrigin(pair.x, pair.y); this.addPositionedRenderable(r, false, false); // Size of block does not change - it's // set in stone? } private final void addPositionedRenderable(BoundableRenderable renderable, boolean verticalAlignable, boolean isFloat) { // Expected to be called only in GUI thread. SortedSet others = this.positionedRenderables; if(others == null) { others = new TreeSet(new ZIndexComparator()); this.positionedRenderables = others; } others.add(new PositionedRenderable(renderable, verticalAlignable, this.positionedOrdinal++, isFloat)); renderable.setParent(this); if(renderable instanceof RUIControl) { this.container.addComponent(((RUIControl) renderable).widget.getComponent()); } } public int getFirstLineHeight() { ArrayList renderables = this.seqRenderables; if(renderables != null) { int size = renderables.size(); if(size == 0) { return 0; } for(int i = 0; i < size; i++) { BoundableRenderable br = (BoundableRenderable) renderables.get(0); int height = br.getHeight(); if(height != 0) { return height; } } } // Not found!! return 1; } public int getFirstBaselineOffset() { ArrayList renderables = this.seqRenderables; if(renderables != null) { Iterator i = renderables.iterator(); while(i.hasNext()) { Object r = i.next(); if(r instanceof RLine) { int blo =((RLine) r).getBaselineOffset(); if(blo != 0) { return blo; } } else if(r instanceof RBlock) { RBlock block = (RBlock) r; if(block.getHeight() > 0) { Insets insets = block.getInsets(false, false); Insets paddingInsets = this.paddingInsets; return block.getFirstBaselineOffset() + insets.top + (paddingInsets == null ? 0 : paddingInsets.top); } } } } return 0; } //---------------------------------------------------------------- public RenderableSpot getLowestRenderableSpot(int x, int y) { BoundableRenderable br = this.getRenderable(new Point(x, y)); if(br != null) { return br.getLowestRenderableSpot(x - br.getX(), y - br.getY()); } else { return new RenderableSpot(this, x, y); } } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BoundableRenderable#onMouseClick(java.awt.event.MouseEvent, int, int) */ public boolean onMouseClick(MouseEvent event, int x, int y) { Iterator i = this.getRenderables(new Point(x, y)); if(i != null) { while(i.hasNext()) { BoundableRenderable br = (BoundableRenderable) i.next(); if(br != null) { Rectangle bounds = br.getBounds(); if(!br.onMouseClick(event, x - bounds.x, y - bounds.y)) { return false; } } } } return true; } public boolean onDoubleClick(MouseEvent event, int x, int y) { Iterator i = this.getRenderables(new Point(x, y)); if(i != null) { while(i.hasNext()) { BoundableRenderable br = (BoundableRenderable) i.next(); if(br != null) { Rectangle bounds = br.getBounds(); if(!br.onDoubleClick(event, x - bounds.x, y - bounds.y)) { return false; } } } } return true; } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BoundableRenderable#onMouseDisarmed(java.awt.event.MouseEvent) */ public boolean onMouseDisarmed(MouseEvent event) { BoundableRenderable br = this.armedRenderable; if(br != null) { try { return br.onMouseDisarmed(event); } finally { this.armedRenderable = null; } } else { return true; } } private BoundableRenderable armedRenderable; /* (non-Javadoc) * @see org.xamjwg.html.renderer.BoundableRenderable#onMousePressed(java.awt.event.MouseEvent, int, int) */ public boolean onMousePressed(MouseEvent event, int x, int y) { Iterator i = this.getRenderables(new Point(x, y)); if(i != null) { while(i.hasNext()) { BoundableRenderable br = (BoundableRenderable) i.next(); if(br != null) { Rectangle bounds = br.getBounds(); if(!br.onMousePressed(event, x - bounds.x, y - bounds.y)) { this.armedRenderable = br; return false; } } } } return true; } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BoundableRenderable#onMouseReleased(java.awt.event.MouseEvent, int, int) */ public boolean onMouseReleased(MouseEvent event, int x, int y) { Iterator i = this.getRenderables(new Point(x, y)); if(i != null) { while(i.hasNext()) { BoundableRenderable br = (BoundableRenderable) i.next(); if(br != null) { Rectangle bounds = br.getBounds(); if(!br.onMouseReleased(event, x - bounds.x, y - bounds.y)) { BoundableRenderable oldArmedRenderable = this.armedRenderable; if(oldArmedRenderable != null && br != oldArmedRenderable) { oldArmedRenderable.onMouseDisarmed(event); this.armedRenderable = null; } return false; } } } } BoundableRenderable oldArmedRenderable = this.armedRenderable; if(oldArmedRenderable != null) { oldArmedRenderable.onMouseDisarmed(event); this.armedRenderable = null; } return true; } public void paint(Graphics g) { Rectangle clipBounds = g.getClipBounds(); Iterator i = this.getRenderables(clipBounds); if(i != null) { int renderableCount = 0; while(i.hasNext()) { renderableCount++; Object robj = i.next(); // The expected behavior in HTML is for boxes // not to be clipped unless overflow=hidden. if(robj instanceof BoundableRenderable) { BoundableRenderable renderable = (BoundableRenderable) robj; renderable.paintTranslated(g); //numRenderables++; } else { ((Renderable) robj).paint(g); } } } } //---------------------------------------------------------------- private static class NopLayout implements MarkupLayout { public void layoutMarkup(RBlockViewport bodyLayout, HTMLElementImpl markupElement) { } } private static class NoScriptLayout implements MarkupLayout { public void layoutMarkup(RBlockViewport bodyLayout, HTMLElementImpl markupElement) { UserAgentContext ucontext = bodyLayout.userAgentContext; if(!ucontext.isScriptingEnabled()) { bodyLayout.layoutMarkup( markupElement); } else { //NOP } } } private static class ChildrenLayout implements MarkupLayout { /* (non-Javadoc) * @see org.xamjwg.html.renderer.MarkupLayout#layoutMarkup(java.awt.Container, java.awt.Insets, org.xamjwg.html.domimpl.HTMLElementImpl) */ public void layoutMarkup(RBlockViewport bodyLayout, HTMLElementImpl markupElement) { bodyLayout.layoutChildren(markupElement); } } private static class MiscLayout extends CommonLayout { public MiscLayout() { super(DISPLAY_INLINE); } } private static class HLayout extends CommonLayout { public HLayout(int fontSize) { super(DISPLAY_BLOCK); } /* (non-Javadoc) * @see org.xamjwg.html.renderer.MarkupLayout#layoutMarkup(java.awt.Container, java.awt.Insets, org.xamjwg.html.domimpl.HTMLElementImpl) */ public void layoutMarkup(RBlockViewport bodyLayout, HTMLElementImpl markupElement) { super.layoutMarkup(bodyLayout, markupElement); } } private static class PLayout extends CommonLayout { public PLayout() { super(DISPLAY_BLOCK); } /* (non-Javadoc) * @see org.xamjwg.html.renderer.MarkupLayout#layoutMarkup(java.awt.Container, java.awt.Insets, org.xamjwg.html.domimpl.HTMLElementImpl) */ public void layoutMarkup(RBlockViewport bodyLayout, HTMLElementImpl markupElement) { super.layoutMarkup(bodyLayout, markupElement); } } private static class ListItemLayout extends CommonLayout { public ListItemLayout() { super(DISPLAY_LIST_ITEM); } } private static class BrLayout implements MarkupLayout { /* (non-Javadoc) * @see org.xamjwg.html.renderer.MarkupLayout#layoutMarkup(java.awt.Container, java.awt.Insets, org.xamjwg.html.domimpl.HTMLElementImpl) */ public void layoutMarkup(RBlockViewport bodyLayout, HTMLElementImpl markupElement) { String clear = markupElement.getAttribute("clear"); bodyLayout.addLineBreak(markupElement, LineBreak.getBreakType(clear)); } } private static class HrLayout implements MarkupLayout { /* (non-Javadoc) * @see org.xamjwg.html.renderer.MarkupLayout#layoutMarkup(java.awt.Container, java.awt.Insets, org.xamjwg.html.domimpl.HTMLElementImpl) */ public void layoutMarkup(RBlockViewport bodyLayout, HTMLElementImpl markupElement) { bodyLayout.layoutHr( markupElement); } } private static class TableLayout extends CommonLayout { public TableLayout() { super(DISPLAY_TABLE); } } private static class CommonBlockLayout extends CommonLayout { public CommonBlockLayout() { super(DISPLAY_BLOCK); } } //--------------------------------------------------------------------------- private static class DivLayout extends CommonLayout { public DivLayout() { super(DISPLAY_BLOCK); } } private static class BlockQuoteLayout extends CommonLayout { public BlockQuoteLayout() { super(DISPLAY_BLOCK); } } private static class SpanLayout extends CommonLayout { public SpanLayout() { super(DISPLAY_INLINE); } } private static class EmLayout extends CommonLayout { public EmLayout() { super(DISPLAY_INLINE); } /* (non-Javadoc) * @see org.xamjwg.html.renderer.MarkupLayout#layoutMarkup(java.awt.Container, java.awt.Insets, org.xamjwg.html.domimpl.HTMLElementImpl) */ public void layoutMarkup(RBlockViewport bodyLayout, HTMLElementImpl markupElement) { super.layoutMarkup(bodyLayout, markupElement); } } private static class ULayout extends CommonLayout { public ULayout() { super(DISPLAY_INLINE); } /* (non-Javadoc) * @see org.xamjwg.html.renderer.MarkupLayout#layoutMarkup(java.awt.Container, java.awt.Insets, org.xamjwg.html.domimpl.HTMLElementImpl) */ public void layoutMarkup(RBlockViewport bodyLayout, HTMLElementImpl markupElement) { super.layoutMarkup(bodyLayout, markupElement); } } private static class StrikeLayout extends CommonLayout { public StrikeLayout() { super(DISPLAY_INLINE); } } private static class StrongLayout extends CommonLayout { public StrongLayout() { super(DISPLAY_INLINE); } } private static class AnchorLayout extends CommonLayout { public AnchorLayout() { super(DISPLAY_INLINE); } } private static class ObjectLayout extends CommonWidgetLayout { private boolean tryToRenderContent; /** * @param tryToRenderContent If the object is unknown, content is rendered as HTML. * @param usesAlignAttribute */ public ObjectLayout(boolean tryToRenderContent, boolean usesAlignAttribute) { super(ADD_INLINE, usesAlignAttribute); this.tryToRenderContent = tryToRenderContent; } /** * Must use this ThreadLocal because * an ObjectLayout instance is shared * across renderers. */ private final ThreadLocal htmlObject = new ThreadLocal(); public void layoutMarkup(RBlockViewport bodyLayout, HTMLElementImpl markupElement) { HtmlObject ho = bodyLayout.rendererContext.getHtmlObject(markupElement); if(ho == null && this.tryToRenderContent) { // Don't know what to do with it - render contents. bodyLayout.layoutMarkup( markupElement); } else if (ho != null) { this.htmlObject.set(ho); super.layoutMarkup(bodyLayout, markupElement); } } protected RElement createRenderable(RBlockViewport bodyLayout, HTMLElementImpl markupElement) { HtmlObject ho = (HtmlObject) this.htmlObject.get(); UIControl uiControl = new UIControlWrapper(ho); RUIControl ruiControl = new RUIControl(markupElement, uiControl, bodyLayout.container, bodyLayout.frameContext, bodyLayout.userAgentContext); return ruiControl; } } private static class ImgLayout extends CommonWidgetLayout { public ImgLayout() { super(ADD_INLINE, true); } protected RElement createRenderable(RBlockViewport bodyLayout, HTMLElementImpl markupElement) { UIControl control = new ImgControl((HTMLImageElementImpl) markupElement); return new RImgControl(markupElement, control, bodyLayout.container, bodyLayout.frameContext, bodyLayout.userAgentContext); } } private static class InputLayout2 extends CommonWidgetLayout { public InputLayout2() { super(ADD_INLINE, true); } protected RElement createRenderable(RBlockViewport bodyLayout, HTMLElementImpl markupElement) { HTMLBaseInputElement bie = (HTMLBaseInputElement) markupElement; BaseInputControl uiControl = bodyLayout.createInputControl(bie); if(uiControl == null) { return null; } bie.setInputContext(uiControl); return new RUIControl(markupElement, uiControl, bodyLayout.container, bodyLayout.frameContext, bodyLayout.userAgentContext); } } private static class SelectLayout extends CommonWidgetLayout { public SelectLayout() { super(ADD_INLINE, true); } protected RElement createRenderable(RBlockViewport bodyLayout, HTMLElementImpl markupElement) { HTMLBaseInputElement bie = (HTMLBaseInputElement) markupElement; BaseInputControl uiControl = new InputSelectControl(bie); bie.setInputContext(uiControl); return new RUIControl(markupElement, uiControl, bodyLayout.container, bodyLayout.frameContext, bodyLayout.userAgentContext); } } private static class TextAreaLayout2 extends CommonWidgetLayout { public TextAreaLayout2() { super(ADD_INLINE, true); } protected RElement createRenderable(RBlockViewport bodyLayout, HTMLElementImpl markupElement) { HTMLBaseInputElement bie = (HTMLBaseInputElement) markupElement; BaseInputControl control = new InputTextAreaControl(bie); bie.setInputContext(control); return new RUIControl(markupElement, control, bodyLayout.container, bodyLayout.frameContext, bodyLayout.userAgentContext); } } private static class IFrameLayout extends CommonWidgetLayout { public IFrameLayout() { super(ADD_INLINE, true); } protected RElement createRenderable(RBlockViewport bodyLayout, HTMLElementImpl markupElement) { BrowserFrame frame = bodyLayout.rendererContext.createBrowserFrame(); ((HTMLIFrameElementImpl) markupElement).setBrowserFrame(frame); UIControl control = new BrowserFrameUIControl(markupElement, frame); return new RUIControl(markupElement, control, bodyLayout.container, bodyLayout.frameContext, bodyLayout.userAgentContext); } } //------------------------------------------------------------------------ /** * This is layout common to elements that render themselves, * except RBlock, RTable and RList. */ private static abstract class CommonWidgetLayout implements MarkupLayout { protected static final int ADD_INLINE = 0; protected static final int ADD_AS_BLOCK = 1; private final int method; private final boolean useAlignAttribute; public CommonWidgetLayout(int method, boolean usesAlignAttribute) { this.method = method; this.useAlignAttribute = usesAlignAttribute; } public void layoutMarkup(RBlockViewport bodyLayout, HTMLElementImpl markupElement) { AbstractCSS2Properties style = markupElement.getCurrentStyle(); if(style != null) { String display = style.getDisplay(); if(display != null && "none".equalsIgnoreCase(display)) { return; } } UINode node = markupElement.getUINode(); RElement renderable = null; if(node == null) { renderable = this.createRenderable(bodyLayout, markupElement); if(renderable == null) { if(logger.isLoggable(Level.INFO)) { logger.info("layoutMarkup(): Don't know how to render " + markupElement + "."); } return; } markupElement.setUINode((UINode) renderable); } else { renderable = (RElement) node; } renderable.setOriginalParent(bodyLayout); switch(this.method) { case ADD_INLINE: bodyLayout.addRenderableToLineCheckStyle(renderable, markupElement, this.useAlignAttribute); break; case ADD_AS_BLOCK: bodyLayout.positionRElement(markupElement, renderable, this.useAlignAttribute, true, false); break; } } protected abstract RElement createRenderable(RBlockViewport bodyLayout, HTMLElementImpl markupElement); } private static abstract class CommonLayout implements MarkupLayout { protected static final int DISPLAY_NONE = 0; protected static final int DISPLAY_INLINE = 1; protected static final int DISPLAY_BLOCK = 2; protected static final int DISPLAY_LIST_ITEM = 3; protected static final int DISPLAY_TABLE_ROW = 4; protected static final int DISPLAY_TABLE_CELL = 5; protected static final int DISPLAY_TABLE = 6; private final int display; public CommonLayout(int defaultDisplay) { this.display = defaultDisplay; } public void layoutMarkup(RBlockViewport bodyLayout, HTMLElementImpl markupElement) { RenderState rs = markupElement.getRenderState(); int display = rs == null ? this.display : rs.getDisplay(); if(display == RenderState.DISPLAY_INLINE) { // Inline elements with absolute or fixed positions need // to be treated as blocks. int position = rs == null ? RenderState.POSITION_STATIC : rs.getPosition(); if(position == RenderState.POSITION_ABSOLUTE || position == RenderState.POSITION_FIXED) { display = RenderState.DISPLAY_BLOCK; } else { int boxFloat = rs == null ? RenderState.FLOAT_NONE : rs.getFloat(); if(boxFloat != RenderState.FLOAT_NONE) { display = RenderState.DISPLAY_BLOCK; } } } switch(display) { case DISPLAY_NONE: // skip it completely. UINode node = markupElement.getUINode(); if(node instanceof BaseBoundableRenderable) { // This is necessary so that if the element is made // visible again, it can be invalidated. ((BaseBoundableRenderable) node).markLayoutValid(); } break; case DISPLAY_BLOCK: bodyLayout.layoutRBlock( markupElement); break; case DISPLAY_LIST_ITEM: String tagName = markupElement.getTagName(); if("UL".equalsIgnoreCase(tagName) || "OL".equalsIgnoreCase(tagName)) { bodyLayout.layoutList( markupElement); } else { bodyLayout.layoutListItem( markupElement); } break; case DISPLAY_TABLE: bodyLayout.layoutRTable( markupElement); break; default: // Assume INLINE bodyLayout.layoutMarkup( markupElement); break; } } } public boolean isContainedByNode() { return false; } public String toString() { return "RBlockViewport[node=" + this.modelNode + "]"; } // /** // * Performs layout adjustment step. // * @param desiredWidth The desired viewport width, including padding. // * @param desiredHeight The desired viewport height, including padding. // * @param paddingInsets The padding insets. // * @param floatBounds The starting float bounds, including floats // * in ancestors. // */ // public void adjust(int desiredWidth, int desiredHeight, Insets paddingInsets, FloatingBounds floatBounds) { // // Initializations // this.paddingInsets = paddingInsets; // this.desiredHeight = desiredHeight; // this.desiredWidth = desiredWidth; // this.floatBounds = floatBounds; // // int availw = desiredWidth - paddingInsets.left - paddingInsets.right; // if(availw < 0) { // availw = 0; // } // int availh = desiredHeight - paddingInsets.top - paddingInsets.bottom; // if(availh < 0) { // availh = 0; // } // this.availContentWidth = availw; // this.availContentHeight = availh; // // // maxX and maxY should not be reset by layoutPass. // this.maxX = paddingInsets.left; // this.maxY = paddingInsets.top; // // // Keep copy of old sequential renderables, // // and clear the list. // ArrayList oldSeqRenderables = this.seqRenderables; // this.seqRenderables = null; // // // Clear current line // this.currentLine = null; // // // Reprocess all sequential renderables // if(oldSeqRenderables != null) { // Iterator i = oldSeqRenderables.iterator(); // while(i.hasNext()) { // Renderable r = (Renderable) i.next(); // this.reprocessSeqRenderable(r); // } // } // // RLine lastLine = this.currentLine; // // // This adds any pending floats // this.lineDone(this.currentLine); // // // Calculate maxX and maxY. // if(lastLine != null) { // Rectangle lastBounds = lastLine.getBounds(); // int lastTopX = lastBounds.x + lastBounds.width; // if(lastTopX > this.maxX) { // this.maxX = lastTopX; // } // int lastTopY = lastBounds.y + lastBounds.height; // int maxY = this.maxY; // if(lastTopY > maxY) { // this.maxY = maxY = lastTopY; // } // } // // // Check positioned renderables for maxX and maxY // SortedSet posRenderables = this.positionedRenderables; // if(posRenderables != null) { // Iterator i = posRenderables.iterator(); // while(i.hasNext()) { // PositionedRenderable pr = (PositionedRenderable) i.next(); // BoundableRenderable br = pr.renderable; // if(br.getX() + br.getWidth() > this.maxX) { // this.maxX = br.getX() + br.getWidth(); // } // if(br.getY() + br.getHeight() > this.maxY) { // this.maxY = br.getY() + br.getHeight(); // } // } // } // // this.width = paddingInsets.right + this.maxX; // this.height = paddingInsets.bottom + maxY; // } // private void reprocessSeqRenderable(Renderable r) { // if(r instanceof RLine) { // this.reprocessLine((RLine) r); // } // else if(r instanceof RElement) { // this.reprocessElement((RElement) r); // } // else if(r instanceof RRelative) { // this.reprocessRelative((RRelative) r); // } // else { // throw new IllegalStateException("Unexpected Renderable: " + r); // } // } // // private void reprocessLine(RLine line) { // Iterator renderables = line.getRenderables(); // if(renderables != null) { // while(renderables.hasNext()) { // Renderable r = (Renderable) renderables.next(); // if(this.currentLine == null) { // // Must add at this point in case there was a float. // this.currentLine = this.addLine(r.getModelNode(), null, this.paddingInsets.top); // } // if(r instanceof RWord) { // RWord word = (RWord) r; // this.addWordToLine(word); // } // else if (r instanceof RFloatInfo) { // RFloatInfo oldr = (RFloatInfo) r; // // Switch to a float info with registerElement=true. // this.scheduleFloat(new RFloatInfo(oldr.getModelNode(), oldr.getRenderable(), oldr.isLeftFloat())); // } // else if (r instanceof RStyleChanger) { // RStyleChanger sc = (RStyleChanger) r; // RenderState rs = sc.getModelNode().getRenderState(); // int whiteSpace = rs == null ? RenderState.WS_NORMAL : rs.getWhiteSpace(); // boolean isAO = this.currentLine.isAllowOverflow(); // if(!isAO && whiteSpace == RenderState.WS_NOWRAP) { // this.currentLine.setAllowOverflow(true); // } // else if(isAO && whiteSpace != RenderState.WS_NOWRAP) { // this.currentLine.setAllowOverflow(false); // } // this.addRenderableToLine(r); // } // else { // this.addRenderableToLine(r); // } // } // } // LineBreak br = line.getLineBreak(); // if(br != null) { // this.addLineBreak(br.getModelNode(), br.getBreakType()); // } // } // // private void reprocessElement(RElement element) { // RLine line = this.currentLine; // this.lineDone(line); // boolean isRBlock = element instanceof RBlock; // boolean obeysFloats = !isRBlock || !((RBlock) element).isOverflowVisibleY() || !((RBlock) element).isOverflowVisibleY(); // if(obeysFloats) { // if(isRBlock) { // RBlock block = (RBlock) element; // int newLineY = line == null ? this.paddingInsets.top : line.y + line.height; // int leftOffset = this.fetchLeftOffset(newLineY); // int rightOffset = this.fetchRightOffset(newLineY); // int availContentWidth = this.desiredWidth - leftOffset - rightOffset; // block.adjust(availContentWidth, this.availContentHeight, true, false, null, true); // // Because a block that obeys margins is also a float limit, // // we don't expect exported float bounds. // } // else if(element instanceof RTable) { // RTable table = (RTable) element; // int newLineY = line == null ? this.paddingInsets.top : line.y + line.height; // int leftOffset = this.fetchLeftOffset(newLineY); // int rightOffset = this.fetchRightOffset(newLineY); // int availContentWidth = this.desiredWidth - leftOffset - rightOffset; // table.adjust(availContentWidth, this.availContentHeight); // } // } // else { // RBlock block = (RBlock) element; // final FloatingBounds currentFloatBounds = this.floatBounds; // FloatingBoundsSource blockFloatBoundsSource = null; // if(currentFloatBounds != null) { // Insets paddingInsets = this.paddingInsets; // final int blockShiftX = paddingInsets.left; // final int blockShiftRight = paddingInsets.right; // final int blockShiftY = line == null ? paddingInsets.top : line.y + line.height; // final int expectedBlockWidth = this.availContentWidth; // blockFloatBoundsSource = new FloatingBoundsSource() { // public FloatingBounds getChildBlockFloatingBounds(int apparentBlockWidth) { // int actualRightShift = blockShiftRight + (expectedBlockWidth - apparentBlockWidth); // return new ShiftedFloatingBounds(currentFloatBounds, -blockShiftX, -actualRightShift, -blockShiftY); // } // }; // } // block.adjust(this.availContentWidth, this.availContentHeight, true, false, blockFloatBoundsSource, true); // FloatingBounds blockBounds = block.getExportableFloatingBounds(); // if(blockBounds != null) { // FloatingBounds prevBounds = this.floatBounds; // FloatingBounds newBounds; // if(prevBounds == null) { // newBounds = blockBounds; // } // else { // newBounds = new CombinedFloatingBounds(prevBounds, blockBounds); // } // if(newBounds.getMaxY() > this.maxY && this.isFloatLimit()) { // this.maxY = newBounds.getMaxY(); // } // } // } // this.addAsSeqBlock(element, obeysFloats, false); // } // private void reprocessRelative(RRelative relative) { // RLine line = this.currentLine; // this.lineDone(line); // boolean obeysFloats = false; // RElement element = relative.getElement(); // if(element instanceof RBlock) { // obeysFloats = false; // RBlock block = (RBlock) element; // final FloatingBounds currentFloatBounds = this.floatBounds; // FloatingBoundsSource blockFloatBoundsSource = null; // if(currentFloatBounds != null) { // Insets paddingInsets = this.paddingInsets; // final int blockShiftX = paddingInsets.left + relative.getXOffset(); // final int blockShiftRight = paddingInsets.right - relative.getXOffset(); // final int blockShiftY = (line == null ? paddingInsets.top : line.y + line.height) + relative.getYOffset(); // final int expectedBlockWidth = this.availContentWidth; // blockFloatBoundsSource = new FloatingBoundsSource() { // public FloatingBounds getChildBlockFloatingBounds(int apparentBlockWidth) { // int actualRightShift = blockShiftRight + (expectedBlockWidth - apparentBlockWidth); // return new ShiftedFloatingBounds(currentFloatBounds, -blockShiftX, -actualRightShift, -blockShiftY); // } // }; // } // block.adjust(this.availContentWidth, this.availContentHeight, true, false, blockFloatBoundsSource, true); // relative.assignDimension(); // FloatingBounds blockBounds = relative.getExportableFloatingBounds(); // if(blockBounds != null) { // FloatingBounds prevBounds = this.floatBounds; // FloatingBounds newBounds; // if(prevBounds == null) { // newBounds = blockBounds; // } // else { // newBounds = new CombinedFloatingBounds(prevBounds, blockBounds); // } // if(newBounds.getMaxY() > this.maxY && this.isFloatLimit()) { // this.maxY = newBounds.getMaxY(); // } // } // } // else { // obeysFloats = true; // } // this.addAsSeqBlock(relative, obeysFloats, false); // } private void scheduleFloat(RFloatInfo floatInfo) { RLine line = this.currentLine; if(line == null) { int y = line == null ? this.paddingInsets.top : line.getY(); this.placeFloat(floatInfo.getRenderable(), y, floatInfo.isLeftFloat()); } else if(line.getWidth() == 0) { int y = line.getY(); this.placeFloat(floatInfo.getRenderable(), y, floatInfo.isLeftFloat()); int leftOffset = this.fetchLeftOffset(y); int rightOffset = this.fetchRightOffset(y); line.changeLimits(leftOffset, this.desiredWidth - leftOffset - rightOffset); } else { // These pending floats are positioned when // lineDone() is called. Collection c = this.pendingFloats; if(c == null) { c = new LinkedList(); this.pendingFloats = c; } c.add(floatInfo); } } private Collection pendingFloats = null; private void lineDone(RLine line) { int yAfterLine = line == null ? this.paddingInsets.top : line.y + line.height; Collection pfs = this.pendingFloats; if(pfs != null) { this.pendingFloats = null; Iterator i = pfs.iterator(); while(i.hasNext()) { RFloatInfo pf = (RFloatInfo) i.next(); this.placeFloat(pf.getRenderable(), yAfterLine, pf.isLeftFloat()); } } } private void addExportableFloat(BoundableRenderable element, boolean leftFloat, int origX, int origY) { ArrayList ep = this.exportableFloats; if(ep == null) { ep = new ArrayList(1); this.exportableFloats = ep; } ep.add(new ExportableFloat(element, leftFloat, origX, origY)); } /** * * @param element * @param y The desired top position of the float element. * @param floatType -1 (left) or +1 (right) */ private void placeFloat(BoundableRenderable element, int y, boolean leftFloat) { Insets insets = this.paddingInsets; int boxY = y; int boxWidth = element.getWidth(); int boxHeight = element.getHeight(); int desiredWidth = this.desiredWidth; int boxX; for(;;) { int leftOffset = this.fetchLeftOffset(boxY); int rightOffset = this.fetchRightOffset(boxY); boxX = leftFloat ? leftOffset : desiredWidth - rightOffset - boxWidth; if(leftOffset == insets.left && rightOffset == insets.right) { // Probably typical scenario. If it's overflowing to the left, // we need to correct. if(!leftFloat && boxX < leftOffset) { boxX = leftOffset; } break; } if(boxWidth <= desiredWidth - rightOffset - leftOffset) { // Size is fine. break; } // At this point the float doesn't fit at the current Y position. if(element instanceof RBlock) { // Try shrinking it. RBlock relement = (RBlock) element; if(!relement.hasDeclaredWidth()) { int availableBoxWidth = desiredWidth - rightOffset - leftOffset; relement.layout(availableBoxWidth, this.availContentHeight, this.sizeOnly); if(relement.getWidth() < boxWidth) { if(relement.getWidth() > desiredWidth - rightOffset - leftOffset) { // Didn't work out. Put it back the way it was. relement.layout(this.availContentWidth, this.availContentHeight, this.sizeOnly); } else { // Retry boxWidth = relement.getWidth(); boxHeight = relement.getHeight(); continue; } } } } FloatingBounds fb = this.floatBounds; int newY = fb == null ? boxY + boxHeight : fb.getFirstClearY(boxY); if(newY == boxY) { // Possible if prior box has height zero? break; } boxY = newY; } // Position element element.setOrigin(boxX, boxY); // Update float bounds accordingly int offsetFromBorder = leftFloat ? boxX + boxWidth : desiredWidth - boxX; this.floatBounds = new FloatingViewportBounds(this.floatBounds, leftFloat, boxY, offsetFromBorder, boxHeight); // Add element to collection boolean isFloatLimit = this.isFloatLimit(); if(isFloatLimit) { this.addPositionedRenderable(element, true, true); } else { this.addExportableFloat(element, leftFloat, boxX, boxY); } // Adjust maxX based on float. if(boxX + boxWidth > this.maxX) { this.maxX = boxX + boxWidth; } // Adjust maxY based on float, but only if this viewport is the float limit. if(this.isFloatLimit()) { if(boxY + boxHeight > this.maxY) { this.maxY = boxY + boxHeight; } } } private Boolean isFloatLimit = null; private boolean isFloatLimit() { Boolean fl = this.isFloatLimit; if(fl == null) { fl = this.isFloatLimitImpl(); this.isFloatLimit = fl; } return fl.booleanValue(); } private Boolean isFloatLimitImpl() { Object parent = this.getOriginalOrCurrentParent(); if(!(parent instanceof RBlock)) { return Boolean.TRUE; } RBlock blockParent = (RBlock) parent; Object grandParent = blockParent.getOriginalOrCurrentParent(); if(!(grandParent instanceof RBlockViewport)) { // Could be contained in a table, or it could // be a list item, for example. return Boolean.TRUE; } ModelNode node = this.modelNode; if(!(node instanceof HTMLElementImpl)) { // Can only be a document here. return Boolean.TRUE; } HTMLElementImpl element = (HTMLElementImpl) node; int position = getPosition(element); if(position == RenderState.POSITION_ABSOLUTE || position == RenderState.POSITION_FIXED) { return Boolean.TRUE; } AbstractCSS2Properties props = element.getCurrentStyle(); RenderState rs = element.getRenderState(); int floatValue = rs == null ? RenderState.FLOAT_NONE : rs.getFloat(); if(floatValue != RenderState.FLOAT_NONE) { return Boolean.TRUE; } int overflowX = rs == null ? RenderState.OVERFLOW_NONE : rs.getOverflowX(); int overflowY = rs == null ? RenderState.OVERFLOW_NONE : rs.getOverflowY(); if(overflowX == RenderState.OVERFLOW_AUTO || overflowX == RenderState.OVERFLOW_SCROLL || overflowY == RenderState.OVERFLOW_AUTO || overflowY == RenderState.OVERFLOW_SCROLL) { return Boolean.TRUE; } return Boolean.FALSE; } // /** // * Gets FloatingBounds from this viewport that should // * be considered by an ancestor block. // */ // public FloatingBounds getExportableFloatingBounds() { // FloatingBounds floatBounds = this.floatBounds; // if(floatBounds == null) { // return null; // } // if(this.isFloatLimit()) { // return null; // } // int maxY = floatBounds.getMaxY(); // if(maxY > this.height) { // return floatBounds; // } // return null; // } public FloatingInfo getExportableFloatingInfo() { ArrayList ef = this.exportableFloats; if(ef == null) { return null; } ExportableFloat[] floats = (ExportableFloat[]) ef.toArray(ExportableFloat.EMPTY_ARRAY); return new FloatingInfo(0, 0, floats); } private void importFloatingInfo(FloatingInfo floatingInfo, BoundableRenderable block) { int shiftX = floatingInfo.shiftX + block.getX(); int shiftY = floatingInfo.shiftY + block.getY(); ExportableFloat[] floats = floatingInfo.floats; int length = floats.length; for(int i = 0; i < length; i++) { ExportableFloat ef = floats[i]; this.importFloat(ef, shiftX, shiftY); } } private void importFloat(ExportableFloat ef, int shiftX, int shiftY) { BoundableRenderable renderable = ef.element; int newX = ef.origX + shiftX; int newY = ef.origY + shiftY; renderable.setOrigin(newX, newY); FloatingBounds prevBounds = this.floatBounds; int offsetFromBorder; boolean leftFloat = ef.leftFloat; if(leftFloat) { offsetFromBorder = newX + renderable.getWidth(); } else { offsetFromBorder = this.desiredWidth - newX; } this.floatBounds = new FloatingViewportBounds(prevBounds, leftFloat, newY, offsetFromBorder, renderable.getHeight()); if(this.isFloatLimit()) { this.addPositionedRenderable(renderable, true, true); } else { this.addExportableFloat(renderable, leftFloat, newX, newY); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/RCollection.java0000644000175000017500000000255310765007636026773 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; import java.util.Iterator; /** * A {@link Renderable} with children. */ public interface RCollection extends BoundableRenderable { /** * Gets the collection of {@link Renderable} children. */ public Iterator getRenderables(); public void updateWidgetBounds(int guiX, int guiY); /** * Invalidates layout in all descendents. */ public void invalidateLayoutDeep(); public void focus(); public void blur(); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/RElement.java0000644000175000017500000000436611134371410026256 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.html.style.RenderState; /** * A renderer node for elements such as blocks, lists, tables, inputs, images, etc. */ public interface RElement extends RCollection, UINode, BoundableRenderable { /** * Lays out the subtree below the RElement. * The RElement is expected to set its own dimensions, but not its origin. * @param availWidth The available width from the parent's canvas. * @param availHeight The available height from the parent's canvas. * @param sizeOnly Whether the layout is for sizing determination only. */ public void layout(int availWidth, int availHeight, boolean sizeOnly); /** * Vertical alignment for elements rendered in a line. * Returns one of the constants defined in this class. */ public int getVAlign(); public int getMarginTop(); public int getMarginLeft(); public int getMarginBottom(); public int getMarginRight(); public int getCollapsibleMarginTop(); public int getCollapsibleMarginBottom(); public static final int VALIGN_TOP = 0; public static final int VALIGN_MIDDLE = 1; public static final int VALIGN_BOTTOM = 2; public static final int VALIGN_ABSMIDDLE = 3; public static final int VALIGN_ABSBOTTOM = 4; public static final int VALIGN_BASELINE = 5; } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/RFloatInfo.java0000644000175000017500000000313411131075270026540 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; import java.awt.Graphics; import org.lobobrowser.html.domimpl.ModelNode; final class RFloatInfo implements Renderable { private final ModelNode modelNode; private final BoundableRenderable element; private final boolean leftFloat; public RFloatInfo(ModelNode node, BoundableRenderable element, boolean leftFloat) { this.modelNode = node; this.element = element; this.leftFloat = leftFloat; } public boolean isLeftFloat() { return this.leftFloat; } public ModelNode getModelNode() { return this.modelNode; } public void paint(Graphics g) { // nop } public final BoundableRenderable getRenderable() { return element; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/RImgControl.java0000644000175000017500000000261111130342750026732 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; import org.lobobrowser.html.UserAgentContext; import org.lobobrowser.html.domimpl.*; import java.awt.*; public class RImgControl extends RUIControl { public RImgControl(ModelNode me, UIControl widget, RenderableContainer container, FrameContext frameContext, UserAgentContext ucontext) { super(me, widget, container, frameContext, ucontext); } protected void applyStyle(int availWidth, int availHeight) { super.applyStyle(availWidth, availHeight); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/RLine.java0000644000175000017500000005211611127155612025556 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 16, 2005 */ package org.lobobrowser.html.renderer; import java.awt.*; import java.util.*; import org.lobobrowser.html.domimpl.ModelNode; import org.lobobrowser.html.style.RenderState; /** * @author J. H. S. */ class RLine extends BaseRCollection { private final ArrayList renderables = new ArrayList(8); //private final RenderState startRenderState; private int baseLineOffset; private int desiredMaxWidth; /** * Offset where next renderable should be placed. * This can be different to width. */ private int xoffset; private boolean allowOverflow = false; private boolean firstAllowOverflowWord = false; public RLine(ModelNode modelNode, RenderableContainer container, int x, int y, int desiredMaxWidth, int height, boolean initialAllowOverflow) { // Note that in the case of RLine, modelNode is the context node // at the beginning of the line, not a node that encloses the whole line. super(container, modelNode); this.x = x; this.y = y; this.height = height; this.desiredMaxWidth = desiredMaxWidth; // Layout here can always be "invalidated" this.layoutUpTreeCanBeInvalidated = true; this.allowOverflow = initialAllowOverflow; } public void setAllowOverflow(boolean flag) { if(flag != this.allowOverflow) { this.allowOverflow = flag; if(flag) { // Set to true only if allowOverflow was // previously false. this.firstAllowOverflowWord = true; } } } public boolean isAllowOverflow() { return this.allowOverflow; } /** * This method should only be invoked when the line has * no items yet. */ public void changeLimits(int x, int desiredMaxWidth) { this.x = x; this.desiredMaxWidth = desiredMaxWidth; } public int getBaselineOffset() { return this.baseLineOffset; } protected void invalidateLayoutLocal() { // Workaround for fact that RBlockViewport does not // get validated or invalidated. this.layoutUpTreeCanBeInvalidated = true; } /* (non-Javadoc) * @see net.sourceforge.xamj.domimpl.markup.Renderable#paint(java.awt.Graphics) */ public void paint(Graphics g) { // Paint according to render state of the start of line first. RenderState rs = this.modelNode.getRenderState(); if(rs != null) { Color textColor = rs.getColor(); g.setColor(textColor); Font font = rs.getFont(); g.setFont(font); } // Note that partial paints of the line can only be done // if all RStyleChanger's are applied first. Iterator i = this.renderables.iterator(); if(i != null) { while(i.hasNext()) { Object r = i.next(); if(r instanceof RElement) { // RElement's should be clipped. RElement relement = (RElement) r; Graphics newG = g.create(relement.getX(), relement.getY(), relement.getWidth(), relement.getHeight()); try { relement.paint(newG); } finally { newG.dispose(); } } else if(r instanceof BoundableRenderable) { BoundableRenderable br = (BoundableRenderable) r; br.paintTranslated(g); } else { ((Renderable) r).paint(g); } } } } public boolean extractSelectionText(StringBuffer buffer, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { boolean result = super.extractSelectionText(buffer, inSelection, startPoint, endPoint); if(result) { LineBreak br = this.lineBreak; if(br != null) { buffer.append(System.getProperty("line.separator")); } else { ArrayList renderables = this.renderables; int size = renderables.size(); if(size > 0 && !(renderables.get(size-1) instanceof RBlank)) { buffer.append(" "); } } } return result; } public final void addStyleChanger(RStyleChanger sc) { this.renderables.add(sc); } public final void simplyAdd(Renderable r) { this.renderables.add(r); } /** * This method adds and positions a renderable in the line, if possible. * Note that RLine does not set sizes, but only origins. * @throws OverflowException Thrown if the renderable overflows the line. All overflowing renderables are added to the exception. */ public final void add(Renderable renderable) throws OverflowException { if(renderable instanceof RWord) { this.addWord((RWord) renderable); } else if(renderable instanceof RBlank) { this.addBlank((RBlank) renderable); } else if(renderable instanceof RUIControl) { this.addElement((RElement) renderable); } else if(renderable instanceof RSpacing) { this.addSpacing((RSpacing) renderable); } else if(renderable instanceof RStyleChanger) { this.addStyleChanger((RStyleChanger) renderable); } else if(renderable instanceof RFloatInfo) { this.simplyAdd((RFloatInfo) renderable); } else { throw new IllegalArgumentException("Can't add " + renderable); } } public final void addWord(RWord rword) throws OverflowException { // Check if it fits horzizontally int offset = this.xoffset; int wiwidth = rword.width; boolean allowOverflow = this.allowOverflow; boolean firstAllowOverflowWord = this.firstAllowOverflowWord; if(allowOverflow && firstAllowOverflowWord) { this.firstAllowOverflowWord = false; } if((!allowOverflow || firstAllowOverflowWord) && offset != 0 && (offset + wiwidth > this.desiredMaxWidth)) { ArrayList renderables = this.renderables; ArrayList overflow = null; boolean cancel = false; // Check if other words need to be overflown (for example, // a word just before a markup tag adjacent to the word // we're trying to add). An RBlank between words prevents // a word from being overflown to the next line (and this // is the usefulness of RBlank.) int newOffset = offset; int newWidth = offset; for(int i = renderables.size(); --i >= 0;) { Renderable renderable = (Renderable) renderables.get(i); if(renderable instanceof RWord || !(renderable instanceof BoundableRenderable)) { if(overflow == null) { overflow = new ArrayList(); } if(renderable != rword && renderable instanceof RWord && ((RWord) renderable).getX() == 0) { // Can't overflow words starting at offset zero. // Note that all or none should be overflown. cancel = true; // No need to set offset - set later. break; } overflow.add(0, renderable); renderables.remove(i); } else { if(renderable instanceof RBlank) { RBlank rblank = (RBlank) renderable; newWidth = rblank.getX(); newOffset = newWidth + rblank.getWidth(); } else { BoundableRenderable br = (BoundableRenderable) renderable; newWidth = newOffset = br.getX() + br.getWidth(); } break; } } if(cancel) { // Oops. Need to undo overflow. if(overflow != null) { Iterator i = overflow.iterator(); while(i.hasNext()) { renderables.add(i.next()); } } } else { this.xoffset = newOffset; this.width = newWidth; if(overflow == null) { throw new OverflowException(Collections.singleton(rword)); } else { overflow.add(rword); throw new OverflowException(overflow); } } } // Add it int extraHeight = 0; int maxDescent = this.height - this.baseLineOffset; if(rword.descent > maxDescent) { extraHeight += (rword.descent - maxDescent); } int maxAscentPlusLeading = this.baseLineOffset; if(rword.ascentPlusLeading > maxAscentPlusLeading) { extraHeight += (rword.ascentPlusLeading - maxAscentPlusLeading); } if(extraHeight > 0) { int newHeight = this.height + extraHeight; this.adjustHeight(newHeight, newHeight, RElement.VALIGN_ABSBOTTOM); } this.renderables.add(rword); rword.setParent(this); int x = offset; offset += wiwidth; this.width = this.xoffset = offset; rword.setOrigin(x, this.baseLineOffset - rword.ascentPlusLeading); } public final void addBlank(RBlank rblank) { //NOTE: Blanks may be added without concern for wrapping (?) int x = this.xoffset; int width = rblank.width; rblank.setOrigin(x, this.baseLineOffset - rblank.ascentPlusLeading); this.renderables.add(rblank); rblank.setParent(this); // Only move xoffset, but not width this.xoffset = x + width; } public final void addSpacing(RSpacing rblank) { //NOTE: Spacing may be added without concern for wrapping (?) int x = this.xoffset; int width = rblank.width; rblank.setOrigin(x, (this.height - rblank.height) / 2); this.renderables.add(rblank); rblank.setParent(this); this.width = this.xoffset = x + width; } /** * * @param relement * @param x * @param elementHeight The required new line height. * @param valign */ private final void setElementY(RElement relement, int elementHeight, int valign) { // At this point height should be more than what's needed. int yoffset; switch(valign) { case RElement.VALIGN_ABSBOTTOM: yoffset = this.height - elementHeight; break; case RElement.VALIGN_ABSMIDDLE: yoffset = (this.height - elementHeight) / 2; break; case RElement.VALIGN_BASELINE: case RElement.VALIGN_BOTTOM: yoffset = this.baseLineOffset - elementHeight; break; case RElement.VALIGN_MIDDLE: yoffset = this.baseLineOffset - elementHeight / 2; break; case RElement.VALIGN_TOP: yoffset = 0; break; default: yoffset = this.baseLineOffset - elementHeight; } //RLine only sets origins, not sizes. //relement.setBounds(x, yoffset, width, height); relement.setY(yoffset); } private final void addElement(RElement relement) throws OverflowException { // Check if it fits horizontally int origXOffset = this.xoffset; int desiredMaxWidth = this.desiredMaxWidth; int pw = relement.getWidth(); boolean allowOverflow = this.allowOverflow; boolean firstAllowOverflowWord = this.firstAllowOverflowWord; if(allowOverflow && firstAllowOverflowWord) { this.firstAllowOverflowWord = false; } if((!allowOverflow || firstAllowOverflowWord) && origXOffset != 0 && (origXOffset + pw > desiredMaxWidth)) { throw new OverflowException(Collections.singleton(relement)); } //Note: Renderable for widget doesn't paint the widget, but //it's needed for height readjustment. int boundsh = this.height; int ph = relement.getHeight(); int requiredHeight; int valign = relement.getVAlign(); switch(valign) { case RElement.VALIGN_BASELINE: case RElement.VALIGN_BOTTOM: requiredHeight = ph + (boundsh - this.baseLineOffset); break; case RElement.VALIGN_MIDDLE: requiredHeight = Math.max(ph, ph / 2 + (boundsh - this.baseLineOffset)); break; default: requiredHeight = ph; break; } if(requiredHeight > boundsh) { // Height adjustment depends on bounds being already set. this.adjustHeight(requiredHeight, ph, valign); } this.renderables.add(relement); relement.setParent(this); relement.setX(origXOffset); this.setElementY(relement, ph, valign); int newX = origXOffset + pw; this.width = this.xoffset = newX; } // /** // * Positions line elements vertically. // */ // public final void positionVertically() { // ArrayList renderables = this.renderables; // // // Find word maximum metrics. // int maxDescent = 0; // int maxAscentPlusLeading = 0; // int maxWordHeight = 0; // for(Iterator i = renderables.iterator(); i.hasNext(); ) { // Renderable r = (Renderable) i.next(); // if(r instanceof RWord) { // RWord rword = (RWord) r; // int descent = rword.descent; // if(descent > maxDescent) { // maxDescent = descent; // } // int ascentPlusLeading = rword.ascentPlusLeading; // if(ascentPlusLeading > maxAscentPlusLeading) { // maxAscentPlusLeading = ascentPlusLeading; // } // if(rword.height > maxWordHeight) { // maxWordHeight = rword.height; // } // } // } // // // Determine proper baseline // int lineHeight = this.height; // int baseLine = lineHeight - maxDescent; // for(Iterator i = renderables.iterator(); i.hasNext(); ) { // Renderable r = (Renderable) i.next(); // if(r instanceof RElement) { // RElement relement = (RElement) r; // switch(relement.getVAlign()) { // case RElement.VALIGN_ABSBOTTOM: // //TODO // break; // case RElement.VALIGN_ABSMIDDLE: // int midWord = baseLine + maxDescent - maxWordHeight / 2; // int halfElementHeight = relement.getHeight() / 2; // if(midWord + halfElementHeight > lineHeight) { // // Change baseLine // midWord = lineHeight - halfElementHeight; // baseLine = midWord + maxWordHeight / 2 - maxDescent; // } // else if(midWord - halfElementHeight < 0) { // midWord = halfElementHeight; // baseLine = midWord + maxWordHeight / 2 - maxDescent; // } // else { // relement.setY(midWord - halfElementHeight); // } // break; // } // } // } // // } /** * Rearrange line elements based on a new line height and * alignment provided. All line elements are expected to * have bounds preset. * @param newHeight * @param alignmentY */ private void adjustHeight(int newHeight, int elementHeight, int valign) { // Set new line height //int oldHeight = this.height; this.height = newHeight; ArrayList renderables = this.renderables; // Find max baseline FontMetrics firstFm = this.modelNode.getRenderState().getFontMetrics(); int maxDescent = firstFm.getDescent(); int maxAscentPlusLeading = firstFm.getAscent() + firstFm.getLeading(); for(Iterator i = renderables.iterator(); i.hasNext();) { Object r = i.next(); if(r instanceof RStyleChanger) { RStyleChanger rstyleChanger = (RStyleChanger) r; FontMetrics fm = rstyleChanger.getModelNode().getRenderState().getFontMetrics(); int descent = fm.getDescent(); if(descent > maxDescent) { maxDescent = descent; } int ascentPlusLeading = fm.getAscent() + fm.getLeading(); if(ascentPlusLeading > maxAscentPlusLeading) { maxAscentPlusLeading = ascentPlusLeading; } } } int textHeight = maxDescent + maxAscentPlusLeading; //TODO: Need to take into account previous RElement's and //their alignments? int baseline; switch(valign) { case RElement.VALIGN_ABSBOTTOM: baseline = newHeight - maxDescent; break; case RElement.VALIGN_ABSMIDDLE: baseline = (newHeight + textHeight) / 2 - maxDescent; break; case RElement.VALIGN_BASELINE: case RElement.VALIGN_BOTTOM: baseline = elementHeight; break; case RElement.VALIGN_MIDDLE: baseline = newHeight / 2; break; case RElement.VALIGN_TOP: baseline = maxAscentPlusLeading; break; default: baseline = elementHeight; break; } this.baseLineOffset = baseline; // Change bounds of renderables accordingly for(Iterator i = renderables.iterator(); i.hasNext();) { Object r = i.next(); if(r instanceof RWord) { RWord rword = (RWord) r; rword.setY(baseline - rword.ascentPlusLeading); } else if(r instanceof RBlank) { RBlank rblank = (RBlank) r; rblank.setY(baseline - rblank.ascentPlusLeading); } else if(r instanceof RElement) { RElement relement = (RElement) r; //int w = relement.getWidth(); this.setElementY(relement, relement.getHeight(), relement.getVAlign()); } else { // RSpacing and RStyleChanger don't matter? } } //TODO: Could throw OverflowException when we add floating widgets } public boolean onMouseClick(java.awt.event.MouseEvent event, int x, int y) { Renderable[] rarray = (Renderable[]) this.renderables.toArray(Renderable.EMPTY_ARRAY); BoundableRenderable r = MarkupUtilities.findRenderable(rarray, x, y, false); if(r != null) { Rectangle rbounds = r.getBounds(); return r.onMouseClick(event, x - rbounds.x, y - rbounds.y); } else { return true; } } public boolean onDoubleClick(java.awt.event.MouseEvent event, int x, int y) { Renderable[] rarray = (Renderable[]) this.renderables.toArray(Renderable.EMPTY_ARRAY); BoundableRenderable r = MarkupUtilities.findRenderable(rarray, x, y, false); if(r != null) { Rectangle rbounds = r.getBounds(); return r.onDoubleClick(event, x - rbounds.x, y - rbounds.y); } else { return true; } } private BoundableRenderable mousePressTarget; public boolean onMousePressed(java.awt.event.MouseEvent event, int x, int y) { Renderable[] rarray = (Renderable[]) this.renderables.toArray(Renderable.EMPTY_ARRAY); BoundableRenderable r = MarkupUtilities.findRenderable(rarray, x, y, false); if(r != null) { this.mousePressTarget = r; Rectangle rbounds = r.getBounds(); return r.onMousePressed(event, x - rbounds.x, y - rbounds.y); } else { return true; } } public RenderableSpot getLowestRenderableSpot(int x, int y) { Renderable[] rarray = (Renderable[]) this.renderables.toArray(Renderable.EMPTY_ARRAY); BoundableRenderable br = MarkupUtilities.findRenderable(rarray, x, y, false); if(br != null) { Rectangle rbounds = br.getBounds(); return br.getLowestRenderableSpot(x - rbounds.x, y - rbounds.y); } else { return new RenderableSpot(this, x, y); } } public boolean onMouseReleased(java.awt.event.MouseEvent event, int x, int y) { Renderable[] rarray = (Renderable[]) this.renderables.toArray(Renderable.EMPTY_ARRAY); BoundableRenderable r = MarkupUtilities.findRenderable(rarray, x, y, false); if(r != null) { Rectangle rbounds = r.getBounds(); BoundableRenderable oldArmedRenderable = this.mousePressTarget; if(oldArmedRenderable != null && r != oldArmedRenderable) { oldArmedRenderable.onMouseDisarmed(event); this.mousePressTarget = null; } return r.onMouseReleased(event, x - rbounds.x, y - rbounds.y); } else { BoundableRenderable oldArmedRenderable = this.mousePressTarget; if(oldArmedRenderable != null) { oldArmedRenderable.onMouseDisarmed(event); this.mousePressTarget = null; } return true; } } public boolean onMouseDisarmed(java.awt.event.MouseEvent event) { BoundableRenderable target = this.mousePressTarget; if(target != null) { this.mousePressTarget = null; return target.onMouseDisarmed(event); } else { return true; } } public Color getBlockBackgroundColor() { return this.container.getPaintedBackgroundColor(); } // public final void adjustHorizontalBounds(int newX, int newMaxWidth) throws OverflowException { // this.x = newX; // this.desiredMaxWidth = newMaxWidth; // int topX = newX + newMaxWidth; // ArrayList renderables = this.renderables; // int size = renderables.size(); // ArrayList overflown = null; // Rectangle lastInLine = null; // for(int i = 0; i < size; i++) { // Object r = renderables.get(i); // if(overflown == null) { // if(r instanceof BoundableRenderable) { // BoundableRenderable br = (BoundableRenderable) r; // Rectangle brb = br.getBounds(); // int x2 = brb.x + brb.width; // if(x2 > topX) { // overflown = new ArrayList(1); // } // else { // lastInLine = brb; // } // } // } // /* must not be else here */ // if(overflown != null) { // //TODO: This could break a word across markup boundary. // overflown.add(r); // renderables.remove(i--); // size--; // } // } // if(overflown != null) { // if(lastInLine != null) { // this.width = this.xoffset = lastInLine.x + lastInLine.width; // } // throw new OverflowException(overflown); // } // } /* (non-Javadoc) * @see org.xamjwg.html.renderer.RCollection#getRenderables() */ public Iterator getRenderables() { return this.renderables.iterator(); } public boolean isContainedByNode() { return false; } private LineBreak lineBreak; public LineBreak getLineBreak() { return lineBreak; } public void setLineBreak(LineBreak lineBreak) { this.lineBreak = lineBreak; } public boolean isEmpty() { return this.xoffset == 0; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/RList.java0000644000175000017500000000652311134327140025576 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; import org.lobobrowser.html.HtmlRendererContext; import org.lobobrowser.html.UserAgentContext; import org.lobobrowser.html.domimpl.HTMLElementImpl; import org.lobobrowser.html.domimpl.NodeImpl; import org.lobobrowser.html.style.ListStyle; import org.lobobrowser.html.style.RenderState; class RList extends BaseRListElement { public RList(NodeImpl modelNode, int listNesting, UserAgentContext pcontext, HtmlRendererContext rcontext, FrameContext frameContext, RenderableContainer parentContainer, RCollection parent) { super(modelNode, listNesting, pcontext, rcontext, frameContext, parentContainer); //this.defaultMarginInsets = new java.awt.Insets(5, 0, 5, 0); } protected void applyStyle(int availWidth, int availHeight) { super.applyStyle(availWidth, availHeight); ListStyle listStyle = this.listStyle; if(listStyle == null || listStyle.type == ListStyle.TYPE_UNSET) { Object rootNode = this.modelNode; if(!(rootNode instanceof HTMLElementImpl)) { return; } HTMLElementImpl rootElement = (HTMLElementImpl) rootNode; if(listStyle == null) { listStyle = new ListStyle(); this.listStyle = listStyle; } if("ul".equalsIgnoreCase(rootElement.getTagName())) { int listNesting = this.listNesting; if(listNesting == 0) { listStyle.type = ListStyle.TYPE_DISC; } else if(listNesting == 1) { listStyle.type = ListStyle.TYPE_CIRCLE; } else { listStyle.type = ListStyle.TYPE_SQUARE; } } else { listStyle.type = ListStyle.TYPE_DECIMAL; } } } public void doLayout(int availWidth, int availHeight, boolean expandWidth, boolean expandHeight, FloatingBoundsSource floatBoundsSource, int defaultOverflowX, int defaultOverflowY, boolean sizeOnly) { RenderState renderState = this.modelNode.getRenderState(); int counterStart = 1; Object rootNode = this.modelNode; if(!(rootNode instanceof HTMLElementImpl)) { return; } HTMLElementImpl rootElement = (HTMLElementImpl) rootNode; String startText = rootElement.getAttribute("start"); if(startText != null) { try { counterStart = Integer.parseInt(startText); } catch(NumberFormatException nfe) { // ignore } } renderState.resetCount(DEFAULT_COUNTER_NAME, this.listNesting, counterStart); super.doLayout(availWidth, availHeight, expandWidth, expandHeight, floatBoundsSource, defaultOverflowX, defaultOverflowY, sizeOnly); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/RListItem.java0000644000175000017500000001345311134327134026420 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; import java.awt.*; import org.lobobrowser.html.HtmlRendererContext; import org.lobobrowser.html.UserAgentContext; import org.lobobrowser.html.domimpl.NodeImpl; import org.lobobrowser.html.style.ListStyle; import org.lobobrowser.html.style.RenderState; import org.w3c.dom.html2.*; class RListItem extends BaseRListElement { private static final int BULLET_WIDTH = 5; private static final int BULLET_HEIGHT = 5; private static final int BULLET_RMARGIN = 5; private static final int BULLET_SPACE_WIDTH = 36; public RListItem(NodeImpl modelNode, int listNesting, UserAgentContext pcontext, HtmlRendererContext rcontext, FrameContext frameContext, RenderableContainer parentContainer, RCollection parent) { super(modelNode, listNesting, pcontext, rcontext, frameContext, parentContainer); //this.defaultMarginInsets = new java.awt.Insets(0, BULLET_SPACE_WIDTH, 0, 0); } public int getViewportListNesting(int blockNesting) { return blockNesting + 1; } public void invalidateLayoutLocal() { super.invalidateLayoutLocal(); this.value = null; } private static final Integer UNSET = new Integer(Integer.MIN_VALUE); private Integer value = null; private Integer getValue() { Integer value = this.value; if(value == null) { HTMLElement node = (HTMLElement) this.modelNode; String valueText = node == null ? null : node.getAttribute("value"); if(valueText == null) { value = UNSET; } else { try { value = Integer.valueOf(valueText); } catch(NumberFormatException nfe) { value = UNSET; } } this.value = value; } return value; } private int count; public void doLayout(int availWidth, int availHeight, boolean expandWidth, boolean expandHeight, FloatingBoundsSource floatBoundsSource, int defaultOverflowX, int defaultOverflowY, boolean sizeOnly) { super.doLayout(availWidth, availHeight, expandWidth, expandHeight, floatBoundsSource, defaultOverflowX, defaultOverflowY, sizeOnly); //Note: Count must be calculated even if layout is valid. RenderState renderState = this.modelNode.getRenderState(); Integer value = this.getValue(); if(value == UNSET) { this.count = renderState.incrementCount(DEFAULT_COUNTER_NAME, this.listNesting); } else { int newCount = value.intValue(); this.count = newCount; renderState.resetCount(DEFAULT_COUNTER_NAME, this.listNesting, newCount + 1); } } public void paint(Graphics g) { super.paint(g); RenderState rs = this.modelNode.getRenderState(); Insets marginInsets = this.marginInsets; RBlockViewport layout = this.bodyLayout; if(layout != null) { ListStyle listStyle = this.listStyle; int bulletType = listStyle == null ? ListStyle.TYPE_UNSET : listStyle.type; if(bulletType != ListStyle.TYPE_NONE) { if(bulletType == ListStyle.TYPE_UNSET) { RCollection parent = this.getOriginalOrCurrentParent(); if(!(parent instanceof RList)) { parent = parent.getOriginalOrCurrentParent(); } if(parent instanceof RList) { ListStyle parentListStyle = ((RList) parent).listStyle; bulletType = parentListStyle == null ? ListStyle.TYPE_DISC : parentListStyle.type; } else { bulletType = ListStyle.TYPE_DISC; } } // Paint bullets Color prevColor = g.getColor(); g.setColor(rs.getColor()); try { Insets insets = this.getInsets(this.hasHScrollBar, this.hasVScrollBar); Insets paddingInsets = this.paddingInsets; int baselineOffset = layout.getFirstBaselineOffset(); int bulletRight = (marginInsets == null ? 0 : marginInsets.left) - BULLET_RMARGIN; int bulletBottom = insets.top + baselineOffset + (paddingInsets == null ? 0 : paddingInsets.top); int bulletTop = bulletBottom - BULLET_HEIGHT; int bulletLeft = bulletRight - BULLET_WIDTH; int bulletNumber = this.count; String numberText = null; switch(bulletType) { case ListStyle.TYPE_DECIMAL: numberText = bulletNumber + "."; break; case ListStyle.TYPE_LOWER_ALPHA: numberText = ((char) ('a' + bulletNumber)) + "."; break; case ListStyle.TYPE_UPPER_ALPHA: numberText = ((char) ('A' + bulletNumber)) + "."; break; case ListStyle.TYPE_DISC: g.fillOval(bulletLeft, bulletTop, BULLET_WIDTH, BULLET_HEIGHT); break; case ListStyle.TYPE_CIRCLE: g.drawOval(bulletLeft, bulletTop, BULLET_WIDTH, BULLET_HEIGHT); break; case ListStyle.TYPE_SQUARE: g.fillRect(bulletLeft, bulletTop, BULLET_WIDTH, BULLET_HEIGHT); break; } if(numberText != null) { FontMetrics fm = g.getFontMetrics(); int numberLeft = bulletRight - fm.stringWidth(numberText); int numberY = bulletBottom; g.drawString(numberText, numberLeft, numberY); } } finally { g.setColor(prevColor); } } } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/RRelative.java0000644000175000017500000000752111132606604026440 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.util.Iterator; import org.lobobrowser.html.domimpl.ModelNode; import org.lobobrowser.util.*; public class RRelative extends BaseRCollection { private final RElement child; private final int xoffset; private final int yoffset; public RRelative(RenderableContainer container, ModelNode modelNode, final RElement child, final int xoffset, final int yoffset) { super(container, modelNode); child.setOriginalParent(this); child.setParent(this); child.setOrigin(xoffset, yoffset); this.child = child; this.xoffset = xoffset; this.yoffset = yoffset; } public void assignDimension() { RElement child = this.child; this.width = child.getWidth(); this.height = child.getHeight(); } public FloatingInfo getExportableFloatingInfo() { RElement child = this.child; if(child instanceof RBlock) { // There are no insets, and hence no shift. return ((RBlock) child).getExportableFloatingInfo(); } else { return null; } } // public void adjust() { // RElement child = this.child; // if(child instanceof RBlock) { // ((RBlock) child).adjust(); // } // } // // public FloatingBounds getExportableFloatingBounds() { // RElement child = this.child; // if(!(child instanceof RBlock)) { // return null; // } // FloatingBounds blockBounds = ((RBlock) child).getExportableFloatingBounds(); // if(blockBounds == null) { // return null; // } // return new ShiftedFloatingBounds(blockBounds, this.xoffset, -this.xoffset, this.yoffset); // } // public RElement getElement() { return this.child; } public int getXOffset() { return xoffset; } public int getYOffset() { return yoffset; } public Iterator getRenderables() { return CollectionUtilities.singletonIterator(this.child); } protected void invalidateLayoutLocal() { // nop } public RenderableSpot getLowestRenderableSpot(int x, int y) { return this.child.getLowestRenderableSpot(x - this.xoffset, y - this.yoffset); } public boolean isContainedByNode() { return true; } public boolean onDoubleClick(MouseEvent event, int x, int y) { return this.child.onDoubleClick(event, x - this.xoffset, y - this.yoffset); } public boolean onMouseClick(MouseEvent event, int x, int y) { return this.child.onMouseClick(event, x - this.xoffset, y - this.yoffset); } public boolean onMouseDisarmed(MouseEvent event) { return this.child.onMouseDisarmed(event); } public boolean onMousePressed(MouseEvent event, int x, int y) { return this.child.onMousePressed(event, x - this.xoffset, y - this.yoffset); } public boolean onMouseReleased(MouseEvent event, int x, int y) { return this.child.onMouseReleased(event, x - this.xoffset, y - this.yoffset); } public void paint(Graphics g) { this.child.paintTranslated(g); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/RSpacing.java0000644000175000017500000001045010726473510026252 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on May 21, 2005 */ package org.lobobrowser.html.renderer; import java.awt.*; import java.awt.event.MouseEvent; import org.lobobrowser.html.domimpl.ModelNode; /** * This is used when there's padding or margins in inline elements. */ final class RSpacing extends BaseBoundableRenderable { public RSpacing(ModelNode me, RenderableContainer container, int width, int height) { super(container, me); // Dimensions set when constructed. this.width = width; this.height = height; } protected void invalidateLayoutLocal() { } public boolean onMouseClick(java.awt.event.MouseEvent event, int x, int y) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onMouseClick(me, event, x, y); } else { return true; } } public boolean onDoubleClick(java.awt.event.MouseEvent event, int x, int y) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onDoubleClick(me, event, x, y); } else { return true; } } public boolean onMousePressed(java.awt.event.MouseEvent event, int x, int y) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onMouseDown(me, event, x, y); } else { return true; } } public boolean onMouseReleased(java.awt.event.MouseEvent event, int x, int y) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onMouseUp(me, event, x, y); } else { return true; } } public boolean onMouseDisarmed(java.awt.event.MouseEvent event) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onMouseDisarmed(me, event); } else { return true; } } /* (non-Javadoc) * @see net.sourceforge.xamj.domimpl.markup.Renderable#paint(java.awt.Graphics) */ public final void paint(Graphics g) { // Nothing to paint in spacing. } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BoundableRenderable#paintSelection(java.awt.Graphics, boolean, org.xamjwg.html.renderer.RenderablePoint, org.xamjwg.html.renderer.RenderablePoint) */ public boolean paintSelection(Graphics g, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { if(this == startPoint.renderable || this == endPoint.renderable) { if(inSelection) { return false; } } else if(!inSelection) { return false; } g.setColor(SELECTION_COLOR); g.setXORMode(SELECTION_XOR); g.fillRect(0, 0, this.width, this.height); g.setPaintMode(); return true; } public boolean extractSelectionText(StringBuffer buffer, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { if(this == startPoint.renderable || this == endPoint.renderable) { if(inSelection) { return false; } } else if(!inSelection) { return false; } return true; } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BoundableRenderable#getRenderable(int, int) */ public RenderableSpot getLowestRenderableSpot(int x, int y) { return new RenderableSpot(this, x, y); } public boolean isContainedByNode() { return true; } public boolean onRightClick(MouseEvent event, int x, int y) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onContextMenu(me, event, x, y); } else { return true; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/RStyleChanger.java0000644000175000017500000000444110726473500027260 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 17, 2005 */ package org.lobobrowser.html.renderer; import java.awt.*; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.html.style.RenderState; //import java.util.logging.*; /** * @author J. H. S. */ final class RStyleChanger extends BaseRenderable implements Renderable { //private final static Logger logger = Logger.getLogger(RStyleChanger.class); private final ModelNode modelNode; /** * */ public RStyleChanger(ModelNode modelNode) { this.modelNode = modelNode; } public ModelNode getModelNode() { return this.modelNode; } /* (non-Javadoc) * @see net.sourceforge.xamj.domimpl.markup.Renderable#paint(java.awt.Graphics) */ public void paint(Graphics g) { RenderState rs = this.modelNode.getRenderState(); g.setColor(rs.getColor()); g.setFont(rs.getFont()); } /* (non-Javadoc) * @see org.xamjwg.html.renderer.Renderable#invalidate() */ public void invalidateLayoutUpTree() { } public void onMouseClick(java.awt.event.MouseEvent event, int x, int y) { throw new UnsupportedOperationException("unexpected"); } public void onMousePressed(java.awt.event.MouseEvent event, int x, int y) { throw new UnsupportedOperationException("unexpected"); } public void onMouseReleased(java.awt.event.MouseEvent event, int x, int y) { throw new UnsupportedOperationException("unexpected"); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/RTable.java0000644000175000017500000002747611134643076025735 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Nov 19, 2005 */ package org.lobobrowser.html.renderer; import java.awt.*; import java.awt.event.MouseEvent; import java.util.*; import org.lobobrowser.html.*; import org.lobobrowser.util.*; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.html.style.RenderState; import org.w3c.dom.css.*; class RTable extends BaseElementRenderable { private static final int MAX_CACHE_SIZE = 10; private final Map cachedLayout = new HashMap(5); private final TableMatrix tableMatrix; private SortedSet positionedRenderables; private int otherOrdinal; private LayoutKey lastLayoutKey = null; private LayoutValue lastLayoutValue = null; public RTable(HTMLElementImpl modelNode, UserAgentContext pcontext, HtmlRendererContext rcontext, FrameContext frameContext, RenderableContainer container) { super(container, modelNode, pcontext); this.tableMatrix = new TableMatrix(modelNode, pcontext, rcontext, frameContext, this, this); } public int getVAlign() { // Not used return VALIGN_BASELINE; } public void paint(Graphics g) { RenderState rs = this.modelNode.getRenderState(); if(rs != null && rs.getVisibility() != RenderState.VISIBILITY_VISIBLE) { // Just don't paint it. return; } try { this.prePaint(g); Dimension size = this.getSize(); //TODO: No scrollbars TableMatrix tm = this.tableMatrix; tm.paint(g, size); Collection prs = this.positionedRenderables; if(prs != null) { Iterator i = prs.iterator(); while(i.hasNext()) { PositionedRenderable pr = (PositionedRenderable) i.next(); BoundableRenderable r = pr.renderable; r.paintTranslated(g); } } } finally { // Must always call super implementation super.paint(g); } } public void doLayout(int availWidth, int availHeight, boolean sizeOnly) { Map cachedLayout = this.cachedLayout; RenderState rs = this.modelNode.getRenderState(); int whitespace = rs == null ? RenderState.WS_NORMAL : rs.getWhiteSpace(); Font font = rs == null ? null : rs.getFont(); LayoutKey layoutKey = new LayoutKey(availWidth, availHeight, whitespace, font); LayoutValue layoutValue; if(sizeOnly) { layoutValue = (LayoutValue) cachedLayout.get(layoutKey); } else { if(Objects.equals(layoutKey, this.lastLayoutKey)) { layoutValue = this.lastLayoutValue; } else { layoutValue = null; } } if(layoutValue == null) { Collection prs = this.positionedRenderables; if(prs != null) { prs.clear(); } this.otherOrdinal = 0; this.clearGUIComponents(); this.clearDelayedPairs(); this.applyStyle(availWidth, availHeight); TableMatrix tm = this.tableMatrix; Insets insets = this.getInsets(false, false); tm.reset(insets, availWidth, availHeight); //TODO: No scrollbars tm.build(availWidth, availHeight, sizeOnly); tm.doLayout(insets); // Import applicable delayed pairs. // Only needs to be done if layout was // forced. Otherwise, they should've // been imported already. Collection pairs = this.delayedPairs; if(pairs != null) { Iterator i = pairs.iterator(); while(i.hasNext()) { DelayedPair pair = (DelayedPair) i.next(); if(pair.targetParent == this) { this.importDelayedPair(pair); } } } layoutValue = new LayoutValue(tm.getTableWidth(), tm.getTableHeight()); if(sizeOnly) { if(cachedLayout.size() > MAX_CACHE_SIZE) { // Unlikely, but we should ensure it's bounded. cachedLayout.clear(); } cachedLayout.put(layoutKey, layoutValue); this.lastLayoutKey = null; this.lastLayoutValue = null; } else { this.lastLayoutKey = layoutKey; this.lastLayoutValue = layoutValue; } } this.width = layoutValue.width; this.height = layoutValue.height; this.sendGUIComponentsToParent(); this.sendDelayedPairsToParent(); } public void invalidateLayoutLocal() { super.invalidateLayoutLocal(); this.cachedLayout.clear(); this.lastLayoutKey = null; this.lastLayoutValue = null; } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BoundableRenderable#getRenderablePoint(int, int) */ public RenderableSpot getLowestRenderableSpot(int x, int y) { Collection prs = this.positionedRenderables; if(prs != null) { Iterator i = prs.iterator(); while(i.hasNext()) { PositionedRenderable pr = (PositionedRenderable) i.next(); BoundableRenderable r = pr.renderable; int childX = x - r.getX(); int childY = y - r.getY(); RenderableSpot rs = r.getLowestRenderableSpot(childX, childY); if(rs != null) { return rs; } } } RenderableSpot rs = this.tableMatrix.getLowestRenderableSpot(x, y); if(rs != null) { return rs; } return new RenderableSpot(this, x, y); } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BoundableRenderable#onMouseClick(java.awt.event.MouseEvent, int, int) */ public boolean onMouseClick(MouseEvent event, int x, int y) { Collection prs = this.positionedRenderables; if(prs != null) { Iterator i = prs.iterator(); while(i.hasNext()) { PositionedRenderable pr = (PositionedRenderable) i.next(); BoundableRenderable r = pr.renderable; Rectangle bounds = r.getBounds(); if(bounds.contains(x, y)) { int childX = x - r.getX(); int childY = y - r.getY(); if(!r.onMouseClick(event, childX, childY)) { return false; } } } } return this.tableMatrix.onMouseClick(event, x, y); } public boolean onDoubleClick(MouseEvent event, int x, int y) { Collection prs = this.positionedRenderables; if(prs != null) { Iterator i = prs.iterator(); while(i.hasNext()) { PositionedRenderable pr = (PositionedRenderable) i.next(); BoundableRenderable r = pr.renderable; Rectangle bounds = r.getBounds(); if(bounds.contains(x, y)) { int childX = x - r.getX(); int childY = y - r.getY(); if(!r.onDoubleClick(event, childX, childY)) { return false; } } } } return this.tableMatrix.onDoubleClick(event, x, y); } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BoundableRenderable#onMouseDisarmed(java.awt.event.MouseEvent) */ public boolean onMouseDisarmed(MouseEvent event) { return this.tableMatrix.onMouseDisarmed(event); } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BoundableRenderable#onMousePressed(java.awt.event.MouseEvent, int, int) */ public boolean onMousePressed(MouseEvent event, int x, int y) { Collection prs = this.positionedRenderables; if(prs != null) { Iterator i = prs.iterator(); while(i.hasNext()) { PositionedRenderable pr = (PositionedRenderable) i.next(); BoundableRenderable r = pr.renderable; Rectangle bounds = r.getBounds(); if(bounds.contains(x, y)) { int childX = x - r.getX(); int childY = y - r.getY(); if(!r.onMousePressed(event, childX, childY)) { return false; } } } } return this.tableMatrix.onMousePressed(event, x, y); } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BoundableRenderable#onMouseReleased(java.awt.event.MouseEvent, int, int) */ public boolean onMouseReleased(MouseEvent event, int x, int y) { Collection prs = this.positionedRenderables; if(prs != null) { Iterator i = prs.iterator(); while(i.hasNext()) { PositionedRenderable pr = (PositionedRenderable) i.next(); BoundableRenderable r = pr.renderable; Rectangle bounds = r.getBounds(); if(bounds.contains(x, y)) { int childX = x - r.getX(); int childY = y - r.getY(); if(!r.onMouseReleased(event, childX, childY)) { return false; } } } } return this.tableMatrix.onMouseReleased(event, x, y); } /* (non-Javadoc) * @see org.xamjwg.html.renderer.RCollection#getRenderables() */ public Iterator getRenderables() { Collection prs = this.positionedRenderables; if(prs != null) { Collection c = new java.util.LinkedList(); Iterator i = prs.iterator(); while(i.hasNext()) { PositionedRenderable pr = (PositionedRenderable) i.next(); BoundableRenderable r = pr.renderable; c.add(r); } Iterator i2 = this.tableMatrix.getRenderables(); while(i2.hasNext()) { c.add(i2.next()); } return c.iterator(); } else { return this.tableMatrix.getRenderables(); } } public void repaint(ModelNode modelNode) { //NOP } /* (non-Javadoc) * @see org.xamjwg.html.renderer.RenderableContainer#getBackground() */ public Color getPaintedBackgroundColor() { return this.container.getPaintedBackgroundColor(); } private final void addPositionedRenderable(BoundableRenderable renderable, boolean verticalAlignable, boolean isFloat) { // Expected to be called only in GUI thread. SortedSet others = this.positionedRenderables; if(others == null) { others = new TreeSet(new ZIndexComparator()); this.positionedRenderables = others; } others.add(new PositionedRenderable(renderable, verticalAlignable, this.otherOrdinal++, isFloat)); renderable.setParent(this); if(renderable instanceof RUIControl) { this.container.addComponent(((RUIControl) renderable).widget.getComponent()); } } private void importDelayedPair(DelayedPair pair) { BoundableRenderable r = pair.child; r.setOrigin(pair.x, pair.y); this.addPositionedRenderable(r, false, false); } public String toString() { return "RTable[this=" + System.identityHashCode(this) + ",node=" + this.modelNode + "]"; } private static class LayoutKey { public final int availWidth; public final int availHeight; public final int whitespace; public final Font font; public LayoutKey(int availWidth, int availHeight, int whitespace, Font font) { super(); this.availWidth = availWidth; this.availHeight = availHeight; this.whitespace = whitespace; this.font = font; } public boolean equals(Object obj) { if(obj == this) { return true; } if(!(obj instanceof LayoutKey)) { return false; } LayoutKey other = (LayoutKey) obj; return other.availWidth == this.availWidth && other.availHeight == this.availHeight && other.whitespace == this.whitespace && Objects.equals(other.font, this.font); } public int hashCode() { Font font = this.font; return (this.availWidth * 1000 + this.availHeight) ^ (font == null ? 0 : font.hashCode()); } } private static class LayoutValue { public final int width; public final int height; public LayoutValue(int width, int height) { this.width = width; this.height = height; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/RTableCell.java0000644000175000017500000001213511134665752026524 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Dec 3, 2005 */ package org.lobobrowser.html.renderer; import java.awt.Dimension; import java.awt.Insets; import org.lobobrowser.html.*; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.html.style.RenderState; import org.lobobrowser.html.style.TableCellRenderState; class RTableCell extends RBlock { private final HTMLTableCellElementImpl cellElement; private VirtualCell topLeftVirtualCell; //private int cellPadding; /** * @param element */ public RTableCell(HTMLTableCellElementImpl element, UserAgentContext pcontext, HtmlRendererContext rcontext, FrameContext frameContext, RenderableContainer tableAsContainer) { super(element, 0, pcontext, rcontext, frameContext, tableAsContainer); this.cellElement = element; } /** * @param width The width available, including insets. * @param height The height available, including insets. */ protected Dimension doCellLayout(int width, int height, boolean expandWidth, boolean expandHeight, boolean sizeOnly) { try { this.layout(width, height, expandWidth, expandHeight, null, sizeOnly); return new Dimension(this.width, this.height); } finally { this.layoutUpTreeCanBeInvalidated = true; this.layoutDeepCanBeInvalidated = true; } } // public void setCellPadding(int value) { // this.cellPadding = value; // } protected Integer getDeclaredHeight(RenderState renderState, int availHeight) { // Overridden since height declaration is handled by table. return null; } protected Integer getDeclaredWidth(RenderState renderState, int availWidth) { // Overridden since width declaration is handled by table. return null; } public void finalize() throws Throwable { super.finalize(); } public void setTopLeftVirtualCell(VirtualCell vc) { this.topLeftVirtualCell = vc; } public VirtualCell getTopLeftVirtualCell() { return this.topLeftVirtualCell; } private int colSpan = -1; private int rowSpan = -1; /** * @return Returns the virtualColumn. */ public int getVirtualColumn() { VirtualCell vc = this.topLeftVirtualCell; return vc == null ? 0 : vc.getColumn(); } /** * @return Returns the virtualRow. */ public int getVirtualRow() { VirtualCell vc = this.topLeftVirtualCell; return vc == null ? 0 : vc.getRow(); } public int getColSpan() { int cs = this.colSpan; if(cs == -1) { cs = this.cellElement.getColSpan(); if(cs < 1) { cs = 1; } this.colSpan = cs; } return cs; } public int getRowSpan() { int rs = this.rowSpan; if(rs == -1) { rs = this.cellElement.getRowSpan(); if(rs < 1) { rs = 1; } this.rowSpan = rs; } return rs; } public void setRowSpan(int rowSpan) { this.rowSpan = rowSpan; } public String getHeightText() { return this.cellElement.getHeight(); } public String getWidthText() { return this.cellElement.getWidth(); } // public Dimension layoutMinWidth() { // // return this.panel.layoutMinWidth(); // // } // // public void setCellBounds(TableMatrix.SizeInfo[] colSizes, TableMatrix.SizeInfo[] rowSizes, int hasBorder, int cellSpacingX, int cellSpacingY) { int vcol = this.getVirtualColumn(); int vrow = this.getVirtualRow(); TableMatrix.SizeInfo colSize = colSizes[vcol]; TableMatrix.SizeInfo rowSize = rowSizes[vrow]; int x = colSize.offset; int y = rowSize.offset; int width; int height; int colSpan = this.getColSpan(); if(colSpan > 1) { width = 0; for(int i = 0; i < colSpan; i++) { int vc = vcol + i; width += colSizes[vc].actualSize; if(i + 1 < colSpan) { width += cellSpacingX + hasBorder * 2; } } } else { width = colSizes[vcol].actualSize; } int rowSpan = this.getRowSpan(); if(rowSpan > 1) { height = 0; for(int i = 0; i < rowSpan; i++) { int vr = vrow + i; height += rowSizes[vr].actualSize; if(i + 1 < rowSpan) { height += cellSpacingY + hasBorder * 2; } } } else { height = rowSizes[vrow].actualSize; } this.setBounds(x, y, width, height); } protected boolean isMarginBoundary() { return true; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/RUIControl.java0000644000175000017500000002721711134654572026560 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 17, 2005 */ package org.lobobrowser.html.renderer; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Insets; import java.util.*; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.html.*; import org.lobobrowser.html.style.RenderState; import org.lobobrowser.util.Objects; /** * @author J. H. S. */ class RUIControl extends BaseElementRenderable implements RElement { private static final int MAX_CACHE_SIZE = 10; public final UIControl widget; protected final ModelNode modelNode; private final FrameContext frameContext; public RUIControl(ModelNode me, UIControl widget, RenderableContainer container, FrameContext frameContext, UserAgentContext ucontext) { super(container, me, ucontext); this.modelNode = me; this.widget = widget; this.frameContext = frameContext; widget.setRUIControl(this); } public void focus() { super.focus(); java.awt.Component c = this.widget.getComponent(); c.requestFocus(); } public final void invalidateLayoutLocal() { // Invalidate widget (some redundancy) super.invalidateLayoutLocal(); this.widget.invalidate(); // Invalidate cached values this.cachedLayout.clear(); this.lastLayoutKey = null; this.lastLayoutValue = null; } public int getVAlign() { return this.widget.getVAlign(); } public boolean hasBackground() { return this.backgroundColor != null || this.backgroundImage != null || this.lastBackgroundImageUri != null; } public final void paint(Graphics g) { RenderState rs = this.modelNode.getRenderState(); if(rs != null && rs.getVisibility() != RenderState.VISIBILITY_VISIBLE) { // Just don't paint it. return; } // Prepaint borders, background images, etc. this.prePaint(g); // We need to paint the GUI component. // For various reasons, we need to do that // instead of letting AWT do it. Insets insets = this.getInsets(false, false); g.translate(insets.left, insets.top); try { this.widget.paint(g); } finally { g.translate(-insets.left, -insets.top); } } public boolean onMouseClick(java.awt.event.MouseEvent event, int x, int y) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onMouseClick(me, event, x, y); } else { return true; } } public boolean onDoubleClick(java.awt.event.MouseEvent event, int x, int y) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onDoubleClick(me, event, x, y); } else { return true; } } public boolean onMousePressed(java.awt.event.MouseEvent event, int x, int y) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onMouseDown(me, event, x, y); } else { return true; } } public boolean onMouseReleased(java.awt.event.MouseEvent event, int x, int y) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onMouseUp(me, event, x, y); } else { return true; } } public boolean onMouseDisarmed(java.awt.event.MouseEvent event) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onMouseDisarmed(me, event); } else { return true; } } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BoundableRenderable#invalidateState(org.xamjwg.html.renderer.RenderableContext) */ public void invalidateRenderStyle() { //NOP - No RenderStyle below this node. } /* (non-Javadoc) * @see org.xamjwg.html.domimpl.ContainingBlockContext#repaint(org.xamjwg.html.renderer.RenderableContext) */ public void repaint(ModelNode modelNode) { Object widget = this.widget; if(widget instanceof UINode) { ((UINode) widget).repaint(modelNode); } else { this.repaint(); } } public void updateWidgetBounds(int guiX, int guiY) { // Overrides super.updateWidgetBounds(guiX, guiY); Insets insets = this.getInsets(false, false); this.widget.setBounds(guiX + insets.left, guiY + insets.top, this.width - insets.left - insets.right, this.height - insets.top - insets.bottom); } public Color getBlockBackgroundColor() { return this.widget.getBackgroundColor(); } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BoundableRenderable#paintSelection(java.awt.Graphics, boolean, org.xamjwg.html.renderer.RenderablePoint, org.xamjwg.html.renderer.RenderablePoint) */ public boolean paintSelection(Graphics g, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { inSelection = super.paintSelection(g, inSelection, startPoint, endPoint); if(inSelection) { Color over = new Color(0, 0, 255, 50); if(over != null) { Color oldColor = g.getColor(); try { g.setColor(over); g.fillRect(0, 0, this.width, this.height); } finally { g.setColor(oldColor); } } } return inSelection; } public boolean extractSelectionText(StringBuffer buffer, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { // No text here return inSelection; } public RenderableSpot getLowestRenderableSpot(int x, int y) { // Nothing draggable - return self return new RenderableSpot(this, x, y); } private int declaredWidth = -1; private int declaredHeight = -1; private LayoutKey lastLayoutKey = null; private LayoutValue lastLayoutValue = null; private final Map cachedLayout = new HashMap(5); public void doLayout(int availWidth, int availHeight, boolean sizeOnly) { Map cachedLayout = this.cachedLayout; RenderState rs = this.modelNode.getRenderState(); int whitespace = rs == null ? RenderState.WS_NORMAL : rs.getWhiteSpace(); Font font = rs == null ? null : rs.getFont(); LayoutKey layoutKey = new LayoutKey(availWidth, availHeight, whitespace, font); LayoutValue layoutValue; if(sizeOnly) { layoutValue = (LayoutValue) cachedLayout.get(layoutKey); } else { if(Objects.equals(this.lastLayoutKey, layoutKey)) { layoutValue = this.lastLayoutValue; } else { layoutValue = null; } } if(layoutValue == null) { this.applyStyle(availWidth, availHeight); RenderState renderState = this.modelNode.getRenderState(); Insets paddingInsets = this.paddingInsets; if (paddingInsets == null) { paddingInsets = RBlockViewport.ZERO_INSETS; } Insets borderInsets = this.borderInsets; if(borderInsets == null) { borderInsets = RBlockViewport.ZERO_INSETS; } Insets marginInsets = this.marginInsets; if(marginInsets == null) { marginInsets = RBlockViewport.ZERO_INSETS; } int actualAvailWidth = availWidth - paddingInsets.left - paddingInsets.right - borderInsets.left - borderInsets.right - marginInsets.left - marginInsets.right; int actualAvailHeight = availHeight - paddingInsets.top - paddingInsets.bottom - borderInsets.top - borderInsets.bottom - marginInsets.top - marginInsets.bottom; Integer dw = this.getDeclaredWidth(renderState, actualAvailWidth); Integer dh = this.getDeclaredHeight(renderState, actualAvailHeight); int declaredWidth = dw == null ? -1 : dw.intValue(); int declaredHeight = dh == null ? -1 : dh.intValue(); this.declaredWidth = declaredWidth; this.declaredHeight = declaredHeight; UIControl widget = this.widget; widget.reset(availWidth, availHeight); Insets insets = this.getInsets(false, false); int finalWidth = declaredWidth == -1 ? -1 : declaredWidth - insets.left - insets.right; int finalHeight = declaredHeight == -1 ? -1 : declaredHeight - insets.top - insets.bottom; if(finalWidth == -1 || finalHeight == -1) { Dimension size = widget.getPreferredSize(); if(finalWidth == -1) { finalWidth = size.width + insets.left + insets.right; } if(finalHeight == -1) { finalHeight = size.height + insets.top + insets.bottom; } } layoutValue = new LayoutValue(finalWidth, finalHeight); if(sizeOnly) { if(cachedLayout.size() > MAX_CACHE_SIZE) { // Unlikely, but we should ensure it's bounded. cachedLayout.clear(); } cachedLayout.put(layoutKey, layoutValue); this.lastLayoutKey = null; this.lastLayoutValue = null; } else { this.lastLayoutKey = layoutKey; this.lastLayoutValue = layoutValue; } } this.width = layoutValue.width; this.height = layoutValue.height; } /** * May be called by controls when * they wish to modifiy their preferred * size (e.g. an image after it's loaded). * This method must be called * in the GUI thread. */ public final void preferredSizeInvalidated() { int dw = RUIControl.this.declaredWidth; int dh = RUIControl.this.declaredHeight; if(dw == -1 || dh == -1) { this.frameContext.delayedRelayout((NodeImpl) this.modelNode); } else { RUIControl.this.repaint(); } } public Iterator getRenderables() { // No children for GUI controls return null; } public Color getPaintedBackgroundColor() { return this.container.getPaintedBackgroundColor(); } public Color getForegroundColor() { RenderState rs = this.modelNode.getRenderState(); return rs == null ? null : rs.getColor(); } private static class LayoutKey { public final int availWidth; public final int availHeight; public final int whitespace; public final Font font; public LayoutKey(int availWidth, int availHeight, int whitespace, Font font) { this.availWidth = availWidth; this.availHeight = availHeight; this.whitespace = whitespace; this.font = font; } public boolean equals(Object obj) { if(obj == this) { return true; } if(!(obj instanceof LayoutKey)) { return false; } LayoutKey other = (LayoutKey) obj; return other.availWidth == this.availWidth && other.availHeight == this.availHeight && other.whitespace == this.whitespace && Objects.equals(other.font, this.font); } public int hashCode() { Font font = this.font; return (this.availWidth * 1000 + this.availHeight) ^ (font == null ? 0 : font.hashCode()); } } private static class LayoutValue { public final int width; public final int height; public LayoutValue(int width, int height) { this.width = width; this.height = height; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/RWord.java0000644000175000017500000002242411127147332025601 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 17, 2005 */ package org.lobobrowser.html.renderer; import java.awt.*; import java.awt.event.MouseEvent; import org.lobobrowser.html.domimpl.ModelNode; import org.lobobrowser.html.style.RenderState; final class RWord extends BaseBoundableRenderable { final String shownWord; public final FontMetrics fontMetrics; public final int descent; public final int ascentPlusLeading; public RWord(ModelNode me, String word, RenderableContainer container, FontMetrics fontMetrics, int descent, int ascentPlusLeading, int height, int textTransform) { super(container, me); String renderedWord = textTransform == RenderState.TEXTTRANSFORM_NONE ? word : transformText(word, textTransform); this.shownWord = renderedWord; this.fontMetrics = fontMetrics; this.descent = descent; this.ascentPlusLeading = ascentPlusLeading; this.height = height; // TODO: In anti-aliasing, stringWidth is said not to be reliable. // Dimensions set when constructed. this.width = fontMetrics.stringWidth(renderedWord); } private String transformText( String word, int textTransform) { String string; switch(textTransform) { case RenderState.TEXTTRANSFORM_CAPITALIZE: string = Character.toTitleCase(word.charAt(0)) + word.substring(1).toLowerCase(); break; case RenderState.TEXTTRANSFORM_LOWERCASE: string = word.toLowerCase(); break; case RenderState.TEXTTRANSFORM_UPPERCASE: string = word.toUpperCase(); break; default: string = word; } return string; } protected void invalidateLayoutLocal() { } /* (non-Javadoc) * @see net.sourceforge.xamj.domimpl.markup.Renderable#paint(java.awt.Graphics) */ public void paint(Graphics g) { RenderState rs = this.modelNode.getRenderState(); String word = this.shownWord; int width = this.width; int ascentPlusLeading = this.ascentPlusLeading; int height = this.height; int textDecoration = rs.getTextDecorationMask(); Color bkg = rs.getTextBackgroundColor(); if(bkg != null) { Color oldColor = g.getColor(); try { g.setColor(bkg); g.fillRect(0, 0, width, height); } finally { g.setColor(oldColor); } } g.drawString(word, 0, ascentPlusLeading); int td = textDecoration; if(td != 0) { if((td & RenderState.MASK_TEXTDECORATION_UNDERLINE) != 0) { int lineOffset = ascentPlusLeading + 2; g.drawLine(0, lineOffset, width, lineOffset); } if ((td & RenderState.MASK_TEXTDECORATION_LINE_THROUGH) != 0) { FontMetrics fm = this.fontMetrics; int lineOffset = fm.getLeading() + (fm.getAscent() + fm.getDescent()) / 2; g.drawLine(0, lineOffset, width, lineOffset); } if ((td & RenderState.MASK_TEXTDECORATION_OVERLINE) != 0) { FontMetrics fm = this.fontMetrics; int lineOffset = fm.getLeading(); g.drawLine(0, lineOffset, width, lineOffset); } if ((td & RenderState.MASK_TEXTDECORATION_BLINK) != 0) { //TODO } } Color over = rs.getOverlayColor(); if(over != null) { Color oldColor = g.getColor(); try { g.setColor(over); g.fillRect(0, 0, width, height); } finally { g.setColor(oldColor); } } } public boolean paintSelection(Graphics g, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { int startX = -1; int endX = -1; if(this == startPoint.renderable) { startX = startPoint.x; } if(this == endPoint.renderable) { endX = endPoint.x; } if(!inSelection && startX == -1 && endX == -1) { return false; } if(startX != -1 && endX != -1) { if(endX < startX) { int temp = startX; startX = endX; endX = temp; } } else if(startX != -1 && endX == -1 && inSelection) { endX = startX; startX = -1; } else if(startX == -1 && endX != -1 && !inSelection) { startX = endX; endX = -1; } int width1 = -1; int width2 = -1; char[] wordChars = this.shownWord.toCharArray(); if(startX != -1) { width1 = 0; FontMetrics fm = this.fontMetrics; for(int len = 0; len < wordChars.length; len++) { int w = fm.charsWidth(wordChars, 0, len); if(w > startX) { break; } width1 = w; } } if(endX != -1) { width2 = 0; FontMetrics fm = this.fontMetrics; for(int len = 0; len < wordChars.length; len++) { int w = fm.charsWidth(wordChars, 0, len); if(w > endX) { break; } width2 = w; } } if(width1 != -1 || width2 != -1) { int startPaint = width1 == -1 ? 0 : width1; int endPaint = width2 == -1 ? this.width : width2; g.setColor(SELECTION_COLOR); g.setXORMode(SELECTION_XOR); g.fillRect(startPaint, 0, endPaint - startPaint, this.height); g.setPaintMode(); return (width2 == -1); } else { if(inSelection) { g.setColor(SELECTION_COLOR); g.setXORMode(SELECTION_XOR); g.fillRect(0, 0, this.width, this.height); g.setPaintMode(); } return inSelection; } } public boolean extractSelectionText(StringBuffer buffer, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { int startX = -1; int endX = -1; if(this == startPoint.renderable) { startX = startPoint.x; } if(this == endPoint.renderable) { endX = endPoint.x; } if(!inSelection && startX == -1 && endX == -1) { return false; } if(startX != -1 && endX != -1) { if(endX < startX) { int temp = startX; startX = endX; endX = temp; } } else if(startX != -1 && endX == -1 && inSelection) { endX = startX; startX = -1; } else if(startX == -1 && endX != -1 && !inSelection) { startX = endX; endX = -1; } int index1 = -1; int index2 = -1; char[] wordChars = this.shownWord.toCharArray(); if(startX != -1) { index1 = 0; FontMetrics fm = this.fontMetrics; for(int len = 0; len < wordChars.length; len++) { int w = fm.charsWidth(wordChars, 0, len); if(w > startX) { break; } index1 = len; } } if(endX != -1) { index2 = 0; FontMetrics fm = this.fontMetrics; for(int len = 0; len < wordChars.length; len++) { int w = fm.charsWidth(wordChars, 0, len); if(w > endX) { break; } index2 = len; } } if(index1 != -1 || index2 != -1) { int startIndex = index1 == -1 ? 0 : index1; int endIndex = index2 == -1 ? wordChars.length : index2; buffer.append(wordChars, startIndex, endIndex - startIndex); } else { if(inSelection) { buffer.append(wordChars); return true; } } if(index1 != -1 && index2 != -1) { return false; } else { return !inSelection; } } public boolean onMouseClick(java.awt.event.MouseEvent event, int x, int y) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onMouseClick(me, event, x, y); } else { return true; } } public boolean onDoubleClick(java.awt.event.MouseEvent event, int x, int y) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onDoubleClick(me, event, x, y); } else { return true; } } public boolean onMousePressed(java.awt.event.MouseEvent event, int x, int y) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onMouseDown(me, event, x, y); } else { return true; } } public boolean onMouseReleased(java.awt.event.MouseEvent event, int x, int y) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onMouseUp(me, event, x, y); } else { return true; } } public boolean onMouseDisarmed(java.awt.event.MouseEvent event) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onMouseDisarmed(me, event); } else { return true; } } public RenderableSpot getLowestRenderableSpot(int x, int y) { return new RenderableSpot(this, x, y); } public boolean isContainedByNode() { return true; } public boolean onRightClick(MouseEvent event, int x, int y) { ModelNode me = this.modelNode; if(me != null) { return HtmlController.getInstance().onContextMenu(me, event, x, y); } else { return true; } } public String toString() { return "RWord[word=" + this.shownWord + "]"; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/Range.java0000644000175000017500000000252610726473510025605 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 16, 2005 */ package org.lobobrowser.html.renderer; /** * @author J. H. S. */ class Range { public final int offset; public final int length; /** * @param offset * @param length */ public Range(final int offset, final int length) { super(); this.offset = offset; this.length = length; } public String toString() { return "Range[offset=" + this.offset + ",length=" + this.length + "]"; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/Renderable.java0000644000175000017500000000235610726473502026616 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 16, 2005 */ package org.lobobrowser.html.renderer; import java.awt.*; import org.lobobrowser.html.domimpl.*; /** * Represents a renderer (view) node. */ public interface Renderable { public static final Renderable[] EMPTY_ARRAY = new Renderable[0]; public void paint(Graphics g); public ModelNode getModelNode(); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/RenderableContainer.java0000644000175000017500000000342410742352620030451 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; import java.awt.Color; import java.awt.Component; /** * A RenderableContainer is either usually a parent * block or the root GUI component. It's is a Renderable * or GUI component whose layout may be invalidated. */ public interface RenderableContainer { //public Insets getInsets(); public Component addComponent(Component component); //public void remove(Component component); public void invalidateLayoutUpTree(); public void repaint(int x, int y, int width, int height); public void relayout(); public void updateAllWidgetBounds(); public Color getPaintedBackgroundColor(); public java.awt.Point getGUIPoint(int x, int y); public void focus(); public void addDelayedPair(DelayedPair pair); public java.util.Collection getDelayedPairs(); public RenderableContainer getParentContainer(); public void clearDelayedPairs(); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/RenderableSpot.java0000644000175000017500000000327110726473502027461 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; import java.awt.Point; /** * Contains a renderer node and a position in that node. */ public class RenderableSpot { public final BoundableRenderable renderable; public final int x; public final int y; /** * @param renderable * @param x * @param y */ public RenderableSpot(BoundableRenderable renderable, int x, int y) { super(); this.renderable = renderable; this.x = x; this.y = y; } public Point getPoint() { return new Point(this.x, this.y); } public boolean equals(Object other) { if(!(other instanceof RenderableSpot)) { return false; } RenderableSpot otherRp = (RenderableSpot) other; return otherRp.renderable == this.renderable && otherRp.x == this.x && otherRp.y == this.y; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/ShiftedFloatingBounds.java0000644000175000017500000000606211131100156030755 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; import org.lobobrowser.util.Objects; class ShiftedFloatingBounds implements FloatingBounds { private final FloatingBounds prevBounds; private final int shiftLeft; private final int shiftRight; private final int shiftY; /** * Constructs the ShiftedFloatingBounds. Floatinb bounds moved * up the hierarchy of renderables will generally have positive * shifts. * @param prevBounds The baseline floating bounds. * @param shiftX How much the original bounds have shifted in the X axis. * @param shiftY How much the original bounds have shifted in the Y axis. */ public ShiftedFloatingBounds(final FloatingBounds prevBounds, final int shiftLeft, final int shiftRight, final int shiftY) { super(); this.prevBounds = prevBounds; this.shiftLeft = shiftLeft; this.shiftRight = shiftRight; this.shiftY = shiftY; } public int getClearY(int y) { return this.prevBounds.getClearY(y - this.shiftY) + this.shiftY; } public int getFirstClearY(int y) { return this.prevBounds.getFirstClearY(y - this.shiftY) + this.shiftY; } public int getLeft(int y) { return this.prevBounds.getLeft(y - this.shiftY) + this.shiftLeft; } public int getLeftClearY(int y) { return this.prevBounds.getLeftClearY(y - this.shiftY) + this.shiftY; } public int getRight(int y) { return this.prevBounds.getRight(y - this.shiftY) + this.shiftRight; } public int getRightClearY(int y) { return this.prevBounds.getRightClearY(y - this.shiftY) + this.shiftY; } public int getMaxY() { return this.prevBounds.getMaxY() + this.shiftY; } public boolean equals(Object obj) { // Important for layout caching. if(!(obj instanceof ShiftedFloatingBounds)) { return false; } ShiftedFloatingBounds other = (ShiftedFloatingBounds) obj; return this.shiftY == other.shiftY && this.shiftLeft == other.shiftLeft && this.shiftRight == other.shiftRight && Objects.equals(this.prevBounds, other.prevBounds); } public int hashCode() { return this.shiftY ^ this.shiftLeft ^ this.shiftRight; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/SizeExceededException.java0000644000175000017500000000061510641432550030761 0ustar twernertwernerpackage org.lobobrowser.html.renderer; class SizeExceededException extends RuntimeException { public SizeExceededException() { super(); } public SizeExceededException(String message, Throwable cause) { super(message, cause); } public SizeExceededException(String message) { super(message); } public SizeExceededException(Throwable cause) { super(cause); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/TableMatrix.java0000644000175000017500000015031611134666026026766 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.renderer; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.util.*; import org.lobobrowser.html.*; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.html.style.*; import org.w3c.dom.Node; import org.w3c.dom.html2.HTMLTableCellElement; import org.w3c.dom.html2.HTMLTableRowElement; class TableMatrix { //private static final NodeFilter ROWS_FILTER = new RowsFilter(); private static final NodeFilter COLUMNS_FILTER = new ColumnsFilter(); private final ArrayList ROWS = new ArrayList(); private final ArrayList ALL_CELLS = new ArrayList(); private final ArrayList ROW_ELEMENTS = new ArrayList(); private final HTMLElementImpl tableElement; private final UserAgentContext parserContext; private final HtmlRendererContext rendererContext; private final FrameContext frameContext; private final RElement relement; private final RenderableContainer container; private SizeInfo[] columnSizes; private SizeInfo[] rowSizes; private int tableWidth; private int tableHeight; /* This is so that we can draw the lines inside the table * that appear when a border attribute is used. */ private int hasOldStyleBorder; /** * @param element */ public TableMatrix(HTMLElementImpl element, UserAgentContext pcontext, HtmlRendererContext rcontext, FrameContext frameContext, RenderableContainer tableAsContainer, RElement relement) { this.tableElement = element; this.parserContext = pcontext; this.rendererContext = rcontext; this.frameContext = frameContext; this.relement = relement; this.container = tableAsContainer; } public void finalize() throws Throwable { super.finalize(); } public int getNumRows() { return this.ROWS.size(); } public int getNumColumns() { return this.columnSizes.length; } /** * @return Returns the tableHeight. */ public int getTableHeight() { return this.tableHeight; } /** * @return Returns the tableWidth. */ public int getTableWidth() { return this.tableWidth; } //private int border; private int cellSpacingY; private int cellSpacingX; private int widthsOfExtras; private int heightsOfExtras; private HtmlLength tableWidthLength; /** * Called on every relayout. * Element children might have changed. */ public void reset(Insets insets, int availWidth, int availHeight) { //TODO: Incorporate into build() and calculate //sizes properly based on parameters. ROWS.clear(); ALL_CELLS.clear(); ROW_ELEMENTS.clear(); //TODO: Does it need this old-style border? String borderText = this.tableElement.getAttribute("border"); int border = 0; if(borderText != null) { try { border = Integer.parseInt(borderText); if(border < 0) { border = 0; } } catch(NumberFormatException nfe) { // ignore } } String cellSpacingText = this.tableElement.getAttribute("cellspacing"); int cellSpacing = 1; if(cellSpacingText != null) { try { //TODO: cellSpacing can be a percentage as well cellSpacing = Integer.parseInt(cellSpacingText); if(cellSpacing < 0) { cellSpacing = 0; } } catch(NumberFormatException nfe) { // ignore } } this.cellSpacingX = cellSpacing; this.cellSpacingY = cellSpacing; this.tableWidthLength = TableMatrix.getWidthLength(this.tableElement, availWidth); this.populateRows(); this.adjustForCellSpans(); this.createSizeArrays(); // Calculate widths of extras SizeInfo[] columnSizes = this.columnSizes; int numCols = columnSizes.length; int widthsOfExtras = insets.left + insets.right + (numCols + 1) * cellSpacing; if(border > 0) { widthsOfExtras += (numCols * 2); } this.widthsOfExtras = widthsOfExtras; // Calculate heights of extras SizeInfo[] rowSizes = this.rowSizes; int numRows = rowSizes.length; int heightsOfExtras = insets.top + insets.bottom + (numRows + 1) * cellSpacing; if(border > 0) { heightsOfExtras += (numRows * 2); } this.heightsOfExtras = heightsOfExtras; this.hasOldStyleBorder = border > 0 ? 1 : 0; } public void build(int availWidth, int availHeight, boolean sizeOnly) { int hasBorder = this.hasOldStyleBorder; this.determineColumnSizes(hasBorder, this.cellSpacingX, this.cellSpacingY, availWidth); this.determineRowSizes(hasBorder, this.cellSpacingY, availHeight, sizeOnly); } private final HTMLTableRowElementImpl getParentRow(HTMLTableCellElementImpl cellNode) { org.w3c.dom.Node parentNode = cellNode.getParentNode(); for(;;) { if(parentNode instanceof HTMLTableRowElementImpl) { return (HTMLTableRowElementImpl) parentNode; } if(parentNode instanceof HTMLTableElementImpl) { return null; } parentNode = parentNode.getParentNode(); } } private static HtmlLength getWidthLength(HTMLElementImpl element, int availWidth) { try { AbstractCSS2Properties props = element.getCurrentStyle(); String widthText = props == null ? null : props.getWidth(); if(widthText == null) { String widthAttr=element.getAttribute("width"); if (widthAttr==null) return null; return new HtmlLength(widthAttr); } else { return new HtmlLength(HtmlValues.getPixelSize(widthText, element.getRenderState(), 0, availWidth)); } } catch(Exception err) { return null; } } private static HtmlLength getHeightLength(HTMLElementImpl element, int availHeight) { try { AbstractCSS2Properties props = element.getCurrentStyle(); String heightText = props == null ? null : props.getHeight(); if(heightText == null) { String ha = element.getAttribute("height"); if(ha == null) { return null; } else { return new HtmlLength(ha); } } else { return new HtmlLength(HtmlValues.getPixelSize(heightText, element.getRenderState(), 0, availHeight)); } } catch(Exception err) { return null; } } /** * Populates the ROWS and ALL_CELLS collections. */ private void populateRows() { HTMLElementImpl te = this.tableElement; ArrayList rows = this.ROWS; ArrayList rowElements = this.ROW_ELEMENTS; ArrayList allCells = this.ALL_CELLS; Map rowElementToRowArray = new HashMap(2); ArrayList cellList = te.getDescendents(COLUMNS_FILTER, false); ArrayList currentNullRow = null; Iterator ci = cellList.iterator(); while(ci.hasNext()) { HTMLTableCellElementImpl columnNode = (HTMLTableCellElementImpl) ci.next(); HTMLTableRowElementImpl rowElement = this.getParentRow(columnNode); if(rowElement != null && rowElement.getRenderState().getDisplay() == RenderState.DISPLAY_NONE) { // Skip row [ 2047122 ] continue; } ArrayList row; if(rowElement != null) { currentNullRow = null; row = (ArrayList) rowElementToRowArray.get(rowElement); if(row == null) { row = new ArrayList(); rowElementToRowArray.put(rowElement, row); rows.add(row); rowElements.add(rowElement); } } else { // Doesn't have a TR parent. Let's add a ROW just for itself. // Both IE and FireFox have this behavior. if(currentNullRow != null) { row = currentNullRow; } else { row = new ArrayList(); currentNullRow = row; rows.add(row); // Null TR element must be added to match. rowElements.add(null); } } RTableCell ac = (RTableCell) columnNode.getUINode(); if(ac == null) { // Saved UI nodes must be reused, because they // can contain a collection of GUI components. ac = new RTableCell(columnNode, this.parserContext, this.rendererContext, this.frameContext, this.container); ac.setParent(this.relement); columnNode.setUINode(ac); } VirtualCell vc = new VirtualCell(ac, true); ac.setTopLeftVirtualCell(vc); row.add(vc); allCells.add(ac); } } /** * Based on colspans and rowspans, creates * additional virtual cells from actual * table cells. */ private void adjustForCellSpans() { ArrayList rows = this.ROWS; int numRows = rows.size(); for(int r = 0; r < numRows; r++) { ArrayList row = (ArrayList) rows.get(r); int numCols = row.size(); for(int c = 0; c < numCols; c++) { VirtualCell vc = (VirtualCell) row.get(c); if(vc != null && vc.isTopLeft()) { RTableCell ac = vc.getActualCell(); int colspan = ac.getColSpan(); if(colspan < 1) { colspan = 1; } int rowspan = ac.getRowSpan(); if(rowspan < 1) { rowspan = 1; } // Can't go beyond last row (Fix bug #2022584) int targetRows = r + rowspan; if(numRows < targetRows) { rowspan = numRows - r; ac.setRowSpan(rowspan); } numRows = rows.size(); for(int y = 0; y < rowspan; y++) { if(colspan > 1 || y > 0) { // Get row int nr = r + y; ArrayList newRow = (ArrayList) rows.get(nr); // Insert missing cells in row int xstart = y == 0 ? 1 : 0; // Insert virtual cells, potentially // shifting others to the right. for(int cc = xstart; cc < colspan; cc++) { int nc = c + cc; while(newRow.size() < nc) { newRow.add(null); } newRow.add(nc, new VirtualCell(ac, false)); } if(row == newRow) { numCols = row.size(); } } } } } } // Adjust row and column of virtual cells for(int r = 0; r < numRows; r++) { ArrayList row = (ArrayList) rows.get(r); int numCols = row.size(); for(int c = 0; c < numCols; c++) { VirtualCell vc = (VirtualCell) row.get(c); if(vc != null) { vc.setColumn(c); vc.setRow(r); } } } } /** * Populates the columnSizes and rowSizes arrays, * setting htmlLength in each element. */ private void createSizeArrays() { ArrayList rows = this.ROWS; int numRows = rows.size(); SizeInfo[] rowSizes = new SizeInfo[numRows]; this.rowSizes = rowSizes; int numCols = 0; ArrayList rowElements = this.ROW_ELEMENTS; for(int i = 0; i < numRows; i++) { ArrayList row = (ArrayList) rows.get(i); int rs = row.size(); if(rs > numCols) { numCols = rs; } SizeInfo rowSizeInfo = new SizeInfo(); rowSizes[i] = rowSizeInfo; HTMLTableRowElement rowElement; try { rowElement = (HTMLTableRowElement) rowElements.get(i); // Possible rowElement is null because TD does not have TR parent } catch(IndexOutOfBoundsException iob) { //Possible if rowspan expands beyond that rowElement = null; } //TODO: TR.height an IE quirk? String rowHeightText = rowElement == null ? null : rowElement.getAttribute("height"); HtmlLength rowHeightLength = null; if(rowHeightText != null) { try { rowHeightLength = new HtmlLength(rowHeightText); } catch(Exception err) { // ignore } } if(rowHeightLength != null) { rowSizeInfo.htmlLength = rowHeightLength; } else { HtmlLength bestHeightLength = null; for(int x = 0; x < rs; x++) { VirtualCell vc = (VirtualCell) row.get(x); if(vc != null) { HtmlLength vcHeightLength = vc.getHeightLength(); if(vcHeightLength != null && vcHeightLength.isPreferredOver(bestHeightLength)) { bestHeightLength = vcHeightLength; } } } rowSizeInfo.htmlLength = bestHeightLength; } } SizeInfo[] columnSizes = new SizeInfo[numCols]; this.columnSizes = columnSizes; for(int i = 0; i < numCols; i++) { HtmlLength bestWidthLength = null; // Cells with colspan==1 first. for(int y = 0; y < numRows; y++) { ArrayList row = (ArrayList) rows.get(y); VirtualCell vc; try { vc = (VirtualCell) row.get(i); } catch(IndexOutOfBoundsException iob) { vc = null; } if(vc != null) { RTableCell ac = vc.getActualCell(); if(ac.getColSpan() == 1) { HtmlLength vcWidthLength = vc.getWidthLength(); if(vcWidthLength != null && vcWidthLength.isPreferredOver(bestWidthLength)) { bestWidthLength = vcWidthLength; } } } } // Now cells with colspan>1. if(bestWidthLength == null) { for(int y = 0; y < numRows; y++) { ArrayList row = (ArrayList) rows.get(y); VirtualCell vc; try { vc = (VirtualCell) row.get(i); } catch(IndexOutOfBoundsException iob) { vc = null; } if(vc != null) { RTableCell ac = vc.getActualCell(); if(ac.getColSpan() > 1) { HtmlLength vcWidthLength = vc.getWidthLength(); if(vcWidthLength != null && vcWidthLength.isPreferredOver(bestWidthLength)) { bestWidthLength = vcWidthLength; } } } } } SizeInfo colSizeInfo = new SizeInfo(); colSizeInfo.htmlLength = bestWidthLength; columnSizes[i] = colSizeInfo; } } /** * Determines the size of each column, and the table width. * Does the following: *

    *
  1. Determine tentative widths. This is done by looking * at declared column widths, any table width, and * filling in the blanks. No rendering is done. * The tentative * width of columns with no declared width is zero. * *
  2. Render all cell blocks. It uses the tentative widths from * the previous step as a desired width. The resulting width * is considered a sort of minimum. If the column * width is not defined, use a NOWRAP override flag to render. * *
  3. Check if cell widths are too narrow for the rendered * width. In the case of columns without a declared width, * check if they are too wide. * *
  4. Finally, adjust widths considering the expected max table * size. Columns are layed out again if necessary to determine * if they can really be shrunk. *
* @param renderState * @param border * @param cellSpacingX * @param cellSpacingY * @param availWidth */ private void determineColumnSizes(int hasBorder, int cellSpacingX, int cellSpacingY, int availWidth) { HtmlLength tableWidthLength = this.tableWidthLength; int tableWidth; boolean widthKnown; if(tableWidthLength != null) { tableWidth = tableWidthLength.getLength(availWidth); widthKnown = true; } else { tableWidth = availWidth; widthKnown = false; } SizeInfo[] columnSizes = this.columnSizes; int widthsOfExtras = this.widthsOfExtras; int cellAvailWidth = tableWidth - widthsOfExtras; if(cellAvailWidth < 0) { tableWidth += (-cellAvailWidth); cellAvailWidth = 0; } // Determine tentative column widths based on specified cell widths this.determineTentativeSizes(columnSizes, widthsOfExtras, cellAvailWidth, widthKnown); // Pre-render cells. This will give the minimum width of each cell, // in addition to the minimum height. this.preLayout(hasBorder, cellSpacingX, cellSpacingY, widthKnown); // Increases column widths if they are less than minimums of each cell. this.adjustForRenderWidths(columnSizes, hasBorder, cellSpacingX, widthKnown); // Adjust for expected total width this.adjustWidthsForExpectedMax(columnSizes, cellAvailWidth, widthKnown); } /** * This method sets the tentative actual sizes of columns (rows) based * on specified witdhs (heights) if available. * @param columnSizes * @param widthsOfExtras * @param cellAvailWidth */ private void determineTentativeSizes(SizeInfo[] columnSizes, int widthsOfExtras, int cellAvailWidth, boolean setNoWidthColumns) { int numCols = columnSizes.length; // Look at percentages first int widthUsedByPercent = 0; for(int i = 0; i < numCols; i++) { SizeInfo colSizeInfo = columnSizes[i]; HtmlLength widthLength = colSizeInfo.htmlLength; if(widthLength != null && widthLength.getLengthType() == HtmlLength.LENGTH) { int actualSizeInt = widthLength.getLength(cellAvailWidth); widthUsedByPercent += actualSizeInt; colSizeInfo.actualSize = actualSizeInt; } } // Look at columns with absolute sizes int widthUsedByAbsolute = 0; int numNoWidthColumns = 0; for(int i = 0; i < numCols; i++) { SizeInfo colSizeInfo = columnSizes[i]; HtmlLength widthLength = colSizeInfo.htmlLength; if(widthLength != null && widthLength.getLengthType() != HtmlLength.LENGTH) { //TODO: MULTI-LENGTH not supported int actualSizeInt = widthLength.getRawValue(); widthUsedByAbsolute += actualSizeInt; colSizeInfo.actualSize = actualSizeInt; } else if(widthLength == null) { numNoWidthColumns++; } } // Tentative width of all columns without a declared // width is set to zero. The pre-render will determine // a better size. // // Assign all columns without widths now // int widthUsedByUnspecified = 0; // if(setNoWidthColumns) { // int remainingWidth = cellAvailWidth - widthUsedByAbsolute - widthUsedByPercent; // if(remainingWidth > 0) { // for(int i = 0; i < numCols; i++) { // SizeInfo colSizeInfo = columnSizes[i]; // HtmlLength widthLength = colSizeInfo.htmlLength; // if(widthLength == null) { // int actualSizeInt = remainingWidth / numNoWidthColumns; // widthUsedByUnspecified += actualSizeInt; // colSizeInfo.actualSize = actualSizeInt; // } // } // } // } // Contract if necessary. This is done again later, but this is // an optimization, as it may prevent re-layout. It is only done // if all columns have some kind of declared width. if(numNoWidthColumns == 0) { int totalWidthUsed = widthUsedByPercent + widthUsedByAbsolute; int difference = totalWidthUsed - cellAvailWidth; // See if absolutes need to be contracted if(difference > 0) { if(widthUsedByAbsolute > 0) { int expectedAbsoluteWidthTotal = widthUsedByAbsolute - difference; if(expectedAbsoluteWidthTotal < 0) { expectedAbsoluteWidthTotal = 0; } double ratio = (double) expectedAbsoluteWidthTotal / widthUsedByAbsolute; for(int i = 0; i < numCols; i++) { SizeInfo sizeInfo = columnSizes[i]; HtmlLength widthLength = columnSizes[i].htmlLength; if(widthLength != null && widthLength.getLengthType() != HtmlLength.LENGTH) { int oldActualSize = sizeInfo.actualSize; int newActualSize = (int) Math.round(oldActualSize * ratio); sizeInfo.actualSize = newActualSize; totalWidthUsed += (newActualSize - oldActualSize); } } difference = totalWidthUsed - cellAvailWidth; } // See if percentages need to be contracted if(difference > 0) { if(widthUsedByPercent > 0) { int expectedPercentWidthTotal = widthUsedByPercent - difference; if(expectedPercentWidthTotal < 0) { expectedPercentWidthTotal = 0; } double ratio = (double) expectedPercentWidthTotal / widthUsedByPercent; for(int i = 0; i < numCols; i++) { SizeInfo sizeInfo = columnSizes[i]; HtmlLength widthLength = columnSizes[i].htmlLength; if(widthLength != null && widthLength.getLengthType() == HtmlLength.LENGTH) { int oldActualSize = sizeInfo.actualSize; int newActualSize = (int) Math.round(oldActualSize * ratio); sizeInfo.actualSize = newActualSize; totalWidthUsed += (newActualSize - oldActualSize); } } } } } } } /** * Contracts column sizes according to render sizes. */ private void adjustForRenderWidths(SizeInfo[] columnSizes, int hasBorder, int cellSpacing, boolean tableWidthKnown) { int numCols = columnSizes.length; for(int i = 0; i < numCols; i++) { SizeInfo si = columnSizes[i]; if(si.actualSize < si.layoutSize) { si.actualSize = si.layoutSize; } // else if(si.htmlLength == null) { // // For cells without a declared width, see if // // their tentative width is a bit too big. // if(si.actualSize > si.layoutSize) { // si.actualSize = si.layoutSize; // } // } } } private void layoutColumn(SizeInfo[] columnSizes, SizeInfo colSize, int col, int cellSpacingX, int hasBorder) { SizeInfo[] rowSizes = this.rowSizes; ArrayList rows = this.ROWS; int numRows = rows.size(); int actualSize = colSize.actualSize; colSize.layoutSize = 0; for(int row = 0; row < numRows;) { //SizeInfo rowSize = rowSizes[row]; ArrayList columns = (ArrayList) rows.get(row); VirtualCell vc = null; try { vc = (VirtualCell) columns.get(col); } catch(IndexOutOfBoundsException iob) { vc = null; } RTableCell ac = vc == null ? null : vc.getActualCell(); if(ac != null) { if(ac.getVirtualRow() == row) { // Only process actual cells with a row // beginning at the current row being processed. int colSpan = ac.getColSpan(); if(colSpan > 1) { int firstCol = ac.getVirtualColumn(); int cellExtras = (colSpan - 1) * (cellSpacingX + 2 * hasBorder); int vcActualWidth = cellExtras; for(int x = 0; x < colSpan; x++) { vcActualWidth += columnSizes[firstCol + x].actualSize; } //TODO: better height possible Dimension size = ac.doCellLayout(vcActualWidth, 0, true, true, true); int vcRenderWidth = size.width; int denominator = (vcActualWidth - cellExtras); int newTentativeCellWidth; if(denominator > 0) { newTentativeCellWidth = actualSize * (vcRenderWidth - cellExtras) / denominator; } else { newTentativeCellWidth = (vcRenderWidth - cellExtras) / colSpan; } if(newTentativeCellWidth > colSize.layoutSize) { colSize.layoutSize = newTentativeCellWidth; } int rowSpan = ac.getRowSpan(); int vch = (size.height - (rowSpan - 1) * (this.cellSpacingY + 2 * hasBorder)) / rowSpan; for(int y = 0; y < rowSpan; y++) { if(rowSizes[row + y].minSize < vch) { rowSizes[row + y].minSize = vch; } } } else { //TODO: better height possible Dimension size = ac.doCellLayout(actualSize, 0, true, true, true); if(size.width > colSize.layoutSize) { colSize.layoutSize = size.width; } int rowSpan = ac.getRowSpan(); int vch = (size.height - (rowSpan - 1) * (this.cellSpacingY + 2 * hasBorder)) / rowSpan; for(int y = 0; y < rowSpan; y++) { if(rowSizes[row + y].minSize < vch) { rowSizes[row + y].minSize = vch; } } } } } //row = (ac == null ? row + 1 : ac.getVirtualRow() + ac.getRowSpan()); row++; } } private int adjustWidthsForExpectedMax(SizeInfo[] columnSizes, int cellAvailWidth, boolean expand) { int hasBorder = this.hasOldStyleBorder; int cellSpacingX = this.cellSpacingX; int currentTotal = 0; int numCols = columnSizes.length; for(int i = 0; i < numCols; i++) { currentTotal += columnSizes[i].actualSize; } int difference = currentTotal - cellAvailWidth; if(difference > 0 || (difference < 0 && expand)) { // First, try to contract/expand columns with no width int noWidthTotal = 0; int numNoWidth = 0; for(int i = 0; i < numCols; i++) { if(columnSizes[i].htmlLength == null) { numNoWidth++; noWidthTotal += columnSizes[i].actualSize; } } if(noWidthTotal > 0) { //TODO: This is not shrinking correctly. int expectedNoWidthTotal = noWidthTotal - difference; if(expectedNoWidthTotal < 0) { expectedNoWidthTotal = 0; } double ratio = (double) expectedNoWidthTotal / noWidthTotal; int noWidthCount = 0; for(int i = 0; i < numCols; i++) { SizeInfo sizeInfo = columnSizes[i]; if(sizeInfo.htmlLength == null) { int oldActualSize = sizeInfo.actualSize; int newActualSize; if(++noWidthCount == numNoWidth) { // Last column without a width. int currentDiff = currentTotal - cellAvailWidth; newActualSize = oldActualSize - currentDiff; if(newActualSize < 0) { newActualSize = 0; } } else { newActualSize = (int) Math.round(oldActualSize * ratio); } sizeInfo.actualSize = newActualSize; if(newActualSize < sizeInfo.layoutSize) { // See if it actually fits. this.layoutColumn(columnSizes, sizeInfo, i, cellSpacingX, hasBorder); if(newActualSize < sizeInfo.layoutSize) { // Didn't fit. newActualSize = sizeInfo.layoutSize; sizeInfo.actualSize = newActualSize; } } currentTotal += (newActualSize - oldActualSize); } } difference = currentTotal - cellAvailWidth; } // See if absolutes need to be contracted if(difference > 0 || (difference < 0 && expand)) { int absoluteWidthTotal = 0; for(int i = 0; i < numCols; i++) { HtmlLength widthLength = columnSizes[i].htmlLength; if(widthLength != null && widthLength.getLengthType() != HtmlLength.LENGTH) { absoluteWidthTotal += columnSizes[i].actualSize; } } if(absoluteWidthTotal > 0) { int expectedAbsoluteWidthTotal = absoluteWidthTotal - difference; if(expectedAbsoluteWidthTotal < 0) { expectedAbsoluteWidthTotal = 0; } double ratio = (double) expectedAbsoluteWidthTotal / absoluteWidthTotal; for(int i = 0; i < numCols; i++) { SizeInfo sizeInfo = columnSizes[i]; HtmlLength widthLength = columnSizes[i].htmlLength; if(widthLength != null && widthLength.getLengthType() != HtmlLength.LENGTH) { int oldActualSize = sizeInfo.actualSize; int newActualSize = (int) Math.round(oldActualSize * ratio); sizeInfo.actualSize = newActualSize; if(newActualSize < sizeInfo.layoutSize) { // See if it actually fits. this.layoutColumn(columnSizes, sizeInfo, i, cellSpacingX, hasBorder); if(newActualSize < sizeInfo.layoutSize) { // Didn't fit. newActualSize = sizeInfo.layoutSize; sizeInfo.actualSize = newActualSize; } } currentTotal += (newActualSize - oldActualSize); } } difference = currentTotal - cellAvailWidth; } // See if percentages need to be contracted if(difference > 0 || (difference < 0 && expand)) { int percentWidthTotal = 0; for(int i = 0; i < numCols; i++) { HtmlLength widthLength = columnSizes[i].htmlLength; if(widthLength != null && widthLength.getLengthType() == HtmlLength.LENGTH) { percentWidthTotal += columnSizes[i].actualSize; } } if(percentWidthTotal > 0) { int expectedPercentWidthTotal = percentWidthTotal - difference; if(expectedPercentWidthTotal < 0) { expectedPercentWidthTotal = 0; } double ratio = (double) expectedPercentWidthTotal / percentWidthTotal; for(int i = 0; i < numCols; i++) { SizeInfo sizeInfo = columnSizes[i]; HtmlLength widthLength = columnSizes[i].htmlLength; if(widthLength != null && widthLength.getLengthType() == HtmlLength.LENGTH) { int oldActualSize = sizeInfo.actualSize; int newActualSize = (int) Math.round(oldActualSize * ratio); sizeInfo.actualSize = newActualSize; if(newActualSize < sizeInfo.layoutSize) { // See if it actually fits. this.layoutColumn(columnSizes, sizeInfo, i, cellSpacingX, hasBorder); if(newActualSize < sizeInfo.layoutSize) { // Didn't fit. newActualSize = sizeInfo.layoutSize; sizeInfo.actualSize = newActualSize; } } currentTotal += (newActualSize - oldActualSize); } } } } } } return currentTotal; } /** * This method renders each cell using already set actual column widths. * It sets minimum row heights based on this. */ private final void preLayout(int hasBorder, int cellSpacingX, int cellSpacingY, boolean tableWidthKnown) { //TODO: Fix for table without width that has a subtable with width=100%. //TODO: Maybe it can be addressed when NOWRAP is implemented. //TODO: Maybe it's possible to eliminate this pre-layout altogether. SizeInfo[] colSizes = this.columnSizes; SizeInfo[] rowSizes = this.rowSizes; // Initialize minSize in rows int numRows = rowSizes.length; for(int i = 0; i < numRows; i++) { rowSizes[i].minSize = 0; } // Initialize layoutSize in columns int numCols = colSizes.length; for(int i = 0; i < numCols; i++) { colSizes[i].layoutSize = 0; } ArrayList allCells = this.ALL_CELLS; int numCells = allCells.size(); for(int i = 0; i < numCells; i++) { RTableCell cell = (RTableCell) allCells.get(i); int col = cell.getVirtualColumn(); int colSpan = cell.getColSpan(); int cellsTotalWidth; int cellsUsedWidth; boolean widthDeclared = false; if(colSpan > 1) { cellsUsedWidth = 0; for(int x = 0; x < colSpan; x++) { SizeInfo colSize = colSizes[col + x]; if(colSize.htmlLength != null) { widthDeclared = true; } cellsUsedWidth += colSize.actualSize; } cellsTotalWidth = cellsUsedWidth + (colSpan - 1) * (cellSpacingX + 2 * hasBorder); } else { SizeInfo colSize = colSizes[col]; if(colSize.htmlLength != null) { widthDeclared = true; } cellsUsedWidth = cellsTotalWidth = colSize.actualSize; } //TODO: A tentative height could be used here: Height of //table divided by number of rows. java.awt.Dimension size; RenderThreadState state = RenderThreadState.getState(); boolean prevOverrideNoWrap = state.overrideNoWrap; try { if(!prevOverrideNoWrap) { state.overrideNoWrap = !widthDeclared; } size = cell.doCellLayout(cellsTotalWidth, 0, true, true, true); } finally { state.overrideNoWrap = prevOverrideNoWrap; } // Set render widths int cellLayoutWidth = size.width; if(colSpan > 1) { if(cellsUsedWidth > 0) { double ratio = (double) cellLayoutWidth / cellsUsedWidth; for(int x = 0; x < colSpan; x++) { SizeInfo si = colSizes[col + x]; int newLayoutSize = (int) Math.round(si.actualSize * ratio); if(si.layoutSize < newLayoutSize) { si.layoutSize = newLayoutSize; } } } else { int newLayoutSize = cellLayoutWidth / colSpan; for(int x = 0; x < colSpan; x++) { SizeInfo si = colSizes[col + x]; if(si.layoutSize < newLayoutSize) { si.layoutSize = newLayoutSize; } } } } else { SizeInfo colSizeInfo = colSizes[col]; if(colSizeInfo.layoutSize < cellLayoutWidth) { colSizeInfo.layoutSize = cellLayoutWidth; } } // Set minimum heights int actualCellHeight = size.height; int row = cell.getVirtualRow(); int rowSpan = cell.getRowSpan(); if(rowSpan > 1) { int vch = (actualCellHeight - (rowSpan - 1) * (cellSpacingY + 2 * hasBorder)) / rowSpan; for(int y = 0; y < rowSpan; y++) { if(rowSizes[row + y].minSize < vch) { rowSizes[row + y].minSize = vch; } } } else { if(rowSizes[row].minSize < actualCellHeight) { rowSizes[row].minSize = actualCellHeight; } } } } private void determineRowSizes(int hasBorder, int cellSpacing, int availHeight, boolean sizeOnly) { HtmlLength tableHeightLength = TableMatrix.getHeightLength(this.tableElement, availHeight); int tableHeight; SizeInfo[] rowSizes = this.rowSizes; int numRows = rowSizes.length; int heightsOfExtras = this.heightsOfExtras; if(tableHeightLength != null) { tableHeight = tableHeightLength.getLength(availHeight); this.determineRowSizesFixedTH(hasBorder, cellSpacing, availHeight, tableHeight, sizeOnly); } else { tableHeight = heightsOfExtras; for(int row = 0; row < numRows; row++) { tableHeight += rowSizes[row].minSize; } this.determineRowSizesFlexibleTH(hasBorder, cellSpacing, availHeight, sizeOnly); } } private void determineRowSizesFixedTH(int hasBorder, int cellSpacing, int availHeight, int tableHeight, boolean sizeOnly) { SizeInfo[] rowSizes = this.rowSizes; int numRows = rowSizes.length; int heightsOfExtras = this.heightsOfExtras; int cellAvailHeight = tableHeight - heightsOfExtras; if(cellAvailHeight < 0) { cellAvailHeight = 0; } // Look at percentages first int heightUsedbyPercent = 0; int otherMinSize = 0; for(int i = 0; i < numRows; i++) { SizeInfo rowSizeInfo = rowSizes[i]; HtmlLength heightLength = rowSizeInfo.htmlLength; if(heightLength != null && heightLength.getLengthType() == HtmlLength.LENGTH) { int actualSizeInt = heightLength.getLength(cellAvailHeight); if(actualSizeInt < rowSizeInfo.minSize) { actualSizeInt = rowSizeInfo.minSize; } heightUsedbyPercent += actualSizeInt; rowSizeInfo.actualSize = actualSizeInt; } else { otherMinSize += rowSizeInfo.minSize; } } // Check if rows with percent are bigger than they should be if(heightUsedbyPercent + otherMinSize > cellAvailHeight) { double ratio = (double) (cellAvailHeight - otherMinSize) / heightUsedbyPercent; for(int i = 0; i < numRows; i++) { SizeInfo rowSizeInfo = rowSizes[i]; HtmlLength heightLength = rowSizeInfo.htmlLength; if(heightLength != null && heightLength.getLengthType() == HtmlLength.LENGTH) { int actualSize = rowSizeInfo.actualSize; int prevActualSize = actualSize; int newActualSize = (int) Math.round(prevActualSize * ratio); if(newActualSize < rowSizeInfo.minSize) { newActualSize = rowSizeInfo.minSize; } heightUsedbyPercent += (newActualSize - prevActualSize); rowSizeInfo.actualSize = newActualSize; } } } // Look at rows with absolute sizes int heightUsedByAbsolute = 0; int noHeightMinSize = 0; int numNoHeightColumns = 0; for(int i = 0; i < numRows; i++) { SizeInfo rowSizeInfo = rowSizes[i]; HtmlLength heightLength = rowSizeInfo.htmlLength; if(heightLength != null && heightLength.getLengthType() != HtmlLength.LENGTH) { //TODO: MULTI-LENGTH not supported int actualSizeInt = heightLength.getRawValue(); if(actualSizeInt < rowSizeInfo.minSize) { actualSizeInt = rowSizeInfo.minSize; } heightUsedByAbsolute += actualSizeInt; rowSizeInfo.actualSize = actualSizeInt; } else if(heightLength == null) { numNoHeightColumns++; noHeightMinSize += rowSizeInfo.minSize; } } // Check if absolute sizing is too much if(heightUsedByAbsolute + heightUsedbyPercent + noHeightMinSize > cellAvailHeight) { double ratio = (double) (cellAvailHeight - noHeightMinSize - heightUsedbyPercent) / heightUsedByAbsolute; for(int i = 0; i < numRows; i++) { SizeInfo rowSizeInfo = rowSizes[i]; HtmlLength heightLength = rowSizeInfo.htmlLength; if(heightLength != null && heightLength.getLengthType() != HtmlLength.LENGTH) { int actualSize = rowSizeInfo.actualSize; int prevActualSize = actualSize; int newActualSize = (int) Math.round(prevActualSize * ratio); if(newActualSize < rowSizeInfo.minSize) { newActualSize = rowSizeInfo.minSize; } heightUsedByAbsolute += (newActualSize - prevActualSize); rowSizeInfo.actualSize = newActualSize; } } } // Assign all rows without heights now int remainingHeight = cellAvailHeight - heightUsedByAbsolute - heightUsedbyPercent; int heightUsedByRemaining = 0; for(int i = 0; i < numRows; i++) { SizeInfo rowSizeInfo = rowSizes[i]; HtmlLength heightLength = rowSizeInfo.htmlLength; if(heightLength == null) { int actualSizeInt = remainingHeight / numNoHeightColumns; if(actualSizeInt < rowSizeInfo.minSize) { actualSizeInt = rowSizeInfo.minSize; } heightUsedByRemaining += actualSizeInt; rowSizeInfo.actualSize = actualSizeInt; } } // Calculate actual table width int totalUsed = heightUsedByAbsolute + heightUsedbyPercent + heightUsedByRemaining; if(totalUsed >= cellAvailHeight) { this.tableHeight = totalUsed + heightsOfExtras; } else { // Rows too short; expand them double ratio = (double) cellAvailHeight / totalUsed; for(int i = 0; i < numRows; i++) { SizeInfo rowSizeInfo = rowSizes[i]; int actualSize = rowSizeInfo.actualSize; rowSizeInfo.actualSize = (int) Math.round(actualSize * ratio); } this.tableHeight = tableHeight; } //TODO: // This final render is probably unnecessary. Avoid exponential rendering // by setting a single height of subcell. Verify that IE only sets height // of subcells when height of row or table are specified. this.finalRender(hasBorder, cellSpacing, sizeOnly); } private void determineRowSizesFlexibleTH(int hasBorder, int cellSpacing, int availHeight, boolean sizeOnly) { SizeInfo[] rowSizes = this.rowSizes; int numRows = rowSizes.length; int heightsOfExtras = this.heightsOfExtras; // Look at rows with absolute sizes int heightUsedByAbsolute = 0; int percentSum = 0; for(int i = 0; i < numRows; i++) { SizeInfo rowSizeInfo = rowSizes[i]; HtmlLength heightLength = rowSizeInfo.htmlLength; if(heightLength != null && heightLength.getLengthType() == HtmlLength.PIXELS) { //TODO: MULTI-LENGTH not supported int actualSizeInt = heightLength.getRawValue(); if(actualSizeInt < rowSizeInfo.minSize) { actualSizeInt = rowSizeInfo.minSize; } heightUsedByAbsolute += actualSizeInt; rowSizeInfo.actualSize = actualSizeInt; } else if(heightLength != null && heightLength.getLengthType() == HtmlLength.LENGTH) { percentSum += heightLength.getRawValue(); } } // Look at rows with no specified heights int heightUsedByNoSize = 0; // Set sizes to in row height for(int i = 0; i < numRows; i++) { SizeInfo rowSizeInfo = rowSizes[i]; HtmlLength widthLength = rowSizeInfo.htmlLength; if(widthLength == null) { int actualSizeInt = rowSizeInfo.minSize; heightUsedByNoSize += actualSizeInt; rowSizeInfo.actualSize = actualSizeInt; } } // Calculate actual total cell width int expectedTotalCellHeight = (int) Math.round((heightUsedByAbsolute + heightUsedByNoSize) / (1 - (percentSum / 100.0))); // Set widths of columns with percentages int heightUsedByPercent = 0; for(int i = 0; i < numRows; i++) { SizeInfo rowSizeInfo = rowSizes[i]; HtmlLength heightLength = rowSizeInfo.htmlLength; if(heightLength != null && heightLength.getLengthType() == HtmlLength.LENGTH) { int actualSizeInt = heightLength.getLength(expectedTotalCellHeight); if(actualSizeInt < rowSizeInfo.minSize) { actualSizeInt = rowSizeInfo.minSize; } heightUsedByPercent += actualSizeInt; rowSizeInfo.actualSize = actualSizeInt; } } // Set width of table this.tableHeight = heightUsedByAbsolute + heightUsedByNoSize + heightUsedByPercent + heightsOfExtras; // Do a final render to set actual cell sizes this.finalRender(hasBorder, cellSpacing, sizeOnly); } /** * This method renders each cell using already set actual column widths. * It sets minimum row heights based on this. */ private final void finalRender(int hasBorder, int cellSpacing, boolean sizeOnly) { // finalRender needs to adjust actualSize of columns and rows // given that things might change as we render one last time. ArrayList allCells = this.ALL_CELLS; SizeInfo[] colSizes = this.columnSizes; SizeInfo[] rowSizes = this.rowSizes; int numCells = allCells.size(); for(int i = 0; i < numCells; i++) { RTableCell cell = (RTableCell) allCells.get(i); int col = cell.getVirtualColumn(); int colSpan = cell.getColSpan(); int totalCellWidth; if(colSpan > 1) { totalCellWidth = (colSpan - 1) * (cellSpacing + 2 * hasBorder); for(int x = 0; x < colSpan; x++) { totalCellWidth += colSizes[col + x].actualSize; } } else { totalCellWidth = colSizes[col].actualSize; } int row = cell.getVirtualRow(); int rowSpan = cell.getRowSpan(); int totalCellHeight; if(rowSpan > 1) { totalCellHeight = (rowSpan - 1) * (cellSpacing + 2 * hasBorder); for(int y = 0; y < rowSpan; y++) { totalCellHeight += rowSizes[row + y].actualSize; } } else { totalCellHeight = rowSizes[row].actualSize; } Dimension size = cell.doCellLayout(totalCellWidth, totalCellHeight, true, true, sizeOnly); if(size.width > totalCellWidth) { if(colSpan == 1) { colSizes[col].actualSize = size.width; } else { colSizes[col].actualSize += (size.width - totalCellWidth); } } if(size.height > totalCellHeight) { if(rowSpan == 1) { rowSizes[row].actualSize = size.height; } else { rowSizes[row].actualSize += (size.height - totalCellHeight); } } } } // public final void adjust() { // // finalRender needs to adjust actualSize of columns and rows // // given that things might change as we render one last time. // int hasBorder = this.hasOldStyleBorder; // int cellSpacingX = this.cellSpacingX; // int cellSpacingY = this.cellSpacingY; // ArrayList allCells = this.ALL_CELLS; // SizeInfo[] colSizes = this.columnSizes; // SizeInfo[] rowSizes = this.rowSizes; // int numCells = allCells.size(); // for(int i = 0; i < numCells; i++) { // RTableCell cell = (RTableCell) allCells.get(i); // int col = cell.getVirtualColumn(); // int colSpan = cell.getColSpan(); // int totalCellWidth; // if(colSpan > 1) { // totalCellWidth = (colSpan - 1) * (cellSpacingX + 2 * hasBorder); // for(int x = 0; x < colSpan; x++) { // totalCellWidth += colSizes[col + x].actualSize; // } // } // else { // totalCellWidth = colSizes[col].actualSize; // } // int row = cell.getVirtualRow(); // int rowSpan = cell.getRowSpan(); // int totalCellHeight; // if(rowSpan > 1) { // totalCellHeight = (rowSpan - 1) * (cellSpacingY + 2 * hasBorder); // for(int y = 0; y < rowSpan; y++) { // totalCellHeight += rowSizes[row + y].actualSize; // } // } // else { // totalCellHeight = rowSizes[row].actualSize; // } // cell.adjust(); // Dimension size = cell.getSize(); // if(size.width > totalCellWidth) { // if(colSpan == 1) { // colSizes[col].actualSize = size.width; // } // else { // colSizes[col].actualSize += (size.width - totalCellWidth); // } // } // if(size.height > totalCellHeight) { // if(rowSpan == 1) { // rowSizes[row].actualSize = size.height; // } // else { // rowSizes[row].actualSize += (size.height - totalCellHeight); // } // } // } // } /** * Sets bounds of each cell's component, and sumps up table width * and height. */ public final void doLayout(Insets insets) { // Set row offsets SizeInfo[] rowSizes = this.rowSizes; int numRows = rowSizes.length; int yoffset = insets.top; int cellSpacingY = this.cellSpacingY; int hasBorder = this.hasOldStyleBorder; for(int i = 0; i < numRows; i++) { yoffset += cellSpacingY; yoffset += hasBorder; SizeInfo rowSizeInfo = rowSizes[i]; rowSizeInfo.offset = yoffset; yoffset += rowSizeInfo.actualSize; yoffset += hasBorder; } this.tableHeight = yoffset + cellSpacingY + insets.bottom; // Set colum offsets SizeInfo[] colSizes = this.columnSizes; int numColumns = colSizes.length; int xoffset = insets.left; int cellSpacingX = this.cellSpacingX; for(int i = 0; i < numColumns; i++) { xoffset += cellSpacingX; xoffset += hasBorder; SizeInfo colSizeInfo = colSizes[i]; colSizeInfo.offset = xoffset; xoffset += colSizeInfo.actualSize; xoffset += hasBorder; } this.tableWidth = xoffset + cellSpacingX + insets.right; // Set offsets of each cell ArrayList allCells = this.ALL_CELLS; int numCells = allCells.size(); for(int i = 0; i < numCells; i++) { RTableCell cell = (RTableCell) allCells.get(i); cell.setCellBounds(colSizes, rowSizes, hasBorder, cellSpacingX, cellSpacingY); } } public final void paint(Graphics g, Dimension size) { ArrayList allCells = this.ALL_CELLS; int numCells = allCells.size(); for(int i = 0; i < numCells; i++) { RTableCell cell = (RTableCell) allCells.get(i); // Should clip table cells, just in case. Graphics newG = g.create(cell.x, cell.y, cell.width, cell.height); try { cell.paint(newG); } finally { newG.dispose(); } } if(this.hasOldStyleBorder > 0) { // // Paint table border // // int tableWidth = this.tableWidth; // int tableHeight = this.tableHeight; // g.setColor(Color.BLACK); //TODO: Actual border color // int x = insets.left; // int y = insets.top; // for(int i = 0; i < border; i++) { // g.drawRect(x + i, y + i, tableWidth - i * 2 - 1, tableHeight - i * 2 - 1); // } // Paint cell borders g.setColor(Color.GRAY); for(int i = 0; i < numCells; i++) { RTableCell cell = (RTableCell) allCells.get(i); int cx = cell.getX() - 1; int cy = cell.getY() - 1; int cwidth = cell.getWidth() + 1; int cheight = cell.getHeight() + 1; g.drawRect(cx, cy, cwidth, cheight); } } } // public boolean paintSelection(Graphics g, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { // ArrayList allCells = this.ALL_CELLS; // int numCells = allCells.size(); // for(int i = 0; i < numCells; i++) { // RTableCell cell = (RTableCell) allCells.get(i); // Rectangle bounds = cell.getBounds(); // int offsetX = bounds.x; // int offsetY = bounds.y; // g.translate(offsetX, offsetY); // try { // boolean newInSelection = cell.paintSelection(g, inSelection, startPoint, endPoint); // if(inSelection && !newInSelection) { // return false; // } // inSelection = newInSelection; // } finally { // g.translate(-offsetX, -offsetY); // } // } // return inSelection; // } // // public boolean extractSelectionText(StringBuffer buffer, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { // ArrayList allCells = this.ALL_CELLS; // int numCells = allCells.size(); // for(int i = 0; i < numCells; i++) { // RTableCell cell = (RTableCell) allCells.get(i); // boolean newInSelection = cell.extractSelectionText(buffer, inSelection, startPoint, endPoint); // if(inSelection && !newInSelection) { // return false; // } // inSelection = newInSelection; // } // return inSelection; // } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BoundableRenderable#getRenderablePoint(int, int) */ public RenderableSpot getLowestRenderableSpot(int x, int y) { ArrayList allCells = this.ALL_CELLS; int numCells = allCells.size(); for(int i = 0; i < numCells; i++) { RTableCell cell = (RTableCell) allCells.get(i); Rectangle bounds = cell.getBounds(); if(bounds.contains(x, y)) { RenderableSpot rp = cell.getLowestRenderableSpot(x - bounds.x, y - bounds.y); if(rp != null) { return rp; } } } return null; } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BoundableRenderable#onMouseClick(java.awt.event.MouseEvent, int, int) */ public boolean onMouseClick(MouseEvent event, int x, int y) { ArrayList allCells = this.ALL_CELLS; int numCells = allCells.size(); for(int i = 0; i < numCells; i++) { RTableCell cell = (RTableCell) allCells.get(i); Rectangle bounds = cell.getBounds(); if(bounds.contains(x, y)) { if(!cell.onMouseClick(event, x - bounds.x, y - bounds.y)) { return false; } break; } } return true; } public boolean onDoubleClick(MouseEvent event, int x, int y) { ArrayList allCells = this.ALL_CELLS; int numCells = allCells.size(); for(int i = 0; i < numCells; i++) { RTableCell cell = (RTableCell) allCells.get(i); Rectangle bounds = cell.getBounds(); if(bounds.contains(x, y)) { if(!cell.onDoubleClick(event, x - bounds.x, y - bounds.y)) { return false; } break; } } return true; } private BoundableRenderable armedRenderable; /* (non-Javadoc) * @see org.xamjwg.html.renderer.BoundableRenderable#onMouseDisarmed(java.awt.event.MouseEvent) */ public boolean onMouseDisarmed(MouseEvent event) { BoundableRenderable ar = this.armedRenderable; if(ar != null) { this.armedRenderable = null; return ar.onMouseDisarmed(event); } else { return true; } } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BoundableRenderable#onMousePressed(java.awt.event.MouseEvent, int, int) */ public boolean onMousePressed(MouseEvent event, int x, int y) { ArrayList allCells = this.ALL_CELLS; int numCells = allCells.size(); for(int i = 0; i < numCells; i++) { RTableCell cell = (RTableCell) allCells.get(i); Rectangle bounds = cell.getBounds(); if(bounds.contains(x, y)) { if(!cell.onMousePressed(event, x - bounds.x, y - bounds.y)) { this.armedRenderable = cell; return false; } break; } } return true; } /* (non-Javadoc) * @see org.xamjwg.html.renderer.BoundableRenderable#onMouseReleased(java.awt.event.MouseEvent, int, int) */ public boolean onMouseReleased(MouseEvent event, int x, int y) { ArrayList allCells = this.ALL_CELLS; int numCells = allCells.size(); boolean found = false; for(int i = 0; i < numCells; i++) { RTableCell cell = (RTableCell) allCells.get(i); Rectangle bounds = cell.getBounds(); if(bounds.contains(x, y)) { found = true; BoundableRenderable oldArmedRenderable = this.armedRenderable; if(oldArmedRenderable != null && cell != oldArmedRenderable) { oldArmedRenderable.onMouseDisarmed(event); this.armedRenderable = null; } if(!cell.onMouseReleased(event, x - bounds.x, y - bounds.y)) { return false; } break; } } if(!found) { BoundableRenderable oldArmedRenderable = this.armedRenderable; if(oldArmedRenderable != null) { oldArmedRenderable.onMouseDisarmed(event); this.armedRenderable = null; } } return true; } public Iterator getRenderables() { return this.ALL_CELLS.iterator(); } private static class RowsFilter implements NodeFilter { public final boolean accept(Node node) { return (node instanceof HTMLTableRowElement); } } private static class ColumnsFilter implements NodeFilter { public final boolean accept(Node node) { return (node instanceof HTMLTableCellElement); } } public static class SizeInfo { public HtmlLength htmlLength; public int actualSize; public int layoutSize; public int minSize; public int offset; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/UIControl.java0000644000175000017500000000347110726473512026431 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Nov 5, 2005 */ package org.lobobrowser.html.renderer; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; abstract interface UIControl { public void setRUIControl(RUIControl ruicontrol); /** * Called as the control is layed out, either * the first time HTML layout occurs or when * the DOM changes. This method should reset * its state assuming the element has changed, * and change its preferred size if appropriate. */ public void reset(int availWidth, int availHeight); public Dimension getPreferredSize(); public int getVAlign(); public void setBounds(int x, int y, int width, int height); public void invalidate(); public Color getBackgroundColor(); // public boolean paintSelection(Graphics g, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint); public void paint(Graphics g); public java.awt.Component getComponent(); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/UIControlWrapper.java0000644000175000017500000000267010641432550027763 0ustar twernertwernerpackage org.lobobrowser.html.renderer; import java.awt.*; import org.lobobrowser.html.*; class UIControlWrapper implements UIControl { private final Component component; private final HtmlObject htmlObject; public UIControlWrapper(HtmlObject ho) { this.htmlObject = ho; Component c; if(ho == null) { c = new BrokenComponent(); } else { c = ho.getComponent(); } this.component = c; } public void reset(int availWidth, int availHeight) { this.htmlObject.reset(availWidth, availHeight); } public Component getComponent() { return this.component; } public int getVAlign() { return RElement.VALIGN_BASELINE; } public Color getBackgroundColor() { return this.component.getBackground(); } public Dimension getPreferredSize() { return this.component.getPreferredSize(); } public void invalidate() { // Calls its AWT parent's invalidate, but I guess that's OK. this.component.invalidate(); } public boolean paintSelection(Graphics g, boolean inSelection, RenderableSpot startPoint, RenderableSpot endPoint) { // Does not paint selection return inSelection; } public void setBounds(int x, int y, int width, int height) { this.component.setBounds(x, y, width, height); } public void setRUIControl(RUIControl ruicontrol) { // Not doing anything with this. } public void paint(Graphics g) { this.component.paint(g); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/VirtualCell.java0000644000175000017500000000603510726473500026775 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Dec 3, 2005 */ package org.lobobrowser.html.renderer; import org.lobobrowser.html.style.HtmlLength; class VirtualCell { private final RTableCell actualCell; private final boolean isTopLeft; private int column; private int row; /** * @param cell */ public VirtualCell(RTableCell cell, boolean isTopLeft) { actualCell = cell; this.isTopLeft = isTopLeft; } public boolean isTopLeft() { return this.isTopLeft; } /** * @return Returns the column. */ public int getColumn() { return column; } /** * @param column The column to set. */ public void setColumn(int column) { this.column = column; } /** * @return Returns the row. */ public int getRow() { return row; } /** * @param row The row to set. */ public void setRow(int row) { this.row = row; } /** * @return Returns the actualCell. */ public RTableCell getActualCell() { return actualCell; } public HtmlLength getHeightLength() { //TODO: Does not consider cellpadding and border RTableCell cell = this.actualCell; String heightText = cell.getHeightText(); HtmlLength length; try { length = heightText == null ? null : new HtmlLength(heightText); } catch(Exception err) { length = null; } if(length != null) { length.divideBy(cell.getRowSpan()); } return length; } public HtmlLength getWidthLength() { RTableCell cell = this.actualCell; String widthText = cell.getWidthText(); HtmlLength length; try { length = widthText == null ? null : new HtmlLength(widthText); } catch(Exception err) { length = null; } if(length != null) { length.divideBy(cell.getColSpan()); } return length; } // public Dimension layoutMinWidth() { // // ActualCell cell = this.actualCell; // // Dimension ad = cell.layoutMinWidth(); // // int colspan = cell.getColSpan(); // // int rowspan = cell.getRowSpan(); // // if(colspan == 1 && rowspan == 1) { // // return ad; // // } // // else { // // return new Dimension(ad.width / colspan, ad.height / rowspan); // // } // // } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/ZIndexComparator.java0000644000175000017500000000131110641432550027764 0ustar twernertwernerpackage org.lobobrowser.html.renderer; import java.util.Comparator; class ZIndexComparator implements Comparator { //Note: It is assumed that objects don't change their //z-indexes or ordinals after entering the sorted set. //They may do so after the sorted set is no longer valid. public int compare(Object object1, Object object2) { PositionedRenderable element1 = (PositionedRenderable) object1; PositionedRenderable element2 = (PositionedRenderable) object2; int zIndex1 = element1.renderable.getZIndex(); int zIndex2 = element2.renderable.getZIndex(); int diff = zIndex1 - zIndex2; if(diff != 0) { return diff; } return element1.ordinal - element2.ordinal; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/renderer/package.html0000644000175000017500000000017010712365640026157 0ustar twernertwernerContains the HTML renderer infrastructure. libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/0000755000175000017500000000000011134435706023232 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/AbstractCSS2Properties.java0000644000175000017500000016154011127362274030360 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Nov 20, 2005 */ package org.lobobrowser.html.style; import java.util.*; import java.util.logging.*; import org.w3c.dom.DOMException; import org.w3c.dom.css.*; import org.lobobrowser.js.AbstractScriptableDelegate; import org.lobobrowser.util.Urls; import org.lobobrowser.util.gui.ColorFactory; public abstract class AbstractCSS2Properties extends AbstractScriptableDelegate implements CSS2Properties { private static final Logger logger = Logger.getLogger(AbstractCSS2Properties.class.getName()); public static final String FLOAT = "float"; public static final String AZIMUTH = "azimuth"; public static final String BACKGROUND = "background"; public static final String BACKGROUND_ATTACHMENT = "background-attachment"; public static final String BACKGROUND_COLOR = "background-color"; public static final String BACKGROUND_IMAGE = "background-image"; public static final String BACKGROUND_POSITION = "background-position"; public static final String BACKGROUND_REPEAT = "background-repeat"; public static final String BORDER = "border"; public static final String BORDER_BOTTOM = "border-bottom"; public static final String BORDER_BOTTOM_COLOR = "border-bottom-color"; public static final String BORDER_BOTTOM_STYLE = "border-bottom-style"; public static final String BORDER_BOTTOM_WIDTH = "border-bottom-width"; public static final String BORDER_COLLAPSE = "border-collapse"; public static final String BORDER_COLOR = "border-color"; public static final String BORDER_LEFT = "border-left"; public static final String BORDER_LEFT_COLOR = "border-left-color"; public static final String BORDER_LEFT_STYLE = "border-left-style"; public static final String BORDER_LEFT_WIDTH = "border-left-width"; public static final String BORDER_RIGHT = "border-right"; public static final String BORDER_RIGHT_COLOR = "border-right-color"; public static final String BORDER_RIGHT_STYLE = "border-right-style"; public static final String BORDER_RIGHT_WIDTH = "border-right-width"; public static final String BORDER_SPACING = "border-spacing"; public static final String BORDER_STYLE = "border-style"; public static final String BORDER_TOP = "border-top"; public static final String BORDER_TOP_COLOR = "border-top-color"; public static final String BORDER_TOP_STYLE = "border-top-style"; public static final String BORDER_TOP_WIDTH = "border-top-width"; public static final String BORDER_WIDTH = "border-width"; public static final String BOTTOM = "bottom"; public static final String CAPTION_SIDE = "caption-side"; public static final String CLEAR = "clear"; public static final String CLIP = "clip"; public static final String COLOR = "color"; public static final String CONTENT = "content"; public static final String COUNTER_INCREMENT = "counter-increment"; public static final String COUNTER_RESET = "counter-reset"; public static final String CSS_FLOAT = "css-float"; public static final String CUE = "cue"; public static final String CUE_AFTER = "cue-after"; public static final String CUE_BEFORE = "cue-before"; public static final String CURSOR = "cursor"; public static final String DIRECTION = "direction"; public static final String DISPLAY = "display"; public static final String ELEVATION = "elevation"; public static final String EMPTY_CELLS = "empty-cells"; public static final String FONT = "font"; public static final String FONT_FAMILY = "font-family"; public static final String FONT_SIZE = "font-size"; public static final String FONT_SIZE_ADJUST = "font-size-adjust"; public static final String FONT_STRETCH = "font-stretch"; public static final String FONT_STYLE = "font-style"; public static final String FONT_VARIANT = "font-variant"; public static final String FONT_WEIGHT = "font-weight"; public static final String HEIGHT = "height"; public static final String LEFT = "left"; public static final String LETTER_SPACING = "letter-spacing"; public static final String LINE_HEIGHT = "line-height"; public static final String LIST_STYLE = "list-style"; public static final String LIST_STYLE_IMAGE = "list-style-image"; public static final String LIST_STYLE_POSITION = "list-style-position"; public static final String LIST_STYLE_TYPE = "list-style-type"; public static final String MARGIN = "margin"; public static final String MARGIN_BOTTOM = "margin-bottom"; public static final String MARGIN_LEFT = "margin-left"; public static final String MARGIN_RIGHT = "margin-right"; public static final String MARGIN_TOP = "margin-top"; public static final String MARKER_OFFSET = "marker-offset"; public static final String MARKS = "marks"; public static final String MAX_HEIGHT = "max-height"; public static final String MAX_WIDTH = "max-width"; public static final String MIN_HEIGHT = "min-height"; public static final String MIN_WIDTH = "min-width"; public static final String ORPHANS = "orphans"; public static final String OUTLINE = "outline"; public static final String OUTLINE_COLOR = "outline-color"; public static final String OUTLINE_STYLE = "outline-style"; public static final String OUTLINE_WIDTH = "outline-width"; public static final String OVERFLOW = "overflow"; public static final String PADDING = "padding"; public static final String PADDING_BOTTOM = "padding-bottom"; public static final String PADDING_LEFT = "padding-left"; public static final String PADDING_RIGHT = "padding-right"; public static final String PADDING_TOP = "padding-top"; public static final String PAGE = "page"; public static final String PAGE_BREAK_AFTER = "page-break-after"; public static final String PAGE_BREAK_BEFORE = "page-break-before"; public static final String PAGE_BREAK_INSIDE = "page-break-inside"; public static final String PAUSE = "pause"; public static final String PAUSE_AFTER = "pause-after"; public static final String PAUSE_BEFORE = "pause-before"; public static final String PITCH = "pitch"; public static final String PITCH_RANGE = "pitch-range"; public static final String PLAY_DURING = "play-during"; public static final String POSITION = "position"; public static final String QUOTES = "quotes"; public static final String RICHNESS = "richness"; public static final String RIGHT = "right"; public static final String SIZE = "size"; public static final String SPEAK = "speak"; public static final String SPEAK_HEADER = "speak-header"; public static final String SPEAK_NUMERAL = "speak-numeral"; public static final String SPEAK_PUNCTUATION = "speak-puctuation"; public static final String SPEECH_RATE = "speech-rate"; public static final String STRESS = "stress"; public static final String TABLE_LAYOUT = "table-layout"; public static final String TEXT_ALIGN = "text-align"; public static final String TEXT_DECORATION = "text-decoration"; public static final String TEXT_INDENT = "text-indent"; public static final String TEXT_SHADOW = "text-shadow"; public static final String TEXT_TRANSFORM = "text-transform"; public static final String TOP = "top"; public static final String UNICODE_BIDI = "unicode-bidi"; public static final String VERTICAL_ALIGN = "vertical-align"; public static final String VISIBILITY = "visibility"; public static final String VOICE_FAMILY = "voice-family"; public static final String VOLUME = "volume"; public static final String WHITE_SPACE = "white-space"; public static final String WIDOWS = "widows"; public static final String WIDTH = "width"; public static final String WORD_SPACING = "word_spacing"; public static final String Z_INDEX = "z-index"; private static final Map SUB_SETTERS = new HashMap(20); private final CSS2PropertiesContext context; private AbstractCSS2Properties localStyleProperties; private Collection styleDeclarations; private Map valueMap = null; static { Map subSetters = SUB_SETTERS; subSetters.put(MARGIN, new FourCornersSetter(MARGIN, "margin-", "")); subSetters.put(PADDING, new FourCornersSetter(PADDING, "padding-", "")); subSetters.put(BORDER, new BorderSetter1()); subSetters.put(BORDER_TOP, new BorderSetter2(BORDER_TOP)); subSetters.put(BORDER_LEFT, new BorderSetter2(BORDER_LEFT)); subSetters.put(BORDER_BOTTOM, new BorderSetter2(BORDER_BOTTOM)); subSetters.put(BORDER_RIGHT, new BorderSetter2(BORDER_RIGHT)); subSetters.put(BORDER_COLOR, new FourCornersSetter(BORDER_COLOR, "border-", "-color")); subSetters.put(BORDER_STYLE, new FourCornersSetter(BORDER_STYLE, "border-", "-style")); subSetters.put(BORDER_WIDTH, new FourCornersSetter(BORDER_WIDTH, "border-", "-width")); subSetters.put(BACKGROUND, new BackgroundSetter()); subSetters.put(BACKGROUND_IMAGE, new BackgroundImageSetter()); subSetters.put(FONT, new FontSetter()); } public AbstractCSS2Properties(CSS2PropertiesContext context) { this.context = context; } public void addStyleDeclaration(CSSStyleDeclaration styleDeclaration) { synchronized(this) { Collection sd = this.styleDeclarations; if(sd == null) { sd = new LinkedList(); this.styleDeclarations = sd; } sd.add(styleDeclaration); int length = styleDeclaration.getLength(); for(int i = 0; i < length; i++) { String propertyName = styleDeclaration.item(i); String propertyValue = styleDeclaration.getPropertyValue(propertyName); String priority = styleDeclaration.getPropertyPriority(propertyName); boolean important = priority != null && priority.length() != 0 && "important".equals(priority); this.setPropertyValueProcessed(propertyName.toLowerCase(), propertyValue, styleDeclaration, important); } } } public void setLocalStyleProperties(AbstractCSS2Properties properties) { if(properties == this) { throw new IllegalStateException("setting same"); } synchronized(this) { this.localStyleProperties = properties; } } public AbstractCSS2Properties getLocalStyleProperties() { synchronized(this) { return this.localStyleProperties; } } // private final String getPropertyValue(String name) { // String lowerCase = name.toLowerCase(); // return this.getPropertyValueLC(lowerCase); // } public final String getPropertyValue(String name) { return this.getPropertyValueLC(name.toLowerCase()); } private final String getPropertyValueLC(String lowerCaseName) { Map vm = this.valueMap; synchronized(this) { // Local properties have precedence AbstractCSS2Properties localProps = this.localStyleProperties; if(localProps != null) { String value = localProps.getPropertyValueLC(lowerCaseName); if(value != null) { return value; } } if(vm != null) { Property p = (Property) vm.get(lowerCaseName); return p == null ? null : p.value; } } return null; } /** * Method called by property setters to set property values. * @param lowerCaseName The name of the property in lowercase. * @param value The property value. */ protected void setPropertyValueLC(String lowerCaseName, String value) { Map vm = this.valueMap; synchronized(this) { if(vm == null) { vm = new HashMap(1); this.valueMap = vm; } vm.put(lowerCaseName, new Property(value, true)); } } /** * Alternate method called to set property values from * CSS declarations. *

* This method checks importance of the value. * @param lowerCaseName The name of the property in lowercase. * @param value The property value. */ protected final void setPropertyValueLCAlt(String lowerCaseName, String value, boolean important) { Map vm = this.valueMap; synchronized(this) { if(vm == null) { vm = new HashMap(1); this.valueMap = vm; } else { if(!important) { Property oldProperty = (Property) vm.get(lowerCaseName); if(oldProperty != null && oldProperty.important) { // Ignore setting return; } } } vm.put(lowerCaseName, new Property(value, important)); } } protected final void setPropertyValueProcessed(String lowerCaseName, String value, CSSStyleDeclaration declaration, boolean important) { SubPropertySetter setter = (SubPropertySetter) SUB_SETTERS.get(lowerCaseName); if(setter != null) { setter.changeValue(this, value, declaration, important); } else { this.setPropertyValueLCAlt(lowerCaseName, value, important); } } // /** // * Gets the style declaration where a property value might have come from. // * This method can be used to obtain the URL of the style document, in // * order to resolve relative URLs. // * @param lowerCaseName The name of the property in lowercase. // */ // public final CSSStyleDeclaration getStyleDeclaration(String lowerCaseName) { // // Converts blanks to nulls. // synchronized(this) { // Collection sds = this.styleDeclarations; // if(sds == null) { // return null; // } // Iterator i = sds.iterator(); // while(i.hasNext()) { // Object styleObject = i.next(); // if(styleObject instanceof CSSStyleDeclaration) { // CSSStyleDeclaration styleDeclaration = (CSSStyleDeclaration) styleObject; // String pv = styleDeclaration.getPropertyValue(lowerCaseName); // if(pv != null && pv.length() != 0) { // return styleDeclaration; // } // } // } // } // return null; // } //---------- NonStandard properties private String overlayColor; public String getOverlayColor() { return this.overlayColor; } public void setOverlayColor(String value) { this.overlayColor = value; this.context.informLookInvalid(); } public String getFloat() { return this.getPropertyValueLC(FLOAT); } public void setFloat(String value) { this.setPropertyValueLC(FLOAT, value); } //---------- Implemented properties public String getAzimuth() { return this.getPropertyValueLC(AZIMUTH); } public String getBackground() { return this.getPropertyValueLC(BACKGROUND); } public String getBackgroundAttachment() { return this.getPropertyValueLC(BACKGROUND_ATTACHMENT); } public String getBackgroundColor() { return this.getPropertyValueLC(BACKGROUND_COLOR); } public String getBackgroundImage() { return this.getPropertyValueLC(BACKGROUND_IMAGE); } public String getBackgroundPosition() { return this.getPropertyValueLC(BACKGROUND_POSITION); } public String getBackgroundRepeat() { return this.getPropertyValueLC(BACKGROUND_REPEAT); } public String getBorder() { return this.getPropertyValueLC(BORDER); } public String getBorderBottom() { return this.getPropertyValueLC(BORDER_BOTTOM); } public String getBorderBottomColor() { return this.getPropertyValueLC(BORDER_BOTTOM_COLOR); } public String getBorderBottomStyle() { return this.getPropertyValueLC(BORDER_BOTTOM_STYLE); } public String getBorderBottomWidth() { return this.getPropertyValueLC(BORDER_BOTTOM_WIDTH); } public String getBorderCollapse() { return this.getPropertyValueLC(BORDER_COLLAPSE); } public String getBorderColor() { return this.getPropertyValueLC(BORDER_COLOR); } public String getBorderLeft() { return this.getPropertyValueLC(BORDER_LEFT); } public String getBorderLeftColor() { return this.getPropertyValueLC(BORDER_LEFT_COLOR); } public String getBorderLeftStyle() { return this.getPropertyValueLC(BORDER_LEFT_STYLE); } public String getBorderLeftWidth() { return this.getPropertyValueLC(BORDER_LEFT_WIDTH); } public String getBorderRight() { return this.getPropertyValueLC(BORDER_RIGHT); } public String getBorderRightColor() { return this.getPropertyValueLC(BORDER_RIGHT_COLOR); } public String getBorderRightStyle() { return this.getPropertyValueLC(BORDER_RIGHT_STYLE); } public String getBorderRightWidth() { return this.getPropertyValueLC(BORDER_RIGHT_WIDTH); } public String getBorderSpacing() { return this.getPropertyValueLC(BORDER_SPACING); } public String getBorderStyle() { return this.getPropertyValueLC(BORDER_STYLE); } public String getBorderTop() { return this.getPropertyValueLC(BORDER_TOP); } public String getBorderTopColor() { return this.getPropertyValueLC(BORDER_TOP_COLOR); } public String getBorderTopStyle() { return this.getPropertyValueLC(BORDER_TOP_STYLE); } public String getBorderTopWidth() { return this.getPropertyValueLC(BORDER_TOP_WIDTH); } public String getBorderWidth() { return this.getPropertyValueLC(BORDER_WIDTH); } public String getBottom() { return this.getPropertyValueLC(BOTTOM); } public String getCaptionSide() { return this.getPropertyValueLC(CAPTION_SIDE); } public String getClear() { return this.getPropertyValueLC(CLEAR); } public String getClip() { return this.getPropertyValueLC(CLIP); } public String getColor() { return this.getPropertyValueLC(COLOR); } public String getContent() { return this.getPropertyValueLC(CONTENT); } public String getCounterIncrement() { return this.getPropertyValueLC(COUNTER_INCREMENT); } public String getCounterReset() { return this.getPropertyValueLC(COUNTER_RESET); } public String getCssFloat() { return this.getPropertyValueLC(CSS_FLOAT); } public String getCue() { return this.getPropertyValueLC(CUE); } public String getCueAfter() { return this.getPropertyValueLC(CUE_AFTER); } public String getCueBefore() { return this.getPropertyValueLC(CUE_BEFORE); } public String getCursor() { return this.getPropertyValueLC(CURSOR); } public String getDirection() { return this.getPropertyValueLC(DIRECTION); } public String getDisplay() { return this.getPropertyValueLC(DISPLAY); } public String getElevation() { return this.getPropertyValueLC(ELEVATION); } public String getEmptyCells() { return this.getPropertyValueLC(EMPTY_CELLS); } public String getFont() { return this.getPropertyValueLC(FONT); } public String getFontFamily() { return this.getPropertyValueLC(FONT_FAMILY); } public String getFontSize() { return this.getPropertyValueLC(FONT_SIZE); } public String getFontSizeAdjust() { return this.getPropertyValueLC(FONT_SIZE_ADJUST); } public String getFontStretch() { return this.getPropertyValueLC(FONT_STRETCH); } public String getFontStyle() { return this.getPropertyValueLC(FONT_STYLE); } public String getFontVariant() { return this.getPropertyValueLC(FONT_VARIANT); } public String getFontWeight() { return this.getPropertyValueLC(FONT_WEIGHT); } public String getHeight() { return this.getPropertyValueLC(HEIGHT); } public String getLeft() { return this.getPropertyValueLC(LEFT); } public String getLetterSpacing() { return this.getPropertyValueLC(LETTER_SPACING); } public String getLineHeight() { return this.getPropertyValueLC(LINE_HEIGHT); } public String getListStyle() { return this.getPropertyValueLC(LIST_STYLE); } public String getListStyleImage() { return this.getPropertyValueLC(LIST_STYLE_IMAGE); } public String getListStylePosition() { return this.getPropertyValueLC(LIST_STYLE_POSITION); } public String getListStyleType() { return this.getPropertyValueLC(LIST_STYLE_TYPE); } public String getMargin() { return this.getPropertyValueLC(MARGIN); } public String getMarginBottom() { return this.getPropertyValueLC(MARGIN_BOTTOM); } public String getMarginLeft() { return this.getPropertyValueLC(MARGIN_LEFT); } public String getMarginRight() { return this.getPropertyValueLC(MARGIN_RIGHT); } public String getMarginTop() { return this.getPropertyValueLC(MARGIN_TOP); } public String getMarkerOffset() { return this.getPropertyValueLC(MARKER_OFFSET); } public String getMarks() { return this.getPropertyValueLC(MARKS); } public String getMaxHeight() { return this.getPropertyValueLC(MAX_HEIGHT); } public String getMaxWidth() { return this.getPropertyValueLC(MAX_WIDTH); } public String getMinHeight() { return this.getPropertyValueLC(MIN_HEIGHT); } public String getMinWidth() { return this.getPropertyValueLC(MIN_WIDTH); } public String getOrphans() { return this.getPropertyValueLC(ORPHANS); } public String getOutline() { return this.getPropertyValueLC(OUTLINE); } public String getOutlineColor() { return this.getPropertyValueLC(OUTLINE_COLOR); } public String getOutlineStyle() { return this.getPropertyValueLC(OUTLINE_STYLE); } public String getOutlineWidth() { return this.getPropertyValueLC(OUTLINE_WIDTH); } public String getOverflow() { return this.getPropertyValueLC(OVERFLOW); } public String getPadding() { return this.getPropertyValueLC(PADDING); } public String getPaddingBottom() { return this.getPropertyValueLC(PADDING_BOTTOM); } public String getPaddingLeft() { return this.getPropertyValueLC(PADDING_LEFT); } public String getPaddingRight() { return this.getPropertyValueLC(PADDING_RIGHT); } public String getPaddingTop() { return this.getPropertyValueLC(PADDING_TOP); } public String getPage() { return this.getPropertyValueLC(PAGE); } public String getPageBreakAfter() { return this.getPropertyValueLC(PAGE_BREAK_AFTER); } public String getPageBreakBefore() { return this.getPropertyValueLC(PAGE_BREAK_BEFORE); } public String getPageBreakInside() { return this.getPropertyValueLC(PAGE_BREAK_INSIDE); } public String getPause() { return this.getPropertyValueLC(PAUSE); } public String getPauseAfter() { return this.getPropertyValueLC(PAUSE_AFTER); } public String getPauseBefore() { return this.getPropertyValueLC(PAUSE_BEFORE); } public String getPitch() { return this.getPropertyValueLC(PITCH); } public String getPitchRange() { return this.getPropertyValueLC(PITCH_RANGE); } public String getPlayDuring() { return this.getPropertyValueLC(PLAY_DURING); } public String getPosition() { return this.getPropertyValueLC(POSITION); } public String getQuotes() { return this.getPropertyValueLC(QUOTES); } public String getRichness() { return this.getPropertyValueLC(RICHNESS); } public String getRight() { return this.getPropertyValueLC(RIGHT); } public String getSize() { return this.getPropertyValueLC(SIZE); } public String getSpeak() { return this.getPropertyValueLC(SPEAK); } public String getSpeakHeader() { return this.getPropertyValueLC(SPEAK_HEADER); } public String getSpeakNumeral() { return this.getPropertyValueLC(SPEAK_NUMERAL); } public String getSpeakPunctuation() { return this.getPropertyValueLC(SPEAK_PUNCTUATION); } public String getSpeechRate() { return this.getPropertyValueLC(SPEECH_RATE); } public String getStress() { return this.getPropertyValueLC(STRESS); } public String getTableLayout() { return this.getPropertyValueLC(TABLE_LAYOUT); } public String getTextAlign() { return this.getPropertyValueLC(TEXT_ALIGN); } public String getTextDecoration() { return this.getPropertyValueLC(TEXT_DECORATION); } public String getTextIndent() { return this.getPropertyValueLC(TEXT_INDENT); } public String getTextShadow() { return this.getPropertyValueLC(TEXT_SHADOW); } public String getTextTransform() { return this.getPropertyValueLC(TEXT_TRANSFORM); } public String getTop() { return this.getPropertyValueLC(TOP); } public String getUnicodeBidi() { return this.getPropertyValueLC(UNICODE_BIDI); } public String getVerticalAlign() { return this.getPropertyValueLC(VERTICAL_ALIGN); } public String getVisibility() { return this.getPropertyValueLC(VISIBILITY); } public String getVoiceFamily() { return this.getPropertyValueLC(VOICE_FAMILY); } public String getVolume() { return this.getPropertyValueLC(VOLUME); } public String getWhiteSpace() { return this.getPropertyValueLC(WHITE_SPACE); } public String getWidows() { return this.getPropertyValueLC(WIDOWS); } public String getWidth() { return this.getPropertyValueLC(WIDTH); } public String getWordSpacing() { return this.getPropertyValueLC(WORD_SPACING); } public String getZIndex() { return this.getPropertyValueLC(Z_INDEX); } public void setAzimuth(String azimuth) throws DOMException { this.setPropertyValueLC(AZIMUTH, azimuth); } public void setBackground(String background) throws DOMException { this.checkSetProperty(); new BackgroundSetter().changeValue(this, background, null); this.context.informLookInvalid(); } public void setBackgroundAttachment(String backgroundAttachment) throws DOMException { this.setPropertyValueLC(BACKGROUND_ATTACHMENT, backgroundAttachment); this.context.informLookInvalid(); } public void setBackgroundColor(String backgroundColor) throws DOMException { this.setPropertyValueLC(BACKGROUND_COLOR, backgroundColor); this.context.informLookInvalid(); } public void setBackgroundImage(String backgroundImage) throws DOMException { this.checkSetProperty(); new BackgroundImageSetter().changeValue(this, backgroundImage, null); this.context.informLookInvalid(); } public void setBackgroundPosition(String backgroundPosition) throws DOMException { this.setPropertyValueLC(BACKGROUND_POSITION, backgroundPosition); this.context.informLookInvalid(); } public void setBackgroundRepeat(String backgroundRepeat) throws DOMException { this.setPropertyValueLC(BACKGROUND_REPEAT, backgroundRepeat); this.context.informLookInvalid(); } public void setBorder(String border) throws DOMException { this.checkSetProperty(); new BorderSetter1().changeValue(this, border, null); this.context.informInvalid(); } public void setBorderBottom(String borderBottom) throws DOMException { this.checkSetProperty(); new BorderSetter2(BORDER_BOTTOM).changeValue(this, borderBottom, null); this.context.informInvalid(); } public void setBorderBottomColor(String borderBottomColor) throws DOMException { this.setPropertyValueLC(BORDER_BOTTOM_COLOR, borderBottomColor); this.context.informLookInvalid(); } public void setBorderBottomStyle(String borderBottomStyle) throws DOMException { this.setPropertyValueLC(BORDER_BOTTOM_STYLE, borderBottomStyle); this.context.informLookInvalid(); } public void setBorderBottomWidth(String borderBottomWidth) throws DOMException { this.setPropertyValueLC(BORDER_BOTTOM_WIDTH, borderBottomWidth); this.context.informInvalid(); } public void setBorderCollapse(String borderCollapse) throws DOMException { this.setPropertyValueLC(BORDER_COLLAPSE, borderCollapse); this.context.informInvalid(); } public void setBorderColor(String borderColor) throws DOMException { this.checkSetProperty(); new FourCornersSetter(BORDER_COLOR, "border-", "-color").changeValue(this, borderColor, null); this.context.informLookInvalid(); } public void setBorderLeft(String borderLeft) throws DOMException { this.checkSetProperty(); new BorderSetter2(BORDER_LEFT).changeValue(this, borderLeft, null); this.context.informInvalid(); } public void setBorderLeftColor(String borderLeftColor) throws DOMException { this.setPropertyValueLC(BORDER_LEFT_COLOR, borderLeftColor); this.context.informLookInvalid(); } public void setBorderLeftStyle(String borderLeftStyle) throws DOMException { this.setPropertyValueLC(BORDER_LEFT_STYLE, borderLeftStyle); this.context.informLookInvalid(); } public void setBorderLeftWidth(String borderLeftWidth) throws DOMException { this.setPropertyValueLC(BORDER_LEFT_WIDTH, borderLeftWidth); this.context.informInvalid(); } public void setBorderRight(String borderRight) throws DOMException { this.checkSetProperty(); new BorderSetter2(BORDER_RIGHT).changeValue(this, borderRight, null); this.context.informInvalid(); } public void setBorderRightColor(String borderRightColor) throws DOMException { this.setPropertyValueLC(BORDER_RIGHT_COLOR, borderRightColor); this.context.informLookInvalid(); } public void setBorderRightStyle(String borderRightStyle) throws DOMException { this.setPropertyValueLC(BORDER_RIGHT_STYLE, borderRightStyle); this.context.informLookInvalid(); } public void setBorderRightWidth(String borderRightWidth) throws DOMException { this.setPropertyValueLC(BORDER_RIGHT_WIDTH, borderRightWidth); this.context.informInvalid(); } public void setBorderSpacing(String borderSpacing) throws DOMException { this.setPropertyValueLC(BORDER_SPACING, borderSpacing); this.context.informInvalid(); } public void setBorderStyle(String borderStyle) throws DOMException { this.checkSetProperty(); new FourCornersSetter(BORDER_STYLE, "border-", "-style").changeValue(this, borderStyle, null); this.context.informLookInvalid(); } public void setBorderTop(String borderTop) throws DOMException { this.checkSetProperty(); new BorderSetter2(BORDER_TOP).changeValue(this, borderTop, null); this.context.informInvalid(); } public void setBorderTopColor(String borderTopColor) throws DOMException { this.setPropertyValueLC(BORDER_TOP_COLOR, borderTopColor); this.context.informLookInvalid(); } public void setBorderTopStyle(String borderTopStyle) throws DOMException { this.setPropertyValueLC(BORDER_TOP_STYLE, borderTopStyle); this.context.informLookInvalid(); } public void setBorderTopWidth(String borderTopWidth) throws DOMException { this.setPropertyValueLC(BORDER_TOP_WIDTH, borderTopWidth); this.context.informInvalid(); } public void setBorderWidth(String borderWidth) throws DOMException { this.checkSetProperty(); new FourCornersSetter(BORDER_WIDTH, "border-", "-width").changeValue(this, borderWidth, null); this.context.informInvalid(); } public void setBottom(String bottom) throws DOMException { this.setPropertyValueLC(BOTTOM, bottom); this.context.informPositionInvalid(); } public void setCaptionSide(String captionSide) throws DOMException { this.setPropertyValueLC(CAPTION_SIDE, captionSide); } public void setClear(String clear) throws DOMException { this.setPropertyValueLC(CLEAR, clear); this.context.informInvalid(); } public void setClip(String clip) throws DOMException { this.setPropertyValueLC(CLIP, clip); } public void setColor(String color) throws DOMException { this.setPropertyValueLC(COLOR, color); this.context.informLookInvalid(); } public void setContent(String content) throws DOMException { this.setPropertyValueLC(CONTENT, content); this.context.informInvalid(); } public void setCounterIncrement(String counterIncrement) throws DOMException { this.setPropertyValueLC(COUNTER_INCREMENT, counterIncrement); this.context.informLookInvalid(); } public void setCounterReset(String counterReset) throws DOMException { this.setPropertyValueLC(COUNTER_RESET, counterReset); this.context.informLookInvalid(); } public void setCssFloat(String cssFloat) throws DOMException { this.setPropertyValueLC(CSS_FLOAT, cssFloat); this.context.informInvalid(); } public void setCue(String cue) throws DOMException { this.setPropertyValueLC(CUE, cue); } public void setCueAfter(String cueAfter) throws DOMException { this.setPropertyValueLC(CUE_AFTER, cueAfter); } public void setCueBefore(String cueBefore) throws DOMException { this.setPropertyValueLC(CUE_BEFORE, cueBefore); } public void setCursor(String cursor) throws DOMException { this.setPropertyValueLC(CURSOR, cursor); this.context.informLookInvalid(); } public void setDirection(String direction) throws DOMException { this.setPropertyValueLC(DIRECTION, direction); this.context.informInvalid(); } public void setDisplay(String display) throws DOMException { this.setPropertyValueLC(DISPLAY, display); this.context.informInvalid(); } public void setElevation(String elevation) throws DOMException { this.setPropertyValueLC(ELEVATION, elevation); this.context.informInvalid(); } public void setEmptyCells(String emptyCells) throws DOMException { this.setPropertyValueLC(EMPTY_CELLS, emptyCells); } public void setFont(String font) throws DOMException { this.checkSetProperty(); new FontSetter().changeValue(this, font, null); this.context.informInvalid(); } public void setFontFamily(String fontFamily) throws DOMException { this.setPropertyValueLC(FONT_FAMILY, fontFamily); this.context.informInvalid(); } public void setFontSize(String fontSize) throws DOMException { this.setPropertyValueLC(FONT_SIZE, fontSize); this.context.informInvalid(); } public void setFontSizeAdjust(String fontSizeAdjust) throws DOMException { this.setPropertyValueLC(FONT_SIZE_ADJUST, fontSizeAdjust); this.context.informInvalid(); } public void setFontStretch(String fontStretch) throws DOMException { this.setPropertyValueLC(FONT_STRETCH, fontStretch); this.context.informInvalid(); } public void setFontStyle(String fontStyle) throws DOMException { this.setPropertyValueLC(FONT_STYLE, fontStyle); this.context.informInvalid(); } public void setFontVariant(String fontVariant) throws DOMException { this.setPropertyValueLC(FONT_VARIANT, fontVariant); this.context.informInvalid(); } public void setFontWeight(String fontWeight) throws DOMException { this.setPropertyValueLC(FONT_WEIGHT, fontWeight); this.context.informInvalid(); } public void setHeight(String height) throws DOMException { this.setPropertyValueLC(HEIGHT, height); this.context.informSizeInvalid(); } public void setLeft(String left) throws DOMException { this.setPropertyValueLC(LEFT, left); this.context.informPositionInvalid(); } public void setLetterSpacing(String letterSpacing) throws DOMException { this.setPropertyValueLC(LETTER_SPACING, letterSpacing); this.context.informInvalid(); } public void setLineHeight(String lineHeight) throws DOMException { this.setPropertyValueLC(LINE_HEIGHT, lineHeight); this.context.informInvalid(); } public void setListStyle(String listStyle) throws DOMException { this.setPropertyValueLC(LIST_STYLE, listStyle); this.context.informInvalid(); } public void setListStyleImage(String listStyleImage) throws DOMException { this.setPropertyValueLC(LIST_STYLE_IMAGE, listStyleImage); this.context.informLookInvalid(); } public void setListStylePosition(String listStylePosition) throws DOMException { this.setPropertyValueLC(LIST_STYLE_POSITION, listStylePosition); this.context.informInvalid(); } public void setListStyleType(String listStyleType) throws DOMException { this.setPropertyValueLC(LIST_STYLE_TYPE, listStyleType); this.context.informLookInvalid(); } public void setMargin(String margin) throws DOMException { this.checkSetProperty(); new AbstractCSS2Properties.FourCornersSetter(MARGIN, "margin-", "").changeValue(this, margin, null); this.context.informInvalid(); } public void setMarginBottom(String marginBottom) throws DOMException { this.setPropertyValueLC(MARGIN_BOTTOM, marginBottom); this.context.informInvalid(); } public void setMarginLeft(String marginLeft) throws DOMException { this.setPropertyValueLC(MARGIN_LEFT, marginLeft); this.context.informInvalid(); } public void setMarginRight(String marginRight) throws DOMException { this.setPropertyValueLC(MARGIN_RIGHT, marginRight); this.context.informInvalid(); } public void setMarginTop(String marginTop) throws DOMException { this.setPropertyValueLC(MARGIN_TOP, marginTop); this.context.informInvalid(); } public void setMarkerOffset(String markerOffset) throws DOMException { this.setPropertyValueLC(MARKER_OFFSET, markerOffset); } public void setMarks(String marks) throws DOMException { this.setPropertyValueLC(MARKS, marks); } public void setMaxHeight(String maxHeight) throws DOMException { this.setPropertyValueLC(MAX_HEIGHT, maxHeight); this.context.informSizeInvalid(); } public void setMaxWidth(String maxWidth) throws DOMException { this.setPropertyValueLC(MAX_WIDTH, maxWidth); this.context.informSizeInvalid(); } public void setMinHeight(String minHeight) throws DOMException { this.setPropertyValueLC(MIN_HEIGHT, minHeight); this.context.informSizeInvalid(); } public void setMinWidth(String minWidth) throws DOMException { this.setPropertyValueLC(MIN_WIDTH, minWidth); this.context.informSizeInvalid(); } public void setOrphans(String orphans) throws DOMException { this.setPropertyValueLC(ORPHANS, orphans); } public void setOutline(String outline) throws DOMException { this.setPropertyValueLC(OUTLINE, outline); this.context.informInvalid(); } public void setOutlineColor(String outlineColor) throws DOMException { this.setPropertyValueLC(OUTLINE_COLOR, outlineColor); this.context.informLookInvalid(); } public void setOutlineStyle(String outlineStyle) throws DOMException { this.setPropertyValueLC(OUTLINE_STYLE, outlineStyle); this.context.informLookInvalid(); } public void setOutlineWidth(String outlineWidth) throws DOMException { this.setPropertyValueLC(OUTLINE_WIDTH, outlineWidth); this.context.informInvalid(); } public void setOverflow(String overflow) throws DOMException { this.setPropertyValueLC(OVERFLOW, overflow); this.context.informInvalid(); } public void setPadding(String padding) throws DOMException { this.checkSetProperty(); new FourCornersSetter(PADDING, "padding-", "").changeValue(this, padding, null); this.context.informInvalid(); } public void setPaddingBottom(String paddingBottom) throws DOMException { this.setPropertyValueLC(PADDING_BOTTOM, paddingBottom); this.context.informInvalid(); } public void setPaddingLeft(String paddingLeft) throws DOMException { this.setPropertyValueLC(PADDING_LEFT, paddingLeft); this.context.informInvalid(); } public void setPaddingRight(String paddingRight) throws DOMException { this.setPropertyValueLC(PADDING_RIGHT, paddingRight); this.context.informInvalid(); } public void setPaddingTop(String paddingTop) throws DOMException { this.setPropertyValueLC(PADDING_TOP, paddingTop); this.context.informInvalid(); } public void setPage(String page) throws DOMException { this.setPropertyValueLC(PAGE, page); } public void setPageBreakAfter(String pageBreakAfter) throws DOMException { this.setPropertyValueLC(PAGE_BREAK_AFTER, pageBreakAfter); this.context.informInvalid(); } public void setPageBreakBefore(String pageBreakBefore) throws DOMException { this.setPropertyValueLC(PAGE_BREAK_BEFORE, pageBreakBefore); this.context.informInvalid(); } public void setPageBreakInside(String pageBreakInside) throws DOMException { this.setPropertyValueLC(PAGE_BREAK_INSIDE, pageBreakInside); this.context.informInvalid(); } public void setPause(String pause) throws DOMException { this.setPropertyValueLC(PAUSE, pause); } public void setPauseAfter(String pauseAfter) throws DOMException { this.setPropertyValueLC(PAUSE_AFTER, pauseAfter); } public void setPauseBefore(String pauseBefore) throws DOMException { this.setPropertyValueLC(PAUSE_BEFORE, pauseBefore); } public void setPitch(String pitch) throws DOMException { this.setPropertyValueLC(PITCH, pitch); } public void setPitchRange(String pitchRange) throws DOMException { this.setPropertyValueLC(PITCH_RANGE, pitchRange); } public void setPlayDuring(String playDuring) throws DOMException { this.setPropertyValueLC(PLAY_DURING, playDuring); } public void setPosition(String position) throws DOMException { this.setPropertyValueLC(POSITION, position); this.context.informPositionInvalid(); } public void setQuotes(String quotes) throws DOMException { this.setPropertyValueLC(QUOTES, quotes); } public void setRichness(String richness) throws DOMException { this.setPropertyValueLC(RICHNESS, richness); } public void setRight(String right) throws DOMException { this.setPropertyValueLC(RIGHT, right); this.context.informPositionInvalid(); } public void setSize(String size) throws DOMException { this.setPropertyValueLC(SIZE, size); this.context.informInvalid(); } public void setSpeak(String speak) throws DOMException { this.setPropertyValueLC(SPEAK, speak); } public void setSpeakHeader(String speakHeader) throws DOMException { this.setPropertyValueLC(SPEAK_HEADER, speakHeader); } public void setSpeakNumeral(String speakNumeral) throws DOMException { this.setPropertyValueLC(SPEAK_NUMERAL, speakNumeral); } public void setSpeakPunctuation(String speakPunctuation) throws DOMException { this.setPropertyValueLC(SPEAK_PUNCTUATION, speakPunctuation); } public void setSpeechRate(String speechRate) throws DOMException { this.setPropertyValueLC(SPEECH_RATE, speechRate); } public void setStress(String stress) throws DOMException { this.setPropertyValueLC(STRESS, stress); } public void setTableLayout(String tableLayout) throws DOMException { this.setPropertyValueLC(TABLE_LAYOUT, tableLayout); this.context.informInvalid(); } public void setTextAlign(String textAlign) throws DOMException { this.setPropertyValueLC(TEXT_ALIGN, textAlign); this.context.informLayoutInvalid(); } public void setTextDecoration(String textDecoration) throws DOMException { this.setPropertyValueLC(TEXT_DECORATION, textDecoration); this.context.informLookInvalid(); } public void setTextIndent(String textIndent) throws DOMException { this.setPropertyValueLC(TEXT_INDENT, textIndent); this.context.informLayoutInvalid(); } public void setTextShadow(String textShadow) throws DOMException { this.setPropertyValueLC(TEXT_SHADOW, textShadow); this.context.informLookInvalid(); } public void setTextTransform(String textTransform) throws DOMException { this.setPropertyValueLC(TEXT_TRANSFORM, textTransform); this.context.informInvalid(); } public void setTop(String top) throws DOMException { this.setPropertyValueLC(TOP, top); this.context.informPositionInvalid(); } public void setUnicodeBidi(String unicodeBidi) throws DOMException { this.setPropertyValueLC(UNICODE_BIDI, unicodeBidi); this.context.informInvalid(); } public void setVerticalAlign(String verticalAlign) throws DOMException { this.setPropertyValueLC(VERTICAL_ALIGN, verticalAlign); this.context.informInvalid(); } public void setVisibility(String visibility) throws DOMException { this.setPropertyValueLC(VISIBILITY, visibility); this.context.informLookInvalid(); } public void setVoiceFamily(String voiceFamily) throws DOMException { this.setPropertyValueLC(VOICE_FAMILY, voiceFamily); } public void setVolume(String volume) throws DOMException { this.setPropertyValueLC(VOLUME, volume); } public void setWhiteSpace(String whiteSpace) throws DOMException { this.setPropertyValueLC(WHITE_SPACE, whiteSpace); this.context.informInvalid(); } public void setWidows(String widows) throws DOMException { this.setPropertyValueLC(WIDOWS, widows); } public void setWidth(String width) throws DOMException { this.setPropertyValueLC(WIDTH, width); this.context.informSizeInvalid(); } public void setWordSpacing(String wordSpacing) throws DOMException { this.setPropertyValueLC(WORD_SPACING, wordSpacing); this.context.informInvalid(); } public void setZIndex(String zIndex) throws DOMException { this.setPropertyValueLC(Z_INDEX, zIndex); this.context.informPositionInvalid(); } /** * Does nothing but may be overridden. This method * is called by some property setters. */ protected void checkSetProperty() { } public String toString() { int size; synchronized(this) { Map map = this.valueMap; size = map == null ? 0 : map.size(); } return this.getClass().getSimpleName() + "[size=" + size + "]"; } private static interface SubPropertySetter { public void changeValue(AbstractCSS2Properties properties, String newValue, CSSStyleDeclaration declaration, boolean important); } private static class BorderSetter1 implements SubPropertySetter { public void changeValue(AbstractCSS2Properties properties, String newValue, CSSStyleDeclaration declaration) { this.changeValue(properties, newValue, declaration, true); } public void changeValue(AbstractCSS2Properties properties, String newValue, CSSStyleDeclaration declaration, boolean important) { properties.setPropertyValueLCAlt(BORDER, newValue, important); properties.setPropertyValueProcessed(BORDER_TOP, newValue, declaration, important); properties.setPropertyValueProcessed(BORDER_LEFT, newValue, declaration, important); properties.setPropertyValueProcessed(BORDER_BOTTOM, newValue, declaration, important); properties.setPropertyValueProcessed(BORDER_RIGHT, newValue, declaration, important); } } private static class BorderSetter2 implements SubPropertySetter { private final String name; public BorderSetter2(String baseName) { this.name = baseName; } public void changeValue(AbstractCSS2Properties properties, String value, CSSStyleDeclaration declaration) { this.changeValue(properties, value, declaration, true); } public void changeValue(AbstractCSS2Properties properties, String value, CSSStyleDeclaration declaration, boolean important) { properties.setPropertyValueLCAlt(this.name, value, important); if(value != null && value.length() > 0) { String[] array = HtmlValues.splitCssValue(value); String color = null; String style = null; String width = null; for(int i = 0; i < array.length; i++) { String token = array[i]; if(HtmlValues.isBorderStyle(token)) { style = token; } else if(org.lobobrowser.util.gui.ColorFactory.getInstance().isColor(token)) { color = token; } else { width = token; } } String name = this.name; if(color != null) { properties.setPropertyValueLCAlt(name + "-color", color, important); } if(width != null) { properties.setPropertyValueLCAlt(name + "-width", width, important); } if(style != null) { properties.setPropertyValueLCAlt(name + "-style", style, important); } } } } private static class FourCornersSetter implements SubPropertySetter { private final String prefix; private final String suffix; private final String property; public FourCornersSetter(String property, String prefix, String suffix) { this.prefix = prefix; this.suffix = suffix; this.property = property; } public void changeValue(AbstractCSS2Properties properties, String newValue, CSSStyleDeclaration declaration) { this.changeValue(properties, newValue, declaration, true); } public void changeValue(AbstractCSS2Properties properties, String newValue, CSSStyleDeclaration declaration, boolean important) { properties.setPropertyValueLCAlt(this.property, newValue, important); if(newValue != null && newValue.length() > 0) { String[] array = HtmlValues.splitCssValue(newValue); int size = array.length; if(size == 1) { String prefix = this.prefix; String suffix = this.suffix; String value = array[0]; properties.setPropertyValueLCAlt(prefix + "top" + suffix, value, important); properties.setPropertyValueLCAlt(prefix + "right" + suffix, value, important); properties.setPropertyValueLCAlt(prefix + "bottom" + suffix, value, important); properties.setPropertyValueLCAlt(prefix + "left" + suffix, value, important); } else if(size >= 4) { String prefix = this.prefix; String suffix = this.suffix; properties.setPropertyValueLCAlt(prefix + "top" + suffix, array[0], important); properties.setPropertyValueLCAlt(prefix + "right" + suffix, array[1], important); properties.setPropertyValueLCAlt(prefix + "bottom" + suffix, array[2], important); properties.setPropertyValueLCAlt(prefix + "left" + suffix, array[3], important); } else if(size == 2) { String prefix = this.prefix; String suffix = this.suffix; properties.setPropertyValueLCAlt(prefix + "top" + suffix, array[0], important); properties.setPropertyValueLCAlt(prefix + "right" + suffix, array[1], important); properties.setPropertyValueLCAlt(prefix + "bottom" + suffix, array[0], important); properties.setPropertyValueLCAlt(prefix + "left" + suffix, array[1], important); } else if(size == 3) { String prefix = this.prefix; String suffix = this.suffix; properties.setPropertyValueLCAlt(prefix + "top" + suffix, array[0], important); properties.setPropertyValueLCAlt(prefix + "right" + suffix, array[1], important); properties.setPropertyValueLCAlt(prefix + "bottom" + suffix, array[2], important); properties.setPropertyValueLCAlt(prefix + "left" + suffix, array[1], important); } } } } private static class BackgroundImageSetter implements SubPropertySetter { public void changeValue(AbstractCSS2Properties properties, String newValue, CSSStyleDeclaration declaration) { this.changeValue(properties, newValue, declaration, true); } public void changeValue(AbstractCSS2Properties properties, String newValue, CSSStyleDeclaration declaration, boolean important) { String baseHref = null; String finalValue; if(declaration != null) { CSSRule rule = declaration.getParentRule(); if (rule != null) { CSSStyleSheet sheet = rule.getParentStyleSheet(); if (sheet instanceof com.steadystate.css.dom.CSSStyleSheetImpl) { com.steadystate.css.dom.CSSStyleSheetImpl ssheet = (com.steadystate.css.dom.CSSStyleSheetImpl) sheet; baseHref = ssheet.getHref(); } } } if(baseHref == null) { baseHref = properties.context.getDocumentBaseURI(); } String start = "url("; if (newValue == null || !newValue.toLowerCase().startsWith(start)) { finalValue = newValue; } else { int startIdx = start.length(); int closingIdx = newValue.lastIndexOf(')'); if (closingIdx == -1) { finalValue = newValue; } else { String quotedUri = newValue.substring(startIdx, closingIdx); String tentativeUri = HtmlValues.unquoteAndUnescape(quotedUri); if (baseHref == null) { finalValue = newValue; } else { try { java.net.URL styleUrl = Urls.createURL(null, baseHref); finalValue = "url(" + HtmlValues.quoteAndEscape(Urls.createURL(styleUrl, tentativeUri).toExternalForm()) + ")"; } catch (java.net.MalformedURLException mfu) { logger.log(Level.WARNING, "Unable to create URL for URI=[" + tentativeUri + "], with base=[" + baseHref + "].", mfu); finalValue = newValue; } } } } properties.setPropertyValueLCAlt(BACKGROUND_IMAGE, finalValue, important); } } private static class BackgroundSetter implements SubPropertySetter { public void changeValue(AbstractCSS2Properties properties, String newValue, CSSStyleDeclaration declaration) { this.changeValue(properties, newValue, declaration, true); } public void changeValue(AbstractCSS2Properties properties, String newValue, CSSStyleDeclaration declaration, boolean important) { properties.setPropertyValueLCAlt(BACKGROUND, newValue, important); if(newValue != null && newValue.length() > 0) { String[] tokens = HtmlValues.splitCssValue(newValue); boolean hasXPosition = false; boolean hasYPosition = false; String color = null; String image = null; String backgroundRepeat = null; String position = null; for(int i = 0; i < tokens.length; i++) { String token = tokens[i]; if(ColorFactory.getInstance().isColor(token)) { color = token; } else if(HtmlValues.isUrl(token)) { image = token; } else if(HtmlValues.isBackgroundRepeat(token)) { backgroundRepeat = token; } else if(HtmlValues.isBackgroundPosition(token)) { if(hasXPosition && !hasYPosition) { position += (" " + token); hasYPosition = true; } else { hasXPosition = true; position = token; } } } if(color != null) { properties.setPropertyValueLCAlt(BACKGROUND_COLOR, color, important); } if(image != null) { properties.setPropertyValueProcessed(BACKGROUND_IMAGE, image, declaration, important); } if(backgroundRepeat != null) { properties.setPropertyValueLCAlt(BACKGROUND_REPEAT, backgroundRepeat, important); } if(position != null) { properties.setPropertyValueLCAlt(BACKGROUND_POSITION, position, important); } } } } private static class FontSetter implements SubPropertySetter { public void changeValue(AbstractCSS2Properties properties, String newValue, CSSStyleDeclaration declaration) { this.changeValue(properties, newValue, declaration, true); } public void changeValue(AbstractCSS2Properties properties, String newValue, CSSStyleDeclaration declaration, boolean important) { properties.setPropertyValueLCAlt(FONT, newValue, important); if(newValue != null && newValue.length() > 0) { String fontSpecTL = newValue.toLowerCase(); FontInfo fontInfo = (FontInfo) HtmlValues.SYSTEM_FONTS.get(fontSpecTL); if(fontInfo != null) { if(fontInfo.fontFamily != null) { properties.setPropertyValueLCAlt(FONT_FAMILY, fontInfo.fontFamily, important); } if(fontInfo.fontSize != null) { properties.setPropertyValueLCAlt(FONT_SIZE, fontInfo.fontSize, important); } if(fontInfo.fontStyle != null) { properties.setPropertyValueLCAlt(FONT_STYLE, fontInfo.fontStyle, important); } if(fontInfo.fontVariant != null) { properties.setPropertyValueLCAlt(FONT_VARIANT, fontInfo.fontVariant, important); } if(fontInfo.fontWeight != null) { properties.setPropertyValueLCAlt(FONT_WEIGHT, fontInfo.fontWeight, important); } return; } String[] tokens = HtmlValues.splitCssValue(fontSpecTL); String token = null; int length = tokens.length; int i; for(i = 0; i < length; i++) { token = tokens[i]; if(HtmlValues.isFontStyle(token)) { properties.setPropertyValueLCAlt(FONT_STYLE, token, important); continue; } if(HtmlValues.isFontVariant(token)) { properties.setPropertyValueLCAlt(FONT_VARIANT, token, important); continue; } if(HtmlValues.isFontWeight(token)) { properties.setPropertyValueLCAlt(FONT_WEIGHT, token, important); continue; } // Otherwise exit loop break; } if(token != null) { int slashIdx = token.indexOf('/'); String fontSizeText = slashIdx == -1 ? token : token.substring(0, slashIdx); properties.setPropertyValueLCAlt(FONT_SIZE, fontSizeText, important); String lineHeightText = slashIdx == -1 ? null : token.substring(slashIdx+1); if(lineHeightText != null) { properties.setPropertyValueLCAlt(LINE_HEIGHT, lineHeightText, important); } if(++i < length) { StringBuffer fontFamilyBuff = new StringBuffer(); do { token = tokens[i]; fontFamilyBuff.append(token); fontFamilyBuff.append(' '); } while(++i < length); properties.setPropertyValueLCAlt(FONT_FAMILY, fontFamilyBuff.toString(), important); } } } } } private static class Property { public final String value; public final boolean important; public Property(final String value, final boolean important) { this.value = value; this.important = important; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/AbstractMarginRenderState.java0000644000175000017500000000326211134376342031142 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import org.lobobrowser.html.domimpl.HTMLElementImpl; import java.awt.Insets;; public abstract class AbstractMarginRenderState extends BlockRenderState { public AbstractMarginRenderState(RenderState prevRenderState, HTMLElementImpl element) { super(prevRenderState, element); } protected abstract HtmlInsets getDefaultMarginInsets(); public HtmlInsets getMarginInsets() { HtmlInsets insets = this.marginInsets; if(insets != INVALID_INSETS) { return insets; } insets = super.getMarginInsets(); if(insets == null) { insets = this.getDefaultMarginInsets(); } this.marginInsets = insets; return insets; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/AlignXRenderState.java0000644000175000017500000000067710641432566027435 0ustar twernertwernerpackage org.lobobrowser.html.style; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; public class AlignXRenderState extends RenderStateDelegator { private final int alignXPercent; public AlignXRenderState(final RenderState prevRenderState, int alignXPercent) { super(prevRenderState); this.alignXPercent = alignXPercent; } public int getAlignXPercent() { return this.alignXPercent; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/BackgroundInfo.java0000644000175000017500000000264410726473504027002 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import java.awt.*; public class BackgroundInfo { public Color backgroundColor; public java.net.URL backgroundImage; public boolean backgroundXPositionAbsolute; public int backgroundXPosition; public boolean backgroundYPositionAbsolute; public int backgroundYPosition; public int backgroundRepeat = BR_REPEAT; public static final int BR_REPEAT = 0; public static final int BR_NO_REPEAT = 1; public static final int BR_REPEAT_X = 2; public static final int BR_REPEAT_Y = 3; } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/BaseFontRenderState.java0000644000175000017500000000052410641432566027743 0ustar twernertwernerpackage org.lobobrowser.html.style; public class BaseFontRenderState extends RenderStateDelegator { private final int fontBase; public BaseFontRenderState(final RenderState prevRenderState, int fontBase) { super(prevRenderState); this.fontBase = fontBase; } public int getFontBase() { return this.fontBase; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/BlockQuoteRenderState.java0000644000175000017500000000404311134400204030270 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import org.lobobrowser.html.domimpl.HTMLElementImpl; import java.awt.*; public class BlockQuoteRenderState extends AbstractMarginRenderState { public BlockQuoteRenderState(RenderState prevRenderState, HTMLElementImpl element) { super(prevRenderState, element); } protected HtmlInsets getDefaultMarginInsets() { HtmlInsets insets = new HtmlInsets(); RenderState prevRS = this.getPreviousRenderState(); FontMetrics fm = prevRS == null ? this.getFontMetrics() : prevRS.getFontMetrics(); insets.top = fm.getHeight(); insets.bottom = fm.getHeight(); insets.topType = HtmlInsets.TYPE_PIXELS; insets.bottomType = HtmlInsets.TYPE_PIXELS; int dpi = GraphicsEnvironment.isHeadless() ? 72 : Toolkit .getDefaultToolkit().getScreenResolution(); double leftInches = 30 / 72.0; insets.left = (int) Math.round(dpi * 30.0 / 72.0); insets.right = insets.left / 2; insets.leftType = HtmlInsets.TYPE_PIXELS; insets.rightType = HtmlInsets.TYPE_PIXELS; return insets; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/BlockRenderState.java0000644000175000017500000000257110726473506027303 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import org.lobobrowser.html.domimpl.*; /** * Render state for elements that are displayed as blocks by default. */ public class BlockRenderState extends StyleSheetRenderState { public BlockRenderState(RenderState prevRenderState, HTMLElementImpl element) { super(prevRenderState, element); } public BlockRenderState(HTMLDocumentImpl document) { super(document); } public int getDefaultDisplay() { return DISPLAY_BLOCK; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/BodyRenderState.java0000644000175000017500000001062611127420670027134 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import java.awt.Insets; import org.lobobrowser.html.domimpl.HTMLElementImpl; import org.lobobrowser.util.gui.*; public class BodyRenderState extends StyleSheetRenderState { //Note: BODY behaves like an inline element, but the root //block uses the element and treats its properties as those //of a block element. public BodyRenderState(RenderState prevRenderState, HTMLElementImpl element) { super(prevRenderState, element); } public void invalidate() { super.invalidate(); } public BackgroundInfo getBackgroundInfo() { BackgroundInfo binfo = this.iBackgroundInfo; if(binfo != INVALID_BACKGROUND_INFO) { return binfo; } binfo = super.getBackgroundInfo(); if(binfo == null || binfo.backgroundColor == null) { String bgcolor = this.element.getAttribute("bgcolor"); if(bgcolor != null && bgcolor.length() != 0) { if(binfo == null) { binfo = new BackgroundInfo(); } binfo.backgroundColor = ColorFactory.getInstance().getColor(bgcolor); } } this.iBackgroundInfo = binfo; return binfo; } public HtmlInsets getMarginInsets() { HtmlInsets insets = this.marginInsets; if(insets != INVALID_INSETS) { return insets; } insets = super.getMarginInsets(); if(insets == null) { HTMLElementImpl element = this.element; String leftMargin = element.getAttribute("leftmargin"); String rightMargin = element.getAttribute("rightmargin"); String bottomMargin = element.getAttribute("rightmargin"); String topMargin = element.getAttribute("topmargin"); String marginWidth = element.getAttribute("marginwidth"); String marginHeight = element.getAttribute("marginheight"); if(leftMargin == null) { leftMargin = marginWidth; } if(rightMargin == null) { rightMargin = marginWidth; } if(topMargin == null) { topMargin = marginHeight; } if(bottomMargin == null) { bottomMargin = marginHeight; } if(leftMargin != null) { if(insets == null) { insets = new HtmlInsets(); } insets.left = HtmlValues.getOldSyntaxPixelSizeSimple(leftMargin, 0); insets.leftType = HtmlInsets.TYPE_PIXELS; } if(rightMargin != null) { if(insets == null) { insets = new HtmlInsets(); } insets.right = HtmlValues.getOldSyntaxPixelSizeSimple(rightMargin, 0); insets.rightType = HtmlInsets.TYPE_PIXELS; } if(topMargin != null) { if(insets == null) { insets = new HtmlInsets(); } insets.top = HtmlValues.getOldSyntaxPixelSizeSimple(topMargin, 0); insets.topType = HtmlInsets.TYPE_PIXELS; } if(bottomMargin != null) { if(insets == null) { insets = new HtmlInsets(); } insets.bottom = HtmlValues.getOldSyntaxPixelSizeSimple(bottomMargin, 0); insets.bottomType = HtmlInsets.TYPE_PIXELS; } } this.marginInsets = insets; return insets; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/BorderInfo.java0000644000175000017500000000236111130334422026115 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import java.awt.*; public class BorderInfo { public int topStyle; public int leftStyle; public int bottomStyle; public int rightStyle; public Color topColor; public Color leftColor; public Color bottomColor; public Color rightColor; public HtmlInsets insets; } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/CSS2PropertiesContext.java0000644000175000017500000000234310751146764030242 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; public interface CSS2PropertiesContext { public void informLookInvalid(); public void informSizeInvalid(); public void informPositionInvalid(); public void informLayoutInvalid(); public void informInvalid(); public AbstractCSS2Properties getParentStyle(); public String getDocumentBaseURI(); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/CSSUtilities.java0000644000175000017500000001305710760062524026425 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.logging.*; import java.security.*; import org.w3c.css.sac.InputSource; import org.w3c.dom.css.CSSStyleSheet; import org.w3c.dom.stylesheets.*; import org.lobobrowser.html.*; import org.lobobrowser.html.domimpl.HTMLDocumentImpl; import org.lobobrowser.util.*; import com.steadystate.css.dom.CSSStyleSheetImpl; import com.steadystate.css.parser.CSSOMParser; public class CSSUtilities { private static final Logger logger = Logger.getLogger(CSSUtilities.class.getName()); private CSSUtilities() { } public static String preProcessCss(String text) { try { BufferedReader reader = new BufferedReader(new StringReader(text)); String line; StringBuffer sb = new StringBuffer(); String pendingLine = null; // Only last line should be trimmed. while((line = reader.readLine()) != null) { String tline = line.trim(); if(tline.length() != 0) { if(pendingLine != null) { sb.append(pendingLine); sb.append("\r\n"); pendingLine = null; } if(tline.startsWith("//")) { pendingLine = line; continue; } sb.append(line); sb.append("\r\n"); } } return sb.toString(); } catch(IOException ioe) { // not possible throw new IllegalStateException(ioe.getMessage()); } } public static InputSource getCssInputSourceForStyleSheet(String text, String scriptURI) { java.io.Reader reader = new StringReader(text); InputSource is = new InputSource(reader); is.setURI(scriptURI); return is; } public static CSSStyleSheet parse(org.w3c.dom.Node ownerNode, String href, HTMLDocumentImpl doc, String baseUri, boolean considerDoubleSlashComments) throws MalformedURLException { UserAgentContext bcontext = doc.getUserAgentContext(); final HttpRequest request = bcontext.createHttpRequest(); URL baseURL = new URL(baseUri); URL scriptURL = Urls.createURL(baseURL, href); final String scriptURI = scriptURL == null ? href : scriptURL.toExternalForm(); // Perform a synchronous request SecurityManager sm = System.getSecurityManager(); if(sm == null) { try { request.open("GET", scriptURI, false); request.send(null); } catch(java.io.IOException thrown) { logger.log(Level.WARNING, "parse()", thrown); } } else { // Code might have restrictions on loading items from elsewhere. AccessController.doPrivileged(new PrivilegedAction() { public Object run() { try { request.open("GET", scriptURI, false); request.send(null); } catch(java.io.IOException thrown) { logger.log(Level.WARNING, "parse()", thrown); } return null; } }); } int status = request.getStatus(); if(status != 200 && status != 0) { logger.warning("Unable to parse CSS. URI=[" + scriptURI + "]. Response status was " + status + "."); return null; } String text = request.getResponseText(); if(text != null && !"".equals(text)) { String processedText = considerDoubleSlashComments ? preProcessCss(text) : text; CSSOMParser parser = new CSSOMParser(); InputSource is = getCssInputSourceForStyleSheet(processedText, scriptURI); is.setURI(scriptURI); try { CSSStyleSheetImpl sheet = (CSSStyleSheetImpl) parser.parseStyleSheet(is); sheet.setHref(scriptURI); sheet.setOwnerNode(ownerNode); return sheet; } catch(Throwable err) { logger.log(Level.WARNING,"Unable to parse CSS. URI=[" + scriptURI + "].", err); return null; } } else { return null; } } public static boolean matchesMedia(String mediaValues, UserAgentContext rcontext) { if(mediaValues == null || mediaValues.length() == 0) { return true; } if(rcontext == null) { return false; } StringTokenizer tok = new StringTokenizer(mediaValues, ","); while(tok.hasMoreTokens()) { String token = tok.nextToken().trim(); String mediaName = Strings.trimForAlphaNumDash(token); if(rcontext.isMedia(mediaName)) { return true; } } return false; } public static boolean matchesMedia(MediaList mediaList, UserAgentContext rcontext) { if(mediaList == null) { return true; } int length = mediaList.getLength(); if(length == 0) { return true; } if(rcontext == null) { return false; } for(int i = 0; i < length; i++) { String mediaName = mediaList.item(i); if(rcontext.isMedia(mediaName)) { return true; } } return false; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/ColorRenderState.java0000644000175000017500000000233410726473502027320 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import java.awt.Color; public class ColorRenderState extends RenderStateDelegator { private final Color color; public ColorRenderState(RenderState prevRenderState, Color color) { super(prevRenderState); this.color = color; } public Color getColor() { return this.color; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/ComputedCSS2Properties.java0000644000175000017500000000325011134550716030364 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; public class ComputedCSS2Properties extends AbstractCSS2Properties { public ComputedCSS2Properties(CSS2PropertiesContext context) { super(context); } protected void setPropertyValueLC(String lowerCaseName, String value) { throw new java.lang.IllegalAccessError("Style properties cannot be set in this instance."); } protected void checkSetProperty() { throw new java.lang.IllegalAccessError("Style properties cannot be set in this instance."); } public void internalSetLC(String lowerCaseName, String value) { // Should only be called right after creation of the CSS object. // Properties need to be "unimportant" otherwise they won't get overridden. super.setPropertyValueLCAlt(lowerCaseName, value, false); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/DisplayRenderState.java0000644000175000017500000000250710726473506027655 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import org.lobobrowser.html.domimpl.*; public class DisplayRenderState extends StyleSheetRenderState { private final int defaultDisplay; public DisplayRenderState(RenderState prevRenderState, HTMLElementImpl element, final int defaultDisplay) { super(prevRenderState, element); this.defaultDisplay = defaultDisplay; } public int getDefaultDisplay() { return this.defaultDisplay; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/FontInfo.java0000644000175000017500000000211010751132356025610 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; class FontInfo { public String fontFamily; public String fontStyle; public String fontVariant; public String fontWeight; public String fontSize; }libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/FontNameRenderState.java0000644000175000017500000000531410760263042027744 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Toolkit; import java.util.HashMap; import java.util.Map; public class FontNameRenderState extends RenderStateDelegator { private final String fontName; public FontNameRenderState(RenderState prevRenderState, String fontName) { super(prevRenderState); this.fontName = fontName; } private Font iFont; public Font getFont() { Font f = this.iFont; if(f != null) { return f; } Font parentFont = this.delegate.getFont(); f = new Font(this.fontName, parentFont.getStyle(), parentFont.getSize()); this.iFont = f; return f; } private FontMetrics iFontMetrics; public FontMetrics getFontMetrics() { FontMetrics fm = this.iFontMetrics; if(fm == null) { //TODO getFontMetrics deprecated. How to get text width? fm = Toolkit.getDefaultToolkit().getFontMetrics(this.getFont()); this.iFontMetrics = fm; } return fm; } public void invalidate() { super.invalidate(); this.iFont = null; this.iFontMetrics = null; Map map = this.iWordInfoMap; if(map != null) { map.clear(); } } Map iWordInfoMap = null; public final WordInfo getWordInfo(String word) { // Expected to be called only in the GUI (rendering) thread. // No synchronization necessary. Map map = this.iWordInfoMap; if(map == null) { map = new HashMap(1); this.iWordInfoMap = map; } WordInfo wi = (WordInfo) map.get(word); if(wi != null) { return wi; } wi = new WordInfo(); FontMetrics fm = this.getFontMetrics(); wi.fontMetrics = fm; wi.ascentPlusLeading = fm.getAscent() + fm.getLeading(); wi.descent = fm.getDescent(); wi.height = fm.getHeight(); wi.width = fm.stringWidth(word); map.put(word, wi); return wi; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/FontStyleRenderState.java0000644000175000017500000000653011047522134030164 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Toolkit; import java.awt.font.TextAttribute; import java.util.HashMap; import java.util.Map; import org.lobobrowser.util.gui.FontFactory; public class FontStyleRenderState extends RenderStateDelegator { private final int style; private final Integer superscript; public FontStyleRenderState(RenderState prevRenderState, int style) { this(prevRenderState, style, null); } FontStyleRenderState(RenderState prevRenderState, int style, Integer superscript) { super(prevRenderState); this.style = style; this.superscript = superscript; } public static FontStyleRenderState createSuperscriptFontStyleRenderState (RenderState prevRenderState, Integer superscript){ return new FontStyleRenderState(prevRenderState, prevRenderState.getFont().getStyle(), superscript); } private Font iFont; public Font getFont() { Font f = this.iFont; if(f != null) { return f; } Font parentFont = this.delegate.getFont(); if (parentFont.getStyle() != this.style){ f = parentFont.deriveFont(this.style | parentFont.getStyle()); } else { f = parentFont; } f = FontFactory.superscriptFont(f, superscript); this.iFont = f; return f; } private FontMetrics iFontMetrics; public FontMetrics getFontMetrics() { FontMetrics fm = this.iFontMetrics; if(fm == null) { //TODO getFontMetrics deprecated. How to get text width? fm = Toolkit.getDefaultToolkit().getFontMetrics(this.getFont()); this.iFontMetrics = fm; } return fm; } public void invalidate() { this.delegate.invalidate(); this.iFont = null; this.iFontMetrics = null; Map map = this.iWordInfoMap; if(map != null) { map.clear(); } } Map iWordInfoMap = null; public final WordInfo getWordInfo(String word) { // Expected to be called only in the GUI (rendering) thread. // No synchronization necessary. Map map = this.iWordInfoMap; if(map == null) { map = new HashMap(1); this.iWordInfoMap = map; } WordInfo wi = (WordInfo) map.get(word); if(wi != null) { return wi; } wi = new WordInfo(); FontMetrics fm = this.getFontMetrics(); wi.fontMetrics = fm; wi.ascentPlusLeading = fm.getAscent() + fm.getLeading(); wi.descent = fm.getDescent(); wi.height = fm.getHeight(); wi.width = fm.stringWidth(word); map.put(word, wi); return wi; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/HeadingRenderState.java0000644000175000017500000000325311134400072027564 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import org.lobobrowser.html.domimpl.HTMLElementImpl; import java.awt.*; public class HeadingRenderState extends AbstractMarginRenderState { public HeadingRenderState(RenderState prevRenderState, HTMLElementImpl element) { super(prevRenderState, element); } protected HtmlInsets getDefaultMarginInsets() { HtmlInsets insets = new HtmlInsets(); RenderState prevRS = this.getPreviousRenderState(); FontMetrics fm = prevRS == null ? this.getFontMetrics() : prevRS.getFontMetrics(); insets.top = fm.getHeight(); insets.bottom = fm.getHeight(); insets.topType = HtmlInsets.TYPE_PIXELS; insets.bottomType = HtmlInsets.TYPE_PIXELS; return insets; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/HtmlInsets.java0000644000175000017500000001040611130355440026160 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import java.awt.Insets; public class HtmlInsets { public static final int TYPE_UNDEFINED = 0; public static final int TYPE_PIXELS = 1; public static final int TYPE_AUTO = 2; public static final int TYPE_PERCENT = 3; public int top, bottom, left, right; /* Types assumed to be initialized as UNDEFINED */ public int topType, bottomType, leftType, rightType; public HtmlInsets() { } public int getTop() { return top; } public void setTop(int top) { this.top = top; } public int getBottom() { return bottom; } public void setBottom(int bottom) { this.bottom = bottom; } public int getLeft() { return left; } public void setLeft(int left) { this.left = left; } public int getRight() { return right; } public void setRight(int right) { this.right = right; } public int getTopType() { return topType; } public void setTopType(int topType) { this.topType = topType; } public int getBottomType() { return bottomType; } public void setBottomType(int bottomType) { this.bottomType = bottomType; } public int getLeftType() { return leftType; } public void setLeftType(int leftType) { this.leftType = leftType; } public int getRightType() { return rightType; } public void setRightType(int rightType) { this.rightType = rightType; } public java.awt.Insets getAWTInsets(int defaultTop, int defaultLeft, int defaultBottom, int defaultRight, int availWidth, int availHeight, int autoX, int autoY) { int top = getInsetPixels(this.top, this.topType, defaultTop, availHeight, autoY); int left = getInsetPixels(this.left, this.leftType, defaultLeft, availWidth, autoX); int bottom = getInsetPixels(this.bottom, this.bottomType, defaultBottom, availHeight, autoY); int right = getInsetPixels(this.right, this.rightType, defaultRight, availWidth, autoX); return new Insets(top, left, bottom, right); } public java.awt.Insets getSimpleAWTInsets(int availWidth, int availHeight) { int top = getInsetPixels(this.top, this.topType, 0, availHeight, 0); int left = getInsetPixels(this.left, this.leftType, 0, availWidth, 0); int bottom = getInsetPixels(this.bottom, this.bottomType, 0, availHeight, 0); int right = getInsetPixels(this.right, this.rightType, 0, availWidth, 0); return new Insets(top, left, bottom, right); } private static int getInsetPixels(int value, int type, int defaultValue, int availSize, int autoValue) { if(type == TYPE_PIXELS) { return value; } else if(type == TYPE_UNDEFINED) { return defaultValue; } else if(type == TYPE_AUTO) { return autoValue; } else if(type == TYPE_PERCENT) { return (availSize * value) / 100; } else { throw new IllegalStateException(); } } public String toString() { return "[" + this.top + "," + this.left + "," + this.bottom + "," + this.right + "]"; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/HtmlLength.java0000644000175000017500000000540710726473504026155 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Nov 19, 2005 */ package org.lobobrowser.html.style; public final class HtmlLength { // Note: Preferred type has higher value public static final int PIXELS = 1; public static final int LENGTH = 2; public static final int MULTI_LENGTH = 0; public static final HtmlLength[] EMPTY_ARRAY = new HtmlLength[0]; private final int lengthType; private volatile int value; public HtmlLength(String spec) throws IndexOutOfBoundsException, NumberFormatException { spec = spec.trim(); int length = spec.length(); char lastChar = spec.charAt(length - 1); String parseable; if(lastChar == '%') { this.lengthType = LENGTH; parseable = spec.substring(0, length - 1).trim(); } else if(lastChar == '*') { this.lengthType = MULTI_LENGTH; if(length <= 1) { parseable = "1"; } else { parseable = spec.substring(0, length - 1).trim(); } } else { this.lengthType = PIXELS; parseable = spec; } this.value = Integer.parseInt(parseable); } public HtmlLength(int pixels) { this.lengthType = PIXELS; this.value = pixels; } /** * @return Returns the lengthType. */ public final int getLengthType() { return lengthType; } /** * @return Returns the spec. */ public final int getRawValue() { return this.value; } public final int getLength(int availLength) { int lt = this.lengthType; if(lt == LENGTH) { return (availLength * this.value) / 100; } else { return this.value; } } public final void divideBy(int denominator) { int val = this.value; val = val / denominator; this.value = val; } public final boolean isPreferredOver(HtmlLength otherLength) { if(otherLength == null) { return true; } if(this.lengthType > otherLength.lengthType) { return true; } return this.value > otherLength.value; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/HtmlValues.java0000644000175000017500000007565311134546166026204 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Insets; import java.awt.Toolkit; import java.awt.GraphicsEnvironment; import java.awt.font.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; import java.util.logging.*; import org.lobobrowser.util.gui.ColorFactory; import org.w3c.dom.css.*; import org.lobobrowser.util.*; import org.lobobrowser.html.domimpl.*; public class HtmlValues { public static final Map SYSTEM_FONTS = new HashMap(); private static final Logger logger = Logger.getLogger(HtmlValues.class .getName()); public static final float DEFAULT_FONT_SIZE = 14.0f; public static final int DEFAULT_FONT_SIZE_INT = (int) DEFAULT_FONT_SIZE; public static final Float DEFAULT_FONT_SIZE_BOX = new Float(DEFAULT_FONT_SIZE); public static final int DEFAULT_BORDER_WIDTH = 2; public static final int BORDER_STYLE_NONE = 0; public static final int BORDER_STYLE_HIDDEN = 1; public static final int BORDER_STYLE_DOTTED = 2; public static final int BORDER_STYLE_DASHED = 3; public static final int BORDER_STYLE_SOLID = 4; public static final int BORDER_STYLE_DOUBLE = 5; public static final int BORDER_STYLE_GROOVE = 6; public static final int BORDER_STYLE_RIDGE = 7; public static final int BORDER_STYLE_INSET = 8; public static final int BORDER_STYLE_OUTSET = 9; static { FontInfo systemFont = new FontInfo(); SYSTEM_FONTS.put("caption", systemFont); SYSTEM_FONTS.put("icon", systemFont); SYSTEM_FONTS.put("menu", systemFont); SYSTEM_FONTS.put("message-box", systemFont); SYSTEM_FONTS.put("small-caption", systemFont); SYSTEM_FONTS.put("status-bar", systemFont); } private HtmlValues() { } public static boolean isBorderStyle(String token) { String tokenTL = token.toLowerCase(); return tokenTL.equals("solid") || tokenTL.equals("dashed") || tokenTL.equals("dotted") || tokenTL.equals("double") || tokenTL.equals("none") || tokenTL.equals("hidden") || tokenTL.equals("groove") || tokenTL.equals("ridge") || tokenTL.equals("inset") || tokenTL.equals("outset"); } public static HtmlInsets getMarginInsets(CSS2Properties cssProperties, RenderState renderState) { HtmlInsets insets = null; String topText = cssProperties.getMarginTop(); insets = updateTopInset(insets, topText, renderState); String leftText = cssProperties.getMarginLeft(); insets = updateLeftInset(insets, leftText, renderState); String bottomText = cssProperties.getMarginBottom(); insets = updateBottomInset(insets, bottomText, renderState); String rightText = cssProperties.getMarginRight(); insets = updateRightInset(insets, rightText, renderState); return insets; } public static HtmlInsets getPaddingInsets(CSS2Properties cssProperties, RenderState renderState) { HtmlInsets insets = null; String topText = cssProperties.getPaddingTop(); insets = updateTopInset(insets, topText, renderState); String leftText = cssProperties.getPaddingLeft(); insets = updateLeftInset(insets, leftText, renderState); String bottomText = cssProperties.getPaddingBottom(); insets = updateBottomInset(insets, bottomText, renderState); String rightText = cssProperties.getPaddingRight(); insets = updateRightInset(insets, rightText, renderState); return insets; } public static HtmlInsets getBorderInsets(Insets borderStyles, CSS2Properties cssProperties, RenderState renderState) { HtmlInsets insets = null; if(borderStyles.top != HtmlValues.BORDER_STYLE_NONE) { String topText = cssProperties.getBorderTopWidth(); insets = updateTopInset(insets, topText, renderState); } if(borderStyles.left != HtmlValues.BORDER_STYLE_NONE) { String leftText = cssProperties.getBorderLeftWidth(); insets = updateLeftInset(insets, leftText, renderState); } if(borderStyles.bottom != HtmlValues.BORDER_STYLE_NONE) { String bottomText = cssProperties.getBorderBottomWidth(); insets = updateBottomInset(insets, bottomText, renderState); } if(borderStyles.right != HtmlValues.BORDER_STYLE_NONE) { String rightText = cssProperties.getBorderRightWidth(); insets = updateRightInset(insets, rightText, renderState); } return insets; } /** * Populates {@link BorderInfo.insets}. * @param binfo A BorderInfo with its styles already populated. * @param cssProperties The CSS properties object. * @param renderState The current render state. */ public static void populateBorderInsets(BorderInfo binfo, CSS2Properties cssProperties, RenderState renderState) { HtmlInsets insets = null; if(binfo.topStyle != HtmlValues.BORDER_STYLE_NONE) { String topText = cssProperties.getBorderTopWidth(); insets = updateTopInset(insets, topText, renderState); } if(binfo.leftStyle != HtmlValues.BORDER_STYLE_NONE) { String leftText = cssProperties.getBorderLeftWidth(); insets = updateLeftInset(insets, leftText, renderState); } if(binfo.bottomStyle != HtmlValues.BORDER_STYLE_NONE) { String bottomText = cssProperties.getBorderBottomWidth(); insets = updateBottomInset(insets, bottomText, renderState); } if(binfo.rightStyle != HtmlValues.BORDER_STYLE_NONE) { String rightText = cssProperties.getBorderRightWidth(); insets = updateRightInset(insets, rightText, renderState); } binfo.insets = insets; } private static int getBorderWidth(String sizeText, int borderStyle, RenderState renderState) { if (borderStyle == BORDER_STYLE_NONE) { return 0; } else { if (sizeText == null || sizeText.length() == 0) { return DEFAULT_BORDER_WIDTH; } return HtmlValues.getPixelSize(sizeText, renderState, DEFAULT_BORDER_WIDTH); } } private static HtmlInsets updateTopInset(HtmlInsets insets, String sizeText, RenderState renderState) { if (sizeText == null) { return insets; } sizeText = sizeText.trim(); if(sizeText.length() == 0) { return insets; } if(insets == null) { insets = new HtmlInsets(); } if("auto".equalsIgnoreCase(sizeText)) { insets.topType = HtmlInsets.TYPE_AUTO; } else if(sizeText.endsWith("%")) { insets.topType = HtmlInsets.TYPE_PERCENT; try { insets.top = Integer.parseInt(sizeText.substring(0, sizeText.length() - 1)); } catch(NumberFormatException nfe) { insets.top = 0; } } else { insets.topType = HtmlInsets.TYPE_PIXELS; insets.top = HtmlValues.getPixelSize(sizeText, renderState, 0); } return insets; } private static HtmlInsets updateLeftInset(HtmlInsets insets, String sizeText, RenderState renderState) { if (sizeText == null) { return insets; } sizeText = sizeText.trim(); if(sizeText.length() == 0) { return insets; } if(insets == null) { insets = new HtmlInsets(); } if("auto".equalsIgnoreCase(sizeText)) { insets.leftType = HtmlInsets.TYPE_AUTO; } else if(sizeText.endsWith("%")) { insets.leftType = HtmlInsets.TYPE_PERCENT; try { insets.left = Integer.parseInt(sizeText.substring(0, sizeText.length() - 1)); } catch(NumberFormatException nfe) { insets.left = 0; } } else { insets.leftType = HtmlInsets.TYPE_PIXELS; insets.left = HtmlValues.getPixelSize(sizeText, renderState, 0); } return insets; } private static HtmlInsets updateBottomInset(HtmlInsets insets, String sizeText, RenderState renderState) { if (sizeText == null) { return insets; } sizeText = sizeText.trim(); if(sizeText.length() == 0) { return insets; } if(insets == null) { insets = new HtmlInsets(); } if("auto".equalsIgnoreCase(sizeText)) { insets.bottomType = HtmlInsets.TYPE_AUTO; } else if(sizeText.endsWith("%")) { insets.bottomType = HtmlInsets.TYPE_PERCENT; try { insets.bottom = Integer.parseInt(sizeText.substring(0, sizeText.length() - 1)); } catch(NumberFormatException nfe) { insets.bottom = 0; } } else { insets.bottomType = HtmlInsets.TYPE_PIXELS; insets.bottom = HtmlValues.getPixelSize(sizeText, renderState, 0); } return insets; } private static HtmlInsets updateRightInset(HtmlInsets insets, String sizeText, RenderState renderState) { if (sizeText == null) { return insets; } sizeText = sizeText.trim(); if(sizeText.length() == 0) { return insets; } if(insets == null) { insets = new HtmlInsets(); } if("auto".equalsIgnoreCase(sizeText)) { insets.rightType = HtmlInsets.TYPE_AUTO; } else if(sizeText.endsWith("%")) { insets.rightType = HtmlInsets.TYPE_PERCENT; try { insets.right = Integer.parseInt(sizeText.substring(0, sizeText.length() - 1)); } catch(NumberFormatException nfe) { insets.right = 0; } } else { insets.rightType = HtmlInsets.TYPE_PIXELS; insets.right = HtmlValues.getPixelSize(sizeText, renderState, 0); } return insets; } public static Insets getInsets(String insetsSpec, RenderState renderState, boolean negativeOK) { int[] insetsArray = new int[4]; int size = 0; StringTokenizer tok = new StringTokenizer(insetsSpec); if (tok.hasMoreTokens()) { String token = tok.nextToken(); insetsArray[0] = getPixelSize(token, renderState, 0); if (negativeOK || insetsArray[0] >= 0) { size = 1; if (tok.hasMoreTokens()) { token = tok.nextToken(); insetsArray[1] = getPixelSize(token, renderState, 0); if (negativeOK || insetsArray[1] >= 0) { size = 2; if (tok.hasMoreTokens()) { token = tok.nextToken(); insetsArray[2] = getPixelSize(token, renderState, 0); if (negativeOK || insetsArray[2] >= 0) { size = 3; if (tok.hasMoreTokens()) { token = tok.nextToken(); insetsArray[3] = getPixelSize(token, renderState, 0); size = 4; if (negativeOK || insetsArray[3] >= 0) { // nop } else { insetsArray[3] = 0; } } } else { size = 4; insetsArray[2] = 0; } } } else { size = 4; insetsArray[1] = 0; } } } else { size = 1; insetsArray[0] = 0; } } if (size == 4) { return new Insets(insetsArray[0], insetsArray[3], insetsArray[2], insetsArray[1]); } else if (size == 1) { int val = insetsArray[0]; return new Insets(val, val, val, val); } else if (size == 2) { return new Insets(insetsArray[0], insetsArray[1], insetsArray[0], insetsArray[1]); } else if (size == 3) { return new Insets(insetsArray[0], insetsArray[1], insetsArray[2], insetsArray[1]); } else { return null; } } /** * Gets a number for 1 to 7. * * @param oldHtmlSpec * A number from 1 to 7 or +1, etc. */ public static final int getFontNumberOldStyle(String oldHtmlSpec, RenderState renderState) { oldHtmlSpec = oldHtmlSpec.trim(); int tentative; try { if (oldHtmlSpec.startsWith("+")) { tentative = renderState.getFontBase() + Integer.parseInt(oldHtmlSpec.substring(1)); } else if (oldHtmlSpec.startsWith("-")) { tentative = renderState.getFontBase() + Integer.parseInt(oldHtmlSpec); } else { tentative = Integer.parseInt(oldHtmlSpec); } if (tentative < 1) { tentative = 1; } else if (tentative > 7) { tentative = 7; } } catch (NumberFormatException nfe) { // ignore tentative = 3; } return tentative; } public static final float getFontSize(int fontNumber) { switch (fontNumber) { case 1: return 10.0f; case 2: return 11.0f; case 3: return 13.0f; case 4: return 16.0f; case 5: return 21.0f; case 6: return 29.0f; case 7: return 42.0f; default: return 63.0f; } } public static final String getFontSizeSpec(int fontNumber) { switch (fontNumber) { case 1: return "10px"; case 2: return "11px"; case 3: return "13px"; case 4: return "16px"; case 5: return "21px"; case 6: return "29px"; case 7: return "42px"; default: return "63px"; } } public static final float getFontSize(String spec, RenderState parentRenderState) { String specTL = spec.toLowerCase(); if(specTL.endsWith("em")) { if(parentRenderState == null) { return DEFAULT_FONT_SIZE; } Font font = parentRenderState.getFont(); String pxText = specTL.substring(0, specTL.length() - 2); double value; try { value = Double.parseDouble(pxText); } catch (NumberFormatException nfe) { return DEFAULT_FONT_SIZE; } return (int) Math.round(font.getSize() * value); } else if (specTL.endsWith("px") || specTL.endsWith("pt") || specTL.endsWith("cm") || specTL.endsWith("pc") || specTL.endsWith("cm") || specTL.endsWith("mm") || specTL.endsWith("ex")) { int pixelSize = getPixelSize(spec, parentRenderState, DEFAULT_FONT_SIZE_INT); int dpi = GraphicsEnvironment.isHeadless() ? 72 : Toolkit .getDefaultToolkit().getScreenResolution(); // Normally the factor below should be 72, but // the font-size concept in HTML is handled differently. return pixelSize * 96 / dpi; } else if (specTL.endsWith("%")) { String value = specTL.substring(0, specTL.length() - 1); try { double valued = Double.parseDouble(value); double parentFontSize = parentRenderState == null ? 14.0 : parentRenderState.getFont().getSize(); return (float) (parentFontSize * valued / 100.0); } catch (NumberFormatException nfe) { return DEFAULT_FONT_SIZE; } } else if ("small".equals(specTL)) { return 12.0f; } else if ("medium".equals(specTL)) { return 14.0f; } else if ("large".equals(specTL)) { return 20.0f; } else if ("x-small".equals(specTL)) { return 11.0f; } else if ("xx-small".equals(specTL)) { return 10.0f; } else if ("x-large".equals(specTL)) { return 26.0f; } else if ("xx-large".equals(specTL)) { return 40.0f; } else if ("larger".equals(specTL)) { int parentFontSize = parentRenderState == null ? DEFAULT_FONT_SIZE_INT : parentRenderState.getFont().getSize(); return parentFontSize * 1.2f; } else if ("smaller".equals(specTL)) { int parentFontSize = parentRenderState == null ? DEFAULT_FONT_SIZE_INT : parentRenderState.getFont().getSize(); return parentFontSize / 1.2f; } else { return getPixelSize(spec, parentRenderState, DEFAULT_FONT_SIZE_INT); } } public static final int getPixelSize(String spec, RenderState renderState, int errorValue, int availSize) { if (spec.endsWith("%")) { String perText = spec.substring(0, spec.length() - 1); try { double val = Double.parseDouble(perText); return (int) Math.round(availSize * val / 100.0); } catch (NumberFormatException nfe) { return errorValue; } } else { return getPixelSize(spec, renderState, errorValue); } } public static final int getPixelSize(String spec, RenderState renderState, int errorValue) { String lcSpec = spec.toLowerCase(); if (lcSpec.endsWith("px")) { String pxText = lcSpec .substring(0, lcSpec.length() - 2); try { return (int) Math.round(Double.parseDouble(pxText)); } catch (NumberFormatException nfe) { return errorValue; } } else if (lcSpec.endsWith("em") && renderState != null) { Font f = renderState.getFont(); String valText = lcSpec.substring(0, lcSpec.length() - 2); double val; try { val = Double.parseDouble(valText); } catch (NumberFormatException nfe) { return errorValue; } // Get fontSize in 1/72 of an inch. int fontSize = f.getSize(); int dpi = GraphicsEnvironment.isHeadless() ? 72 : Toolkit .getDefaultToolkit().getScreenResolution(); // The factor below should normally be 72, but font sizes // are calculated differently in HTML. double pixelSize = fontSize * dpi / 96; return (int) Math.round(pixelSize * val); } else if (lcSpec.endsWith("pt")) { String valText = lcSpec.substring(0, lcSpec.length() - 2); double val; try { val = Double.parseDouble(valText); } catch (NumberFormatException nfe) { return errorValue; } int dpi = GraphicsEnvironment.isHeadless() ? 72 : Toolkit .getDefaultToolkit().getScreenResolution(); double inches = val / 72; return (int) Math.round(dpi * inches); } else if (lcSpec.endsWith("pc")) { String valText = lcSpec.substring(0, lcSpec.length() - 2); double val; try { val = Double.parseDouble(valText); } catch (NumberFormatException nfe) { return errorValue; } int dpi = GraphicsEnvironment.isHeadless() ? 72 : Toolkit.getDefaultToolkit().getScreenResolution(); double inches = val / 6; return (int) Math.round(dpi * inches); } else if (lcSpec.endsWith("cm")) { String valText = lcSpec.substring(0, lcSpec.length() - 2); double val; try { val = Double.parseDouble(valText); } catch (NumberFormatException nfe) { return errorValue; } int dpi = GraphicsEnvironment.isHeadless() ? 72 : Toolkit.getDefaultToolkit().getScreenResolution(); double inches = val / 2.54; return (int) Math.round(dpi * inches); } else if (lcSpec.endsWith("mm")) { String valText = lcSpec.substring(0, lcSpec.length() - 2); double val; try { val = Double.parseDouble(valText); } catch (NumberFormatException nfe) { return errorValue; } int dpi = GraphicsEnvironment.isHeadless() ? 72 : Toolkit.getDefaultToolkit().getScreenResolution(); double inches = val / 25.4; return (int) Math.round(dpi * inches); } else if (lcSpec.endsWith("ex") && renderState != null) { // Factor below is to try to match size in other browsers. double xHeight = renderState.getFontMetrics().getAscent() * 0.47; String valText = lcSpec.substring(0, lcSpec.length() - 2); double val; try { val = Double.parseDouble(valText); } catch (NumberFormatException nfe) { return errorValue; } return (int) Math.round(xHeight * val); } else { String pxText = lcSpec; try { return (int) Math.round(Double.parseDouble(pxText)); } catch (NumberFormatException nfe) { return errorValue; } } } public static int getOldSyntaxPixelSize(String spec, int availSize, int errorValue) { if (spec == null) { return errorValue; } spec = spec.trim(); try { if (spec.endsWith("%")) { return availSize * Integer .parseInt(spec.substring(0, spec.length() - 1)) / 100; } else { return Integer.parseInt(spec); } } catch (NumberFormatException nfe) { return errorValue; } } public static int getOldSyntaxPixelSizeSimple(String spec, int errorValue) { if (spec == null) { return errorValue; } spec = spec.trim(); try { return Integer.parseInt(spec); } catch (NumberFormatException nfe) { return errorValue; } } public static java.net.URL getURIFromStyleValue(String fullURLStyleValue) { String start = "url("; if (!fullURLStyleValue.toLowerCase().startsWith(start)) { return null; } int startIdx = start.length(); int closingIdx = fullURLStyleValue.lastIndexOf(')'); if (closingIdx == -1) { return null; } String quotedUri = fullURLStyleValue.substring(startIdx, closingIdx); String tentativeUri = unquoteAndUnescape(quotedUri); try { return Urls.createURL(null, tentativeUri); } catch (java.net.MalformedURLException mfu) { logger.log(Level.WARNING, "Unable to create URL for URI=[" + tentativeUri + "].", mfu); return null; } } public static String unquoteAndUnescape(String text) { StringBuffer result = new StringBuffer(); int index = 0; int length = text.length(); boolean escape = false; boolean single = false; if (index < length) { char ch = text.charAt(index); switch (ch) { case '\'': single = true; break; case '"': break; case '\\': escape = true; break; default: result.append(ch); } index++; } OUTER: for (; index < length; index++) { char ch = text.charAt(index); switch (ch) { case '\'': if (escape || !single) { escape = false; result.append(ch); } else { break OUTER; } break; case '"': if (escape || single) { escape = false; result.append(ch); } else { break OUTER; } break; case '\\': if (escape) { escape = false; result.append(ch); } else { escape = true; } break; default: if (escape) { escape = false; result.append('\\'); } result.append(ch); } } return result.toString(); } public static String quoteAndEscape(String text) { StringBuffer result = new StringBuffer(); result.append("'"); int index = 0; int length = text.length(); while(index < length) { char ch = text.charAt(index); switch (ch) { case '\'': result.append("\\'"); break; case '\\': result.append("\\\\"); break; default: result.append(ch); } index++; } result.append("'"); return result.toString(); } public static String getColorFromBackground(String background) { String[] backgroundParts = HtmlValues.splitCssValue(background); for (int i = 0; i < backgroundParts.length; i++) { String token = backgroundParts[i]; if (ColorFactory.getInstance().isColor(token)) { return token; } } return null; } public static boolean isLength(String token) { if (token.endsWith("px") || token.endsWith("pt") || token.endsWith("pc") || token.endsWith("cm") || token.endsWith("mm") || token.endsWith("ex") || token.endsWith("em")) { return true; } try { Double.parseDouble(token); return true; } catch (NumberFormatException nfe) { return false; } } public static String[] splitCssValue(String cssValue) { ArrayList tokens = new ArrayList(4); int len = cssValue.length(); int parenCount = 0; StringBuffer currentWord = null; for (int i = 0; i < len; i++) { char ch = cssValue.charAt(i); switch (ch) { case '(': parenCount++; if (currentWord == null) { currentWord = new StringBuffer(); } currentWord.append(ch); break; case ')': parenCount--; if (currentWord == null) { currentWord = new StringBuffer(); } currentWord.append(ch); break; case ' ': case '\t': case '\n': case '\r': if (parenCount == 0) { tokens.add(currentWord.toString()); currentWord = null; break; } else { // Fall through - no break } default: if (currentWord == null) { currentWord = new StringBuffer(); } currentWord.append(ch); break; } } if (currentWord != null) { tokens.add(currentWord.toString()); } return (String[]) tokens.toArray(new String[tokens.size()]); } public static boolean isUrl(String token) { return token.toLowerCase().startsWith("url("); } public static int getListStyleType(String token) { String tokenTL = token.toLowerCase(); if("none".equals(tokenTL)) { return ListStyle.TYPE_NONE; } else if ("disc".equals(tokenTL)) { return ListStyle.TYPE_DISC; } else if ("circle".equals(tokenTL)) { return ListStyle.TYPE_CIRCLE; } else if ("square".equals(tokenTL)) { return ListStyle.TYPE_SQUARE; } else if ("decimal".equals(tokenTL)) { return ListStyle.TYPE_DECIMAL; } else if ("lower-alpha".equals(tokenTL) || "lower-latin".equals(tokenTL)) { return ListStyle.TYPE_LOWER_ALPHA; } else if ("upper-alpha".equals(tokenTL) || "upper-latin".equals(tokenTL)) { return ListStyle.TYPE_UPPER_ALPHA; } else { // TODO: Many types missing here return ListStyle.TYPE_UNSET; } } public static int getListStyleTypeDeprecated(String token) { String tokenTL = token.toLowerCase(); if ("disc".equals(tokenTL)) { return ListStyle.TYPE_DISC; } else if ("circle".equals(tokenTL)) { return ListStyle.TYPE_CIRCLE; } else if ("square".equals(tokenTL)) { return ListStyle.TYPE_SQUARE; } else if ("1".equals(tokenTL)) { return ListStyle.TYPE_DECIMAL; } else if ("a".equals(tokenTL)) { return ListStyle.TYPE_LOWER_ALPHA; } else if ("A".equals(tokenTL)) { return ListStyle.TYPE_UPPER_ALPHA; } else { // TODO: Missing i, I. return ListStyle.TYPE_UNSET; } } public static int getListStylePosition(String token) { String tokenTL = token.toLowerCase(); if ("inside".equals(tokenTL)) { return ListStyle.POSITION_INSIDE; } else if ("outside".equals(tokenTL)) { return ListStyle.POSITION_OUTSIDE; } else { return ListStyle.POSITION_UNSET; } } public static ListStyle getListStyle(String listStyleText) { ListStyle listStyle = new ListStyle(); String[] tokens = HtmlValues.splitCssValue(listStyleText); for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; int listStyleType = HtmlValues.getListStyleType(token); if (listStyleType != ListStyle.TYPE_UNSET) { listStyle.type = listStyleType; } else if (HtmlValues.isUrl(token)) { // TODO: listStyle.image } else { int listStylePosition = HtmlValues.getListStylePosition(token); if (listStylePosition != ListStyle.POSITION_UNSET) { listStyle.position = listStylePosition; } } } return listStyle; } public static boolean isFontStyle(String token) { return "italic".equals(token) || "normal".equals(token) || "oblique".equals(token); } public static boolean isFontVariant(String token) { return "small-caps".equals(token) || "normal".equals(token); } public static boolean isFontWeight(String token) { if ("bold".equals(token) || "bolder".equals(token) || "lighter".equals(token)) { return true; } try { int value = Integer.parseInt(token); return (value % 100) == 0 && value >= 100 && value <= 900; } catch (NumberFormatException nfe) { return false; } } public static BorderInfo getBorderInfo(CSS2Properties properties, RenderState renderState) { BorderInfo binfo = new BorderInfo(); binfo.topStyle = getBorderStyle(properties.getBorderTopStyle()); binfo.rightStyle = getBorderStyle(properties.getBorderRightStyle()); binfo.bottomStyle = getBorderStyle(properties.getBorderBottomStyle()); binfo.leftStyle = getBorderStyle(properties.getBorderLeftStyle()); ColorFactory cf = ColorFactory.getInstance(); String topColorSpec = properties.getBorderTopColor(); if(topColorSpec != null) { binfo.topColor = cf.getColor(topColorSpec); } String rightColorSpec = properties.getBorderRightColor(); if(rightColorSpec != null) { binfo.rightColor = cf.getColor(rightColorSpec); } String bottomColorSpec = properties.getBorderBottomColor(); if(bottomColorSpec != null) { binfo.bottomColor = cf.getColor(bottomColorSpec); } String leftColorSpec = properties.getBorderLeftColor(); if(leftColorSpec != null) { binfo.leftColor = cf.getColor(leftColorSpec); } HtmlValues.populateBorderInsets(binfo, properties, renderState); return binfo; } public static Insets getBorderStyles(CSS2Properties properties) { int topStyle = getBorderStyle(properties.getBorderTopStyle()); int rightStyle = getBorderStyle(properties.getBorderRightStyle()); int bottomStyle = getBorderStyle(properties.getBorderBottomStyle()); int leftStyle = getBorderStyle(properties.getBorderLeftStyle()); return new Insets(topStyle, leftStyle, bottomStyle, rightStyle); } private static int getBorderStyle(String styleText) { if (styleText == null || styleText.length() == 0) { return HtmlValues.BORDER_STYLE_NONE; } String stl = styleText.toLowerCase(); if ("solid".equals(stl)) { return BORDER_STYLE_SOLID; } else if ("dashed".equals(stl)) { return BORDER_STYLE_DASHED; } else if ("dotted".equals(stl)) { return BORDER_STYLE_DOTTED; } else if ("none".equals(stl)) { return BORDER_STYLE_NONE; } else if ("hidden".equals(stl)) { return BORDER_STYLE_HIDDEN; } else if ("double".equals(stl)) { return BORDER_STYLE_DOUBLE; } else if ("groove".equals(stl)) { return BORDER_STYLE_GROOVE; } else if ("ridge".equals(stl)) { return BORDER_STYLE_RIDGE; } else if ("inset".equals(stl)) { return BORDER_STYLE_INSET; } else if ("outset".equals(stl)) { return BORDER_STYLE_OUTSET; } else { return BORDER_STYLE_NONE; } } public static boolean isBackgroundRepeat(String repeat) { String repeatTL = repeat.toLowerCase(); return repeatTL.indexOf("repeat") != -1; } public static boolean isBackgroundPosition(String token) { return isLength(token) || token.endsWith("%") || token.equalsIgnoreCase("top") || token.equalsIgnoreCase("center") || token.equalsIgnoreCase("bottom") || token.equalsIgnoreCase("left") || token.equalsIgnoreCase("right"); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/IFrameRenderState.java0000644000175000017500000001270311130404506027372 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import java.awt.Color; import org.lobobrowser.html.domimpl.HTMLDocumentImpl; import org.lobobrowser.html.domimpl.HTMLElementImpl; public class IFrameRenderState extends StyleSheetRenderState { public IFrameRenderState(RenderState prevRenderState, HTMLElementImpl element) { super(prevRenderState, element); } public int getOverflowX() { int overflow = this.overflowX; if(overflow != -1) { return overflow; } overflow = super.getOverflowX(); if(overflow == OVERFLOW_NONE) { HTMLElementImpl element = this.element; if(element != null) { String scrolling = element.getAttribute("scrolling"); if(scrolling != null) { scrolling = scrolling.trim().toLowerCase(); if("no".equals(scrolling)) { overflow = OVERFLOW_HIDDEN; } else if("yes".equals(scrolling)) { overflow = OVERFLOW_SCROLL; } else if("auto".equals(scrolling)) { overflow = OVERFLOW_AUTO; } } } } this.overflowX = overflow; return overflow; } public int getOverflowY() { int overflow = this.overflowY; if(overflow != -1) { return overflow; } overflow = super.getOverflowY(); if(overflow == OVERFLOW_NONE) { HTMLElementImpl element = this.element; if(element != null) { String scrolling = element.getAttribute("scrolling"); if(scrolling != null) { scrolling = scrolling.trim().toLowerCase(); if("no".equals(scrolling)) { overflow = OVERFLOW_HIDDEN; } else if("yes".equals(scrolling)) { overflow = OVERFLOW_SCROLL; } else if("auto".equals(scrolling)) { overflow = OVERFLOW_AUTO; } } } } this.overflowY = overflow; return overflow; } public BorderInfo getBorderInfo() { BorderInfo binfo = this.borderInfo; if(binfo != INVALID_BORDER_INFO) { return binfo; } binfo = super.getBorderInfo(); if(binfo == null || (binfo.topStyle == HtmlValues.BORDER_STYLE_NONE && binfo.bottomStyle == HtmlValues.BORDER_STYLE_NONE && binfo.leftStyle == HtmlValues.BORDER_STYLE_NONE && binfo.rightStyle == HtmlValues.BORDER_STYLE_NONE)) { if(binfo == null) { binfo = new BorderInfo(); } HTMLElementImpl element = this.element; if(element != null) { String border = element.getAttribute("frameborder"); if(border != null) { border = border.trim(); } int value; if(border != null) { try { value = Integer.parseInt(border); } catch(NumberFormatException nfe) { value = 0; } } else { value = 1; } HtmlInsets borderInsets = new HtmlInsets(); borderInsets.top = borderInsets.left = borderInsets.right = borderInsets.bottom = (value != 0 ? 1 : 0); borderInsets.topType = borderInsets.leftType = borderInsets.rightType = borderInsets.bottomType = HtmlInsets.TYPE_PIXELS; binfo.insets = borderInsets; if(binfo.topColor == null) { binfo.topColor = Color.DARK_GRAY; } if(binfo.leftColor == null) { binfo.leftColor = Color.DARK_GRAY; } if(binfo.rightColor == null) { binfo.rightColor = Color.LIGHT_GRAY; } if(binfo.bottomColor == null) { binfo.bottomColor = Color.LIGHT_GRAY; } if(value != 0) { binfo.topStyle = binfo.leftStyle = binfo.rightStyle = binfo.bottomStyle = HtmlValues.BORDER_STYLE_SOLID; } } } this.borderInfo = binfo; return binfo; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/ImageRenderState.java0000644000175000017500000001204511130357070027253 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import java.awt.Color; import java.awt.Insets; import org.lobobrowser.html.domimpl.HTMLElementImpl; public class ImageRenderState extends StyleSheetRenderState { public ImageRenderState(RenderState prevRenderState, HTMLElementImpl element) { super(prevRenderState, element); } public HtmlInsets getMarginInsets() { HtmlInsets mi = this.marginInsets; if(mi != INVALID_INSETS) { return mi; } AbstractCSS2Properties props = this.getCssProperties(); if(props == null) { mi = null; } else { mi = HtmlValues.getMarginInsets(props, this); } if(mi == null) { int hspace = 0; int vspace = 0; boolean createNew = false; String hspaceText = this.element.getAttribute("hspace"); if(hspaceText != null && hspaceText.length() != 0) { createNew = true; try { hspace = Integer.parseInt(hspaceText); } catch(NumberFormatException nfe) { // TODO: Percentages? } } String vspaceText = this.element.getAttribute("vspace"); if(vspaceText != null && vspaceText.length() != 0) { createNew = true; try { vspace = Integer.parseInt(vspaceText); } catch(NumberFormatException nfe) { // TODO: Percentages? } } if(createNew) { mi = new HtmlInsets(); mi.top = vspace; mi.topType = HtmlInsets.TYPE_PIXELS; mi.bottom = vspace; mi.bottomType = HtmlInsets.TYPE_PIXELS; mi.left = hspace; mi.leftType = HtmlInsets.TYPE_PIXELS; mi.right = hspace; mi.rightType = HtmlInsets.TYPE_PIXELS; } } this.marginInsets = mi; return mi; } public BorderInfo getBorderInfo() { BorderInfo binfo = this.borderInfo; if(binfo != INVALID_BORDER_INFO) { return binfo; } binfo = super.getBorderInfo(); if(binfo == null || (binfo.topStyle == HtmlValues.BORDER_STYLE_NONE && binfo.bottomStyle == HtmlValues.BORDER_STYLE_NONE && binfo.leftStyle == HtmlValues.BORDER_STYLE_NONE && binfo.rightStyle == HtmlValues.BORDER_STYLE_NONE)) { if(binfo == null) { binfo = new BorderInfo(); } HTMLElementImpl element = this.element; if(element != null) { String border = element.getAttribute("border"); if(border != null) { border = border.trim(); int value; int valueType; if(border.endsWith("%")) { valueType = HtmlInsets.TYPE_PERCENT; try { value = Integer.parseInt(border.substring(0, border.length()-1)); } catch(NumberFormatException nfe) { value = 0; } } else { valueType = HtmlInsets.TYPE_PIXELS; try { value = Integer.parseInt(border); } catch(NumberFormatException nfe) { value = 0; } } HtmlInsets borderInsets = new HtmlInsets(); borderInsets.top = borderInsets.left = borderInsets.right = borderInsets.bottom = value; borderInsets.topType = borderInsets.leftType = borderInsets.rightType = borderInsets.bottomType = valueType; binfo.insets = borderInsets; if(binfo.topColor == null) { binfo.topColor = Color.BLACK; } if(binfo.leftColor == null) { binfo.leftColor = Color.BLACK; } if(binfo.rightColor == null) { binfo.rightColor = Color.BLACK; } if(binfo.bottomColor == null) { binfo.bottomColor = Color.BLACK; } if(value != 0) { binfo.topStyle = binfo.leftStyle = binfo.rightStyle = binfo.bottomStyle = HtmlValues.BORDER_STYLE_SOLID; } } } } this.borderInfo = binfo; return binfo; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/ListRenderState.java0000644000175000017500000000401411134400052027132 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import org.lobobrowser.html.domimpl.HTMLElementImpl; import java.awt.*; public class ListRenderState extends AbstractMarginRenderState { public ListRenderState(RenderState prevRenderState, HTMLElementImpl element) { super(prevRenderState, element); } protected HtmlInsets getDefaultMarginInsets() { HtmlInsets insets = new HtmlInsets(); RenderState prevRS = this.getPreviousRenderState(); FontMetrics fm = prevRS == null ? this.getFontMetrics() : prevRS.getFontMetrics(); insets.top = fm.getHeight(); insets.bottom = fm.getHeight(); insets.topType = HtmlInsets.TYPE_PIXELS; insets.bottomType = HtmlInsets.TYPE_PIXELS; int dpi = GraphicsEnvironment.isHeadless() ? 72 : Toolkit .getDefaultToolkit().getScreenResolution(); double leftInches = 30 / 72.0; insets.left = (int) Math.round(dpi * 30.0 / 72.0); insets.leftType = HtmlInsets.TYPE_PIXELS; return insets; } public int getDefaultDisplay() { return DISPLAY_LIST_ITEM; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/ListStyle.java0000644000175000017500000000350511047771300026030 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import java.awt.Image; public class ListStyle { public static final int TYPE_UNSET = 256; public static final int TYPE_NONE = 0; public static final int TYPE_DISC = 1; public static final int TYPE_CIRCLE = 2; public static final int TYPE_SQUARE = 3; public static final int TYPE_DECIMAL = 4; public static final int TYPE_LOWER_ALPHA = 5; public static final int TYPE_UPPER_ALPHA = 6; public static final int TYPE_LOWER_LATIN = 7; public static final int TYPE_UPPER_LATIN = 8; public static final int POSITION_UNSET = 0; public static final int POSITION_INSIDE = 0; public static final int POSITION_OUTSIDE = 0; public int type; public java.awt.Image image; public int position; public ListStyle(final int type, final Image image, final int position) { super(); this.type = type; this.image = image; this.position = position; } public ListStyle() { } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/LocalCSS2Properties.java0000644000175000017500000000210610750317012027626 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; public class LocalCSS2Properties extends AbstractCSS2Properties { public LocalCSS2Properties(CSS2PropertiesContext context) { super(context); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/ParagraphRenderState.java0000644000175000017500000000325711134400100030126 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import org.lobobrowser.html.domimpl.HTMLElementImpl; import java.awt.*; public class ParagraphRenderState extends AbstractMarginRenderState { public ParagraphRenderState(RenderState prevRenderState, HTMLElementImpl element) { super(prevRenderState, element); } protected HtmlInsets getDefaultMarginInsets() { HtmlInsets insets = new HtmlInsets(); RenderState prevRS = this.getPreviousRenderState(); FontMetrics fm = prevRS == null ? this.getFontMetrics() : prevRS.getFontMetrics(); insets.top = fm.getHeight(); insets.bottom = fm.getHeight(); insets.topType = HtmlInsets.TYPE_PIXELS; insets.bottomType = HtmlInsets.TYPE_PIXELS; return insets; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/PreRenderState.java0000644000175000017500000000345610750051540026765 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import org.lobobrowser.html.domimpl.HTMLElementImpl; public class PreRenderState extends BlockRenderState { public PreRenderState(RenderState prevRenderState, HTMLElementImpl element) { super(prevRenderState, element); } public int getWhiteSpace() { Integer ws = this.iWhiteSpace; if(ws != null) { return ws.intValue(); } AbstractCSS2Properties props = this.getCssProperties(); String whiteSpaceText = props == null ? null : props.getWhiteSpace(); int wsValue; if(whiteSpaceText == null) { wsValue = WS_PRE; } else { String whiteSpaceTextTL = whiteSpaceText.toLowerCase(); if("nowrap".equals(whiteSpaceTextTL)) { wsValue = WS_NOWRAP; } else if("normal".equals(whiteSpaceTextTL)) { wsValue = WS_NORMAL; } else { wsValue = WS_PRE; } } this.iWhiteSpace = new Integer(wsValue); return wsValue; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/RenderState.java0000644000175000017500000000766611130335414026323 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 16, 2005 */ package org.lobobrowser.html.style; import java.awt.*; /** * @author J. H. S. */ public interface RenderState { public static final int MASK_TEXTDECORATION_UNDERLINE = 1; public static final int MASK_TEXTDECORATION_OVERLINE = 2; public static final int MASK_TEXTDECORATION_LINE_THROUGH = 4; public static final int MASK_TEXTDECORATION_BLINK = 8; public static final int TEXTTRANSFORM_NONE = 0; public static final int TEXTTRANSFORM_CAPITALIZE = 1; public static final int TEXTTRANSFORM_UPPERCASE = 2; public static final int TEXTTRANSFORM_LOWERCASE = 4; // TODO how to handle style cascading? // public static final int TEXTTRANSFORM_INHERIT = 8; public static final int DISPLAY_NONE = 0; public static final int DISPLAY_INLINE = 1; public static final int DISPLAY_BLOCK = 2; public static final int DISPLAY_LIST_ITEM = 3; public static final int DISPLAY_TABLE_ROW = 4; public static final int DISPLAY_TABLE_CELL = 5; public static final int DISPLAY_TABLE = 6; public static final int WS_NORMAL = 0; public static final int WS_PRE = 1; public static final int WS_NOWRAP = 2; public static final int VISIBILITY_VISIBLE = 0; public static final int VISIBILITY_HIDDEN = 1; public static final int VISIBILITY_COLLAPSE = 2; public static final int POSITION_STATIC = 0; public static final int POSITION_ABSOLUTE = 1; public static final int POSITION_RELATIVE = 2; public static final int POSITION_FIXED = 3; public static final int FLOAT_NONE = 0; public static final int FLOAT_LEFT = 1; public static final int FLOAT_RIGHT = 2; public static final int OVERFLOW_NONE = 0; public static final int OVERFLOW_SCROLL = 1; public static final int OVERFLOW_AUTO = 2; public static final int OVERFLOW_HIDDEN = 3; public static final int OVERFLOW_VISIBLE = 4; public int getPosition(); public int getFloat(); public int getVisibility(); public Font getFont(); public int getFontBase(); public WordInfo getWordInfo(String word); public Color getColor(); public Color getBackgroundColor(); public Color getTextBackgroundColor(); public BackgroundInfo getBackgroundInfo(); public Color getOverlayColor(); public int getTextTransform(); public int getTextDecorationMask(); public FontMetrics getFontMetrics(); public int getBlankWidth(); public boolean isHighlight(); public void setHighlight(boolean highlight); public RenderState getPreviousRenderState(); public int getAlignXPercent(); public int getAlignYPercent(); public int getCount(String counter, int nesting); public int getDisplay(); public void resetCount(String counter, int nesting, int value); public int incrementCount(String counter, int nesting); public int getTextIndent(int availWidth); public String getTextIndentText(); public int getWhiteSpace(); public HtmlInsets getMarginInsets(); public HtmlInsets getPaddingInsets(); public int getOverflowX(); public int getOverflowY(); public void invalidate(); public BorderInfo getBorderInfo(); } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/RenderStateDelegator.java0000644000175000017500000000774711130344314030151 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Insets; public abstract class RenderStateDelegator implements RenderState { protected final RenderState delegate; public RenderStateDelegator(final RenderState delegate) { super(); this.delegate = delegate; } public RenderState getPreviousRenderState() { return this.delegate; } public int getAlignXPercent() { return delegate.getAlignXPercent(); } public int getAlignYPercent() { return delegate.getAlignYPercent(); } public int getBlankWidth() { return delegate.getBlankWidth(); } public Color getColor() { return delegate.getColor(); } public Font getFont() { return delegate.getFont(); } public int getFontBase() { return delegate.getFontBase(); } public FontMetrics getFontMetrics() { return delegate.getFontMetrics(); } public Color getOverlayColor() { return delegate.getOverlayColor(); } public Color getBackgroundColor() { return delegate.getBackgroundColor(); } public int getTextDecorationMask() { return delegate.getTextDecorationMask(); } public int getTextTransform() { return delegate.getTextTransform(); } public WordInfo getWordInfo(String word) { return delegate.getWordInfo(word); } public void invalidate() { delegate.invalidate(); } public boolean isHighlight() { return delegate.isHighlight(); } public void setHighlight(boolean highlight) { delegate.setHighlight(highlight); } public int getCount(String counter, int nesting) { return this.delegate.getCount(counter, nesting); } public void resetCount(String counter, int nesting, int value) { this.delegate.resetCount(counter, nesting, value); } public int incrementCount(String counter, int nesting) { return this.delegate.incrementCount(counter, nesting); } public BackgroundInfo getBackgroundInfo() { return this.delegate.getBackgroundInfo(); } public int getDisplay() { return this.delegate.getDisplay(); } public Color getTextBackgroundColor() { return this.delegate.getTextBackgroundColor(); } public int getTextIndent(int availWidth) { return this.delegate.getTextIndent(availWidth); } public String getTextIndentText() { return this.delegate.getTextIndentText(); } public int getWhiteSpace() { return this.delegate.getWhiteSpace(); } public HtmlInsets getMarginInsets() { return this.delegate.getMarginInsets(); } public HtmlInsets getPaddingInsets() { return this.delegate.getPaddingInsets(); } public int getVisibility() { return this.delegate.getVisibility(); } public int getPosition() { return this.delegate.getPosition(); } public int getFloat() { return this.delegate.getFloat(); } public int getOverflowX() { return this.delegate.getOverflowX(); } public int getOverflowY() { return this.delegate.getOverflowY(); } public BorderInfo getBorderInfo() { return this.delegate.getBorderInfo(); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/RenderThreadState.java0000644000175000017500000000263310726473504027455 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; /** * Additional state that may be set during rendering * to override state determined from elements. */ public class RenderThreadState { private static final ThreadLocal stateTL = new ThreadLocal(); public boolean overrideNoWrap; private RenderThreadState() { } public static RenderThreadState getState() { RenderThreadState ts = (RenderThreadState) stateTL.get(); if(ts == null) { ts = new RenderThreadState(); stateTL.set(ts); } return ts; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/StyleSheetAggregator.java0000644000175000017500000005471311124174352030177 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import java.net.MalformedURLException; import java.util.*; import org.lobobrowser.html.*; import org.lobobrowser.html.domimpl.HTMLDocumentImpl; import org.lobobrowser.html.domimpl.HTMLElementImpl; import org.w3c.dom.css.*; import org.w3c.dom.stylesheets.*; /** * Aggregates all style sheets in a document. * Every time a new STYLE element is found, it is * added to the style sheet aggreagator by means * of the {@link #addStyleSheet(CSSStyleSheet)} method. * HTML elements have a style object * that has a list of CSSStyleDeclaration * instances. The instances inserted in that list * are obtained by means of the {@link #getStyleDeclarations(HTMLElementImpl, String, String, String)} * method. */ public class StyleSheetAggregator { private final HTMLDocumentImpl document; private final Map classMapsByElement = new HashMap(); private final Map idMapsByElement = new HashMap(); private final Map rulesByElement = new HashMap(); public StyleSheetAggregator(HTMLDocumentImpl document) { this.document = document; } public final void addStyleSheets(Collection styleSheets) throws MalformedURLException { Iterator i = styleSheets.iterator(); while(i.hasNext()) { CSSStyleSheet sheet = (CSSStyleSheet) i.next(); this.addStyleSheet(sheet); } } private final void addStyleSheet(CSSStyleSheet styleSheet) throws MalformedURLException { CSSRuleList ruleList = styleSheet.getCssRules(); int length = ruleList.getLength(); for(int i = 0; i < length; i++) { CSSRule rule = ruleList.item(i); this.addRule(styleSheet, rule); } } private final void addRule(CSSStyleSheet styleSheet, CSSRule rule) throws MalformedURLException { HTMLDocumentImpl document = this.document; if(rule instanceof CSSStyleRule) { CSSStyleRule sr = (CSSStyleRule) rule; String selectorList = sr.getSelectorText(); StringTokenizer commaTok = new StringTokenizer(selectorList, ","); while(commaTok.hasMoreTokens()) { String selectorPart = commaTok.nextToken().toLowerCase(); ArrayList simpleSelectors = null; String lastSelectorText = null; StringTokenizer tok = new StringTokenizer(selectorPart, " \t\r\n"); if(tok.hasMoreTokens()) { simpleSelectors = new ArrayList(); SimpleSelector prevSelector = null; SELECTOR_FOR: for(;;) { String token = tok.nextToken(); if(">".equals(token)) { if(prevSelector != null) { prevSelector.setSelectorType(SimpleSelector.PARENT); } continue SELECTOR_FOR; } else if("+".equals(token)) { if(prevSelector != null) { prevSelector.setSelectorType(SimpleSelector.PRECEEDING_SIBLING); } continue SELECTOR_FOR; } int colonIdx = token.indexOf(':'); String simpleSelectorText = colonIdx == -1 ? token : token.substring(0, colonIdx); String pseudoElement = colonIdx == -1 ? null : token.substring(colonIdx+1); prevSelector = new SimpleSelector(simpleSelectorText, pseudoElement); simpleSelectors.add(prevSelector); if(!tok.hasMoreTokens()) { lastSelectorText = simpleSelectorText; break; } } } if(lastSelectorText != null) { int dotIdx = lastSelectorText.indexOf('.'); if(dotIdx != -1) { String elemtl = lastSelectorText.substring(0, dotIdx); String classtl = lastSelectorText.substring(dotIdx+1); this.addClassRule(elemtl, classtl, sr, simpleSelectors); } else { int poundIdx = lastSelectorText.indexOf('#'); if(poundIdx != -1) { String elemtl = lastSelectorText.substring(0, poundIdx); String idtl = lastSelectorText.substring(poundIdx+1); this.addIdRule(elemtl, idtl, sr, simpleSelectors); } else { String elemtl = lastSelectorText; this.addElementRule(elemtl, sr, simpleSelectors); } } } } //TODO: Attribute selectors } else if(rule instanceof CSSImportRule) { UserAgentContext uacontext = document.getUserAgentContext(); if(uacontext.isExternalCSSEnabled()) { CSSImportRule importRule = (CSSImportRule) rule; if(CSSUtilities.matchesMedia(importRule.getMedia(), uacontext)) { String href = importRule.getHref(); String styleHref = styleSheet.getHref(); String baseHref = styleHref == null ? document.getBaseURI() : styleHref; CSSStyleSheet sheet = CSSUtilities.parse(styleSheet.getOwnerNode(), href, document, baseHref, false); if(sheet != null) { this.addStyleSheet(sheet); } } } } else if(rule instanceof CSSMediaRule) { CSSMediaRule mrule = (CSSMediaRule) rule; MediaList mediaList = mrule.getMedia(); if(CSSUtilities.matchesMedia(mediaList, document.getUserAgentContext())) { CSSRuleList ruleList = mrule.getCssRules(); int length = ruleList.getLength(); for(int i = 0; i < length; i++) { CSSRule subRule = ruleList.item(i); this.addRule(styleSheet, subRule); } } } } private final void addClassRule(String elemtl, String classtl, CSSStyleRule styleRule, ArrayList ancestorSelectors) { Map classMap = (Map) this.classMapsByElement.get(elemtl); if(classMap == null) { classMap = new HashMap(); this.classMapsByElement.put(elemtl, classMap); } Collection rules = (Collection) classMap.get(classtl); if(rules == null) { rules = new LinkedList(); classMap.put(classtl, rules); } rules.add(new StyleRuleInfo(ancestorSelectors, styleRule)); } private final void addIdRule(String elemtl, String idtl, CSSStyleRule styleRule, ArrayList ancestorSelectors) { Map idsMap = (Map) this.idMapsByElement.get(elemtl); if(idsMap == null) { idsMap = new HashMap(); this.idMapsByElement.put(elemtl, idsMap); } Collection rules = (Collection) idsMap.get(idtl); if(rules == null) { rules = new LinkedList(); idsMap.put(idtl, rules); } rules.add(new StyleRuleInfo(ancestorSelectors, styleRule)); } private final void addElementRule(String elemtl, CSSStyleRule styleRule, ArrayList ancestorSelectors) { Collection rules = (Collection) this.rulesByElement.get(elemtl); if(rules == null) { rules = new LinkedList(); this.rulesByElement.put(elemtl, rules); } rules.add(new StyleRuleInfo(ancestorSelectors, styleRule)); } public final Collection getActiveStyleDeclarations(HTMLElementImpl element, String elementName, String elementId, String className, Set pseudoNames) { Collection styleDeclarations = null; String elementTL = elementName.toLowerCase(); Collection elementRules = (Collection) this.rulesByElement.get(elementTL); if(elementRules != null) { Iterator i = elementRules.iterator(); while(i.hasNext()) { StyleRuleInfo styleRuleInfo = (StyleRuleInfo) i.next(); if(styleRuleInfo.isSelectorMatch(element, pseudoNames)) { CSSStyleRule styleRule = styleRuleInfo.styleRule; CSSStyleSheet styleSheet = styleRule.getParentStyleSheet(); if(styleSheet != null && styleSheet.getDisabled()) { continue; } if(styleDeclarations == null) { styleDeclarations = new LinkedList(); } styleDeclarations.add(styleRule.getStyle()); } else { } } } elementRules = (Collection) this.rulesByElement.get("*"); if(elementRules != null) { Iterator i = elementRules.iterator(); while(i.hasNext()) { StyleRuleInfo styleRuleInfo = (StyleRuleInfo) i.next(); if(styleRuleInfo.isSelectorMatch(element, pseudoNames)) { CSSStyleRule styleRule = styleRuleInfo.styleRule; CSSStyleSheet styleSheet = styleRule.getParentStyleSheet(); if(styleSheet != null && styleSheet.getDisabled()) { continue; } if(styleDeclarations == null) { styleDeclarations = new LinkedList(); } styleDeclarations.add(styleRule.getStyle()); } } } if(className != null) { String classNameTL = className.toLowerCase(); Map classMaps = (Map) this.classMapsByElement.get(elementTL); if(classMaps != null) { Collection classRules = (Collection) classMaps.get(classNameTL); if(classRules != null) { Iterator i = classRules.iterator(); while(i.hasNext()) { StyleRuleInfo styleRuleInfo = (StyleRuleInfo) i.next(); if(styleRuleInfo.isSelectorMatch(element, pseudoNames)) { CSSStyleRule styleRule = styleRuleInfo.styleRule; CSSStyleSheet styleSheet = styleRule.getParentStyleSheet(); if(styleSheet != null && styleSheet.getDisabled()) { continue; } if(styleDeclarations == null) { styleDeclarations = new LinkedList(); } styleDeclarations.add(styleRule.getStyle()); } } } } classMaps = (Map) this.classMapsByElement.get("*"); if(classMaps != null) { Collection classRules = (Collection) classMaps.get(classNameTL); if(classRules != null) { Iterator i = classRules.iterator(); while(i.hasNext()) { StyleRuleInfo styleRuleInfo = (StyleRuleInfo) i.next(); if(styleRuleInfo.isSelectorMatch(element, pseudoNames)) { CSSStyleRule styleRule = styleRuleInfo.styleRule; CSSStyleSheet styleSheet = styleRule.getParentStyleSheet(); if(styleSheet != null && styleSheet.getDisabled()) { continue; } if(styleDeclarations == null) { styleDeclarations = new LinkedList(); } styleDeclarations.add(styleRule.getStyle()); } } } } } if(elementId != null) { Map idMaps = (Map) this.idMapsByElement.get(elementTL); if(idMaps != null) { String elementIdTL = elementId.toLowerCase(); Collection idRules = (Collection) idMaps.get(elementIdTL); if(idRules != null) { Iterator i = idRules.iterator(); while(i.hasNext()) { StyleRuleInfo styleRuleInfo = (StyleRuleInfo) i.next(); if(styleRuleInfo.isSelectorMatch(element, pseudoNames)) { CSSStyleRule styleRule = styleRuleInfo.styleRule; CSSStyleSheet styleSheet = styleRule.getParentStyleSheet(); if(styleSheet != null && styleSheet.getDisabled()) { continue; } if(styleDeclarations == null) { styleDeclarations = new LinkedList(); } styleDeclarations.add(styleRule.getStyle()); } } } } idMaps = (Map) this.idMapsByElement.get("*"); if(idMaps != null) { String elementIdTL = elementId.toLowerCase(); Collection idRules = (Collection) idMaps.get(elementIdTL); if(idRules != null) { Iterator i = idRules.iterator(); while(i.hasNext()) { StyleRuleInfo styleRuleInfo = (StyleRuleInfo) i.next(); if(styleRuleInfo.isSelectorMatch(element, pseudoNames)) { CSSStyleRule styleRule = styleRuleInfo.styleRule; CSSStyleSheet styleSheet = styleRule.getParentStyleSheet(); if(styleSheet != null && styleSheet.getDisabled()) { continue; } if(styleDeclarations == null) { styleDeclarations = new LinkedList(); } styleDeclarations.add(styleRule.getStyle()); } } } } } return styleDeclarations; } public final boolean affectedByPseudoNameInAncestor(HTMLElementImpl element, HTMLElementImpl ancestor, String elementName, String elementId, String[] classArray, String pseudoName) { String elementTL = elementName.toLowerCase(); Collection elementRules = (Collection) this.rulesByElement.get(elementTL); if(elementRules != null) { Iterator i = elementRules.iterator(); while(i.hasNext()) { StyleRuleInfo styleRuleInfo = (StyleRuleInfo) i.next(); CSSStyleSheet styleSheet = styleRuleInfo.styleRule.getParentStyleSheet(); if(styleSheet != null && styleSheet.getDisabled()) { continue; } if(styleRuleInfo.affectedByPseudoNameInAncestor(element, ancestor, pseudoName)) { return true; } } } elementRules = (Collection) this.rulesByElement.get("*"); if(elementRules != null) { Iterator i = elementRules.iterator(); while(i.hasNext()) { StyleRuleInfo styleRuleInfo = (StyleRuleInfo) i.next(); CSSStyleSheet styleSheet = styleRuleInfo.styleRule.getParentStyleSheet(); if(styleSheet != null && styleSheet.getDisabled()) { continue; } if(styleRuleInfo.affectedByPseudoNameInAncestor(element, ancestor, pseudoName)) { return true; } } } if(classArray != null) { for(int cidx = 0; cidx < classArray.length; cidx++) { String className = classArray[cidx]; String classNameTL = className.toLowerCase(); Map classMaps = (Map) this.classMapsByElement.get(elementTL); if(classMaps != null) { Collection classRules = (Collection) classMaps.get(classNameTL); if(classRules != null) { Iterator i = classRules.iterator(); while(i.hasNext()) { StyleRuleInfo styleRuleInfo = (StyleRuleInfo) i.next(); CSSStyleSheet styleSheet = styleRuleInfo.styleRule.getParentStyleSheet(); if(styleSheet != null && styleSheet.getDisabled()) { continue; } if(styleRuleInfo.affectedByPseudoNameInAncestor(element, ancestor, pseudoName)) { return true; } } } } classMaps = (Map) this.classMapsByElement.get("*"); if(classMaps != null) { Collection classRules = (Collection) classMaps.get(classNameTL); if(classRules != null) { Iterator i = classRules.iterator(); while(i.hasNext()) { StyleRuleInfo styleRuleInfo = (StyleRuleInfo) i.next(); CSSStyleSheet styleSheet = styleRuleInfo.styleRule.getParentStyleSheet(); if(styleSheet != null && styleSheet.getDisabled()) { continue; } if(styleRuleInfo.affectedByPseudoNameInAncestor(element, ancestor, pseudoName)) { return true; } } } } } } if(elementId != null) { Map idMaps = (Map) this.idMapsByElement.get(elementTL); if(idMaps != null) { String elementIdTL = elementId.toLowerCase(); Collection idRules = (Collection) idMaps.get(elementIdTL); if(idRules != null) { Iterator i = idRules.iterator(); while(i.hasNext()) { StyleRuleInfo styleRuleInfo = (StyleRuleInfo) i.next(); CSSStyleSheet styleSheet = styleRuleInfo.styleRule.getParentStyleSheet(); if(styleSheet != null && styleSheet.getDisabled()) { continue; } if(styleRuleInfo.affectedByPseudoNameInAncestor(element, ancestor, pseudoName)) { return true; } } } } idMaps = (Map) this.idMapsByElement.get("*"); if(idMaps != null) { String elementIdTL = elementId.toLowerCase(); Collection idRules = (Collection) idMaps.get(elementIdTL); if(idRules != null) { Iterator i = idRules.iterator(); while(i.hasNext()) { StyleRuleInfo styleRuleInfo = (StyleRuleInfo) i.next(); CSSStyleSheet styleSheet = styleRuleInfo.styleRule.getParentStyleSheet(); if(styleSheet != null && styleSheet.getDisabled()) { continue; } if(styleRuleInfo.affectedByPseudoNameInAncestor(element, ancestor, pseudoName)) { return true; } } } } } return false; } private static class StyleRuleInfo { private final CSSStyleRule styleRule; private final ArrayList ancestorSelectors; /** * @param selectors A collection of SimpleSelector's. * @param rule A CSS rule. */ public StyleRuleInfo(ArrayList simpleSelectors, CSSStyleRule rule) { super(); ancestorSelectors = simpleSelectors; styleRule = rule; } public final boolean affectedByPseudoNameInAncestor(HTMLElementImpl element, HTMLElementImpl ancestor, String pseudoName) { ArrayList as = this.ancestorSelectors; HTMLElementImpl currentElement = element; int size = as.size(); boolean first = true; for(int i = size; --i >= 0;) { SimpleSelector simpleSelector = (SimpleSelector) as.get(i); if(first) { if(ancestor == element) { return simpleSelector.hasPseudoName(pseudoName); } first = false; continue; } String selectorText = simpleSelector.simpleSelectorText; int dotIdx = selectorText.indexOf('.'); HTMLElementImpl newElement; if(dotIdx != -1) { String elemtl = selectorText.substring(0, dotIdx); String classtl = selectorText.substring(dotIdx+1); newElement = currentElement.getAncestorWithClass(elemtl, classtl); } else { int poundIdx = selectorText.indexOf('#'); if(poundIdx != -1) { String elemtl = selectorText.substring(0, poundIdx); String idtl = selectorText.substring(poundIdx+1); newElement = currentElement.getAncestorWithId(elemtl, idtl); } else { String elemtl = selectorText; newElement = currentElement.getAncestor(elemtl); } } if(newElement == null) { return false; } currentElement = newElement; if(currentElement == ancestor) { return simpleSelector.hasPseudoName(pseudoName); } } return false; } /** * * @param element The element to test for a match. * @param pseudoNames A set of pseudo-names in lowercase. */ private final boolean isSelectorMatch(HTMLElementImpl element, Set pseudoNames) { ArrayList as = this.ancestorSelectors; HTMLElementImpl currentElement = element; int size = as.size(); boolean first = true; for(int i = size; --i >= 0;) { SimpleSelector simpleSelector = (SimpleSelector) as.get(i); if(first) { if(!simpleSelector.matches(pseudoNames)) { return false; } first = false; continue; } String selectorText = simpleSelector.simpleSelectorText; int dotIdx = selectorText.indexOf('.'); int selectorType = simpleSelector.selectorType; HTMLElementImpl priorElement; if(dotIdx != -1) { String elemtl = selectorText.substring(0, dotIdx); String classtl = selectorText.substring(dotIdx+1); if(selectorType == SimpleSelector.ANCESTOR) { priorElement = currentElement.getAncestorWithClass(elemtl, classtl); } else if(selectorType == SimpleSelector.PARENT) { priorElement = currentElement.getParentWithClass(elemtl, classtl); } else if(selectorType == SimpleSelector.PRECEEDING_SIBLING) { priorElement = currentElement.getPreceedingSiblingWithClass(elemtl, classtl); } else { throw new IllegalStateException("selectorType=" + selectorType); } } else { int poundIdx = selectorText.indexOf('#'); if(poundIdx != -1) { String elemtl = selectorText.substring(0, poundIdx); String idtl = selectorText.substring(poundIdx+1); if(selectorType == SimpleSelector.ANCESTOR) { priorElement = currentElement.getAncestorWithId(elemtl, idtl); } else if(selectorType == SimpleSelector.PARENT) { priorElement = currentElement.getParentWithId(elemtl, idtl); } else if(selectorType == SimpleSelector.PRECEEDING_SIBLING) { priorElement = currentElement.getPreceedingSiblingWithId(elemtl, idtl); } else { throw new IllegalStateException("selectorType=" + selectorType); } } else { String elemtl = selectorText; if(selectorType == SimpleSelector.ANCESTOR) { priorElement = currentElement.getAncestor(elemtl); } else if(selectorType == SimpleSelector.PARENT) { priorElement = currentElement.getParent(elemtl); } else if(selectorType == SimpleSelector.PRECEEDING_SIBLING) { priorElement = currentElement.getPreceedingSibling(elemtl); } else { throw new IllegalStateException("selectorType=" + selectorType); } } } if(priorElement == null) { return false; } if(!simpleSelector.matches(priorElement)) { return false; } currentElement = priorElement; } return true; } } static class SimpleSelector { public static final int ANCESTOR = 0; public static final int PARENT = 1; public static final int PRECEEDING_SIBLING = 2; public final String simpleSelectorText; public final String pseudoElement; public int selectorType; /** * * @param simpleSelectorText Simple selector text in lower case. * @param pseudoElement The pseudo-element if any. */ public SimpleSelector(String simpleSelectorText, String pseudoElement) { super(); this.simpleSelectorText = simpleSelectorText; this.pseudoElement = pseudoElement; this.selectorType = ANCESTOR; } public final boolean matches(HTMLElementImpl element) { Set names = element.getPseudoNames(); if(names == null) { return this.pseudoElement == null; } else { String pe = this.pseudoElement; return pe == null || names.contains(pe); } } public final boolean matches(Set names) { if(names == null) { return this.pseudoElement == null; } else { String pe = this.pseudoElement; return pe == null || names.contains(pe); } } public final boolean matches(String pseudoName) { if(pseudoName == null) { return this.pseudoElement == null; } else { String pe = this.pseudoElement; return pe == null || pseudoName.equals(pe); } } public final boolean hasPseudoName(String pseudoName) { return pseudoName.equals(this.pseudoElement); } public int getSelectorType() { return selectorType; } public void setSelectorType(int selectorType) { this.selectorType = selectorType; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/StyleSheetRenderState.java0000644000175000017500000010035311134554610030325 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 16, 2005 */ package org.lobobrowser.html.style; import java.awt.*; import java.awt.font.TextAttribute; import java.util.*; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.util.gui.ColorFactory; import org.lobobrowser.util.gui.FontFactory; import org.w3c.dom.css.*; import org.w3c.dom.html2.*; /** * @author J. H. S. */ public class StyleSheetRenderState implements RenderState { private static final FontFactory FONT_FACTORY = FontFactory.getInstance(); // Default font needs to be something that displays in all languages. // Serif, SansSerif, Monospaced. private static final String DEFAULT_FONT_FAMILY = "SansSerif"; private static final Font DEFAULT_FONT = FONT_FACTORY.getFont(DEFAULT_FONT_FAMILY, null, null, null, HtmlValues.DEFAULT_FONT_SIZE, null, null); protected static final HtmlInsets INVALID_INSETS = new HtmlInsets(); protected static final BackgroundInfo INVALID_BACKGROUND_INFO = new BackgroundInfo(); protected static final BorderInfo INVALID_BORDER_INFO = new BorderInfo(); protected static final Color INVALID_COLOR = new Color(100, 0, 100); protected final HTMLElementImpl element; protected final HTMLDocumentImpl document; protected final RenderState prevRenderState; private Font iFont; private FontMetrics iFontMetrics; private Color iColor; private Color iBackgroundColor = INVALID_COLOR; private Color iTextBackgroundColor = INVALID_COLOR; private Color iOverlayColor = INVALID_COLOR; private int iTextDecoration = -1; private int iTextTransform = -1; private int iBlankWidth = -1; private boolean iHighlight; protected BackgroundInfo iBackgroundInfo = INVALID_BACKGROUND_INFO; static { } public StyleSheetRenderState(RenderState prevRenderState, HTMLElementImpl element) { this.prevRenderState = prevRenderState; this.element = element; this.document = (HTMLDocumentImpl) element.getOwnerDocument(); } public StyleSheetRenderState(HTMLDocumentImpl document) { this.prevRenderState = null; this.element = null; this.document = document; } // public TextRenderState(RenderState prevRenderState) { // this.css2properties = new CSS2PropertiesImpl(this); // this.prevRenderState = prevRenderState; // } protected int getDefaultDisplay() { return DISPLAY_INLINE; } private Integer iDisplay; public int getDisplay() { Integer d = this.iDisplay; if(d != null) { return d.intValue(); } CSS2Properties props = this.getCssProperties(); String displayText = props == null ? null : props.getDisplay(); int displayInt; if(displayText != null) { String displayTextTL = displayText.toLowerCase(); if("block".equals(displayTextTL)) { displayInt = DISPLAY_BLOCK; } else if("inline".equals(displayTextTL)) { displayInt = DISPLAY_INLINE; } else if("none".equals(displayTextTL)) { displayInt = DISPLAY_NONE; } else if("list-item".equals(displayTextTL)) { displayInt = DISPLAY_LIST_ITEM; } else if("table".equals(displayTextTL)) { displayInt = DISPLAY_TABLE; } else if("table-cell".equals(displayTextTL)) { displayInt = DISPLAY_TABLE_CELL; } else if("table-row".equals(displayTextTL)) { displayInt = DISPLAY_TABLE_ROW; } else { displayInt = this.getDefaultDisplay(); } } else { displayInt = this.getDefaultDisplay(); } d = new Integer(displayInt); this.iDisplay = d; return displayInt; } public RenderState getPreviousRenderState() { return this.prevRenderState; } public int getFontBase() { RenderState prs = this.prevRenderState; return prs == null ? 3 : prs.getFontBase(); } public void repaint() { // Dummy implementation } protected final AbstractCSS2Properties getCssProperties() { HTMLElementImpl element = this.element; return element == null ? null : element.getCurrentStyle(); } public void invalidate() { Map map = this.iWordInfoMap; if(map != null) { map.clear(); } this.iFont = null; this.iFontMetrics = null; this.iColor = null; this.iTextDecoration = -1; this.iBlankWidth = -1; this.alignXPercent = -1; this.iBackgroundColor = INVALID_COLOR; this.iTextBackgroundColor = INVALID_COLOR; this.iOverlayColor = INVALID_COLOR; this.iBackgroundInfo = INVALID_BACKGROUND_INFO; this.iDisplay = null; this.iTextIndentText = null; this.iWhiteSpace = null; this.marginInsets = INVALID_INSETS; this.paddingInsets = INVALID_INSETS; this.overflowX = -1; this.overflowY = -1; this.borderInfo = INVALID_BORDER_INFO; // Should NOT invalidate parent render state. } public Font getFont() { Font f = this.iFont; if(f != null) { return f; } AbstractCSS2Properties style = this.getCssProperties(); RenderState prs = this.prevRenderState; if(style == null) { if(prs != null) { f = prs.getFont(); this.iFont = f; return f; } f = DEFAULT_FONT; this.iFont = f; return f; } Float fontSize = null; String fontStyle = null; String fontVariant = null; String fontWeight = null; String fontFamily = null; String newFontSize = style == null ? null : style.getFontSize(); String newFontFamily = style == null ? null : style.getFontFamily(); String newFontStyle = style == null ? null : style.getFontStyle(); String newFontVariant = style == null ? null : style.getFontVariant(); String newFontWeight = style == null ? null : style.getFontWeight(); String verticalAlign = style == null ? null : style.getVerticalAlign(); boolean isSuper = verticalAlign != null && verticalAlign.equalsIgnoreCase("super"); boolean isSub = verticalAlign != null && verticalAlign.equalsIgnoreCase("sub"); if(newFontSize == null && newFontWeight == null && newFontStyle == null && newFontFamily == null && newFontVariant == null) { if (!isSuper && !isSub) { if(prs != null) { f = prs.getFont(); this.iFont = f; return f; } f = DEFAULT_FONT; this.iFont = f; return f; } } if(newFontSize != null) { try { fontSize = new Float(HtmlValues.getFontSize(newFontSize, prs)); } catch(Exception err) { fontSize = HtmlValues.DEFAULT_FONT_SIZE_BOX; } } else if(fontSize == null) { if(prs != null) { fontSize = new Float(prs.getFont().getSize()); } else { fontSize = HtmlValues.DEFAULT_FONT_SIZE_BOX; } } if(newFontFamily != null) { fontFamily = newFontFamily; } else if(fontFamily == null && prs != null) { fontFamily = prs.getFont().getFamily(); } if(fontFamily == null) { fontFamily = DEFAULT_FONT_FAMILY; } if(newFontStyle != null) { fontStyle = newFontStyle; } else if(fontStyle == null && prs != null) { int fstyle = prs.getFont().getStyle(); if((fstyle & Font.ITALIC) != 0) { fontStyle = "italic"; } } if(newFontVariant != null) { fontVariant = newFontVariant; } else if(prs != null) { // TODO: smallcaps? } if(newFontWeight != null) { fontWeight = newFontWeight; } else if(fontWeight == null && prs != null) { int fstyle = prs.getFont().getStyle(); if((fstyle & Font.BOLD) != 0) { fontWeight = "bold"; } } HTMLDocumentImpl document = this.document; Set locales = document == null ? null : document.getLocales(); Integer superscript = null; if(isSuper) { superscript = new Integer(1); } else if (isSub) { superscript = new Integer(-1); } if (superscript == null && prs != null){ superscript = (Integer) prs.getFont().getAttributes().get(TextAttribute.SUPERSCRIPT); } f = FONT_FACTORY.getFont(fontFamily, fontStyle, fontVariant, fontWeight, fontSize.floatValue(), locales, superscript); this.iFont = f; return f; } public Color getColor() { Color c = this.iColor; if(c != null) { return c; } AbstractCSS2Properties props = this.getCssProperties(); String colorValue = props == null ? null : props.getColor(); if(colorValue == null || "".equals(colorValue)) { RenderState prs = this.prevRenderState; if(prs != null) { c = prs.getColor(); this.iColor = c; return c; } else { colorValue = "black"; } } c = ColorFactory.getInstance().getColor(colorValue); this.iColor = c; return c; } public Color getBackgroundColor() { Color c = this.iBackgroundColor; if(c != INVALID_COLOR) { return c; } Color localColor; BackgroundInfo binfo = this.getBackgroundInfo(); localColor = binfo == null ? null : binfo.backgroundColor; if(localColor == null && this.getDisplay() == DISPLAY_INLINE) { RenderState prs = this.prevRenderState; if(prs != null) { Color ancestorColor = prs.getBackgroundColor(); if(ancestorColor != null) { this.iBackgroundColor = ancestorColor; return ancestorColor; } } } this.iBackgroundColor = localColor; return localColor; } public Color getTextBackgroundColor() { Color c = this.iTextBackgroundColor; if(c != INVALID_COLOR) { return c; } Color localColor; if(this.getDisplay() != DISPLAY_INLINE) { // Background painted by block. localColor = null; } else { BackgroundInfo binfo = this.getBackgroundInfo(); localColor = binfo == null ? null : binfo.backgroundColor; if(localColor == null) { RenderState prs = this.prevRenderState; if(prs != null) { Color ancestorColor = prs.getTextBackgroundColor(); if(ancestorColor != null) { this.iTextBackgroundColor = ancestorColor; return ancestorColor; } } } } this.iTextBackgroundColor = localColor; return localColor; } public Color getOverlayColor() { Color c = this.iOverlayColor; if(c != INVALID_COLOR) { return c; } AbstractCSS2Properties props = this.getCssProperties(); String colorValue = props == null ? null : props.getOverlayColor(); if(colorValue == null || colorValue.length() == 0) { RenderState prs = this.prevRenderState; if(prs != null) { c = prs.getOverlayColor(); this.iOverlayColor = c; return c; } else { colorValue = null; } } c = colorValue == null ? null : ColorFactory.getInstance().getColor(colorValue); this.iOverlayColor = c; return c; } public int getTextDecorationMask() { int td = this.iTextDecoration; if(td != -1) { return td; } AbstractCSS2Properties props = this.getCssProperties(); String tdText = props == null ? null : props.getTextDecoration(); if(tdText == null) { RenderState prs = this.prevRenderState; if(prs != null) { td = prs.getTextDecorationMask(); this.iTextDecoration = td; return td; } } td = 0; if(tdText != null) { StringTokenizer tok = new StringTokenizer(tdText.toLowerCase(), ", \t\n\r"); while(tok.hasMoreTokens()) { String token = tok.nextToken(); if("none".equals(token)) { // continue } else if("underline".equals(token)) { td |= StyleSheetRenderState.MASK_TEXTDECORATION_UNDERLINE; } else if("line-through".equals(token)) { td |= StyleSheetRenderState.MASK_TEXTDECORATION_LINE_THROUGH; } else if("blink".equals(token)) { td |= StyleSheetRenderState.MASK_TEXTDECORATION_BLINK; } else if("overline".equals(token)) { td |= StyleSheetRenderState.MASK_TEXTDECORATION_OVERLINE; } } } this.iTextDecoration = td; return td; } public int getTextTransform() { int tt = this.iTextTransform; if(tt != -1) { return tt; } AbstractCSS2Properties props = this.getCssProperties(); String tdText = props == null ? null : props.getTextTransform(); if(tdText == null) { RenderState prs = this.prevRenderState; if(prs != null) { tt = prs.getTextTransform(); this.iTextTransform = tt; return tt; } } tt = 0; if(tdText != null) { if("none".equals(tdText)) { // continue } else if("capitalize".equals(tdText)) { tt = TEXTTRANSFORM_CAPITALIZE; } else if("uppercase".equals(tdText)) { tt = TEXTTRANSFORM_UPPERCASE; } else if("lowercase".equals(tdText)) { tt = TEXTTRANSFORM_LOWERCASE; } // TODO how the explicit "inherit" value is to be handled? // Who is responsible for CSS cascading? // ... painting code? prevRenderState? // // else if("inherit".equals(tdText)) { // tt = TEXTTRANSFORM_INHERIT; // } } this.iTextTransform = tt; return tt; } public final FontMetrics getFontMetrics() { FontMetrics fm = this.iFontMetrics; if(fm == null) { //TODO getFontMetrics deprecated. How to get text width? fm = Toolkit.getDefaultToolkit().getFontMetrics(this.getFont()); this.iFontMetrics = fm; } return fm; } public int getBlankWidth() { int bw = this.iBlankWidth; if(bw == -1) { bw = this.getFontMetrics().charWidth(' '); this.iBlankWidth = bw; } return bw; } /** * @return Returns the iHighlight. */ public boolean isHighlight() { return this.iHighlight; } /** * @param highlight The iHighlight to set. */ public void setHighlight(boolean highlight) { this.iHighlight = highlight; } Map iWordInfoMap = null; public final WordInfo getWordInfo(String word) { // Expected to be called only in the GUI (rendering) thread. // No synchronization necessary. Map map = this.iWordInfoMap; if(map == null) { map = new HashMap(1); this.iWordInfoMap = map; } WordInfo wi = (WordInfo) map.get(word); if(wi != null) { return wi; } wi = new WordInfo(); FontMetrics fm = this.getFontMetrics(); wi.fontMetrics = fm; wi.ascentPlusLeading = fm.getAscent() + fm.getLeading(); wi.descent = fm.getDescent(); wi.height = fm.getHeight(); wi.width = fm.stringWidth(word); map.put(word, wi); return wi; } private int alignXPercent = -1; public int getAlignXPercent() { int axp = this.alignXPercent; if(axp != -1) { return axp; } CSS2Properties props = this.getCssProperties(); String textAlign = props == null ? null : props.getTextAlign(); if(textAlign == null || textAlign.length() == 0) { // Fall back to align attribute. HTMLElement element = this.element; if(element != null) { textAlign = element.getAttribute("align"); if(textAlign == null || textAlign.length() == 0) { RenderState prs = this.prevRenderState; if(prs != null) { return prs.getAlignXPercent(); } textAlign = null; } } } if(textAlign == null) { axp = 0; } else if("center".equalsIgnoreCase(textAlign)) { axp = 50; } else if("right".equalsIgnoreCase(textAlign)) { axp = 100; } else { //TODO: justify, axp = 0; } this.alignXPercent = axp; return axp; } public int getAlignYPercent() { // This is only settable in table cells. // TODO: Does it work with display: table-cell? return 0; } private Map counters = null; public int getCount(String counter, int nesting) { // Expected to be called only in GUI thread. RenderState prs = this.prevRenderState; if(prs != null) { return prs.getCount(counter, nesting); } Map counters = this.counters; if(counters == null) { return 0; } ArrayList counterArray = (ArrayList) counters.get(counter); if(nesting < 0 || nesting >= counterArray.size()) { return 0; } Integer integer = (Integer) counterArray.get(nesting); return integer == null ? 0 : integer.intValue(); } public void resetCount(String counter, int nesting, int value) { // Expected to be called only in the GUI thread. RenderState prs = this.prevRenderState; if(prs != null) { prs.resetCount(counter, nesting, value); } else { Map counters = this.counters; if(counters == null) { counters = new HashMap(2); this.counters = counters; counters.put(counter, new ArrayList(0)); } ArrayList counterArray = (ArrayList) counters.get(counter); while(counterArray.size() <= nesting) { counterArray.add(null); } counterArray.set(nesting, new Integer(value)); } } public int incrementCount(String counter, int nesting) { // Expected to be called only in the GUI thread. RenderState prs = this.prevRenderState; if(prs != null) { return prs.incrementCount(counter, nesting); } Map counters = this.counters; if(counters == null) { counters = new HashMap(2); this.counters = counters; counters.put(counter, new ArrayList(0)); } ArrayList counterArray = (ArrayList) counters.get(counter); while(counterArray.size() <= nesting) { counterArray.add(null); } Integer integer = (Integer) counterArray.get(nesting); int prevValue = integer == null ? 0 : integer.intValue(); counterArray.set(nesting, new Integer(prevValue + 1)); return prevValue; } public BackgroundInfo getBackgroundInfo() { BackgroundInfo binfo = this.iBackgroundInfo; if(binfo != INVALID_BACKGROUND_INFO) { return binfo; } binfo = null; AbstractCSS2Properties props = this.getCssProperties(); if(props != null) { String backgroundColorText = props.getBackgroundColor(); if(backgroundColorText != null) { if(binfo == null) { binfo = new BackgroundInfo(); } binfo.backgroundColor = ColorFactory.getInstance().getColor(backgroundColorText); } String backgroundImageText = props.getBackgroundImage(); if(backgroundImageText != null && backgroundImageText.length() > 0) { java.net.URL backgroundImage = HtmlValues.getURIFromStyleValue(backgroundImageText); if(backgroundImage != null) { if(binfo == null) { binfo = new BackgroundInfo(); } binfo.backgroundImage = backgroundImage; } } String backgroundRepeatText = props.getBackgroundRepeat(); if(backgroundRepeatText != null) { if(binfo == null) { binfo = new BackgroundInfo(); } this.applyBackgroundRepeat(binfo, backgroundRepeatText); } String backgroundPositionText = props.getBackgroundPosition(); if(backgroundPositionText != null) { if(binfo == null) { binfo = new BackgroundInfo(); } this.applyBackgroundPosition(binfo, backgroundPositionText); } } this.iBackgroundInfo = binfo; return binfo; } private String iTextIndentText = null; public String getTextIndentText() { String tiText = this.iTextIndentText; if(tiText != null) { return tiText; } AbstractCSS2Properties props = this.getCssProperties(); tiText = props == null ? null : props.getTextIndent(); if(tiText == null) { RenderState prs = this.prevRenderState; if(prs != null) { String parentText = prs.getTextIndentText(); this.iTextIndentText = parentText; return parentText; } else { tiText = ""; } } return tiText; } public int getTextIndent(int availSize) { // No caching for this one. String tiText = this.getTextIndentText(); if(tiText.length() == 0) { return 0; } else { return HtmlValues.getPixelSize(tiText, this, 0, availSize); } } protected Integer iWhiteSpace; public int getWhiteSpace() { if(RenderThreadState.getState().overrideNoWrap) { return WS_NOWRAP; } Integer ws = this.iWhiteSpace; if(ws != null) { return ws.intValue(); } AbstractCSS2Properties props = this.getCssProperties(); String whiteSpaceText = props == null ? null : props.getWhiteSpace(); int wsValue; if(whiteSpaceText == null) { RenderState prs = this.prevRenderState; if(prs != null) { wsValue = prs.getWhiteSpace(); } else { wsValue = WS_NORMAL; } } else { String whiteSpaceTextTL = whiteSpaceText.toLowerCase(); if("nowrap".equals(whiteSpaceTextTL)) { wsValue = WS_NOWRAP; } else if("pre".equals(whiteSpaceTextTL)) { wsValue = WS_PRE; } else { wsValue = WS_NORMAL; } } this.iWhiteSpace = new Integer(wsValue); return wsValue; } protected HtmlInsets marginInsets = INVALID_INSETS; protected HtmlInsets paddingInsets = INVALID_INSETS; public HtmlInsets getMarginInsets() { HtmlInsets mi = this.marginInsets; if(mi != INVALID_INSETS) { return mi; } AbstractCSS2Properties props = this.getCssProperties(); if(props == null) { mi = null; } else { mi = HtmlValues.getMarginInsets(props, this); } this.marginInsets = mi; return mi; } public HtmlInsets getPaddingInsets() { HtmlInsets mi = this.paddingInsets; if(mi != INVALID_INSETS) { return mi; } AbstractCSS2Properties props = this.getCssProperties(); if(props == null) { mi = null; } else { mi = HtmlValues.getPaddingInsets(props, this); this.paddingInsets = mi; } return mi; } private void applyBackgroundHorizontalPositon(BackgroundInfo binfo, String xposition) { if(xposition.endsWith("%")) { binfo.backgroundXPositionAbsolute = false; try { binfo.backgroundXPosition = (int) Double.parseDouble(xposition.substring(0, xposition.length() - 1).trim()); } catch(NumberFormatException nfe) { binfo.backgroundXPosition = 0; } } else if("center".equalsIgnoreCase(xposition)) { binfo.backgroundXPositionAbsolute = false; binfo.backgroundXPosition = 50; } else if("right".equalsIgnoreCase(xposition)) { binfo.backgroundXPositionAbsolute = false; binfo.backgroundXPosition = 100; } else if("left".equalsIgnoreCase(xposition)) { binfo.backgroundXPositionAbsolute = false; binfo.backgroundXPosition = 0; } else if("bottom".equalsIgnoreCase(xposition)) { // Can happen binfo.backgroundYPositionAbsolute = false; binfo.backgroundYPosition = 100; } else if("top".equalsIgnoreCase(xposition)) { // Can happen binfo.backgroundYPositionAbsolute = false; binfo.backgroundYPosition = 0; } else { binfo.backgroundXPositionAbsolute = true; binfo.backgroundXPosition = HtmlValues.getPixelSize(xposition, this, 0); } } private void applyBackgroundVerticalPosition(BackgroundInfo binfo, String yposition) { if(yposition.endsWith("%")) { binfo.backgroundYPositionAbsolute = false; try { binfo.backgroundYPosition = (int) Double.parseDouble(yposition.substring(0, yposition.length() - 1).trim()); } catch(NumberFormatException nfe) { binfo.backgroundYPosition = 0; } } else if("center".equalsIgnoreCase(yposition)) { binfo.backgroundYPositionAbsolute = false; binfo.backgroundYPosition = 50; } else if("bottom".equalsIgnoreCase(yposition)) { binfo.backgroundYPositionAbsolute = false; binfo.backgroundYPosition = 100; } else if("top".equalsIgnoreCase(yposition)) { binfo.backgroundYPositionAbsolute = false; binfo.backgroundYPosition = 0; } else if("right".equalsIgnoreCase(yposition)) { // Can happen binfo.backgroundXPositionAbsolute = false; binfo.backgroundXPosition = 100; } else if("left".equalsIgnoreCase(yposition)) { // Can happen binfo.backgroundXPositionAbsolute = false; binfo.backgroundXPosition = 0; } else { binfo.backgroundYPositionAbsolute = true; binfo.backgroundYPosition = HtmlValues.getPixelSize(yposition, this, 0); } } private void applyBackgroundPosition(BackgroundInfo binfo, String position) { binfo.backgroundXPositionAbsolute = false; binfo.backgroundYPositionAbsolute = false; binfo.backgroundXPosition = 50; binfo.backgroundYPosition = 50; StringTokenizer tok = new StringTokenizer(position, " \t\r\n"); if(tok.hasMoreTokens()) { String xposition = tok.nextToken(); this.applyBackgroundHorizontalPositon(binfo, xposition); if(tok.hasMoreTokens()) { String yposition = tok.nextToken(); this.applyBackgroundVerticalPosition(binfo, yposition); } } } // private void applyBackground(BackgroundInfo binfo, String background, CSSStyleDeclaration declaration) { // String[] tokens = HtmlValues.splitCssValue(background); // boolean hasXPosition = false; // for(int i = 0; i < tokens.length; i++) { // String token = tokens[i]; // if(ColorFactory.getInstance().isColor(token)) { // binfo.backgroundColor = ColorFactory.getInstance().getColor(token); // } // else if(HtmlValues.isUrl(token)) { // binfo.backgroundImage = HtmlValues.getURIFromStyleValue(token, declaration, this.document); // } // else if(isBackgroundRepeat(token)) { // this.applyBackgroundRepeat(binfo, token); // } // else if(isBackgroundPosition(token)) { // if(hasXPosition) { // this.applyBackgroundVerticalPosition(binfo, token); // } // else { // hasXPosition = true; // this.applyBackgroundHorizontalPositon(binfo, token); // } // } // } // } private void applyBackgroundRepeat(BackgroundInfo binfo, String backgroundRepeatText) { String brtl = backgroundRepeatText.toLowerCase(); if("repeat".equals(brtl)) { binfo.backgroundRepeat = BackgroundInfo.BR_REPEAT; } else if("repeat-x".equals(brtl)) { binfo.backgroundRepeat = BackgroundInfo.BR_REPEAT_X; } else if("repeat-y".equals(brtl)) { binfo.backgroundRepeat = BackgroundInfo.BR_REPEAT_Y; } else if("no-repeat".equals(brtl)) { binfo.backgroundRepeat = BackgroundInfo.BR_NO_REPEAT; } } private Integer cachedVisibility; public int getVisibility() { Integer v = this.cachedVisibility; if(v != null) { return v.intValue(); } AbstractCSS2Properties props = this.getCssProperties(); int visibility; if(props == null) { visibility = VISIBILITY_VISIBLE; } else { String visibText = props.getVisibility(); if(visibText == null || visibText.length() == 0) { visibility = VISIBILITY_VISIBLE; } else { String visibTextTL = visibText.toLowerCase(); if(visibTextTL.equals("hidden")) { visibility = VISIBILITY_HIDDEN; } else if(visibTextTL.equals("visible")) { visibility = VISIBILITY_VISIBLE; } else if(visibTextTL.equals("collapse")) { visibility = VISIBILITY_COLLAPSE; } else { visibility = VISIBILITY_VISIBLE; } } } this.cachedVisibility = new Integer(visibility); return visibility; } private Integer cachedPosition; public int getPosition() { Integer p = this.cachedPosition; if(p != null) { return p.intValue(); } AbstractCSS2Properties props = this.getCssProperties(); int position; if(props == null) { position = POSITION_STATIC; } else { String positionText = props.getPosition(); if(positionText == null || positionText.length() == 0) { position = POSITION_STATIC; } else { String positionTextTL = positionText.toLowerCase(); if(positionTextTL.equals("absolute")) { position = POSITION_ABSOLUTE; } else if(positionTextTL.equals("static")) { position = POSITION_STATIC; } else if(positionTextTL.equals("relative")) { position = POSITION_RELATIVE; } else if(positionTextTL.equals("fixed")) { position = POSITION_FIXED; } else { position = POSITION_STATIC; } } } this.cachedPosition = new Integer(position); return position; } private Integer cachedFloat; public int getFloat() { Integer p = this.cachedFloat; if(p != null) { return p.intValue(); } AbstractCSS2Properties props = this.getCssProperties(); int floatValue; if(props == null) { floatValue = FLOAT_NONE; } else { String floatText = props.getFloat(); if(floatText == null || floatText.length() == 0) { floatValue = FLOAT_NONE; } else { String floatTextTL = floatText.toLowerCase(); if(floatTextTL.equals("left")) { floatValue = FLOAT_LEFT; } else if(floatTextTL.equals("right")) { floatValue = FLOAT_RIGHT; } else { floatValue = FLOAT_NONE; } } } this.cachedFloat = new Integer(floatValue); return floatValue; } public String toString() { return "StyleSheetRenderState[font=" + this.getFont() + ",textDecoration=" + this.getTextDecorationMask() + "]"; } protected int overflowX = -1; protected int overflowY = -1; public int getOverflowX() { int overflow = this.overflowX; if(overflow != -1) { return overflow; } AbstractCSS2Properties props = this.getCssProperties(); if(props == null) { overflow = OVERFLOW_NONE; } else { String overflowText = props.getPropertyValue("overflow-x"); if(overflowText == null) { overflowText = props.getOverflow(); } if(overflowText == null) { overflow = OVERFLOW_NONE; } else { String overflowTextTL = overflowText.toLowerCase(); if("scroll".equals(overflowTextTL)) { overflow = OVERFLOW_SCROLL; } else if("auto".equals(overflowTextTL)) { overflow = OVERFLOW_AUTO; } else if("hidden".equals(overflowTextTL)) { overflow = OVERFLOW_HIDDEN; } else if("visible".equals(overflowTextTL)) { overflow = OVERFLOW_VISIBLE; } else { overflow = OVERFLOW_NONE; } } } this.overflowX = overflow; return overflow; } public int getOverflowY() { int overflow = this.overflowY; if(overflow != -1) { return overflow; } AbstractCSS2Properties props = this.getCssProperties(); if(props == null) { overflow = OVERFLOW_NONE; } else { String overflowText = props.getPropertyValue("overflow-y"); if(overflowText == null) { overflowText = props.getOverflow(); } if(overflowText == null) { overflow = OVERFLOW_NONE; } else { String overflowTextTL = overflowText.toLowerCase(); if("scroll".equals(overflowTextTL)) { overflow = OVERFLOW_SCROLL; } else if("auto".equals(overflowTextTL)) { overflow = OVERFLOW_AUTO; } else if("hidden".equals(overflowTextTL)) { overflow = OVERFLOW_HIDDEN; } else if("visible".equals(overflowTextTL)) { overflow = OVERFLOW_VISIBLE; } else { overflow = OVERFLOW_NONE; } } } this.overflowY = overflow; return overflow; } protected BorderInfo borderInfo = INVALID_BORDER_INFO; public BorderInfo getBorderInfo() { BorderInfo binfo = this.borderInfo; if(binfo != INVALID_BORDER_INFO) { return binfo; } AbstractCSS2Properties props = this.getCssProperties(); if(props != null) { binfo = HtmlValues.getBorderInfo(props, this); } else { binfo = null; } this.borderInfo = binfo; return binfo; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/TableCellRenderState.java0000644000175000017500000002004711127756766030106 0ustar twernertwernerpackage org.lobobrowser.html.style; import java.awt.Color; import java.awt.Insets; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.util.gui.ColorFactory; import org.w3c.dom.css.CSS2Properties; import org.w3c.dom.html2.*; public class TableCellRenderState extends DisplayRenderState { public TableCellRenderState(RenderState prevRenderState, HTMLElementImpl element) { super(prevRenderState, element, RenderState.DISPLAY_TABLE_CELL); } private int alignXPercent = -1; private int alignYPercent = -1; private BackgroundInfo backgroundInfo = INVALID_BACKGROUND_INFO; public void invalidate() { super.invalidate(); this.alignXPercent = -1; this.alignYPercent = -1; this.backgroundInfo = INVALID_BACKGROUND_INFO; this.paddingInsets = INVALID_INSETS; } public int getAlignXPercent() { int axp = this.alignXPercent; if(axp != -1) { return axp; } CSS2Properties props = this.getCssProperties(); if(props != null) { String textAlign = props.getTextAlign(); if(textAlign != null && textAlign.length() != 0) { return super.getAlignXPercent(); } } // Parent already knows about "align" attribute, but override because of TH. String align = this.element.getAttribute("align"); HTMLElement element = this.element; HTMLElement rowElement = null; Object parent = element.getParentNode(); if(parent instanceof HTMLElement) { rowElement = (HTMLElement) parent; } if(align == null || align.length() == 0) { if(rowElement != null) { align = rowElement.getAttribute("align"); if(align != null && align.length() == 0) { align = null; } } else { align = null; } } if(align == null) { if("TH".equalsIgnoreCase(element.getNodeName())) { axp = 50; } else { axp = 0; } } else if("center".equalsIgnoreCase(align) || "middle".equalsIgnoreCase(align)) { axp = 50; } else if("left".equalsIgnoreCase(align)) { axp = 0; } else if("right".equalsIgnoreCase(align)) { axp = 100; } else { // TODO: justify, etc. axp = 0; } this.alignXPercent = axp; return axp; } public int getAlignYPercent() { int ayp = this.alignYPercent; if(ayp != -1) { return ayp; } CSS2Properties props = this.getCssProperties(); if(props != null) { String textAlign = props.getVerticalAlign(); if(textAlign != null && textAlign.length() != 0) { return super.getAlignYPercent(); } } String valign = this.element.getAttribute("valign"); HTMLElement element = this.element; HTMLElement rowElement = null; Object parent = element.getParentNode(); if(parent instanceof HTMLElement) { rowElement = (HTMLElement) parent; } if(valign == null || valign.length() == 0) { if(rowElement != null) { valign = rowElement.getAttribute("valign"); if(valign != null && valign.length() == 0) { valign = null; } } else { valign = null; } } if(valign == null) { ayp = 50; } else if("top".equalsIgnoreCase(valign)) { ayp = 0; } else if("middle".equalsIgnoreCase(valign) || "center".equalsIgnoreCase(valign)) { ayp = 50; } else if("bottom".equalsIgnoreCase(valign)) { ayp = 100; } else { //TODO: baseline, etc. ayp = 50; } this.alignYPercent = ayp; return ayp; } public BackgroundInfo getBackgroundInfo() { BackgroundInfo binfo = this.backgroundInfo; if(binfo != INVALID_BACKGROUND_INFO) { return binfo; } // Apply style based on deprecated attributes. binfo = super.getBackgroundInfo(); HTMLTableCellElementImpl element = (HTMLTableCellElementImpl) this.element; HTMLTableRowElementImpl rowElement = null; Object parentNode = element.getParentNode(); if(parentNode instanceof HTMLTableRowElementImpl) { rowElement = (HTMLTableRowElementImpl) parentNode; } if(binfo == null || binfo.backgroundColor == null) { String bgColor = element.getBgColor(); if(bgColor == null || "".equals(bgColor)) { if(rowElement != null) { bgColor = rowElement.getBgColor(); } } if(bgColor != null && !"".equals(bgColor)) { Color bgc = ColorFactory.getInstance().getColor(bgColor); if(binfo == null) { binfo = new BackgroundInfo(); } binfo.backgroundColor = bgc; } } if(binfo == null || binfo.backgroundImage == null) { String background = element.getAttribute("background"); if(background != null && !"".equals(background)) { if(binfo == null) { binfo = new BackgroundInfo(); } binfo.backgroundImage = this.document.getFullURL(background); } } this.backgroundInfo = binfo; return binfo; } private HTMLTableElement getTableElement() { org.w3c.dom.Node ancestor = this.element.getParentNode(); while(ancestor != null && !(ancestor instanceof HTMLTableElement)) { ancestor = ancestor.getParentNode(); } return (HTMLTableElement) ancestor; } private HtmlInsets paddingInsets = INVALID_INSETS; public HtmlInsets getPaddingInsets() { HtmlInsets insets = this.paddingInsets; if(insets != INVALID_INSETS) { return insets; } insets = super.getPaddingInsets(); if(insets == null) { HTMLTableElement tableElement = this.getTableElement(); if(tableElement == null) { // Return without caching return null; } String cellPaddingText = tableElement.getAttribute("cellpadding"); if(cellPaddingText != null && cellPaddingText.length() != 0) { cellPaddingText = cellPaddingText.trim(); int cellPadding; int cellPaddingType; if(cellPaddingText.endsWith("%")) { cellPaddingType = HtmlInsets.TYPE_PERCENT; try { cellPadding = Integer.parseInt(cellPaddingText.substring(0, cellPaddingText.length()-1)); } catch(NumberFormatException nfe) { cellPadding = 0; } } else { cellPaddingType = HtmlInsets.TYPE_PIXELS; try { cellPadding = Integer.parseInt(cellPaddingText); } catch(NumberFormatException nfe) { cellPadding = 0; } } insets = new HtmlInsets(); insets.top = insets.left = insets.right = insets.bottom = cellPadding; insets.topType = insets.leftType = insets.rightType = insets.bottomType = cellPaddingType; } } this.paddingInsets = insets; return insets; } public int getWhiteSpace() { // Overrides super. if(RenderThreadState.getState().overrideNoWrap) { return WS_NOWRAP; } Integer ws = this.iWhiteSpace; if(ws != null) { return ws.intValue(); } AbstractCSS2Properties props = this.getCssProperties(); String whiteSpaceText = props == null ? null : props.getWhiteSpace(); int wsValue; if(whiteSpaceText == null) { HTMLElementImpl element = this.element; if(element != null && element.getAttributeAsBoolean("nowrap")) { wsValue = WS_NOWRAP; } else { RenderState prs = this.prevRenderState; if(prs != null) { wsValue = prs.getWhiteSpace(); } else { wsValue = WS_NORMAL; } } } else { String whiteSpaceTextTL = whiteSpaceText.toLowerCase(); if("nowrap".equals(whiteSpaceTextTL)) { wsValue = WS_NOWRAP; } else if("pre".equals(whiteSpaceTextTL)) { wsValue = WS_PRE; } else { wsValue = WS_NORMAL; } } if(wsValue == WS_NOWRAP) { // In table cells, if the width is defined as an absolute value, // nowrap has no effect (IE and FireFox behavior). HTMLElementImpl element = this.element; String width = props == null ? null : props.getWidth(); if(width == null) { width = element.getAttribute("width"); if(width != null && width.length() > 0 && !width.endsWith("%")) { wsValue = WS_NORMAL; } } else { if(!width.trim().endsWith("%")) { wsValue = WS_NORMAL; } } } this.iWhiteSpace = new Integer(wsValue); return wsValue; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/TableRenderState.java0000644000175000017500000001235311130412556027263 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; import java.awt.Color; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.util.gui.ColorFactory; public class TableRenderState extends StyleSheetRenderState { public TableRenderState(RenderState prevRenderState, HTMLElementImpl element) { super(prevRenderState, element); } public Color getTextBackgroundColor() { return super.getTextBackgroundColor(); } protected int getDefaultDisplay() { return DISPLAY_TABLE; } private BackgroundInfo backgroundInfo = INVALID_BACKGROUND_INFO; public void invalidate() { super.invalidate(); this.backgroundInfo = INVALID_BACKGROUND_INFO; } public BackgroundInfo getBackgroundInfo() { BackgroundInfo binfo = this.backgroundInfo; if(binfo != INVALID_BACKGROUND_INFO) { return binfo; } // Apply style based on deprecated attributes. binfo = super.getBackgroundInfo(); HTMLTableElementImpl element = (HTMLTableElementImpl) this.element; if(binfo == null || binfo.backgroundColor == null) { String bgColor = element.getBgColor(); if(bgColor != null && !"".equals(bgColor)) { Color bgc = ColorFactory.getInstance().getColor(bgColor); if(binfo == null) { binfo = new BackgroundInfo(); } binfo.backgroundColor = bgc; } } if(binfo == null || binfo.backgroundImage == null) { String background = element.getAttribute("background"); if(background != null && !"".equals(background)) { if(binfo == null) { binfo = new BackgroundInfo(); } binfo.backgroundImage = this.document.getFullURL(background); } } this.backgroundInfo = binfo; return binfo; } public BorderInfo getBorderInfo() { BorderInfo binfo = this.borderInfo; if(binfo != INVALID_BORDER_INFO) { return binfo; } binfo = super.getBorderInfo(); if(binfo == null || (binfo.topStyle == HtmlValues.BORDER_STYLE_NONE && binfo.bottomStyle == HtmlValues.BORDER_STYLE_NONE && binfo.leftStyle == HtmlValues.BORDER_STYLE_NONE && binfo.rightStyle == HtmlValues.BORDER_STYLE_NONE)) { if(binfo == null) { binfo = new BorderInfo(); } HTMLElementImpl element = this.element; if(element != null) { String border = element.getAttribute("border"); if(border != null) { border = border.trim(); int value; int valueType; if(border.endsWith("%")) { valueType = HtmlInsets.TYPE_PERCENT; try { value = Integer.parseInt(border.substring(0, border.length()-1)); } catch(NumberFormatException nfe) { value = 0; } } else { valueType = HtmlInsets.TYPE_PIXELS; try { value = Integer.parseInt(border); } catch(NumberFormatException nfe) { value = 0; } } HtmlInsets borderInsets = new HtmlInsets(); borderInsets.top = borderInsets.left = borderInsets.right = borderInsets.bottom = value; borderInsets.topType = borderInsets.leftType = borderInsets.rightType = borderInsets.bottomType = valueType; binfo.insets = borderInsets; if(binfo.topColor == null) { binfo.topColor = Color.LIGHT_GRAY; } if(binfo.leftColor == null) { binfo.leftColor = Color.LIGHT_GRAY; } if(binfo.rightColor == null) { binfo.rightColor = Color.GRAY; } if(binfo.bottomColor == null) { binfo.bottomColor = Color.GRAY; } if(value != 0) { binfo.topStyle = binfo.leftStyle = binfo.rightStyle = binfo.bottomStyle = HtmlValues.BORDER_STYLE_SOLID; } } } } this.borderInfo = binfo; return binfo; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/TextDecorationRenderState.java0000644000175000017500000000261410760263042031171 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.html.style; public class TextDecorationRenderState extends RenderStateDelegator { private int textDecorationMask; public TextDecorationRenderState(RenderState prevRenderState, int textDecorationMask) { super(prevRenderState); this.textDecorationMask = textDecorationMask; } public int getTextDecorationMask() { RenderState prs = this.delegate; int parentMask = prs == null ? 0 : prs.getTextDecorationMask(); return parentMask | this.textDecorationMask; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/style/WordInfo.java0000644000175000017500000000225310726473502025630 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 17, 2005 */ package org.lobobrowser.html.style; import java.awt.*; /** * @author J. H. S. */ class WordInfo { public FontMetrics fontMetrics; public int descent; public int ascentPlusLeading; public int width; public int height; } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/test/0000755000175000017500000000000011125630300023034 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/lobobrowser/html/test/CssParserTest.java0000644000175000017500000001355710760056632026475 0ustar twernertwernerpackage org.lobobrowser.html.test; import java.awt.BorderLayout; import java.awt.Container; import java.awt.HeadlessException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.*; import java.io.*; import java.util.logging.*; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.lobobrowser.html.*; import org.lobobrowser.html.gui.*; import org.lobobrowser.html.parser.*; import org.lobobrowser.html.style.*; import org.lobobrowser.util.io.*; import org.w3c.css.sac.*; import org.w3c.css.*; import org.w3c.dom.css.*; import com.steadystate.css.parser.CSSOMParser; /** * Tests only the CSS parser. */ public class CssParserTest extends JFrame { private static final Logger logger = Logger.getLogger(CssParserTest.class.getName()); private final HtmlPanel cssOutput; private final JTextArea textArea; public CssParserTest() throws HeadlessException { this("CSS Parser Test Tool"); } public CssParserTest(String title) throws HeadlessException { super(title); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = this.getContentPane(); contentPane.setLayout(new BorderLayout()); JPanel topPanel = new JPanel(); topPanel.setLayout(new BorderLayout()); JPanel bottomPanel = new JPanel(); bottomPanel.setLayout(new BorderLayout()); final JTextField textField = new JTextField(); JButton button = new JButton("Parse & Render"); final JTabbedPane tabbedPane = new JTabbedPane(); HtmlPanel htmlPanel = new HtmlPanel(); this.cssOutput = htmlPanel; contentPane.add(topPanel, BorderLayout.NORTH); contentPane.add(bottomPanel, BorderLayout.CENTER); topPanel.add(new JLabel("URL: "), BorderLayout.WEST); topPanel.add(textField, BorderLayout.CENTER); topPanel.add(button, BorderLayout.EAST); bottomPanel.add(tabbedPane, BorderLayout.CENTER); final JTextArea textArea = new JTextArea(); this.textArea = textArea; final JScrollPane textAreaSp = new JScrollPane(textArea); tabbedPane.addTab("Parsed CSS", htmlPanel); tabbedPane.addTab("Source Code", textAreaSp); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { process(textField.getText()); } }); } private void process(String uri) { try { URL url; try { url = new URL(uri); } catch(java.net.MalformedURLException mfu) { int idx = uri.indexOf(':'); if(idx == -1 || idx == 1) { // try file url = new URL("file:" + uri); } else { throw mfu; } } logger.info("process(): Loading URI=[" + uri + "]."); long time0 = System.currentTimeMillis(); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible;) Cobra/0.96.1+"); connection.setRequestProperty("Cookie", ""); if(connection instanceof HttpURLConnection) { HttpURLConnection hc = (HttpURLConnection) connection; hc.setInstanceFollowRedirects(true); int responseCode = hc.getResponseCode(); logger.info("process(): HTTP response code: " + responseCode); } InputStream in = connection.getInputStream(); byte[] content; try { content = IORoutines.load(in, 8192); } finally { in.close(); } String source = new String(content, "ISO-8859-1"); this.textArea.setText(source); long time1 = System.currentTimeMillis(); CSSOMParser parser = new CSSOMParser(); InputSource is = CSSUtilities.getCssInputSourceForStyleSheet(source, uri); CSSStyleSheet styleSheet = parser.parseStyleSheet(is); long time2 = System.currentTimeMillis(); logger.info("Parsed URI=[" + uri + "]: Parse elapsed: " + (time2 - time1) + " ms. Load elapsed: " + (time1 - time0) + " ms."); this.showStyleSheet(styleSheet); } catch(Exception err) { logger.log(Level.SEVERE, "Error trying to load URI=[" + uri + "].", err); this.clearCssOutput(); } } private void clearCssOutput() { this.cssOutput.clearDocument(); } private void showStyleSheet(CSSStyleSheet styleSheet) { StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); writer.println("

"); CSSRuleList ruleList = styleSheet.getCssRules(); int length = ruleList.getLength(); for(int i = 0; i < length; i++) { CSSRule rule = ruleList.item(i); writer.println("
Rule: type=" + rule.getType() + ",class=" + rule.getClass().getName() + "
"); writer.println("
"); this.writeRuleInfo(writer, rule); writer.println("
"); } writer.println("
"); writer.flush(); String html = stringWriter.toString(); HtmlRendererContext rcontext = new SimpleHtmlRendererContext(this.cssOutput); this.cssOutput.setHtml(html, "about:css", rcontext); } private void writeRuleInfo(PrintWriter writer, CSSRule rule) { if(rule instanceof CSSStyleRule) { CSSStyleRule styleRule = (CSSStyleRule) rule; writer.println("Selector: " + styleRule.getSelectorText()); writer.println("
"); writer.println("CSS Text: " + styleRule.getCssText()); } else if(rule instanceof CSSImportRule) { CSSImportRule styleRule = (CSSImportRule) rule; writer.println("HREF: " + styleRule.getHref()); writer.println("
"); writer.println("CSS Text: " + styleRule.getCssText()); } } public static void main(String[] args) { CssParserTest frame = new CssParserTest(); frame.setSize(800, 400); frame.setExtendedState(TestFrame.MAXIMIZED_BOTH); frame.setVisible(true); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/test/NodeTreeModel.java0000644000175000017500000000463610726473512026416 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 22, 2005 */ package org.lobobrowser.html.test; import javax.swing.event.TreeModelListener; import javax.swing.tree.*; import org.w3c.dom.*; class NodeTreeModel implements TreeModel { private final Node rootNode; /** * @param node */ public NodeTreeModel(Node node) { super(); rootNode = node; } public Object getRoot() { return this.rootNode; } public Object getChild(Object parent, int index) { Node parentNode = (Node) parent; return parentNode == null ? null : parentNode.getChildNodes().item(index); } public int getChildCount(Object parent) { Node parentNode = (Node) parent; return parentNode == null ? 0 : parentNode.getChildNodes().getLength(); } public boolean isLeaf(Object node) { if(node == this.rootNode) { return false; } Node domNode = (Node) node; return domNode == null ? true : domNode.getChildNodes().getLength() == 0; } public void valueForPathChanged(TreePath path, Object newValue) { } public int getIndexOfChild(Object parent, Object child) { Node parentNode = (Node) parent; NodeList nodeList = parentNode == null ? null : parentNode.getChildNodes(); if(nodeList == null) { return -1; } int length = nodeList.getLength(); for(int i = 0; i < length; i++) { if(nodeList.item(i) == child) { return i; } } return -1; } public void addTreeModelListener(TreeModelListener l) { // nop } public void removeTreeModelListener(TreeModelListener l) { // nop } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/test/ParserTest.java0000644000175000017500000001076510725771352026026 0ustar twernertwernerpackage org.lobobrowser.html.test; import java.awt.BorderLayout; import java.awt.Container; import java.awt.HeadlessException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.*; import java.io.*; import java.util.logging.*; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTree; import org.lobobrowser.html.*; import org.lobobrowser.html.parser.*; import org.lobobrowser.util.io.*; import org.w3c.dom.*; /** * Parser-only test frame. */ public class ParserTest extends JFrame { private static final Logger logger = Logger.getLogger(ParserTest.class.getName()); private final JTree tree; private final JTextArea textArea; public ParserTest() throws HeadlessException { this("HTML Parser-Only Test Tool"); } public ParserTest(String title) throws HeadlessException { super(title); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = this.getContentPane(); contentPane.setLayout(new BorderLayout()); JPanel topPanel = new JPanel(); topPanel.setLayout(new BorderLayout()); JPanel bottomPanel = new JPanel(); bottomPanel.setLayout(new BorderLayout()); final JTextField textField = new JTextField(); JButton button = new JButton("Parse & Render"); final JTabbedPane tabbedPane = new JTabbedPane(); final JTree tree = new JTree(); tree.setModel(null); final JScrollPane scrollPane = new JScrollPane(tree); this.tree = tree; contentPane.add(topPanel, BorderLayout.NORTH); contentPane.add(bottomPanel, BorderLayout.CENTER); topPanel.add(new JLabel("URL: "), BorderLayout.WEST); topPanel.add(textField, BorderLayout.CENTER); topPanel.add(button, BorderLayout.EAST); bottomPanel.add(tabbedPane, BorderLayout.CENTER); final JTextArea textArea = new JTextArea(); textArea.setEditable(false); this.textArea = textArea; final JScrollPane textAreaSp = new JScrollPane(textArea); tabbedPane.addTab("HTML DOM", scrollPane); tabbedPane.addTab("Source Code", textAreaSp); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { process(textField.getText()); } }); } private void process(String uri) { try { URL url; try { url = new URL(uri); } catch(java.net.MalformedURLException mfu) { int idx = uri.indexOf(':'); if(idx == -1 || idx == 1) { // try file url = new URL("file:" + uri); } else { throw mfu; } } logger.info("process(): Loading URI=[" + uri + "]."); long time0 = System.currentTimeMillis(); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible;) Cobra/0.96.1+"); connection.setRequestProperty("Cookie", ""); if(connection instanceof HttpURLConnection) { HttpURLConnection hc = (HttpURLConnection) connection; hc.setInstanceFollowRedirects(true); int responseCode = hc.getResponseCode(); logger.info("process(): HTTP response code: " + responseCode); } InputStream in = connection.getInputStream(); byte[] content; try { content = IORoutines.load(in, 8192); } finally { in.close(); } String source = new String(content, "ISO-8859-1"); this.textArea.setText(source); long time1 = System.currentTimeMillis(); InputStream bin = new ByteArrayInputStream(content); UserAgentContext ucontext = new SimpleUserAgentContext(); DocumentBuilderImpl builder = new DocumentBuilderImpl(ucontext); // Provide a proper URI, in case it was a file. String actualURI = url.toExternalForm(); // Should change to use proper charset. Document document = builder.parse(new InputSourceImpl(bin, actualURI, "ISO-8859-1")); long time2 = System.currentTimeMillis(); logger.info("Parsed URI=[" + uri + "]: Parse elapsed: " + (time2 - time1) + " ms. Load elapsed: " + (time1 - time0) + " ms."); this.tree.setModel(new NodeTreeModel(document)); } catch(Exception err) { logger.log(Level.SEVERE, "Error trying to load URI=[" + uri + "].", err); } } public static void main(String[] args) { ParserTest frame = new ParserTest(); frame.setSize(800, 400); frame.setExtendedState(TestFrame.MAXIMIZED_BOTH); frame.setVisible(true); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/test/SimpleBrowserFrame.java0000644000175000017500000000564011130610334027455 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 29, 2006 */ package org.lobobrowser.html.test; import java.awt.Component; import java.awt.Insets; import java.net.URL; import org.lobobrowser.html.*; import org.lobobrowser.html.gui.HtmlPanel; import org.w3c.dom.Document; /** * The SimpleBrowserFrame class implements * the {@link org.lobobrowser.html.BrowserFrame} interface. * It represents a browser frame component. * @see HtmlRendererContext#createBrowserFrame() */ public class SimpleBrowserFrame extends HtmlPanel implements BrowserFrame { /** The {@link HtmlRendererContext} associated with the browser frame. */ private final HtmlRendererContext rcontext; private final HtmlRendererContext parentRcontext; public SimpleBrowserFrame(HtmlRendererContext parentRcontext) { this.parentRcontext = parentRcontext; this.rcontext = this.createHtmlRendererContext(parentRcontext); } /** * Creates the {@link HtmlRendererContext} associated with this browser * frame. Override to use a specialized instance. * @param parentRcontext The parent context. */ protected HtmlRendererContext createHtmlRendererContext(HtmlRendererContext parentRcontext) { return new SimpleHtmlRendererContext(this, parentRcontext); } public HtmlRendererContext getHtmlRendererContext() { return this.rcontext; } public Component getComponent() { return this; } public void loadURL(URL url) { this.rcontext.navigate(url, "_this"); } public Document getContentDocument() { return (Document) this.getRootNode(); } public HtmlRendererContext getParentHtmlRendererContext() { return this.parentRcontext; } public void setDefaultMarginInsets(Insets insets) { // Current implementation is the frame HtmlPanel. super.setDefaultMarginInsets(insets); } public void setDefaultOverflowX(int overflowX) { super.setDefaultOverflowX(overflowX); } public void setDefaultOverflowY(int overflowY) { super.setDefaultOverflowY(overflowY); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/test/SimpleHtmlObject.java0000644000175000017500000000136310641432610027115 0ustar twernertwernerpackage org.lobobrowser.html.test; import java.awt.*; import javax.swing.*; import org.lobobrowser.html.HtmlObject; import org.w3c.dom.html2.*; /** * Simple implementation of {@link org.lobobrowser.html.HtmlObject}. */ public class SimpleHtmlObject extends JComponent implements HtmlObject { protected final HTMLElement element; public SimpleHtmlObject(HTMLElement element) { this.element = element; this.setLayout(new FlowLayout()); this.add(new JLabel("[" + element.getTagName() + "]")); } public void reset(int availWidth, int availHeight) { // nop } public void destroy() { } public Component getComponent() { return this; } public void resume() { } public void suspend() { } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/test/SimpleHtmlRendererContext.java0000644000175000017500000006423111130111750031016 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 22, 2005 */ package org.lobobrowser.html.test; import java.awt.Component; import java.awt.event.MouseEvent; import java.io.*; import java.net.*; import javax.swing.JOptionPane; import org.lobobrowser.html.*; import org.lobobrowser.html.domimpl.*; import org.lobobrowser.html.gui.HtmlPanel; import org.lobobrowser.html.parser.DocumentBuilderImpl; import org.lobobrowser.html.parser.InputSourceImpl; import org.lobobrowser.util.io.*; import org.lobobrowser.util.*; import org.w3c.dom.html2.*; import java.util.logging.*; /** * The SimpleHtmlRendererContext class implements * the {@link org.lobobrowser.html.HtmlRendererContext} interface. * Note that this class provides rudimentary implementations * of most callback methods. Overridding some of the methods * in this class will usually be necessary in a professional application. *

* A simple way to load a URL into the {@link HtmlPanel} of the * renderer context is to invoke {@link #navigate(String)}. */ public class SimpleHtmlRendererContext implements HtmlRendererContext { private static final Logger logger = Logger.getLogger(SimpleHtmlRendererContext.class.getName()); private final HtmlPanel htmlPanel; private final HtmlRendererContext parentRcontext; /** * Constructs a SimpleHtmlRendererContext. * @param contextComponent The component that will render HTML. * @deprecated Use constructor that takes HtmlPanel and UserAgentContext */ public SimpleHtmlRendererContext(HtmlPanel contextComponent) { this(contextComponent, (UserAgentContext) null); } /** * Constructs a SimpleHtmlRendererContext. * @param contextComponent The component that will render HTML. * @see SimpleUserAgentContext */ public SimpleHtmlRendererContext(HtmlPanel contextComponent, UserAgentContext ucontext) { super(); this.htmlPanel = contextComponent; this.parentRcontext = null; this.bcontext = ucontext; } /** * Constructs a SimpleHtmlRendererContext that is a child of another * {@link HtmlRendererContext}. * @param contextComponent The component that will render HTML. * @param parentRcontext The parent's renderer context. */ public SimpleHtmlRendererContext(HtmlPanel contextComponent, HtmlRendererContext parentRcontext) { super(); this.htmlPanel = contextComponent; this.parentRcontext = parentRcontext; this.bcontext = parentRcontext == null ? null : parentRcontext.getUserAgentContext(); } public HtmlPanel getHtmlPanel() { return this.htmlPanel; } private volatile String sourceCode; /** * Gets the source code of the current HTML document. */ public String getSourceCode() { return this.sourceCode; } /** * Gets a collection of current document frames, by querying * the document currently held by the local * {@link org.lobobrowser.html.gui.HtmlPanel} * instance. */ public HTMLCollection getFrames() { Object rootNode = this.htmlPanel.getRootNode(); if(rootNode instanceof HTMLDocumentImpl) { return ((HTMLDocumentImpl) rootNode).getFrames(); } else { return null; } } /** * Implements reload as navigation to current URL. * Override to implement a more robust reloading * mechanism. */ public void reload() { HTMLDocumentImpl document = (HTMLDocumentImpl) this.htmlPanel.getRootNode(); if(document != null) { try { URL url = new URL(document.getDocumentURI()); this.navigate(url, null); } catch(java.net.MalformedURLException throwable) { this.warn("reload(): Malformed URL", throwable); } } } /** * Implements the link click handler by invoking {@link #navigate(URL, String)}. */ public void linkClicked(HTMLElement linkNode, URL url, String target) { this.navigate(url, target); } /** * Gets the connection proxy used in {@link #navigate(URL, String)}. * This implementation calls {@link SimpleUserAgentContext#getProxy()} * if {@link #getUserAgentContext()} returns an instance assignable to {@link SimpleUserAgentContext}. * The method may be overridden to provide a different proxy setting. */ protected Proxy getProxy() { Object ucontext = this.getUserAgentContext(); if(ucontext instanceof SimpleUserAgentContext) { return ((SimpleUserAgentContext) ucontext).getProxy(); } return Proxy.NO_PROXY; } /** * Implements simple navigation with incremental * rendering by invoking {@link #submitForm(String, URL, String, String, FormInput[])} * with a GET request method. */ public void navigate(final URL href, String target) { this.submitForm("GET", href, target, null, null); } /** * Convenience method provided to allow loading a document into * the renderer. * @param fullURL The absolute URL of the document. * @see #navigate(URL, String) */ public void navigate(String fullURL) throws java.net.MalformedURLException { java.net.URL href = Urls.createURL(null, fullURL); this.navigate(href, "_this"); } /** * Implements simple navigation and form submission with incremental * rendering and target processing, including * frame lookup. Should be overridden to allow for * more robust browser navigation and form submission. *

* Notes: *

* @see #navigate(URL, String) */ public void submitForm(final String method, final java.net.URL action, final String target, final String enctype, final FormInput[] formInputs) { // This method implements simple incremental rendering. if(target != null) { HtmlRendererContext topCtx = this.getTop(); HTMLCollection frames = topCtx.getFrames(); if(frames != null) { org.w3c.dom.Node frame = frames.namedItem(target); if(logger.isLoggable(Level.INFO)) { logger.info("submitForm(): Frame matching target=" + target + " is " + frame); } if(frame instanceof FrameNode) { BrowserFrame bframe = ((FrameNode) frame).getBrowserFrame(); if(bframe == null) { throw new IllegalStateException("Frame node without a BrowserFrame instance: " + frame); } if(bframe.getHtmlRendererContext() != this) { bframe.loadURL(action); return; } } } String actualTarget = target.trim().toLowerCase(); if("_top".equals(actualTarget)) { this.getTop().navigate(action, null); return; } else if ("_parent".equals(actualTarget)) { HtmlRendererContext parent = this.getParent(); if(parent != null) { parent.navigate(action, null); return; } } else if("_blank".equals(actualTarget)) { this.open(action, "cobra.blank", "", false); return; } else if("_this".equals(actualTarget)) { // fall through } else { logger.warning("submitForm(): Link target unrecognized: " + actualTarget); } } // Make request asynchronously. if(this.isNavigationAsynchronous()) { new Thread() { public void run() { try { SimpleHtmlRendererContext.this.submitFormSync(method, action, target, enctype, formInputs); } catch (Exception err) { SimpleHtmlRendererContext.this.error( "navigate(): Error loading or parsing request.", err); } } }.start(); } else { try { SimpleHtmlRendererContext.this.submitFormSync(method, action, target, enctype, formInputs); } catch (Exception err) { SimpleHtmlRendererContext.this.error( "navigate(): Error loading or parsing request.", err); } } } /** * Indicates whether navigation (via {@link #submitForm(String, URL, String, String, FormInput[])}) should be asynchronous. * This overridable implementation returns true. */ protected boolean isNavigationAsynchronous() { return true; } /** * The connection currently opened by openSync() if any. */ protected URLConnection currentConnection; /** * Submits a form and/or navigates by making * a synchronous request. This method is invoked * by {@link #submitForm(String, URL, String, String, FormInput[])}. * @param method The request method. * @param action The action URL. * @param target The target identifier. * @param enctype The encoding type. * @param formInputs The form inputs. * @throws IOException * @throws org.xml.sax.SAXException * @see #submitForm(String, URL, String, String, FormInput[]) */ protected void submitFormSync(final String method, final java.net.URL action, final String target, String enctype, final FormInput[] formInputs) throws IOException, org.xml.sax.SAXException { final String actualMethod = method.toUpperCase(); URL resolvedURL; if("GET".equals(actualMethod) && formInputs != null) { boolean firstParam = true; //TODO: What about the userInfo part of the URL? URL noRefAction = new URL(action.getProtocol(), action.getHost(), action.getPort(), action.getFile()); StringBuffer newUrlBuffer = new StringBuffer(noRefAction.toExternalForm()); if(action.getQuery() == null) { newUrlBuffer.append("?"); } else { newUrlBuffer.append("&"); } for(int i = 0; i < formInputs.length; i++) { FormInput parameter = formInputs[i]; String name = parameter.getName(); String encName = URLEncoder.encode(name, "UTF-8"); if(parameter.isText()) { if(firstParam) { firstParam = false; } else { newUrlBuffer.append("&"); } String valueStr = parameter.getTextValue(); String encValue = URLEncoder.encode(valueStr, "UTF-8"); newUrlBuffer.append(encName); newUrlBuffer.append("="); newUrlBuffer.append(encValue); } else { logger.warning("postData(): Ignoring non-textual parameter " + name + " for GET."); } } resolvedURL = new java.net.URL(newUrlBuffer.toString()); } else { resolvedURL = action; } URL urlForLoading; if(resolvedURL.getProtocol().equalsIgnoreCase("file")) { // Remove query so it works. try { String ref = action.getRef(); String refText = ref == null || ref.length() == 0 ? "" : "#" + ref; urlForLoading = new URL(resolvedURL.getProtocol(), action.getHost(), action.getPort(), action.getPath() + refText); } catch(java.net.MalformedURLException throwable) { this.warn("malformed", throwable); urlForLoading = action; } } else { urlForLoading = resolvedURL; } if(logger.isLoggable(Level.INFO)) { logger.info("process(): Loading URI=[" + urlForLoading + "]."); } long time0 = System.currentTimeMillis(); // Using potentially different URL for loading. Proxy proxy = SimpleHtmlRendererContext.this.getProxy(); boolean isPost = "POST".equals(actualMethod); URLConnection connection = proxy == null || proxy == Proxy.NO_PROXY ? urlForLoading.openConnection() : urlForLoading.openConnection(proxy); this.currentConnection = connection; try { connection.setRequestProperty("User-Agent", getUserAgentContext().getUserAgent()); connection.setRequestProperty("Cookie", ""); if (connection instanceof HttpURLConnection) { HttpURLConnection hc = (HttpURLConnection) connection; hc.setRequestMethod(actualMethod); hc.setInstanceFollowRedirects(false); } if(isPost) { connection.setDoOutput(true); ByteArrayOutputStream bufOut = new ByteArrayOutputStream(); boolean firstParam = true; if(formInputs != null) { for(int i = 0; i < formInputs.length; i++) { FormInput parameter = formInputs[i]; String name = parameter.getName(); String encName = URLEncoder.encode(name, "UTF-8"); if(parameter.isText()) { if(firstParam) { firstParam = false; } else { bufOut.write((byte) '&'); } String valueStr = parameter.getTextValue(); String encValue = URLEncoder.encode(valueStr, "UTF-8"); bufOut.write(encName.getBytes("UTF-8")); bufOut.write((byte) '='); bufOut.write(encValue.getBytes("UTF-8")); } else { logger.warning("postData(): Ignoring non-textual parameter " + name + " for POST."); } } } // Do not add a line break to post content. Some servers // can be picky about that (namely, java.net). byte[] postContent = bufOut.toByteArray(); if(connection instanceof HttpURLConnection) { ((HttpURLConnection) connection).setFixedLengthStreamingMode(postContent.length); } connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //connection.setRequestProperty("Content-Length", String.valueOf(postContent.length)); OutputStream postOut = connection.getOutputStream(); postOut.write(postContent); postOut.flush(); } if (connection instanceof HttpURLConnection) { HttpURLConnection hc = (HttpURLConnection) connection; int responseCode = hc.getResponseCode(); if(logger.isLoggable(Level.INFO)) { logger.info("process(): HTTP response code: " + responseCode); } if(responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_SEE_OTHER) { String location = hc.getHeaderField("Location"); if(location == null) { logger.warning("No Location header in redirect from " + action + "."); } else { java.net.URL href; href = Urls.createURL(action, location); SimpleHtmlRendererContext.this.navigate(href, target); } return; } } InputStream in = connection.getInputStream(); try { SimpleHtmlRendererContext.this.sourceCode = null; long time1 = System.currentTimeMillis(); RecordedInputStream rin = new RecordedInputStream(in, 1000000); InputStream bin = new BufferedInputStream(rin, 8192); String actualURI = urlForLoading.toExternalForm(); // Only create document, don't parse. HTMLDocumentImpl document = this.createDocument(new InputSourceImpl(bin, actualURI, getDocumentCharset(connection))); // Set document in HtmlPanel. Safe to call outside GUI thread. HtmlPanel panel = htmlPanel; panel.setDocument(document, SimpleHtmlRendererContext.this); // Now start loading. document.load(); long time2 = System.currentTimeMillis(); if(logger.isLoggable(Level.INFO)) { logger.info("Parsed URI=[" + urlForLoading + "]: Parse elapsed: " + (time2 - time1) + " ms. Connection elapsed: " + (time1 - time0) + " ms."); } String ref = urlForLoading.getRef(); if(ref != null && ref.length() != 0) { panel.scrollToElement(ref); } try { SimpleHtmlRendererContext.this.sourceCode = rin.getString("ISO-8859-1"); } catch(BufferExceededException bee) { SimpleHtmlRendererContext.this.sourceCode = "[TOO BIG]"; } } finally { in.close(); } } finally { this.currentConnection = null; } } /** * Creates a blank document instance. This method * is invoked whenever navigation or form submission * occur. It is provided so it can be overridden * to create specialized document implmentations. * @param inputSource The document input source. * @throws IOException * @throws org.xml.sax.SAXException */ protected HTMLDocumentImpl createDocument(org.xml.sax.InputSource inputSource) throws IOException, org.xml.sax.SAXException { DocumentBuilderImpl builder = new DocumentBuilderImpl(this.getUserAgentContext(), SimpleHtmlRendererContext.this); return (HTMLDocumentImpl) builder.createDocument(inputSource); } /** * This method is invoked by {@link #submitForm(String, URL, String, String, FormInput[])} * to determine the charset of a document. The charset is determined by looking * at the Content-Type header. * @param connection A URL connection. */ protected String getDocumentCharset(URLConnection connection) { String encoding = Urls.getCharset(connection); return encoding == null ? "ISO-8859-1" : encoding; } // Methods useful to Window below: /** * Opens a simple message dialog. */ public void alert(String message) { JOptionPane.showMessageDialog(this.htmlPanel, message); } /** * It should give up focus on the current browser window. This implementation does nothing * and should be overridden. */ public void blur() { this.warn("back(): Not overridden"); } /** * It should close the current browser window. This implementation does nothing * and should be overridden. */ public void close() { this.warn("close(): Not overridden"); } /** * Opens a simple confirmation window. */ public boolean confirm(String message) { int retValue = JOptionPane.showConfirmDialog(htmlPanel, message, "Confirm", JOptionPane.YES_NO_OPTION); return retValue == JOptionPane.YES_OPTION; } /** * It should request focus for the current browser window. This implementation does nothing * and should be overridden. */ public void focus() { this.warn("focus(): Not overridden"); } /** * @deprecated Use {@link #open(URL, String, String, boolean)}. */ public final HtmlRendererContext open(String url, String windowName, String windowFeatures, boolean replace) { URL urlObj; try { urlObj = new URL(url); } catch(MalformedURLException mfu) { throw new IllegalArgumentException("Malformed URL: " + url); } return this.open(urlObj, windowName, windowFeatures, replace); } /** * It should open a new browser window. This implementation does nothing * and should be overridden. * @param url The requested URL. * @param windowName A window identifier. * @param windowFeatures Window features specified in a format equivalent to * that of window.open() in Javascript. * @param replace Whether an existing window with the same name should be replaced. */ public HtmlRendererContext open(java.net.URL url, String windowName, String windowFeatures, boolean replace) { this.warn("open(): Not overridden"); return null; } /** * Shows a simple prompt dialog. */ public String prompt(String message, String inputDefault) { return JOptionPane.showInputDialog(htmlPanel, message); } /** * Changes the origin of the HTML block's scrollable area * according to the position given. *

* This method may be called outside of the GUI thread. * The operation is scheduled immediately in that thread as needed. * @param x The new x coordinate for the origin. * @param y The new y coordinate for the origin. */ public void scroll(int x, int y) { this.htmlPanel.scroll(x, y); } public void scrollBy(int x, int y) { this.htmlPanel.scrollBy(x, y); } /** * Should return true if and only if the current browser window is closed. * This implementation returns false and should be overridden. */ public boolean isClosed() { this.warn("isClosed(): Not overridden"); return false; } /** * Should return true if and only if the current browser window is closed. * This implementation returns false and should be overridden. */ public String getDefaultStatus() { this.warn("getDefaultStatus(): Not overridden"); return ""; } /** * It should return the name of the browser window, if this * renderer context is for the top frame in the window. This * implementation returns a blank string, so it should be overridden. */ public String getName() { this.warn("getName(): Not overridden"); return ""; } public HtmlRendererContext getParent() { return this.parentRcontext; } private volatile HtmlRendererContext opener; public HtmlRendererContext getOpener() { return this.opener; } public void setOpener(HtmlRendererContext opener) { this.opener = opener; } public String getStatus() { this.warn("getStatus(): Not overridden"); return ""; } public void setStatus(String message) { this.warn("setStatus(): Not overridden"); } public HtmlRendererContext getTop() { HtmlRendererContext ancestor = this.parentRcontext; if(ancestor == null) { return this; } return ancestor.getTop(); } public BrowserFrame createBrowserFrame() { return new SimpleBrowserFrame(this); } public void warn(String message, Throwable throwable) { if(logger.isLoggable(Level.WARNING)) { logger.log(Level.WARNING, message, throwable); } } public void error(String message, Throwable throwable) { if(logger.isLoggable(Level.SEVERE)) { logger.log(Level.SEVERE, message, throwable); } } public void warn(String message) { if(logger.isLoggable(Level.WARNING)) { logger.log(Level.WARNING, message); } } public void error(String message) { if(logger.isLoggable(Level.SEVERE)) { logger.log(Level.SEVERE, message); } } /** * Returns null. This method should be overridden * to provide OBJECT, EMBED or APPLET functionality. */ public HtmlObject getHtmlObject(HTMLElement element) { return null; } public void setDefaultStatus(String message) { this.warn("setDefaultStatus(): Not overridden."); } private UserAgentContext bcontext = null; /** * If a {@link org.lobobrowser.html.UserAgentContext} instance * was provided in the constructor, then that instance is returned. * Otherwise, an instance of {@link SimpleUserAgentContext} is * created and returned. *

* The context returned by this method is used by local request * facilities and other parts of the renderer. */ public UserAgentContext getUserAgentContext() { synchronized(this) { if(this.bcontext == null) { this.warn("getUserAgentContext(): UserAgentContext not provided in constructor. Creating a simple one."); this.bcontext = new SimpleUserAgentContext(); } return this.bcontext; } } /** * Should be overridden to return true if the link * has been visited. */ public boolean isVisitedLink(HTMLLinkElement link) { return false; } /** * This method must be overridden to implement a context menu. */ public boolean onContextMenu(HTMLElement element, MouseEvent event) { return true; } /** * This method can be overridden to receive notifications when the * mouse leaves an element. */ public void onMouseOut(HTMLElement element, MouseEvent event) { } /** * This method can be overridden to receive notifications when the * mouse first enters an element. */ public void onMouseOver(HTMLElement element, MouseEvent event) { } public boolean isImageLoadingEnabled() { return true; } public boolean onDoubleClick(HTMLElement element, MouseEvent event) { return true; } public boolean onMouseClick(HTMLElement element, MouseEvent event) { return true; } private static java.awt.Window getWindow(Component c) { java.awt.Component current = c; while(current != null && !(current instanceof java.awt.Window)) { current = current.getParent(); } return (java.awt.Window) current; } public void resizeBy(int byWidth, int byHeight) { java.awt.Window window = getWindow(this.htmlPanel); if(window != null) { window.setSize(window.getWidth() + byWidth, window.getHeight() + byHeight); } } public void resizeTo(int width, int height) { java.awt.Window window = getWindow(this.htmlPanel); if(window != null) { window.setSize(width, height); } } /** * It should navigate back one page. This implementation does nothing * and should be overridden. */ public void back() { if(logger.isLoggable(Level.WARNING)) { logger.log(Level.WARNING, "back() does nothing, unless overridden."); } } public void forward() { if(logger.isLoggable(Level.WARNING)) { logger.log(Level.WARNING, "forward() does nothing, unless overridden."); } } public String getCurrentURL() { Object node = this.htmlPanel.getRootNode(); if(node instanceof HTMLDocumentImpl) { HTMLDocumentImpl doc = (HTMLDocumentImpl) node; return doc.getDocumentURI(); } return null; } public int getHistoryLength() { return 0; } public String getNextURL() { return null; } public String getPreviousURL() { return null; } public void goToHistoryURL(String url) { if(logger.isLoggable(Level.WARNING)) { logger.log(Level.WARNING, "goToHistoryURL() does nothing, unless overridden."); } } public void moveInHistory(int offset) { if(logger.isLoggable(Level.WARNING)) { logger.log(Level.WARNING, "moveInHistory() does nothing, unless overridden."); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/test/SimpleHttpRequest.java0000644000175000017500000002527510764553746027406 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Nov 19, 2005 */ package org.lobobrowser.html.test; import java.awt.Image; import java.awt.Toolkit; import java.io.*; import java.net.*; import java.util.EventObject; import java.util.Map; import java.util.logging.*; import javax.xml.parsers.DocumentBuilderFactory; import org.lobobrowser.html.*; import org.lobobrowser.util.*; import org.lobobrowser.util.io.IORoutines; import org.w3c.dom.Document; /** * The SimpleHttpRequest class implements * the {@link org.lobobrowser.html.HttpRequest} interface. * The HttpRequest implementation provided * by this class is simple, with no caching. It creates * a new thread for each new asynchronous request. * @author J. H. S. */ public class SimpleHttpRequest implements HttpRequest { private static final Logger logger = Logger.getLogger(SimpleHttpRequest.class.getName()); private int readyState; private int status; private String statusText; private byte[] responseBytes; private final UserAgentContext context; private final Proxy proxy; private boolean isAsync; private java.net.URL requestURL; protected String requestMethod; protected String requestUserName; protected String requestPassword; /** * The URLConnection is assigned to * this field while it is ongoing. */ protected java.net.URLConnection connection; /** * Response headers are set in this map after * a response is received. */ protected java.util.Map responseHeadersMap; /** * Response headers are set in this string after * a response is received. */ protected String responseHeaders; public SimpleHttpRequest(UserAgentContext context, java.net.Proxy proxy) { super(); this.context = context; this.proxy = proxy; } public synchronized int getReadyState() { return this.readyState; } public synchronized String getResponseText() { byte[] bytes = this.responseBytes; java.net.URLConnection connection = this.connection; String encoding = connection == null ? "ISO-8859-1" : Urls.getCharset(connection); if(encoding == null) { encoding = "ISO-8859-1"; } try { return bytes == null ? null : new String(bytes, encoding); } catch(UnsupportedEncodingException uee) { logger.log(Level.WARNING, "getResponseText(): Charset '" + encoding + "' did not work. Retrying with ISO-8859-1.", uee); try { return new String(bytes, "ISO-8859-1"); } catch(UnsupportedEncodingException uee2) { // Ignore this time return null; } } } public synchronized Document getResponseXML() { byte[] bytes = this.responseBytes; if(bytes == null) { return null; } java.io.InputStream in = new ByteArrayInputStream(bytes); try { return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in); } catch(Exception err) { logger.log(Level.WARNING, "Unable to parse response as XML.", err); return null; } } public synchronized byte[] getResponseBytes() { return this.responseBytes; } /* (non-Javadoc) * @see org.xamjwg.html.HttpRequest#getResponseImage() */ public synchronized Image getResponseImage() { byte[] bytes = this.responseBytes; if(bytes == null) { return null; } return Toolkit.getDefaultToolkit().createImage(bytes); } public synchronized int getStatus() { return this.status; } public synchronized String getStatusText() { return this.statusText; } public void abort() { URLConnection c; synchronized(this) { c = this.connection; } if(c instanceof HttpURLConnection) { ((HttpURLConnection) c).disconnect(); } else if(c != null) { try { c.getInputStream().close(); } catch(IOException ioe) { ioe.printStackTrace(); } } } public synchronized String getAllResponseHeaders() { return this.responseHeaders; } public synchronized String getResponseHeader(String headerName) { Map headers = this.responseHeadersMap; return headers == null ? null : (String) headers.get(headerName); } public void open(String method, String url) throws IOException { this.open(method, url, true); } public void open(String method, URL url) throws IOException { this.open(method, url, true, null, null); } public void open(String method, URL url, boolean asyncFlag) throws IOException { this.open(method, url, asyncFlag, null, null); } public void open(String method, String url, boolean asyncFlag) throws IOException { URL urlObj = Urls.createURL(null, url); this.open(method, urlObj, asyncFlag, null); } public void open(String method, java.net.URL url, boolean asyncFlag, String userName) throws IOException { this.open(method, url, asyncFlag, userName, null); } /** * Opens the request. Call {@link #send(String)} to complete it. * @param method The request method. * @param url The request URL. * @param asyncFlag Whether the request should be asynchronous. * @param userName The user name of the request (not supported.) * @param password The password of the request (not supported.) */ public void open(final String method, final java.net.URL url, boolean asyncFlag, final String userName, final String password) throws java.io.IOException { this.abort(); Proxy proxy = this.proxy; URLConnection c = proxy == null || proxy == Proxy.NO_PROXY ? url.openConnection() : url.openConnection(proxy); synchronized(this) { this.connection = c; this.isAsync = asyncFlag; this.requestMethod = method; this.requestURL = url; this.requestUserName = userName; this.requestPassword = password; } this.changeState(HttpRequest.STATE_LOADING, 0, null, null); } /** * Sends POST content, if any, and causes the request * to proceed. *

* In the case of asynchronous requests, a new thread * is created. * @param content POST content or null if there's no such content. */ public void send(final String content) throws java.io.IOException { final java.net.URL url = this.requestURL; if(url == null) { throw new IOException("No URL has been provided."); } if(this.isAsync) { // Should use a thread pool instead new Thread("SimpleHttpRequest-" + url.getHost()) { public void run() { try { sendSync(content); } catch(Throwable thrown) { logger.log(Level.WARNING, "send(): Error in asynchronous request on " + url, thrown); } } }.start(); } else { sendSync(content); } } /** * This is the charset used to post data provided * to {@link #send(String)}. It returns "UTF-8" unless overridden. */ protected String getPostCharset() { return "UTF-8"; } /** * This is a synchronous implementation of {@link #send(String)} method * functionality. * It may be overridden to change the behavior of the class. * @param content POST content if any. It may be null. * @throws IOException */ protected void sendSync(String content) throws IOException { try { // FireFox posts a "loading" state twice as well. this.changeState(HttpRequest.STATE_LOADING, 0, null, null); URLConnection c; synchronized(this) { c = this.connection; } c.setRequestProperty("User-Agent", this.context.getUserAgent()); int istatus; String istatusText; java.io.InputStream err; if(c instanceof HttpURLConnection) { HttpURLConnection hc = (HttpURLConnection) c; String method = this.requestMethod; if(method == null) { throw new java.io.IOException("Null method."); } method = method.toUpperCase(); hc.setRequestMethod(method); if("POST".equals(method) && content != null) { hc.setDoOutput(true); byte[] contentBytes = content.getBytes(this.getPostCharset()); hc.setFixedLengthStreamingMode(contentBytes.length); OutputStream out = hc.getOutputStream(); try { out.write(contentBytes); } finally { out.flush(); } } istatus = hc.getResponseCode(); istatusText = hc.getResponseMessage(); err = hc.getErrorStream(); } else { istatus = 0; istatusText = ""; err = null; } synchronized(this) { this.responseHeaders = this.getAllResponseHeaders(c); this.responseHeadersMap = c.getHeaderFields(); } this.changeState(HttpRequest.STATE_LOADED, istatus, istatusText, null); java.io.InputStream in = err == null ? c.getInputStream() : err; int contentLength = c.getContentLength(); //TODO: In the "interactive" state, some response text is supposed to be available. this.changeState(HttpRequest.STATE_INTERACTIVE, istatus, istatusText, null); byte[] bytes = IORoutines.load(in, contentLength == -1 ? 4096 : contentLength); this.changeState(HttpRequest.STATE_COMPLETE, istatus, istatusText, bytes); } finally { synchronized(this) { this.connection = null; } } } private final EventDispatch readyEvent = new EventDispatch(); public void addReadyStateChangeListener(final ReadyStateChangeListener listener) { readyEvent.addListener(new GenericEventListener() { public void processEvent(EventObject event) { listener.readyStateChanged(); } }); } private void changeState(int readyState, int status, String statusMessage, byte[] bytes) { synchronized(this) { this.readyState = readyState; this.status = status; this.statusText = statusMessage; this.responseBytes = bytes; } this.readyEvent.fireEvent(null); } private String getAllResponseHeaders(URLConnection c) { int idx = 0; String value; StringBuffer buf = new StringBuffer(); while((value = c.getHeaderField(idx)) != null) { String key = c.getHeaderFieldKey(idx); buf.append(key); buf.append(": "); buf.append(value); idx++; } return buf.toString(); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/test/SimpleUserAgentContext.java0000644000175000017500000002240411125160304030317 0ustar twernertwernerpackage org.lobobrowser.html.test; import java.security.Policy; import java.util.*; import java.util.logging.*; import org.lobobrowser.html.HttpRequest; import org.lobobrowser.html.UserAgentContext; /** * Simple implementation of {@link org.lobobrowser.html.UserAgentContext}. * This class is provided for user convenience. * Usually this class should be extended in order to provide appropriate * user agent information and more robust content loading routines. * Its setters can be called to modify certain user agent defaults. */ public class SimpleUserAgentContext implements UserAgentContext { private static final Logger logger = Logger.getLogger(SimpleUserAgentContext.class.getName()); private static final Set mediaNames = new HashSet(); static { // Media names claimed by this context. Set mn = mediaNames; mn.add("screen"); mn.add("tv"); mn.add("tty"); mn.add("all"); } /** * This implementation returns true for certain media names, * such as screen. */ public boolean isMedia(String mediaName) { return mediaNames.contains(mediaName.toLowerCase()); } /** * Creates a {@link org.lobobrowser.html.test.SimpleHttpRequest} instance. * The {@link org.lobobrowser.html.HttpRequest} object returned by this method is * used to load images, scripts, style sheets, and to implement * the Javascript XMLHttpRequest class. * Override if a custom mechanism to make requests is needed. */ public HttpRequest createHttpRequest() { return new SimpleHttpRequest(this, this.getProxy()); } private java.net.Proxy proxy = java.net.Proxy.NO_PROXY; /** * Gets the connection proxy used in requests created * by {@link #createHttpRequest()} by default. This implementation returns * the value of a local field. * @see #setProxy(java.net.Proxy) */ protected java.net.Proxy getProxy() { return this.proxy; } /** * Sets the value of the proxy normally returned by * {@link #getProxy()}. * @param proxy A java.net.Proxy instance. */ public void setProxy(java.net.Proxy proxy) { this.proxy = proxy; } private String appCodeName = "Cobra"; /** * Returns the application "code name." This implementation * returns the value of a local field. * @see #setAppCodeName(String) */ public String getAppCodeName() { return this.appCodeName; } /** * Sets the application code name normally returned by * {@link #getAppCodeName()}. * @param appCodeName An application "code name." */ public void setAppCodeName(String appCodeName) { this.appCodeName = appCodeName; } private String appMinorVersion = "0"; /** * Gets the "minor version" of the application. This implementation * returns the value of a local field. * @see #setAppMinorVersion(String) */ public String getAppMinorVersion() { return this.appMinorVersion; } /** * Sets the value normally returned by {@link #getAppMinorVersion()}. * @param appMinorVersion The application's "minor version." */ public void setAppMinorVersion(String appMinorVersion) { this.appMinorVersion = appMinorVersion; } private String appName = "Cobra"; /** * Gets the application name. This implementation returns * the value of a local field. * @see #setAppName(String) */ public String getAppName() { return this.appName; } /** * Sets the value normally returned by {@link #getAppName()}. * @param appName The application name. */ public void setAppName(String appName) { this.appName = appName; } private String appVersion = "1"; /** * Gets the major application version. This implementation * returns the value of a local field. * @see #setAppVersion(String) */ public String getAppVersion() { return this.appVersion; } /** * Sets the value normally returned by {@link #getAppVersion()}. * @param appVersion The application version. */ public void setAppVersion(String appVersion) { this.appVersion = appVersion; } /** * Get the browser language. This implementation returns * the language of the default locale. It may be overridden * to provide a different value. */ public String getBrowserLanguage() { return Locale.getDefault().getLanguage(); } /** * Returns the value of Java property os.name. * It may be overridden to provide a different value. */ public String getPlatform() { return System.getProperty("os.name"); } private String userAgent = "Mozilla/4.0 (compatible; MSIE 6.0;) Cobra/Simple"; /** * Gets the User-Agent string. This implementation returns * the value of a local field. * @see #setUserAgent(String) */ public String getUserAgent() { return this.userAgent; } /** * Sets the value normally returned by {@link #getUserAgent()}. * @param userAgent A User-Agent string. */ public void setUserAgent(String userAgent) { this.userAgent = userAgent; } /** * This implementation returns true if and only if * java.net.CookieHandler.getDefault() * is returning a non-null value. The method may * be overridden to provide an alternative means * of determining cookie enabling state. */ public boolean isCookieEnabled() { return java.net.CookieHandler.getDefault() != null; } /** * This implementation uses the default java.net.CookieHandler, * if any, to get cookie information for the given URL. If no cookie handler * is available, this method returns the empty string. */ public String getCookie(java.net.URL url) { java.net.CookieHandler handler = java.net.CookieHandler.getDefault(); if(handler == null) { return ""; } Map results; try { results = handler.get(url.toURI(), new HashMap()); } catch(Exception err) { logger.log(Level.WARNING, "getCookie()", err); return ""; } if(results == null) { return ""; } StringBuffer buffer = new StringBuffer(); Iterator i = results.entrySet().iterator(); boolean firstTime = true; while(i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); String key = (String) entry.getKey(); if("Cookie".equalsIgnoreCase(key) || "Cookie2".equalsIgnoreCase(key)) { List list = (List) entry.getValue(); Iterator li = list.iterator(); while(li.hasNext()) { String value = (String) li.next(); if(firstTime) { firstTime = false; } else { buffer.append("; "); } buffer.append(value); } } } return buffer.toString(); } private boolean scriptingEnabled = true; /** * Determines whether scripting should be enabled. This * implementation returns the value of a local field defaulting * to true. * @see #setScriptingEnabled(boolean) */ public boolean isScriptingEnabled() { return this.scriptingEnabled; } /** * Sets the value normally returned by {@link #isScriptingEnabled()}. * @param enable A boolean value. */ public void setScriptingEnabled(boolean enable) { this.scriptingEnabled = enable; } /** * This method uses the default CookieHandler, if one is available, * to set a cookie value. */ public void setCookie(java.net.URL url, String cookieSpec) { java.net.CookieHandler handler = java.net.CookieHandler.getDefault(); if(handler == null) { return; } Map headers = new HashMap(2); headers.put("Set-Cookie", Collections.singletonList(cookieSpec)); try { handler.put(url.toURI(), headers); } catch(Exception err) { logger.log(Level.WARNING, "setCookie()", err); } } /** * Returns null. This method must be overridden * if JavaScript code is untrusted. */ public Policy getSecurityPolicy() { return null; } private int scriptingOptimizationLevel = -1; /** * Gets the Rhino optimization level. This implementation returns * the value of a local field defaulting to -1. * @see #setScriptingOptimizationLevel(int) */ public int getScriptingOptimizationLevel() { return this.scriptingOptimizationLevel; } /** * Sets the value normally returned by {@link #getScriptingOptimizationLevel()}. * @param level A Rhino optimization level. */ public void setScriptingOptimizationLevel(int level) { this.scriptingOptimizationLevel = level; } private String vendor = "The Lobo Project"; public String getVendor() { return this.vendor; } public void setVendor(String vendor) { this.vendor = vendor; } private String product = "Cobra"; public String getProduct() { return this.product; } public void setProduct(String product) { this.product = product; } private boolean externalCSSEnabled = true; /** * Determines whether external CSS loading should be enabled. * This implementation returns the value of a local field * defaulting to true. * @see #setExternalCSSEnabled(boolean) */ public boolean isExternalCSSEnabled() { return this.externalCSSEnabled; } /** * Sets the value normally returned by {@link #isExternalCSSEnabled()}. * @param enabled A boolean value. */ public void setExternalCSSEnabled(boolean enabled) { this.externalCSSEnabled = enabled; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/test/TestEntry.java0000644000175000017500000000311710726473506025665 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 22, 2005 */ package org.lobobrowser.html.test; /** * The TestEntry class is a Java test * program for the Cobra HTML rendering engine. It * displays a frame with a text field and three tabs. * The tabs show the renderered HTML, the HTML DOM * represented as a JTree, and the HTML source code. */ public class TestEntry { private TestEntry() { super(); } /** * Test application entry point. * @param args Program arguments. */ public static void main(String[] args) { TestFrame frame = new TestFrame("Cobra Test Tool"); frame.setSize(800, 400); frame.setExtendedState(TestFrame.MAXIMIZED_BOTH); frame.setVisible(true); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/test/TestFrame.java0000644000175000017500000001243410742375372025620 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 22, 2005 */ package org.lobobrowser.html.test; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import java.net.*; import java.util.logging.*; import org.lobobrowser.html.gui.*; import org.lobobrowser.html.*; /** * A Swing frame that can be used to test the * Cobra HTML rendering engine. */ public class TestFrame extends JFrame { private static final Logger logger = Logger.getLogger(TestFrame.class.getName()); private final SimpleHtmlRendererContext rcontext; private final JTree tree; private final HtmlPanel htmlPanel; private final JTextArea textArea; private final JTextField addressField; public TestFrame() throws HeadlessException { this(""); } public TestFrame(String title) throws HeadlessException { super(title); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = this.getContentPane(); contentPane.setLayout(new BorderLayout()); JPanel topPanel = new JPanel(); topPanel.setLayout(new BorderLayout()); JPanel bottomPanel = new JPanel(); bottomPanel.setLayout(new BorderLayout()); final JTextField textField = new JTextField(); this.addressField = textField; JButton button = new JButton("Parse & Render"); final JTabbedPane tabbedPane = new JTabbedPane(); final JTree tree = new JTree(); final JScrollPane scrollPane = new JScrollPane(tree); this.tree = tree; contentPane.add(topPanel, BorderLayout.NORTH); contentPane.add(bottomPanel, BorderLayout.CENTER); topPanel.add(new JLabel("URL: "), BorderLayout.WEST); topPanel.add(textField, BorderLayout.CENTER); topPanel.add(button, BorderLayout.EAST); bottomPanel.add(tabbedPane, BorderLayout.CENTER); final HtmlPanel panel = new HtmlPanel(); panel.addSelectionChangeListener(new SelectionChangeListener() { public void selectionChanged(SelectionChangeEvent event) { if(logger.isLoggable(Level.INFO)) { logger.info("selectionChanged(): selection node: " + panel.getSelectionNode()); } } }); this.htmlPanel = panel; UserAgentContext ucontext = new SimpleUserAgentContext(); this.rcontext = new LocalHtmlRendererContext(panel, ucontext); final JTextArea textArea = new JTextArea(); this.textArea = textArea; textArea.setEditable(false); final JScrollPane textAreaSp = new JScrollPane(textArea); tabbedPane.addTab("HTML", panel); tabbedPane.addTab("Tree", scrollPane); tabbedPane.addTab("Source", textAreaSp); tabbedPane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { Component component = tabbedPane.getSelectedComponent(); if(component == scrollPane) { tree.setModel(new NodeTreeModel(panel.getRootNode())); } else if(component == textAreaSp) { textArea.setText(rcontext.getSourceCode()); } } }); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { process(textField.getText()); } }); } public HtmlRendererContext getHtmlRendererContext() { return this.rcontext; } public void navigate(String uri) { this.addressField.setText(uri); this.process(uri); } private void process(String uri) { try { URL url; try { url = new URL(uri); } catch(java.net.MalformedURLException mfu) { int idx = uri.indexOf(':'); if(idx == -1 || idx == 1) { // try file url = new URL("file:" + uri); } else { throw mfu; } } // Call SimpleHtmlRendererContext.navigate() // which implements incremental rendering. this.rcontext.navigate(url, null); } catch(Exception err) { logger.log(Level.SEVERE, "Error trying to load URI=[" + uri + "].", err); } } private class LocalHtmlRendererContext extends SimpleHtmlRendererContext { public LocalHtmlRendererContext(HtmlPanel contextComponent, UserAgentContext ucontext) { super(contextComponent, ucontext); } public HtmlRendererContext open(URL url, String windowName, String windowFeatures, boolean replace) { TestFrame frame = new TestFrame("Cobra Test Tool"); frame.setSize(600, 400); frame.setExtendedState(TestFrame.NORMAL); frame.setVisible(true); HtmlRendererContext ctx = frame.getHtmlRendererContext(); ctx.setOpener(this); frame.navigate(url.toExternalForm()); return ctx; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/html/test/package.html0000644000175000017500000000023610712365652025336 0ustar twernertwernerContains test software classes and simple implementations of context interfaces. libcobra-java-0.98.4.orig/src/org/lobobrowser/js/0000755000175000017500000000000011125630300021525 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/lobobrowser/js/AbstractScriptableDelegate.java0000644000175000017500000000234110742363402027611 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.js; import org.mozilla.javascript.*; public abstract class AbstractScriptableDelegate implements ScriptableDelegate { private Scriptable scriptable; public Scriptable getScriptable() { return this.scriptable; } public void setScriptable(Scriptable scriptable) { this.scriptable = scriptable; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/js/JavaClassWrapper.java0000644000175000017500000001365310742202326025617 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.js; import java.util.*; import java.lang.reflect.*; import org.mozilla.javascript.*; public class JavaClassWrapper { private final Class javaClass; private final Map functions = new HashMap(); private final Map properties = new HashMap(); private PropertyInfo nameIndexer; private PropertyInfo integerIndexer; public JavaClassWrapper(Class class1) { super(); this.javaClass = class1; this.scanMethods(); } public Object newInstance() throws InstantiationException, IllegalAccessException { return this.javaClass.newInstance(); } public String getClassName() { String className = this.javaClass.getName(); int lastDotIdx = className.lastIndexOf('.'); return lastDotIdx == -1 ? className : className.substring(lastDotIdx+1); } public Function getFunction(String name) { return (Function) this.functions.get(name); } public PropertyInfo getProperty(String name) { return (PropertyInfo) this.properties.get(name); } private void scanMethods() { Method[] methods = this.javaClass.getMethods(); int len = methods.length; for(int i = 0; i < len; i++) { Method method = methods[i]; String name = method.getName(); if(isPropertyMethod(name, method)) { this.ensurePropertyKnown(name, method); } else { if(isNameIndexer(name, method)) { this.updateNameIndexer(name, method); } else if(this.isIntegerIndexer(name, method)) { this.updateIntegerIndexer(name, method); } JavaFunctionObject f = (JavaFunctionObject) this.functions.get(name); if(f == null) { f = new JavaFunctionObject(name); this.functions.put(name, f); } f.addMethod(method); } } } private boolean isNameIndexer(String name, Method method) { return ("namedItem".equals(name) && method.getParameterTypes().length == 1) || ("setNamedItem".equals(name) && method.getParameterTypes().length == 2); } private boolean isIntegerIndexer(String name, Method method) { return ("item".equals(name) && method.getParameterTypes().length == 1) || ("setItem".equals(name) && method.getParameterTypes().length == 2); } private void updateNameIndexer(String methodName, Method method) { boolean getter = true; if(methodName.startsWith("set")) { getter = false; } PropertyInfo indexer = this.nameIndexer; if(indexer == null) { indexer = new PropertyInfo("$item", Object.class); this.nameIndexer = indexer; } if(getter) { indexer.setGetter(method); } else { indexer.setSetter(method); } } private void updateIntegerIndexer(String methodName, Method method) { boolean getter = true; if(methodName.startsWith("set")) { getter = false; } PropertyInfo indexer = this.integerIndexer; if(indexer == null) { Class pt = getter ? method.getReturnType() : method.getParameterTypes()[1]; indexer = new PropertyInfo("$item", pt); this.integerIndexer = indexer; } if(getter) { indexer.setGetter(method); } else { indexer.setSetter(method); } } public PropertyInfo getIntegerIndexer() { return this.integerIndexer; } public PropertyInfo getNameIndexer() { return this.nameIndexer; } private boolean isPropertyMethod(String name, Method method) { if(name.startsWith("get") || name.startsWith("is")) { return method.getParameterTypes().length == 0; } else if(name.startsWith("set")) { return method.getParameterTypes().length == 1; } else { return false; } } private String propertyUncapitalize(String text) { try { if(text.length() > 1 && Character.isUpperCase(text.charAt(1))) { // If second letter is capitalized, don't uncapitalize, // e.g. getURL. return text; } return Character.toLowerCase(text.charAt(0)) + text.substring(1); } catch(IndexOutOfBoundsException iob) { return text; } } private void ensurePropertyKnown(String methodName, Method method) { String capPropertyName; String propertyName; boolean getter = false; if(methodName.startsWith("get")) { capPropertyName = methodName.substring(3); propertyName = propertyUncapitalize(capPropertyName); getter = true; } else if(methodName.startsWith("set")) { capPropertyName = methodName.substring(3); propertyName = propertyUncapitalize(capPropertyName); } else if(methodName.startsWith("is")) { capPropertyName = methodName.substring(2); propertyName = propertyUncapitalize(capPropertyName); getter = true; } else { throw new IllegalArgumentException("methodName=" + methodName); } PropertyInfo pinfo = (PropertyInfo) this.properties.get(propertyName); if(pinfo == null) { Class pt = getter ? method.getReturnType() : method.getParameterTypes()[0]; pinfo = new PropertyInfo(propertyName, pt); this.properties.put(propertyName, pinfo); } if(getter) { pinfo.setGetter(method); } else { pinfo.setSetter(method); } } public String toString() { return this.javaClass.getName(); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/js/JavaClassWrapperFactory.java0000644000175000017500000000365410726473476027171 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.js; import java.util.*; import java.lang.ref.*; public class JavaClassWrapperFactory { private static JavaClassWrapperFactory instance; private final Map classWrappers = new WeakHashMap(); private JavaClassWrapperFactory() { } public static JavaClassWrapperFactory getInstance() { if(instance == null) { synchronized(JavaClassWrapperFactory.class) { if(instance == null) { instance = new JavaClassWrapperFactory(); } } } return instance; } public JavaClassWrapper getClassWrapper(Class clazz) { synchronized(this) { //WeakHashMaps where the value refers to //the key will retain keys. Must make it //refer to the value weakly too. WeakReference jcwr = (WeakReference) this.classWrappers.get(clazz); JavaClassWrapper jcw = null; if(jcwr != null) { jcw = (JavaClassWrapper) jcwr.get(); } if(jcw == null) { jcw = new JavaClassWrapper(clazz); this.classWrappers.put(clazz, new WeakReference(jcw)); } return jcw; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/js/JavaConstructorObject.java0000644000175000017500000000531010726473510026663 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.js; import org.mozilla.javascript.*; public class JavaConstructorObject extends ScriptableObject implements Function { private final JavaClassWrapper classWrapper; private final JavaInstantiator instantiator; private final String name; public JavaConstructorObject(String name, JavaClassWrapper classWrapper) { this.name = name; this.classWrapper = classWrapper; this.instantiator = new SimpleInstantiator(classWrapper); } public JavaConstructorObject(String name, JavaClassWrapper classWrapper, JavaInstantiator instantiator) { this.name = name; this.classWrapper = classWrapper; this.instantiator = instantiator; } public String getClassName() { return this.name; } public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { throw new UnsupportedOperationException(); } public Scriptable construct(Context cx, Scriptable scope, Object[] args) { try { Object javaObject = this.instantiator.newInstance(); Scriptable newObject = new JavaObjectWrapper(this.classWrapper, javaObject); newObject.setParentScope(scope); return newObject; } catch(Exception err) { throw new IllegalStateException(err.getMessage()); } } public java.lang.Object getDefaultValue(java.lang.Class hint) { if(String.class.equals(hint)) { return "function " + this.name; } else { return super.getDefaultValue(hint); } } public static class SimpleInstantiator implements JavaInstantiator { private final JavaClassWrapper classWrapper; public SimpleInstantiator(final JavaClassWrapper classWrapper) { super(); this.classWrapper = classWrapper; } public Object newInstance() throws InstantiationException, IllegalAccessException { return this.classWrapper.newInstance(); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/js/JavaFunctionObject.java0000644000175000017500000001213510726473510026126 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.js; import org.mozilla.javascript.*; import java.lang.reflect.*; import java.util.logging.*; import java.util.*; import org.lobobrowser.util.*; public class JavaFunctionObject extends ScriptableObject implements Function { private static final Logger logger = Logger.getLogger(JavaFunctionObject.class.getName()); private static final boolean loggableInfo = logger.isLoggable(Level.INFO); private final String className; private final ArrayList methods = new ArrayList(); public JavaFunctionObject(String name) { super(); this.className = name; } public void addMethod(Method m) { this.methods.add(m); } public String getClassName() { return this.className; } private String getTypeName(Object object) { return object == null ? "[null]" : object.getClass().getName(); } private Method getBestMethod(Object[] args) { ArrayList methods = this.methods; int size = methods.size(); int matchingNumParams = 0; Method matchingMethod = null; for(int i = 0; i < size; i++) { Method m = (Method) methods.get(i); Class[] parameterTypes = m.getParameterTypes(); if(args == null) { if(parameterTypes == null || parameterTypes.length == 0) { return m; } } else if(parameterTypes != null && args.length >= parameterTypes.length) { if(Objects.areAssignableTo(args, parameterTypes)) { return m; } if(matchingMethod == null || parameterTypes.length > matchingNumParams) { matchingNumParams = parameterTypes.length; matchingMethod = m; } } } if(size == 0) { throw new IllegalStateException("zero methods"); } return matchingMethod; } public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { JavaObjectWrapper jcw = (JavaObjectWrapper) thisObj; Method method = this.getBestMethod(args); if(method == null) { throw new EvaluatorException("No method matching " + this.className + " with " + (args == null ? 0 : args.length) + " arguments."); } Class[] actualArgTypes = method.getParameterTypes(); int numParams = actualArgTypes.length; Object[] actualArgs = args == null ? new Object[0] : new Object[numParams]; boolean linfo = loggableInfo; if(linfo) { Object javaObject = jcw.getJavaObject(); logger.info("call(): Calling method " + method.getName() + " on object " + javaObject + " of type " + this.getTypeName(javaObject)); } JavaScript manager = JavaScript.getInstance(); for(int i = 0; i < numParams; i++) { Object arg = args[i]; Object actualArg = manager.getJavaObject(arg, actualArgTypes[i]); if(linfo) { logger.info("call(): For method=" + method.getName() + ": Converted arg=" + arg + " (type=" + this.getTypeName(arg) + ") into actualArg=" + actualArg + ". Type expected by method is " + actualArgTypes[i].getName() + "."); } actualArgs[i] = actualArg; } try { Object raw = method.invoke(jcw.getJavaObject(), actualArgs); return manager.getJavascriptObject(raw, scope); } catch(IllegalAccessException iae) { throw new IllegalStateException("Unable to call " + this.className + ".", iae); } catch(InvocationTargetException ite) { throw new WrappedException(new InvocationTargetException(ite.getCause(), "Unable to call " + this.className + " on " + jcw.getJavaObject() + ".")); } catch(IllegalArgumentException iae) { StringBuffer argTypes = new StringBuffer(); for(int i = 0; i < actualArgs.length; i++) { if(i > 0) { argTypes.append(", "); } argTypes.append(actualArgs[i] == null ? "" : actualArgs[i].getClass().getName()); } throw new WrappedException(new IllegalArgumentException("Unable to call " + this.className + ". Argument types: " + argTypes + ".", iae)); } } public java.lang.Object getDefaultValue(java.lang.Class hint) { if(loggableInfo) { logger.info("getDefaultValue(): hint=" + hint + ",this=" + this); } if(hint == null || String.class.equals(hint)) { return "function " + this.className; } else { return super.getDefaultValue(hint); } } public Scriptable construct(Context cx, Scriptable scope, Object[] args) { throw new UnsupportedOperationException(); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/js/JavaInstantiator.java0000644000175000017500000000023410641432632025662 0ustar twernertwernerpackage org.lobobrowser.js; public interface JavaInstantiator { public Object newInstance() throws InstantiationException, IllegalAccessException; } libcobra-java-0.98.4.orig/src/org/lobobrowser/js/JavaObjectWrapper.java0000644000175000017500000002152211056264524025761 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.js; import org.mozilla.javascript.*; import java.lang.reflect.*; import java.util.logging.Level; import java.util.logging.Logger; public class JavaObjectWrapper extends ScriptableObject { private static final Logger logger = Logger.getLogger(JavaObjectWrapper.class.getName()); private static final boolean loggableInfo = logger.isLoggable(Level.INFO); private final Object delegate; private final JavaClassWrapper classWrapper; public JavaObjectWrapper(JavaClassWrapper classWrapper) throws InstantiationException, IllegalAccessException { this.classWrapper = classWrapper; // Retaining a strong reference, but note // that the object wrapper map uses weak keys // and weak values. Object delegate = this.classWrapper.newInstance(); this.delegate = delegate; } public JavaObjectWrapper(JavaClassWrapper classWrapper, Object delegate) { if(delegate == null) { throw new IllegalArgumentException("Argument delegate cannot be null."); } this.classWrapper = classWrapper; // Retaining a strong reference, but note // that the object wrapper map uses weak keys // and weak values. this.delegate = delegate; } /** * Returns the Java object. * @return An object or null if garbage collected. */ public Object getJavaObject() { // Cannot retain delegate with a strong reference. return this.delegate; } public String getClassName() { return this.classWrapper.getClassName(); } public Object get(int index, Scriptable start) { PropertyInfo pinfo = this.classWrapper.getIntegerIndexer(); if(pinfo == null) { return super.get(index, start); } else { try { Method getter = pinfo.getGetter(); if(getter == null) { throw new EvaluatorException("Indexer is write-only"); } // Cannot retain delegate with a strong reference. Object javaObject = this.getJavaObject(); if(javaObject == null) { throw new IllegalStateException("Java object (class=" + this.classWrapper + ") is null."); } Object raw = getter.invoke(javaObject, new Object[] { new Integer(index) }); if(raw == null) { // Return this instead of null. return Scriptable.NOT_FOUND; } return JavaScript.getInstance().getJavascriptObject(raw, this.getParentScope()); } catch(Exception err) { throw new WrappedException(err); } } } public Object get(String name, Scriptable start) { PropertyInfo pinfo = this.classWrapper.getProperty(name); if(pinfo != null) { Method getter = pinfo.getGetter(); if(getter == null) { throw new EvaluatorException("Property '" + name + "' is not readable"); } try { // Cannot retain delegate with a strong reference. Object javaObject = this.getJavaObject(); if(javaObject == null) { throw new IllegalStateException("Java object (class=" + this.classWrapper + ") is null."); } Object val = getter.invoke(javaObject, (Object[]) null); return JavaScript.getInstance().getJavascriptObject(val, start.getParentScope()); } catch(Exception err) { throw new WrappedException(err); } } else { Function f = this.classWrapper.getFunction(name); if(f != null) { return f; } else { // Should check properties set in context // first. Consider element IDs should not // override Window variables set by user. Object result = super.get(name, start); if(result != Scriptable.NOT_FOUND) { return result; } PropertyInfo ni = this.classWrapper.getNameIndexer(); if(ni != null) { Method getter = ni.getGetter(); if(getter != null) { // Cannot retain delegate with a strong reference. Object javaObject = this.getJavaObject(); if(javaObject == null) { throw new IllegalStateException("Java object (class=" + this.classWrapper + ") is null."); } try { Object val = getter.invoke(javaObject, new Object[] { name }); if(val == null) { // There might not be an indexer setter. return super.get(name, start); } else { return JavaScript.getInstance().getJavascriptObject(val, start.getParentScope()); } } catch(Exception err) { throw new WrappedException(err); } } } return Scriptable.NOT_FOUND; } } } public void put(int index, Scriptable start, Object value) { PropertyInfo pinfo = this.classWrapper.getIntegerIndexer(); if(pinfo == null) { super.put(index, start, value); } else { try { Method setter = pinfo.getSetter(); if(setter == null) { throw new EvaluatorException("Indexer is read-only"); } Object actualValue; actualValue = JavaScript.getInstance().getJavaObject(value, pinfo.getPropertyType()); setter.invoke(this.getJavaObject(), new Object[] { new Integer(index), actualValue }); } catch(Exception err) { throw new WrappedException(err); } } } public void put(String name, Scriptable start, Object value) { if(value instanceof org.mozilla.javascript.Undefined) { super.put(name, start, value); } else { PropertyInfo pinfo = this.classWrapper.getProperty(name); if(pinfo != null) { Method setter = pinfo.getSetter(); if(setter == null) { throw new EvaluatorException("Property '" + name + "' is not settable in " + this.classWrapper.getClassName() + "."); } try { Object actualValue; actualValue = JavaScript.getInstance().getJavaObject(value, pinfo.getPropertyType()); setter.invoke(this.getJavaObject(), new Object[] { actualValue }); } catch(IllegalArgumentException iae) { Exception newException = new IllegalArgumentException("Property named '" + name + "' could not be set with value " + value + ".", iae); throw new WrappedException(newException); } catch(Exception err) { throw new WrappedException(err); } } else { PropertyInfo ni = this.classWrapper.getNameIndexer(); if(ni != null) { Method setter = ni.getSetter(); if(setter != null) { try { Object actualValue; actualValue = JavaScript.getInstance().getJavaObject(value, ni.getPropertyType()); setter.invoke(this.getJavaObject(), new Object[] { name, actualValue }); } catch(Exception err) { throw new WrappedException(err); } } else { super.put(name, start, value); } } else { super.put(name, start, value); } } } } public static Function getConstructor(String className, JavaClassWrapper classWrapper, Scriptable scope) { return new JavaConstructorObject(className, classWrapper); } public static Function getConstructor(String className, JavaClassWrapper classWrapper, Scriptable scope, JavaInstantiator instantiator) { return new JavaConstructorObject(className, classWrapper, instantiator); } public java.lang.Object getDefaultValue(java.lang.Class hint) { if(loggableInfo) { logger.info("getDefaultValue(): hint=" + hint + ",this=" + this.getJavaObject()); } if(hint == null || String.class.equals(hint)) { Object javaObject = this.getJavaObject(); if(javaObject == null) { throw new IllegalStateException("Java object (class=" + this.classWrapper + ") is null."); } return javaObject.toString(); } else if(Number.class.isAssignableFrom(hint)) { Object javaObject = this.getJavaObject(); if(javaObject instanceof Number) { return javaObject; } else if(javaObject instanceof String) { return Double.valueOf((String) javaObject); } else { return super.getDefaultValue(hint); } } else { return super.getDefaultValue(hint); } } public String toString() { Object javaObject = this.getJavaObject(); String type = javaObject == null ? "" : javaObject.getClass().getName(); return "JavaObjectWrapper[object=" + this.getJavaObject() + ",type=" + type + "]"; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/js/JavaScript.java0000644000175000017500000001222110742132476024453 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.js; import java.util.WeakHashMap; import java.lang.ref.*; import org.mozilla.javascript.*; import org.lobobrowser.util.*; public class JavaScript { private static JavaScript instance = new JavaScript(); // objectMap must be a map that uses weak keys // and refers to values using weak references. // Keys are java objects other than ScriptableDelegate instances. private final WeakHashMap javaObjectToWrapper = new WeakHashMap(); public static JavaScript getInstance() { return instance; } /** * Returns an object that may be used by * the Javascript engine. * @param raw * @return */ public Object getJavascriptObject(Object raw, Scriptable scope) { if(raw instanceof String || raw instanceof Scriptable) { return raw; } else if(raw == null) { return null; } else if(raw.getClass().isPrimitive()) { return raw; } else if(raw instanceof ScriptableDelegate) { // Classes that implement ScriptableDelegate retain // the JavaScript object. Reciprocal linking cannot // be done with weak hash maps and without leaking. synchronized(this) { Scriptable javascriptObject = ((ScriptableDelegate) raw).getScriptable(); if(javascriptObject == null) { JavaObjectWrapper jow = new JavaObjectWrapper(JavaClassWrapperFactory.getInstance().getClassWrapper(raw.getClass()), raw); javascriptObject = jow; jow.setParentScope(scope); ((ScriptableDelegate) raw).setScriptable(jow); } javascriptObject.setParentScope(scope); return javascriptObject; } } else if(Objects.isBoxClass(raw.getClass())) { return raw; } else { synchronized(this.javaObjectToWrapper) { //WeakHashMaps will retain keys if the value refers to the key. //That's why we need to refer to the value weakly too. WeakReference valueRef = (WeakReference) this.javaObjectToWrapper.get(raw); JavaObjectWrapper jow = null; if(valueRef != null) { jow = (JavaObjectWrapper) valueRef.get(); } if(jow == null) { Class javaClass = raw.getClass(); JavaClassWrapper wrapper = JavaClassWrapperFactory.getInstance().getClassWrapper(javaClass); jow = new JavaObjectWrapper(wrapper, raw); this.javaObjectToWrapper.put(raw, new WeakReference(jow)); } jow.setParentScope(scope); return jow; } } } private static String getStringValue(Object object) { if(object instanceof Undefined) { return "undefined"; } else if(object instanceof Scriptable) { return (String) ((Scriptable) object).getDefaultValue(String.class); } else { return String.valueOf(object); } } public Object getJavaObject(Object javascriptObject, Class type) { if(javascriptObject instanceof JavaObjectWrapper) { Object rawJavaObject = ((JavaObjectWrapper) javascriptObject).getJavaObject(); if(String.class == type) { return String.valueOf(rawJavaObject); } else { return rawJavaObject; } } else if(javascriptObject == null) { return null; } else if(type == String.class) { if(javascriptObject instanceof String) { return javascriptObject; } else if(javascriptObject instanceof Double) { String text = String.valueOf(javascriptObject); if(text.endsWith(".0")) { return text.substring(0, text.length() - 2); } else { return text; } } else { return getStringValue(javascriptObject); } } else if(type == int.class || type == Integer.class) { if(javascriptObject instanceof Double) { return new Integer(((Double) javascriptObject).intValue()); } else if(javascriptObject instanceof Integer) { return javascriptObject; } else if(javascriptObject instanceof String) { return Integer.valueOf((String) javascriptObject); } else if(javascriptObject instanceof Short) { return new Integer(((Short) javascriptObject).shortValue()); } else if(javascriptObject instanceof Long) { return new Integer(((Long) javascriptObject).intValue()); } else if(javascriptObject instanceof Float) { return new Integer(((Float) javascriptObject).intValue()); } else { return javascriptObject; } } else { return javascriptObject; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/js/PropertyInfo.java0000644000175000017500000000306710726473504025057 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.js; import java.lang.reflect.*; public class PropertyInfo { private final String name; private final Class propertyType; private Method getter, setter; public PropertyInfo(String name, Class propType) { super(); this.name = name; this.propertyType = propType; } public Method getGetter() { return getter; } public void setGetter(Method getter) { this.getter = getter; } public Method getSetter() { return setter; } public void setSetter(Method setter) { this.setter = setter; } public String getName() { return this.name; } public Class getPropertyType() { return propertyType; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/js/ScriptableDelegate.java0000644000175000017500000000254610726473506026145 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.js; import org.mozilla.javascript.*; /** * Java classes used in Javascript should implement this * interface. While all classes can be mapped to * JavaScript, implementing this interface ensures that * the Java object proxy is not garbage collected as long * as the Java object is not garbage collected. */ public interface ScriptableDelegate { public void setScriptable(Scriptable scriptable); public Scriptable getScriptable(); } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/0000755000175000017500000000000011125630232022072 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/lobobrowser/util/ArrayUtilities.java0000644000175000017500000000370410726473506025732 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 17, 2005 */ package org.lobobrowser.util; import java.util.*; /** * @author J. H. S. */ public class ArrayUtilities { /** * */ private ArrayUtilities() { super(); } public static Iterator iterator(Object[] array, int offset, int length) { return new ArrayIterator(array, offset, length); } private static class ArrayIterator implements Iterator { private final Object[] array; private final int top; private int offset; public ArrayIterator(Object[] array, int offset, int length) { this.array = array; this.offset = offset; this.top = offset + length; } /* (non-Javadoc) * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return this.offset < this.top; } /* (non-Javadoc) * @see java.util.Iterator#next() */ public Object next() { return this.array[this.offset++]; } /* (non-Javadoc) * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/BaseClassLoader.java0000644000175000017500000000304610726473476025754 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jun 19, 2005 */ package org.lobobrowser.util; import java.security.SecureClassLoader; /** * Base class for all project class loaders. * @author J. H. S. */ public abstract class BaseClassLoader extends SecureClassLoader { /** * @param parent */ public BaseClassLoader(ClassLoader parent) { super(parent); } /** * */ public BaseClassLoader() { super(); } /* (non-Javadoc) * @see java.lang.ClassLoader#loadClass(java.lang.String, boolean) */ public synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { return super.loadClass(name, resolve); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/Bean.java0000644000175000017500000001305610726473500023620 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Mar 20, 2005 */ package org.lobobrowser.util; //import java.util.logging.*; import java.beans.*; import java.lang.reflect.Method; import java.util.*; /** * @author J. H. S. */ public class Bean { //private static final java.util.logging.Logger logger = Logger.getLogger(Bean.class); private final Class clazz; public Bean(Class clazz) { this.clazz = clazz; } private Map propertyDescriptors = null; private void populateDescriptors(Map map, Class clazz) throws IntrospectionException { BeanInfo beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); for(int i = 0; i < pds.length; i++) { map.put(pds[i].getName(), pds[i]); } if(clazz.isInterface()) { java.lang.reflect.Type[] interfaces = clazz.getGenericInterfaces(); for(int i = 0; i < interfaces.length; i++) { this.populateDescriptors(map, (Class) interfaces[i]); } } } public PropertyDescriptor getPropertyDescriptor(String propertyName) throws IntrospectionException { synchronized(this) { if(this.propertyDescriptors == null) { this.propertyDescriptors = new HashMap(); this.populateDescriptors(this.propertyDescriptors, this.clazz); } return (PropertyDescriptor) this.propertyDescriptors.get(propertyName); } } public Map getPropertyDescriptorsMap() throws IntrospectionException { synchronized(this) { if(this.propertyDescriptors == null) { this.propertyDescriptors = new HashMap(); this.populateDescriptors(this.propertyDescriptors, this.clazz); } return this.propertyDescriptors; } } public PropertyDescriptor[] getPropertyDescriptors() throws IntrospectionException { synchronized(this) { return (PropertyDescriptor[]) this.getPropertyDescriptorsMap().values().toArray(new PropertyDescriptor[0]); } } public void setPropertyForFQN(Object receiver, String fullyQualifiedPropertyName, Object value) throws Exception { int idx = fullyQualifiedPropertyName.indexOf('.'); if(idx == -1) { PropertyDescriptor pd = this.getPropertyDescriptor(fullyQualifiedPropertyName); if(pd == null) { throw new IllegalStateException("Property '" + fullyQualifiedPropertyName + "' unknown"); } Method method = pd.getWriteMethod(); if(method == null) { throw new IllegalStateException("Property '" + fullyQualifiedPropertyName + "' not settable"); } Object actualValue = convertValue(value, pd.getPropertyType()); method.invoke(receiver, new Object[] { actualValue }); } else { String prefix = fullyQualifiedPropertyName.substring(0, idx); PropertyDescriptor pinfo = this.getPropertyDescriptor(prefix); if(pinfo == null) { throw new IllegalStateException("Property '" + prefix + "' unknown"); } Method readMethod = pinfo.getReadMethod(); if(readMethod == null) { throw new IllegalStateException("Property '" + prefix + "' not readable"); } Object newReceiver = readMethod.invoke(receiver, new Object[0]); //Class newClass = pinfo.getPropertyType(); String nameRest = fullyQualifiedPropertyName.substring(idx + 1); this.setPropertyForFQN(newReceiver, nameRest, value); } } private static Object convertValue(Object value, Class targetType) { boolean targetString = targetType.isAssignableFrom(String.class); if(value instanceof String && targetString) { // ignore } else if(targetString) { value = String.valueOf(value); } else if(!(value instanceof Byte) && (targetType == Byte.class || targetType == byte.class)) { value = Byte.valueOf(String.valueOf(value)); } else if(!(value instanceof Boolean) && (targetType == Boolean.class || targetType == boolean.class)) { value = Boolean.valueOf(String.valueOf(value)); } else if(!(value instanceof Short) && (targetType == Short.class || targetType == short.class)) { value = Short.valueOf(String.valueOf(value)); } else if(!(value instanceof Integer) && (targetType == Integer.class || targetType == int.class)) { value = Integer.valueOf(String.valueOf(value)); } else if(!(value instanceof Long) && (targetType == Long.class || targetType == long.class)) { value = Long.valueOf(String.valueOf(value)); } return value; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/BoxedObject.java0000644000175000017500000000052010620620320025116 0ustar twernertwernerpackage org.lobobrowser.util; public class BoxedObject { private Object object; public BoxedObject() { } public BoxedObject(Object object) { super(); this.object = object; } public Object getObject() { return object; } public void setObject(Object object) { this.object = object; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/CollectionUtilities.java0000644000175000017500000000615510726473500026744 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jun 9, 2005 */ package org.lobobrowser.util; import java.util.*; /** * @author J. H. S. */ public class CollectionUtilities { /** * */ private CollectionUtilities() { super(); } public static Enumeration getIteratorEnumeration(final Iterator i) { return new Enumeration() { public boolean hasMoreElements() { return i.hasNext(); } public Object nextElement() { return i.next(); } }; } public static Iterator iteratorUnion(final Iterator[] iterators) { return new Iterator() { private int iteratorIndex = 0; private Iterator current = iterators.length > 0 ? iterators[0] : null; public boolean hasNext() { for(;;) { if(current == null) { return false; } if(current.hasNext()) { return true; } iteratorIndex++; current = iteratorIndex >= iterators.length ? null : iterators[iteratorIndex]; } } public Object next() { for(;;) { if(this.current == null) { throw new NoSuchElementException(); } try { return this.current.next(); } catch(NoSuchElementException nse) { this.iteratorIndex++; this.current = this.iteratorIndex >= iterators.length ? null : iterators[this.iteratorIndex]; } } } public void remove() { if(this.current == null) { throw new NoSuchElementException(); } this.current.remove(); } }; } public static Collection reverse(Collection collection) { LinkedList newCollection = new LinkedList(); Iterator i = collection.iterator(); while(i.hasNext()) { newCollection.addFirst(i.next()); } return newCollection; } public static Iterator singletonIterator(final Object item) { return new Iterator() { private boolean gotItem = false; public boolean hasNext() { return !this.gotItem; } public Object next() { if(this.gotItem) { throw new NoSuchElementException(); } this.gotItem = true; return item; } public void remove() { if(!this.gotItem) { this.gotItem = true; } else { throw new NoSuchElementException(); } } }; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/Diagnostics.java0000644000175000017500000000237310726473500025222 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Mar 31, 2005 */ package org.lobobrowser.util; /** * @author J. H. S. */ public class Diagnostics { /** * */ private Diagnostics() { super(); } public static void Assert(boolean condition, String message) { if(!condition) { throw new AssertionError(message); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/Domains.java0000644000175000017500000000674710726473504024362 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jun 2, 2005 */ package org.lobobrowser.util; import java.util.*; /** * @author J. H. S. */ public class Domains { private static final Collection gTLDs; static { gTLDs = new HashSet(); gTLDs.add(".com"); gTLDs.add(".edu"); gTLDs.add(".gov"); gTLDs.add(".int"); gTLDs.add(".mil"); gTLDs.add(".net"); gTLDs.add(".org"); gTLDs.add(".biz"); gTLDs.add(".info"); gTLDs.add(".name"); gTLDs.add(".pro"); gTLDs.add(".aero"); gTLDs.add(".coop"); gTLDs.add(".museum"); //TODO: New gTLDs? } /** * */ private Domains() { super(); } public static boolean isValidCookieDomain(String domain, String hostName) { String plainDomain; if(!domain.startsWith(".")) { // Valid domains must start with a dot // according to RFC 2109, but // RFC 2965 specifies a dot is prepended // in the Set-Cookie2 header. plainDomain = domain; domain = "." + domain; } else { plainDomain = domain.substring(1); } String plainDomainTL = plainDomain.toLowerCase(); String hostNameTL = hostName.toLowerCase(); if(!hostNameTL.endsWith(plainDomainTL)) { return false; } int lastDotIdx = domain.lastIndexOf('.'); if(lastDotIdx == -1) { return false; } String suffix = domain.substring(lastDotIdx).toLowerCase(); if(gTLDs.contains(suffix)) { return Strings.countChars(domain, '.') >= 2; } else { return Strings.countChars(domain, '.') >= 3; } } /** * * @param host A host name in lower case. * @return */ public static boolean endsWithGTLD(String host) { Iterator i = gTLDs.iterator(); while(i.hasNext()) { String ending = (String) i.next(); if(host.endsWith(ending)) { return true; } } return false; } public static boolean isLikelyHostName(String name) { String nameTL = name.toLowerCase(); if(nameTL.startsWith("www.")) { return true; } if(endsWithGTLD(name)) { return true; } int lastDotIdx = nameTL.lastIndexOf('.'); if(lastDotIdx == -1) { return false; } // Check for country code. return lastDotIdx == nameTL.length() - 3; } public static Collection getPossibleDomains(String hostName) { Collection domains = new LinkedList(); domains.add(hostName); int dotIdx = hostName.indexOf('.', 1); if(dotIdx == -1) { return domains; } String testDomain = hostName.substring(dotIdx); if(!Domains.isValidCookieDomain(testDomain, hostName)) { return domains; } domains.addAll(Domains.getPossibleDomains(testDomain.substring(1))); return domains; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/EmptyInputStream.java0000644000175000017500000000307710726473506026255 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 9, 2005 */ package org.lobobrowser.util; import java.io.IOException; import java.io.InputStream; public class EmptyInputStream extends InputStream { public EmptyInputStream() { super(); } public int read() throws IOException { return -1; } /* (non-Javadoc) * @see java.io.InputStream#available() */ public int available() throws IOException { return 0; } /* (non-Javadoc) * @see java.io.InputStream#close() */ public void close() throws IOException { } /* (non-Javadoc) * @see java.io.InputStream#read(byte[], int, int) */ public int read(byte[] b, int off, int len) throws IOException { return -1; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/EventDispatch.java0000644000175000017500000000434410726473500025514 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Mar 19, 2005 */ package org.lobobrowser.util; import java.util.*; /** * @author J. H. S. */ public class EventDispatch { private Collection listeners; public EventDispatch() { } public Collection createListenerCollection() { return new LinkedList(); } public final void addListener(GenericEventListener listener) { synchronized(this) { if(this.listeners == null) { this.listeners = this.createListenerCollection(); } this.listeners.add(listener); } } public final void removeListener(GenericEventListener listener) { synchronized(this) { if(this.listeners != null) { this.listeners.remove(listener); } } } public final void fireEvent(EventObject event) { GenericEventListener[] larray = null; synchronized(this) { if(this.listeners != null) { larray = (GenericEventListener[]) this.listeners.toArray(GenericEventListener.EMPTY_ARRAY); } } if(larray != null) { for(int i = 0; i < larray.length; i++) { // Call holding no locks larray[i].processEvent(event); } } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/EventDispatch2.java0000644000175000017500000000467510726473502025607 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Mar 19, 2005 */ package org.lobobrowser.util; import java.util.*; /** * @author J. H. S. */ public abstract class EventDispatch2 { private Collection listeners; private static final EventListener[] EMPTY_ARRAY = new EventListener[0]; public EventDispatch2() { } public Collection createListenerCollection() { return new ArrayList(); } public final void addListener(EventListener listener) { synchronized(this) { if(this.listeners == null) { this.listeners = this.createListenerCollection(); } this.listeners.add(listener); } } public final void removeListener(EventListener listener) { synchronized(this) { if(this.listeners != null) { this.listeners.remove(listener); } } } public final boolean fireEvent(EventObject event) { EventListener[] larray; synchronized(this) { Collection listeners = this.listeners; if(listeners == null || listeners.size() == 0) { return false; } larray = (EventListener[]) this.listeners.toArray(EMPTY_ARRAY); } int length = larray.length; for(int i = 0; i < length; i++) { // Call holding no locks this.dispatchEvent(larray[i], event); } return true; } protected abstract void dispatchEvent(EventListener listener, EventObject event); } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/FilteredCollection.java0000644000175000017500000001076410726473506026536 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 8, 2005 */ package org.lobobrowser.util; import java.util.*; public class FilteredCollection implements Collection { private final ObjectFilter filter; private final Collection sourceCollection; public FilteredCollection(Collection sourceCollection, ObjectFilter filter) { this.filter = filter; this.sourceCollection = sourceCollection; } public int size() { int count = 0; Iterator i = this.sourceCollection.iterator(); while(i.hasNext()) { if(this.filter.decode(i.next()) != null) { count++; } } return count; } public boolean isEmpty() { Iterator i = this.sourceCollection.iterator(); while(i.hasNext()) { if(this.filter.decode(i.next()) != null) { return false; } } return true; } public boolean contains(Object o) { return this.sourceCollection.contains(this.filter.encode(o)); } public Iterator iterator() { final Iterator sourceIterator = this.sourceCollection.iterator(); return new Iterator() { private Boolean hasNext; private Object next; private void scanNext() { while(sourceIterator.hasNext()) { Object item = filter.decode(sourceIterator.next()); if(item != null) { hasNext = Boolean.TRUE; this.next = item; } } hasNext = Boolean.FALSE; } /* (non-Javadoc) * @see java.util.Iterator#hasNext() */ public boolean hasNext() { if(this.hasNext == null) { scanNext(); } return this.hasNext.booleanValue(); } /* (non-Javadoc) * @see java.util.Iterator#next() */ public Object next() { if(this.hasNext == null) { scanNext(); } if(Boolean.FALSE.equals(this.hasNext)) { throw new NoSuchElementException(); } Object next = this.next; this.hasNext = null; return next; } /* (non-Javadoc) * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } }; } public Object[] toArray() { return this.toArray(new Object[0]); } public Object[] toArray(Object[] a) { Collection bucket = new ArrayList(); Iterator i = this.sourceCollection.iterator(); while(i.hasNext()) { Object item = this.filter.decode(i.next()); if(item != null) { bucket.add(item); } } return bucket.toArray(a); } public boolean add(Object o) { return this.sourceCollection.add(this.filter.encode(o)); } public boolean remove(Object o) { return this.sourceCollection.remove(this.filter.encode(o)); } public boolean containsAll(Collection c) { Iterator i = c.iterator(); while(i.hasNext()) { if(!this.contains(i.next())) { return false; } } return true; } public boolean addAll(Collection c) { boolean result = false; Iterator i = c.iterator(); while(i.hasNext()) { if(this.add(i.next())) { result = true; } } return result; } public boolean removeAll(Collection c) { boolean result = false; Iterator i = c.iterator(); while(i.hasNext()) { if(this.remove(i.next())) { result = true; } } return result; } public boolean retainAll(Collection c) { boolean result = false; Object[] values = this.toArray(); for(int i = 0; i < values.length; i++) { if(!c.contains(values[i])) { if(this.remove(values[i])) { result = true; } } } return result; } public void clear() { Object[] values = this.toArray(); for(int i = 0; i < values.length; i++) { this.sourceCollection.remove(this.filter.encode(values[i])); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/GenericEventListener.java0000644000175000017500000000232510726473504027040 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Mar 19, 2005 */ package org.lobobrowser.util; import java.util.*; /** * @author J. H. S. */ public interface GenericEventListener extends EventListener { public static final GenericEventListener[] EMPTY_ARRAY = new GenericEventListener[0]; public void processEvent(EventObject event); } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/GenericPropertyChangeListener.java0000644000175000017500000000346510726473502030715 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Mar 19, 2005 */ package org.lobobrowser.util; import java.util.EventObject; import java.beans.*; /** * @author J. H. S. */ public class GenericPropertyChangeListener implements GenericEventListener { private final PropertyChangeListener delegate; public GenericPropertyChangeListener(PropertyChangeListener delegate) { this.delegate = delegate; } /* (non-Javadoc) * @see net.sourceforge.xamj.util.GenericEventListener#processEvent(java.util.EventObject) */ public void processEvent(EventObject event) { this.delegate.propertyChange((PropertyChangeEvent) event); } public boolean equals(Object other) { return other instanceof GenericPropertyChangeListener && ((GenericPropertyChangeListener) other).delegate.equals(this.delegate); } public int hashCode() { return this.delegate.hashCode(); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/GenericURLConnection.java0000644000175000017500000000434610726473506026742 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jun 22, 2005 */ package org.lobobrowser.util; import java.io.IOException; import java.io.InputStream; import java.net.URLConnection; import java.util.Collections; import java.util.Map; /** * @author J. H. S. */ public class GenericURLConnection extends URLConnection { private final java.io.InputStream inputStream; /** * */ public GenericURLConnection(java.net.URL url, InputStream in) { super(url); this.inputStream = in; } /* (non-Javadoc) * @see java.net.URLConnection#connect() */ public void connect() throws IOException { } /* (non-Javadoc) * @see java.net.URLConnection#getInputStream() */ public InputStream getInputStream() throws IOException { return this.inputStream; } /* (non-Javadoc) * @see java.net.URLConnection#getHeaderField(int) */ public String getHeaderField(int n) { return null; } /* (non-Javadoc) * @see java.net.URLConnection#getHeaderField(java.lang.String) */ public String getHeaderField(String name) { return null; } /* (non-Javadoc) * @see java.net.URLConnection#getHeaderFieldKey(int) */ public String getHeaderFieldKey(int n) { return null; } /* (non-Javadoc) * @see java.net.URLConnection#getHeaderFields() */ public Map getHeaderFields() { return Collections.EMPTY_MAP; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/History.java0000644000175000017500000001463610726473500024421 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jun 6, 2005 */ package org.lobobrowser.util; import java.util.*; /** * @author J. H. S. */ public class History implements java.io.Serializable { private static final long serialVersionUID = 2257845000800300100L; private transient ArrayList historySequence; private final SortedSet historySortedSet = new TreeSet(); private final Map historyMap = new HashMap(); private final SortedSet historyTimedSet = new TreeSet(); private int sequenceCapacity; private int commonEntriesCapacity; private transient int sequenceIndex; /** * @param sequenceCapacity * @param commonEntriesCapacity */ public History(int sequenceCapacity, int commonEntriesCapacity) { super(); this.historySequence = new ArrayList(); this.sequenceIndex = -1; this.sequenceCapacity = sequenceCapacity; this.commonEntriesCapacity = commonEntriesCapacity; } private void readObject(java.io.ObjectInputStream in) throws ClassNotFoundException, java.io.IOException { this.historySequence = new ArrayList(); this.sequenceIndex = -1; in.defaultReadObject(); } /** * @return Returns the commonEntriesCapacity. */ public int getCommonEntriesCapacity() { return commonEntriesCapacity; } /** * @param commonEntriesCapacity The commonEntriesCapacity to set. */ public void setCommonEntriesCapacity(int commonEntriesCapacity) { this.commonEntriesCapacity = commonEntriesCapacity; } /** * @return Returns the sequenceCapacity. */ public int getSequenceCapacity() { return sequenceCapacity; } /** * @param sequenceCapacity The sequenceCapacity to set. */ public void setSequenceCapacity(int sequenceCapacity) { this.sequenceCapacity = sequenceCapacity; } public String getCurrentItem() { if(this.sequenceIndex >= 0) { return (String) this.historySequence.get(this.sequenceIndex); } else { return null; } } public String back() { if(this.sequenceIndex > 0) { this.sequenceIndex--; return this.getCurrentItem(); } else { return null; } } public String forward() { if(this.sequenceIndex + 1 < this.historySequence.size()) { this.sequenceIndex++; return this.getCurrentItem(); } else { return null; } } public Collection getRecentItems(int maxNumItems) { Collection items = new LinkedList(); Iterator i = this.historyTimedSet.iterator(); int count = 0; while(i.hasNext() && count++ < maxNumItems) { TimedEntry entry = (TimedEntry) i.next(); items.add(entry.value); } return items; } public Collection getHeadMatchItems(String item, int maxNumItems) { Object[] array = this.historySortedSet.toArray(); int idx = Arrays.binarySearch(array, item); int startIdx = idx >= 0 ? idx : (-idx - 1); int count = 0; Collection items = new LinkedList(); for(int i = startIdx; i < array.length && (count++ < maxNumItems); i++) { String potentialItem = (String) array[i]; if(potentialItem.startsWith(item)) { items.add(potentialItem); } else { break; } } return items; } public void addAsRecentOnly(String item) { TimedEntry entry = (TimedEntry) this.historyMap.get(item); if(entry != null) { this.historyTimedSet.remove(entry); entry.touch(); this.historyTimedSet.add(entry); } else { entry = new TimedEntry(item); this.historyTimedSet.add(entry); this.historyMap.put(item, entry); this.historySortedSet.add(item); if(this.historyTimedSet.size() > this.commonEntriesCapacity) { // Most outdated goes last TimedEntry entryToRemove = (TimedEntry) this.historyTimedSet.last(); this.historyMap.remove(entryToRemove.value); this.historySortedSet.remove(entryToRemove.value); this.historyTimedSet.remove(entryToRemove); } } } public void addItem(String item, boolean updateAsRecent) { int newIndex = this.sequenceIndex + 1; while(newIndex >= this.historySequence.size()) { this.historySequence.add(null); } this.historySequence.set(newIndex, item); this.sequenceIndex = newIndex; int expectedSize = newIndex + 1; while(this.historySequence.size() > expectedSize) { this.historySequence.remove(expectedSize); } while(this.historySequence.size() > this.sequenceCapacity) { this.historySequence.remove(0); this.sequenceIndex--; } if(updateAsRecent) { this.addAsRecentOnly(item); } } private class TimedEntry implements Comparable, java.io.Serializable { private static final long serialVersionUID = 2257845000000000200L; private long timestamp = System.currentTimeMillis(); private final String value; /** * @param value */ public TimedEntry(String value) { this.value = value; } public void touch() { this.timestamp = System.currentTimeMillis(); } public boolean equals(Object obj) { TimedEntry other = (TimedEntry) obj; return other.value.equals(this.value); } /* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(Object arg0) { if(this.equals(arg0)) { return 0; } TimedEntry other = (TimedEntry) arg0; long time1 = this.timestamp; long time2 = other.timestamp; if(time1 > time2) { // More recent goes first return -1; } else if(time2 > time1){ return +1; } else { int diff = System.identityHashCode(this) - System.identityHashCode(other); if(diff == 0) { return +1; } return diff; } } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/Html.java0000644000175000017500000000414610756064602023661 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.util; public class Html { public static String textToHTML(String text) { if(text == null) { return null; } int length = text.length(); boolean prevSlashR = false; StringBuffer out = new StringBuffer(); for(int i = 0; i < length; i++) { char ch = text.charAt(i); switch(ch) { case '\r': if(prevSlashR) { out.append("
"); } prevSlashR = true; break; case '\n': prevSlashR = false; out.append("
"); break; case '"': if(prevSlashR) { out.append("
"); prevSlashR = false; } out.append("""); break; case '<': if(prevSlashR) { out.append("
"); prevSlashR = false; } out.append("<"); break; case '>': if(prevSlashR) { out.append("
"); prevSlashR = false; } out.append(">"); break; case '&': if(prevSlashR) { out.append("
"); prevSlashR = false; } out.append("&"); break; default: if(prevSlashR) { out.append("
"); prevSlashR = false; } out.append(ch); break; } } return out.toString(); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/ID.java0000644000175000017500000000663010726473476023263 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jun 7, 2005 */ package org.lobobrowser.util; import java.util.*; import java.util.logging.*; import java.security.*; import java.math.*; import java.net.InetAddress; /** * @author J. H. S. */ public class ID { private static final Random RANDOM1; private static final Random RANDOM2; private static final Random RANDOM3; private static final long globalProcessID; private static final Logger logger = Logger.getLogger(ID.class.getName()); static { long time = System.currentTimeMillis(); long nanoTime = System.nanoTime(); long freeMemory = Runtime.getRuntime().freeMemory(); long addressHashCode; try { InetAddress inetAddress; inetAddress = InetAddress.getLocalHost(); addressHashCode = inetAddress.getHostName().hashCode() ^ inetAddress.getHostAddress().hashCode(); } catch(Exception err) { logger.log(Level.WARNING, "Unable to get local host information.", err); addressHashCode = ID.class.hashCode(); } globalProcessID = time ^ nanoTime ^ freeMemory ^ addressHashCode; RANDOM1 = new Random(time); RANDOM2 = new Random(nanoTime); RANDOM3 = new Random(addressHashCode ^ freeMemory); } private ID() { } public static long generateLong() { return Math.abs(RANDOM1.nextLong() ^ RANDOM2.nextLong() ^ RANDOM3.nextLong()); } public static int generateInt() { return (int) generateLong(); } public static byte[] getMD5Bytes(String content) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); return digest.digest(content.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } catch(java.io.UnsupportedEncodingException uee) { throw new IllegalStateException(uee); } } public static String getHexString(byte[] bytes) { // This method cannot change even if it's wrong. BigInteger bigInteger = BigInteger.ZERO; int shift = 0; for(int i = bytes.length; --i >= 0;) { BigInteger contrib = BigInteger.valueOf(bytes[i] & 0xFF); contrib = contrib.shiftLeft(shift); bigInteger = bigInteger.add(contrib); shift += 8; } return bigInteger.toString(16).toUpperCase(); } /** * Gets a process ID that is nearly guaranteed to be globally unique. */ public static long getGlobalProcessID() { return globalProcessID; } public static int random(int min, int max) { if(max <= min) { return min; } return Math.abs(RANDOM1.nextInt()) % (max - min) + min; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/InputProgressEvent.java0000644000175000017500000000245110726473506026604 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 15, 2005 */ package org.lobobrowser.util; import java.util.EventObject; /** * @author J. H. S. */ public class InputProgressEvent extends EventObject { private final int progress; /** * @param arg0 */ public InputProgressEvent(Object arg0, int progress) { super(arg0); this.progress = progress; } public int getProgress() { return this.progress; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/Items.java0000644000175000017500000000126610620620322024021 0ustar twernertwernerpackage org.lobobrowser.util; import java.util.*; public class Items { private Items() { } private static Map sourceMap = new WeakHashMap(); public static Object getItem(Object source, String name) { Map sm = sourceMap; synchronized(sm) { Map itemMap = (Map) sm.get(source); if(itemMap == null) { return null; } return itemMap.get(name); } } public static void setItem(Object source, String name, Object value) { Map sm = sourceMap; synchronized(sm) { Map itemMap = (Map) sm.get(source); if(itemMap == null) { itemMap = new HashMap(1); sm.put(source, itemMap); } itemMap.put(name, value); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/JoinableTask.java0000644000175000017500000000140410620620322025300 0ustar twernertwernerpackage org.lobobrowser.util; /** * A task that can be used in a thread or thread pool. * The caller can wait for the task to finish by joining it. */ public abstract class JoinableTask implements SimpleThreadPoolTask { private boolean done = false; public final void run() { try { this.execute(); } finally { synchronized(this) { this.done = true; this.notifyAll(); } } } public final void forceDone() { synchronized(this) { this.done = true; this.notifyAll(); } } public void join() throws InterruptedException { synchronized(this) { while(!this.done) { this.wait(); } } } public void cancel() { this.forceDone(); } protected abstract void execute(); } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/LRUCache.java0000644000175000017500000001446111033114036024326 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.util; import java.util.*; /** * A cache with least-recently-used policy. * Note that this class is not thread safe by itself. */ public class LRUCache implements java.io.Serializable { private static final long serialVersionUID = 940427225784212823L; private int approxMaxSize; private final Map cacheMap = new HashMap(); private volatile transient EventDispatch2 removalEvent; /** * Ascending timestamp order. First is least recently used. */ private final TreeSet timedSet = new TreeSet(); private int currentSize = 0; public LRUCache(int approxMaxSize) { this.approxMaxSize = approxMaxSize; this.removalEvent = new RemovalDispatch(); } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { in.defaultReadObject(); // Need to initialize transient fields here. this.removalEvent = new RemovalDispatch(); } public int getApproxMaxSize() { return approxMaxSize; } public void setApproxMaxSize(int approxMaxSize) { this.approxMaxSize = approxMaxSize; } public void put(Object key, Object value, int approxSize) { if(approxSize > this.approxMaxSize) { // Can't be inserted. return; } OrderedValue ordVal = (OrderedValue) this.cacheMap.get(key); if(ordVal != null) { if(ordVal.value != value) { this.removalEvent.fireEvent(new RemovalEvent(this, ordVal.value)); } this.currentSize += (approxSize - ordVal.approximateSize); this.timedSet.remove(ordVal); ordVal.approximateSize = approxSize; ordVal.value = value; ordVal.touch(); this.timedSet.add(ordVal); } else { ordVal = new OrderedValue(key, value, approxSize); this.cacheMap.put(key, ordVal); this.timedSet.add(ordVal); this.currentSize += approxSize; } while(this.currentSize > this.approxMaxSize) { this.removeLRU(); } } private void removeLRU() { OrderedValue ordVal = (OrderedValue) this.timedSet.first(); if(ordVal != null) { this.removalEvent.fireEvent(new RemovalEvent(this, ordVal.value)); if(this.timedSet.remove(ordVal)) { this.cacheMap.remove(ordVal.key); this.currentSize -= ordVal.approximateSize; } else { throw new IllegalStateException("Could not remove existing tree node."); } } else { throw new IllegalStateException("Cannot remove LRU since the cache is empty."); } } public Object get(Object key) { OrderedValue ordVal = (OrderedValue) this.cacheMap.get(key); if(ordVal != null) { this.timedSet.remove(ordVal); ordVal.touch(); this.timedSet.add(ordVal); return ordVal.value; } else { return null; } } public Object remove(Object key) { OrderedValue ordVal = (OrderedValue) this.cacheMap.get(key); if(ordVal != null) { this.removalEvent.fireEvent(new RemovalEvent(this, ordVal.value)); this.currentSize -= ordVal.approximateSize; this.timedSet.remove(ordVal); return ordVal.value; } else { return null; } } public void addRemovalListener(RemovalListener listener) { this.removalEvent.addListener(listener); } public void removeRemovalListener(RemovalListener listener) { this.removalEvent.removeListener(listener); } public int getApproxSize() { return this.currentSize; } public int getNumEntries() { return this.cacheMap.size(); } public List getEntryInfoList() { List list = new ArrayList(); Iterator i = this.cacheMap.values().iterator(); while(i.hasNext()) { OrderedValue ov = (OrderedValue) i.next(); Object value = ov.value; Class vc = value == null ? null : value.getClass(); list.add(new EntryInfo(vc, ov.approximateSize)); } return list; } public static class EntryInfo { public final Class valueClass; public final int approximateSize; public EntryInfo(final Class valueClass, final int approximateSize) { super(); this.valueClass = valueClass; this.approximateSize = approximateSize; } public String toString() { Class vc = this.valueClass; String vcName = vc == null ? "" : vc.getName(); return "[class=" + vcName + ",approx-size=" + this.approximateSize + "]"; } } private class OrderedValue implements Comparable, java.io.Serializable { private static final long serialVersionUID = 340227625744215821L; private long timestamp; private int approximateSize; private Object value; private Object key; private OrderedValue(Object key, Object value, int approxSize) { this.key = key; this.value = value; this.approximateSize = approxSize; this.touch(); } private final void touch() { this.timestamp = System.currentTimeMillis(); } public int compareTo(Object arg0) { if(this == arg0) { return 0; } OrderedValue other = (OrderedValue) arg0; long diff = this.timestamp - other.timestamp; if(diff > 0) { return +1; } else if(diff < 0) { return -1; } int hc1 = System.identityHashCode(this); int hc2 = System.identityHashCode(other); if(hc1 == hc2) { hc1 = System.identityHashCode(this.value); hc2 = System.identityHashCode(other.value); } return hc1 - hc2; } } private class RemovalDispatch extends EventDispatch2 { protected void dispatchEvent(EventListener listener, EventObject event) { ((RemovalListener) listener).removed((RemovalEvent) event); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/ListSet.java0000644000175000017500000001272610726473510024346 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Sep 3, 2005 */ package org.lobobrowser.util; import java.util.*; public class ListSet implements List, Set { private final List list = new ArrayList(); private final Set set = new HashSet(); public ListSet() { super(); } /* (non-Javadoc) * @see java.util.List#add(int, E) */ public void add(int index, Object element) { if(this.set.add(element)) { list.add(index, element); } } /* (non-Javadoc) * @see java.util.List#add(E) */ public boolean add(Object o) { if(this.set.add(o)) { return this.list.add(o); } else { return false; } } /* (non-Javadoc) * @see java.util.List#addAll(java.util.Collection) */ public boolean addAll(Collection c) { boolean changed = false; Iterator i = c.iterator(); while(i.hasNext()) { Object element = i.next(); if(this.add(element)) { changed = true; } } return changed; } /* (non-Javadoc) * @see java.util.List#addAll(int, java.util.Collection) */ public boolean addAll(int index, Collection c) { boolean changed = false; int insertIndex = index; Iterator i = c.iterator(); while(i.hasNext()) { Object element = i.next(); if(this.set.add(element)) { this.list.add(insertIndex++, element); changed = true; } } return changed; } /* (non-Javadoc) * @see java.util.List#clear() */ public void clear() { this.set.clear(); this.list.clear(); } /* (non-Javadoc) * @see java.util.List#contains(java.lang.Object) */ public boolean contains(Object o) { return this.set.contains(o); } /* (non-Javadoc) * @see java.util.List#containsAll(java.util.Collection) */ public boolean containsAll(Collection c) { return this.set.containsAll(c); } /* (non-Javadoc) * @see java.util.List#get(int) */ public Object get(int index) { return this.list.get(index); } /* (non-Javadoc) * @see java.util.List#indexOf(java.lang.Object) */ public int indexOf(Object o) { return this.list.indexOf(o); } /* (non-Javadoc) * @see java.util.List#isEmpty() */ public boolean isEmpty() { return this.set.isEmpty(); } /* (non-Javadoc) * @see java.util.List#iterator() */ public Iterator iterator() { return this.list.iterator(); } /* (non-Javadoc) * @see java.util.List#lastIndexOf(java.lang.Object) */ public int lastIndexOf(Object o) { return this.list.lastIndexOf(o); } /* (non-Javadoc) * @see java.util.List#listIterator() */ public ListIterator listIterator() { return this.list.listIterator(); } /* (non-Javadoc) * @see java.util.List#listIterator(int) */ public ListIterator listIterator(int index) { return this.list.listIterator(index); } /* (non-Javadoc) * @see java.util.List#remove(int) */ public Object remove(int index) { Object element = this.list.remove(index); if(element != null) { this.set.remove(element); } return element; } /* (non-Javadoc) * @see java.util.List#remove(java.lang.Object) */ public boolean remove(Object o) { if(this.set.remove(o)) { this.list.remove(o); return true; } else { return false; } } /* (non-Javadoc) * @see java.util.List#removeAll(java.util.Collection) */ public boolean removeAll(Collection c) { if(this.set.removeAll(c)) { this.list.removeAll(c); return true; } else { return false; } } /* (non-Javadoc) * @see java.util.List#retainAll(java.util.Collection) */ public boolean retainAll(Collection c) { if(this.set.retainAll(c)) { this.list.retainAll(c); return true; } else { return false; } } /* (non-Javadoc) * @see java.util.List#set(int, E) */ public Object set(int index, Object element) { this.set.add(element); return this.list.set(index, element); } /* (non-Javadoc) * @see java.util.List#size() */ public int size() { return this.list.size(); } /* (non-Javadoc) * @see java.util.List#subList(int, int) */ public List subList(int fromIndex, int toIndex) { return this.list.subList(fromIndex, toIndex); } /* (non-Javadoc) * @see java.util.List#toArray() */ public Object[] toArray() { return this.list.toArray(); } /* (non-Javadoc) * @see java.util.List#toArray(T[]) */ public Object[] toArray(Object[] a) { return this.list.toArray(a); } public boolean equals(Object other) { return other instanceof ListSet && this.list.equals(((ListSet) other).list); } public int hashCode() { return this.list.hashCode(); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/MonitoredInputStream.java0000644000175000017500000000522010726473502027103 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 15, 2005 */ package org.lobobrowser.util; import java.io.*; /** * @author J. H. S. */ public class MonitoredInputStream extends InputStream { private final InputStream delegate; private int progress = 0; private final long minProgressEventGap; public final EventDispatch evtProgress = new EventDispatch(); public MonitoredInputStream(InputStream delegate, int minProgressEventGap) { this.delegate = delegate; this.minProgressEventGap = minProgressEventGap; } public MonitoredInputStream(InputStream delegate) { this(delegate, 200); } /* (non-Javadoc) * @see java.io.InputStream#available() */ public int available() throws IOException { return this.delegate.available(); } /* (non-Javadoc) * @see java.io.InputStream#close() */ public void close() throws IOException { this.delegate.close(); } /* (non-Javadoc) * @see java.io.InputStream#markSupported() */ public boolean markSupported() { return false; } /* (non-Javadoc) * @see java.io.InputStream#read() */ public int read() throws IOException { int b = this.delegate.read(); if(b != -1) { this.progress++; } return b; } private long lastEvenPosted = 0; /* (non-Javadoc) * @see java.io.InputStream#read(byte[], int, int) */ public int read(byte[] arg0, int arg1, int arg2) throws IOException { int numRead = this.delegate.read(arg0, arg1, arg2); if(numRead != -1) { this.progress += numRead; long currentTime = System.currentTimeMillis(); if(currentTime - this.lastEvenPosted > this.minProgressEventGap) { this.evtProgress.fireEvent(new InputProgressEvent(this, this.progress)); this.lastEvenPosted = currentTime; } } return numRead; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/MultiplexClassLoader.java0000644000175000017500000000472710726473506027066 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jun 19, 2005 */ package org.lobobrowser.util; import java.util.*; /** * @author J. H. S. */ public abstract class MultiplexClassLoader extends BaseClassLoader { private static final BaseClassLoader[] EMPTY_CLASS_LOADERS = new BaseClassLoader[0]; private final BaseClassLoader[] parentLoaders; /** * @param parent */ public MultiplexClassLoader(Collection classLoaders) { super(null); this.parentLoaders = (BaseClassLoader[]) classLoaders.toArray(EMPTY_CLASS_LOADERS); } /* (non-Javadoc) * @see java.lang.ClassLoader#loadClass(java.lang.String, boolean) */ public synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { // First, check if the class has already been loaded Class c = findLoadedClass(name); if (c == null) { try { int len = this.parentLoaders.length; if(len == 0) { c = findSystemClass(name); } else { for(int i = 0; i < len; i++) { BaseClassLoader parent = this.parentLoaders[i]; try { c = parent.loadClass(name, false); if(c != null) { return c; } } catch(ClassNotFoundException cnfe) { // ignore } } } } catch (ClassNotFoundException e) { // If still not found, then invoke findClass in order // to find the class. c = findClass(name); } if(c == null) { c = findClass(name); } } if (resolve) { resolveClass(c); } return c; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/NameValuePair.java0000644000175000017500000000303010746432060025431 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jun 12, 2005 */ package org.lobobrowser.util; /** * @author J. H. S. */ public class NameValuePair implements java.io.Serializable { private static final long serialVersionUID = 22574500600001010L; public final String name; public final String value; /** * @param name * @param value */ public NameValuePair(final String name, final String value) { super(); this.name = name; this.value = value; } /** * @return Returns the name. */ public String getName() { return name; } /** * @return Returns the value. */ public String getValue() { return value; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/Nodes.java0000644000175000017500000000124010620620320023776 0ustar twernertwernerpackage org.lobobrowser.util; import org.w3c.dom.*; public class Nodes { public static Node getCommonAncestor(Node node1, Node node2) { if(node1 == null || node2 == null) { return null; } Node checkNode = node1; while(!isSameOrAncestorOf(checkNode, node2)) { checkNode = checkNode.getParentNode(); if(checkNode == null) { return null; } } return checkNode; } public static boolean isSameOrAncestorOf(Node node, Node child) { if(child.isSameNode(node)) { return true; } Node parent = child.getParentNode(); if(parent == null) { return false; } return isSameOrAncestorOf(node, parent); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/OS.java0000644000175000017500000000373410726473506023304 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on May 14, 2005 */ package org.lobobrowser.util; /** * @author J. H. S. */ public class OS { /** * */ private OS() { super(); } public static boolean isWindows() { String osName = System.getProperty("os.name"); return osName.indexOf("Windows") != -1; } public static void launchBrowser(String url) throws java.io.IOException { String cmdLine; if(isWindows()) { cmdLine = "rundll32 url.dll,FileProtocolHandler " + url; } else { cmdLine = "firefox " + url; } try { Runtime.getRuntime().exec(cmdLine); } catch(java.io.IOException ioe) { Runtime.getRuntime().exec("netscape " + url); } } /** * Opens a file a directory with an appropriate program. */ public static void launchPath(String path) throws java.io.IOException { if(isWindows()) { Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", "start", "\"title\"", path }); } else { throw new UnsupportedOperationException("Unsupported"); } } public static boolean supportsLaunchPath() { return isWindows(); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/ObjectFilter.java0000644000175000017500000000207310726473502025326 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 8, 2005 */ package org.lobobrowser.util; public interface ObjectFilter { public Object decode(Object source); public Object encode(Object source); } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/Objects.java0000644000175000017500000000606610742111044024335 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 10, 2005 */ package org.lobobrowser.util; /** * @author J. H. S. */ public class Objects { /** * */ private Objects() { } public static boolean equals(Object obj1, Object obj2) { return obj1 == null ? (obj2 == null) : (obj1.equals(obj2)); } public static boolean isBoxClass(Class clazz) { return clazz == Integer.class || clazz == Boolean.class || clazz == Double.class || clazz == Float.class || clazz == Long.class || clazz == Byte.class || clazz == Short.class || clazz == Character.class; } public static boolean areAssignableTo(Object[] objects, Class[] types) { int length = objects.length; if(length != types.length) { return false; } for(int i = 0; i < length; i++) { if(!isAssignableOrBox(objects[i], types[i])) { return false; } } return true; } public static boolean isAssignableOrBox(Object value, Class clazz) { if(clazz.isInstance(value)) { return true; } if(clazz.isPrimitive()) { if((clazz == double.class && value instanceof Double) || (clazz == int.class && value instanceof Integer) || (clazz == long.class && value instanceof Long) || (clazz == boolean.class && value instanceof Boolean) || (clazz == byte.class && value instanceof Byte) || (clazz == char.class && value instanceof Character) || (clazz == short.class && value instanceof Short) || (clazz == float.class && value instanceof Float) ) { return true; } } if(isNumeric(clazz) && isNumeric(value)) { return true; } if(clazz.isAssignableFrom(String.class)) { return value == null || !value.getClass().isPrimitive(); } return false; } private static boolean isNumeric(Class clazz) { return Number.class.isAssignableFrom(clazz) || (clazz.isPrimitive() && (clazz == int.class || clazz == double.class || clazz == byte.class || clazz == short.class || clazz == float.class || clazz == long.class) ); } private static boolean isNumeric(Object value) { if(value == null) { return false; } return isNumeric(value.getClass()); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/RemovalEvent.java0000644000175000017500000000223010756053670025357 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.util; import java.util.EventObject; public class RemovalEvent extends EventObject { public final Object valueRemoved; public RemovalEvent(Object source, Object valueRemoved) { super(source); this.valueRemoved = valueRemoved; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/RemovalListener.java0000644000175000017500000000206010756053576026071 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.util; import java.util.EventListener; public interface RemovalListener extends EventListener { public void removed(RemovalEvent event); } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/SimpleThreadPool.java0000644000175000017500000000772311125655702026172 0ustar twernertwernerpackage org.lobobrowser.util; import java.util.*; import java.util.logging.*; /** * A thread pool that allows cancelling all running tasks without * shutting down the thread pool. */ public class SimpleThreadPool { private static final Logger logger = Logger.getLogger(SimpleThreadPool.class.getName()); private final LinkedList taskList = new LinkedList(); private final Set runningSet = new HashSet(); private final int minThreads; private final int maxThreads; private final String name; private final int idleAliveMillis; private final Object taskMonitor = new Object(); private final ThreadGroup threadGroup; private int numThreads = 0; private int numIdleThreads = 0; private int threadNumber = 0; public SimpleThreadPool(String name, int minShrinkToThreads, int maxThreads, int idleAliveMillis) { this.minThreads = minShrinkToThreads; this.maxThreads = maxThreads; this.idleAliveMillis = idleAliveMillis; this.name = name; // Thread group needed so item requests // don't get assigned sub-thread groups. //TODO: Thread group needs to be thought through. It's retained in //memory, and we need to return the right one in the GUI thread as well. this.threadGroup = null; //new ThreadGroup(name); } public void schedule(SimpleThreadPoolTask task) { if(task == null) { throw new IllegalArgumentException("null task"); } Object monitor = this.taskMonitor; synchronized(monitor) { if(this.numIdleThreads == 0) { this.addThreadImpl(); } this.taskList.add(task); monitor.notify(); } } public void cancel(SimpleThreadPoolTask task) { synchronized(this.taskMonitor) { this.taskList.remove(task); } task.cancel(); } private void addThreadImpl() { if(this.numThreads < this.maxThreads) { Thread t = new Thread(this.threadGroup, new ThreadRunnable(), this.name + this.threadNumber++); t.setDaemon(true); t.start(); this.numThreads++; } } /** * Cancels all waiting tasks and any currently running task. */ public void cancelAll() { synchronized(this.taskMonitor) { this.taskList.clear(); Iterator i = this.runningSet.iterator(); while(i.hasNext()) { ((SimpleThreadPoolTask) i.next()).cancel(); } } } private class ThreadRunnable implements Runnable { public void run() { Object monitor = taskMonitor; LinkedList tl = taskList; Set rs = runningSet; int iam = idleAliveMillis; SimpleThreadPoolTask task = null; for(;;) { try { synchronized(monitor) { if(task != null) { rs.remove(task); } numIdleThreads++; try { long waitBase = System.currentTimeMillis(); INNER: while(tl.isEmpty()) { long maxWait = iam - (System.currentTimeMillis() - waitBase); if(maxWait <= 0) { if(numThreads > minThreads) { // Should be only way to exit thread. numThreads--; return; } else { waitBase = System.currentTimeMillis(); continue INNER; } } monitor.wait(maxWait); } } finally { numIdleThreads--; } task = (SimpleThreadPoolTask) taskList.removeFirst(); rs.add(task); } Thread currentThread = Thread.currentThread(); String baseName = currentThread.getName(); try { try { currentThread.setName(baseName + ":" + task.toString()); } catch(Throwable thrown) { logger.log(Level.WARNING, "run(): Unable to set task name.", thrown); } try { task.run(); } catch(Throwable thrown) { logger.log(Level.SEVERE, "run(): Error in task: " + task + ".", thrown); } } finally { currentThread.setName(baseName); } } catch(Throwable thrown) { logger.log(Level.SEVERE, "run(): Error in thread pool: " + SimpleThreadPool.this.name + ".", thrown); } } } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/SimpleThreadPoolTask.java0000644000175000017500000000016610620620322026774 0ustar twernertwernerpackage org.lobobrowser.util; public interface SimpleThreadPoolTask extends Runnable { public void cancel(); } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/Strings.java0000644000175000017500000002425311125124144024374 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.util; import java.io.*; import java.security.*; import java.util.ArrayList; public class Strings { private static final MessageDigest MESSAGE_DIGEST; public static final String[] EMPTY_ARRAY = new String[0]; static { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch(NoSuchAlgorithmException err) { throw new IllegalStateException(); } MESSAGE_DIGEST = md; } private Strings() {} public static int compareVersions(String version1, String version2, boolean startsWithDigits) { if(version1 == null) { return version2 == null ? 0 : -1; } else if(version2 == null) { return +1; } if(startsWithDigits) { String v1prefix = leadingDigits(version1); String v2prefix = leadingDigits(version2); if(v1prefix.length() == 0) { if(v2prefix.length() == 0) { return 0; } return -1; } else if(v2prefix.length() == 0) { return +1; } int diff; try { diff = Integer.parseInt(v1prefix) - Integer.parseInt(v2prefix); } catch(NumberFormatException nfe) { diff = 0; } if(diff == 0) { return compareVersions(version1.substring(v1prefix.length()), version2.substring(v2prefix.length()), false); } return diff; } else { String v1prefix = leadingNonDigits(version1); String v2prefix = leadingNonDigits(version2); if(v1prefix.length() == 0) { if(v2prefix.length() == 0) { return 0; } return -1; } else if(v2prefix.length() == 0) { return +1; } int diff = v1prefix.compareTo(v2prefix); if(diff == 0) { return compareVersions(version1.substring(v1prefix.length()), version2.substring(v2prefix.length()), true); } return diff; } } public static String leadingDigits(String text) { int length = text.length(); StringBuffer buffer = null; for(int i = 0; i < length; i++) { char ch = text.charAt(i); if(!Character.isDigit(ch)) { break; } if(buffer == null) { buffer = new StringBuffer(3); } buffer.append(ch); } return buffer == null ? "" : buffer.toString(); } public static String leadingNonDigits(String text) { int length = text.length(); StringBuffer buffer = null; for(int i = 0; i < length; i++) { char ch = text.charAt(i); if(Character.isDigit(ch)) { break; } if(buffer == null) { buffer = new StringBuffer(3); } buffer.append(ch); } return buffer == null ? "" : buffer.toString(); } public static boolean isBlank(String text) { return text == null || "".equals(text); } public static int countLines(String text) { int startIdx = 0; int lineCount = 1; for(;;) { int lbIdx = text.indexOf('\n', startIdx); if(lbIdx == -1) { break; } lineCount++; startIdx = lbIdx + 1; } return lineCount; } public static boolean isJavaIdentifier(String id) { if(id == null) { return false; } int len = id.length(); if(len == 0) { return false; } if(!Character.isJavaIdentifierStart(id.charAt(0))) { return false; } for(int i = 1; i < len; i++) { if(!Character.isJavaIdentifierPart(id.charAt(i))) { return false; } } return true; } public static String getJavaStringLiteral(String text) { StringBuffer buf = new StringBuffer(); buf.append('"'); int len = text.length(); for(int i = 0; i < len; i++) { char ch = text.charAt(i); switch(ch) { case '\\': buf.append("\\\\"); break; case '\n': buf.append("\\n"); break; case '\r': buf.append("\\r"); break; case '\t': buf.append("\\t"); break; case '"': buf.append("\\\""); break; default: buf.append(ch); break; } } buf.append('"'); return buf.toString(); } public static String getJavaIdentifier(String candidateID) { int len = candidateID.length(); StringBuffer buf = new StringBuffer(); for(int i = 0; i < len; i++) { char ch = candidateID.charAt(i); boolean good = i == 0 ? Character.isJavaIdentifierStart(ch) : Character.isJavaIdentifierPart(ch); if(good) { buf.append(ch); } else { buf.append('_'); } } return buf.toString(); } private static final String HEX_CHARS = "0123456789ABCDEF"; public static String getMD5(String source) { byte[] bytes; try { bytes = source.getBytes("UTF-8"); } catch(java.io.UnsupportedEncodingException ue) { throw new IllegalStateException(ue); } byte[] result; synchronized(MESSAGE_DIGEST) { MESSAGE_DIGEST.update(bytes); result = MESSAGE_DIGEST.digest(); } char[] resChars = new char[32]; int len = result.length; for(int i = 0; i < len; i++) { byte b = result[i]; int lo4 = b & 0x0F; int hi4 = (b & 0xF0) >> 4; resChars[i*2] = HEX_CHARS.charAt(hi4); resChars[i*2 + 1] = HEX_CHARS.charAt(lo4); } return new String(resChars); } public static String getHash32(String source) throws UnsupportedEncodingException { String md5 = getMD5(source); return md5.substring(0, 8); } public static String getHash64(String source) throws UnsupportedEncodingException { String md5 = getMD5(source); return md5.substring(0, 16); } public static int countChars(String text, char ch) { int len = text.length(); int count = 0; for(int i = 0; i < len; i++) { if(ch == text.charAt(i)) { count++; } } return count; } // public static boolean isTrimmable(char ch) { // switch(ch) { // case ' ': // case '\t': // case '\r': // case '\n': // return true; // } // return false; // } // // /** // * Trims blanks, line breaks and tabs. // * @param text // * @return // */ // public static String trim(String text) { // int len = text.length(); // int startIdx; // for(startIdx = 0; startIdx < len; startIdx++) { // char ch = text.charAt(startIdx); // if(!isTrimmable(ch)) { // break; // } // } // int endIdx; // for(endIdx = len; --endIdx > startIdx; ) { // char ch = text.charAt(endIdx); // if(!isTrimmable(ch)) { // break; // } // } // return text.substring(startIdx, endIdx + 1); // } public static String unquote(String text) { if(text.startsWith("\"") && text.endsWith("\"")) { // substring works on indices return text.substring(1, text.length() - 1); } return text; } public static String[] split(String phrase) { int length = phrase.length(); ArrayList wordList = new ArrayList(); StringBuffer word = null; for(int i = 0; i < length; i++) { char ch = phrase.charAt(i); switch(ch) { case ' ': case '\t': case '\r': case '\n': if(word != null) { wordList.add(word.toString()); word = null; } break; default: if(word == null) { word = new StringBuffer(); } word.append(ch); } } if(word != null) { wordList.add(word.toString()); } return (String[]) wordList.toArray(EMPTY_ARRAY); } public static String truncate(String text, int maxLength) { if(text == null) { return null; } if(text.length() <= maxLength) { return text; } return text.substring(0, Math.max(maxLength - 3, 0)) + "..."; } public static String strictHtmlEncode(String rawText, boolean quotes) { StringBuffer output = new StringBuffer(); int length = rawText.length(); for(int i = 0; i < length; i++) { char ch = rawText.charAt(i); switch(ch) { case '&': output.append("&"); break; case '"': if(quotes) { output.append("""); } else { output.append(ch); } break; case '<': output.append("<"); break; case '>': output.append(">"); break; default: output.append(ch); } } return output.toString(); } public static String trimForAlphaNumDash(String rawText) { int length = rawText.length(); for(int i = 0; i < length; i++) { char ch = rawText.charAt(i); if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '-') { continue; } return rawText.substring(0, i); } return rawText; } public static String getCRLFString(String original) { if(original == null) { return null; } int length = original.length(); StringBuffer buffer = new StringBuffer(); boolean lastSlashR = false; for(int i = 0; i < length; i++) { char ch = original.charAt(i); switch(ch) { case '\r': lastSlashR = true; break; case '\n': lastSlashR = false; buffer.append("\r\n"); break; default: if(lastSlashR) { lastSlashR = false; buffer.append("\r\n"); } buffer.append(ch); break; } } return buffer.toString(); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/Timing.java0000644000175000017500000000325310726473510024201 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.util; public class Timing { public static double round1(double value) { return Math.round(value * 10.0) / 10.0; } public static String getElapsedText(long elapsedMillis) { if(elapsedMillis < 60000) { double unit = round1(elapsedMillis / 1000.0); return unit + (unit == 1 ? " second" : " seconds"); } else if(elapsedMillis < 60000 * 60) { double unit = round1(elapsedMillis / 60000.0); return unit + (unit == 1 ? " minute" : " minutes"); } else if(elapsedMillis < 60000 * 60 * 24) { double unit = round1(elapsedMillis / (60000.0 * 60)); return unit + (unit == 1 ? " hour" : " hours"); } else { double unit = round1(elapsedMillis / (60000.0 * 60 * 24)); return unit + (unit == 1 ? " day" : " days"); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/Urls.java0000644000175000017500000002043311134574706023701 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jun 12, 2005 */ package org.lobobrowser.util; import java.net.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.logging.*; public class Urls { private static final Logger logger = Logger.getLogger(Urls.class.getName()); public static final DateFormat PATTERN_RFC1123 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); static { DateFormat df = PATTERN_RFC1123; df.setTimeZone(TimeZone.getTimeZone("GMT")); } private Urls() { super(); } /** Whether the URL refers to a resource in the local file system. */ public static boolean isLocal(java.net.URL url) { if(isLocalFile(url)) { return true; } String protocol = url.getProtocol(); if("jar".equalsIgnoreCase(protocol)) { String path = url.getPath(); int emIdx = path.lastIndexOf('!'); String subUrlString = emIdx == -1 ? path : path.substring(0, emIdx); try { URL subUrl = new URL(subUrlString); return isLocal(subUrl); } catch(java.net.MalformedURLException mfu) { return false; } } else { return false; } } /** Whether the URL is a file in the local file system. */ public static boolean isLocalFile(java.net.URL url) { String scheme = url.getProtocol(); return "file".equalsIgnoreCase(scheme) && !hasHost(url); } public static boolean hasHost(java.net.URL url) { String host = url.getHost(); return host != null && !"".equals(host); } /** * Creates an absolute URL in a manner equivalent to * major browsers. */ public static URL createURL(URL baseUrl, String relativeUrl) throws java.net.MalformedURLException { return new URL(baseUrl, relativeUrl); } /** * Returns the time when the document should be considered expired. * The time will be zero if the document always needs to be revalidated. * It will be null if no expiration time is specified. */ public static Long getExpiration(URLConnection connection, long baseTime) { String cacheControl = connection.getHeaderField("Cache-Control"); if(cacheControl != null) { StringTokenizer tok = new StringTokenizer(cacheControl, ","); while(tok.hasMoreTokens()) { String token = tok.nextToken().trim().toLowerCase(); if("must-revalidate".equals(token)) { return new Long(0); } else if(token.startsWith("max-age")) { int eqIdx = token.indexOf('='); if(eqIdx != -1) { String value = token.substring(eqIdx+1).trim(); int seconds; try { seconds = Integer.parseInt(value); return new Long(baseTime + seconds * 1000); } catch(NumberFormatException nfe) { logger.warning("getExpiration(): Bad Cache-Control max-age value: " + value); // ignore } } } } } String expires = connection.getHeaderField("Expires"); if(expires != null) { try { synchronized(PATTERN_RFC1123) { Date expDate = PATTERN_RFC1123.parse(expires); return new Long(expDate.getTime()); } } catch(java.text.ParseException pe) { int seconds; try { seconds = Integer.parseInt(expires); return new Long(baseTime + seconds * 1000); } catch(NumberFormatException nfe) { logger.warning("getExpiration(): Bad Expires header value: " + expires); } } } return null; } public static List getHeaders(URLConnection connection) { // Random access index recommended. List headers = new ArrayList(); for(int n = 0; ; n++) { String value = connection.getHeaderField(n); if(value == null) { break; } // Key may be null for n == 0. String key = connection.getHeaderFieldKey(n); if(key != null) { headers.add(new NameValuePair(key, value)); } } return headers; } public static URL guessURL(URL baseURL, String spec) throws MalformedURLException { URL finalURL; try { if (baseURL != null) { int colonIdx = spec.indexOf(':'); String newProtocol = colonIdx == -1 ? null : spec.substring(0, colonIdx); if (newProtocol != null && !newProtocol.equalsIgnoreCase(baseURL.getProtocol())) { baseURL = null; } } finalURL = createURL(baseURL, spec); } catch (MalformedURLException mfu) { spec = spec.trim(); int idx = spec.indexOf(':'); if (idx == -1) { int slashIdx = spec.indexOf('/'); if (slashIdx == 0) { // A file, absolute finalURL = new URL("file:" + spec); } else { if (slashIdx == -1) { // No slash, no colon, must be host. finalURL = new URL(baseURL, "http://" + spec); } else { String possibleHost = spec.substring(0, slashIdx) .toLowerCase(); if (Domains.isLikelyHostName(possibleHost)) { finalURL = new URL(baseURL, "http://" + spec); } else { finalURL = new URL(baseURL, "file:" + spec); } } } } else { if (idx == 1) { // Likely a drive finalURL = new URL(baseURL, "file:" + spec); } else { throw mfu; } } } if (!"".equals(finalURL.getHost()) && finalURL.toExternalForm().indexOf(' ') != -1) { throw new MalformedURLException("There are blanks in the URL: " + finalURL.toExternalForm()); } return finalURL; } public static URL guessURL(String spec) throws MalformedURLException { return guessURL(null, spec); } public static String getCharset(URLConnection connection) { String contentType = connection.getContentType(); if(contentType == null) { return getDefaultCharset(connection); } StringTokenizer tok = new StringTokenizer(contentType, ";"); if(tok.hasMoreTokens()) { tok.nextToken(); while(tok.hasMoreTokens()) { String assignment = tok.nextToken().trim(); int eqIdx = assignment.indexOf('='); if(eqIdx != -1) { String varName = assignment.substring(0, eqIdx).trim(); if("charset".equalsIgnoreCase(varName)) { String varValue = assignment.substring(eqIdx+1); return Strings.unquote(varValue.trim()); } } } } return getDefaultCharset(connection); } private static String getDefaultCharset(URLConnection connection) { URL url = connection.getURL(); if(Urls.isLocalFile(url)) { String charset = System.getProperty("file.encoding"); return charset == null ? "ISO-8859-1" : charset; } else { return "ISO-8859-1"; } } public static String getNoRefForm(URL url) { String host = url.getHost(); int port = url.getPort(); String portText = port == -1 ? "" : ":" + port; String userInfo = url.getUserInfo(); String userInfoText = userInfo == null || userInfo.length() == 0 ? "" : userInfo + "@"; String hostPort = host == null || host.length() == 0 ? "" : "//" + userInfoText + host + portText; return url.getProtocol() + ":" + hostPort + url.getFile(); } /** * Comparison that does not consider Ref. * @param url1 * @param url2 */ public static boolean sameNoRefURL(URL url1, URL url2) { return Objects.equals(url1.getHost(), url2.getHost()) && Objects.equals(url1.getProtocol(), url2.getProtocol()) && url1.getPort() == url2.getPort() && Objects.equals(url1.getFile(), url2.getFile()) && Objects.equals(url1.getUserInfo(), url2.getUserInfo()); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/WeakValueHashMap.java0000644000175000017500000001024110761736356026104 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 8, 2005 */ package org.lobobrowser.util; import java.util.*; import java.lang.ref.*; public class WeakValueHashMap implements Map { private final Map map = new HashMap(); private final ReferenceQueue queue = new ReferenceQueue(); public WeakValueHashMap() { super(); } public int size() { return this.map.size(); } public boolean isEmpty() { return this.map.isEmpty(); } public boolean containsKey(Object key) { WeakReference wf = (WeakReference) this.map.get(key); return wf != null && wf.get() != null; } public boolean containsValue(Object value) { throw new UnsupportedOperationException(); } public Object get(Object key) { this.checkQueue(); WeakReference wf = (WeakReference) this.map.get(key); return wf == null ? null : wf.get(); } public Object put(Object key, Object value) { this.checkQueue(); return this.putImpl(key, value); } private final Object putImpl(Object key, Object value) { if(value == null) { throw new IllegalArgumentException("null values not accepted"); } Reference ref = new LocalWeakReference(key, value, this.queue); WeakReference oldWf = (WeakReference) this.map.put(key, ref); return oldWf == null ? null : oldWf.get(); } public Object remove(Object key) { this.checkQueue(); WeakReference wf = (WeakReference) this.map.remove(key); return wf == null ? null : wf.get(); } public void putAll(Map t) { this.checkQueue(); Iterator i = t.entrySet().iterator(); while(i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); this.putImpl(entry.getKey(), entry.getValue()); } } public void clear() { this.checkQueue(); this.map.clear(); } public Set keySet() { return this.map.keySet(); } private final void checkQueue() { ReferenceQueue queue = this.queue; LocalWeakReference ref; while((ref = (LocalWeakReference) queue.poll()) != null) { this.map.remove(ref.getKey()); } } public Collection values() { return new FilteredCollection(this.map.values(), new LocalFilter()); } public Set entrySet() { throw new UnsupportedOperationException(); } private class LocalFilter implements ObjectFilter { /* (non-Javadoc) * @see org.xamjwg.util.ObjectFilter#decode(java.lang.Object) */ public Object decode(Object source) { WeakReference wf = (WeakReference) source; return wf == null ? null : wf.get(); } /* (non-Javadoc) * @see org.xamjwg.util.ObjectFilter#encode(java.lang.Object) */ public Object encode(Object source) { throw new java.lang.UnsupportedOperationException("Read-only collection."); } } private static class LocalWeakReference extends WeakReference { private final Object key; public LocalWeakReference(Object key, Object target, ReferenceQueue queue) { super(target, queue); this.key = key; } public Object getKey() { return key; } public boolean equals(Object other) { Object target1 = this.get(); Object target2 = other instanceof LocalWeakReference ? ((LocalWeakReference) other).get() : null; return Objects.equals(target1, target2); } public int hashCode() { Object target = this.get(); return target == null ? 0 : target.hashCode(); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/WrapperException.java0000644000175000017500000000243210726473510026247 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Aug 6, 2005 */ package org.lobobrowser.util; public class WrapperException extends RuntimeException { public WrapperException() { super(); } public WrapperException(String message) { super(message); } public WrapperException(String message, Throwable cause) { super(message, cause); } public WrapperException(Throwable cause) { super(cause); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/gui/0000755000175000017500000000000011125630232022656 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/lobobrowser/util/gui/CenterLayout.java0000644000175000017500000001000011123235114026124 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Mar 19, 2005 */ package org.lobobrowser.util.gui; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.LayoutManager; /** * @author J. H. S. */ public class CenterLayout implements LayoutManager { public void addLayoutComponent(String arg0, Component arg1) { } public void removeLayoutComponent(Component arg0) { } public Dimension preferredLayoutSize(Container arg0) { java.awt.Insets insets = arg0.getInsets(); int count = arg0.getComponentCount(); if(count > 0) { Dimension d = arg0.getComponent(0).getPreferredSize(); return new Dimension(d.width + insets.left + insets.right, d.height + insets.top + insets.bottom); } else { return new Dimension(insets.left + insets.right, insets.top + insets.bottom); } } /* (non-Javadoc) * @see java.awt.LayoutManager#minimumLayoutSize(java.awt.Container) */ public Dimension minimumLayoutSize(Container arg0) { java.awt.Insets insets = arg0.getInsets(); int count = arg0.getComponentCount(); if(count > 0) { Dimension d = arg0.getComponent(0).getMinimumSize(); return new Dimension(d.width + insets.left + insets.right, d.height + insets.top + insets.bottom); } else { return new Dimension(insets.left + insets.right, insets.top + insets.bottom); } } /* (non-Javadoc) * @see java.awt.LayoutManager#layoutContainer(java.awt.Container) */ public void layoutContainer(Container container) { int count = container.getComponentCount(); if(count > 0) { Component child = container.getComponent(0); java.awt.Insets insets = container.getInsets(); int availWidth = container.getWidth() - insets.left - insets.right; int availHeight = container.getHeight() - insets.top - insets.bottom; Dimension preferredSize = child.getPreferredSize(); double preferredWidth = preferredSize.getWidth(); double preferredHeight = preferredSize.getHeight(); int width; int height; int x; int y; if(preferredWidth < availWidth) { x = (int) Math.round(insets.left + (availWidth - preferredWidth) / 2); width = (int) Math.round(preferredWidth); } else { x = insets.left; width = availWidth; } if(preferredHeight < availHeight) { y = (int) Math.round(insets.top + (availHeight - preferredHeight) / 2); height = (int) Math.round(preferredHeight); } else { y = insets.top; height = availHeight; } child.setBounds(x, y, width, height); } } private static CenterLayout instance = new CenterLayout(); public static CenterLayout getInstance() { return instance; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/gui/ColorFactory.java0000644000175000017500000002726510750066702026153 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 17, 2005 */ package org.lobobrowser.util.gui; import java.util.*; import java.util.logging.*; import java.awt.*; /** * @author J. H. S. */ public class ColorFactory { private static final Logger logger = Logger.getLogger(ColorFactory.class.getName()); public static final Color TRANSPARENT = new Color(0, 0, 0, 0); private static ColorFactory instance; private final Map colorMap = new HashMap(256); private ColorFactory() { Map colorMap = this.colorMap; synchronized(this) { colorMap.put("transparent", TRANSPARENT); //http://www.w3schools.com/css/css_colornames.asp colorMap.put("aliceblue", new Color(0xf0f8ff)); colorMap.put("antiquewhite", new Color(0xfaebd7)); colorMap.put("aqua", new Color(0x00ffff)); colorMap.put("aquamarine", new Color(0x7fffd4)); colorMap.put("azure", new Color(0xf0ffff)); colorMap.put("beige", new Color(0xf5f5dc)); colorMap.put("bisque", new Color(0xffe4c4)); colorMap.put("black", new Color(0x000000)); colorMap.put("blanchedalmond", new Color(0xffebcd)); colorMap.put("blue", new Color(0x0000ff)); colorMap.put("blueviolet", new Color(0x8a2be2)); colorMap.put("brown", new Color(0xa52a2a)); colorMap.put("burlywood", new Color(0xdeb887)); colorMap.put("cadetblue", new Color(0x5f9ea0)); colorMap.put("chartreuse", new Color(0x7fff00)); colorMap.put("chocolate", new Color(0xd2691e)); colorMap.put("coral", new Color(0xff7f50)); colorMap.put("cornflowerblue", new Color(0x6495ed)); colorMap.put("cornsilk", new Color(0xfff8dc)); colorMap.put("crimson", new Color(0xdc143c)); colorMap.put("cyan", new Color(0x00ffff)); colorMap.put("darkblue", new Color(0x00008b)); colorMap.put("darkcyan", new Color(0x008b8b)); colorMap.put("darkgoldenrod", new Color(0xb8860b)); colorMap.put("darkgray", new Color(0xa9a9a9)); colorMap.put("darkgrey", new Color(0xa9a9a9)); colorMap.put("darkgreen", new Color(0x006400)); colorMap.put("darkkhaki", new Color(0xbdb76b)); colorMap.put("darkmagenta", new Color(0x8b008b)); colorMap.put("darkolivegreen", new Color(0x556b2f)); colorMap.put("darkorange", new Color(0xff8c00)); colorMap.put("darkorchid", new Color(0x9932cc)); colorMap.put("darkred", new Color(0x8b0000)); colorMap.put("darksalmon", new Color(0xe9967a)); colorMap.put("darkseagreen", new Color(0x8fbc8f)); colorMap.put("darkslateblue", new Color(0x483d8b)); colorMap.put("darkslategray", new Color(0x2f4f4f)); colorMap.put("darkslategrey", new Color(0x2f4f4f)); colorMap.put("darkturquoise", new Color(0x00ced1)); colorMap.put("darkviolet", new Color(0x9400d3)); colorMap.put("deeppink", new Color(0xff1493)); colorMap.put("deepskyblue", new Color(0x00bfff)); colorMap.put("dimgray", new Color(0x696969)); colorMap.put("dimgrey", new Color(0x696969)); colorMap.put("dodgerblue", new Color(0x1e90ff)); colorMap.put("firebrick", new Color(0xb22222)); colorMap.put("floralwhite", new Color(0xfffaf0)); colorMap.put("forestgreen", new Color(0x228b22)); colorMap.put("fuchsia", new Color(0xff00ff)); colorMap.put("gainsboro", new Color(0xdcdcdc)); colorMap.put("ghostwhite", new Color(0xf8f8ff)); colorMap.put("gold", new Color(0xffd700)); colorMap.put("goldenrod", new Color(0xdaa520)); colorMap.put("gray", new Color(0x808080)); colorMap.put("grey", new Color(0x808080)); colorMap.put("green", new Color(0x008000)); colorMap.put("greenyellow", new Color(0xadff2f)); colorMap.put("honeydew", new Color(0xf0fff0)); colorMap.put("hotpink", new Color(0xff69b4)); colorMap.put("indianred", new Color(0xcd5c5c)); colorMap.put("indigo", new Color(0x4b0082)); colorMap.put("ivory", new Color(0xfffff0)); colorMap.put("khaki", new Color(0xf0e68c)); colorMap.put("lavender", new Color(0xe6e6fa)); colorMap.put("lavenderblush", new Color(0xfff0f5)); colorMap.put("lawngreen", new Color(0x7cfc00)); colorMap.put("lemonchiffon", new Color(0xfffacd)); colorMap.put("lightblue", new Color(0xadd8e6)); colorMap.put("lightcoral", new Color(0xf08080)); colorMap.put("lightcyan", new Color(0xe0ffff)); colorMap.put("lightgoldenrodyellow", new Color(0xfafad2)); colorMap.put("lightgray", new Color(0xd3d3d3)); colorMap.put("lightgrey", new Color(0xd3d3d3)); colorMap.put("lightgreen", new Color(0x90ee90)); colorMap.put("lightpink", new Color(0xffb6c1)); colorMap.put("lightsalmon", new Color(0xffa07a)); colorMap.put("lightseagreen", new Color(0x20b2aa)); colorMap.put("lightskyblue", new Color(0x87cefa)); colorMap.put("lightslategray", new Color(0x778899)); colorMap.put("lightslategrey", new Color(0x778899)); colorMap.put("lightsteelblue", new Color(0xb0c4de)); colorMap.put("lightyellow", new Color(0xffffe0)); colorMap.put("lime", new Color(0x00ff00)); colorMap.put("limegreen", new Color(0x32cd32)); colorMap.put("linen", new Color(0xfaf0e6)); colorMap.put("magenta", new Color(0xff00ff)); colorMap.put("maroon", new Color(0x800000)); colorMap.put("mediumaquamarine", new Color(0x66cdaa)); colorMap.put("mediumblue", new Color(0x0000cd)); colorMap.put("mediumorchid", new Color(0xba55d3)); colorMap.put("mediumpurple", new Color(0x9370d8)); colorMap.put("mediumseagreen", new Color(0x3cb371)); colorMap.put("mediumslateblue", new Color(0x7b68ee)); colorMap.put("mediumspringgreen", new Color(0x00fa9a)); colorMap.put("mediumturquoise", new Color(0x48d1cc)); colorMap.put("mediumvioletred", new Color(0xc71585)); colorMap.put("midnightblue", new Color(0x191970)); colorMap.put("mintcream", new Color(0xf5fffa)); colorMap.put("mistyrose", new Color(0xffe4e1)); colorMap.put("moccasin", new Color(0xffe4b5)); colorMap.put("navajowhite", new Color(0xffdead)); colorMap.put("navy", new Color(0x000080)); colorMap.put("oldlace", new Color(0xfdf5e6)); colorMap.put("olive", new Color(0x808000)); colorMap.put("olivedrab", new Color(0x6b8e23)); colorMap.put("orange", new Color(0xffa500)); colorMap.put("orangered", new Color(0xff4500)); colorMap.put("orchid", new Color(0xda70d6)); colorMap.put("palegoldenrod", new Color(0xeee8aa)); colorMap.put("palegreen", new Color(0x98fb98)); colorMap.put("paleturquoise", new Color(0xafeeee)); colorMap.put("palevioletred", new Color(0xd87093)); colorMap.put("papayawhip", new Color(0xffefd5)); colorMap.put("peachpuff", new Color(0xffdab9)); colorMap.put("peru", new Color(0xcd853f)); colorMap.put("pink", new Color(0xffc0cb)); colorMap.put("plum", new Color(0xdda0dd)); colorMap.put("powderblue", new Color(0xb0e0e6)); colorMap.put("purple", new Color(0x800080)); colorMap.put("red", new Color(0xff0000)); colorMap.put("rosybrown", new Color(0xbc8f8f)); colorMap.put("royalblue", new Color(0x4169e1)); colorMap.put("saddlebrown", new Color(0x8b4513)); colorMap.put("salmon", new Color(0xfa8072)); colorMap.put("sandybrown", new Color(0xf4a460)); colorMap.put("seagreen", new Color(0x2e8b57)); colorMap.put("seashell", new Color(0xfff5ee)); colorMap.put("sienna", new Color(0xa0522d)); colorMap.put("silver", new Color(0xc0c0c0)); colorMap.put("skyblue", new Color(0x87ceeb)); colorMap.put("slateblue", new Color(0x6a5acd)); colorMap.put("slategray", new Color(0x708090)); colorMap.put("slategrey", new Color(0x708090)); colorMap.put("snow", new Color(0xfffafa)); colorMap.put("springgreen", new Color(0x00ff7f)); colorMap.put("steelblue", new Color(0x4682b4)); colorMap.put("tan", new Color(0xd2b48c)); colorMap.put("teal", new Color(0x008080)); colorMap.put("thistle", new Color(0xd8bfd8)); colorMap.put("tomato", new Color(0xff6347)); colorMap.put("turquoise", new Color(0x40e0d0)); colorMap.put("violet", new Color(0xee82ee)); colorMap.put("wheat", new Color(0xf5deb3)); colorMap.put("white", new Color(0xffffff)); colorMap.put("whitesmoke", new Color(0xf5f5f5)); colorMap.put("yellow", new Color(0xffff00)); colorMap.put("yellowgreen", new Color(0x9acd32)); } } public static final ColorFactory getInstance() { if(instance == null) { synchronized(ColorFactory.class) { if(instance == null) { instance = new ColorFactory(); } } } return instance; } private static final String RGB_START = "rgb("; public boolean isColor(String colorSpec) { if(colorSpec.startsWith("#")) { return true; } String normalSpec = colorSpec.toLowerCase(); if(normalSpec.startsWith(RGB_START)) { return true; } synchronized(this) { return colorMap.containsKey(normalSpec); } } public Color getColor(String colorSpec) { String normalSpec = colorSpec.toLowerCase(); synchronized(this) { Color color = (Color) colorMap.get(normalSpec); if(color == null) { if(normalSpec.startsWith(RGB_START)) { // CssParser produces this format. int endIdx = normalSpec.lastIndexOf(')'); String commaValues = endIdx == -1 ? normalSpec.substring(RGB_START.length()) : normalSpec.substring(RGB_START.length(), endIdx); StringTokenizer tok = new StringTokenizer(commaValues, ","); int r = 0, g = 0, b = 0; if(tok.hasMoreTokens()) { String rstr = tok.nextToken().trim(); try { r = Integer.parseInt(rstr); } catch(NumberFormatException nfe) { // ignore } if(tok.hasMoreTokens()) { String gstr = tok.nextToken().trim(); try { g = Integer.parseInt(gstr); } catch(NumberFormatException nfe) { // ignore } if(tok.hasMoreTokens()) { String bstr = tok.nextToken().trim(); try { b = Integer.parseInt(bstr); } catch(NumberFormatException nfe) { // ignore } } } } color = new Color(r, g, b); } else if(normalSpec.startsWith("#")) { //TODO: OPTIMIZE: It would be more efficient to //create new Color(hex), but CssParser doesn't //give us values formatted with "#" either way. int len = normalSpec.length(); int[] rgba = new int[4]; rgba[3] = 255; for(int i = 0; i < rgba.length; i++) { int idx = 2 * i + 1; if(idx < len) { String hexText = normalSpec.substring(idx, idx + Math.min(2, len - idx)); try { rgba[i] = Integer.parseInt(hexText, 16); } catch(NumberFormatException nfe) { // Ignore } } } color = new Color(rgba[0], rgba[1], rgba[2], rgba[3]); } else { if(logger.isLoggable(Level.INFO)) { logger.warning("getColor(): Color spec [" + normalSpec + "] unknown."); } return Color.RED; } colorMap.put(normalSpec, color); } return color; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/gui/FontFactory.java0000644000175000017500000002252311125725142025770 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 17, 2005 */ package org.lobobrowser.util.gui; import java.util.*; import java.awt.*; import java.awt.font.TextAttribute; import java.util.logging.*; import org.lobobrowser.util.Objects; /** Note: Undocumented class? */ import sun.font.FontManager; /** * @author J. H. S. */ public class FontFactory { private static final Logger logger = Logger.getLogger(FontFactory.class.getName()); private static final boolean loggableFine = logger.isLoggable(Level.FINE); private static final FontFactory instance = new FontFactory(); private final Set fontFamilies = new HashSet(40); private final Map fontMap = new HashMap(50); /** * */ private FontFactory() { boolean liflag = loggableFine; String[] ffns = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(); Set fontFamilies = this.fontFamilies; synchronized(this) { for(int i = 0; i < ffns.length; i++) { String ffn = ffns[i]; if(liflag) { logger.fine("FontFactory(): family=" + ffn); } fontFamilies.add(ffn.toLowerCase()); } } } public static final FontFactory getInstance() { return instance; } private final Map registeredFonts = new HashMap(0); /** * Registers a font family. It does not close the stream provided. * Fonts should be registered before the renderer has a chance to * cache document font specifications. * @param fontName The name of a font as it would appear in a font-family specification. * @param fontFormat Should be {@link Font#TRUETYPE_FONT}. */ public void registerFont(String fontName, int fontFormat, java.io.InputStream fontStream) throws java.awt.FontFormatException, java.io.IOException { Font f = Font.createFont(fontFormat, fontStream); synchronized(this) { this.registeredFonts.put(fontName.toLowerCase(), f); } } /** * Unregisters a font previously registered with {@link #registerFont(String, int, java.io.InputStream)}. * @param fontName The font name to be removed. */ public void unregisterFont(String fontName) { synchronized(this) { this.registeredFonts.remove(fontName.toLowerCase()); } } public Font getFont(String fontFamily, String fontStyle, String fontVariant, String fontWeight, float fontSize, Set locales, Integer superscript) { FontKey key = new FontKey(fontFamily, fontStyle, fontVariant, fontWeight, fontSize, locales, superscript); synchronized(this) { Font font = (Font) this.fontMap.get(key); if(font == null) { font = this.createFont(key); this.fontMap.put(key, font); } return font; } } private String defaultFontName = "SansSerif"; public String getDefaultFontName() { return defaultFontName; } /** * Sets the default font name to be used when a name is unrecognized * or when a font is determined not to be capable of diplaying characters * from a given language. * This should be the name of a font that can display unicode text * across all or most languages. * @param defaultFontName The name of a font. */ public void setDefaultFontName(String defaultFontName) { if(defaultFontName == null) { throw new IllegalArgumentException("defaultFontName cannot be null"); } this.defaultFontName = defaultFontName; } private final Font createFont(FontKey key) { Font font = createFont_Impl(key); return superscriptFont(font, key.superscript); } public static Font superscriptFont(Font baseFont, Integer newSuperscript) { if (newSuperscript == null){ return baseFont; } Integer fontSuperScript = (Integer) baseFont.getAttributes().get(TextAttribute.SUPERSCRIPT); if (fontSuperScript == null){ fontSuperScript = new Integer(0); } if (fontSuperScript.equals(newSuperscript)){ return baseFont; } else { Map additionalAttributes = new HashMap(); additionalAttributes.put(TextAttribute.SUPERSCRIPT, newSuperscript); return baseFont.deriveFont(additionalAttributes); } } private final Font createFont_Impl(FontKey key) { String fontNames = key.fontFamily; String matchingFace = null; Set fontFamilies = this.fontFamilies; Map registeredFonts = this.registeredFonts; Font baseFont = null; if(fontNames != null) { StringTokenizer tok = new StringTokenizer(fontNames, ","); while(tok.hasMoreTokens()) { String face = tok.nextToken().trim(); String faceTL = face.toLowerCase(); if(registeredFonts.containsKey(faceTL)) { baseFont = (Font) registeredFonts.get(faceTL); break; } else if(fontFamilies.contains(faceTL)) { matchingFace = faceTL; break; } } } int fontStyle = Font.PLAIN; if("italic".equalsIgnoreCase(key.fontStyle)) { fontStyle |= Font.ITALIC; } if("bold".equalsIgnoreCase(key.fontWeight) || "bolder".equalsIgnoreCase(key.fontWeight)) { fontStyle |= Font.BOLD; } if(baseFont != null) { return baseFont.deriveFont(fontStyle, key.fontSize); } else if(matchingFace != null) { Font font = createFont(matchingFace, fontStyle, (int) Math.round(key.fontSize)); Set locales = key.locales; if(locales == null) { Locale locale = Locale.getDefault(); if(font.canDisplayUpTo(locale.getDisplayLanguage(locale)) == -1) { return font; } } else { Iterator i = locales.iterator(); boolean allMatch = true; while(i.hasNext()) { Locale locale = (Locale) i.next(); if(font.canDisplayUpTo(locale.getDisplayLanguage(locale)) != -1) { allMatch = false; break; } } if(allMatch) { return font; } } // Otherwise, fall through. } // Last resort: return createFont(this.defaultFontName, fontStyle, (int) Math.round(key.fontSize)); } private Font createFont(String name, int style, int size) { // Proprietary Sun API. Maybe shouldn't use it. Works well for Chinese. return FontManager.getCompositeFontUIResource(new Font(name, style, size)); } private static class FontKey { public final String fontFamily; public final String fontStyle; public final String fontVariant; public final String fontWeight; public final float fontSize; public final Set locales; public final Integer superscript; /** * @param fontFamily * @param fontStyle * @param fontVariant * @param fontWeight * @param fontSize */ public FontKey(final String fontFamily, final String fontStyle, final String fontVariant, final String fontWeight, final float fontSize, final Set locales, final Integer superscript) { this.fontFamily = fontFamily == null ? null : fontFamily.intern(); this.fontStyle = fontStyle == null ? null : fontStyle.intern(); this.fontVariant = fontVariant == null ? null : fontVariant.intern(); this.fontWeight = fontWeight == null ? null : fontWeight.intern(); this.fontSize = fontSize; this.locales = locales; this.superscript = superscript; } public boolean equals(Object other) { if(other == this) { // Quick check. return true; } FontKey ors; try { ors = (FontKey) other; } catch(ClassCastException cce) { // Not expected return false; } // Note that we use String.intern() for all string fields, // so we can do instance comparisons. return this.fontSize == ors.fontSize && this.fontFamily == ors.fontFamily && this.fontStyle == ors.fontStyle && this.fontWeight == ors.fontWeight && this.fontVariant == ors.fontVariant && this.superscript == ors.superscript && Objects.equals(this.locales,ors.locales); } private int cachedHash = -1; public int hashCode() { int ch = this.cachedHash; if(ch != -1) { // Object is immutable - caching is ok. return ch; } String ff = this.fontFamily; if(ff == null) { ff = ""; } String fw = this.fontWeight; if(fw == null) { fw = ""; } String fs = this.fontStyle; if(fs == null) { fs = ""; } Integer ss = this.superscript; ch = ff.hashCode() ^ fw.hashCode() ^ fs.hashCode() ^ (int) this.fontSize ^ (ss == null ? 0 : ss.intValue()); this.cachedHash = ch; return ch; } public String toString() { return "FontKey[family=" + this.fontFamily + ",size=" + this.fontSize + ",style=" + this.fontStyle + ",weight=" + this.fontWeight + ",variant=" + this.fontVariant + ",superscript="+this.superscript+"]"; } } }libcobra-java-0.98.4.orig/src/org/lobobrowser/util/gui/GUITasks.java0000644000175000017500000000444310726473476025205 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.util.gui; import java.awt.*; public class GUITasks { public static Frame getTopFrame() { Frame[] frames = Frame.getFrames(); for(int i = 0; i < frames.length; i++) { if(frames[i].getFocusOwner() != null) { return frames[i]; } } if(frames.length > 0) { return frames[0]; } return null; } public static void drawDashed(Graphics g, int x1, int y1, int x2, int y2, int dashSize, int gapSize) { if(x2 < x1) { int temp = x1; x1 = x2; x2 = temp; } if(y2 < y1) { int temp = y1; y1 = y2; y2 = temp; } int totalDash = dashSize + gapSize; if(y1 == y2) { int virtualStartX = (x1 / totalDash) * totalDash; for(int x = virtualStartX; x < x2; x += totalDash) { int topX = x + dashSize; if(topX > x2) { topX = x2; } int firstX = x; if(firstX < x1) { firstX = x1; } if(firstX < topX) { g.drawLine(firstX, y1, topX, y1); } } } else if(x1 == x2) { int virtualStartY = (y1 / totalDash) * totalDash; for(int y = virtualStartY; y < y2; y += totalDash) { int topY = y + dashSize; if(topY > y2) { topY = y2; } int firstY = y; if(firstY < y1) { firstY = y1; } if(firstY < topY) { g.drawLine(x1, firstY, x1, topY); } } } else { // Not supported g.drawLine(x1, y1, x2, y2); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/gui/WrapperLayout.java0000644000175000017500000000660310726473506026363 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Mar 19, 2005 */ package org.lobobrowser.util.gui; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.LayoutManager; /** * @author J. H. S. */ public class WrapperLayout implements LayoutManager { /* (non-Javadoc) * @see java.awt.LayoutManager#addLayoutComponent(java.lang.String, java.awt.Component) */ public void addLayoutComponent(String arg0, Component arg1) { } /* (non-Javadoc) * @see java.awt.LayoutManager#removeLayoutComponent(java.awt.Component) */ public void removeLayoutComponent(Component arg0) { } /* (non-Javadoc) * @see java.awt.LayoutManager#preferredLayoutSize(java.awt.Container) */ public Dimension preferredLayoutSize(Container arg0) { java.awt.Insets insets = arg0.getInsets(); int count = arg0.getComponentCount(); if(count > 0) { Dimension d = arg0.getComponent(0).getPreferredSize(); return new Dimension(d.width + insets.left + insets.right, d.height + insets.top + insets.bottom); } else { return new Dimension(insets.left + insets.right, insets.top + insets.bottom); } } /* (non-Javadoc) * @see java.awt.LayoutManager#minimumLayoutSize(java.awt.Container) */ public Dimension minimumLayoutSize(Container arg0) { java.awt.Insets insets = arg0.getInsets(); int count = arg0.getComponentCount(); if(count > 0) { Dimension d = arg0.getComponent(0).getMinimumSize(); return new Dimension(d.width + insets.left + insets.right, d.height + insets.top + insets.bottom); } else { return new Dimension(insets.left + insets.right, insets.top + insets.bottom); } } /* (non-Javadoc) * @see java.awt.LayoutManager#layoutContainer(java.awt.Container) */ public void layoutContainer(Container arg0) { int count = arg0.getComponentCount(); if(count > 0) { Component child = arg0.getComponent(0); java.awt.Insets insets = arg0.getInsets(); child.setBounds(insets.left, insets.top, arg0.getWidth() - insets.left - insets.right, arg0.getHeight() - insets.top - insets.bottom); } } private static WrapperLayout instance = new WrapperLayout(); public static WrapperLayout getInstance() { return instance; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/io/0000755000175000017500000000000011125630232022501 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/lobobrowser/util/io/BufferExceededException.java0000644000175000017500000000242510751366524030104 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.util.io; public class BufferExceededException extends Exception { public BufferExceededException() { super(); } public BufferExceededException(String message, Throwable cause) { super(message, cause); } public BufferExceededException(String message) { super(message); } public BufferExceededException(Throwable cause) { super(cause); } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/io/EmptyReader.java0000644000175000017500000000042110620620242025561 0ustar twernertwernerpackage org.lobobrowser.util.io; import java.io.IOException; import java.io.Reader; public class EmptyReader extends Reader { public void close() throws IOException { } public int read(char[] cbuf, int off, int len) throws IOException { return 0; } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/io/Files.java0000644000175000017500000000325510726473510024425 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.util.io; import java.io.*; public class Files { private Files() { } /** * Guesses the right content-type for a local * file, and includes a charset if appropriate. */ public static String getContentType(File file) { // Not very complete at the moment :) String name = file.getName(); int dotIdx = name.lastIndexOf('.'); String extension = dotIdx == -1 ? null : name.substring(dotIdx+1); if("txt".equalsIgnoreCase(extension)) { return "text/plain; charset=\"" + System.getProperty("file.encoding") + "\""; } if("html".equalsIgnoreCase(extension) || "htm".equalsIgnoreCase(extension)) { return "text/html; charset=\"" + System.getProperty("file.encoding") + "\""; } else { return "application/octet-stream"; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/io/IORoutines.java0000644000175000017500000001417110726473500025421 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Mar 19, 2005 */ package org.lobobrowser.util.io; import java.io.*; /** * @author J. H. S. */ public class IORoutines { public static final byte[] LINE_BREAK_BYTES = { (byte) 13, (byte) 10 }; public static String loadAsText(InputStream in, String encoding) throws IOException { return loadAsText(in, encoding, 4096); } public static String loadAsText(InputStream in, String encoding, int bufferSize) throws IOException { InputStreamReader reader = new InputStreamReader(in, encoding); char[] buffer = new char[bufferSize]; int offset = 0; for(;;) { int remain = buffer.length - offset; if(remain <= 0) { char[] newBuffer = new char[buffer.length * 2]; System.arraycopy(buffer, 0, newBuffer, 0, offset); buffer = newBuffer; remain = buffer.length - offset; } int numRead = reader.read(buffer, offset, remain); if(numRead == -1) { break; } offset += numRead; } return new String(buffer, 0, offset); } public static byte[] load(File file) throws IOException { long fileLength = file.length(); if(fileLength > Integer.MAX_VALUE) { throw new IOException("File '" + file.getName() + "' too big"); } InputStream in = new FileInputStream(file); try { return loadExact(in, (int) fileLength); } finally { in.close(); } } public static byte[] load(InputStream in) throws IOException { return load(in, 4096); } public static byte[] load(InputStream in, int initialBufferSize) throws IOException { if(initialBufferSize == 0) { initialBufferSize = 1; } byte[] buffer = new byte[initialBufferSize]; int offset = 0; for(;;) { int remain = buffer.length - offset; if(remain <= 0) { int newSize = buffer.length * 2; byte[] newBuffer = new byte[newSize]; System.arraycopy(buffer, 0, newBuffer, 0, offset); buffer = newBuffer; remain = buffer.length - offset; } int numRead = in.read(buffer, offset, remain); if(numRead == -1) { break; } offset += numRead; } if(offset < buffer.length) { byte[] newBuffer = new byte[offset]; System.arraycopy(buffer, 0, newBuffer, 0, offset); buffer = newBuffer; } return buffer; } public static byte[] loadExact(InputStream in, int length) throws IOException { byte[] buffer = new byte[length]; int offset = 0; for(;;) { int remain = length - offset; if(remain <= 0) { break; } int numRead = in.read(buffer, offset, remain); if(numRead == -1) { throw new IOException("Reached EOF, read " + offset + " expecting " + length); } offset += numRead; } return buffer; } public static boolean equalContent(File file, byte[] content) throws IOException { long length = file.length(); if(length > Integer.MAX_VALUE) { throw new IOException("File '" + file + "' too big"); } InputStream in = new FileInputStream(file); try { byte[] fileContent = loadExact(in, (int) length); return java.util.Arrays.equals(content, fileContent); } finally { in.close(); } } public static void save(File file, byte[] content) throws IOException { FileOutputStream out = new FileOutputStream(file); try { out.write(content); } finally { out.close(); } } /** * Reads line without buffering. */ public static String readLine(InputStream in) throws IOException { int b; StringBuffer sb = null; OUTER: while((b = in.read()) != -1) { if(sb == null) { sb = new StringBuffer(); } switch(b) { case (byte) '\n': break OUTER; case (byte) '\r': break; default: sb.append((char) b); break; } } return sb == null ? null : sb.toString(); } public static void touch(File file) { file.setLastModified(System.currentTimeMillis()); } public static void saveStrings(File file, java.util.Collection list) throws IOException { BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(file)); try { PrintWriter writer = new PrintWriter(bout); java.util.Iterator i = list.iterator(); while(i.hasNext()) { String text = (String) i.next(); writer.println(text); } writer.flush(); } finally { bout.close(); } } public static java.util.List loadStrings(File file) throws IOException { java.util.List list = new java.util.LinkedList(); InputStream in = new FileInputStream(file); try { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; while((line = reader.readLine()) != null) { list.add(line); } return list; } finally { in.close(); } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/io/NetRoutines.java0000644000175000017500000000244710726473506025651 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The XAMJ Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ package org.lobobrowser.util.io; import java.net.*; public class NetRoutines { public static boolean isLocalAddress(String host) { try { InetAddress address = InetAddress.getByName(host); return address.isAnyLocalAddress() || address.isLinkLocalAddress() || address.isLoopbackAddress() || address.isSiteLocalAddress(); } catch(java.net.UnknownHostException uhe) { return false; } } } libcobra-java-0.98.4.orig/src/org/lobobrowser/util/io/RecordedInputStream.java0000644000175000017500000001171310753623456027312 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Apr 15, 2005 */ package org.lobobrowser.util.io; import java.io.*; /** * Wraps an InputStream and records all of the * bytes read. This stream supports mark() and reset(). *

* Note: Buffered streams should wrap this class * as opposed to the other way around. * @author J. H. S. */ public class RecordedInputStream extends InputStream { private final InputStream delegate; private final ByteArrayOutputStream store = new ByteArrayOutputStream(); private final int maxBufferSize; private boolean hasReachedEOF = false; private boolean hasReachedMaxBufferSize = false; private int markPosition = -1; private int readPosition = -1; private byte[] resetBuffer = null; /** * */ public RecordedInputStream(InputStream delegate, int maxBufferSize) { super(); this.delegate = delegate; this.maxBufferSize = maxBufferSize; } /* (non-Javadoc) * @see java.io.InputStream#read() */ public int read() throws IOException { if(this.readPosition != -1 && this.readPosition < this.resetBuffer.length) { int b = this.resetBuffer[this.readPosition]; this.readPosition++; return b; } else { int b = this.delegate.read(); if(b != -1) { if(!this.hasReachedMaxBufferSize) { this.store.write(b); if(this.store.size() > this.maxBufferSize) { this.hasReachedMaxBufferSize = true; } } } else { this.hasReachedEOF = true; } return b; } } /* (non-Javadoc) * @see java.io.InputStream#available() */ public int available() throws IOException { return this.delegate.available(); } /* (non-Javadoc) * @see java.io.InputStream#close() */ public void close() throws IOException { this.delegate.close(); } /* (non-Javadoc) * @see java.io.InputStream#markSupported() */ public boolean markSupported() { return true; } public synchronized void mark(int readlimit) { if(this.hasReachedMaxBufferSize) { throw new java.lang.IllegalStateException("Maximum buffer size was already reached."); } this.markPosition = this.store.size(); } public synchronized void reset() throws IOException { if(this.hasReachedMaxBufferSize) { throw new java.lang.IllegalStateException("Maximum buffer size was already reached."); } int mp = this.markPosition; byte[] wholeBuffer = this.store.toByteArray(); byte[] resetBuffer = new byte[wholeBuffer.length - mp]; System.arraycopy(wholeBuffer, mp, resetBuffer, 0, resetBuffer.length); this.resetBuffer = resetBuffer; this.readPosition = 0; } /* (non-Javadoc) * @see java.io.InputStream#read(byte[], int, int) */ public int read(byte[] buffer, int offset, int length) throws IOException { if(this.readPosition != -1 && this.readPosition < this.resetBuffer.length) { int minLength = Math.min(this.resetBuffer.length - this.readPosition, length); System.arraycopy(this.resetBuffer, this.readPosition, buffer, offset, minLength); this.readPosition += minLength; return minLength; } else { int numRead = this.delegate.read(buffer, offset, length); if(numRead != -1) { if(!this.hasReachedMaxBufferSize) { this.store.write(buffer, offset, numRead); if(this.store.size() > this.maxBufferSize) { this.hasReachedMaxBufferSize = true; } } } else { this.hasReachedEOF = true; } return numRead; } } public void consumeToEOF() throws IOException { byte[] buffer = new byte[8192]; while(this.read(buffer) != -1) {;} } public byte[] getBytesRead() throws BufferExceededException { if(this.hasReachedMaxBufferSize) { throw new BufferExceededException(); } return this.store.toByteArray(); } public String getString(String encoding) throws java.io.UnsupportedEncodingException, BufferExceededException { if(this.hasReachedMaxBufferSize) { throw new BufferExceededException(); } byte[] bytes = this.store.toByteArray(); return new String(bytes, encoding); } public boolean hasReachedEOF() { return this.hasReachedEOF; } } libcobra-java-0.98.4.orig/src/org/w3c/0000755000175000017500000000000010577445316017273 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/w3c/COPYRIGHT.html0000644000175000017500000001146210310572434021520 0ustar twernertwerner W3C IPR SOFTWARE NOTICE

W3C IPR SOFTWARE NOTICE

Copyright © 2002 World Wide Web Consortium, (Massachusetts Institute of Technology, Institut National de Recherche en Informatique et en Automatique, Keio University). All Rights Reserved.

The DOM bindings are published under the W3C Software Copyright Notice and License. The software license requires "Notice of any changes or modifications to the W3C files, including the date changes were made." Consequently, modified versions of the DOM bindings must document that they do not conform to the W3C standard; in the case of the IDL definitions, the pragma prefix can no longer be 'w3c.org'; in the case of the Java language binding, the package names can no longer be in the 'org.w3c' package.

Note: The original version of the W3C Software Copyright Notice and License could be found at http://www.w3.org/Consortium/Legal/copyright-software-19980720

Copyright © 1994-2002 World Wide Web Consortium, (Massachusetts Institute of Technology, Institut National de Recherche en Informatique et en Automatique, Keio University). All Rights Reserved. http://www.w3.org/Consortium/Legal/

This W3C work (including software, documents, or other related items) is being provided by the copyright holders under the following license. By obtaining, using and/or copying this work, you (the licensee) agree that you have read, understood, and will comply with the following terms and conditions:

Permission to use, copy, and modify this software and its documentation, with or without modification,  for any purpose and without fee or royalty is hereby granted, provided that you include the following on ALL copies of the software and documentation or portions thereof, including modifications, that you make:

  1. The full text of this NOTICE in a location viewable to users of the redistributed or derivative work.
  2. Any pre-existing intellectual property disclaimers, notices, or terms and conditions. If none exist, a short notice of the following form (hypertext is preferred, text is permitted) should be used within the body of any redistributed or derivative code: "Copyright © [$date-of-software] World Wide Web Consortium, (Massachusetts Institute of Technology, Institut National de Recherche en Informatique et en Automatique, Keio University). All Rights Reserved. http://www.w3.org/Consortium/Legal/"
  3. Notice of any changes or modifications to the W3C files, including the date changes were made. (We recommend you provide URIs to the location from which the code is derived.)

THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.

COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENTATION.

The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the software without specific, written prior permission. Title to copyright in this software and any associated documentation will at all times remain with copyright holders.

libcobra-java-0.98.4.orig/src/org/w3c/dom/0000755000175000017500000000000010577445316020052 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/w3c/dom/html2/0000755000175000017500000000000011125630300021053 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLAnchorElement.java0000644000175000017500000001376010726473504025157 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * The anchor element. See the A element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLAnchorElement extends HTMLElement { /** * A single character access key to give access to the form control. See * the accesskey attribute definition in HTML 4.01. */ public String getAccessKey(); /** * A single character access key to give access to the form control. See * the accesskey attribute definition in HTML 4.01. */ public void setAccessKey(String accessKey); /** * The character encoding of the linked resource. See the charset * attribute definition in HTML 4.01. */ public String getCharset(); /** * The character encoding of the linked resource. See the charset * attribute definition in HTML 4.01. */ public void setCharset(String charset); /** * Comma-separated list of lengths, defining an active region geometry. * See also shape for the shape of the region. See the * coords attribute definition in HTML 4.01. */ public String getCoords(); /** * Comma-separated list of lengths, defining an active region geometry. * See also shape for the shape of the region. See the * coords attribute definition in HTML 4.01. */ public void setCoords(String coords); /** * The absolute URI [IETF RFC 2396] of the linked resource. See the href attribute * definition in HTML 4.01. */ public String getHref(); /** * The absolute URI [IETF RFC 2396] of the linked resource. See the href attribute * definition in HTML 4.01. */ public void setHref(String href); /** * Language code of the linked resource. See the hreflang attribute * definition in HTML 4.01. */ public String getHreflang(); /** * Language code of the linked resource. See the hreflang attribute * definition in HTML 4.01. */ public void setHreflang(String hreflang); /** * Anchor name. See the name attribute definition in HTML 4.01. */ public String getName(); /** * Anchor name. See the name attribute definition in HTML 4.01. */ public void setName(String name); /** * Forward link type. See the rel attribute definition in HTML 4.01. */ public String getRel(); /** * Forward link type. See the rel attribute definition in HTML 4.01. */ public void setRel(String rel); /** * Reverse link type. See the rev attribute definition in HTML 4.01. */ public String getRev(); /** * Reverse link type. See the rev attribute definition in HTML 4.01. */ public void setRev(String rev); /** * The shape of the active area. The coordinates are given by * coords. See the shape attribute definition in HTML 4.01. */ public String getShape(); /** * The shape of the active area. The coordinates are given by * coords. See the shape attribute definition in HTML 4.01. */ public void setShape(String shape); /** * Index that represents the element's position in the tabbing order. See * the tabindex attribute definition in HTML 4.01. */ public int getTabIndex(); /** * Index that represents the element's position in the tabbing order. See * the tabindex attribute definition in HTML 4.01. */ public void setTabIndex(int tabIndex); /** * Frame to render the resource in. See the target attribute definition in * HTML 4.01. */ public String getTarget(); /** * Frame to render the resource in. See the target attribute definition in * HTML 4.01. */ public void setTarget(String target); /** * Advisory content type. See the type attribute definition in HTML 4.01. */ public String getType(); /** * Advisory content type. See the type attribute definition in HTML 4.01. */ public void setType(String type); /** * Removes keyboard focus from this element. */ public void blur(); /** * Gives keyboard focus to this element. */ public void focus(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLAppletElement.java0000644000175000017500000001527110726473506025173 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * An embedded Java applet. See the APPLET element definition in HTML 4.01. * This element is deprecated in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLAppletElement extends HTMLElement { /** * Aligns this object (vertically or horizontally) with respect to its * surrounding text. See the align attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public String getAlign(); /** * Aligns this object (vertically or horizontally) with respect to its * surrounding text. See the align attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public void setAlign(String align); /** * Alternate text for user agents not rendering the normal content of this * element. See the alt attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public String getAlt(); /** * Alternate text for user agents not rendering the normal content of this * element. See the alt attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public void setAlt(String alt); /** * Comma-separated archive list. See the archive attribute definition in * HTML 4.01. This attribute is deprecated in HTML 4.01. */ public String getArchive(); /** * Comma-separated archive list. See the archive attribute definition in * HTML 4.01. This attribute is deprecated in HTML 4.01. */ public void setArchive(String archive); /** * Applet class file. See the code attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public String getCode(); /** * Applet class file. See the code attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public void setCode(String code); /** * Optional base URI [IETF RFC 2396] for applet. See the codebase attribute definition in * HTML 4.01. This attribute is deprecated in HTML 4.01. */ public String getCodeBase(); /** * Optional base URI [IETF RFC 2396] for applet. See the codebase attribute definition in * HTML 4.01. This attribute is deprecated in HTML 4.01. */ public void setCodeBase(String codeBase); /** * Override height. See the height attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public String getHeight(); /** * Override height. See the height attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public void setHeight(String height); /** * Horizontal space, in pixels, to the left and right of this image, * applet, or object. See the hspace attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. * @version DOM Level 2 */ public int getHspace(); /** * Horizontal space, in pixels, to the left and right of this image, * applet, or object. See the hspace attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. * @version DOM Level 2 */ public void setHspace(int hspace); /** * The name of the applet. See the name attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public String getName(); /** * The name of the applet. See the name attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public void setName(String name); /** * The value of the "object" attribute. See the object attribute definition * in HTML 4.01. This attribute is deprecated in HTML 4.01. * @version DOM Level 2 */ public String getObject(); /** * The value of the "object" attribute. See the object attribute definition * in HTML 4.01. This attribute is deprecated in HTML 4.01. * @version DOM Level 2 */ public void setObject(String object); /** * Vertical space, in pixels, above and below this image, applet, or * object. See the vspace attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. * @version DOM Level 2 */ public int getVspace(); /** * Vertical space, in pixels, above and below this image, applet, or * object. See the vspace attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. * @version DOM Level 2 */ public void setVspace(int vspace); /** * Override width. See the width attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public String getWidth(); /** * Override width. See the width attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public void setWidth(String width); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLAreaElement.java0000644000175000017500000001165610726473502024615 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Client-side image map area definition. See the AREA element definition in * HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLAreaElement extends HTMLElement { /** * A single character access key to give access to the form control. See * the accesskey attribute definition in HTML 4.01. */ public String getAccessKey(); /** * A single character access key to give access to the form control. See * the accesskey attribute definition in HTML 4.01. */ public void setAccessKey(String accessKey); /** * Alternate text for user agents not rendering the normal content of this * element. See the alt attribute definition in HTML 4.01. */ public String getAlt(); /** * Alternate text for user agents not rendering the normal content of this * element. See the alt attribute definition in HTML 4.01. */ public void setAlt(String alt); /** * Comma-separated list of lengths, defining an active region geometry. * See also shape for the shape of the region. See the * coords attribute definition in HTML 4.01. */ public String getCoords(); /** * Comma-separated list of lengths, defining an active region geometry. * See also shape for the shape of the region. See the * coords attribute definition in HTML 4.01. */ public void setCoords(String coords); /** * The URI [IETF RFC 2396] of the linked resource. See the href attribute definition in * HTML 4.01. */ public String getHref(); /** * The URI [IETF RFC 2396] of the linked resource. See the href attribute definition in * HTML 4.01. */ public void setHref(String href); /** * Specifies that this area is inactive, i.e., has no associated action. * See the nohref attribute definition in HTML 4.01. */ public boolean getNoHref(); /** * Specifies that this area is inactive, i.e., has no associated action. * See the nohref attribute definition in HTML 4.01. */ public void setNoHref(boolean noHref); /** * The shape of the active area. The coordinates are given by * coords. See the shape attribute definition in HTML 4.01. */ public String getShape(); /** * The shape of the active area. The coordinates are given by * coords. See the shape attribute definition in HTML 4.01. */ public void setShape(String shape); /** * Index that represents the element's position in the tabbing order. See * the tabindex attribute definition in HTML 4.01. */ public int getTabIndex(); /** * Index that represents the element's position in the tabbing order. See * the tabindex attribute definition in HTML 4.01. */ public void setTabIndex(int tabIndex); /** * Frame to render the resource in. See the target attribute definition in * HTML 4.01. */ public String getTarget(); /** * Frame to render the resource in. See the target attribute definition in * HTML 4.01. */ public void setTarget(String target); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLBRElement.java0000644000175000017500000000420710726473476024254 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Force a line break. See the BR element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLBRElement extends HTMLElement { /** * Control flow of text around floats. See the clear attribute definition * in HTML 4.01. This attribute is deprecated in HTML 4.01. */ public String getClear(); /** * Control flow of text around floats. See the clear attribute definition * in HTML 4.01. This attribute is deprecated in HTML 4.01. */ public void setClear(String clear); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLBaseElement.java0000644000175000017500000000474210726473502024615 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Document base URI [IETF RFC 2396]. See the BASE element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLBaseElement extends HTMLElement { /** * The base URI [IETF RFC 2396]. See the href attribute definition in HTML 4.01. */ public String getHref(); /** * The base URI [IETF RFC 2396]. See the href attribute definition in HTML 4.01. */ public void setHref(String href); /** * The default target frame. See the target attribute definition in HTML * 4.01. */ public String getTarget(); /** * The default target frame. See the target attribute definition in HTML * 4.01. */ public void setTarget(String target); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLBaseFontElement.java0000644000175000017500000000562610726473506025452 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Base font. See the BASEFONT element definition in HTML 4.01. This element * is deprecated in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLBaseFontElement extends HTMLElement { /** * Font color. See the color attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public String getColor(); /** * Font color. See the color attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public void setColor(String color); /** * Font face identifier. See the face attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public String getFace(); /** * Font face identifier. See the face attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public void setFace(String face); /** * Computed font size. See the size attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. * @version DOM Level 2 */ public int getSize(); /** * Computed font size. See the size attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. * @version DOM Level 2 */ public void setSize(int size); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLBodyElement.java0000644000175000017500000001101410726473506024632 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * The HTML document body. This element is always present in the DOM API, even * if the tags are not present in the source document. See the BODY element * definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLBodyElement extends HTMLElement { /** * Color of active links (after mouse-button down, but before mouse-button * up). See the alink attribute definition in HTML 4.01. This attribute * is deprecated in HTML 4.01. */ public String getALink(); /** * Color of active links (after mouse-button down, but before mouse-button * up). See the alink attribute definition in HTML 4.01. This attribute * is deprecated in HTML 4.01. */ public void setALink(String aLink); /** * URI [IETF RFC 2396] of the background texture tile image. See the background attribute * definition in HTML 4.01. This attribute is deprecated in HTML 4.01. */ public String getBackground(); /** * URI [IETF RFC 2396] of the background texture tile image. See the background attribute * definition in HTML 4.01. This attribute is deprecated in HTML 4.01. */ public void setBackground(String background); /** * Document background color. See the bgcolor attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public String getBgColor(); /** * Document background color. See the bgcolor attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public void setBgColor(String bgColor); /** * Color of links that are not active and unvisited. See the link * attribute definition in HTML 4.01. This attribute is deprecated in * HTML 4.01. */ public String getLink(); /** * Color of links that are not active and unvisited. See the link * attribute definition in HTML 4.01. This attribute is deprecated in * HTML 4.01. */ public void setLink(String link); /** * Document text color. See the text attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public String getText(); /** * Document text color. See the text attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public void setText(String text); /** * Color of links that have been visited by the user. See the vlink * attribute definition in HTML 4.01. This attribute is deprecated in * HTML 4.01. */ public String getVLink(); /** * Color of links that have been visited by the user. See the vlink * attribute definition in HTML 4.01. This attribute is deprecated in * HTML 4.01. */ public void setVLink(String vLink); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLButtonElement.java0000644000175000017500000000755110726473502025217 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Push button. See the BUTTON element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLButtonElement extends HTMLElement { /** * Returns the FORM element containing this control. Returns * null if this control is not within the context of a * form. */ public HTMLFormElement getForm(); /** * A single character access key to give access to the form control. See * the accesskey attribute definition in HTML 4.01. */ public String getAccessKey(); /** * A single character access key to give access to the form control. See * the accesskey attribute definition in HTML 4.01. */ public void setAccessKey(String accessKey); /** * The control is unavailable in this context. See the disabled attribute * definition in HTML 4.01. */ public boolean getDisabled(); /** * The control is unavailable in this context. See the disabled attribute * definition in HTML 4.01. */ public void setDisabled(boolean disabled); /** * Form control or object name when submitted with a form. See the name * attribute definition in HTML 4.01. */ public String getName(); /** * Form control or object name when submitted with a form. See the name * attribute definition in HTML 4.01. */ public void setName(String name); /** * Index that represents the element's position in the tabbing order. See * the tabindex attribute definition in HTML 4.01. */ public int getTabIndex(); /** * Index that represents the element's position in the tabbing order. See * the tabindex attribute definition in HTML 4.01. */ public void setTabIndex(int tabIndex); /** * The type of button (all lower case). See the type attribute definition * in HTML 4.01. */ public String getType(); /** * The current form control value. See the value attribute definition in * HTML 4.01. */ public String getValue(); /** * The current form control value. See the value attribute definition in * HTML 4.01. */ public void setValue(String value); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLCollection.java0000644000175000017500000000727310726473510024525 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; import org.w3c.dom.Node; /** * An HTMLCollection is a list of nodes. An individual node may * be accessed by either ordinal index or the node's name or * id attributes. Collections in the HTML DOM are assumed to be * live meaning that they are automatically updated when the underlying * document is changed. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLCollection { /** * This attribute specifies the length or size of the list. */ public int getLength(); /** * This method retrieves a node specified by ordinal index. Nodes are * numbered in tree order (depth-first traversal order). * @param index The index of the node to be fetched. The index origin is * 0. * @return The Node at the corresponding position upon * success. A value of null is returned if the index is * out of range. */ public Node item(int index); /** * This method retrieves a Node using a name. With [HTML 4.01] * documents, it first searches for a Node with a matching * id attribute. If it doesn't find one, it then searches * for a Node with a matching name attribute, * but only on those elements that are allowed a name attribute. With [XHTML 1.0] * documents, this method only searches for Nodes with a * matching id attribute. This method is case insensitive * in HTML documents and case sensitive in XHTML documents. * @param name The name of the Node to be fetched. * @return The Node with a name or * id attribute whose value corresponds to the specified * string. Upon failure (e.g., no node with this name exists), returns * null. */ public Node namedItem(String name); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLDListElement.java0000644000175000017500000000422110726473476024764 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Definition list. See the DL element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLDListElement extends HTMLElement { /** * Reduce spacing between list items. See the compact attribute definition * in HTML 4.01. This attribute is deprecated in HTML 4.01. */ public boolean getCompact(); /** * Reduce spacing between list items. See the compact attribute definition * in HTML 4.01. This attribute is deprecated in HTML 4.01. */ public void setCompact(boolean compact); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLDirectoryElement.java0000644000175000017500000000430310726473510025677 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Directory list. See the DIR element definition in HTML 4.01. This element * is deprecated in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLDirectoryElement extends HTMLElement { /** * Reduce spacing between list items. See the compact attribute definition * in HTML 4.01. This attribute is deprecated in HTML 4.01. */ public boolean getCompact(); /** * Reduce spacing between list items. See the compact attribute definition * in HTML 4.01. This attribute is deprecated in HTML 4.01. */ public void setCompact(boolean compact); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLDivElement.java0000644000175000017500000000417410726473506024470 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Generic block container. See the DIV element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLDivElement extends HTMLElement { /** * Horizontal text alignment. See the align attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public String getAlign(); /** * Horizontal text alignment. See the align attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public void setAlign(String align); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLDocument.java0000644000175000017500000003231610726473510024204 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.DOMException; /** * An HTMLDocument is the root of the HTML hierarchy and holds * the entire content. Besides providing access to the hierarchy, it also * provides some convenience methods for accessing certain sets of * information from the document. *

The following properties have been deprecated in favor of the * corresponding ones for the BODY element:alinkColorbackground * bgColorfgColorlinkColorvlinkColorIn DOM Level 2, the method * getElementById is inherited from the Document * interface where it was moved to. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLDocument extends Document { /** * The title of a document as specified by the TITLE element * in the head of the document. */ public String getTitle(); /** * The title of a document as specified by the TITLE element * in the head of the document. */ public void setTitle(String title); /** * Returns the URI [IETF RFC 2396] of the page that linked to this page. The value is an * empty string if the user navigated to the page directly (not through * a link, but, for example, via a bookmark). */ public String getReferrer(); /** * The domain name of the server that served the document, or * null if the server cannot be identified by a domain * name. */ public String getDomain(); /** * The absolute URI [IETF RFC 2396] of the document. */ public String getURL(); /** * The element that contains the content for the document. In documents * with BODY contents, returns the BODY * element. In frameset documents, this returns the outermost * FRAMESET element. */ public HTMLElement getBody(); /** * The element that contains the content for the document. In documents * with BODY contents, returns the BODY * element. In frameset documents, this returns the outermost * FRAMESET element. */ public void setBody(HTMLElement body); /** * A collection of all the IMG elements in a document. The * behavior is limited to IMG elements for backwards * compatibility. As suggested by [HTML 4.01], to include images, authors may use * the OBJECT element or the IMG element. * Therefore, it is recommended not to use this attribute to find the * images in the document but getElementsByTagName with * HTML 4.01 or getElementsByTagNameNS with XHTML 1.0. */ public HTMLCollection getImages(); /** * A collection of all the OBJECT elements that include * applets and APPLET (deprecated) elements in a document. */ public HTMLCollection getApplets(); /** * A collection of all AREA elements and anchor ( * A) elements in a document with a value for the * href attribute. */ public HTMLCollection getLinks(); /** * A collection of all the forms of a document. */ public HTMLCollection getForms(); /** * A collection of all the anchor (A) elements in a document * with a value for the name attribute. For reasons of * backward compatibility, the returned set of anchors only contains * those anchors created with the name attribute, not those * created with the id attribute. Note that in [XHTML 1.0], the * name attribute (see section 4.10) has no semantics and * is only present for legacy user agents: the id attribute * is used instead. Users should prefer the iterator mechanisms provided * by [DOM Level 2 Traversal] instead. */ public HTMLCollection getAnchors(); /** * This mutable string attribute denotes persistent state information * that (1) is associated with the current frame or document and (2) is * composed of information described by the cookies * non-terminal of [IETF RFC 2965], Section 4.2.2. *
If no persistent state information is available for the current * frame or document document, then this property's value is an empty * string. *
When this attribute is read, all cookies are returned as a single * string, with each cookie's name-value pair concatenated into a list * of name-value pairs, each list item being separated by a ';' * (semicolon). *
When this attribute is set, the value it is set to should be a * string that adheres to the cookie non-terminal of [IETF RFC 2965]; that * is, it should be a single name-value pair followed by zero or more * cookie attribute values. If no domain attribute is specified, then * the domain attribute for the new value defaults to the host portion * of an absolute URI [IETF RFC 2396] of the current frame or document. If no path * attribute is specified, then the path attribute for the new value * defaults to the absolute path portion of the URI [IETF RFC 2396] of the current * frame or document. If no max-age attribute is specified, then the * max-age attribute for the new value defaults to a user agent defined * value. If a cookie with the specified name is already associated with * the current frame or document, then the new value as well as the new * attributes replace the old value and attributes. If a max-age * attribute of 0 is specified for the new value, then any existing * cookies of the specified name are removed from the cookie storage. * See [IETF RFC 2965] for the semantics of persistent state item attribute value * pairs. The precise nature of a user agent session is not defined by * this specification. */ public String getCookie(); /** * This mutable string attribute denotes persistent state information * that (1) is associated with the current frame or document and (2) is * composed of information described by the cookies * non-terminal of [IETF RFC 2965], Section 4.2.2. *
If no persistent state information is available for the current * frame or document document, then this property's value is an empty * string. *
When this attribute is read, all cookies are returned as a single * string, with each cookie's name-value pair concatenated into a list * of name-value pairs, each list item being separated by a ';' * (semicolon). *
When this attribute is set, the value it is set to should be a * string that adheres to the cookie non-terminal of [IETF RFC 2965]; that * is, it should be a single name-value pair followed by zero or more * cookie attribute values. If no domain attribute is specified, then * the domain attribute for the new value defaults to the host portion * of an absolute URI [IETF RFC 2396] of the current frame or document. If no path * attribute is specified, then the path attribute for the new value * defaults to the absolute path portion of the URI [IETF RFC 2396] of the current * frame or document. If no max-age attribute is specified, then the * max-age attribute for the new value defaults to a user agent defined * value. If a cookie with the specified name is already associated with * the current frame or document, then the new value as well as the new * attributes replace the old value and attributes. If a max-age * attribute of 0 is specified for the new value, then any existing * cookies of the specified name are removed from the cookie storage. * See [IETF RFC 2965] for the semantics of persistent state item attribute value * pairs. The precise nature of a user agent session is not defined by * this specification. * @exception DOMException * SYNTAX_ERR: If the new value does not adhere to the cookie syntax * specified by [IETF RFC 2965]. */ public void setCookie(String cookie) throws DOMException; /** * Open a document stream for writing. If a document exists in the target, * this method clears it. This method and the ones following allow a * user to add to or replace the structure model of a document using * strings of unparsed HTML. At the time of writing alternate methods * for providing similar functionality for both HTML and XML documents * were being considered (see [DOM Level 3 Load and Save]). */ public void open(); /** * Closes a document stream opened by open() and forces * rendering. */ public void close(); /** * Write a string of text to a document stream opened by * open(). Note that the function will produce a document * which is not necessarily driven by a DTD and therefore might be * produce an invalid result in the context of the document. * @param text The string to be parsed into some structure in the * document structure model. */ public void write(String text); /** * Write a string of text followed by a newline character to a document * stream opened by open(). Note that the function will * produce a document which is not necessarily driven by a DTD and * therefore might be produce an invalid result in the context of the * document * @param text The string to be parsed into some structure in the * document structure model. */ public void writeln(String text); /** * With [HTML 4.01] documents, this method returns the (possibly empty) collection * of elements whose name value is given by * elementName. In [XHTML 1.0] documents, this methods only return the * (possibly empty) collection of form controls with matching name. This * method is case sensitive. * @param elementName The name attribute value for an * element. * @return The matching elements. */ public NodeList getElementsByName(String elementName); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLElement.java0000644000175000017500000001027010726473510024012 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; import org.w3c.dom.Element; /** * All HTML element interfaces derive from this class. Elements that only * expose the HTML core attributes are represented by the base * HTMLElement interface. These elements are as follows: * special: SUB, SUP, SPAN, BDOfont: TT, I, B, U, S, STRIKE, BIG, SMALL * phrase: EM, STRONG, DFN, CODE, SAMP, KBD, VAR, CITE, ACRONYM, ABBRlist: * DD, DTNOFRAMES, NOSCRIPTADDRESS, CENTERThe style attribute * of an HTML element is accessible through the * ElementCSSInlineStyle interface which is defined in the CSS * module [DOM Level 2 Style Sheets and CSS]. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLElement extends Element { /** * The element's identifier. See the id attribute definition in HTML 4.01. */ public String getId(); /** * The element's identifier. See the id attribute definition in HTML 4.01. */ public void setId(String id); /** * The element's advisory title. See the title attribute definition in * HTML 4.01. */ public String getTitle(); /** * The element's advisory title. See the title attribute definition in * HTML 4.01. */ public void setTitle(String title); /** * Language code defined in RFC 1766. See the lang attribute definition in * HTML 4.01. */ public String getLang(); /** * Language code defined in RFC 1766. See the lang attribute definition in * HTML 4.01. */ public void setLang(String lang); /** * Specifies the base direction of directionally neutral text and the * directionality of tables. See the dir attribute definition in HTML * 4.01. */ public String getDir(); /** * Specifies the base direction of directionally neutral text and the * directionality of tables. See the dir attribute definition in HTML * 4.01. */ public void setDir(String dir); /** * The class attribute of the element. This attribute has been renamed due * to conflicts with the "class" keyword exposed by many languages. See * the class attribute definition in HTML 4.01. */ public String getClassName(); /** * The class attribute of the element. This attribute has been renamed due * to conflicts with the "class" keyword exposed by many languages. See * the class attribute definition in HTML 4.01. */ public void setClassName(String className); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLFieldSetElement.java0000644000175000017500000000400510726473506025436 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Organizes form controls into logical groups. See the FIELDSET element * definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLFieldSetElement extends HTMLElement { /** * Returns the FORM element containing this control. Returns * null if this control is not within the context of a * form. */ public HTMLFormElement getForm(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLFontElement.java0000644000175000017500000000552310726473504024651 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Local change to font. See the FONT element definition in HTML 4.01. This * element is deprecated in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLFontElement extends HTMLElement { /** * Font color. See the color attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public String getColor(); /** * Font color. See the color attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public void setColor(String color); /** * Font face identifier. See the face attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public String getFace(); /** * Font face identifier. See the face attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public void setFace(String face); /** * Font size. See the size attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public String getSize(); /** * Font size. See the size attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public void setSize(String size); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLFormElement.java0000644000175000017500000001153010726473506024643 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * The FORM element encompasses behavior similar to a collection * and an element. It provides direct access to the contained form controls * as well as the attributes of the form element. See the FORM element * definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLFormElement extends HTMLElement { /** * Returns a collection of all form control elements in the form. */ public HTMLCollection getElements(); /** * The number of form controls in the form. */ public int getLength(); /** * Names the form. */ public String getName(); /** * Names the form. */ public void setName(String name); /** * List of character sets supported by the server. See the accept-charset * attribute definition in HTML 4.01. */ public String getAcceptCharset(); /** * List of character sets supported by the server. See the accept-charset * attribute definition in HTML 4.01. */ public void setAcceptCharset(String acceptCharset); /** * Server-side form handler. See the action attribute definition in HTML * 4.01. */ public String getAction(); /** * Server-side form handler. See the action attribute definition in HTML * 4.01. */ public void setAction(String action); /** * The content type of the submitted form, generally * "application/x-www-form-urlencoded". See the enctype attribute * definition in HTML 4.01. The onsubmit even handler is not guaranteed * to be triggered when invoking this method. The behavior is * inconsistent for historical reasons and authors should not rely on a * particular one. */ public String getEnctype(); /** * The content type of the submitted form, generally * "application/x-www-form-urlencoded". See the enctype attribute * definition in HTML 4.01. The onsubmit even handler is not guaranteed * to be triggered when invoking this method. The behavior is * inconsistent for historical reasons and authors should not rely on a * particular one. */ public void setEnctype(String enctype); /** * HTTP method [IETF RFC 2616] used to submit form. See the method attribute definition * in HTML 4.01. */ public String getMethod(); /** * HTTP method [IETF RFC 2616] used to submit form. See the method attribute definition * in HTML 4.01. */ public void setMethod(String method); /** * Frame to render the resource in. See the target attribute definition in * HTML 4.01. */ public String getTarget(); /** * Frame to render the resource in. See the target attribute definition in * HTML 4.01. */ public void setTarget(String target); /** * Submits the form. It performs the same action as a submit button. */ public void submit(); /** * Restores a form element's default values. It performs the same action * as a reset button. */ public void reset(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLFrameElement.java0000644000175000017500000001171310726473500024767 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; import org.w3c.dom.Document; /** * Create a frame. See the FRAME element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLFrameElement extends HTMLElement { /** * Request frame borders. See the frameborder attribute definition in HTML * 4.01. */ public String getFrameBorder(); /** * Request frame borders. See the frameborder attribute definition in HTML * 4.01. */ public void setFrameBorder(String frameBorder); /** * URI [IETF RFC 2396] designating a long description of this image or frame. See the * longdesc attribute definition in HTML 4.01. */ public String getLongDesc(); /** * URI [IETF RFC 2396] designating a long description of this image or frame. See the * longdesc attribute definition in HTML 4.01. */ public void setLongDesc(String longDesc); /** * Frame margin height, in pixels. See the marginheight attribute * definition in HTML 4.01. */ public String getMarginHeight(); /** * Frame margin height, in pixels. See the marginheight attribute * definition in HTML 4.01. */ public void setMarginHeight(String marginHeight); /** * Frame margin width, in pixels. See the marginwidth attribute definition * in HTML 4.01. */ public String getMarginWidth(); /** * Frame margin width, in pixels. See the marginwidth attribute definition * in HTML 4.01. */ public void setMarginWidth(String marginWidth); /** * The frame name (object of the target attribute). See the * name attribute definition in HTML 4.01. */ public String getName(); /** * The frame name (object of the target attribute). See the * name attribute definition in HTML 4.01. */ public void setName(String name); /** * When true, forbid user from resizing frame. See the noresize attribute * definition in HTML 4.01. */ public boolean getNoResize(); /** * When true, forbid user from resizing frame. See the noresize attribute * definition in HTML 4.01. */ public void setNoResize(boolean noResize); /** * Specify whether or not the frame should have scrollbars. See the * scrolling attribute definition in HTML 4.01. */ public String getScrolling(); /** * Specify whether or not the frame should have scrollbars. See the * scrolling attribute definition in HTML 4.01. */ public void setScrolling(String scrolling); /** * A URI [IETF RFC 2396] designating the initial frame contents. See the src attribute * definition in HTML 4.01. */ public String getSrc(); /** * A URI [IETF RFC 2396] designating the initial frame contents. See the src attribute * definition in HTML 4.01. */ public void setSrc(String src); /** * The document this frame contains, if there is any and it is available, * or null otherwise. * @since DOM Level 2 */ public Document getContentDocument(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLFrameSetElement.java0000644000175000017500000000464010726473506025452 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Create a grid of frames. See the FRAMESET element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLFrameSetElement extends HTMLElement { /** * The number of columns of frames in the frameset. See the cols attribute * definition in HTML 4.01. */ public String getCols(); /** * The number of columns of frames in the frameset. See the cols attribute * definition in HTML 4.01. */ public void setCols(String cols); /** * The number of rows of frames in the frameset. See the rows attribute * definition in HTML 4.01. */ public String getRows(); /** * The number of rows of frames in the frameset. See the rows attribute * definition in HTML 4.01. */ public void setRows(String rows); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLHRElement.java0000644000175000017500000000661010726473506024254 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Create a horizontal rule. See the HR element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLHRElement extends HTMLElement { /** * Align the rule on the page. See the align attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public String getAlign(); /** * Align the rule on the page. See the align attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public void setAlign(String align); /** * Indicates to the user agent that there should be no shading in the * rendering of this element. See the noshade attribute definition in * HTML 4.01. This attribute is deprecated in HTML 4.01. */ public boolean getNoShade(); /** * Indicates to the user agent that there should be no shading in the * rendering of this element. See the noshade attribute definition in * HTML 4.01. This attribute is deprecated in HTML 4.01. */ public void setNoShade(boolean noShade); /** * The height of the rule. See the size attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public String getSize(); /** * The height of the rule. See the size attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public void setSize(String size); /** * The width of the rule. See the width attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public String getWidth(); /** * The width of the rule. See the width attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public void setWidth(String width); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLHeadElement.java0000644000175000017500000000431210726473502024575 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Document head information. See the HEAD element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLHeadElement extends HTMLElement { /** * URI [IETF RFC 2396] designating a metadata profile. See the profile attribute * definition in HTML 4.01. */ public String getProfile(); /** * URI [IETF RFC 2396] designating a metadata profile. See the profile attribute * definition in HTML 4.01. */ public void setProfile(String profile); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLHeadingElement.java0000644000175000017500000000424010726473510025272 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * For the H1 to H6 elements. See the H1 element * definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLHeadingElement extends HTMLElement { /** * Horizontal text alignment. See the align attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public String getAlign(); /** * Horizontal text alignment. See the align attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public void setAlign(String align); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLHtmlElement.java0000644000175000017500000000425710726473510024647 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Root of an HTML document. See the HTML element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLHtmlElement extends HTMLElement { /** * Version information about the document's DTD. See the version attribute * definition in HTML 4.01. This attribute is deprecated in HTML 4.01. */ public String getVersion(); /** * Version information about the document's DTD. See the version attribute * definition in HTML 4.01. This attribute is deprecated in HTML 4.01. */ public void setVersion(String version); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLIFrameElement.java0000644000175000017500000001316610726473502025106 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; import org.w3c.dom.Document; /** * Inline subwindows. See the IFRAME element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLIFrameElement extends HTMLElement { /** * Aligns this object (vertically or horizontally) with respect to its * surrounding text. See the align attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public String getAlign(); /** * Aligns this object (vertically or horizontally) with respect to its * surrounding text. See the align attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public void setAlign(String align); /** * Request frame borders. See the frameborder attribute definition in HTML * 4.01. */ public String getFrameBorder(); /** * Request frame borders. See the frameborder attribute definition in HTML * 4.01. */ public void setFrameBorder(String frameBorder); /** * Frame height. See the height attribute definition in HTML 4.01. */ public String getHeight(); /** * Frame height. See the height attribute definition in HTML 4.01. */ public void setHeight(String height); /** * URI [IETF RFC 2396] designating a long description of this image or frame. See the * longdesc attribute definition in HTML 4.01. */ public String getLongDesc(); /** * URI [IETF RFC 2396] designating a long description of this image or frame. See the * longdesc attribute definition in HTML 4.01. */ public void setLongDesc(String longDesc); /** * Frame margin height, in pixels. See the marginheight attribute * definition in HTML 4.01. */ public String getMarginHeight(); /** * Frame margin height, in pixels. See the marginheight attribute * definition in HTML 4.01. */ public void setMarginHeight(String marginHeight); /** * Frame margin width, in pixels. See the marginwidth attribute definition * in HTML 4.01. */ public String getMarginWidth(); /** * Frame margin width, in pixels. See the marginwidth attribute definition * in HTML 4.01. */ public void setMarginWidth(String marginWidth); /** * The frame name (object of the target attribute). See the * name attribute definition in HTML 4.01. */ public String getName(); /** * The frame name (object of the target attribute). See the * name attribute definition in HTML 4.01. */ public void setName(String name); /** * Specify whether or not the frame should have scrollbars. See the * scrolling attribute definition in HTML 4.01. */ public String getScrolling(); /** * Specify whether or not the frame should have scrollbars. See the * scrolling attribute definition in HTML 4.01. */ public void setScrolling(String scrolling); /** * A URI [IETF RFC 2396] designating the initial frame contents. See the src attribute * definition in HTML 4.01. */ public String getSrc(); /** * A URI [IETF RFC 2396] designating the initial frame contents. See the src attribute * definition in HTML 4.01. */ public void setSrc(String src); /** * Frame width. See the width attribute definition in HTML 4.01. */ public String getWidth(); /** * Frame width. See the width attribute definition in HTML 4.01. */ public void setWidth(String width); /** * The document this frame contains, if there is any and it is available, * or null otherwise. * @since DOM Level 2 */ public Document getContentDocument(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLImageElement.java0000644000175000017500000002026010726473500024754 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Embedded image. See the IMG element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLImageElement extends HTMLElement { /** * The name of the element (for backwards compatibility). */ public String getName(); /** * The name of the element (for backwards compatibility). */ public void setName(String name); /** * Aligns this object (vertically or horizontally) with respect to its * surrounding text. See the align attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public String getAlign(); /** * Aligns this object (vertically or horizontally) with respect to its * surrounding text. See the align attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public void setAlign(String align); /** * Alternate text for user agents not rendering the normal content of this * element. See the alt attribute definition in HTML 4.01. */ public String getAlt(); /** * Alternate text for user agents not rendering the normal content of this * element. See the alt attribute definition in HTML 4.01. */ public void setAlt(String alt); /** * Width of border around image. See the border attribute definition in * HTML 4.01. This attribute is deprecated in HTML 4.01. Note that the * type of this attribute was DOMString in DOM Level 1 HTML [DOM Level 1] * . */ public String getBorder(); /** * Width of border around image. See the border attribute definition in * HTML 4.01. This attribute is deprecated in HTML 4.01. Note that the * type of this attribute was DOMString in DOM Level 1 HTML [DOM Level 1] * . */ public void setBorder(String border); /** * Height of the image in pixels. See the height attribute definition in * HTML 4.01. Note that the type of this attribute was * DOMString in DOM Level 1 HTML [DOM Level 1]. * @version DOM Level 2 */ public int getHeight(); /** * Height of the image in pixels. See the height attribute definition in * HTML 4.01. Note that the type of this attribute was * DOMString in DOM Level 1 HTML [DOM Level 1]. * @version DOM Level 2 */ public void setHeight(int height); /** * Horizontal space to the left and right of this image in pixels. See the * hspace attribute definition in HTML 4.01. This attribute is * deprecated in HTML 4.01. Note that the type of this attribute was * DOMString in DOM Level 1 HTML [DOM Level 1]. * @version DOM Level 2 */ public int getHspace(); /** * Horizontal space to the left and right of this image in pixels. See the * hspace attribute definition in HTML 4.01. This attribute is * deprecated in HTML 4.01. Note that the type of this attribute was * DOMString in DOM Level 1 HTML [DOM Level 1]. * @version DOM Level 2 */ public void setHspace(int hspace); /** * Use server-side image map. See the ismap attribute definition in HTML * 4.01. */ public boolean getIsMap(); /** * Use server-side image map. See the ismap attribute definition in HTML * 4.01. */ public void setIsMap(boolean isMap); /** * URI [IETF RFC 2396] designating a long description of this image or frame. See the * longdesc attribute definition in HTML 4.01. */ public String getLongDesc(); /** * URI [IETF RFC 2396] designating a long description of this image or frame. See the * longdesc attribute definition in HTML 4.01. */ public void setLongDesc(String longDesc); /** * URI [IETF RFC 2396] designating the source of this image. See the src attribute * definition in HTML 4.01. */ public String getSrc(); /** * URI [IETF RFC 2396] designating the source of this image. See the src attribute * definition in HTML 4.01. */ public void setSrc(String src); /** * Use client-side image map. See the usemap attribute definition in HTML * 4.01. */ public String getUseMap(); /** * Use client-side image map. See the usemap attribute definition in HTML * 4.01. */ public void setUseMap(String useMap); /** * Vertical space above and below this image in pixels. See the vspace * attribute definition in HTML 4.01. This attribute is deprecated in * HTML 4.01. Note that the type of this attribute was "DOMString" in * DOM Level 1 HTML [DOM Level 1]. * @version DOM Level 2 */ public int getVspace(); /** * Vertical space above and below this image in pixels. See the vspace * attribute definition in HTML 4.01. This attribute is deprecated in * HTML 4.01. Note that the type of this attribute was "DOMString" in * DOM Level 1 HTML [DOM Level 1]. * @version DOM Level 2 */ public void setVspace(int vspace); /** * The width of the image in pixels. See the width attribute definition in * HTML 4.01. Note that the type of this attribute was * DOMString in DOM Level 1 HTML [DOM Level 1]. * @version DOM Level 2 */ public int getWidth(); /** * The width of the image in pixels. See the width attribute definition in * HTML 4.01. Note that the type of this attribute was * DOMString in DOM Level 1 HTML [DOM Level 1]. * @version DOM Level 2 */ public void setWidth(int width); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLInputElement.java0000644000175000017500000003237010726473506025044 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Form control.Depending upon the environment in which the page is being * viewed, the value property may be read-only for the file upload input * type. For the "password" input type, the actual value returned may be * masked to prevent unauthorized use. See the INPUT element definition in [HTML 4.01]. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLInputElement extends HTMLElement { /** * When the type attribute of the element has the value * "text", "file" or "password", this represents the HTML value * attribute of the element. The value of this attribute does not change * if the contents of the corresponding form control, in an interactive * user agent, changes. See the value attribute definition in HTML 4.01. */ public String getDefaultValue(); /** * When the type attribute of the element has the value * "text", "file" or "password", this represents the HTML value * attribute of the element. The value of this attribute does not change * if the contents of the corresponding form control, in an interactive * user agent, changes. See the value attribute definition in HTML 4.01. */ public void setDefaultValue(String defaultValue); /** * When type has the value "radio" or "checkbox", this * represents the HTML checked attribute of the element. The value of * this attribute does not change if the state of the corresponding form * control, in an interactive user agent, changes. See the checked * attribute definition in HTML 4.01. */ public boolean getDefaultChecked(); /** * When type has the value "radio" or "checkbox", this * represents the HTML checked attribute of the element. The value of * this attribute does not change if the state of the corresponding form * control, in an interactive user agent, changes. See the checked * attribute definition in HTML 4.01. */ public void setDefaultChecked(boolean defaultChecked); /** * Returns the FORM element containing this control. Returns * null if this control is not within the context of a * form. */ public HTMLFormElement getForm(); /** * A comma-separated list of content types that a server processing this * form will handle correctly. See the accept attribute definition in * HTML 4.01. */ public String getAccept(); /** * A comma-separated list of content types that a server processing this * form will handle correctly. See the accept attribute definition in * HTML 4.01. */ public void setAccept(String accept); /** * A single character access key to give access to the form control. See * the accesskey attribute definition in HTML 4.01. */ public String getAccessKey(); /** * A single character access key to give access to the form control. See * the accesskey attribute definition in HTML 4.01. */ public void setAccessKey(String accessKey); /** * Aligns this object (vertically or horizontally) with respect to its * surrounding text. See the align attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public String getAlign(); /** * Aligns this object (vertically or horizontally) with respect to its * surrounding text. See the align attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public void setAlign(String align); /** * Alternate text for user agents not rendering the normal content of this * element. See the alt attribute definition in HTML 4.01. */ public String getAlt(); /** * Alternate text for user agents not rendering the normal content of this * element. See the alt attribute definition in HTML 4.01. */ public void setAlt(String alt); /** * When the type attribute of the element has the value * "radio" or "checkbox", this represents the current state of the form * control, in an interactive user agent. Changes to this attribute * change the state of the form control, but do not change the value of * the HTML checked attribute of the INPUT element.During the handling * of a click event on an input element with a type attribute that has * the value "radio" or "checkbox", some implementations may change the * value of this property before the event is being dispatched in the * document. If the default action of the event is canceled, the value * of the property may be changed back to its original value. This means * that the value of this property during the handling of click events * is implementation dependent. */ public boolean getChecked(); /** * When the type attribute of the element has the value * "radio" or "checkbox", this represents the current state of the form * control, in an interactive user agent. Changes to this attribute * change the state of the form control, but do not change the value of * the HTML checked attribute of the INPUT element.During the handling * of a click event on an input element with a type attribute that has * the value "radio" or "checkbox", some implementations may change the * value of this property before the event is being dispatched in the * document. If the default action of the event is canceled, the value * of the property may be changed back to its original value. This means * that the value of this property during the handling of click events * is implementation dependent. */ public void setChecked(boolean checked); /** * The control is unavailable in this context. See the disabled attribute * definition in HTML 4.01. */ public boolean getDisabled(); /** * The control is unavailable in this context. See the disabled attribute * definition in HTML 4.01. */ public void setDisabled(boolean disabled); /** * Maximum number of characters for text fields, when type * has the value "text" or "password". See the maxlength attribute * definition in HTML 4.01. */ public int getMaxLength(); /** * Maximum number of characters for text fields, when type * has the value "text" or "password". See the maxlength attribute * definition in HTML 4.01. */ public void setMaxLength(int maxLength); /** * Form control or object name when submitted with a form. See the name * attribute definition in HTML 4.01. */ public String getName(); /** * Form control or object name when submitted with a form. See the name * attribute definition in HTML 4.01. */ public void setName(String name); /** * This control is read-only. Relevant only when type has the * value "text" or "password". See the readonly attribute definition in * HTML 4.01. */ public boolean getReadOnly(); /** * This control is read-only. Relevant only when type has the * value "text" or "password". See the readonly attribute definition in * HTML 4.01. */ public void setReadOnly(boolean readOnly); /** * Size information. The precise meaning is specific to each type of * field. See the size attribute definition in HTML 4.01. * @version DOM Level 2 */ public int getSize(); /** * Size information. The precise meaning is specific to each type of * field. See the size attribute definition in HTML 4.01. * @version DOM Level 2 */ public void setSize(int size); /** * When the type attribute has the value "image", this * attribute specifies the location of the image to be used to decorate * the graphical submit button. See the src attribute definition in HTML * 4.01. */ public String getSrc(); /** * When the type attribute has the value "image", this * attribute specifies the location of the image to be used to decorate * the graphical submit button. See the src attribute definition in HTML * 4.01. */ public void setSrc(String src); /** * Index that represents the element's position in the tabbing order. See * the tabindex attribute definition in HTML 4.01. */ public int getTabIndex(); /** * Index that represents the element's position in the tabbing order. See * the tabindex attribute definition in HTML 4.01. */ public void setTabIndex(int tabIndex); /** * The type of control created (all lower case). See the type attribute * definition in HTML 4.01. * @version DOM Level 2 */ public String getType(); /** * The type of control created (all lower case). See the type attribute * definition in HTML 4.01. * @version DOM Level 2 */ public void setType(String type); /** * Use client-side image map. See the usemap attribute definition in HTML * 4.01. */ public String getUseMap(); /** * Use client-side image map. See the usemap attribute definition in HTML * 4.01. */ public void setUseMap(String useMap); /** * When the type attribute of the element has the value * "text", "file" or "password", this represents the current contents of * the corresponding form control, in an interactive user agent. * Changing this attribute changes the contents of the form control, but * does not change the value of the HTML value attribute of the element. * When the type attribute of the element has the value * "button", "hidden", "submit", "reset", "image", "checkbox" or * "radio", this represents the HTML value attribute of the element. See * the value attribute definition in HTML 4.01. */ public String getValue(); /** * When the type attribute of the element has the value * "text", "file" or "password", this represents the current contents of * the corresponding form control, in an interactive user agent. * Changing this attribute changes the contents of the form control, but * does not change the value of the HTML value attribute of the element. * When the type attribute of the element has the value * "button", "hidden", "submit", "reset", "image", "checkbox" or * "radio", this represents the HTML value attribute of the element. See * the value attribute definition in HTML 4.01. */ public void setValue(String value); /** * Removes keyboard focus from this element. */ public void blur(); /** * Gives keyboard focus to this element. */ public void focus(); /** * Select the contents of the text area. For INPUT elements * whose type attribute has one of the following values: * "text", "file", or "password". */ public void select(); /** * Simulate a mouse-click. For INPUT elements whose * type attribute has one of the following values: * "button", "checkbox", "radio", "reset", or "submit". */ public void click(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLIsIndexElement.java0000644000175000017500000000464510726473506025314 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * This element is used for single-line text input. See the ISINDEX element * definition in HTML 4.01. This element is deprecated in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLIsIndexElement extends HTMLElement { /** * Returns the FORM element containing this control. Returns * null if this control is not within the context of a * form. */ public HTMLFormElement getForm(); /** * The prompt message. See the prompt attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public String getPrompt(); /** * The prompt message. See the prompt attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public void setPrompt(String prompt); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLLIElement.java0000644000175000017500000000503510726473502024243 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * List item. See the LI element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLLIElement extends HTMLElement { /** * List item bullet style. See the type attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public String getType(); /** * List item bullet style. See the type attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public void setType(String type); /** * Reset sequence number when used in OL. See the value * attribute definition in HTML 4.01. This attribute is deprecated in * HTML 4.01. */ public int getValue(); /** * Reset sequence number when used in OL. See the value * attribute definition in HTML 4.01. This attribute is deprecated in * HTML 4.01. */ public void setValue(int value); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLLabelElement.java0000644000175000017500000000544410726473510024761 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Form field label text. See the LABEL element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLLabelElement extends HTMLElement { /** * Returns the FORM element containing this control. Returns * null if this control is not within the context of a * form. */ public HTMLFormElement getForm(); /** * A single character access key to give access to the form control. See * the accesskey attribute definition in HTML 4.01. */ public String getAccessKey(); /** * A single character access key to give access to the form control. See * the accesskey attribute definition in HTML 4.01. */ public void setAccessKey(String accessKey); /** * This attribute links this label with another form control by * id attribute. See the for attribute definition in HTML * 4.01. */ public String getHtmlFor(); /** * This attribute links this label with another form control by * id attribute. See the for attribute definition in HTML * 4.01. */ public void setHtmlFor(String htmlFor); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLLegendElement.java0000644000175000017500000000552510726473502025141 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Provides a caption for a FIELDSET grouping. See the LEGEND * element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLLegendElement extends HTMLElement { /** * Returns the FORM element containing this control. Returns * null if this control is not within the context of a * form. */ public HTMLFormElement getForm(); /** * A single character access key to give access to the form control. See * the accesskey attribute definition in HTML 4.01. */ public String getAccessKey(); /** * A single character access key to give access to the form control. See * the accesskey attribute definition in HTML 4.01. */ public void setAccessKey(String accessKey); /** * Text alignment relative to FIELDSET. See the align * attribute definition in HTML 4.01. This attribute is deprecated in * HTML 4.01. */ public String getAlign(); /** * Text alignment relative to FIELDSET. See the align * attribute definition in HTML 4.01. This attribute is deprecated in * HTML 4.01. */ public void setAlign(String align); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLLinkElement.java0000644000175000017500000001173310726473510024635 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * The LINK element specifies a link to an external resource, and * defines this document's relationship to that resource (or vice versa). * See the LINK element definition in HTML 4.01 (see also the * LinkStyle interface in the StyleSheet module [DOM Level 2 Style Sheets and CSS]). *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLLinkElement extends HTMLElement { /** * Enables/disables the link. This is currently only used for style sheet * links, and may be used to activate or deactivate style sheets. */ public boolean getDisabled(); /** * Enables/disables the link. This is currently only used for style sheet * links, and may be used to activate or deactivate style sheets. */ public void setDisabled(boolean disabled); /** * The character encoding of the resource being linked to. See the charset * attribute definition in HTML 4.01. */ public String getCharset(); /** * The character encoding of the resource being linked to. See the charset * attribute definition in HTML 4.01. */ public void setCharset(String charset); /** * The URI [IETF RFC 2396] of the linked resource. See the href attribute definition in * HTML 4.01. */ public String getHref(); /** * The URI [IETF RFC 2396] of the linked resource. See the href attribute definition in * HTML 4.01. */ public void setHref(String href); /** * Language code of the linked resource. See the hreflang attribute * definition in HTML 4.01. */ public String getHreflang(); /** * Language code of the linked resource. See the hreflang attribute * definition in HTML 4.01. */ public void setHreflang(String hreflang); /** * Designed for use with one or more target media. See the media attribute * definition in HTML 4.01. */ public String getMedia(); /** * Designed for use with one or more target media. See the media attribute * definition in HTML 4.01. */ public void setMedia(String media); /** * Forward link type. See the rel attribute definition in HTML 4.01. */ public String getRel(); /** * Forward link type. See the rel attribute definition in HTML 4.01. */ public void setRel(String rel); /** * Reverse link type. See the rev attribute definition in HTML 4.01. */ public String getRev(); /** * Reverse link type. See the rev attribute definition in HTML 4.01. */ public void setRev(String rev); /** * Frame to render the resource in. See the target attribute definition in * HTML 4.01. */ public String getTarget(); /** * Frame to render the resource in. See the target attribute definition in * HTML 4.01. */ public void setTarget(String target); /** * Advisory content type. See the type attribute definition in HTML 4.01. */ public String getType(); /** * Advisory content type. See the type attribute definition in HTML 4.01. */ public void setType(String type); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLMapElement.java0000644000175000017500000000427610726473510024461 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Client-side image map. See the MAP element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLMapElement extends HTMLElement { /** * The list of areas defined for the image map. */ public HTMLCollection getAreas(); /** * Names the map (for use with usemap). See the name * attribute definition in HTML 4.01. */ public String getName(); /** * Names the map (for use with usemap). See the name * attribute definition in HTML 4.01. */ public void setName(String name); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLMenuElement.java0000644000175000017500000000427210726473504024647 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Menu list. See the MENU element definition in HTML 4.01. This element is * deprecated in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLMenuElement extends HTMLElement { /** * Reduce spacing between list items. See the compact attribute definition * in HTML 4.01. This attribute is deprecated in HTML 4.01. */ public boolean getCompact(); /** * Reduce spacing between list items. See the compact attribute definition * in HTML 4.01. This attribute is deprecated in HTML 4.01. */ public void setCompact(boolean compact); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLMetaElement.java0000644000175000017500000000610510726473506024630 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * This contains generic meta-information about the document. See the META * element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLMetaElement extends HTMLElement { /** * Associated information. See the content attribute definition in HTML * 4.01. */ public String getContent(); /** * Associated information. See the content attribute definition in HTML * 4.01. */ public void setContent(String content); /** * HTTP response header name [IETF RFC 2616]. See the http-equiv attribute definition in * HTML 4.01. */ public String getHttpEquiv(); /** * HTTP response header name [IETF RFC 2616]. See the http-equiv attribute definition in * HTML 4.01. */ public void setHttpEquiv(String httpEquiv); /** * Meta information name. See the name attribute definition in HTML 4.01. */ public String getName(); /** * Meta information name. See the name attribute definition in HTML 4.01. */ public void setName(String name); /** * Select form of content. See the scheme attribute definition in HTML * 4.01. */ public String getScheme(); /** * Select form of content. See the scheme attribute definition in HTML * 4.01. */ public void setScheme(String scheme); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLModElement.java0000644000175000017500000000514410726473502024457 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Notice of modification to part of a document. See the INS and DEL element * definitions in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLModElement extends HTMLElement { /** * A URI [IETF RFC 2396] designating a document that describes the reason for the change. * See the cite attribute definition in HTML 4.01. */ public String getCite(); /** * A URI [IETF RFC 2396] designating a document that describes the reason for the change. * See the cite attribute definition in HTML 4.01. */ public void setCite(String cite); /** * The date and time of the change. See the datetime attribute definition * in HTML 4.01. */ public String getDateTime(); /** * The date and time of the change. See the datetime attribute definition * in HTML 4.01. */ public void setDateTime(String dateTime); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLOListElement.java0000644000175000017500000000555110726473510024773 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Ordered list. See the OL element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLOListElement extends HTMLElement { /** * Reduce spacing between list items. See the compact attribute definition * in HTML 4.01. This attribute is deprecated in HTML 4.01. */ public boolean getCompact(); /** * Reduce spacing between list items. See the compact attribute definition * in HTML 4.01. This attribute is deprecated in HTML 4.01. */ public void setCompact(boolean compact); /** * Starting sequence number. See the start attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public int getStart(); /** * Starting sequence number. See the start attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public void setStart(int start); /** * Numbering style. See the type attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public String getType(); /** * Numbering style. See the type attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public void setType(String type); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLObjectElement.java0000644000175000017500000002172410726473502025150 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; import org.w3c.dom.Document; /** * Generic embedded object.In principle, all properties on the object element * are read-write but in some environments some properties may be read-only * once the underlying object is instantiated. See the OBJECT element * definition in [HTML 4.01]. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLObjectElement extends HTMLElement { /** * Returns the FORM element containing this control. Returns * null if this control is not within the context of a * form. */ public HTMLFormElement getForm(); /** * Applet class file. See the code attribute for * HTMLAppletElement. */ public String getCode(); /** * Applet class file. See the code attribute for * HTMLAppletElement. */ public void setCode(String code); /** * Aligns this object (vertically or horizontally) with respect to its * surrounding text. See the align attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public String getAlign(); /** * Aligns this object (vertically or horizontally) with respect to its * surrounding text. See the align attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public void setAlign(String align); /** * Space-separated list of archives. See the archive attribute definition * in HTML 4.01. */ public String getArchive(); /** * Space-separated list of archives. See the archive attribute definition * in HTML 4.01. */ public void setArchive(String archive); /** * Width of border around the object. See the border attribute definition * in HTML 4.01. This attribute is deprecated in HTML 4.01. */ public String getBorder(); /** * Width of border around the object. See the border attribute definition * in HTML 4.01. This attribute is deprecated in HTML 4.01. */ public void setBorder(String border); /** * Base URI [IETF RFC 2396] for classid, data, and * archive attributes. See the codebase attribute definition * in HTML 4.01. */ public String getCodeBase(); /** * Base URI [IETF RFC 2396] for classid, data, and * archive attributes. See the codebase attribute definition * in HTML 4.01. */ public void setCodeBase(String codeBase); /** * Content type for data downloaded via classid attribute. * See the codetype attribute definition in HTML 4.01. */ public String getCodeType(); /** * Content type for data downloaded via classid attribute. * See the codetype attribute definition in HTML 4.01. */ public void setCodeType(String codeType); /** * A URI [IETF RFC 2396] specifying the location of the object's data. See the data * attribute definition in HTML 4.01. */ public String getData(); /** * A URI [IETF RFC 2396] specifying the location of the object's data. See the data * attribute definition in HTML 4.01. */ public void setData(String data); /** * Declare (for future reference), but do not instantiate, this object. * See the declare attribute definition in HTML 4.01. */ public boolean getDeclare(); /** * Declare (for future reference), but do not instantiate, this object. * See the declare attribute definition in HTML 4.01. */ public void setDeclare(boolean declare); /** * Override height. See the height attribute definition in HTML 4.01. */ public String getHeight(); /** * Override height. See the height attribute definition in HTML 4.01. */ public void setHeight(String height); /** * Horizontal space, in pixels, to the left and right of this image, * applet, or object. See the hspace attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public int getHspace(); /** * Horizontal space, in pixels, to the left and right of this image, * applet, or object. See the hspace attribute definition in HTML 4.01. * This attribute is deprecated in HTML 4.01. */ public void setHspace(int hspace); /** * Form control or object name when submitted with a form. See the name * attribute definition in HTML 4.01. */ public String getName(); /** * Form control or object name when submitted with a form. See the name * attribute definition in HTML 4.01. */ public void setName(String name); /** * Message to render while loading the object. See the standby attribute * definition in HTML 4.01. */ public String getStandby(); /** * Message to render while loading the object. See the standby attribute * definition in HTML 4.01. */ public void setStandby(String standby); /** * Index that represents the element's position in the tabbing order. See * the tabindex attribute definition in HTML 4.01. */ public int getTabIndex(); /** * Index that represents the element's position in the tabbing order. See * the tabindex attribute definition in HTML 4.01. */ public void setTabIndex(int tabIndex); /** * Content type for data downloaded via data attribute. See * the type attribute definition in HTML 4.01. */ public String getType(); /** * Content type for data downloaded via data attribute. See * the type attribute definition in HTML 4.01. */ public void setType(String type); /** * Use client-side image map. See the usemap attribute definition in HTML * 4.01. */ public String getUseMap(); /** * Use client-side image map. See the usemap attribute definition in HTML * 4.01. */ public void setUseMap(String useMap); /** * Vertical space, in pixels, above and below this image, applet, or * object. See the vspace attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public int getVspace(); /** * Vertical space, in pixels, above and below this image, applet, or * object. See the vspace attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public void setVspace(int vspace); /** * Override width. See the width attribute definition in HTML 4.01. */ public String getWidth(); /** * Override width. See the width attribute definition in HTML 4.01. */ public void setWidth(String width); /** * The document this object contains, if there is any and it is available, * or null otherwise. * @since DOM Level 2 */ public Document getContentDocument(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLOptGroupElement.java0000644000175000017500000000467510726473500025525 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Group options together in logical subdivisions. See the OPTGROUP element * definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLOptGroupElement extends HTMLElement { /** * The control is unavailable in this context. See the disabled attribute * definition in HTML 4.01. */ public boolean getDisabled(); /** * The control is unavailable in this context. See the disabled attribute * definition in HTML 4.01. */ public void setDisabled(boolean disabled); /** * Assigns a label to this option group. See the label attribute definition * in HTML 4.01. */ public String getLabel(); /** * Assigns a label to this option group. See the label attribute definition * in HTML 4.01. */ public void setLabel(String label); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLOptionElement.java0000644000175000017500000001112510726473506025210 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * A selectable choice. See the OPTION element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLOptionElement extends HTMLElement { /** * Returns the FORM element containing this control. Returns * null if this control is not within the context of a * form. */ public HTMLFormElement getForm(); /** * Represents the value of the HTML selected attribute. The value of this * attribute does not change if the state of the corresponding form * control, in an interactive user agent, changes. See the selected * attribute definition in HTML 4.01. * @version DOM Level 2 */ public boolean getDefaultSelected(); /** * Represents the value of the HTML selected attribute. The value of this * attribute does not change if the state of the corresponding form * control, in an interactive user agent, changes. See the selected * attribute definition in HTML 4.01. * @version DOM Level 2 */ public void setDefaultSelected(boolean defaultSelected); /** * The text contained within the option element. */ public String getText(); /** * The index of this OPTION in its parent SELECT * , starting from 0. * @version DOM Level 2 */ public int getIndex(); /** * The control is unavailable in this context. See the disabled attribute * definition in HTML 4.01. */ public boolean getDisabled(); /** * The control is unavailable in this context. See the disabled attribute * definition in HTML 4.01. */ public void setDisabled(boolean disabled); /** * Option label for use in hierarchical menus. See the label attribute * definition in HTML 4.01. */ public String getLabel(); /** * Option label for use in hierarchical menus. See the label attribute * definition in HTML 4.01. */ public void setLabel(String label); /** * Represents the current state of the corresponding form control, in an * interactive user agent. Changing this attribute changes the state of * the form control, but does not change the value of the HTML selected * attribute of the element. */ public boolean getSelected(); /** * Represents the current state of the corresponding form control, in an * interactive user agent. Changing this attribute changes the state of * the form control, but does not change the value of the HTML selected * attribute of the element. */ public void setSelected(boolean selected); /** * The current form control value. See the value attribute definition in * HTML 4.01. */ public String getValue(); /** * The current form control value. See the value attribute definition in * HTML 4.01. */ public void setValue(String value); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLOptionsCollection.java0000644000175000017500000000746710726473500026105 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; import org.w3c.dom.Node; import org.w3c.dom.DOMException; /** * An HTMLOptionsCollection is a list of nodes representing HTML * option element. An individual node may be accessed by either ordinal * index or the node's name or id attributes. * Collections in the HTML DOM are assumed to be live meaning that they are * automatically updated when the underlying document is changed. *

See also the Document Object Model (DOM) Level 2 HTML Specification. * @since DOM Level 2 */ public interface HTMLOptionsCollection { /** * This attribute specifies the length or size of the list. */ public int getLength(); /** * This attribute specifies the length or size of the list. * @exception DOMException * NOT_SUPPORTED_ERR: if setting the length is not allowed by the * implementation. */ public void setLength(int length) throws DOMException; /** * This method retrieves a node specified by ordinal index. Nodes are * numbered in tree order (depth-first traversal order). * @param index The index of the node to be fetched. The index origin is * 0. * @return The Node at the corresponding position upon * success. A value of null is returned if the index is * out of range. */ public Node item(int index); /** * This method retrieves a Node using a name. It first * searches for a Node with a matching id * attribute. If it doesn't find one, it then searches for a * Node with a matching name attribute, but * only on those elements that are allowed a name attribute. This method * is case insensitive in HTML documents and case sensitive in XHTML * documents. * @param name The name of the Node to be fetched. * @return The Node with a name or * id attribute whose value corresponds to the specified * string. Upon failure (e.g., no node with this name exists), returns * null. */ public Node namedItem(String name); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLParagraphElement.java0000644000175000017500000000416310726473510025644 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Paragraphs. See the P element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLParagraphElement extends HTMLElement { /** * Horizontal text alignment. See the align attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public String getAlign(); /** * Horizontal text alignment. See the align attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public void setAlign(String align); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLParamElement.java0000644000175000017500000000634710726473506025012 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Parameters fed to the OBJECT element. See the PARAM element * definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLParamElement extends HTMLElement { /** * The name of a run-time parameter. See the name attribute definition in * HTML 4.01. */ public String getName(); /** * The name of a run-time parameter. See the name attribute definition in * HTML 4.01. */ public void setName(String name); /** * Content type for the value attribute when * valuetype has the value "ref". See the type attribute * definition in HTML 4.01. */ public String getType(); /** * Content type for the value attribute when * valuetype has the value "ref". See the type attribute * definition in HTML 4.01. */ public void setType(String type); /** * The value of a run-time parameter. See the value attribute definition * in HTML 4.01. */ public String getValue(); /** * The value of a run-time parameter. See the value attribute definition * in HTML 4.01. */ public void setValue(String value); /** * Information about the meaning of the value attribute * value. See the valuetype attribute definition in HTML 4.01. */ public String getValueType(); /** * Information about the meaning of the value attribute * value. See the valuetype attribute definition in HTML 4.01. */ public void setValueType(String valueType); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLPreElement.java0000644000175000017500000000415410726473512024467 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Preformatted text. See the PRE element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLPreElement extends HTMLElement { /** * Fixed width for content. See the width attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public int getWidth(); /** * Fixed width for content. See the width attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public void setWidth(int width); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLQuoteElement.java0000644000175000017500000000437010726473510025034 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * For the Q and BLOCKQUOTE elements. See the Q * element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLQuoteElement extends HTMLElement { /** * A URI [IETF RFC 2396] designating a source document or message. See the cite attribute * definition in HTML 4.01. */ public String getCite(); /** * A URI [IETF RFC 2396] designating a source document or message. See the cite attribute * definition in HTML 4.01. */ public void setCite(String cite); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLScriptElement.java0000644000175000017500000000736010726473500025204 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Script statements. See the SCRIPT element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLScriptElement extends HTMLElement { /** * The script content of the element. */ public String getText(); /** * The script content of the element. */ public void setText(String text); /** * Reserved for future use. */ public String getHtmlFor(); /** * Reserved for future use. */ public void setHtmlFor(String htmlFor); /** * Reserved for future use. */ public String getEvent(); /** * Reserved for future use. */ public void setEvent(String event); /** * The character encoding of the linked resource. See the charset * attribute definition in HTML 4.01. */ public String getCharset(); /** * The character encoding of the linked resource. See the charset * attribute definition in HTML 4.01. */ public void setCharset(String charset); /** * Indicates that the user agent can defer processing of the script. See * the defer attribute definition in HTML 4.01. */ public boolean getDefer(); /** * Indicates that the user agent can defer processing of the script. See * the defer attribute definition in HTML 4.01. */ public void setDefer(boolean defer); /** * URI [IETF RFC 2396] designating an external script. See the src attribute definition * in HTML 4.01. */ public String getSrc(); /** * URI [IETF RFC 2396] designating an external script. See the src attribute definition * in HTML 4.01. */ public void setSrc(String src); /** * The content type of the script language. See the type attribute * definition in HTML 4.01. */ public String getType(); /** * The content type of the script language. See the type attribute * definition in HTML 4.01. */ public void setType(String type); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLSelectElement.java0000644000175000017500000001644110726473504025163 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; import org.w3c.dom.DOMException; /** * The select element allows the selection of an option. The contained options * can be directly accessed through the select element as a collection. See * the SELECT element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLSelectElement extends HTMLElement { /** * The type of this form control. This is the string "select-multiple" * when the multiple attribute is true and the string * "select-one" when false. */ public String getType(); /** * The ordinal index of the selected option, starting from 0. The value -1 * is returned if no element is selected. If multiple options are * selected, the index of the first selected option is returned. */ public int getSelectedIndex(); /** * The ordinal index of the selected option, starting from 0. The value -1 * is returned if no element is selected. If multiple options are * selected, the index of the first selected option is returned. */ public void setSelectedIndex(int selectedIndex); /** * The current form control value (i.e. the value of the currently * selected option), if multiple options are selected this is the value * of the first selected option. */ public String getValue(); /** * The current form control value (i.e. the value of the currently * selected option), if multiple options are selected this is the value * of the first selected option. */ public void setValue(String value); /** * The number of options in this SELECT. * @version DOM Level 2 */ public int getLength(); /** * The number of options in this SELECT. * @exception DOMException * NOT_SUPPORTED_ERR: if setting the length is not allowed by the * implementation. * @version DOM Level 2 */ public void setLength(int length) throws DOMException; /** * Returns the FORM element containing this control. Returns * null if this control is not within the context of a * form. */ public HTMLFormElement getForm(); /** * The collection of OPTION elements contained by this * element. * @version DOM Level 2 */ public HTMLOptionsCollection getOptions(); /** * The control is unavailable in this context. See the disabled attribute * definition in HTML 4.01. */ public boolean getDisabled(); /** * The control is unavailable in this context. See the disabled attribute * definition in HTML 4.01. */ public void setDisabled(boolean disabled); /** * If true, multiple OPTION elements may be selected in this * SELECT. See the multiple attribute definition in HTML * 4.01. */ public boolean getMultiple(); /** * If true, multiple OPTION elements may be selected in this * SELECT. See the multiple attribute definition in HTML * 4.01. */ public void setMultiple(boolean multiple); /** * Form control or object name when submitted with a form. See the name * attribute definition in HTML 4.01. */ public String getName(); /** * Form control or object name when submitted with a form. See the name * attribute definition in HTML 4.01. */ public void setName(String name); /** * Number of visible rows. See the size attribute definition in HTML 4.01. */ public int getSize(); /** * Number of visible rows. See the size attribute definition in HTML 4.01. */ public void setSize(int size); /** * Index that represents the element's position in the tabbing order. See * the tabindex attribute definition in HTML 4.01. */ public int getTabIndex(); /** * Index that represents the element's position in the tabbing order. See * the tabindex attribute definition in HTML 4.01. */ public void setTabIndex(int tabIndex); /** * Add a new element to the collection of OPTION elements for * this SELECT. This method is the equivalent of the * appendChild method of the Node interface if * the before parameter is null. It is * equivalent to the insertBefore method on the parent of * before in all other cases. This method may have no * effect if the new element is not an OPTION or an * OPTGROUP. * @param element The element to add. * @param before The element to insert before, or null for * the tail of the list. * @exception DOMException * NOT_FOUND_ERR: Raised if before is not a descendant of * the SELECT element. */ public void add(HTMLElement element, HTMLElement before) throws DOMException; /** * Remove an element from the collection of OPTION elements * for this SELECT. Does nothing if no element has the * given index. * @param index The index of the item to remove, starting from 0. */ public void remove(int index); /** * Removes keyboard focus from this element. */ public void blur(); /** * Gives keyboard focus to this element. */ public void focus(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLStyleElement.java0000644000175000017500000000563110726473506025045 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Style information. See the STYLE element definition in HTML 4.01, the CSS * module [DOM Level 2 Style Sheets and CSS] and the LinkStyle interface in the StyleSheets * module [DOM Level 2 Style Sheets and CSS]. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLStyleElement extends HTMLElement { /** * Enables/disables the style sheet. */ public boolean getDisabled(); /** * Enables/disables the style sheet. */ public void setDisabled(boolean disabled); /** * Designed for use with one or more target media. See the media attribute * definition in HTML 4.01. */ public String getMedia(); /** * Designed for use with one or more target media. See the media attribute * definition in HTML 4.01. */ public void setMedia(String media); /** * The content type of the style sheet language. See the type attribute * definition in HTML 4.01. */ public String getType(); /** * The content type of the style sheet language. See the type attribute * definition in HTML 4.01. */ public void setType(String type); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLTableCaptionElement.java0000644000175000017500000000424210726473510026302 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Table caption See the CAPTION element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLTableCaptionElement extends HTMLElement { /** * Caption alignment with respect to the table. See the align attribute * definition in HTML 4.01. This attribute is deprecated in HTML 4.01. */ public String getAlign(); /** * Caption alignment with respect to the table. See the align attribute * definition in HTML 4.01. This attribute is deprecated in HTML 4.01. */ public void setAlign(String align); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLTableCellElement.java0000644000175000017500000001502310726473510025563 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * The object used to represent the TH and TD * elements. See the TD element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLTableCellElement extends HTMLElement { /** * The index of this cell in the row, starting from 0. This index is in * document tree order and not display order. */ public int getCellIndex(); /** * Abbreviation for header cells. See the abbr attribute definition in * HTML 4.01. */ public String getAbbr(); /** * Abbreviation for header cells. See the abbr attribute definition in * HTML 4.01. */ public void setAbbr(String abbr); /** * Horizontal alignment of data in cell. See the align attribute definition * in HTML 4.01. */ public String getAlign(); /** * Horizontal alignment of data in cell. See the align attribute definition * in HTML 4.01. */ public void setAlign(String align); /** * Names group of related headers. See the axis attribute definition in * HTML 4.01. */ public String getAxis(); /** * Names group of related headers. See the axis attribute definition in * HTML 4.01. */ public void setAxis(String axis); /** * Cell background color. See the bgcolor attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public String getBgColor(); /** * Cell background color. See the bgcolor attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public void setBgColor(String bgColor); /** * Alignment character for cells in a column. See the char attribute * definition in HTML 4.01. */ public String getCh(); /** * Alignment character for cells in a column. See the char attribute * definition in HTML 4.01. */ public void setCh(String ch); /** * Offset of alignment character. See the charoff attribute definition in * HTML 4.01. */ public String getChOff(); /** * Offset of alignment character. See the charoff attribute definition in * HTML 4.01. */ public void setChOff(String chOff); /** * Number of columns spanned by cell. See the colspan attribute definition * in HTML 4.01. */ public int getColSpan(); /** * Number of columns spanned by cell. See the colspan attribute definition * in HTML 4.01. */ public void setColSpan(int colSpan); /** * List of id attribute values for header cells. See the * headers attribute definition in HTML 4.01. */ public String getHeaders(); /** * List of id attribute values for header cells. See the * headers attribute definition in HTML 4.01. */ public void setHeaders(String headers); /** * Cell height. See the height attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public String getHeight(); /** * Cell height. See the height attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public void setHeight(String height); /** * Suppress word wrapping. See the nowrap attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public boolean getNoWrap(); /** * Suppress word wrapping. See the nowrap attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public void setNoWrap(boolean noWrap); /** * Number of rows spanned by cell. See the rowspan attribute definition in * HTML 4.01. */ public int getRowSpan(); /** * Number of rows spanned by cell. See the rowspan attribute definition in * HTML 4.01. */ public void setRowSpan(int rowSpan); /** * Scope covered by header cells. See the scope attribute definition in * HTML 4.01. */ public String getScope(); /** * Scope covered by header cells. See the scope attribute definition in * HTML 4.01. */ public void setScope(String scope); /** * Vertical alignment of data in cell. See the valign attribute definition * in HTML 4.01. */ public String getVAlign(); /** * Vertical alignment of data in cell. See the valign attribute definition * in HTML 4.01. */ public void setVAlign(String vAlign); /** * Cell width. See the width attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public String getWidth(); /** * Cell width. See the width attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public void setWidth(String width); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLTableColElement.java0000644000175000017500000000727210726473500025427 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Regroups the COL and COLGROUP elements. See the * COL element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLTableColElement extends HTMLElement { /** * Horizontal alignment of cell data in column. See the align attribute * definition in HTML 4.01. */ public String getAlign(); /** * Horizontal alignment of cell data in column. See the align attribute * definition in HTML 4.01. */ public void setAlign(String align); /** * Alignment character for cells in a column. See the char attribute * definition in HTML 4.01. */ public String getCh(); /** * Alignment character for cells in a column. See the char attribute * definition in HTML 4.01. */ public void setCh(String ch); /** * Offset of alignment character. See the charoff attribute definition in * HTML 4.01. */ public String getChOff(); /** * Offset of alignment character. See the charoff attribute definition in * HTML 4.01. */ public void setChOff(String chOff); /** * Indicates the number of columns in a group or affected by a grouping. * See the span attribute definition in HTML 4.01. */ public int getSpan(); /** * Indicates the number of columns in a group or affected by a grouping. * See the span attribute definition in HTML 4.01. */ public void setSpan(int span); /** * Vertical alignment of cell data in column. See the valign attribute * definition in HTML 4.01. */ public String getVAlign(); /** * Vertical alignment of cell data in column. See the valign attribute * definition in HTML 4.01. */ public void setVAlign(String vAlign); /** * Default column width. See the width attribute definition in HTML 4.01. */ public String getWidth(); /** * Default column width. See the width attribute definition in HTML 4.01. */ public void setWidth(String width); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLTableElement.java0000644000175000017500000002406310726473502024770 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; import org.w3c.dom.DOMException; /** * The create* and delete* methods on the table allow authors to construct and * modify tables. [HTML 4.01] specifies that only one of each of the * CAPTION, THEAD, and TFOOT elements * may exist in a table. Therefore, if one exists, and the createTHead() or * createTFoot() method is called, the method returns the existing THead or * TFoot element. See the TABLE element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLTableElement extends HTMLElement { /** * Returns the table's CAPTION, or void if none exists. * @version DOM Level 2 */ public HTMLTableCaptionElement getCaption(); /** * Returns the table's CAPTION, or void if none exists. * @exception DOMException * HIERARCHY_REQUEST_ERR: if the element is not a CAPTION. * @version DOM Level 2 */ public void setCaption(HTMLTableCaptionElement caption) throws DOMException; /** * Returns the table's THEAD, or null if none * exists. * @version DOM Level 2 */ public HTMLTableSectionElement getTHead(); /** * Returns the table's THEAD, or null if none * exists. * @exception DOMException * HIERARCHY_REQUEST_ERR: if the element is not a THEAD. * @version DOM Level 2 */ public void setTHead(HTMLTableSectionElement tHead) throws DOMException; /** * Returns the table's TFOOT, or null if none * exists. * @version DOM Level 2 */ public HTMLTableSectionElement getTFoot(); /** * Returns the table's TFOOT, or null if none * exists. * @exception DOMException * HIERARCHY_REQUEST_ERR: if the element is not a TFOOT. * @version DOM Level 2 */ public void setTFoot(HTMLTableSectionElement tFoot) throws DOMException; /** * Returns a collection of all the rows in the table, including all in * THEAD, TFOOT, all TBODY * elements. */ public HTMLCollection getRows(); /** * Returns a collection of the table bodies (including implicit ones). */ public HTMLCollection getTBodies(); /** * Specifies the table's position with respect to the rest of the * document. See the align attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public String getAlign(); /** * Specifies the table's position with respect to the rest of the * document. See the align attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public void setAlign(String align); /** * Cell background color. See the bgcolor attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public String getBgColor(); /** * Cell background color. See the bgcolor attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public void setBgColor(String bgColor); /** * The width of the border around the table. See the border attribute * definition in HTML 4.01. */ public String getBorder(); /** * The width of the border around the table. See the border attribute * definition in HTML 4.01. */ public void setBorder(String border); /** * Specifies the horizontal and vertical space between cell content and * cell borders. See the cellpadding attribute definition in HTML 4.01. */ public String getCellPadding(); /** * Specifies the horizontal and vertical space between cell content and * cell borders. See the cellpadding attribute definition in HTML 4.01. */ public void setCellPadding(String cellPadding); /** * Specifies the horizontal and vertical separation between cells. See the * cellspacing attribute definition in HTML 4.01. */ public String getCellSpacing(); /** * Specifies the horizontal and vertical separation between cells. See the * cellspacing attribute definition in HTML 4.01. */ public void setCellSpacing(String cellSpacing); /** * Specifies which external table borders to render. See the frame * attribute definition in HTML 4.01. */ public String getFrame(); /** * Specifies which external table borders to render. See the frame * attribute definition in HTML 4.01. */ public void setFrame(String frame); /** * Specifies which internal table borders to render. See the rules * attribute definition in HTML 4.01. */ public String getRules(); /** * Specifies which internal table borders to render. See the rules * attribute definition in HTML 4.01. */ public void setRules(String rules); /** * Description about the purpose or structure of a table. See the summary * attribute definition in HTML 4.01. */ public String getSummary(); /** * Description about the purpose or structure of a table. See the summary * attribute definition in HTML 4.01. */ public void setSummary(String summary); /** * Specifies the desired table width. See the width attribute definition * in HTML 4.01. */ public String getWidth(); /** * Specifies the desired table width. See the width attribute definition * in HTML 4.01. */ public void setWidth(String width); /** * Create a table header row or return an existing one. * @return A new table header element (THEAD). */ public HTMLElement createTHead(); /** * Delete the header from the table, if one exists. */ public void deleteTHead(); /** * Create a table footer row or return an existing one. * @return A footer element (TFOOT). */ public HTMLElement createTFoot(); /** * Delete the footer from the table, if one exists. */ public void deleteTFoot(); /** * Create a new table caption object or return an existing one. * @return A CAPTION element. */ public HTMLElement createCaption(); /** * Delete the table caption, if one exists. */ public void deleteCaption(); /** * Insert a new empty row in the table. The new row is inserted * immediately before and in the same section as the current * indexth row in the table. If index is -1 or * equal to the number of rows, the new row is appended. In addition, * when the table is empty the row is inserted into a TBODY * which is created and inserted into the table.A table row cannot be * empty according to [HTML 4.01]. * @param index The row number where to insert a new row. This index * starts from 0 and is relative to the logical order (not document * order) of all the rows contained inside the table. * @return The newly created row. * @exception DOMException * INDEX_SIZE_ERR: Raised if the specified index is greater than the * number of rows or if the index is a negative number other than -1. * @version DOM Level 2 */ public HTMLElement insertRow(int index) throws DOMException; /** * Delete a table row. * @param index The index of the row to be deleted. This index starts * from 0 and is relative to the logical order (not document order) of * all the rows contained inside the table. If the index is -1 the * last row in the table is deleted. * @exception DOMException * INDEX_SIZE_ERR: Raised if the specified index is greater than or * equal to the number of rows or if the index is a negative number * other than -1. * @version DOM Level 2 */ public void deleteRow(int index) throws DOMException; } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLTableRowElement.java0000644000175000017500000001266510726473510025464 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; import org.w3c.dom.DOMException; /** * A row in a table. See the TR element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLTableRowElement extends HTMLElement { /** * This is in logical order and not in document order. The * rowIndex does take into account sections ( * THEAD, TFOOT, or TBODY) within * the table, placing THEAD rows first in the index, * followed by TBODY rows, followed by TFOOT * rows. * @version DOM Level 2 */ public int getRowIndex(); /** * The index of this row, relative to the current section ( * THEAD, TFOOT, or TBODY), * starting from 0. * @version DOM Level 2 */ public int getSectionRowIndex(); /** * The collection of cells in this row. * @version DOM Level 2 */ public HTMLCollection getCells(); /** * Horizontal alignment of data within cells of this row. See the align * attribute definition in HTML 4.01. */ public String getAlign(); /** * Horizontal alignment of data within cells of this row. See the align * attribute definition in HTML 4.01. */ public void setAlign(String align); /** * Background color for rows. See the bgcolor attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public String getBgColor(); /** * Background color for rows. See the bgcolor attribute definition in HTML * 4.01. This attribute is deprecated in HTML 4.01. */ public void setBgColor(String bgColor); /** * Alignment character for cells in a column. See the char attribute * definition in HTML 4.01. */ public String getCh(); /** * Alignment character for cells in a column. See the char attribute * definition in HTML 4.01. */ public void setCh(String ch); /** * Offset of alignment character. See the charoff attribute definition in * HTML 4.01. */ public String getChOff(); /** * Offset of alignment character. See the charoff attribute definition in * HTML 4.01. */ public void setChOff(String chOff); /** * Vertical alignment of data within cells of this row. See the valign * attribute definition in HTML 4.01. */ public String getVAlign(); /** * Vertical alignment of data within cells of this row. See the valign * attribute definition in HTML 4.01. */ public void setVAlign(String vAlign); /** * Insert an empty TD cell into this row. If * index is -1 or equal to the number of cells, the new * cell is appended. * @param index The place to insert the cell, starting from 0. * @return The newly created cell. * @exception DOMException * INDEX_SIZE_ERR: Raised if the specified index is greater * than the number of cells or if the index is a negative number other * than -1. * @version DOM Level 2 */ public HTMLElement insertCell(int index) throws DOMException; /** * Delete a cell from the current row. * @param index The index of the cell to delete, starting from 0. If the * index is -1 the last cell in the row is deleted. * @exception DOMException * INDEX_SIZE_ERR: Raised if the specified index is greater * than or equal to the number of cells or if the index is a negative * number other than -1. * @version DOM Level 2 */ public void deleteCell(int index) throws DOMException; } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLTableSectionElement.java0000644000175000017500000001125010726473500026305 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; import org.w3c.dom.DOMException; /** * The THEAD, TFOOT, and TBODY * elements. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLTableSectionElement extends HTMLElement { /** * Horizontal alignment of data in cells. See the align * attribute for HTMLTheadElement for details. */ public String getAlign(); /** * Horizontal alignment of data in cells. See the align * attribute for HTMLTheadElement for details. */ public void setAlign(String align); /** * Alignment character for cells in a column. See the char attribute * definition in HTML 4.01. */ public String getCh(); /** * Alignment character for cells in a column. See the char attribute * definition in HTML 4.01. */ public void setCh(String ch); /** * Offset of alignment character. See the charoff attribute definition in * HTML 4.01. */ public String getChOff(); /** * Offset of alignment character. See the charoff attribute definition in * HTML 4.01. */ public void setChOff(String chOff); /** * Vertical alignment of data in cells. See the valign * attribute for HTMLTheadElement for details. */ public String getVAlign(); /** * Vertical alignment of data in cells. See the valign * attribute for HTMLTheadElement for details. */ public void setVAlign(String vAlign); /** * The collection of rows in this table section. */ public HTMLCollection getRows(); /** * Insert a row into this section. The new row is inserted immediately * before the current indexth row in this section. If * index is -1 or equal to the number of rows in this * section, the new row is appended. * @param index The row number where to insert a new row. This index * starts from 0 and is relative only to the rows contained inside * this section, not all the rows in the table. * @return The newly created row. * @exception DOMException * INDEX_SIZE_ERR: Raised if the specified index is greater than the * number of rows of if the index is a negative number other than -1. * @version DOM Level 2 */ public HTMLElement insertRow(int index) throws DOMException; /** * Delete a row from this section. * @param index The index of the row to be deleted, or -1 to delete the * last row. This index starts from 0 and is relative only to the rows * contained inside this section, not all the rows in the table. * @exception DOMException * INDEX_SIZE_ERR: Raised if the specified index is greater than or * equal to the number of rows or if the index is a negative number * other than -1. * @version DOM Level 2 */ public void deleteRow(int index) throws DOMException; } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLTextAreaElement.java0000644000175000017500000001412410726473500025451 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Multi-line text field. See the TEXTAREA element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLTextAreaElement extends HTMLElement { /** * Represents the contents of the element. The value of this attribute * does not change if the contents of the corresponding form control, in * an interactive user agent, changes. * @version DOM Level 2 */ public String getDefaultValue(); /** * Represents the contents of the element. The value of this attribute * does not change if the contents of the corresponding form control, in * an interactive user agent, changes. * @version DOM Level 2 */ public void setDefaultValue(String defaultValue); /** * Returns the FORM element containing this control. Returns * null if this control is not within the context of a * form. */ public HTMLFormElement getForm(); /** * A single character access key to give access to the form control. See * the accesskey attribute definition in HTML 4.01. */ public String getAccessKey(); /** * A single character access key to give access to the form control. See * the accesskey attribute definition in HTML 4.01. */ public void setAccessKey(String accessKey); /** * Width of control (in characters). See the cols attribute definition in * HTML 4.01. */ public int getCols(); /** * Width of control (in characters). See the cols attribute definition in * HTML 4.01. */ public void setCols(int cols); /** * The control is unavailable in this context. See the disabled attribute * definition in HTML 4.01. */ public boolean getDisabled(); /** * The control is unavailable in this context. See the disabled attribute * definition in HTML 4.01. */ public void setDisabled(boolean disabled); /** * Form control or object name when submitted with a form. See the name * attribute definition in HTML 4.01. */ public String getName(); /** * Form control or object name when submitted with a form. See the name * attribute definition in HTML 4.01. */ public void setName(String name); /** * This control is read-only. See the readonly attribute definition in * HTML 4.01. */ public boolean getReadOnly(); /** * This control is read-only. See the readonly attribute definition in * HTML 4.01. */ public void setReadOnly(boolean readOnly); /** * Number of text rows. See the rows attribute definition in HTML 4.01. */ public int getRows(); /** * Number of text rows. See the rows attribute definition in HTML 4.01. */ public void setRows(int rows); /** * Index that represents the element's position in the tabbing order. See * the tabindex attribute definition in HTML 4.01. */ public int getTabIndex(); /** * Index that represents the element's position in the tabbing order. See * the tabindex attribute definition in HTML 4.01. */ public void setTabIndex(int tabIndex); /** * The type of this form control. This the string "textarea". */ public String getType(); /** * Represents the current contents of the corresponding form control, in * an interactive user agent. Changing this attribute changes the * contents of the form control, but does not change the contents of the * element. If the entirety of the data can not fit into a single * DOMString, the implementation may truncate the data. */ public String getValue(); /** * Represents the current contents of the corresponding form control, in * an interactive user agent. Changing this attribute changes the * contents of the form control, but does not change the contents of the * element. If the entirety of the data can not fit into a single * DOMString, the implementation may truncate the data. */ public void setValue(String value); /** * Removes keyboard focus from this element. */ public void blur(); /** * Gives keyboard focus to this element. */ public void focus(); /** * Select the contents of the TEXTAREA. */ public void select(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLTitleElement.java0000644000175000017500000000367410726473506025033 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * The document title. See the TITLE element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLTitleElement extends HTMLElement { /** * The specified title as a string. */ public String getText(); /** * The specified title as a string. */ public void setText(String text); } libcobra-java-0.98.4.orig/src/org/w3c/dom/html2/HTMLUListElement.java0000644000175000017500000000475710726473506025015 0ustar twernertwerner/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Copyright (c) 2003 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.html2; /** * Unordered list. See the UL element definition in HTML 4.01. *

See also the Document Object Model (DOM) Level 2 HTML Specification. */ public interface HTMLUListElement extends HTMLElement { /** * Reduce spacing between list items. See the compact attribute definition * in HTML 4.01. This attribute is deprecated in HTML 4.01. */ public boolean getCompact(); /** * Reduce spacing between list items. See the compact attribute definition * in HTML 4.01. This attribute is deprecated in HTML 4.01. */ public void setCompact(boolean compact); /** * Bullet style. See the type attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public String getType(); /** * Bullet style. See the type attribute definition in HTML 4.01. This * attribute is deprecated in HTML 4.01. */ public void setType(String type); } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/0000755000175000017500000000000010630473006020625 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/w3c/dom/css/CSS2Properties.java0000644000175000017500000016063510445070346024276 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; import org.w3c.dom.DOMException; /** * The CSS2Properties interface represents a convenience * mechanism for retrieving and setting properties within a * CSSStyleDeclaration. The attributes of this interface * correspond to all the properties specified in CSS2. Getting an attribute * of this interface is equivalent to calling the * getPropertyValue method of the * CSSStyleDeclaration interface. Setting an attribute of this * interface is equivalent to calling the setProperty method of * the CSSStyleDeclaration interface. *

A conformant implementation of the CSS module is not required to * implement the CSS2Properties interface. If an implementation * does implement this interface, the expectation is that language-specific * methods can be used to cast from an instance of the * CSSStyleDeclaration interface to the * CSS2Properties interface. *

If an implementation does implement this interface, it is expected to * understand the specific syntax of the shorthand properties, and apply * their semantics; when the margin property is set, for * example, the marginTop, marginRight, * marginBottom and marginLeft properties are * actually being set by the underlying implementation. *

When dealing with CSS "shorthand" properties, the shorthand properties * should be decomposed into their component longhand properties as * appropriate, and when querying for their value, the form returned should * be the shortest form exactly equivalent to the declarations made in the * ruleset. However, if there is no shorthand declaration that could be * added to the ruleset without changing in any way the rules already * declared in the ruleset (i.e., by adding longhand rules that were * previously not declared in the ruleset), then the empty string should be * returned for the shorthand property. *

For example, querying for the font property should not * return "normal normal normal 14pt/normal Arial, sans-serif", when "14pt * Arial, sans-serif" suffices. (The normals are initial values, and are * implied by use of the longhand property.) *

If the values for all the longhand properties that compose a particular * string are the initial values, then a string consisting of all the * initial values should be returned (e.g. a border-width value * of "medium" should be returned as such, not as ""). *

For some shorthand properties that take missing values from other * sides, such as the margin, padding, and * border-[width|style|color] properties, the minimum number of * sides possible should be used; i.e., "0px 10px" will be returned instead * of "0px 10px 0px 10px". *

If the value of a shorthand property can not be decomposed into its * component longhand properties, as is the case for the font * property with a value of "menu", querying for the values of the component * longhand properties should return the empty string. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface CSS2Properties { /** * See the azimuth property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getAzimuth(); public void setAzimuth(String azimuth) throws DOMException; /** * See the background property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBackground(); public void setBackground(String background) throws DOMException; /** * See the background-attachment property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBackgroundAttachment(); public void setBackgroundAttachment(String backgroundAttachment) throws DOMException; /** * See the background-color property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBackgroundColor(); public void setBackgroundColor(String backgroundColor) throws DOMException; /** * See the background-image property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBackgroundImage(); public void setBackgroundImage(String backgroundImage) throws DOMException; /** * See the background-position property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBackgroundPosition(); public void setBackgroundPosition(String backgroundPosition) throws DOMException; /** * See the background-repeat property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBackgroundRepeat(); public void setBackgroundRepeat(String backgroundRepeat) throws DOMException; /** * See the border property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorder(); public void setBorder(String border) throws DOMException; /** * See the border-collapse property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorderCollapse(); public void setBorderCollapse(String borderCollapse) throws DOMException; /** * See the border-color property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorderColor(); public void setBorderColor(String borderColor) throws DOMException; /** * See the border-spacing property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorderSpacing(); public void setBorderSpacing(String borderSpacing) throws DOMException; /** * See the border-style property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorderStyle(); public void setBorderStyle(String borderStyle) throws DOMException; /** * See the border-top property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorderTop(); public void setBorderTop(String borderTop) throws DOMException; /** * See the border-right property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorderRight(); public void setBorderRight(String borderRight) throws DOMException; /** * See the border-bottom property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorderBottom(); public void setBorderBottom(String borderBottom) throws DOMException; /** * See the border-left property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorderLeft(); public void setBorderLeft(String borderLeft) throws DOMException; /** * See the border-top-color property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorderTopColor(); public void setBorderTopColor(String borderTopColor) throws DOMException; /** * See the border-right-color property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorderRightColor(); public void setBorderRightColor(String borderRightColor) throws DOMException; /** * See the border-bottom-color property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorderBottomColor(); public void setBorderBottomColor(String borderBottomColor) throws DOMException; /** * See the border-left-color property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorderLeftColor(); public void setBorderLeftColor(String borderLeftColor) throws DOMException; /** * See the border-top-style property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorderTopStyle(); public void setBorderTopStyle(String borderTopStyle) throws DOMException; /** * See the border-right-style property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorderRightStyle(); public void setBorderRightStyle(String borderRightStyle) throws DOMException; /** * See the border-bottom-style property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorderBottomStyle(); public void setBorderBottomStyle(String borderBottomStyle) throws DOMException; /** * See the border-left-style property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorderLeftStyle(); public void setBorderLeftStyle(String borderLeftStyle) throws DOMException; /** * See the border-top-width property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorderTopWidth(); public void setBorderTopWidth(String borderTopWidth) throws DOMException; /** * See the border-right-width property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorderRightWidth(); public void setBorderRightWidth(String borderRightWidth) throws DOMException; /** * See the border-bottom-width property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorderBottomWidth(); public void setBorderBottomWidth(String borderBottomWidth) throws DOMException; /** * See the border-left-width property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorderLeftWidth(); public void setBorderLeftWidth(String borderLeftWidth) throws DOMException; /** * See the border-width property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBorderWidth(); public void setBorderWidth(String borderWidth) throws DOMException; /** * See the bottom property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getBottom(); public void setBottom(String bottom) throws DOMException; /** * See the caption-side property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getCaptionSide(); public void setCaptionSide(String captionSide) throws DOMException; /** * See the clear property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getClear(); public void setClear(String clear) throws DOMException; /** * See the clip property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getClip(); public void setClip(String clip) throws DOMException; /** * See the color property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getColor(); public void setColor(String color) throws DOMException; /** * See the content property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getContent(); public void setContent(String content) throws DOMException; /** * See the counter-increment property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getCounterIncrement(); public void setCounterIncrement(String counterIncrement) throws DOMException; /** * See the counter-reset property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getCounterReset(); public void setCounterReset(String counterReset) throws DOMException; /** * See the cue property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getCue(); public void setCue(String cue) throws DOMException; /** * See the cue-after property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getCueAfter(); public void setCueAfter(String cueAfter) throws DOMException; /** * See the cue-before property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getCueBefore(); public void setCueBefore(String cueBefore) throws DOMException; /** * See the cursor property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getCursor(); public void setCursor(String cursor) throws DOMException; /** * See the direction property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getDirection(); public void setDirection(String direction) throws DOMException; /** * See the display property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getDisplay(); public void setDisplay(String display) throws DOMException; /** * See the elevation property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getElevation(); public void setElevation(String elevation) throws DOMException; /** * See the empty-cells property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getEmptyCells(); public void setEmptyCells(String emptyCells) throws DOMException; /** * See the float property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getCssFloat(); public void setCssFloat(String cssFloat) throws DOMException; /** * See the font property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getFont(); public void setFont(String font) throws DOMException; /** * See the font-family property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getFontFamily(); public void setFontFamily(String fontFamily) throws DOMException; /** * See the font-size property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getFontSize(); public void setFontSize(String fontSize) throws DOMException; /** * See the font-size-adjust property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getFontSizeAdjust(); public void setFontSizeAdjust(String fontSizeAdjust) throws DOMException; /** * See the font-stretch property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getFontStretch(); public void setFontStretch(String fontStretch) throws DOMException; /** * See the font-style property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getFontStyle(); public void setFontStyle(String fontStyle) throws DOMException; /** * See the font-variant property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getFontVariant(); public void setFontVariant(String fontVariant) throws DOMException; /** * See the font-weight property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getFontWeight(); public void setFontWeight(String fontWeight) throws DOMException; /** * See the height property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getHeight(); public void setHeight(String height) throws DOMException; /** * See the left property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getLeft(); public void setLeft(String left) throws DOMException; /** * See the letter-spacing property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getLetterSpacing(); public void setLetterSpacing(String letterSpacing) throws DOMException; /** * See the line-height property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getLineHeight(); public void setLineHeight(String lineHeight) throws DOMException; /** * See the list-style property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getListStyle(); public void setListStyle(String listStyle) throws DOMException; /** * See the list-style-image property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getListStyleImage(); public void setListStyleImage(String listStyleImage) throws DOMException; /** * See the list-style-position property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getListStylePosition(); public void setListStylePosition(String listStylePosition) throws DOMException; /** * See the list-style-type property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getListStyleType(); public void setListStyleType(String listStyleType) throws DOMException; /** * See the margin property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getMargin(); public void setMargin(String margin) throws DOMException; /** * See the margin-top property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getMarginTop(); public void setMarginTop(String marginTop) throws DOMException; /** * See the margin-right property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getMarginRight(); public void setMarginRight(String marginRight) throws DOMException; /** * See the margin-bottom property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getMarginBottom(); public void setMarginBottom(String marginBottom) throws DOMException; /** * See the margin-left property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getMarginLeft(); public void setMarginLeft(String marginLeft) throws DOMException; /** * See the marker-offset property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getMarkerOffset(); public void setMarkerOffset(String markerOffset) throws DOMException; /** * See the marks property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getMarks(); public void setMarks(String marks) throws DOMException; /** * See the max-height property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getMaxHeight(); public void setMaxHeight(String maxHeight) throws DOMException; /** * See the max-width property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getMaxWidth(); public void setMaxWidth(String maxWidth) throws DOMException; /** * See the min-height property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getMinHeight(); public void setMinHeight(String minHeight) throws DOMException; /** * See the min-width property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getMinWidth(); public void setMinWidth(String minWidth) throws DOMException; /** * See the orphans property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getOrphans(); public void setOrphans(String orphans) throws DOMException; /** * See the outline property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getOutline(); public void setOutline(String outline) throws DOMException; /** * See the outline-color property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getOutlineColor(); public void setOutlineColor(String outlineColor) throws DOMException; /** * See the outline-style property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getOutlineStyle(); public void setOutlineStyle(String outlineStyle) throws DOMException; /** * See the outline-width property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getOutlineWidth(); public void setOutlineWidth(String outlineWidth) throws DOMException; /** * See the overflow property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getOverflow(); public void setOverflow(String overflow) throws DOMException; /** * See the padding property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getPadding(); public void setPadding(String padding) throws DOMException; /** * See the padding-top property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getPaddingTop(); public void setPaddingTop(String paddingTop) throws DOMException; /** * See the padding-right property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getPaddingRight(); public void setPaddingRight(String paddingRight) throws DOMException; /** * See the padding-bottom property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getPaddingBottom(); public void setPaddingBottom(String paddingBottom) throws DOMException; /** * See the padding-left property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getPaddingLeft(); public void setPaddingLeft(String paddingLeft) throws DOMException; /** * See the page property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getPage(); public void setPage(String page) throws DOMException; /** * See the page-break-after property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getPageBreakAfter(); public void setPageBreakAfter(String pageBreakAfter) throws DOMException; /** * See the page-break-before property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getPageBreakBefore(); public void setPageBreakBefore(String pageBreakBefore) throws DOMException; /** * See the page-break-inside property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getPageBreakInside(); public void setPageBreakInside(String pageBreakInside) throws DOMException; /** * See the pause property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getPause(); public void setPause(String pause) throws DOMException; /** * See the pause-after property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getPauseAfter(); public void setPauseAfter(String pauseAfter) throws DOMException; /** * See the pause-before property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getPauseBefore(); public void setPauseBefore(String pauseBefore) throws DOMException; /** * See the pitch property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getPitch(); public void setPitch(String pitch) throws DOMException; /** * See the pitch-range property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getPitchRange(); public void setPitchRange(String pitchRange) throws DOMException; /** * See the play-during property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getPlayDuring(); public void setPlayDuring(String playDuring) throws DOMException; /** * See the position property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getPosition(); public void setPosition(String position) throws DOMException; /** * See the quotes property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getQuotes(); public void setQuotes(String quotes) throws DOMException; /** * See the richness property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getRichness(); public void setRichness(String richness) throws DOMException; /** * See the right property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getRight(); public void setRight(String right) throws DOMException; /** * See the size property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getSize(); public void setSize(String size) throws DOMException; /** * See the speak property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getSpeak(); public void setSpeak(String speak) throws DOMException; /** * See the speak-header property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getSpeakHeader(); public void setSpeakHeader(String speakHeader) throws DOMException; /** * See the speak-numeral property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getSpeakNumeral(); public void setSpeakNumeral(String speakNumeral) throws DOMException; /** * See the speak-punctuation property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getSpeakPunctuation(); public void setSpeakPunctuation(String speakPunctuation) throws DOMException; /** * See the speech-rate property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getSpeechRate(); public void setSpeechRate(String speechRate) throws DOMException; /** * See the stress property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getStress(); public void setStress(String stress) throws DOMException; /** * See the table-layout property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getTableLayout(); public void setTableLayout(String tableLayout) throws DOMException; /** * See the text-align property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getTextAlign(); public void setTextAlign(String textAlign) throws DOMException; /** * See the text-decoration property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getTextDecoration(); public void setTextDecoration(String textDecoration) throws DOMException; /** * See the text-indent property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getTextIndent(); public void setTextIndent(String textIndent) throws DOMException; /** * See the text-shadow property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getTextShadow(); public void setTextShadow(String textShadow) throws DOMException; /** * See the text-transform property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getTextTransform(); public void setTextTransform(String textTransform) throws DOMException; /** * See the top property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getTop(); public void setTop(String top) throws DOMException; /** * See the unicode-bidi property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getUnicodeBidi(); public void setUnicodeBidi(String unicodeBidi) throws DOMException; /** * See the vertical-align property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getVerticalAlign(); public void setVerticalAlign(String verticalAlign) throws DOMException; /** * See the visibility property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getVisibility(); public void setVisibility(String visibility) throws DOMException; /** * See the voice-family property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getVoiceFamily(); public void setVoiceFamily(String voiceFamily) throws DOMException; /** * See the volume property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getVolume(); public void setVolume(String volume) throws DOMException; /** * See the white-space property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getWhiteSpace(); public void setWhiteSpace(String whiteSpace) throws DOMException; /** * See the widows property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getWidows(); public void setWidows(String widows) throws DOMException; /** * See the width property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getWidth(); public void setWidth(String width) throws DOMException; /** * See the word-spacing property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getWordSpacing(); public void setWordSpacing(String wordSpacing) throws DOMException; /** * See the z-index property definition in CSS2. * @exception DOMException * SYNTAX_ERR: Raised if the new value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public String getZIndex(); public void setZIndex(String zIndex) throws DOMException; } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/CSSCharsetRule.java0000644000175000017500000000443710445070346024276 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; import org.w3c.dom.DOMException; /** * The CSSCharsetRule interface represents a @charset rule in a * CSS style sheet. The value of the encoding attribute does * not affect the encoding of text data in the DOM objects; this encoding is * always UTF-16. After a stylesheet is loaded, the value of the * encoding attribute is the value found in the * @charset rule. If there was no @charset in the * original document, then no CSSCharsetRule is created. The * value of the encoding attribute may also be used as a hint * for the encoding used on serialization of the style sheet. *

The value of the @charset rule (and therefore of the * CSSCharsetRule) may not correspond to the encoding the * document actually came in; character encoding information e.g. in an HTTP * header, has priority (see CSS document representation) but this is not * reflected in the CSSCharsetRule. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface CSSCharsetRule extends CSSRule { /** * The encoding information used in this @charset rule. * @exception DOMException * SYNTAX_ERR: Raised if the specified encoding value has a syntax error * and is unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this encoding rule is * readonly. */ public String getEncoding(); public void setEncoding(String encoding) throws DOMException; } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/CSSFontFaceRule.java0000644000175000017500000000215510445070346024365 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; /** * The CSSFontFaceRule interface represents a @font-face rule in * a CSS style sheet. The @font-face rule is used to hold a set * of font descriptions. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface CSSFontFaceRule extends CSSRule { /** * The declaration-block of this rule. */ public CSSStyleDeclaration getStyle(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/CSSImportRule.java0000644000175000017500000000334410445070346024153 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; import org.w3c.dom.stylesheets.MediaList; /** * The CSSImportRule interface represents a @import rule within * a CSS style sheet. The @import rule is used to import style * rules from other style sheets. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface CSSImportRule extends CSSRule { /** * The location of the style sheet to be imported. The attribute will not * contain the "url(...)" specifier around the URI. */ public String getHref(); /** * A list of media types for which this style sheet may be used. */ public MediaList getMedia(); /** * The style sheet referred to by this rule, if it has been loaded. The * value of this attribute is null if the style sheet has * not yet been loaded or if it will not be loaded (e.g. if the style * sheet is for a media type not supported by the user agent). */ public CSSStyleSheet getStyleSheet(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/CSSMediaRule.java0000644000175000017500000000625410445070346023723 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; import org.w3c.dom.DOMException; import org.w3c.dom.stylesheets.MediaList; /** * The CSSMediaRule interface represents a @media rule in a CSS * style sheet. A @media rule can be used to delimit style * rules for specific media types. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface CSSMediaRule extends CSSRule { /** * A list of media types for this rule. */ public MediaList getMedia(); /** * A list of all CSS rules contained within the media block. */ public CSSRuleList getCssRules(); /** * Used to insert a new rule into the media block. * @param rule The parsable text representing the rule. For rule sets * this contains both the selector and the style declaration. For * at-rules, this specifies both the at-identifier and the rule * content. * @param index The index within the media block's rule collection of the * rule before which to insert the specified rule. If the specified * index is equal to the length of the media blocks's rule collection, * the rule will be added to the end of the media block. * @return The index within the media block's rule collection of the * newly inserted rule. * @exception DOMException * HIERARCHY_REQUEST_ERR: Raised if the rule cannot be inserted at the * specified index, e.g., if an @import rule is inserted * after a standard rule set or other at-rule. *
INDEX_SIZE_ERR: Raised if the specified index is not a valid * insertion point. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this media rule is * readonly. *
SYNTAX_ERR: Raised if the specified rule has a syntax error and * is unparsable. */ public int insertRule(String rule, int index) throws DOMException; /** * Used to delete a rule from the media block. * @param index The index within the media block's rule collection of the * rule to remove. * @exception DOMException * INDEX_SIZE_ERR: Raised if the specified index does not correspond to * a rule in the media rule list. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this media rule is * readonly. */ public void deleteRule(int index) throws DOMException; } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/CSSPageRule.java0000644000175000017500000000320210445070346023546 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; import org.w3c.dom.DOMException; /** * The CSSPageRule interface represents a @page rule within a * CSS style sheet. The @page rule is used to specify the * dimensions, orientation, margins, etc. of a page box for paged media. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface CSSPageRule extends CSSRule { /** * The parsable textual representation of the page selector for the rule. * @exception DOMException * SYNTAX_ERR: Raised if the specified CSS string value has a syntax * error and is unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this rule is readonly. */ public String getSelectorText(); public void setSelectorText(String selectorText) throws DOMException; /** * The declaration-block of this rule. */ public CSSStyleDeclaration getStyle(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/CSSPrimitiveValue.java0000644000175000017500000003233410445070346025017 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; import org.w3c.dom.DOMException; /** * The CSSPrimitiveValue interface represents a single CSS value * . This interface may be used to determine the value of a specific style * property currently set in a block or to set a specific style property * explicitly within the block. An instance of this interface might be * obtained from the getPropertyCSSValue method of the * CSSStyleDeclaration interface. A * CSSPrimitiveValue object only occurs in a context of a CSS * property. *

Conversions are allowed between absolute values (from millimeters to * centimeters, from degrees to radians, and so on) but not between relative * values. (For example, a pixel value cannot be converted to a centimeter * value.) Percentage values can't be converted since they are relative to * the parent value (or another property value). There is one exception for * color percentage values: since a color percentage value is relative to * the range 0-255, a color percentage value can be converted to a number; * (see also the RGBColor interface). *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface CSSPrimitiveValue extends CSSValue { // UnitTypes /** * The value is not a recognized CSS2 value. The value can only be * obtained by using the cssText attribute. */ public static final short CSS_UNKNOWN = 0; /** * The value is a simple number. The value can be obtained by using the * getFloatValue method. */ public static final short CSS_NUMBER = 1; /** * The value is a percentage. The value can be obtained by using the * getFloatValue method. */ public static final short CSS_PERCENTAGE = 2; /** * The value is a length (ems). The value can be obtained by using the * getFloatValue method. */ public static final short CSS_EMS = 3; /** * The value is a length (exs). The value can be obtained by using the * getFloatValue method. */ public static final short CSS_EXS = 4; /** * The value is a length (px). The value can be obtained by using the * getFloatValue method. */ public static final short CSS_PX = 5; /** * The value is a length (cm). The value can be obtained by using the * getFloatValue method. */ public static final short CSS_CM = 6; /** * The value is a length (mm). The value can be obtained by using the * getFloatValue method. */ public static final short CSS_MM = 7; /** * The value is a length (in). The value can be obtained by using the * getFloatValue method. */ public static final short CSS_IN = 8; /** * The value is a length (pt). The value can be obtained by using the * getFloatValue method. */ public static final short CSS_PT = 9; /** * The value is a length (pc). The value can be obtained by using the * getFloatValue method. */ public static final short CSS_PC = 10; /** * The value is an angle (deg). The value can be obtained by using the * getFloatValue method. */ public static final short CSS_DEG = 11; /** * The value is an angle (rad). The value can be obtained by using the * getFloatValue method. */ public static final short CSS_RAD = 12; /** * The value is an angle (grad). The value can be obtained by using the * getFloatValue method. */ public static final short CSS_GRAD = 13; /** * The value is a time (ms). The value can be obtained by using the * getFloatValue method. */ public static final short CSS_MS = 14; /** * The value is a time (s). The value can be obtained by using the * getFloatValue method. */ public static final short CSS_S = 15; /** * The value is a frequency (Hz). The value can be obtained by using the * getFloatValue method. */ public static final short CSS_HZ = 16; /** * The value is a frequency (kHz). The value can be obtained by using the * getFloatValue method. */ public static final short CSS_KHZ = 17; /** * The value is a number with an unknown dimension. The value can be * obtained by using the getFloatValue method. */ public static final short CSS_DIMENSION = 18; /** * The value is a STRING. The value can be obtained by using the * getStringValue method. */ public static final short CSS_STRING = 19; /** * The value is a URI. The value can be obtained by using the * getStringValue method. */ public static final short CSS_URI = 20; /** * The value is an identifier. The value can be obtained by using the * getStringValue method. */ public static final short CSS_IDENT = 21; /** * The value is a attribute function. The value can be obtained by using * the getStringValue method. */ public static final short CSS_ATTR = 22; /** * The value is a counter or counters function. The value can be obtained * by using the getCounterValue method. */ public static final short CSS_COUNTER = 23; /** * The value is a rect function. The value can be obtained by using the * getRectValue method. */ public static final short CSS_RECT = 24; /** * The value is a RGB color. The value can be obtained by using the * getRGBColorValue method. */ public static final short CSS_RGBCOLOR = 25; /** * The type of the value as defined by the constants specified above. */ public short getPrimitiveType(); /** * A method to set the float value with a specified unit. If the property * attached with this value can not accept the specified unit or the * float value, the value will be unchanged and a * DOMException will be raised. * @param unitType A unit code as defined above. The unit code can only * be a float unit type (i.e. CSS_NUMBER, * CSS_PERCENTAGE, CSS_EMS, * CSS_EXS, CSS_PX, CSS_CM, * CSS_MM, CSS_IN, CSS_PT, * CSS_PC, CSS_DEG, CSS_RAD, * CSS_GRAD, CSS_MS, CSS_S, * CSS_HZ, CSS_KHZ, * CSS_DIMENSION). * @param floatValue The new float value. * @exception DOMException * INVALID_ACCESS_ERR: Raised if the attached property doesn't support * the float value or the unit type. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public void setFloatValue(short unitType, float floatValue) throws DOMException; /** * This method is used to get a float value in a specified unit. If this * CSS value doesn't contain a float value or can't be converted into * the specified unit, a DOMException is raised. * @param unitType A unit code to get the float value. The unit code can * only be a float unit type (i.e. CSS_NUMBER, * CSS_PERCENTAGE, CSS_EMS, * CSS_EXS, CSS_PX, CSS_CM, * CSS_MM, CSS_IN, CSS_PT, * CSS_PC, CSS_DEG, CSS_RAD, * CSS_GRAD, CSS_MS, CSS_S, * CSS_HZ, CSS_KHZ, * CSS_DIMENSION). * @return The float value in the specified unit. * @exception DOMException * INVALID_ACCESS_ERR: Raised if the CSS value doesn't contain a float * value or if the float value can't be converted into the specified * unit. */ public float getFloatValue(short unitType) throws DOMException; /** * A method to set the string value with the specified unit. If the * property attached to this value can't accept the specified unit or * the string value, the value will be unchanged and a * DOMException will be raised. * @param stringType A string code as defined above. The string code can * only be a string unit type (i.e. CSS_STRING, * CSS_URI, CSS_IDENT, and * CSS_ATTR). * @param stringValue The new string value. * @exception DOMException * INVALID_ACCESS_ERR: Raised if the CSS value doesn't contain a string * value or if the string value can't be converted into the specified * unit. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly. */ public void setStringValue(short stringType, String stringValue) throws DOMException; /** * This method is used to get the string value. If the CSS value doesn't * contain a string value, a DOMException is raised. Some * properties (like 'font-family' or 'voice-family') convert a * whitespace separated list of idents to a string. * @return The string value in the current unit. The current * primitiveType can only be a string unit type (i.e. * CSS_STRING, CSS_URI, * CSS_IDENT and CSS_ATTR). * @exception DOMException * INVALID_ACCESS_ERR: Raised if the CSS value doesn't contain a string * value. */ public String getStringValue() throws DOMException; /** * This method is used to get the Counter value. If this CSS value * doesn't contain a counter value, a DOMException is * raised. Modification to the corresponding style property can be * achieved using the Counter interface. * @return The Counter value. * @exception DOMException * INVALID_ACCESS_ERR: Raised if the CSS value doesn't contain a * Counter value (e.g. this is not CSS_COUNTER). */ public Counter getCounterValue() throws DOMException; /** * This method is used to get the Rect value. If this CSS value doesn't * contain a rect value, a DOMException is raised. * Modification to the corresponding style property can be achieved * using the Rect interface. * @return The Rect value. * @exception DOMException * INVALID_ACCESS_ERR: Raised if the CSS value doesn't contain a Rect * value. (e.g. this is not CSS_RECT). */ public Rect getRectValue() throws DOMException; /** * This method is used to get the RGB color. If this CSS value doesn't * contain a RGB color value, a DOMException is raised. * Modification to the corresponding style property can be achieved * using the RGBColor interface. * @return the RGB color value. * @exception DOMException * INVALID_ACCESS_ERR: Raised if the attached property can't return a * RGB color value (e.g. this is not CSS_RGBCOLOR). */ public RGBColor getRGBColorValue() throws DOMException; } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/CSSRule.java0000644000175000017500000000712610445070346022762 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; import org.w3c.dom.DOMException; /** * The CSSRule interface is the abstract base interface for any * type of CSS statement. This includes both rule sets and at-rules. An * implementation is expected to preserve all rules specified in a CSS style * sheet, even if the rule is not recognized by the parser. Unrecognized * rules are represented using the CSSUnknownRule interface. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface CSSRule { // RuleType /** * The rule is a CSSUnknownRule. */ public static final short UNKNOWN_RULE = 0; /** * The rule is a CSSStyleRule. */ public static final short STYLE_RULE = 1; /** * The rule is a CSSCharsetRule. */ public static final short CHARSET_RULE = 2; /** * The rule is a CSSImportRule. */ public static final short IMPORT_RULE = 3; /** * The rule is a CSSMediaRule. */ public static final short MEDIA_RULE = 4; /** * The rule is a CSSFontFaceRule. */ public static final short FONT_FACE_RULE = 5; /** * The rule is a CSSPageRule. */ public static final short PAGE_RULE = 6; /** * The type of the rule, as defined above. The expectation is that * binding-specific casting methods can be used to cast down from an * instance of the CSSRule interface to the specific * derived interface implied by the type. */ public short getType(); /** * The parsable textual representation of the rule. This reflects the * current state of the rule and not its initial value. * @exception DOMException * SYNTAX_ERR: Raised if the specified CSS string value has a syntax * error and is unparsable. *
INVALID_MODIFICATION_ERR: Raised if the specified CSS string * value represents a different type of rule than the current one. *
HIERARCHY_REQUEST_ERR: Raised if the rule cannot be inserted at * this point in the style sheet. *
NO_MODIFICATION_ALLOWED_ERR: Raised if the rule is readonly. */ public String getCssText(); public void setCssText(String cssText) throws DOMException; /** * The style sheet that contains this rule. */ public CSSStyleSheet getParentStyleSheet(); /** * If this rule is contained inside another rule (e.g. a style rule * inside an @media block), this is the containing rule. If this rule is * not nested inside any other rules, this returns null. */ public CSSRule getParentRule(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/CSSRuleList.java0000644000175000017500000000341710445070346023615 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; /** * The CSSRuleList interface provides the abstraction of an * ordered collection of CSS rules. *

The items in the CSSRuleList are accessible via an * integral index, starting from 0. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface CSSRuleList { /** * The number of CSSRules in the list. The range of valid * child rule indices is 0 to length-1 * inclusive. */ public int getLength(); /** * Used to retrieve a CSS rule by ordinal index. The order in this * collection represents the order of the rules in the CSS style sheet. * If index is greater than or equal to the number of rules in the list, * this returns null. * @param indexIndex into the collection * @return The style rule at the index position in the * CSSRuleList, or null if that is not a * valid index. */ public CSSRule item(int index); } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/CSSStyleDeclaration.java0000644000175000017500000001555210445070346025323 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; import org.w3c.dom.DOMException; /** * The CSSStyleDeclaration interface represents a single CSS * declaration block. This interface may be used to determine the style * properties currently set in a block or to set style properties explicitly * within the block. *

While an implementation may not recognize all CSS properties within a * CSS declaration block, it is expected to provide access to all specified * properties in the style sheet through the CSSStyleDeclaration * interface. Furthermore, implementations that support a specific level of * CSS should correctly handle CSS shorthand properties for that level. For * a further discussion of shorthand properties, see the * CSS2Properties interface. *

This interface is also used to provide a read-only access to the * computed values of an element. See also the ViewCSS * interface. The CSS Object Model doesn't provide an access to the * specified or actual values of the CSS cascade. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface CSSStyleDeclaration { /** * The parsable textual representation of the declaration block * (excluding the surrounding curly braces). Setting this attribute will * result in the parsing of the new value and resetting of all the * properties in the declaration block including the removal or addition * of properties. * @exception DOMException * SYNTAX_ERR: Raised if the specified CSS string value has a syntax * error and is unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this declaration is * readonly or a property is readonly. */ public String getCssText(); public void setCssText(String cssText) throws DOMException; /** * Used to retrieve the value of a CSS property if it has been explicitly * set within this declaration block. * @param propertyName The name of the CSS property. See the CSS property * index. * @return Returns the value of the property if it has been explicitly * set for this declaration block. Returns the empty string if the * property has not been set. */ public String getPropertyValue(String propertyName); /** * Used to retrieve the object representation of the value of a CSS * property if it has been explicitly set within this declaration block. * This method returns null if the property is a shorthand * property. Shorthand property values can only be accessed and modified * as strings, using the getPropertyValue and * setProperty methods. * @param propertyName The name of the CSS property. See the CSS property * index. * @return Returns the value of the property if it has been explicitly * set for this declaration block. Returns null if the * property has not been set. */ public CSSValue getPropertyCSSValue(String propertyName); /** * Used to remove a CSS property if it has been explicitly set within * this declaration block. * @param propertyName The name of the CSS property. See the CSS property * index. * @return Returns the value of the property if it has been explicitly * set for this declaration block. Returns the empty string if the * property has not been set or the property name does not correspond * to a known CSS property. * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this declaration is readonly * or the property is readonly. */ public String removeProperty(String propertyName) throws DOMException; /** * Used to retrieve the priority of a CSS property (e.g. the * "important" qualifier) if the property has been * explicitly set in this declaration block. * @param propertyName The name of the CSS property. See the CSS property * index. * @return A string representing the priority (e.g. * "important") if one exists. The empty string if none * exists. */ public String getPropertyPriority(String propertyName); /** * Used to set a property value and priority within this declaration * block. * @param propertyName The name of the CSS property. See the CSS property * index. * @param value The new value of the property. * @param priority The new priority of the property (e.g. * "important"). * @exception DOMException * SYNTAX_ERR: Raised if the specified value has a syntax error and is * unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this declaration is * readonly or the property is readonly. */ public void setProperty(String propertyName, String value, String priority) throws DOMException; /** * The number of properties that have been explicitly set in this * declaration block. The range of valid indices is 0 to length-1 * inclusive. */ public int getLength(); /** * Used to retrieve the properties that have been explicitly set in this * declaration block. The order of the properties retrieved using this * method does not have to be the order in which they were set. This * method can be used to iterate over all properties in this declaration * block. * @param index Index of the property name to retrieve. * @return The name of the property at this ordinal position. The empty * string if no property exists at this position. */ public String item(int index); /** * The CSS rule that contains this declaration block or null * if this CSSStyleDeclaration is not attached to a * CSSRule. */ public CSSRule getParentRule(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/CSSStyleRule.java0000644000175000017500000000315610445070346024002 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; import org.w3c.dom.DOMException; /** * The CSSStyleRule interface represents a single rule set in a * CSS style sheet. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface CSSStyleRule extends CSSRule { /** * The textual representation of the selector for the rule set. The * implementation may have stripped out insignificant whitespace while * parsing the selector. * @exception DOMException * SYNTAX_ERR: Raised if the specified CSS string value has a syntax * error and is unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this rule is readonly. */ public String getSelectorText(); public void setSelectorText(String selectorText) throws DOMException; /** * The declaration-block of this rule set. */ public CSSStyleDeclaration getStyle(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/CSSStyleSheet.java0000644000175000017500000000737110445070346024146 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; import org.w3c.dom.DOMException; import org.w3c.dom.stylesheets.StyleSheet; /** * The CSSStyleSheet interface is a concrete interface used to * represent a CSS style sheet i.e., a style sheet whose content type is * "text/css". *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface CSSStyleSheet extends StyleSheet { /** * If this style sheet comes from an @import rule, the * ownerRule attribute will contain the * CSSImportRule. In that case, the ownerNode * attribute in the StyleSheet interface will be * null. If the style sheet comes from an element or a * processing instruction, the ownerRule attribute will be * null and the ownerNode attribute will * contain the Node. */ public CSSRule getOwnerRule(); /** * The list of all CSS rules contained within the style sheet. This * includes both rule sets and at-rules. */ public CSSRuleList getCssRules(); /** * Used to insert a new rule into the style sheet. The new rule now * becomes part of the cascade. * @param rule The parsable text representing the rule. For rule sets * this contains both the selector and the style declaration. For * at-rules, this specifies both the at-identifier and the rule * content. * @param index The index within the style sheet's rule list of the rule * before which to insert the specified rule. If the specified index * is equal to the length of the style sheet's rule collection, the * rule will be added to the end of the style sheet. * @return The index within the style sheet's rule collection of the * newly inserted rule. * @exception DOMException * HIERARCHY_REQUEST_ERR: Raised if the rule cannot be inserted at the * specified index e.g. if an @import rule is inserted * after a standard rule set or other at-rule. *
INDEX_SIZE_ERR: Raised if the specified index is not a valid * insertion point. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this style sheet is * readonly. *
SYNTAX_ERR: Raised if the specified rule has a syntax error and * is unparsable. */ public int insertRule(String rule, int index) throws DOMException; /** * Used to delete a rule from the style sheet. * @param index The index within the style sheet's rule list of the rule * to remove. * @exception DOMException * INDEX_SIZE_ERR: Raised if the specified index does not correspond to * a rule in the style sheet's rule list. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this style sheet is * readonly. */ public void deleteRule(int index) throws DOMException; } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/CSSUnknownRule.java0000644000175000017500000000166010445070346024337 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; /** * The CSSUnknownRule interface represents an at-rule not * supported by this user agent. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface CSSUnknownRule extends CSSRule { } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/CSSValue.java0000644000175000017500000000525710445070346023132 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; import org.w3c.dom.DOMException; /** * The CSSValue interface represents a simple or a complex * value. A CSSValue object only occurs in a context of a CSS * property. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface CSSValue { // UnitTypes /** * The value is inherited and the cssText contains "inherit". */ public static final short CSS_INHERIT = 0; /** * The value is a primitive value and an instance of the * CSSPrimitiveValue interface can be obtained by using * binding-specific casting methods on this instance of the * CSSValue interface. */ public static final short CSS_PRIMITIVE_VALUE = 1; /** * The value is a CSSValue list and an instance of the * CSSValueList interface can be obtained by using * binding-specific casting methods on this instance of the * CSSValue interface. */ public static final short CSS_VALUE_LIST = 2; /** * The value is a custom value. */ public static final short CSS_CUSTOM = 3; /** * A string representation of the current value. * @exception DOMException * SYNTAX_ERR: Raised if the specified CSS string value has a syntax * error (according to the attached property) or is unparsable. *
INVALID_MODIFICATION_ERR: Raised if the specified CSS string * value represents a different type of values than the values allowed * by the CSS property. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this value is readonly. */ public String getCssText(); public void setCssText(String cssText) throws DOMException; /** * A code defining the type of the value as defined above. */ public short getCssValueType(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/CSSValueList.java0000644000175000017500000000403410445070346023756 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; /** * The CSSValueList interface provides the abstraction of an * ordered collection of CSS values. *

Some properties allow an empty list into their syntax. In that case, * these properties take the none identifier. So, an empty list * means that the property has the value none. *

The items in the CSSValueList are accessible via an * integral index, starting from 0. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface CSSValueList extends CSSValue { /** * The number of CSSValues in the list. The range of valid * values of the indices is 0 to length-1 * inclusive. */ public int getLength(); /** * Used to retrieve a CSSValue by ordinal index. The order in * this collection represents the order of the values in the CSS style * property. If index is greater than or equal to the number of values * in the list, this returns null. * @param indexIndex into the collection. * @return The CSSValue at the index position * in the CSSValueList, or null if that is * not a valid index. */ public CSSValue item(int index); } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/Counter.java0000644000175000017500000000252210445070346023114 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; /** * The Counter interface is used to represent any counter or * counters function value. This interface reflects the values in the * underlying style property. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface Counter { /** * This attribute is used for the identifier of the counter. */ public String getIdentifier(); /** * This attribute is used for the style of the list. */ public String getListStyle(); /** * This attribute is used for the separator of the nested counters. */ public String getSeparator(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/DOMImplementationCSS.java0000644000175000017500000000337210445070346025377 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; import org.w3c.dom.DOMImplementation; import org.w3c.dom.DOMException; /** * This interface allows the DOM user to create a CSSStyleSheet * outside the context of a document. There is no way to associate the new * CSSStyleSheet with a document in DOM Level 2. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface DOMImplementationCSS extends DOMImplementation { /** * Creates a new CSSStyleSheet. * @param title The advisory title. See also the section. * @param media The comma-separated list of media associated with the new * style sheet. See also the section. * @return A new CSS style sheet. * @exception DOMException * SYNTAX_ERR: Raised if the specified media string value has a syntax * error and is unparsable. */ public CSSStyleSheet createCSSStyleSheet(String title, String media) throws DOMException; } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/DocumentCSS.java0000644000175000017500000000476110445070346023633 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; import org.w3c.dom.stylesheets.DocumentStyle; import org.w3c.dom.Element; /** * This interface represents a document with a CSS view. *

The getOverrideStyle method provides a mechanism through * which a DOM author could effect immediate change to the style of an * element without modifying the explicitly linked style sheets of a * document or the inline style of elements in the style sheets. This style * sheet comes after the author style sheet in the cascade algorithm and is * called override style sheet. The override style sheet takes precedence * over author style sheets. An "!important" declaration still takes * precedence over a normal declaration. Override, author, and user style * sheets all may contain "!important" declarations. User "!important" rules * take precedence over both override and author "!important" rules, and * override "!important" rules take precedence over author "!important" * rules. *

The expectation is that an instance of the DocumentCSS * interface can be obtained by using binding-specific casting methods on an * instance of the Document interface. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface DocumentCSS extends DocumentStyle { /** * This method is used to retrieve the override style declaration for a * specified element and a specified pseudo-element. * @param elt The element whose style is to be modified. This parameter * cannot be null. * @param pseudoElt The pseudo-element or null if none. * @return The override style declaration. */ public CSSStyleDeclaration getOverrideStyle(Element elt, String pseudoElt); } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/ElementCSSInlineStyle.java0000644000175000017500000000264010602443500025607 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; /** * Inline style information attached to elements is exposed through the * style attribute. This represents the contents of the STYLE * attribute for HTML elements (or elements in other schemas or DTDs which * use the STYLE attribute in the same way). The expectation is that an * instance of the ElementCSSInlineStyle interface can be obtained by using * binding-specific casting methods on an instance of the Element interface * when the element supports inline CSS style informations. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface ElementCSSInlineStyle { /** * The style attribute. */ public CSSStyleDeclaration getStyle(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/RGBColor.java0000644000175000017500000000363210445070346023111 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; /** * The RGBColor interface is used to represent any RGB color * value. This interface reflects the values in the underlying style * property. Hence, modifications made to the CSSPrimitiveValue * objects modify the style property. *

A specified RGB color is not clipped (even if the number is outside the * range 0-255 or 0%-100%). A computed RGB color is clipped depending on the * device. *

Even if a style sheet can only contain an integer for a color value, * the internal storage of this integer is a float, and this can be used as * a float in the specified or the computed style. *

A color percentage value can always be converted to a number and vice * versa. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface RGBColor { /** * This attribute is used for the red value of the RGB color. */ public CSSPrimitiveValue getRed(); /** * This attribute is used for the green value of the RGB color. */ public CSSPrimitiveValue getGreen(); /** * This attribute is used for the blue value of the RGB color. */ public CSSPrimitiveValue getBlue(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/Rect.java0000644000175000017500000000301710445070346022372 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; /** * The Rect interface is used to represent any rect value. This * interface reflects the values in the underlying style property. Hence, * modifications made to the CSSPrimitiveValue objects modify * the style property. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface Rect { /** * This attribute is used for the top of the rect. */ public CSSPrimitiveValue getTop(); /** * This attribute is used for the right of the rect. */ public CSSPrimitiveValue getRight(); /** * This attribute is used for the bottom of the rect. */ public CSSPrimitiveValue getBottom(); /** * This attribute is used for the left of the rect. */ public CSSPrimitiveValue getLeft(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/css/ViewCSS.java0000644000175000017500000000403110445070346022755 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.css; import org.w3c.dom.views.AbstractView; import org.w3c.dom.Element; /** * This interface represents a CSS view. The getComputedStyle * method provides a read only access to the computed values of an element. *

The expectation is that an instance of the ViewCSS * interface can be obtained by using binding-specific casting methods on an * instance of the AbstractView interface. *

Since a computed style is related to an Element node, if * this element is removed from the document, the associated * CSSStyleDeclaration and CSSValue related to * this declaration are no longer valid. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface ViewCSS extends AbstractView { /** * This method is used to get the computed style as it is defined in . * @param elt The element whose style is to be computed. This parameter * cannot be null. * @param pseudoElt The pseudo-element or null if none. * @return The computed style. The CSSStyleDeclaration is * read-only and contains only absolute values. */ public CSSStyleDeclaration getComputedStyle(Element elt, String pseudoElt); } libcobra-java-0.98.4.orig/src/org/w3c/dom/stylesheets/0000755000175000017500000000000010630473006022411 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/w3c/dom/stylesheets/DocumentStyle.java0000644000175000017500000000307610445070346026065 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.stylesheets; /** * The DocumentStyle interface provides a mechanism by which the * style sheets embedded in a document can be retrieved. The expectation is * that an instance of the DocumentStyle interface can be * obtained by using binding-specific casting methods on an instance of the * Document interface. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface DocumentStyle { /** * A list containing all the style sheets explicitly linked into or * embedded in a document. For HTML documents, this includes external * style sheets, included via the HTML LINK element, and inline STYLE * elements. In XML, this includes external style sheets, included via * style sheet processing instructions (see ). */ public StyleSheetList getStyleSheets(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/stylesheets/LinkStyle.java0000644000175000017500000000250310445070346025176 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.stylesheets; /** * The LinkStyle interface provides a mechanism by which a style * sheet can be retrieved from the node responsible for linking it into a * document. An instance of the LinkStyle interface can be * obtained using binding-specific casting methods on an instance of a * linking node (HTMLLinkElement, HTMLStyleElement * or ProcessingInstruction in DOM Level 2). *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface LinkStyle { /** * The style sheet. */ public StyleSheet getSheet(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/stylesheets/MediaList.java0000644000175000017500000000651210445070346025137 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.stylesheets; import org.w3c.dom.DOMException; /** * The MediaList interface provides the abstraction of an * ordered collection of media, without defining or constraining how this * collection is implemented. An empty list is the same as a list that * contains the medium "all". *

The items in the MediaList are accessible via an integral * index, starting from 0. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface MediaList { /** * The parsable textual representation of the media list. This is a * comma-separated list of media. * @exception DOMException * SYNTAX_ERR: Raised if the specified string value has a syntax error * and is unparsable. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this media list is * readonly. */ public String getMediaText(); public void setMediaText(String mediaText) throws DOMException; /** * The number of media in the list. The range of valid media is * 0 to length-1 inclusive. */ public int getLength(); /** * Returns the indexth in the list. If index is * greater than or equal to the number of media in the list, this * returns null. * @param index Index into the collection. * @return The medium at the indexth position in the * MediaList, or null if that is not a valid * index. */ public String item(int index); /** * Deletes the medium indicated by oldMedium from the list. * @param oldMediumThe medium to delete in the media list. * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this list is readonly. *
NOT_FOUND_ERR: Raised if oldMedium is not in the * list. */ public void deleteMedium(String oldMedium) throws DOMException; /** * Adds the medium newMedium to the end of the list. If the * newMedium is already used, it is first removed. * @param newMediumThe new medium to add. * @exception DOMException * INVALID_CHARACTER_ERR: If the medium contains characters that are * invalid in the underlying style language. *
NO_MODIFICATION_ALLOWED_ERR: Raised if this list is readonly. */ public void appendMedium(String newMedium) throws DOMException; } libcobra-java-0.98.4.orig/src/org/w3c/dom/stylesheets/StyleSheet.java0000644000175000017500000001055110445070346025353 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.stylesheets; import org.w3c.dom.Node; /** * The StyleSheet interface is the abstract base interface for * any type of style sheet. It represents a single style sheet associated * with a structured document. In HTML, the StyleSheet interface represents * either an external style sheet, included via the HTML LINK element, or * an inline STYLE element. In XML, this interface represents an external * style sheet, included via a style sheet processing instruction. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface StyleSheet { /** * This specifies the style sheet language for this style sheet. The * style sheet language is specified as a content type (e.g. * "text/css"). The content type is often specified in the * ownerNode. Also see the type attribute definition for * the LINK element in HTML 4.0, and the type * pseudo-attribute for the XML style sheet processing instruction. */ public String getType(); /** * false if the style sheet is applied to the document. * true if it is not. Modifying this attribute may cause a * new resolution of style for the document. A stylesheet only applies * if both an appropriate medium definition is present and the disabled * attribute is false. So, if the media doesn't apply to the current * user agent, the disabled attribute is ignored. */ public boolean getDisabled(); public void setDisabled(boolean disabled); /** * The node that associates this style sheet with the document. For HTML, * this may be the corresponding LINK or STYLE * element. For XML, it may be the linking processing instruction. For * style sheets that are included by other style sheets, the value of * this attribute is null. */ public Node getOwnerNode(); /** * For style sheet languages that support the concept of style sheet * inclusion, this attribute represents the including style sheet, if * one exists. If the style sheet is a top-level style sheet, or the * style sheet language does not support inclusion, the value of this * attribute is null. */ public StyleSheet getParentStyleSheet(); /** * If the style sheet is a linked style sheet, the value of its attribute * is its location. For inline style sheets, the value of this attribute * is null. See the href attribute definition for the * LINK element in HTML 4.0, and the href pseudo-attribute * for the XML style sheet processing instruction. */ public String getHref(); /** * The advisory title. The title is often specified in the * ownerNode. See the title attribute definition for the * LINK element in HTML 4.0, and the title pseudo-attribute * for the XML style sheet processing instruction. */ public String getTitle(); /** * The intended destination media for style information. The media is * often specified in the ownerNode. If no media has been * specified, the MediaList will be empty. See the media * attribute definition for the LINK element in HTML 4.0, * and the media pseudo-attribute for the XML style sheet processing * instruction . Modifying the media list may cause a change to the * attribute disabled. */ public MediaList getMedia(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/stylesheets/StyleSheetList.java0000644000175000017500000000333410445070346026210 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.stylesheets; /** * The StyleSheetList interface provides the abstraction of an * ordered collection of style sheets. *

The items in the StyleSheetList are accessible via an * integral index, starting from 0. *

See also the Document Object Model (DOM) Level 2 Style Specification. * @since DOM Level 2 */ public interface StyleSheetList { /** * The number of StyleSheets in the list. The range of valid * child stylesheet indices is 0 to length-1 * inclusive. */ public int getLength(); /** * Used to retrieve a style sheet by ordinal index. If index is greater * than or equal to the number of style sheets in the list, this returns * null. * @param indexIndex into the collection * @return The style sheet at the index position in the * StyleSheetList, or null if that is not a * valid index. */ public StyleSheet item(int index); } libcobra-java-0.98.4.orig/src/org/w3c/dom/views/0000755000175000017500000000000010630473006021172 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/w3c/dom/views/AbstractView.java0000644000175000017500000000201310445070346024433 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.views; /** * A base interface that all views shall derive from. *

See also the Document Object Model (DOM) Level 2 Views Specification. * @since DOM Level 2 */ public interface AbstractView { /** * The source DocumentView of which this is an * AbstractView. */ public DocumentView getDocument(); } libcobra-java-0.98.4.orig/src/org/w3c/dom/views/DocumentView.java0000644000175000017500000000231410445070346024452 0ustar twernertwerner/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.views; /** * The DocumentView interface is implemented by * Document objects in DOM implementations supporting DOM * Views. It provides an attribute to retrieve the default view of a * document. *

See also the Document Object Model (DOM) Level 2 Views Specification. * @since DOM Level 2 */ public interface DocumentView { /** * The default AbstractView for this Document, * or null if none available. */ public AbstractView getDefaultView(); } libcobra-java-0.98.4.orig/src/org/w3c/css/0000755000175000017500000000000010577442262020060 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/w3c/css/sac/0000755000175000017500000000000010630473006020614 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/w3c/css/sac/AttributeCondition.java0000644000175000017500000000520510737110112025265 0ustar twernertwerner/* * Copyright (c) 1999 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. * * $Id: AttributeCondition.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * @version $Revision: 1.4 $ * @author Philippe Le Hegaret * @see Condition#SAC_ATTRIBUTE_CONDITION * @see Condition#SAC_ONE_OF_ATTRIBUTE_CONDITION * @see Condition#SAC_BEGIN_HYPHEN_ATTRIBUTE_CONDITION * @see Condition#SAC_ID_CONDITION * @see Condition#SAC_CLASS_CONDITION * @see Condition#SAC_PSEUDO_CLASS_CONDITION */ public interface AttributeCondition extends Condition { /** * Returns the * namespace * URI of this attribute condition. *

NULL if : *

*/ public String getNamespaceURI(); /** * Returns the * local part * of the * qualified * name of this attribute. *

NULL if : *

*/ public String getLocalName(); /** * Returns true if the attribute must have an explicit value * in the original document, false otherwise. If this is a * pseudo class, the return value is unspecified. *

false if: *

*/ public boolean getSpecified(); /** * Returns the value of the attribute. * If this attribute is a class or a pseudo class attribute, you'll get * the class name (or psedo class name) without the '.' or ':'. */ public String getValue(); } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/CSSException.java0000644000175000017500000000506010737110112023761 0ustar twernertwerner/* * Copyright (c) 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * The original version of this interface comes from SAX : * http://www.megginson.com/SAX/ * * $Id: CSSException.java,v 1.5 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * @version $Revision: 1.5 $ * @author Philippe Le Hegaret */ public class CSSException extends RuntimeException { /** * this error is unspecified. */ public static short SAC_UNSPECIFIED_ERR = 0; /** * If the operation is not supported */ public static short SAC_NOT_SUPPORTED_ERR = 1; /** * If an invalid or illegal string is specified */ public static short SAC_SYNTAX_ERR = 2; protected short code; /** * Creates a new CSSException */ public CSSException() { } /** * Creates a new CSSException */ public CSSException(String s) { super(s); this.code = SAC_UNSPECIFIED_ERR; } /** * Creates a new CSSException with an embeded exception. * @param a the embeded exception. */ public CSSException(Exception e) { super(e); this.code = SAC_UNSPECIFIED_ERR; } /** * Creates a new CSSException with a specific code. * @param a the embeded exception. */ public CSSException(short code) { this.code = code; } /** * Creates a new CSSException with an embeded exception and a specified * message. * @param code the specified code. * @param e the embeded exception. */ public CSSException(short code, String s, Exception e) { super(s, e); this.code = code; } /** * Returns the detail message of this throwable object. * * @return the detail message of this Throwable, or null if this Throwable * does not have a detail message. */ public String getMessage() { return super.getMessage(); } /** * returns the error code for this exception. */ public short getCode() { return code; } /** * Returns the internal exception if any, null otherwise. */ public Exception getException() { Throwable cause = this.getCause(); return cause instanceof Exception ? (Exception) cause : null; } } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/CSSParseException.java0000644000175000017500000001351610737110112024761 0ustar twernertwerner/* * Copyright (c) 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * The original version of this interface comes from SAX : * http://www.megginson.com/SAX/ * * $Id: CSSParseException.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * Encapsulate a CSS parse error or warning. * *

This exception will include information for locating the error * in the original CSS document. Note that although the application * will receive a CSSParseException as the argument to the handlers * in the ErrorHandler interface, the application is not actually * required to throw the exception; instead, it can simply read the * information in it and take a different action.

* *

Since this exception is a subclass of CSSException, it * inherits the ability to wrap another exception.

* * @version $Revision: 1.4 $ * @author Philippe Le Hegaret */ public class CSSParseException extends CSSException { private String uri; private int lineNumber; private int columnNumber; /** * Create a new CSSParseException from a message and a Locator. * *

This constructor is especially useful when an application is * creating its own exception from within a DocumentHandler * callback.

* * @param message The error or warning message. * @param locator The locator object for the error or warning. * @see Locator * @see Parser#setLocale */ public CSSParseException(String message, Locator locator) { super(message); this.code = SAC_SYNTAX_ERR; this.uri = locator.getURI(); this.lineNumber = locator.getLineNumber(); this.columnNumber = locator.getColumnNumber(); } /** * Wrap an existing exception in a CSSParseException. * *

This constructor is especially useful when an application is * creating its own exception from within a DocumentHandler * callback, and needs to wrap an existing exception that is not a * subclass of CSSException.

* * @param message The error or warning message, or null to * use the message from the embedded exception. * @param locator The locator object for the error or warning. * @param e Any exception * @see Locator * @see Parser#setLocale */ public CSSParseException(String message, Locator locator, Exception e) { super(SAC_SYNTAX_ERR, message, e); this.uri = locator.getURI(); this.lineNumber = locator.getLineNumber(); this.columnNumber = locator.getColumnNumber(); } /** * Create a new CSSParseException. * *

This constructor is most useful for parser writers.

* *

the parser must resolve the URI fully before creating the exception.

* * @param message The error or warning message. * @param uri The URI of the document that generated the error or warning. * @param lineNumber The line number of the end of the text that * caused the error or warning. * @param columnNumber The column number of the end of the text that * cause the error or warning. * @see Parser#setLocale */ public CSSParseException(String message, String uri, int lineNumber, int columnNumber) { super(message); this.code = SAC_SYNTAX_ERR; this.uri = uri; this.lineNumber = lineNumber; this.columnNumber = columnNumber; } /** * Create a new CSSParseException with an embedded exception. * *

This constructor is most useful for parser writers who * need to wrap an exception that is not a subclass of * CSSException.

* *

The parser must resolve the URI fully before creating the * exception.

* * @param message The error or warning message, or null to use * the message from the embedded exception. * @param uri The URI of the document that generated * the error or warning. * @param lineNumber The line number of the end of the text that * caused the error or warning. * @param columnNumber The column number of the end of the text that * cause the error or warning. * @param e Another exception to embed in this one. * @see Parser#setLocale */ public CSSParseException(String message, String uri, int lineNumber, int columnNumber, Exception e) { super(SAC_SYNTAX_ERR, message, e); this.uri = uri; this.lineNumber = lineNumber; this.columnNumber = columnNumber; } /** * Get the URI of the document where the exception occurred. * *

The URI will be resolved fully.

* * @return A string containing the URI, or null * if none is available. * @see Locator#getURI */ public String getURI() { return this.uri; } /** * The line number of the end of the text where the exception occurred. * * @return An integer representing the line number, or -1 * if none is available. * @see Locator#getLineNumber */ public int getLineNumber() { return this.lineNumber; } /** * The column number of the end of the text where the exception occurred. * *

The first column in a line is position 1.

* * @return An integer representing the column number, or -1 * if none is available. * @see Locator#getColumnNumber */ public int getColumnNumber() { return this.columnNumber; } } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/CharacterDataSelector.java0000644000175000017500000000133010737110112025635 0ustar twernertwerner/* * (c) COPYRIGHT 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * $Id: CharacterDataSelector.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * @version $Revision: 1.4 $ * @author Philippe Le Hegaret * @see Selector#SAC_TEXT_NODE_SELECTOR * @see Selector#SAC_CDATA_SECTION_NODE_SELECTOR * @see Selector#SAC_COMMENT_NODE_SELECTOR */ public interface CharacterDataSelector extends SimpleSelector { /** * Returns the character data. */ public String getData(); } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/CombinatorCondition.java0000644000175000017500000000141110737110112025412 0ustar twernertwerner/* * (c) COPYRIGHT 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * $Id: CombinatorCondition.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * @version $Revision: 1.4 $ * @author Philippe Le Hegaret * @see Condition#SAC_AND_CONDITION * @see Condition#SAC_OR_CONDITION */ public interface CombinatorCondition extends Condition { /** * Returns the first condition. */ public Condition getFirstCondition(); /** * Returns the second condition. */ public Condition getSecondCondition(); } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/Condition.java0000644000175000017500000001010310737110112023372 0ustar twernertwerner/* * Copyright (c) 1999 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. * * $Id: Condition.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * @version $Revision: 1.4 $ * @author Philippe Le Hegaret */ public interface Condition { /** * This condition checks exactly two conditions. * example: *
     *   .part1:lang(fr)
     * 
* @see CombinatorCondition */ public static final short SAC_AND_CONDITION = 0; /** * This condition checks one of two conditions. * @see CombinatorCondition */ public static final short SAC_OR_CONDITION = 1; /** * This condition checks that a condition can't be applied to a node. * @see NegativeCondition */ public static final short SAC_NEGATIVE_CONDITION = 2; /** * This condition checks a specified position. * example: *
     *   :first-child
     * 
* @see PositionalCondition */ public static final short SAC_POSITIONAL_CONDITION = 3; /** * This condition checks an attribute. * example: *
     *   [simple]
     *   [restart="never"]
     * 
* @see AttributeCondition */ public static final short SAC_ATTRIBUTE_CONDITION = 4; /** * This condition checks an id attribute. * example: *
     *   #myId
     * 
* @see AttributeCondition */ public static final short SAC_ID_CONDITION = 5; /** * This condition checks the language of the node. * example: *
     *   :lang(fr)
     * 
* @see LangCondition */ public static final short SAC_LANG_CONDITION = 6; /** * This condition checks for a value in a space-separated values in a * specified attribute * example: *
     *   [values~="10"]
     * 
* @see AttributeCondition */ public static final short SAC_ONE_OF_ATTRIBUTE_CONDITION = 7; /** * This condition checks if the value is in a hypen-separated list of values * in a specified attribute. * example: *
     *   [languages|="fr"]
     * 
* @see AttributeCondition */ public static final short SAC_BEGIN_HYPHEN_ATTRIBUTE_CONDITION = 8; /** * This condition checks for a specified class. * example: *
     *   .example
     * 
* @see AttributeCondition */ public static final short SAC_CLASS_CONDITION = 9; /** * This condition checks for the link pseudo class. * example: *
     *   :link
     *   :visited
     *   :hover
     * 
* @see AttributeCondition */ public static final short SAC_PSEUDO_CLASS_CONDITION = 10; /** * This condition checks if a node is the only one in the node list. */ public static final short SAC_ONLY_CHILD_CONDITION = 11; /** * This condition checks if a node is the only one of his type. */ public static final short SAC_ONLY_TYPE_CONDITION = 12; /** * This condition checks the content of a node. * @see ContentCondition */ public static final short SAC_CONTENT_CONDITION = 13; /** * An integer indicating the type of Condition. */ public short getConditionType(); } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/ConditionFactory.java0000644000175000017500000001533110737110112024732 0ustar twernertwerner/* * Copyright (c) 1999 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. * * $Id: ConditionFactory.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * @version $Revision: 1.4 $ * @author Philippe Le Hegaret */ public interface ConditionFactory { /** * Creates an and condition * * @param first the first condition * @param second the second condition * @return A combinator condition * @exception CSSException if this exception is not supported. */ CombinatorCondition createAndCondition(Condition first, Condition second) throws CSSException; /** * Creates an or condition * * @param first the first condition * @param second the second condition * @return A combinator condition * @exception CSSException if this exception is not supported. */ CombinatorCondition createOrCondition(Condition first, Condition second) throws CSSException; /** * Creates a negative condition * * @param condition the condition * @return A negative condition * @exception CSSException if this exception is not supported. */ NegativeCondition createNegativeCondition(Condition condition) throws CSSException; /** * Creates a positional condition * * @param position the position of the node in the list. * @param typeNode true if the list should contain * only nodes of the same type (element, text node, ...). * @param type true true if the list should contain * only nodes of the same node (for element, same localName * and same namespaceURI). * @return A positional condition * @exception CSSException if this exception is not supported. */ PositionalCondition createPositionalCondition(int position, boolean typeNode, boolean type) throws CSSException; /** * Creates an attribute condition * * @param localName the localName of the attribute * @param namespaceURI the namespace URI of the attribute * @param specified true if the attribute must be specified * in the document. * @param value the value of this attribute. * @return An attribute condition * @exception CSSException if this exception is not supported. */ AttributeCondition createAttributeCondition(String localName, String namespaceURI, boolean specified, String value) throws CSSException; /** * Creates an id condition * * @param value the value of the id. * @return An Id condition * @exception CSSException if this exception is not supported. */ AttributeCondition createIdCondition(String value) throws CSSException; /** * Creates a lang condition * * @param value the value of the language. * @return A lang condition * @exception CSSException if this exception is not supported. */ LangCondition createLangCondition(String lang) throws CSSException; /** * Creates a "one of" attribute condition * * @param localName the localName of the attribute * @param namespaceURI the namespace URI of the attribute * @param specified true if the attribute must be specified * in the document. * @param value the value of this attribute. * @return A "one of" attribute condition * @exception CSSException if this exception is not supported. */ AttributeCondition createOneOfAttributeCondition(String localName, String namespaceURI, boolean specified, String value) throws CSSException; /** * Creates a "begin hyphen" attribute condition * * @param localName the localName of the attribute * @param namespaceURI the namespace URI of the attribute * @param specified true if the attribute must be specified * in the document. * @param value the value of this attribute. * @return A "begin hyphen" attribute condition * @exception CSSException if this exception is not supported. */ AttributeCondition createBeginHyphenAttributeCondition(String localName, String namespaceURI, boolean specified, String value) throws CSSException; /** * Creates a class condition * * @param localName the localName of the attribute * @param namespaceURI the namespace URI of the attribute * @param specified true if the attribute must be specified * in the document. * @param value the name of the class. * @return A class condition * @exception CSSException if this exception is not supported. */ AttributeCondition createClassCondition(String namespaceURI, String value) throws CSSException; /** * Creates a pseudo class condition * * @param namespaceURI the namespace URI of the attribute * @param value the name of the pseudo class * @return A pseudo class condition * @exception CSSException if this exception is not supported. */ AttributeCondition createPseudoClassCondition(String namespaceURI, String value) throws CSSException; /** * Creates a "only one" child condition * * @return A "only one" child condition * @exception CSSException if this exception is not supported. */ Condition createOnlyChildCondition() throws CSSException; /** * Creates a "only one" type condition * * @return A "only one" type condition * @exception CSSException if this exception is not supported. */ Condition createOnlyTypeCondition() throws CSSException; /** * Creates a content condition * * @param data the data in the content * @return A content condition * @exception CSSException if this exception is not supported. */ ContentCondition createContentCondition(String data) throws CSSException; } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/ConditionalSelector.java0000644000175000017500000000153510737110112025421 0ustar twernertwerner/* * (c) COPYRIGHT 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * $Id: ConditionalSelector.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * @version $Revision: 1.4 $ * @author Philippe Le Hegaret * @see Selector#SAC_CONDITIONAL_SELECTOR */ public interface ConditionalSelector extends SimpleSelector { /** * Returns the simple selector. *

The simple selector can't be a ConditionalSelector.

*/ public SimpleSelector getSimpleSelector(); /** * Returns the condition to be applied on the simple selector. */ public Condition getCondition(); } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/ContentCondition.java0000644000175000017500000000113610737110112024733 0ustar twernertwerner/* * (c) COPYRIGHT 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * $Id: ContentCondition.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * @version $Revision: 1.4 $ * @author Philippe Le Hegaret * @see Condition#SAC_CONTENT_CONDITION */ public interface ContentCondition extends Condition { /** * Returns the content. */ public String getData(); } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/DescendantSelector.java0000644000175000017500000000142310737110112025222 0ustar twernertwerner/* * (c) COPYRIGHT 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * $Id: DescendantSelector.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * @version $Revision: 1.4 $ * @author Philippe Le Hegaret * @see Selector#SAC_DESCENDANT_SELECTOR * @see Selector#SAC_CHILD_SELECTOR */ public interface DescendantSelector extends Selector { /** * Returns the parent selector. */ public Selector getAncestorSelector(); /* * Returns the simple selector. */ public SimpleSelector getSimpleSelector(); } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/DocumentHandler.java0000644000175000017500000001673410737110112024540 0ustar twernertwerner/* * Copyright (c) 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * $Id: DocumentHandler.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * This is the main interface that most CSS applications implement: if the * application needs to be informed of basic parsing events, it implements this * interface and registers an instance with the CSS parser using the * setCSSHandler method. * * @version $Revision: 1.4 $ * @author Philippe Le Hegaret */ public interface DocumentHandler { /** * Receive notification of the beginning of a style sheet. * * The CSS parser will invoke this method only once, before any other * methods in this interface. * * @param uri The URI of the style sheet. @@TODO can be NULL ! (inline style sheet) * @exception CSSException Any CSS exception, possibly wrapping another * exception. */ public void startDocument(InputSource source) throws CSSException; /** * Receive notification of the end of a document. * * The CSS parser will invoke this method only once, and it will be the * last method invoked during the parse. The parser shall not invoke this * method until it has either abandoned parsing (because of an * unrecoverable error) or reached the end of input. * * @param uri The URI of the style sheet. * @exception CSSException Any CSS exception, possibly wrapping another * exception. */ public void endDocument(InputSource source) throws CSSException; /** * Receive notification of a comment. * If the comment appears in a declaration (e.g. color: /* comment * / blue;), * the parser notifies the comment before the declaration. * * @param text The comment. * @exception CSSException Any CSS exception, possibly wrapping another * exception. */ public void comment(String text) throws CSSException; /** * Receive notification of an unknown rule t-rule not supported by this * parser. * * @param at-rule The complete ignored at-rule. * @exception CSSException Any CSS exception, possibly wrapping another * exception. */ public void ignorableAtRule(String atRule) throws CSSException; /** * Receive notification of an unknown rule t-rule not supported by this * parser. * * @param prefix null if this is the default namespace * @param uri The URI for this namespace. * @exception CSSException Any CSS exception, possibly wrapping another * exception. */ public void namespaceDeclaration(String prefix, String uri) throws CSSException; /** * Receive notification of a import statement in the style sheet. * * @param uri The URI of the imported style sheet. * @param media The intended destination media for style information. * @param defaultNamepaceURI The default namespace URI for the imported * style sheet. * @exception CSSException Any CSS exception, possibly wrapping another * exception. */ public void importStyle(String uri, SACMediaList media, String defaultNamespaceURI) throws CSSException; /** * Receive notification of the beginning of a media statement. * * The Parser will invoke this method at the beginning of every media * statement in the style sheet. there will be a corresponding endMedia() * event for every startElement() event. * * @param media The intended destination media for style information. * @exception CSSException Any CSS exception, possibly wrapping another * exception. */ public void startMedia(SACMediaList media) throws CSSException; /** * Receive notification of the end of a media statement. * * @param media The intended destination media for style information. * @exception CSSException Any CSS exception, possibly wrapping another * exception. */ public void endMedia(SACMediaList media) throws CSSException; /** * Receive notification of the beginning of a page statement. * * The Parser will invoke this method at the beginning of every page * statement in the style sheet. there will be a corresponding endPage() * event for every startPage() event. * * @param name the name of the page (if any, null otherwise) * @param pseudo_page the pseudo page (if any, null otherwise) * @exception CSSException Any CSS exception, possibly wrapping another * exception. */ public void startPage(String name, String pseudo_page) throws CSSException; /** * Receive notification of the end of a media statement. * * @param media The intended destination medium for style information. * @param pseudo_page the pseudo page (if any, null otherwise) * @exception CSSException Any CSS exception, possibly wrapping another * exception. */ public void endPage(String name, String pseudo_page) throws CSSException; /** * Receive notification of the beginning of a font face statement. * * The Parser will invoke this method at the beginning of every font face * statement in the style sheet. there will be a corresponding endFontFace() * event for every startFontFace() event. * * @exception CSSException Any CSS exception, possibly wrapping another * exception. */ public void startFontFace() throws CSSException; /** * Receive notification of the end of a font face statement. * * @exception CSSException Any CSS exception, possibly wrapping another * exception. */ public void endFontFace() throws CSSException; /** * Receive notification of the beginning of a rule statement. * * @param selectors All intended selectors for all declarations. * @exception CSSException Any CSS exception, possibly wrapping another * exception. */ public void startSelector(SelectorList selectors) throws CSSException; /** * Receive notification of the end of a rule statement. * * @param selectors All intended selectors for all declarations. * @exception CSSException Any CSS exception, possibly wrapping another * exception. */ public void endSelector(SelectorList selectors) throws CSSException; /** * Receive notification of a declaration. * * @param name the name of the property. * @param value the value of the property. All whitespace are stripped. * @param important is this property important ? * @exception CSSException Any CSS exception, possibly wrapping another * exception. */ public void property(String name, LexicalUnit value, boolean important) throws CSSException; } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/ElementSelector.java0000644000175000017500000000274410737110112024552 0ustar twernertwerner/* * Copyright (c) 1999 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. * * $Id: ElementSelector.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * @version $Revision: 1.4 $ * @author Philippe Le Hegaret * @see Selector#SAC_ELEMENT_NODE_SELECTOR */ public interface ElementSelector extends SimpleSelector { /** * Returns the * namespace * URI of this element selector. *

NULL if this element selector can match any namespace.

*/ public String getNamespaceURI(); /** * Returns the * local part * of the * qualified * name of this element. *

NULL if this element selector can match any element.

* */ public String getLocalName(); } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/ErrorHandler.java0000644000175000017500000001066010737110112024043 0ustar twernertwerner/* * Copyright (c) 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * The original version of this interface comes from SAX : * http://www.megginson.com/SAX/ * * $Id: ErrorHandler.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * Basic interface for CSS error handlers. * *

If a CSS application needs to implement customized error * handling, it must implement this interface and then register an * instance with the CSS parser using the parser's setErrorHandler * method. The parser will then report all errors and warnings * through this interface.

* *

The parser shall use this interface instead of throwing an * exception: it is up to the application whether to throw an * exception for different types of errors and warnings. Note, * however, that there is no requirement that the parser continue to * provide useful information after a call to fatalError (in other * words, a CSS driver class could catch an exception and report a * fatalError).

* *

The HandlerBase class provides a default implementation of this * interface, ignoring warnings and recoverable errors and throwing a * SAXParseException for fatal errors. An application may extend * that class rather than implementing the complete interface * itself.

* * @version $Revision: 1.4 $ * @author Philippe Le Hegaret */ public interface ErrorHandler { /** * Receive notification of a warning. * *

CSS parsers will use this method to report conditions that * are not errors or fatal errors as defined by the XML 1.0 * recommendation. The default behaviour is to take no action.

* *

The CSS parser must continue to provide normal parsing events * after invoking this method: it should still be possible for the * application to process the document through to the end.

* * @param exception The warning information encapsulated in a * CSS parse exception. * @exception CSSException Any CSS exception, possibly * wrapping another exception. * @see CSSParseException */ public void warning(CSSParseException exception) throws CSSException; /** * Receive notification of a recoverable error. * *

This corresponds to the definition of "error" in section 1.2 * of the W3C XML 1.0 Recommendation. For example, a validating * parser would use this callback to report the violation of a * validity constraint. The default behaviour is to take no * action.

* *

The CSS parser must continue to provide normal parsing events * after invoking this method: it should still be possible for the * application to process the document through to the end. If the * application cannot do so, then the parser should report a fatal * error even if the XML 1.0 recommendation does not require it to * do so.

* * @param exception The error information encapsulated in a * CSS parse exception. * @exception CSSException Any CSS exception, possibly * wrapping another exception. * @see CSSParseException */ public void error(CSSParseException exception) throws CSSException; /** * Receive notification of a non-recoverable error. * *

This corresponds to the definition of "fatal error" in * section 1.2 of the W3C XML 1.0 Recommendation. For example, a * parser would use this callback to report the violation of a * well-formedness constraint.

* *

The application must assume that the document is unusable * after the parser has invoked this method, and should continue * (if at all) only for the sake of collecting addition error * messages: in fact, CSS parsers are free to stop reporting any * other events once this method has been invoked.

* * @param exception The error information encapsulated in a * CSS parse exception. * @exception CSSException Any CSS exception, possibly * wrapping another exception. * @see CSSParseException */ public void fatalError(CSSParseException exception) throws CSSException; } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/InputSource.java0000644000175000017500000001732310737110112023737 0ustar twernertwerner/* * Copyright (c) 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * The original version of this interface comes from SAX : * http://www.megginson.com/SAX/ * * $Id: InputSource.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; import java.io.InputStream; import java.io.Reader; /** * A single input source for a CSS source. * *

This class allows a CSS application to encapsulate information about an * input source in a single object, which may include a URI, a byte stream * (possibly with a specified encoding), and/or a character stream.

* *

The CSS parser will use the InputSource object to determine how * to read CSS input. If there is a character stream available, the * parser will read that stream directly; if not, the parser will use * a byte stream, if available; if neither a character stream nor a * byte stream is available, the parser will attempt to open a URI * connection to the resource identified by the URI.

* *

An InputSource object belongs to the application: the CSS parser * shall never modify it in any way (it may modify a copy if * necessary).

* * @version $Revision: 1.4 $ * @author Philippe Le Hegaret */ public class InputSource { private String uri; private InputStream byteStream; private String encoding; private Reader characterStream; private String title; private String media; /** * Zero-argument default constructor. * * @see #setURI * @see #setByteStream * @see #setCharacterStream * @see #setEncoding */ public InputSource() { } /** * Create a new input source with a URI. * *

The URI must be full resolved.

* * @param uri The URI. * @see #setURI * @see #setByteStream * @see #setEncoding * @see #setCharacterStream */ public InputSource(String uri) { setURI(uri); } /** * Create a new input source with a character stream. * *

Application writers may use setURI() to provide a base * for resolving relative URIs, and setPublicId to include a * public identifier.

* *

The character stream shall not include a byte order mark.

* * @see #setURI * @see #setByteStream * @see #setCharacterStream */ public InputSource(Reader characterStream) { setCharacterStream(characterStream); } /** * Set the URI for this input source. * *

The URI is optional if there is a byte stream or a character stream, * but it is still useful to provide one, since the application can use it * to resolve relative URIs and can include it in error messages and * warnings (the parser will attempt to open a connection to the URI only * if there is no byte stream or character stream specified).

* *

If the application knows the character encoding of the * object pointed to by the URI, it can register * the encoding using the setEncoding method.

* *

The URI must be fully resolved.

* * @param uri The URI as a string. * @see #setEncoding * @see #getURI * @see Locator#getURI * @see CSSParseException#getURI */ public void setURI(String uri) { this.uri = uri; } /** * Get the URI for this input source. * *

The getEncoding method will return the character encoding * of the object pointed to, or null if unknown.

* *

The URI will be fully resolved.

* * @return The URI. * @see #setURI * @see #getEncoding */ public String getURI() { return uri; } /** * Set the byte stream for this input source. * *

The SAX parser will ignore this if there is also a character * stream specified, but it will use a byte stream in preference * to opening a URI connection itself.

* *

If the application knows the character encoding of the * byte stream, it should set it with the setEncoding method.

* * @param byteStream A byte stream containing an CSS document or * other entity. * @see #setEncoding * @see #getByteStream * @see #getEncoding */ public void setByteStream(InputStream byteStream) { this.byteStream = byteStream; } /** * Get the byte stream for this input source. * *

The getEncoding method will return the character * encoding for this byte stream, or null if unknown.

* * @return The byte stream, or null if none was supplied. * @see #getEncoding * @see #setByteStream */ public InputStream getByteStream() { return byteStream; } /** * Set the character encoding, if known. * *

The encoding must be a string acceptable for an * CHARSET encoding declaration (see section 4.4 of the CSS * recommendation Level 2).

* *

This method has no effect when the application provides a * character stream.

* * @param encoding A string describing the character encoding. * @see #setURI * @see #setByteStream * @see #getEncoding */ public void setEncoding(String encoding) { this.encoding = encoding; } /** * Get the character encoding for a byte stream or URI. * * @return The encoding, or null if none was supplied. * @see #setByteStream * @see #getURI * @see #getByteStream */ public String getEncoding() { return encoding; } /** * Set the character stream for this input source. * *

If there is a character stream specified, the SAX parser * will ignore any byte stream and will not attempt to open * a URI connection to the URI.

* * @param characterStream The character stream containing the * CSS document or other entity. * @see #getCharacterStream */ public void setCharacterStream(Reader characterStream) { this.characterStream = characterStream; } /** * Get the character stream for this input source. * * @return The character stream, or null if none was supplied. * @see #setCharacterStream */ public Reader getCharacterStream() { return characterStream; } /** * Set the title for this input source. * @param title The advisory title. See the title attribute definition * for the LINK * element in HTML 4.0, and the title pseudo-attribute for the XML * style sheet processing instruction. */ public void setTitle(String title) { this.title = title; } /** * Returns the title for this input source. */ public String getTitle() { return title; } /** * Set the media for this input source. * @param media A comma separated list with all media. */ public void setMedia(String media) { this.media = media; } /** * Returns the media associated to the input source or null * if media are currently unknown. * @return the media associated to this input source. */ public String getMedia() { if (media == null) { return "all"; } return media; } } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/LangCondition.java0000644000175000017500000000112510737110112024200 0ustar twernertwerner/* * (c) COPYRIGHT 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * $Id: LangCondition.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * @version $Revision: 1.4 $ * @author Philippe Le Hegaret * @see Condition#SAC_LANG_CONDITION */ public interface LangCondition extends Condition { /** * Returns the language */ public String getLang(); } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/LexicalUnit.java0000644000175000017500000002365010760217246023714 0ustar twernertwerner/* * Copyright (c) 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * $Id: LexicalUnit.java,v 1.5 2008/02/24 13:37:10 xamjadmin Exp $ */ package org.w3c.css.sac; /** * This is a lexical unit for CSS values. *

Remarks: Not all the following lexical units are supported (or * will be supported) by CSS. *

All examples are CSS2 compliant. * * @version $Revision: 1.5 $ * @author Philippe Le Hegaret */ public interface LexicalUnit { /** * , */ public static final short SAC_OPERATOR_COMMA = 0; /** * + */ public static final short SAC_OPERATOR_PLUS = 1; /** * - */ public static final short SAC_OPERATOR_MINUS = 2; /** * * */ public static final short SAC_OPERATOR_MULTIPLY = 3; /** * / */ public static final short SAC_OPERATOR_SLASH = 4; /** * % */ public static final short SAC_OPERATOR_MOD = 5; /** * ^ */ public static final short SAC_OPERATOR_EXP = 6; /** * < */ public static final short SAC_OPERATOR_LT = 7; /** * > */ public static final short SAC_OPERATOR_GT = 8; /** * <= */ public static final short SAC_OPERATOR_LE = 9; /** * >= */ public static final short SAC_OPERATOR_GE = 10; /** * ~ */ public static final short SAC_OPERATOR_TILDE = 11; /** * identifier inherit. */ public static final short SAC_INHERIT = 12; /** * Integers. * @see #getIntegerValue */ public static final short SAC_INTEGER = 13; /** * reals. * @see #getFloatValue * @see #getDimensionUnitText */ public static final short SAC_REAL = 14; /** * Relative lengthem. * @see #getFloatValue * @see #getDimensionUnitText */ public static final short SAC_EM = 15; /** * Relative lengthex. * @see #getFloatValue * @see #getDimensionUnitText */ public static final short SAC_EX = 16; /** * Relative length px. * @see #getFloatValue * @see #getDimensionUnitText */ public static final short SAC_PIXEL = 17; /** * Absolute length in. * @see #getFloatValue * @see #getDimensionUnitText */ public static final short SAC_INCH = 18; /** * Absolute length cm. * @see #getFloatValue * @see #getDimensionUnitText */ public static final short SAC_CENTIMETER = 19; /** * Absolute length mm. * @see #getFloatValue * @see #getDimensionUnitText */ public static final short SAC_MILLIMETER = 20; /** * Absolute length pt. * @see #getFloatValue * @see #getDimensionUnitText */ public static final short SAC_POINT = 21; /** * Absolute length pc. * @see #getFloatValue * @see #getDimensionUnitText */ public static final short SAC_PICA = 22; /** * Percentage. * @see #getFloatValue * @see #getDimensionUnitText */ public static final short SAC_PERCENTAGE = 23; /** * URI: uri(...). * @see #getStringValue */ public static final short SAC_URI = 24; /** * function counter. * @see #getFunctionName * @see #getParameters */ public static final short SAC_COUNTER_FUNCTION = 25; /** * function counters. * @see #getFunctionName * @see #getParameters */ public static final short SAC_COUNTERS_FUNCTION = 26; /** * RGB Colors. * rgb(0, 0, 0) and #000 * @see #getFunctionName * @see #getParameters */ public static final short SAC_RGBCOLOR = 27; /** * Angle deg. * @see #getFloatValue * @see #getDimensionUnitText */ public static final short SAC_DEGREE = 28; /** * Angle grad. * @see #getFloatValue * @see #getDimensionUnitText */ public static final short SAC_GRADIAN = 29; /** * Angle rad. * @see #getFloatValue * @see #getDimensionUnitText */ public static final short SAC_RADIAN = 30; /** * Time ms. * @see #getFloatValue * @see #getDimensionUnitText */ public static final short SAC_MILLISECOND = 31; /** * Time s. * @see #getFloatValue * @see #getDimensionUnitText */ public static final short SAC_SECOND = 32; /** * Frequency Hz. * @see #getFloatValue * @see #getDimensionUnitText */ public static final short SAC_HERTZ = 33; /** * Frequency kHz. * @see #getFloatValue * @see #getDimensionUnitText */ public static final short SAC_KILOHERTZ = 34; /** * any identifier except inherit. * @see #getStringValue */ public static final short SAC_IDENT = 35; /** * A string. * @see #getStringValue */ public static final short SAC_STRING_VALUE = 36; /** * Attribute: attr(...). * @see #getStringValue */ public static final short SAC_ATTR = 37; /** * function rect. * @see #getFunctionName * @see #getParameters */ public static final short SAC_RECT_FUNCTION = 38; /** * A unicode range. @@TO BE DEFINED */ public static final short SAC_UNICODERANGE = 39; /** * sub expressions * (a) (a + b) (normal/none) * @see #getSubValues */ public static final short SAC_SUB_EXPRESSION = 40; /** * unknown function. * @see #getFunctionName * @see #getParameters */ public static final short SAC_FUNCTION = 41; /** * unknown dimension. * @see #getFloatValue * @see #getDimensionUnitText */ public static final short SAC_DIMENSION = 42; /** Added to support filter: alpha(opacity=x) */ public static final short SAC_OPERATOR_EQUALS = 43; /** Added to support filter: alpha(opacity=x) */ public static final short SAC_ALPHA_FUNCTION = 44; /** * An integer indicating the type of LexicalUnit. */ public short getLexicalUnitType(); /** * Returns the next value or null if any. */ public LexicalUnit getNextLexicalUnit(); /** * Returns the previous value or null if any. */ public LexicalUnit getPreviousLexicalUnit(); /** * Returns the integer value. * @see #SAC_INTEGER */ public int getIntegerValue(); /** * Returns the float value. *

If the type of LexicalUnit is one of SAC_DEGREE, * SAC_GRADIAN, SAC_RADIAN, SAC_MILLISECOND, SAC_SECOND, SAC_HERTZ * or SAC_KILOHERTZ, the value can never be negative.

* * @see #SAC_REAL * @see #SAC_DIMENSION * @see #SAC_EM * @see #SAC_EX * @see #SAC_PIXEL * @see #SAC_INCH * @see #SAC_CENTIMETER * @see #SAC_MILLIMETER * @see #SAC_POINT * @see #SAC_PICA * @see #SAC_PERCENTAGE * @see #SAC_DEGREE * @see #SAC_GRADIAN * @see #SAC_RADIAN * @see #SAC_MILLISECOND * @see #SAC_SECOND * @see #SAC_HERTZ * @see #SAC_KILOHERTZ */ public float getFloatValue(); /** * Returns the string representation of the unit. *

if this lexical unit represents a float, the dimension is an empty * string.

* @see #SAC_REAL * @see #SAC_DIMENSION * @see #SAC_EM * @see #SAC_EX * @see #SAC_PIXEL * @see #SAC_INCH * @see #SAC_CENTIMETER * @see #SAC_MILLIMETER * @see #SAC_POINT * @see #SAC_PICA * @see #SAC_PERCENTAGE * @see #SAC_DEGREE * @see #SAC_GRADIAN * @see #SAC_RADIAN * @see #SAC_MILLISECOND * @see #SAC_SECOND * @see #SAC_HERTZ * @see #SAC_KILOHERTZ */ public String getDimensionUnitText(); /** * Returns the name of the function. * @see #SAC_COUNTER_FUNCTION * @see #SAC_COUNTERS_FUNCTION * @see #SAC_RECT_FUNCTION * @see #SAC_FUNCTION * @see #SAC_RGBCOLOR */ public String getFunctionName(); /** * The function parameters including operators (like the comma). * #000 is converted to rgb(0, 0, 0) * can return null if SAC_FUNCTION. * @see #SAC_COUNTER_FUNCTION * @see #SAC_COUNTERS_FUNCTION * @see #SAC_RECT_FUNCTION * @see #SAC_FUNCTION * @see #SAC_RGBCOLOR */ public LexicalUnit getParameters(); /** * Returns the string value. *

If the type is SAC_URI, the return value doesn't contain * uri(....) or quotes. *

If the type is SAC_ATTR, the return value doesn't contain * attr(....). * * @see #SAC_URI * @see #SAC_ATTR * @see #SAC_IDENT * @see #SAC_STRING_VALUE * @see #SAC_UNICODERANGE @@TO BE DEFINED */ public String getStringValue(); /** * Returns a list of values inside the sub expression. * @see #SAC_SUB_EXPRESSION */ public LexicalUnit getSubValues(); } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/Locator.java0000644000175000017500000000516210737110112023060 0ustar twernertwerner/* * Copyright (c) 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * The original version of this interface comes from SAX : * http://www.megginson.com/SAX/ * * $Id: Locator.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * Interface for associating a CSS event with a document location. * *

If a SAX parser provides location information to the SAX * application, it does so by implementing this interface and then * passing an instance to the application using the document * handler's setDocumentLocator method. The application can use the * object to obtain the location of any other document handler event * in the CSS source document.

* *

Note that the results returned by the object will be valid only * during the scope of each document handler method: the application * will receive unpredictable results if it attempts to use the * locator at any other time.

* *

CSS parsers are not required to supply a locator, but they are * very strong encouraged to do so. If the parser supplies a * locator, it must do so before reporting any other document events. * If no locator has been set by the time the application receives * the startDocument event, the application should assume that a * locator is not available.

* * @version $Revision: 1.4 $ * @author Philippe Le Hegaret */ public interface Locator { /** * Return the URI for the current document event. * *

The parser must resolve the URI fully before passing it to the * application.

* * @return A string containing the URI, or null * if none is available. */ public String getURI(); /** * Return the line number where the current document event ends. * Note that this is the line position of the first character * after the text associated with the document event. * @return The line number, or -1 if none is available. * @see #getColumnNumber */ public int getLineNumber(); /** * Return the column number where the current document event ends. * Note that this is the column number of the first * character after the text associated with the document * event. The first column in a line is position 1. * @return The column number, or -1 if none is available. * @see #getLineNumber */ public int getColumnNumber(); } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/NegativeCondition.java0000644000175000017500000000116110737110112025061 0ustar twernertwerner/* * (c) COPYRIGHT 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * $Id: NegativeCondition.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * @version $Revision: 1.4 $ * @author Philippe Le Hegaret * @see Condition#SAC_NEGATIVE_CONDITION */ public interface NegativeCondition extends Condition { /** * Returns the condition. */ public Condition getCondition(); } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/NegativeSelector.java0000644000175000017500000000120210737110112024707 0ustar twernertwerner/* * (c) COPYRIGHT 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * $Id: NegativeSelector.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * @version $Revision: 1.4 $ * @author Philippe Le Hegaret * @see Selector#SAC_NEGATIVE_SELECTOR */ public interface NegativeSelector extends SimpleSelector { /** * Returns the simple selector. */ public SimpleSelector getSimpleSelector(); } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/Parser.java0000644000175000017500000002047210737110112022712 0ustar twernertwerner/* * Copyright (c) 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * The original version of this interface comes from SAX : * http://www.megginson.com/SAX/ * * $Id: Parser.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; import java.io.IOException; import java.util.Locale; /** * Basic interface for CSS (Simple API for CSS) parsers. * *

All CSS parsers must implement this basic interface: it allows * applications to register handlers for different types of events * and to initiate a parse from a URI, or a character stream.

* *

All CSS parsers must also implement a zero-argument constructor * (though other constructors are also allowed).

* *

CSS parsers are reusable but not re-entrant: the application * may reuse a parser object (possibly with a different input source) * once the first parse has completed successfully, but it may not * invoke the parse() methods recursively within a parse.

* * @version $Revision: 1.4 $ * @author Philippe Le Hegaret * @see DocumentHandler * @see ErrorHandler * @see InputSource */ public interface Parser { /** * Allow an application to request a locale for errors and warnings. * *

CSS parsers are not required to provide localisation for errors * and warnings; if they cannot support the requested locale, * however, they must throw a CSS exception. Applications may * not request a locale change in the middle of a parse.

* * @param locale A Java Locale object. * @exception CSSException Throws an exception * (using the previous or default locale) if the * requested locale is not supported. * @see CSSException * @see CSSParseException */ public void setLocale(Locale locale) throws CSSException; /** * Allow an application to register a document event handler. * *

If the application does not register a document handler, all * document events reported by the CSS parser will be silently * ignored (this is the default behaviour implemented by * HandlerBase).

* *

Applications may register a new or different handler in the * middle of a parse, and the CSS parser must begin using the new * handler immediately.

* * @param handler The document handler. * @see DocumentHandler */ public void setDocumentHandler(DocumentHandler handler); public void setSelectorFactory(SelectorFactory selectorFactory); public void setConditionFactory(ConditionFactory conditionFactory); /** * Allow an application to register an error event handler. * *

If the application does not register an error event handler, * all error events reported by the CSS parser will be silently * ignored, except for fatalError, which will throw a CSSException * (this is the default behaviour implemented by HandlerBase).

* *

Applications may register a new or different handler in the * middle of a parse, and the CSS parser must begin using the new * handler immediately.

* * @param handler The error handler. * @see ErrorHandler * @see CSSException */ public void setErrorHandler(ErrorHandler handler); /** * Parse a CSS document. * *

The application can use this method to instruct the CSS parser * to begin parsing an CSS document from any valid input * source (a character stream, a byte stream, or a URI).

* *

Applications may not invoke this method while a parse is in * progress (they should create a new Parser instead for each * additional CSS document). Once a parse is complete, an * application may reuse the same Parser object, possibly with a * different input source.

* * @param source The input source for the top-level of the * CSS document. * @exception CSSException Any CSS exception, possibly * wrapping another exception. * @exception java.io.IOException An IO exception from the parser, * possibly from a byte stream or character stream * supplied by the application. * @see InputSource * @see #parseStyleSheet(java.lang.String) * @see #setDocumentHandler * @see #setErrorHandler */ public void parseStyleSheet(InputSource source) throws CSSException, IOException; /** * Parse a CSS document from a URI. * *

This method is a shortcut for the common case of reading a document * from a URI. It is the exact equivalent of the following:

* *
     * parse(new InputSource(uri));
     * 
* *

The URI must be fully resolved by the application before it is passed * to the parser.

* * @param uri The URI. * @exception CSSException Any CSS exception, possibly * wrapping another exception. * @exception java.io.IOException An IO exception from the parser, * possibly from a byte stream or character stream * supplied by the application. * @see #parseStyleSheet(InputSource) */ public void parseStyleSheet(String uri) throws CSSException, IOException; /** * Parse a CSS style declaration (without '{' and '}'). * * @param styleValue The declaration. * @exception CSSException Any CSS exception, possibly * wrapping another exception. * @exception java.io.IOException An IO exception from the parser, * possibly from a byte stream or character stream * supplied by the application. */ public void parseStyleDeclaration(InputSource source) throws CSSException, IOException; /** * Parse a CSS rule. * * @exception CSSException Any CSS exception, possibly * wrapping another exception. * @exception java.io.IOException An IO exception from the parser, * possibly from a byte stream or character stream * supplied by the application. */ public void parseRule(InputSource source) throws CSSException, IOException; /** * Returns a string about which CSS language is supported by this * parser. For CSS Level 1, it returns "http://www.w3.org/TR/REC-CSS1", for * CSS Level 2, it returns "http://www.w3.org/TR/REC-CSS2". Note that a * "CSSx" parser can return lexical unit other than those allowed by CSS * Level x but this usage is not recommended. */ public String getParserVersion(); /** * Parse a comma separated list of selectors. * * * @exception CSSException Any CSS exception, possibly * wrapping another exception. * @exception java.io.IOException An IO exception from the parser, * possibly from a byte stream or character stream * supplied by the application. */ public SelectorList parseSelectors(InputSource source) throws CSSException, IOException; /** * Parse a CSS property value. * * * @exception CSSException Any CSS exception, possibly * wrapping another exception. * @exception java.io.IOException An IO exception from the parser, * possibly from a byte stream or character stream * supplied by the application. */ public LexicalUnit parsePropertyValue(InputSource source) throws CSSException, IOException; /** * Parse a CSS priority value (e.g. "!important"). * * * @exception CSSException Any CSS exception, possibly * wrapping another exception. * @exception java.io.IOException An IO exception from the parser, * possibly from a byte stream or character stream * supplied by the application. */ public boolean parsePriority(InputSource source) throws CSSException, IOException; } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/PositionalCondition.java0000644000175000017500000000214510737110112025443 0ustar twernertwerner/* * (c) COPYRIGHT 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * $Id: PositionalCondition.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * @version $Revision: 1.4 $ * @author Philippe Le Hegaret * @see Condition#SAC_POSITIONAL_CONDITION */ public interface PositionalCondition extends Condition { /** * Returns the position in the tree. *

A negative value means from the end of the child node list. *

The child node list begins at 0. */ public int getPosition(); /** * true if the child node list only shows nodes of the same * type of the selector (only elements, only PIS, ...) */ public boolean getTypeNode(); /** * true if the node should have the same node type (for * element, same namespaceURI and same localName). */ public boolean getType(); } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/ProcessingInstructionSelector.java0000644000175000017500000000167110737110112027535 0ustar twernertwerner/* * (c) COPYRIGHT 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * $Id: ProcessingInstructionSelector.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * This simple matches a * processing instruction. * * @version $Revision: 1.4 $ * @author Philippe Le Hegaret * @see Selector#SAC_PROCESSING_INSTRUCTION_NODE_SELECTOR */ public interface ProcessingInstructionSelector extends SimpleSelector { /** * Returns the target * of the processing instruction. */ public String getTarget(); /** * Returns the character data. */ public String getData(); } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/SACMediaList.java0000644000175000017500000000133110737110112023651 0ustar twernertwerner/* * (c) COPYRIGHT 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * $Id: SACMediaList.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * @version $Revision: 1.4 $ * @author Philippe Le Hegaret */ public interface SACMediaList { /** * Returns the length of this media list */ public int getLength(); /** * Returns the medium at the specified index, or null if this * is not a valid index. */ public String item(int index); } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/Selector.java0000644000175000017500000001005510737110112023232 0ustar twernertwerner/* * Copyright (c) 1999 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. * * $Id: Selector.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * This interface defines a selector. *

Remarks: Not all the following selectors are supported (or will be * supported) by CSS. *

All examples are CSS2 compliant. * * @version $Revision: 1.4 $ * @author Philippe Le Hegaret */ public interface Selector { /* simple selectors */ /** * This is a conditional selector. * example: *

     *   simple[role="private"]
     *   .part1
     *   H1#myId
     *   P:lang(fr).p1
     * 
* * @see ConditionalSelector */ public static final short SAC_CONDITIONAL_SELECTOR = 0; /** * This selector matches any node. * @see SimpleSelector */ public static final short SAC_ANY_NODE_SELECTOR = 1; /** * This selector matches the root node. * @see SimpleSelector */ public static final short SAC_ROOT_NODE_SELECTOR = 2; /** * This selector matches only node that are different from a specified one. * @see NegativeSelector */ public static final short SAC_NEGATIVE_SELECTOR = 3; /** * This selector matches only element node. * example: *
     *   H1
     *   animate
     * 
* @see ElementSelector */ public static final short SAC_ELEMENT_NODE_SELECTOR = 4; /** * This selector matches only text node. * @see CharacterDataSelector */ public static final short SAC_TEXT_NODE_SELECTOR = 5; /** * This selector matches only cdata node. * @see CharacterDataSelector */ public static final short SAC_CDATA_SECTION_NODE_SELECTOR = 6; /** * This selector matches only processing instruction node. * @see ProcessingInstructionSelector */ public static final short SAC_PROCESSING_INSTRUCTION_NODE_SELECTOR = 7; /** * This selector matches only comment node. * @see CharacterDataSelector */ public static final short SAC_COMMENT_NODE_SELECTOR = 8; /** * This selector matches the 'first line' pseudo element. * example: *
     *   :first-line
     * 
* @see ElementSelector */ public static final short SAC_PSEUDO_ELEMENT_SELECTOR = 9; /* combinator selectors */ /** * This selector matches an arbitrary descendant of some ancestor element. * example: *
     *   E F
     * 
* @see DescendantSelector */ public static final short SAC_DESCENDANT_SELECTOR = 10; /** * This selector matches a childhood relationship between two elements. * example: *
     *   E > F
     * 
* @see DescendantSelector */ public static final short SAC_CHILD_SELECTOR = 11; /** * This selector matches two selectors who shared the same parent in the * document tree and the element represented by the first sequence * immediately precedes the element represented by the second one. * example: *
     *   E + F
     * 
* @see SiblingSelector */ public static final short SAC_DIRECT_ADJACENT_SELECTOR = 12; /** * An integer indicating the type of Selector */ public short getSelectorType(); } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/SelectorFactory.java0000644000175000017500000001315710737110112024570 0ustar twernertwerner/* * Copyright (c) 1999 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. * * $Id: SelectorFactory.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * @version $Revision: 1.4 $ * @author Philippe Le Hegaret * @see org.w3c.css.sac.Selector */ public interface SelectorFactory { /** * Creates a conditional selector. * * @param selector a selector. * @param condition a condition * @return the conditional selector. * @exception CSSException If this selector is not supported. */ ConditionalSelector createConditionalSelector(SimpleSelector selector, Condition condition) throws CSSException; /** * Creates an any node selector. * * @return the any node selector. * @exception CSSException If this selector is not supported. */ SimpleSelector createAnyNodeSelector() throws CSSException; /** * Creates an root node selector. * * @return the root node selector. * @exception CSSException If this selector is not supported. */ SimpleSelector createRootNodeSelector() throws CSSException; /** * Creates an negative selector. * * @param selector a selector. * @return the negative selector. * @exception CSSException If this selector is not supported. */ NegativeSelector createNegativeSelector(SimpleSelector selector) throws CSSException; /** * Creates an element selector. * * @param namespaceURI the namespace * URI of the element selector. * @param tagName the local * part of the element name. NULL if this element * selector can match any element.

* @return the element selector * @exception CSSException If this selector is not supported. */ ElementSelector createElementSelector(String namespaceURI, String tagName) throws CSSException; /** * Creates a text node selector. * * @param data the data * @return the text node selector * @exception CSSException If this selector is not supported. */ CharacterDataSelector createTextNodeSelector(String data) throws CSSException; /** * Creates a cdata section node selector. * * @param data the data * @return the cdata section node selector * @exception CSSException If this selector is not supported. */ CharacterDataSelector createCDataSectionSelector(String data) throws CSSException; /** * Creates a processing instruction node selector. * * @param target the target * @param data the data * @return the processing instruction node selector * @exception CSSException If this selector is not supported. */ ProcessingInstructionSelector createProcessingInstructionSelector(String target, String data) throws CSSException; /** * Creates a comment node selector. * * @param data the data * @return the comment node selector * @exception CSSException If this selector is not supported. */ CharacterDataSelector createCommentSelector(String data) throws CSSException; /** * Creates a pseudo element selector. * * @param pseudoName the pseudo element name. NULL if this * element selector can match any pseudo element.

* @return the element selector * @exception CSSException If this selector is not supported. */ ElementSelector createPseudoElementSelector(String namespaceURI, String pseudoName) throws CSSException; /** * Creates a descendant selector. * * @param parent the parent selector * @param descendant the descendant selector * @return the combinator selector. * @exception CSSException If this selector is not supported. */ DescendantSelector createDescendantSelector(Selector parent, SimpleSelector descendant) throws CSSException; /** * Creates a child selector. * * @param parent the parent selector * @param child the child selector * @return the combinator selector. * @exception CSSException If this selector is not supported. */ DescendantSelector createChildSelector(Selector parent, SimpleSelector child) throws CSSException; /** * Creates a sibling selector. * * @param nodeType the type of nodes in the siblings list. * @param child the child selector * @param adjacent the direct adjacent selector * @return the sibling selector with nodeType equals to org.w3c.dom.Node.ELEMENT_NODE * @exception CSSException If this selector is not supported. */ SiblingSelector createDirectAdjacentSelector(short nodeType, Selector child, SimpleSelector directAdjacent) throws CSSException; } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/SelectorList.java0000644000175000017500000000162110737110112024065 0ustar twernertwerner/* * Copyright (c) 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * $Id: SelectorList.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * The SelectorList interface provides the abstraction of an ordered collection * of selectors, without defining or constraining how this collection is * implemented. * * @version $Revision: 1.4 $ * @author Philippe Le Hegaret */ public interface SelectorList { /** * Returns the length of this selector list */ public int getLength(); /** * Returns the selector at the specified index, or null if this * is not a valid index. */ public Selector item(int index); } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/SiblingSelector.java0000644000175000017500000000202210737110112024535 0ustar twernertwerner/* * (c) COPYRIGHT 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * $Id: SiblingSelector.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * @version $Revision: 1.4 $ * @author Philippe Le Hegaret * @see Selector#SAC_DIRECT_ADJACENT_SELECTOR */ public interface SiblingSelector extends Selector { public static final short ANY_NODE = 201; /** * The node type to considered in the siblings list. * All DOM node types are supported. In order to support the "any" node * type, the code ANY_NODE is added to the DOM node types. */ public short getNodeType(); /** * Returns the first selector. */ public Selector getSelector(); /* * Returns the second selector. */ public SimpleSelector getSiblingSelector(); } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/SimpleSelector.java0000644000175000017500000000123310737110112024402 0ustar twernertwerner/* * (c) COPYRIGHT 1999 World Wide Web Consortium * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ * * $Id: SimpleSelector.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package org.w3c.css.sac; /** * This interface is only for constraints on selectors. * *

A ConditionalSelector can only accept a simple selector or a * negative selector.

* * @version $Revision: 1.4 $ * @author Philippe Le Hegaret */ public interface SimpleSelector extends Selector { // empty } libcobra-java-0.98.4.orig/src/org/w3c/css/sac/helpers/0000755000175000017500000000000010630473006022256 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/org/w3c/css/sac/helpers/ParserFactory.java0000644000175000017500000000253410737110114025705 0ustar twernertwerner/* * Copyright (c) 1999 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details. * * $Id: ParserFactory.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package org.w3c.css.sac.helpers; import org.w3c.css.sac.Parser; /** * @version $Revision: 1.4 $ * @author Philippe Le Hegaret */ public class ParserFactory { /** * Create a parser with given selectors factory and conditions factory. */ public Parser makeParser() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NullPointerException, ClassCastException { String className = System.getProperty("org.w3c.css.sac.parser"); if (className == null) { throw new NullPointerException("No value for sac.parser property"); } else { return (Parser)(Class.forName(className).newInstance()); } } } libcobra-java-0.98.4.orig/src/com/0000755000175000017500000000000010577442236016564 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/com/steadystate/0000755000175000017500000000000010577442236021116 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/com/steadystate/css/0000755000175000017500000000000010630473006021673 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/com/steadystate/css/CSS2Parser.java0000644000175000017500000001035310737110114024423 0ustar twernertwerner/* * CSS2Parser.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: CSS2Parser.java,v 1.5 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css; import java.io.*; import org.w3c.dom.*; import org.w3c.dom.css.*; import org.w3c.css.sac.InputSource; import com.steadystate.css.parser.CSSOMParser; /** * * @author David Schweinsberg * @version $Release$ * @deprecated As of 0.9.0, replaced by * {@link com.steadystate.css.parsers.CSSOMParser} */ public class CSS2Parser { private CSSOMParser _parser = null; private InputSource _is = null; public CSS2Parser( Reader stream, Node ownerNode, String href, String title, String media) { _parser = new CSSOMParser(); _is = new InputSource(stream); } public CSS2Parser( InputStream stream, Node ownerNode, String href, String title, String media) { this(new InputStreamReader(stream), ownerNode, href, title, media); } public CSS2Parser(Reader stream) { this(stream, null, null, null, null); } public CSS2Parser(InputStream stream) { this(stream, null, null, null, null); } /* public CSS2Parser( InputStream stream, StyleSheet parentStyleSheet, CSSRule ownerRule, String href, String title, String media) { _parentStyleSheet = parentStyleSheet; _ownerRule = ownerRule; _href = href; _title = title; _media = media; } public CSS2Parser( Reader stream, StyleSheet parentStyleSheet, CSSRule ownerRule, String href, String title, String media) { _parser = new CSSOMParser(); _is = new InputSource(stream); } */ public CSSStyleSheet styleSheet() { try { return _parser.parseStyleSheet(_is); } catch (IOException e) { return null; } } public CSSRuleList styleSheetRuleList() throws IOException { return null; } public CSSCharsetRule charsetRule() throws IOException { return null; } public CSSUnknownRule unknownRule() throws IOException { return null; } public CSSImportRule importRule() throws IOException { return null; } public CSSMediaRule mediaRule() throws IOException { return null; } public CSSPageRule pageRule() throws IOException { return null; } public CSSFontFaceRule fontFaceRule() throws IOException { return null; } public CSSStyleRule styleRule() throws IOException { return null; } public CSSStyleDeclaration styleDeclaration() { try { return _parser.parseStyleDeclaration(_is); } catch (IOException e) { return null; } } public CSSValue expr() { try { return _parser.parsePropertyValue(_is); } catch (IOException e) { return null; } } }libcobra-java-0.98.4.orig/src/com/steadystate/css/HexColor.java0000644000175000017500000000441410737110114024260 0ustar twernertwerner/* * HexColor.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: HexColor.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css; /** * @author David Schweinsberg * @version $Release$ */ public class HexColor { private int r = 0; private int g = 0; private int b = 0; public HexColor(String hex) { // Step past the hash at the beginning int i = 0; if (hex.charAt( 0 ) == '#') { i++; } int len = hex.length() - i; if (len == 3) { r = Integer.parseInt(hex.substring(i + 0, i + 1), 16); g = Integer.parseInt(hex.substring(i + 1, i + 2), 16); b = Integer.parseInt(hex.substring(i + 2, i + 3), 16); r = (r << 4) | r; g = (g << 4) | g; b = (b << 4) | b; } else if(len == 6) { r = Integer.parseInt(hex.substring(i + 0, i + 2), 16); g = Integer.parseInt(hex.substring(i + 2, i + 4), 16); b = Integer.parseInt(hex.substring(i + 4, i + 6), 16); } } int getRed() { return r; } int getGreen() { return g; } int getBlue() { return b; } } libcobra-java-0.98.4.orig/src/com/steadystate/css/ParseException.java0000644000175000017500000000031310434145436025471 0ustar twernertwerner/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 0.7pre6 */ package com.steadystate.css; public class ParseException extends com.steadystate.css.parser.ParseException { } libcobra-java-0.98.4.orig/src/com/steadystate/css/RGBColorImpl.java0000644000175000017500000000446010434145436025002 0ustar twernertwerner/* * RGBColorImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk */ package com.steadystate.css; import org.w3c.css.sac.*; import org.w3c.dom.css.CSSPrimitiveValue; import com.steadystate.css.dom.CSSValueImpl; import com.steadystate.css.parser.*; /** * * @author David Schweinsberg * @version $Release$ * @deprecated As of 0.9.0, replaced by {@link com.steadystate.css.dom.RGBColorImpl} */ public class RGBColorImpl extends com.steadystate.css.dom.RGBColorImpl { protected RGBColorImpl(HexColor h) { setRed(new CSSValueImpl( LexicalUnitImpl.createNumber(null, h.getRed()), true)); setGreen(new CSSValueImpl( LexicalUnitImpl.createNumber(null, h.getGreen()), true)); setBlue(new CSSValueImpl( LexicalUnitImpl.createNumber(null, h.getBlue()), true)); } /* protected RGBColorImpl( CSSValue value ) { if( value.getValueType() != CSSValue.CSS_VALUE_LIST ) return; CSSValueList vl = (CSSValueList) value; if( vl.getLength() != 3 ) return; _red = (CSSPrimitiveValue) vl.item( 0 ); _green = (CSSPrimitiveValue) vl.item( 1 ); _blue = (CSSPrimitiveValue) vl.item( 2 ); } */ } libcobra-java-0.98.4.orig/src/com/steadystate/css/dom/0000755000175000017500000000000010630473006022452 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/com/steadystate/css/dom/CSS2PropertiesImpl.java0000644000175000017500000004653210737110114026734 0ustar twernertwerner/* * CSS2PropertiesImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: CSS2PropertiesImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.dom; import java.io.Serializable; import org.w3c.dom.*; import org.w3c.dom.css.*; /** * * @author David * @version */ public class CSS2PropertiesImpl implements CSS2Properties, Serializable { /** Creates new CSS2PropertiesImpl */ public CSS2PropertiesImpl() { } public String getAzimuth() { return null; } public void setAzimuth(String azimuth) throws DOMException { } public String getBackground() { return null; } public void setBackground(String background) throws DOMException { } public String getBackgroundAttachment() { return null; } public void setBackgroundAttachment(String backgroundAttachment) throws DOMException { } public String getBackgroundColor() { return null; } public void setBackgroundColor(String backgroundColor) throws DOMException { } public String getBackgroundImage() { return null; } public void setBackgroundImage(String backgroundImage) throws DOMException { } public String getBackgroundPosition() { return null; } public void setBackgroundPosition(String backgroundPosition) throws DOMException { } public String getBackgroundRepeat() { return null; } public void setBackgroundRepeat(String backgroundRepeat) throws DOMException { } public String getBorder() { return null; } public void setBorder(String border) throws DOMException { } public String getBorderCollapse() { return null; } public void setBorderCollapse(String borderCollapse) throws DOMException { } public String getBorderColor() { return null; } public void setBorderColor(String borderColor) throws DOMException { } public String getBorderSpacing() { return null; } public void setBorderSpacing(String borderSpacing) throws DOMException { } public String getBorderStyle() { return null; } public void setBorderStyle(String borderStyle) throws DOMException { } public String getBorderTop() { return null; } public void setBorderTop(String borderTop) throws DOMException { } public String getBorderRight() { return null; } public void setBorderRight(String borderRight) throws DOMException { } public String getBorderBottom() { return null; } public void setBorderBottom(String borderBottom) throws DOMException { } public String getBorderLeft() { return null; } public void setBorderLeft(String borderLeft) throws DOMException { } public String getBorderTopColor() { return null; } public void setBorderTopColor(String borderTopColor) throws DOMException { } public String getBorderRightColor() { return null; } public void setBorderRightColor(String borderRightColor) throws DOMException { } public String getBorderBottomColor() { return null; } public void setBorderBottomColor(String borderBottomColor) throws DOMException { } public String getBorderLeftColor() { return null; } public void setBorderLeftColor(String borderLeftColor) throws DOMException { } public String getBorderTopStyle() { return null; } public void setBorderTopStyle(String borderTopStyle) throws DOMException { } public String getBorderRightStyle() { return null; } public void setBorderRightStyle(String borderRightStyle) throws DOMException { } public String getBorderBottomStyle() { return null; } public void setBorderBottomStyle(String borderBottomStyle) throws DOMException { } public String getBorderLeftStyle() { return null; } public void setBorderLeftStyle(String borderLeftStyle) throws DOMException { } public String getBorderTopWidth() { return null; } public void setBorderTopWidth(String borderTopWidth) throws DOMException { } public String getBorderRightWidth() { return null; } public void setBorderRightWidth(String borderRightWidth) throws DOMException { } public String getBorderBottomWidth() { return null; } public void setBorderBottomWidth(String borderBottomWidth) throws DOMException { } public String getBorderLeftWidth() { return null; } public void setBorderLeftWidth(String borderLeftWidth) throws DOMException { } public String getBorderWidth() { return null; } public void setBorderWidth(String borderWidth) throws DOMException { } public String getBottom() { return null; } public void setBottom(String bottom) throws DOMException { } public String getCaptionSide() { return null; } public void setCaptionSide(String captionSide) throws DOMException { } public String getClear() { return null; } public void setClear(String clear) throws DOMException { } public String getClip() { return null; } public void setClip(String clip) throws DOMException { } public String getColor() { return null; } public void setColor(String color) throws DOMException { } public String getContent() { return null; } public void setContent(String content) throws DOMException { } public String getCounterIncrement() { return null; } public void setCounterIncrement(String counterIncrement) throws DOMException { } public String getCounterReset() { return null; } public void setCounterReset(String counterReset) throws DOMException { } public String getCue() { return null; } public void setCue(String cue) throws DOMException { } public String getCueAfter() { return null; } public void setCueAfter(String cueAfter) throws DOMException { } public String getCueBefore() { return null; } public void setCueBefore(String cueBefore) throws DOMException { } public String getCursor() { return null; } public void setCursor(String cursor) throws DOMException { } public String getDirection() { return null; } public void setDirection(String direction) throws DOMException { } public String getDisplay() { return null; } public void setDisplay(String display) throws DOMException { } public String getElevation() { return null; } public void setElevation(String elevation) throws DOMException { } public String getEmptyCells() { return null; } public void setEmptyCells(String emptyCells) throws DOMException { } public String getCssFloat() { return null; } public void setCssFloat(String cssFloat) throws DOMException { } public String getFont() { return null; } public void setFont(String font) throws DOMException { } public String getFontFamily() { return null; } public void setFontFamily(String fontFamily) throws DOMException { } public String getFontSize() { return null; } public void setFontSize(String fontSize) throws DOMException { } public String getFontSizeAdjust() { return null; } public void setFontSizeAdjust(String fontSizeAdjust) throws DOMException { } public String getFontStretch() { return null; } public void setFontStretch(String fontStretch) throws DOMException { } public String getFontStyle() { return null; } public void setFontStyle(String fontStyle) throws DOMException { } public String getFontVariant() { return null; } public void setFontVariant(String fontVariant) throws DOMException { } public String getFontWeight() { return null; } public void setFontWeight(String fontWeight) throws DOMException { } public String getHeight() { return null; } public void setHeight(String height) throws DOMException { } public String getLeft() { return null; } public void setLeft(String left) throws DOMException { } public String getLetterSpacing() { return null; } public void setLetterSpacing(String letterSpacing) throws DOMException { } public String getLineHeight() { return null; } public void setLineHeight(String lineHeight) throws DOMException { } public String getListStyle() { return null; } public void setListStyle(String listStyle) throws DOMException { } public String getListStyleImage() { return null; } public void setListStyleImage(String listStyleImage) throws DOMException { } public String getListStylePosition() { return null; } public void setListStylePosition(String listStylePosition) throws DOMException { } public String getListStyleType() { return null; } public void setListStyleType(String listStyleType) throws DOMException { } public String getMargin() { return null; } public void setMargin(String margin) throws DOMException { } public String getMarginTop() { return null; } public void setMarginTop(String marginTop) throws DOMException { } public String getMarginRight() { return null; } public void setMarginRight(String marginRight) throws DOMException { } public String getMarginBottom() { return null; } public void setMarginBottom(String marginBottom) throws DOMException { } public String getMarginLeft() { return null; } public void setMarginLeft(String marginLeft) throws DOMException { } public String getMarkerOffset() { return null; } public void setMarkerOffset(String markerOffset) throws DOMException { } public String getMarks() { return null; } public void setMarks(String marks) throws DOMException { } public String getMaxHeight() { return null; } public void setMaxHeight(String maxHeight) throws DOMException { } public String getMaxWidth() { return null; } public void setMaxWidth(String maxWidth) throws DOMException { } public String getMinHeight() { return null; } public void setMinHeight(String minHeight) throws DOMException { } public String getMinWidth() { return null; } public void setMinWidth(String minWidth) throws DOMException { } public String getOrphans() { return null; } public void setOrphans(String orphans) throws DOMException { } public String getOutline() { return null; } public void setOutline(String outline) throws DOMException { } public String getOutlineColor() { return null; } public void setOutlineColor(String outlineColor) throws DOMException { } public String getOutlineStyle() { return null; } public void setOutlineStyle(String outlineStyle) throws DOMException { } public String getOutlineWidth() { return null; } public void setOutlineWidth(String outlineWidth) throws DOMException { } public String getOverflow() { return null; } public void setOverflow(String overflow) throws DOMException { } public String getPadding() { return null; } public void setPadding(String padding) throws DOMException { } public String getPaddingTop() { return null; } public void setPaddingTop(String paddingTop) throws DOMException { } public String getPaddingRight() { return null; } public void setPaddingRight(String paddingRight) throws DOMException { } public String getPaddingBottom() { return null; } public void setPaddingBottom(String paddingBottom) throws DOMException { } public String getPaddingLeft() { return null; } public void setPaddingLeft(String paddingLeft) throws DOMException { } public String getPage() { return null; } public void setPage(String page) throws DOMException { } public String getPageBreakAfter() { return null; } public void setPageBreakAfter(String pageBreakAfter) throws DOMException { } public String getPageBreakBefore() { return null; } public void setPageBreakBefore(String pageBreakBefore) throws DOMException { } public String getPageBreakInside() { return null; } public void setPageBreakInside(String pageBreakInside) throws DOMException { } public String getPause() { return null; } public void setPause(String pause) throws DOMException { } public String getPauseAfter() { return null; } public void setPauseAfter(String pauseAfter) throws DOMException { } public String getPauseBefore() { return null; } public void setPauseBefore(String pauseBefore) throws DOMException { } public String getPitch() { return null; } public void setPitch(String pitch) throws DOMException { } public String getPitchRange() { return null; } public void setPitchRange(String pitchRange) throws DOMException { } public String getPlayDuring() { return null; } public void setPlayDuring(String playDuring) throws DOMException { } public String getPosition() { return null; } public void setPosition(String position) throws DOMException { } public String getQuotes() { return null; } public void setQuotes(String quotes) throws DOMException { } public String getRichness() { return null; } public void setRichness(String richness) throws DOMException { } public String getRight() { return null; } public void setRight(String right) throws DOMException { } public String getSize() { return null; } public void setSize(String size) throws DOMException { } public String getSpeak() { return null; } public void setSpeak(String speak) throws DOMException { } public String getSpeakHeader() { return null; } public void setSpeakHeader(String speakHeader) throws DOMException { } public String getSpeakNumeral() { return null; } public void setSpeakNumeral(String speakNumeral) throws DOMException { } public String getSpeakPunctuation() { return null; } public void setSpeakPunctuation(String speakPunctuation) throws DOMException { } public String getSpeechRate() { return null; } public void setSpeechRate(String speechRate) throws DOMException { } public String getStress() { return null; } public void setStress(String stress) throws DOMException { } public String getTableLayout() { return null; } public void setTableLayout(String tableLayout) throws DOMException { } public String getTextAlign() { return null; } public void setTextAlign(String textAlign) throws DOMException { } public String getTextDecoration() { return null; } public void setTextDecoration(String textDecoration) throws DOMException { } public String getTextIndent() { return null; } public void setTextIndent(String textIndent) throws DOMException { } public String getTextShadow() { return null; } public void setTextShadow(String textShadow) throws DOMException { } public String getTextTransform() { return null; } public void setTextTransform(String textTransform) throws DOMException { } public String getTop() { return null; } public void setTop(String top) throws DOMException { } public String getUnicodeBidi() { return null; } public void setUnicodeBidi(String unicodeBidi) throws DOMException { } public String getVerticalAlign() { return null; } public void setVerticalAlign(String verticalAlign) throws DOMException { } public String getVisibility() { return null; } public void setVisibility(String visibility) throws DOMException { } public String getVoiceFamily() { return null; } public void setVoiceFamily(String voiceFamily) throws DOMException { } public String getVolume() { return null; } public void setVolume(String volume) throws DOMException { } public String getWhiteSpace() { return null; } public void setWhiteSpace(String whiteSpace) throws DOMException { } public String getWidows() { return null; } public void setWidows(String widows) throws DOMException { } public String getWidth() { return null; } public void setWidth(String width) throws DOMException { } public String getWordSpacing() { return null; } public void setWordSpacing(String wordSpacing) throws DOMException { } public String getZIndex() { return null; } public void setZIndex(String zIndex) throws DOMException { } }libcobra-java-0.98.4.orig/src/com/steadystate/css/dom/CSSCharsetRuleImpl.java0000644000175000017500000000730610737110114026733 0ustar twernertwerner/* * CSSCharsetRule.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: CSSCharsetRuleImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.dom; import java.io.IOException; import java.io.Serializable; import java.io.StringReader; import org.w3c.dom.*; import org.w3c.dom.css.*; import org.w3c.css.sac.*; import com.steadystate.css.parser.*; /** * * @author David Schweinsberg * @version $Release$ */ public class CSSCharsetRuleImpl implements CSSCharsetRule, Serializable { CSSStyleSheetImpl _parentStyleSheet = null; CSSRule _parentRule = null; String _encoding = null; public CSSCharsetRuleImpl( CSSStyleSheetImpl parentStyleSheet, CSSRule parentRule, String encoding) { _parentStyleSheet = parentStyleSheet; _parentRule = parentRule; _encoding = encoding; } public short getType() { return CHARSET_RULE; } public String getCssText() { return "@charset \"" + getEncoding() + "\";"; } public void setCssText(String cssText) throws DOMException { if (_parentStyleSheet != null && _parentStyleSheet.isReadOnly()) { throw new DOMExceptionImpl( DOMException.NO_MODIFICATION_ALLOWED_ERR, DOMExceptionImpl.READ_ONLY_STYLE_SHEET); } try { InputSource is = new InputSource(new StringReader(cssText)); CSSOMParser parser = new CSSOMParser(); CSSRule r = parser.parseRule(is); // The rule must be a charset rule if (r.getType() == CSSRule.CHARSET_RULE) { _encoding = ((CSSCharsetRuleImpl)r)._encoding; } else { throw new DOMExceptionImpl( DOMException.INVALID_MODIFICATION_ERR, DOMExceptionImpl.EXPECTING_CHARSET_RULE); } } catch (CSSException e) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage()); } catch (IOException e) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage()); } } public CSSStyleSheet getParentStyleSheet() { return _parentStyleSheet; } public CSSRule getParentRule() { return _parentRule; } public String getEncoding() { return _encoding; } public void setEncoding(String encoding) throws DOMException { _encoding = encoding; } } libcobra-java-0.98.4.orig/src/com/steadystate/css/dom/CSSFontFaceRuleImpl.java0000644000175000017500000000712510737110114027026 0ustar twernertwerner/* * CSSFontFaceRuleImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: CSSFontFaceRuleImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.dom; import java.io.IOException; import java.io.Serializable; import java.io.StringReader; import org.w3c.dom.*; import org.w3c.dom.css.*; import org.w3c.css.sac.*; import com.steadystate.css.parser.*; public class CSSFontFaceRuleImpl implements CSSFontFaceRule, Serializable { private CSSStyleSheetImpl _parentStyleSheet = null; private CSSRule _parentRule = null; private CSSStyleDeclarationImpl _style = null; public CSSFontFaceRuleImpl(CSSStyleSheetImpl parentStyleSheet, CSSRule parentRule) { _parentStyleSheet = parentStyleSheet; _parentRule = parentRule; } public short getType() { return FONT_FACE_RULE; } public String getCssText() { return "@font-face " + getStyle().getCssText(); } public void setCssText(String cssText) throws DOMException { if (_parentStyleSheet != null && _parentStyleSheet.isReadOnly()) { throw new DOMExceptionImpl( DOMException.NO_MODIFICATION_ALLOWED_ERR, DOMExceptionImpl.READ_ONLY_STYLE_SHEET); } try { InputSource is = new InputSource(new StringReader(cssText)); CSSOMParser parser = new CSSOMParser(); CSSRule r = parser.parseRule(is); // The rule must be a font face rule if (r.getType() == CSSRule.FONT_FACE_RULE) { _style = ((CSSFontFaceRuleImpl)r)._style; } else { throw new DOMExceptionImpl( DOMException.INVALID_MODIFICATION_ERR, DOMExceptionImpl.EXPECTING_FONT_FACE_RULE); } } catch (CSSException e) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage()); } catch (IOException e) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage()); } } public CSSStyleSheet getParentStyleSheet() { return _parentStyleSheet; } public CSSRule getParentRule() { return _parentRule; } public CSSStyleDeclaration getStyle() { return _style; } public void setStyle(CSSStyleDeclarationImpl style) { _style = style; } } libcobra-java-0.98.4.orig/src/com/steadystate/css/dom/CSSImportRuleImpl.java0000644000175000017500000001034610737110114026612 0ustar twernertwerner/* * CSSImportRuleImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: CSSImportRuleImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.dom; import java.io.IOException; import java.io.Serializable; import java.io.StringReader; import org.w3c.dom.*; import org.w3c.dom.stylesheets.*; import org.w3c.dom.css.*; import org.w3c.css.sac.*; import com.steadystate.css.parser.*; /** * TODO: * Implement getStyleSheet() * * @author David Schweinsberg * @version $Release$ */ public class CSSImportRuleImpl implements CSSImportRule, Serializable { CSSStyleSheetImpl _parentStyleSheet = null; CSSRule _parentRule = null; String _href = null; MediaList _media = null; public CSSImportRuleImpl( CSSStyleSheetImpl parentStyleSheet, CSSRule parentRule, String href, MediaList media) { _parentStyleSheet = parentStyleSheet; _parentRule = parentRule; _href = href; _media = media; } public short getType() { return IMPORT_RULE; } public String getCssText() { StringBuffer sb = new StringBuffer(); sb.append("@import url(") .append(getHref()) .append(")"); if (getMedia().getLength() > 0) { sb.append(" ").append(getMedia().toString()); } sb.append(";"); return sb.toString(); } public void setCssText(String cssText) throws DOMException { if (_parentStyleSheet != null && _parentStyleSheet.isReadOnly()) { throw new DOMExceptionImpl( DOMException.NO_MODIFICATION_ALLOWED_ERR, DOMExceptionImpl.READ_ONLY_STYLE_SHEET); } try { InputSource is = new InputSource(new StringReader(cssText)); CSSOMParser parser = new CSSOMParser(); CSSRule r = parser.parseRule(is); // The rule must be an import rule if (r.getType() == CSSRule.IMPORT_RULE) { _href = ((CSSImportRuleImpl)r)._href; _media = ((CSSImportRuleImpl)r)._media; } else { throw new DOMExceptionImpl( DOMException.INVALID_MODIFICATION_ERR, DOMExceptionImpl.EXPECTING_IMPORT_RULE); } } catch (CSSException e) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage()); } catch (IOException e) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage()); } } public CSSStyleSheet getParentStyleSheet() { return _parentStyleSheet; } public CSSRule getParentRule() { return _parentRule; } public String getHref() { return _href; } public MediaList getMedia() { return _media; } public CSSStyleSheet getStyleSheet() { return null; } public String toString() { return getCssText(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/dom/CSSMediaRuleImpl.java0000644000175000017500000001434410737110114026361 0ustar twernertwerner/* * CSSMediaRuleImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: CSSMediaRuleImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.dom; import java.io.IOException; import java.io.Serializable; import java.io.StringReader; import org.w3c.dom.*; import org.w3c.dom.stylesheets.*; import org.w3c.dom.css.*; import org.w3c.css.sac.*; import com.steadystate.css.parser.*; /** * * @author David Schweinsberg * @version $Release$ */ public class CSSMediaRuleImpl implements CSSMediaRule, Serializable { private CSSStyleSheetImpl _parentStyleSheet = null; private CSSRule _parentRule = null; private MediaList _media = null; private CSSRuleList _rules = null; public CSSMediaRuleImpl( CSSStyleSheetImpl parentStyleSheet, CSSRule parentRule, MediaList media) { _parentStyleSheet = parentStyleSheet; _parentRule = parentRule; _media = media; } public short getType() { return MEDIA_RULE; } public String getCssText() { StringBuffer sb = new StringBuffer("@media "); sb.append(getMedia().toString()).append(" {"); for (int i = 0; i < getCssRules().getLength(); i++) { CSSRule rule = getCssRules().item(i); sb.append(rule.getCssText()).append(" "); } sb.append("}"); return sb.toString(); } public void setCssText(String cssText) throws DOMException { if (_parentStyleSheet != null && _parentStyleSheet.isReadOnly()) { throw new DOMExceptionImpl( DOMException.NO_MODIFICATION_ALLOWED_ERR, DOMExceptionImpl.READ_ONLY_STYLE_SHEET); } try { InputSource is = new InputSource(new StringReader(cssText)); CSSOMParser parser = new CSSOMParser(); CSSRule r = parser.parseRule(is); // The rule must be a media rule if (r.getType() == CSSRule.MEDIA_RULE) { _media = ((CSSMediaRuleImpl)r)._media; _rules = ((CSSMediaRuleImpl)r)._rules; } else { throw new DOMExceptionImpl( DOMException.INVALID_MODIFICATION_ERR, DOMExceptionImpl.EXPECTING_MEDIA_RULE); } } catch (CSSException e) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage()); } catch (IOException e) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage()); } } public CSSStyleSheet getParentStyleSheet() { return _parentStyleSheet; } public CSSRule getParentRule() { return _parentRule; } public MediaList getMedia() { return _media; } public CSSRuleList getCssRules() { return _rules; } public int insertRule(String rule, int index) throws DOMException { if (_parentStyleSheet != null && _parentStyleSheet.isReadOnly()) { throw new DOMExceptionImpl( DOMException.NO_MODIFICATION_ALLOWED_ERR, DOMExceptionImpl.READ_ONLY_STYLE_SHEET); } try { InputSource is = new InputSource(new StringReader(rule)); CSSOMParser parser = new CSSOMParser(); parser.setParentStyleSheet(_parentStyleSheet); //parser.setParentRule(_parentRule); CSSRule r = parser.parseRule(is); // Insert the rule into the list of rules ((CSSRuleListImpl)getCssRules()).insert(r, index); } catch (ArrayIndexOutOfBoundsException e) { throw new DOMExceptionImpl( DOMException.INDEX_SIZE_ERR, DOMExceptionImpl.ARRAY_OUT_OF_BOUNDS, e.getMessage()); } catch (CSSException e) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage()); } catch (IOException e) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage()); } return index; } public void deleteRule(int index) throws DOMException { if (_parentStyleSheet != null && _parentStyleSheet.isReadOnly()) { throw new DOMExceptionImpl( DOMException.NO_MODIFICATION_ALLOWED_ERR, DOMExceptionImpl.READ_ONLY_STYLE_SHEET); } try { ((CSSRuleListImpl)getCssRules()).delete(index); } catch (ArrayIndexOutOfBoundsException e) { throw new DOMExceptionImpl( DOMException.INDEX_SIZE_ERR, DOMExceptionImpl.ARRAY_OUT_OF_BOUNDS, e.getMessage()); } } public void setRuleList(CSSRuleListImpl rules) { _rules = rules; } public String toString() { return getCssText(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/dom/CSSPageRuleImpl.java0000644000175000017500000001077110737110114026216 0ustar twernertwerner/* * CSSPageRuleImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: CSSPageRuleImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.dom; import java.io.IOException; import java.io.Serializable; import java.io.StringReader; import org.w3c.dom.*; import org.w3c.dom.css.*; import org.w3c.css.sac.*; import com.steadystate.css.parser.*; /** * TO DO: * Implement setSelectorText() * * @author David Schweinsberg * @version $Release$ */ public class CSSPageRuleImpl implements CSSPageRule, Serializable { private CSSStyleSheetImpl _parentStyleSheet = null; private CSSRule _parentRule = null; private String _ident = null; private String _pseudoPage = null; private CSSStyleDeclaration _style = null; public CSSPageRuleImpl( CSSStyleSheetImpl parentStyleSheet, CSSRule parentRule, String ident, String pseudoPage) { _parentStyleSheet = parentStyleSheet; _parentRule = parentRule; _ident = ident; _pseudoPage = pseudoPage; } public short getType() { return PAGE_RULE; } public String getCssText() { String sel = getSelectorText(); return "@page " + sel + ((sel.length() > 0) ? " " : "") + getStyle().getCssText(); } public void setCssText(String cssText) throws DOMException { if (_parentStyleSheet != null && _parentStyleSheet.isReadOnly()) { throw new DOMExceptionImpl( DOMException.NO_MODIFICATION_ALLOWED_ERR, DOMExceptionImpl.READ_ONLY_STYLE_SHEET); } try { InputSource is = new InputSource(new StringReader(cssText)); CSSOMParser parser = new CSSOMParser(); CSSRule r = parser.parseRule(is); // The rule must be a page rule if (r.getType() == CSSRule.PAGE_RULE) { _ident = ((CSSPageRuleImpl)r)._ident; _pseudoPage = ((CSSPageRuleImpl)r)._pseudoPage; _style = ((CSSPageRuleImpl)r)._style; } else { throw new DOMExceptionImpl( DOMException.INVALID_MODIFICATION_ERR, DOMExceptionImpl.EXPECTING_PAGE_RULE); } } catch (CSSException e) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage()); } catch (IOException e) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage()); } } public CSSStyleSheet getParentStyleSheet() { return _parentStyleSheet; } public CSSRule getParentRule() { return _parentRule; } public String getSelectorText() { return ((_ident != null) ? _ident : "") + ((_pseudoPage != null) ? ":" + _pseudoPage : ""); } public void setSelectorText(String selectorText) throws DOMException { } public CSSStyleDeclaration getStyle() { return _style; } protected void setIdent(String ident) { _ident = ident; } protected void setPseudoPage(String pseudoPage) { _pseudoPage = pseudoPage; } public void setStyle(CSSStyleDeclarationImpl style) { _style = style; } } libcobra-java-0.98.4.orig/src/com/steadystate/css/dom/CSSRuleListImpl.java0000644000175000017500000000461410737110114026254 0ustar twernertwerner/* * CSSRuleListImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: CSSRuleListImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.dom; import java.io.Serializable; import java.util.Vector; import org.w3c.dom.css.*; public class CSSRuleListImpl implements CSSRuleList, Serializable { private Vector _rules = null; public CSSRuleListImpl() { } public int getLength() { return (_rules != null) ? _rules.size() : 0; } public CSSRule item(int index) { return (_rules != null) ? (CSSRule) _rules.elementAt(index) : null; } public void add(CSSRule rule) { if (_rules == null) { _rules = new Vector(); } _rules.addElement(rule); } public void insert(CSSRule rule, int index) { if (_rules == null) { _rules = new Vector(); } _rules.insertElementAt(rule, index); } public void delete(int index) { if (_rules == null) { _rules = new Vector(); } _rules.removeElementAt(index); } public String toString() { StringBuffer sb = new StringBuffer(); for (int i = 0; i < getLength(); i++ ) { sb.append(item(i).toString()).append("\r\n"); } return sb.toString(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/dom/CSSStyleDeclarationImpl.java0000644000175000017500000001340410773711566027776 0ustar twernertwerner/* * CSSStyleDeclarationImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: CSSStyleDeclarationImpl.java,v 1.10 2008/02/02 19:55:23 xamjadmin Exp $ */ package com.steadystate.css.dom; import java.io.Serializable; import java.io.StringReader; import java.util.*; import org.w3c.css.sac.*; import org.w3c.dom.*; import org.w3c.dom.css.*; import com.steadystate.css.parser.*; /** * @author David Schweinsberg * @version $Release$ */ public class CSSStyleDeclarationImpl implements CSSStyleDeclaration, Serializable { private final CSSRule _parentRule; private final ArrayList _properties = new ArrayList(4); private final Map _propertiesMap = new HashMap(6); public CSSStyleDeclarationImpl(CSSRule parentRule) { _parentRule = parentRule; } public String getCssText() { StringBuffer sb = new StringBuffer(); sb.append("{"); //if newlines requested in text //sb.append("\n"); ArrayList props = this._properties; int size = props.size(); for (int i = 0; i < size; ++i) { Property p = (Property) props.get(i); if (p != null) { sb.append(p.toString()); } if (i < size - 1) { sb.append("; "); } //if newlines requested in text //sb.append("\n"); } sb.append("}"); return sb.toString(); } public void setCssText(String cssText) throws DOMException { try { InputSource is = new InputSource(new StringReader(cssText)); CSSOMParser parser = new CSSOMParser(); this._properties.clear(); this._propertiesMap.clear(); parser.parseStyleDeclaration(this, is); } catch (Exception e) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage()); } } public String getPropertyValue(String propertyName) { Property p = getPropertyDeclaration(propertyName); return (p != null) ? p.getValue().getCssText() : ""; } public CSSValue getPropertyCSSValue(String propertyName) { Property p = getPropertyDeclaration(propertyName); return (p != null) ? p.getValue() : null; } public String removeProperty(String propertyName) throws DOMException { Map propsMap = this._propertiesMap; Property prop = (Property) propsMap.remove(propertyName.toLowerCase()); if(prop != null) { this._properties.remove(prop); CSSValue value = prop.getValue(); return value == null ? "" : value.getCssText(); } return ""; } public String getPropertyPriority(String propertyName) { Property p = getPropertyDeclaration(propertyName); if (p != null) { return p.isImportant() ? "important" : ""; } else { return ""; } } public void setProperty( String propertyName, String value, String priority ) throws DOMException { try { InputSource is = new InputSource(new StringReader(value)); CSSOMParser parser = new CSSOMParser(); CSSValue expr = parser.parsePropertyValue(is); Property p = getPropertyDeclaration(propertyName); boolean important = (priority != null) ? priority.equalsIgnoreCase("important") : false; if (p == null) { p = new Property(propertyName, expr, important); addProperty(p); } else { p.setValue(expr); p.setImportant(important); } } catch (Exception e) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage()); } } public int getLength() { return _properties.size(); } public String item(int index) { Property p = (Property) _properties.get(index); return (p != null) ? p.getName() : ""; } public CSSRule getParentRule() { return _parentRule; } public void addProperty(Property p) { _propertiesMap.put(p.getName().toLowerCase(), p); _properties.add(p); } private Property getPropertyDeclaration(String name) { // Must visit from last to first. Bbc.co.uk is a // site that has multiple property names in one declaration. return (Property) this._propertiesMap.get(name.toLowerCase()); } public String toString() { return this.getCssText(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/dom/CSSStyleRuleImpl.java0000644000175000017500000001156610737110114026445 0ustar twernertwerner/* * CSSStyleRuleImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: CSSStyleRuleImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.dom; import java.io.IOException; import java.io.Serializable; import java.io.StringReader; import org.w3c.dom.*; import org.w3c.dom.css.*; import org.w3c.css.sac.*; import com.steadystate.css.parser.*; /** * * @author David Schweinsberg * @version $Release$ */ public class CSSStyleRuleImpl implements CSSStyleRule, Serializable { private CSSStyleSheetImpl _parentStyleSheet = null; private CSSRule _parentRule = null; private SelectorList _selectors = null; private CSSStyleDeclaration _style = null; public CSSStyleRuleImpl(CSSStyleSheetImpl parentStyleSheet, CSSRule parentRule, SelectorList selectors) { _parentStyleSheet = parentStyleSheet; _parentRule = parentRule; _selectors = selectors; } public short getType() { return STYLE_RULE; } public String getCssText() { return getSelectorText() + " " + getStyle().toString(); } public void setCssText(String cssText) throws DOMException { if (_parentStyleSheet != null && _parentStyleSheet.isReadOnly()) { throw new DOMExceptionImpl( DOMException.NO_MODIFICATION_ALLOWED_ERR, DOMExceptionImpl.READ_ONLY_STYLE_SHEET); } try { InputSource is = new InputSource(new StringReader(cssText)); CSSOMParser parser = new CSSOMParser(); CSSRule r = parser.parseRule(is); // The rule must be a style rule if (r.getType() == CSSRule.STYLE_RULE) { _selectors = ((CSSStyleRuleImpl)r)._selectors; _style = ((CSSStyleRuleImpl)r)._style; } else { throw new DOMExceptionImpl( DOMException.INVALID_MODIFICATION_ERR, DOMExceptionImpl.EXPECTING_STYLE_RULE); } } catch (CSSException e) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage()); } catch (IOException e) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage()); } } public CSSStyleSheet getParentStyleSheet() { return _parentStyleSheet; } public CSSRule getParentRule() { return _parentRule; } public String getSelectorText() { return _selectors.toString(); } public void setSelectorText(String selectorText) throws DOMException { if (_parentStyleSheet != null && _parentStyleSheet.isReadOnly()) { throw new DOMExceptionImpl( DOMException.NO_MODIFICATION_ALLOWED_ERR, DOMExceptionImpl.READ_ONLY_STYLE_SHEET ); } try { InputSource is = new InputSource(new StringReader(selectorText)); CSSOMParser parser = new CSSOMParser(); _selectors = parser.parseSelectors(is); } catch (CSSException e) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage()); } catch (IOException e) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage()); } } public CSSStyleDeclaration getStyle() { return _style; } public void setStyle(CSSStyleDeclarationImpl style) { _style = style; } public String toString() { return getCssText(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/dom/CSSStyleSheetImpl.java0000644000175000017500000001677311047607504026624 0ustar twernertwerner/* * CSSStyleSheetImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: CSSStyleSheetImpl.java,v 1.5 2008/08/10 22:54:43 xamjadmin Exp $ */ package com.steadystate.css.dom; import java.io.IOException; import java.io.Serializable; import java.io.StringReader; import org.w3c.dom.*; import org.w3c.dom.stylesheets.*; import org.w3c.dom.css.*; import org.w3c.css.sac.*; import com.steadystate.css.parser.*; /** * TODO: Setting the media list * * @author David Schweinsberg * @version $Release$ */ public class CSSStyleSheetImpl implements CSSStyleSheet, Serializable { public static final String KEY_DISABLED_CHANGED = "styleSheet.disabled.changed"; private boolean _disabled = false; private Node _ownerNode = null; private StyleSheet _parentStyleSheet = null; private String _href = null; private String _title = null; private MediaList _media = null; private CSSRule _ownerRule = null; private boolean _readOnly = false; private CSSRuleListImpl _rules = null; public CSSStyleSheetImpl() { } public String getType() { return "text/css"; } public boolean getDisabled() { return _disabled; } /** * We will need to respond more fully if a stylesheet is disabled, probably * by generating an event for the main application. */ public void setDisabled(boolean disabled) { if(this._disabled != disabled) { _disabled = disabled; Node node = this.getOwnerNode(); if(node != null) { node.setUserData(KEY_DISABLED_CHANGED, Boolean.valueOf(disabled), null); } } } public void setDisabledOnly(boolean disabled) { this._disabled = disabled; } public Node getOwnerNode() { return _ownerNode; } public StyleSheet getParentStyleSheet() { return _parentStyleSheet; } public String getHref() { return _href; } public String getTitle() { return _title; } public MediaList getMedia() { return _media; } public CSSRule getOwnerRule() { return _ownerRule; } public CSSRuleList getCssRules() { return _rules; } public int insertRule(String rule, int index) throws DOMException { if (_readOnly) { throw new DOMExceptionImpl( DOMException.NO_MODIFICATION_ALLOWED_ERR, DOMExceptionImpl.READ_ONLY_STYLE_SHEET); } try { InputSource is = new InputSource(new StringReader(rule)); CSSOMParser parser = new CSSOMParser(); parser.setParentStyleSheet(this); CSSRule r = parser.parseRule(is); if (getCssRules().getLength() > 0) { // We need to check that this type of rule can legally go into // the requested position. int msg = -1; if (r.getType() == CSSRule.CHARSET_RULE) { // Index must be 0, and there can be only one charset rule if (index != 0) { msg = DOMExceptionImpl.CHARSET_NOT_FIRST; } else if (getCssRules().item(0).getType() == CSSRule.CHARSET_RULE) { msg = DOMExceptionImpl.CHARSET_NOT_UNIQUE; } } else if (r.getType() == CSSRule.IMPORT_RULE) { // Import rules must preceed all other rules (except // charset rules) if (index <= getCssRules().getLength()) { for (int i = 0; i < index; i++) { int rt = getCssRules().item(i).getType(); if ((rt != CSSRule.CHARSET_RULE) || (rt != CSSRule.IMPORT_RULE)) { msg = DOMExceptionImpl.IMPORT_NOT_FIRST; break; } } } } if (msg > -1) { throw new DOMExceptionImpl( DOMException.HIERARCHY_REQUEST_ERR, msg); } } // Insert the rule into the list of rules ((CSSRuleListImpl)getCssRules()).insert(r, index); } catch (ArrayIndexOutOfBoundsException e) { throw new DOMExceptionImpl( DOMException.INDEX_SIZE_ERR, DOMExceptionImpl.ARRAY_OUT_OF_BOUNDS, e.getMessage()); } catch (CSSException e) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage()); } catch (IOException e) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage()); } return index; } public void deleteRule(int index) throws DOMException { if (_readOnly) { throw new DOMExceptionImpl( DOMException.NO_MODIFICATION_ALLOWED_ERR, DOMExceptionImpl.READ_ONLY_STYLE_SHEET); } try { ((CSSRuleListImpl)getCssRules()).delete(index); } catch (ArrayIndexOutOfBoundsException e) { throw new DOMExceptionImpl( DOMException.INDEX_SIZE_ERR, DOMExceptionImpl.ARRAY_OUT_OF_BOUNDS, e.getMessage()); } } public boolean isReadOnly() { return _readOnly; } public void setReadOnly(boolean b) { _readOnly = b; } public void setOwnerNode(Node ownerNode) { _ownerNode = ownerNode; } public void setParentStyleSheet(StyleSheet parentStyleSheet) { _parentStyleSheet = parentStyleSheet; } public void setHref(String href) { _href = href; } public void setTitle(String title) { _title = title; } public void setMedia(String mediaText) { // MediaList _media = null; } public void setOwnerRule(CSSRule ownerRule) { _ownerRule = ownerRule; } public void setRuleList(CSSRuleListImpl rules) { _rules = rules; } public String toString() { return _rules.toString(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/dom/CSSUnknownRuleImpl.java0000644000175000017500000000707710737110114027006 0ustar twernertwerner/* * CSSUnknownRuleImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: CSSUnknownRuleImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.dom; import java.io.IOException; import java.io.Serializable; import java.io.StringReader; import org.w3c.dom.*; import org.w3c.dom.css.*; /* * * @author David Schweinsberg * @version $Release$ */ public class CSSUnknownRuleImpl implements CSSUnknownRule, Serializable { CSSStyleSheetImpl _parentStyleSheet = null; CSSRule _parentRule = null; String _text = null; public CSSUnknownRuleImpl( CSSStyleSheetImpl parentStyleSheet, CSSRule parentRule, String text) { _parentStyleSheet = parentStyleSheet; _parentRule = parentRule; _text = text; } public short getType() { return UNKNOWN_RULE; } public String getCssText() { return _text; } public void setCssText(String cssText) throws DOMException { /* if( _parentStyleSheet != null && _parentStyleSheet.isReadOnly() ) throw new DOMExceptionImpl( DOMException.NO_MODIFICATION_ALLOWED_ERR, DOMExceptionImpl.READ_ONLY_STYLE_SHEET ); try { // // Parse the rule string and retrieve the rule // StringReader sr = new StringReader( cssText ); CSS2Parser parser = new CSS2Parser( sr ); ASTStyleSheetRuleSingle ssrs = parser.styleSheetRuleSingle(); CSSRule r = (CSSRule) ssrs.jjtGetChild( 0 ); // // The rule must be an unknown rule // if( r.getType() == CSSRule.UNKNOWN_RULE ) { _text = ((ASTUnknownRule)r)._text; setChildren( ((SimpleNode)r).getChildren() ); } else { throw new DOMExceptionImpl( DOMException.INVALID_MODIFICATION_ERR, DOMExceptionImpl.EXPECTING_UNKNOWN_RULE ); } } catch( ParseException e ) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage() ); } */ } public CSSStyleSheet getParentStyleSheet() { return _parentStyleSheet; } public CSSRule getParentRule() { return _parentRule; } public String toString() { return getCssText(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/dom/CSSValueImpl.java0000644000175000017500000003444411134564236025603 0ustar twernertwerner/* * CSSValueImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: CSSValueImpl.java,v 1.9 2009/01/18 14:30:22 xamjadmin Exp $ */ package com.steadystate.css.dom; import java.util.logging.*; import java.io.IOException; import java.io.Serializable; import java.io.StringReader; import java.util.*; import org.w3c.css.sac.*; import org.w3c.dom.*; import org.w3c.dom.css.*; import com.steadystate.css.parser.CSSOMParser; import com.steadystate.css.parser.LexicalUnitImpl; /** * The CSSValueImpl class can represent either a * CSSPrimitiveValue or a CSSValueList so that * the type can successfully change when using setCssText. * * TO DO: * Float unit conversions, * A means of checking valid primitive types for properties * * @author David Schweinsberg * @version $Release$ */ public class CSSValueImpl implements CSSPrimitiveValue, CSSValueList, Serializable { private static final Logger logger = Logger.getLogger(CSSValueImpl.class.getName()); private Object _value = null; /** * Constructor */ public CSSValueImpl(LexicalUnit value, boolean forcePrimitive) { if(value == null) { _value = null; } else if (value.getParameters() != null) { if (value.getLexicalUnitType() == LexicalUnit.SAC_RECT_FUNCTION) { // Rect _value = new RectImpl(value.getParameters()); } else if (value.getLexicalUnitType() == LexicalUnit.SAC_RGBCOLOR) { // RGBColor _value = new RGBColorImpl(value.getParameters()); LexicalUnit nextValue; if((nextValue = value.getNextLexicalUnit()) != null) { Vector v = new Vector(); v.add(_value); while(nextValue != null) { if ((nextValue.getLexicalUnitType() != LexicalUnit.SAC_OPERATOR_COMMA) && (nextValue.getLexicalUnitType() != LexicalUnit.SAC_OPERATOR_SLASH)) { v.addElement(new CSSValueImpl(nextValue, true)); } nextValue = nextValue.getNextLexicalUnit(); } _value = v; } } else if (value.getLexicalUnitType() == LexicalUnit.SAC_COUNTER_FUNCTION) { // Counter _value = new CounterImpl(false, value.getParameters()); } else if (value.getLexicalUnitType() == LexicalUnit.SAC_COUNTERS_FUNCTION) { // Counter _value = new CounterImpl(true, value.getParameters()); } else { _value = value; } } else if (forcePrimitive || (value.getNextLexicalUnit() == null)) { // We need to be a CSSPrimitiveValue _value = value; } else { // We need to be a CSSValueList // Values in an "expr" can be seperated by "operator"s, which are // either '/' or ',' - ignore these operators Vector v = new Vector(); LexicalUnit lu = value; while (lu != null) { if ((lu.getLexicalUnitType() != LexicalUnit.SAC_OPERATOR_COMMA) && (lu.getLexicalUnitType() != LexicalUnit.SAC_OPERATOR_SLASH)) { v.addElement(new CSSValueImpl(lu, true)); } lu = lu.getNextLexicalUnit(); } _value = v; } } public CSSValueImpl(LexicalUnit value) { this(value, false); } private String toString(Object value) { if(value instanceof Vector) { StringBuffer sb = new StringBuffer(); Vector v = (Vector) value; int size = v.size(); boolean firstTime = true; for(int i = 0; i < size; i++) { Object element = v.elementAt(i); if (element instanceof CSSValueImpl) { Object itemValue = ((CSSValueImpl) element)._value; if(itemValue instanceof LexicalUnit) { LexicalUnit lu = (LexicalUnit) itemValue; if(lu != null) { if(firstTime) { firstTime = false; } else { sb.append(" "); } sb.append(lu.toString()); // See if there's a comma or slash after value. LexicalUnit potentialOp = lu.getNextLexicalUnit(); if(potentialOp != null) { int type = potentialOp.getLexicalUnitType(); switch(type) { case LexicalUnit.SAC_OPERATOR_COMMA: sb.append(","); break; case LexicalUnit.SAC_OPERATOR_SLASH: sb.append("/"); break; case LexicalUnit.SAC_OPERATOR_EQUALS: sb.append("="); break; } } } } else if(itemValue instanceof RGBColor) { if(firstTime) { firstTime = false; } else { sb.append(" "); } sb.append(itemValue.toString()); } else if(itemValue instanceof Vector) { if(firstTime) { firstTime = false; } else { sb.append(" "); } sb.append(this.toString(itemValue)); } else if(itemValue != null) { logger.warning("toString(): Unknown item value type: " + itemValue.getClass().getName()); } } else { if(element != null) { if(firstTime) { firstTime = false; } else { sb.append(" "); } sb.append(element.toString()); } } } return sb.toString(); } else { return String.valueOf(value); } } public String getCssText() { return this.toString(_value); } public void setCssText(String cssText) throws DOMException { try { InputSource is = new InputSource(new StringReader(cssText)); CSSOMParser parser = new CSSOMParser(); CSSValueImpl v2 = (CSSValueImpl) parser.parsePropertyValue(is); _value = v2._value; } catch (Exception e) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage() ); } } public short getCssValueType() { return (_value instanceof Vector) ? CSS_VALUE_LIST : CSS_PRIMITIVE_VALUE; } public short getPrimitiveType() { if (_value instanceof LexicalUnit) { LexicalUnit lu = (LexicalUnit) _value; switch (lu.getLexicalUnitType()) { case LexicalUnit.SAC_INHERIT: return CSS_IDENT; case LexicalUnit.SAC_INTEGER: case LexicalUnit.SAC_REAL: return CSS_NUMBER; case LexicalUnit.SAC_EM: return CSS_EMS; case LexicalUnit.SAC_EX: return CSS_EXS; case LexicalUnit.SAC_PIXEL: return CSS_PX; case LexicalUnit.SAC_INCH: return CSS_IN; case LexicalUnit.SAC_CENTIMETER: return CSS_CM; case LexicalUnit.SAC_MILLIMETER: return CSS_MM; case LexicalUnit.SAC_POINT: return CSS_PT; case LexicalUnit.SAC_PICA: return CSS_PC; case LexicalUnit.SAC_PERCENTAGE: return CSS_PERCENTAGE; case LexicalUnit.SAC_URI: return CSS_URI; // case LexicalUnit.SAC_COUNTER_FUNCTION: // case LexicalUnit.SAC_COUNTERS_FUNCTION: // return CSS_COUNTER; // case LexicalUnit.SAC_RGBCOLOR: // return CSS_RGBCOLOR; case LexicalUnit.SAC_DEGREE: return CSS_DEG; case LexicalUnit.SAC_GRADIAN: return CSS_GRAD; case LexicalUnit.SAC_RADIAN: return CSS_RAD; case LexicalUnit.SAC_MILLISECOND: return CSS_MS; case LexicalUnit.SAC_SECOND: return CSS_S; case LexicalUnit.SAC_HERTZ: return CSS_KHZ; case LexicalUnit.SAC_KILOHERTZ: return CSS_HZ; case LexicalUnit.SAC_IDENT: return CSS_IDENT; case LexicalUnit.SAC_STRING_VALUE: return CSS_STRING; case LexicalUnit.SAC_ATTR: return CSS_ATTR; // case LexicalUnit.SAC_RECT_FUNCTION: // return CSS_RECT; case LexicalUnit.SAC_UNICODERANGE: case LexicalUnit.SAC_SUB_EXPRESSION: case LexicalUnit.SAC_FUNCTION: return CSS_STRING; case LexicalUnit.SAC_DIMENSION: return CSS_DIMENSION; } } else if (_value instanceof RectImpl) { return CSS_RECT; } else if (_value instanceof RGBColorImpl) { return CSS_RGBCOLOR; } else if (_value instanceof CounterImpl) { return CSS_COUNTER; } return CSS_UNKNOWN; } public void setFloatValue(short unitType, float floatValue) throws DOMException { _value = LexicalUnitImpl.createNumber(null, floatValue); } public float getFloatValue(short unitType) throws DOMException { if (_value instanceof LexicalUnit) { LexicalUnit lu = (LexicalUnit) _value; return lu.getFloatValue(); } throw new DOMExceptionImpl( DOMException.INVALID_ACCESS_ERR, DOMExceptionImpl.FLOAT_ERROR); // We need to attempt a conversion // return 0; } public void setStringValue(short stringType, String stringValue) throws DOMException { switch (stringType) { case CSS_STRING: _value = LexicalUnitImpl.createString(null, stringValue); break; case CSS_URI: _value = LexicalUnitImpl.createURI(null, stringValue); break; case CSS_IDENT: _value = LexicalUnitImpl.createIdent(null, stringValue); break; case CSS_ATTR: // _value = LexicalUnitImpl.createAttr(null, stringValue); // break; throw new DOMExceptionImpl( DOMException.NOT_SUPPORTED_ERR, DOMExceptionImpl.NOT_IMPLEMENTED); default: throw new DOMExceptionImpl( DOMException.INVALID_ACCESS_ERR, DOMExceptionImpl.STRING_ERROR); } } /** * TODO: return a value for a list type */ public String getStringValue() throws DOMException { if (_value instanceof LexicalUnit) { LexicalUnit lu = (LexicalUnit) _value; if ((lu.getLexicalUnitType() == LexicalUnit.SAC_IDENT) || (lu.getLexicalUnitType() == LexicalUnit.SAC_STRING_VALUE) || (lu.getLexicalUnitType() == LexicalUnit.SAC_URI) || (lu.getLexicalUnitType() == LexicalUnit.SAC_ATTR)) { return lu.getStringValue(); } } else if (_value instanceof Vector) { return null; } throw new DOMExceptionImpl( DOMException.INVALID_ACCESS_ERR, DOMExceptionImpl.STRING_ERROR); } public Counter getCounterValue() throws DOMException { if ((_value instanceof Counter) == false) { throw new DOMExceptionImpl( DOMException.INVALID_ACCESS_ERR, DOMExceptionImpl.COUNTER_ERROR); } return (Counter) _value; } public Rect getRectValue() throws DOMException { if ((_value instanceof Rect) == false) { throw new DOMExceptionImpl( DOMException.INVALID_ACCESS_ERR, DOMExceptionImpl.RECT_ERROR); } return (Rect) _value; } public RGBColor getRGBColorValue() throws DOMException { if ((_value instanceof RGBColor) == false) { throw new DOMExceptionImpl( DOMException.INVALID_ACCESS_ERR, DOMExceptionImpl.RGBCOLOR_ERROR); } return (RGBColor) _value; } public int getLength() { return (_value instanceof Vector) ? ((Vector)_value).size() : 0; } public CSSValue item(int index) { return (_value instanceof Vector) ? ((CSSValue)((Vector)_value).elementAt(index)) : null; } public String toString() { return getCssText(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/dom/CounterImpl.java0000644000175000017500000000562310737110114025560 0ustar twernertwerner/* * CounterImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: CounterImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.dom; import java.io.Serializable; import org.w3c.dom.css.*; import org.w3c.css.sac.*; /** * * @author David Schweinsberg * @version $Release$ */ public class CounterImpl implements Counter, Serializable { private String _identifier; private String _listStyle; private String _separator; /** Creates new CounterImpl */ public CounterImpl(boolean separatorSpecified, LexicalUnit lu) { LexicalUnit next = lu; _identifier = next.getStringValue(); next = next.getNextLexicalUnit(); if (separatorSpecified && (next != null)) { next = next.getNextLexicalUnit(); _separator = next.getStringValue(); next = next.getNextLexicalUnit(); } if (next != null) { _listStyle = next.getStringValue(); next = next.getNextLexicalUnit(); } } public String getIdentifier() { return _identifier; } public String getListStyle() { return _listStyle; } public String getSeparator() { return _separator; } public String toString() { StringBuffer sb = new StringBuffer(); if (_separator == null) { // This is a 'counter()' function sb.append("counter("); } else { // This is a 'counters()' function sb.append("counters("); } sb.append(_identifier); if (_separator != null) { sb.append(", \"").append(_separator).append("\""); } if (_listStyle != null) { sb.append(", ").append(_listStyle); } sb.append(")"); return sb.toString(); } }libcobra-java-0.98.4.orig/src/com/steadystate/css/dom/DOMExceptionImpl.java0000644000175000017500000000616610737110114026442 0ustar twernertwerner/* * DOMExceptionImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: DOMExceptionImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.dom; import java.util.*; import org.w3c.dom.*; /** * * @author David Schweinsberg * @version $Release$ */ public class DOMExceptionImpl extends DOMException { public static final int SYNTAX_ERROR = 0; public static final int ARRAY_OUT_OF_BOUNDS = 1; public static final int READ_ONLY_STYLE_SHEET = 2; public static final int EXPECTING_UNKNOWN_RULE = 3; public static final int EXPECTING_STYLE_RULE = 4; public static final int EXPECTING_CHARSET_RULE = 5; public static final int EXPECTING_IMPORT_RULE = 6; public static final int EXPECTING_MEDIA_RULE = 7; public static final int EXPECTING_FONT_FACE_RULE = 8; public static final int EXPECTING_PAGE_RULE = 9; public static final int FLOAT_ERROR = 10; public static final int STRING_ERROR = 11; public static final int COUNTER_ERROR = 12; public static final int RECT_ERROR = 13; public static final int RGBCOLOR_ERROR = 14; public static final int CHARSET_NOT_FIRST = 15; public static final int CHARSET_NOT_UNIQUE = 16; public static final int IMPORT_NOT_FIRST = 17; public static final int NOT_FOUND = 18; public static final int NOT_IMPLEMENTED = 19; private static ResourceBundle _exceptionResource = ResourceBundle.getBundle( "com.steadystate.css.parser.ExceptionResource", Locale.getDefault()); public DOMExceptionImpl(short code, int messageKey) { super(code, _exceptionResource.getString(keyString(messageKey))); } public DOMExceptionImpl(int code, int messageKey) { super((short) code, _exceptionResource.getString(keyString(messageKey))); } public DOMExceptionImpl(short code, int messageKey, String info) { super(code, _exceptionResource.getString(keyString(messageKey))); } private static String keyString(int key) { return "s" + String.valueOf(key); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/dom/MediaListImpl.java0000644000175000017500000000656210737110114026017 0ustar twernertwerner/* * MediaListImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: MediaListImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.dom; import java.io.Serializable; import java.util.*; import org.w3c.dom.*; import org.w3c.dom.stylesheets.*; import org.w3c.css.sac.*; /** * * @author David Schweinsberg * @version $Release$ */ public class MediaListImpl implements MediaList, Serializable { private Vector _media = new Vector(); public MediaListImpl(SACMediaList mediaList) { for (int i = 0; i < mediaList.getLength(); i++) { _media.addElement(mediaList.item(i)); } } public String getMediaText() { StringBuffer sb = new StringBuffer(""); for (int i = 0; i < _media.size(); i++) { sb.append(_media.elementAt(i).toString()); if (i < _media.size() - 1) { sb.append( ", " ); } } return sb.toString(); } public void setMediaText(String mediaText) throws DOMException { /* try { StringReader sr = new StringReader( mediaText ); CSS2Parser parser = new CSS2Parser( sr ); ASTMediaList ml = parser.mediaList(); _media = ml._media; } catch( ParseException e ) { throw new DOMExceptionImpl( DOMException.SYNTAX_ERR, DOMExceptionImpl.SYNTAX_ERROR, e.getMessage() ); } */ } public int getLength() { return _media.size(); } public String item(int index) { return (index < _media.size()) ? (String) _media.elementAt(index) : null; } public void deleteMedium(String oldMedium) throws DOMException { for (int i = 0; i < _media.size(); i++) { String str = (String) _media.elementAt(i); if (str.equalsIgnoreCase(oldMedium)) { _media.removeElementAt(i); return; } } throw new DOMExceptionImpl( DOMException.NOT_FOUND_ERR, DOMExceptionImpl.NOT_FOUND); } public void appendMedium(String newMedium) throws DOMException { _media.addElement(newMedium); } public String toString() { return getMediaText(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/dom/Property.java0000644000175000017500000000426110737110114025140 0ustar twernertwerner/* * Property.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: Property.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.dom; import java.io.Serializable; import org.w3c.dom.css.CSSValue; /** * * @author David Schweinsberg * @version $Release$ */ public class Property implements Serializable { private String _name; private CSSValue _value; private boolean _important; /** Creates new Property */ public Property(String name, CSSValue value, boolean important) { _name = name; _value = value; _important = important; } public String getName() { return _name; } public CSSValue getValue() { return _value; } public boolean isImportant() { return _important; } public void setValue(CSSValue value) { _value = value; } public void setImportant(boolean important) { _important = important; } public String toString() { return _name + ": " + _value.toString() + (_important ? " !important" : ""); } }libcobra-java-0.98.4.orig/src/com/steadystate/css/dom/RGBColorImpl.java0000644000175000017500000000510010737110114025540 0ustar twernertwerner/* * RGBColorImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: RGBColorImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.dom; import java.io.Serializable; import org.w3c.css.sac.*; import org.w3c.dom.css.*; public class RGBColorImpl implements RGBColor, Serializable { private CSSPrimitiveValue _red = null; private CSSPrimitiveValue _green = null; private CSSPrimitiveValue _blue = null; protected RGBColorImpl(LexicalUnit lu) { LexicalUnit next = lu; _red = new CSSValueImpl(next, true); next = next.getNextLexicalUnit(); next = next.getNextLexicalUnit(); _green = new CSSValueImpl(next, true); next = next.getNextLexicalUnit(); next = next.getNextLexicalUnit(); _blue = new CSSValueImpl(next, true); } protected RGBColorImpl() { } public CSSPrimitiveValue getRed() { return _red; } public void setRed(CSSPrimitiveValue red) { _red = red; } public CSSPrimitiveValue getGreen() { return _green; } public void setGreen(CSSPrimitiveValue green) { _green = green; } public CSSPrimitiveValue getBlue() { return _blue; } public void setBlue(CSSPrimitiveValue blue) { _blue = blue; } public String toString() { return "rgb(" + _red.toString() + ", " + _green.toString() + ", " + _blue.toString() + ")"; } } libcobra-java-0.98.4.orig/src/com/steadystate/css/dom/RectImpl.java0000644000175000017500000000565211134564236025052 0ustar twernertwerner/* * RectImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: RectImpl.java,v 1.5 2009/01/18 14:30:22 xamjadmin Exp $ */ package com.steadystate.css.dom; import java.io.Serializable; import org.w3c.dom.css.*; import org.w3c.css.sac.*; /** * * @author David Schweinsberg * @version $Release$ */ public class RectImpl implements Rect, Serializable { private CSSPrimitiveValue _left; private CSSPrimitiveValue _top; private CSSPrimitiveValue _right; private CSSPrimitiveValue _bottom; /** Creates new RectImpl */ public RectImpl(LexicalUnit lu) { LexicalUnit next = lu; _left = new CSSValueImpl(next, true); next = next == null ? null : next.getNextLexicalUnit(); next = next == null ? null : next.getNextLexicalUnit(); _top = new CSSValueImpl(next, true); next = next == null ? null : next.getNextLexicalUnit(); next = next == null ? null : next.getNextLexicalUnit(); _right = new CSSValueImpl(next, true); next = next == null ? null : next.getNextLexicalUnit(); next = next == null ? null : next.getNextLexicalUnit(); _bottom = new CSSValueImpl(next, true); } public CSSPrimitiveValue getTop() { return _top; } public CSSPrimitiveValue getRight() { return _right; } public CSSPrimitiveValue getBottom() { return _bottom; } public CSSPrimitiveValue getLeft() { return _left; } public String toString() { return new StringBuffer() .append("rect(") .append(_left.toString()) .append(", ") .append(_top.toString()) .append(", ") .append(_right.toString()) .append(", ") .append(_bottom.toString()) .append(")") .toString(); } }libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/0000755000175000017500000000000010630473006023167 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/com/steadystate/css/parser/ASCII_CharStream.java0000644000175000017500000002305210445070340026773 0ustar twernertwerner/* Generated By:JavaCC: Do not edit this line. ASCII_CharStream.java Version 0.7pre6 */ package com.steadystate.css.parser; /** * An implementation of interface CharStream, where the stream is assumed to * contain only ASCII characters (without unicode processing). */ public final class ASCII_CharStream implements CharStream { public static final boolean staticFlag = false; int bufsize; int available; int tokenBegin; public int bufpos = -1; private int bufline[]; private int bufcolumn[]; private int column = 0; private int line = 1; private boolean prevCharIsCR = false; private boolean prevCharIsLF = false; private java.io.Reader inputStream; private char[] buffer; private int maxNextCharInd = 0; private int inBuf = 0; private final void ExpandBuff(boolean wrapAround) { char[] newbuffer = new char[bufsize + 2048]; int newbufline[] = new int[bufsize + 2048]; int newbufcolumn[] = new int[bufsize + 2048]; try { if (wrapAround) { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos += (bufsize - tokenBegin)); } else { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos -= tokenBegin); } } catch (Throwable t) { throw new Error(t.getMessage()); } bufsize += 2048; available = bufsize; tokenBegin = 0; } private final void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } } public final char BeginToken() throws java.io.IOException { tokenBegin = -1; char c = readChar(); tokenBegin = bufpos; return c; } private final void UpdateLineColumn(char c) { column++; if (prevCharIsLF) { prevCharIsLF = false; line += (column = 1); } else if (prevCharIsCR) { prevCharIsCR = false; if (c == '\n') { prevCharIsLF = true; } else line += (column = 1); } switch (c) { case '\r' : prevCharIsCR = true; break; case '\n' : prevCharIsLF = true; break; case '\t' : column--; column += (8 - (column & 07)); break; default : break; } bufline[bufpos] = line; bufcolumn[bufpos] = column; } public final char readChar() throws java.io.IOException { if (inBuf > 0) { --inBuf; return (char)((char)0xff & buffer[(bufpos == bufsize - 1) ? (bufpos = 0) : ++bufpos]); } if (++bufpos >= maxNextCharInd) FillBuff(); char c = (char)((char)0xff & buffer[bufpos]); UpdateLineColumn(c); return (c); } /** * @deprecated * @see #getEndColumn */ public final int getColumn() { return bufcolumn[bufpos]; } /** * @deprecated * @see #getEndLine */ public final int getLine() { return bufline[bufpos]; } public final int getEndColumn() { return bufcolumn[bufpos]; } public final int getEndLine() { return bufline[bufpos]; } public final int getBeginColumn() { return bufcolumn[tokenBegin]; } public final int getBeginLine() { return bufline[tokenBegin]; } public final void backup(int amount) { inBuf += amount; if ((bufpos -= amount) < 0) bufpos += bufsize; } public ASCII_CharStream(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } public ASCII_CharStream(java.io.Reader dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } public void ReInit(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; if (buffer == null || buffersize != buffer.length) { available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } prevCharIsLF = prevCharIsCR = false; tokenBegin = inBuf = maxNextCharInd = 0; bufpos = -1; } public void ReInit(java.io.Reader dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } public ASCII_CharStream(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { this(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096); } public ASCII_CharStream(java.io.InputStream dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } public void ReInit(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096); } public void ReInit(java.io.InputStream dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } public final String GetImage() { if (bufpos >= tokenBegin) return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); else return new String(buffer, tokenBegin, bufsize - tokenBegin) + new String(buffer, 0, bufpos + 1); } public final char[] GetSuffix(int len) { char[] ret = new char[len]; if ((bufpos + 1) >= len) System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); else { System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); } return ret; } public void Done() { buffer = null; bufline = null; bufcolumn = null; } /** * Method to adjust line and column numbers for the start of a token.
*/ public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/CSSOMParseTest.java0000644000175000017500000000611310737110114026546 0ustar twernertwerner/* * CSSOMParseTest.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: CSSOMParseTest.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.parser; import java.io.*; import org.w3c.css.sac.*; import org.w3c.dom.css.*; /** * * @author David Schweinsberg * @version $Release$ */ public class CSSOMParseTest extends Object { /** Creates new CSSOMParseTest */ public CSSOMParseTest() { try { Reader r = new FileReader("stylesheets/page_test.css"); // Reader r = new StringReader("FOO { color: rgb(1,2,3) }"); InputSource is = new InputSource(r); CSSOMParser parser = new CSSOMParser(); CSSStyleSheet ss = parser.parseStyleSheet(is); System.out.println(ss.toString()); CSSRuleList rl = ss.getCssRules(); for (int i = 0; i < rl.getLength(); i++) { CSSRule rule = rl.item(i); if (rule.getType() == CSSRule.STYLE_RULE) { CSSStyleRule sr = (CSSStyleRule) rule; CSSStyleDeclaration style = sr.getStyle(); for (int j = 0; j < style.getLength(); j++) { CSSValue value = style.getPropertyCSSValue(style.item(j)); if (value.getCssValueType() == CSSValue.CSS_PRIMITIVE_VALUE) { CSSPrimitiveValue pv = (CSSPrimitiveValue) value; System.out.println(">> " + pv.toString()); if (pv.getPrimitiveType() == CSSPrimitiveValue.CSS_COUNTER) { System.out.println("CSS_COUNTER(" + pv.toString() + ")"); } } } } } } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); e.printStackTrace(System.err); } } public static void main(String[] args) { new CSSOMParseTest(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/CSSOMParser.java0000644000175000017500000002452510764477130026115 0ustar twernertwerner/* * CSSOMParser.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: CSSOMParser.java,v 1.11 2008/03/08 17:53:59 xamjadmin Exp $ */ package com.steadystate.css.parser; import java.io.*; import java.util.*; import org.w3c.dom.css.*; import org.w3c.css.sac.*; import com.steadystate.css.dom.*; /** * * @author David Schweinsberg * @version $Release$ */ public class CSSOMParser { private static final String PARSER = "com.steadystate.css.parser.SACParser"; private Parser _parser = null; private CSSStyleSheetImpl _parentStyleSheet = null; //private CSSRule _parentRule = null; /** Creates new CSSOMParser */ public CSSOMParser() { try { //Modifying to always use local parser. //The commented code does not perform as //well and has class loader issues. (Jose 6/3/2007) //setProperty("org.w3c.css.sac.parser", PARSER); //ParserFactory factory = new ParserFactory(); //_parser = factory.makeParser(); _parser = new com.steadystate.css.parser.SACParser(); } catch (Exception e) { System.err.println(e.getMessage()); } } public CSSStyleSheet parseStyleSheet(InputSource source) throws IOException { CSSOMHandler handler = new CSSOMHandler(); _parser.setDocumentHandler(handler); _parser.parseStyleSheet(source); return (CSSStyleSheet) handler.getRoot(); } public CSSStyleDeclaration parseStyleDeclaration(InputSource source) throws IOException { CSSStyleDeclarationImpl sd = new CSSStyleDeclarationImpl(null); parseStyleDeclaration(sd, source); return sd; } public void parseStyleDeclaration(CSSStyleDeclaration sd, InputSource source) throws IOException { Stack nodeStack = new Stack(); nodeStack.push(sd); CSSOMHandler handler = new CSSOMHandler(nodeStack); _parser.setDocumentHandler(handler); _parser.parseStyleDeclaration(source); } public CSSValue parsePropertyValue(InputSource source) throws IOException { CSSOMHandler handler = new CSSOMHandler(); _parser.setDocumentHandler(handler); return new CSSValueImpl(_parser.parsePropertyValue(source)); } public CSSRule parseRule(InputSource source) throws IOException { CSSOMHandler handler = new CSSOMHandler(); _parser.setDocumentHandler(handler); _parser.parseRule(source); return (CSSRule) handler.getRoot(); } public SelectorList parseSelectors(InputSource source) throws IOException { HandlerBase handler = new HandlerBase(); _parser.setDocumentHandler(handler); return _parser.parseSelectors(source); } public void setParentStyleSheet(CSSStyleSheetImpl parentStyleSheet) { _parentStyleSheet = parentStyleSheet; } // public void setParentRule(CSSRule parentRule) { // _parentRule = parentRule; // } class CSSOMHandler implements DocumentHandler { private Stack _nodeStack; private Object _root = null; public CSSOMHandler(Stack nodeStack) { _nodeStack = nodeStack; } public CSSOMHandler() { _nodeStack = new Stack(); } public Object getRoot() { return _root; } public void startDocument(InputSource source) throws CSSException { if (_nodeStack.empty()) { CSSStyleSheetImpl ss = new CSSStyleSheetImpl(); _parentStyleSheet = ss; // Create the rule list CSSRuleListImpl rules = new CSSRuleListImpl(); ss.setRuleList(rules); _nodeStack.push(ss); _nodeStack.push(rules); } else { // Error } } public void endDocument(InputSource source) throws CSSException { // Pop the rule list and style sheet nodes _nodeStack.pop(); _root = _nodeStack.pop(); } public void comment(String text) throws CSSException { } public void ignorableAtRule(String atRule) throws CSSException { // Create the unknown rule and add it to the rule list CSSUnknownRuleImpl ir = new CSSUnknownRuleImpl( _parentStyleSheet, null, atRule); if (!_nodeStack.empty()) { ((CSSRuleListImpl)_nodeStack.peek()).add(ir); } else { // _nodeStack.push(ir); _root = ir; } } public void namespaceDeclaration(String prefix, String uri) throws CSSException { } public void importStyle( String uri, SACMediaList media, String defaultNamespaceURI) throws CSSException { // Create the import rule and add it to the rule list CSSImportRuleImpl ir = new CSSImportRuleImpl( _parentStyleSheet, null, uri, new MediaListImpl(media)); if (!_nodeStack.empty()) { ((CSSRuleListImpl)_nodeStack.peek()).add(ir); } else { // _nodeStack.push(ir); _root = ir; } } public void startMedia(SACMediaList media) throws CSSException { // Create the media rule and add it to the rule list CSSMediaRuleImpl mr = new CSSMediaRuleImpl( _parentStyleSheet, null, new MediaListImpl(media)); if (!_nodeStack.empty()) { ((CSSRuleListImpl)_nodeStack.peek()).add(mr); } // Create the rule list CSSRuleListImpl rules = new CSSRuleListImpl(); mr.setRuleList(rules); _nodeStack.push(mr); _nodeStack.push(rules); } public void endMedia(SACMediaList media) throws CSSException { // Pop the rule list and media rule nodes _nodeStack.pop(); _root = _nodeStack.pop(); } public void startPage(String name, String pseudo_page) throws CSSException { // Create the page rule and add it to the rule list CSSPageRuleImpl pr = new CSSPageRuleImpl(_parentStyleSheet, null, name, pseudo_page); if (!_nodeStack.empty()) { ((CSSRuleListImpl)_nodeStack.peek()).add(pr); } // Create the style declaration CSSStyleDeclarationImpl decl = new CSSStyleDeclarationImpl(pr); pr.setStyle(decl); _nodeStack.push(pr); _nodeStack.push(decl); } public void endPage(String name, String pseudo_page) throws CSSException { // Pop both the style declaration and the page rule nodes _nodeStack.pop(); _root = _nodeStack.pop(); } public void startFontFace() throws CSSException { // Create the font face rule and add it to the rule list CSSFontFaceRuleImpl ffr = new CSSFontFaceRuleImpl(_parentStyleSheet, null); if (!_nodeStack.empty()) { ((CSSRuleListImpl)_nodeStack.peek()).add(ffr); } // Create the style declaration CSSStyleDeclarationImpl decl = new CSSStyleDeclarationImpl(ffr); ffr.setStyle(decl); _nodeStack.push(ffr); _nodeStack.push(decl); } public void endFontFace() throws CSSException { // Pop both the style declaration and the font face rule nodes _nodeStack.pop(); _root = _nodeStack.pop(); } public void startSelector(SelectorList selectors) throws CSSException { // Create the style rule and add it to the rule list CSSStyleRuleImpl sr = new CSSStyleRuleImpl(_parentStyleSheet, null, selectors); if (!_nodeStack.empty()) { ((CSSRuleListImpl)_nodeStack.peek()).add(sr); } // Create the style declaration CSSStyleDeclarationImpl decl = new CSSStyleDeclarationImpl(sr); sr.setStyle(decl); _nodeStack.push(sr); _nodeStack.push(decl); } public void endSelector(SelectorList selectors) throws CSSException { // Pop both the style declaration and the style rule nodes _nodeStack.pop(); _root = _nodeStack.pop(); } public void property(String name, LexicalUnit value, boolean important) throws CSSException { CSSStyleDeclarationImpl decl = (CSSStyleDeclarationImpl) _nodeStack.peek(); decl.addProperty( new Property(name, new CSSValueImpl(value), important)); } } public static void setProperty(String key, String val) { Properties props = System.getProperties(); props.put(key, val); System.setProperties(props); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/CharStream.java0000644000175000017500000000732310434145436026075 0ustar twernertwerner/* Generated By:JavaCC: Do not edit this line. CharStream.java Version 4.0 */ package com.steadystate.css.parser; /** * This interface describes a character stream that maintains line and * column number positions of the characters. It also has the capability * to backup the stream to some extent. An implementation of this * interface is used in the TokenManager implementation generated by * JavaCCParser. * * All the methods except backup can be implemented in any fashion. backup * needs to be implemented correctly for the correct operation of the lexer. * Rest of the methods are all used to get information like line number, * column number and the String that constitutes a token and are not used * by the lexer. Hence their implementation won't affect the generated lexer's * operation. */ public interface CharStream { /** * Returns the next character from the selected input. The method * of selecting the input is the responsibility of the class * implementing this interface. Can throw any java.io.IOException. */ char readChar() throws java.io.IOException; /** * Returns the column position of the character last read. * @deprecated * @see #getEndColumn */ int getColumn(); /** * Returns the line number of the character last read. * @deprecated * @see #getEndLine */ int getLine(); /** * Returns the column number of the last character for current token (being * matched after the last call to BeginTOken). */ int getEndColumn(); /** * Returns the line number of the last character for current token (being * matched after the last call to BeginTOken). */ int getEndLine(); /** * Returns the column number of the first character for current token (being * matched after the last call to BeginTOken). */ int getBeginColumn(); /** * Returns the line number of the first character for current token (being * matched after the last call to BeginTOken). */ int getBeginLine(); /** * Backs up the input stream by amount steps. Lexer calls this method if it * had already read some characters, but could not use them to match a * (longer) token. So, they will be used again as the prefix of the next * token and it is the implemetation's responsibility to do this right. */ void backup(int amount); /** * Returns the next character that marks the beginning of the next token. * All characters must remain in the buffer between two successive calls * to this method to implement backup correctly. */ char BeginToken() throws java.io.IOException; /** * Returns a string made up of characters from the marked token beginning * to the current buffer position. Implementations have the choice of returning * anything that they want to. For example, for efficiency, one might decide * to just return null, which is a valid implementation. */ String GetImage(); /** * Returns an array of characters that make up the suffix of length 'len' for * the currently matched token. This is used to build up the matched string * for use in actions in the case of MORE. A simple and inefficient * implementation of this is as follows : * * { * String t = GetImage(); * return t.substring(t.length() - len, t.length()).toCharArray(); * } */ char[] GetSuffix(int len); /** * The lexer calls this function to indicate that it is done with the stream * and hence implementations can free any resources held by this class. * Again, the body of this function can be just empty and it will not * affect the lexer's operation. */ void Done(); } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/ExceptionResource.java0000644000175000017500000000465410737110114027505 0ustar twernertwerner/* * ExceptionResource.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: ExceptionResource.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.parser; import java.util.*; public class ExceptionResource extends ListResourceBundle { public Object[][] getContents() { return contents; } static final Object[][] contents = { {"s0", "Syntax error"}, {"s1", "Array out of bounds error"}, {"s2", "This style sheet is read only"}, {"s3", "The text does not represent an unknown rule"}, {"s4", "The text does not represent a style rule"}, {"s5", "The text does not represent a charset rule"}, {"s6", "The text does not represent an import rule"}, {"s7", "The text does not represent a media rule"}, {"s8", "The text does not represent a font face rule"}, {"s9", "The text does not represent a page rule"}, {"s10", "This isn't a Float type"}, {"s11", "This isn't a String type"}, {"s12", "This isn't a Counter type"}, {"s13", "This isn't a Rect type"}, {"s14", "This isn't an RGBColor type"}, {"s15", "A charset rule must be the first rule"}, {"s16", "A charset rule already exists"}, {"s17", "An import rule must preceed all other rules"}, {"s18", "The specified type was not found"} }; } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/HandlerBase.java0000644000175000017500000000755610737110114026213 0ustar twernertwerner/* * HandlerBase.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: HandlerBase.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.parser; import org.w3c.css.sac.*; public class HandlerBase implements DocumentHandler, ErrorHandler { public void startDocument(InputSource source) throws CSSException { } public void endDocument(InputSource source) throws CSSException { } public void comment(String text) throws CSSException { } public void ignorableAtRule(String atRule) throws CSSException { } public void namespaceDeclaration(String prefix, String uri) throws CSSException { } public void importStyle(String uri, SACMediaList media, String defaultNamespaceURI) throws CSSException { } public void startMedia(SACMediaList media) throws CSSException { } public void endMedia(SACMediaList media) throws CSSException { } public void startPage(String name, String pseudo_page) throws CSSException { } public void endPage(String name, String pseudo_page) throws CSSException { } public void startFontFace() throws CSSException { } public void endFontFace() throws CSSException { } public void startSelector(SelectorList selectors) throws CSSException { } public void endSelector(SelectorList selectors) throws CSSException { } public void property(String name, LexicalUnit value, boolean important) throws CSSException { } public void warning(CSSParseException exception) throws CSSException { StringBuffer sb = new StringBuffer(); sb.append(exception.getURI()) .append(" [") .append(exception.getLineNumber()) .append(":") .append(exception.getColumnNumber()) .append("] ") .append(exception.getMessage()); System.err.println(sb.toString()); } public void error(CSSParseException exception) throws CSSException { StringBuffer sb = new StringBuffer(); sb.append(exception.getURI()) .append(" [") .append(exception.getLineNumber()) .append(":") .append(exception.getColumnNumber()) .append("] ") .append(exception.getMessage()); System.err.println(sb.toString()); } public void fatalError(CSSParseException exception) throws CSSException { StringBuffer sb = new StringBuffer(); sb.append(exception.getURI()) .append(" [") .append(exception.getLineNumber()) .append(":") .append(exception.getColumnNumber()) .append("] ") .append(exception.getMessage()); System.err.println(sb.toString()); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/LexicalUnitImpl.java0000644000175000017500000005612710760217246027116 0ustar twernertwerner/* * LexicalUnitImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: LexicalUnitImpl.java,v 1.5 2008/02/24 13:37:09 xamjadmin Exp $ */ package com.steadystate.css.parser; import java.io.Serializable; import org.w3c.css.sac.*; /** * * @author David Schweinsberg * @version $Release$ */ public class LexicalUnitImpl implements LexicalUnit, Serializable { /* public static final short SAC_OPERATOR_COMMA = 0; public static final short SAC_OPERATOR_PLUS = 1; public static final short SAC_OPERATOR_MINUS = 2; public static final short SAC_OPERATOR_MULTIPLY = 3; public static final short SAC_OPERATOR_SLASH = 4; public static final short SAC_OPERATOR_MOD = 5; public static final short SAC_OPERATOR_EXP = 6; public static final short SAC_OPERATOR_LT = 7; public static final short SAC_OPERATOR_GT = 8; public static final short SAC_OPERATOR_LE = 9; public static final short SAC_OPERATOR_GE = 10; public static final short SAC_OPERATOR_TILDE = 11; public static final short SAC_INHERIT = 12; public static final short SAC_INTEGER = 13; public static final short SAC_REAL = 14; public static final short SAC_EM = 15; public static final short SAC_EX = 16; public static final short SAC_PIXEL = 17; public static final short SAC_INCH = 18; public static final short SAC_CENTIMETER = 19; public static final short SAC_MILLIMETER = 20; public static final short SAC_POINT = 21; public static final short SAC_PICA = 22; public static final short SAC_PERCENTAGE = 23; public static final short SAC_URI = 24; public static final short SAC_COUNTER_FUNCTION = 25; public static final short SAC_COUNTERS_FUNCTION = 26; public static final short SAC_RGBCOLOR = 27; public static final short SAC_DEGREE = 28; public static final short SAC_GRADIAN = 29; public static final short SAC_RADIAN = 30; public static final short SAC_MILLISECOND = 31; public static final short SAC_SECOND = 32; public static final short SAC_HERTZ = 33; public static final short SAC_KILOHERTZ = 34; public static final short SAC_IDENT = 35; public static final short SAC_STRING_VALUE = 36; public static final short SAC_ATTR = 37; public static final short SAC_RECT_FUNCTION = 38; public static final short SAC_UNICODERANGE = 39; public static final short SAC_SUB_EXPRESSION = 40; public static final short SAC_FUNCTION = 41; public static final short SAC_DIMENSION = 42; */ private short _type; private LexicalUnit _next; private LexicalUnit _prev; // private int _intVal; private float _floatVal; private String _dimension; private String _function; private LexicalUnit _params; private String _stringVal; protected LexicalUnitImpl(LexicalUnit previous, short type) { _type = type; _prev = previous; if (_prev != null) { ((LexicalUnitImpl)_prev)._next = this; } } /** * Integer */ protected LexicalUnitImpl(LexicalUnit previous, int value) { this(previous, SAC_INTEGER); // _intVal = value; _floatVal = value; } /** * Dimension */ protected LexicalUnitImpl(LexicalUnit previous, short type, float value) { this(previous, type); _floatVal = value; } /** * Unknown dimension */ protected LexicalUnitImpl( LexicalUnit previous, short type, String dimension, float value) { this(previous, type); _dimension = dimension; _floatVal = value; } /** * String */ protected LexicalUnitImpl(LexicalUnit previous, short type, String value) { this(previous, type); _stringVal = value; } /** * Function */ protected LexicalUnitImpl( LexicalUnit previous, short type, String name, LexicalUnit params) { this(previous, type); _function = name; _params = params; } public short getLexicalUnitType() { return _type; } public LexicalUnit getNextLexicalUnit() { return _next; } public LexicalUnit getPreviousLexicalUnit() { return _prev; } public int getIntegerValue() { // return _intVal; return (int) _floatVal; } public float getFloatValue() { return _floatVal; } public String getDimensionUnitText() { switch (_type) { case SAC_EM: return "em"; case SAC_EX: return "ex"; case SAC_PIXEL: return "px"; case SAC_INCH: return "in"; case SAC_CENTIMETER: return "cm"; case SAC_MILLIMETER: return "mm"; case SAC_POINT: return "pt"; case SAC_PICA: return "pc"; case SAC_PERCENTAGE: return "%"; case SAC_DEGREE: return "deg"; case SAC_GRADIAN: return "grad"; case SAC_RADIAN: return "rad"; case SAC_MILLISECOND: return "ms"; case SAC_SECOND: return "s"; case SAC_HERTZ: return "Hz"; case SAC_KILOHERTZ: return "kHz"; case SAC_DIMENSION: return _dimension; } return ""; } public String getFunctionName() { return _function; } public LexicalUnit getParameters() { return _params; } public String getStringValue() { return _stringVal; } public LexicalUnit getSubValues() { return _params; } public String toString() { StringBuffer sb = new StringBuffer(); switch (_type) { case SAC_OPERATOR_COMMA: sb.append(","); break; case SAC_OPERATOR_PLUS: sb.append("+"); break; case SAC_OPERATOR_MINUS: sb.append("-"); break; case SAC_OPERATOR_MULTIPLY: sb.append("*"); break; case SAC_OPERATOR_SLASH: sb.append("/"); break; case SAC_OPERATOR_MOD: sb.append("%"); break; case SAC_OPERATOR_EXP: sb.append("^"); break; case SAC_OPERATOR_LT: sb.append("<"); break; case SAC_OPERATOR_GT: sb.append(">"); break; case SAC_OPERATOR_LE: sb.append("<="); break; case SAC_OPERATOR_GE: sb.append(">="); break; case SAC_OPERATOR_TILDE: sb.append("~"); break; case SAC_OPERATOR_EQUALS: sb.append("="); break; case SAC_INHERIT: sb.append("inherit"); break; case SAC_INTEGER: sb.append(String.valueOf(getIntegerValue())); break; case SAC_REAL: sb.append(trimFloat(getFloatValue())); break; case SAC_EM: case SAC_EX: case SAC_PIXEL: case SAC_INCH: case SAC_CENTIMETER: case SAC_MILLIMETER: case SAC_POINT: case SAC_PICA: case SAC_PERCENTAGE: case SAC_DEGREE: case SAC_GRADIAN: case SAC_RADIAN: case SAC_MILLISECOND: case SAC_SECOND: case SAC_HERTZ: case SAC_KILOHERTZ: case SAC_DIMENSION: sb.append(trimFloat(getFloatValue())) .append(getDimensionUnitText()); break; case SAC_URI: sb.append("url(").append(getStringValue()).append(")"); break; case SAC_COUNTER_FUNCTION: sb.append("counter("); appendParams(sb, _params); sb.append(")"); break; case SAC_COUNTERS_FUNCTION: sb.append("counters("); appendParams(sb, _params); sb.append(")"); break; case SAC_RGBCOLOR: sb.append("rgb("); appendParams(sb, _params); sb.append(")"); break; case SAC_IDENT: sb.append(getStringValue()); break; case SAC_STRING_VALUE: sb.append("\"").append(getStringValue()).append("\""); break; case SAC_ATTR: sb.append("attr("); appendParams(sb, _params); sb.append(")"); break; case SAC_RECT_FUNCTION: sb.append("rect("); appendParams(sb, _params); sb.append(")"); break; case SAC_UNICODERANGE: sb.append(getStringValue()); break; case SAC_SUB_EXPRESSION: sb.append(getStringValue()); break; case SAC_FUNCTION: sb.append(getFunctionName()); appendParams(sb, _params); sb.append(")"); break; case SAC_ALPHA_FUNCTION: sb.append(getFunctionName() + "("); appendParams(sb, _params); sb.append(")"); break; } return sb.toString(); } public String toDebugString() { StringBuffer sb = new StringBuffer(); switch (_type) { case SAC_OPERATOR_COMMA: sb.append("SAC_OPERATOR_COMMA"); break; case SAC_OPERATOR_PLUS: sb.append("SAC_OPERATOR_PLUS"); break; case SAC_OPERATOR_MINUS: sb.append("SAC_OPERATOR_MINUS"); break; case SAC_OPERATOR_MULTIPLY: sb.append("SAC_OPERATOR_MULTIPLY"); break; case SAC_OPERATOR_SLASH: sb.append("SAC_OPERATOR_SLASH"); break; case SAC_OPERATOR_MOD: sb.append("SAC_OPERATOR_MOD"); break; case SAC_OPERATOR_EXP: sb.append("SAC_OPERATOR_EXP"); break; case SAC_OPERATOR_LT: sb.append("SAC_OPERATOR_LT"); break; case SAC_OPERATOR_GT: sb.append("SAC_OPERATOR_GT"); break; case SAC_OPERATOR_LE: sb.append("SAC_OPERATOR_LE"); break; case SAC_OPERATOR_GE: sb.append("SAC_OPERATOR_GE"); break; case SAC_OPERATOR_TILDE: sb.append("SAC_OPERATOR_TILDE"); break; case SAC_INHERIT: sb.append("SAC_INHERIT"); break; case SAC_INTEGER: sb.append("SAC_INTEGER(") .append(String.valueOf(getIntegerValue())) .append(")"); break; case SAC_REAL: sb.append("SAC_REAL(") .append(trimFloat(getFloatValue())) .append(")"); break; case SAC_EM: sb.append("SAC_EM(") .append(trimFloat(getFloatValue())) .append(getDimensionUnitText()) .append(")"); break; case SAC_EX: sb.append("SAC_EX(") .append(trimFloat(getFloatValue())) .append(getDimensionUnitText()) .append(")"); break; case SAC_PIXEL: sb.append("SAC_PIXEL(") .append(trimFloat(getFloatValue())) .append(getDimensionUnitText()) .append(")"); break; case SAC_INCH: sb.append("SAC_INCH(") .append(trimFloat(getFloatValue())) .append(getDimensionUnitText()) .append(")"); break; case SAC_CENTIMETER: sb.append("SAC_CENTIMETER(") .append(trimFloat(getFloatValue())) .append(getDimensionUnitText()) .append(")"); break; case SAC_MILLIMETER: sb.append("SAC_MILLIMETER(") .append(trimFloat(getFloatValue())) .append(getDimensionUnitText()) .append(")"); break; case SAC_POINT: sb.append("SAC_POINT(") .append(trimFloat(getFloatValue())) .append(getDimensionUnitText()) .append(")"); break; case SAC_PICA: sb.append("SAC_PICA(") .append(trimFloat(getFloatValue())) .append(getDimensionUnitText()) .append(")"); break; case SAC_PERCENTAGE: sb.append("SAC_PERCENTAGE(") .append(trimFloat(getFloatValue())) .append(getDimensionUnitText()) .append(")"); break; case SAC_DEGREE: sb.append("SAC_DEGREE(") .append(trimFloat(getFloatValue())) .append(getDimensionUnitText()) .append(")"); break; case SAC_GRADIAN: sb.append("SAC_GRADIAN(") .append(trimFloat(getFloatValue())) .append(getDimensionUnitText()) .append(")"); break; case SAC_RADIAN: sb.append("SAC_RADIAN(") .append(trimFloat(getFloatValue())) .append(getDimensionUnitText()) .append(")"); break; case SAC_MILLISECOND: sb.append("SAC_MILLISECOND(") .append(trimFloat(getFloatValue())) .append(getDimensionUnitText()) .append(")"); break; case SAC_SECOND: sb.append("SAC_SECOND(") .append(trimFloat(getFloatValue())) .append(getDimensionUnitText()) .append(")"); break; case SAC_HERTZ: sb.append("SAC_HERTZ(") .append(trimFloat(getFloatValue())) .append(getDimensionUnitText()) .append(")"); break; case SAC_KILOHERTZ: sb.append("SAC_KILOHERTZ(") .append(trimFloat(getFloatValue())) .append(getDimensionUnitText()) .append(")"); break; case SAC_DIMENSION: sb.append("SAC_DIMENSION(") .append(trimFloat(getFloatValue())) .append(getDimensionUnitText()) .append(")"); break; case SAC_URI: sb.append("SAC_URI(url(") .append(getStringValue()) .append("))"); break; case SAC_COUNTER_FUNCTION: sb.append("SAC_COUNTER_FUNCTION(counter("); appendParams(sb, _params); sb.append("))"); break; case SAC_COUNTERS_FUNCTION: sb.append("SAC_COUNTERS_FUNCTION(counters("); appendParams(sb, _params); sb.append("))"); break; case SAC_RGBCOLOR: sb.append("SAC_RGBCOLOR(rgb("); appendParams(sb, _params); sb.append("))"); break; case SAC_IDENT: sb.append("SAC_IDENT(") .append(getStringValue()) .append(")"); break; case SAC_STRING_VALUE: sb.append("SAC_STRING_VALUE(\"") .append(getStringValue()) .append("\")"); break; case SAC_ATTR: sb.append("SAC_ATTR(attr("); appendParams(sb, _params); sb.append("))"); break; case SAC_RECT_FUNCTION: sb.append("SAC_RECT_FUNCTION(rect("); appendParams(sb, _params); sb.append("))"); break; case SAC_UNICODERANGE: sb.append("SAC_UNICODERANGE(") .append(getStringValue()) .append(")"); break; case SAC_SUB_EXPRESSION: sb.append("SAC_SUB_EXPRESSION(") .append(getStringValue()) .append(")"); break; case SAC_FUNCTION: sb.append("SAC_FUNCTION(") .append(getFunctionName()) .append("("); appendParams(sb, _params); sb.append("))"); break; } return sb.toString(); } private void appendParams(StringBuffer sb, LexicalUnit first) { LexicalUnit l = first; while (l != null) { sb.append(l.toString()); l = l.getNextLexicalUnit(); } } private String trimFloat(float f) { String s = String.valueOf(getFloatValue()); return (f - (int) f != 0) ? s : s.substring(0, s.length() - 2); } // private static float value(char op, String s) { // return ((op == '-') ? -1 : 1) * Float.valueOf(s).floatValue(); // } // public static LexicalUnit createNumber(LexicalUnit prev, float f) { if (f > (int) f) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_REAL, f); } else { return new LexicalUnitImpl(prev, (int) f); } } public static LexicalUnit createPercentage(LexicalUnit prev, float f) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_PERCENTAGE, f); } public static LexicalUnit createPixel(LexicalUnit prev, float f) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_PIXEL, f); } public static LexicalUnit createCentimeter(LexicalUnit prev, float f) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_CENTIMETER, f); } public static LexicalUnit createMillimeter(LexicalUnit prev, float f) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_MILLIMETER, f); } public static LexicalUnit createInch(LexicalUnit prev, float f) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_INCH, f); } public static LexicalUnit createPoint(LexicalUnit prev, float f) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_POINT, f); } public static LexicalUnit createPica(LexicalUnit prev, float f) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_PICA, f); } public static LexicalUnit createEm(LexicalUnit prev, float f) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_EM, f); } public static LexicalUnit createEx(LexicalUnit prev, float f) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_EX, f); } public static LexicalUnit createDegree(LexicalUnit prev, float f) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_DEGREE, f); } public static LexicalUnit createRadian(LexicalUnit prev, float f) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_RADIAN, f); } public static LexicalUnit createGradian(LexicalUnit prev, float f) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_GRADIAN, f); } public static LexicalUnit createMillisecond(LexicalUnit prev, float f) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_MILLISECOND, f); } public static LexicalUnit createSecond(LexicalUnit prev, float f) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_SECOND, f); } public static LexicalUnit createHertz(LexicalUnit prev, float f) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_HERTZ, f); } public static LexicalUnit createDimension(LexicalUnit prev, float f, String dim) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_DIMENSION, dim, f); } public static LexicalUnit createKiloHertz(LexicalUnit prev, float f) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_KILOHERTZ, f); } public static LexicalUnit createCounter(LexicalUnit prev, LexicalUnit params) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_COUNTER_FUNCTION, "counter", params); } public static LexicalUnit createAlpha(LexicalUnit prev, LexicalUnit params) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_ALPHA_FUNCTION, "alpha", params); } public static LexicalUnit createCounters(LexicalUnit prev, LexicalUnit params) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_COUNTERS_FUNCTION, "counters", params); } public static LexicalUnit createAttr(LexicalUnit prev, LexicalUnit params) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_ATTR, "attr", params); } public static LexicalUnit createRect(LexicalUnit prev, LexicalUnit params) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_RECT_FUNCTION, "rect", params); } public static LexicalUnit createRgbColor(LexicalUnit prev, LexicalUnit params) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_RGBCOLOR, "rgb", params); } public static LexicalUnit createFunction(LexicalUnit prev, String name, LexicalUnit params) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_FUNCTION, name, params); } public static LexicalUnit createString(LexicalUnit prev, String value) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_STRING_VALUE, value); } public static LexicalUnit createIdent(LexicalUnit prev, String value) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_IDENT, value); } public static LexicalUnit createURI(LexicalUnit prev, String value) { return new LexicalUnitImpl(prev, LexicalUnit.SAC_URI, value); } public static LexicalUnit createComma(LexicalUnit prev) { return new LexicalUnitImpl(prev, SAC_OPERATOR_COMMA); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/LocatorImpl.java0000644000175000017500000000517310737110114026261 0ustar twernertwerner/* * LocatorImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: LocatorImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.parser; import org.w3c.css.sac.Locator; /** * * @author David Schweinsberg * @version $Release$ */ public class LocatorImpl implements Locator { private String _uri; private int _line; private int _column; /** Creates new LocatorImpl */ public LocatorImpl() { } /** * Return the line number where the current document event ends. * Note that this is the line position of the first character * after the text associated with the document event. * @return The line number, or -1 if none is available. * @see #getColumnNumber */ public int getLineNumber() { return _line; } /** * Return the URI for the current document event. * *

The parser must resolve the URI fully before passing it to the * application.

* * @return A string containing the URI, or null * if none is available. */ public String getURI() { return _uri; } /** * Return the column number where the current document event ends. * Note that this is the column number of the first * character after the text associated with the document * event. The first column in a line is position 1. * @return The column number, or -1 if none is available. * @see #getLineNumber */ public int getColumnNumber() { return _column; } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/ParseException.java0000644000175000017500000001532010760063776027001 0ustar twernertwerner/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 3.0 */ package com.steadystate.css.parser; import java.util.*; /** * This exception is thrown when parse errors are encountered. * You can explicitly create objects of this exception type by * calling the method generateParseException in the generated * parser. * * You can modify this class to customize your error reporting * mechanisms so long as you retain the public fields. */ public class ParseException extends Exception { public String uri; /** * This constructor is used by the method "generateParseException" * in the generated parser. Calling this constructor generates * a new object of this type with the fields "currentToken", * "expectedTokenSequences", and "tokenImage" set. The boolean * flag "specialConstructor" is also set to true to indicate that * this constructor was used to create this object. * This constructor calls its super class with the empty string * to force the "toString" method of parent class "Throwable" to * print the error message in the form: * ParseException: */ public ParseException(Token currentTokenVal, int[][] expectedTokenSequencesVal, String[] tokenImageVal ) { specialConstructor = true; currentToken = currentTokenVal; expectedTokenSequences = expectedTokenSequencesVal; tokenImage = tokenImageVal; } /** * The following constructors are for use by you for whatever * purpose you can think of. Constructing the exception in this * manner makes the exception behave in the normal way - i.e., as * documented in the class "Throwable". The fields "errorToken", * "expectedTokenSequences", and "tokenImage" do not contain * relevant information. The JavaCC generated code does not use * these constructors. */ public ParseException() { super(); this.uri = null; specialConstructor = false; } public ParseException(String message) { super(message); this.uri = null; specialConstructor = false; } /** * This variable determines which constructor was used to create * this object and thereby affects the semantics of the * "getMessage" method (see below). */ protected boolean specialConstructor; /** * This is the last token that has been consumed successfully. If * this object has been created due to a parse error, the token * followng this token will (therefore) be the first error token. */ public Token currentToken; /** * Each entry in this array is an array of integers. Each array * of integers represents a sequence of tokens (by their ordinal * values) that is expected at this point of the parse. */ public int[][] expectedTokenSequences; /** * This is a reference to the "tokenImage" array of the generated * parser within which the parse error occurred. This array is * defined in the generated ...Constants interface. */ public String[] tokenImage; /** * This method has the standard behavior when this object has been * created using the standard constructors. Otherwise, it uses * "currentToken" and "expectedTokenSequences" to generate a parse * error message and returns it. If this object has been created * due to a parse error, and you do not catch it (it gets thrown * from the parser), then this method is called during the printing * of the final stack trace, and hence the correct error message * gets displayed. */ public String getMessage() { if (!specialConstructor) { return super.getMessage(); } StringBuffer expected = new StringBuffer(); int maxSize = 0; for (int i = 0; i < expectedTokenSequences.length; i++) { if (maxSize < expectedTokenSequences[i].length) { maxSize = expectedTokenSequences[i].length; } for (int j = 0; j < expectedTokenSequences[i].length; j++) { expected.append(tokenImage[expectedTokenSequences[i][j]]).append(" "); } if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { expected.append("..."); } expected.append(eol).append(" "); } String uri = this.uri; String retval = (uri == null ? "" : (uri + ": ")) + "Encountered \""; Token tok = currentToken.next; Collection kinds = new ArrayList(); for (int i = 0; i < maxSize; i++) { if (i != 0) retval += " "; if (tok.kind == 0) { retval += tokenImage[0]; break; } retval += add_escapes(tok.image); kinds.add(new Integer(tok.kind)); tok = tok.next; } retval += "\" (kinds=" + kinds + ") at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; retval += "." + eol; if (expectedTokenSequences.length == 1) { retval += "Was expecting:" + eol + " "; } else { retval += "Was expecting one of:" + eol + " "; } retval += expected.toString(); return retval; } /** * The end of line string for this machine. */ protected String eol = System.getProperty("line.separator", "\n"); /** * Used to convert raw characters to their escaped version * when these raw version cannot be used as part of an ASCII * string literal. */ protected String add_escapes(String str) { StringBuffer retval = new StringBuffer(); char ch; for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { case 0 : continue; case '\b': retval.append("\\b"); continue; case '\t': retval.append("\\t"); continue; case '\n': retval.append("\\n"); continue; case '\f': retval.append("\\f"); continue; case '\r': retval.append("\\r"); continue; case '\"': retval.append("\\\""); continue; case '\'': retval.append("\\\'"); continue; case '\\': retval.append("\\\\"); continue; default: if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { String s = "0000" + Integer.toString(ch, 16); retval.append("\\u" + s.substring(s.length() - 4, s.length())); } else { retval.append(ch); } continue; } } return retval.toString(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/ParseTest.java0000644000175000017500000001473410737110114025751 0ustar twernertwerner/* * ParseTest.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: ParseTest.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.parser; import java.io.*; import org.w3c.css.sac.*; import org.w3c.css.sac.helpers.ParserFactory; /** * * @author David Schweinsberg * @version $Release$ */ public class ParseTest extends HandlerBase { private static final String PARSER = "com.steadystate.css.parser.SACParser"; private int _propertyCounter = 0; private int _indentSize = 0; public ParseTest() { try { CSSOMParser.setProperty("org.w3c.css.sac.parser", PARSER); ParserFactory factory = new ParserFactory(); Parser parser = factory.makeParser(); // Parser parser = new SACParser(); parser.setDocumentHandler(this); // Reader r = new FileReader("d:\\working\\CSS2Parser\\primary.css"); // Reader r = new FileReader("d:\\project\\css2\\html40.css"); // Reader r = new FileReader("d:\\project\\css2\\test.css"); // BufferedReader r = new BufferedReader(new InputStreamReader( // new FileInputStream("c:\\working\\CSS2Parser\\stylesheets\\test-unicode.css"), // "UTF-16")); // Reader r = new FileReader("d:\\project\\css2\\single-color.css"); Reader r = new FileReader("c:\\working\\css2parser\\stylesheets\\page_test.css"); InputSource is = new InputSource(r); // InputSource is = new InputSource("file:///d:/project/css2/test-unicode.css"); // InputSource is = new InputSource("file:///d:/project/css2/test.css"); parser.parseStyleSheet(is); } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); } } public static void main(String[] args) { new ParseTest(); } public void startDocument(InputSource source) throws CSSException { System.out.println("startDocument"); } public void endDocument(InputSource source) throws CSSException { System.out.println("endDocument"); } public void comment(String text) throws CSSException { } public void ignorableAtRule(String atRule) throws CSSException { System.out.println(atRule); } public void namespaceDeclaration(String prefix, String uri) throws CSSException { } public void importStyle(String uri, SACMediaList media, String defaultNamespaceURI) throws CSSException { System.out.print("@import url(" + uri + ")"); if (media.getLength() > 0) { System.out.println(" " + media.toString() + ";"); } else { System.out.println(";"); } } public void startMedia(SACMediaList media) throws CSSException { System.out.println(indent() + "@media " + media.toString() + " {"); incIndent(); } public void endMedia(SACMediaList media) throws CSSException { decIndent(); System.out.println(indent() + "}"); } public void startPage(String name, String pseudo_page) throws CSSException { System.out.print(indent() + "@page"); if (name != null) { System.out.print(" " + name); } if (pseudo_page != null) { System.out.println(" " + pseudo_page); } System.out.println(" {"); _propertyCounter = 0; incIndent(); } public void endPage(String name, String pseudo_page) throws CSSException { System.out.println(); decIndent(); System.out.println(indent() + "}"); } public void startFontFace() throws CSSException { System.out.println(indent() + "@font-face {"); _propertyCounter = 0; incIndent(); } public void endFontFace() throws CSSException { System.out.println(); decIndent(); System.out.println(indent() + "}"); } public void startSelector(SelectorList selectors) throws CSSException { System.out.println(indent() + selectors.toString() + " {"); _propertyCounter = 0; incIndent(); } public void endSelector(SelectorList selectors) throws CSSException { System.out.println(); decIndent(); System.out.println(indent() + "}"); } public void property(String name, LexicalUnit value, boolean important) throws CSSException { if (_propertyCounter++ > 0) { System.out.println(";"); } System.out.print(indent() + name + ":"); // Iterate through the chain of lexical units LexicalUnit nextVal = value; while (nextVal != null) { // System.out.print(" " + nextVal.toString()); System.out.print(" " + ((LexicalUnitImpl)nextVal).toDebugString()); nextVal = nextVal.getNextLexicalUnit(); } // Is it important? if (important) { System.out.print(" !important"); } } private String indent() { StringBuffer sb = new StringBuffer(16); for (int i = 0; i < _indentSize; i++) { sb.append(" "); } return sb.toString(); } private void incIndent() { _indentSize += 4; } private void decIndent() { _indentSize -= 4; } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/SACMediaListImpl.java0000644000175000017500000000366510737110114027064 0ustar twernertwerner/* * SACMediaListImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: SACMediaListImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.parser; import java.util.*; import org.w3c.css.sac.*; public class SACMediaListImpl implements SACMediaList { private Vector _selectors = new Vector(10, 10); public int getLength() { return _selectors.size(); } public String item(int index) { return (String) _selectors.elementAt(index); } public void add(String s) { _selectors.addElement(s); } public String toString() { StringBuffer sb = new StringBuffer(); int len = getLength(); for (int i = 0; i < len; i++) { sb.append(item(i)); if (i < len - 1) { sb.append(", "); } } return sb.toString(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/SACParser.java0000644000175000017500000022464111056203710025622 0ustar twernertwerner/* Generated By:JavaCC: Do not edit this line. SACParser.java */ package com.steadystate.css.parser; import java.io.*; import java.net.*; import java.util.*; import org.w3c.css.sac.*; import com.steadystate.css.parser.selectors.*; import java.util.logging.*; /** * @author David Schweinsberg * @version $Release$ */ public class SACParser implements Parser, SACParserConstants { private static final Logger logger = Logger.getLogger(SACParser.class.getName()); private InputSource _source = null; private Locale _locale = null; private DocumentHandler _docHandler = null; private ErrorHandler _errHandler = null; private SelectorFactory _selectorFactory = new SelectorFactoryImpl(); private ConditionFactory _conditionFactory = new ConditionFactoryImpl(); private boolean _quiet = true; public SACParser() { this((CharStream) null); } public void setLocale(Locale locale) throws CSSException { _locale = locale; // TODO: Search for requested locale throw new CSSException(CSSException.SAC_NOT_SUPPORTED_ERR); } public void setDocumentHandler(DocumentHandler handler) { _docHandler = handler; } public void setSelectorFactory(SelectorFactory selectorFactory) { _selectorFactory = selectorFactory; } public void setConditionFactory(ConditionFactory conditionFactory) { _conditionFactory = conditionFactory; } public void setErrorHandler(ErrorHandler handler) { _errHandler = handler; } public void parseStyleSheet(InputSource source) throws CSSException, IOException { _source = source; ReInit(getCharStream(source)); try { styleSheet(); } catch (ParseException e) { throw new CSSException(CSSException.SAC_SYNTAX_ERR, e.getMessage(), e); } } public void parseStyleSheet(String uri) throws CSSException, IOException { parseStyleSheet(new InputSource(uri)); } public void parseStyleDeclaration(InputSource source) throws CSSException, IOException { _source = source; ReInit(getCharStream(source)); try { styleDeclaration(); } catch (ParseException e) { throw new CSSException(CSSException.SAC_SYNTAX_ERR, e.getMessage(), e); } } public void parseRule(InputSource source) throws CSSException, IOException { _source = source; ReInit(getCharStream(source)); try { styleSheetRuleSingle(); } catch (ParseException e) { throw new CSSException(CSSException.SAC_SYNTAX_ERR, e.getMessage(), e); } } public String getParserVersion() { return "http://www.w3.org/TR/REC-CSS2"; } public SelectorList parseSelectors(InputSource source) throws CSSException, IOException { _source = source; ReInit(getCharStream(source)); SelectorList sl = null; try { sl = selectorList(); } catch (ParseException e) { throw new CSSException(CSSException.SAC_SYNTAX_ERR, e.getMessage(), e); } return sl; } public LexicalUnit parsePropertyValue(InputSource source) throws CSSException, IOException { _source = source; ReInit(getCharStream(source)); LexicalUnit lu = null; try { lu = expr(); } catch (ParseException e) { throw new CSSException(CSSException.SAC_SYNTAX_ERR, e.getMessage(), e); } return lu; } public boolean parsePriority(InputSource source) throws CSSException, IOException { _source = source; ReInit(getCharStream(source)); boolean b = false; try { b = prio(); } catch (ParseException e) { throw new CSSException(CSSException.SAC_SYNTAX_ERR, e.getMessage(), e); } return b; } private CharStream getCharStream(InputSource source) throws CSSException, IOException { if (source.getCharacterStream() != null) { return new ASCII_CharStream(source.getCharacterStream(), 1, 1); } else { // TODO: Handle other sources return null; } } private Locator getLocator() { return null; } // // stylesheet // : [ CHARSET_SYM S* STRING S* ';' ]? // [S|CDO|CDC]* [ import [S|CDO|CDC]* ]* // [ [ ruleset | media | page | font_face ] [S|CDO|CDC]* ]* // ; // final public void styleSheet() throws ParseException { try { _docHandler.startDocument(_source); styleSheetRuleList(); try { jj_consume_token(0); } catch (ParseException pe) { logger.log(Level.WARNING, "styleSheet(): " + _source.getURI() + ": Skipping last part of style sheet: " + pe.getMessage()); } } finally { _docHandler.endDocument(_source); } } final public void styleSheetRuleList() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case CHARSET_SYM: charsetRule(); break; default: jj_la1[0] = jj_gen; ; } label_1: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: case CDO: case CDC: ; break; default: jj_la1[1] = jj_gen; break label_1; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: jj_consume_token(S); break; case CDO: jj_consume_token(CDO); break; case CDC: jj_consume_token(CDC); break; default: jj_la1[2] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } label_2: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IMPORT_SYM: ; break; default: jj_la1[3] = jj_gen; break label_2; } importRule(); label_3: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: case CDO: case CDC: ; break; default: jj_la1[4] = jj_gen; break label_3; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: jj_consume_token(S); break; case CDO: jj_consume_token(CDO); break; case CDC: jj_consume_token(CDC); break; default: jj_la1[5] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } } label_4: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DOT: case COLON: case ASTERISK: case LSQUARE: case HASH: case PAGE_SYM: case MEDIA_SYM: case FONT_FACE_SYM: case ATKEYWORD: case DIMEN: case IDENT: ; break; default: jj_la1[6] = jj_gen; break label_4; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DOT: case COLON: case ASTERISK: case LSQUARE: case HASH: case DIMEN: case IDENT: styleRule(); break; case MEDIA_SYM: mediaRule(); break; case PAGE_SYM: pageRule(); break; case FONT_FACE_SYM: fontFaceRule(); break; case ATKEYWORD: unknownRule(); break; default: jj_la1[7] = jj_gen; jj_consume_token(-1); throw new ParseException(); } label_5: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: case CDO: case CDC: ; break; default: jj_la1[8] = jj_gen; break label_5; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: jj_consume_token(S); break; case CDO: jj_consume_token(CDO); break; case CDC: jj_consume_token(CDC); break; default: jj_la1[9] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } } } // // This is used by ASTStyleSheet.insertRule to parse a single rule // final public void styleSheetRuleSingle() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case CHARSET_SYM: charsetRule(); break; case IMPORT_SYM: importRule(); break; case DOT: case COLON: case ASTERISK: case LSQUARE: case HASH: case DIMEN: case IDENT: styleRule(); break; case MEDIA_SYM: mediaRule(); break; case PAGE_SYM: pageRule(); break; case FONT_FACE_SYM: fontFaceRule(); break; case ATKEYWORD: unknownRule(); break; default: jj_la1[10] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } final public void charsetRule() throws ParseException { Token t; jj_consume_token(CHARSET_SYM); label_6: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[11] = jj_gen; break label_6; } jj_consume_token(S); } t = jj_consume_token(STRING); label_7: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[12] = jj_gen; break label_7; } jj_consume_token(S); } jj_consume_token(SEMICOLON); } final public void unknownRule() throws ParseException { Token t; String s; t = jj_consume_token(ATKEYWORD); s = skip(); _docHandler.ignorableAtRule(s); } // // import // : IMPORT_SYM S* // [STRING|URI] S* [ medium [ ',' S* medium]* ]? ';' S* // ; // final public void importRule() throws ParseException { Token t; String s; SACMediaListImpl ml = new SACMediaListImpl(); jj_consume_token(IMPORT_SYM); label_8: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[13] = jj_gen; break label_8; } jj_consume_token(S); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case STRING: t = jj_consume_token(STRING); break; case URI: t = jj_consume_token(URI); break; default: jj_la1[14] = jj_gen; jj_consume_token(-1); throw new ParseException(); } label_9: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[15] = jj_gen; break label_9; } jj_consume_token(S); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENT: mediaList(ml); break; default: jj_la1[16] = jj_gen; ; } jj_consume_token(SEMICOLON); _docHandler.importStyle(unescape(t.image), ml, null); } // // media // : MEDIA_SYM S* medium [ ',' S* medium ]* '{' S* ruleset* '}' S* // ; // final public void mediaRule() throws ParseException { boolean start = false; SACMediaListImpl ml = new SACMediaListImpl(); try { jj_consume_token(MEDIA_SYM); label_10: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[17] = jj_gen; break label_10; } jj_consume_token(S); } mediaQuery(ml); start = true; _docHandler.startMedia(ml); jj_consume_token(LBRACE); label_11: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[18] = jj_gen; break label_11; } jj_consume_token(S); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DOT: case COLON: case ASTERISK: case LSQUARE: case HASH: case PAGE_SYM: case ATKEYWORD: case DIMEN: case IDENT: mediaRuleList(); break; default: jj_la1[19] = jj_gen; ; } jj_consume_token(RBRACE); } finally { if (start) { _docHandler.endMedia(ml); } } } final public void mediaQuery(SACMediaListImpl ml) throws ParseException { String s; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case NOT: case ONLY: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case ONLY: jj_consume_token(ONLY); break; case NOT: jj_consume_token(NOT); break; default: jj_la1[20] = jj_gen; jj_consume_token(-1); throw new ParseException(); } break; default: jj_la1[21] = jj_gen; ; } s = medium(); ml.add(s); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case COMMA: case AND: mediaListOrExpression(ml); break; default: jj_la1[22] = jj_gen; ; } } final public void mediaListOrExpression(SACMediaListImpl ml) throws ParseException { String s; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case COMMA: label_12: while (true) { jj_consume_token(COMMA); label_13: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[23] = jj_gen; break label_13; } jj_consume_token(S); } s = medium(); ml.add(s); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case COMMA: ; break; default: jj_la1[24] = jj_gen; break label_12; } } break; case AND: label_14: while (true) { jj_consume_token(AND); label_15: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[25] = jj_gen; break label_15; } jj_consume_token(S); } mediaExpression(ml); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case AND: ; break; default: jj_la1[26] = jj_gen; break label_14; } } break; default: jj_la1[27] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } final public void mediaExpression(SACMediaListImpl ml) throws ParseException { jj_consume_token(LPAREN); label_16: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[28] = jj_gen; break label_16; } jj_consume_token(S); } mediaFeature(ml); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case COLON: jj_consume_token(COLON); label_17: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[29] = jj_gen; break label_17; } jj_consume_token(S); } expr(); break; default: jj_la1[30] = jj_gen; ; } jj_consume_token(RROUND); } final public void mediaFeature(SACMediaListImpl ml) throws ParseException { Token t; t = jj_consume_token(IDENT); } final public void mediaList(SACMediaListImpl ml) throws ParseException { String s; s = medium(); label_18: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case COMMA: ; break; default: jj_la1[31] = jj_gen; break label_18; } jj_consume_token(COMMA); label_19: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[32] = jj_gen; break label_19; } jj_consume_token(S); } ml.add(s); s = medium(); } ml.add(s); } final public void mediaRuleList() throws ParseException { label_20: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DOT: case COLON: case ASTERISK: case LSQUARE: case HASH: case DIMEN: case IDENT: styleRule(); break; case PAGE_SYM: pageRule(); break; case ATKEYWORD: unknownRule(); break; default: jj_la1[33] = jj_gen; jj_consume_token(-1); throw new ParseException(); } label_21: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[34] = jj_gen; break label_21; } jj_consume_token(S); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DOT: case COLON: case ASTERISK: case LSQUARE: case HASH: case PAGE_SYM: case ATKEYWORD: case DIMEN: case IDENT: ; break; default: jj_la1[35] = jj_gen; break label_20; } } } final public void mediaRuleSingle() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DOT: case COLON: case ASTERISK: case LSQUARE: case HASH: case DIMEN: case IDENT: styleRule(); break; case PAGE_SYM: pageRule(); break; case ATKEYWORD: unknownRule(); break; default: jj_la1[36] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } // // medium // : IDENT S* // ; // final public String medium() throws ParseException { Token t; t = jj_consume_token(IDENT); label_22: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[37] = jj_gen; break label_22; } jj_consume_token(S); } {if (true) return t.image;} throw new Error("Missing return statement in function"); } // // page // : PAGE_SYM S* IDENT? pseudo_page? S* // '{' S* declaration [ ';' S* declaration ]* '}' S* // ; // final public void pageRule() throws ParseException { Token t = null; String s = null; boolean start = false; try { jj_consume_token(PAGE_SYM); label_23: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[38] = jj_gen; break label_23; } jj_consume_token(S); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case COLON: case IDENT: if (jj_2_1(2)) { t = jj_consume_token(IDENT); label_24: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[39] = jj_gen; break label_24; } jj_consume_token(S); } } else { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENT: t = jj_consume_token(IDENT); s = pseudoPage(); label_25: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[40] = jj_gen; break label_25; } jj_consume_token(S); } break; case COLON: s = pseudoPage(); label_26: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[41] = jj_gen; break label_26; } jj_consume_token(S); } break; default: jj_la1[42] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } break; default: jj_la1[43] = jj_gen; ; } jj_consume_token(LBRACE); label_27: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[44] = jj_gen; break label_27; } jj_consume_token(S); } start = true; _docHandler.startPage((t != null) ? unescape(t.image) : null, s); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENT: declaration(); break; default: jj_la1[45] = jj_gen; ; } label_28: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case SEMICOLON: ; break; default: jj_la1[46] = jj_gen; break label_28; } jj_consume_token(SEMICOLON); label_29: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[47] = jj_gen; break label_29; } jj_consume_token(S); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENT: declaration(); break; default: jj_la1[48] = jj_gen; ; } } jj_consume_token(RBRACE); } finally { if (start) { _docHandler.endPage((t != null) ? unescape(t.image) : null, s); } } } // // pseudoPage // : ':' IDENT // ; // final public String pseudoPage() throws ParseException { Token t; jj_consume_token(COLON); t = jj_consume_token(IDENT); {if (true) return t.image;} throw new Error("Missing return statement in function"); } // // font_face // : FONT_FACE_SYM S* // '{' S* declaration [ ';' S* declaration ]* '}' S* // ; // final public void fontFaceRule() throws ParseException { boolean start = false; try { jj_consume_token(FONT_FACE_SYM); label_30: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[49] = jj_gen; break label_30; } jj_consume_token(S); } jj_consume_token(LBRACE); label_31: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[50] = jj_gen; break label_31; } jj_consume_token(S); } start = true; _docHandler.startFontFace(); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENT: declaration(); break; default: jj_la1[51] = jj_gen; ; } label_32: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case SEMICOLON: ; break; default: jj_la1[52] = jj_gen; break label_32; } jj_consume_token(SEMICOLON); label_33: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[53] = jj_gen; break label_33; } jj_consume_token(S); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENT: declaration(); break; default: jj_la1[54] = jj_gen; ; } } jj_consume_token(RBRACE); } finally { if (start) { _docHandler.endFontFace(); } } } // // operator // : '/' S* | ',' S* | // ; // final public LexicalUnit operator(LexicalUnit prev) throws ParseException { Token t; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case SLASH: t = jj_consume_token(SLASH); label_34: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[55] = jj_gen; break label_34; } jj_consume_token(S); } {if (true) return new LexicalUnitImpl(prev, LexicalUnit.SAC_OPERATOR_SLASH);} break; case COMMA: t = jj_consume_token(COMMA); label_35: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[56] = jj_gen; break label_35; } jj_consume_token(S); } {if (true) return new LexicalUnitImpl(prev, LexicalUnit.SAC_OPERATOR_COMMA);} break; case EQUALS: t = jj_consume_token(EQUALS); label_36: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[57] = jj_gen; break label_36; } jj_consume_token(S); } {if (true) return new LexicalUnitImpl(prev, LexicalUnit.SAC_OPERATOR_EQUALS);} break; default: jj_la1[58] = jj_gen; jj_consume_token(-1); throw new ParseException(); } throw new Error("Missing return statement in function"); } // // combinator // : '+' S* | '>' S* | // ; // final public char combinator() throws ParseException { char c = ' '; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PLUS: jj_consume_token(PLUS); c='+'; label_37: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[59] = jj_gen; break label_37; } jj_consume_token(S); } break; case GT: jj_consume_token(GT); c='>'; label_38: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[60] = jj_gen; break label_38; } jj_consume_token(S); } break; case S: jj_consume_token(S); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PLUS: case GT: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PLUS: jj_consume_token(PLUS); c='+'; break; case GT: jj_consume_token(GT); c='>'; break; default: jj_la1[61] = jj_gen; jj_consume_token(-1); throw new ParseException(); } label_39: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[62] = jj_gen; break label_39; } jj_consume_token(S); } break; default: jj_la1[63] = jj_gen; ; } break; default: jj_la1[64] = jj_gen; jj_consume_token(-1); throw new ParseException(); } {if (true) return c;} throw new Error("Missing return statement in function"); } // // unary_operator // : '-' | '+' // ; // final public char unaryOperator() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case MINUS: jj_consume_token(MINUS); {if (true) return '-';} break; case PLUS: jj_consume_token(PLUS); {if (true) return '+';} break; default: jj_la1[65] = jj_gen; jj_consume_token(-1); throw new ParseException(); } throw new Error("Missing return statement in function"); } // // property // : IDENT S* // ; // final public String property() throws ParseException { Token t; t = jj_consume_token(IDENT); label_40: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[66] = jj_gen; break label_40; } jj_consume_token(S); } {if (true) return unescape(t.image);} throw new Error("Missing return statement in function"); } // // ruleset // : selector [ ',' S* selector ]* // '{' S* declaration [ ';' S* declaration ]* '}' S* // ; // final public void styleRule() throws ParseException { SelectorList selList = null; boolean start = false; boolean noError = true; try { selList = selectorList(); jj_consume_token(LBRACE); label_41: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[67] = jj_gen; break label_41; } jj_consume_token(S); } start = true; _docHandler.startSelector(selList); styleRuleDeclarations(); } catch (ParseException e) { logger.log(Level.WARNING,"styleRule(): " + _source.getURI() + ": Skipping block: " + e.getMessage() + "."); if(logger.isLoggable(Level.INFO)) { logger.log(Level.INFO, "styleRule()", e); } noError = false; error_skipblock(); } finally { if (start) { _docHandler.endSelector(selList); } } } final public void styleRuleDeclarations() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENT: declaration(); break; default: jj_la1[68] = jj_gen; ; } label_42: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case SEMICOLON: ; break; default: jj_la1[69] = jj_gen; break label_42; } jj_consume_token(SEMICOLON); label_43: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[70] = jj_gen; break label_43; } jj_consume_token(S); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENT: declaration(); break; default: jj_la1[71] = jj_gen; ; } } try { jj_consume_token(RBRACE); } catch (ParseException e) { logger.log(Level.WARNING,"styleRule(): " + _source.getURI() + ": Skipping declaration: " + e.getMessage() + "."); if(logger.isLoggable(Level.INFO)) { logger.log(Level.INFO, "styleRule()", e); } error_skipdecl(); styleRuleDeclarations(); } } final public SelectorList selectorList() throws ParseException { SelectorListImpl selList = new SelectorListImpl(); Selector sel; // try { sel = selector(); label_44: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case COMMA: ; break; default: jj_la1[72] = jj_gen; break label_44; } jj_consume_token(COMMA); label_45: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[73] = jj_gen; break label_45; } jj_consume_token(S); } selList.add(sel); sel = selector(); } selList.add(sel); {if (true) return selList;} throw new Error("Missing return statement in function"); } // // selector // : simple_selector [ combinator simple_selector ]* // ; // final public Selector selector() throws ParseException { Selector sel; char comb; sel = simpleSelector(null, ' '); label_46: while (true) { if (jj_2_2(2)) { ; } else { break label_46; } comb = combinator(); sel = simpleSelector(sel, comb); } label_47: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[74] = jj_gen; break label_47; } jj_consume_token(S); } {if (true) return sel;} throw new Error("Missing return statement in function"); } // // simple_selector // : element_name? [ HASH | class | attrib | pseudo ]* S* // ; // final public Selector simpleSelector(Selector sel, char comb) throws ParseException { SimpleSelector simpleSel = null; Condition c = null; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case ASTERISK: case IDENT: simpleSel = elementName(); label_48: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DOT: case COLON: case LSQUARE: case HASH: case DIMEN: ; break; default: jj_la1[75] = jj_gen; break label_48; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case HASH: c = hash(c); break; case DOT: case DIMEN: c = _class(c); break; case LSQUARE: c = attrib(c); break; case COLON: c = pseudo(c); break; default: jj_la1[76] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } break; case DOT: case COLON: case LSQUARE: case HASH: case DIMEN: simpleSel = _selectorFactory.createElementSelector(null, null); label_49: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case HASH: c = hash(c); break; case DOT: case DIMEN: c = _class(c); break; case LSQUARE: c = attrib(c); break; case COLON: c = pseudo(c); break; default: jj_la1[77] = jj_gen; jj_consume_token(-1); throw new ParseException(); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DOT: case COLON: case LSQUARE: case HASH: case DIMEN: ; break; default: jj_la1[78] = jj_gen; break label_49; } } break; default: jj_la1[79] = jj_gen; jj_consume_token(-1); throw new ParseException(); } if (c != null) { simpleSel = _selectorFactory.createConditionalSelector(simpleSel, c); } if (sel != null) { switch (comb) { case ' ': sel = _selectorFactory.createDescendantSelector(sel, simpleSel); break; case '+': sel = _selectorFactory.createDirectAdjacentSelector(sel.getSelectorType(), sel, simpleSel); break; case '>': sel = _selectorFactory.createChildSelector(sel, simpleSel); break; } } else { sel = simpleSel; } {if (true) return sel;} throw new Error("Missing return statement in function"); } // // class // : ('.' ) | // ; // final public Condition _class(Condition pred) throws ParseException { Token t; boolean isDimen = false; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case DOT: jj_consume_token(DOT); t = jj_consume_token(IDENT); break; case DIMEN: t = jj_consume_token(DIMEN); isDimen = true; break; default: jj_la1[80] = jj_gen; jj_consume_token(-1); throw new ParseException(); } String className; if(isDimen) { String timage = t.image; if(!timage.startsWith(".")) { {if (true) return null;} } className = timage.substring(1); } else { className = t.image; } Condition c = _conditionFactory.createClassCondition(null, className); {if (true) return (pred == null) ? c : _conditionFactory.createAndCondition(pred, c);} throw new Error("Missing return statement in function"); } // // element_name // : IDENT | '*' // ; // final public SimpleSelector elementName() throws ParseException { Token t; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENT: t = jj_consume_token(IDENT); {if (true) return _selectorFactory.createElementSelector(null, unescape(t.image));} break; case ASTERISK: jj_consume_token(ASTERISK); {if (true) return _selectorFactory.createElementSelector(null, null);} break; default: jj_la1[81] = jj_gen; jj_consume_token(-1); throw new ParseException(); } throw new Error("Missing return statement in function"); } // // attrib // : '[' S* IDENT S* [ [ '=' | INCLUDES | DASHMATCH ] S* // [ IDENT | STRING ] S* ]? ']' // ; // final public Condition attrib(Condition pred) throws ParseException { Token t; String name = null; String value = null; int type = 0; jj_consume_token(LSQUARE); label_50: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[82] = jj_gen; break label_50; } jj_consume_token(S); } t = jj_consume_token(IDENT); name = unescape(t.image); label_51: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[83] = jj_gen; break label_51; } jj_consume_token(S); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case EQUALS: case INCLUDES: case DASHMATCH: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case EQUALS: jj_consume_token(EQUALS); type = 1; break; case INCLUDES: jj_consume_token(INCLUDES); type = 2; break; case DASHMATCH: jj_consume_token(DASHMATCH); type = 3; break; default: jj_la1[84] = jj_gen; jj_consume_token(-1); throw new ParseException(); } label_52: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[85] = jj_gen; break label_52; } jj_consume_token(S); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENT: t = jj_consume_token(IDENT); value = t.image; break; case STRING: t = jj_consume_token(STRING); value = unescape(t.image); break; default: jj_la1[86] = jj_gen; jj_consume_token(-1); throw new ParseException(); } label_53: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[87] = jj_gen; break label_53; } jj_consume_token(S); } break; default: jj_la1[88] = jj_gen; ; } jj_consume_token(RSQUARE); Condition c = null; switch (type) { case 0: c = _conditionFactory.createAttributeCondition(name, null, false, null); break; case 1: c = _conditionFactory.createAttributeCondition(name, null, false, value); break; case 2: c = _conditionFactory.createOneOfAttributeCondition(name, null, false, value); break; case 3: c = _conditionFactory.createBeginHyphenAttributeCondition(name, null, false, value); break; } {if (true) return (pred == null) ? c : _conditionFactory.createAndCondition(pred, c);} throw new Error("Missing return statement in function"); } // // pseudo // : ':' [ IDENT | FUNCTION S* IDENT S* ')' ] // ; // final public Condition pseudo(Condition pred) throws ParseException { Condition c; Token t; String function; String arg; jj_consume_token(COLON); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENT: t = jj_consume_token(IDENT); // There appears to be an issue here regarding "first-letter" & "first-line" String s = unescape(t.image); c = _conditionFactory.createPseudoClassCondition(null, s); {if (true) return (pred == null) ? c : _conditionFactory.createAndCondition(pred, c);} break; case FUNCTION: t = jj_consume_token(FUNCTION); function = unescape(t.image); label_54: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[89] = jj_gen; break label_54; } jj_consume_token(S); } t = jj_consume_token(IDENT); arg = unescape(t.image); label_55: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[90] = jj_gen; break label_55; } jj_consume_token(S); } jj_consume_token(RROUND); if (function.equalsIgnoreCase("lang(")) { c = _conditionFactory.createLangCondition(unescape(arg)); {if (true) return (pred == null) ? c : _conditionFactory.createAndCondition(pred, c);} } else { {if (true) throw new CSSParseException( "Invalid pseudo function name " + function, getLocator());} } break; default: jj_la1[91] = jj_gen; jj_consume_token(-1); throw new ParseException(); } throw new Error("Missing return statement in function"); } final public Condition hash(Condition pred) throws ParseException { Token t; t = jj_consume_token(HASH); Condition c = _conditionFactory.createIdCondition(t.image.substring(1)); {if (true) return (pred == null) ? c : _conditionFactory.createAndCondition(pred, c);} throw new Error("Missing return statement in function"); } final public void styleDeclaration() throws ParseException { jj_consume_token(LBRACE); label_56: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[92] = jj_gen; break label_56; } jj_consume_token(S); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENT: declaration(); break; default: jj_la1[93] = jj_gen; ; } label_57: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case SEMICOLON: ; break; default: jj_la1[94] = jj_gen; break label_57; } jj_consume_token(SEMICOLON); label_58: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[95] = jj_gen; break label_58; } jj_consume_token(S); } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENT: declaration(); break; default: jj_la1[96] = jj_gen; ; } } jj_consume_token(RBRACE); } // // declaration // : property ':' S* expr prio? // | // ; // final public void declaration() throws ParseException { String p; LexicalUnit e; boolean priority = false; // CSSValue e; boolean noError = true; try { p = property(); jj_consume_token(COLON); label_59: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[97] = jj_gen; break label_59; } jj_consume_token(S); } e = expr(); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IMPORTANT_SYM: priority = prio(); break; default: jj_la1[98] = jj_gen; ; } _docHandler.property(p, e, priority); } catch (ParseException ex) { logger.log(Level.WARNING, "declaration(): " + _source.getURI() + ": Skipping declaration due to: " + ex.getMessage() + "."); if(logger.isLoggable(Level.INFO)) { logger.log(Level.INFO, "declaration()", ex); } noError = false; error_skipdecl(); } } // // prio // : IMPORTANT_SYM S* // ; // final public boolean prio() throws ParseException { jj_consume_token(IMPORTANT_SYM); label_60: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[99] = jj_gen; break label_60; } jj_consume_token(S); } {if (true) return true;} throw new Error("Missing return statement in function"); } // // expr // : term [ operator term ]* // ; // // TODO: Deal with the operator // final public LexicalUnit expr() throws ParseException { LexicalUnit head; LexicalUnit body; head = term(null); body = head; label_61: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case COMMA: case SLASH: case PLUS: case MINUS: case EQUALS: case HASH: case STRING: case URI: case INHERIT: case EMS: case EXS: case LENGTH_PX: case LENGTH_CM: case LENGTH_MM: case LENGTH_IN: case LENGTH_PT: case LENGTH_PC: case ANGLE_DEG: case ANGLE_RAD: case ANGLE_GRAD: case TIME_MS: case TIME_S: case FREQ_HZ: case FREQ_KHZ: case DIMEN: case PERCENTAGE: case NUMBER: case RGB: case FUNCTION: case IDENT: case UNICODERANGE: ; break; default: jj_la1[100] = jj_gen; break label_61; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case COMMA: case SLASH: case EQUALS: body = operator(body); break; default: jj_la1[101] = jj_gen; ; } body = term(body); } {if (true) return head;} throw new Error("Missing return statement in function"); } // // term // : unary_operator? // [ NUMBER S* | PERCENTAGE S* | LENGTH S* | EMS S* | EXS S* | ANGLE S* | // TIME S* | FREQ S* | function ] // | STRING S* | IDENT S* | URI S* | RGB S* | UNICODERANGE S* | hexcolor // ; // final public LexicalUnit term(LexicalUnit prev) throws ParseException { Token t; char op = ' '; String s; LexicalUnit value = null; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PLUS: case MINUS: op = unaryOperator(); break; default: jj_la1[102] = jj_gen; ; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case EMS: case EXS: case LENGTH_PX: case LENGTH_CM: case LENGTH_MM: case LENGTH_IN: case LENGTH_PT: case LENGTH_PC: case ANGLE_DEG: case ANGLE_RAD: case ANGLE_GRAD: case TIME_MS: case TIME_S: case FREQ_HZ: case FREQ_KHZ: case PERCENTAGE: case NUMBER: case FUNCTION: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case NUMBER: t = jj_consume_token(NUMBER); value = LexicalUnitImpl.createNumber(prev, value(op, t.image)); break; case PERCENTAGE: t = jj_consume_token(PERCENTAGE); value = LexicalUnitImpl.createPercentage(prev, value(op, t.image)); break; case LENGTH_PX: t = jj_consume_token(LENGTH_PX); value = LexicalUnitImpl.createPixel(prev, value(op, t.image)); break; case LENGTH_CM: t = jj_consume_token(LENGTH_CM); value = LexicalUnitImpl.createCentimeter(prev, value(op, t.image)); break; case LENGTH_MM: t = jj_consume_token(LENGTH_MM); value = LexicalUnitImpl.createMillimeter(prev, value(op, t.image)); break; case LENGTH_IN: t = jj_consume_token(LENGTH_IN); value = LexicalUnitImpl.createInch(prev, value(op, t.image)); break; case LENGTH_PT: t = jj_consume_token(LENGTH_PT); value = LexicalUnitImpl.createPoint(prev, value(op, t.image)); break; case LENGTH_PC: t = jj_consume_token(LENGTH_PC); value = LexicalUnitImpl.createPica(prev, value(op, t.image)); break; case EMS: t = jj_consume_token(EMS); value = LexicalUnitImpl.createEm(prev, value(op, t.image)); break; case EXS: t = jj_consume_token(EXS); value = LexicalUnitImpl.createEx(prev, value(op, t.image)); break; case ANGLE_DEG: t = jj_consume_token(ANGLE_DEG); value = LexicalUnitImpl.createDegree(prev, value(op, t.image)); break; case ANGLE_RAD: t = jj_consume_token(ANGLE_RAD); value = LexicalUnitImpl.createRadian(prev, value(op, t.image)); break; case ANGLE_GRAD: t = jj_consume_token(ANGLE_GRAD); value = LexicalUnitImpl.createGradian(prev, value(op, t.image)); break; case TIME_MS: t = jj_consume_token(TIME_MS); value = LexicalUnitImpl.createMillisecond(prev, value(op, t.image)); break; case TIME_S: t = jj_consume_token(TIME_S); value = LexicalUnitImpl.createSecond(prev, value(op, t.image)); break; case FREQ_HZ: t = jj_consume_token(FREQ_HZ); value = LexicalUnitImpl.createHertz(prev, value(op, t.image)); break; case FREQ_KHZ: t = jj_consume_token(FREQ_KHZ); value = LexicalUnitImpl.createKiloHertz(prev, value(op, t.image)); break; case FUNCTION: value = function(prev); break; default: jj_la1[103] = jj_gen; jj_consume_token(-1); throw new ParseException(); } break; case STRING: t = jj_consume_token(STRING); value = new LexicalUnitImpl(prev, LexicalUnit.SAC_STRING_VALUE, t.image); break; case IDENT: t = jj_consume_token(IDENT); value = new LexicalUnitImpl(prev, LexicalUnit.SAC_IDENT, t.image); break; case URI: t = jj_consume_token(URI); value = new LexicalUnitImpl(prev, LexicalUnit.SAC_URI, t.image); break; case UNICODERANGE: t = jj_consume_token(UNICODERANGE); value = new LexicalUnitImpl(prev, LexicalUnit.SAC_UNICODERANGE, t.image); break; case RGB: value = rgb(prev); break; case HASH: value = hexcolor(prev); break; case DIMEN: t = jj_consume_token(DIMEN); int n = getLastNumPos(t.image); value = LexicalUnitImpl.createDimension( prev, value(op, t.image.substring(0, n+1)), t.image.substring(n+1)); break; case INHERIT: t = jj_consume_token(INHERIT); value = new LexicalUnitImpl(prev, LexicalUnit.SAC_INHERIT, t.image); break; default: jj_la1[104] = jj_gen; jj_consume_token(-1); throw new ParseException(); } label_62: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[105] = jj_gen; break label_62; } jj_consume_token(S); } {if (true) return value;} throw new Error("Missing return statement in function"); } // // function // : FUNCTION S* expr ')' S* // ; // final public LexicalUnit function(LexicalUnit prev) throws ParseException { Token t; LexicalUnit params; t = jj_consume_token(FUNCTION); label_63: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[106] = jj_gen; break label_63; } jj_consume_token(S); } params = expr(); jj_consume_token(RROUND); if (t.image.equalsIgnoreCase("counter(")) { {if (true) return LexicalUnitImpl.createCounter(prev, params);} } else if (t.image.equalsIgnoreCase("counters(")) { {if (true) return LexicalUnitImpl.createCounters(prev, params);} } else if (t.image.equalsIgnoreCase("attr(")) { {if (true) return LexicalUnitImpl.createAttr(prev, params);} } else if (t.image.equalsIgnoreCase("rect(")) { {if (true) return LexicalUnitImpl.createRect(prev, params);} } else if (t.image.equalsIgnoreCase("alpha(")) { // This is a Microsoft value {if (true) return LexicalUnitImpl.createAlpha(prev, params);} } {if (true) return LexicalUnitImpl.createFunction( prev, t.image.substring(0, t.image.length() - 1), params);} throw new Error("Missing return statement in function"); } // // rgb // : RGB S* expr ')' S* // ; // final public LexicalUnit rgb(LexicalUnit prev) throws ParseException { Token t; LexicalUnit params; t = jj_consume_token(RGB); label_64: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case S: ; break; default: jj_la1[107] = jj_gen; break label_64; } jj_consume_token(S); } params = expr(); jj_consume_token(RROUND); {if (true) return LexicalUnitImpl.createRgbColor(prev, params);} throw new Error("Missing return statement in function"); } // // hexcolor // : HASH S* // ; // final public LexicalUnit hexcolor(LexicalUnit prev) throws ParseException { Token t; t = jj_consume_token(HASH); // Step past the hash at the beginning int i = 1; int r = 0; int g = 0; int b = 0; int len = t.image.length() - 1; try { if (len == 3) { r = Integer.parseInt(t.image.substring(i + 0, i + 1), 16); g = Integer.parseInt(t.image.substring(i + 1, i + 2), 16); b = Integer.parseInt(t.image.substring(i + 2, i + 3), 16); r = (r << 4) | r; g = (g << 4) | g; b = (b << 4) | b; } else if (len == 6) { r = Integer.parseInt(t.image.substring(i + 0, i + 2), 16); g = Integer.parseInt(t.image.substring(i + 2, i + 4), 16); b = Integer.parseInt(t.image.substring(i + 4, i + 6), 16); } else { // Error } } catch(NumberFormatException nfe) { logger.warning("hexcolor(): Unable to parse color: " + t.image); } // Turn into an "rgb()" LexicalUnit lr = LexicalUnitImpl.createNumber(null, r); LexicalUnit lc1 = LexicalUnitImpl.createComma(lr); LexicalUnit lg = LexicalUnitImpl.createNumber(lc1, g); LexicalUnit lc2 = LexicalUnitImpl.createComma(lg); LexicalUnit lb = LexicalUnitImpl.createNumber(lc2, b); {if (true) return LexicalUnitImpl.createRgbColor(prev, lr);} throw new Error("Missing return statement in function"); } float value(char op, String s) throws ParseException { return ((op == '-') ? -1 : 1) * Float.parseFloat(s); } int getLastNumPos(String s) throws ParseException { int i; for (i = 0; i < s.length(); i++) { if (Character.isLetter(s.charAt(i))) { break; } } return i - 1; } String unescape(String s) throws ParseException { int len = s.length(); StringBuffer buf = new StringBuffer(len); int index = 0; while (index < len) { char c = s.charAt(index); if (c == '\\') { if (++index < len) { c = s.charAt(index); switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': int numValue = Character.digit(c, 16); int count = 0; int p = 16; while (index + 1 < len && count < 6) { c = s.charAt(index+1); if (Character.digit(c, 16) != -1) { numValue = (numValue * 16) + Character.digit(c, 16); p *= 16; index++; } else { if (c == ' ') { // skip the latest white space index++; } break; } } buf.append((char) numValue); break; case '\n': case '\f': break; case '\r': if (index + 1 < len) { if (s.charAt(index + 1) == '\n') { index ++; } } break; default: buf.append(c); } } else { throw new CSSParseException("invalid string " + s, getLocator()); } } else { buf.append(c); } index++; } return buf.toString(); } void skipSelector() throws ParseException { Token t = getToken(1); while (t.kind != COMMA && t.kind != SEMICOLON && t.kind != LBRACE && t.kind != EOF ) { getNextToken(); t = getToken(1); } } String skip() throws ParseException { StringBuffer sb = new StringBuffer(); int nesting = 0; Token t = getToken(0); if (t.image != null) { sb.append(t.image); } do { t = getNextToken(); if (t.kind == EOF) break; sb.append(t.image); if (t.kind == LBRACE) nesting++; else if (t.kind == RBRACE) nesting--; else if (t.kind == SEMICOLON && nesting <= 0) break; } while ((t.kind != RBRACE) || (nesting > 0)); return sb.toString(); } void error_skipblock() throws ParseException { if (!_quiet) { ParseException e = generateParseException(); System.err.println( "** error_skipblock **\n" + e.toString() ); } Token t; int nesting = 0; do { t = getNextToken(); if( t.kind == LBRACE ) nesting++; else if( t.kind == RBRACE ) nesting--; else if( t.kind == EOF ) break; } while ((t.kind != RBRACE) || (nesting > 0)); } void error_skipdecl() throws ParseException { if (!_quiet) { ParseException e = generateParseException(); System.err.println("** error_skipdecl **\n" + e.toString()); } Token t = getToken(1); while (t.kind != SEMICOLON && t.kind != RBRACE && t.kind != EOF ) { getNextToken(); t = getToken(1); } } final private boolean jj_2_1(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_1(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(0, xla); } } final private boolean jj_2_2(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_2(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(1, xla); } } final private boolean jj_3R_71() { Token xsp; if (jj_3R_74()) return true; while (true) { xsp = jj_scanpos; if (jj_3R_74()) { jj_scanpos = xsp; break; } } return false; } final private boolean jj_3R_87() { if (jj_scan_token(DOT)) return true; return false; } final private boolean jj_3R_85() { if (jj_scan_token(LSQUARE)) return true; return false; } final private boolean jj_3R_84() { Token xsp; xsp = jj_scanpos; if (jj_3R_87()) { jj_scanpos = xsp; if (jj_3R_88()) return true; } return false; } final private boolean jj_3R_69() { if (jj_scan_token(S)) return true; Token xsp; xsp = jj_scanpos; if (jj_3R_72()) jj_scanpos = xsp; return false; } final private boolean jj_3R_68() { if (jj_scan_token(GT)) return true; Token xsp; while (true) { xsp = jj_scanpos; if (jj_scan_token(1)) { jj_scanpos = xsp; break; } } return false; } final private boolean jj_3R_67() { if (jj_scan_token(PLUS)) return true; Token xsp; while (true) { xsp = jj_scanpos; if (jj_scan_token(1)) { jj_scanpos = xsp; break; } } return false; } final private boolean jj_3R_83() { if (jj_scan_token(HASH)) return true; return false; } final private boolean jj_3R_65() { Token xsp; xsp = jj_scanpos; if (jj_3R_67()) { jj_scanpos = xsp; if (jj_3R_68()) { jj_scanpos = xsp; if (jj_3R_69()) return true; } } return false; } final private boolean jj_3R_70() { if (jj_3R_73()) return true; return false; } final private boolean jj_3R_66() { Token xsp; xsp = jj_scanpos; if (jj_3R_70()) { jj_scanpos = xsp; if (jj_3R_71()) return true; } return false; } final private boolean jj_3R_78() { if (jj_scan_token(ASTERISK)) return true; return false; } final private boolean jj_3R_76() { if (jj_scan_token(GT)) return true; return false; } final private boolean jj_3R_73() { Token xsp; xsp = jj_scanpos; if (jj_3R_77()) { jj_scanpos = xsp; if (jj_3R_78()) return true; } return false; } final private boolean jj_3R_77() { if (jj_scan_token(IDENT)) return true; return false; } final private boolean jj_3R_88() { if (jj_scan_token(DIMEN)) return true; return false; } final private boolean jj_3_2() { if (jj_3R_65()) return true; if (jj_3R_66()) return true; return false; } final private boolean jj_3R_82() { if (jj_3R_86()) return true; return false; } final private boolean jj_3R_81() { if (jj_3R_85()) return true; return false; } final private boolean jj_3_1() { if (jj_scan_token(IDENT)) return true; Token xsp; while (true) { xsp = jj_scanpos; if (jj_scan_token(1)) { jj_scanpos = xsp; break; } } return false; } final private boolean jj_3R_80() { if (jj_3R_84()) return true; return false; } final private boolean jj_3R_74() { Token xsp; xsp = jj_scanpos; if (jj_3R_79()) { jj_scanpos = xsp; if (jj_3R_80()) { jj_scanpos = xsp; if (jj_3R_81()) { jj_scanpos = xsp; if (jj_3R_82()) return true; } } } return false; } final private boolean jj_3R_79() { if (jj_3R_83()) return true; return false; } final private boolean jj_3R_75() { if (jj_scan_token(PLUS)) return true; return false; } final private boolean jj_3R_86() { if (jj_scan_token(COLON)) return true; return false; } final private boolean jj_3R_72() { Token xsp; xsp = jj_scanpos; if (jj_3R_75()) { jj_scanpos = xsp; if (jj_3R_76()) return true; } return false; } public SACParserTokenManager token_source; public Token token, jj_nt; private int jj_ntk; private Token jj_scanpos, jj_lastpos; private int jj_la; public boolean lookingAhead = false; private boolean jj_semLA; private int jj_gen; final private int[] jj_la1 = new int[108]; static private int[] jj_la1_0; static private int[] jj_la1_1; static private int[] jj_la1_2; static { jj_la1_0(); jj_la1_1(); jj_la1_2(); } private static void jj_la1_0() { jj_la1_0 = new int[] {0x0,0x30000002,0x30000002,0x0,0x30000002,0x30000002,0x841a00,0x841a00,0x30000002,0x30000002,0x841a00,0x2,0x2,0x2,0x9000000,0x2,0x0,0x2,0x2,0x841a00,0x300000,0x300000,0x400100,0x2,0x100,0x2,0x400000,0x400100,0x2,0x2,0x800,0x100,0x2,0x841a00,0x2,0x841a00,0x841a00,0x2,0x2,0x2,0x2,0x2,0x800,0x800,0x2,0x0,0x400,0x2,0x0,0x2,0x2,0x0,0x400,0x2,0x0,0x2,0x2,0x2,0x12100,0x2,0x2,0x24000,0x2,0x24000,0x24002,0xc000,0x2,0x2,0x0,0x400,0x2,0x0,0x100,0x2,0x2,0x840a00,0x840a00,0x840a00,0x840a00,0x841a00,0x200,0x1000,0x2,0x2,0xc0010000,0x2,0x1000000,0x2,0xc0010000,0x2,0x2,0x0,0x2,0x0,0x400,0x2,0x0,0x2,0x0,0x2,0x981e100,0x12100,0xc000,0x0,0x9800000,0x2,0x2,0x2,}; } private static void jj_la1_1() { jj_la1_1 = new int[] {0x10,0x0,0x0,0x1,0x0,0x0,0x1080002e,0x1080002e,0x0,0x0,0x1080003f,0x0,0x0,0x0,0x0,0x0,0x10000000,0x0,0x0,0x10800022,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x10800022,0x0,0x10800022,0x10800022,0x0,0x0,0x0,0x0,0x0,0x10000000,0x10000000,0x0,0x10000000,0x0,0x0,0x10000000,0x0,0x0,0x10000000,0x0,0x0,0x10000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x10000000,0x0,0x0,0x10000000,0x0,0x0,0x0,0x800000,0x800000,0x800000,0x800000,0x10800000,0x800000,0x10000000,0x0,0x0,0x0,0x0,0x10000000,0x0,0x0,0x0,0x0,0x18000000,0x0,0x10000000,0x0,0x0,0x10000000,0x0,0x40,0x0,0x9fffff80,0x0,0x0,0xb7fff00,0x9fffff80,0x0,0x0,0x0,}; } private static void jj_la1_2() { jj_la1_2 = new int[] {0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,}; } final private JJCalls[] jj_2_rtns = new JJCalls[2]; private boolean jj_rescan = false; private int jj_gc = 0; public SACParser(CharStream stream) { token_source = new SACParserTokenManager(stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 108; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); } public void ReInit(CharStream stream) { token_source.ReInit(stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 108; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); } public SACParser(SACParserTokenManager tm) { token_source = tm; token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 108; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); } public void ReInit(SACParserTokenManager tm) { token_source = tm; token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 108; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); } final private Token jj_consume_token(int kind) throws ParseException { Token oldToken; if ((oldToken = token).next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; if (token.kind == kind) { jj_gen++; if (++jj_gc > 100) { jj_gc = 0; for (int i = 0; i < jj_2_rtns.length; i++) { JJCalls c = jj_2_rtns[i]; while (c != null) { if (c.gen < jj_gen) c.first = null; c = c.next; } } } return token; } token = oldToken; jj_kind = kind; throw generateParseException(); } static private final class LookaheadSuccess extends java.lang.Error { } final private LookaheadSuccess jj_ls = new LookaheadSuccess(); final private boolean jj_scan_token(int kind) { if (jj_scanpos == jj_lastpos) { jj_la--; if (jj_scanpos.next == null) { jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken(); } else { jj_lastpos = jj_scanpos = jj_scanpos.next; } } else { jj_scanpos = jj_scanpos.next; } if (jj_rescan) { int i = 0; Token tok = token; while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; } if (tok != null) jj_add_error_token(kind, i); } if (jj_scanpos.kind != kind) return true; if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls; return false; } final public Token getNextToken() { if (token.next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; jj_gen++; return token; } final public Token getToken(int index) { Token t = lookingAhead ? jj_scanpos : token; for (int i = 0; i < index; i++) { if (t.next != null) t = t.next; else t = t.next = token_source.getNextToken(); } return t; } final private int jj_ntk() { if ((jj_nt=token.next) == null) return (jj_ntk = (token.next=token_source.getNextToken()).kind); else return (jj_ntk = jj_nt.kind); } private java.util.Vector jj_expentries = new java.util.Vector(); private int[] jj_expentry; private int jj_kind = -1; private int[] jj_lasttokens = new int[100]; private int jj_endpos; private void jj_add_error_token(int kind, int pos) { if (pos >= 100) return; if (pos == jj_endpos + 1) { jj_lasttokens[jj_endpos++] = kind; } else if (jj_endpos != 0) { jj_expentry = new int[jj_endpos]; for (int i = 0; i < jj_endpos; i++) { jj_expentry[i] = jj_lasttokens[i]; } boolean exists = false; for (java.util.Enumeration e = jj_expentries.elements(); e.hasMoreElements();) { int[] oldentry = (int[])(e.nextElement()); if (oldentry.length == jj_expentry.length) { exists = true; for (int i = 0; i < jj_expentry.length; i++) { if (oldentry[i] != jj_expentry[i]) { exists = false; break; } } if (exists) break; } } if (!exists) jj_expentries.addElement(jj_expentry); if (pos != 0) jj_lasttokens[(jj_endpos = pos) - 1] = kind; } } public ParseException generateParseException() { jj_expentries.removeAllElements(); boolean[] la1tokens = new boolean[83]; for (int i = 0; i < 83; i++) { la1tokens[i] = false; } if (jj_kind >= 0) { la1tokens[jj_kind] = true; jj_kind = -1; } for (int i = 0; i < 108; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { if ((jj_la1_0[i] & (1< jj_gen) { jj_la = p.arg; jj_lastpos = jj_scanpos = p.first; switch (i) { case 0: jj_3_1(); break; case 1: jj_3_2(); break; } } p = p.next; } while (p != null); } catch(LookaheadSuccess ls) { } } jj_rescan = false; } final private void jj_save(int index, int xla) { JJCalls p = jj_2_rtns[index]; while (p.gen > jj_gen) { if (p.next == null) { p = p.next = new JJCalls(); break; } p = p.next; } p.gen = jj_gen + xla - jj_la; p.first = token; p.arg = xla; } static final class JJCalls { int gen; Token first; int arg; JJCalls next; } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/SACParserConstants.java0000644000175000017500000000622211056203710027510 0ustar twernertwerner/* Generated By:JavaCC: Do not edit this line. SACParserConstants.java */ package com.steadystate.css.parser; public interface SACParserConstants { int EOF = 0; int S = 1; int LBRACE = 5; int RBRACE = 6; int LPAREN = 7; int COMMA = 8; int DOT = 9; int SEMICOLON = 10; int COLON = 11; int ASTERISK = 12; int SLASH = 13; int PLUS = 14; int MINUS = 15; int EQUALS = 16; int GT = 17; int LSQUARE = 18; int RSQUARE = 19; int NOT = 20; int ONLY = 21; int AND = 22; int HASH = 23; int STRING = 24; int RROUND = 25; int URL = 26; int URI = 27; int CDO = 28; int CDC = 29; int INCLUDES = 30; int DASHMATCH = 31; int IMPORT_SYM = 32; int PAGE_SYM = 33; int MEDIA_SYM = 34; int FONT_FACE_SYM = 35; int CHARSET_SYM = 36; int ATKEYWORD = 37; int IMPORTANT_SYM = 38; int INHERIT = 39; int EMS = 40; int EXS = 41; int LENGTH_PX = 42; int LENGTH_CM = 43; int LENGTH_MM = 44; int LENGTH_IN = 45; int LENGTH_PT = 46; int LENGTH_PC = 47; int ANGLE_DEG = 48; int ANGLE_RAD = 49; int ANGLE_GRAD = 50; int TIME_MS = 51; int TIME_S = 52; int FREQ_HZ = 53; int FREQ_KHZ = 54; int DIMEN = 55; int PERCENTAGE = 56; int NUMBER = 57; int RGB = 58; int FUNCTION = 59; int IDENT = 60; int NAME = 61; int NUM = 62; int UNICODERANGE = 63; int RANGE = 64; int Q16 = 65; int Q15 = 66; int Q14 = 67; int Q13 = 68; int Q12 = 69; int Q11 = 70; int NMSTART = 71; int NMCHAR = 72; int STRING1 = 73; int STRING2 = 74; int NONASCII = 75; int ESCAPE = 76; int NL = 77; int UNICODE = 78; int HNUM = 79; int H = 80; int MEDIUM = 81; int UNKNOWN = 82; int DEFAULT = 0; int COMMENT = 1; String[] tokenImage = { "", "", "\"/*\"", "\"*/\"", "", "\"{\"", "\"}\"", "\"(\"", "\",\"", "\".\"", "\";\"", "\":\"", "\"*\"", "\"/\"", "\"+\"", "\"-\"", "\"=\"", "\">\"", "\"[\"", "\"]\"", "\"not\"", "\"only\"", "\"and\"", "", "", "\")\"", "", "", "\"\"", "\"~=\"", "\"|=\"", "\"@import\"", "\"@page\"", "\"@media\"", "\"@font-face\"", "\"@charset\"", "", "", "\"inherit\"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "\"rgb(\"", "", "", "", "", "", "", "", "", "", "", "", "\"?\"", "", "", "", "", "", "", "", "", "", "", "", "", }; } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/SACParserTokenManager.java0000644000175000017500000042724711056203710030125 0ustar twernertwerner/* Generated By:JavaCC: Do not edit this line. SACParserTokenManager.java */ package com.steadystate.css.parser; import java.io.*; import java.net.*; import java.util.*; import org.w3c.css.sac.*; import com.steadystate.css.parser.selectors.*; import java.util.logging.*; public class SACParserTokenManager implements SACParserConstants { private boolean _quiet = true; /* private int getLastNumPos(StringBuffer sb) { int i; for( i = 0; i < sb.length(); i++ ) if( Character.isLetter( sb.charAt( i ) ) ) break; return i - 1; } */ private String trimBy(StringBuffer s, int left, int right) { int end = s.length(); return s.toString().substring(left, end-right); } private String trimUrl(StringBuffer s) { StringBuffer s1 = new StringBuffer( trimBy(s, 4, 1).trim() ); int end = s1.length() - 1; if(end <= 0) { return s1.toString(); } if ((s1.charAt(0) == '"' && s1.charAt(end) == '"') || (s1.charAt(0) == '\'' && s1.charAt(end) == '\'')) return trimBy(s1, 1, 1); else return s1.toString(); } public java.io.PrintStream debugStream = System.out; public void setDebugStream(java.io.PrintStream ds) { debugStream = ds; } private final int jjStopStringLiteralDfa_0(int pos, long active0) { switch (pos) { case 0: if ((active0 & 0x1f00000000L) != 0L) return 61; if ((active0 & 0x400000L) != 0L) { jjmatchedKind = 60; return 132; } if ((active0 & 0x200L) != 0L) return 477; if ((active0 & 0x400008000300000L) != 0L) { jjmatchedKind = 60; return 478; } if ((active0 & 0x20008000L) != 0L) return 478; return -1; case 1: if ((active0 & 0x1f00000000L) != 0L) { jjmatchedKind = 37; jjmatchedPos = 1; return 479; } if ((active0 & 0x400008020700000L) != 0L) { jjmatchedKind = 60; jjmatchedPos = 1; return 478; } return -1; case 2: if ((active0 & 0x400008000200000L) != 0L) { jjmatchedKind = 60; jjmatchedPos = 2; return 478; } if ((active0 & 0x1f00000000L) != 0L) { jjmatchedKind = 37; jjmatchedPos = 2; return 479; } if ((active0 & 0x500000L) != 0L) return 478; return -1; case 3: if ((active0 & 0x8000000000L) != 0L) { jjmatchedKind = 60; jjmatchedPos = 3; return 478; } if ((active0 & 0x1f00000000L) != 0L) { jjmatchedKind = 37; jjmatchedPos = 3; return 479; } if ((active0 & 0x200000L) != 0L) return 478; return -1; case 4: if ((active0 & 0x200000000L) != 0L) return 479; if ((active0 & 0x8000000000L) != 0L) { jjmatchedKind = 60; jjmatchedPos = 4; return 478; } if ((active0 & 0x1d00000000L) != 0L) { jjmatchedKind = 37; jjmatchedPos = 4; return 479; } return -1; case 5: if ((active0 & 0x8000000000L) != 0L) { jjmatchedKind = 60; jjmatchedPos = 5; return 478; } if ((active0 & 0x400000000L) != 0L) return 479; if ((active0 & 0x1900000000L) != 0L) { jjmatchedKind = 37; jjmatchedPos = 5; return 479; } return -1; case 6: if ((active0 & 0x1800000000L) != 0L) { jjmatchedKind = 37; jjmatchedPos = 6; return 479; } if ((active0 & 0x100000000L) != 0L) return 479; if ((active0 & 0x8000000000L) != 0L) return 478; return -1; case 7: if ((active0 & 0x1000000000L) != 0L) return 479; if ((active0 & 0x800000000L) != 0L) { jjmatchedKind = 37; jjmatchedPos = 7; return 479; } return -1; case 8: if ((active0 & 0x800000000L) != 0L) { jjmatchedKind = 37; jjmatchedPos = 8; return 479; } return -1; default : return -1; } } private final int jjStartNfa_0(int pos, long active0) { return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0), pos + 1); } private final int jjStopAtPos(int pos, int kind) { jjmatchedKind = kind; jjmatchedPos = pos; return pos + 1; } private final int jjStartNfaWithStates_0(int pos, int kind, int state) { jjmatchedKind = kind; jjmatchedPos = pos; try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { return pos + 1; } return jjMoveNfa_0(state, pos + 1); } private final int jjMoveStringLiteralDfa0_0() { switch(curChar) { case 40: return jjStopAtPos(0, 7); case 41: return jjStopAtPos(0, 25); case 42: return jjStopAtPos(0, 12); case 43: return jjStopAtPos(0, 14); case 44: return jjStopAtPos(0, 8); case 45: jjmatchedKind = 15; return jjMoveStringLiteralDfa1_0(0x20000000L); case 46: return jjStartNfaWithStates_0(0, 9, 477); case 47: jjmatchedKind = 13; return jjMoveStringLiteralDfa1_0(0x4L); case 58: return jjStopAtPos(0, 11); case 59: return jjStopAtPos(0, 10); case 60: return jjMoveStringLiteralDfa1_0(0x10000000L); case 61: return jjStopAtPos(0, 16); case 62: return jjStopAtPos(0, 17); case 64: return jjMoveStringLiteralDfa1_0(0x1f00000000L); case 91: return jjStopAtPos(0, 18); case 93: return jjStopAtPos(0, 19); case 65: case 97: return jjMoveStringLiteralDfa1_0(0x400000L); case 73: case 105: return jjMoveStringLiteralDfa1_0(0x8000000000L); case 78: case 110: return jjMoveStringLiteralDfa1_0(0x100000L); case 79: case 111: return jjMoveStringLiteralDfa1_0(0x200000L); case 82: case 114: return jjMoveStringLiteralDfa1_0(0x400000000000000L); case 123: return jjStopAtPos(0, 5); case 124: return jjMoveStringLiteralDfa1_0(0x80000000L); case 125: return jjStopAtPos(0, 6); case 126: return jjMoveStringLiteralDfa1_0(0x40000000L); default : return jjMoveNfa_0(1, 0); } } private final int jjMoveStringLiteralDfa1_0(long active0) { try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(0, active0); return 1; } switch(curChar) { case 33: return jjMoveStringLiteralDfa2_0(active0, 0x10000000L); case 42: if ((active0 & 0x4L) != 0L) return jjStopAtPos(1, 2); break; case 45: return jjMoveStringLiteralDfa2_0(active0, 0x20000000L); case 61: if ((active0 & 0x40000000L) != 0L) return jjStopAtPos(1, 30); else if ((active0 & 0x80000000L) != 0L) return jjStopAtPos(1, 31); break; case 67: case 99: return jjMoveStringLiteralDfa2_0(active0, 0x1000000000L); case 70: case 102: return jjMoveStringLiteralDfa2_0(active0, 0x800000000L); case 71: case 103: return jjMoveStringLiteralDfa2_0(active0, 0x400000000000000L); case 73: case 105: return jjMoveStringLiteralDfa2_0(active0, 0x100000000L); case 77: case 109: return jjMoveStringLiteralDfa2_0(active0, 0x400000000L); case 78: case 110: return jjMoveStringLiteralDfa2_0(active0, 0x8000600000L); case 79: case 111: return jjMoveStringLiteralDfa2_0(active0, 0x100000L); case 80: case 112: return jjMoveStringLiteralDfa2_0(active0, 0x200000000L); default : break; } return jjStartNfa_0(0, active0); } private final int jjMoveStringLiteralDfa2_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(0, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(1, active0); return 2; } switch(curChar) { case 45: return jjMoveStringLiteralDfa3_0(active0, 0x10000000L); case 62: if ((active0 & 0x20000000L) != 0L) return jjStopAtPos(2, 29); break; case 65: case 97: return jjMoveStringLiteralDfa3_0(active0, 0x200000000L); case 66: case 98: return jjMoveStringLiteralDfa3_0(active0, 0x400000000000000L); case 68: case 100: if ((active0 & 0x400000L) != 0L) return jjStartNfaWithStates_0(2, 22, 478); break; case 69: case 101: return jjMoveStringLiteralDfa3_0(active0, 0x400000000L); case 72: case 104: return jjMoveStringLiteralDfa3_0(active0, 0x9000000000L); case 76: case 108: return jjMoveStringLiteralDfa3_0(active0, 0x200000L); case 77: case 109: return jjMoveStringLiteralDfa3_0(active0, 0x100000000L); case 79: case 111: return jjMoveStringLiteralDfa3_0(active0, 0x800000000L); case 84: case 116: if ((active0 & 0x100000L) != 0L) return jjStartNfaWithStates_0(2, 20, 478); break; default : break; } return jjStartNfa_0(1, active0); } private final int jjMoveStringLiteralDfa3_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(1, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(2, active0); return 3; } switch(curChar) { case 40: if ((active0 & 0x400000000000000L) != 0L) return jjStopAtPos(3, 58); break; case 45: if ((active0 & 0x10000000L) != 0L) return jjStopAtPos(3, 28); break; case 65: case 97: return jjMoveStringLiteralDfa4_0(active0, 0x1000000000L); case 68: case 100: return jjMoveStringLiteralDfa4_0(active0, 0x400000000L); case 69: case 101: return jjMoveStringLiteralDfa4_0(active0, 0x8000000000L); case 71: case 103: return jjMoveStringLiteralDfa4_0(active0, 0x200000000L); case 78: case 110: return jjMoveStringLiteralDfa4_0(active0, 0x800000000L); case 80: case 112: return jjMoveStringLiteralDfa4_0(active0, 0x100000000L); case 89: case 121: if ((active0 & 0x200000L) != 0L) return jjStartNfaWithStates_0(3, 21, 478); break; default : break; } return jjStartNfa_0(2, active0); } private final int jjMoveStringLiteralDfa4_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(2, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(3, active0); return 4; } switch(curChar) { case 69: case 101: if ((active0 & 0x200000000L) != 0L) return jjStartNfaWithStates_0(4, 33, 479); break; case 73: case 105: return jjMoveStringLiteralDfa5_0(active0, 0x400000000L); case 79: case 111: return jjMoveStringLiteralDfa5_0(active0, 0x100000000L); case 82: case 114: return jjMoveStringLiteralDfa5_0(active0, 0x9000000000L); case 84: case 116: return jjMoveStringLiteralDfa5_0(active0, 0x800000000L); default : break; } return jjStartNfa_0(3, active0); } private final int jjMoveStringLiteralDfa5_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(3, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(4, active0); return 5; } switch(curChar) { case 45: return jjMoveStringLiteralDfa6_0(active0, 0x800000000L); case 65: case 97: if ((active0 & 0x400000000L) != 0L) return jjStartNfaWithStates_0(5, 34, 479); break; case 73: case 105: return jjMoveStringLiteralDfa6_0(active0, 0x8000000000L); case 82: case 114: return jjMoveStringLiteralDfa6_0(active0, 0x100000000L); case 83: case 115: return jjMoveStringLiteralDfa6_0(active0, 0x1000000000L); default : break; } return jjStartNfa_0(4, active0); } private final int jjMoveStringLiteralDfa6_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(4, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(5, active0); return 6; } switch(curChar) { case 69: case 101: return jjMoveStringLiteralDfa7_0(active0, 0x1000000000L); case 70: case 102: return jjMoveStringLiteralDfa7_0(active0, 0x800000000L); case 84: case 116: if ((active0 & 0x100000000L) != 0L) return jjStartNfaWithStates_0(6, 32, 479); else if ((active0 & 0x8000000000L) != 0L) return jjStartNfaWithStates_0(6, 39, 478); break; default : break; } return jjStartNfa_0(5, active0); } private final int jjMoveStringLiteralDfa7_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(5, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(6, active0); return 7; } switch(curChar) { case 65: case 97: return jjMoveStringLiteralDfa8_0(active0, 0x800000000L); case 84: case 116: if ((active0 & 0x1000000000L) != 0L) return jjStartNfaWithStates_0(7, 36, 479); break; default : break; } return jjStartNfa_0(6, active0); } private final int jjMoveStringLiteralDfa8_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(6, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(7, active0); return 8; } switch(curChar) { case 67: case 99: return jjMoveStringLiteralDfa9_0(active0, 0x800000000L); default : break; } return jjStartNfa_0(7, active0); } private final int jjMoveStringLiteralDfa9_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(7, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(8, active0); return 9; } switch(curChar) { case 69: case 101: if ((active0 & 0x800000000L) != 0L) return jjStartNfaWithStates_0(9, 35, 479); break; default : break; } return jjStartNfa_0(8, active0); } private final void jjCheckNAdd(int state) { if (jjrounds[state] != jjround) { jjstateSet[jjnewStateCnt++] = state; jjrounds[state] = jjround; } } private final void jjAddStates(int start, int end) { do { jjstateSet[jjnewStateCnt++] = jjnextStates[start]; } while (start++ != end); } private final void jjCheckNAddTwoStates(int state1, int state2) { jjCheckNAdd(state1); jjCheckNAdd(state2); } private final void jjCheckNAddStates(int start, int end) { do { jjCheckNAdd(jjnextStates[start]); } while (start++ != end); } private final void jjCheckNAddStates(int start) { jjCheckNAdd(jjnextStates[start]); jjCheckNAdd(jjnextStates[start + 1]); } static final long[] jjbitVec0 = { 0xfffffffffffffffeL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL }; static final long[] jjbitVec2 = { 0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL }; private final int jjMoveNfa_0(int startState, int curPos) { int[] nextStates; int startsAt = 0; jjnewStateCnt = 477; int i = 1; jjstateSet[0] = startState; int j, kind = 0x7fffffff; for (;;) { if (++jjround == 0x7fffffff) ReInitRounds(); if (curChar < 64) { long l = 1L << curChar; MatchLoop: do { switch(jjstateSet[--i]) { case 479: case 62: if ((0x3ff200000000000L & l) == 0L) break; if (kind > 37) kind = 37; jjCheckNAddTwoStates(62, 63); break; case 477: if ((0x3ff000000000000L & l) != 0L) { if (kind > 62) kind = 62; jjCheckNAdd(359); } if ((0x3ff000000000000L & l) != 0L) { if (kind > 57) kind = 57; jjCheckNAdd(358); } if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(356, 357); if ((0x3ff000000000000L & l) != 0L) jjCheckNAddStates(0, 2); if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(321, 324); if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(318, 320); if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(316, 317); if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(313, 315); if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(308, 312); if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(304, 307); if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(300, 303); if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(297, 299); if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(294, 296); if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(291, 293); if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(288, 290); if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(285, 287); if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(282, 284); if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(279, 281); if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(276, 278); break; case 1: if ((0x3ff000000000000L & l) != 0L) { if (kind > 57) kind = 57; jjCheckNAddStates(3, 77); } else if ((0x100003600L & l) != 0L) { if (kind > 1) kind = 1; jjCheckNAdd(0); } else if (curChar == 45) { if (kind > 60) kind = 60; jjCheckNAddStates(78, 82); } else if (curChar == 46) jjCheckNAddStates(83, 101); else if (curChar == 33) jjCheckNAddTwoStates(92, 101); else if (curChar == 39) jjCheckNAddStates(102, 104); else if (curChar == 34) jjCheckNAddStates(105, 107); else if (curChar == 35) jjCheckNAddTwoStates(2, 3); break; case 61: if (curChar != 45) break; if (kind > 37) kind = 37; jjCheckNAddTwoStates(62, 63); break; case 132: if ((0x3ff200000000000L & l) != 0L) { if (kind > 60) kind = 60; jjCheckNAddTwoStates(378, 379); } else if (curChar == 40) { if (kind > 59) kind = 59; } if ((0x3ff200000000000L & l) != 0L) jjCheckNAddStates(108, 110); break; case 478: if ((0x3ff200000000000L & l) != 0L) { if (kind > 60) kind = 60; jjCheckNAddTwoStates(378, 379); } else if (curChar == 40) { if (kind > 59) kind = 59; } if ((0x3ff200000000000L & l) != 0L) jjCheckNAddStates(108, 110); break; case 0: if ((0x100003600L & l) == 0L) break; if (kind > 1) kind = 1; jjCheckNAdd(0); break; case 2: if ((0x3ff200000000000L & l) == 0L) break; if (kind > 23) kind = 23; jjCheckNAddTwoStates(2, 3); break; case 4: if ((0xffffffff00000000L & l) == 0L) break; if (kind > 23) kind = 23; jjCheckNAddTwoStates(2, 3); break; case 5: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 23) kind = 23; jjCheckNAddStates(111, 118); break; case 6: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 23) kind = 23; jjCheckNAddStates(119, 121); break; case 7: if ((0x100003600L & l) == 0L) break; if (kind > 23) kind = 23; jjCheckNAddTwoStates(2, 3); break; case 8: case 10: case 13: case 17: if ((0x3ff000000000000L & l) != 0L) jjCheckNAdd(6); break; case 9: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 10; break; case 11: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 12; break; case 12: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 13; break; case 14: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 15; break; case 15: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 16; break; case 16: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 17; break; case 18: if (curChar == 34) jjCheckNAddStates(105, 107); break; case 19: if ((0xfffffffb00000200L & l) != 0L) jjCheckNAddStates(105, 107); break; case 20: if (curChar == 34 && kind > 24) kind = 24; break; case 22: if ((0x3400L & l) != 0L) jjCheckNAddStates(105, 107); break; case 23: if (curChar == 10) jjCheckNAddStates(105, 107); break; case 24: if (curChar == 13) jjstateSet[jjnewStateCnt++] = 23; break; case 25: if ((0xffffffff00000000L & l) != 0L) jjCheckNAddStates(105, 107); break; case 26: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddStates(122, 130); break; case 27: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddStates(131, 134); break; case 28: if ((0x100003600L & l) != 0L) jjCheckNAddStates(105, 107); break; case 29: case 31: case 34: case 38: if ((0x3ff000000000000L & l) != 0L) jjCheckNAdd(27); break; case 30: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 31; break; case 32: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 33; break; case 33: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 34; break; case 35: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 36; break; case 36: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 37; break; case 37: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 38; break; case 39: if (curChar == 39) jjCheckNAddStates(102, 104); break; case 40: if ((0xffffff7f00000200L & l) != 0L) jjCheckNAddStates(102, 104); break; case 41: if (curChar == 39 && kind > 24) kind = 24; break; case 43: if ((0x3400L & l) != 0L) jjCheckNAddStates(102, 104); break; case 44: if (curChar == 10) jjCheckNAddStates(102, 104); break; case 45: if (curChar == 13) jjstateSet[jjnewStateCnt++] = 44; break; case 46: if ((0xffffffff00000000L & l) != 0L) jjCheckNAddStates(102, 104); break; case 47: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddStates(135, 143); break; case 48: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddStates(144, 147); break; case 49: if ((0x100003600L & l) != 0L) jjCheckNAddStates(102, 104); break; case 50: case 52: case 55: case 59: if ((0x3ff000000000000L & l) != 0L) jjCheckNAdd(48); break; case 51: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 52; break; case 53: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 54; break; case 54: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 55; break; case 56: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 57; break; case 57: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 58; break; case 58: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 59; break; case 64: if ((0xffffffff00000000L & l) == 0L) break; if (kind > 37) kind = 37; jjCheckNAddTwoStates(62, 63); break; case 65: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 37) kind = 37; jjCheckNAddStates(148, 155); break; case 66: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 37) kind = 37; jjCheckNAddStates(156, 158); break; case 67: if ((0x100003600L & l) == 0L) break; if (kind > 37) kind = 37; jjCheckNAddTwoStates(62, 63); break; case 68: case 70: case 73: case 77: if ((0x3ff000000000000L & l) != 0L) jjCheckNAdd(66); break; case 69: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 70; break; case 71: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 72; break; case 72: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 73; break; case 74: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 75; break; case 75: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 76; break; case 76: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 77; break; case 79: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 37) kind = 37; jjCheckNAddStates(159, 166); break; case 80: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 37) kind = 37; jjCheckNAddStates(167, 169); break; case 81: case 83: case 86: case 90: if ((0x3ff000000000000L & l) != 0L) jjCheckNAdd(80); break; case 82: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 83; break; case 84: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 85; break; case 85: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 86; break; case 87: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 88; break; case 88: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 89; break; case 89: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 90; break; case 91: if (curChar == 33) jjCheckNAddTwoStates(92, 101); break; case 92: if ((0x100003600L & l) != 0L) jjCheckNAddTwoStates(92, 101); break; case 154: if (curChar == 40) jjCheckNAddStates(170, 175); break; case 155: if ((0xfffffc7a00000000L & l) != 0L) jjCheckNAddStates(176, 179); break; case 156: if ((0x100003600L & l) != 0L) jjCheckNAddTwoStates(156, 157); break; case 157: if (curChar == 41 && kind > 27) kind = 27; break; case 159: if ((0xffffffff00000000L & l) != 0L) jjCheckNAddStates(176, 179); break; case 160: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddStates(180, 188); break; case 161: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddStates(189, 192); break; case 162: if ((0x100003600L & l) != 0L) jjCheckNAddStates(176, 179); break; case 163: case 165: case 168: case 172: if ((0x3ff000000000000L & l) != 0L) jjCheckNAdd(161); break; case 164: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 165; break; case 166: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 167; break; case 167: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 168; break; case 169: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 170; break; case 170: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 171; break; case 171: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 172; break; case 173: if (curChar == 39) jjCheckNAddStates(193, 195); break; case 174: if ((0xffffff7f00000200L & l) != 0L) jjCheckNAddStates(193, 195); break; case 175: if (curChar == 39) jjCheckNAddTwoStates(156, 157); break; case 177: if ((0x3400L & l) != 0L) jjCheckNAddStates(193, 195); break; case 178: if (curChar == 10) jjCheckNAddStates(193, 195); break; case 179: if (curChar == 13) jjstateSet[jjnewStateCnt++] = 178; break; case 180: if ((0xffffffff00000000L & l) != 0L) jjCheckNAddStates(193, 195); break; case 181: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddStates(196, 204); break; case 182: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddStates(205, 208); break; case 183: if ((0x100003600L & l) != 0L) jjCheckNAddStates(193, 195); break; case 184: case 186: case 189: case 193: if ((0x3ff000000000000L & l) != 0L) jjCheckNAdd(182); break; case 185: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 186; break; case 187: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 188; break; case 188: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 189; break; case 190: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 191; break; case 191: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 192; break; case 192: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 193; break; case 194: if (curChar == 34) jjCheckNAddStates(209, 211); break; case 195: if ((0xfffffffb00000200L & l) != 0L) jjCheckNAddStates(209, 211); break; case 196: if (curChar == 34) jjCheckNAddTwoStates(156, 157); break; case 198: if ((0x3400L & l) != 0L) jjCheckNAddStates(209, 211); break; case 199: if (curChar == 10) jjCheckNAddStates(209, 211); break; case 200: if (curChar == 13) jjstateSet[jjnewStateCnt++] = 199; break; case 201: if ((0xffffffff00000000L & l) != 0L) jjCheckNAddStates(209, 211); break; case 202: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddStates(212, 220); break; case 203: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddStates(221, 224); break; case 204: if ((0x100003600L & l) != 0L) jjCheckNAddStates(209, 211); break; case 205: case 207: case 210: case 214: if ((0x3ff000000000000L & l) != 0L) jjCheckNAdd(203); break; case 206: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 207; break; case 208: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 209; break; case 209: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 210; break; case 211: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 212; break; case 212: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 213; break; case 213: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 214; break; case 215: if ((0x100003600L & l) != 0L) jjCheckNAddStates(225, 231); break; case 218: if (curChar == 43) jjCheckNAddStates(232, 234); break; case 219: case 248: if (curChar == 63 && kind > 63) kind = 63; break; case 220: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 63) kind = 63; jjCheckNAddStates(235, 243); break; case 221: if ((0x3ff000000000000L & l) != 0L) jjCheckNAdd(222); break; case 222: if (curChar == 45) jjstateSet[jjnewStateCnt++] = 223; break; case 223: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 63) kind = 63; jjCheckNAddStates(244, 248); break; case 224: if ((0x3ff000000000000L & l) != 0L && kind > 63) kind = 63; break; case 225: case 227: case 230: case 234: if ((0x3ff000000000000L & l) != 0L) jjCheckNAdd(224); break; case 226: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 227; break; case 228: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 229; break; case 229: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 230; break; case 231: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 232; break; case 232: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 233; break; case 233: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 234; break; case 235: case 237: case 240: case 244: if ((0x3ff000000000000L & l) != 0L) jjCheckNAdd(221); break; case 236: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 237; break; case 238: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 239; break; case 239: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 240; break; case 241: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 242; break; case 242: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 243; break; case 243: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 244; break; case 245: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 63) kind = 63; jjCheckNAddStates(249, 251); break; case 246: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 63) kind = 63; jjCheckNAddStates(252, 254); break; case 247: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 63) kind = 63; jjCheckNAddStates(255, 257); break; case 249: case 252: case 254: case 255: case 258: case 259: case 261: case 265: case 269: case 272: case 274: if (curChar == 63) jjCheckNAdd(248); break; case 250: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 63) kind = 63; jjCheckNAddTwoStates(219, 224); break; case 251: if (curChar == 63) jjCheckNAddTwoStates(248, 252); break; case 253: if (curChar == 63) jjCheckNAddStates(258, 260); break; case 256: if (curChar == 63) jjstateSet[jjnewStateCnt++] = 255; break; case 257: if (curChar == 63) jjCheckNAddStates(261, 264); break; case 260: if (curChar == 63) jjstateSet[jjnewStateCnt++] = 259; break; case 262: if (curChar == 63) jjstateSet[jjnewStateCnt++] = 261; break; case 263: if (curChar == 63) jjstateSet[jjnewStateCnt++] = 262; break; case 264: if (curChar == 63) jjCheckNAddStates(265, 269); break; case 266: if (curChar == 63) jjstateSet[jjnewStateCnt++] = 265; break; case 267: if (curChar == 63) jjstateSet[jjnewStateCnt++] = 266; break; case 268: if (curChar == 63) jjstateSet[jjnewStateCnt++] = 267; break; case 270: if (curChar == 63) jjstateSet[jjnewStateCnt++] = 269; break; case 271: if (curChar == 63) jjstateSet[jjnewStateCnt++] = 270; break; case 273: if (curChar == 63) jjstateSet[jjnewStateCnt++] = 272; break; case 275: if (curChar == 46) jjCheckNAddStates(83, 101); break; case 276: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(276, 278); break; case 279: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(279, 281); break; case 282: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(282, 284); break; case 285: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(285, 287); break; case 288: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(288, 290); break; case 291: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(291, 293); break; case 294: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(294, 296); break; case 297: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(297, 299); break; case 300: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(300, 303); break; case 304: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(304, 307); break; case 308: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(308, 312); break; case 313: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(313, 315); break; case 316: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(316, 317); break; case 318: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(318, 320); break; case 321: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(321, 324); break; case 325: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddStates(0, 2); break; case 326: if (curChar != 45) break; if (kind > 55) kind = 55; jjCheckNAddTwoStates(327, 328); break; case 327: if ((0x3ff200000000000L & l) == 0L) break; if (kind > 55) kind = 55; jjCheckNAddTwoStates(327, 328); break; case 329: if ((0xffffffff00000000L & l) == 0L) break; if (kind > 55) kind = 55; jjCheckNAddTwoStates(327, 328); break; case 330: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 55) kind = 55; jjCheckNAddStates(270, 277); break; case 331: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 55) kind = 55; jjCheckNAddStates(278, 280); break; case 332: if ((0x100003600L & l) == 0L) break; if (kind > 55) kind = 55; jjCheckNAddTwoStates(327, 328); break; case 333: case 335: case 338: case 342: if ((0x3ff000000000000L & l) != 0L) jjCheckNAdd(331); break; case 334: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 335; break; case 336: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 337; break; case 337: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 338; break; case 339: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 340; break; case 340: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 341; break; case 341: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 342; break; case 344: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 55) kind = 55; jjCheckNAddStates(281, 288); break; case 345: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 55) kind = 55; jjCheckNAddStates(289, 291); break; case 346: case 348: case 351: case 355: if ((0x3ff000000000000L & l) != 0L) jjCheckNAdd(345); break; case 347: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 348; break; case 349: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 350; break; case 350: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 351; break; case 352: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 353; break; case 353: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 354; break; case 354: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 355; break; case 356: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(356, 357); break; case 357: if (curChar == 37 && kind > 56) kind = 56; break; case 358: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 57) kind = 57; jjCheckNAdd(358); break; case 359: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 62) kind = 62; jjCheckNAdd(359); break; case 360: if (curChar != 45) break; if (kind > 60) kind = 60; jjCheckNAddStates(78, 82); break; case 361: if ((0x3ff200000000000L & l) != 0L) jjCheckNAddStates(108, 110); break; case 362: if (curChar == 40 && kind > 59) kind = 59; break; case 364: if ((0xffffffff00000000L & l) != 0L) jjCheckNAddStates(108, 110); break; case 365: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddStates(292, 300); break; case 366: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddStates(301, 304); break; case 367: if ((0x100003600L & l) != 0L) jjCheckNAddStates(108, 110); break; case 368: case 370: case 373: case 377: if ((0x3ff000000000000L & l) != 0L) jjCheckNAdd(366); break; case 369: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 370; break; case 371: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 372; break; case 372: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 373; break; case 374: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 375; break; case 375: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 376; break; case 376: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 377; break; case 378: if ((0x3ff200000000000L & l) == 0L) break; if (kind > 60) kind = 60; jjCheckNAddTwoStates(378, 379); break; case 380: if ((0xffffffff00000000L & l) == 0L) break; if (kind > 60) kind = 60; jjCheckNAddTwoStates(378, 379); break; case 381: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 60) kind = 60; jjCheckNAddStates(305, 312); break; case 382: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 60) kind = 60; jjCheckNAddStates(313, 315); break; case 383: if ((0x100003600L & l) == 0L) break; if (kind > 60) kind = 60; jjCheckNAddTwoStates(378, 379); break; case 384: case 386: case 389: case 393: if ((0x3ff000000000000L & l) != 0L) jjCheckNAdd(382); break; case 385: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 386; break; case 387: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 388; break; case 388: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 389; break; case 390: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 391; break; case 391: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 392; break; case 392: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 393; break; case 394: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 57) kind = 57; jjCheckNAddStates(3, 77); break; case 395: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(395, 278); break; case 396: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(396, 397); break; case 397: if (curChar == 46) jjCheckNAdd(276); break; case 398: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(398, 281); break; case 399: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(399, 400); break; case 400: if (curChar == 46) jjCheckNAdd(279); break; case 401: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(401, 284); break; case 402: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(402, 403); break; case 403: if (curChar == 46) jjCheckNAdd(282); break; case 404: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(404, 287); break; case 405: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(405, 406); break; case 406: if (curChar == 46) jjCheckNAdd(285); break; case 407: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(407, 290); break; case 408: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(408, 409); break; case 409: if (curChar == 46) jjCheckNAdd(288); break; case 410: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(410, 293); break; case 411: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(411, 412); break; case 412: if (curChar == 46) jjCheckNAdd(291); break; case 413: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(413, 296); break; case 414: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(414, 415); break; case 415: if (curChar == 46) jjCheckNAdd(294); break; case 416: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(416, 299); break; case 417: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(417, 418); break; case 418: if (curChar == 46) jjCheckNAdd(297); break; case 419: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(419, 303); break; case 420: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(420, 421); break; case 421: if (curChar == 46) jjCheckNAdd(300); break; case 422: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(422, 307); break; case 423: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(423, 424); break; case 424: if (curChar == 46) jjCheckNAdd(304); break; case 425: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(425, 312); break; case 426: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(426, 427); break; case 427: if (curChar == 46) jjCheckNAdd(308); break; case 428: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(428, 315); break; case 429: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(429, 430); break; case 430: if (curChar == 46) jjCheckNAdd(313); break; case 431: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(431, 317); break; case 432: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(432, 433); break; case 433: if (curChar == 46) jjCheckNAdd(316); break; case 434: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(434, 320); break; case 435: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(435, 436); break; case 436: if (curChar == 46) jjCheckNAdd(318); break; case 437: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(437, 324); break; case 438: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(438, 439); break; case 439: if (curChar == 46) jjCheckNAdd(321); break; case 440: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddStates(316, 318); break; case 441: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(441, 442); break; case 442: if (curChar == 46) jjCheckNAdd(325); break; case 443: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(443, 357); break; case 444: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(444, 445); break; case 445: if (curChar == 46) jjCheckNAdd(356); break; case 446: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 57) kind = 57; jjCheckNAdd(446); break; case 447: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(447, 448); break; case 448: if (curChar == 46) jjCheckNAdd(358); break; case 449: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 62) kind = 62; jjCheckNAdd(449); break; case 450: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(450, 451); break; case 451: if (curChar == 46) jjCheckNAdd(359); break; case 453: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 60) kind = 60; jjCheckNAddStates(319, 326); break; case 454: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 60) kind = 60; jjCheckNAddStates(327, 329); break; case 455: case 457: case 460: case 464: if ((0x3ff000000000000L & l) != 0L) jjCheckNAdd(454); break; case 456: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 457; break; case 458: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 459; break; case 459: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 460; break; case 461: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 462; break; case 462: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 463; break; case 463: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 464; break; case 465: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddStates(330, 338); break; case 466: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddStates(339, 342); break; case 467: case 469: case 472: case 476: if ((0x3ff000000000000L & l) != 0L) jjCheckNAdd(466); break; case 468: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 469; break; case 470: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 471; break; case 471: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 472; break; case 473: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 474; break; case 474: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 475; break; case 475: if ((0x3ff000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 476; break; default : break; } } while(i != startsAt); } else if (curChar < 128) { long l = 1L << (curChar & 077); MatchLoop: do { switch(jjstateSet[--i]) { case 479: if ((0x7fffffe87fffffeL & l) != 0L) { if (kind > 37) kind = 37; jjCheckNAddTwoStates(62, 63); } else if (curChar == 92) jjCheckNAddTwoStates(64, 65); break; case 1: if ((0x7fffffe87fffffeL & l) != 0L) { if (kind > 60) kind = 60; jjCheckNAddStates(78, 82); } else if (curChar == 92) jjCheckNAddStates(343, 346); else if (curChar == 64) jjAddStates(347, 348); if ((0x20000000200000L & l) != 0L) jjAddStates(349, 350); else if ((0x10000000100000L & l) != 0L) jjAddStates(351, 352); else if ((0x1000000010000L & l) != 0L) jjAddStates(353, 354); else if ((0x200000002L & l) != 0L) jjAddStates(355, 356); else if ((0x2000000020L & l) != 0L) jjstateSet[jjnewStateCnt++] = 128; else if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 121; else if ((0x10000000100L & l) != 0L) jjstateSet[jjnewStateCnt++] = 115; else if ((0x400000004L & l) != 0L) jjstateSet[jjnewStateCnt++] = 107; break; case 61: if ((0x7fffffe87fffffeL & l) != 0L) { if (kind > 37) kind = 37; jjCheckNAddTwoStates(62, 63); } else if (curChar == 92) jjCheckNAddTwoStates(64, 79); break; case 132: if ((0x7fffffe87fffffeL & l) != 0L) { if (kind > 60) kind = 60; jjCheckNAddTwoStates(378, 379); } else if (curChar == 92) jjCheckNAddTwoStates(364, 365); if ((0x7fffffe87fffffeL & l) != 0L) jjCheckNAddStates(108, 110); else if (curChar == 92) jjCheckNAddTwoStates(380, 381); if ((0x20000000200000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 134; else if ((0x100000001000L & l) != 0L) jjCheckNAdd(131); break; case 478: if ((0x7fffffe87fffffeL & l) != 0L) { if (kind > 60) kind = 60; jjCheckNAddTwoStates(378, 379); } else if (curChar == 92) jjCheckNAddTwoStates(364, 365); if ((0x7fffffe87fffffeL & l) != 0L) jjCheckNAddStates(108, 110); else if (curChar == 92) jjCheckNAddTwoStates(380, 381); break; case 2: if ((0x7fffffe87fffffeL & l) == 0L) break; if (kind > 23) kind = 23; jjCheckNAddTwoStates(2, 3); break; case 3: if (curChar == 92) jjAddStates(357, 358); break; case 4: if ((0x7fffffffffffffffL & l) == 0L) break; if (kind > 23) kind = 23; jjCheckNAddTwoStates(2, 3); break; case 5: if ((0x7e0000007eL & l) == 0L) break; if (kind > 23) kind = 23; jjCheckNAddStates(111, 118); break; case 6: if ((0x7e0000007eL & l) == 0L) break; if (kind > 23) kind = 23; jjCheckNAddStates(119, 121); break; case 8: case 10: case 13: case 17: if ((0x7e0000007eL & l) != 0L) jjCheckNAdd(6); break; case 9: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 10; break; case 11: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 12; break; case 12: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 13; break; case 14: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 15; break; case 15: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 16; break; case 16: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 17; break; case 19: case 25: if ((0x7fffffffffffffffL & l) != 0L) jjCheckNAddStates(105, 107); break; case 21: if (curChar == 92) jjAddStates(359, 362); break; case 26: if ((0x7e0000007eL & l) != 0L) jjCheckNAddStates(122, 130); break; case 27: if ((0x7e0000007eL & l) != 0L) jjCheckNAddStates(131, 134); break; case 29: case 31: case 34: case 38: if ((0x7e0000007eL & l) != 0L) jjCheckNAdd(27); break; case 30: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 31; break; case 32: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 33; break; case 33: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 34; break; case 35: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 36; break; case 36: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 37; break; case 37: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 38; break; case 40: case 46: if ((0x7fffffffffffffffL & l) != 0L) jjCheckNAddStates(102, 104); break; case 42: if (curChar == 92) jjAddStates(363, 366); break; case 47: if ((0x7e0000007eL & l) != 0L) jjCheckNAddStates(135, 143); break; case 48: if ((0x7e0000007eL & l) != 0L) jjCheckNAddStates(144, 147); break; case 50: case 52: case 55: case 59: if ((0x7e0000007eL & l) != 0L) jjCheckNAdd(48); break; case 51: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 52; break; case 53: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 54; break; case 54: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 55; break; case 56: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 57; break; case 57: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 58; break; case 58: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 59; break; case 60: if (curChar == 64) jjAddStates(347, 348); break; case 62: if ((0x7fffffe87fffffeL & l) == 0L) break; if (kind > 37) kind = 37; jjCheckNAddTwoStates(62, 63); break; case 63: if (curChar == 92) jjCheckNAddTwoStates(64, 65); break; case 64: if ((0x7fffffffffffffffL & l) == 0L) break; if (kind > 37) kind = 37; jjCheckNAddTwoStates(62, 63); break; case 65: if ((0x7e0000007eL & l) == 0L) break; if (kind > 37) kind = 37; jjCheckNAddStates(148, 155); break; case 66: if ((0x7e0000007eL & l) == 0L) break; if (kind > 37) kind = 37; jjCheckNAddStates(156, 158); break; case 68: case 70: case 73: case 77: if ((0x7e0000007eL & l) != 0L) jjCheckNAdd(66); break; case 69: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 70; break; case 71: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 72; break; case 72: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 73; break; case 74: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 75; break; case 75: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 76; break; case 76: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 77; break; case 78: if (curChar == 92) jjCheckNAddTwoStates(64, 79); break; case 79: if ((0x7e0000007eL & l) == 0L) break; if (kind > 37) kind = 37; jjCheckNAddStates(159, 166); break; case 80: if ((0x7e0000007eL & l) == 0L) break; if (kind > 37) kind = 37; jjCheckNAddStates(167, 169); break; case 81: case 83: case 86: case 90: if ((0x7e0000007eL & l) != 0L) jjCheckNAdd(80); break; case 82: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 83; break; case 84: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 85; break; case 85: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 86; break; case 87: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 88; break; case 88: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 89; break; case 89: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 90; break; case 93: if ((0x10000000100000L & l) != 0L && kind > 38) kind = 38; break; case 94: if ((0x400000004000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 93; break; case 95: if ((0x200000002L & l) != 0L) jjstateSet[jjnewStateCnt++] = 94; break; case 96: if ((0x10000000100000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 95; break; case 97: if ((0x4000000040000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 96; break; case 98: if ((0x800000008000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 97; break; case 99: if ((0x1000000010000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 98; break; case 100: if ((0x200000002000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 99; break; case 101: if ((0x20000000200L & l) != 0L) jjstateSet[jjnewStateCnt++] = 100; break; case 102: if ((0x2000000020L & l) != 0L && kind > 81) kind = 81; break; case 103: if ((0x100000001000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 102; break; case 104: if ((0x100000001000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 103; break; case 105: if ((0x20000000200L & l) != 0L) jjstateSet[jjnewStateCnt++] = 104; break; case 106: if ((0x200000002L & l) != 0L) jjstateSet[jjnewStateCnt++] = 105; break; case 107: if ((0x4000000040000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 106; break; case 108: if ((0x400000004L & l) != 0L) jjstateSet[jjnewStateCnt++] = 107; break; case 109: if ((0x1000000010L & l) != 0L && kind > 81) kind = 81; break; case 110: if ((0x100000001000L & l) != 0L) jjCheckNAdd(109); break; case 111: if ((0x2000000020L & l) != 0L) jjstateSet[jjnewStateCnt++] = 110; break; case 112: if ((0x10000000100L & l) != 0L) jjstateSet[jjnewStateCnt++] = 111; break; case 113: if ((0x1000000010L & l) != 0L) jjstateSet[jjnewStateCnt++] = 112; break; case 114: if ((0x400000004000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 113; break; case 115: if ((0x200000002L & l) != 0L) jjstateSet[jjnewStateCnt++] = 114; break; case 116: if ((0x10000000100L & l) != 0L) jjstateSet[jjnewStateCnt++] = 115; break; case 117: if ((0x400000004000L & l) != 0L && kind > 81) kind = 81; break; case 118: if ((0x2000000020L & l) != 0L) jjCheckNAdd(117); break; case 119: if ((0x2000000020L & l) != 0L) jjstateSet[jjnewStateCnt++] = 118; break; case 120: if ((0x4000000040000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 119; break; case 121: if ((0x800000008L & l) != 0L) jjstateSet[jjnewStateCnt++] = 120; break; case 122: if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 121; break; case 123: if ((0x2000000020L & l) != 0L) jjCheckNAdd(109); break; case 124: if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 123; break; case 125: if ((0x8000000080000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 124; break; case 126: if ((0x800000008000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 125; break; case 127: if ((0x400000004L & l) != 0L) jjstateSet[jjnewStateCnt++] = 126; break; case 128: if ((0x200000002000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 127; break; case 129: if ((0x2000000020L & l) != 0L) jjstateSet[jjnewStateCnt++] = 128; break; case 130: if ((0x200000002L & l) != 0L) jjAddStates(355, 356); break; case 131: if ((0x100000001000L & l) != 0L && kind > 81) kind = 81; break; case 133: if ((0x200000002L & l) != 0L) jjCheckNAdd(131); break; case 134: if ((0x4000000040000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 133; break; case 135: if ((0x20000000200000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 134; break; case 136: if ((0x1000000010000L & l) != 0L) jjAddStates(353, 354); break; case 137: if ((0x10000000100000L & l) != 0L && kind > 81) kind = 81; break; case 138: if ((0x400000004000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 137; break; case 139: if ((0x20000000200L & l) != 0L) jjstateSet[jjnewStateCnt++] = 138; break; case 140: if ((0x4000000040000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 139; break; case 141: if ((0x800000008000L & l) != 0L) jjCheckNAdd(117); break; case 142: if ((0x20000000200L & l) != 0L) jjstateSet[jjnewStateCnt++] = 141; break; case 143: if ((0x10000000100000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 142; break; case 144: if ((0x800000008L & l) != 0L) jjstateSet[jjnewStateCnt++] = 143; break; case 145: if ((0x2000000020L & l) != 0L) jjstateSet[jjnewStateCnt++] = 144; break; case 146: if ((0x40000000400L & l) != 0L) jjstateSet[jjnewStateCnt++] = 145; break; case 147: if ((0x800000008000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 146; break; case 148: if ((0x4000000040000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 147; break; case 149: if ((0x10000000100000L & l) != 0L) jjAddStates(351, 352); break; case 150: if ((0x200000002000000L & l) != 0L && kind > 81) kind = 81; break; case 151: if ((0x10000000100000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 150; break; case 152: if ((0x40000000400000L & l) != 0L && kind > 81) kind = 81; break; case 153: if ((0x20000000200000L & l) != 0L) jjAddStates(349, 350); break; case 155: case 159: if ((0x7fffffffffffffffL & l) != 0L) jjCheckNAddStates(176, 179); break; case 158: if (curChar == 92) jjAddStates(367, 368); break; case 160: if ((0x7e0000007eL & l) != 0L) jjCheckNAddStates(180, 188); break; case 161: if ((0x7e0000007eL & l) != 0L) jjCheckNAddStates(189, 192); break; case 163: case 165: case 168: case 172: if ((0x7e0000007eL & l) != 0L) jjCheckNAdd(161); break; case 164: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 165; break; case 166: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 167; break; case 167: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 168; break; case 169: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 170; break; case 170: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 171; break; case 171: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 172; break; case 174: case 180: if ((0x7fffffffffffffffL & l) != 0L) jjCheckNAddStates(193, 195); break; case 176: if (curChar == 92) jjAddStates(369, 372); break; case 181: if ((0x7e0000007eL & l) != 0L) jjCheckNAddStates(196, 204); break; case 182: if ((0x7e0000007eL & l) != 0L) jjCheckNAddStates(205, 208); break; case 184: case 186: case 189: case 193: if ((0x7e0000007eL & l) != 0L) jjCheckNAdd(182); break; case 185: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 186; break; case 187: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 188; break; case 188: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 189; break; case 190: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 191; break; case 191: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 192; break; case 192: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 193; break; case 195: case 201: if ((0x7fffffffffffffffL & l) != 0L) jjCheckNAddStates(209, 211); break; case 197: if (curChar == 92) jjAddStates(373, 376); break; case 202: if ((0x7e0000007eL & l) != 0L) jjCheckNAddStates(212, 220); break; case 203: if ((0x7e0000007eL & l) != 0L) jjCheckNAddStates(221, 224); break; case 205: case 207: case 210: case 214: if ((0x7e0000007eL & l) != 0L) jjCheckNAdd(203); break; case 206: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 207; break; case 208: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 209; break; case 209: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 210; break; case 211: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 212; break; case 212: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 213; break; case 213: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 214; break; case 216: if ((0x100000001000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 154; break; case 217: if ((0x4000000040000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 216; break; case 220: if ((0x7e0000007eL & l) == 0L) break; if (kind > 63) kind = 63; jjCheckNAddStates(235, 243); break; case 221: if ((0x7e0000007eL & l) != 0L) jjCheckNAdd(222); break; case 223: if ((0x7e0000007eL & l) == 0L) break; if (kind > 63) kind = 63; jjCheckNAddStates(244, 248); break; case 224: if ((0x7e0000007eL & l) != 0L && kind > 63) kind = 63; break; case 225: case 227: case 230: case 234: if ((0x7e0000007eL & l) != 0L) jjCheckNAdd(224); break; case 226: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 227; break; case 228: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 229; break; case 229: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 230; break; case 231: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 232; break; case 232: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 233; break; case 233: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 234; break; case 235: case 237: case 240: case 244: if ((0x7e0000007eL & l) != 0L) jjCheckNAdd(221); break; case 236: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 237; break; case 238: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 239; break; case 239: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 240; break; case 241: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 242; break; case 242: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 243; break; case 243: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 244; break; case 245: if ((0x7e0000007eL & l) == 0L) break; if (kind > 63) kind = 63; jjCheckNAddStates(249, 251); break; case 246: if ((0x7e0000007eL & l) == 0L) break; if (kind > 63) kind = 63; jjCheckNAddStates(252, 254); break; case 247: if ((0x7e0000007eL & l) == 0L) break; if (kind > 63) kind = 63; jjCheckNAddStates(255, 257); break; case 250: if ((0x7e0000007eL & l) == 0L) break; if (kind > 63) kind = 63; jjCheckNAddTwoStates(219, 224); break; case 277: if ((0x200000002000L & l) != 0L && kind > 40) kind = 40; break; case 278: if ((0x2000000020L & l) != 0L) jjstateSet[jjnewStateCnt++] = 277; break; case 280: if ((0x100000001000000L & l) != 0L && kind > 41) kind = 41; break; case 281: if ((0x2000000020L & l) != 0L) jjstateSet[jjnewStateCnt++] = 280; break; case 283: if ((0x100000001000000L & l) != 0L && kind > 42) kind = 42; break; case 284: if ((0x1000000010000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 283; break; case 286: if ((0x200000002000L & l) != 0L && kind > 43) kind = 43; break; case 287: if ((0x800000008L & l) != 0L) jjstateSet[jjnewStateCnt++] = 286; break; case 289: if ((0x200000002000L & l) != 0L && kind > 44) kind = 44; break; case 290: if ((0x200000002000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 289; break; case 292: if ((0x400000004000L & l) != 0L && kind > 45) kind = 45; break; case 293: if ((0x20000000200L & l) != 0L) jjstateSet[jjnewStateCnt++] = 292; break; case 295: if ((0x10000000100000L & l) != 0L && kind > 46) kind = 46; break; case 296: if ((0x1000000010000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 295; break; case 298: if ((0x800000008L & l) != 0L && kind > 47) kind = 47; break; case 299: if ((0x1000000010000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 298; break; case 301: if ((0x8000000080L & l) != 0L && kind > 48) kind = 48; break; case 302: if ((0x2000000020L & l) != 0L) jjstateSet[jjnewStateCnt++] = 301; break; case 303: if ((0x1000000010L & l) != 0L) jjstateSet[jjnewStateCnt++] = 302; break; case 305: if ((0x1000000010L & l) != 0L && kind > 49) kind = 49; break; case 306: if ((0x200000002L & l) != 0L) jjstateSet[jjnewStateCnt++] = 305; break; case 307: if ((0x4000000040000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 306; break; case 309: if ((0x1000000010L & l) != 0L && kind > 50) kind = 50; break; case 310: if ((0x200000002L & l) != 0L) jjstateSet[jjnewStateCnt++] = 309; break; case 311: if ((0x4000000040000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 310; break; case 312: if ((0x8000000080L & l) != 0L) jjstateSet[jjnewStateCnt++] = 311; break; case 314: if ((0x8000000080000L & l) != 0L && kind > 51) kind = 51; break; case 315: if ((0x200000002000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 314; break; case 317: if ((0x8000000080000L & l) != 0L && kind > 52) kind = 52; break; case 319: if ((0x400000004000000L & l) != 0L && kind > 53) kind = 53; break; case 320: if ((0x10000000100L & l) != 0L) jjstateSet[jjnewStateCnt++] = 319; break; case 322: if ((0x400000004000000L & l) != 0L && kind > 54) kind = 54; break; case 323: if ((0x10000000100L & l) != 0L) jjstateSet[jjnewStateCnt++] = 322; break; case 324: if ((0x80000000800L & l) != 0L) jjstateSet[jjnewStateCnt++] = 323; break; case 326: case 327: if ((0x7fffffe87fffffeL & l) == 0L) break; if (kind > 55) kind = 55; jjCheckNAddTwoStates(327, 328); break; case 328: if (curChar == 92) jjCheckNAddTwoStates(329, 330); break; case 329: if ((0x7fffffffffffffffL & l) == 0L) break; if (kind > 55) kind = 55; jjCheckNAddTwoStates(327, 328); break; case 330: if ((0x7e0000007eL & l) == 0L) break; if (kind > 55) kind = 55; jjCheckNAddStates(270, 277); break; case 331: if ((0x7e0000007eL & l) == 0L) break; if (kind > 55) kind = 55; jjCheckNAddStates(278, 280); break; case 333: case 335: case 338: case 342: if ((0x7e0000007eL & l) != 0L) jjCheckNAdd(331); break; case 334: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 335; break; case 336: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 337; break; case 337: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 338; break; case 339: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 340; break; case 340: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 341; break; case 341: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 342; break; case 343: if (curChar == 92) jjCheckNAddTwoStates(329, 344); break; case 344: if ((0x7e0000007eL & l) == 0L) break; if (kind > 55) kind = 55; jjCheckNAddStates(281, 288); break; case 345: if ((0x7e0000007eL & l) == 0L) break; if (kind > 55) kind = 55; jjCheckNAddStates(289, 291); break; case 346: case 348: case 351: case 355: if ((0x7e0000007eL & l) != 0L) jjCheckNAdd(345); break; case 347: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 348; break; case 349: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 350; break; case 350: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 351; break; case 352: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 353; break; case 353: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 354; break; case 354: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 355; break; case 360: if ((0x7fffffe87fffffeL & l) == 0L) break; if (kind > 60) kind = 60; jjCheckNAddStates(78, 82); break; case 361: if ((0x7fffffe87fffffeL & l) != 0L) jjCheckNAddStates(108, 110); break; case 363: if (curChar == 92) jjCheckNAddTwoStates(364, 365); break; case 364: if ((0x7fffffffffffffffL & l) != 0L) jjCheckNAddStates(108, 110); break; case 365: if ((0x7e0000007eL & l) != 0L) jjCheckNAddStates(292, 300); break; case 366: if ((0x7e0000007eL & l) != 0L) jjCheckNAddStates(301, 304); break; case 368: case 370: case 373: case 377: if ((0x7e0000007eL & l) != 0L) jjCheckNAdd(366); break; case 369: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 370; break; case 371: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 372; break; case 372: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 373; break; case 374: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 375; break; case 375: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 376; break; case 376: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 377; break; case 378: if ((0x7fffffe87fffffeL & l) == 0L) break; if (kind > 60) kind = 60; jjCheckNAddTwoStates(378, 379); break; case 379: if (curChar == 92) jjCheckNAddTwoStates(380, 381); break; case 380: if ((0x7fffffffffffffffL & l) == 0L) break; if (kind > 60) kind = 60; jjCheckNAddTwoStates(378, 379); break; case 381: if ((0x7e0000007eL & l) == 0L) break; if (kind > 60) kind = 60; jjCheckNAddStates(305, 312); break; case 382: if ((0x7e0000007eL & l) == 0L) break; if (kind > 60) kind = 60; jjCheckNAddStates(313, 315); break; case 384: case 386: case 389: case 393: if ((0x7e0000007eL & l) != 0L) jjCheckNAdd(382); break; case 385: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 386; break; case 387: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 388; break; case 388: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 389; break; case 390: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 391; break; case 391: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 392; break; case 392: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 393; break; case 452: if (curChar == 92) jjCheckNAddStates(343, 346); break; case 453: if ((0x7e0000007eL & l) == 0L) break; if (kind > 60) kind = 60; jjCheckNAddStates(319, 326); break; case 454: if ((0x7e0000007eL & l) == 0L) break; if (kind > 60) kind = 60; jjCheckNAddStates(327, 329); break; case 455: case 457: case 460: case 464: if ((0x7e0000007eL & l) != 0L) jjCheckNAdd(454); break; case 456: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 457; break; case 458: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 459; break; case 459: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 460; break; case 461: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 462; break; case 462: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 463; break; case 463: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 464; break; case 465: if ((0x7e0000007eL & l) != 0L) jjCheckNAddStates(330, 338); break; case 466: if ((0x7e0000007eL & l) != 0L) jjCheckNAddStates(339, 342); break; case 467: case 469: case 472: case 476: if ((0x7e0000007eL & l) != 0L) jjCheckNAdd(466); break; case 468: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 469; break; case 470: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 471; break; case 471: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 472; break; case 473: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 474; break; case 474: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 475; break; case 475: if ((0x7e0000007eL & l) != 0L) jjstateSet[jjnewStateCnt++] = 476; break; default : break; } } while(i != startsAt); } else { int i2 = (curChar & 0xff) >> 6; long l2 = 1L << (curChar & 077); MatchLoop: do { switch(jjstateSet[--i]) { case 479: case 62: case 64: if ((jjbitVec2[i2] & l2) == 0L) break; if (kind > 37) kind = 37; jjCheckNAddTwoStates(62, 63); break; case 1: if ((jjbitVec2[i2] & l2) == 0L) break; if (kind > 60) kind = 60; jjCheckNAddStates(78, 82); break; case 61: if ((jjbitVec2[i2] & l2) == 0L) break; if (kind > 37) kind = 37; jjCheckNAddTwoStates(62, 63); break; case 132: if ((jjbitVec2[i2] & l2) != 0L) jjCheckNAddStates(108, 110); if ((jjbitVec2[i2] & l2) != 0L) { if (kind > 60) kind = 60; jjCheckNAddTwoStates(378, 379); } break; case 478: if ((jjbitVec2[i2] & l2) != 0L) jjCheckNAddStates(108, 110); if ((jjbitVec2[i2] & l2) != 0L) { if (kind > 60) kind = 60; jjCheckNAddTwoStates(378, 379); } break; case 2: case 4: if ((jjbitVec2[i2] & l2) == 0L) break; if (kind > 23) kind = 23; jjCheckNAddTwoStates(2, 3); break; case 19: case 25: if ((jjbitVec2[i2] & l2) != 0L) jjCheckNAddStates(105, 107); break; case 40: case 46: if ((jjbitVec2[i2] & l2) != 0L) jjCheckNAddStates(102, 104); break; case 155: case 159: if ((jjbitVec2[i2] & l2) != 0L) jjCheckNAddStates(176, 179); break; case 174: case 180: if ((jjbitVec2[i2] & l2) != 0L) jjCheckNAddStates(193, 195); break; case 195: case 201: if ((jjbitVec2[i2] & l2) != 0L) jjCheckNAddStates(209, 211); break; case 326: case 327: case 329: if ((jjbitVec2[i2] & l2) == 0L) break; if (kind > 55) kind = 55; jjCheckNAddTwoStates(327, 328); break; case 361: case 364: if ((jjbitVec2[i2] & l2) != 0L) jjCheckNAddStates(108, 110); break; case 378: case 380: if ((jjbitVec2[i2] & l2) == 0L) break; if (kind > 60) kind = 60; jjCheckNAddTwoStates(378, 379); break; default : break; } } while(i != startsAt); } if (kind != 0x7fffffff) { jjmatchedKind = kind; jjmatchedPos = curPos; kind = 0x7fffffff; } ++curPos; if ((i = jjnewStateCnt) == (startsAt = 477 - (jjnewStateCnt = startsAt))) return curPos; try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { return curPos; } } } private final int jjMoveStringLiteralDfa0_1() { switch(curChar) { case 42: return jjMoveStringLiteralDfa1_1(0x8L); default : return 1; } } private final int jjMoveStringLiteralDfa1_1(long active0) { try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { return 1; } switch(curChar) { case 47: if ((active0 & 0x8L) != 0L) return jjStopAtPos(1, 3); break; default : return 2; } return 2; } static final int[] jjnextStates = { 325, 326, 343, 395, 396, 397, 278, 398, 399, 400, 281, 401, 402, 403, 284, 404, 405, 406, 287, 407, 408, 409, 290, 410, 411, 412, 293, 413, 414, 415, 296, 416, 417, 418, 299, 419, 420, 421, 303, 422, 423, 424, 307, 425, 426, 427, 312, 428, 429, 430, 315, 431, 432, 433, 317, 434, 435, 436, 320, 437, 438, 439, 324, 440, 441, 442, 326, 443, 444, 445, 357, 446, 447, 448, 449, 450, 451, 343, 361, 362, 378, 379, 363, 276, 279, 282, 285, 288, 291, 294, 297, 300, 304, 308, 313, 316, 318, 321, 325, 356, 358, 359, 40, 41, 42, 19, 20, 21, 361, 362, 363, 2, 6, 8, 9, 11, 14, 7, 3, 2, 7, 3, 19, 27, 29, 30, 32, 35, 28, 20, 21, 19, 28, 20, 21, 40, 48, 50, 51, 53, 56, 49, 41, 42, 40, 49, 41, 42, 62, 66, 68, 69, 71, 74, 67, 63, 62, 67, 63, 80, 81, 82, 84, 87, 67, 62, 63, 67, 62, 63, 155, 173, 194, 157, 158, 215, 155, 156, 157, 158, 155, 161, 163, 164, 166, 169, 157, 158, 162, 155, 157, 158, 162, 174, 175, 176, 174, 182, 184, 185, 187, 190, 183, 175, 176, 174, 183, 175, 176, 195, 196, 197, 195, 203, 205, 206, 208, 211, 204, 196, 197, 195, 204, 196, 197, 155, 173, 194, 156, 157, 158, 215, 219, 220, 264, 221, 235, 236, 238, 241, 222, 219, 245, 257, 224, 225, 226, 228, 231, 219, 246, 253, 219, 247, 251, 219, 249, 250, 248, 254, 256, 248, 258, 260, 263, 268, 271, 273, 274, 248, 327, 331, 333, 334, 336, 339, 332, 328, 327, 332, 328, 345, 346, 347, 349, 352, 332, 327, 328, 332, 327, 328, 361, 366, 368, 369, 371, 374, 367, 362, 363, 361, 367, 362, 363, 378, 382, 384, 385, 387, 390, 383, 379, 378, 383, 379, 440, 326, 343, 454, 455, 456, 458, 461, 383, 378, 379, 383, 378, 379, 466, 467, 468, 470, 473, 367, 361, 362, 363, 367, 361, 362, 363, 364, 380, 453, 465, 61, 78, 217, 218, 151, 152, 140, 148, 132, 135, 4, 5, 22, 24, 25, 26, 43, 45, 46, 47, 159, 160, 177, 179, 180, 181, 198, 200, 201, 202, }; public static final String[] jjstrLiteralImages = { "", null, null, null, null, "\173", "\175", "\50", "\54", "\56", "\73", "\72", "\52", "\57", "\53", "\55", "\75", "\76", "\133", "\135", null, null, null, null, null, "\51", null, null, "\74\41\55\55", "\55\55\76", "\176\75", "\174\75", null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, }; public static final String[] lexStateNames = { "DEFAULT", "COMMENT", }; public static final int[] jjnewLexState = { -1, -1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; static final long[] jjtoToken = { 0xdffffffffbffffe3L, 0x60000L, }; static final long[] jjtoSkip = { 0x8L, 0x0L, }; static final long[] jjtoMore = { 0x14L, 0x0L, }; protected CharStream input_stream; private final int[] jjrounds = new int[477]; private final int[] jjstateSet = new int[954]; StringBuffer image; int jjimageLen; int lengthOfMatch; protected char curChar; public SACParserTokenManager(CharStream stream){ input_stream = stream; } public SACParserTokenManager(CharStream stream, int lexState){ this(stream); SwitchTo(lexState); } public void ReInit(CharStream stream) { jjmatchedPos = jjnewStateCnt = 0; curLexState = defaultLexState; input_stream = stream; ReInitRounds(); } private final void ReInitRounds() { int i; jjround = 0x80000001; for (i = 477; i-- > 0;) jjrounds[i] = 0x80000000; } public void ReInit(CharStream stream, int lexState) { ReInit(stream); SwitchTo(lexState); } public void SwitchTo(int lexState) { if (lexState >= 2 || lexState < 0) throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE); else curLexState = lexState; } protected Token jjFillToken() { Token t = Token.newToken(jjmatchedKind); t.kind = jjmatchedKind; String im = jjstrLiteralImages[jjmatchedKind]; t.image = (im == null) ? input_stream.GetImage() : im; t.beginLine = input_stream.getBeginLine(); t.beginColumn = input_stream.getBeginColumn(); t.endLine = input_stream.getEndLine(); t.endColumn = input_stream.getEndColumn(); return t; } int curLexState = 0; int defaultLexState = 0; int jjnewStateCnt; int jjround; int jjmatchedPos; int jjmatchedKind; public Token getNextToken() { int kind; Token specialToken = null; Token matchedToken; int curPos = 0; EOFLoop : for (;;) { try { curChar = input_stream.BeginToken(); } catch(java.io.IOException e) { jjmatchedKind = 0; matchedToken = jjFillToken(); return matchedToken; } image = null; jjimageLen = 0; for (;;) { switch(curLexState) { case 0: jjmatchedKind = 0x7fffffff; jjmatchedPos = 0; curPos = jjMoveStringLiteralDfa0_0(); if (jjmatchedPos == 0 && jjmatchedKind > 82) { jjmatchedKind = 82; } break; case 1: jjmatchedKind = 0x7fffffff; jjmatchedPos = 0; curPos = jjMoveStringLiteralDfa0_1(); if (jjmatchedPos == 0 && jjmatchedKind > 4) { jjmatchedKind = 4; } break; } if (jjmatchedKind != 0x7fffffff) { if (jjmatchedPos + 1 < curPos) input_stream.backup(curPos - jjmatchedPos - 1); if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) { matchedToken = jjFillToken(); TokenLexicalActions(matchedToken); if (jjnewLexState[jjmatchedKind] != -1) curLexState = jjnewLexState[jjmatchedKind]; return matchedToken; } else if ((jjtoSkip[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) { if (jjnewLexState[jjmatchedKind] != -1) curLexState = jjnewLexState[jjmatchedKind]; continue EOFLoop; } jjimageLen += jjmatchedPos + 1; if (jjnewLexState[jjmatchedKind] != -1) curLexState = jjnewLexState[jjmatchedKind]; curPos = 0; jjmatchedKind = 0x7fffffff; try { curChar = input_stream.readChar(); continue; } catch (java.io.IOException e1) { } } int error_line = input_stream.getEndLine(); int error_column = input_stream.getEndColumn(); String error_after = null; boolean EOFSeen = false; try { input_stream.readChar(); input_stream.backup(1); } catch (java.io.IOException e1) { EOFSeen = true; error_after = curPos <= 1 ? "" : input_stream.GetImage(); if (curChar == '\n' || curChar == '\r') { error_line++; error_column = 0; } else error_column++; } if (!EOFSeen) { input_stream.backup(1); error_after = curPos <= 1 ? "" : input_stream.GetImage(); } throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR); } } } void TokenLexicalActions(Token matchedToken) { switch(jjmatchedKind) { case 24 : if (image == null) image = new StringBuffer(); image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); matchedToken.image = trimBy(image, 1, 1); break; case 27 : if (image == null) image = new StringBuffer(); image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); matchedToken.image = trimUrl(image); break; case 40 : if (image == null) image = new StringBuffer(); image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); matchedToken.image = trimBy(image, 0, 2); break; case 41 : if (image == null) image = new StringBuffer(); image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); matchedToken.image = trimBy(image, 0, 2); break; case 42 : if (image == null) image = new StringBuffer(); image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); matchedToken.image = trimBy(image, 0, 2); break; case 43 : if (image == null) image = new StringBuffer(); image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); matchedToken.image = trimBy(image, 0, 2); break; case 44 : if (image == null) image = new StringBuffer(); image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); matchedToken.image = trimBy(image, 0, 2); break; case 45 : if (image == null) image = new StringBuffer(); image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); matchedToken.image = trimBy(image, 0, 2); break; case 46 : if (image == null) image = new StringBuffer(); image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); matchedToken.image = trimBy(image, 0, 2); break; case 47 : if (image == null) image = new StringBuffer(); image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); matchedToken.image = trimBy(image, 0, 2); break; case 48 : if (image == null) image = new StringBuffer(); image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); matchedToken.image = trimBy(image, 0, 3); break; case 49 : if (image == null) image = new StringBuffer(); image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); matchedToken.image = trimBy(image, 0, 3); break; case 50 : if (image == null) image = new StringBuffer(); image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); matchedToken.image = trimBy(image, 0, 4); break; case 51 : if (image == null) image = new StringBuffer(); image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); matchedToken.image = trimBy(image, 0, 2); break; case 52 : if (image == null) image = new StringBuffer(); image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); matchedToken.image = trimBy(image, 0, 1); break; case 53 : if (image == null) image = new StringBuffer(); image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); matchedToken.image = trimBy(image, 0, 2); break; case 54 : if (image == null) image = new StringBuffer(); image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); matchedToken.image = trimBy(image, 0, 3); break; case 56 : if (image == null) image = new StringBuffer(); image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); matchedToken.image = trimBy(image, 0, 1); break; case 82 : if (image == null) image = new StringBuffer(); image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); if (!_quiet) { System.err.println("Illegal character : " + image.toString()); } break; default : break; } } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/SelectorListImpl.java0000644000175000017500000000376610737110114027300 0ustar twernertwerner/* * SelectorListImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: SelectorListImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.parser; import java.io.Serializable; import java.util.*; import org.w3c.css.sac.*; public class SelectorListImpl implements SelectorList, Serializable { private Vector _selectors = new Vector(10, 10); public int getLength() { return _selectors.size(); } public Selector item(int index) { return (Selector) _selectors.elementAt(index); } public void add(Selector sel) { _selectors.addElement(sel); } public String toString() { StringBuffer sb = new StringBuffer(); int len = getLength(); for (int i = 0; i < len; i++) { sb.append(item(i).toString()); if (i < len - 1) { sb.append(", "); } } return sb.toString(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/Token.java0000644000175000017500000000530210434145436025117 0ustar twernertwerner/* Generated By:JavaCC: Do not edit this line. Token.java Version 3.0 */ package com.steadystate.css.parser; /** * Describes the input token stream. */ public class Token { /** * An integer that describes the kind of this token. This numbering * system is determined by JavaCCParser, and a table of these numbers is * stored in the file ...Constants.java. */ public int kind; /** * beginLine and beginColumn describe the position of the first character * of this token; endLine and endColumn describe the position of the * last character of this token. */ public int beginLine, beginColumn, endLine, endColumn; /** * The string image of the token. */ public String image; /** * A reference to the next regular (non-special) token from the input * stream. If this is the last token from the input stream, or if the * token manager has not read tokens beyond this one, this field is * set to null. This is true only if this token is also a regular * token. Otherwise, see below for a description of the contents of * this field. */ public Token next; /** * This field is used to access special tokens that occur prior to this * token, but after the immediately preceding regular (non-special) token. * If there are no such special tokens, this field is set to null. * When there are more than one such special token, this field refers * to the last of these special tokens, which in turn refers to the next * previous special token through its specialToken field, and so on * until the first special token (whose specialToken field is null). * The next fields of special tokens refer to other special tokens that * immediately follow it (without an intervening regular token). If there * is no such token, this field is null. */ public Token specialToken; /** * Returns the image. */ public String toString() { return image; } /** * Returns a new Token object, by default. However, if you want, you * can create and return subclass objects based on the value of ofKind. * Simply add the cases to the switch for all those special cases. * For example, if you have a subclass of Token called IDToken that * you want to create if ofKind is ID, simlpy add something like : * * case MyParserConstants.ID : return new IDToken(); * * to the following switch statement. Then you can cast matchedToken * variable to the appropriate type and use it in your lexical actions. */ public static final Token newToken(int ofKind) { switch(ofKind) { default : return new Token(); } } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/TokenMgrError.java0000644000175000017500000001037610434145436026606 0ustar twernertwerner/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 3.0 */ package com.steadystate.css.parser; public class TokenMgrError extends Error { /* * Ordinals for various reasons why an Error of this type can be thrown. */ /** * Lexical error occured. */ static final int LEXICAL_ERROR = 0; /** * An attempt wass made to create a second instance of a static token manager. */ static final int STATIC_LEXER_ERROR = 1; /** * Tried to change to an invalid lexical state. */ static final int INVALID_LEXICAL_STATE = 2; /** * Detected (and bailed out of) an infinite loop in the token manager. */ static final int LOOP_DETECTED = 3; /** * Indicates the reason why the exception is thrown. It will have * one of the above 4 values. */ int errorCode; /** * Replaces unprintable characters by their espaced (or unicode escaped) * equivalents in the given string */ protected static final String addEscapes(String str) { StringBuffer retval = new StringBuffer(); char ch; for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { case 0 : continue; case '\b': retval.append("\\b"); continue; case '\t': retval.append("\\t"); continue; case '\n': retval.append("\\n"); continue; case '\f': retval.append("\\f"); continue; case '\r': retval.append("\\r"); continue; case '\"': retval.append("\\\""); continue; case '\'': retval.append("\\\'"); continue; case '\\': retval.append("\\\\"); continue; default: if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { String s = "0000" + Integer.toString(ch, 16); retval.append("\\u" + s.substring(s.length() - 4, s.length())); } else { retval.append(ch); } continue; } } return retval.toString(); } /** * Returns a detailed message for the Error when it is thrown by the * token manager to indicate a lexical error. * Parameters : * EOFSeen : indicates if EOF caused the lexicl error * curLexState : lexical state in which this error occured * errorLine : line number when the error occured * errorColumn : column number when the error occured * errorAfter : prefix that was seen before this error occured * curchar : the offending character * Note: You can customize the lexical error message by modifying this method. */ protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) { return("Lexical error at line " + errorLine + ", column " + errorColumn + ". Encountered: " + (EOFSeen ? " " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") + "after : \"" + addEscapes(errorAfter) + "\""); } /** * You can also modify the body of this method to customize your error messages. * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not * of end-users concern, so you can return something like : * * "Internal Error : Please file a bug report .... " * * from this method for such cases in the release version of your parser. */ public String getMessage() { return super.getMessage(); } /* * Constructors of various flavors follow. */ public TokenMgrError() { } public TokenMgrError(String message, int reason) { super(message); errorCode = reason; } public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) { this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/selectors/0000755000175000017500000000000010630473006025172 5ustar twernertwernerlibcobra-java-0.98.4.orig/src/com/steadystate/css/parser/selectors/AndConditionImpl.java0000644000175000017500000000360310737110114031226 0ustar twernertwerner/* * AndConditionImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: AndConditionImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.parser.selectors; import java.io.Serializable; import org.w3c.css.sac.*; public class AndConditionImpl implements CombinatorCondition, Serializable { private Condition _c1; private Condition _c2; public AndConditionImpl(Condition c1, Condition c2) { _c1 = c1; _c2 = c2; } public short getConditionType() { return Condition.SAC_AND_CONDITION; } public Condition getFirstCondition() { return _c1; } public Condition getSecondCondition() { return _c2; } public String toString() { return getFirstCondition().toString() + getSecondCondition().toString(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/selectors/AttributeConditionImpl.java0000644000175000017500000000424410737110112032467 0ustar twernertwerner/* * AttributeConditionImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: AttributeConditionImpl.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package com.steadystate.css.parser.selectors; import java.io.Serializable; import org.w3c.css.sac.*; public class AttributeConditionImpl implements AttributeCondition, Serializable { private String _localName; private String _value; public AttributeConditionImpl(String localName, String value) { _localName = localName; _value = value; } public short getConditionType() { return Condition.SAC_ATTRIBUTE_CONDITION; } public String getNamespaceURI() { return null; } public String getLocalName() { return _localName; } public boolean getSpecified() { return true; } public String getValue() { return _value; } public String toString() { if (getValue() != null) { return "[" + getLocalName() + "=\"" + getValue() + "\"]"; } else { return "[" + getLocalName() + "]"; } } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibcobra-java-0.98.4.orig/src/com/steadystate/css/parser/selectors/BeginHyphenAttributeConditionImpl.javalibcobra-java-0.98.4.orig/src/com/steadystate/css/parser/selectors/BeginHyphenAttributeConditionImpl0000644000175000017500000000414610737110114033673 0ustar twernertwerner/* * BeginHyphenAttributeConditionImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: BeginHyphenAttributeConditionImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.parser.selectors; import java.io.Serializable; import org.w3c.css.sac.*; public class BeginHyphenAttributeConditionImpl implements AttributeCondition, Serializable { private String _localName; private String _value; public BeginHyphenAttributeConditionImpl(String localName, String value) { _localName = localName; _value = value; } public short getConditionType() { return Condition.SAC_BEGIN_HYPHEN_ATTRIBUTE_CONDITION; } public String getNamespaceURI() { return null; } public String getLocalName() { return _localName; } public boolean getSpecified() { return true; } public String getValue() { return _value; } public String toString() { return "[" + getLocalName() + "|=\"" + getValue() + "\"]"; } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/selectors/CharacterDataSelectorImpl.java0000644000175000017500000000335110737110114033044 0ustar twernertwerner/* * CharacterDataSelectorImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: CharacterDataSelectorImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.parser.selectors; import java.io.Serializable; import org.w3c.css.sac.*; public class CharacterDataSelectorImpl implements CharacterDataSelector, Serializable { private String _data; public CharacterDataSelectorImpl(String data) { _data = data; } public short getSelectorType() { return Selector.SAC_CDATA_SECTION_NODE_SELECTOR; } public String getData() { return _data; } public String toString() { return getData(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/selectors/ChildSelectorImpl.java0000644000175000017500000000373110737110112031401 0ustar twernertwerner/* * ChildSelectorImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: ChildSelectorImpl.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package com.steadystate.css.parser.selectors; import java.io.Serializable; import org.w3c.css.sac.*; public class ChildSelectorImpl implements DescendantSelector, Serializable { private Selector _parent; private SimpleSelector _simpleSelector; public ChildSelectorImpl(Selector parent, SimpleSelector simpleSelector) { _parent = parent; _simpleSelector = simpleSelector; } public short getSelectorType() { return Selector.SAC_CHILD_SELECTOR; } public Selector getAncestorSelector() { return _parent; } public SimpleSelector getSimpleSelector() { return _simpleSelector; } public String toString() { return _parent.toString() + " > " + _simpleSelector.toString(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/selectors/ClassConditionImpl.java0000644000175000017500000000364210737110112031572 0ustar twernertwerner/* * ClassConditionImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: ClassConditionImpl.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package com.steadystate.css.parser.selectors; import java.io.Serializable; import org.w3c.css.sac.*; public class ClassConditionImpl implements AttributeCondition, Serializable { private String _value; public ClassConditionImpl(String value) { _value = value; } public short getConditionType() { return Condition.SAC_CLASS_CONDITION; } public String getNamespaceURI() { return null; } public String getLocalName() { return null; } public boolean getSpecified() { return true; } public String getValue() { return _value; } public String toString() { return "." + getValue(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/selectors/ConditionFactoryImpl.java0000644000175000017500000001100210737110112032121 0ustar twernertwerner/* * ConditionFactoryImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: ConditionFactoryImpl.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package com.steadystate.css.parser.selectors; import org.w3c.css.sac.*; public class ConditionFactoryImpl implements ConditionFactory { public CombinatorCondition createAndCondition( Condition first, Condition second) throws CSSException { return new AndConditionImpl(first, second); } public CombinatorCondition createOrCondition( Condition first, Condition second) throws CSSException { throw new CSSException(CSSException.SAC_NOT_SUPPORTED_ERR); } public NegativeCondition createNegativeCondition(Condition condition) throws CSSException { throw new CSSException(CSSException.SAC_NOT_SUPPORTED_ERR); } public PositionalCondition createPositionalCondition( int position, boolean typeNode, boolean type) throws CSSException { throw new CSSException(CSSException.SAC_NOT_SUPPORTED_ERR); } public AttributeCondition createAttributeCondition( String localName, String namespaceURI, boolean specified, String value) throws CSSException { // if ((namespaceURI != null) || !specified) { // throw new CSSException(CSSException.SAC_NOT_SUPPORTED_ERR); // } else { return new AttributeConditionImpl(localName, value); // } } public AttributeCondition createIdCondition(String value) throws CSSException { return new IdConditionImpl(value); } public LangCondition createLangCondition(String lang) throws CSSException { return new LangConditionImpl(lang); } public AttributeCondition createOneOfAttributeCondition( String localName, String namespaceURI, boolean specified, String value) throws CSSException { // if ((namespaceURI != null) || !specified) { // throw new CSSException(CSSException.SAC_NOT_SUPPORTED_ERR); // } else { return new OneOfAttributeConditionImpl(localName, value); // } } public AttributeCondition createBeginHyphenAttributeCondition( String localName, String namespaceURI, boolean specified, String value) throws CSSException { // if ((namespaceURI != null) || !specified) { // throw new CSSException(CSSException.SAC_NOT_SUPPORTED_ERR); // } else { return new BeginHyphenAttributeConditionImpl(localName, value); // } } public AttributeCondition createClassCondition( String namespaceURI, String value) throws CSSException { return new ClassConditionImpl(value); } public AttributeCondition createPseudoClassCondition( String namespaceURI, String value) throws CSSException { return new PseudoClassConditionImpl(value); } public Condition createOnlyChildCondition() throws CSSException { throw new CSSException(CSSException.SAC_NOT_SUPPORTED_ERR); } public Condition createOnlyTypeCondition() throws CSSException { throw new CSSException(CSSException.SAC_NOT_SUPPORTED_ERR); } public ContentCondition createContentCondition(String data) throws CSSException { throw new CSSException(CSSException.SAC_NOT_SUPPORTED_ERR); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/selectors/ConditionalSelectorImpl.java0000644000175000017500000000401510737110114032617 0ustar twernertwerner/* * ConditionalSelectorImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: ConditionalSelectorImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.parser.selectors; import java.io.Serializable; import org.w3c.css.sac.*; public class ConditionalSelectorImpl implements ConditionalSelector, Serializable { private SimpleSelector _simpleSelector; private Condition _condition; public ConditionalSelectorImpl( SimpleSelector simpleSelector, Condition condition) { _simpleSelector = simpleSelector; _condition = condition; } public short getSelectorType() { return Selector.SAC_CONDITIONAL_SELECTOR; } public SimpleSelector getSimpleSelector() { return _simpleSelector; } public Condition getCondition() { return _condition; } public String toString() { return _simpleSelector.toString() + _condition.toString(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/selectors/DescendantSelectorImpl.java0000644000175000017500000000377610737110114032441 0ustar twernertwerner/* * DescendantSelectorImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: DescendantSelectorImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.parser.selectors; import java.io.Serializable; import org.w3c.css.sac.*; public class DescendantSelectorImpl implements DescendantSelector, Serializable { private Selector _parent; private SimpleSelector _simpleSelector; public DescendantSelectorImpl(Selector parent, SimpleSelector simpleSelector) { _parent = parent; _simpleSelector = simpleSelector; } public short getSelectorType() { return Selector.SAC_DESCENDANT_SELECTOR; } public Selector getAncestorSelector() { return _parent; } public SimpleSelector getSimpleSelector() { return _simpleSelector; } public String toString() { return getAncestorSelector().toString() + " " + getSimpleSelector().toString(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/selectors/DirectAdjacentSelectorImpl.java0000644000175000017500000000421210737110114033217 0ustar twernertwerner/* * DirectAdjacentSelectorImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: DirectAdjacentSelectorImpl.java,v 1.4 2008/01/03 13:35:39 xamjadmin Exp $ */ package com.steadystate.css.parser.selectors; import java.io.Serializable; import org.w3c.css.sac.*; public class DirectAdjacentSelectorImpl implements SiblingSelector, Serializable { private short _nodeType; private Selector _child; private SimpleSelector _directAdjacent; public DirectAdjacentSelectorImpl(short nodeType, Selector child, SimpleSelector directAdjacent) { _nodeType = nodeType; _child = child; _directAdjacent = directAdjacent; } public short getNodeType() { return _nodeType; } public short getSelectorType() { return Selector.SAC_DIRECT_ADJACENT_SELECTOR; } public Selector getSelector() { return _child; } public SimpleSelector getSiblingSelector() { return _directAdjacent; } public String toString() { return _child.toString() + " + " + _directAdjacent.toString(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/selectors/ElementSelectorImpl.java0000644000175000017500000000352710737110114031754 0ustar twernertwerner/* * ElementSelectorImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: ElementSelectorImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.parser.selectors; import java.io.Serializable; import org.w3c.css.sac.*; public class ElementSelectorImpl implements ElementSelector, Serializable { private String _localName; public ElementSelectorImpl(String localName) { _localName = localName; } public short getSelectorType() { return Selector.SAC_ELEMENT_NODE_SELECTOR; } public String getNamespaceURI() { return null; } public String getLocalName() { return _localName; } public String toString() { return (getLocalName() != null) ? getLocalName() : "*"; } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/selectors/IdConditionImpl.java0000644000175000017500000000361710737110112031063 0ustar twernertwerner/* * IdConditionImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: IdConditionImpl.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package com.steadystate.css.parser.selectors; import java.io.Serializable; import org.w3c.css.sac.*; public class IdConditionImpl implements AttributeCondition, Serializable { private String _value; public IdConditionImpl(String value) { _value = value; } public short getConditionType() { return Condition.SAC_ID_CONDITION; } public String getNamespaceURI() { return null; } public String getLocalName() { return null; } public boolean getSpecified() { return true; } public String getValue() { return _value; } public String toString() { return "#" + getValue(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/selectors/LangConditionImpl.java0000644000175000017500000000341510737110112031404 0ustar twernertwerner/* * LangConditionImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: LangConditionImpl.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package com.steadystate.css.parser.selectors; import java.io.Serializable; import org.w3c.css.sac.*; /** * * @author David Schweinsberg * @version $Release$ */ public class LangConditionImpl implements LangCondition, Serializable { private String _lang; public LangConditionImpl(String lang) { _lang = lang; } public short getConditionType() { return Condition.SAC_LANG_CONDITION; } public String getLang() { return _lang; } public String toString() { return ":lang(" + getLang() + ")"; } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/selectors/OneOfAttributeConditionImpl.java0000644000175000017500000000411410737110112033412 0ustar twernertwerner/* * OneOfAttributeConditionImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: OneOfAttributeConditionImpl.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package com.steadystate.css.parser.selectors; import java.io.Serializable; import org.w3c.css.sac.*; public class OneOfAttributeConditionImpl implements AttributeCondition, Serializable { private String _localName; private String _value; public OneOfAttributeConditionImpl(String localName, String value) { _localName = localName; _value = value; } public short getConditionType() { return Condition.SAC_ONE_OF_ATTRIBUTE_CONDITION; } public String getNamespaceURI() { return null; } public String getLocalName() { return _localName; } public boolean getSpecified() { return true; } public String getValue() { return _value; } public String toString() { return "[" + getLocalName() + "~=\"" + getValue() + "\"]"; } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/selectors/PseudoClassConditionImpl.java0000644000175000017500000000370110737110114032750 0ustar twernertwerner/* * PseudoClassConditionImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: PseudoClassConditionImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.parser.selectors; import java.io.Serializable; import org.w3c.css.sac.*; public class PseudoClassConditionImpl implements AttributeCondition, Serializable { private String _value; public PseudoClassConditionImpl(String value) { _value = value; } public short getConditionType() { return Condition.SAC_PSEUDO_CLASS_CONDITION; } public String getNamespaceURI() { return null; } public String getLocalName() { return null; } public boolean getSpecified() { return true; } public String getValue() { return _value; } public String toString() { return ":" + getValue(); } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/selectors/PseudoElementSelectorImpl.java0000644000175000017500000000337710737110114033137 0ustar twernertwerner/* * PseudoElementSelectorImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: PseudoElementSelectorImpl.java,v 1.4 2008/01/03 13:35:40 xamjadmin Exp $ */ package com.steadystate.css.parser.selectors; import org.w3c.css.sac.*; import java.io.Serializable; public class PseudoElementSelectorImpl implements ElementSelector, Serializable { private String _localName; public PseudoElementSelectorImpl(String localName) { _localName = localName; } public short getSelectorType() { return Selector.SAC_PSEUDO_ELEMENT_SELECTOR; } public String getNamespaceURI() { return null; } public String getLocalName() { return _localName; } } libcobra-java-0.98.4.orig/src/com/steadystate/css/parser/selectors/SelectorFactoryImpl.java0000644000175000017500000001010010737110112031751 0ustar twernertwerner/* * SelectorFactoryImpl.java * * Steady State CSS2 Parser * * Copyright (C) 1999, 2002 Steady State Software Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * To contact the authors of the library, write to Steady State Software Ltd., * 49 Littleworth, Wing, Buckinghamshire, LU7 0JX, England * * http://www.steadystate.com/css/ * mailto:css@steadystate.co.uk * * $Id: SelectorFactoryImpl.java,v 1.4 2008/01/03 13:35:38 xamjadmin Exp $ */ package com.steadystate.css.parser.selectors; import org.w3c.css.sac.*; public class SelectorFactoryImpl implements SelectorFactory { public ConditionalSelector createConditionalSelector( SimpleSelector selector, Condition condition) throws CSSException { return new ConditionalSelectorImpl(selector, condition); } public SimpleSelector createAnyNodeSelector() throws CSSException { throw new CSSException(CSSException.SAC_NOT_SUPPORTED_ERR); } public SimpleSelector createRootNodeSelector() throws CSSException { throw new CSSException(CSSException.SAC_NOT_SUPPORTED_ERR); } public NegativeSelector createNegativeSelector(SimpleSelector selector) throws CSSException { throw new CSSException(CSSException.SAC_NOT_SUPPORTED_ERR); } public ElementSelector createElementSelector(String namespaceURI, String localName) throws CSSException { if (namespaceURI != null) { throw new CSSException(CSSException.SAC_NOT_SUPPORTED_ERR); } else { return new ElementSelectorImpl(localName); } } public CharacterDataSelector createTextNodeSelector(String data) throws CSSException { throw new CSSException(CSSException.SAC_NOT_SUPPORTED_ERR); } public CharacterDataSelector createCDataSectionSelector(String data) throws CSSException { throw new CSSException(CSSException.SAC_NOT_SUPPORTED_ERR); } public ProcessingInstructionSelector createProcessingInstructionSelector( String target, String data) throws CSSException { throw new CSSException(CSSException.SAC_NOT_SUPPORTED_ERR); } public CharacterDataSelector createCommentSelector(String data) throws CSSException { throw new CSSException(CSSException.SAC_NOT_SUPPORTED_ERR); } public ElementSelector createPseudoElementSelector( String namespaceURI, String pseudoName) throws CSSException { if (namespaceURI != null) { throw new CSSException(CSSException.SAC_NOT_SUPPORTED_ERR); } else { return new PseudoElementSelectorImpl(pseudoName); } } public DescendantSelector createDescendantSelector( Selector parent, SimpleSelector descendant) throws CSSException { return new DescendantSelectorImpl(parent, descendant); } public DescendantSelector createChildSelector( Selector parent, SimpleSelector child) throws CSSException { return new ChildSelectorImpl(parent, child); } public SiblingSelector createDirectAdjacentSelector( short nodeType, Selector child, SimpleSelector directAdjacent) throws CSSException { return new DirectAdjacentSelectorImpl(nodeType, child, directAdjacent); } } libcobra-java-0.98.4.orig/doc/0000755000175000017500000000000011134672336015760 5ustar twernertwernerlibcobra-java-0.98.4.orig/doc/api/0000755000175000017500000000000011134672336016531 5ustar twernertwernerlibcobra-java-0.98.4.orig/doc/index.html0000644000175000017500000000051010742431666017754 0ustar twernertwerner Cobra Documentation