- Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy pathAbstractWriter.java
721 lines (667 loc) · 23.7 KB
/
AbstractWriter.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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
/*
* Copyright (c) 1998, 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.io.Writer;
importjava.io.IOException;
importjava.util.Enumeration;
/**
* AbstractWriter is an abstract class that actually
* does the work of writing out the element tree
* including the attributes. In terms of how much is
* written out per line, the writer defaults to 100.
* But this value can be set by subclasses.
*
* @author Sunita Mani
*/
publicabstractclassAbstractWriter {
privateElementIteratorit;
privateWriterout;
privateintindentLevel = 0;
privateintindentSpace = 2;
privateDocumentdoc = null;
privateintmaxLineLength = 100;
privateintcurrLength = 0;
privateintstartOffset = 0;
privateintendOffset = 0;
// If (indentLevel * indentSpace) becomes >= maxLineLength, this will
// get incremented instead of indentLevel to avoid indenting going greater
// than line length.
privateintoffsetIndent = 0;
/**
* String used for end of line. If the Document has the property
* EndOfLineStringProperty, it will be used for newlines. Otherwise
* the System property line.separator will be used. The line separator
* can also be set.
*/
privateStringlineSeparator;
/**
* True indicates that when writing, the line can be split, false
* indicates that even if the line is > than max line length it should
* not be split.
*/
privatebooleancanWrapLines;
/**
* True while the current line is empty. This will remain true after
* indenting.
*/
privatebooleanisLineEmpty;
/**
* Used when indenting. Will contain the spaces.
*/
privatechar[] indentChars;
/**
* Used when writing out a string.
*/
privatechar[] tempChars;
/**
* This is used in <code>writeLineSeparator</code> instead of
* tempChars. If tempChars were used it would mean write couldn't invoke
* <code>writeLineSeparator</code> as it might have been passed
* tempChars.
*/
privatechar[] newlineChars;
/**
* Used for writing text.
*/
privateSegmentsegment;
/**
* How the text packages models newlines.
* @see #getLineSeparator
*/
protectedstaticfinalcharNEWLINE = '\n';
/**
* Creates a new AbstractWriter.
* Initializes the ElementIterator with the default
* root of the document.
*
* @param w a Writer.
* @param doc a Document
*/
protectedAbstractWriter(Writerw, Documentdoc) {
this(w, doc, 0, doc.getLength());
}
/**
* Creates a new AbstractWriter.
* Initializes the ElementIterator with the
* element passed in.
*
* @param w a Writer
* @param doc an Element
* @param pos The location in the document to fetch the
* content.
* @param len The amount to write out.
*/
protectedAbstractWriter(Writerw, Documentdoc, intpos, intlen) {
this.doc = doc;
it = newElementIterator(doc.getDefaultRootElement());
out = w;
startOffset = pos;
endOffset = pos + len;
ObjectdocNewline = doc.getProperty(DefaultEditorKit.
EndOfLineStringProperty);
if (docNewlineinstanceofString) {
setLineSeparator((String)docNewline);
}
else {
Stringnewline = System.lineSeparator();
if (newline == null) {
// Should not get here, but if we do it means we could not
// find a newline string, use \n in this case.
newline = "\n";
}
setLineSeparator(newline);
}
canWrapLines = true;
}
/**
* Creates a new AbstractWriter.
* Initializes the ElementIterator with the
* element passed in.
*
* @param w a Writer
* @param root an Element
*/
protectedAbstractWriter(Writerw, Elementroot) {
this(w, root, 0, root.getEndOffset());
}
/**
* Creates a new AbstractWriter.
* Initializes the ElementIterator with the
* element passed in.
*
* @param w a Writer
* @param root an Element
* @param pos The location in the document to fetch the
* content.
* @param len The amount to write out.
*/
protectedAbstractWriter(Writerw, Elementroot, intpos, intlen) {
this.doc = root.getDocument();
it = newElementIterator(root);
out = w;
startOffset = pos;
endOffset = pos + len;
canWrapLines = true;
}
/**
* Returns the first offset to be output.
* @return the first offset to be output
* @since 1.3
*/
publicintgetStartOffset() {
returnstartOffset;
}
/**
* Returns the last offset to be output.
* @return the last offset to be output
* @since 1.3
*/
publicintgetEndOffset() {
returnendOffset;
}
/**
* Fetches the ElementIterator.
*
* @return the ElementIterator.
*/
protectedElementIteratorgetElementIterator() {
returnit;
}
/**
* Returns the Writer that is used to output the content.
* @return the Writer that is used to output the content
* @since 1.3
*/
protectedWritergetWriter() {
returnout;
}
/**
* Fetches the document.
*
* @return the Document.
*/
protectedDocumentgetDocument() {
returndoc;
}
/**
* This method determines whether the current element
* is in the range specified. When no range is specified,
* the range is initialized to be the entire document.
* inRange() returns true if the range specified intersects
* with the element's range.
*
* @param next an Element.
* @return boolean that indicates whether the element
* is in the range.
*/
protectedbooleaninRange(Elementnext) {
intstartOffset = getStartOffset();
intendOffset = getEndOffset();
if ((next.getStartOffset() >= startOffset &&
next.getStartOffset() < endOffset) ||
(startOffset >= next.getStartOffset() &&
startOffset < next.getEndOffset())) {
returntrue;
}
returnfalse;
}
/**
* This abstract method needs to be implemented
* by subclasses. Its responsibility is to
* iterate over the elements and use the write()
* methods to generate output in the desired format.
* @throws IOException if an I/O problem has occurred
* @throws BadLocationException for an invalid location within
* the document
*/
protectedabstractvoidwrite() throwsIOException, BadLocationException;
/**
* Returns the text associated with the element.
* The assumption here is that the element is a
* leaf element. Throws a BadLocationException
* when encountered.
*
* @param elem an <code>Element</code>
* @throws BadLocationException if pos represents an invalid
* location within the document
* @return the text as a <code>String</code>
*/
protectedStringgetText(Elementelem) throwsBadLocationException {
returndoc.getText(elem.getStartOffset(),
elem.getEndOffset() - elem.getStartOffset());
}
/**
* Writes out text. If a range is specified when the constructor
* is invoked, then only the appropriate range of text is written
* out.
*
* @param elem an Element.
* @throws IOException on any I/O error
* @throws BadLocationException if pos represents an invalid
* location within the document.
*/
protectedvoidtext(Elementelem) throwsBadLocationException,
IOException {
intstart = Math.max(getStartOffset(), elem.getStartOffset());
intend = Math.min(getEndOffset(), elem.getEndOffset());
if (start < end) {
if (segment == null) {
segment = newSegment();
}
getDocument().getText(start, end - start, segment);
if (segment.count > 0) {
write(segment.array, segment.offset, segment.count);
}
}
}
/**
* Enables subclasses to set the number of characters they
* want written per line. The default is 100.
*
* @param l the maximum line length.
*/
protectedvoidsetLineLength(intl) {
maxLineLength = l;
}
/**
* Returns the maximum line length.
* @return the maximum line length
* @since 1.3
*/
protectedintgetLineLength() {
returnmaxLineLength;
}
/**
* Sets the current line length.
* @param length the new line length
* @since 1.3
*/
protectedvoidsetCurrentLineLength(intlength) {
currLength = length;
isLineEmpty = (currLength == 0);
}
/**
* Returns the current line length.
* @return the current line length
* @since 1.3
*/
protectedintgetCurrentLineLength() {
returncurrLength;
}
/**
* Returns true if the current line should be considered empty. This
* is true when <code>getCurrentLineLength</code> == 0 ||
* <code>indent</code> has been invoked on an empty line.
* @return true if the current line should be considered empty
* @since 1.3
*/
protectedbooleanisLineEmpty() {
returnisLineEmpty;
}
/**
* Sets whether or not lines can be wrapped. This can be toggled
* during the writing of lines. For example, outputting HTML might
* set this to false when outputting a quoted string.
* @param newValue new value for line wrapping
* @since 1.3
*/
protectedvoidsetCanWrapLines(booleannewValue) {
canWrapLines = newValue;
}
/**
* Returns whether or not the lines can be wrapped. If this is false
* no lineSeparator's will be output.
* @return whether or not the lines can be wrapped
* @since 1.3
*/
protectedbooleangetCanWrapLines() {
returncanWrapLines;
}
/**
* Enables subclasses to specify how many spaces an indent
* maps to. When indentation takes place, the indent level
* is multiplied by this mapping. The default is 2.
*
* @param space an int representing the space to indent mapping.
*/
protectedvoidsetIndentSpace(intspace) {
indentSpace = space;
}
/**
* Returns the amount of space to indent.
* @return the amount of space to indent
* @since 1.3
*/
protectedintgetIndentSpace() {
returnindentSpace;
}
/**
* Sets the String used to represent newlines. This is initialized
* in the constructor from either the Document, or the System property
* line.separator.
* @param value the new line separator
* @since 1.3
*/
publicvoidsetLineSeparator(Stringvalue) {
lineSeparator = value;
}
/**
* Returns the string used to represent newlines.
* @return the string used to represent newlines
* @since 1.3
*/
publicStringgetLineSeparator() {
returnlineSeparator;
}
/**
* Increments the indent level. If indenting would cause
* <code>getIndentSpace()</code> *<code>getIndentLevel()</code> to be >
* than <code>getLineLength()</code> this will not cause an indent.
*/
protectedvoidincrIndent() {
// Only increment to a certain point.
if (offsetIndent > 0) {
offsetIndent++;
}
else {
if (++indentLevel * getIndentSpace() >= getLineLength()) {
offsetIndent++;
--indentLevel;
}
}
}
/**
* Decrements the indent level.
*/
protectedvoiddecrIndent() {
if (offsetIndent > 0) {
--offsetIndent;
}
else {
indentLevel--;
}
}
/**
* Returns the current indentation level. That is, the number of times
* <code>incrIndent</code> has been invoked minus the number of times
* <code>decrIndent</code> has been invoked.
* @return the current indentation level
* @since 1.3
*/
protectedintgetIndentLevel() {
returnindentLevel;
}
/**
* Does indentation. The number of spaces written
* out is indent level times the space to map mapping. If the current
* line is empty, this will not make it so that the current line is
* still considered empty.
*
* @throws IOException on any I/O error
*/
protectedvoidindent() throwsIOException {
intmax = getIndentLevel() * getIndentSpace();
if (indentChars == null || max > indentChars.length) {
indentChars = newchar[max];
for (intcounter = 0; counter < max; counter++) {
indentChars[counter] = ' ';
}
}
intlength = getCurrentLineLength();
booleanwasEmpty = isLineEmpty();
output(indentChars, 0, max);
if (wasEmpty && length == 0) {
isLineEmpty = true;
}
}
/**
* Writes out a character. This is implemented to invoke
* the <code>write</code> method that takes a char[].
*
* @param ch a char.
* @throws IOException on any I/O error
*/
protectedvoidwrite(charch) throwsIOException {
if (tempChars == null) {
tempChars = newchar[128];
}
tempChars[0] = ch;
write(tempChars, 0, 1);
}
/**
* Writes out a string. This is implemented to invoke the
* <code>write</code> method that takes a char[].
*
* @param content a String.
* @throws IOException on any I/O error
*/
protectedvoidwrite(Stringcontent) throwsIOException {
if (content == null) {
return;
}
intsize = content.length();
if (tempChars == null || tempChars.length < size) {
tempChars = newchar[size];
}
content.getChars(0, size, tempChars, 0);
write(tempChars, 0, size);
}
/**
* Writes the line separator. This invokes <code>output</code> directly
* as well as setting the <code>lineLength</code> to 0.
* @throws IOException on any I/O error
* @since 1.3
*/
protectedvoidwriteLineSeparator() throwsIOException {
Stringnewline = getLineSeparator();
intlength = newline.length();
if (newlineChars == null || newlineChars.length < length) {
newlineChars = newchar[length];
}
newline.getChars(0, length, newlineChars, 0);
output(newlineChars, 0, length);
setCurrentLineLength(0);
}
/**
* All write methods call into this one. If <code>getCanWrapLines()</code>
* returns false, this will call <code>output</code> with each sequence
* of <code>chars</code> that doesn't contain a NEWLINE, followed
* by a call to <code>writeLineSeparator</code>. On the other hand,
* if <code>getCanWrapLines()</code> returns true, this will split the
* string, as necessary, so <code>getLineLength</code> is honored.
* The only exception is if the current string contains no whitespace,
* and won't fit in which case the line length will exceed
* <code>getLineLength</code>.
*
* @param chars characters to output
* @param startIndex starting index
* @param length length of output
* @throws IOException on any I/O error
* @since 1.3
*/
protectedvoidwrite(char[] chars, intstartIndex, intlength)
throwsIOException {
if (!getCanWrapLines()) {
// We can not break string, just track if a newline
// is in it.
intlastIndex = startIndex;
intendIndex = startIndex + length;
intnewlineIndex = indexOf(chars, NEWLINE, startIndex, endIndex);
while (newlineIndex != -1) {
if (newlineIndex > lastIndex) {
output(chars, lastIndex, newlineIndex - lastIndex);
}
writeLineSeparator();
lastIndex = newlineIndex + 1;
newlineIndex = indexOf(chars, '\n', lastIndex, endIndex);
}
if (lastIndex < endIndex) {
output(chars, lastIndex, endIndex - lastIndex);
}
}
else {
// We can break chars if the length exceeds maxLength.
intlastIndex = startIndex;
intendIndex = startIndex + length;
intlineLength = getCurrentLineLength();
intmaxLength = getLineLength();
while (lastIndex < endIndex) {
intnewlineIndex = indexOf(chars, NEWLINE, lastIndex,
endIndex);
booleanneedsNewline = false;
booleanforceNewLine = false;
lineLength = getCurrentLineLength();
if (newlineIndex != -1 && (lineLength +
(newlineIndex - lastIndex)) < maxLength) {
if (newlineIndex > lastIndex) {
output(chars, lastIndex, newlineIndex - lastIndex);
}
lastIndex = newlineIndex + 1;
forceNewLine = true;
}
elseif (newlineIndex == -1 && (lineLength +
(endIndex - lastIndex)) < maxLength) {
if (endIndex > lastIndex) {
output(chars, lastIndex, endIndex - lastIndex);
}
lastIndex = endIndex;
}
else {
// Need to break chars, find a place to split chars at,
// from lastIndex to endIndex,
// or maxLength - lineLength whichever is smaller
intbreakPoint = -1;
intmaxBreak = Math.min(endIndex - lastIndex,
maxLength - lineLength - 1);
intcounter = 0;
while (counter < maxBreak) {
if (Character.isWhitespace(chars[counter +
lastIndex])) {
breakPoint = counter;
}
counter++;
}
if (breakPoint != -1) {
// Found a place to break at.
breakPoint += lastIndex + 1;
output(chars, lastIndex, breakPoint - lastIndex);
lastIndex = breakPoint;
needsNewline = true;
}
else {
// No where good to break.
// find the next whitespace, or write out the
// whole string.
// maxBreak will be negative if current line too
// long.
counter = Math.max(0, maxBreak);
maxBreak = endIndex - lastIndex;
while (counter < maxBreak) {
if (Character.isWhitespace(chars[counter +
lastIndex])) {
breakPoint = counter;
break;
}
counter++;
}
if (breakPoint == -1) {
output(chars, lastIndex, endIndex - lastIndex);
breakPoint = endIndex;
}
else {
breakPoint += lastIndex;
if (chars[breakPoint] == NEWLINE) {
output(chars, lastIndex, breakPoint++ -
lastIndex);
forceNewLine = true;
}
else {
output(chars, lastIndex, ++breakPoint -
lastIndex);
needsNewline = true;
}
}
lastIndex = breakPoint;
}
}
if (forceNewLine || needsNewline || lastIndex < endIndex) {
writeLineSeparator();
if (lastIndex < endIndex || !forceNewLine) {
indent();
}
}
}
}
}
/**
* Writes out the set of attributes as " <name>=<value>"
* pairs. It throws an IOException when encountered.
*
* @param attr an AttributeSet.
* @throws IOException on any I/O error
*/
protectedvoidwriteAttributes(AttributeSetattr) throwsIOException {
Enumeration<?> names = attr.getAttributeNames();
while (names.hasMoreElements()) {
Objectname = names.nextElement();
write(" " + name + "=" + attr.getAttribute(name));
}
}
/**
* The last stop in writing out content. All the write methods eventually
* make it to this method, which invokes <code>write</code> on the
* Writer.
* <p>This method also updates the line length based on
* <code>length</code>. If this is invoked to output a newline, the
* current line length will need to be reset as will no longer be
* valid. If it is up to the caller to do this. Use
* <code>writeLineSeparator</code> to write out a newline, which will
* property update the current line length.
*
* @param content characters to output
* @param start starting index
* @param length length of output
* @throws IOException on any I/O error
* @since 1.3
*/
protectedvoidoutput(char[] content, intstart, intlength)
throwsIOException {
getWriter().write(content, start, length);
setCurrentLineLength(getCurrentLineLength() + length);
}
/**
* Support method to locate an occurrence of a particular character.
*/
privateintindexOf(char[] chars, charsChar, intstartIndex,
intendIndex) {
while(startIndex < endIndex) {
if (chars[startIndex] == sChar) {
returnstartIndex;
}
startIndex++;
}
return -1;
}
}