home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Chip 1998 November
/
Chip_1998-11_cd.bin
/
tema
/
Cafe
/
jfc.bin
/
PlainView.java
< prev
next >
Wrap
Text File
|
1998-02-26
|
19KB
|
508 lines
/*
* @(#)PlainView.java 1.46 98/02/05
*
* Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved.
*
* This software is the confidential and proprietary information of Sun
* Microsystems, Inc. ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Sun.
*
* SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
* SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES
* SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
* THIS SOFTWARE OR ITS DERIVATIVES.
*
*/
package com.sun.java.swing.text;
import java.util.Vector;
import java.util.Properties;
import java.awt.*;
import com.sun.java.swing.event.*;
/**
* Implements View interface for a simple multi-line text view
* that has text in one font and color. The view represents each
* child element as a line of text.
*
* @author Timothy Prinzing
* @version 1.46 02/05/98
* @see View
*/
public class PlainView extends View implements TabExpander {
/**
* Constructs a new view wrapped on an element.
*
* @param elem the element
*/
public PlainView(Element elem) {
super(elem);
lineBuffer = new Segment();
}
/**
* Returns the tab size set for the document, defaulting to 8.
*
* @return the tab size
*/
protected int getTabSize() {
Integer i = (Integer) getDocument().getProperty(PlainDocument.tabSizeAttribute);
int size = (i != null) ? i.intValue() : 8;
return size;
}
/**
* Returns the max number of characters per line set for the document,
*
* @return the max number
*/
protected int getLineLimit() {
Integer lineLimit = (Integer) getDocument().getProperty(PlainDocument.lineLimitAttribute);
if(lineLimit == null) {
int width = 0;
int totalLines = getElement().getElementCount();
for(int i = 0; i < totalLines; i++) {
Element line = getElement().getElement(i);
int p0 = line.getStartOffset();
int p1 = line.getEndOffset();
if(p1 - p0 > width) {
width = p1 - p0;
}
}
lineLimit = new Integer(width);
getDocument().putProperty(PlainDocument.lineLimitAttribute, lineLimit);
}
return lineLimit.intValue();
}
/**
* Renders a line of text, suppressing whitespace at the end
* and exanding any tabs. This is implemented to make calls
* to the methods <code>drawUnselectedText</code> and
* <code>drawSelectedText</code> so that the way selected and
* unselected text are rendered can be customized.
*
* @param lineIndex the line to draw
* @param g the graphics context
* @param x the starting X position
* @param y the starting Y position
* @see #drawUnselectedText
* @see #drawSelectedText
*/
protected void drawLine(int lineIndex, Graphics g, int x, int y) {
try {
Element line = getElement().getElement(lineIndex);
int p0 = line.getStartOffset();
int p1 = line.getEndOffset();
p1 = Math.min(getDocument().getLength(), p1);
if (sel0 == sel1) {
// no selection
drawUnselectedText(g, x, y, p0, p1);
} else if ((p0 >= sel0 && p0 <= sel1) && (p1 >= sel0 && p1 <= sel1)) {
drawSelectedText(g, x, y, p0, p1);
} else if (sel0 >= p0 && sel0 <= p1) {
if (sel1 >= p0 && sel1 <= p1) {
x = drawUnselectedText(g, x, y, p0, sel0);
x = drawSelectedText(g, x, y, sel0, sel1);
drawUnselectedText(g, x, y, sel1, p1);
} else {
x = drawUnselectedText(g, x, y, p0, sel0);
drawSelectedText(g, x, y, sel0, p1);
}
} else if (sel1 >= p0 && sel1 <= p1) {
x = drawSelectedText(g, x, y, p0, sel1);
drawUnselectedText(g, x, y, sel1, p1);
} else {
drawUnselectedText(g, x, y, p0, p1);
}
} catch (BadLocationException e) {
throw new StateInvariantError("Can't render line: " + lineIndex);
}
}
/**
* Renders the given range in the model as normal unselected
* text.
*
* @param g the graphics context
* @param x the starting X coordinate
* @param y the starting Y coordinate
* @param p0 the beginning position in the model
* @param p1 the ending position in the model
* @returns the location of the end of the range
* @exception BadLocationException if the range is invalid
*/
protected int drawUnselectedText(Graphics g, int x, int y,
int p0, int p1) throws BadLocationException {
g.setColor(unselected);
Document doc = getDocument();
doc.getText(p0, p1 - p0, lineBuffer);
return Utilities.drawTabbedText(lineBuffer, x, y, g, this, p0);
}
/**
* Renders the given range in the model as selected text. This
* is implemented to render the text in the color specified in
* the hosting component. It assumes the highlighter will render
* the selected background.
*
* @param g the graphics context
* @param x the starting X coordinate
* @param y the starting Y coordinate
* @param p0 the beginning position in the model
* @param p1 the ending position in the model
* @returns the location of the end of the range.
* @exception BadLocationException if the range is invalid
*/
protected int drawSelectedText(Graphics g, int x,
int y, int p0, int p1) throws BadLocationException {
g.setColor(selected);
Document doc = getDocument();
doc.getText(p0, p1 - p0, lineBuffer);
return Utilities.drawTabbedText(lineBuffer, x, y, g, this, p0);
}
/**
* Gives access to a buffer that can be used to fetch
* text from the associated document.
*
* @returns the buffer
*/
protected final Segment getLineBuffer() {
return lineBuffer;
}
final void updateMetrics() {
Component host = getContainer();
Font f = host.getFont();
metrics = host.getFontMetrics(f);
int columnWidth = metrics.charWidth('m');
width = getLineLimit() * columnWidth;
tabSize = getTabSize() * columnWidth;
}
// ---- View methods ----------------------------------------------------
/**
* Sets the parent of the view.
* The parent calls this on the child to tell it who its
* parent is. If this is null, the view has been removed
* and we need to remove the associated component from its
* parent. This is used here to determine what the hosting
* component is.
*
* @param p the parent view
*/
public void setParent(View p) {
super.setParent(p);
host = (JTextComponent) getContainer();
}
/**
* Determines the preferred span for this view along an
* axis.
*
* @param axis may be either X_AXIS or Y_AXIS
* @returns 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.
*/
public float getPreferredSpan(int axis) {
updateMetrics();
switch (axis) {
case View.X_AXIS:
return width;
case View.Y_AXIS:
return getElement().getElementCount() * metrics.getHeight();
default:
throw new IllegalArgumentException("Invalid axis: " + axis);
}
}
/**
* Renders using the given rendering surface and area on that surface.
* The view may need to do layout and create child views to enable
* itself to render into the given allocation.
*
* @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 alloc = a.getBounds();
tabBase = alloc.x;
g.setFont(host.getFont());
sel0 = host.getSelectionStart();
sel1 = host.getSelectionEnd();
unselected = (host.isEnabled()) ?
host.getForeground() : host.getDisabledTextColor();
Caret c = host.getCaret();
selected = c.isSelectionVisible() ? host.getSelectedTextColor() : unselected;
updateMetrics();
// If the lines are clipped then we don't expend the effort to
// try and paint them. Since all of the lines are the same height
// with this object, determination of what lines need to be repainted
// is quick.
Rectangle clip = g.getClipBounds();
int fontHeight = metrics.getHeight();
int heightBelow = (alloc.y + alloc.height) - (clip.y + clip.height);
int linesBelow = Math.max(0, heightBelow / fontHeight);
int heightAbove = clip.y - alloc.y;
int linesAbove = Math.max(0, heightAbove / fontHeight);
int linesTotal = alloc.height / fontHeight;
// update the visible lines
Rectangle lineArea = lineToRect(a, linesAbove);
int y = lineArea.y + metrics.getAscent();
int x = lineArea.x;
Element map = getElement();
int endLine = Math.min(map.getElementCount(), linesTotal - linesBelow);
for (int line = linesAbove; line < endLine; line++) {
drawLine(line, g, x, y);
y += fontHeight;
}
}
/**
* Desired span has changed.
*
* @param child the child view
* @param width true if the width preference has changed
* @param height true if the height preference has changed
* @see com.sun.java.swing.JComponent#revalidate
*/
public void preferenceChanged(View child, boolean width, boolean height) {
getDocument().putProperty(PlainDocument.lineLimitAttribute, null);
super.preferenceChanged(child, width, height);
}
/**
* Provides a mapping from the document model coordinate space
* to the coordinate space of the view mapped to it.
*
* @param pos the position to convert
* @param a the allocated region to render into
* @return the bounding box of the given position
* @exception BadLocationException if the given position does not
* represent a valid location in the associated document
* @see View#modelToView
*/
public Shape modelToView(int pos, Shape a) throws BadLocationException {
// line coordinates
Document doc = getDocument();
Element map = getElement();
int lineIndex = map.getElementIndex(pos);
Rectangle lineArea = lineToRect(a, lineIndex);
tabBase = lineArea.x;
// determine span from the start of the line
tabBase = lineArea.x;
Element line = map.getElement(lineIndex);
int p0 = line.getStartOffset();
doc.getText(p0, pos - p0, lineBuffer);
int xOffs = Utilities.getTabbedTextWidth(lineBuffer, metrics, 0, this, p0);
// fill in the results and return
lineArea.x += xOffs;
lineArea.width = 1;
lineArea.height = metrics.getHeight();
return lineArea;
}
/**
* Provides a mapping from the view coordinate space to the logical
* coordinate space of the model.
*
* @param fx the X coordinate
* @param fy the Y coordinate
* @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 fx, float fy, Shape a) {
Rectangle alloc = a.getBounds();
Document doc = getDocument();
int x = (int) fx;
int y = (int) fy;
if (y < alloc.y) {
// above the area covered by this icon, so the the position
// is assumed to be the start of the coverage for this view.
return getStartOffset();
} else if (y > alloc.y + alloc.height) {
// below the area covered by this icon, so the the position
// is assumed to be the end of the coverage for this view.
return getEndOffset() - 1;
} else {
// positioned within the coverage of this view vertically,
// so we figure out which line the point corresponds to.
// if the line is greater than the number of lines contained, then
// simply use the last line as it represents the last possible place
// we can position to.
Element map = doc.getDefaultRootElement();
int lineIndex = Math.abs((y - alloc.y) / metrics.getHeight() );
if (lineIndex >= map.getElementCount()) {
return getEndOffset() - 1;
}
Element line = map.getElement(lineIndex);
if (x < alloc.x) {
// point is to the left of the line
return line.getStartOffset();
} else if (x > alloc.x + alloc.width) {
// point is to the right of the line
return line.getEndOffset() - 1;
} else {
// Determine the offset into the text
try {
int p0 = line.getStartOffset();
int p1 = line.getEndOffset() - 1;
doc.getText(p0, p1 - p0, lineBuffer);
tabBase = alloc.x;
int offs = p0 + Utilities.getTabbedTextOffset(lineBuffer, metrics,
tabBase, x, this, p0);
return offs;
} catch (BadLocationException e) {
// should not happen
return -1;
}
}
}
}
/**
* Gives notification that something was inserted into the document
* in a location that this view is responsible for.
*
* @param changes the change information from the associated document
* @param a the current allocation of the view
* @param f the factory to use to rebuild if the view has children
* @see View#insertUpdate
*/
public void insertUpdate(DocumentEvent changes, Shape a, ViewFactory f) {
updateDamage(changes, a, f);
}
/**
* Gives notification that something was removed from the document
* in a location that this view is responsible for.
*
* @param changes the change information from the associated document
* @param a the current allocation of the view
* @param f the factory to use to rebuild if the view has children
* @see View#removeUpdate
*/
public void removeUpdate(DocumentEvent changes, Shape a, ViewFactory f) {
updateDamage(changes, a, f);
}
/**
* Gives notification from the document that attributes were changed
* in a location that this view is responsible for.
*
* @param changes the change information from the associated document
* @param a the current allocation of the view
* @param f the factory to use to rebuild if the view has children
* @see View#changedUpdate
*/
public void changedUpdate(DocumentEvent changes, Shape a, ViewFactory f) {
updateDamage(changes, a, f);
}
// --- TabExpander methods ------------------------------------------
/**
* Returns the next tab stop position after a given reference position.
* This implementation does not support things like centering so it
* ignores the tabOffset argument.
*
* @param x the current position
* @param tabOffset the position within the text stream
* that the tab occurred at.
* @return the tab stop, measured in points
*/
public float nextTabStop(float x, int tabOffset) {
int ntabs = (((int) x) - tabBase) / tabSize;
return (ntabs + 1) * tabSize;
}
// --- local methods ------------------------------------------------
/*
* We can damage the line that begins the range to cover
* the case when the insert is only on one line. If lines
* are added or removed we will damage the whole view.
*/
void updateDamage(DocumentEvent changes, Shape a, ViewFactory f) {
if (host.isShowing()) {
updateMetrics();
Element elem = getElement();
DocumentEvent.ElementChange ec = changes.getChange(elem);
Element[] added = (ec != null) ? ec.getChildrenAdded() : null;
Element[] removed = (ec != null) ? ec.getChildrenRemoved() : null;
if (((added != null) && (added.length > 0)) ||
((removed != null) && (removed.length > 0))) {
preferenceChanged(null, true, true);
host.repaint();
} else {
preferenceChanged(null, true, false);
Element map = getElement();
int line = map.getElementIndex(changes.getOffset());
damageLineRange(line, line, a, host);
}
}
}
private void damageLineRange(int line0, int line1, Shape a, Component host) {
if (a != null) {
Rectangle area0 = lineToRect(a, line0);
Rectangle area1 = lineToRect(a, line1);
if ((area0 != null) && (area1 != null)) {
Rectangle damage = area0.union(area1);
host.repaint(damage.x, damage.y, damage.width, damage.height);
} else {
host.repaint();
}
}
}
private Rectangle lineToRect(Shape a, int line) {
Rectangle r = null;
if (metrics != null) {
Rectangle alloc = a.getBounds();
r = new Rectangle(alloc.x, alloc.y + (line * metrics.getHeight()),
alloc.width, metrics.getHeight());
}
return r;
}
// --- member variables -----------------------------------------------
/**
* Font metrics for the currrent font.
*/
protected FontMetrics metrics;
Segment lineBuffer;
int width;
int tabSize;
int tabBase;
JTextComponent host;
int sel0;
int sel1;
Color unselected;
Color selected;
}