1 22 23 package org.gjt.sp.jedit.buffer; 24 25 import javax.swing.text.Position ; 27 import java.util.*; 28 import org.gjt.sp.util.Log; 29 31 39 public class PositionManager 40 { 41 public PositionManager(JEditBuffer buffer) 43 { 44 this.buffer = buffer; 45 } 47 public synchronized Position createPosition(int offset) 49 { 50 PosBottomHalf bh = new PosBottomHalf(offset); 51 PosBottomHalf existing = (PosBottomHalf)positions.get(bh); 52 if(existing == null) 53 { 54 positions.put(bh,bh); 55 existing = bh; 56 } 57 58 return new PosTopHalf(existing); 59 } 61 public synchronized void contentInserted(int offset, int length) 63 { 64 if(positions.size() == 0) 65 return; 66 67 68 Iterator iter = positions.tailMap(new PosBottomHalf(offset)) 69 .keySet().iterator(); 70 71 iteration = true; 72 while(iter.hasNext()) 73 { 74 ((PosBottomHalf)iter.next()) 75 .contentInserted(offset,length); 76 } 77 iteration = false; 78 } 80 public synchronized void contentRemoved(int offset, int length) 82 { 83 if(positions.size() == 0) 84 return; 85 86 87 Iterator iter = positions.tailMap(new PosBottomHalf(offset)) 88 .keySet().iterator(); 89 90 iteration = true; 91 while(iter.hasNext()) 92 { 93 ((PosBottomHalf)iter.next()) 94 .contentRemoved(offset,length); 95 } 96 iteration = false; 97 98 } 100 boolean iteration; 101 102 private JEditBuffer buffer; 104 private SortedMap positions = new TreeMap(); 105 107 109 class PosTopHalf implements Position 111 { 112 PosBottomHalf bh; 113 114 PosTopHalf(PosBottomHalf bh) 116 { 117 this.bh = bh; 118 bh.ref(); 119 } 121 public int getOffset() 123 { 124 return bh.offset; 125 } 127 protected void finalize() 129 { 130 synchronized(PositionManager.this) 131 { 132 bh.unref(); 133 } 134 } } 137 class PosBottomHalf implements Comparable 139 { 140 int offset; 141 int ref; 142 143 PosBottomHalf(int offset) 145 { 146 this.offset = offset; 147 } 149 void ref() 151 { 152 ref++; 153 } 155 void unref() 157 { 158 if(--ref == 0) 159 positions.remove(this); 160 } 162 void contentInserted(int offset, int length) 164 { 165 if(offset > this.offset) 166 throw new ArrayIndexOutOfBoundsException (); 167 this.offset += length; 168 checkInvariants(); 169 } 171 void contentRemoved(int offset, int length) 173 { 174 if(offset > this.offset) 175 throw new ArrayIndexOutOfBoundsException (); 176 if(this.offset <= offset + length) 177 this.offset = offset; 178 else 179 this.offset -= length; 180 checkInvariants(); 181 } 183 public boolean equals(Object o) 185 { 186 if(!(o instanceof PosBottomHalf)) 187 return false; 188 189 return ((PosBottomHalf)o).offset == offset; 190 } 192 public int compareTo(Object o) 194 { 195 if(iteration) 196 Log.log(Log.ERROR,this,"Consistency failure"); 197 return offset - ((PosBottomHalf)o).offset; 198 } 200 private void checkInvariants() 202 { 203 if(offset < 0 || offset > buffer.getLength()) 204 throw new ArrayIndexOutOfBoundsException (); 205 } } 208 } 210 | Popular Tags |