Source for javax.swing.text.FieldView

   1: /* FieldView.java -- 
   2:    Copyright (C) 2004, 2006 Free Software Foundation, Inc.
   3: 
   4: This file is part of GNU Classpath.
   5: 
   6: GNU Classpath is free software; you can redistribute it and/or modify
   7: it under the terms of the GNU General Public License as published by
   8: the Free Software Foundation; either version 2, or (at your option)
   9: any later version.
  10: 
  11: GNU Classpath is distributed in the hope that it will be useful, but
  12: WITHOUT ANY WARRANTY; without even the implied warranty of
  13: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  14: General Public License for more details.
  15: 
  16: You should have received a copy of the GNU General Public License
  17: along with GNU Classpath; see the file COPYING.  If not, write to the
  18: Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  19: 02110-1301 USA.
  20: 
  21: Linking this library statically or dynamically with other modules is
  22: making a combined work based on this library.  Thus, the terms and
  23: conditions of the GNU General Public License cover the whole
  24: combination.
  25: 
  26: As a special exception, the copyright holders of this library give you
  27: permission to link this library with independent modules to produce an
  28: executable, regardless of the license terms of these independent
  29: modules, and to copy and distribute the resulting executable under
  30: terms of your choice, provided that you also meet, for each linked
  31: independent module, the terms and conditions of the license of that
  32: module.  An independent module is a module which is not derived from
  33: or based on this library.  If you modify this library, you may extend
  34: this exception to your version of the library, but you are not
  35: obligated to do so.  If you do not wish to do so, delete this
  36: exception statement from your version. */
  37: 
  38: 
  39: package javax.swing.text;
  40: 
  41: import java.awt.Component;
  42: import java.awt.Container;
  43: import java.awt.FontMetrics;
  44: import java.awt.Graphics;
  45: import java.awt.Insets;
  46: import java.awt.Rectangle;
  47: import java.awt.Shape;
  48: import java.awt.event.ActionEvent;
  49: import java.awt.event.ActionListener;
  50: 
  51: import javax.swing.BoundedRangeModel;
  52: import javax.swing.JTextField;
  53: import javax.swing.SwingUtilities;
  54: import javax.swing.event.ChangeEvent;
  55: import javax.swing.event.ChangeListener;
  56: import javax.swing.event.DocumentEvent;
  57: 
  58: public class FieldView extends PlainView
  59: {
  60:   BoundedRangeModel horizontalVisibility;
  61:   
  62:   /** Caches the preferred span of the X axis. It is invalidated by
  63:    * setting it to -1f. This is done when text in the document
  64:    * is inserted, removed or changed. The value is corrected as
  65:    * soon as calculateHorizontalSpan() is called. 
  66:    */
  67:   float cachedSpan = -1f;
  68: 
  69:   public FieldView(Element elem)
  70:   {
  71:     super(elem);
  72:     
  73:   }
  74:   
  75:   /** Checks whether the given container is a JTextField. If so
  76:    * it retrieves the textfield's horizontalVisibility instance.
  77:    * 
  78:    * <p>This method should be only called when the view's container
  79:    * is valid. Naturally that would be the setParent() method however
  80:    * that method is not overridden in the RI and that is why we chose
  81:    * paint() instead.</p>
  82:    */ 
  83:   private void checkContainer()
  84:   {
  85:     Container c = getContainer();
  86:     
  87:     if (c instanceof JTextField)
  88:       {
  89:         horizontalVisibility = ((JTextField) c).getHorizontalVisibility();
  90:         
  91:         // Provokes a repaint when the BoundedRangeModel's values change
  92:         // (which is what the RI does).
  93:         horizontalVisibility.addChangeListener(new ChangeListener(){
  94:           public void stateChanged(ChangeEvent event) {
  95:             getContainer().repaint();
  96:           };
  97:         });
  98: 
  99:         // It turned out that the span calculated at this point is wrong
 100:         // and needs to be recalculated (e.g. a different font setting is
 101:         // not taken into account).
 102:         calculateHorizontalSpan();
 103:         
 104:         // Initializes the BoundedRangeModel properly.
 105:         updateVisibility();
 106:       }
 107:     
 108:   }
 109:   
 110:   private void updateVisibility()
 111:   {
 112:     JTextField tf = (JTextField) getContainer();
 113:     Insets insets = tf.getInsets();
 114: 
 115:     int width = tf.getWidth() - insets.left - insets.right;
 116:         
 117:     horizontalVisibility.setMaximum(Math.max((int) ((cachedSpan != -1f)
 118:                                                  ? cachedSpan
 119:                                                  : calculateHorizontalSpan()),
 120:                                              width));
 121:         
 122:     horizontalVisibility.setExtent(width - 1);
 123:   }
 124: 
 125:   protected FontMetrics getFontMetrics()
 126:   {
 127:     Component container = getContainer();
 128:     return container.getFontMetrics(container.getFont());
 129:   }
 130: 
 131:   /**
 132:    * Vertically centers the single line of text within the
 133:    * bounds of the input shape. The returned Rectangle is centered
 134:    * vertically within <code>shape</code> and has a height of the
 135:    * preferred span along the Y axis. Horizontal adjustment is done according
 136:    * to the horizontalAligment property of the component that is rendered.
 137:    *
 138:    * @param shape the shape within which the line is beeing centered
 139:    */
 140:   protected Shape adjustAllocation(Shape shape)
 141:   {
 142:     // Return null when the original allocation is null (like the RI).
 143:     if (shape == null)
 144:       return null;
 145:     
 146:     Rectangle rectIn = shape.getBounds();
 147:     // vertical adjustment
 148:     int height = (int) getPreferredSpan(Y_AXIS);
 149:     int y = rectIn.y + (rectIn.height - height) / 2;
 150:     // horizontal adjustment
 151:     JTextField textField = (JTextField) getContainer();
 152:     int width = (int) ((cachedSpan != -1f) ? cachedSpan : calculateHorizontalSpan());
 153:     int x;
 154:     if (horizontalVisibility != null && horizontalVisibility.getExtent() < width)
 155:         x = rectIn.x - horizontalVisibility.getValue();
 156:     else
 157:       switch (textField.getHorizontalAlignment())
 158:         {
 159:         case JTextField.CENTER:
 160:           x = rectIn.x + (rectIn.width - width) / 2;
 161:           break;
 162:         case JTextField.RIGHT:
 163:           x = rectIn.x + (rectIn.width - width - 1);
 164:           break;
 165:         case JTextField.TRAILING:
 166:           if (textField.getComponentOrientation().isLeftToRight())
 167:             x = rectIn.x + (rectIn.width - width - 1);
 168:           else
 169:             x = rectIn.x;
 170:           break;
 171:         case JTextField.LEADING:
 172:           if (textField.getComponentOrientation().isLeftToRight())
 173:             x = rectIn.x;
 174:           else
 175:             x = rectIn.x + (rectIn.width - width - 1);
 176:           break;
 177:         case JTextField.LEFT:
 178:         default:
 179:           x = rectIn.x;
 180:           break;
 181:         }
 182:     
 183:     return new Rectangle(x, y, width, height);
 184:   }
 185: 
 186:   public float getPreferredSpan(int axis)
 187:   {
 188:     if (axis != X_AXIS && axis != Y_AXIS)
 189:       throw new IllegalArgumentException();
 190: 
 191: 
 192:     if (axis == Y_AXIS)
 193:       return super.getPreferredSpan(axis);
 194: 
 195:     if (cachedSpan != -1f)
 196:       return cachedSpan;
 197:     
 198:     return calculateHorizontalSpan();
 199:   }
 200:   
 201:   /** Calculates and sets the horizontal span and stores the value
 202:    * in cachedSpan.
 203:    */ 
 204:   private float calculateHorizontalSpan()
 205:   {
 206:     Segment s = getLineBuffer();
 207:     Element elem = getElement();
 208: 
 209:     try
 210:       {
 211:         elem.getDocument().getText(elem.getStartOffset(),
 212:                                           elem.getEndOffset() - 1,
 213:                                           s);
 214:         
 215:         return cachedSpan = Utilities.getTabbedTextWidth(s, getFontMetrics(), 0, this, s.offset);
 216:       }
 217:     catch (BadLocationException e)
 218:       {
 219:     // Should never happen
 220:     AssertionError ae = new AssertionError();
 221:     ae.initCause(e);
 222:     throw ae;
 223:       }
 224:   }
 225: 
 226:   public int getResizeWeight(int axis)
 227:   {
 228:     return axis = axis == X_AXIS ? 1 : 0;
 229:   }
 230:   
 231:   public Shape modelToView(int pos, Shape a, Position.Bias bias)
 232:     throws BadLocationException
 233:   {
 234:     Shape newAlloc = adjustAllocation(a);
 235:     return super.modelToView(pos, newAlloc, bias);
 236:   }
 237:   
 238:   public void paint(Graphics g, Shape s)
 239:   {
 240:     if (horizontalVisibility == null)
 241:       checkContainer();
 242: 
 243:     Shape newAlloc = adjustAllocation(s);
 244:     
 245:     Shape clip = g.getClip();
 246:     if (clip != null)
 247:       {
 248:         // Reason for this: The allocation area is always determined by the
 249:         // size of the component (and its insets) regardless of whether
 250:         // parts of the component are invisible or not (e.g. when the
 251:         // component is part of a JScrollPane and partly moved out of
 252:         // the user-visible range). However the clip of the Graphics
 253:         // instance may be adjusted properly to that condition but
 254:         // does not handle insets. By calculating the intersection
 255:         // we get the correct clip to paint the text in all cases.
 256:         Rectangle r = s.getBounds();
 257:         Rectangle cb = clip.getBounds();
 258:         SwingUtilities.computeIntersection(r.x, r.y, r.width, r.height, cb);
 259: 
 260:         g.setClip(cb);
 261:       }
 262:     else
 263:       g.setClip(s);
 264: 
 265:     super.paint(g, newAlloc);
 266:     g.setClip(clip);
 267:     
 268:   }
 269: 
 270:   public void insertUpdate(DocumentEvent ev, Shape shape, ViewFactory vf)
 271:   {
 272:     cachedSpan = -1f;
 273:     
 274:     if (horizontalVisibility != null)
 275:       updateVisibility();
 276:     
 277:     Shape newAlloc = adjustAllocation(shape);
 278:     
 279:     super.insertUpdate(ev, newAlloc, vf);
 280:     getContainer().repaint();
 281:   }
 282: 
 283:   public void removeUpdate(DocumentEvent ev, Shape shape, ViewFactory vf)
 284:   {
 285:     cachedSpan = -1f;
 286:     
 287:     if (horizontalVisibility != null)
 288:       updateVisibility();
 289: 
 290:     Shape newAlloc = adjustAllocation(shape);
 291:     super.removeUpdate(ev, newAlloc, vf);
 292:     getContainer().repaint();
 293:   }
 294: 
 295:   public void changedUpdate(DocumentEvent ev, Shape shape, ViewFactory vf)
 296:   {
 297:     cachedSpan = -1f;
 298:     
 299:     if (horizontalVisibility != null)
 300:       updateVisibility();
 301: 
 302:     Shape newAlloc = adjustAllocation(shape);
 303:     super.changedUpdate(ev, newAlloc, vf);
 304:     getContainer().repaint();
 305:   }
 306: 
 307:   public int viewToModel(float fx, float fy, Shape a, Position.Bias[] bias)
 308:   {
 309:     return super.viewToModel(fx, fy, adjustAllocation(a), bias);
 310:   }
 311:   
 312: }