-
Notifications
You must be signed in to change notification settings - Fork 118
/
StyledText.java
10856 lines (10745 loc) · 368 KB
/
StyledText.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
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) 2000, 2021 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
* Andrey Loskutov <loskutov@gmx.de> - bug 488172
* Stefan Xenos (Google) - bug 487254 - StyledText.getTopIndex() can return negative values
* Angelo Zerr <angelo.zerr@gmail.com> - Customize different line spacing of StyledText - Bug 522020
* Karsten Thoms <thoms@itemis.de> - bug 528746 add getOffsetAtPoint(Point)
*******************************************************************************/
package org.eclipse.swt.custom;
import java.util.*;
import java.util.stream.*;
import org.eclipse.swt.*;
import org.eclipse.swt.accessibility.*;
import org.eclipse.swt.dnd.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.internal.*;
import org.eclipse.swt.printing.*;
import org.eclipse.swt.widgets.*;
/**
* A StyledText is an editable user interface object that displays lines
* of text. The following style attributes can be defined for the text:
* <ul>
* <li>foreground color
* <li>background color
* <li>font style (bold, italic, bold-italic, regular)
* <li>underline
* <li>strikeout
* </ul>
* <p>
* In addition to text style attributes, the background color of a line may
* be specified.
* </p><p>
* There are two ways to use this widget when specifying text style information.
* You may use the API that is defined for StyledText or you may define your own
* LineStyleListener. If you define your own listener, you will be responsible
* for maintaining the text style information for the widget. IMPORTANT: You may
* not define your own listener and use the StyledText API. The following
* StyledText API is not supported if you have defined a LineStyleListener:</p>
* <ul>
* <li>getStyleRangeAtOffset(int)
* <li>getStyleRanges()
* <li>replaceStyleRanges(int,int,StyleRange[])
* <li>setStyleRange(StyleRange)
* <li>setStyleRanges(StyleRange[])
* </ul>
* <p>
* There are two ways to use this widget when specifying line background colors.
* You may use the API that is defined for StyledText or you may define your own
* LineBackgroundListener. If you define your own listener, you will be responsible
* for maintaining the line background color information for the widget.
* IMPORTANT: You may not define your own listener and use the StyledText API.
* The following StyledText API is not supported if you have defined a
* LineBackgroundListener:</p>
* <ul>
* <li>getLineBackground(int)
* <li>setLineBackground(int,int,Color)
* </ul>
* <p>
* The content implementation for this widget may also be user-defined. To do so,
* you must implement the StyledTextContent interface and use the StyledText API
* setContent(StyledTextContent) to initialize the widget.
* </p>
* <dl>
* <dt><b>Styles:</b><dd>FULL_SELECTION, MULTI, READ_ONLY, SINGLE, WRAP
* <dt><b>Events:</b><dd>ExtendedModify, LineGetBackground, LineGetSegments, LineGetStyle, Modify, Selection, Verify, VerifyKey, OrientationChange
* </dl>
* <p>
* IMPORTANT: This class is <em>not</em> intended to be subclassed.
* </p>
*
* @see <a href="http://www.eclipse.org/swt/snippets/#styledtext">StyledText snippets</a>
* @see <a href="http://www.eclipse.org/swt/examples.php">SWT Examples: CustomControlExample, TextEditor</a>
* @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a>
* @noextend This class is not intended to be subclassed by clients.
*/
public class StyledText extends Canvas {
static final char TAB = '\t';
static final String PlatformLineDelimiter = System.lineSeparator();
static final int BIDI_CARET_WIDTH = 3;
static final int DEFAULT_WIDTH = 64;
static final int DEFAULT_HEIGHT = 64;
static final int V_SCROLL_RATE = 50;
static final int H_SCROLL_RATE = 10;
static final int PREVIOUS_OFFSET_TRAILING = 0;
static final int OFFSET_LEADING = 1;
static final String STYLEDTEXT_KEY = "org.eclipse.swt.internal.cocoa.styledtext"; //$NON-NLS-1$
private static int getX(Point p) { return p.x; } // workaround p -> p.x lose typing and cannot be chained in comparing...
static final Comparator<Point> SELECTION_COMPARATOR = Comparator.comparingInt(StyledText::getX).thenComparingInt(p -> p.y);
Color selectionBackground; // selection background color
Color selectionForeground; // selection foreground color
StyledTextContent content; // native content (default or user specified)
StyledTextRenderer renderer;
Listener listener;
TextChangeListener textChangeListener; // listener for TextChanging, TextChanged and TextSet events from StyledTextContent
int verticalScrollOffset = 0; // pixel based
int horizontalScrollOffset = 0; // pixel based
boolean alwaysShowScroll = true;
int ignoreResize = 0;
int topIndex = 0; // top visible line
int topIndexY;
int clientAreaHeight = 0; // the client area height. Needed to calculate content width for new visible lines during Resize callback
int clientAreaWidth = 0; // the client area width. Needed during Resize callback to determine if line wrap needs to be recalculated
int tabLength = 4; // number of characters in a tab
int [] tabs;
int leftMargin;
int topMargin;
int rightMargin;
int bottomMargin;
Color marginColor;
int columnX; // keep track of the horizontal caret position when changing lines/pages. Fixes bug 5935
Caret[] carets;
int[] caretOffsets = {0};
int caretAlignment;
Point[] selection = { new Point(0, 0) }; // x and y are start and end caret offsets of selection (x <= y)
int[] selectionAnchors = {0}; // position of selection anchor for the selection ranges. 0 based offset from beginning of text
Point clipboardSelection; // x and y are start and end caret offsets of previous selection
Point doubleClickSelection; // selection after last mouse double click
boolean editable = true;
boolean wordWrap = false; // text is wrapped automatically
boolean visualWrap = false; // process line breaks inside logical lines (inserted by BidiSegmentEvent)
boolean hasStyleWithVariableHeight = false;
boolean hasVerticalIndent = false;
boolean doubleClickEnabled = true; // see getDoubleClickEnabled
boolean overwrite = false; // insert/overwrite edit mode
int textLimit = -1; // limits the number of characters the user can type in the widget. Unlimited by default.
Map<Integer, Integer> keyActionMap = new HashMap<>();
Color background = null; // workaround for bug 4791
Color foreground = null; //
/** True if a non-default background color is set */
boolean customBackground;
/** True if a non-default foreground color is set */
boolean customForeground;
/** False iff the widget is disabled */
boolean enabled = true;
/** True iff the widget is in the midst of being enabled or disabled */
boolean insideSetEnableCall;
Clipboard clipboard;
int clickCount;
int autoScrollDirection = SWT.NULL; // the direction of autoscrolling (up, down, right, left)
int autoScrollDistance = 0;
int lastTextChangeStart; // cache data of the
int lastTextChangeNewLineCount; // last text changing
int lastTextChangeNewCharCount; // event for use in the
int lastTextChangeReplaceLineCount; // text changed handler
int lastTextChangeReplaceCharCount;
int lastCharCount = 0;
int lastLineBottom; // the bottom pixel of the last line been replaced
boolean bidiColoring = false; // apply the BIDI algorithm on text segments of the same color
Image leftCaretBitmap = null;
Image rightCaretBitmap = null;
int caretDirection = SWT.NULL;
int caretWidth = 0;
Caret defaultCaret = null;
boolean updateCaretDirection = true;
boolean dragDetect = true;
IME ime;
Cursor cursor;
int alignment;
boolean justify;
int indent, wrapIndent;
int lineSpacing;
int alignmentMargin;
int newOrientation = SWT.NONE;
int accCaretOffset;
Accessible acc;
AccessibleControlAdapter accControlAdapter;
AccessibleAttributeAdapter accAttributeAdapter;
AccessibleEditableTextListener accEditableTextListener;
AccessibleTextExtendedAdapter accTextExtendedAdapter;
AccessibleAdapter accAdapter;
MouseNavigator mouseNavigator;
boolean middleClickPressed;
//block selection
boolean blockSelection;
int blockXAnchor = -1, blockYAnchor = -1;
int blockXLocation = -1, blockYLocation = -1;
final static boolean IS_MAC, IS_GTK;
static {
String platform = SWT.getPlatform();
IS_MAC = "cocoa".equals(platform);
IS_GTK = "gtk".equals(platform);
}
/**
* The Printing class implements printing of a range of text.
* An instance of <code>Printing</code> is returned in the
* StyledText#print(Printer) API. The run() method may be
* invoked from any thread.
*/
static class Printing implements Runnable {
final static int LEFT = 0; // left aligned header/footer segment
final static int CENTER = 1; // centered header/footer segment
final static int RIGHT = 2; // right aligned header/footer segment
Printer printer;
StyledTextRenderer printerRenderer;
StyledTextPrintOptions printOptions;
Rectangle clientArea;
FontData fontData;
Font printerFont;
Map<Resource, Resource> resources;
int tabLength;
GC gc; // printer GC
int pageWidth; // width of a printer page in pixels
int startPage; // first page to print
int endPage; // last page to print
int scope; // scope of print job
int startLine; // first (wrapped) line to print
int endLine; // last (wrapped) line to print
boolean singleLine; // widget single line mode
Point[] selection = { new Point(0, 0) }; // x and y are start and end caret offsets of selection (x <= y)
boolean mirrored; // indicates the printing gc should be mirrored
int lineSpacing;
int printMargin;
/**
* Creates an instance of <code>Printing</code>.
* Copies the widget content and rendering data that needs
* to be requested from listeners.
*
* @param parent StyledText widget to print.
* @param printer printer device to print on.
* @param printOptions print options
*/
Printing(StyledText styledText, Printer printer, StyledTextPrintOptions printOptions) {
this.printer = printer;
this.printOptions = printOptions;
this.mirrored = (styledText.getStyle() & SWT.MIRRORED) != 0;
singleLine = styledText.isSingleLine();
startPage = 1;
endPage = Integer.MAX_VALUE;
PrinterData data = printer.getPrinterData();
scope = data.scope;
if (scope == PrinterData.PAGE_RANGE) {
startPage = data.startPage;
endPage = data.endPage;
if (endPage < startPage) {
int temp = endPage;
endPage = startPage;
startPage = temp;
}
} else if (scope == PrinterData.SELECTION) {
selection = Arrays.copyOf(styledText.selection, styledText.selection.length);
}
printerRenderer = new StyledTextRenderer(printer, null);
printerRenderer.setContent(copyContent(styledText.getContent()));
cacheLineData(styledText);
}
/**
* Caches all line data that needs to be requested from a listener.
*
* @param printerContent <code>StyledTextContent</code> to request
* line data for.
*/
void cacheLineData(StyledText styledText) {
StyledTextRenderer renderer = styledText.renderer;
renderer.copyInto(printerRenderer);
fontData = styledText.getFont().getFontData()[0];
tabLength = styledText.tabLength;
int lineCount = printerRenderer.lineCount;
if (styledText.isListening(ST.LineGetBackground) || (styledText.isListening(ST.LineGetSegments)) || styledText.isListening(ST.LineGetStyle)) {
StyledTextContent content = printerRenderer.content;
for (int i = 0; i < lineCount; i++) {
String line = content.getLine(i);
int lineOffset = content.getOffsetAtLine(i);
StyledTextEvent event = styledText.getLineBackgroundData(lineOffset, line);
if (event != null && event.lineBackground != null) {
printerRenderer.setLineBackground(i, 1, event.lineBackground);
}
event = styledText.getBidiSegments(lineOffset, line);
if (event != null) {
printerRenderer.setLineSegments(i, 1, event.segments);
printerRenderer.setLineSegmentChars(i, 1, event.segmentsChars);
}
event = styledText.getLineStyleData(lineOffset, line);
if (event != null) {
printerRenderer.setLineIndent(i, 1, event.indent);
printerRenderer.setLineAlignment(i, 1, event.alignment);
printerRenderer.setLineJustify(i, 1, event.justify);
printerRenderer.setLineBullet(i, 1, event.bullet);
StyleRange[] styles = event.styles;
if (styles != null && styles.length > 0) {
printerRenderer.setStyleRanges(event.ranges, styles);
}
}
}
}
Point screenDPI = styledText.getDisplay().getDPI();
Point printerDPI = printer.getDPI();
resources = new HashMap<> ();
for (int i = 0; i < lineCount; i++) {
Color color = printerRenderer.getLineBackground(i, null);
if (color != null) {
if (printOptions.printLineBackground) {
Color printerColor = (Color)resources.get(color);
if (printerColor == null) {
printerColor = new Color (color.getRGB());
resources.put(color, printerColor);
}
printerRenderer.setLineBackground(i, 1, printerColor);
} else {
printerRenderer.setLineBackground(i, 1, null);
}
}
int indent = printerRenderer.getLineIndent(i, 0);
if (indent != 0) {
printerRenderer.setLineIndent(i, 1, indent * printerDPI.x / screenDPI.x);
}
}
StyleRange[] styles = printerRenderer.styles;
for (int i = 0; i < printerRenderer.styleCount; i++) {
StyleRange style = styles[i];
Font font = style.font;
if (style.font != null) {
Font printerFont = (Font)resources.get(font);
if (printerFont == null) {
printerFont = new Font (printer, font.getFontData());
resources.put(font, printerFont);
}
style.font = printerFont;
}
Color color = style.foreground;
if (color != null) {
Color printerColor = (Color)resources.get(color);
if (printOptions.printTextForeground) {
if (printerColor == null) {
printerColor = new Color (color.getRGB());
resources.put(color, printerColor);
}
style.foreground = printerColor;
} else {
style.foreground = null;
}
}
color = style.background;
if (color != null) {
Color printerColor = (Color)resources.get(color);
if (printOptions.printTextBackground) {
if (printerColor == null) {
printerColor = new Color (color.getRGB());
resources.put(color, printerColor);
}
style.background = printerColor;
} else {
style.background = null;
}
}
if (!printOptions.printTextFontStyle) {
style.fontStyle = SWT.NORMAL;
}
style.rise = style.rise * printerDPI.y / screenDPI.y;
GlyphMetrics metrics = style.metrics;
if (metrics != null) {
metrics.ascent = metrics.ascent * printerDPI.y / screenDPI.y;
metrics.descent = metrics.descent * printerDPI.y / screenDPI.y;
metrics.width = metrics.width * printerDPI.x / screenDPI.x;
}
}
lineSpacing = styledText.lineSpacing * printerDPI.y / screenDPI.y;
if (printOptions.printLineNumbers) {
printMargin = 3 * printerDPI.x / screenDPI.x;
}
}
/**
* Copies the text of the specified <code>StyledTextContent</code>.
*
* @param original the <code>StyledTextContent</code> to copy.
*/
StyledTextContent copyContent(StyledTextContent original) {
StyledTextContent printerContent = new DefaultContent();
int insertOffset = 0;
for (int i = 0; i < original.getLineCount(); i++) {
int insertEndOffset;
if (i < original.getLineCount() - 1) {
insertEndOffset = original.getOffsetAtLine(i + 1);
} else {
insertEndOffset = original.getCharCount();
}
printerContent.replaceTextRange(insertOffset, 0, original.getTextRange(insertOffset, insertEndOffset - insertOffset));
insertOffset = insertEndOffset;
}
return printerContent;
}
/**
* Disposes of the resources and the <code>PrintRenderer</code>.
*/
void dispose() {
if (gc != null) {
gc.dispose();
gc = null;
}
if (resources != null) {
for (Resource resource : resources.values()) {
resource.dispose();
}
resources = null;
}
if (printerFont != null) {
printerFont.dispose();
printerFont = null;
}
if (printerRenderer != null) {
printerRenderer.dispose();
printerRenderer = null;
}
}
void init() {
Rectangle trim = printer.computeTrim(0, 0, 0, 0);
Point dpi = printer.getDPI();
printerFont = new Font(printer, fontData.getName(), fontData.getHeight(), SWT.NORMAL);
clientArea = printer.getClientArea();
pageWidth = clientArea.width;
// one inch margin around text
clientArea.x = dpi.x + trim.x;
clientArea.y = dpi.y + trim.y;
clientArea.width -= (clientArea.x + trim.width);
clientArea.height -= (clientArea.y + trim.height);
int style = mirrored ? SWT.RIGHT_TO_LEFT : SWT.LEFT_TO_RIGHT;
gc = new GC(printer, style);
gc.setFont(printerFont);
printerRenderer.setFont(printerFont, tabLength);
int lineHeight = printerRenderer.getLineHeight();
if (printOptions.header != null) {
clientArea.y += lineHeight * 2;
clientArea.height -= lineHeight * 2;
}
if (printOptions.footer != null) {
clientArea.height -= lineHeight * 2;
}
// TODO not wrapped
StyledTextContent content = printerRenderer.content;
startLine = 0;
endLine = singleLine ? 0 : content.getLineCount() - 1;
if (scope == PrinterData.PAGE_RANGE) {
int pageSize = clientArea.height / lineHeight;//WRONG
startLine = (startPage - 1) * pageSize;
} else if (scope == PrinterData.SELECTION) {
startLine = content.getLineAtOffset(selection[0].x);
if (selection[0].y > 0) {
endLine = content.getLineAtOffset(selection[0].y);
} else {
endLine = startLine - 1;
}
}
}
/**
* Prints the lines in the specified page range.
*/
void print() {
Color background = gc.getBackground();
Color foreground = gc.getForeground();
int paintY = clientArea.y;
int paintX = clientArea.x;
int width = clientArea.width;
int page = startPage;
int pageBottom = clientArea.y + clientArea.height;
int orientation = gc.getStyle() & (SWT.RIGHT_TO_LEFT | SWT.LEFT_TO_RIGHT);
TextLayout printLayout = null;
if (printOptions.printLineNumbers || printOptions.header != null || printOptions.footer != null) {
printLayout = new TextLayout(printer);
printLayout.setFont(printerFont);
}
if (printOptions.printLineNumbers) {
int numberingWidth = 0;
int count = endLine - startLine + 1;
String[] lineLabels = printOptions.lineLabels;
if (lineLabels != null) {
for (int i = startLine; i < Math.min(count, lineLabels.length); i++) {
if (lineLabels[i] != null) {
printLayout.setText(lineLabels[i]);
int lineWidth = printLayout.getBounds().width;
numberingWidth = Math.max(numberingWidth, lineWidth);
}
}
} else {
StringBuilder buffer = new StringBuilder("0");
while ((count /= 10) > 0) buffer.append("0");
printLayout.setText(buffer.toString());
numberingWidth = printLayout.getBounds().width;
}
numberingWidth += printMargin;
if (numberingWidth > width) numberingWidth = width;
paintX += numberingWidth;
width -= numberingWidth;
}
for (int i = startLine; i <= endLine && page <= endPage; i++) {
if (paintY == clientArea.y) {
printer.startPage();
printDecoration(page, true, printLayout);
}
TextLayout layout = printerRenderer.getTextLayout(i, orientation, width, lineSpacing);
Color lineBackground = printerRenderer.getLineBackground(i, background);
int paragraphBottom = paintY + layout.getBounds().height;
if (paragraphBottom <= pageBottom) {
//normal case, the whole paragraph fits in the current page
printLine(paintX, paintY, gc, foreground, lineBackground, layout, printLayout, i);
paintY = paragraphBottom;
} else {
int lineCount = layout.getLineCount();
while (paragraphBottom > pageBottom && lineCount > 0) {
lineCount--;
paragraphBottom -= layout.getLineBounds(lineCount).height + layout.getSpacing();
}
if (lineCount == 0) {
//the whole paragraph goes to the next page
printDecoration(page, false, printLayout);
printer.endPage();
page++;
if (page <= endPage) {
printer.startPage();
printDecoration(page, true, printLayout);
paintY = clientArea.y;
printLine(paintX, paintY, gc, foreground, lineBackground, layout, printLayout, i);
paintY += layout.getBounds().height;
}
} else {
//draw paragraph top in the current page and paragraph bottom in the next
int height = paragraphBottom - paintY;
gc.setClipping(clientArea.x, paintY, clientArea.width, height);
printLine(paintX, paintY, gc, foreground, lineBackground, layout, printLayout, i);
gc.setClipping((Rectangle)null);
printDecoration(page, false, printLayout);
printer.endPage();
page++;
if (page <= endPage) {
printer.startPage();
printDecoration(page, true, printLayout);
paintY = clientArea.y - height;
int layoutHeight = layout.getBounds().height;
gc.setClipping(clientArea.x, clientArea.y, clientArea.width, layoutHeight - height);
printLine(paintX, paintY, gc, foreground, lineBackground, layout, printLayout, i);
gc.setClipping((Rectangle)null);
paintY += layoutHeight;
}
}
}
printerRenderer.disposeTextLayout(layout);
}
if (page <= endPage && paintY > clientArea.y) {
// close partial page
printDecoration(page, false, printLayout);
printer.endPage();
}
if (printLayout != null) printLayout.dispose();
}
/**
* Print header or footer decorations.
*
* @param page page number to print, if specified in the StyledTextPrintOptions header or footer.
* @param header true = print the header, false = print the footer
*/
void printDecoration(int page, boolean header, TextLayout layout) {
String text = header ? printOptions.header : printOptions.footer;
if (text == null) return;
int lastSegmentIndex = 0;
for (int i = 0; i < 3; i++) {
int segmentIndex = text.indexOf(StyledTextPrintOptions.SEPARATOR, lastSegmentIndex);
String segment;
if (segmentIndex == -1) {
segment = text.substring(lastSegmentIndex);
printDecorationSegment(segment, i, page, header, layout);
break;
} else {
segment = text.substring(lastSegmentIndex, segmentIndex);
printDecorationSegment(segment, i, page, header, layout);
lastSegmentIndex = segmentIndex + StyledTextPrintOptions.SEPARATOR.length();
}
}
}
/**
* Print one segment of a header or footer decoration.
* Headers and footers have three different segments.
* One each for left aligned, centered, and right aligned text.
*
* @param segment decoration segment to print
* @param alignment alignment of the segment. 0=left, 1=center, 2=right
* @param page page number to print, if specified in the decoration segment.
* @param header true = print the header, false = print the footer
*/
void printDecorationSegment(String segment, int alignment, int page, boolean header, TextLayout layout) {
int pageIndex = segment.indexOf(StyledTextPrintOptions.PAGE_TAG);
if (pageIndex != -1) {
int pageTagLength = StyledTextPrintOptions.PAGE_TAG.length();
StringBuilder buffer = new StringBuilder(segment.substring (0, pageIndex));
buffer.append (page);
buffer.append (segment.substring(pageIndex + pageTagLength));
segment = buffer.toString();
}
if (segment.length() > 0) {
layout.setText(segment);
int segmentWidth = layout.getBounds().width;
int segmentHeight = printerRenderer.getLineHeight();
int drawX = 0, drawY;
if (alignment == LEFT) {
drawX = clientArea.x;
} else if (alignment == CENTER) {
drawX = (pageWidth - segmentWidth) / 2;
} else if (alignment == RIGHT) {
drawX = clientArea.x + clientArea.width - segmentWidth;
}
if (header) {
drawY = clientArea.y - segmentHeight * 2;
} else {
drawY = clientArea.y + clientArea.height + segmentHeight;
}
layout.draw(gc, drawX, drawY);
}
}
void printLine(int x, int y, GC gc, Color foreground, Color background, TextLayout layout, TextLayout printLayout, int index) {
if (background != null) {
Rectangle rect = layout.getBounds();
gc.setBackground(background);
gc.fillRectangle(x, y, rect.width, rect.height);
// int lineCount = layout.getLineCount();
// for (int i = 0; i < lineCount; i++) {
// Rectangle rect = layout.getLineBounds(i);
// rect.x += paintX;
// rect.y += paintY + layout.getSpacing();
// rect.width = width;//layout bounds
// gc.fillRectangle(rect);
// }
}
if (printOptions.printLineNumbers) {
FontMetrics metrics = layout.getLineMetrics(0);
printLayout.setAscent(metrics.getAscent() + metrics.getLeading());
printLayout.setDescent(metrics.getDescent());
String[] lineLabels = printOptions.lineLabels;
if (lineLabels != null) {
if (0 <= index && index < lineLabels.length && lineLabels[index] != null) {
printLayout.setText(lineLabels[index]);
} else {
printLayout.setText("");
}
} else {
printLayout.setText(String.valueOf(index));
}
int paintX = x - printMargin - printLayout.getBounds().width;
printLayout.draw(gc, paintX, y);
printLayout.setAscent(-1);
printLayout.setDescent(-1);
}
gc.setForeground(foreground);
layout.draw(gc, x, y);
}
/**
* Starts a print job and prints the pages specified in the constructor.
*/
@Override
public void run() {
String jobName = printOptions.jobName;
if (jobName == null) {
jobName = "Printing";
}
if (printer.startJob(jobName)) {
init();
print();
dispose();
printer.endJob();
}
}
}
/**
* Constructs a new instance of this class given its parent
* and a style value describing its behavior and appearance.
* <p>
* The style value is either one of the style constants defined in
* class <code>SWT</code> which is applicable to instances of this
* class, or must be built by <em>bitwise OR</em>'ing together
* (that is, using the <code>int</code> "|" operator) two or more
* of those <code>SWT</code> style constants. The class description
* lists the style constants that are applicable to the class.
* Style bits are also inherited from superclasses.
* </p>
*
* @param parent a widget which will be the parent of the new instance (cannot be null)
* @param style the style of widget to construct
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the parent</li>
* </ul>
*
* @see SWT#FULL_SELECTION
* @see SWT#MULTI
* @see SWT#READ_ONLY
* @see SWT#SINGLE
* @see SWT#WRAP
* @see #getStyle
*/
public StyledText(Composite parent, int style) {
super(parent, checkStyle(style));
// set the fg in the OS to ensure that these are the same as StyledText, necessary
// for ensuring that the bg/fg the IME box uses is the same as what StyledText uses
super.setForeground(getForeground());
super.setDragDetect(false);
Display display = getDisplay();
if ((style & SWT.READ_ONLY) != 0) {
setEditable(false);
}
leftMargin = rightMargin = isBidiCaret() ? BIDI_CARET_WIDTH - 1: 0;
if ((style & SWT.SINGLE) != 0 && (style & SWT.BORDER) != 0) {
leftMargin = topMargin = rightMargin = bottomMargin = 2;
}
alignment = style & (SWT.LEFT | SWT.RIGHT | SWT.CENTER);
if (alignment == 0) alignment = SWT.LEFT;
clipboard = new Clipboard(display);
installDefaultContent();
renderer = new StyledTextRenderer(getDisplay(), this);
renderer.setContent(content);
renderer.setFont(getFont(), tabLength);
ime = new IME(this, SWT.NONE);
defaultCaret = new Caret(this, SWT.NONE);
if ((style & SWT.WRAP) != 0) {
setWordWrap(true);
}
if (isBidiCaret()) {
createCaretBitmaps();
Runnable runnable = () -> {
int direction = BidiUtil.getKeyboardLanguage() == BidiUtil.KEYBOARD_BIDI ? SWT.RIGHT : SWT.LEFT;
if (direction == caretDirection) return;
if (getCaret() != defaultCaret) return;
setCaretLocations(Arrays.stream(caretOffsets).mapToObj(this::getPointAtOffset).toArray(Point[]::new), direction);
};
BidiUtil.addLanguageListener(this, runnable);
}
setCaret(defaultCaret);
calculateScrollBars();
createKeyBindings();
super.setCursor(display.getSystemCursor(SWT.CURSOR_IBEAM));
installListeners();
initializeAccessible();
setData("DEFAULT_DROP_TARGET_EFFECT", new StyledTextDropTargetEffect(this));
if (IS_MAC) setData(STYLEDTEXT_KEY);
}
/**
* Adds an extended modify listener. An ExtendedModify event is sent by the
* widget when the widget text has changed.
*
* @param extendedModifyListener the listener
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT when listener is null</li>
* </ul>
*/
public void addExtendedModifyListener(ExtendedModifyListener extendedModifyListener) {
checkWidget();
if (extendedModifyListener == null) SWT.error(SWT.ERROR_NULL_ARGUMENT);
StyledTextListener typedListener = new StyledTextListener(extendedModifyListener);
addListener(ST.ExtendedModify, typedListener);
}
/**
* Adds a bidirectional segment listener.
* <p>
* A BidiSegmentEvent is sent
* whenever a line of text is measured or rendered. You can
* specify text ranges in the line that should be treated as if they
* had a different direction than the surrounding text.
* This may be used when adjacent segments of right-to-left text should
* not be reordered relative to each other.
* E.g., multiple Java string literals in a right-to-left language
* should generally remain in logical order to each other, that is, the
* way they are stored.
* </p>
*
* @param listener the listener
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT when listener is null</li>
* </ul>
* @see BidiSegmentEvent
* @since 2.0
*/
public void addBidiSegmentListener(BidiSegmentListener listener) {
checkWidget();
if (listener == null) SWT.error(SWT.ERROR_NULL_ARGUMENT);
addListener(ST.LineGetSegments, new StyledTextListener(listener));
resetCache(0, content.getLineCount());
setCaretLocations();
super.redraw();
}
/**
* Adds a caret listener. CaretEvent is sent when the caret offset changes.
*
* @param listener the listener
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT when listener is null</li>
* </ul>
*
* @since 3.5
*/
public void addCaretListener(CaretListener listener) {
checkWidget();
if (listener == null) SWT.error(SWT.ERROR_NULL_ARGUMENT);
addListener(ST.CaretMoved, new StyledTextListener(listener));
}
/**
* Adds a line background listener. A LineGetBackground event is sent by the
* widget to determine the background color for a line.
*
* @param listener the listener
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT when listener is null</li>
* </ul>
*/
public void addLineBackgroundListener(LineBackgroundListener listener) {
checkWidget();
if (listener == null) SWT.error(SWT.ERROR_NULL_ARGUMENT);
if (!isListening(ST.LineGetBackground)) {
renderer.clearLineBackground(0, content.getLineCount());
}
addListener(ST.LineGetBackground, new StyledTextListener(listener));
}
/**
* Adds a line style listener. A LineGetStyle event is sent by the widget to
* determine the styles for a line.
*
* @param listener the listener
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT when listener is null</li>
* </ul>
*/
public void addLineStyleListener(LineStyleListener listener) {
checkWidget();
if (listener == null) SWT.error(SWT.ERROR_NULL_ARGUMENT);
if (!isListening(ST.LineGetStyle)) {
setStyleRanges(0, 0, null, null, true);
renderer.clearLineStyle(0, content.getLineCount());
}
addListener(ST.LineGetStyle, new StyledTextListener(listener));
setCaretLocations();
}
/**
* Adds a modify listener. A Modify event is sent by the widget when the widget text
* has changed.
*
* @param modifyListener the listener
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT when listener is null</li>
* </ul>
*/
public void addModifyListener(ModifyListener modifyListener) {
addTypedListener(modifyListener, SWT.Modify);
}
/**
* Adds a paint object listener. A paint object event is sent by the widget when an object
* needs to be drawn.
*
* @param listener the listener
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT when listener is null</li>
* </ul>
*
* @since 3.2
*
* @see PaintObjectListener
* @see PaintObjectEvent
*/
public void addPaintObjectListener(PaintObjectListener listener) {
checkWidget();
if (listener == null) SWT.error(SWT.ERROR_NULL_ARGUMENT);
addListener(ST.PaintObject, new StyledTextListener(listener));
}
/**
* Adds a selection listener. A Selection event is sent by the widget when the
* user changes the selection.
* <p>
* When <code>widgetSelected</code> is called, the event x and y fields contain
* the start and end caret indices of the selection[0]. The selection values returned are visual
* (i.e., x will always always be <= y).
* No event is sent when the caret is moved while the selection length is 0.
* </p><p>
* <code>widgetDefaultSelected</code> is not called for StyledTexts.
* </p>
*
* @param listener the listener which should be notified when the user changes the receiver's selection
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
* </ul>
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
*
* @see SelectionListener
* @see #removeSelectionListener
* @see SelectionEvent
*/
public void addSelectionListener(SelectionListener listener) {
addTypedListener(listener, SWT.Selection); //TODO: default selection?
}
/**
* Adds a verify key listener. A VerifyKey event is sent by the widget when a key
* is pressed. The widget ignores the key press if the listener sets the doit field
* of the event to false.
*
* @param listener the listener
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT when listener is null</li>
* </ul>
*/
public void addVerifyKeyListener(VerifyKeyListener listener) {
checkWidget();
if (listener == null) SWT.error(SWT.ERROR_NULL_ARGUMENT);
addListener(ST.VerifyKey, new StyledTextListener(listener));
}
/**
* Adds a verify listener. A Verify event is sent by the widget when the widget text
* is about to change. The listener can set the event text and the doit field to
* change the text that is set in the widget or to force the widget to ignore the
* text change.
*
* @param verifyListener the listener
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT when listener is null</li>
* </ul>
*/
public void addVerifyListener(VerifyListener verifyListener) {
addTypedListener(verifyListener, SWT.Verify);
}
/**
* Adds a word movement listener. A movement event is sent when the boundary
* of a word is needed. For example, this occurs during word next and word
* previous actions.
*
* @param movementListener the listener
* @exception SWTException <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
* </ul>
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT when listener is null</li>
* </ul>
*
* @see MovementEvent
* @see MovementListener
* @see #removeWordMovementListener
*
* @since 3.3
*/
public void addWordMovementListener(MovementListener movementListener) {