jxwb-cvs Mailing List for Java Extensible Web Browser (JXWB)
Status: Pre-Alpha
Brought to you by:
devilm
You can subscribe to this list here.
2003 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(14) |
Nov
|
Dec
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
2004 |
Jan
(38) |
Feb
|
Mar
(1) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: DevilM <de...@us...> - 2004-03-24 16:53:23
|
Update of /cvsroot/jxwb/wwe In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv2451 Added Files: build.xml Log Message: added ant build script from Jochen Wiedmann --- NEW FILE: build.xml --- <project name="wwe" default="all"> <property name="debug" value="true"/> <property name="optimize" value="false"/> <property name="src" location="src"/> <property name="build" location="build"/> <property name="build.classes" location="${build}/classes"/> <property name="build.dist" location="${build}/dist"/> <property name="flute.jar" location="lib/flute.jar"/> <property name="sac.jar" location="lib/sac.jar"/> <path id="wwe.class.path"> <pathelement location="${flute.jar}"/> <pathelement location="${sac.jar}"/> </path> <target name="clean"> <delete dir="${build}"/> </target> <target name="compile"> <mkdir dir="${build.classes}"/> <javac debug="${debug}" optimize="${optimize}" srcdir="${src}" destdir="${build.classes}" classpathref="wwe.class.path"/> <copy todir="${build.classes}"> <fileset dir="${src}"> <include name="**/*.gif"/> <include name="**/*.bdtd"/> </fileset> </copy> </target> <target name="jar" depends="compile"> <mkdir dir="${build.dist}"/> <jar destfile="${build.dist}/wwe.jar"> <fileset dir="${build.classes}"/> </jar> <zip destfile="${build.dist}/wwe-src.zip"> <fileset dir="${src}"/> </zip> </target> <target name="all" depends="compile,jar"/> <target name="dist" depends="clean,all"/> </project> |
From: <de...@us...> - 2004-01-05 05:13:27
|
Update of /cvsroot/jxwb/jxwb/lib In directory sc8-pr-cvs1:/tmp/cvs-serv403/lib Removed Files: wwe.jar sac.jar flute.jar Log Message: added cvsignore for bin removed libs from project made project dependent on the wwe project --- wwe.jar DELETED --- --- sac.jar DELETED --- --- flute.jar DELETED --- |
From: <de...@us...> - 2004-01-05 05:13:27
|
Update of /cvsroot/jxwb/jxwb In directory sc8-pr-cvs1:/tmp/cvs-serv403 Modified Files: .classpath .project Added Files: .cvsignore Log Message: added cvsignore for bin removed libs from project made project dependent on the wwe project --- NEW FILE: .cvsignore --- bin Index: .classpath =================================================================== RCS file: /cvsroot/jxwb/jxwb/.classpath,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** .classpath 5 Jan 2004 03:03:35 -0000 1.2 --- .classpath 5 Jan 2004 05:13:20 -0000 1.3 *************** *** 3,9 **** <classpathentry kind="src" path="src"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> ! <classpathentry kind="lib" path="lib/wwe.jar"/> ! <classpathentry kind="lib" path="lib/sac.jar"/> ! <classpathentry kind="lib" path="lib/flute.jar"/> <classpathentry kind="output" path="bin"/> </classpath> --- 3,7 ---- <classpathentry kind="src" path="src"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> ! <classpathentry kind="src" path="/wwe"/> <classpathentry kind="output" path="bin"/> </classpath> Index: .project =================================================================== RCS file: /cvsroot/jxwb/jxwb/.project,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** .project 23 Oct 2003 03:49:26 -0000 1.1 --- .project 5 Jan 2004 05:13:20 -0000 1.2 *************** *** 4,7 **** --- 4,8 ---- <comment></comment> <projects> + <project>wwe</project> </projects> <buildSpec> |
From: <de...@us...> - 2004-01-05 05:12:24
|
Update of /cvsroot/jxwb/wwe In directory sc8-pr-cvs1:/tmp/cvs-serv32763 Added Files: .cvsignore Log Message: added cvsignore for bin --- NEW FILE: .cvsignore --- bin |
From: <de...@us...> - 2004-01-05 04:03:20
|
Update of /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe In directory sc8-pr-cvs1:/tmp/cvs-serv23688/src/com/montarasoftware/wwe Modified Files: WWEAuthenticator.java Log Message: removed unneeded comments Index: WWEAuthenticator.java =================================================================== RCS file: /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/WWEAuthenticator.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** WWEAuthenticator.java 5 Jan 2004 03:06:58 -0000 1.1 --- WWEAuthenticator.java 5 Jan 2004 04:03:16 -0000 1.2 *************** *** 207,230 **** } } ! /* ! * $Log$ ! * Revision 1.1 2004/01/05 03:06:58 devilm ! * initial load of HTML editor pane and kit ! * Revision 1.4 2003/12/17 10:23:30 ! * jitender.sachdeva Integrated with JTidy to handle many instances of ! * malformed HTML ! * ! * ! * 6 11/25/03 12:16p Faruk.khan ! * ! * 5 10/29/03 4:12p Faruk.khan ! * ! * 4 10/28/03 10:10a Faruk.khan ! * ! * 3 10/24/03 3:31p Faruk.khan Changed it completely. Added a lot more ! * functionality. ! * ! * 2 10/17/03 3:52p Faruk.khan Optimized Imports ! * ! * 1 9/24/03 5:50p Faruk.khan ! */ --- 207,209 ---- } } ! |
Update of /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/view In directory sc8-pr-cvs1:/tmp/cvs-serv15363/src/com/montarasoftware/wwe/view Added Files: WWENoFramesView.java WWEAppletView.java WWEFrameSetView.java WWEFieldSetView.java WWEHiddenTagView.java WWEParagraphView.java WWECustCommentView.java WWETableView.java WWEIsindexView.java WWEBRView.java WWEListView.java WWEInlineView.java WWEBDOView.java WWEImageView.java WWEBasicButtonUI.java WWECommentView.java WWEIFrameView.java WWEFrameView.java WWEEditableView.java WWEBlockView.java WWESelectView.java WWEObjectView.java WWEHRuleView.java WWEButtonView.java WWEFormView.java WWELineView.java WWEBasicButtonListener.java WWENullView.java WWELabelView.java Log Message: initial load of HTML editor pane and kit --- NEW FILE: WWENoFramesView.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.view; import java.awt.Container; import java.awt.Graphics; import java.awt.Shape; import javax.swing.text.Element; import javax.swing.text.JTextComponent; import javax.swing.text.View; //import javax.swing.text.*; //import java.awt.*; //import javax.swing.text.html.*; /** * This is the view associated with the html tag NOFRAMES. * This view has been written to ignore the contents of the * NOFRAMES tag. The contents of the tag will only be visible * when the JTextComponent the view is contained in is editable. * * @author * @version */ public class WWENoFramesView extends WWEBlockView { /** * Creates a new view that represents an * html box. This can be used for a number * of elements. By default this view is not * visible. * * @param elem the element to create a view for * @param axis either View.X_AXIS or View.Y_AXIS */ public WWENoFramesView(Element elem, int axis) { super(elem, axis); visible = false; } /** * If this view is not visible, then it returns. * Otherwise it invokes the superclass. * * @param g the rendering surface to use * @param allocation the allocated region to render into * @see #isVisible * @see text.ParagraphView#paint */ public void paint(Graphics g, Shape allocation) { Container host = getContainer(); if (host != null && visible != ((JTextComponent)host).isEditable()) { visible = ((JTextComponent)host).isEditable(); } if (!isVisible()) { return; } super.paint(g, allocation); } /** * Determines if the JTextComponent that the view * is contained in is editable. If so, then this * view and all its child views are visible. * Once this has been determined, the superclass * is invoked to continue processing. * * @param p the parent View. * @see javax.swing.text.html.BlockView#setParent */ public void setParent(View p) { if (p != null) { Container host = p.getContainer(); if (host != null) { visible = ((JTextComponent)host).isEditable(); } } super.setParent(p); } /** * Returns a true/false value that represents * whether the view is visible or not. */ public boolean isVisible() { return visible; } /** * Do nothing if the view is not visible, otherwise * invoke the superclass to perform layout. */ protected void layout(int width, int height) { if (!isVisible()) { return; } super.layout(width, height); } /** * Determines the preferred span for this view. Returns * 0 if the view is not visible, otherwise it calls the * superclass method to get the preferred span. * axis. * * @param axis may be either View.X_AXIS or View.Y_AXIS * @return the span the view would like to be rendered into; * typically the view is told to render into the span * that is returned, although there is no guarantee; * the parent may choose to resize or break the view * @see text.ParagraphView#getPreferredSpan */ public float getPreferredSpan(int axis) { if (!visible) { return 0; } return super.getPreferredSpan(axis); } /** * Determines the minimum span for this view along an * axis. Returns 0 if the view is not visible, otherwise * it calls the superclass method to get the minimum span. * * @param axis may be either <code>View.X_AXIS</code> or * <code>View.Y_AXIS</code> * @return the minimum span the view can be rendered into * @see text.ParagraphView#getMinimumSpan */ public float getMinimumSpan(int axis) { if (!visible) { return 0; } return super.getMinimumSpan(axis); } /** * Determines the maximum span for this view along an * axis. Returns 0 if the view is not visible, otherwise * it calls the superclass method ot get the maximum span. * * @param axis may be either <code>View.X_AXIS</code> or * <code>View.Y_AXIS</code> * @return the maximum span the view can be rendered into * @see text.ParagraphView#getMaximumSpan */ public float getMaximumSpan(int axis) { if (!visible) { return 0; } return super.getMaximumSpan(axis); } boolean visible; } --- NEW FILE: WWEAppletView.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.view; import java.awt.Color; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.Shape; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.Element; import javax.swing.text.Position; import javax.swing.text.View; import javax.swing.text.html.HTML; /* * MSAppletView.java * An extension of the View that renders a grey area equal to the size of the applet * requested on the Document rendering componenet in case of APPLET tag * @author Tarundeep Singh * @version 1.0 07 August 2003 */ public class WWEAppletView extends View{ /* @param elem the element to create a view for. * Extracts the height and width of the applet from the * attributes of the given element. */ public WWEAppletView(Element elm){ super(elm); AttributeSet a = elm.getAttributes(); String s1 = (String) a.getAttribute(HTML.Attribute.HEIGHT); String s2 = (String) a.getAttribute(HTML.Attribute.WIDTH ); if ((s1 != null)&&(s2 != null)) { try { m_height = Integer.parseInt(s1); m_width = Integer.parseInt(s2); } catch (NumberFormatException nfe) { // fall through to one column } } } /* @param axis the axis for which the span is required */ public float getMinimumSpan(int axis){ if ((axis != X_AXIS) && (axis != Y_AXIS)) { throw new IllegalArgumentException("Invalid axis: " + axis); } if (axis == X_AXIS) return m_width; else return m_height; } /* @param axis the axis for which the span is required */ public float getPreferredSpan(int axis){ if ((axis != X_AXIS) && (axis != Y_AXIS)) { throw new IllegalArgumentException("Invalid axis: " + axis); } if (axis == X_AXIS) return m_width; else return m_height; } /* @param axis the axis for which the span is required */ public float getMaximumSpan(int axis){ if ((axis != X_AXIS) && (axis != Y_AXIS)) { throw new IllegalArgumentException("Invalid axis: " + axis); } if (axis == X_AXIS) return m_width; else return m_height; } /* @param g graphis object for rendering the view * a Shape object - area allocated to perform the rendering */ public void paint(Graphics g,Shape a){ Rectangle r = (Rectangle)a; int x = r.x; int y = r.y; g.setColor(Color.LIGHT_GRAY); g.fillRect(x,y,m_width,m_height); g.setColor(Color.RED); g.drawLine(x+5,y+5,x+15,y+15); g.drawLine(x+15,y+5,x+5,y+15); // g.drawString("Applet not supported",x+5,y+height-5); } /* * Provides a mapping, for a given character, * from the document model coordinate space * to the view coordinate space. * * @param pos the position of the desired character (>=0) * @param a the area of the view, which encompasses the requested character * @param b the bias toward the previous character or the * next character represented by the offset * @return the bounding box, in view coordinate space, * of the character at the specified position * @exception BadLocationException if the specified position does * not represent a valid location in the associated document */ public Shape modelToView(int pos,Shape s,Position.Bias b) throws BadLocationException{ int p0 = getStartOffset(); int p1 = getEndOffset(); if ((pos >= p0) && (pos <= p1)) { Rectangle r = s.getBounds(); r.setSize(m_width,m_height); return r; } throw new BadLocationException(pos + " not in range " + p0 + "," + p1, pos); } /** * Provides a mapping from the view coordinate space to the logical * coordinate space of the model. * * @param x the X coordinate >= 0 * @param y the Y coordinate >= 0 * @param a the allocated region to render into * @return the location within the model that best represents * the given point in the view * @see View#viewToModel */ public int viewToModel(float x,float y, Shape a,Position.Bias[] Bias){ Rectangle alloc = (Rectangle) a; if (x < alloc.x + (alloc.width / 2)) { Bias[0] = Position.Bias.Forward; return getStartOffset(); } Bias[0] = Position.Bias.Backward; return getEndOffset(); } /*Returns the preferd base of alignment along the axis for *which the method is called *@param axis the axis for which alignment is desired */ public float getAlignment(int axis) { if(axis == View.X_AXIS) return 0.5f; else return 1; } private int m_height; private int m_width; } --- NEW FILE: WWEFrameSetView.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.view; import java.util.StringTokenizer; import javax.swing.SizeRequirements; import javax.swing.text.AttributeSet; import javax.swing.text.Element; import javax.swing.text.View; import javax.swing.text.html.HTML; /** * Implements a FrameSetView, intended to support the HTML * <FRAMESET> tag. Supports the ROWS and COLS attributes. * * @author Anuj Jain * @version 1.0 07 August 2003 */ public class WWEFrameSetView extends javax.swing.text.BoxView { String[] children; int[] percentChildren; int[] absoluteChildren; int[] relativeChildren; int percentTotals; int absoluteTotals; int relativeTotals; /** * Constructs a FrameSetView for the given element. * * @param elem the element that this view is responsible for */ public WWEFrameSetView(Element elem, int axis) { super(elem, axis); if (axis == View.Y_AXIS) { children = parseRowColSpec(HTML.Attribute.ROWS); } else { children = parseRowColSpec(HTML.Attribute.COLS); } init(); } /** * Parses the ROW or COL attributes and returns * an array of strings that represent the space * distribution. * */ private String[] parseRowColSpec(HTML.Attribute key) { AttributeSet attributes = getElement().getAttributes(); String spec = "*"; if (attributes != null) { if (attributes.getAttribute(key) != null) { spec = (String)attributes.getAttribute(key); } } StringTokenizer tokenizer = new StringTokenizer(spec, ","); int nTokens = tokenizer.countTokens(); String[] items = new String[nTokens]; for (int i = 0; i < nTokens; i++) { items[i] = tokenizer.nextToken().trim(); // As per the spec, 100% is the same as * // hence the mapping. // if (items[i].equals("100%")) { items[i] = "*"; } } return items; } /** * Initializes a number of internal state variables * that store information about space allocation * for the frames contained within the frameset. */ private void init() { percentChildren = new int[children.length]; relativeChildren = new int[children.length]; absoluteChildren = new int[children.length]; for (int i = 0; i < children.length; i++) { percentChildren[i] = -1; relativeChildren[i] = -1; absoluteChildren[i] = -1; if (children[i].endsWith("*")) { if (children[i].length() > 1) { relativeChildren[i] = Integer.parseInt(children[i].substring( 0, children[i].length()-1)); relativeTotals += relativeChildren[i]; } else { relativeChildren[i] = 1; relativeTotals += 1; } } else if (children[i].indexOf('%') != -1) { percentChildren[i] = parseDigits(children[i]); percentTotals += percentChildren[i]; } else { absoluteChildren[i] = Integer.parseInt(children[i]); } } if (percentTotals > 100) { for (int i = 0; i < percentChildren.length; i++) { if (percentChildren[i] > 0) { percentChildren[i] = (percentChildren[i] * 100) / percentTotals; } } percentTotals = 100; } } /** * Perform layout for the major axis of the box (i.e. the * axis that it represents). The results of the layout should * be placed in the given arrays which represent the allocations * to the children along the major axis. * * @param targetSpan the total span given to the view, which * whould be used to layout the children * @param axis the axis being layed out * @param offsets the offsets from the origin of the view for * each of the child views; this is a return value and is * filled in by the implementation of this method * @param spans the span of each child view; this is a return * value and is filled in by the implementation of this method * @return the offset and span for each child view in the * offsets and spans parameters */ protected void layoutMajorAxis(int targetSpan, int axis, int[] offsets, int[] spans) { SizeRequirements.calculateTiledPositions(targetSpan, null, getChildRequests(targetSpan, axis), offsets, spans); } protected SizeRequirements[] getChildRequests(int targetSpan, int axis) { int span[] = new int[children.length]; spread(targetSpan, span); int n = getViewCount(); SizeRequirements[] reqs = new SizeRequirements[n]; for (int i = 0, sIndex = 0; i < n; i++) { View v = getView(i); if ((v instanceof WWEFrameView) || (v instanceof WWEFrameSetView)) { reqs[i] = new SizeRequirements((int) v.getMinimumSpan(axis), span[sIndex], (int) v.getMaximumSpan(axis), 0.5f); sIndex++; } else { int min = (int) v.getMinimumSpan(axis); int pref = (int) v.getPreferredSpan(axis); int max = (int) v.getMaximumSpan(axis); float a = v.getAlignment(axis); reqs[i] = new SizeRequirements(min, pref, max, a); } } return reqs; } /** * This method is responsible for returning in span[] the * span for each child view along the major axis. it * computes this based on the information that extracted * from the value of the ROW/COL attribute. */ private void spread(int targetSpan, int span[]) { if (targetSpan == 0) { return; } int tempSpace = 0; int remainingSpace = targetSpan; // allocate the absolute's first, they have // precedence // for (int i = 0; i < span.length; i++) { if (absoluteChildren[i] > 0) { span[i] = absoluteChildren[i]; remainingSpace -= span[i]; } } // then deal with percents. // tempSpace = remainingSpace; for (int i = 0; i < span.length; i++) { if (percentChildren[i] > 0 && tempSpace > 0) { span[i] = (percentChildren[i] * tempSpace) / 100; remainingSpace -= span[i]; } else if (percentChildren[i] > 0 && tempSpace <= 0) { span[i] = targetSpan / span.length; remainingSpace -= span[i]; } } // allocate remainingSpace to relative if (remainingSpace > 0 && relativeTotals > 0) { for (int i = 0; i < span.length; i++) { if (relativeChildren[i] > 0) { span[i] = (remainingSpace * relativeChildren[i]) / relativeTotals; } } } else if (remainingSpace > 0) { // There are no relative columns and the space has been // under- or overallocated. In this case, turn all the // percentage and pixel specified columns to percentage // columns based on the ratio of their pixel count to the // total "virtual" size. (In the case of percentage columns, // the pixel count would equal the specified percentage // of the screen size. // This action is in accordance with the HTML // 4.0 spec (see section 8.3, the end of the discussion of // the FRAMESET tag). The precedence of percentage and pixel // specified columns is unclear (spec seems to indicate that // they share priority, however, unspecified what happens when // overallocation occurs.) // addendum is that we behave similiar to netscape in that specified // widths have precedance over percentage widths... float vTotal = (float)(targetSpan - remainingSpace); float[] tempPercents = new float[span.length]; remainingSpace = targetSpan; for (int i = 0; i < span.length; i++) { // ok we know what our total space is, and we know how large each // column should be relative to each other... therefore we can use // that relative information to deduce their percentages of a whole // and then scale them appropriately for the correct size tempPercents[i] = ((float)span[i] / vTotal) * 100.00f; span[i] = (int) ( ((float)targetSpan * tempPercents[i]) / 100.00f); remainingSpace -= span[i]; } // this is for just in case there is something left over.. if there is we just // add it one pixel at a time to the frames in order.. We shouldn't really ever get // here and if we do it shouldn't be with more than 1 pixel, maybe two. int i = 0; while (remainingSpace != 0) { if (remainingSpace < 0) { span[i++]--; remainingSpace++; } else { span[i++]++; remainingSpace--; } // just in case there are more pixels than frames...should never happen.. if (i == span.length)i = 0; } } } /* * Users have been known to type things like "%25" and "25 %". Deal * with it. */ private int parseDigits(String mixedStr) { int result = 0; for (int i = 0; i < mixedStr.length(); i++) { char ch = mixedStr.charAt(i); if (Character.isDigit(ch)) { result = (result * 10) + Character.digit(ch, 10); } } return result; } } --- NEW FILE: WWEFieldSetView.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.view; import java.awt.Color; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.Shape; import javax.swing.text.Element; import javax.swing.text.View; /** * WWEFieldSetView.java * Implements a FieldSetView, intended to support the HTML * <FIELDSET> tag,<LEGEND>. Supports drawing of a border together with * other inline Elements around the child views * * @author Tarundeep S Sodhi * @version 1.23, 01/23/03 */ public class WWEFieldSetView extends WWEBlockView{ public WWEFieldSetView(Element elem){ super(elem,View.Y_AXIS); } /* Renders a Rectangle around the child element with brak in * the top side of the rectangle equal to the space required for * the Legend Elements * @param g graphis object for rendering the view * @Shape object - area allocated to perform the rendering */ public void paint(Graphics g, Shape a) { boolean flag = false; Rectangle rect = a.getBounds(); g.setColor(Color.black); Element elem = getElement(); Element c_elem =null; int x = rect.x; int y = rect.y; int height = rect.height; int width = rect.width; // System.out.println("Values of X and Y are : "+x+" * "+y); /*for(int i=0;i<elem.getElementCount();i++){ c_elem=elem.getElement(i); if(c_elem.getName().equals("legend")){ flag = true; setInsets((short)0,(short)10,(short)0,(short)0); } }*/ if(elem.getElement(0).getName().equals("legend")){ flag = true; setInsets((short)0,(short)10,(short)0,(short)10); } if (flag == true){ int size = (int)getSpan(elem); g.drawLine(x,y+10,x+8,y+10); g.drawLine(x+10+size,y+10,x+width-5,y+10); g.drawLine(x,y+10,x,y+height); g.drawLine(x,y+height,x+width-5,y+height); g.drawLine(x+width-5,y+10,x+width-5,y+height); }else if(flag == false){ setInsets((short)10,(short)10,(short)0,(short)10); g.drawLine(x,y,x+width-5,y); g.drawLine(x,y,x,y+height); g.drawLine(x,y+height,x+width-5,y+height); g.drawLine(x+width-5,y,x+width-5,y+height); } super.paint(g,rect); } int getSpan(Element elem){ Element c_elem =null; View v = null; for(int i=0;i<elem.getElementCount();i++){ v = getView(i); if(v.getClass().getName().equals("com.montarasoftware.alchemy.client.java.comp.view.WWEBlockView")); break; //System.out.println(v.getClass().getName()); } for(int i=0;i<elem.getElementCount();i++){ c_elem=elem.getElement(i); //System.out.println("element name is :"+c_elem.getName());//.equals("legend")) //v = getView(i); } //int width =0; //if(v != null){ // return (int)v.getMinimumSpan(View.X_AXIS); //} //return 0; if(v != null){ return (int)v.getPreferredSpan(View.X_AXIS); } return 0; } public int getBreakWeight(int axis, float pos, float len) { return View.BadBreakWeight; } } --- NEW FILE: WWEHiddenTagView.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.view; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Insets; import java.awt.Shape; import java.awt.Toolkit; import java.io.Serializable; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.border.Border; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.AbstractDocument; import javax.swing.text.AttributeSet; import javax.swing.text.Document; import javax.swing.text.Element; import javax.swing.text.JTextComponent; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import javax.swing.text.View; import javax.swing.text.ViewFactory; import javax.swing.text.html.HTML; /** * WWEHiddenTagView subclasses EditableView to contain a JTextField showing * the element name. When the textfield is edited the element name is * reset. As this inherits from EditableView if the JTextComponent is * not editable, the textfield will not be visible. * * @author RSI * @version */ public class WWEHiddenTagView extends WWEEditableView implements DocumentListener { public WWEHiddenTagView(Element e) { super(e); yAlign = 1; } protected Component createComponent() { JTextField tf = new JTextField(getElement().getName()); Document doc = getDocument(); Font font; if (doc instanceof StyledDocument) { font = ((StyledDocument)doc).getFont(getAttributes()); tf.setFont(font); } else { font = tf.getFont(); } tf.getDocument().addDocumentListener(this); updateYAlign(font); // Create a panel to wrap the textfield so that the textfields // laf border shows through. JPanel panel = new JPanel(new BorderLayout()); panel.setBackground(null); if (isEndTag()) { panel.setBorder(EndBorder); } else { panel.setBorder(StartBorder); } panel.add(tf); return panel; } public float getAlignment(int axis) { if (axis == View.Y_AXIS) { return yAlign; } return 0.5f; } public float getMinimumSpan(int axis) { if (axis == View.X_AXIS && isVisible()) { // Default to preferred. return Math.max(30, super.getPreferredSpan(axis)); } return super.getMinimumSpan(axis); } public float getPreferredSpan(int axis) { if (axis == View.X_AXIS && isVisible()) { return Math.max(30, super.getPreferredSpan(axis)); } return super.getPreferredSpan(axis); } public float getMaximumSpan(int axis) { if (axis == View.X_AXIS && isVisible()) { // Default to preferred. return Math.max(30, super.getMaximumSpan(axis)); } return super.getMaximumSpan(axis); } // DocumentListener methods public void insertUpdate(DocumentEvent e) { updateModelFromText(); } public void removeUpdate(DocumentEvent e) { updateModelFromText(); } public void changedUpdate(DocumentEvent e) { updateModelFromText(); } // View method public void changedUpdate(DocumentEvent e, Shape a, ViewFactory f) { if (!isSettingAttributes) { setTextFromModel(); } } // local methods void updateYAlign(Font font) { FontMetrics fm = Toolkit.getDefaultToolkit().getFontMetrics(font); float h = fm.getHeight(); float d = fm.getDescent(); yAlign = (h - d) / h; } void resetBorder() { Component comp = getComponent(); if (comp != null) { if (isEndTag()) { ((JPanel)comp).setBorder(EndBorder); } else { ((JPanel)comp).setBorder(StartBorder); } } } /** * This resets the text on the text component we created to match * that of the AttributeSet for the Element we represent. * <p>If this is invoked on the event dispatching thread, this * directly invokes <code>_setTextFromModel</code>, otherwise * <code>SwingUtilities.invokeLater</code> is used to schedule execution * of <code>_setTextFromModel</code>. */ void setTextFromModel() { if (SwingUtilities.isEventDispatchThread()) { _setTextFromModel(); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { _setTextFromModel(); } }); } } /** * This resets the text on the text component we created to match * that of the AttributeSet for the Element we represent. */ void _setTextFromModel() { Document doc = getDocument(); try { isSettingAttributes = true; if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readLock(); } JTextComponent text = getTextComponent(); if (text != null) { text.setText(getRepresentedText()); resetBorder(); Container host = getContainer(); if (host != null) { preferenceChanged(this, true, true); host.repaint(); } } } finally { isSettingAttributes = false; if (doc instanceof AbstractDocument) { ((AbstractDocument)doc).readUnlock(); } } } /** * This copies the text from the text component we've created * to the Element's AttributeSet we represent. * <p>If this is invoked on the event dispatching thread, this * directly invokes <code>_updateModelFromText</code>, otherwise * <code>SwingUtilities.invokeLater</code> is used to schedule execution * of <code>_updateModelFromText</code>. */ void updateModelFromText() { if (!isSettingAttributes) { if (SwingUtilities.isEventDispatchThread()) { _updateModelFromText(); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { _updateModelFromText(); } }); } } } /** * This copies the text from the text component we've created * to the Element's AttributeSet we represent. */ void _updateModelFromText() { Document doc = getDocument(); Object name = getElement().getAttributes().getAttribute (StyleConstants.NameAttribute); if ((name instanceof HTML.UnknownTag) && (doc instanceof StyledDocument)) { SimpleAttributeSet sas = new SimpleAttributeSet(); JTextComponent textComponent = getTextComponent(); if (textComponent != null) { String text = textComponent.getText(); isSettingAttributes = true; try { sas.addAttribute(StyleConstants.NameAttribute, new HTML.UnknownTag(text)); ((StyledDocument)doc).setCharacterAttributes (getStartOffset(), getEndOffset() - getStartOffset(), sas, false); } finally { isSettingAttributes = false; } } } } JTextComponent getTextComponent() { Component comp = getComponent(); return (comp == null) ? null : (JTextComponent)((Container)comp). getComponent(0); } String getRepresentedText() { String retValue = getElement().getName(); return (retValue == null) ? "" : retValue; } boolean isEndTag() { AttributeSet as = getElement().getAttributes(); if (as != null) { Object end = as.getAttribute(HTML.Attribute.ENDTAG); if (end != null && (end instanceof String) && ((String)end).equals("true")) { return true; } } return false; } /** Alignment along the y axis, based on the font of the textfield. */ float yAlign; /** Set to true when setting attributes. */ boolean isSettingAttributes; // Following are for Borders that used for Unknown tags and comments. // // Border defines static final int circleR = 3; static final int circleD = circleR * 2; static final int tagSize = 6; static final int padding = 3; static final Color UnknownTagBorderColor = Color.black; static final Border StartBorder = new StartTagBorder(); static final Border EndBorder = new EndTagBorder(); static class StartTagBorder implements Border, Serializable { public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { g.setColor(UnknownTagBorderColor); x += padding; width -= (padding * 2); g.drawLine(x, y + circleR, x, y + height - circleR); g.drawArc(x, y + height - circleD - 1, circleD, circleD, 180, 90); g.drawArc(x, y, circleD, circleD, 90, 90); g.drawLine(x + circleR, y, x + width - tagSize, y); g.drawLine(x + circleR, y + height - 1, x + width - tagSize, y + height - 1); g.drawLine(x + width - tagSize, y, x + width - 1, y + height / 2); g.drawLine(x + width - tagSize, y + height, x + width - 1, y + height / 2); } public Insets getBorderInsets(Component c) { return new Insets(2, 2 + padding, 2, tagSize + 2 + padding); } public boolean isBorderOpaque() { return false; } } // End of class WWEHiddenTagView.StartTagBorder static class EndTagBorder implements Border, Serializable { public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { g.setColor(UnknownTagBorderColor); x += padding; width -= (padding * 2); g.drawLine(x + width - 1, y + circleR, x + width - 1, y + height - circleR); g.drawArc(x + width - circleD - 1, y + height - circleD - 1, circleD, circleD, 270, 90); g.drawArc(x + width - circleD - 1, y, circleD, circleD, 0, 90); g.drawLine(x + tagSize, y, x + width - circleR, y); g.drawLine(x + tagSize, y + height - 1, x + width - circleR, y + height - 1); g.drawLine(x + tagSize, y, x, y + height / 2); g.drawLine(x + tagSize, y + height, x, y + height / 2); } public Insets getBorderInsets(Component c) { return new Insets(2, tagSize + 2 + padding, 2, 2 + padding); } public boolean isBorderOpaque() { return false; } } // End of class WWEHiddenTagView.EndTagBorder } // End of WWEHiddenTagView --- NEW FILE: WWEParagraphView.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.view; import java.awt.Component; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.Shape; import java.net.MalformedURLException; import java.net.URL; import java.util.StringTokenizer; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.SizeRequirements; import javax.swing.text.AttributeSet; import javax.swing.text.Element; import javax.swing.text.JTextComponent; import javax.swing.text.StyleConstants; import javax.swing.text.View; import com.montarasoftware.wwe.WWECSS; import com.montarasoftware.wwe.WWEHTMLDocument; import com.montarasoftware.wwe.WWEStyleSheet; /** * Displays the a paragraph, and uses css attributes for its * configuration. * * @author * @version */ public class WWEParagraphView extends javax.swing.text.ParagraphView { //Variables used for line-height implementation. String text; String elementName; /** * Constructs a ParagraphView for the given element. * * @param elem the element that this view is responsible for */ public WWEParagraphView(Element elem) { super(elem); //Added by Avisek for removing some blank lines after textarea try { int start = elem.getStartOffset(); int end = elem.getEndOffset(); elementName = elem.getName(); WWEHTMLDocument doc = (WWEHTMLDocument)elem.getDocument(); text = (doc.getText(start, end-start)).trim(); }catch(Exception e){ System.err.println(" Error - WWEParagraphView - Consturctor - "+e); } } /** * Establishes the parent view for this view. This is * guaranteed to be called before any other methods if the * parent view is functioning properly. * <p> * This is implemented * to forward to the superclass as well as call the * <a href="#setPropertiesFromAttributes">setPropertiesFromAttributes</a> * method to set the paragraph properties from the css * attributes. The call is made at this time to ensure * the ability to resolve upward through the parents * view attributes. * * @param parent the new parent, or null if the view is * being removed from a parent it was previously added * to */ public void setParent(View parent) { super.setParent(parent); if (parent != null) { setPropertiesFromAttributes(); } } /** * Fetches the attributes to use when rendering. This is * implemented to multiplex the attributes specified in the * model with a StyleSheet. */ public AttributeSet getAttributes() { if (attr == null) { WWEStyleSheet sheet = getStyleSheet(); attr = sheet.getViewAttributes(this); } return attr; } /** * Sets up the paragraph from css attributes instead of * the values found in StyleConstants (i.e. which are used * by the superclass). Since */ protected void setPropertiesFromAttributes() { WWEStyleSheet sheet = getStyleSheet(); attr = sheet.getViewAttributes(this); /* Enumeration enum=attr.getAttributeNames(); while(enum.hasMoreElements()){ Object attrname=enum.nextElement(); Object attrvalue=attr.getAttribute(attrname); System.err.println("Attribute Names and Values are : "+attrname+"******"+attrvalue); } */ painter = sheet.getBoxPainter(attr); if (attr != null) { super.setPropertiesFromAttributes(); setInsets((short) painter.getInset(TOP, this), (short) painter.getInset(LEFT, this), (short) painter.getInset(BOTTOM, this), (short) painter.getInset(RIGHT, this)); Object o = attr.getAttribute(WWECSS.Attribute.TEXT_ALIGN); if (o != null) { // set horizontal alignment String ta = o.toString(); if (ta.equals("left")) { setJustification(StyleConstants.ALIGN_LEFT); } else if (ta.equals("center")) { setJustification(StyleConstants.ALIGN_CENTER); } else if (ta.equals("right")) { setJustification(StyleConstants.ALIGN_RIGHT); } else if (ta.equals("justify")) { setJustification(StyleConstants.ALIGN_JUSTIFIED); } } // Get the width/height cssWidth = (WWECSS.LengthValue)attr.getAttribute( WWECSS.Attribute.WIDTH); cssHeight = (WWECSS.LengthValue)attr.getAttribute( WWECSS.Attribute.HEIGHT); cssMinHeight = (WWECSS.LengthValue)attr.getAttribute( WWECSS.Attribute.MIN_HEIGHT); cssMaxHeight = (WWECSS.LengthValue)attr.getAttribute( WWECSS.Attribute.MAX_HEIGHT); cssMinWidth = (WWECSS.LengthValue)attr.getAttribute( WWECSS.Attribute.MIN_WIDTH); cssMaxWidth = (WWECSS.LengthValue)attr.getAttribute( WWECSS.Attribute.MAX_WIDTH); /* Added by Avisek for LIST_STYLE_IMAGE to set the height of the row as per * the height of the image */ Icon img = null; String imgstr = null; Object style = attr.getAttribute(WWECSS.Attribute.LIST_STYLE_IMAGE); if(style != null) imgstr = style.toString(); if (imgstr != null && !imgstr.equals("none")) { String tmpstr = null; try { StringTokenizer st = new StringTokenizer(imgstr, "()"); if (st.hasMoreTokens()) tmpstr = st.nextToken(); if (st.hasMoreTokens()) tmpstr = st.nextToken(); URL u = new URL(tmpstr); img = new ImageIcon(u); } catch (MalformedURLException e) { if (tmpstr != null && sheet != null && sheet.getBase() != null) { try { URL u = new URL(sheet.getBase(), tmpstr); img = new ImageIcon(u); } catch (MalformedURLException murle) { img = null; } } else { img = null; } } } if(img != null) { int w = img.getIconWidth(); int h = img.getIconHeight(); //setFirstLineIndent(15f); setLineSpacing(h/24);//* This value is given on hit & trial basis //System.err.println("w="+w+" h="+h+" "+img); } //***/ //Added by Avisek for line-height and text-indent //System.out.println("*** WWEParagraphView "+elementName+"\n***"+text); Object line_height = attr.getAttribute(WWECSS.Attribute.LINE_HEIGHT); if(line_height != null) { //System.out.println("*** WWEParagraphView line_height - "+line_height.toString()); try{ String strLineHeight = line_height.toString().trim(); int n = strLineHeight.indexOf("attr(em)");// attr(em) is automaticaly converted by the API if(n != -1)// Check if attr(em) is present in the value of this attribute strLineHeight = strLineHeight.substring(0,n).trim(); n = strLineHeight.indexOf("em"); if(n != -1)// Check if em is present in the value of this attribute strLineHeight = strLineHeight.substring(0,n).trim(); n = strLineHeight.indexOf("%"); if(n != -1) strLineHeight = strLineHeight.substring(0,n).trim(); float f = Float.parseFloat(strLineHeight); if(elementName.equals("null") || text.equals("null") || text.trim().equals("")) return; //** The method will return so that line spacing is not called //** otherwise some extra space comes below a TEXTAREA f /= 4; setLineSpacing(f); }catch(Exception e ){ setLineSpacing(1/4); } } Object text_indent = attr.getAttribute(WWECSS.Attribute.TEXT_INDENT); if(text_indent != null) { System.out.println("### WWEParagraphView - "+elementName+" - text_indent - "+text_indent.toString()); try { String strTextIndent = text_indent.toString().trim(); int index = strTextIndent.indexOf("%"); if(index != -1) strTextIndent = strTextIndent.substring(0,index).trim(); WWECSS.LengthUnit lu = new WWECSS.LengthUnit(strTextIndent, (short)1, 1f); float i = lu.value; //System.err.println("### - "+elementName+" - text_indent - "+strTextIndent+" value = "+i); setFirstLineIndent(i); }catch(Exception e ){System.err.println("*** ERROR "+e); } } //end code for text-indent and line-height } } protected WWEStyleSheet getStyleSheet() { WWEHTMLDocument doc = (WWEHTMLDocument) getDocument(); return doc.getStyleSheet(); } /** * Calculate the needs for the paragraph along the minor axis. * This implemented to use the requirements of the superclass, * modified slightly to set a minimum span allowed. Typical * html rendering doesn't let the view size shrink smaller than * the length of the longest word. */ protected SizeRequirements calculateMinorAxisRequirements(int axis, SizeRequirements r) { r = super.calculateMinorAxisRequirements(axis, r); if (!WWEBlockView.spanSetFromAttributes(axis, r, cssWidth, cssHeight)) { // ??? Need to make this better so it doesn't require // WWEInlineView and works with font changes within the word. // find the longest minimum span. float min = 0; int n = getLayoutViewCount(); for (int i = 0; i < n; i++) { View v = getLayoutView(i); if (v instanceof WWEInlineView) { float wordSpan = ((WWEInlineView) v).getLongestWordSpan(); min = Math.max(wordSpan, min); } else { min = Math.max(v.getMinimumSpan(axis), min); } } r.minimum = Math.max(r.minimum, (int) min); r.preferred = Math.max(r.minimum, r.preferred); r.maximum = Math.max(r.preferred, r.maximum); } else { // Offset by the margins so that pref/min/max return the // right value. int margin = (axis == X_AXIS) ? getLeftInset() + getRightInset() : getTopInset() + getBottomInset(); r.minimum -= margin; r.preferred -= margin; r.maximum -= margin; } return r; } /** * Indicates whether or not this view should be * displayed. If none of the children wish to be * displayed and the only visible child is the * break that ends the paragraph, the paragraph * will not be considered visible. Otherwise, * it will be considered visible and return true. * * @return true if the paragraph should be displayed */ public boolean isVisible() { int n = getLayoutViewCount() - 1; for (int i = 0; i < n; i++) { View v = getLayoutView(i); if (v.isVisible()) { return true; } } if (n > 0) { View v = getLayoutView(n); if ((v.getEndOffset() - v.getStartOffset()) == 1) { return false; } } // If it's the last paragraph and not editable, it shouldn't // be visible. if (getStartOffset() == getDocument().getLength()) { boolean editable = false; Component c = getContainer(); if (c instanceof JTextComponent) { editable = ((JTextComponent)c).isEditable(); } if (!editable) { return false; } } return true; } /** * Renders using the given rendering surface and area on that * surface. This is implemented to delgate to the superclass * after stashing the base coordinate for tab calculations. * * @param g the rendering surface to use * @param a the allocated region to render into * @see View#paint */ public void paint(Graphics g, Shape a) { Rectangle r; if (a instanceof Rectangle) { r = (Rectangle) a; } else { r = a.getBounds(); } painter.paint(g, r.x, r.y, r.width, r.height, this); super.paint(g, a); } /** * Determines the preferred span for this view. Returns * 0 if the view is not visible, otherwise it calls the * superclass method to get the preferred span. * axis. * * @param axis may be either View.X_AXIS or View.Y_AXIS * @return the span the view would like to be rendered into; * typically the view is told to render into the span * that is returned, although there is no guarantee; * the parent may choose to resize or break the view * @see javax.swing.text.ParagraphView#getPreferredSpan */ /* public float getPreferredSpan(int axis) { if (!isVisible()) { return 0; } return super.getPreferredSpan(axis); } */ public float getPreferredSpan(int axis) { if (!isVisible()) { return 0; } if(axis==View.Y_AXIS) { WWECSS.LengthValue height=getRealHeight(); if(height!=null) return height.getValue(); } else if(axis==View.X_AXIS) { WWECSS.LengthValue width=getRealWidth(); if(width!=null) return width.getValue(); } return super.getPreferredSpan(axis); } /** * Algorithm as per w3c specs for calculating real height. * */ private WWECSS.LengthValue getRealHeight() { if(cssHeight!=null){ float height=cssHeight.getValue(); if(cssMinHeight!=null && cssMaxHeight!=null){ float minHeight=cssMinHeight.getValue(); float maxHeight=cssMaxHeight.getValue(); //if Max Height is less than Min height then as per W3C make max height as Min height. if(maxHeight < minHeight) cssMaxHeight=cssMinHeight; if(height<minHeight) cssHeight=cssMinHeight; else if(height > maxHeight) cssHeight=cssMaxHeight; }else if(cssMinHeight!=null){ float minHeight=cssMinHeight.getValue(); if(height<minHeight) cssHeight=cssMinHeight; } else if(cssMaxHeight!=null){ float maxHeight=cssMaxHeight.getValue(); if(height > maxHeight) cssHeight=cssMaxHeight; } }else { if(cssMinHeight!=null) cssHeight=cssMinHeight; } return cssHeight; } /** * Algorithm as per w3c specs for calculating real width. * */ private WWECSS.LengthValue getRealWidth() { if(cssWidth!=null){ float width=cssWidth.getValue(); if(cssMinWidth!=null && cssMaxWidth!=null){ float minWidth=cssMinWidth.getValue(); float maxWidth=cssMaxWidth.getValue(); //if Max Width is less than Min Width then as per W3C make max Width as Min Width. if(maxWidth < minWidth) cssMaxWidth=cssMinWidth; if(width<minWidth) cssWidth=cssMinWidth; else if(width > maxWidth) cssWidth=cssMaxWidth; }else if(cssMinWidth!=null){ float minWidth=cssMinWidth.getValue(); if(width<minWidth) cssWidth=cssMinWidth; } else if(cssMaxWidth!=null){ float maxWidth=cssMaxWidth.getValue(); if(width > maxWidth) cssWidth=cssMaxWidth; } }else { if(cssMinWi... [truncated message content] |
Update of /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe In directory sc8-pr-cvs1:/tmp/cvs-serv15363/src/com/montarasoftware/wwe Added Files: WWEStyleSheet.java WWEHTMLWriter.java WWEHTMLTextSelection.java WWEToggleButton.java WWEAbstractAction.java WWEConstants.java WWEComponent.java image-delayed.gif WWEHTMLEditorKit.java WWEHTML.java WWEEditorPane.java WWEFontFamilyPicker.java WWEOptionListModel.java WWEStylePicker.java WWECSS.java WWEActionNameConstants.java WWEHTMLText.java WWEProgressMonitorCallback.java WWEOptionComboBoxModel.java WWEHTMLAction.java WWECSSParser.java image-failed.gif WWEFontSizePicker.java SAC_CSSBridge.java AbstractActionPropertyChangeListener.java WWEMuxingAttributeSet.java WWEOption.java WWEAuthenticator.java WWEPageLoadProperties.java WWEHTMLDocument.java WWETextAreaDocument.java Log Message: initial load of HTML editor pane and kit --- NEW FILE: WWEStyleSheet.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: [...3799 lines suppressed...] selectors.addElement(selector); selectorTokens.removeAllElements(); } Vector selectors = new Vector(); Vector selectorTokens = new Vector(); /** Name of the current property. */ String propertyName; MutableAttributeSet declaration = new SimpleAttributeSet(); /** True if parsing a declaration, that is the Reader will not * contain a selector. */ boolean parsingDeclaration; /** True if the attributes are coming from a linked/imported style. */ boolean isLink; /** Where the CSS stylesheet lives. */ URL base; WWECSSParser parser = new WWECSSParser(); } } --- NEW FILE: WWEHTMLWriter.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: [...1268 lines suppressed...] */ public PropertiesMissingException() { super(); } /** * Constructs an <code>WriterPropertiesMissingException</code> with * the specified detail message. The error message string <code>s</code> * can later be retrieved by the <code>{@link java.lang.Throwable#getMessage}</code> * method of class <code>java.lang.Throwable</code>. * * @param s the detail message. */ public PropertiesMissingException(String s) { super(s); } } } --- NEW FILE: WWEHTMLTextSelection.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; /** * A transferable for HTML text. * * <p>It can be used in drag and drop operations or in copy and paste * operations. It supports two data flavors <code>WWEHTMLText</code> * and <code>String</code></p> * * @author Faruk M Khan * @version 1.0 17 October 2003 * * @see java.awt.datatransfer.DataFlavor * @see com.montarasoftware.alchemy.client.java.comp.WWEHTMLText */ public class WWEHTMLTextSelection implements Transferable, ClipboardOwner { /** index of HTML text data flavor */ private static final int HTML_TEXT = 0; /** index of String data flavor */ private static final int STRING = 1; /** the data to transfer */ private WWEHTMLText data; /** the data flavor of this transferable */ private static final DataFlavor[] flavors = { new DataFlavor(WWEHTMLText.class, "WWEHTMLText"), DataFlavor.stringFlavor }; /** * construct a <code>WWEHTMLTextSelection</code> with a chunk * of styled text. * * @param data - a WWEHTMLText object * * @see WWEHTMLText */ public WWEHTMLTextSelection(WWEHTMLText data) { this.data = data; } /* ---- start of Transferable implementation ----------------------------*/ /** * Returns an array of DataFlavor objects indicating the flavors the data * can be provided in. The array should be ordered according to preference * for providing the data (from most richly descriptive to least descriptive). * @return an array of data flavors in which this data can be transferred */ public DataFlavor[] getTransferDataFlavors() { return (DataFlavor[])flavors.clone(); } /** * Returns whether or not the specified data flavor is supported for * this object. * @param flavor the requested flavor for the data * @return boolean indicating wjether or not the data flavor is supported */ public boolean isDataFlavorSupported(DataFlavor flavor) { for (int i = 0; i < flavors.length; i++) { if (flavors[i].equals(flavor)) { return true; } } return false; } /** * Returns an object which represents the data to be transferred. The class * of the object returned is defined by the representation class of the flavor. * * @param flavor the requested flavor for the data * @see DataFlavor#getRepresentationClass * @exception IOException if the data is no longer available * in the requested flavor. * @exception UnsupportedFlavorException if the requested data flavor is * not supported. */ public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { if (flavor.equals(flavors[HTML_TEXT])) { return data; } else if (flavor.equals(flavors[STRING])) { return data.toString(); } else { throw new UnsupportedFlavorException(flavor); } } /* ----------- end of Transferable implementation ------------------- */ /* ----------- start of ClipboardOwner implementation --------------- */ /** * Notifies this object that it is no longer the owner of * the contents of the clipboard. * @param clipboard the clipboard that is no longer owned * @param contents the contents which this owner had placed on the clipboard */ public void lostOwnership(Clipboard clipboard, Transferable contents) { } /* ------------ end of ClipboardOwner implementation ---------------- */ } --- NEW FILE: WWEToggleButton.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.AbstractButton; import javax.swing.Action; import javax.swing.Icon; import javax.swing.JToggleButton; /** * Class provides a wrapper around the inherited from * <code>AbstractAction</code> class in JDK1.4. * This has been doen as a work around for the BugId: 4133141 * Please see * {@link http://developer.java.sun.com/developer/bugParade/bugs/4133141.html}. * * This class should or a wrapped version of this class should only * be used whenever we need to use a WWEToggleButton * * @author Faruk M Khan * @version 1.0 25 Aug 2003 */ public class WWEToggleButton extends JToggleButton{ /** * Creates an initially unselected toggle button * without setting the text or image. */ public WWEToggleButton () { super(null, null, false); } /** * Creates an initially unselected toggle button * with the specified image but no text. * * @param icon the image that the button should display */ public WWEToggleButton(Icon icon) { super(null, icon, false); } /** * Creates a toggle button with the specified image * and selection state, but no text. * * @param icon the image that the button should display * @param selected if true, the button is initially selected; * otherwise, the button is initially unselected */ public WWEToggleButton(Icon icon, boolean selected) { super(null, icon, selected); } /** * Creates an unselected toggle button with the specified text. * * @param text the string displayed on the toggle button */ public WWEToggleButton (String text) { super(text, null, false); } /** * Creates a toggle button with the specified text * and selection state. * * @param text the string displayed on the toggle button * @param selected if true, the button is initially selected; * otherwise, the button is initially unselected */ public WWEToggleButton (String text, boolean selected) { super(text, null, selected); } /** * Creates a toggle button where properties are taken from the * Action supplied. * * @since 1.3 */ public WWEToggleButton(Action a) { super(a); } /** * Creates a toggle button that has the specified text and image, * and that is initially unselected. * * @param text the string displayed on the button * @param icon the image that the button should display */ public WWEToggleButton(String text, Icon icon) { super(text, icon, false); } /** * Creates a toggle button with the specified text, image, and * selection state. * * @param text the text of the toggle button * @param icon the image that the button should display * @param selected if true, the button is initially selected; * otherwise, the button is initially unselected */ public WWEToggleButton (String text, Icon icon, boolean selected) { super(text, icon, selected); } /** * Factory method which creates the <code>PropertyChangeListener</code> * used to update the <code>ActionEvent</code> source as properties * change on its <code>Action</code> instance. Subclasses may * override this in order to provide their own * <code>PropertyChangeListener</code> if the set of * properties which should be kept up to date differs from the * default properties (<code>Text, Icon, Enabled, ToolTipText, * Mnemonic</code>). * <p> * Note that <code>PropertyChangeListeners</code> should avoid holding * strong references to the <code>ActionEvent</code> source, * as this may hinder garbage collection of the * <code>ActionEvent</code> source and all components * in its containment hierarchy. * * <b>Note: This method and the corresponding class has been overloaded to * handle the BugId:4133141</b> * * @param a the new action for the button * @since 1.3 * @see Action * @see #setAction */ protected PropertyChangeListener createActionPropertyChangeListener(Action a) { return new ButtonActionPropertyChangeListener(this, a); } private static class ButtonActionPropertyChangeListener extends AbstractActionPropertyChangeListener { ButtonActionPropertyChangeListener(AbstractButton b, Action a) { super(b, a); } public void propertyChange(PropertyChangeEvent e) { String propertyName = e.getPropertyName(); AbstractButton button = (AbstractButton)getTarget(); if (button == null) { //WeakRef GC'ed in 1.2 Action action = (Action)e.getSource(); action.removePropertyChangeListener(this); } else { if (e.getPropertyName().equals("selected")) { Boolean selectedState = (Boolean) e.getNewValue(); button.setSelected(selectedState.booleanValue()); button.repaint(); }else if (e.getPropertyName().equals(Action.NAME)) { Boolean hide = (Boolean)button.getClientProperty("hideActionText"); if (hide == null || hide == Boolean.FALSE) { String text = (String) e.getNewValue(); button.setText(text); button.repaint(); } } else if (e.getPropertyName().equals(Action.SHORT_DESCRIPTION)) { String text = (String) e.getNewValue(); button.setToolTipText(text); } else if (propertyName.equals("enabled")) { Boolean enabledState = (Boolean) e.getNewValue(); button.setEnabled(enabledState.booleanValue()); button.repaint(); } else if (e.getPropertyName().equals(Action.SMALL_ICON)) { Icon icon = (Icon) e.getNewValue(); button.setIcon(icon); button.invalidate(); button.repaint(); } else if (e.getPropertyName().equals(Action.MNEMONIC_KEY)) { Integer mn = (Integer) e.getNewValue(); button.setMnemonic(mn.intValue()); button.invalidate(); button.repaint(); } else if (e.getPropertyName().equals(Action.ACTION_COMMAND_KEY)) { button.setActionCommand((String)e.getNewValue()); } } } } } --- NEW FILE: WWEAbstractAction.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe; import javax.swing.AbstractAction; /** * Class provides a wrapper around the inherited from <code>AbstractAction</code> * class in JDK1.4. This has been doen as a work around for the BugId: 4133141 * Please see * {@link http://developer.java.sun.com/developer/bugParade/bugs/4133141.html}. * * This class should or a wrapped version of this class should only be used * whenever we need to use a WWEToggleButton * * @author Faruk M Khan * @version 1.0 25 Aug 2003 */ public abstract class WWEAbstractAction extends AbstractAction { /** * Specifies whether action is enabled; the default is true. */ protected boolean selected = true; /** * Returns true if the action is selected. * * @return true if the action is selected, false otherwise */ public boolean isSelected() { return selected; } /** * Selectes or deselects the action. * * @param newValue * true to enable the action, false to disable it */ public void setSelected(boolean newValue) { boolean oldValue = this.selected; if (oldValue != newValue) { this.selected = newValue; firePropertyChange( "selected", Boolean.valueOf(oldValue), Boolean.valueOf(newValue)); } } } --- NEW FILE: WWEConstants.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe; import javax.swing.text.html.HTML; /** * Constants used by WWEComponent. * * This constants are used to while creating the FontPickers and FontDialog * * <b>Note: I am not user whether this should be public or not. We need to * think. In case we need this as public we could merge WWEActionNameConstants * and this one</b> * * @author Faruk M Khan * @version 1.0 24 Aug 2003 */ public interface WWEConstants { static final String[] FONT_SIZES = new String[] { " ", "8", "10", "12", "14", "18", "24", "36" }; /* * The below 2 constants should have equal number of correctly mapped * elements */ static final String[] STYLE_NAMES = { "Paragraph", "Heading 1", "Heading 2", "Heading 3", "Heading 4", "Heading 5", "Heading 6", "BlockQuote", "Center", "Cite", "Code", "Pre" }; static final HTML.Tag[] STYLE_TAGS = { HTML.Tag.P, HTML.Tag.H1, HTML.Tag.H2, HTML.Tag.H3, HTML.Tag.H4, HTML.Tag.H5, HTML.Tag.H6, HTML.Tag.BLOCKQUOTE, HTML.Tag.CENTER, HTML.Tag.CITE, HTML.Tag.CODE, HTML.Tag.PRE }; static final String CFONTSTYLE = "char-font-style"; } --- NEW FILE: WWEComponent.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: [...3087 lines suppressed...] pous.close(); sw.close(); pous = null; WWEDebugInfoDialog dlg = new WWEDebugInfoDialog( m_parent, sw.toString(), "WWEHTMLDocument DOM Dump (AbstractDocument dump method)"); dlg.show(); } catch (Exception ex) { System.err.println("Failed to show the Dom Dump source"); } } public void update() { } } /*----------------Debug Actions end-------------------------------------------------------------------*/ } --- NEW FILE: image-delayed.gif --- (This appears to be a binary file; contents omitted.) --- NEW FILE: WWEHTMLEditorKit.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: [...2196 lines suppressed...] && currentOffset <= currentElement.getEndOffset()) { activateLink((String) href, doc, editor, currentOffset); return; } } else if (name.equals(HTML.Tag.OBJECT.toString())) { Object obj = getAttrValue(attr, HTML.Attribute.CLASSID); if (obj != null) { if (currentOffset >= currentElement.getStartOffset() && currentOffset <= currentElement.getEndOffset()) { doObjectAction(editor, currentElement); return; } } } } } } } --- NEW FILE: WWEHTML.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe; import java.util.Hashtable; import javax.swing.text.StyleConstants; import javax.swing.text.html.HTML; /** * A wrapper class for HTML Tags. * * @author Anuj Jain * @version 1.0 29 August 2003 * */ public class WWEHTML extends HTML { static Hashtable unknownTagHash = new Hashtable(); /** Maps from StyleConstant key to HTML.Tag. */ private static final Hashtable scMapping = new Hashtable(8); public static final UnknownTag ABBR = new UnknownTag("abbr"); public static final UnknownTag ACRONYM = new UnknownTag("acronym"); public static final UnknownTag BDO = new UnknownTag("bdo"); public static final UnknownTag BUTTON = new UnknownTag("button"); public static final UnknownTag COL = new UnknownTag("col"); public static final UnknownTag COLGROUP = new UnknownTag("colgroup"); public static final UnknownTag DEL = new UnknownTag("del"); public static final UnknownTag FIELDSET = new UnknownTag("fieldset"); public static final UnknownTag FRAMESET = new UnknownTag("frameset"); public static final UnknownTag FRAME = new UnknownTag("frame"); public static final UnknownTag IFRAME = new UnknownTag("iframe"); public static final UnknownTag INS = new UnknownTag("ins"); public static final UnknownTag LABEL = new UnknownTag("label"); public static final UnknownTag LEGEND = new UnknownTag("legend"); public static final UnknownTag NOFRAMES = new UnknownTag("noframes"); public static final UnknownTag NOSCRIPT = new UnknownTag("noscript"); public static final UnknownTag OBJECT = new UnknownTag("object"); public static final UnknownTag OPTGROUP = new UnknownTag("optgroup"); public static final UnknownTag Q = new UnknownTag("q"); public static final UnknownTag S = new UnknownTag("s"); public static final UnknownTag SPAN = new UnknownTag("span"); public static final UnknownTag THEAD = new UnknownTag("thead"); public static final UnknownTag TBODY = new UnknownTag("tbody"); public static final UnknownTag TFOOT = new UnknownTag("tfoot"); public static final UnknownTag unknownTags[] = { ABBR, ACRONYM, BDO, BUTTON, COL, COLGROUP, DEL, FIELDSET, FRAMESET, FRAME, IFRAME, INS, LABEL, LEGEND, NOFRAMES, NOSCRIPT, OBJECT, OPTGROUP, Q, S, SPAN, THEAD, TBODY, TFOOT }; public static UnknownTag getUnknownTag(String tagName) { Object t = unknownTagHash.get(tagName); return (t == null ? new UnknownTag(tagName) : (UnknownTag) t); } static { for (int i = 0; i < unknownTags.length; i++) { unknownTagHash.put(unknownTags[i].toString(), unknownTags[i]); } scMapping.put(StyleConstants.Bold, HTML.Tag.B); scMapping.put(StyleConstants.Italic, HTML.Tag.I); scMapping.put(StyleConstants.Underline, HTML.Tag.U); scMapping.put(StyleConstants.StrikeThrough, HTML.Tag.STRIKE); scMapping.put(StyleConstants.Superscript, HTML.Tag.SUP); scMapping.put(StyleConstants.Subscript, HTML.Tag.SUB); scMapping.put(StyleConstants.FontFamily, HTML.Tag.FONT); scMapping.put(StyleConstants.FontSize, HTML.Tag.FONT); } /** * Returns the HTML <code>Tag</code> associated with the <code>StyleConstants</code> * key <code>sc</code>. If no matching <code>Tag</code> is found, * returns <code>null</code>. * * @param sc * the <code>StyleConstants</code> key * @return tag which corresponds to <code>sc</code>, or <code>null</code> * if not found */ static Tag getTagForStyleConstantsKey(StyleConstants sc) { return (Tag) scMapping.get(sc); } } --- NEW FILE: WWEEditorPane.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: [...2240 lines suppressed...] return prevCell; } //End - Amit ahuja // --- variables --------------------------------------- /** * Stream currently loading asynchronously (potentially cancelable). Access * to this variable should be synchronized. */ private WWEPageStream loading; private WWEPageLoadProperties m_pageLoadProperties; private EditorKit kit; } --- NEW FILE: WWEFontFamilyPicker.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe; import java.awt.Dimension; import javax.swing.JComboBox; import javax.swing.text.AttributeSet; import javax.swing.text.MutableAttributeSet; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import com.montarasoftware.wwe.callback.WWECallbackRoutine; /** * Class provides a FontFamilyPicker. * * @author Faruk M Khan * @version 1.0 17 August 2003 */ class WWEFontFamilyPicker extends JComboBox implements WWECallbackRoutine { protected boolean m_succeeded = false; public WWEFontFamilyPicker(String[] names) { super(names); setMaximumSize(new Dimension(200, 23)); setEditable(false); } /** * set the value of this combo box * * @param a * the set of attributes possibly having a font size attribute * this pick list could display * @return true, if the set of attributes had a font size attribute, false * if not */ public void setAttributes(AttributeSet a) { m_succeeded = true; String name = StyleConstants.getFontFamily(a); setSelectedItem(name); m_succeeded = false; } /** * get the value of this <code>WWECallbackRoutine</code> * * @return the value selected from this component */ public AttributeSet getAttributes() { String fontName; fontName = getSelectedItem().toString(); MutableAttributeSet attr = new SimpleAttributeSet(); StyleConstants.setFontFamily(attr, fontName); return attr; } public boolean succeeded() { return m_succeeded; } } --- NEW FILE: WWEOptionListModel.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe; import java.io.Serializable; import java.util.BitSet; import javax.swing.DefaultListModel; import javax.swing.ListSelectionModel; import javax.swing.event.EventListenerList; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; /** * This class extends DefaultListModel, and also implements * the ListSelectionModel interface, allowing for it to store state * relevant to a SELECT form element which is implemented as a List. * If SELECT has a size attribute whose value is greater than 1, * or if allows multiple selection then a JList is used to * represent it and the WWEOptionListModel is used as its model. * It also stores the initial state of the JList, to ensure an * accurate reset, if the user requests a reset of the form. * @author Sunita Mani @version 1.10 01/23/03 */ public class WWEOptionListModel extends DefaultListModel implements ListSelectionModel, Serializable { private static final int MIN = -1; private static final int MAX = Integer.MAX_VALUE; private int selectionMode = SINGLE_SELECTION; private int minIndex = MAX; private int maxIndex = MIN; private int anchorIndex = -1; private int leadIndex = -1; private int firstChangedIndex = MAX; private int lastChangedIndex = MIN; private boolean isAdjusting = false; private BitSet value = new BitSet(32); private BitSet initialValue = new BitSet(32); protected EventListenerList listenerList = new EventListenerList(); protected boolean leadAnchorNotificationEnabled = true; public int getMinSelectionIndex() { return isSelectionEmpty() ? -1 : minIndex; } public int getMaxSelectionIndex() { return maxIndex; } public boolean getValueIsAdjusting() { return isAdjusting; } public int getSelectionMode() { return selectionMode; } public void setSelectionMode(int selectionMode) { switch (selectionMode) { case SINGLE_SELECTION: case SINGLE_INTERVAL_SELECTION: case MULTIPLE_INTERVAL_SELECTION: this.selectionMode = selectionMode; break; default: throw new IllegalArgumentException("invalid selectionMode"); } } public boolean isSelectedIndex(int index) { return ((index < minIndex) || (index > maxIndex)) ? false : value.get(index); } public boolean isSelectionEmpty() { return (minIndex > maxIndex); } public void addListSelectionListener(ListSelectionListener l) { listenerList.add(ListSelectionListener.class, l); } public void removeListSelectionListener(ListSelectionListener l) { listenerList.remove(ListSelectionListener.class, l); } /** * Returns an array of all the <code>ListSelectionListener</code>s added * to this WWEOptionListModel with addListSelectionListener(). * * @return all of the <code>ListSelectionListener</code>s added or an empty * array if no listeners have been added * @since 1.4 */ public ListSelectionListener[] getListSelectionListeners() { return (ListSelectionListener[])listenerList.getListeners( ListSelectionListener.class); } /** * Notify listeners that we are beginning or ending a * series of value changes */ protected void fireValueChanged(boolean isAdjusting) { fireValueChanged(getMinSelectionIndex(), getMaxSelectionIndex(), isAdjusting); } /** * Notify ListSelectionListeners that the value of the selection, * in the closed interval firstIndex,lastIndex, has changed. */ protected void fireValueChanged(int firstIndex, int lastIndex) { fireValueChanged(firstIndex, lastIndex, getValueIsAdjusting()); } /** * @param firstIndex The first index in the interval. * @param index1 The last index in the interval. * @param isAdjusting True if this is the final change in a series of them. * @see EventListenerList */ protected void fireValueChanged(int firstIndex, int lastIndex, boolean isAdjusting) { Object[] listeners = listenerList.getListenerList(); ListSelectionEvent e = null; for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ListSelectionListener.class) { if (e == null) { e = new ListSelectionEvent(this, firstIndex, lastIndex, isAdjusting); } ((ListSelectionListener)listeners[i+1]).valueChanged(e); } } } private void fireValueChanged() { if (lastChangedIndex == MIN) { return; } /* Change the values before sending the event to the * listeners in case the event causes a listener to make * another change to the selection. */ int oldFirstChangedIndex = firstChangedIndex; int oldLastChangedIndex = lastChangedIndex; firstChangedIndex = MAX; lastChangedIndex = MIN; fireValueChanged(oldFirstChangedIndex, oldLastChangedIndex); } // Update first and last change indices private void markAsDirty(int r) { firstChangedIndex = Math.min(firstChangedIndex, r); lastChangedIndex = Math.max(lastChangedIndex, r); } // Set the state at this index and update all relevant state. private void set(int r) { if (value.get(r)) { return; } value.set(r); WWEOption option = (WWEOption)get(r); option.setSelection(true); markAsDirty(r); // Update minimum and maximum indices minIndex = Math.min(minIndex, r); maxIndex = Math.max(maxIndex, r); } // Clear the state at this index and update all relevant state. private void clear(int r) { if (!value.get(r)) { return; } value.clear(r); WWEOption option = (WWEOption)get(r); option.setSelection(false); markAsDirty(r); // Update minimum and maximum indices /* If (r > minIndex) the minimum has not changed. The case (r < minIndex) is not possible because r'th value was set. We only need to check for the case when lowest entry has been cleared, and in this case we need to search for the first value set above it. */ if (r == minIndex) { for(minIndex = minIndex + 1; minIndex <= maxIndex; minIndex++) { if (value.get(minIndex)) { break; } } } /* If (r < maxIndex) the maximum has not changed. The case (r > maxIndex) is not possible because r'th value was set. We only need to check for the case when highest entry has been cleared, and in this case we need to search for the first value set below it. */ if (r == maxIndex) { for(maxIndex = maxIndex - 1; minIndex <= maxIndex; maxIndex--) { if (value.get(maxIndex)) { break; } } } /* Performance note: This method is called from inside a loop in changeSelection() but we will only iterate in the loops above on the basis of one iteration per deselected cell - in total. Ie. the next time this method is called the work of the previous deselection will not be repeated. We also don't need to worry about the case when the min and max values are in their unassigned states. This cannot happen because this method's initial check ensures that the selection was not empty and therefore that the minIndex and maxIndex had 'real' values. If we have cleared the whole selection, set the minIndex and maxIndex to their cannonical values so that the next set command always works just by using Math.min and Math.max. */ if (isSelectionEmpty()) { minIndex = MAX; maxIndex = MIN; } } /** * Sets the value of the leadAnchorNotificationEnabled flag. * @see #isLeadAnchorNotificationEnabled() */ public void setLeadAnchorNotificationEnabled(boolean flag) { leadAnchorNotificationEnabled = flag; } /** * Returns the value of the leadAnchorNotificationEnabled flag. * When leadAnchorNotificationEnabled is true the model * generates notification events with bounds that cover all the changes to * the selection plus the changes to the lead and anchor indices. * Setting the flag to false causes a norrowing of the event's bounds to * include only the elements that have been selected or deselected since * the last change. Either way, the model continues to maintain the lead * and anchor variables internally. The default is true. * @return the value of the leadAnchorNotificationEnabled flag * @see #setLeadAnchorNotificationEnabled(boolean) */ public boolean isLeadAnchorNotificationEnabled() { return leadAnchorNotificationEnabled; } private void updateLeadAnchorIndices(int anchorIndex, int leadIndex) { if (leadAnchorNotificationEnabled) { if (this.anchorIndex != anchorIndex) { if (this.anchorIndex != -1) { // The unassigned state. markAsDirty(this.anchorIndex); } markAsDirty(anchorIndex); } if (this.leadIndex != leadIndex) { if (this.leadIndex != -1) { // The unassigned state. markAsDirty(this.leadIndex); } markAsDirty(leadIndex); } } this.anchorIndex = anchorIndex; this.leadIndex = leadIndex; } private boolean contains(int a, int b, int i) { return (i >= a) && (i <= b); } private void changeSelection(int clearMin, int clearMax, int setMin, int setMax, boolean clearFirst) { for(int i = Math.min(setMin, clearMin); i <= Math.max(setMax, clearMax); i++) { boolean shouldClear = contains(clearMin, clearMax, i); boolean shouldSet = contains(setMin, setMax, i); if (shouldSet && shouldClear) { if (clearFirst) { shouldClear = false; } else { shouldSet = false; } } if (shouldSet) { set(i); } if (shouldClear) { clear(i); } } fireValueChanged(); } /* Change the selection with the effect of first clearing the values * in the inclusive range [clearMin, clearMax] then setting the values * in the inclusive range [setMin, setMax]. Do this in one pass so * that no values are cleared if they would later be set. */ private void changeSelection(int clearMin, int clearMax, int setMin, int setMax) { changeSelection(clearMin, clearMax, setMin, setMax, true); } public void clearSelection() { removeSelectionInterval(minIndex, maxIndex); } public void setSelectionInterval(int index0, int index1) { if (index0 == -1 || index1 == -1) { return; } if (getSelectionMode() == SINGLE_SELECTION) { index0 = index1; } updateLeadAnchorIndices(index0, index1); int clearMin = minIndex; int clearMax = maxIndex; int setMin = Math.min(index0, index1); int setMax = Math.max(index0, index1); changeSelection(clearMin, clearMax, setMin, setMax); } public void addSelectionInterval(int index0, int index1) { if (index0 == -1 || index1 == -1) { return; } if (getSelectionMode() != MULTIPLE_INTERVAL_SELECTION) { setSelectionInterval(index0, index1); return; } updateLeadAnchorIndices(index0, index1); int clearMin = MAX; int clearMax = MIN; int setMin = Math.min(index0, index1); int setMax = Math.max(index0, index1); changeSelection(clearMin, clearMax, setMin, setMax); } public void removeSelectionInterval(int index0, int index1) { if (index0 == -1 || index1 == -1) { return; } updateLeadAnchorIndices(index0, index1); int clearMin = Math.min(index0, index1); int clearMax = Math.max(index0, index1); int setMin = MAX; int setMax = MIN; changeSelection(clearMin, clearMax, setMin, setMax); } private void setState(int index, boolean state) { if (state) { set(index); } else { clear(index); } } /** * Insert length indices beginning before/after index. If the value * at index is itself selected, set all of the newly inserted * items, otherwise leave them unselected. This method is typically * called to sync the selection model with a corresponding change * in the data model. */ public void insertIndexInterval(int index, int length, boolean before) { /* The first new index will appear at insMinIndex and the last * one will appear at insMaxIndex */ int insMinIndex = (before) ? index : index + 1; int insMaxIndex = (insMinIndex + length) - 1; /* Right shift the entire bitset by length, beginning with * index-1 if before is true, index+1 if it's false (i.e. with * insMinIndex). */ for(int i = maxIndex; i >= insMinIndex; i--) { setState(i + length, value.get(i)); } /* Initialize the newly inserted indices. */ boolean setInsertedValues = value.get(index); for(int i = insMinIndex; i <= insMaxIndex; i++) { setState(i, setInsertedValues); } } /** * Remove the indices in the interval index0,index1 (inclusive) from * the selection model. This is typically called to sync the selection * model width a corresponding change in the data model. Note * that (as always) index0 can be greater than index1. */ public void removeIndexInterval(int index0, int index1) { int rmMinIndex = Math.min(index0, index1); int rmMaxIndex = Math.max(index0, index1); int gapLength = (rmMaxIndex - rmMinIndex) + 1; /* Shift the entire bitset to the left to close the index0, index1 * gap. */ for(int i = rmMinIndex; i <= maxIndex; i++) { setState(i, value.get(i + gapLength)); } } public void setValueIsAdjusting(boolean isAdjusting) { if (isAdjusting != this.isAdjusting) { this.isAdjusting = isAdjusting; this.fireValueChanged(isAdjusting); } } public String toString() { String s = ((getValueIsAdjusting()) ? "~" : "=") + value.toString(); return getClass().getName() + " " + Integer.toString(hashCode()) + " " + s; } /** * Returns a clone of the receiver with the same selection. * <code>listenerLists</code> are not duplicated. * * @return a clone of the receiver * @exception CloneNotSupportedException if the receiver does not * both (a) implement the <code>Cloneable</code> interface * and (b) define a <code>clone</code> method */ public Object clone() throws CloneNotSupportedException { WWEOptionListModel clone = (WWEOptionListModel)super.clone(); clone.value = (BitSet)value.clone(); clone.listenerList = new EventListenerList(); return clone; } public int getAnchorSelectionIndex() { return anchorIndex; } public int getLeadSelectionIndex() { return leadIndex; } /** * Set the anchor selection index, leaving all selection values unchanged. * * @see #getAnchorSelectionIndex * @see #setLeadSelectionIndex */ public void setAnchorSelectionIndex(int anchorIndex) { this.anchorIndex = anchorIndex; } /** * Set the lead selection index, ensuring that values between the * anchor and the new lead are either all selected or all deselected. * If the value at the anchor index is selected, first clear all the * values in the range [anchor, oldLeadIndex], then select all the values * values in the range [anchor, newLeadIndex], where oldLeadIndex is the old * leadIndex and newLeadIndex is the new one. * <p> * If the value at the anchor index is not selected, do the same thing in reverse, * selecting values in the old range and deslecting values in the new one. * <p> * Generate a single event for this change and notify all listeners. * For the purposes of generating minimal bounds in this event, do the * operation in a single pass; that way the first and last index inside the * ListSelectionEvent that is broadcast will refer to cells that actually * changed value because of this method. If, instead, this operation were * done in two steps the effect on the selection state would be the same * but two events would be generated and the bounds around the changed values * would be wider, including cells that had been first cleared and only * to later be set. * <p> * This method can be used in the mouseDragged() method of a UI class * to extend a selection. * * @see #getLeadSelectionIndex * @see #setAnchorSelectionIndex */ public void setLeadSelectionIndex(int leadIndex) { int anchorIndex = this.anchorIndex; if (getSelectionMode() == SINGLE_SELECTION) { anchorIndex = leadIndex; } int oldMin = Math.min(this.anchorIndex, this.leadIndex);; int oldMax = Math.max(this.anchorIndex, this.leadIndex);; int newMin = Math.min(anchorIndex, leadIndex); int newMax = Math.max(anchorIndex, leadIndex); if (value.get(this.anchorIndex)) { changeSelection(oldMin, oldMax, newMin, newMax); } else { changeSelection(newMin, newMax, oldMin, oldMax, false); } this.anchorIndex = anchorIndex; this.leadIndex = leadIndex; } /** * This method is responsible for storing the state * of the initial selection. If the selectionMode * is the default, i.e allowing only for SINGLE_SELECTION, * then the very last OPTION that has the selected * attribute set wins. */ public void setInitialSelection(int i) { if (initialValue.get(i)) { return; } if (selectionMode == SINGLE_SELECTION) { // reset to empty initialValue.and(new BitSet()); } initialValue.set(i); } /** * Fetches the BitSet that represents the initial * set of selected items in the list. */ public BitSet get... [truncated message content] |
Update of /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/parser In directory sc8-pr-cvs1:/tmp/cvs-serv15363/src/com/montarasoftware/wwe/parser Added Files: WWEContentModel.java WWEElement.java html32.bdtd WWEAttributeList.java WWETagStack.java WWEDTDConstants.java WWEEntity.java WWEContentModelState.java WWEParserDelegator.java WWEDTD.java WWEParser.java WWETagElement.java html401.bdtd WWEDocumentParser.java Log Message: initial load of HTML editor pane and kit --- NEW FILE: WWEContentModel.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.parser; import java.io.Serializable; import java.util.Vector; /** * A representation of a content model. A content model is * basically a restricted BNF expression. It is restricted in * the sense that it must be deterministic. This means that you * don't have to represent it as a finite state automata.<p> * See Annex H on page 556 of the SGML handbook for more information. * * @author Arthur van Hoff * @version 1.8,12/03/01 * */ public final class WWEContentModel implements Serializable { /** * Type. Either '*', '?', '+', ',', '|', '&'. */ public int type; /** * The content. Either an WWEElement or a WWEContentModel. */ public Object content; /** * The next content model (in a ',', '|' or '&' expression). */ public WWEContentModel next; public WWEContentModel() { } /** * Create a content model for an element. */ public WWEContentModel(WWEElement content) { this(0, content, null); } /** * Create a content model of a particular type. */ public WWEContentModel(int type, WWEContentModel content) { this(type, content, null); } /** * Create a content model of a particular type. */ public WWEContentModel(int type, Object content, WWEContentModel next) { this.type = type; this.content = content; this.next = next; } /** * Return true if the content model could * match an empty input stream. */ public boolean empty() { switch (type) { case '*': case '?': return true; case '+': case '|': for (WWEContentModel m = (WWEContentModel) content; m != null; m = m.next) { if (m.empty()) { return true; } } return false; case ',': case '&': for (WWEContentModel m = (WWEContentModel) content; m != null; m = m.next) { if (!m.empty()) { return false; } } return true; default: return false; } } /** * Update elemVec with the list of elements that are * part of the this contentModel. */ public void getElements(Vector elemVec) { switch (type) { case '*': case '?': case '+': ((WWEContentModel) content).getElements(elemVec); break; case ',': case '|': case '&': for (WWEContentModel m = (WWEContentModel) content; m != null; m = m.next) { m.getElements(elemVec); } break; default: elemVec.addElement(content); } } private boolean valSet[]; private boolean val[]; // A cache used by first(). This cache was found to speed parsing // by about 10% (based on measurements of the 4-12 code base after // buffering was fixed). /** * Return true if the token could potentially be the * first token in the input stream. */ public boolean first(Object token) { switch (type) { case '*': case '?': case '+': return ((WWEContentModel) content).first(token); case ',': for (WWEContentModel m = (WWEContentModel) content; m != null; m = m.next) { if (m.first(token)) { return true; } if (!m.empty()) { return false; } } return false; case '|': case '&': { WWEElement e = (WWEElement) token; if (valSet == null) { valSet = new boolean[WWEElement.maxIndex + 1]; val = new boolean[WWEElement.maxIndex + 1]; // All WWEElement instances are created before this ever executes } if (valSet[e.index]) { return val[e.index]; } for (WWEContentModel m = (WWEContentModel) content; m != null; m = m.next) { if (m.first(token)) { val[e.index] = true; break; } } valSet[e.index] = true; return val[e.index]; } default: return (content == token); // PENDING: refer to comment in WWEContentModelState /* if (content == token) { return true; } WWEElement e = (WWEElement)content; if (e.omitStart() && e.content != null) { return e.content.first(token); } return false; */ } } /** * Return the element that must be next. */ public WWEElement first() { switch (type) { case '&': case '|': case '*': case '?': return null; case '+': case ',': return ((WWEContentModel) content).first(); default: return (WWEElement) content; } } /** * Convert to a string. */ public String toString() { switch (type) { case '*': return content + "*"; case '?': return content + "?"; case '+': return content + "+"; case ',': case '|': case '&': char data[] = {' ', (char) type, ' '}; String str = ""; for (WWEContentModel m = (WWEContentModel) content; m != null; m = m.next) { str = str + m; if (m.next != null) { str += new String(data); } } return "(" + str + ")"; default: return content.toString(); } } } --- NEW FILE: WWEElement.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.parser; import java.io.Serializable; import java.util.BitSet; import java.util.Hashtable; /** * An element as described in a WWEDTD using the ELEMENT construct. * This is essentiall the description of a tag. It describes the * type, content model, attributes, attribute types etc. It is used * to correctly parse a document by the Parser. * * @see WWEDTD * @see WWEAttributeList * @version 1.7, 12/03/01 * @author Arthur van Hoff */ public final class WWEElement implements WWEDTDConstants, Serializable { public int index; public String name; public boolean oStart; public boolean oEnd; public BitSet inclusions; public BitSet exclusions; public int type = ANY; public WWEContentModel content; public WWEAttributeList atts; static int maxIndex = 0; /** * A field to store user data. Mostly used to store * style sheets. */ public Object data; WWEElement() { } /** * Create a new element. */ WWEElement(String name, int index) { this.name = name; this.index = index; maxIndex = Math.max(maxIndex, index); } /** * Get the name of the element. */ public String getName() { return name; } /** * Return true if the start tag can be omitted. */ public boolean omitStart() { return oStart; } /** * Return true if the end tag can be omitted. */ public boolean omitEnd() { return oEnd; } /** * Get type. */ public int getType() { return type; } /** * Get content model */ public WWEContentModel getContent() { return content; } /** * Get the attributes. */ public WWEAttributeList getAttributes() { return atts; } /** * Get index. */ public int getIndex() { return index; } /** * Check if empty */ public boolean isEmpty() { return type == EMPTY; } /** * Convert to a string. */ public String toString() { return name; } /** * Get an attribute by name. */ public WWEAttributeList getAttribute(String name) { for (WWEAttributeList a = atts; a != null; a = a.next) { if (a.name.equals(name)) { return a; } } return null; } /** * Get an attribute by value. */ public WWEAttributeList getAttributeByValue(String name) { for (WWEAttributeList a = atts; a != null; a = a.next) { if ((a.values != null) && a.values.contains(name)) { return a; } } return null; } static Hashtable contentTypes = new Hashtable(); static { contentTypes.put("CDATA", new Integer(CDATA)); contentTypes.put("RCDATA", new Integer(RCDATA)); contentTypes.put("EMPTY", new Integer(EMPTY)); contentTypes.put("ANY", new Integer(ANY)); } public static int name2type(String nm) { Integer val = (Integer) contentTypes.get(nm); return (val != null) ? val.intValue() : 0; } } --- NEW FILE: html32.bdtd --- (This appears to be a binary file; contents omitted.) --- NEW FILE: WWEAttributeList.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.parser; import java.io.Serializable; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; /** * This class defines the attributes of an SGML element * as described in a DTD using the ATTLIST construct. * An WWEAttributeList can be obtained from the WWEElement * class using the getAttributes() method. * <p> * It is actually an element in a linked list. Use the * getNext() method repeatedly to enumerate all the attributes * of an element. * * @see WWEElement * @author Arthur Van Hoff * @version 1.8 12/03/01 * */ public final class WWEAttributeList implements WWEDTDConstants, Serializable { public String name; public int type; public Vector values; public int modifier; public String value; public WWEAttributeList next; WWEAttributeList() { } /** * Create an attribute list element. */ public WWEAttributeList(String name) { this.name = name; } /** * Create an attribute list element. */ public WWEAttributeList(String name, int type, int modifier, String value, Vector values, WWEAttributeList next) { this.name = name; this.type = type; this.modifier = modifier; this.value = value; this.values = values; this.next = next; } /** * @return attribute name */ public String getName() { return name; } /** * @return attribute type * @see WWEDTDConstants */ public int getType() { return type; } /** * @return attribute modifier * @see WWEDTDConstants */ public int getModifier() { return modifier; } /** * @return possible attribute values */ public Enumeration getValues() { return (values != null) ? values.elements() : null; } /** * @return default attribute value */ public String getValue() { return value; } /** * @return the next attribute in the list */ public WWEAttributeList getNext() { return next; } /** * @return string representation */ public String toString() { return name; } /** * Create a hashtable of attribute types. */ static Hashtable attributeTypes = new Hashtable(); static void defineAttributeType(String nm, int val) { Integer num = new Integer(val); attributeTypes.put(nm, num); attributeTypes.put(num, nm); } static { defineAttributeType("CDATA", CDATA); defineAttributeType("ENTITY", ENTITY); defineAttributeType("ENTITIES", ENTITIES); defineAttributeType("ID", ID); defineAttributeType("IDREF", IDREF); defineAttributeType("IDREFS", IDREFS); defineAttributeType("NAME", NAME); defineAttributeType("NAMES", NAMES); defineAttributeType("NMTOKEN", NMTOKEN); defineAttributeType("NMTOKENS", NMTOKENS); defineAttributeType("NOTATION", NOTATION); defineAttributeType("NUMBER", NUMBER); defineAttributeType("NUMBERS", NUMBERS); defineAttributeType("NUTOKEN", NUTOKEN); defineAttributeType("NUTOKENS", NUTOKENS); attributeTypes.put("fixed", new Integer(FIXED)); attributeTypes.put("required", new Integer(REQUIRED)); attributeTypes.put("current", new Integer(CURRENT)); attributeTypes.put("conref", new Integer(CONREF)); attributeTypes.put("implied", new Integer(IMPLIED)); } public static int name2type(String nm) { Integer i = (Integer) attributeTypes.get(nm); return (i == null) ? CDATA : i.intValue(); } public static String type2name(int tp) { return (String) attributeTypes.get(new Integer(tp)); } } --- NEW FILE: WWETagStack.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.parser; import java.io.PrintWriter; import java.util.BitSet; import java.util.Vector; /** * A stack of tags. Used while parsing an HTML document. * It, together with the ContentModelStates, defines the * complete state of the parser while reading a document. * When a start tag is encountered an element is pushed onto * the stack, when an end tag is enountered an element is popped * of the stack. * * @see WWEParser * @see WWEDTD * @see WWEContentModelState * @version 1.8, 12/03/01 * @author Arthur van Hoff */ final class WWETagStack implements WWEDTDConstants { WWETagElement tag; WWEElement elem; WWEContentModelState state; WWETagStack next; BitSet inclusions; BitSet exclusions; boolean net; boolean pre; /** * Construct a stack element. */ WWETagStack(WWETagElement tag, WWETagStack next) { this.tag = tag; this.elem = tag.getElement(); this.next = next; WWEElement elem = tag.getElement(); if (elem.getContent() != null) { this.state = new WWEContentModelState(elem.getContent()); } if (next != null) { inclusions = next.inclusions; exclusions = next.exclusions; pre = next.pre; } if (tag.isPreformatted()) { pre = true; } if (elem.inclusions != null) { if (inclusions != null) { inclusions = (BitSet) inclusions.clone(); inclusions.or(elem.inclusions); } else { inclusions = elem.inclusions; } } if (elem.exclusions != null) { if (exclusions != null) { exclusions = (BitSet) exclusions.clone(); exclusions.or(elem.exclusions); } else { exclusions = elem.exclusions; } } } /** * Return the element that must come next in the * input stream. */ public WWEElement first() { return (state != null) ? state.first() : null; } /** * Return the ContentModel that must be satisfied by * what comes next in the input stream. */ public WWEContentModel contentModel() { if (state == null) { return null; } else { return state.getModel(); } } /** * Return true if the element that is contained at * the index specified by the parameter is part of * the exclusions specified in the DTD for the element * currently on the TagStack. */ boolean excluded(int elemIndex) { return (exclusions != null) && exclusions.get(elem.getIndex()); } /** * Update the Vector elemVec with all the elements that * are part of the inclusions listed in DTD for the element * currently on the TagStack. */ boolean included(Vector elemVec, WWEDTD dtd) { for (int i = 0; i < inclusions.size(); i++) { if (inclusions.get(i)) { elemVec.addElement(dtd.getElement(i)); System.out.println("Element add thru' inclusions: " + dtd.getElement(i).getName()); } } return (!elemVec.isEmpty()); } /** * Advance the state by reducing the given element. * Returns false if the element is not legal and the * state is not advanced. */ boolean advance(WWEElement elem) { if ((exclusions != null) && exclusions.get(elem.getIndex())) { return false; } if (state != null) { WWEContentModelState newState = state.advance(elem); if (newState != null) { state = newState; return true; } } else if (this.elem.getType() == ANY) { return true; } return (inclusions != null) && inclusions.get(elem.getIndex()); } /** * Return true if the current state can be terminated. */ boolean terminate() { return (state == null) || state.terminate(); } /** * Convert to a string. */ public String toString() { return (next == null) ? "<" + tag.getElement().getName() + ">" : next + " <" + tag.getElement().getName() + ">"; } } class NPrintWriter extends PrintWriter { private int numLines = 5; private int numPrinted = 0; public NPrintWriter(int numberOfLines) { super(System.out); numLines = numberOfLines; } public void println(char[] array) { if (numPrinted >= numLines) { return; } char[] partialArray = null; for (int i = 0; i < array.length; i++) { if (array[i] == '\n') { numPrinted++; } if (numPrinted == numLines) { System.arraycopy(array, 0, partialArray, 0, i); } } if (partialArray != null) { super.print(partialArray); } if (numPrinted == numLines) { return; } super.println(array); numPrinted++; } } --- NEW FILE: WWEDTDConstants.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.parser; /** * SGML constants used in a WWEDTD. The names of the * constants correspond the the equivalent SGML constructs * as described in "The SGML Handbook" by Charles F. Goldfarb. * * @see WWEDTD * @see WWEElement * @version 1.8, 12/03/01 * @author Arthur van Hoff */ public interface WWEDTDConstants { // Attribute value types int CDATA = 1; int ENTITY = 2; int ENTITIES = 3; int ID = 4; int IDREF = 5; int IDREFS = 6; int NAME = 7; int NAMES = 8; int NMTOKEN = 9; int NMTOKENS = 10; int NOTATION = 11; int NUMBER = 12; int NUMBERS = 13; int NUTOKEN = 14; int NUTOKENS = 15; // Content model types int RCDATA = 16; int EMPTY = 17; int MODEL = 18; int ANY = 19; // Attribute value modifiers int FIXED = 1; int REQUIRED = 2; int CURRENT = 3; int CONREF = 4; int IMPLIED = 5; // Entity types int PUBLIC = 10; int SDATA = 11; int PI = 12; int STARTTAG = 13; int ENDTAG = 14; int MS = 15; int MD = 16; int SYSTEM = 17; int GENERAL = 1 << 16; int DEFAULT = 1 << 17; int PARAMETER = 1 << 18; } --- NEW FILE: WWEEntity.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.parser; import java.util.Hashtable; /** * An entity is described in a DTD using the ENTITY construct. * It defines the type and value of the the entity. * * @see WWEDTD * @version 1.8, 12/03/01 * @author Arthur van Hoff */ public final class WWEEntity implements WWEDTDConstants { public String name; public int type; public char data[]; /** * Creates an entity. * @param name the name of the entity * @param type the type of the entity * @param data the char array of data */ public WWEEntity(String name, int type, char data[]) { this.name = name; this.type = type; this.data = data; } /** * Gets the name of the entity. * @return the name of the entity, as a <code>String</code> */ public String getName() { return name; } /** * Gets the type of the entity. * @return the type of the entity */ public int getType() { return type & 0xFFFF; } /** * Returns <code>true</code> if it is a parameter entity. * @return <code>true</code> if it is a parameter entity */ public boolean isParameter() { return (type & PARAMETER) != 0; } /** * Returns <code>true</code> if it is a general entity. * @return <code>true</code> if it is a general entity */ public boolean isGeneral() { return (type & GENERAL) != 0; } /** * Returns the <code>data</code>. * @return the <code>data</code> */ public char getData()[] { return data; } /** * Returns the data as a <code>String</code>. * @return the data as a <code>String</code> */ public String getString() { return new String(data, 0, data.length); } static Hashtable entityTypes = new Hashtable(); static { entityTypes.put("PUBLIC", new Integer(PUBLIC)); entityTypes.put("CDATA", new Integer(CDATA)); entityTypes.put("SDATA", new Integer(SDATA)); entityTypes.put("PI", new Integer(PI)); entityTypes.put("STARTTAG", new Integer(STARTTAG)); entityTypes.put("ENDTAG", new Integer(ENDTAG)); entityTypes.put("MS", new Integer(MS)); entityTypes.put("MD", new Integer(MD)); entityTypes.put("SYSTEM", new Integer(SYSTEM)); } /** * Converts <code>nm</code> string to the corresponding * entity type. If the string does not have a corresponding * entity type, returns the type corresponding to "CDATA". * Valid entity types are: "PUBLIC", "CDATA", "SDATA", "PI", * "STARTTAG", "ENDTAG", "MS", "MD", "SYSTEM". * * @param nm the string to be converted * @return the corresponding entity type, or the type corresponding * to "CDATA", if none exists */ public static int name2type(String nm) { Integer i = (Integer) entityTypes.get(nm); return (i == null) ? CDATA : i.intValue(); } } --- NEW FILE: WWEContentModelState.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.parser; /** * A content model state. This is basically a list of pointers to * the BNF expression representing the model (the ContentModel). * Each element in a DTD has a content model which describes the * elements that may occur inside, and the order in which they can * occur. * <p> * Each time a token is reduced a new state is created. * <p> * See Annex H on page 556 of the SGML handbook for more information. * * @see Parser * @see DTD * @see WWEElement * @see ContentModel * @author Arthur van Hoff * @version 1.9 12/03/01 */ class WWEContentModelState { WWEContentModel model; long value; WWEContentModelState next; /** * Create a content model state for a content model. */ public WWEContentModelState(WWEContentModel model) { this(model, null, 0); } /** * Create a content model state for a content model given the * remaining state that needs to be reduce. */ WWEContentModelState(Object content, WWEContentModelState next) { this(content, next, 0); } /** * Create a content model state for a content model given the * remaining state that needs to be reduce. */ WWEContentModelState(Object content, WWEContentModelState next, long value) { this.model = (WWEContentModel) content; this.next = next; this.value = value; } /** * Return the content model that is relevant to the current state. */ public WWEContentModel getModel() { WWEContentModel m = model; for (int i = 0; i < value; i++) { if (m.next != null) { m = m.next; } else { return null; } } return m; } /** * Check if the state can be terminated. That is there are no more * tokens required in the input stream. * @return true if the model can terminate without further input */ public boolean terminate() { switch (model.type) { case '+': if ((value == 0) && !(model).empty()) { return false; } case '*': case '?': return (next == null) || next.terminate(); case '|': for (WWEContentModel m = (WWEContentModel) model.content; m != null; m = m.next) { if (m.empty()) { return (next == null) || next.terminate(); } } return false; case '&': { WWEContentModel m = (WWEContentModel) model.content; for (int i = 0; m != null; i++, m = m.next) { if ((value & (1L << i)) == 0) { if (!m.empty()) { return false; } } } return (next == null) || next.terminate(); } case ',': { WWEContentModel m = (WWEContentModel) model.content; for (int i = 0; i < value; i++, m = m.next) ; for (; (m != null) && m.empty(); m = m.next) ; if (m != null) { return false; } return (next == null) || next.terminate(); } default: return false; } } /** * Check if the state can be terminated. That is there are no more * tokens required in the input stream. * @return the only possible element that can occur next */ public WWEElement first() { switch (model.type) { case '*': case '?': case '|': case '&': return null; case '+': return model.first(); case ',': { WWEContentModel m = (WWEContentModel) model.content; for (int i = 0; i < value; i++, m = m.next) ; return m.first(); } default: return model.first(); } } /** * Advance this state to a new state. An exception is thrown if the * token is illegal at this point in the content model. * @return next state after reducing a token */ public WWEContentModelState advance(Object token) { switch (model.type) { case '+': if (model.first(token)) { return new WWEContentModelState(model.content, new WWEContentModelState(model, next, value + 1)).advance(token); } if (value != 0) { if (next != null) { return next.advance(token); } else { return null; } } break; case '*': if (model.first(token)) { return new WWEContentModelState(model.content, this).advance(token); } if (next != null) { return next.advance(token); } else { return null; } case '?': if (model.first(token)) { return new WWEContentModelState(model.content, next).advance(token); } if (next != null) { return next.advance(token); } else { return null; } case '|': for (WWEContentModel m = (WWEContentModel) model.content; m != null; m = m.next) { if (m.first(token)) { return new WWEContentModelState(m, next).advance(token); } } break; case ',': { WWEContentModel m = (WWEContentModel) model.content; for (int i = 0; i < value; i++, m = m.next) ; if (m.first(token) || m.empty()) { if (m.next == null) { return new WWEContentModelState(m, next).advance(token); } else { return new WWEContentModelState(m, new WWEContentModelState(model, next, value + 1)).advance(token); } } break; } case '&': { WWEContentModel m = (WWEContentModel) model.content; boolean complete = true; for (int i = 0; m != null; i++, m = m.next) { if ((value & (1L << i)) == 0) { if (m.first(token)) { return new WWEContentModelState(m, new WWEContentModelState(model, next, value | (1L << i))).advance(token); } if (!m.empty()) { complete = false; } } } if (complete) { if (next != null) { return next.advance(token); } else { return null; } } break; } default: if (model.content == token) { if (next == null && (token instanceof WWEElement) && ((WWEElement) token).content != null) { return new WWEContentModelState(((WWEElement) token).content); } return next; } // PENDING: Currently we don't correctly deal with optional start // tags. This can most notably be seen with the 4.01 spec where // TBODY's start and end tags are optional. // Uncommenting this and the PENDING in WWEContentModel will // correctly skip the omit tags, but the delegate is not notified. // Some additional API needs to be added to track skipped tags, // and this can then be added back. /* if ((model.content instanceof WWEElement)) { WWEElement e = (WWEElement)model.content; if (e.omitStart() && e.content != null) { return new WWEContentModelState(e.content, next).advance( token); } } */ } // We used to throw this exception at this point. However, it // was determined that throwing this exception was more expensive // than returning null, and we could not justify to ourselves why // it was necessary to throw an exception, rather than simply // returning null. I'm leaving it in a commented out state so // that it can be easily restored if the situation ever arises. // // throw new IllegalArgumentException("invalid token: " + token); return null; } } --- NEW FILE: WWEParserDelegator.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.parser; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.Reader; import java.io.Serializable; import java.io.StringWriter; import com.montarasoftware.wwe.WWEHTMLEditorKit; import com.montarasoftware.wwe.debug.WWEDebug; import com.montarasoftware.wwe.util.WWEResourceLoader; public class WWEParserDelegator extends WWEHTMLEditorKit.Parser implements Serializable { private static WWEDTD m_dtd = null; public WWEParserDelegator() { if (m_dtd == null) { setDTD(); } } protected static void setDTD() { if (m_dtd == null) { synchronized (WWEParserDelegator.class) { if (m_dtd == null) { WWEDTD dtd = null; // We want to force the use of our dtd and not // allow it to be overridden // hence we can hard code! //String nm = "html32"; String nm = "html401"; try { dtd = WWEDTD.getDTD(nm); } catch (IOException e) { System.err.println("Failed to get the dtd " + nm); } dtd = createDTD(dtd, nm); m_dtd = dtd; } } } } protected static WWEDTD createDTD(WWEDTD dtd, String name) { InputStream in = null; boolean debug = true; try { String path = name + ".bdtd"; in = getResourceAsStream(path); if (in != null) { dtd.read(new DataInputStream(new BufferedInputStream(in))); dtd.putDTDHash(name, dtd); } } catch (Exception e) { System.err.println("Failed to create the dtd: " + e); } if(WWEDebug.PARSER_DELEGATOR){ if(dtd == null){ System.out.println("Returning a null dtd"); }else{ System.out.println("Returning a non-null dtd"); System.out.println("Entity No: " + dtd.entityHash.size() + " Entity hash: " + dtd.entityHash + "\n"); System.out.println("Elements No: " + dtd.elementHash.size() + " Element hash: " + dtd.elementHash + "\n"); } } return dtd; } public void parse(Reader r, StringWriter sw, WWEHTMLEditorKit.ParserCallback cb, boolean ignoreCharSet) throws IOException { new WWEDocumentParser(m_dtd).parse(r, sw, cb, ignoreCharSet); } /** * Fetch a resource relative to the ParserDelegator classfile. * If this is called on 1.2 the loading will occur under the * protection of a doPrivileged call to allow the ParserDelegator * to function when used in an applet. * * @param name the name of the resource, relative to the * ParserDelegator class. * @returns a stream representing the resource */ static InputStream getResourceAsStream(String name) { try { return WWEResourceLoader.getResourceAsStream(name, WWEParserDelegator.class); } catch (Throwable e) { return WWEParserDelegator.class.getResourceAsStream(name); } } private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException { s.defaultReadObject(); if (m_dtd == null) { setDTD(); } } } --- NEW FILE: WWEDTD.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.parser; import java.io.DataInputStream; import java.io.IOException; import java.util.BitSet; import java.util.Hashtable; import java.util.StringTokenizer; import java.util.Vector; /** * The representation of an SGML WWEDTD. WWEDTD describes a document * syntax and is used in parsing of HTML documents. It contains * a list of elements and their attributes as well as a list of * entities defined in the WWEDTD. * * @see WWEElement * @see WWEAttributeList * @see WWEContentModel * @see Parser */ public class WWEDTD implements WWEDTDConstants { public String name; public Vector elements = new Vector(); public Hashtable elementHash = new Hashtable(); public Hashtable entityHash = new Hashtable(); public final WWEElement pcdata = getElement("#pcdata"); public final WWEElement html = getElement("html"); public final WWEElement meta = getElement("meta"); public final WWEElement base = getElement("base"); public final WWEElement isindex = getElement("isindex"); public final WWEElement head = getElement("head"); public final WWEElement body = getElement("body"); public final WWEElement applet = getElement("applet"); public final WWEElement param = getElement("param"); public final WWEElement p = getElement("p"); public final WWEElement title = getElement("title"); final WWEElement style = getElement("style"); final WWEElement link = getElement("link"); public static int FILE_VERSION = 1; /** * Creates a new WWEDTD with the specified name. * @param name the name, as a <code>String</code> of the new WWEDTD */ protected WWEDTD(String name) { this.name = name; defEntity("#RE", GENERAL, '\r'); defEntity("#RS", GENERAL, '\n'); defEntity("#SPACE", GENERAL, ' '); defineElement("unknown", EMPTY, false, true, null, null, null, null); } /** * Gets the name of the WWEDTD. * @return the name of the WWEDTD */ public String getName() { return name; } /** * Gets an entity by name. * @return the <code>WWEEntity</code> corresponding to the * <code>name</code> <code>String</code> */ public WWEEntity getEntity(String name) { return (WWEEntity) entityHash.get(name); } /** * Gets a character entity. * @return the <code>WWEEntity</code> corresponding to the * <code>ch</code> character */ public WWEEntity getEntity(int ch) { return (WWEEntity) entityHash.get(new Integer(ch)); } /** * Returns <code>true</code> if the element is part of the WWEDTD, * otherwise returns <code>false</code>. * * @param name the requested <code>String</code> * @return <code>true</code> if <code>name</code> exists as * part of the WWEDTD, otherwise returns <code>false</code> */ boolean elementExists(String name) { WWEElement e = (WWEElement) elementHash.get(name); return ((e == null) ? false : true); } /** * Gets an element by name. A new element is * created if the element doesn't exist. * * @param name the requested <code>String</code> * @return the <code>WWEElement</code> corresponding to * <code>name</code>, which may be newly created */ public WWEElement getElement(String name) { WWEElement e = (WWEElement) elementHash.get(name); if (e == null) { e = new WWEElement(name, elements.size()); elements.addElement(e); elementHash.put(name, e); } return e; } /** * Gets an element by index. * * @param index the requested index * @return the <code>WWEElement</code> corresponding to * <code>index</code> */ public WWEElement getElement(int index) { return (WWEElement) elements.elementAt(index); } /** * Defines an entity. If the <code>WWEEntity</code> specified * by <code>name</code>, <code>type</code>, and <code>data</code> * exists, it is returned; otherwise a new <code>WWEEntity</code> * is created and is returned. * * @param name the name of the <code>WWEEntity</code> as a <code>String</code> * @param type the type of the <code>WWEEntity</code> * @param data the <code>WWEEntity</code>'s data * @return the <code>WWEEntity</code> requested or a new <code>WWEEntity</code> * if not found */ public WWEEntity defineEntity(String name, int type, char data[]) { WWEEntity ent = (WWEEntity) entityHash.get(name); if (ent == null) { ent = new WWEEntity(name, type, data); entityHash.put(name, ent); if (((type & GENERAL) != 0) && (data.length == 1)) { switch (type & ~GENERAL) { case CDATA: case SDATA: entityHash.put(new Integer(data[0]), ent); break; } } } return ent; } /** * Returns the <code>WWEElement</code> which matches the * specified parameters. If one doesn't exist, a new * one is created and returned. * * @param name the name of the <code>WWEElement</code> * @param type the type of the <code>WWEElement</code> * @param omitStart <code>true</code if start should be omitted * @param omitEnd <code>true</code> if end should be omitted * @param content the <code>WWEContentModel</code> * @param atts the <code>WWEAttributeList</code> specifying the * <code>WWEElement</code> * @return the <code>WWEElement</code> specified */ public WWEElement defineElement(String name, int type, boolean omitStart, boolean omitEnd, WWEContentModel content, BitSet exclusions, BitSet inclusions, WWEAttributeList atts) { WWEElement e = getElement(name); e.type = type; e.oStart = omitStart; e.oEnd = omitEnd; e.content = content; e.exclusions = exclusions; e.inclusions = inclusions; e.atts = atts; return e; } /** * Returns the <code>WWEElement</code> which matches the * specified <code>WWEWWEAttributeList</code>. * If one doesn't exist, a new one is created and returned. * * @param name the name of the <code>WWEElement</code> * @param atts the <code>WWEAttributeList</code> specifying the * <code>WWEElement</code> * @return the <code>WWEElement</code> specified */ public void defineAttributes(String name, WWEAttributeList atts) { WWEElement e = getElement(name); e.atts = atts; } /** * Creates and returns a character <code>WWEEntity</code>. * @param name the entity's name * @return the new character <code>WWEEntity</code> */ public WWEEntity defEntity(String name, int type, int ch) { char data[] = {(char) ch}; return defineEntity(name, type, data); } /** * Creates and returns an <code>WWEEntity</code>. * @param name the entity's name * @return the new <code>WWEEntity</code> */ protected WWEEntity defEntity(String name, int type, String str) { int len = str.length(); char data[] = new char[len]; str.getChars(0, len, data, 0); return defineEntity(name, type, data); } /** * Creates and returns an <code>WWEElement</code>. * @param the element's name * @return the new <code>WWEElement</code> */ protected WWEElement defElement(String name, int type, boolean omitStart, boolean omitEnd, WWEContentModel content, String[] exclusions, String[] inclusions, WWEAttributeList atts) { BitSet excl = null; if (exclusions != null && exclusions.length > 0) { excl = new BitSet(); for (int i = 0; i < exclusions.length; i++) { String str = exclusions[i]; if (str.length() > 0) { excl.set(getElement(str).getIndex()); } } } BitSet incl = null; if (inclusions != null && inclusions.length > 0) { incl = new BitSet(); for (int i = 0; i < inclusions.length; i++) { String str = inclusions[i]; if (str.length() > 0) { incl.set(getElement(str).getIndex()); } } } return defineElement(name, type, omitStart, omitEnd, content, excl, incl, atts); } /** * Creates and returns an <code>WWEAttributeList</code>. * @param name the attribute list's name * @return the new <code>WWEAttributeList</code> */ protected WWEAttributeList defAttributeList(String name, int type, int modifier, String value, String values, WWEAttributeList atts) { Vector vals = null; if (values != null) { vals = new Vector(); for (StringTokenizer s = new StringTokenizer(values, "|"); s.hasMoreTokens();) { String str = s.nextToken(); if (str.length() > 0) { vals.addElement(str); } } } return new WWEAttributeList(name, type, modifier, value, vals, atts); } /** * Creates and returns a new content model. * @param type the type of the new content model * @return the new <code>WWEContentModel</code> */ protected WWEContentModel defContentModel(int type, Object obj, WWEContentModel next) { return new WWEContentModel(type, obj, next); } /** * Returns a string representation of this WWEDTD. * @return the string representation of this WWEDTD */ public String toString() { return name; } /** * The hashtable of WWEDTDs. */ static Hashtable dtdHash = new Hashtable(); public static void putDTDHash(String name, WWEDTD dtd) { dtdHash.put(name, dtd); } /** * Returns a WWEDTD with the specified <code>name</code>. If * a WWEDTD with that name doesn't exist, one is created * and returned. Any uppercase characters in the name * are converted to lowercase. * * @param the name of the WWEDTD * @return the WWEDTD which ... [truncated message content] |
From: <de...@us...> - 2004-01-05 03:07:04
|
Update of /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/util In directory sc8-pr-cvs1:/tmp/cvs-serv15363/src/com/montarasoftware/wwe/util Added Files: WWEMap.java WWEFilePreviewer.java WWESpringUtilities.java WWEHTMLWriter.java WWEResourceLoader.java WWEHTMLUtilities.java WWEExceptionDialog.java WWEFileFilter.java WWEDialogLayout.java WWEUtil.java WWEDocumentWrapper.java Log Message: initial load of HTML editor pane and kit --- NEW FILE: WWEMap.java --- /* * @(#)Map.java 1.6 01/12/03 * * Copyright 2002 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.montarasoftware.wwe.util; import java.awt.Polygon; import java.io.Serializable; import java.util.StringTokenizer; import java.util.Vector; import javax.swing.text.AttributeSet; import javax.swing.text.html.HTML; /** * Map is used to represent a map element that is part of an HTML document. * Once a Map has been created, and any number of areas have been added, * you can test if a point falls inside the map via the contains method. * * @author Scott Violet * @version 1.6 12/03/01 */ public class WWEMap implements Serializable{ /** Name of the Map. */ private String name; /** An array of AttributeSets. */ private Vector areaAttributes; /** An array of RegionContainments, will slowly grow to match the * length of areaAttributes as needed. */ private Vector areas; public WWEMap() { } public WWEMap(String name) { this.name = name; } /** * Returns the name of the Map. */ public String getName() { return name; } /** * Defines a region of the Map, based on the passed in AttributeSet. */ public void addArea(AttributeSet as) { if (as == null) { return; } if (areaAttributes == null) { areaAttributes = new Vector(2); } areaAttributes.addElement(as.copyAttributes()); } /** * Removes the previously created area. */ public void removeArea(AttributeSet as) { if (as != null && areaAttributes != null) { int numAreas = (areas != null) ? areas.size() : 0; for (int counter = areaAttributes.size() - 1; counter >= 0; counter--) { if (((AttributeSet)areaAttributes.elementAt(counter)). isEqual(as)){ areaAttributes.removeElementAt(counter); if (counter < numAreas) { areas.removeElementAt(counter); } } } } } /** * Returns the AttributeSets representing the differet areas of the Map. */ public AttributeSet[] getAreas() { int numAttributes = (areaAttributes != null) ? areaAttributes.size() : 0; if (numAttributes != 0) { AttributeSet[] retValue = new AttributeSet[numAttributes]; areaAttributes.copyInto(retValue); return retValue; } return null; } /** * Returns the AttributeSet that contains the passed in location, * <code>x</code>, <code>y</code>. <code>width</code>, <code>height</code> * gives the size of the region the map is defined over. If a matching * area is found, the AttribueSet for it is returned. */ public AttributeSet getArea(int x, int y, int width, int height) { int numAttributes = (areaAttributes != null) ? areaAttributes.size() : 0; if (numAttributes > 0) { int numAreas = (areas != null) ? areas.size() : 0; if (areas == null) { areas = new Vector(numAttributes); } for (int counter = 0; counter < numAttributes; counter++) { if (counter >= numAreas) { areas.addElement(createRegionContainment ((AttributeSet)areaAttributes.elementAt(counter))); } RegionContainment rc = (RegionContainment)areas. elementAt(counter); if (rc != null && rc.contains(x, y, width, height)) { return (AttributeSet)areaAttributes.elementAt(counter); } } } return null; } /** * Creates and returns an instance of RegionContainment that can be * used to test if a particular point lies inside a region. */ protected RegionContainment createRegionContainment (AttributeSet attributes) { Object shape = attributes.getAttribute(HTML.Attribute.SHAPE); if (shape == null) { shape = "rect"; } if (shape instanceof String) { String shapeString = ((String)shape).toLowerCase(); RegionContainment rc = null; try { if (shapeString.equals("rect")) { rc = new RectangleRegionContainment(attributes); } else if (shapeString.equals("circle")) { rc = new CircleRegionContainment(attributes); } else if (shapeString.equals("poly")) { rc = new PolygonRegionContainment(attributes); } else if (shapeString.equals("default")) { rc = DefaultRegionContainment.sharedInstance(); } } catch (RuntimeException re) { // Something wrong with attributes. rc = null; } return rc; } return null; } /** * Creates and returns an array of integers from the String * <code>stringCoords</code>. If one of the values represents a * % the returned value with be negative. If a parse error results * from trying to parse one of the numbers null is returned. */ static protected int[] extractCoords(Object stringCoords) { if (stringCoords == null || !(stringCoords instanceof String)) { return null; } StringTokenizer st = new StringTokenizer((String)stringCoords, ", \t\n\r"); int[] retValue = null; int numCoords = 0; while(st.hasMoreElements()) { String token = st.nextToken(); int scale; if (token.endsWith("%")) { scale = -1; token = token.substring(0, token.length() - 1); } else { scale = 1; } try { int intValue = Integer.parseInt(token); if (retValue == null) { retValue = new int[4]; } else if(numCoords == retValue.length) { int[] temp = new int[retValue.length * 2]; System.arraycopy(retValue, 0, temp, 0, retValue.length); retValue = temp; } retValue[numCoords++] = intValue * scale; } catch (NumberFormatException nfe) { return null; } } if (numCoords > 0 && numCoords != retValue.length) { int[] temp = new int[numCoords]; System.arraycopy(retValue, 0, temp, 0, numCoords); retValue = temp; } return retValue; } /** * Defines the interface used for to check if a point is inside a * region. */ interface RegionContainment { /** * Returns true if the location <code>x</code>, <code>y</code> * falls inside the region defined in the receiver. * <code>width</code>, <code>height</code> is the size of * the enclosing region. */ public boolean contains(int x, int y, int width, int height); } /** * Used to test for containment in a rectangular region. */ static class RectangleRegionContainment implements RegionContainment, Serializable { /** Will be non-null if one of the values is a percent, and any value * that is non null indicates it is a percent * (order is x, y, width, height). */ float[] percents; /** Last value of width passed in. */ int lastWidth; /** Last value of height passed in. */ int lastHeight; /** Top left. */ int x0; int y0; /** Bottom right. */ int x1; int y1; public RectangleRegionContainment(AttributeSet as) { int[] coords = WWEMap.extractCoords(as.getAttribute(HTML. Attribute.COORDS)); percents = null; if (coords == null || coords.length != 4) { throw new RuntimeException("Unable to parse rectangular area"); } else { x0 = coords[0]; y0 = coords[1]; x1 = coords[2]; y1 = coords[3]; if (x0 < 0 || y0 < 0 || x1 < 0 || y1 < 0) { percents = new float[4]; lastWidth = lastHeight = -1; for (int counter = 0; counter < 4; counter++) { if (coords[counter] < 0) { percents[counter] = Math.abs (coords[counter]) / 100.0f; } else { percents[counter] = -1.0f; } } } } } public boolean contains(int x, int y, int width, int height) { if (percents == null) { return contains(x, y); } if (lastWidth != width || lastHeight != height) { lastWidth = width; lastHeight = height; if (percents[0] != -1.0f) { x0 = (int)(percents[0] * width); } if (percents[1] != -1.0f) { y0 = (int)(percents[1] * height); } if (percents[2] != -1.0f) { x1 = (int)(percents[2] * width); } if (percents[3] != -1.0f) { y1 = (int)(percents[3] * height); } } return contains(x, y); } public boolean contains(int x, int y) { return ((x >= x0 && x <= x1) && (y >= y0 && y <= y1)); } } /** * Used to test for containment in a polygon region. */ static class PolygonRegionContainment extends Polygon implements RegionContainment, Serializable { /** If any value is a percent there will be an entry here for the * percent value. Use percentIndex to find out the index for it. */ float[] percentValues; int[] percentIndexs; /** Last value of width passed in. */ int lastWidth; /** Last value of height passed in. */ int lastHeight; public PolygonRegionContainment(AttributeSet as) { int[] coords = WWEMap.extractCoords(as.getAttribute(HTML.Attribute. COORDS)); if (coords == null || coords.length == 0 || coords.length % 2 != 0) { throw new RuntimeException("Unable to parse polygon area"); } else { int numPercents = 0; lastWidth = lastHeight = -1; for (int counter = coords.length - 1; counter >= 0; counter--) { if (coords[counter] < 0) { numPercents++; } } if (numPercents > 0) { percentIndexs = new int[numPercents]; percentValues = new float[numPercents]; for (int counter = coords.length - 1, pCounter = 0; counter >= 0; counter--) { if (coords[counter] < 0) { percentValues[pCounter] = coords[counter] / -100.0f; percentIndexs[pCounter] = counter; pCounter++; } } } else { percentIndexs = null; percentValues = null; } npoints = coords.length / 2; xpoints = new int[npoints]; ypoints = new int[npoints]; for (int counter = 0; counter < npoints; counter++) { xpoints[counter] = coords[counter + counter]; ypoints[counter] = coords[counter + counter + 1]; } } } public boolean contains(int x, int y, int width, int height) { if (percentValues == null || (lastWidth == width && lastHeight == height)) { return contains(x, y); } // Force the bounding box to be recalced. bounds = null; lastWidth = width; lastHeight = height; float fWidth = (float)width; float fHeight = (float)height; for (int counter = percentValues.length - 1; counter >= 0; counter--) { if (percentIndexs[counter] % 2 == 0) { // x xpoints[percentIndexs[counter] / 2] = (int)(percentValues[counter] * fWidth); } else { // y ypoints[percentIndexs[counter] / 2] = (int)(percentValues[counter] * fHeight); } } return contains(x, y); } } /** * Used to test for containment in a circular region. */ static class CircleRegionContainment implements RegionContainment, Serializable { /** X origin of the circle. */ int x; /** Y origin of the circle. */ int y; /** Radius of the circle. */ int radiusSquared; /** Non-null indicates one of the values represents a percent. */ float[] percentValues; /** Last value of width passed in. */ int lastWidth; /** Last value of height passed in. */ int lastHeight; public CircleRegionContainment(AttributeSet as) { int[] coords = WWEMap.extractCoords(as.getAttribute(HTML.Attribute. COORDS)); if (coords == null || coords.length != 3) { throw new RuntimeException("Unable to parse circular area"); } x = coords[0]; y = coords[1]; radiusSquared = coords[2] * coords[2]; if (coords[0] < 0 || coords[1] < 0 || coords[2] < 0) { lastWidth = lastHeight = -1; percentValues = new float[3]; for (int counter = 0; counter < 3; counter++) { if (coords[counter] < 0) { percentValues[counter] = coords[counter] / -100.0f; } else { percentValues[counter] = -1.0f; } } } else { percentValues = null; } } public boolean contains(int x, int y, int width, int height) { if (percentValues != null && (lastWidth != width || lastHeight != height)) { int newRad = Math.min(width, height) / 2; lastWidth = width; lastHeight = height; if (percentValues[0] != -1.0f) { this.x = (int)(percentValues[0] * width); } if (percentValues[1] != -1.0f) { this.y = (int)(percentValues[1] * height); } if (percentValues[2] != -1.0f) { radiusSquared = (int)(percentValues[2] * Math.min(width, height)); radiusSquared *= radiusSquared; } } return (((x - this.x) * (x - this.x) + (y - this.y) * (y - this.y)) <= radiusSquared); } } /** * An implementation that will return true if the x, y location is * inside a rectangle defined by origin 0, 0, and width equal to * width passed in, and height equal to height passed in. */ static class DefaultRegionContainment implements RegionContainment, Serializable { /** A global shared instance. */ static DefaultRegionContainment si = null; public static DefaultRegionContainment sharedInstance() { if (si == null) { si = new DefaultRegionContainment(); } return si; } public boolean contains(int x, int y, int width, int height) { return (x <= width && x >= 0 && y >= 0 && y <= width); } } } --- NEW FILE: WWEFilePreviewer.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.util; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.border.BevelBorder; /** * A previewer for Images File Chooser. * * @version 1.0 27 Aug 2003 * @author Faruk Khan */ public class WWEFilePreviewer extends JComponent implements PropertyChangeListener { ImageIcon thumbnail = null; public WWEFilePreviewer(JFileChooser fc) { setPreferredSize(new Dimension(100, 50)); fc.addPropertyChangeListener(this); setBorder(new BevelBorder(BevelBorder.LOWERED)); } public void loadImage(File f) { if(f == null){ thumbnail = null; }else{ ImageIcon tmpIcon = new ImageIcon(f.getPath()); if(tmpIcon.getIconWidth() > 90) { thumbnail = new ImageIcon( tmpIcon.getImage().getScaledInstance(90, -1, Image.SCALE_DEFAULT)); }else{ thumbnail = tmpIcon; } } } public void propertyChange(PropertyChangeEvent e) { String prop = e.getPropertyName(); if(prop == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY){ if(isShowing()){ loadImage((File) e.getNewValue()); repaint(); } } } public void paint(Graphics g){ super.paint(g); if(thumbnail != null){ int x = getWidth()/2 - thumbnail.getIconWidth()/2; int y = getHeight()/2 - thumbnail.getIconHeight()/2; if(y < 0){ y = 0; } if(x < 5){ x = 5; } thumbnail.paintIcon(this, g, x, y); } } } --- NEW FILE: WWESpringUtilities.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.util; import java.awt.Component; import java.awt.Container; import javax.swing.Spring; import javax.swing.SpringLayout; /** * Provides utility methods for * creating form- or grid-style layouts with SpringLayout. */ public class WWESpringUtilities { /** * A debugging utility that prints to stdout the component's * minimum, preferred, and maximum sizes. */ public static void printSizes(Component c) { System.out.println("minimumSize = " + c.getMinimumSize()); System.out.println("preferredSize = " + c.getPreferredSize()); System.out.println("maximumSize = " + c.getMaximumSize()); } /** * Aligns the first <code>rows</code> * <code>cols</code> * components of <code>parent</code> in * a grid. Each component is as big as the maximum * preferred width and height of the components. * The parent is made just big enough to fit them all. * * @param rows number of rows * @param cols number of columns * @param initialX x location to start the grid at * @param initialY y location to start the grid at * @param xPad x padding between cells * @param yPad y padding between cells */ public static void makeGrid(Container parent, int rows, int cols, int initialX, int initialY, int xPad, int yPad) { SpringLayout layout; try { layout = (SpringLayout)parent.getLayout(); } catch (ClassCastException exc) { System.err.println("The first argument to makeGrid must use SpringLayout."); return; } Spring xPadSpring = Spring.constant(xPad); Spring yPadSpring = Spring.constant(yPad); Spring initialXSpring = Spring.constant(initialX); Spring initialYSpring = Spring.constant(initialY); int max = rows * cols; //Calculate Springs that are the max of the width/height so that all //cells have the same size. Spring maxWidthSpring = layout.getConstraints(parent.getComponent(0)). getWidth(); Spring maxHeightSpring = layout.getConstraints(parent.getComponent(0)). getWidth(); for (int i = 1; i < max; i++) { SpringLayout.Constraints cons = layout.getConstraints( parent.getComponent(i)); maxWidthSpring = Spring.max(maxWidthSpring, cons.getWidth()); maxHeightSpring = Spring.max(maxHeightSpring, cons.getHeight()); } //Apply the new width/height Spring. This forces all the //components to have the same size. for (int i = 0; i < max; i++) { SpringLayout.Constraints cons = layout.getConstraints( parent.getComponent(i)); cons.setWidth(maxWidthSpring); cons.setHeight(maxHeightSpring); } //Then adjust the x/y constraints of all the cells so that they //are aligned in a grid. SpringLayout.Constraints lastCons = null; SpringLayout.Constraints lastRowCons = null; for (int i = 0; i < max; i++) { SpringLayout.Constraints cons = layout.getConstraints( parent.getComponent(i)); if (i % cols == 0) { //start of new row lastRowCons = lastCons; cons.setX(initialXSpring); } else { //x position depends on previous component cons.setX(Spring.sum(lastCons.getConstraint(SpringLayout.EAST), xPadSpring)); } if (i / cols == 0) { //first row cons.setY(initialYSpring); } else { //y position depends on previous row cons.setY(Spring.sum(lastRowCons.getConstraint(SpringLayout.SOUTH), yPadSpring)); } lastCons = cons; } //Set the parent's size. SpringLayout.Constraints pCons = layout.getConstraints(parent); pCons.setConstraint(SpringLayout.SOUTH, Spring.sum( Spring.constant(yPad), lastCons.getConstraint(SpringLayout.SOUTH))); pCons.setConstraint(SpringLayout.EAST, Spring.sum( Spring.constant(xPad), lastCons.getConstraint(SpringLayout.EAST))); } /* Used by makeCompactGrid. */ private static SpringLayout.Constraints getConstraintsForCell( int row, int col, Container parent, int cols) { SpringLayout layout = (SpringLayout) parent.getLayout(); Component c = parent.getComponent(row * cols + col); return layout.getConstraints(c); } /** * Aligns the first <code>rows</code> * <code>cols</code> * components of <code>parent</code> in * a grid. Each component in a column is as wide as the maximum * preferred width of the components in that column; * height is similarly determined for each row. * The parent is made just big enough to fit them all. * * @param rows number of rows * @param cols number of columns * @param initialX x location to start the grid at * @param initialY y location to start the grid at * @param xPad x padding between cells * @param yPad y padding between cells */ public static void makeCompactGrid(Container parent, int rows, int cols, int initialX, int initialY, int xPad, int yPad) { SpringLayout layout; try { layout = (SpringLayout)parent.getLayout(); } catch (ClassCastException exc) { System.err.println("The first argument to makeCompactGrid must use SpringLayout."); return; } //Align all cells in each column and make them the same width. Spring x = Spring.constant(initialX); for (int c = 0; c < cols; c++) { Spring width = Spring.constant(0); for (int r = 0; r < rows; r++) { width = Spring.max(width, getConstraintsForCell(r, c, parent, cols). getWidth()); } for (int r = 0; r < rows; r++) { SpringLayout.Constraints constraints = getConstraintsForCell(r, c, parent, cols); constraints.setX(x); constraints.setWidth(width); } x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad))); } //Align all cells in each row and make them the same height. Spring y = Spring.constant(initialY); for (int r = 0; r < rows; r++) { Spring height = Spring.constant(0); for (int c = 0; c < cols; c++) { height = Spring.max(height, getConstraintsForCell(r, c, parent, cols). getHeight()); } for (int c = 0; c < cols; c++) { SpringLayout.Constraints constraints = getConstraintsForCell(r, c, parent, cols); constraints.setY(y); constraints.setHeight(height); } y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad))); } //Set the parent's size. SpringLayout.Constraints pCons = layout.getConstraints(parent); pCons.setConstraint(SpringLayout.SOUTH, y); pCons.setConstraint(SpringLayout.EAST, x); } /** * Aligns the first <code>rows</code> * <code>cols</code> * components of <code>parent</code> in * a grid. Each component in the First column is as wide as the maximum * preferred width of the components in that column; * height is similarly determined for each row. * The second column is aligned properly but honours the components preferred width. * The parent is made just big enough to fit them all. * * <b> * Note: This method has been specially overloaded to * support the scenario's like the Insert HyperLink Dialog. * Please do not use this method if your grid has more than 2 columns. * </b> * * @param rows number of rows * @param cols number of columns * @param initialX x location to start the grid at * @param initialY y location to start the grid at * @param xPad x padding between cells * @param yPad y padding between cells * @param hPWidth honour preferred width of components in second column */ public static void makeCompactGrid(Container parent, int rows, int cols, int initialX, int initialY, int xPad, int yPad, boolean hPWidth) { SpringLayout layout; try { layout = (SpringLayout)parent.getLayout(); } catch (ClassCastException exc) { System.err.println("The first argument to makeCompactGrid must use SpringLayout."); return; } //Align all cells in each column and make them the same width. Spring x = Spring.constant(initialX); for (int c = 0; c < cols; c++) { Spring width = Spring.constant(0); for (int r = 0; r < rows; r++) { width = Spring.max(width, getConstraintsForCell(r, c, parent, cols). getWidth()); } for (int r = 0; r < rows; r++) { SpringLayout.Constraints constraints = getConstraintsForCell(r, c, parent, cols); constraints.setX(x); if(cols == 2){ if(!hPWidth) constraints.setWidth(width); }else{ constraints.setWidth(width); } } x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad))); } //Align all cells in each row and make them the same height. Spring y = Spring.constant(initialY); for (int r = 0; r < rows; r++) { Spring height = Spring.constant(0); for (int c = 0; c < cols; c++) { height = Spring.max(height, getConstraintsForCell(r, c, parent, cols). getHeight()); } for (int c = 0; c < cols; c++) { SpringLayout.Constraints constraints = getConstraintsForCell(r, c, parent, cols); constraints.setY(y); constraints.setHeight(height); } y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad))); } //Set the parent's size. SpringLayout.Constraints pCons = layout.getConstraints(parent); pCons.setConstraint(SpringLayout.SOUTH, y); pCons.setConstraint(SpringLayout.EAST, x); } } --- NEW FILE: WWEHTMLWriter.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.util; import java.io.IOException; import java.io.Writer; import java.util.Enumeration; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.Element; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.html.HTML; import com.montarasoftware.wwe.WWEHTMLDocument; /** * * <p><code>WWEHTMLWriter</code> implements an own approach to * clean writing of HTML * To keep it simple, <code>WWEHTMLWriter</code> * only writes HTML content * * @Later it will also write CSS content * * @NOTE some Variables/Functions in this Class is not used currently * as they are not complete (they are written for CSS Support) * * @author Amit Ahuja * */ public class WWEHTMLWriter { /** the document this writer is to generate HTML for */ private WWEHTMLDocument doc; /** the writer for HTML output */ private Writer w; /** * constant for new line character (handled differnetly * on Windows, Unix/Linux and Mac) */ private String newline = System.getProperty("line.separator"); /** start position in document for writing HTML */ private int startOffset; /** end position in document for writing HTML */ private int endOffset; /** indicates if the writer currently works on an implied tag */ private boolean inImpliedTag = false; /** indicates if the writer currently works on a link */ private boolean inLink = false; /** indicates if the wrtier currenty is inside of content */ private boolean inContent = false; /** indicates if the writer has already worked on the first tag inside of any content */ private boolean firstContent = true; /** * the mode for writing * * <p>This is built in as a workaround for bug id 4765271 * (see http://developer.java.sun.com/developer/bugParade/bugs/4765271.html)</p> */ private int mode; /** * indicator for writing 'normal' HTML * * <p>This is built in as a workaround for bug id 4765271 * (see http://developer.java.sun.com/developer/bugParade/bugs/4765271.html)</p> */ public static final int MODE_HTML = 1; /** * indicator for writing 'adjusted Java HTML' * * <p>This is built in as a workaround for bug id 4765271 * (see http://developer.java.sun.com/developer/bugParade/bugs/4765271.html)</p> */ public static final int MODE_JAVA = 2; /** * construct a new WWEHTMLWriter to generate HTML for a * given part of a document * * @param w the writer for HTML output * @param doc the document to generate HTML from * @param pos the start position of the part of the document * to generate HTML for * @param len the length of the part of the document to * generate HTML for * @param mode the writing mode, one of MODE_HTML and MODE_JAVA */ public WWEHTMLWriter(Writer w, WWEHTMLDocument doc, int pos, int len, int mode) { this.doc = doc; this.w = w; this.startOffset = pos; this.endOffset = pos + len; this.mode = mode; } /** * construct a new WWEHTMLWriter to generate HTML for a * given part of a document * * @param w the writer for HTML output * @param doc the document to generate HTML from * @param pos the start position of the part of the document * to generate HTML for * @param len the length of the part of the document to * generate HTML for */ public WWEHTMLWriter(Writer w, WWEHTMLDocument doc, int pos, int len) { this(w, doc, pos, len, MODE_JAVA); } /** * construct a new WWEHTMLWriter to generate HTML for a * given document * * @param w the writer for HTML output * @param doc the document to generate HTML from * @param mode the writing mode, one of MODE_HTML and MODE_JAVA */ public WWEHTMLWriter(Writer w, WWEHTMLDocument doc, int mode) { this(w, doc, 0, doc.getLength(), mode); } /** * construct a new WWEHTMLWriter to generate HTML for a * given document * * @param w the writer for HTML output * @param doc the document to generate HTML from */ public WWEHTMLWriter(Writer w, WWEHTMLDocument doc) { this(w, doc, 0, doc.getLength(), MODE_JAVA); } /** * construct an uninitialized WWEHTMLWriter * * <p>This can be used for snythesizing HTML instead of * reading it from the element structure of a document.</p> * * <p>If a WWEHTMLWriter was constructed with this constructor * which shall be used for writing a document, the document and * writeSegment properties of the WWEHTMLWriter need to be set * before calling its write() methods.</p> * * @param w the writer to write to */ public WWEHTMLWriter(Writer w) { this(w, null, 0, 0, MODE_JAVA); } /** * set the document to write from * * @param doc the document to write from */ public void setDocument(WWEHTMLDocument doc) { this.doc = doc; } /** * specify the text segment of the document to be written * * @param pos the start position of the text segment * @param len the length of the text segment */ public void setWriteSegment(int pos, int len) { this.startOffset = pos; this.endOffset = pos + len; } /** * invoke HTML creation for the document or part of document * given in the constructor of this WWEHTMLWriter * * @exception IOException on any i/o error * @exception BadLocationException if text retrieval via doc.getText is * passed an invalid location within the document * @exception PropertiesMissingException if the document is not set prior * to calling this method */ public void write() throws IOException, BadLocationException, PropertiesMissingException { if((doc != null) && (endOffset > 0)) { if(startOffset == 0) { write(doc.getDefaultRootElement()); } else { write(doc.getParagraphElement(startOffset).getParentElement()); } } else { throw new PropertiesMissingException(); } } /** * invoke HTML creation for a given element and all its children * * <p>This iterates through the element structure below the given * element by calling itself recursively for each branch element * found.</p> * * @param e the element to generate HTML for * * @exception IOException on any i/o error * @exception BadLocationException if text retrieval via doc.getText is * passed an invalid location within the document */ public void write(Element e) throws IOException, BadLocationException { if (e.isLeaf()) { System.out.println(" e.isLeaf() "+e.toString()); inContent = true; leafTag(e); inContent = false; } else { System.out.println(" !e.isLeaf() "); startTag(e); int childCount = e.getElementCount(); int index = 0; while (index < childCount) { write(e.getElement(index)); // drill down in recursion index++; } endTag(e); } } /** * write an element and all its children. If a given element is reached, * writing stops with this element. If the end element is a leaf, * it is written as the last element, otherwise it is not written. * * @param e the element to write including its children (if any) * @param end the last leaf element to write or the branch element * to stop writing at (whatever applies) */ public void writeElementsUntil(Element e, Element end) throws IOException, BadLocationException { if(e.isLeaf()) { inContent = true; leafTag(e); inContent = false; } else { if(e != end) { startTag(e); int childCount = e.getElementCount(); int index = 0; while(index < childCount) { writeElementsUntil(e.getElement(index), end); // drill down in recursion index++; } endTag(e); } } } /** * write elements and their children starting at a * given element until a given element is reached. * The end element is written as the last element, * if it is a leaf element. * * @param start the element to start writing with * @param end the last element to write */ public void write(Element start, Element end) throws IOException, BadLocationException { Element parent = start.getParentElement(); int count = parent.getElementCount(); int i = 0; Element e = parent.getElement(i); while(i < count && e != start) { e = parent.getElement(i++); } while(i < count) { writeElementsUntil(e, end); e = parent.getElement(i++); } } /** * invoke HTML creation for all children of a given element. * * @param elem the element which children are to be written as HTML */ public void writeChildElements(Element elem) throws IOException, BadLocationException, PropertiesMissingException { Element para; for(int i = 0; i < elem.getElementCount(); i++) { para = elem.getElement(i); write(para); } } /* --------- tag writing start -------------- */ private char returnChar = '\r'; private char newlineChar = '\n'; /* HTML syntax constants */ public static final char htmlTagStart = '<'; public static final char htmlTagEnd = '>'; public static final char htmlEndTagIndicator = '/'; public static final char htmlAttributeSeparator = '='; public static final char htmlAttributeTerminator = ' '; public static final char htmlAttributeStartEnd = '\"'; /* CSS syntax constants */ public static final char cssAttributeTerminator = ';'; public static final char cssAttributeSeparator = ':'; /** * write out a start tag including tag attributes for a given element * * <p>This will not write start tags for implied elements. Indicator * inImpliedTag is set instead to signal subsequent methods that we are * inside an implied tag. Indicator inImpliedTag is cleared by method * endTag.</p> * * <p>CAUTION: This will not work for nested implied tags! Not sure yet, * if these can happen, watch out accordingly.</p> * * @param e the element to generate a start tag for * * @exception IOException on any i/o error */ private void startTag(Element e) throws IOException { AttributeSet a = e.getAttributes(); if(nameEquals(a, HTML.Tag.IMPLIED.toString())) { inImpliedTag = true; } else { startTag(e.getName(), a); } } /** * write out a start tag for a given tag name * including tag attributes (if any) * * @param name the name of the tag to generate * @param a the set of attributes to generate in tag or null if none * * @exception IOException on any i/o error */ public void startTag(String name, AttributeSet a) throws IOException { if (!name.equalsIgnoreCase(HTML.Tag.A.toString())) { w.write(newline); indent(); System.out.println(" starttag name "+name); } w.write(htmlTagStart); w.write(name); if (a != null) { writeTagAttributes(a, false); } w.write(htmlTagEnd); increaseIndent(); } /** * write a leaf tag * * leaf tags can have different content in the element * structure of a document * * 1. 'normal' leaf: the element name is CONTENT. * * a) element has no attributes: * only the text from the document is written. * * b) element has attributes: * a SPAN start tag is synthesized holding the attributes, * then the text from the document is written and * a SPAN end tag is written finally. * * c) the leaf is the CONTENT element of an implied paragraph: * nothing is written. * * 2. leaf holding a tag name for which no end tag is needed: * the element name is other than CONTENT. * * a start tag is generated for the element (endTag does not * write an end tag for this startTag in this case). * * @exception IOException on any i/o error * @exception BadLocationException if text retrieval via doc.getText is * passed an invalid location within the document. */ private void leafTag(Element e) throws IOException, BadLocationException { System.out.println("WWEHTMLWriter.leafTag e= " + e.getName()); // get the element attributes AttributeSet a = e.getAttributes(); // get value of name attribute and see if we are in content if(nameEquals(a, HTML.Tag.CONTENT.toString())) { // we are in content but only write content, if not inside an implied tag if(!inImpliedTag) { // get start and end position of text to write System.out.println(" startOffset "+startOffset); System.out.println(" endOffset "+endOffset); System.out.println(" e.getStartOffset() "+e.getStartOffset()); System.out.println(" e.getEndOffset() "+e.getEndOffset()); int start = Math.max(startOffset, e.getStartOffset()); int end = Math.min(endOffset, e.getEndOffset()); if(end > start) { // element is inside the part of document to write, get the text String text = doc.getText(start, end - start); if(text != null) { // we have text, write attributes, if any extractLink(a); if(writeTagAttributes(a, true)) { //if(true) { // attributes written, write content text and... writeContentText(text); // ..write SPAN end tag decreaseIndent(); /** w.write(htmlTagStart); w.write(htmlEndTagIndicator); w.write(HTML.Tag.SPAN.toString()); w.write(htmlTagEnd); **/ if(inLink) { // a link tag was found in attributes and written out, write end tag for it decreaseIndent(); endTag(HTML.Tag.A.toString()); inLink = false; } } else { // no style attributes written, just write content text writeContentText(text); if(inLink) { // a link tag was found in attributes and written out, write end tag for it decreaseIndent(); endTag(HTML.Tag.A.toString()); inLink = false; } } // writeTagAttributes } // text != null } // end > start } // !inImpliedTag } // nameEquals content else { // not in content, write an implied startTag or endTag (if any) if (!isEndtag(a)) { extractLink(a); startTag(e.getName(), a); decreaseIndent(); } else { indent(); endTag(e.getName()); } } } /** * test, if an attribute set contains another attribute set identifying a link * if yes, write a link tag with respective attributes * * @param a the attribute set to look for a link attribute set * * @return true, when a link was written, false, if not */ private boolean extractLink(AttributeSet a) throws IOException { Object key = a.getAttribute(HTML.Tag.A); if(key != null) { AttributeSet linkAttrs = (AttributeSet) key; startTag(HTML.Tag.A.toString(), linkAttrs); inLink = true; } return inLink; } /** * determine by a given set of attributes whether or not the tag * the attributes belong to is an implied endtag. */ private boolean isEndtag(AttributeSet a) { boolean hasEndtag = false; if(a != null) { Object endtag = a.getAttribute(HTML.Attribute.ENDTAG); if(endtag != null) { hasEndtag = true; } } return hasEndtag; } /** * write out an end tag for a given element * * <p>This will not write an end tag if we are inside an implied tag. * Indicator inImpliedTag will be cleared in this case instead.</p> * * <p>CAUTION: This will not work for nested implied tags! Not sure yet, * if these can happen, watch out accordingly.</p> * * @param e the element to generate an end tag for * * @exception IOException on any i/o error */ private void endTag(Element e) throws IOException { if(inImpliedTag) { inImpliedTag = false; } else { decreaseIndent(); indent(); endTag(e.getName()); } } /** * write out an end tag for a given tag name * * @param name the name of the tag to generate an end tag for */ public void endTag(String name) throws IOException { if(!inLink) { w.write(newline); indent(); } w.write(htmlTagStart); w.write(htmlEndTagIndicator); w.write(name); w.write(htmlTagEnd); } /** * write attributes of a tag * * this first collects all attributes and generates HTML or * CSS code according to the type of attribute. * * Single members of CSS shorthand properties are * filtered out using method filterAttributes and Vector * unwantedCssAttributes. For these attributes CSS shorthand * properties are generated instead. * * It then writes out the attributes according to their type: * * a) if HTML attributes were generated, they are written as * key/value pairs in HTML syntax following the HTML tag * name. * * b) if CSS attributes were generated, they are written as * key/value pairs in CSS syntax inside a STYLE attribute * follwing the HTML tag name or a) above, whatever applies. * * If attributes were generated for a CONTENT tag, a) and b) * above are generated inside a synthesized SPAN start tag. Method * leafTag generates the SPAN end tag after writing the content * accordingly in this case. * * In stage 9 link handling is added: Links (tag A) are attributes * in Java instead of tags. * * @param a set of attributes to write * @param inContent true if we are in content (SPAN), false if not * * @exception IOException on any i/o error */ private boolean writeTagAttributes(AttributeSet a, boolean inContent) throws IOException { boolean wroteAttributes = false; a = new SimpleAttributeSet(a); StringBuffer style = new StringBuffer(); StringBuffer html = new StringBuffer(); splitToAttrBuffers(a, html, style); if ( ( (html.length() > 0) || (style.length() > 0)) && (inContent)) { if (!inLink && firstContent) { w.write(newline); indent(); firstContent = false; } indent(); w.write(htmlTagStart); w.write(HTML.Tag.SPAN.toString()); } if (html.length() > 0) { w.write(html.toString()); wroteAttributes = true; } if (style.length() > 0) { w.write(htmlAttributeTerminator); w.write(HTML.Attribute.STYLE.toString()); w.write(htmlAttributeSeparator); w.write(htmlAttributeStartEnd); w.write(style.toString()); w.write(htmlAttributeStartEnd); wroteAttributes = true; } if ( ( (html.length() > 0) || (style.length() > 0)) && (inContent)) { w.write(htmlTagEnd); increaseIndent(); } return wroteAttributes; } /** * split an attribute set into CSS and HTML attributes */ private void splitToAttrBuffers(AttributeSet a, StringBuffer html, StringBuffer style) throws IOException { Enumeration keys = a.getAttributeNames(); while(keys.hasMoreElements()) { Object key = keys.nextElement(); if(key != null) { Object val = a.getAttribute(key); if (val != null) { /* temp -- AA if (key instanceof CSS.Attribute) { filterCSSAttributes(style, key, val); } else */ if (key instanceof HTML.Attribute) { html.append(htmlAttributeTerminator); html.append(key.toString()); html.append(htmlAttributeSeparator); html.append(htmlAttributeStartEnd); html.append(val.toString()); html.append(htmlAttributeStartEnd); } } } } } /** * write a given CSS attribute to a given output buffer * * @param buf the output buffer to write to * @param key the CSS attribute key to write * @param val the value of the attribute to write */ private void writeCssAttribute(StringBuffer buf, Object key, Object val) { if(buf.length() > 0) { buf.append(htmlAttributeTerminator); } buf.append(key.toString()); buf.append(cssAttributeSeparator); buf.append(val.toString()); buf.append(cssAttributeTerminator); } /* -------- tag writing end ------------------- */ /* -------- tag writing help methods start ------------------- */ /** * Returns true if the StyleConstants.NameAttribute is * equal to name that is passed in as a parameter. * * @param attr the set of attributes to look for a name * @param name the name to look for * * @return true if the set of attributes has a name attribute equal to * the name in question, false if not */ private boolean nameEquals(AttributeSet attr, String name) { boolean found = false; Object value = attr.getAttribute(StyleConstants.NameAttribute); if(value != null) { found = value.toString().equalsIgnoreCase(name); } return found; } /** * write the text found as content and append a new line * if none is found in the content text. * * @param text the content text to write */ private void writeContentText(String text) throws IOException { transformSpecialChars(text.toCharArray()); //if(!hasNewLine(text)) { //System.out.println("writeContentText newline"); //w.write(newline); //} } /** * transform special characters in content text by replacing certain * characters with their HTML equivalents before actually * writing them out. * * @param text the uncleaned content text to write * * @exception IOException on any i/o error */ private void transformSpecialChars(char[] text) throws IOException { int last = 0; int length = text.length; for(int i = 0; i < text.length; i++) { switch(text[i]) { case '<': if (i > last) { w.write(text, last, i - last); } last = i + 1; w.write("<"); break; case '>': if (i > last) { w.write(text, last, i - last); } last = i + 1; w.write(">"); break; case '&': if (i > last) { w.write(text, last, i - last); } last = i + 1; w.write("&"); break; case '"': if (i > last) { w.write(text, last, i - last); } last = i + 1; w.write("""); break; case '\n': if (i > last) { w.write(text, last, i - last); } last = i + 1; break; case '\t': case '\r': break; default: if (text[i] < ' ' || text[i] > 127) { if (i > last) { w.write(text, last, i - last); } last = i + 1; w.write("&#"); w.write(String.valueOf((int) text[i])); w.write(";"); } break; } } if (last < length) { w.write(text, last, length - last); } } /** * test whether or not a given string contains newline chars * * @param text the string to look for newline chars * * @return true, if the string contains newline chars, false if not */ private boolean hasNewLine(String text) { int rPos = text.indexOf(returnChar); int nPos = text.indexOf(newlineChar); return ((rPos > -1) || (nPos > -1)); //return (text.indexOf(newline) > -1); } /* -------- tag writing help methods end ------------------- */ /* -------- indent handling start ------------- */ private char[] indentChars; private int indentLevel = 0; private int indentSpace = 2; /** * decrement the indent level. */ private void decreaseIndent() { --indentLevel; } /** * increment the indent level. */ private void increaseIndent() { ++indentLevel; } /** * write spaces according to the current indentLevel. * * The number of spaces written is determined by the * amount of spaces per indent step multiplied by the * level of indentation. * * Indent spaces are generated in a char[] as needed. * * @exception IOException on any i/o error */ private void indent() throws IOException { if(!inContent || firstContent) { int max = indentLevel * indentSpace; if (indentChars == null || max > indentChars.length) { indentChars = new char[max]; for (int i = 0; i < max; i++) { indentChars[i] = ' '; } } w.write(indentChars, 0, max /*Math.max(0, max)*/); } } /* -------- indent handling end --------------- */ /** * inner class for signaling that properties were missing for * proper execution. */ public class PropertiesMissingException extends Exception { /** * Constructs a <code>WriterPropertiesMissingException</code> with * <code>null</code> as its error detail message. */ public PropertiesMissingException() { super(); } /** * Constructs an <code>WriterPropertiesMissingException</code> with * the specified detail message. The error message string <code>s</code> * can later be retrieved by the <code>{@link java.lang.Throwable#getMessage}</code> * method of class <code>java.lang.Throwable</code>. * * @param s the detail message. */ public PropertiesMissingException(String s) { super(s); } } } --- NEW FILE: WWEResourceLoader.java --- /* ==================================================================== * The Apache Software Lice... [truncated message content] |
Update of /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/event In directory sc8-pr-cvs1:/tmp/cvs-serv15363/src/com/montarasoftware/wwe/event Added Files: WWEPageLoadListener.java WWEComponentListener.java WWEEventManager.java WWEPageLoadEvent.java WWEComponentEvent.java Log Message: initial load of HTML editor pane and kit --- NEW FILE: WWEPageLoadListener.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.event; import java.util.EventListener; /* * WWEPageLoadEvent.java * * @author Faruk Khan * @version 1.0 07 October 2003 */ public interface WWEPageLoadListener extends EventListener { public void pageLoaded(WWEPageLoadEvent evt); } --- NEW FILE: WWEComponentListener.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.event; import java.util.EventListener; /** * @author Tarundeep S Sodhi */ public interface WWEComponentListener extends EventListener { public void mouseClicked(WWEComponentEvent evt); } --- NEW FILE: WWEEventManager.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.event; import java.awt.Component; import java.awt.Cursor; import java.awt.Point; import java.awt.Rectangle; import java.awt.Shape; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URL; import javax.swing.Box; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.plaf.TextUI; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.Element; import javax.swing.text.Position; import javax.swing.text.StyleConstants; import javax.swing.text.html.HTML; import com.montarasoftware.wwe.WWEEditorPane; import com.montarasoftware.wwe.WWEHTML; import com.montarasoftware.wwe.WWEHTMLDocument; import com.montarasoftware.wwe.util.WWEHTMLUtilities; import com.montarasoftware.wwe.util.WWEMap; /* * Class to watch the associated component and fire * the appropriate events. * * @author Faruk m Khan * @author Tarundeep S Sodhi * @version 1.0 26 August 2003 */ public class WWEEventManager implements MouseListener, MouseMotionListener, Serializable { private Element curElem = null; /** * If true, the current element (curElem) represents an image. * */ private boolean curElemImage = false; private String href = null; /** * This is used by viewToModel to avoid allocing a new array each * time. */ private Position.Bias[] bias = new Position.Bias[1]; /** * Current offset. */ private Point pt; private static final Cursor LINKCURSOR = Cursor.getPredefinedCursor (Cursor.HAND_CURSOR); private static final Cursor DEFAULTCURSOR = Cursor.getPredefinedCursor (Cursor.DEFAULT_CURSOR); private static final Cursor TEXTCURSOR = Cursor.getPredefinedCursor (Cursor.TEXT_CURSOR); /** * A property used to indicate whether a Popup Menu * should appear with a certain gestures. * If <code>popupTrigger</code> = <code>false</code>, * no popup menu should appear. If it is <code>true</code> * then a popup menu should appear. * * @serial * @see java.awt.PopupMenu */ boolean m_popupTrigger = false; /** * Called for a mouse click event. * If the component is read-only (ie a browser) then * the clicked event is used to drive an attempt to * follow the reference specified by a link. * * @param e the mouse event * * @see MouseListener#mouseClicked */ public void mouseClicked(MouseEvent e) { if(e.getButton()==MouseEvent.BUTTON3){ WWEEditorPane editor = (WWEEditorPane) e.getSource(); int pos = editor.viewToModel(e.getPoint()); if (pos >= 0) { int xStart = editor.getSelectionStart(); int xFinish = editor.getSelectionEnd(); if(pos < xStart || pos > xFinish) editor.setCaretPosition(pos); } } setPopupTrigger(e.isPopupTrigger()); processClick(e); } // ignore the drags public void mouseDragged(MouseEvent e){} public void mousePressed(MouseEvent e){ setPopupTrigger(e.isPopupTrigger()); } public void mouseReleased(MouseEvent e){ setPopupTrigger(e.isPopupTrigger()); } public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} /** * track the moving of the mouse * */ public void mouseMoved(MouseEvent e) { WWEEditorPane editor = (WWEEditorPane) e.getSource(); boolean adjustCursor = true; Cursor newCursor = DEFAULTCURSOR; boolean editable = editor.isEditable(); Point pt = new Point(e.getX(), e.getY()); int pos = editor.getUI().viewToModel(editor, pt, bias); if (bias[0] == Position.Bias.Backward && pos > 0) { pos--; } if (!(pos >= 0 &&(editor.getDocument() instanceof WWEHTMLDocument))){ return; } WWEHTMLDocument hdoc = (WWEHTMLDocument)editor.getDocument(); Element elem = hdoc.getCharacterElement(pos); if (!WWEHTMLUtilities.doesElementContainLocation(editor, elem, pos, e.getX(), e.getY())) { elem = null; } Element lastElem = null; String href = null; if (elem != null) { if (curElem != elem /*|| curElemImage*/) { lastElem = curElem; curElem = elem; //curElemImage = false; AttributeSet a = elem.getAttributes(); AttributeSet anchor = (AttributeSet)a.getAttribute(HTML.Tag.A); Object o = a.getAttribute(StyleConstants.NameAttribute); HTML.Tag kind = null; kind = o instanceof HTML.Tag ? (HTML.Tag) o: null; if(anchor != null){ href = (String)anchor.getAttribute(HTML.Attribute.HREF); if (href != this.href && href != null){ if(!editable){ newCursor = LINKCURSOR; }else{ if(kind == HTML.Tag.IMG){ //curElemImage = true; newCursor = DEFAULTCURSOR; } else newCursor = TEXTCURSOR; } } }else if(kind == HTML.Tag.IMG){ //curElemImage = true; newCursor = DEFAULTCURSOR; }else if(kind == HTML.Tag.CONTENT){ newCursor = TEXTCURSOR; }else{ adjustCursor = false; } }else{ if(this.href!=null) href=this.href; adjustCursor = false; } }else{ curElem = elem; //curElemImage = false; newCursor = DEFAULTCURSOR; } if (href != this.href && !editable){ // reference changed, fire event(s) fireMouseOverHyperlinkEvent(editor, hdoc, href, lastElem); this.href = href; } if (adjustCursor && editor.getCursor() != newCursor){ editor.setCursor(newCursor); } } private void processClick(MouseEvent evt){ WWEEditorPane editor = (WWEEditorPane) evt.getSource(); pt = new Point(evt.getX(), evt.getY()); int pos = editor.viewToModel(pt); if (pos < 0) { return; } boolean editable = editor.isEditable(); Document doc = editor.getDocument(); if (!(doc instanceof WWEHTMLDocument)){ return; } WWEHTMLDocument hdoc = (WWEHTMLDocument) doc; Element elem = hdoc.getCharacterElement(pos); AttributeSet a = elem.getAttributes(); AttributeSet anchor = (AttributeSet)a.getAttribute(HTML.Tag.A); AttributeSet label = (AttributeSet)a.getAttribute(WWEHTML.LABEL); Object o = a.getAttribute(StyleConstants.NameAttribute); HTML.Tag kind = null; if(o instanceof HTML.Tag){ kind = (HTML.Tag) o; } int xStart = editor.getSelectionStart(); int xFinish = editor.getSelectionEnd(); boolean contentSelected = xStart < xFinish; Element tableElement = WWEHTMLUtilities.findElementUp(HTML.Tag.TABLE.toString(), elem); Element orderedListElement = WWEHTMLUtilities.findElementUp(HTML.Tag.OL.toString(), elem); Element unorderedListElement = WWEHTMLUtilities.findElementUp(HTML.Tag.UL.toString(), elem); WWEComponentEvent compEvent = null; //The below if condition blocks decide which event to fire. //The order is **IMP** if(!m_popupTrigger && editable ){ //"Left Click + Editable //Nothing to do here }else if(!m_popupTrigger && !editable ){ //"Left Click + Non-Editable if(getMapHREF(editor, hdoc, elem, a, pos, evt.getX(), evt.getY())!= null || anchor != null){ //"Fire Hyperlink Event: Type HPL_LEFT_CLICKED" compEvent = createHyperlinkEvent(pos, editor, hdoc, evt.getX(), evt.getY()); }else if(label != null){ Component target = null; String forattr = (String)label.getAttribute("for"); if(forattr != null){ target = (Component)hdoc.getFormComponent(forattr); }else{ int fctrlpos = elem.getEndOffset(); target = (Component)hdoc.getFormComponent(fctrlpos + ""); } if(target != null){ if(target instanceof JToggleButton){ JToggleButton jtb = (JToggleButton) target; jtb.doClick(); }else if(target instanceof Box){ //This form control is a Input with type as file Box box = (Box) target; for(int i=0; i<box.getComponentCount(); i++){ target = box.getComponent(i); if(target instanceof JTextField){ target.requestFocus(); } } }else{ target.requestFocus(); } } } }else if(m_popupTrigger && editable ){ //"Right Click + Editable if(/*!contentSelected &&*/ tableElement != null){ //"Fire Table Event: Type TABLE_RIGHT_CLICKED" compEvent = new WWEComponentEvent(editor, WWEComponentEvent.EventType.TABLE_RIGHT_CLICKED, null,"Table Right-Clicked",elem, pt); }else if(kind == HTML.Tag.IMG){ //"Fire Image Event: Type IMAGE_RIGHT_CLICKED" compEvent = new WWEComponentEvent(editor,WWEComponentEvent.EventType.IMAGE_RIGHT_CLICKED, null,"Image Right-Clicked", elem, pt); }else if(anchor != null){ //Remember we cannot handle here the anchor if it has a HMAP //"Fire HyperLink Event: Type HPL_RIGHT_CLICKED" compEvent = createHyperlinkEvent(pos, editor, hdoc, evt.getX(), evt.getY()); }else if(orderedListElement != null || unorderedListElement != null){ //"Fire List Event: Type LIST_RIGHT_CLICKED" compEvent = new WWEComponentEvent(editor,WWEComponentEvent.EventType.LIST_RIGHT_CLICKED, null,"List Right-Clicked", elem, pt); }else{ //This seems to be plain text //"Fire Text Selection Event: Type TEXT_RIGHT_CLICKED" compEvent = new WWEComponentEvent(editor,WWEComponentEvent.EventType.TEXT_RIGHT_CLICKED, null,"Text Right-Clicked", elem, pt); } }else if(m_popupTrigger && !editable ){ //"Right Click + Non-Editable //if(kind == HTML.Tag.IMG){ // //"Fire Image Event: Type IMAGE_RIGHT_CLICKED" // compEvent = new WWEComponentEvent(editor,WWEComponentEvent.EventType.IMAGE_RIGHT_CLICKED, // null,"Image Right-Clicked", elem, pt); //}else if(getMapHREF(editor, hdoc, elem, a, pos, evt.getX(), evt.getY())!= null || anchor != null){ //"Fire HyperLink Event: Type HPL_RIGHT_CLICKED" compEvent = createHyperlinkEvent(pos, editor, hdoc, evt.getX(), evt.getY()); }else if(contentSelected && (pos >= xStart || pos <= xFinish) ){ //This seems to be plain text //"Fire Text Selection Event: Type TEXT_RIGHT_CLICKED" compEvent = new WWEComponentEvent(editor,WWEComponentEvent.EventType.TEXT_RIGHT_CLICKED, null,"Text Right-Clicked", elem, pt); } } if(compEvent != null) editor.fireWWEComponentEvent(compEvent); m_popupTrigger = false; } /** * Creates and returns a new instance of HyperlinkEvent. If * <code>hdoc</code> is a frame document a HTMLFrameHyperlinkEvent * will be created. */ private WWEComponentEvent createHyperlinkEvent(int pos, WWEEditorPane editor, WWEHTMLDocument hdoc, int x, int y){ WWEComponentEvent linkEvent = null; Element elem = hdoc.getCharacterElement(pos); AttributeSet a = elem.getAttributes(); AttributeSet anchor = (AttributeSet)a.getAttribute(HTML.Tag.A); if (anchor == null){ href = getMapHREF(editor, hdoc, elem, a, pos, x, y); }else{ href = (String)anchor.getAttribute(HTML.Attribute.HREF); } if (href != null) { URL u = createURL(hdoc, href); if(u != null){ if (!hdoc.isFrameDocument()) { if(m_popupTrigger){ linkEvent = new WWEComponentEvent(editor, WWEComponentEvent.EventType.HPL_RIGHT_CLICKED, u, href, elem, pt); }else{ linkEvent = new WWEComponentEvent(editor, WWEComponentEvent.EventType.HPL_LEFT_CLICKED, u, href, elem, pt); } } //[PENDING]Tarundeep we need to implement HTMLFrameHyperLinkEvent check it later /* else{ String target = (anchor != null) ?(String)anchor.getAttribute(HTML.Attribute.TARGET) : null; if ((target == null) || (target.equals(""))){ target = "_self"; } linkEvent = new HTMLFrameHyperlinkEvent(editor, HyperlinkEvent. EventType.ACTIVATED, u, href, element, target); } */ } } return linkEvent; } private void fireMouseOverHyperlinkEvent(WWEEditorPane editor, WWEHTMLDocument hdoc, String href, Element lastElem){ //If href points to a unsupported url //e.g. javascript:, mailto: etc //Then the createURL would return a null Value. //In the HyperLink click event we simply ignore this. //But here we would instead send it further and let the WWEComponent //Do the checking and return the href instead to be displayed as //[UNSUPPORTED URL] --> + href if (this.href != null) { // fire an exited event on the old link URL u = createURL(hdoc, this.href); WWEComponentEvent exit = new WWEComponentEvent(editor, WWEComponentEvent.EventType.HPL_EXITED, u, this.href, lastElem, pt); editor.fireWWEComponentEvent(exit); } if (href != null) { URL u = createURL(hdoc, href); WWEComponentEvent entered = new WWEComponentEvent(editor, WWEComponentEvent.EventType.HPL_ENTERED, u, href, curElem, pt); editor.fireWWEComponentEvent(entered); } } private URL createURL(WWEHTMLDocument hdoc, String href){ URL u; try{ URL base = hdoc.getBase(); u = new URL(base, href); // Following is a workaround for 1.2, in which // new URL("file://...", "#...") causes the filename to // be lost. if (href != null && "file".equals(u.getProtocol()) && href.startsWith("#")) { String baseFile = base.getFile(); String newFile = u.getFile(); if (baseFile != null && newFile != null && !newFile.startsWith(baseFile)) { u = new URL(base, baseFile + href); } } } catch (MalformedURLException m) { //This could be a unsupported url //e.g. javascript:, mailto: etc //So we should handle this in the calling method u = null; } //[FARUK] --> //A URL is termed as unsupported if it is not http, https or file. //In Java 1.4.2 we have protocol handlers for the protocols //(doc, file, ftp, gopher, http, jar, mailto, netdoc, systemresource and verbatim) //Now again this is not documented anywhere. //You can see these standard handlers, and associated implementation classes,in the //JDK's RT.JAR file. Look for classes whose fully-qualified name starts with //sun.net.www.protocol.For example,the class sun.net.www.protocol.http.Handler //defines the HTTP protocol handler. Class sun.net.www.protocol.ftp.Handler defines //the FTP protocol handler class. // //Again existance of protocol handler for a protocol does not mean we can support it. //E.g creating a URL object for string with 'mailto' as protocol will not throw the above exception //but this will mess up the Filemanager code. Hence Even if the URL obect is non-null I am adding //the below check to stop the mess which might follow in FileManager if(u != null && !(u.getProtocol().equals("http") || u.getProtocol().equals("https") || u.getProtocol().equals("file"))){ u = null; } return u; } /** * Returns a string anchor if the passed in element has a * USEMAP that contains the passed in location. */ private String getMapHREF(WWEEditorPane editor, WWEHTMLDocument hdoc, Element elem, AttributeSet attr, int offset, int x, int y) { Object useMap = attr.getAttribute(HTML.Attribute.USEMAP); if (useMap != null && (useMap instanceof String)){ WWEMap m = hdoc.getMap((String)useMap); if (m != null && offset < hdoc.getLength()){ Rectangle bounds; TextUI ui = editor.getUI(); try{ Shape lBounds = ui.modelToView(editor, offset, Position.Bias.Forward); Shape rBounds = ui.modelToView(editor, offset + 1, Position.Bias.Backward); bounds = lBounds.getBounds(); bounds.add((rBounds instanceof Rectangle) ? (Rectangle)rBounds : rBounds.getBounds()); }catch(BadLocationException ble){ bounds = null; } if(bounds != null){ AttributeSet area = m.getArea(x - bounds.x, y - bounds.y, bounds.width, bounds.height); if(area != null){ return (String)area.getAttribute(HTML.Attribute. HREF); } } } } return null; } private void setPopupTrigger(boolean val){ if(val) m_popupTrigger = val; } } --- NEW FILE: WWEPageLoadEvent.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.event; import java.net.URL; import java.util.EventObject; /* * WWEPageLoadEvent.java * * @author Faruk Khan * @version 1.0 07 October 2003 */ public class WWEPageLoadEvent extends EventObject{ public WWEPageLoadEvent(Object source, Result result) { this(source, result, null); } public WWEPageLoadEvent(Object source, Result result, Exception exception) { this(source, result, exception, null); } public WWEPageLoadEvent(Object source, Result result, Exception exception, URL requestedURL) { this(source, result, exception, requestedURL, null); } public WWEPageLoadEvent(Object source, Result result, Exception exception, URL requestedURL, URL fetchedURL) { this(source, result, exception, requestedURL, fetchedURL, false); } public WWEPageLoadEvent(Object source, Result result, Exception exception, URL requestedURL, URL fetchedURL, boolean redirected) { this(source, result, exception, requestedURL, fetchedURL, redirected, 0); } public WWEPageLoadEvent(Object source, Result result, Exception exception, URL requestedURL, URL fetchedURL, boolean redirected, double loadingTime) { this(source, result, exception, requestedURL, fetchedURL, redirected, loadingTime, null); } /** * Creates a new object representing a PageLoad event. * * @param source the object responsible for the event * @param result the result of page loading * @param exception the exception if any * @param requestedURL the URL requested by console. * @param fetchedURL the URL fetched by the file manager. * Could differ from requested url if the * connection goes through a redirection. * @param redirected if redirection occurs * @param loadingTime time required for page to load * @param description description about the event */ public WWEPageLoadEvent(Object source, Result result, Exception exception, URL requestedURL, URL fetchedURL, boolean redirected, double loadingTime, String description) { super(source); this.result = result; this.exception = exception; this.requestedURL = requestedURL; this.fetchedURL = fetchedURL; this.redirected = redirected; this.loadingTime = loadingTime; this.description = description; } /** * Gets the type of result. * * @return the result */ public Result getResult() { return result; } /** * Gets the exception stack trace. * * Whenever the result type is Failed, Error, * Canceled this will return a non null exception object * * @return the exception */ public Exception getException(){ return exception; } /** * Get the URL which was requested to be fetced * by the component. * * @return the url */ public URL getRequestedURL() { return requestedURL; } /** * Gets the URL that was finally fetched. * * In case there is a redirection this * will always be different than the * requested url. * * @return the URL */ public URL getFetchedURL() { return fetchedURL; } public boolean Redirected(){ return redirected; } public double getLoadingTime(){ return loadingTime; } public String getDescription(){ return description; } private Result result ; private Exception exception; private URL requestedURL ; private URL fetchedURL ; private boolean redirected ; private double loadingTime ; private String description ; /** * Defines all the Component event types, along * with their string representations, returned by toString(). */ public static final class Result { private Result(String r) { resultString = r; } /** Result Types*/ public static final Result LOADED = new Result("LOADED"); public static final Result RELOADED = new Result("RELOADED"); public static final Result LOADED_FROM_CACHE = new Result("LOADED_FROM_CACHE"); public static final Result FAILED = new Result("FAILED"); public static final Result CANCELED = new Result("CANCELED"); public static final Result ERRORSTREAM = new Result("ERRORSTREAM"); public static final Result LOADING_IGNORED = new Result("LOADING_IGNORED"); /** * Converts the result to a string. * * @return the string */ public String toString() { return resultString; } private String resultString; } } --- NEW FILE: WWEComponentEvent.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.event; import java.awt.Point; import java.net.URL; import java.util.EventObject; import javax.swing.text.Element; /* * WWEComponentEvent.java * * @author Tarundeep Singh * @version 1.0 07 August 2003 */ public class WWEComponentEvent extends EventObject{ /** * Creates a new object representing a Component event. * The other constructor is preferred, as it provides more * information if a URL could not be formed. This constructor * is primarily for backward compatibility. * * @param source the object responsible for the event * @param type the event type * @param u the affected URL */ public WWEComponentEvent(Object source, EventType type, URL u) { this(source, type, u, null); } /** * Creates a new object representing a Component event. * * @param source the object responsible for the event * @param type the event type * @param u the affected URL. This may be null if a valid URL * could not be created. * @param desc the description of the link. This may be useful * when attempting to form a URL resulted in a MalformedURLException. * The description provides the text used when attempting to form the * URL. */ public WWEComponentEvent(Object source, EventType type, URL u, String desc) { this(source, type, u, desc, null,null); } /** * Creates a new object representing a hypertext link event. * * @param source the object responsible for the event * @param type the event type * @param u the affected URL. This may be null if a valid URL * could not be created. * @param desc the description of the link. This may be useful * when attempting to form a URL resulted in a MalformedURLException. * The description provides the text used when attempting to form the * URL. * @param sourceElement Element in the Document representing the * anchor * @since 1.4 */ public WWEComponentEvent(Object source, EventType type, URL u, String desc, Element sourceElement,Point pt) { super(source); this.type = type; this.u = u; this.desc = desc; this.sourceElement = sourceElement; this.pt = pt; } /** * Gets the type of event. * * @return the type */ public EventType getEventType() { return type; } /** * Get the description of the link as a string. * This may be useful if a URL can't be formed * from the description, in which case the associated * URL would be null. */ public String getDescription() { if(u == null){ //This could be a unsupported url //e.g. javascript:, mailto: etc return "[UnSupported URL] --> " + desc; }else{ return desc; } } /** * Gets the URL that the link refers to. * * @return the URL */ public URL getURL() { return u; } public Point getPoint(){ return pt; } /** * Returns the <code>Element</code> that corresponds to the source of the * event. This will typically be an <code>Element</code> representing * an anchor. If a constructur that is used that does not specify a source * <code>Element</code>, or null was specified as the source * <code>Element</code>, this will return null. * * @return Element indicating source of event, or null * @since 1.4 */ public Element getSourceElement() { return sourceElement; } private EventType type; private URL u; private String desc; private Element sourceElement; private Point pt; /** * Defines all the Component event types, along * with their string representations, returned by toString(). */ public static final class EventType { private EventType(String s) { typeString = s; } /** Hyper Link Event Types*/ public static final EventType HPL_LEFT_CLICKED = new EventType("HPL_LEFT_CLICKED"); public static final EventType HPL_RIGHT_CLICKED = new EventType("HPL_RIGHT_CLICKED"); public static final EventType HPL_ENTERED = new EventType("HPL_ENTERED"); public static final EventType HPL_EXITED = new EventType("HPL_EXITED"); /** Table Event Types*/ //public static final EventType TABLE_LEFT_CLICKED = new EventType("TABLE_LEFT_CLICKED"); public static final EventType TABLE_RIGHT_CLICKED = new EventType("TABLE_RIGHT_CLICKED"); /** Image Event Types*/ //public static final EventType IMAGE_LEFT_CLICKED = new EventType("IMAGE_LEFT_CLICKED"); public static final EventType IMAGE_RIGHT_CLICKED = new EventType("IMAGE_RIGHT_CLICKED"); /** List Event Types*/ public static final EventType LIST_RIGHT_CLICKED = new EventType("LIST_RIGHT_CLICKED"); // Text Selection Event Types*/ //public static final EventType TEXT_LEFT_CLICKED = new EventType("TEXT_LEFT_CLICKED"); This is not possible public static final EventType TEXT_RIGHT_CLICKED = new EventType("TEXT_RIGHT_CLICKED"); /** * Converts the type to a string. * * @return the string */ public String toString() { return typeString; } private String typeString; } } |
From: <de...@us...> - 2004-01-05 03:07:04
|
Update of /cvsroot/jxwb/wwe/lib In directory sc8-pr-cvs1:/tmp/cvs-serv15363/lib Added Files: sac.jar flute.jar Log Message: initial load of HTML editor pane and kit --- NEW FILE: sac.jar --- (This appears to be a binary file; contents omitted.) --- NEW FILE: flute.jar --- (This appears to be a binary file; contents omitted.) |
From: <de...@us...> - 2004-01-05 03:07:03
|
Update of /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/debug In directory sc8-pr-cvs1:/tmp/cvs-serv15363/src/com/montarasoftware/wwe/debug Added Files: WWEStreamWriter.java WWEDialogLayout.java WWEHTMLViewDisplayer.java WWEDebug.java WWEDebugInfoDialog.java WWEFindDialog.java WWEHTMLDocDisplay.java Log Message: initial load of HTML editor pane and kit --- NEW FILE: WWEStreamWriter.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.debug; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.io.StringWriter; /** * A class to copy <code>OutputStream</code> * to <code>StringWriter</code> * * @author Faruk m Khan * @version 1.0 04 September 2003 * */ public class WWEStreamWriter extends OutputStream { private StringWriter sw = null; private PrintStream ps = null; private ByteArrayOutputStream os = new ByteArrayOutputStream( 256); public WWEStreamWriter(StringWriter sw){ this.sw = sw; } /** * This will redirect the stream to System.err/System.out as well */ public WWEStreamWriter(StringWriter sw, PrintStream ps){ this.sw = sw; this.ps = ps; } public void write(int b) throws IOException{ os.write(b); } public void flush() throws IOException{ super.flush(); try{ if( sw != null){ sw.write(new String(os.toByteArray())); } if ( ps != null) { ps.write( os.toByteArray()); } os.reset(); }catch ( Exception e){} } } --- NEW FILE: WWEDialogLayout.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.debug; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.awt.LayoutManager; import java.util.Vector; import javax.swing.AbstractButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; public class WWEDialogLayout implements LayoutManager { protected static final int COMP_TWO_COL = 0; protected static final int COMP_BIG = 1; protected static final int COMP_BUTTON = 2; protected int m_divider = -1; protected int m_hGap = 10; protected int m_vGap = 5; protected Vector m_v = new Vector(); public WWEDialogLayout() {} public WWEDialogLayout(int hGap, int vGap) { m_hGap = hGap; m_vGap = vGap; } public void addLayoutComponent(String name, Component comp) {} public void removeLayoutComponent(Component comp) {} public Dimension preferredLayoutSize(Container parent) { m_v.removeAllElements(); int w = 0; int h = 0; int type = -1; for (int k=0 ; k<parent.getComponentCount(); k++) { Component comp = parent.getComponent(k); int newType = getLayoutType(comp); if (k == 0) type = newType; if (type != newType) { Dimension d = preferredLayoutSize(m_v, type); w = Math.max(w, d.width); h += d.height + m_vGap; m_v.removeAllElements(); type = newType; } m_v.addElement(comp); } Dimension d = preferredLayoutSize(m_v, type); w = Math.max(w, d.width); h += d.height + m_vGap; h -= m_vGap; Insets insets = parent.getInsets(); return new Dimension(w+insets.left+insets.right, h+insets.top+insets.bottom); } protected Dimension preferredLayoutSize(Vector v, int type) { int w = 0; int h = 0; switch (type) { case COMP_TWO_COL: int divider = getDivider(v); for (int k=1 ; k<v.size(); k+=2) { Component comp = (Component)v.elementAt(k); Dimension d = comp.getPreferredSize(); w = Math.max(w, d.width); h += d.height + m_vGap; } h -= m_vGap; return new Dimension(divider+w, h); case COMP_BIG: for (int k=0 ; k<v.size(); k++) { Component comp = (Component)v.elementAt(k); Dimension d = comp.getPreferredSize(); w = Math.max(w, d.width); h += d.height + m_vGap; } h -= m_vGap; return new Dimension(w, h); case COMP_BUTTON: Dimension d = getMaxDimension(v); w = d.width + m_hGap; h = d.height; return new Dimension(w*v.size()-m_hGap, h); } throw new IllegalArgumentException("Illegal type "+type); } public Dimension minimumLayoutSize(Container parent) { return preferredLayoutSize(parent); } public void layoutContainer(Container parent) { m_v.removeAllElements(); int type = -1; Insets insets = parent.getInsets(); int w = parent.getWidth() - insets.left - insets.right; int x = insets.left; int y = insets.top; for (int k=0 ; k<parent.getComponentCount(); k++) { Component comp = parent.getComponent(k); int newType = getLayoutType(comp); if (k == 0) type = newType; if (type != newType) { y = layoutComponents(m_v, type, x, y, w); m_v.removeAllElements(); type = newType; } m_v.addElement(comp); } y = layoutComponents(m_v, type, x, y, w); m_v.removeAllElements(); } protected int layoutComponents(Vector v, int type, int x, int y, int w) { switch (type) { case COMP_TWO_COL: int divider = getDivider(v); for (int k=1 ; k<v.size(); k+=2) { Component comp1 = (Component)v.elementAt(k-1); Component comp2 = (Component)v.elementAt(k); Dimension d = comp2.getPreferredSize(); comp1.setBounds(x, y, divider, d.height); comp2.setBounds(x+divider, y, w-divider, d.height); y += d.height + m_vGap; } //y -= m_vGap; return y; case COMP_BIG: for (int k=0 ; k<v.size(); k++) { Component comp = (Component)v.elementAt(k); Dimension d = comp.getPreferredSize(); comp.setBounds(x, y, w, d.height); y += d.height + m_vGap; } //y -= m_vGap; return y; case COMP_BUTTON: Dimension d = getMaxDimension(v); int ww = d.width*v.size() + m_hGap*(v.size()-1); int xx = x + Math.max(0, (w - ww)/2); for (int k=0 ; k<v.size(); k++) { Component comp = (Component)v.elementAt(k); comp.setBounds(xx, y, d.width, d.height); xx += d.width + m_hGap; } return y + d.height; } throw new IllegalArgumentException("Illegal type "+type); } public int getHGap() { return m_hGap; } public int getVGap() { return m_vGap; } public void setDivider(int divider) { if (divider > 0) m_divider = divider; } public int getDivider() { return m_divider; } protected int getDivider(Vector v) { if (m_divider > 0) return m_divider; int divider = 0; for (int k=0 ; k<v.size(); k+=2) { Component comp = (Component)v.elementAt(k); Dimension d = comp.getPreferredSize(); divider = Math.max(divider, d.width); } divider += m_hGap; return divider; } protected Dimension getMaxDimension(Vector v) { int w = 0; int h = 0; for (int k=0 ; k<v.size(); k++) { Component comp = (Component)v.elementAt(k); Dimension d = comp.getPreferredSize(); w = Math.max(w, d.width); h = Math.max(h, d.height); } return new Dimension(w, h); } protected int getLayoutType(Component comp) { if (comp instanceof AbstractButton) return COMP_BUTTON; else if (comp instanceof JPanel || comp instanceof JScrollPane || comp instanceof JTabbedPane) return COMP_BIG; else return COMP_TWO_COL; } public String toString() { return getClass().getName() + "[hgap=" + m_hGap + ",vgap=" + m_vGap + ",divider=" + m_divider + "]"; } } --- NEW FILE: WWEHTMLViewDisplayer.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.debug; import java.io.StringWriter; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import javax.swing.text.View; public class WWEHTMLViewDisplayer { public static void displayViews(JTextComponent comp, StringWriter sw) { displayViews(comp, sw, false); } public static void displayViews(JTextComponent comp, StringWriter sw, boolean displayAttributes) { View rootView = comp.getUI().getRootView(comp); displayView(rootView, 0, comp.getDocument(), sw,displayAttributes); } public static void displayView(View view, int indent, Document doc, StringWriter sw, boolean displayAttributes) { String name = view.getClass().getName(); for (int i = 0; i < indent; i++) { sw.write(" "); } int start = view.getStartOffset(); int end = view.getEndOffset(); sw.write(name + "; offsets [" + start + ", " + end + "]"); sw.write("\n"); if(displayAttributes){ WWEHTMLDocDisplay.displayAttributes(view.getAttributes(), indent, sw); } int viewCount = view.getViewCount(); if (viewCount == 0) { int length = Math.min(32, end - start); try { String txt = doc.getText(start, length); for (int i = 0; i < indent + 1; i++) { sw.write(" "); } sw.write("[" + txt + "]"); sw.write("\n"); } catch (BadLocationException e) { } } else { for (int i = 0; i < viewCount; i++) { displayView(view.getView(i), indent + 1, doc, sw, displayAttributes); } } } } --- NEW FILE: WWEDebug.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.debug; import javax.swing.JFrame; /** * A class to hold debug options * * @author Faruk m Khan * @version 1.0 07 October 2003 * */ public class WWEDebug{ public static final boolean DEBUG = true; public static JFrame parent; public static final boolean HTTP; public static final boolean DATATRANSFER; public static final boolean SYSTEM_PROPERTIES; public static final boolean PARSER_DELEGATOR; public static final boolean PARSER; public static final boolean SAC_CSSBRIDGE; public static final boolean PROXY; //Final varaibles (When not intialised while declaration) //can only be initialised in static blocks. static{ if(DEBUG){ HTTP = false; DATATRANSFER = false; SYSTEM_PROPERTIES = false; PARSER_DELEGATOR = false; PARSER = false; SAC_CSSBRIDGE = false; PROXY = false; }else{ //The below assignments as good as false HTTP = DEBUG; DATATRANSFER = DEBUG; SYSTEM_PROPERTIES = DEBUG; PARSER_DELEGATOR = DEBUG; PARSER = DEBUG; SAC_CSSBRIDGE = DEBUG; PROXY = DEBUG; } } } --- NEW FILE: WWEDebugInfoDialog.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.debug; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Cursor; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import java.io.File; import java.io.FileOutputStream; import java.io.FilterOutputStream; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JEditorPane; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.swing.text.BadLocationException; import javax.swing.text.JTextComponent; /** * A class to display dialog for displaying * debugging information * * @author Faruk m Khan * @version 1.0 04 September 2003 * */ public class WWEDebugInfoDialog extends JFrame { protected boolean m_succeeded = false; protected JTextComponent m_dataPane; protected WWEFindDialog m_findDialog; protected JScrollPane m_scrollpane; protected String m_source; public WWEDebugInfoDialog(JFrame parent, String source, String caption) { this(parent, source, caption, "text/plain"); } public WWEDebugInfoDialog(JFrame parent, String source, String caption, String contentType) { super("Debug Window"); m_source = source; JPanel pp = new JPanel(new BorderLayout()); pp.setBorder(new EmptyBorder(10, 10, 5, 10)); JLabel captionL = new JLabel(caption); Font f = new Font("Monospaced", Font.BOLD, 24); captionL.setFont(f); pp.add(captionL, BorderLayout.NORTH); if(contentType.equals("text/html")){ m_dataPane = new JEditorPane(); JEditorPane m_dataEditorPane = (JEditorPane) m_dataPane; m_dataEditorPane.setContentType(contentType); m_dataEditorPane.setText(source); try { Rectangle r = m_dataEditorPane.modelToView(0); if (r != null) { // the view is visible, scroll it to the // center of the current visible area. Rectangle vis = m_dataEditorPane.getVisibleRect(); //r.y -= (vis.height / 2); r.height = vis.height; m_dataEditorPane.scrollRectToVisible(r); } } catch (BadLocationException ble) { UIManager.getLookAndFeel().provideErrorFeedback(this); //Failed to scroll to the reference } }else{ m_dataPane = new JTextArea(); m_dataPane.setText(source); } m_dataPane.setEditable(false); m_dataPane.setCaretPosition(0); m_dataPane.setFont(new Font("Courier", Font.PLAIN, 12)); m_scrollpane = new JScrollPane(); m_scrollpane.setViewportView(m_dataPane); pp.add(m_scrollpane, BorderLayout.CENTER); JPanel p = new JPanel(new FlowLayout()); JButton bt = new JButton("Ok"); ActionListener lst = new ActionListener() { public void actionPerformed(ActionEvent e) { m_succeeded = true; dispose(); } }; bt.addActionListener(lst); p.add(bt); pp.add(p, BorderLayout.SOUTH); getContentPane().add(pp, BorderLayout.CENTER); JMenuBar menuBar = createMenuBar(); setJMenuBar(menuBar); pack(); setSize(500, 500); setResizable(true); setLocationRelativeTo(parent); } public boolean succeeded() { return m_succeeded; } public String getSource() { return m_dataPane.getText(); } protected JMenuBar createMenuBar(){ JMenuBar menuBar = new JMenuBar(); JMenu mFile = new JMenu("File"); mFile.setMnemonic('f'); AbstractAction saveAction = new AbstractAction("Save..."){ public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); chooser.setSelectedFile(new File("DebugInfo1.txt")); int returnVal = chooser.showSaveDialog(getRootPane().getParent()); if(returnVal == JFileChooser.APPROVE_OPTION){ File saveTo = chooser.getSelectedFile(); WWEDebugInfoDialog.this.setCursor( Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); // Can't do this in thread try { FileOutputStream fous = new FileOutputStream(saveTo); FilterOutputStream flous = new FilterOutputStream(fous); byte b[] = m_source.getBytes(); flous.write(b); flous.close(); fous.close(); flous = null; fous = null; }catch (Exception ex) { System.err.println("Failed to save file"); } WWEDebugInfoDialog.this.setCursor(Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR)); } } }; JMenuItem item = new JMenuItem(saveAction); mFile.add(item); menuBar.add(mFile); JMenu mEdit = new JMenu("Edit"); mEdit.setMnemonic('e'); Action findAction = new AbstractAction("Find..."){ public void actionPerformed(ActionEvent e) { if (m_findDialog==null){ m_findDialog = new WWEFindDialog(WWEDebugInfoDialog.this, m_dataPane); } m_findDialog.show(); } }; item = mEdit.add(findAction); item.setMnemonic('f'); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, KeyEvent.CTRL_MASK)); mEdit.add(item); menuBar.add(mEdit); JMenu mTools = new JMenu("Tools"); mTools.setMnemonic('T'); ItemListener ilist = new ItemListener(){ public void itemStateChanged(ItemEvent e) { showLineNo((e.getStateChange() == ItemEvent.SELECTED)); } }; JCheckBoxMenuItem citem = new JCheckBoxMenuItem("Show Line Nos"); citem.addItemListener(ilist); citem.setEnabled(m_dataPane instanceof JTextArea); mTools.add(citem); menuBar.add(mTools); return menuBar; } protected void showLineNo(boolean show){ if(show && (m_dataPane instanceof JTextArea)){ JTextArea lineNo = new JTextArea(); lineNo.setForeground(Color.red); lineNo.setBackground(Color.gray); String lineNos = ""; for(int i=1; i<=((JTextArea)m_dataPane).getLineCount(); i++){ lineNos = lineNos + i + "\n"; } lineNo.setText(lineNos); m_scrollpane.setRowHeaderView(lineNo); }else{ m_scrollpane.setRowHeader(null); } } } --- NEW FILE: WWEFindDialog.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.debug; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.ButtonGroup; import javax.swing.ButtonModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import javax.swing.border.EtchedBorder; import javax.swing.border.TitledBorder; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.JTextComponent; /** * A class to display Find dialog for searching a * text withing the debug info dialog. * * @author Faruk m Khan * @version 1.0 04 September 2003 * */ public class WWEFindDialog extends JDialog { protected javax.swing.text.JTextComponent m_dataPane; protected JTabbedPane m_tb; protected JTextField m_txtFind1; protected JTextField m_txtFind2; protected Document m_docFind; protected Document m_docReplace; protected ButtonModel m_modelWord; protected ButtonModel m_modelCase; protected ButtonModel m_modelUp; protected ButtonModel m_modelDown; protected int m_searchIndex = -1; protected boolean m_searchUp = false; protected String m_searchData; public static final char[] WORD_SEPARATORS = {' ', '\t', '\n', '\r', '\f', '.', ',', ':', '-', '(', ')', '[', ']', '{', '}', '<', '>', '/', '|', '\\', '\'', '\"'}; public WWEFindDialog(JFrame owner, JTextComponent editor) { super(owner, "Find Text", false); m_dataPane = editor; // "Find" panel JPanel p1 = new JPanel(new BorderLayout()); JPanel pc1 = new JPanel(new BorderLayout()); JPanel pf = new JPanel(); pf.setLayout(new WWEDialogLayout(20, 5)); pf.setBorder(new EmptyBorder(8, 5, 8, 0)); pf.add(new JLabel("Find what:")); m_txtFind1 = new JTextField(); m_docFind = m_txtFind1.getDocument(); pf.add(m_txtFind1); pc1.add(pf, BorderLayout.CENTER); JPanel po = new JPanel(new GridLayout(2, 2, 8, 2)); po.setBorder(new TitledBorder(new EtchedBorder(), "Options")); JCheckBox chkWord = new JCheckBox("Whole words only"); chkWord.setMnemonic('w'); m_modelWord = chkWord.getModel(); po.add(chkWord); ButtonGroup bg = new ButtonGroup(); JRadioButton rdUp = new JRadioButton("Search up"); rdUp.setMnemonic('u'); m_modelUp = rdUp.getModel(); bg.add(rdUp); po.add(rdUp); JCheckBox chkCase = new JCheckBox("Match case"); chkCase.setMnemonic('c'); m_modelCase = chkCase.getModel(); po.add(chkCase); JRadioButton rdDown = new JRadioButton("Search down", true); rdDown.setMnemonic('d'); m_modelDown = rdDown.getModel(); bg.add(rdDown); po.add(rdDown); pc1.add(po, BorderLayout.SOUTH); p1.add(pc1, BorderLayout.CENTER); JPanel p01 = new JPanel(new FlowLayout()); JPanel p = new JPanel(new GridLayout(2, 1, 2, 8)); ActionListener findAction = new ActionListener() { public void actionPerformed(ActionEvent e) { findNext(false); } }; JButton btFind = new JButton("Find Next"); btFind.addActionListener(findAction); btFind.setMnemonic('f'); p.add(btFind); getRootPane().setDefaultButton(btFind); ActionListener closeAction = new ActionListener() { public void actionPerformed(ActionEvent e) { setVisible(false); } }; JButton btClose = new JButton("Close"); btClose.addActionListener(closeAction); btClose.setDefaultCapable(true); p.add(btClose); p01.add(p); p1.add(p01, BorderLayout.EAST); JPanel pp = new JPanel(new BorderLayout()); pp.setBorder(new EmptyBorder(5,5,5,5)); pp.add(p1, BorderLayout.CENTER); getContentPane().add(pp, BorderLayout.CENTER); pack(); setResizable(false); setLocationRelativeTo(owner); m_txtFind1.requestFocus(); WindowListener flst = new WindowAdapter() { public void windowActivated(WindowEvent e) { m_searchIndex = -1; } public void windowDeactivated(WindowEvent e) { m_searchData = null; } }; addWindowListener(flst); } public int findNext(boolean showWarnings) { int pos = m_dataPane.getCaretPosition(); if (m_modelUp.isSelected() != m_searchUp) { m_searchUp = m_modelUp.isSelected(); m_searchIndex = -1; } if (m_searchIndex == -1) { try { Document doc = m_dataPane.getDocument(); if (m_searchUp) m_searchData = doc.getText(0, pos); else m_searchData = doc.getText(pos, doc.getLength()-pos); m_searchIndex = pos; } catch (BadLocationException ex) { warning(ex.toString()); return -1; } } String key = ""; try { key = m_docFind.getText(0, m_docFind.getLength()); } catch (BadLocationException ex) {} if (key.length()==0) { warning("Please enter the target to search"); return -1; } if (!m_modelCase.isSelected()) { m_searchData = m_searchData.toLowerCase(); key = key.toLowerCase(); } if (m_modelWord.isSelected()) { for (int k=0; k<WORD_SEPARATORS.length; k++) { if (key.indexOf(WORD_SEPARATORS[k]) >= 0) { warning("The text target contains an illegal "+ "character \'"+WORD_SEPARATORS[k]+"\'"); return -1; } } } int xStart = -1; int xFinish = -1; while (true) { if (m_searchUp) xStart = m_searchData.lastIndexOf(key, pos-1); else xStart = m_searchData.indexOf(key, pos-m_searchIndex); if (xStart < 0) { if (showWarnings) warning("Text not found"); return 0; } xFinish = xStart+key.length(); if (m_modelWord.isSelected()) { boolean s1 = xStart>0; boolean b1 = s1 && !isSeparator(m_searchData.charAt( xStart-1)); boolean s2 = xFinish<m_searchData.length(); boolean b2 = s2 && !isSeparator(m_searchData.charAt( xFinish)); if (b1 || b2) // Not a whole word { if (m_searchUp && s1) // Can continue up { pos = xStart; continue; } if (!m_searchUp && s2) // Can continue down { pos = xFinish+1; continue; } // Found, but not a whole word, and we cannot continue if (showWarnings) warning("Text not found"); return 0; } } break; } if (!m_searchUp) { xStart += m_searchIndex; xFinish += m_searchIndex; } setSelection(xStart, xFinish, m_searchUp); return 1; } public static boolean isSeparator(char ch) { for (int k=0; k<WORD_SEPARATORS.length; k++) if (ch == WORD_SEPARATORS[k]) return true; return false; } protected void warning(String message) { JOptionPane.showMessageDialog(this, message, "Find Text", JOptionPane.INFORMATION_MESSAGE); } public void setSelection(int xStart, int xFinish, boolean moveUp) { if (moveUp) { m_dataPane.setCaretPosition(xFinish); m_dataPane.moveCaretPosition(xStart); } else{ m_dataPane.select(xStart, xFinish); } } } --- NEW FILE: WWEHTMLDocDisplay.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.debug; import java.io.StringWriter; import java.util.Enumeration; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.Element; import javax.swing.text.JTextComponent; public class WWEHTMLDocDisplay { public static void displayAttributes(AttributeSet a, int indent, StringWriter sw) { if (a == null) return; a = a.copyAttributes(); Enumeration x = a.getAttributeNames(); for (int i = 0; i < indent; i++) { sw.write(" "); } if (x != null) { sw.write("ATTRIBUTES:"); sw.write("\n"); while (x.hasMoreElements()) { for (int i = 0; i < indent; i++) { sw.write(" "); } Object attr = x.nextElement(); sw.write(" (" + attr + ", " + a.getAttribute(attr) + ")" + " [" + getShortClassName(attr.getClass()) + "/" + getShortClassName(a.getAttribute(attr).getClass()) + "] "); sw.write("\n"); } } else { sw.write("No attributes"); sw.write("\n"); } if (a.getResolveParent() != null) { displayAttributes(a.getResolveParent().copyAttributes(), indent + 1, sw); } } public static void displayModel(JTextComponent comp, StringWriter sw) { Document doc = comp.getDocument(); Element e = doc.getDefaultRootElement(); displayElement(doc, e, 0, sw); } public static void displayElement(Document doc, Element e, int indent, StringWriter sw) { for (int i = 0; i < indent; i++) { sw.write(" "); } sw.write("===== Element Class: " + getShortClassName(e.getClass())); sw.write("\n"); for (int i = 0; i < indent; i++) { sw.write(" "); } int startOffset = e.getStartOffset(); int endOffset = e.getEndOffset(); sw.write("Offsets [" + startOffset + ", " + endOffset + "]"); sw.write("\n"); AttributeSet a = e.getAttributes(); Enumeration x = a.getAttributeNames(); for (int i = 0; i < indent; i++) { sw.write(" "); } sw.write("ATTRIBUTES:"); sw.write("\n"); while (x.hasMoreElements()) { for (int i = 0; i < indent; i++) { sw.write(" "); } Object attr = x.nextElement(); sw.write(" (" + attr + ", " + a.getAttribute(attr) + ")" + " [" + getShortClassName(attr.getClass()) + "/" + getShortClassName(a.getAttribute(attr).getClass()) + "] "); sw.write("\n"); } // Display the text for a leaf element if (e.isLeaf()) { try { String str = doc.getText(startOffset, endOffset - startOffset); if (str.length() > 40) { str = str.substring(0, 40); } if (str.length() > 0) { for (int i = 0; i < indent; i++) { sw.write(" "); } sw.write("[" + str + "]"); sw.write("\n"); } } catch (BadLocationException ex) { } } // Display child elements int count = e.getElementCount(); for (int i = 0; i < count ; i++) { displayElement(doc, e.getElement(i), indent + 1, sw); } } public static String getShortClassName(Class clazz) { String className = clazz.getName(); return className.substring(className.lastIndexOf(".") + 1); } } |
Update of /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/callback In directory sc8-pr-cvs1:/tmp/cvs-serv15363/src/com/montarasoftware/wwe/callback Added Files: WWEFontDialog.java WWEOpenList.java WWETableConfigurationVO.java WWEListDialog.java WWEColorPanel.java WWEColorComboRenderer.java WWEAbstractCallbackRoutine.java WWECallbackRoutine.java WWEImageDialog.java WWETableDialog.java WWELinkDialog.java WWEListConfigurationVO.java Log Message: initial load of HTML editor pane and kit --- NEW FILE: WWEFontDialog.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.callback; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Vector; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.border.EtchedBorder; import javax.swing.border.LineBorder; import javax.swing.border.TitledBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.text.AttributeSet; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.html.HTML; import com.montarasoftware.wwe.WWEConstants; import com.montarasoftware.wwe.WWEHTMLDocument; import com.montarasoftware.wwe.util.WWEHTMLUtilities; //import com.montarasoftware.alchemy.client.java.comp.WWECSS; /** * This dialog acts as font properties editor and previewer for out HTML. * * @author Faruk m Khan * @author Amit Ahuja * @version 1.0 14 August 2003 */ public class WWEFontDialog extends WWEAbstractCallbackRoutine implements WWEConstants { protected WWEOpenList m_lstFontName; protected WWEOpenList m_lstFontSize; protected JCheckBox m_chkBold; protected JCheckBox m_chkItalic; protected JCheckBox m_chkUnderline; /*private String m_fontName; private String m_fontSize; private boolean m_isBold; private boolean m_isItalic; private String m_styleClass; */ private boolean m_isUnderLine; private Color m_fontColor; //[FARUK]-> According to the current req specification // we don't need them here I am commenting them because // there functionality is buggy. We can decomment to whole // code relating to this attributes once we have removed // the bugs related to these //protected JCheckBox m_chkStrikethrough; //protected JCheckBox m_chkSubscript; //protected JCheckBox m_chkSuperscript; protected WWEColorPanel m_pnlColor; protected JLabel m_preview; private String m_previewText; private Vector m_FStyleNames; protected WWEHTMLDocument m_doc; protected JComboBox m_styleComboBox; public WWEFontDialog(JFrame parent, WWEHTMLDocument doc, String[] names, String[] sizes) { super(parent, "Font", true); m_doc=doc; JPanel pp = new JPanel(); pp.setBorder(new EmptyBorder(5,5,5,5)); pp.setLayout(new BoxLayout(pp, BoxLayout.Y_AXIS)); //CSS Combo m_FStyleNames = WWEHTMLUtilities.getStyleNamesForTag(m_doc.getStyleSheet(),CFONTSTYLE); JPanel p = new JPanel(new GridLayout(1, 2, 2, 2)); p.setBorder(new TitledBorder(new EtchedBorder(), "CSS Style")); JLabel styleLabel = new JLabel("CSS style"); p.add(styleLabel); m_styleComboBox = new JComboBox(m_FStyleNames); styleLabel.setLabelFor(m_styleComboBox); p.add(m_styleComboBox); pp.add(p); p = new JPanel(new GridLayout(1, 2, 10, 2)); p.setBorder(new TitledBorder(new EtchedBorder(), "Font")); m_lstFontName = new WWEOpenList(names, "Name:"); p.add(m_lstFontName); m_lstFontSize = new WWEOpenList(sizes, "Size:"); p.add(m_lstFontSize); pp.add(p); //p = new JPanel(new GridLayout(2, 3, 10, 5)); p = new JPanel(new GridLayout(1, 3, 10, 5)); p.setBorder(new TitledBorder(new EtchedBorder(), "Effects")); m_chkBold = new JCheckBox("Bold"); p.add(m_chkBold); m_chkItalic = new JCheckBox("Italic"); p.add(m_chkItalic); m_chkUnderline = new JCheckBox("Underline"); p.add(m_chkUnderline); pp.add(p); pp.add(Box.createVerticalStrut(5)); p = new JPanel(new BorderLayout()); JLabel colorLabel = new JLabel("Font Color:"); p.add(colorLabel, BorderLayout.WEST); p.setBorder(new TitledBorder(new EtchedBorder(), "Color")); m_pnlColor = new WWEColorPanel(Color.black); p.add(m_pnlColor, BorderLayout.EAST); pp.add(p); ListSelectionListener lsel = new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { updatePreview(); } }; m_lstFontName.addListSelectionListener(lsel); m_lstFontSize.addListSelectionListener(lsel); ActionListener lst = new ActionListener() { public void actionPerformed(ActionEvent e) { updatePreview(); } }; m_chkBold.addActionListener(lst); m_chkItalic.addActionListener(lst); m_chkUnderline.addActionListener(lst); WWEColorPanel.WWEColorPanelListener cpl = new WWEColorPanel.WWEColorPanelListener(){ public void colorChanged(WWEColorPanel.WWEColorPanelEvent e){ updatePreview(); } }; m_pnlColor.addColorPanelListener(cpl); p = new JPanel(new BorderLayout()); p.setBorder(new TitledBorder(new EtchedBorder(), "Preview")); m_preview = new JLabel("Preview Font", JLabel.CENTER); m_preview.setBackground(Color.white); m_preview.setForeground(Color.black); m_preview.setOpaque(true); m_preview.setBorder(new LineBorder(Color.black)); m_preview.setPreferredSize(new Dimension(120, 40)); p.add(m_preview, BorderLayout.CENTER); pp.add(p); m_previewText=m_preview.getText(); p = new JPanel(new FlowLayout()); JPanel p1 = new JPanel(new GridLayout(1, 2, 10, 0)); JButton btOK = new JButton("OK"); lst = new ActionListener() { public void actionPerformed(ActionEvent e) { m_succeeded = true; dispose(); } }; btOK.addActionListener(lst); p1.add(btOK); JButton btCancel = new JButton("Cancel"); lst = new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }; btCancel.addActionListener(lst); p1.add(btCancel); p.add(p1); pp.add(p); getContentPane().add(pp, BorderLayout.CENTER); pack(); setResizable(false); setLocationRelativeTo(parent); } /** * setting dialog values * * @author amit ahuja * **/ public void setValues(String fName, String fSize, boolean bold, boolean italic, boolean ULine,String styleClass, Color fontColor) { /*m_fontName=fName; m_fontSize=fSize; m_isBold=bold; m_isItalic=italic; m_styleClass=styleClass;*/ m_isUnderLine=ULine; m_fontColor=fontColor; m_lstFontName.setSelected(fName); m_lstFontSize.setSelected(fSize); m_chkBold.setSelected(bold); m_chkItalic.setSelected(italic); m_chkUnderline.setSelected(ULine); if( styleClass==null || styleClass.equalsIgnoreCase("") ) m_styleComboBox.setSelectedIndex(0); else m_styleComboBox.setSelectedItem(styleClass); if(fontColor!=null) m_pnlColor.setColor(fontColor); else m_pnlColor.setColor(Color.black); updatePreview(); } public void setAttributes(AttributeSet a) { m_attributes = new SimpleAttributeSet(a); } public AttributeSet getAttributes() { if (m_attributes == null) return null; StyleConstants.setFontFamily(m_attributes, m_lstFontName.getSelected()); StyleConstants.setFontSize(m_attributes, m_lstFontSize.getSelectedInt()); StyleConstants.setBold(m_attributes, m_chkBold.isSelected()); StyleConstants.setItalic(m_attributes, m_chkItalic.isSelected()); if( m_isUnderLine!=m_chkUnderline.isSelected() ) StyleConstants.setUnderline(m_attributes, m_chkUnderline.isSelected()); if(!m_fontColor.toString().equals(m_pnlColor.getColor().toString())) StyleConstants.setForeground(m_attributes, m_pnlColor.getColor()); String styleClass = (String)m_styleComboBox.getSelectedItem(); if(!styleClass.equals("Standard")){ m_attributes.addAttribute(HTML.Attribute.CLASS, styleClass); m_attributes.addAttribute(HTML.Tag.SPAN,m_attributes); } return m_attributes; } public boolean succeeded() { return m_succeeded; } protected void updatePreview() { String name = m_lstFontName.getSelected(); int size = m_lstFontSize.getSelectedInt(); if (size <= 0) size=12; int style = Font.PLAIN; if (m_chkBold.isSelected()) style |= Font.BOLD; if (m_chkItalic.isSelected()) style |= Font.ITALIC; if (m_chkUnderline.isSelected()) m_preview.setText("<html><u>"+m_previewText+"</u></html>"); else m_preview.setText(m_previewText); // Bug Alert! This doesn't work if only style is changed. Font fn = new Font(name, style, size); m_preview.setFont(fn); Color c = m_pnlColor.getColor(); m_preview.setForeground(c); m_preview.repaint(); } } --- NEW FILE: WWEOpenList.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.callback; import java.awt.Dimension; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.ListModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; /** * This component is a editable combobox that always * keeps their drop-down list open. * * @author Faruk m Khan * @version 1.0 14 August 2003 */ class WWEOpenList extends JPanel implements ListSelectionListener, ActionListener { protected JLabel m_title; protected JTextField m_text; protected JList m_list; protected JScrollPane m_scroll; public WWEOpenList(String[] data, String title) { setLayout(null); m_title = new JLabel(title, JLabel.LEFT); add(m_title); m_text = new JTextField(); m_text.addActionListener(this); add(m_text); m_list = new JList(data); m_list.setVisibleRowCount(4); m_list.addListSelectionListener(this); m_list.setFont(m_text.getFont()); m_scroll = new JScrollPane(m_list); add(m_scroll); } public void setSelected(String sel) { m_list.setSelectedValue(sel, true); m_text.setText(sel); } public String getSelected() { return m_text.getText(); } public void setSelectedInt(int value) { setSelected(Integer.toString(value)); } public int getSelectedInt() { try { return Integer.parseInt(getSelected()); } catch (NumberFormatException ex) { return -1; } } public void valueChanged(ListSelectionEvent e) { Object obj = m_list.getSelectedValue(); if (obj != null) m_text.setText(obj.toString()); } public void actionPerformed(ActionEvent e) { ListModel model = m_list.getModel(); String key = m_text.getText().toLowerCase(); for (int k=0; k<model.getSize(); k++) { String data = (String)model.getElementAt(k); if (data.toLowerCase().startsWith(key)) { m_list.setSelectedValue(data, true); break; } } } public void addListSelectionListener(ListSelectionListener lst) { m_list.addListSelectionListener(lst); } public Dimension getPreferredSize() { Insets ins = getInsets(); Dimension d1 = m_title.getPreferredSize(); Dimension d2 = m_text.getPreferredSize(); Dimension d3 = m_scroll.getPreferredSize(); int w = Math.max(Math.max(d1.width, d2.width), d3.width); int h = d1.height + d2.height + d3.height; return new Dimension(w+ins.left+ins.right, h+ins.top+ins.bottom); } public Dimension getMaximumSize() { Insets ins = getInsets(); Dimension d1 = m_title.getMaximumSize(); Dimension d2 = m_text.getMaximumSize(); Dimension d3 = m_scroll.getMaximumSize(); int w = Math.max(Math.max(d1.width, d2.width), d3.width); int h = d1.height + d2.height + d3.height; return new Dimension(w+ins.left+ins.right, h+ins.top+ins.bottom); } public Dimension getMinimumSize() { Insets ins = getInsets(); Dimension d1 = m_title.getMinimumSize(); Dimension d2 = m_text.getMinimumSize(); Dimension d3 = m_scroll.getMinimumSize(); int w = Math.max(Math.max(d1.width, d2.width), d3.width); int h = d1.height + d2.height + d3.height; return new Dimension(w+ins.left+ins.right, h+ins.top+ins.bottom); } public void doLayout() { Insets ins = getInsets(); Dimension d = getSize(); int x = ins.left; int y = ins.top; int w = d.width-ins.left-ins.right; int h = d.height-ins.top-ins.bottom; Dimension d1 = m_title.getPreferredSize(); m_title.setBounds(x, y, w, d1.height); y += d1.height; Dimension d2 = m_text.getPreferredSize(); m_text.setBounds(x, y, w, d2.height); y += d2.height; m_scroll.setBounds(x, y, w, h-y); } } --- NEW FILE: WWETableConfigurationVO.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.callback; import java.util.Vector; /** * A Component for data navigation in Call Back Routine. * * @author Amit Ahuja * * @version 1.0 01 October 2003 * */ public class WWETableConfigurationVO { private int m_rowCount; private int m_colCount; private int m_cellSpacing; private int m_cellPadding; private int m_borderWidth; private int m_tableWidth; private Vector m_unit; public WWETableConfigurationVO() { } public void setRowCount(int p_rowCount) { m_rowCount=p_rowCount; } public int getRowCount() { return m_rowCount; } public void setColCount(int p_colCount) { m_colCount=p_colCount; } public int getColCount() { return m_colCount; } public void setCellSpacing(int p_cellSpacing) { m_cellSpacing=p_cellSpacing; } public int getCellSpacing() { return m_cellSpacing; } public void setCellPadding(int p_cellPadding) { m_cellPadding=p_cellPadding; } public int getCellPadding() { return m_cellPadding; } public void setBorderWidth(int p_borderWidth) { m_borderWidth=p_borderWidth; } public int getBorderWidth() { return m_borderWidth; } public void setTableWidth(int p_tableWidth) { m_tableWidth=p_tableWidth; } public int getTableWidth() { return m_tableWidth; } public void setUnit(Vector p_unit) { m_unit=p_unit; } public Vector getUnit() { return m_unit; } } --- NEW FILE: WWEListDialog.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.callback; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.Vector; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import javax.swing.SpringLayout; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.text.AttributeSet; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.html.HTML; import com.montarasoftware.wwe.WWEHTMLDocument; import com.montarasoftware.wwe.util.WWEHTMLUtilities; import com.montarasoftware.wwe.util.WWESpringUtilities; /** * Dialog to create and edit Html List. * * @author Amit Ahuja * */ public class WWEListDialog extends WWEAbstractCallbackRoutine implements ChangeListener, ItemListener{ protected WWEHTMLDocument m_doc; protected JComboBox m_styleComboBox; protected JComboBox m_typeComboBox; protected JSpinner m_startSpn; protected JCheckBox m_compactCheckBox; protected JCheckBox m_listOffCheckBox; protected JButton m_btOK; protected boolean m_mode; private int m_ulStartIndex; private Vector m_olStyleNames; private Vector m_ulStyleNames; private String listTag; /** list tag from setValue/getValue (UL or OL) */ public WWEListDialog(JFrame parent, WWEHTMLDocument doc,boolean mode){ super(parent, "List", true); m_doc = doc; m_mode=mode; JPanel panel = new JPanel(new GridLayout(0,1)); //mainPanel part of panel center component of Dialog JPanel mainPanel = new JPanel(new SpringLayout()); //Type Combo JLabel typeLabel = new JLabel("Type"); mainPanel.add(typeLabel); m_typeComboBox = new JComboBox(); typeLabel.setLabelFor(m_typeComboBox); m_typeComboBox.addItemListener(this); mainPanel.add(m_typeComboBox); //Start Field JLabel startLabel = new JLabel("Start"); mainPanel.add(startLabel); m_startSpn = new JSpinner(new SpinnerNumberModel( new Integer(0), new Integer(0), null, new Integer(1))); startLabel.setLabelFor(m_startSpn); m_startSpn.addChangeListener(this); mainPanel.add(m_startSpn); //CSS Combo JLabel styleLabel = new JLabel("CSS style"); mainPanel.add(styleLabel); m_ulStyleNames = WWEHTMLUtilities.getStyleNamesForTag(m_doc.getStyleSheet(),HTML.Tag.UL.toString()); m_olStyleNames = WWEHTMLUtilities.getStyleNamesForTag(m_doc.getStyleSheet(),HTML.Tag.OL.toString()); m_styleComboBox = new JComboBox(); styleLabel.setLabelFor(m_styleComboBox); mainPanel.add(m_styleComboBox); JLabel compactLabel = new JLabel("Compact"); mainPanel.add(compactLabel); m_compactCheckBox = new JCheckBox(); compactLabel.setLabelFor(m_compactCheckBox); mainPanel.add(m_compactCheckBox); if(!m_mode){ JLabel listOffLabel = new JLabel("List Off"); mainPanel.add(listOffLabel); m_listOffCheckBox = new JCheckBox(); listOffLabel.setLabelFor(m_listOffCheckBox); m_listOffCheckBox.addChangeListener(this); mainPanel.add(m_listOffCheckBox); WWESpringUtilities.makeCompactGrid(mainPanel, 5, 2, //rows, cols 15, 15, //initX, initY 6, 6, false); //xPad, yPad, honour Preferred width of second column } else if (m_mode){ WWESpringUtilities.makeCompactGrid(mainPanel, 4, 2, //rows, cols 15, 15, //initX, initY 6, 6, false); //xPad, yPad, honour Preferred width of second column } panel.add(mainPanel); getContentPane().add(panel, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new FlowLayout()); JPanel p1 = new JPanel(new GridLayout(1, 2, 10, 0)); m_btOK = new JButton("OK"); ActionListener lst = new ActionListener() { public void actionPerformed(ActionEvent e) { m_succeeded = true; dispose(); } }; m_btOK.addActionListener(lst); m_btOK.setEnabled(false); p1.add(m_btOK); JButton btCancel = new JButton("Cancel"); lst = new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }; btCancel.addActionListener(lst); p1.add(btCancel); buttonPanel.add(p1); getContentPane().add(buttonPanel, BorderLayout.SOUTH); pack(); setResizable(false); setLocationRelativeTo(parent); } /** * setting the Default Values * * @author amit ahuja * */ public void setDefaults(WWEListConfigurationVO listObj){ if(listObj.getOlTypes().size()>0 || listObj.getUlTypes().size()>0) m_typeComboBox.removeAllItems(); m_ulStartIndex=(listObj.getOlTypes().size()); fillOlStyles(); for(int i=0;i<listObj.getOlTypes().size();i++) m_typeComboBox.addItem(listObj.getOlTypes().elementAt(i)); for(int i=0;i<listObj.getUlTypes().size();i++) m_typeComboBox.addItem(listObj.getUlTypes().elementAt(i)); m_startSpn.setValue(new Integer(listObj.getListStart())); if(listObj.getCompact().equals("true")) m_compactCheckBox.setSelected(true); else m_compactCheckBox.setSelected(false); } public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { validateDialog(); validate(); repaint(); } } public void stateChanged(ChangeEvent e) { setCursor(Cursor.getPredefinedCursor( Cursor.WAIT_CURSOR)); try { validateDialog(); validate(); repaint(); }catch (Exception ex) { ex.printStackTrace(); }finally { setCursor(Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR)); } } private void validateDialog(){ if(!m_mode){ if(m_listOffCheckBox.isSelected()){ m_styleComboBox.setSelectedIndex(0); m_styleComboBox.setEnabled(false); m_typeComboBox.setSelectedIndex(0); m_startSpn.setValue(new Integer(0)); m_compactCheckBox.setSelected(false); m_typeComboBox.setEnabled(false); m_startSpn.setEnabled(false); m_compactCheckBox.setEnabled(false); } else{ m_styleComboBox.setEnabled(true); m_typeComboBox.setEnabled(true); m_startSpn.setEnabled(true); m_compactCheckBox.setEnabled(true); } } if(m_typeComboBox.getSelectedIndex()>m_ulStartIndex-1){ m_startSpn.setValue(new Integer(0)); m_startSpn.setEnabled(false); m_btOK.setEnabled(true); fillUlStyles(); } else if(m_typeComboBox.getSelectedIndex()>0){ m_startSpn.setEnabled(true); m_btOK.setEnabled(true); fillOlStyles(); } else if(m_typeComboBox.getSelectedIndex()==0 && m_startSpn.getValue().toString().equals("0")){ if(!m_mode){ if(!m_listOffCheckBox.isSelected()) m_btOK.setEnabled(false); else m_btOK.setEnabled(true); } else m_btOK.setEnabled(false); } if(!m_startSpn.getValue().toString().equals("0") ){ m_btOK.setEnabled(true); fillOlStyles(); } } private void fillOlStyles(){ m_styleComboBox.removeAllItems(); for(int i=0;i<m_olStyleNames.size();i++) m_styleComboBox.addItem(m_olStyleNames.elementAt(i)); } private void fillUlStyles(){ m_styleComboBox.removeAllItems(); for(int i=0;i<m_ulStyleNames.size();i++) m_styleComboBox.addItem(m_ulStyleNames.elementAt(i)); } public AttributeSet getAttributes(){ String start = m_startSpn.getValue().toString(); setTagFromType(); SimpleAttributeSet attr = new SimpleAttributeSet(); int index = m_typeComboBox.getSelectedIndex(); if(m_typeComboBox.getSelectedItem().toString().equals("")){ attr.addAttribute(HTML.Attribute.TYPE, ""); if(!start.equals("0")) attr.addAttribute(HTML.Attribute.START, start); } else if(index > m_ulStartIndex-1) { attr.addAttribute(HTML.Attribute.TYPE, m_typeComboBox.getSelectedItem().toString()); } else if(index > 0) { if(!start.equals("0")) attr.addAttribute(HTML.Attribute.START, start); if(!m_typeComboBox.getSelectedItem().toString().equals("")) attr.addAttribute(HTML.Attribute.TYPE, m_typeComboBox.getSelectedItem().toString()); } String styleClass = (String)m_styleComboBox.getSelectedItem(); if(!styleClass.equals("Standard")){ attr.addAttribute(HTML.Attribute.CLASS, styleClass); } if(m_compactCheckBox.isSelected()) attr.addAttribute(HTML.Attribute.COMPACT, "true"); return attr; } public String generateHTML() { StringBuffer buff = new StringBuffer(); String start = m_startSpn.getValue().toString(); int index = m_typeComboBox.getSelectedIndex(); if(m_typeComboBox.getSelectedItem().toString().equals("") ){ buff.append("<ol"); if(!start.equals("0")) buff.append(" start=\"").append(start).append("\""); } else if(index > m_ulStartIndex-1) { buff.append("<ul"); buff.append(" type=\"").append(m_typeComboBox.getSelectedItem().toString()).append("\""); } else if(index > 0) { buff.append("<ol"); buff.append(" type=\"").append(m_typeComboBox.getSelectedItem().toString()).append("\""); if(!start.equals("0") ) buff.append(" start=\"").append(start).append("\""); } if(m_compactCheckBox.isSelected()) buff.append(" compact=\"").append("true").append("\""); buff.append(">\n"); buff.append("<li>\n"); buff.append("</li>\n"); if(index > m_ulStartIndex-1) { buff.append("</ul>\n"); } else if(index > 0) { buff.append("</ol>\n"); } else if(m_typeComboBox.getSelectedItem().toString().equals("") && !start.equals("0")){ buff.append("</ol>"); } buff.append("<p></p>"); return buff.toString(); } /** * get the list tag currently selected * * @return the list tag currently selected or null, if no list is selected */ public String getListTag() { return listTag; } public void setAttributes(AttributeSet attr){ listTag = attr.getAttribute(StyleConstants.NameAttribute).toString(); if(attr.isDefined(HTML.Attribute.TYPE)) m_typeComboBox.setSelectedItem(attr.getAttribute(HTML.Attribute.TYPE).toString()); if(attr.isDefined(HTML.Attribute.START)) m_startSpn.setValue(new Integer(attr.getAttribute(HTML.Attribute.START).toString())); if( !attr.isDefined(HTML.Attribute.TYPE) && !attr.isDefined(HTML.Attribute.START) ) { if(listTag.equalsIgnoreCase(HTML.Tag.OL.toString())) m_startSpn.setValue(new Integer(1)); else if(listTag.equalsIgnoreCase(HTML.Tag.UL.toString())) m_typeComboBox.setSelectedIndex(m_ulStartIndex); } if(listTag.equalsIgnoreCase(HTML.Tag.OL.toString())) fillOlStyles(); else if(listTag.equalsIgnoreCase(HTML.Tag.UL.toString())) fillUlStyles(); if(attr.isDefined(HTML.Attribute.CLASS)){ m_styleComboBox.setSelectedItem(attr.getAttribute(HTML.Attribute.CLASS)); }else{ m_styleComboBox.setSelectedIndex(0); } if(attr.isDefined(HTML.Attribute.COMPACT)){ System.out.println(" got compact "); if( attr.getAttribute(HTML.Attribute.COMPACT).toString().equals("true")){ System.out.println(" got compact true "); m_compactCheckBox.setSelected(true); } else if( attr.getAttribute(HTML.Attribute.COMPACT).toString().equals("false") || attr.getAttribute(HTML.Attribute.COMPACT).toString().equals("")) m_compactCheckBox.setSelected(false); } else m_compactCheckBox.setSelected(false); if(m_typeComboBox.getSelectedIndex() > m_ulStartIndex-1) m_startSpn.setEnabled(false); } /** * translate list types into list * tag (UL or OL). */ private void setTagFromType() { int index = m_typeComboBox.getSelectedIndex(); String start = m_startSpn.getValue().toString(); if(!m_mode){ if(m_listOffCheckBox.isSelected()){ listTag=null; return; } } if(index > m_ulStartIndex-1) { listTag = HTML.Tag.UL.toString(); } else if(index > 0) { listTag = HTML.Tag.OL.toString(); } else { if(!start.equals("0")) listTag = HTML.Tag.OL.toString(); else listTag = null; } } } --- NEW FILE: WWEColorPanel.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.callback; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Enumeration; import java.util.EventListener; import java.util.EventObject; import java.util.Vector; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JPanel; import javax.swing.JTextField; /** * This class provides a Color Chooser JButton. * * @author Faruk m Khan * @version 1.0 17 September 2003 */ class WWEColorPanel extends JPanel implements ActionListener{ private Color m_color; /** default color */ private Color defaultColor; /** the component showing the chosen color code*/ JTextField m_colorCode; ColorButton m_browseButton; public WWEColorPanel(Color col){ setLayout(null); this.defaultColor = col; m_colorCode = new JTextField(0); //We need this to have a Monospaced font. //Else it will keep resizing the text field //If it is annoying do the below //m_colorCode.setFont(new Font("Monospaced", Font.PLAIN, 11)); //Cannot make it enabled false //since this will make it gray //m_colorCode.setEnabled(false); add(m_colorCode); m_browseButton = new ColorButton(); m_browseButton.addActionListener(this); add(m_browseButton); setColor(col); } /** * get the selected color * * @return the selected color */ public Color getColor() { return m_color; } /** * set the selected color * * @param color the selected color */ public void setColor(Color color) { m_color = color; String strColor = "#" + Integer.toHexString(color.getRGB()).substring(2); m_colorCode.setText(strColor); fireColorChanged(); } /** * open a color chooser when a 'Browse' button * is clicked and change the associated color * display accordingly, when another color * is selected from the color chooser */ public void actionPerformed(ActionEvent e) { JColorChooser cc = new JColorChooser(); Color color = cc.showDialog(this, "Select Color", m_color); if(color != null) { //System.err.println("Setting color : " + color); setColor(color); } } public Dimension getPreferredSize() { Insets ins = getInsets(); Dimension d1 = m_colorCode.getPreferredSize(); Dimension d2 = m_browseButton.getPreferredSize(); int w = d1.width + d2.width; int h = Math.max(d1.height, d2.height); return new Dimension(w+ins.left+ins.right, h+ins.top+ins.bottom); } public Dimension getMaximumSize() { Insets ins = getInsets(); Dimension d1 = m_colorCode.getMaximumSize(); Dimension d2 = m_browseButton.getMaximumSize(); int w = d1.width + d2.width; int h = Math.max(d1.height, d2.height); return new Dimension(w+ins.left+ins.right, h+ins.top+ins.bottom); } public Dimension getMinimumSize() { Insets ins = getInsets(); Dimension d1 = m_colorCode.getMinimumSize(); Dimension d2 = m_browseButton.getMinimumSize(); int w = d1.width + d2.width; int h = Math.max(d1.height, d2.height); return new Dimension(w+ins.left+ins.right, h+ins.top+ins.bottom); } public void doLayout() { Insets ins = getInsets(); Dimension d = getSize(); int x = ins.left; int y = ins.top; //int w = d.width-ins.left-ins.right; int h = d.height-ins.top-ins.bottom; Dimension d1 = m_colorCode.getPreferredSize(); m_colorCode.setBounds(x, y, d1.width, h); x += d1.width; Dimension d2 = m_browseButton.getPreferredSize(); m_browseButton.setBounds(x, y, d2.width, h); } /* -------------- event listener implementation start ----------- */ /** the listeners for ColorPanelEvents */ private Vector listeners = new Vector(0); /** * add an event listener. * * @param listener the event listener to add */ public void addColorPanelListener(WWEColorPanelListener listener) { listeners.addElement(listener); } /** * remove an event listener. * * @param listener the event listener to remove */ public void removeColorPanelListener(WWEColorPanelListener listener) { listeners.removeElement(listener); } /** fire a color changed event to all registered listeners */ void fireColorChanged() { Enumeration listenerList = listeners.elements(); while(listenerList.hasMoreElements()) { ((WWEColorPanelListener) listenerList.nextElement()).colorChanged( new WWEColorPanelEvent(this)); } } /** the event object definition for ColorPanels */ class WWEColorPanelEvent extends EventObject { public WWEColorPanelEvent(Object source) { super(source); } } /** the event listener definition for ColorPanels */ interface WWEColorPanelListener extends EventListener { public void colorChanged(WWEColorPanelEvent e); } class ColorButton extends JButton{ ColorButton(){ super("..."); setIconTextGap(0); } public void paintComponent(Graphics g){ super.paintComponent(g); int xPoints[] = new int[6]; int yPoints[] = new int[6]; //Draw the ouline xPoints[0] = 6; xPoints[1] = getWidth()-6; xPoints[2] = xPoints[1]; xPoints[3] = getWidth()-12; xPoints[4] = xPoints[3]; xPoints[5] = xPoints[0]; yPoints[0] = 6; yPoints[1] = yPoints[0]; yPoints[2] = getHeight()-11; yPoints[3] = yPoints[2]; yPoints[4] = getHeight()-6; yPoints[5] = yPoints[4]; g.setColor(this.getForeground()); g.drawPolygon(xPoints, yPoints, 6); //Fill the polygon xPoints[0] = 7; xPoints[1] = getWidth()-6; xPoints[2] = xPoints[1]; xPoints[3] = getWidth()-12; xPoints[4] = xPoints[3]; xPoints[5] = xPoints[0]; yPoints[0] = 7; yPoints[1] = yPoints[0]; yPoints[2] = getHeight()-11; yPoints[3] = yPoints[2]; yPoints[4] = getHeight()-6; yPoints[5] = yPoints[4]; //The below getColor is a method for the WWEColorPanel. //Not the most elegant way to do it. g.setColor(getColor()); g.fillPolygon(xPoints, yPoints, 6); //Draw filled upside down triangle xPoints[0] = getWidth()-11; xPoints[1] = getWidth()-4; xPoints[2] = getWidth()-8; yPoints[0] = getHeight()-9; yPoints[1] = getHeight()-9; yPoints[2] = getHeight()-5; g.setColor(this.getForeground()); g.fillPolygon(xPoints, yPoints, 3); } } } --- NEW FILE: WWEColorComboRenderer.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.callback; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.ListCellRenderer; import javax.swing.UIManager; import javax.swing.border.CompoundBorder; import javax.swing.border.LineBorder; import javax.swing.border.MatteBorder; /** * This class implements the ListCellRenderer interface * and is used to represent various Colors. * * @author Faruk m Khan * @version 1.0 14 August 2003 */ class WWEColorComboRenderer extends JPanel implements ListCellRenderer { protected Color m_color = Color.black; protected Color m_focusColor = (Color) UIManager.get("List.selectionBackground"); protected Color m_nonFocusColor = Color.white; public Component getListCellRendererComponent(JList list, Object obj, int row, boolean sel, boolean hasFocus) { if (hasFocus || sel) setBorder(new CompoundBorder( new MatteBorder(2, 10, 2, 10, m_focusColor), new LineBorder(Color.black))); else setBorder(new CompoundBorder( new MatteBorder(2, 10, 2, 10, m_nonFocusColor), new LineBorder(Color.black))); if (obj instanceof Color) m_color = (Color) obj; return this; } public void paintComponent(Graphics g) { setBackground(m_color); super.paintComponent(g); } } --- NEW FILE: WWEAbstractCallbackRoutine.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.callback; import java.awt.HeadlessException; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.text.AttributeSet; import javax.swing.text.MutableAttributeSet; /** * A interface for the callback routines. * * Defines a set of methods which each of the callback routines should implement. * * @author Faruk M Khan * @version 1.0 24 August 2003 */ public abstract class WWEAbstractCallbackRoutine extends JDialog implements WWECallbackRoutine{ public boolean m_succeeded = false; public MutableAttributeSet m_attributes = null; public WWEAbstractCallbackRoutine(JFrame owner, String title, boolean modal) throws HeadlessException { super(owner, title, modal); } public abstract void setAttributes(AttributeSet a); public AttributeSet getAttributes(){ return m_attributes; } public boolean succeeded(){ return m_succeeded; } } --- NEW FILE: WWECallbackRoutine.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.callback; import javax.swing.text.AttributeSet; /** * A interface for the callback routines. * * Defines a set of methods which each of the callback routines should implement. * * @author Faruk M Khan * @version 1.0 24 August 2003 */ public interface WWECallbackRoutine{ public void setAttributes(AttributeSet a); public AttributeSet getAttributes(); public boolean succeeded(); } --- NEW FILE: WWEImageDialog.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.callback; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.net.MalformedURLException; import java.net.URL; import java.util.Vector; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.SpinnerNumberModel; import javax.swing.SpringLayout; import javax.swing.border.EtchedBorder; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.AttributeSet; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.html.HTML; import com.montarasoftware.wwe.WWEComponent; import com.montarasoftware.wwe.WWEHTMLDocument; import com.montarasoftware.wwe.util.WWEDialogLayout; import com.montarasoftware.wwe.util.WWEFileFilter; import com.montarasoftware.wwe.util.WWEFilePreviewer; import com.montarasoftware.wwe.util.WWEHTMLUtilities; import com.montarasoftware.wwe.util.WWESpringUtilities; /** * Dialog to create and edit Images. * * @author Amit Ahuja * @author Faruk m Khan * @version 1.0 23 August 2003 */ public class WWEImageDialog extends WWEAbstractCallbackRoutine implements ChangeListener{ protected WWEHTMLDocument m_doc; protected JComboBox m_styleComboBox; protected JTextField m_sourceTextField; protected JTextField m_altTextField; //protected JComboBox m_alignComboBox; protected JSpinner m_hspacingSpn; protected JSpinner m_vspacingSpn; protected JSpinner m_imageWidthSpn; protected JSpinner m_imageHeightSpn; protected JSpinner m_borderWidthSpn; protected JButton m_browseButton; protected JButton m_btOK; /** * check the size of image from the image location * and set it as a value for the * <code>m_imageHeightSpn</code> and * <code>m_imageWidthSpn</code>. * * The variable is set to true whenever a new image location * is entered into the m_sourceTextField. * It is set to false when the user explicitly modifies * the dimensions of the image. */ protected boolean checkImageSize; protected SimpleAttributeSet m_originalAttributes=new SimpleAttributeSet(); private Vector m_attributeComponents; public WWEImageDialog(JFrame parent, WWEHTMLDocument doc){ super(parent, "Image", true); m_doc = doc; JPanel panel = new JPanel(new GridLayout(0,1)); //mainPanel part of panel center component of Dialog JPanel mainPanel = new JPanel(new SpringLayout()); JLabel styleLabel = new JLabel("CSS style"); mainPanel.add(styleLabel); Vector styleNames = WWEHTMLUtilities. getStyleNamesForTag( m_doc.getStyleSheet(), HTML.Tag.IMG.toString()); m_styleComboBox = new JComboBox(styleNames); styleLabel.setLabelFor(m... [truncated message content] |
From: <de...@us...> - 2004-01-05 03:07:03
|
Update of /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/file In directory sc8-pr-cvs1:/tmp/cvs-serv15363/src/com/montarasoftware/wwe/file Added Files: WWEFileManager.java WWEHTTPIOException.java WWEPageStream.java Log Message: initial load of HTML editor pane and kit --- NEW FILE: WWEFileManager.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.file; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Hashtable; import javax.swing.SwingUtilities; import javax.swing.text.Document; import com.montarasoftware.wwe.WWEEditorPane; import com.montarasoftware.wwe.WWEPageLoadProperties; import com.montarasoftware.wwe.WWEProgressMonitorCallback; import com.montarasoftware.wwe.event.WWEPageLoadEvent; /** * A class handle all files/page related actions, like opening a page from * file system or network URL and same ways Saving of the page. * @version 1.0 07/30/03 * @author Anuj Jain * @author Faruk M Khan */ public class WWEFileManager{ /** * Creates a FileManager object */ private WWEFileManager(){ } /** * Returns the object of this class(Implemented as a singleton) * @return Object of this class. */ public static WWEFileManager getInstance() { if(m_manager==null){ m_manager=new WWEFileManager(); } return m_manager; } /** * Fetches a stream for the given URL, which is about to * be loaded by the <code>setPage</code> method. By * default, this simply opens the URL and returns the * stream. This can be reimplemented to do useful things * like fetch the stream from a cache, monitor the progress * of the stream, etc. * <p> * This method is expected to have the the side effect of * establishing the content type, and therefore setting the * appropriate <code>EditorKit</code> to use for loading the stream. * <p> * If this the stream was an http connection, redirects * will be followed and the resulting URL will be set as * the <code>Document.StreamDescriptionProperty</code> so that relative * URL's can be properly resolved. * * @param page the URL of the page * @param pageProperties the Document properties */ public InputStream getStream(WWEEditorPane editor, URL page, Hashtable pageProperties, WWEPageLoadProperties pageLoadProperties, WWEProgressMonitorCallback monitor) throws IOException { this.editor = editor; this.page = page; this.pageProperties = pageProperties; this.pageLoadProperties = pageLoadProperties; this.monitor = monitor; page_redirected = false; if(monitor != null){ monitor.setNote("Connecting to " + page.getHost() + "..."); } return getStream(); } private InputStream getStream() throws IOException{ URLConnection conn = page.openConnection(); if (conn instanceof HttpURLConnection) { HttpURLConnection hconn = (HttpURLConnection) conn; hconn.setInstanceFollowRedirects(false); if(com.montarasoftware.wwe.debug.WWEDebug.PROXY){ /* DEBUGSTATEMENT */ System.err.println("Proxy-Set: " + System.getProperty("https.proxySet")); /* DEBUGSTATEMENT */ System.err.println("Proxy-Host: " + System.getProperty("http.proxyHost")); /* DEBUGSTATEMENT */ System.err.println("Proxy-Port: " + System.getProperty("http.proxyPort")); /* DEBUGSTATEMENT */ } /* DEBUGSTATEMENT */ if(com.montarasoftware.wwe.debug.WWEDebug.HTTP){ /* DEBUGSTATEMENT */ System.err.println("..................HTTP headers.................."); /* DEBUGSTATEMENT */ System.err.println("Request-Method: " + hconn.getRequestMethod()); /* DEBUGSTATEMENT */ for(int i=0; i<40; i++){ /* DEBUGSTATEMENT */ if(hconn.getHeaderFieldKey(i) != null || hconn.getHeaderField(i) != null){ /* DEBUGSTATEMENT */ System.err.println(hconn.getHeaderFieldKey(i) + ": " + hconn.getHeaderField(i)); /* DEBUGSTATEMENT */ }else{ /* DEBUGSTATEMENT */ break; /* DEBUGSTATEMENT */ } /* DEBUGSTATEMENT */ } /* DEBUGSTATEMENT */ System.err.println("..................HTTP headers complete........."); /* DEBUGSTATEMENT */ } /* DEBUGSTATEMENT */ int response = hconn.getResponseCode(); if(response >= 400){ InputStream errorStream = hconn.getErrorStream(); if(errorStream != null){ pageLoadProperties.put(WWEPageLoadProperties.RESULT, WWEPageLoadEvent.Result.ERRORSTREAM); pageLoadProperties.put(WWEPageLoadProperties.DESCRIPTION, "Server Returned a Error page"); return errorStream; }else{ throw new WWEHTTPIOException(hconn.getResponseMessage(), response); } }else if(response >= 300 && response <= 399){ /* * In the case of a redirect, we want to actually change the URL * that was input to the new, redirected URL */ page_redirected = true; String loc = conn.getHeaderField("Location"); if (loc.startsWith("http", 0)) { page = new URL(loc); if(monitor != null){ monitor.setNote("Redirecting page..."); } } else { page = new URL(page, loc); } return getStream(); }else if(response >= 200){ if(monitor != null){ int len = hconn.getContentLength(); if(len>0){ //If the GET request gives away we are lucky. monitor.setMaximum(len); }else{ SwingUtilities.invokeLater(new Runnable() { public void run() { try{ HttpURLConnection lconn =(HttpURLConnection)page.openConnection(); lconn.setRequestMethod("HEAD"); lconn.setInstanceFollowRedirects(true); int len = lconn.getContentLength(); if(len>0){ monitor.setMaximum(len); } }catch(Exception e){ //Some error happened monitor.setMaximum() //may not be called } } }); } } } }else{ if(com.montarasoftware.wwe.debug.WWEDebug.HTTP){ /* DEBUGSTATEMENT */ System.err.println("..................Connection headers.................."); /* DEBUGSTATEMENT */ System.err.println("The connection handler class is : " + conn.getClass().getName()); /* DEBUGSTATEMENT */ System.err.println("The URL being fetched is : " + conn.getURL().toString()); /* DEBUGSTATEMENT */ for(int i=0; i<40; i++){ /* DEBUGSTATEMENT */ if(conn.getHeaderFieldKey(i) != null || conn.getHeaderField(i) != null){ /* DEBUGSTATEMENT */ System.err.println(conn.getHeaderFieldKey(i) + ": " + conn.getHeaderField(i)); /* DEBUGSTATEMENT */ }else{ /* DEBUGSTATEMENT */ break; /* DEBUGSTATEMENT */ } /* DEBUGSTATEMENT */ } /* DEBUGSTATEMENT */ System.err.println("..................Connection headers complete........."); /* DEBUGSTATEMENT */ } /* DEBUGSTATEMENT */ //conn may be a instance of FileURLConnection //We cannot check this out. //Lets still try to get the Content-Length if(monitor != null){ int len = conn.getContentLength(); if(len>0){ monitor.setMaximum(len); } } } if (pageProperties == null) { pageProperties = new Hashtable(); } String type = conn.getContentType(); if (type != null) { editor.setContentType(type); pageProperties.put("content-type", type); } pageProperties.put(Document.StreamDescriptionProperty, page); String enc = conn.getContentEncoding(); if (enc != null) { pageProperties.put("content-encoding", enc); } InputStream in = conn.getInputStream(); return in; } /** * returns the redirected page. * If while creating the InputStream there occurs a redirection then * the method returns the new value. Else returns a null. * * @return the redirected page or null */ public URL getRedirectedPage(){ if(page_redirected){ return page; }else{ return null; } } /** * Returns the outputstream object for the given file. * @param fileobj File object whose outputstream is to be get. * @return A handle to the output stream for the given file object. */ public synchronized OutputStream getOutputSream(File fileobj){ try{ FileOutputStream outstream=new FileOutputStream(fileobj); return outstream; }catch(FileNotFoundException excep){ System.err.println("Class: WWEFileManager, Line: 145, Failed to find file"); return null; } } /** * Saves the file to the file system after reading from the passed input stream. * @param filepath FilePath where file is to be saved * @param istream InputStream object from where data is to be read. */ public synchronized void saveFileToFS(String filepath,InputStream istream){ try{ int size=istream.available(); byte data[]=new byte[size]; istream.read(data); istream.close(); FileOutputStream outstream=null; try{ outstream=new FileOutputStream(filepath); }catch(FileNotFoundException fexcep){ //Handle the exception using Montaras API //ThrowableHandler.handle(fexcep,ThrowableHandler.INFO); } if(outstream!=null){ outstream.write(data); outstream.flush(); outstream.close(); } }catch(IOException ioexcep){ //Handle the exception using Montaras API //ThrowableHandler.handle(ioexcep,ThrowableHandler.INFO); } } /** * Saves the file to the network url after reading from the passed input stream. * @param networkurl Network Url where file is to be saved. * @param istream InputStream object from where data is to be read. */ public synchronized void saveFileToNetwork(String networkurl,InputStream istream){ try{ int size=istream.available(); byte data[]=new byte[size]; istream.read(data); URL url=new URL(networkurl); URLConnection urlconnection=url.openConnection(); OutputStream outstream=urlconnection.getOutputStream(); outstream.write(data); outstream.flush(); outstream.close(); }catch(MalformedURLException mfexcep){ //Handle the exception using Montaras API //ThrowableHandler.handle(mfexcep,ThrowableHandler.INFO); } catch(IOException ioexcep){ //Handle the exception using Montaras API //ThrowableHandler.handle(ioexcep,ThrowableHandler.INFO); } } // --- variables --------------------------------------- private WWEEditorPane editor; private URL page; private boolean page_redirected; private Hashtable pageProperties; private WWEPageLoadProperties pageLoadProperties; private WWEProgressMonitorCallback monitor; //Static ref. of this class. private static WWEFileManager m_manager; } --- NEW FILE: WWEHTTPIOException.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.file; import java.io.IOException; /** * extends the <code>IOException</code> and adds a * attribute which specifies the HTTP Respose Code. * * This exception should ideally by used only to * denote response codes for above 400 * * @author Faruk m Khan * @version 1.0 04 August 2003 */ public class WWEHTTPIOException extends IOException { private int responsecode; /** * Constructs an <code>WWEIOException</code> with <code>null</code> * as its error detail message. */ public WWEHTTPIOException() { super(); } /** * Constructs an <code>WWEIOException</code> with the specified detail * message. The error message string <code>s</code> can later be * retrieved by the <code>{@link java.lang.Throwable#getMessage}</code> * method of class <code>java.lang.Throwable</code>. * * @param s the detail message. */ public WWEHTTPIOException(String s){ super(s); } /** * Constructs an <code>WWEIOException</code> with the specified detail * message and the response code from the HTTP Server. * * @param s the detail message * @param code the HTTP Response code */ public WWEHTTPIOException(String s, int code){ super(s); this.responsecode = code; } /** * this method helps us retrive the HTTP response code. * * @return HTTP response code */ public int getResponseCode(){ return responsecode; } } --- NEW FILE: WWEPageStream.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.file; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import com.montarasoftware.wwe.WWEProgressMonitorCallback; /** * @author Faruk m Khan * @version 1.0 04 August 2003 */ public class WWEPageStream extends FilterInputStream { private WWEProgressMonitorCallback monitor; private int nread = 0; private int size = 0; private boolean canceled; public WWEPageStream(InputStream i) { this(i, null); } public WWEPageStream(InputStream i, WWEProgressMonitorCallback monitor) { super(i); canceled = false; this.monitor = monitor; /* * Remember the monitor.setMaximum() has already been called on * the monitor object in the FileManager class so we don't need * to do it here like before. */ } /** * Cancel the loading of the stream by throwing * an IOException on the next request. */ public synchronized void cancel() { canceled = true; } protected synchronized void checkCanceled() throws InterruptedIOException { if (canceled) { InterruptedIOException exc = new InterruptedIOException("Page Canceled"); exc.bytesTransferred = nread; throw exc; } } /** * Overrides <code>FilterInputStream.read</code> * to update the progress monitor after the read. */ public int read() throws IOException { checkCanceled(); int c = super.read(); if(monitor != null){ if (c >= 0) monitor.setProgress(++nread); if (monitor.isCanceled()) { cancel(); } } return c; } /** * Overrides <code>FilterInputStream.read</code> * to update the progress monitor after the read. */ public int read(byte b[]) throws IOException { checkCanceled(); int nr = super.read(b); if(monitor != null){ if (nr > 0) monitor.setProgress(nread += nr); if (monitor.isCanceled()) { cancel(); } } return nr; } /** * Overrides <code>FilterInputStream.read</code> * to update the progress monitor after the read. */ public int read(byte b[], int off, int len) throws IOException { checkCanceled(); int nr = super.read(b, off, len); if(monitor != null){ if (nr > 0) monitor.setProgress(nread += nr); if (monitor.isCanceled()) { cancel(); } } return nr; } /** * Overrides <code>FilterInputStream.skip</code> * to update the progress monitor after the skip. */ public long skip(long n) throws IOException { checkCanceled(); long nr = super.skip(n); if(monitor != null){ if (nr > 0) monitor.setProgress(nread += nr); } return nr; } /** * Overrides <code>FilterInputStream.close</code> * to close the progress monitor as well as the stream. */ public void close() throws IOException { super.close(); if(monitor != null){ monitor.close(); } } public int available() throws IOException { checkCanceled(); return super.available(); } /** * Overrides <code>FilterInputStream.reset</code> * to reset the progress monitor as well as the stream. */ public synchronized void reset() throws IOException { checkCanceled(); super.reset(); if(monitor != null){ nread = size - super.available(); monitor.setProgress(nread); } } } |
From: <de...@us...> - 2004-01-05 03:07:03
|
Update of /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/popup In directory sc8-pr-cvs1:/tmp/cvs-serv15363/src/com/montarasoftware/wwe/popup Added Files: WWEPopupMenuOverNonEditableLink.java WWEPopupMenuOverTable.java WWEPopupMenuOverEditableLink.java WWEPopupMenuOverEditableList.java WWEPopupMenuOverNonEditableText.java WWEPopupMenuOverEditableText.java WWEPopupMenuOverEditableImage.java Log Message: initial load of HTML editor pane and kit --- NEW FILE: WWEPopupMenuOverNonEditableLink.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.popup; import java.awt.Component; import java.awt.Point; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.util.Hashtable; import javax.swing.AbstractAction; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import com.montarasoftware.wwe.WWEComponent; import com.montarasoftware.wwe.event.WWEComponentEvent; /** * An implementation of a JPopupMenu -- a small window that pops up * and displays a series of tag specific choices. * * This popup menus has been designed to be used when the * mouse clicks over table tag. When no text is selected. * * @author Faruk m Khan * @version 1.0 16 August 2003 */ public class WWEPopupMenuOverNonEditableLink extends JPopupMenu implements ClipboardOwner{ /** * Instance of WWEComponent. * * Used to call the openPage method when user * selects the Open menu item on the * popup menu. */ WWEComponent comp; /** * Used to fetch the url for the hyperlink * to open */ WWEComponentEvent event; /** * Constructs a <code>WWEPopupMenuOverNonEditableLink</code> with * menuitems created from supplied actions. * * @param actionHash the hastable which contains * list of all actions to use for creating the JMenuItems. */ public WWEPopupMenuOverNonEditableLink(Hashtable actionHash) { super("PopupMenu Over Link"); AbstractAction actionOpen = new AbstractAction(){ public void actionPerformed(ActionEvent evt){ comp.openPage(event.getURL(), true); } }; JMenuItem item = new JMenuItem(actionOpen); item.setText("Open"); add(item); addSeparator(); AbstractAction actionCopy = (AbstractAction) actionHash.get("copy"); item = new JMenuItem(actionCopy); item.setText("Copy"); add(item); AbstractAction actionCopyShortcut = new AbstractAction(){ public void actionPerformed(ActionEvent evt){ StringSelection ss = new StringSelection(event.getURL().toString()); Clipboard cb = getToolkit().getSystemClipboard(); cb.setContents(ss, WWEPopupMenuOverNonEditableLink.this); } }; item = new JMenuItem(actionCopyShortcut); item.setText("Copy Shortcut"); add(item); } /** * Displays the popup menu at the position represented by point object in the coordinate * space of the component invoker. * * @param invoker the component in whose space the popup menu is to appear * @param pt the Point object in invoker's coordinate space at which * the popup menu is to be displayed */ public void show(Component invoker, WWEComponent comp, WWEComponentEvent event) { Point pt = event.getPoint(); this.comp = comp; this.event = event; super.show(invoker, (int)pt.getX(), (int)pt.getY()); } /* Implementation of ClipboardOwner */ public void lostOwnership(Clipboard c, Transferable t){} } --- NEW FILE: WWEPopupMenuOverTable.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.popup; import java.awt.Component; import java.awt.Point; import java.util.Hashtable; import javax.swing.AbstractAction; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; /** * An implementation of a JPopupMenu -- a small window that pops up * and displays a series of tag specific choices. * * This popup menus has been designed to be used when the * mouse clicks over table tag. When no text is selected. * * @author Faruk m Khan * @version 1.0 16 August 2003 */ public class WWEPopupMenuOverTable extends JPopupMenu{ /** * Constructs a <code>WWEPopupMenuOverTable</code> with * menuitems created from supplied actions. * * @param actionHash the hastable which contains * list of all actions to use for creating the JMenuItems. */ public WWEPopupMenuOverTable(Hashtable actionHash) { super("PopupMenu Over Table"); AbstractAction action = (AbstractAction) actionHash.get("cut"); JMenuItem item = new JMenuItem(action); item.setText("Cut"); add(item); action = (AbstractAction) actionHash.get("copy"); item = new JMenuItem(action); item.setText("Copy"); add(item); action = (AbstractAction) actionHash.get("paste"); item = new JMenuItem(action); item.setText("Paste"); add(item); addSeparator(); action = (AbstractAction) actionHash.get("insert-image"); item = new JMenuItem(action); item.setText("Insert Image..."); add(item); action = (AbstractAction) actionHash.get("insert-list"); item = new JMenuItem(action); item.setText("Insert List..."); add(item); action = (AbstractAction) actionHash.get("insert-table"); item = new JMenuItem(action); item.setText("Insert Table..."); add(item); addSeparator(); JMenu tableOptionsMenu = new JMenu("Table Options"); action = (AbstractAction) actionHash.get("append-table-row"); item = new JMenuItem(action); item.setText("Append Row"); tableOptionsMenu.add(item); action = (AbstractAction) actionHash.get("append-table-col"); item = new JMenuItem(action); item.setText("Append Column"); tableOptionsMenu.add(item); tableOptionsMenu.addSeparator(); action = (AbstractAction) actionHash.get("insert-table-row"); item = new JMenuItem(action); item.setText("Insert Row"); tableOptionsMenu.add(item); action = (AbstractAction) actionHash.get("insert-table-col"); item = new JMenuItem(action); item.setText("Insert Column"); tableOptionsMenu.add(item); tableOptionsMenu.addSeparator(); action = (AbstractAction) actionHash.get("delete-table-row"); item = new JMenuItem(action); item.setText("Delete Row"); tableOptionsMenu.add(item); action = (AbstractAction) actionHash.get("delete-table-col"); item = new JMenuItem(action); item.setText("Delete Column"); tableOptionsMenu.add(item); tableOptionsMenu.addSeparator(); action = (AbstractAction) actionHash.get("delete-table"); item = new JMenuItem(action); item.setText("Delete Table"); tableOptionsMenu.add(item); add(tableOptionsMenu); action = (AbstractAction) actionHash.get("format-table"); item = new JMenuItem(action); item.setText("Format Table..."); add(item); addSeparator(); action = (AbstractAction) actionHash.get("format-font"); item = new JMenuItem(action); item.setText("Font Properties..."); add(item); } /** * Displays the popup menu at the position represented by point object in the coordinate * space of the component invoker. * * @param invoker the component in whose space the popup menu is to appear * @param pt the Point object in invoker's coordinate space at which * the popup menu is to be displayed */ public void show(Component invoker, Point pt) { super.show(invoker, (int)pt.getX(), (int)pt.getY()); } } --- NEW FILE: WWEPopupMenuOverEditableLink.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.popup; import java.awt.Component; import java.awt.Point; import java.util.Hashtable; import javax.swing.AbstractAction; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; /** * An implementation of a JPopupMenu -- a small window that pops up * and displays a series of tag specific choices. * * This popup menus has been designed to be used when the * mouse clicks over table tag. When no text is selected. * * @author Faruk m Khan * @version 1.0 16 August 2003 */ public class WWEPopupMenuOverEditableLink extends JPopupMenu{ /** * Constructs a <code>WWEPopupMenuOverEditableLink</code> with * menuitems created from supplied actions. * * @param actionHash the hastable which contains * list of all actions to use for creating the JMenuItems. */ public WWEPopupMenuOverEditableLink(Hashtable actionHash) { super("PopupMenu Over Editable Link"); AbstractAction action = (AbstractAction) actionHash.get("cut"); JMenuItem item = new JMenuItem(action); item.setText("Cut"); add(item); action = (AbstractAction) actionHash.get("copy"); item = new JMenuItem(action); item.setText("Copy"); add(item); action = (AbstractAction) actionHash.get("paste"); item = new JMenuItem(action); item.setText("Paste"); add(item); addSeparator(); action = (AbstractAction) actionHash.get("insert-image"); item = new JMenuItem(action); item.setText("Insert Image..."); add(item); action = (AbstractAction) actionHash.get("insert-list"); item = new JMenuItem(action); item.setText("Insert List..."); add(item); action = (AbstractAction) actionHash.get("insert-table"); item = new JMenuItem(action); item.setText("Insert Table..."); add(item); addSeparator(); action = (AbstractAction) actionHash.get("hyperlink"); item = new JMenuItem(action); item.setText("Format Link..."); add(item); addSeparator(); action = (AbstractAction) actionHash.get("format-font"); item = new JMenuItem(action); item.setText("Font Properties..."); add(item); } /** * Displays the popup menu at the position represented by point object in the coordinate * space of the component invoker. * * @param invoker the component in whose space the popup menu is to appear * @param pt the Point object in invoker's coordinate space at which * the popup menu is to be displayed */ public void show(Component invoker, Point pt) { super.show(invoker, (int)pt.getX(), (int)pt.getY()); } } --- NEW FILE: WWEPopupMenuOverEditableList.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.popup; import java.awt.Component; import java.awt.Point; import java.util.Hashtable; import javax.swing.AbstractAction; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; /** * An implementation of a JPopupMenu -- a small window that pops up * and displays a series of tag specific choices. * * This popup menus has been designed to be used when the * mouse clicks over table tag. When no text is selected. * * @author Faruk m Khan * @version 1.0 16 August 2003 */ public class WWEPopupMenuOverEditableList extends JPopupMenu{ /** * Constructs a <code>WWEPopupMenuOverEditableList</code> with * menuitems created from supplied actions. * * @param actionHash the hastable which contains * list of all actions to use for creating the JMenuItems. */ public WWEPopupMenuOverEditableList(Hashtable actionHash) { super("PopupMenu Over Editable Link"); AbstractAction action = (AbstractAction) actionHash.get("cut"); JMenuItem item = new JMenuItem(action); item.setText("Cut"); add(item); action = (AbstractAction) actionHash.get("copy"); item = new JMenuItem(action); item.setText("Copy"); add(item); action = (AbstractAction) actionHash.get("paste"); item = new JMenuItem(action); item.setText("Paste"); add(item); addSeparator(); action = (AbstractAction) actionHash.get("insert-image"); item = new JMenuItem(action); item.setText("Insert Image..."); add(item); action = (AbstractAction) actionHash.get("insert-list"); item = new JMenuItem(action); item.setText("Insert List..."); add(item); action = (AbstractAction) actionHash.get("insert-table"); item = new JMenuItem(action); item.setText("Insert Table..."); add(item); addSeparator(); action = (AbstractAction) actionHash.get("format-list"); item = new JMenuItem(action); item.setText("Format List..."); add(item); addSeparator(); action = (AbstractAction) actionHash.get("format-font"); item = new JMenuItem(action); item.setText("Font Properties..."); add(item); } /** * Displays the popup menu at the position represented by point object in the coordinate * space of the component invoker. * * @param invoker the component in whose space the popup menu is to appear * @param pt the Point object in invoker's coordinate space at which * the popup menu is to be displayed */ public void show(Component invoker, Point pt) { super.show(invoker, (int)pt.getX(), (int)pt.getY()); } } --- NEW FILE: WWEPopupMenuOverNonEditableText.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.popup; import java.awt.Component; import java.awt.Point; import java.util.Hashtable; import javax.swing.AbstractAction; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; /** * An implementation of a JPopupMenu -- a small window that pops up * and displays a series of tag specific choices. * * This popup menus has been designed to be used when the * mouse clicks over table tag. When no text is selected. * * @author Faruk m Khan * @version 1.0 16 August 2003 */ public class WWEPopupMenuOverNonEditableText extends JPopupMenu{ /** * Constructs a <code>WWEPopupMenuOverNonEditableText</code> with * menuitems created from supplied actions. * * @param actionHash the hastable which contains * list of all actions to use for creating the JMenuItems. */ public WWEPopupMenuOverNonEditableText(Hashtable actionHash) { super("PopupMenu Over NonEditableText"); AbstractAction actionCopy = (AbstractAction) actionHash.get("copy"); JMenuItem item = new JMenuItem(actionCopy); item.setText("Copy"); add(item); } /** * Displays the popup menu at the position represented by point object in the coordinate * space of the component invoker. * * @param invoker the component in whose space the popup menu is to appear * @param pt the Point object in invoker's coordinate space at which * the popup menu is to be displayed */ public void show(Component invoker, Point pt) { super.show(invoker, (int)pt.getX(), (int)pt.getY()); } } --- NEW FILE: WWEPopupMenuOverEditableText.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.popup; import java.awt.Component; import java.awt.Point; import java.util.Hashtable; import javax.swing.AbstractAction; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; /** * An implementation of a JPopupMenu -- a small window that pops up * and displays a series of tag specific choices. * * This popup menus has been designed to be used when the * mouse clicks over table tag. When no text is selected. * * @author Faruk m Khan * @version 1.0 16 August 2003 */ public class WWEPopupMenuOverEditableText extends JPopupMenu{ /** * Constructs a <code>WWEPopupMenuOverEditableText</code> with * menuitems created from supplied actions. * * @param actionHash the hastable which contains * list of all actions to use for creating the JMenuItems. */ public WWEPopupMenuOverEditableText(Hashtable actionHash) { super("PopupMenu Over EditableText"); AbstractAction action = (AbstractAction) actionHash.get("cut"); JMenuItem item = new JMenuItem(action); item.setText("Cut"); add(item); action = (AbstractAction) actionHash.get("copy"); item = new JMenuItem(action); item.setText("Copy"); add(item); action = (AbstractAction) actionHash.get("paste"); item = new JMenuItem(action); item.setText("Paste"); add(item); addSeparator(); action = (AbstractAction) actionHash.get("insert-image"); item = new JMenuItem(action); item.setText("Insert Image..."); add(item); action = (AbstractAction) actionHash.get("hyperlink"); item = new JMenuItem(action); item.setText("Insert Link..."); add(item); action = (AbstractAction) actionHash.get("insert-list"); item = new JMenuItem(action); item.setText("Insert List..."); add(item); action = (AbstractAction) actionHash.get("insert-table"); item = new JMenuItem(action); item.setText("Insert Table..."); add(item); addSeparator(); action = (AbstractAction) actionHash.get("format-font"); item = new JMenuItem(action); item.setText("Font Properties..."); add(item); } /** * Displays the popup menu at the position represented by point object in the coordinate * space of the component invoker. * * @param invoker the component in whose space the popup menu is to appear * @param pt the Point object in invoker's coordinate space at which * the popup menu is to be displayed */ public void show(Component invoker, Point pt) { super.show(invoker, (int)pt.getX(), (int)pt.getY()); } } --- NEW FILE: WWEPopupMenuOverEditableImage.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.popup; import java.awt.Component; import java.awt.Point; import java.util.Hashtable; import javax.swing.AbstractAction; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; /** * An implementation of a JPopupMenu -- a small window that pops up * and displays a series of tag specific choices. * * This popup menus has been designed to be used when the * mouse clicks over table tag. When no text is selected. * * @author Faruk m Khan * @version 1.0 16 August 2003 */ public class WWEPopupMenuOverEditableImage extends JPopupMenu{ /** * Constructs a <code>WWEPopupMenuOverEditableImage</code> with * menuitems created from supplied actions. * * @param actionHash the hastable which contains * list of all actions to use for creating the JMenuItems. */ public WWEPopupMenuOverEditableImage(Hashtable actionHash) { super("PopupMenu Over Editable Link"); AbstractAction action = (AbstractAction) actionHash.get("cut"); JMenuItem item = new JMenuItem(action); item.setText("Cut"); add(item); action = (AbstractAction) actionHash.get("copy"); item = new JMenuItem(action); item.setText("Copy"); add(item); action = (AbstractAction) actionHash.get("paste"); item = new JMenuItem(action); item.setText("Paste"); add(item); addSeparator(); action = (AbstractAction) actionHash.get("insert-image"); item = new JMenuItem(action); item.setText("Insert Image..."); add(item); action = (AbstractAction) actionHash.get("hyperlink"); item = new JMenuItem(action); item.setText("Insert Link..."); add(item); action = (AbstractAction) actionHash.get("insert-list"); item = new JMenuItem(action); item.setText("Insert List..."); add(item); action = (AbstractAction) actionHash.get("insert-table"); item = new JMenuItem(action); item.setText("Insert Table..."); add(item); addSeparator(); action = (AbstractAction) actionHash.get("format-image"); item = new JMenuItem(action); item.setText("Format Image..."); add(item); addSeparator(); action = (AbstractAction) actionHash.get("format-font"); item = new JMenuItem(action); item.setText("Font Properties..."); add(item); } /** * Displays the popup menu at the position represented by point object in the coordinate * space of the component invoker. * * @param invoker the component in whose space the popup menu is to appear * @param pt the Point object in invoker's coordinate space at which * the popup menu is to be displayed */ public void show(Component invoker, Point pt) { super.show(invoker, (int)pt.getX(), (int)pt.getY()); } } |
Update of /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/inmemorycache In directory sc8-pr-cvs1:/tmp/cvs-serv15363/src/com/montarasoftware/wwe/inmemorycache Added Files: WWECacheConfigurationVO.java WWECacheEntryExistsException.java WWECachedObject.java WWECacheable.java WWECacheManager.java WWECacheException.java Log Message: initial load of HTML editor pane and kit --- NEW FILE: WWECacheConfigurationVO.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.inmemorycache; public class WWECacheConfigurationVO { private int maxSize; private long timeToLive; private long idleTimedOut; public WWECacheConfigurationVO() { } public void setMaxSize(int amaxsize) { maxSize=amaxsize; } public int getMaxSize() { return maxSize; } public void setTimeToLive(long atimeToLive) { timeToLive=atimeToLive; } public long getTimeToLive() { return timeToLive; } public void setIdleTimeOut(long aidleTimedOut) { idleTimedOut=aidleTimedOut; } public long getIdleTimedOut() { return idleTimedOut; } } --- NEW FILE: WWECacheEntryExistsException.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.inmemorycache; /** * A exception thrown when the entry already * exists in the In-Memory-Cache. * * @author Faruk m Khan * @version 1.0 05 October 2003 */ public class WWECacheEntryExistsException extends WWECacheException{ public WWECacheEntryExistsException() { super("Cache Entry already exists"); } public WWECacheEntryExistsException(String msg) { super(msg); } } --- NEW FILE: WWECachedObject.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.inmemorycache; public class WWECachedObject implements WWECacheable { private Object cachedData; private long timeCached; private long timeAccessedLast; private long idleTimedOut; private long cacheTimeToLive; public WWECachedObject(Object cData) { cachedData = cData; cacheTimeToLive = 0; // Live forever idleTimedOut = 60 * 60 * 10000; // 60 Minutes setTimeCached(); setTimeAccessedLast(); } public WWECachedObject(Object cData, long ttl, long ito) { setCachedData(cData); setCacheTimeToLive(ttl); setIdleTimedOut(ito); setTimeCached(); setTimeAccessedLast(); } public void setCachedData(Object cData) { cachedData = cData; } public Object getCachedData() { return cachedData; } public void setTimeCached() { timeCached = System.currentTimeMillis(); // timeCached = Calendar.getInstance().getTime(); } public long getTimeCached() { return timeCached; } public void setTimeAccessedLast() { timeAccessedLast = System.currentTimeMillis(); // timeAccessedLast = Calendar.getInstance().getTime(); } public long getTimeAccessedLast() { return timeAccessedLast; } public void setIdleTimedOut(long ito) { idleTimedOut = ito; } public long getIdleTimedOut() { return idleTimedOut; } public void setCacheTimeToLive(long ttl) { cacheTimeToLive = ttl; } public long getCacheTimeToLive() { return cacheTimeToLive; } public boolean isExpired() { // cache would be expired if timeToLive is over or the idleTimedOut if (cacheTimeToLive == 0) return false; // cache will live forever and never expire long currentTime = System.currentTimeMillis(); if ( (currentTime - timeCached) >= cacheTimeToLive || (currentTime - timeAccessedLast) >= idleTimedOut) { return true; } return false; } } --- NEW FILE: WWECacheable.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.inmemorycache; import java.io.Serializable; public interface WWECacheable extends Serializable { public boolean isExpired(); } --- NEW FILE: WWECacheManager.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.inmemorycache; import java.util.Hashtable; import java.util.LinkedList; import java.util.zip.CRC32; public class WWECacheManager { private Hashtable cacheTable; private LinkedList cacheMRUList; // Have to retrieve the following values from Configuration Manager private int maxSize; private long cacheTimeToLive; private long idleTimedOut; private long remainingSize; public WWECacheManager() { } /* Creates an empty cache. The size of the cache has to be decided carefully. If large objects are stored in the cache, the number of entries in the cache should be small. */ /* Creates an empty cache. The size of the cache has to be decided carefully. If large objects are stored in the cache, the number of entries in the cache should be small. */ public WWECacheManager(WWECacheConfigurationVO cacheConfigurationVO) { cacheTable = new Hashtable(); cacheMRUList = new LinkedList(); maxSize = cacheConfigurationVO.getMaxSize(); cacheTimeToLive = cacheConfigurationVO.getTimeToLive(); idleTimedOut = cacheConfigurationVO.getIdleTimedOut(); remainingSize= maxSize; } /* Generates a unique key for an entry in the cache. This method can be overriden to support a different key generation algorithm. */ private Long createKey(String searchArgs) { long value = getCRC32(searchArgs.getBytes()); return new Long(value); } /* Adds a new entry into the cache. If the cache size has been exceeded, the entry that has not been accessed for the longest period of time is removed and the new entry is inserted. */ public synchronized void addEntry(String uri, Object entry) throws WWECacheEntryExistsException { if (maxSize > 0) // maxSize must be >0 to work otherwise it will be disabled { Long key = createKey(uri); if (cacheTable.get(key) != null) { throw new WWECacheEntryExistsException(); } WWECachedObject cobject = new WWECachedObject(entry,cacheTimeToLive,idleTimedOut); if (remainingSize == 0) { Object leastUsedEntryKey = cacheMRUList.removeFirst(); cacheTable.remove(leastUsedEntryKey); } else{ remainingSize=remainingSize-1; } cacheTable.put(key, cobject); cacheMRUList.addLast(key); } } /* Add/Replace the entry into the cache. If the entry is available in the cache, it is replaced with new entry otherwise it is added. If the cache size has been exceeded, the entry that has not been accessed for the longest period of time is removed and the new entry is inserted. */ public synchronized void addEntry(String uri, Object entry, boolean force) throws WWECacheEntryExistsException { if (maxSize > 0) // maxSize must be >0 to work otherwise it will be disabled { Long key = createKey(uri); if (!force) // Not forced to replace the existing entry { if (cacheTable.get(key) != null) { // Entry already exists throw new WWECacheEntryExistsException(); } } WWECachedObject cobject = new WWECachedObject(entry,cacheTimeToLive,idleTimedOut); if (remainingSize == 0) { Object leastUsedEntryKey = cacheMRUList.removeFirst(); cacheTable.remove(leastUsedEntryKey); } else{ remainingSize=remainingSize-1; } cacheTable.put(key, cobject); cacheMRUList.addLast(key); } } /* Retrieves the cache entry specified by the key. If the entry is not found, null is returned. */ public Object fetchEntry(String uri) { Long key = createKey(uri); WWECachedObject obj = (WWECachedObject) cacheTable.get(key); if (obj != null) { cacheMRUList.remove(key); cacheMRUList.addFirst(key); return obj.getCachedData(); } return null; } /* Retrieves the last accessed cache entry. If the entry is not found, null is returned. */ public Object fetchLastEntry() { Long lastKey=(Long)cacheMRUList.getLast(); WWECachedObject obj = (WWECachedObject) cacheTable.get(lastKey); return obj.getCachedData(); } /** * Flushes all entries from the cache. */ public synchronized void flushEntries() { cacheTable.clear(); cacheMRUList.clear(); remainingSize = maxSize; } /* Returns the size available in the cache for more entries. The number of new entries that can be accomodated in the cache. */ public long getAvailableSize() { return remainingSize; } /* Returns the Used Cache size Current Size = Max Cache Size - Remaining Size */ public long getUsedSize() { return maxSize-remainingSize; } public Hashtable getAllEntries() { return cacheTable; } private long getCRC32(byte[] barray) { if (barray == null) { return 0; } CRC32 crcVal = new CRC32(); crcVal.update(barray); return crcVal.getValue(); } public WWECacheConfigurationVO getCacheConfiguration() { return null; } public long setEntryTTL() { return 0; } } --- NEW FILE: WWECacheException.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.inmemorycache; public class WWECacheException extends Exception{ public WWECacheException() { super(); } public WWECacheException(String msg) { super(msg); } } |
Update of /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/config In directory sc8-pr-cvs1:/tmp/cvs-serv15363/src/com/montarasoftware/wwe/config Added Files: WWEConfigurationManager.java WWEConfigurationConstants.java WWEConfigurationAccessXML.java WWEConfigurationAccess.java WWEConfigurationAccessFactory.java Log Message: initial load of HTML editor pane and kit --- NEW FILE: WWEConfigurationManager.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.config; /** * A class for getting access to configuration access factory through which * configuration access xml parser is obtained. * @version 1.0 08/01/03 * @author Anuj Jain */ public class WWEConfigurationManager{ /** * Creates a ConfigurationManager object */ public WWEConfigurationManager(){ } /** * Gets the configuration access factory object. * @return Configuration Access Factory instance. */ public WWEConfigurationAccessFactory getConfigurationFactory(){ WWEConfigurationAccessFactory configfactory = WWEConfigurationAccessFactory.getInstance(); return configfactory; } } --- NEW FILE: WWEConfigurationConstants.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.config; /** * An interface for declaring config xml file constants. * @version 1.0 08/01/03 * @author Anuj Jain */ public interface WWEConfigurationConstants{ //A variable indicating configuration file name. String CONFIG_XML_FILE_NAME="WYSIWYG.xml"; //A variable indicating directory for configuration xml file String CONFIG_XML_FILE_DIR="."; //A variable indicating Cache element in confiuration file String CACHE="Cache"; //A variable indicating max Size attribute in cache Tag. String CACHE_MAX_SIZE="MaxSize"; //A variable indicating TimeToLive attribute in cache Tag. String CACHE_TIME_TO_LIVE="TimeToLive"; //A variable indicating AccessTimeOut attribute in cache Tag. String CACHE_Idle_TIME_OUT="IdleTimeOut"; //A variable indicating Default Css element in configuration file String DEFAULT_CSS="DefaultCSS"; //A variable indicating Default Html element in configuration file String DEFAULT_HTML="DefaultHtml"; //A variable indicating Html Path attribute in DefaultHtml Tag. String HTML_PATH="Path"; //A variable indicating CSS Path attribute in DefaultCSS Tag. String CSS_PATH="Path"; //Table Constants String TABLE="TableCallback"; String TABLE_ROW_COUNT="RowCount"; String TABLE_COL_COUNT="ColCount"; String TABLE_CELL_SPACING="CellSpacing"; String TABLE_CELL_PADDING="CellPadding"; String TABLE_BORDER_WIDTH="BorderWidth"; String TABLE_WIDTH="TableWidth"; String TABLE_WIDTH_UNITS="Units"; String TABLE_WIDTH_UNIT="Unit"; String VALUE="Value"; //List Constants String LIST="ListCallback"; String LIST_OL_TYPES="OLTypes"; String LIST_TYPE="Type"; String LIST_UL_TYPES="ULTypes"; String LIST_START="Start"; String LIST_COMPACT="Compact"; //Home Page String HOME_PAGE="HomePage"; String HOME_URL="url"; //Proxy Setting String PROXY_SETTINGS="proxy"; String HTTP_PROXY="http"; String HTTPS_PROXY="https"; String PROXY_SET="set"; String PROXY_HOST="host"; String PROXY_PORT="port"; String SOCKS_PROXY="socks"; String NO_PROXY="nonproxyhost"; String PRE_PARSER = "PRE_PARSER"; String USE_JTIDY = "USE_JTIDY"; } --- NEW FILE: WWEConfigurationAccessXML.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.config; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Properties; import java.util.Vector; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import com.montarasoftware.wwe.callback.WWEListConfigurationVO; import com.montarasoftware.wwe.callback.WWETableConfigurationVO; import com.montarasoftware.wwe.inmemorycache.WWECacheConfigurationVO; /** * A class for parsing the XML configuration file. * @version 1.0 08/01/03 * @author Anuj Jain * @author amit ahuja */ class WWEConfigurationAccessXML extends WWEConfigurationAccess{ //Ref. of DOM for config xml file Document CONFIG_DOM=null; //Configuration file url InputStream m_configStream; /** * Constructor for creating an object of this class. * @param stream Url reprn the configuration file path. */ protected WWEConfigurationAccessXML(InputStream stream){ m_configStream=stream; parsexml(); } /** * parses the configuration xml file and prepares a DOM. */ private void parsexml(){ try{ DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=factory.newDocumentBuilder(); if(m_configStream!=null) { InputStream istream=m_configStream; CONFIG_DOM=builder.parse(istream); } } catch(IOException configexception){ } catch(ParserConfigurationException parseexception){ } catch(SAXException saxexception){ } } /** * Finds the values related to Cache from DOM and populates the * Cache Value Object. * @return Cache Object */ public Object getCacheValueObject(){ if(CONFIG_DOM!=null){ NodeList nlist=CONFIG_DOM.getElementsByTagName(WWEConfigurationConstants.CACHE); Node cacheNode=nlist.item(0); NamedNodeMap nmap=cacheNode.getAttributes(); Node maxNode=nmap.getNamedItem(WWEConfigurationConstants.CACHE_MAX_SIZE); Node timeToLiveNode=nmap.getNamedItem(WWEConfigurationConstants.CACHE_TIME_TO_LIVE); Node accessNode=nmap.getNamedItem(WWEConfigurationConstants.CACHE_Idle_TIME_OUT); String maxSize=maxNode.getNodeValue(); String timeToLive=timeToLiveNode.getNodeValue(); String idleTimeOut=accessNode.getNodeValue(); WWECacheConfigurationVO cacheObject=new WWECacheConfigurationVO(); cacheObject.setMaxSize(Integer.parseInt(maxSize)); cacheObject.setTimeToLive(Long.parseLong(timeToLive)); cacheObject.setIdleTimeOut(Long.parseLong(idleTimeOut)); return cacheObject; //return maxSize+timeToLive+accessTimeOut; } else{ return null; } } /** * Finds the default css path from DOM of configuration fle. * @return URL object reprn the default css path. */ public URL getDefaultCSSPath(){ if(CONFIG_DOM!=null){ NodeList nlist=CONFIG_DOM.getElementsByTagName(WWEConfigurationConstants.DEFAULT_CSS); Node cssNode=nlist.item(0); NamedNodeMap nmap=cssNode.getAttributes(); Node cssPath=nmap.getNamedItem(WWEConfigurationConstants.CSS_PATH); String path=cssPath.getNodeValue(); try{ URL cssURL=new URL(path); return cssURL; }catch(MalformedURLException excep){ //log the error return null; } }else{ return null; } } /** * Finds the default html path from DOM of configuration fle. * @return URL object reprn the default html path. */ public URL getDefaultHTMLPath(){ if(CONFIG_DOM!=null){ NodeList nlist=CONFIG_DOM.getElementsByTagName(WWEConfigurationConstants.DEFAULT_HTML); Node htmlNode=nlist.item(0); NamedNodeMap nmap=htmlNode.getAttributes(); Node htmlPath=nmap.getNamedItem(WWEConfigurationConstants.HTML_PATH); String path=htmlPath.getNodeValue(); try{ URL htmlURL=new URL(path); return htmlURL; }catch(MalformedURLException excep){ //log the error return null; } }else{ return null; } } /** * Finds the values related to Table from DOM and populates the * Table Value Object. * @return Table Object */ public Object getTableValueObject(){ if(CONFIG_DOM!=null) { NodeList nlist=CONFIG_DOM.getElementsByTagName(WWEConfigurationConstants.TABLE); Node tableNode=nlist.item(0); NodeList childList=tableNode.getChildNodes(); WWETableConfigurationVO tableObject=new WWETableConfigurationVO(); tableObject.setRowCount(Integer.parseInt(getNodeValue(childList,WWEConfigurationConstants.TABLE_ROW_COUNT))); tableObject.setColCount(Integer.parseInt(getNodeValue(childList,WWEConfigurationConstants.TABLE_COL_COUNT))); tableObject.setCellSpacing(Integer.parseInt(getNodeValue(childList,WWEConfigurationConstants.TABLE_CELL_SPACING))); tableObject.setCellPadding(Integer.parseInt(getNodeValue(childList,WWEConfigurationConstants.TABLE_CELL_PADDING))); tableObject.setBorderWidth(Integer.parseInt(getNodeValue(childList,WWEConfigurationConstants.TABLE_BORDER_WIDTH))); tableObject.setTableWidth(Integer.parseInt(getNodeValue(childList,WWEConfigurationConstants.TABLE_WIDTH))); /* NodeList unitsChildList=getNode(childList,WWEConfigurationConstants.TABLE_WIDTH_UNITS).getChildNodes(); Vector units=new Vector(); for(int i=0;i<unitsChildList.getLength();i++) { if(unitsChildList.item(i).getNodeName().equals(WWEConfigurationConstants.TABLE_WIDTH_UNIT)) { units.addElement(unitsChildList.item(i).getAttributes().getNamedItem(WWEConfigurationConstants.VALUE).getNodeValue()); } }*/ tableObject.setUnit(getList(childList,WWEConfigurationConstants.TABLE_WIDTH_UNITS,WWEConfigurationConstants.TABLE_WIDTH_UNIT)); return tableObject; } else { return null; } } /** * Finds the values related to List from DOM and populates the * List Value Object. * @return List Object */ public Object getListValueObject(){ if(CONFIG_DOM!=null) { NodeList nlist=CONFIG_DOM.getElementsByTagName(WWEConfigurationConstants.LIST); Node listNode=nlist.item(0); NodeList childList=listNode.getChildNodes(); WWEListConfigurationVO listObject=new WWEListConfigurationVO(); listObject.setOlTypes(getList(childList,WWEConfigurationConstants.LIST_OL_TYPES,WWEConfigurationConstants.LIST_TYPE)); listObject.setUlTypes(getList(childList,WWEConfigurationConstants.LIST_UL_TYPES,WWEConfigurationConstants.LIST_TYPE)); listObject.setListStart(Integer.parseInt(getNodeValue(childList,WWEConfigurationConstants.LIST_START))); listObject.setCompact(getNodeValue(childList,WWEConfigurationConstants.LIST_COMPACT)); return listObject; } else { return null; } } private String getNodeValue(NodeList nodeList,String nodeName) { for(int i=0;i<nodeList.getLength();i++) { if(nodeList.item(i).getNodeName().equals(nodeName)) { return nodeList.item(i).getAttributes().getNamedItem(WWEConfigurationConstants.VALUE).getNodeValue(); } } return null; } private Node getNode(NodeList nodeList,String nodeName) { for(int i=0;i<nodeList.getLength();i++) { if(nodeList.item(i).getNodeName().equals(nodeName)) { return nodeList.item(i); } } return null; } private Vector getList(NodeList nodeList,String nodeName,String childNodeName) { NodeList childList=getNode(nodeList,nodeName).getChildNodes(); Vector vecList=new Vector(); for(int i=0;i<childList.getLength();i++) { if(childList.item(i).getNodeName().equals(childNodeName)) { vecList.addElement(childList.item(i).getAttributes().getNamedItem(WWEConfigurationConstants.VALUE).getNodeValue()); } } return vecList; } /** * Finds the HOME PAGE path from DOM of configuration fle. * @return URL object reprn the default css path. */ public URL getHomePage(){ if(CONFIG_DOM!=null){ NodeList nlist=CONFIG_DOM.getElementsByTagName(WWEConfigurationConstants.HOME_PAGE); if(nlist != null){ Node homepageNode=nlist.item(0); if(homepageNode != null){ NamedNodeMap nmap=homepageNode.getAttributes(); if(nmap != null){ Node homeurl= nmap.getNamedItem(WWEConfigurationConstants.HOME_URL); if(homeurl != null){ String url=homeurl.getNodeValue(); try{ URL homepage=new URL(url); return homepage; }catch(MalformedURLException excep){ //log the error } } } } } } return null; } /** * returns the proxy properties */ public Properties getProxySettings(){ Properties prop = new Properties(); NamedNodeMap nmap = null; Node set = null; Node host = null; Node port = null; if(CONFIG_DOM!=null){ NodeList nlist=CONFIG_DOM.getElementsByTagName(WWEConfigurationConstants.PROXY_SETTINGS); if(nlist != null){ Node proxyNode=nlist.item(0); if(proxyNode != null){ NodeList childList=proxyNode.getChildNodes(); if(childList != null){ Node httpNode=getNode(childList, WWEConfigurationConstants.HTTP_PROXY); if(httpNode != null){ nmap= httpNode.getAttributes(); if(nmap != null){ set = nmap.getNamedItem(WWEConfigurationConstants.PROXY_SET); if(set != null){ prop.setProperty("http.proxySet", set.getNodeValue()); } host = nmap.getNamedItem(WWEConfigurationConstants.PROXY_HOST); if(host != null){ prop.setProperty("http.proxyHost", host.getNodeValue()); } port = nmap.getNamedItem(WWEConfigurationConstants.PROXY_PORT); if(port != null){ prop.setProperty("http.proxyPort", port.getNodeValue()); } } } Node httpsNode=getNode(childList, WWEConfigurationConstants.HTTPS_PROXY); if(httpsNode != null){ nmap=httpsNode.getAttributes(); if(nmap != null){ set = nmap.getNamedItem(WWEConfigurationConstants.PROXY_SET); if(set != null){ prop.setProperty("https.proxySet", set.getNodeValue()); } host = nmap.getNamedItem(WWEConfigurationConstants.PROXY_HOST); if(host != null){ prop.setProperty("https.proxyHost", host.getNodeValue()); } port = nmap.getNamedItem(WWEConfigurationConstants.PROXY_PORT); if(port != null){ prop.setProperty("https.proxyPort", port.getNodeValue()); } } } Node socksNode=getNode(childList, WWEConfigurationConstants.SOCKS_PROXY); if(socksNode != null){ nmap=socksNode.getAttributes(); if(nmap != null){ set = nmap.getNamedItem(WWEConfigurationConstants.PROXY_SET); if(set != null){ prop.setProperty("socks.proxySet", set.getNodeValue()); } host = nmap.getNamedItem(WWEConfigurationConstants.PROXY_HOST); if(host != null){ prop.setProperty("socks.proxyHost", host.getNodeValue()); } port = nmap.getNamedItem(WWEConfigurationConstants.PROXY_PORT); if(port != null){ prop.setProperty("socks.proxyPort", port.getNodeValue()); } } } } } } } return prop; } /** * Finds out if JTidy is to be used as a preparser */ public boolean getUseJTidy(){ boolean retval = false; if(CONFIG_DOM!=null){ NodeList nlist=CONFIG_DOM.getElementsByTagName(WWEConfigurationConstants.PRE_PARSER); if(nlist != null){ Node parserNode=nlist.item(0); if(parserNode != null){ NamedNodeMap nmap=parserNode.getAttributes(); if(nmap != null){ Node useJTidy = nmap.getNamedItem(WWEConfigurationConstants.USE_JTIDY); if(useJTidy != null){ String value=useJTidy.getNodeValue(); retval = Boolean.valueOf(value).booleanValue(); } } } } } return retval; } } --- NEW FILE: WWEConfigurationAccess.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.config; import java.net.URL; import java.util.Properties; /** * An abstract class having methods for getting different * configuration properties. * @version 1.0 08/01/03 * @author Anuj Jain */ public abstract class WWEConfigurationAccess{ /** * Method for getting the cache object from the * configuration resource. * @return Cache Object */ public abstract Object getCacheValueObject(); /** * Method for getting the defualt CSS path from * configuration resource * @return URL object reprn the default css path */ public abstract URL getDefaultCSSPath(); /** * Method for getting the defualt html path from * configuration resource * @return URL object reprn the default html path */ public abstract URL getDefaultHTMLPath(); /** * Method for getting the Table object from the * configuration resource. * @return Table Object */ public abstract Object getTableValueObject(); /** * Method for getting the List object from the * configuration resource. * @return List Object */ public abstract Object getListValueObject(); /** * Finds the HOME PAGE path from DOM of configuration fle. * @return URL object reprn the default css path. */ public abstract URL getHomePage(); /** * Finds the Proxy Settings from DOM of configuration file.. * @return Properties object. */ public abstract Properties getProxySettings(); /** * Finds out if JTidy is to be used as a preparser */ public abstract boolean getUseJTidy(); } --- NEW FILE: WWEConfigurationAccessFactory.java --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ package com.montarasoftware.wwe.config; import java.io.InputStream; /** * A class for getting configuartion file parser. * @version 1.0 08/01/03 * @author Anuj Jain */ public class WWEConfigurationAccessFactory{ //Static ref. of this class(for making this class as singleton) private static WWEConfigurationAccessFactory accessfactory; /** * Constructor for creating an object of this class. * Declared protected as access is not allowed for * classes outside this package. */ protected WWEConfigurationAccessFactory(){ } /** * Gets the object of this class. * @return Instance of this class. */ public static WWEConfigurationAccessFactory getInstance() { if(accessfactory==null){ accessfactory=new WWEConfigurationAccessFactory(); } return accessfactory; } /** * Gets the xml configuration file parser. * @param config Configuration url object. * @return XML Url reprn the configuration file path. */ public WWEConfigurationAccess getConfigurationAccessXML(InputStream config){ WWEConfigurationAccess configxml =new WWEConfigurationAccessXML(config); return configxml; } } |
From: <de...@us...> - 2004-01-05 03:07:01
|
Update of /cvsroot/jxwb/wwe In directory sc8-pr-cvs1:/tmp/cvs-serv15363 Added Files: .classpath license.txt .project Log Message: initial load of HTML editor pane and kit --- NEW FILE: .classpath --- <?xml version="1.0" encoding="UTF-8"?> <classpath> <classpathentry kind="src" path="src"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> <classpathentry kind="lib" path="lib/sac.jar"/> <classpathentry kind="lib" path="lib/flute.jar"/> <classpathentry kind="output" path="bin"/> </classpath> --- NEW FILE: license.txt --- /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2003, 2004 Montara Software. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Montara Software (http://www.montarasoftware.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "WWE" and "Montara Software" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact ml...@mo.... * * 5. Products derived from this software may not be called "WWE", * nor may "WWE" appear in their name, without prior written * permission of Montara Software. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * */ --- NEW FILE: .project --- <?xml version="1.0" encoding="UTF-8"?> <projectDescription> <name>wwe</name> <comment></comment> <projects> </projects> <buildSpec> <buildCommand> <name>org.eclipse.jdt.core.javabuilder</name> <arguments> </arguments> </buildCommand> </buildSpec> <natures> <nature>org.eclipse.jdt.core.javanature</nature> </natures> </projectDescription> |
From: <de...@us...> - 2004-01-05 03:05:42
|
Update of /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/view In directory sc8-pr-cvs1:/tmp/cvs-serv15244/src/com/montarasoftware/wwe/view Log Message: Directory /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/view added to the repository |
From: <de...@us...> - 2004-01-05 03:05:42
|
Update of /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/util In directory sc8-pr-cvs1:/tmp/cvs-serv15244/src/com/montarasoftware/wwe/util Log Message: Directory /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/util added to the repository |
From: <de...@us...> - 2004-01-05 03:05:41
|
Update of /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/inmemorycache In directory sc8-pr-cvs1:/tmp/cvs-serv15244/src/com/montarasoftware/wwe/inmemorycache Log Message: Directory /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/inmemorycache added to the repository |
From: <de...@us...> - 2004-01-05 03:05:41
|
Update of /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/file In directory sc8-pr-cvs1:/tmp/cvs-serv15244/src/com/montarasoftware/wwe/file Log Message: Directory /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/file added to the repository |
From: <de...@us...> - 2004-01-05 03:05:41
|
Update of /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/parser In directory sc8-pr-cvs1:/tmp/cvs-serv15244/src/com/montarasoftware/wwe/parser Log Message: Directory /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/parser added to the repository |
From: <de...@us...> - 2004-01-05 03:05:41
|
Update of /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/popup In directory sc8-pr-cvs1:/tmp/cvs-serv15244/src/com/montarasoftware/wwe/popup Log Message: Directory /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/popup added to the repository |
From: <de...@us...> - 2004-01-05 03:05:41
|
Update of /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/event In directory sc8-pr-cvs1:/tmp/cvs-serv15244/src/com/montarasoftware/wwe/event Log Message: Directory /cvsroot/jxwb/wwe/src/com/montarasoftware/wwe/event added to the repository |