-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathAbstractDocument.java
More file actions
3116 lines (2822 loc) · 108 KB
/
AbstractDocument.java
File metadata and controls
3116 lines (2822 loc) · 108 KB
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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package javax.swing.text;
import java.util.*;
import java.io.*;
import java.awt.font.TextAttribute;
import java.text.Bidi;
import javax.swing.UIManager;
import javax.swing.undo.*;
import javax.swing.event.*;
import javax.swing.tree.TreeNode;
import sun.font.BidiUtils;
import sun.swing.SwingUtilities2;
/**
* An implementation of the document interface to serve as a
* basis for implementing various kinds of documents. At this
* level there is very little policy, so there is a corresponding
* increase in difficulty of use.
* <p>
* This class implements a locking mechanism for the document. It
* allows multiple readers or one writer, and writers must wait until
* all observers of the document have been notified of a previous
* change before beginning another mutation to the document. The
* read lock is acquired and released using the <code>render</code>
* method. A write lock is acquired by the methods that mutate the
* document, and are held for the duration of the method call.
* Notification is done on the thread that produced the mutation,
* and the thread has full read access to the document for the
* duration of the notification, but other readers are kept out
* until the notification has finished. The notification is a
* beans event notification which does not allow any further
* mutations until all listeners have been notified.
* <p>
* Any models subclassed from this class and used in conjunction
* with a text component that has a look and feel implementation
* that is derived from BasicTextUI may be safely updated
* asynchronously, because all access to the View hierarchy
* is serialized by BasicTextUI if the document is of type
* <code>AbstractDocument</code>. The locking assumes that an
* independent thread will access the View hierarchy only from
* the DocumentListener methods, and that there will be only
* one event thread active at a time.
* <p>
* If concurrency support is desired, there are the following
* additional implications. The code path for any DocumentListener
* implementation and any UndoListener implementation must be threadsafe,
* and not access the component lock if trying to be safe from deadlocks.
* The <code>repaint</code> and <code>revalidate</code> methods
* on JComponent are safe.
* <p>
* AbstractDocument models an implied break at the end of the document.
* Among other things this allows you to position the caret after the last
* character. As a result of this, <code>getLength</code> returns one less
* than the length of the Content. If you create your own Content, be
* sure and initialize it to have an additional character. Refer to
* StringContent and GapContent for examples of this. Another implication
* of this is that Elements that model the implied end character will have
* an endOffset == (getLength() + 1). For example, in DefaultStyledDocument
* <code>getParagraphElement(getLength()).getEndOffset() == getLength() + 1
* </code>.
* <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
*/
public abstract class AbstractDocument implements Document, Serializable {
/**
* Constructs a new <code>AbstractDocument</code>, wrapped around some
* specified content storage mechanism.
*
* @param data the content
*/
protected AbstractDocument(Content data) {
this(data, StyleContext.getDefaultStyleContext());
}
/**
* Constructs a new <code>AbstractDocument</code>, wrapped around some
* specified content storage mechanism.
*
* @param data the content
* @param context the attribute context
*/
protected AbstractDocument(Content data, AttributeContext context) {
this.data = data;
this.context = context;
bidiRoot = new BidiRootElement();
if (defaultI18NProperty == null) {
// determine default setting for i18n support
String o = java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<String>() {
public String run() {
return System.getProperty(I18NProperty);
}
}
);
if (o != null) {
defaultI18NProperty = Boolean.valueOf(o);
} else {
defaultI18NProperty = Boolean.FALSE;
}
}
putProperty( I18NProperty, defaultI18NProperty);
//REMIND(bcb) This creates an initial bidi element to account for
//the \n that exists by default in the content. Doing it this way
//seems to expose a little too much knowledge of the content given
//to us by the sub-class. Consider having the sub-class' constructor
//make an initial call to insertUpdate.
writeLock();
try {
Element[] p = new Element[1];
p[0] = new BidiElement( bidiRoot, 0, 1, 0 );
bidiRoot.replace(0,0,p);
} finally {
writeUnlock();
}
}
/**
* Supports managing a set of properties. Callers
* can use the <code>documentProperties</code> dictionary
* to annotate the document with document-wide properties.
*
* @return a non-<code>null</code> <code>Dictionary</code>
* @see #setDocumentProperties
*/
public Dictionary<Object,Object> getDocumentProperties() {
if (documentProperties == null) {
documentProperties = new Hashtable<Object, Object>(2);
}
return documentProperties;
}
/**
* Replaces the document properties dictionary for this document.
*
* @param x the new dictionary
* @see #getDocumentProperties
*/
public void setDocumentProperties(Dictionary<Object,Object> x) {
documentProperties = x;
}
/**
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
*
* @param e the event
* @see EventListenerList
*/
protected void fireInsertUpdate(DocumentEvent e) {
notifyingListeners = true;
try {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==DocumentListener.class) {
// Lazily create the event:
// if (e == null)
// e = new ListSelectionEvent(this, firstIndex, lastIndex);
((DocumentListener)listeners[i+1]).insertUpdate(e);
}
}
} finally {
notifyingListeners = false;
}
}
/**
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
*
* @param e the event
* @see EventListenerList
*/
protected void fireChangedUpdate(DocumentEvent e) {
notifyingListeners = true;
try {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==DocumentListener.class) {
// Lazily create the event:
// if (e == null)
// e = new ListSelectionEvent(this, firstIndex, lastIndex);
((DocumentListener)listeners[i+1]).changedUpdate(e);
}
}
} finally {
notifyingListeners = false;
}
}
/**
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
*
* @param e the event
* @see EventListenerList
*/
protected void fireRemoveUpdate(DocumentEvent e) {
notifyingListeners = true;
try {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==DocumentListener.class) {
// Lazily create the event:
// if (e == null)
// e = new ListSelectionEvent(this, firstIndex, lastIndex);
((DocumentListener)listeners[i+1]).removeUpdate(e);
}
}
} finally {
notifyingListeners = false;
}
}
/**
* Notifies all listeners that have registered interest for
* notification on this event type. The event instance
* is lazily created using the parameters passed into
* the fire method.
*
* @param e the event
* @see EventListenerList
*/
protected void fireUndoableEditUpdate(UndoableEditEvent e) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==UndoableEditListener.class) {
// Lazily create the event:
// if (e == null)
// e = new ListSelectionEvent(this, firstIndex, lastIndex);
((UndoableEditListener)listeners[i+1]).undoableEditHappened(e);
}
}
}
/**
* Returns an array of all the objects currently registered
* as <code><em>Foo</em>Listener</code>s
* upon this document.
* <code><em>Foo</em>Listener</code>s are registered using the
* <code>add<em>Foo</em>Listener</code> method.
*
* <p>
* You can specify the <code>listenerType</code> argument
* with a class literal, such as
* <code><em>Foo</em>Listener.class</code>.
* For example, you can query a
* document <code>d</code>
* for its document listeners with the following code:
*
* <pre>DocumentListener[] mls = (DocumentListener[])(d.getListeners(DocumentListener.class));</pre>
*
* If no such listeners exist, this method returns an empty array.
*
* @param listenerType the type of listeners requested; this parameter
* should specify an interface that descends from
* <code>java.util.EventListener</code>
* @return an array of all objects registered as
* <code><em>Foo</em>Listener</code>s on this component,
* or an empty array if no such
* listeners have been added
* @exception ClassCastException if <code>listenerType</code>
* doesn't specify a class or interface that implements
* <code>java.util.EventListener</code>
*
* @see #getDocumentListeners
* @see #getUndoableEditListeners
*
* @since 1.3
*/
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
return listenerList.getListeners(listenerType);
}
/**
* Gets the asynchronous loading priority. If less than zero,
* the document should not be loaded asynchronously.
*
* @return the asynchronous loading priority, or <code>-1</code>
* if the document should not be loaded asynchronously
*/
public int getAsynchronousLoadPriority() {
Integer loadPriority = (Integer)
getProperty(AbstractDocument.AsyncLoadPriority);
if (loadPriority != null) {
return loadPriority.intValue();
}
return -1;
}
/**
* Sets the asynchronous loading priority.
* @param p the new asynchronous loading priority; a value
* less than zero indicates that the document should not be
* loaded asynchronously
*/
public void setAsynchronousLoadPriority(int p) {
Integer loadPriority = (p >= 0) ? Integer.valueOf(p) : null;
putProperty(AbstractDocument.AsyncLoadPriority, loadPriority);
}
/**
* Sets the <code>DocumentFilter</code>. The <code>DocumentFilter</code>
* is passed <code>insert</code> and <code>remove</code> to conditionally
* allow inserting/deleting of the text. A <code>null</code> value
* indicates that no filtering will occur.
*
* @param filter the <code>DocumentFilter</code> used to constrain text
* @see #getDocumentFilter
* @since 1.4
*/
public void setDocumentFilter(DocumentFilter filter) {
documentFilter = filter;
}
/**
* Returns the <code>DocumentFilter</code> that is responsible for
* filtering of insertion/removal. A <code>null</code> return value
* implies no filtering is to occur.
*
* @since 1.4
* @see #setDocumentFilter
* @return the DocumentFilter
*/
public DocumentFilter getDocumentFilter() {
return documentFilter;
}
// --- Document methods -----------------------------------------
/**
* This allows the model to be safely rendered in the presence
* of currency, if the model supports being updated asynchronously.
* The given runnable will be executed in a way that allows it
* to safely read the model with no changes while the runnable
* is being executed. The runnable itself may <em>not</em>
* make any mutations.
* <p>
* This is implemented to acquire a read lock for the duration
* of the runnables execution. There may be multiple runnables
* executing at the same time, and all writers will be blocked
* while there are active rendering runnables. If the runnable
* throws an exception, its lock will be safely released.
* There is no protection against a runnable that never exits,
* which will effectively leave the document locked for it's
* lifetime.
* <p>
* If the given runnable attempts to make any mutations in
* this implementation, a deadlock will occur. There is
* no tracking of individual rendering threads to enable
* detecting this situation, but a subclass could incur
* the overhead of tracking them and throwing an error.
* <p>
* This method is thread safe, although most Swing methods
* are not. Please see
* <A HREF="https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html">Concurrency
* in Swing</A> for more information.
*
* @param r the renderer to execute
*/
public void render(Runnable r) {
readLock();
try {
r.run();
} finally {
readUnlock();
}
}
/**
* Returns the length of the data. This is the number of
* characters of content that represents the users data.
*
* @return the length >= 0
* @see Document#getLength
*/
public int getLength() {
return data.length() - 1;
}
/**
* Adds a document listener for notification of any changes.
*
* @param listener the <code>DocumentListener</code> to add
* @see Document#addDocumentListener
*/
public void addDocumentListener(DocumentListener listener) {
listenerList.add(DocumentListener.class, listener);
}
/**
* Removes a document listener.
*
* @param listener the <code>DocumentListener</code> to remove
* @see Document#removeDocumentListener
*/
public void removeDocumentListener(DocumentListener listener) {
listenerList.remove(DocumentListener.class, listener);
}
/**
* Returns an array of all the document listeners
* registered on this document.
*
* @return all of this document's <code>DocumentListener</code>s
* or an empty array if no document listeners are
* currently registered
*
* @see #addDocumentListener
* @see #removeDocumentListener
* @since 1.4
*/
public DocumentListener[] getDocumentListeners() {
return listenerList.getListeners(DocumentListener.class);
}
/**
* Adds an undo listener for notification of any changes.
* Undo/Redo operations performed on the <code>UndoableEdit</code>
* will cause the appropriate DocumentEvent to be fired to keep
* the view(s) in sync with the model.
*
* @param listener the <code>UndoableEditListener</code> to add
* @see Document#addUndoableEditListener
*/
public void addUndoableEditListener(UndoableEditListener listener) {
listenerList.add(UndoableEditListener.class, listener);
}
/**
* Removes an undo listener.
*
* @param listener the <code>UndoableEditListener</code> to remove
* @see Document#removeDocumentListener
*/
public void removeUndoableEditListener(UndoableEditListener listener) {
listenerList.remove(UndoableEditListener.class, listener);
}
/**
* Returns an array of all the undoable edit listeners
* registered on this document.
*
* @return all of this document's <code>UndoableEditListener</code>s
* or an empty array if no undoable edit listeners are
* currently registered
*
* @see #addUndoableEditListener
* @see #removeUndoableEditListener
*
* @since 1.4
*/
public UndoableEditListener[] getUndoableEditListeners() {
return listenerList.getListeners(UndoableEditListener.class);
}
/**
* A convenience method for looking up a property value. It is
* equivalent to:
* <pre>
* getDocumentProperties().get(key);
* </pre>
*
* @param key the non-<code>null</code> property key
* @return the value of this property or <code>null</code>
* @see #getDocumentProperties
*/
public final Object getProperty(Object key) {
return getDocumentProperties().get(key);
}
/**
* A convenience method for storing up a property value. It is
* equivalent to:
* <pre>
* getDocumentProperties().put(key, value);
* </pre>
* If <code>value</code> is <code>null</code> this method will
* remove the property.
*
* @param key the non-<code>null</code> key
* @param value the property value
* @see #getDocumentProperties
*/
public final void putProperty(Object key, Object value) {
if (value != null) {
getDocumentProperties().put(key, value);
} else {
getDocumentProperties().remove(key);
}
if( key == TextAttribute.RUN_DIRECTION
&& Boolean.TRUE.equals(getProperty(I18NProperty)) )
{
//REMIND - this needs to flip on the i18n property if run dir
//is rtl and the i18n property is not already on.
writeLock();
try {
DefaultDocumentEvent e
= new DefaultDocumentEvent(0, getLength(),
DocumentEvent.EventType.INSERT);
updateBidi( e );
} finally {
writeUnlock();
}
}
}
/**
* Removes some content from the document.
* Removing content causes a write lock to be held while the
* actual changes are taking place. Observers are notified
* of the change on the thread that called this method.
* <p>
* This method is thread safe, although most Swing methods
* are not. Please see
* <A HREF="https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html">Concurrency
* in Swing</A> for more information.
*
* @param offs the starting offset >= 0
* @param len the number of characters to remove >= 0
* @exception BadLocationException the given remove position is not a valid
* position within the document
* @see Document#remove
*/
public void remove(int offs, int len) throws BadLocationException {
DocumentFilter filter = getDocumentFilter();
writeLock();
try {
if (filter != null) {
filter.remove(getFilterBypass(), offs, len);
}
else {
handleRemove(offs, len);
}
} finally {
writeUnlock();
}
}
/**
* Performs the actual work of the remove. It is assumed the caller
* will have obtained a <code>writeLock</code> before invoking this.
*/
void handleRemove(int offs, int len) throws BadLocationException {
if (len > 0) {
if (offs < 0 || (offs + len) > getLength()) {
throw new BadLocationException("Invalid remove",
getLength() + 1);
}
DefaultDocumentEvent chng =
new DefaultDocumentEvent(offs, len, DocumentEvent.EventType.REMOVE);
boolean isComposedTextElement;
// Check whether the position of interest is the composed text
isComposedTextElement = Utilities.isComposedTextElement(this, offs);
removeUpdate(chng);
UndoableEdit u = data.remove(offs, len);
if (u != null) {
chng.addEdit(u);
}
postRemoveUpdate(chng);
// Mark the edit as done.
chng.end();
fireRemoveUpdate(chng);
// only fire undo if Content implementation supports it
// undo for the composed text is not supported for now
if ((u != null) && !isComposedTextElement) {
fireUndoableEditUpdate(new UndoableEditEvent(this, chng));
}
}
}
/**
* Deletes the region of text from <code>offset</code> to
* <code>offset + length</code>, and replaces it with <code>text</code>.
* It is up to the implementation as to how this is implemented, some
* implementations may treat this as two distinct operations: a remove
* followed by an insert, others may treat the replace as one atomic
* operation.
*
* @param offset index of child element
* @param length length of text to delete, may be 0 indicating don't
* delete anything
* @param text text to insert, <code>null</code> indicates no text to insert
* @param attrs AttributeSet indicating attributes of inserted text,
* <code>null</code>
* is legal, and typically treated as an empty attributeset,
* but exact interpretation is left to the subclass
* @exception BadLocationException the given position is not a valid
* position within the document
* @since 1.4
*/
public void replace(int offset, int length, String text,
AttributeSet attrs) throws BadLocationException {
if (length == 0 && (text == null || text.length() == 0)) {
return;
}
DocumentFilter filter = getDocumentFilter();
writeLock();
try {
if (filter != null) {
filter.replace(getFilterBypass(), offset, length, text,
attrs);
}
else {
if (length > 0) {
remove(offset, length);
}
if (text != null && text.length() > 0) {
insertString(offset, text, attrs);
}
}
} finally {
writeUnlock();
}
}
/**
* Inserts some content into the document.
* Inserting content causes a write lock to be held while the
* actual changes are taking place, followed by notification
* to the observers on the thread that grabbed the write lock.
* <p>
* This method is thread safe, although most Swing methods
* are not. Please see
* <A HREF="https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html">Concurrency
* in Swing</A> for more information.
*
* @param offs the starting offset >= 0
* @param str the string to insert; does nothing with null/empty strings
* @param a the attributes for the inserted content
* @exception BadLocationException the given insert position is not a valid
* position within the document
* @see Document#insertString
*/
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if ((str == null) || (str.length() == 0)) {
return;
}
DocumentFilter filter = getDocumentFilter();
writeLock();
try {
if (filter != null) {
filter.insertString(getFilterBypass(), offs, str, a);
} else {
handleInsertString(offs, str, a);
}
} finally {
writeUnlock();
}
}
/**
* Performs the actual work of inserting the text; it is assumed the
* caller has obtained a write lock before invoking this.
*/
private void handleInsertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if ((str == null) || (str.length() == 0)) {
return;
}
UndoableEdit u = data.insertString(offs, str);
DefaultDocumentEvent e =
new DefaultDocumentEvent(offs, str.length(), DocumentEvent.EventType.INSERT);
if (u != null) {
e.addEdit(u);
}
// see if complex glyph layout support is needed
if( getProperty(I18NProperty).equals( Boolean.FALSE ) ) {
// if a default direction of right-to-left has been specified,
// we want complex layout even if the text is all left to right.
Object d = getProperty(TextAttribute.RUN_DIRECTION);
if ((d != null) && (d.equals(TextAttribute.RUN_DIRECTION_RTL))) {
putProperty( I18NProperty, Boolean.TRUE);
} else {
char[] chars = str.toCharArray();
if (SwingUtilities2.isComplexLayout(chars, 0, chars.length)) {
putProperty( I18NProperty, Boolean.TRUE);
}
}
}
insertUpdate(e, a);
// Mark the edit as done.
e.end();
fireInsertUpdate(e);
// only fire undo if Content implementation supports it
// undo for the composed text is not supported for now
if (u != null && (a == null || !a.isDefined(StyleConstants.ComposedTextAttribute))) {
fireUndoableEditUpdate(new UndoableEditEvent(this, e));
}
}
/**
* Gets a sequence of text from the document.
*
* @param offset the starting offset >= 0
* @param length the number of characters to retrieve >= 0
* @return the text
* @exception BadLocationException the range given includes a position
* that is not a valid position within the document
* @see Document#getText
*/
public String getText(int offset, int length) throws BadLocationException {
if (length < 0) {
throw new BadLocationException("Length must be positive", length);
}
String str = data.getString(offset, length);
return str;
}
/**
* Fetches the text contained within the given portion
* of the document.
* <p>
* If the partialReturn property on the txt parameter is false, the
* data returned in the Segment will be the entire length requested and
* may or may not be a copy depending upon how the data was stored.
* If the partialReturn property is true, only the amount of text that
* can be returned without creating a copy is returned. Using partial
* returns will give better performance for situations where large
* parts of the document are being scanned. The following is an example
* of using the partial return to access the entire document:
*
* <pre>
* int nleft = doc.getDocumentLength();
* Segment text = new Segment();
* int offs = 0;
* text.setPartialReturn(true);
* while (nleft > 0) {
* doc.getText(offs, nleft, text);
* // do something with text
* nleft -= text.count;
* offs += text.count;
* }
* </pre>
*
* @param offset the starting offset >= 0
* @param length the number of characters to retrieve >= 0
* @param txt the Segment object to retrieve the text into
* @exception BadLocationException the range given includes a position
* that is not a valid position within the document
*/
public void getText(int offset, int length, Segment txt) throws BadLocationException {
if (length < 0) {
throw new BadLocationException("Length must be positive", length);
}
data.getChars(offset, length, txt);
}
/**
* Returns a position that will track change as the document
* is altered.
* <p>
* This method is thread safe, although most Swing methods
* are not. Please see
* <A HREF="https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html">Concurrency
* in Swing</A> for more information.
*
* @param offs the position in the model >= 0
* @return the position
* @exception BadLocationException if the given position does not
* represent a valid location in the associated document
* @see Document#createPosition
*/
public synchronized Position createPosition(int offs) throws BadLocationException {
return data.createPosition(offs);
}
/**
* Returns a position that represents the start of the document. The
* position returned can be counted on to track change and stay
* located at the beginning of the document.
*
* @return the position
*/
public final Position getStartPosition() {
Position p;
try {
p = createPosition(0);
} catch (BadLocationException bl) {
p = null;
}
return p;
}
/**
* Returns a position that represents the end of the document. The
* position returned can be counted on to track change and stay
* located at the end of the document.
*
* @return the position
*/
public final Position getEndPosition() {
Position p;
try {
p = createPosition(data.length());
} catch (BadLocationException bl) {
p = null;
}
return p;
}
/**
* Gets all root elements defined. Typically, there
* will only be one so the default implementation
* is to return the default root element.
*
* @return the root element
*/
public Element[] getRootElements() {
Element[] elems = new Element[2];
elems[0] = getDefaultRootElement();
elems[1] = getBidiRootElement();
return elems;
}
/**
* Returns the root element that views should be based upon
* unless some other mechanism for assigning views to element
* structures is provided.
*
* @return the root element
* @see Document#getDefaultRootElement
*/
public abstract Element getDefaultRootElement();
// ---- local methods -----------------------------------------
/**
* Returns the <code>FilterBypass</code>. This will create one if one
* does not yet exist.
*/
private DocumentFilter.FilterBypass getFilterBypass() {
if (filterBypass == null) {
filterBypass = new DefaultFilterBypass();
}
return filterBypass;
}
/**
* Returns the root element of the bidirectional structure for this
* document. Its children represent character runs with a given
* Unicode bidi level.
*/
public Element getBidiRootElement() {
return bidiRoot;
}
/**
* Returns true if the text in the range <code>p0</code> to
* <code>p1</code> is left to right.
*/
static boolean isLeftToRight(Document doc, int p0, int p1) {
if (Boolean.TRUE.equals(doc.getProperty(I18NProperty))) {
if (doc instanceof AbstractDocument) {
AbstractDocument adoc = (AbstractDocument) doc;
Element bidiRoot = adoc.getBidiRootElement();
int index = bidiRoot.getElementIndex(p0);
Element bidiElem = bidiRoot.getElement(index);
if (bidiElem.getEndOffset() >= p1) {
AttributeSet bidiAttrs = bidiElem.getAttributes();
return ((StyleConstants.getBidiLevel(bidiAttrs) % 2) == 0);
}
}
}
return true;
}
/**
* Get the paragraph element containing the given position. Sub-classes
* must define for themselves what exactly constitutes a paragraph. They
* should keep in mind however that a paragraph should at least be the
* unit of text over which to run the Unicode bidirectional algorithm.
*
* @param pos the starting offset >= 0
* @return the element */
public abstract Element getParagraphElement(int pos);
/**
* Fetches the context for managing attributes. This
* method effectively establishes the strategy used
* for compressing AttributeSet information.
*
* @return the context
*/
protected final AttributeContext getAttributeContext() {
return context;
}
/**
* Updates document structure as a result of text insertion. This
* will happen within a write lock. If a subclass of
* this class reimplements this method, it should delegate to the
* superclass as well.
*
* @param chng a description of the change
* @param attr the attributes for the change
*/
protected void insertUpdate(DefaultDocumentEvent chng, AttributeSet attr) {
if( getProperty(I18NProperty).equals( Boolean.TRUE ) )
updateBidi( chng );
// Check if a multi byte is encountered in the inserted text.
if (chng.type == DocumentEvent.EventType.INSERT &&
chng.getLength() > 0 &&
!Boolean.TRUE.equals(getProperty(MultiByteProperty))) {
Segment segment = SegmentCache.getSharedSegment();
try {
getText(chng.getOffset(), chng.getLength(), segment);
segment.first();
do {
if ((int)segment.current() > 255) {
putProperty(MultiByteProperty, Boolean.TRUE);
break;
}
} while (segment.next() != Segment.DONE);
} catch (BadLocationException ble) {
// Should never happen
}
SegmentCache.releaseSharedSegment(segment);
}
}
/**
* Updates any document structure as a result of text removal. This
* method is called before the text is actually removed from the Content.
* This will happen within a write lock. If a subclass
* of this class reimplements this method, it should delegate to the
* superclass as well.
*
* @param chng a description of the change
*/
protected void removeUpdate(DefaultDocumentEvent chng) {
}
/**