Source for javax.swing.text.PlainDocument

   1: /* PlainDocument.java --
   2:    Copyright (C) 2002, 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.util.ArrayList;
  42: 
  43: /**
  44:  * A simple document class which maps lines to {@link Element}s.
  45:  *
  46:  * @author Anthony Balkissoon (abalkiss@redhat.com)
  47:  * @author Graydon Hoare (graydon@redhat.com)
  48:  * @author Roman Kennke (roman@kennke.org)
  49:  * @author Michael Koch (konqueror@gmx.de)
  50:  * @author Robert Schuster (robertschuster@fsfe.org)
  51:  */
  52: public class PlainDocument extends AbstractDocument
  53: {
  54:   private static final long serialVersionUID = 4758290289196893664L;
  55:     
  56:   public static final String lineLimitAttribute = "lineLimit";
  57:   public static final String tabSizeAttribute = "tabSize";
  58: 
  59:   private BranchElement rootElement;
  60:   private int tabSize;
  61:   
  62:   public PlainDocument()
  63:   {
  64:     this(new GapContent());
  65:   }
  66: 
  67:   public PlainDocument(AbstractDocument.Content content)
  68:   {
  69:     super(content);
  70:     tabSize = 8;
  71:     rootElement = (BranchElement) createDefaultRoot();
  72:   }
  73: 
  74:   private void reindex()
  75:   {
  76:     Element[] lines;
  77:     try 
  78:       {
  79:         String str = content.getString(0, content.length());
  80: 
  81:         ArrayList elts = new ArrayList();
  82:         int j = 0;
  83:         for (int i = str.indexOf('\n', 0); i != -1; i = str.indexOf('\n', i + 1))
  84:           {
  85:             elts.add(createLeafElement(rootElement, SimpleAttributeSet.EMPTY, j, i + 1));
  86:             j = i + 1;
  87:           }
  88:         
  89:         if (j < content.length())
  90:           elts.add(createLeafElement(rootElement, SimpleAttributeSet.EMPTY, j, content.length()));
  91:         
  92:         lines = new Element[elts.size()];
  93:         for (int i = 0; i < elts.size(); ++i)
  94:           lines[i] = (Element) elts.get(i);
  95:       }
  96:     catch (BadLocationException e)
  97:       {
  98:         lines = new Element[1];
  99:         lines[0] = createLeafElement(rootElement, SimpleAttributeSet.EMPTY, 0, 1);
 100:       }
 101: 
 102:     ((BranchElement) rootElement).replace(0, rootElement.getElementCount(), lines);
 103:   }
 104: 
 105:   protected AbstractDocument.AbstractElement createDefaultRoot()
 106:   {
 107:     BranchElement root =
 108:       (BranchElement) createBranchElement(null, SimpleAttributeSet.EMPTY);
 109: 
 110:     Element[] array = new Element[1];
 111:     array[0] = createLeafElement(root, SimpleAttributeSet.EMPTY, 0, 1);
 112:     root.replace(0, 0, array);
 113:     
 114:     return root;
 115:   }
 116: 
 117:   protected void insertUpdate(DefaultDocumentEvent event,
 118:                               AttributeSet attributes)
 119:   {
 120:     int offset = event.getOffset();
 121:     int eventLength = event.getLength();
 122:     int end = offset + event.getLength();
 123:     int oldElementIndex, elementIndex = rootElement.getElementIndex(offset);
 124:     Element firstElement = rootElement.getElement(elementIndex);
 125:     oldElementIndex = elementIndex;
 126:         
 127:     // If we're inserting immediately after a newline we have to fix the 
 128:     // Element structure (but only if we are dealing with a line which
 129:     // has not existed as Element before).
 130:     if (offset > 0 && firstElement.getStartOffset() != offset)
 131:       {
 132:         try
 133:         {
 134:           String s = getText(offset - 1, 1);
 135:           if (s.equals("\n") )
 136:             {
 137:               int newEl2EndOffset = end;
 138:               boolean replaceNext = false;
 139:               if (rootElement.getElementCount() > elementIndex + 1)
 140:                 {
 141:                   replaceNext = true;
 142:                   newEl2EndOffset = 
 143:                     rootElement.getElement(elementIndex + 1).getEndOffset();
 144:                 }
 145:               Element newEl1 = 
 146:                 createLeafElement(rootElement, firstElement.getAttributes(), 
 147:                                   firstElement.getStartOffset(), offset);
 148:               Element newEl2 = 
 149:                 createLeafElement (rootElement, firstElement.getAttributes(), 
 150:                                    offset, newEl2EndOffset);
 151:               if (replaceNext)
 152:                 rootElement.replace(elementIndex, 2, new Element[] { newEl1, newEl2 });
 153:               else
 154:                 rootElement.replace(elementIndex, 1, new Element[] { newEl1, newEl2 });
 155:               firstElement = newEl2;
 156:               elementIndex ++;
 157:             }
 158:         }
 159:         catch (BadLocationException ble)
 160:         {          
 161:           // This shouldn't happen.
 162:           AssertionError ae = new AssertionError();
 163:           ae.initCause(ble);
 164:           throw ae;
 165:         }        
 166:       }
 167: 
 168:     // added and removed are Element arrays used to add an ElementEdit
 169:     // to the DocumentEvent if there were entire lines added or removed.
 170:     Element[] removed = new Element[1];
 171:     Element[] added;
 172:     try 
 173:       {
 174:         String str = content.getString(offset, eventLength);
 175:         ArrayList elts = new ArrayList();
 176: 
 177:         // Determine how many NEW lines were added by finding the newline
 178:         // characters within the newly inserted text
 179:         int j = firstElement.getStartOffset();
 180:         int i = str.indexOf('\n', 0);
 181:         int contentLength = content.length();
 182:           
 183:         while (i != -1 && i <= eventLength)
 184:           {            
 185:             // For each new line, create a new element
 186:             elts.add(createLeafElement(rootElement, SimpleAttributeSet.EMPTY,
 187:                                        j, offset + i + 1));
 188:                   
 189:             j = offset + i + 1;
 190:             if (j >= contentLength)
 191:                 break;
 192:             i = str.indexOf('\n', i + 1);
 193:           }
 194: 
 195:         // If there were new lines added we have to add an ElementEdit to 
 196:         // the DocumentEvent and we have to call rootElement.replace to 
 197:         // insert the new lines
 198:         if (elts.size() != 0)
 199:           {
 200:             // If we have created new lines test whether there are remaining
 201:             // characters in firstElement after the inserted text and if so
 202:             // create a new element for them.
 203:             if (j < firstElement.getEndOffset())
 204:               elts.add(createLeafElement(rootElement, SimpleAttributeSet.EMPTY, j, firstElement.getEndOffset()));
 205: 
 206:             // Set up the ElementEdit by filling the added and removed 
 207:             // arrays with the proper Elements
 208:             added = new Element[elts.size()];
 209:             elts.toArray(added);
 210:             
 211:             removed[0] = firstElement;
 212:             
 213:             // Now create and add the ElementEdit
 214:             ElementEdit e = new ElementEdit(rootElement, elementIndex, removed,
 215:                                             added);
 216:             event.addEdit(e);
 217:             
 218:             // And call replace to actually make the changes
 219:             ((BranchElement) rootElement).replace(elementIndex, 1, added);
 220:           }
 221:       }
 222:     catch (BadLocationException e)
 223:       {
 224:         // This shouldn't happen so we throw an AssertionError
 225:         AssertionError ae = new AssertionError();
 226:         ae.initCause(e);
 227:         throw ae;
 228:       }
 229:     
 230:     super.insertUpdate(event, attributes);
 231:   }
 232: 
 233:   protected void removeUpdate(DefaultDocumentEvent event)
 234:   {
 235:     super.removeUpdate(event);
 236: 
 237:     // added and removed are Element arrays used to add an ElementEdit
 238:     // to the DocumentEvent if there were entire lines added or removed
 239:     // from the Document
 240:     Element[] added = new Element[1];
 241:     Element[] removed;
 242:     int p0 = event.getOffset();
 243: 
 244:     // check if we must collapse some elements
 245:     int i1 = rootElement.getElementIndex(p0);
 246:     int i2 = rootElement.getElementIndex(p0 + event.getLength());
 247:     if (i1 != i2)
 248:       {
 249:         // If there were lines removed then we have to add an ElementEdit
 250:         // to the DocumentEvent so we set it up now by filling the Element
 251:         // arrays "removed" and "added" appropriately
 252:         removed = new Element [i2 - i1 + 1];
 253:         for (int i = i1; i <= i2; i++)
 254:           removed[i-i1] = rootElement.getElement(i);
 255:         
 256:         int start = rootElement.getElement(i1).getStartOffset();
 257:         int end = rootElement.getElement(i2).getEndOffset();        
 258:         added[0] = createLeafElement(rootElement,
 259:                                           SimpleAttributeSet.EMPTY,
 260:                                           start, end);
 261: 
 262:         // Now create and add the ElementEdit
 263:         ElementEdit e = new ElementEdit(rootElement, i1, removed, added);
 264:         event.addEdit(e);
 265: 
 266:         // collapse elements if the removal spans more than 1 line
 267:         rootElement.replace(i1, i2 - i1 + 1, added);
 268:       }
 269:   }
 270: 
 271:   public Element getDefaultRootElement()
 272:   {
 273:     return rootElement;
 274:   }
 275: 
 276:   public Element getParagraphElement(int pos)
 277:   {
 278:     Element root = getDefaultRootElement();
 279:     return root.getElement(root.getElementIndex(pos));
 280:   }
 281: 
 282:   /**
 283:    * Inserts a string into the document. If the document property
 284:    * '<code>filterNewLines</code>' is set to <code>Boolean.TRUE</code>, then
 285:    * all newlines in the inserted string are replaced by space characters,
 286:    * otherwise the superclasses behaviour is executed.
 287:    *
 288:    * Inserting content causes a write lock to be acquired during this method
 289:    * call.
 290:    *
 291:    * @param offs the offset at which to insert the string
 292:    * @param str the string to be inserted
 293:    * @param atts the text attributes of the string to be inserted
 294:    *
 295:    * @throws BadLocationException
 296:    */
 297:   public void insertString(int offs, String str, AttributeSet atts)
 298:     throws BadLocationException
 299:   {
 300:     String string = str;
 301:     if (str != null && Boolean.TRUE.equals(getProperty("filterNewlines")))
 302:       string = str.replaceAll("\n", " ");
 303:     super.insertString(offs, string, atts);
 304:   }
 305: }