File: HtmlTest.java

package info (click to toggle)
javahelp2 2.0.05.ds1-10
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 2,552 kB
  • sloc: java: 28,795; xml: 1,631; makefile: 16; sh: 2
file content (349 lines) | stat: -rw-r--r-- 10,681 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
/*
 * @(#)HtmlTest.java	1.2 06/10/30
 * 
 * Copyright (c) 2006 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 * 
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 * 
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 * 
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 * 
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import javax.swing.tree.*;
import javax.swing.undo.*;
import java.awt.*;
import java.util.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.IOException;

/**
 * Simple wrapper around JEditorPane to browse html.
 * Useful to browse the javadoc for swing... 
 * java HtmlTest file:/path-to-swing-docs/packages.html
 */
public class HtmlTest {

    public static void main(String[] args) {
	Properties props =  System.getProperties();
	props.put("http.proxyHost", "webcache1.eng");
	props.put("http.proxyPort", "8080");

	if (args.length != 1) {
	    System.err.println("need URL argument");
	    System.exit(1);
	}
	try {
	    URL u = new URL(args[0]);
	    JEditorPane html = new JEditorPane(u);
	    html.setEditable(false);
	    html.addHyperlinkListener(new Hyperactive());
	    html.setBackground(Color.white);
	    JScrollPane scroller = new JScrollPane();
	    JViewport vp = scroller.getViewport();
	    vp.add(html);
	    vp.setBackingStoreEnabled(true);

	    JFrame f = new JFrame("testing");
	    f.getContentPane().setLayout(new BorderLayout());
	    f.getContentPane().add("Center", scroller);
	    f.pack();
	    f.setSize(600, 600);
	    f.setVisible(true);

	    JFrame elems = new JFrame("elements");
	    Container fContentPane = elems.getContentPane();
	    fContentPane.setLayout(new BorderLayout());
	    fContentPane.add(new ElementTreePanel(html));
	    elems.pack();
	    elems.show();
	} catch (MalformedURLException e) {
	    System.err.println("Bad url");
	    System.exit(1);
	} catch (IOException ioe) {
	    System.err.println("IOException: " + ioe.getMessage());
	    System.exit(1);
	}
    }

    static class Hyperactive implements HyperlinkListener {

	/**
	 * Notification of a change relative to a 
	 * hyperlink.
	 */
        public void hyperlinkUpdate(HyperlinkEvent e) {
	    System.err.println("link event: " + e);
	    if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
		JEditorPane html = (JEditorPane) e.getSource();
		if (e instanceof HTMLFrameHyperlinkEvent) {
		    HTMLFrameHyperlinkEvent  evt = (HTMLFrameHyperlinkEvent)e;
		    HTMLDocument doc = (HTMLDocument)html.getDocument();
		    doc.processHTMLFrameHyperlinkEvent(evt);
		} else {
		    try {
			html.setPage(e.getURL());
		    } catch (Throwable t) {
			t.printStackTrace();
		    }
		}
	    }
	}
    }

/**
 * Displays a tree showing all the elements in a text Document. Selecting
 * a node will result in reseting the selection of the JTextComponent.
 *
 * @author Scott Violet
 * @version 1.1 04/28/98
 */
static class ElementTreePanel extends JPanel implements DocumentListener, TreeSelectionListener {
    /** Tree showing the documents element structure. */
    protected JTree             tree;
    /** Text component showing elemenst for. */
    protected JTextComponent    editor;
    /** Model for the tree. */
    protected DefaultTreeModel  treeModel;

    public ElementTreePanel(JTextComponent editor) {
	this.editor = editor;

	Document document = editor.getDocument();

	// Create the tree.
	treeModel = new DefaultTreeModel((TreeNode)document.
					 getDefaultRootElement());
	tree = new JTree(treeModel) {
	    public String convertValueToText(Object value, boolean selected,
					     boolean expanded, boolean leaf,
					     int row, boolean hasFocus) {
		Element        e = (Element)value;
		AttributeSet   as = e.getAttributes().copyAttributes();
		String         asString;

		if(as != null) {
		    StringBuffer       retBuffer = new StringBuffer("[");
		    Enumeration        names = as.getAttributeNames();
	    
		    while(names.hasMoreElements()) {
			Object        nextName = names.nextElement();

			if(nextName != StyleConstants.ResolveAttribute) {
			    retBuffer.append(" ");
			    retBuffer.append(nextName);
			    retBuffer.append("=");
			    retBuffer.append(as.getAttribute(nextName));
			}
		    }
		    retBuffer.append(" ]");
		    asString = retBuffer.toString();
		}
		else
		    asString = "[ ]";

		if(e.isLeaf())
		    return "LEAF: " + e.getName() + " Attributes: " + asString;
		return "Branch: " + e.getName() + " Attributes: " +
 		        asString;
	    }
	};
	tree.addTreeSelectionListener(this);
	// become a listener on the document to update the tree.
	document.addDocumentListener(this);

	// configure the panel and frame containing it.
	setLayout(new BorderLayout());
	add(new JScrollPane(tree), BorderLayout.CENTER);

	// Add a label above tree to describe what is being shown
	JLabel     label = new JLabel("Elements that make up the current document", SwingConstants.CENTER);

	label.setFont(new Font("Dialog", Font.BOLD, 14));
	add(label, BorderLayout.NORTH);

	setPreferredSize(new Dimension(400, 400));
    }


