-
Notifications
You must be signed in to change notification settings - Fork 54
/
TMPresentationReconciler.java
885 lines (811 loc) · 29 KB
/
TMPresentationReconciler.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
/**
* Copyright (c) 2015-2017 Angelo ZERR.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation
*/
package org.eclipse.tm4e.ui.text;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.IPreferenceChangeListener;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.PreferenceChangeEvent;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.CursorLinePainter;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IPainter;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextListener;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension5;
import org.eclipse.jface.text.PaintManager;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextAttribute;
import org.eclipse.jface.text.TextEvent;
import org.eclipse.jface.text.TextPresentation;
import org.eclipse.jface.text.TextViewer;
import org.eclipse.jface.text.presentation.IPresentationDamager;
import org.eclipse.jface.text.presentation.IPresentationReconciler;
import org.eclipse.jface.text.presentation.IPresentationRepairer;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.Token;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Control;
import org.eclipse.tm4e.core.TMException;
import org.eclipse.tm4e.core.grammar.IGrammar;
import org.eclipse.tm4e.core.logger.ILogger;
import org.eclipse.tm4e.core.model.IModelTokensChangedListener;
import org.eclipse.tm4e.core.model.ITMModel;
import org.eclipse.tm4e.core.model.ModelTokensChangedEvent;
import org.eclipse.tm4e.core.model.Range;
import org.eclipse.tm4e.core.model.TMToken;
import org.eclipse.tm4e.registry.EclipseSystemLogger;
import org.eclipse.tm4e.registry.TMEclipseRegistryPlugin;
import org.eclipse.tm4e.ui.TMUIPlugin;
import org.eclipse.tm4e.ui.internal.model.TMDocumentModel;
import org.eclipse.tm4e.ui.internal.preferences.PreferenceConstants;
import org.eclipse.tm4e.ui.internal.text.TMPresentationReconcilerTestGenerator;
import org.eclipse.tm4e.ui.internal.themes.ThemeManager;
import org.eclipse.tm4e.ui.model.ITMModelManager;
import org.eclipse.tm4e.ui.themes.ITheme;
import org.eclipse.tm4e.ui.themes.IThemeManager;
import org.eclipse.tm4e.ui.themes.ITokenProvider;
import org.eclipse.tm4e.ui.utils.ClassHelper;
import org.eclipse.tm4e.ui.utils.ContentTypeHelper;
import org.eclipse.tm4e.ui.utils.ContentTypeInfo;
import org.eclipse.tm4e.ui.utils.PreferenceUtils;
import org.eclipse.ui.IEditorPart;
/**
* TextMate presentation reconciler which must be initialized with:
*
* <ul>
* <li>a TextMate grammar {@link IGrammar} used to initialize the TextMate model
* {@link ITMDocumentModel}.</li>
* <li>a token provider {@link ITokenProvider} to retrieve the {@link IToken}
* from a TextMate token type .</li>
* </ul>
*
*/
public class TMPresentationReconciler implements IPresentationReconciler {
/**
* The default text attribute if non is returned as data by the current token
*/
private final Token defaultToken;
/** The target viewer. */
private ITextViewer viewer;
/** The internal listener. */
private final InternalListener internalListener;
private IGrammar grammar;
private boolean forcedGrammar;
private ITokenProvider tokenProvider;
private boolean forcedTheme;
private final TextAttribute fDefaultTextAttribute;
private IPreferenceChangeListener themeChangeListener;
private List<ITMPresentationReconcilerListener> listeners;
private @NonNull ILogger logger = new EclipseSystemLogger("org.eclipse.tm4e.ui/debug/log/TMPresentationReconciler");
private boolean initializeViewerColors;
private boolean updateTextDecorations;
/**
* true if the presentation reconciler is enabled (grammar and theme are
* available) and false otherwise.
*/
private boolean enabled;
/**
* true if a {@link TMException} should be thrown if grammar or theme cannot be
* found and false otherwise.
*/
private boolean throwError;
public TMPresentationReconciler() {
this.defaultToken = new Token(null);
this.internalListener = new InternalListener();
this.fDefaultTextAttribute = new TextAttribute(null);
listeners = null;
if (TMEclipseRegistryPlugin.isDebugOptionEnabled("org.eclipse.tm4e.ui/debug/log/GenerateTest")) {
addTMPresentationReconcilerListener(new TMPresentationReconcilerTestGenerator());
}
setThrowError(TMEclipseRegistryPlugin.isDebugOptionEnabled("org.eclipse.tm4e.ui/debug/log/ThrowError"));
}
/**
* Listener to recolorize editors when E4 Theme from General / Appearance
* preferences changed or TextMate theme changed..
*
*/
private class ThemeChangeListener implements IPreferenceChangeListener {
@Override
public void preferenceChange(PreferenceChangeEvent event) {
IThemeManager themeManager = TMUIPlugin.getThemeManager();
if (PreferenceConstants.E4_THEME_ID.equals(event.getKey())) {
preferenceThemeChange((String) event.getNewValue(), themeManager);
} else if (PreferenceConstants.THEME_ASSOCIATIONS.equals(event.getKey())) {
preferenceThemeChange(PreferenceUtils.getE4PreferenceCSSThemeId(), themeManager);
}
}
private void preferenceThemeChange(String eclipseThemeId, IThemeManager themeManager) {
IDocument document = viewer.getDocument();
if (document == null) {
return;
}
if (grammar == null) {
return;
}
if (forcedTheme) {
// The theme was forced, don't update it.
return;
}
// Select the well TextMate theme from the given E4 theme id.
boolean dark = themeManager.isDarkEclipseTheme(eclipseThemeId);
ITokenProvider newTheme = themeManager.getThemeForScope(grammar.getScopeName(), dark);
setTheme(newTheme);
}
}
/**
* Internal listener class.
*/
class InternalListener implements ITextInputListener, IModelTokensChangedListener, ITextListener {
private void fireInstall(ITextViewer viewer, IDocument document) {
if (listeners == null) {
return;
}
synchronized (listeners) {
for (ITMPresentationReconcilerListener listener : listeners) {
listener.install(viewer, document);
}
}
}
private void fireUninstall() {
if (listeners == null) {
return;
}
synchronized (listeners) {
for (ITMPresentationReconcilerListener listener : listeners) {
listener.uninstall();
}
}
}
@Override
public void inputDocumentAboutToBeChanged(IDocument oldDocument, IDocument newDocument) {
if (oldDocument != null) {
viewer.removeTextListener(this);
getTMModelManager().disconnect(oldDocument);
fireUninstall();
}
}
@Override
public void inputDocumentChanged(IDocument oldDocument, IDocument newDocument) {
if (newDocument == null) {
return;
}
fireInstall(viewer, newDocument);
try {
viewer.addTextListener(this);
// Update the grammar
IGrammar localGrammar = findGrammar(newDocument);
if (localGrammar != null) {
TMPresentationReconciler.this.grammar = localGrammar;
} else if (isThrowError()) {
throw new TMException("Cannot find TextMate grammar for the given document");
}
// Update the theme
if (localGrammar != null) {
String scopeName = localGrammar.getScopeName();
if (tokenProvider == null) {
tokenProvider = TMUIPlugin.getThemeManager().getThemeForScope(scopeName);
}
if (tokenProvider != null) {
applyThemeEditor();
} else if (isThrowError()) {
throw new TMException("Cannot find Theme for the given grammar '" + scopeName + "'");
}
}
boolean enable = TMPresentationReconciler.this.enabled = localGrammar != null && tokenProvider != null;
if (enable) {
// Connect a TextModel to the new document.
ITMModel model = getTMModelManager().connect(newDocument);
model.setGrammar(localGrammar);
// Add model listener
model.addModelTokensChangedListener(this);
}
} catch (CoreException e) {
if (logger.isEnabled()) {
logger.log("Error while initializing TextMate model.", e);
}
}
}
/**
* Finds a grammar for the given document.
* @param newDocument
* @return
* @throws CoreException
*/
protected IGrammar findGrammar(@NonNull IDocument newDocument) throws CoreException {
IGrammar localGrammar = forcedGrammar ? TMPresentationReconciler.this.grammar : null;
if (localGrammar != null) {
return localGrammar;
}
ContentTypeInfo info = ContentTypeHelper.findContentTypes(newDocument);
if (info == null) {
return null;
}
return findGrammar(info);
}
@Override
public void textChanged(TextEvent e) {
if (!e.getViewerRedrawState()) {
return;
}
// changed text: propagate previous style, which will be overridden
// later asynchronously by TM
if (e.getDocumentEvent() != null) {
int diff = e.getText().length() - e.getLength();
if (diff == 0 || e.getOffset() <= 0) {
return;
}
StyleRange range = viewer.getTextWidget().getStyleRangeAtOffset(e.getOffset() - 1);
if (range == null) {
return;
}
range.length += diff;
viewer.getTextWidget().setStyleRange(range);
return;
}
// TextViewer#invalidateTextPresentation is called (because
// of validation, folding, etc)
// case 2), do the colorization.
IDocument document = viewer.getDocument();
if (document == null) {
return;
}
IRegion region = computeRegionToRedraw(e, document);
if (enabled) {
// case where there is grammar & theme -> update text presentation with the
// grammar tokens
ITMModel model = getTMModelManager().connect(document);
if (model == null) {
return;
}
try {
TMPresentationReconciler.this.colorize(region, (TMDocumentModel) model);
} catch (BadLocationException e1) {
TMUIPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, TMUIPlugin.PLUGIN_ID, e1.getMessage(), e1));
}
} else {
// case where there is no grammar & theme -> update text presentation with the
// default styles (ex: to support highlighting with GenericEditor)
TextPresentation presentation = new TextPresentation(region, 100);
presentation.setDefaultStyleRange(
new StyleRange(region.getOffset(), region.getLength(), null, null));
applyTextRegionCollection(presentation);
}
}
protected @NonNull IRegion computeRegionToRedraw(@NonNull TextEvent e, @NonNull IDocument document) {
IRegion region = null;
if (e.getOffset() == 0 && e.getLength() == 0 && e.getText() == null) {
// redraw state change, damage the whole document
region = new Region(0, document.getLength());
} else {
region = widgetRegion2ModelRegion(e);
}
if (region == null || region.getLength() == 0) {
return new Region(0, 0);
}
return region;
}
/**
* Translates the given text event into the corresponding range of the viewer's
* document.
*
* @param e
* the text event
* @return the widget region corresponding the region of the given event or
* <code>null</code> if none
* @since 2.1
*/
private IRegion widgetRegion2ModelRegion(TextEvent e) {
String text = e.getText();
int length = text == null ? 0 : text.length();
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
return extension.widgetRange2ModelRange(new Region(e.getOffset(), length));
}
IRegion visible = viewer.getVisibleRegion();
return new Region(e.getOffset() + visible.getOffset(), length);
}
@Override
public void modelTokensChanged(ModelTokensChangedEvent event) {
Control control = viewer.getTextWidget();
if (control != null) {
control.getDisplay().asyncExec(() -> {
if (viewer != null) {
colorize(event);
}
});
}
}
private void colorize(ModelTokensChangedEvent event) {
IDocument document = viewer.getDocument();
if (document == null) {
return;
}
ITMModel model = event.getModel();
if (! (model instanceof TMDocumentModel)) {
return;
}
TMDocumentModel docModel = (TMDocumentModel) model;
for (Range range : event.getRanges()) {
try {
int length = document.getLineOffset(range.toLineNumber - 1) + document.getLineLength(range.toLineNumber - 1) - document.getLineOffset(range.fromLineNumber - 1);
IRegion region = new Region(document.getLineOffset(range.fromLineNumber -1), length);
TMPresentationReconciler.this.colorize(region, docModel);
} catch (BadLocationException ex) {
TMUIPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, TMUIPlugin.PLUGIN_ID, ex.getMessage(), ex));
}
}
}
private IGrammar findGrammar(ContentTypeInfo info) {
if (info == null) {
return null;
}
IContentType[] contentTypes = info.getContentTypes();
// Discover the well grammar from the contentTypes
IGrammar res = TMEclipseRegistryPlugin.getGrammarRegistryManager().getGrammarFor(contentTypes);
if (res == null) {
// Discover the well grammar from the filetype
String fileName = info.getFileName();
if (fileName != null) {
String fileType = new Path(fileName).getFileExtension();
res = TMEclipseRegistryPlugin.getGrammarRegistryManager().getGrammarForFileType(fileType);
}
}
return res;
}
}
public void setGrammar(IGrammar grammar) {
boolean changed = (viewer != null && ((this.grammar == null) || !this.grammar.equals(grammar)));
this.grammar = grammar;
this.forcedGrammar = true;
if (changed) {
// Grammar has changed, recreate the TextMate model
IDocument document = viewer.getDocument();
if (document == null) {
return;
}
internalListener.inputDocumentAboutToBeChanged(viewer.getDocument(), null);
internalListener.inputDocumentChanged(null, document);
}
}
public IGrammar getGrammar() {
return grammar;
}
public ITokenProvider getTokenProvider() {
return tokenProvider;
}
public void setTheme(final ITokenProvider newTheme) {
final ITokenProvider oldTheme = this.tokenProvider;
this.forcedTheme = true;
if (!Objects.equals(oldTheme, newTheme) && grammar != null) {
this.tokenProvider = newTheme;
applyThemeEditor();
IDocument document = viewer.getDocument();
ITMModel model = getTMModelManager().connect(document);
if (! (model instanceof TMDocumentModel)) {
return;
}
TMDocumentModel docModel = (TMDocumentModel) model;
try {
colorize(new Region(0, document.getLength()), docModel);
} catch (BadLocationException e) {
TMUIPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, TMUIPlugin.PLUGIN_ID, e.getMessage(), e));
}
}
}
/**
* Force the TextMate theme id to use for the editor.
*
* @param themeId
*/
public void setThemeId(String themeId) {
setTheme(TMUIPlugin.getThemeManager().getThemeById(themeId));
}
@Override
public void install(ITextViewer viewer) {
Assert.isNotNull(viewer);
this.viewer = viewer;
viewer.addTextInputListener(internalListener);
IDocument document = viewer.getDocument();
if (document != null) {
internalListener.inputDocumentChanged(null, document);
}
themeChangeListener = new ThemeChangeListener();
ThemeManager.getInstance().addPreferenceChangeListener(themeChangeListener);
}
@Override
public void uninstall() {
viewer.removeTextInputListener(internalListener);
// Ensure we uninstall all listeners
internalListener.inputDocumentAboutToBeChanged(viewer.getDocument(), null);
if (themeChangeListener != null) {
ThemeManager.getInstance().removePreferenceChangeListener(themeChangeListener);
}
themeChangeListener = null;
}
@Override
public IPresentationDamager getDamager(String contentType) {
return null;
}
@Override
public IPresentationRepairer getRepairer(String contentType) {
return null;
}
private ITMModelManager getTMModelManager() {
return TMUIPlugin.getTMModelManager();
}
void colorize(@NonNull IRegion damage, @NonNull TMDocumentModel model) throws BadLocationException{
IDocument document = model.getDocument();
final int fromLineNumber = document.getLineOfOffset(damage.getOffset());
final int toLineNumber = document.getLineOfOffset(damage.getOffset() + damage.getLength());
applyThemeEditorIfNeeded();
// Refresh the UI Presentation
if (logger.isEnabled()) {
logger.log("Render from: " + fromLineNumber + " to: " + toLineNumber);
}
TextPresentation presentation = null;
Throwable error = null;
try {
presentation = new TextPresentation(damage, 1000);
int lastStart = presentation.getExtent().getOffset();
int length = 0;
boolean firstToken = true;
IToken lastToken = Token.UNDEFINED;
TextAttribute lastAttribute = getTokenTextAttribute(lastToken);
List<TMToken> tokens = null;
for (int line = fromLineNumber; line <= toLineNumber; line++) {
tokens = model.getLineTokens(line);
if (tokens == null) {
// TextMate tokens was not computed for this line.
// This case comes from when the viewer is invalidated (by
// validation for instance) and textChanged is called.
// see https://github.com/eclipse/tm4e/issues/78
if (logger.isEnabled()) {
logger.log("TextMate tokens not available for line " + line);
}
break;
}
int startLineOffset = document.getLineOffset(line);
for (int i = 0; i < tokens.size(); i++) {
TMToken currentToken = tokens.get(i);
TMToken nextToken = (i + 1 < tokens.size()) ? tokens.get(i + 1) : null;
int tokenStartIndex = currentToken.startIndex;
if (isBeforeRegion(currentToken, startLineOffset, damage)) {
// The token is before the damage region
if (nextToken != null) {
if (isBeforeRegion(nextToken, startLineOffset, damage)) {
// ignore it
continue;
} else {
tokenStartIndex = damage.getOffset() - startLineOffset;
}
} else {
tokenStartIndex = damage.getOffset() - startLineOffset;
IToken token = toToken(currentToken);
lastAttribute = getTokenTextAttribute(token);
length += getTokenLengh(tokenStartIndex, nextToken, line, document);
firstToken = false;
// ignore it
continue;
}
} else if (isAfterRegion(currentToken, startLineOffset, damage)) {
// The token is after the damage region, stop the
// colorization process
break;
}
IToken token = toToken(currentToken);
TextAttribute attribute = getTokenTextAttribute(token);
if (lastAttribute != null && lastAttribute.equals(attribute)) {
length += getTokenLengh(tokenStartIndex, nextToken, line, document);
firstToken = false;
} else {
if (!firstToken) {
addRange(presentation, lastStart, length, lastAttribute);
}
firstToken = false;
lastToken = token;
lastAttribute = attribute;
lastStart = tokenStartIndex + startLineOffset;
length = getTokenLengh(tokenStartIndex, nextToken, line, document);
}
}
}
// adjust the length
length = Math.min(length, damage.getOffset() + damage.getLength() - lastStart);
addRange(presentation, lastStart, length, lastAttribute);
applyTextRegionCollection(presentation);
} catch (Exception e) {
error = e;
if (logger.isEnabled()) {
logger.log("Error while rendering from: " + fromLineNumber + " to: " + toLineNumber, e);
}
TMUIPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, TMUIPlugin.PLUGIN_ID, e.getMessage(), e));
} finally {
fireColorize(presentation, error);
}
}
/**
* Return true if the given token is before the given region and false
* otherwise.
*
* @param token
* @param startLineOffset
* @param damage
* @return
*/
private boolean isBeforeRegion(TMToken token, int startLineOffset, IRegion damage) {
return token.startIndex + startLineOffset < damage.getOffset();
}
/**
* Return true if the given token is after the given region and false otherwise.
*
* @param t
* @param startLineOffset
* @param damage
* @return
*/
private boolean isAfterRegion(TMToken t, int startLineOffset, IRegion damage) {
return t.startIndex + startLineOffset >= damage.getOffset() + damage.getLength();
}
private IToken toToken(TMToken t) {
IToken token = getTokenProvider().getToken(t.type);
if (token != null) {
return token;
}
return defaultToken;
}
private int getTokenLengh(int tokenStartIndex, TMToken nextToken, int line, IDocument document)
throws BadLocationException {
if (nextToken != null) {
return nextToken.startIndex - tokenStartIndex;
}
return document.getLineLength(line) - tokenStartIndex;
}
/**
* Returns a text attribute encoded in the given token. If the token's data is
* not <code>null</code> and a text attribute it is assumed that it is the
* encoded text attribute. It returns the default text attribute if there is no
* encoded text attribute found.
*
* @param token
* the token whose text attribute is to be determined
* @return the token's text attribute
*/
protected TextAttribute getTokenTextAttribute(IToken token) {
Object data = token.getData();
if (data instanceof TextAttribute) {
return (TextAttribute) data;
}
return fDefaultTextAttribute;
}
/**
* Adds style information to the given text presentation.
*
* @param presentation
* the text presentation to be extended
* @param offset
* the offset of the range to be styled
* @param length
* the length of the range to be styled
* @param attr
* the attribute describing the style of the range to be styled
* @param lastLineStyleRanges
*/
protected void addRange(TextPresentation presentation, int offset, int length, TextAttribute attr) {
if (attr != null) {
int style = attr.getStyle();
int fontStyle = style & (SWT.ITALIC | SWT.BOLD | SWT.NORMAL);
StyleRange styleRange = new StyleRange(offset, length, attr.getForeground(), attr.getBackground(),
fontStyle);
styleRange.strikeout = (style & TextAttribute.STRIKETHROUGH) != 0;
styleRange.underline = (style & TextAttribute.UNDERLINE) != 0;
styleRange.font = attr.getFont();
presentation.addStyleRange(styleRange);
}
}
/**
* Applies the given text presentation to the text viewer the presentation
* reconciler is installed on.
*
* @param presentation
* the text presentation to be applied to the text viewer
*/
private void applyTextRegionCollection(TextPresentation presentation) {
viewer.changeTextPresentation(presentation, false);
}
/**
* Add a TextMate presentation reconciler listener.
*
* @param listener
* the TextMate presentation reconciler listener to add.
*/
public void addTMPresentationReconcilerListener(ITMPresentationReconcilerListener listener) {
if (listeners == null) {
listeners = new ArrayList<>();
}
synchronized (listeners) {
if (!listeners.contains(listener)) {
listeners.add(listener);
}
}
}
/**
* Remove a TextMate presentation reconciler listener.
*
* @param listener
* the TextMate presentation reconciler listener to remove.
*/
public void removeTMPresentationReconcilerListener(ITMPresentationReconcilerListener listener) {
if (listeners == null) {
return;
}
synchronized (listeners) {
listeners.remove(listener);
}
}
/**
* Fire colorize.
*
* @param presentation
* @param error
*/
private void fireColorize(TextPresentation presentation, Throwable error) {
if (listeners == null) {
return;
}
synchronized (listeners) {
for (ITMPresentationReconcilerListener listener : listeners) {
listener.colorize(presentation, error);
}
}
}
public void setLogger(ILogger logger) {
if (logger == null) {
return;
}
this.logger = logger;
}
public @NonNull ILogger getLogger() {
return logger;
}
public static TMPresentationReconciler getTMPresentationReconciler(IEditorPart editorPart) {
if (editorPart == null) {
return null;
}
@Nullable ITextOperationTarget target = editorPart.getAdapter(ITextOperationTarget.class);
if (target instanceof ITextViewer) {
ITextViewer textViewer = ((ITextViewer) target);
return TMPresentationReconciler.getTMPresentationReconciler(textViewer);
}
return null;
}
/**
* Returns the {@link TMPresentationReconciler} of the given text viewer and
* null otherwise.
*
* @param textViewer
* @return the {@link TMPresentationReconciler} of the given text viewer and
* null otherwise.
*/
public static TMPresentationReconciler getTMPresentationReconciler(ITextViewer textViewer) {
try {
Field field = SourceViewer.class.getDeclaredField("fPresentationReconciler");
if (field != null) {
field.setAccessible(true);
IPresentationReconciler presentationReconciler = (IPresentationReconciler) field.get(textViewer);
return presentationReconciler instanceof TMPresentationReconciler
? (TMPresentationReconciler) presentationReconciler
: null;
}
} catch (Exception e) {
TMUIPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, TMUIPlugin.PLUGIN_ID, e.getMessage(), e));
}
return null;
}
/**
* Initialize foreground, background color, current line highlight from the
* current theme.
*
*/
private void applyThemeEditor() {
this.initializeViewerColors = false;
this.updateTextDecorations = false;
applyThemeEditorIfNeeded();
}
/**
* Initialize foreground, background color, current line highlight from the
* current theme if needed.
*
*/
private void applyThemeEditorIfNeeded() {
if (!initializeViewerColors) {
StyledText styledText = viewer.getTextWidget();
((ITheme) tokenProvider).initializeViewerColors(styledText);
initializeViewerColors = true;
}
if (updateTextDecorations) {
return;
}
try {
// Ugly code to update "current line highlight" :
// - get the PaintManager from the ITextViewer with reflection.
// - get the list of IPainter of PaintManager with reflection
// - loop for IPainter to retrieve CursorLinePainter which manages "current line
// highlight".
PaintManager paintManager = ClassHelper.getFieldValue(viewer, "fPaintManager", TextViewer.class);
if (paintManager == null) {
return;
}
List<IPainter> painters = ClassHelper.getFieldValue(paintManager, "fPainters", PaintManager.class);
if (painters == null) {
return;
}
for (IPainter painter : painters) {
if (painter instanceof CursorLinePainter) {
// Update current line highlight
Color background = tokenProvider.getEditorCurrentLineHighlight();
if (background != null) {
((CursorLinePainter) painter).setHighlightColor(background);
}
updateTextDecorations = true;
}
}
} catch (Exception e) {
TMUIPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, TMUIPlugin.PLUGIN_ID, e.getMessage(), e));
}
}
/**
* Set true if a {@link TMException} should be thrown if grammar or theme cannot
* be found and false otherwise.
*
* @param throwError
*/
public void setThrowError(boolean throwError) {
this.throwError = throwError;
}
/**
* Return true if a {@link TMException} should be thrown if grammar or theme
* cannot be found and false otherwise.
*
* @return true if a {@link TMException} should be thrown if grammar or theme
* cannot be found and false otherwise.
*/
public boolean isThrowError() {
return throwError;
}
/**
* Returns true if the presentation reconciler is enabled (grammar and theme are
* available) and false otherwise.
*
* @return true if the presentation reconciler is enabled (grammar and theme are
* available) and false otherwise.
*/
public boolean isEnabled() {
return enabled;
}
}