- Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy pathStringContent.java
504 lines (464 loc) · 17.4 KB
/
StringContent.java
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
/*
* Copyright (c) 1997, 2023, Oracle and/or its affiliates. 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
packagejavax.swing.text;
importjava.util.Vector;
importjava.io.Serializable;
importjavax.swing.undo.*;
/**
* An implementation of the AbstractDocument.Content interface that is
* a brute force implementation that is useful for relatively small
* documents and/or debugging. It manages the character content
* as a simple character array. It is also quite inefficient.
* <p>
* It is generally recommended that the gap buffer or piece table
* implementations be used instead. This buffer does not scale up
* to large sizes.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Timothy Prinzing
*/
@SuppressWarnings("serial") // Same-version serialization only
publicfinalclassStringContentimplementsAbstractDocument.Content, Serializable {
/**
* Creates a new StringContent object. Initial size defaults to 10.
*/
publicStringContent() {
this(10);
}
/**
* Creates a new StringContent object, with the initial
* size specified. If the length is < 1, a size of 1 is used.
*
* @param initialLength the initial size
*/
publicStringContent(intinitialLength) {
if (initialLength < 1) {
initialLength = 1;
}
data = newchar[initialLength];
data[0] = '\n';
count = 1;
}
/**
* Returns the length of the content.
*
* @return the length >= 1
* @see AbstractDocument.Content#length
*/
publicintlength() {
returncount;
}
/**
* Inserts a string into the content.
*
* @param where the starting position >= 0 && < length()
* @param str the non-null string to insert
* @return an UndoableEdit object for undoing
* @throws BadLocationException if the specified position is invalid
* @see AbstractDocument.Content#insertString
*/
publicUndoableEditinsertString(intwhere, Stringstr) throwsBadLocationException {
if (where >= count || where < 0) {
thrownewBadLocationException("Invalid location", count);
}
char[] chars = str.toCharArray();
replace(where, 0, chars, 0, chars.length);
if (marks != null) {
updateMarksForInsert(where, str.length());
}
returnnewInsertUndo(where, str.length());
}
/**
* Removes part of the content. where + nitems must be < length().
*
* @param where the starting position >= 0
* @param nitems the number of characters to remove >= 0
* @return an UndoableEdit object for undoing
* @throws BadLocationException if the specified position is invalid
* @see AbstractDocument.Content#remove
*/
publicUndoableEditremove(intwhere, intnitems) throwsBadLocationException {
if (where + nitems >= count) {
thrownewBadLocationException("Invalid range", count);
}
StringremovedString = getString(where, nitems);
UndoableEditedit = newRemoveUndo(where, removedString);
replace(where, nitems, empty, 0, 0);
if (marks != null) {
updateMarksForRemove(where, nitems);
}
returnedit;
}
/**
* Retrieves a portion of the content. where + len must be <= length().
*
* @param where the starting position >= 0
* @param len the length to retrieve >= 0
* @return a string representing the content; may be empty
* @throws BadLocationException if the specified position is invalid
* @see AbstractDocument.Content#getString
*/
publicStringgetString(intwhere, intlen) throwsBadLocationException {
if (where + len > count) {
thrownewBadLocationException("Invalid range", count);
}
returnnewString(data, where, len);
}
/**
* Retrieves a portion of the content. where + len must be <= length()
*
* @param where the starting position >= 0
* @param len the number of characters to retrieve >= 0
* @param chars the Segment object to return the characters in
* @throws BadLocationException if the specified position is invalid
* @see AbstractDocument.Content#getChars
*/
publicvoidgetChars(intwhere, intlen, Segmentchars) throwsBadLocationException {
if (where + len > count) {
thrownewBadLocationException("Invalid location", count);
}
chars.array = data;
chars.offset = where;
chars.count = len;
}
/**
* Creates a position within the content that will
* track change as the content is mutated.
*
* @param offset the offset to create a position for >= 0
* @return the position
* @throws BadLocationException if the specified position is invalid
*/
publicPositioncreatePosition(intoffset) throwsBadLocationException {
// some small documents won't have any sticky positions
// at all, so the buffer is created lazily.
if (marks == null) {
marks = newVector<PosRec>();
}
returnnewStickyPosition(offset);
}
// --- local methods ---------------------------------------
/**
* Replaces some of the characters in the array
* @param offset offset into the array to start the replace
* @param length number of characters to remove
* @param replArray replacement array
* @param replOffset offset into the replacement array
* @param replLength number of character to use from the
* replacement array.
*/
voidreplace(intoffset, intlength,
char[] replArray, intreplOffset, intreplLength) {
intdelta = replLength - length;
intsrc = offset + length;
intnmove = count - src;
intdest = src + delta;
if ((count + delta) >= data.length) {
// need to grow the array
intnewLength = Math.max(2*data.length, count + delta);
char[] newData = newchar[newLength];
System.arraycopy(data, 0, newData, 0, offset);
System.arraycopy(replArray, replOffset, newData, offset, replLength);
System.arraycopy(data, src, newData, dest, nmove);
data = newData;
} else {
// patch the existing array
System.arraycopy(data, src, data, dest, nmove);
System.arraycopy(replArray, replOffset, data, offset, replLength);
}
count = count + delta;
}
voidresize(intncount) {
char[] ndata = newchar[ncount];
System.arraycopy(data, 0, ndata, 0, Math.min(ncount, count));
data = ndata;
}
synchronizedvoidupdateMarksForInsert(intoffset, intlength) {
if (offset == 0) {
// zero is a special case where we update only
// marks after it.
offset = 1;
}
intn = marks.size();
for (inti = 0; i < n; i++) {
PosRecmark = marks.elementAt(i);
if (mark.unused) {
// this record is no longer used, get rid of it
marks.removeElementAt(i);
i -= 1;
n -= 1;
} elseif (mark.offset >= offset) {
mark.offset += length;
}
}
}
synchronizedvoidupdateMarksForRemove(intoffset, intlength) {
intn = marks.size();
for (inti = 0; i < n; i++) {
PosRecmark = marks.elementAt(i);
if (mark.unused) {
// this record is no longer used, get rid of it
marks.removeElementAt(i);
i -= 1;
n -= 1;
} elseif (mark.offset >= (offset + length)) {
mark.offset -= length;
} elseif (mark.offset >= offset) {
mark.offset = offset;
}
}
}
/**
* Returns a Vector containing instances of UndoPosRef for the
* Positions in the range
* <code>offset</code> to <code>offset</code> + <code>length</code>.
* If <code>v</code> is not null the matching Positions are placed in
* there. The vector with the resulting Positions are returned.
* <p>
* This is meant for internal usage, and is generally not of interest
* to subclasses.
*
* @param v the Vector to use, with a new one created on null
* @param offset the starting offset >= 0
* @param length the length >= 0
* @return the set of instances
*/
@SuppressWarnings({"rawtypes", "unchecked"}) // UndoPosRef type cannot be exposed
protectedVectorgetPositionsInRange(Vectorv, intoffset,
intlength) {
intn = marks.size();
intend = offset + length;
VectorplaceIn = (v == null) ? newVector() : v;
for (inti = 0; i < n; i++) {
PosRecmark = marks.elementAt(i);
if (mark.unused) {
// this record is no longer used, get rid of it
marks.removeElementAt(i);
i -= 1;
n -= 1;
} elseif(mark.offset >= offset && mark.offset <= end)
placeIn.addElement(newUndoPosRef(mark));
}
returnplaceIn;
}
/**
* Resets the location for all the UndoPosRef instances
* in <code>positions</code>.
* <p>
* This is meant for internal usage, and is generally not of interest
* to subclasses.
*
* @param positions the positions of the instances
*/
@SuppressWarnings("rawtypes") // UndoPosRef type cannot be exposed
protectedvoidupdateUndoPositions(Vectorpositions) {
for(intcounter = positions.size() - 1; counter >= 0; counter--) {
UndoPosRefref = (UndoPosRef) positions.elementAt(counter);
// Check if the Position is still valid.
if(ref.rec.unused) {
positions.removeElementAt(counter);
}
else
ref.resetLocation();
}
}
privatestaticfinalchar[] empty = newchar[0];
privatechar[] data;
privateintcount;
transientVector<PosRec> marks;
/**
* holds the data for a mark... separately from
* the real mark so that the real mark can be
* collected if there are no more references to
* it.... the update table holds only a reference
* to this grungy thing.
*/
staticfinalclassPosRec {
PosRec(intoffset) {
this.offset = offset;
}
intoffset;
booleanunused;
}
/**
* This really wants to be a weak reference but
* in 1.1 we don't have a 100% pure solution for
* this... so this class tries to hack a solution
* to causing the marks to be collected.
*/
finalclassStickyPositionimplementsPosition {
StickyPosition(intoffset) {
rec = newPosRec(offset);
marks.addElement(rec);
}
publicintgetOffset() {
returnrec.offset;
}
@SuppressWarnings("removal")
protectedvoidfinalize() throwsThrowable {
// schedule the record to be removed later
// on another thread.
rec.unused = true;
}
publicStringtoString() {
returnInteger.toString(getOffset());
}
PosRecrec;
}
/**
* Used to hold a reference to a Position that is being reset as the
* result of removing from the content.
*/
staticfinalclassUndoPosRef {
UndoPosRef(PosRecrec) {
this.rec = rec;
this.undoLocation = rec.offset;
}
/**
* Resets the location of the Position to the offset when the
* receiver was instantiated.
*/
protectedvoidresetLocation() {
rec.offset = undoLocation;
}
/** Location to reset to when resetLocation is invoked. */
protectedintundoLocation;
/** Position to reset offset. */
protectedPosRecrec;
}
/**
* UnoableEdit created for inserts.
*/
classInsertUndoextendsAbstractUndoableEdit {
protectedInsertUndo(intoffset, intlength) {
super();
this.offset = offset;
this.length = length;
}
publicvoidundo() throwsCannotUndoException {
super.undo();
try {
synchronized(StringContent.this) {
// Get the Positions in the range being removed.
if(marks != null)
posRefs = getPositionsInRange(null, offset, length);
string = getString(offset, length);
remove(offset, length);
}
} catch (BadLocationExceptionbl) {
thrownewCannotUndoException();
}
}
publicvoidredo() throwsCannotRedoException {
super.redo();
try {
synchronized(StringContent.this) {
insertString(offset, string);
string = null;
// Update the Positions that were in the range removed.
if(posRefs != null) {
updateUndoPositions(posRefs);
posRefs = null;
}
}
} catch (BadLocationExceptionbl) {
thrownewCannotRedoException();
}
}
// Where the string goes.
protectedintoffset;
// Length of the string.
protectedintlength;
// The string that was inserted. To cut down on space needed this
// will only be valid after an undo.
protectedStringstring;
// An array of instances of UndoPosRef for the Positions in the
// range that was removed, valid after undo.
@SuppressWarnings("rawtypes") // UndoPosRef type cannot be exposed
protectedVectorposRefs;
}
/**
* UndoableEdit created for removes.
*/
classRemoveUndoextendsAbstractUndoableEdit {
@SuppressWarnings("unchecked")
protectedRemoveUndo(intoffset, Stringstring) {
super();
this.offset = offset;
this.string = string;
this.length = string.length();
if(marks != null)
posRefs = getPositionsInRange(null, offset, length);
}
publicvoidundo() throwsCannotUndoException {
super.undo();
try {
synchronized(StringContent.this) {
insertString(offset, string);
// Update the Positions that were in the range removed.
if(posRefs != null) {
updateUndoPositions(posRefs);
posRefs = null;
}
string = null;
}
} catch (BadLocationExceptionbl) {
thrownewCannotUndoException();
}
}
@SuppressWarnings("unchecked")
publicvoidredo() throwsCannotRedoException {
super.redo();
try {
synchronized(StringContent.this) {
string = getString(offset, length);
// Get the Positions in the range being removed.
if(marks != null)
posRefs = getPositionsInRange(null, offset, length);
remove(offset, length);
}
} catch (BadLocationExceptionbl) {
thrownewCannotRedoException();
}
}
// Where the string goes.
protectedintoffset;
// Length of the string.
protectedintlength;
// The string that was inserted. This will be null after an undo.
protectedStringstring;
// An array of instances of UndoPosRef for the Positions in the
// range that was removed, valid before undo.
protectedVector<UndoPosRef> posRefs;
}
}