    // DocumentListener

    /**
     * Gives notification that there was an insert into the document.  The 
     * given range bounds the freshly inserted region.
     *
     * @param e the document event
     */
    public void insertUpdate(DocumentEvent e) {
	updateTree(e);
    }

    /**
     * Gives notification that a portion of the document has been 
     * removed.  The range is given in terms of what the view last
     * saw (that is, before updating sticky positions).
     *
     * @param e the document event
     */
    public void removeUpdate(DocumentEvent e) {
	updateTree(e);
    }

    /**
     * Gives notification that an attribute or set of attributes changed.
     *
     * @param e the document event
     */
    public void changedUpdate(DocumentEvent e) {
	updateTree(e);
    }

    // TreeSelectionListener

    /** 
      * Called whenever the value of the selection changes.
      * @param e the event that characterizes the change.
      */
    public void valueChanged(TreeSelectionEvent e) {
	JTree       tree = getTree();

	if(tree.getSelectionCount() == 1) {
	    TreePath      selPath = tree.getSelectionPath();
	    Element       selElement = (Element)selPath.getLastPathComponent();

	    getEditor().select(selElement.getStartOffset(),
			       selElement.getEndOffset());
	}
    }

    // Local methods

    /**
     * @return tree showing elements.
     */
    protected JTree getTree() {
	return tree;
    }

    /**
     * @return JTextComponent showing elements for.
     */
    protected JTextComponent getEditor() {
	return editor;
    }

    /**
     * @return root element of editor.
     */
    protected Element getRootElement() {
	return getEditor().getDocument().getDefaultRootElement();
    }

    /**
     * @return TreeModel implementation used to represent the elements.
     */
    public DefaultTreeModel getTreeModel() {
	return treeModel;
    }

    /**
     * Updates the tree based on the event type. This will invoke either
     * updateTree with the root element, or handleChange.
     */
    protected void updateTree(DocumentEvent event) {
	updateTree(event, getRootElement());
    }

    /**
     * Creates TreeModelEvents based on the DocumentEvent and messages
     * the treemodel. This recursively invokes this method with children
     * elements.
     * @param event indicates what elements in the tree hierarchy have
     * changed.
     * @param element Current element to check for changes against.
     */
    protected void updateTree(DocumentEvent event, Element element) {
        DocumentEvent.ElementChange ec = event.getChange(element);

        if (ec != null) {
	    Element[]       removed = ec.getChildrenRemoved();
	    Element[]       added = ec.getChildrenAdded();
	    int             startIndex = ec.getIndex();

	    // Check for removed.
	    if(removed != null && removed.length > 0) {
		int[]            indices = new int[removed.length];

		for(int counter = 0; counter < removed.length; counter++) {
		    indices[counter] = startIndex + counter;
		}
		getTreeModel().nodesWereRemoved((TreeNode)element, indices,
						removed);
	    }
	    // check for added
	    if(added != null && added.length > 0) {
		int[]            indices = new int[added.length];

		for(int counter = 0; counter < added.length; counter++) {
		    indices[counter] = startIndex + counter;
		}
		getTreeModel().nodesWereInserted((TreeNode)element, indices);
	    }
        }
	else if(!element.isLeaf()) {
	    // If the event is a CHANGE, then need to forward to all
	    // elements in effected range.
	    // Otherwise, only forward to element at the offset of the
	    // event.
	    if(event.getType() == DocumentEvent.EventType.CHANGE) {
		int        startIndex = element.getElementIndex
		                       (event.getOffset());
		int        endIndex = Math.min(element.getElementCount() - 1,
					       element.getElementIndex
				     (event.getOffset() + event.getLength()));

		if(startIndex != -1 && endIndex != -1) {
		    for(int counter = startIndex; counter <= endIndex;
			counter++) {
			updateTree(event, element.getElement(counter));
		    }
		}
	    }
	    else {
		// Element hasn't changed, find the child in the effected
		// region and forward.
		int       childIndex = element.getElementIndex
		                       (event.getOffset());

		if(childIndex >= 0 && childIndex < element.getElementCount())
		    updateTree(event, element.getElement(childIndex));
	    }
	}
	else {
	    // Element is a leaf, assume it changed
	    getTreeModel().nodeChanged((TreeNode)element);
	}
    }
}

}