forked from microsoft/copilot-for-eclipse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseCompletionManager.java
More file actions
706 lines (637 loc) · 25.5 KB
/
Copy pathBaseCompletionManager.java
File metadata and controls
706 lines (637 loc) · 25.5 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
package com.microsoft.copilot.eclipse.ui.completion;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.e4.core.services.events.IEventBroker;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.DefaultPositionUpdater;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextListener;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.TextEvent;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.codemining.ICodeMining;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.lsp4e.LSPEclipseUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.contexts.IContextActivation;
import org.eclipse.ui.contexts.IContextService;
import org.eclipse.ui.progress.WorkbenchJob;
import org.eclipse.ui.texteditor.ITextEditor;
import org.osgi.service.event.EventHandler;
import com.microsoft.copilot.eclipse.core.Constants;
import com.microsoft.copilot.eclipse.core.CopilotCore;
import com.microsoft.copilot.eclipse.core.completion.AcceptSuggestionType;
import com.microsoft.copilot.eclipse.core.completion.CompletionListener;
import com.microsoft.copilot.eclipse.core.completion.CompletionProvider;
import com.microsoft.copilot.eclipse.core.completion.SuggestionUpdateManager;
import com.microsoft.copilot.eclipse.core.events.CopilotEventConstants;
import com.microsoft.copilot.eclipse.core.lsp.CopilotLanguageServerConnection;
import com.microsoft.copilot.eclipse.core.lsp.protocol.CompletionItem;
import com.microsoft.copilot.eclipse.core.lsp.protocol.DidChangeFeatureFlagsParams;
import com.microsoft.copilot.eclipse.core.lsp.protocol.NotifyShownParams;
import com.microsoft.copilot.eclipse.ui.CopilotUi;
import com.microsoft.copilot.eclipse.ui.nes.RenderManager;
import com.microsoft.copilot.eclipse.ui.preferences.LanguageServerSettingManager;
import com.microsoft.copilot.eclipse.ui.utils.CompletionUtils;
import com.microsoft.copilot.eclipse.ui.utils.SwtUtils;
import com.microsoft.copilot.eclipse.ui.utils.UiUtils;
/**
* Abstract base class for completion managers. Provides common functionality for listening to events which are
* completion related and managing completion suggestions.
*/
public abstract class BaseCompletionManager implements KeyListener, MouseListener, ITextListener, CompletionListener,
IPropertyChangeListener, ITextInputListener {
private static final String COMPLETION_CONTEXT = "com.microsoft.copilot.eclipse.completionAvailableContext";
private static IContextActivation completionContextActivation;
protected CopilotLanguageServerConnection lsConnection;
protected CompletionProvider provider;
protected SuggestionUpdateManager suggestionUpdateManager;
protected ITextViewer textViewer;
protected StyledText styledText;
protected String editorTitle;
protected IDocument document;
protected URI documentUri;
protected int documentVersion;
protected org.eclipse.jface.text.Position triggerPosition;
protected List<ICodeMining> codeMinings;
protected int cachedModelOffset;
protected DefaultPositionUpdater positionUpdater;
protected boolean autoShowCompletion;
// Whether NES suggestions are enabled
protected boolean enableNes;
protected LanguageServerSettingManager settingsManager;
// Event handling
protected IEventBroker eventBroker;
protected EventHandler featureFlagsChangedEventHandler;
/**
* Creates a new completion manager. The manager is responsible for trigger the completion, apply suggestions to the
* document. And schedule the rendering of ghost text.
*/
public BaseCompletionManager(CopilotLanguageServerConnection lsConnection, CompletionProvider provider,
ITextEditor editor, LanguageServerSettingManager settingsManager) {
this.codeMinings = new ArrayList<>();
this.textViewer = (ITextViewer) editor.getAdapter(ITextViewer.class);
this.editorTitle = editor.getTitle();
// if the text viewer is null, we will not register listeners.
// the side effect is that the completion will not be triggered for this editor.
if (textViewer == null) {
CopilotCore.LOGGER.info("Text viewer is null for editor: " + this.editorTitle);
return;
}
this.styledText = this.textViewer.getTextWidget();
if (this.styledText == null) {
CopilotCore.LOGGER.info("Styled text is null for editor: " + this.editorTitle);
return;
}
this.lsConnection = lsConnection;
this.document = LSPEclipseUtils.getDocument(editor);
// position updater is used to update the position when the document is changed.
// this is needed because the completion ghost text is rendered based on the
// position in the document. If the document is changed, the position will be
// invalidated.
this.positionUpdater = new DefaultPositionUpdater(this.getCategory());
if (!initializeDocument()) {
return;
}
this.settingsManager = settingsManager;
this.provider = provider;
this.provider.addCompletionListener(this);
this.documentVersion = -1;
this.triggerPosition = new Position(0);
// initialize the auto show completion preference and add listener to update it.
this.autoShowCompletion = settingsManager.getSettings().isEnableAutoCompletions();
// initialize NES preference - only enable if both preference is true AND client preview features are enabled
this.enableNes = CopilotUi.getBooleanPreference(Constants.ENABLE_NEXT_EDIT_SUGGESTION, false)
&& CopilotCore.getPlugin().getFeatureFlags().isClientPreviewFeatureEnabled();
// Cache the model offset to clear line vertical offset when the line is out of the visible range.
// We cache the model offset here because the caret offset won't update when code blocks are collapsed.
SwtUtils.invokeOnDisplayThread(() -> {
this.cachedModelOffset = UiUtils.widgetOffset2ModelOffset(textViewer, this.styledText.getCaretOffset());
}, this.styledText);
// Initialize event handling for feature flags changes
initializeEventHandling();
registerListeners();
}
private void initializeEventHandling() {
this.eventBroker = PlatformUI.getWorkbench().getService(IEventBroker.class);
if (this.eventBroker != null) {
this.featureFlagsChangedEventHandler = event -> {
Object property = event.getProperty(IEventBroker.DATA);
if (property instanceof DidChangeFeatureFlagsParams params) {
// Update NES enablement based on both preference and feature flag
boolean nesPreference = CopilotUi.getBooleanPreference(Constants.ENABLE_NEXT_EDIT_SUGGESTION, false);
this.enableNes = nesPreference && params.isClientPreviewFeaturesEnabled();
}
};
this.eventBroker.subscribe(CopilotEventConstants.TOPIC_CHAT_DID_CHANGE_FEATURE_FLAGS,
this.featureFlagsChangedEventHandler);
}
}
private boolean initializeDocument() {
if (this.document == null) {
CopilotCore.LOGGER.info("Document is null for editor: " + this.editorTitle);
return false;
}
this.document.addPositionCategory(this.getCategory());
this.document.addPositionUpdater(this.positionUpdater);
IFile file = LSPEclipseUtils.getFile(document);
if (file == null || !file.exists()) {
CopilotCore.LOGGER.info("File is null or removed for editor: " + this.editorTitle);
return false;
}
this.documentUri = LSPEclipseUtils.toUri(document);
if (this.documentUri == null) {
CopilotCore.LOGGER.info("Document URI is null for editor: " + this.editorTitle);
return false;
}
this.suggestionUpdateManager = new SuggestionUpdateManager(this.document);
return true;
}
private void registerListeners() {
SwtUtils.invokeOnDisplayThread(() -> {
this.styledText.addKeyListener(this);
this.styledText.addMouseListener(this);
this.textViewer.addTextListener(this);
this.textViewer.addTextInputListener(this);
}, this.styledText);
this.settingsManager.registerPropertyChangeListener(this);
}
/**
* {@inheritDoc} Listen to the text change event and update the ghost text if the change is still among the part of
* the completion.
*/
@Override
public void textChanged(TextEvent event) {
DocumentEvent documentEvent = event.getDocumentEvent();
if (documentEvent == null) {
return;
}
this.cachedModelOffset = UiUtils.widgetOffset2ModelOffset(textViewer, event.getOffset());
if (isReplacement(event)) {
clearGhostTexts();
} else if (isDeletion(event)) {
if (this.suggestionUpdateManager.getSize() > 0
&& this.suggestionUpdateManager.delete(event.getReplacedText().length())) {
this.updateGhostTexts(new Position(this.cachedModelOffset));
} else {
clearGhostTexts();
}
} else if (isInsertion(event)) {
if (this.suggestionUpdateManager.getSize() > 0 && this.suggestionUpdateManager.insert(event.getText())) {
this.updateGhostTexts(new Position(this.cachedModelOffset + event.getText().length()));
} else {
clearGhostTexts();
}
}
}
/**
* Return if the text change event is a deletion event.
*/
protected boolean isDeletion(TextEvent event) {
return StringUtils.isNotEmpty(event.getReplacedText()) && StringUtils.isEmpty(event.getText());
}
/**
* Return if the text change event is a replacement event.
*/
protected boolean isReplacement(TextEvent event) {
return StringUtils.isNotEmpty(event.getReplacedText()) && StringUtils.isNotEmpty(event.getText());
}
/**
* Return if the text change event is an insertion event.
*/
protected boolean isInsertion(TextEvent event) {
return StringUtils.isEmpty(event.getReplacedText()) && StringUtils.isNotEmpty(event.getText());
}
@Override
public void onCompletionResolved(String uriString, List<CompletionItem> completions) {
if (this.lsConnection == null || this.documentUri == null) {
return;
}
if (!uriMatches(uriString)) {
return;
}
if (completions == null || completions.isEmpty()) {
// Clear old completion items when receiving null or empty list (e.g., fallback to NES)
SwtUtils.invokeOnDisplayThread(() -> {
this.clearGhostTexts();
}, this.styledText);
return;
}
if (completions.get(0).getDocVersion() != this.lsConnection.getDocumentVersion(this.documentUri)) {
return;
}
this.suggestionUpdateManager.setCompletionItems(completions);
enableContext();
this.updateGhostTexts(this.triggerPosition);
this.notifyShown();
}
@Override
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
// do nothing
}
@Override
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
this.document = newInput;
initializeDocument();
CopilotCore.LOGGER.info("Completion handler is refreshed for the document: " + this.documentUri);
}
/**
* Abstract method to update ghost texts. Subclasses must implement this method to provide specific ghost text
* rendering behavior.
*/
protected abstract void updateGhostTexts(Position inferredPosition);
/**
* Abstract method to clear completion rendering. Subclasses must implement this method to provide specific behavior
* for clearing ghost text.
*/
public abstract void clearGhostTexts();
/**
* Get the current document line based on the trigger position. This is used to get the current line of text where the
* completion is triggered.
*
* @return the current document line as a string.
* @throws BadLocationException if the trigger position is invalid.
*/
protected String getCurrentLine(Position position) throws BadLocationException {
String documentContent = this.document.get();
int triggerOffset = position.getOffset();
String documentLine = "";
int lineOffset = this.document.getLineOfOffset(triggerOffset);
if (lineOffset == this.document.getNumberOfLines() - 1) {
// this is the last line
documentLine = documentContent.substring(triggerOffset);
} else {
for (int i = triggerOffset; i < this.document.getLength(); i++) {
if (isNewLineCharacter(documentContent, i)) {
documentLine = documentContent.substring(triggerOffset, i);
break;
}
}
}
return documentLine;
}
/**
* Check if the character at the given index in the document content is a new line character.
*
* @param documentContent The content of the document.
* @param index The index to check.
* @return true if the character is a new line character, false otherwise.
*/
protected boolean isNewLineCharacter(String documentContent, int index) {
char currentChar = documentContent.charAt(index);
boolean isLineFeed = currentChar == '\n';
if (isLineFeed) {
return true;
} else {
return currentChar == '\r' && index + 1 < this.document.getLength() && documentContent.charAt(index + 1) == '\n';
}
}
@Override
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(Constants.AUTO_SHOW_COMPLETION)) {
this.autoShowCompletion = Boolean.parseBoolean(event.getNewValue().toString());
} else if (event.getProperty().equals(Constants.ENABLE_NEXT_EDIT_SUGGESTION)) {
// Only enable NES if both preference is true AND client preview features are enabled
this.enableNes = Boolean.parseBoolean(event.getNewValue().toString())
&& CopilotCore.getPlugin().getFeatureFlags().isClientPreviewFeatureEnabled();
}
}
/**
* Trigger the inline completion.
*/
public void triggerCompletion() {
try {
// TODO: this logic cannot handle the case that nes doesn't have a valid suggetion while inline completion has
// result. need merge two results later
if (shouldSkipCompletionDueToNes()) {
return;
}
IFile file = LSPEclipseUtils.getFile(document);
this.provider.triggerCompletion(file, LSPEclipseUtils.toPosition(this.triggerPosition.getOffset(), this.document),
documentVersion, this.enableNes);
} catch (BadLocationException e) {
CopilotCore.LOGGER.error(e);
}
}
/**
* Check if completion should be skipped due to active or pending NES suggestion. This prevents race conditions when
* NES is being fetched or displayed.
*
* @return true if should skip completion, false otherwise
*/
private boolean shouldSkipCompletionDueToNes() {
EditorsManager editorsManager = CopilotUi.getPlugin().getEditorsManager();
if (editorsManager == null) {
return false;
}
ITextEditor editor = editorsManager.getActiveEditor();
if (editor == null) {
return false;
}
RenderManager nesManager = editorsManager.getNesRenderManager(editor);
if (nesManager == null) {
return false;
}
// Check both pending and active states to prevent race conditions
return nesManager.isNesPendingOrActive();
}
/**
* Accept completion suggestion.
*/
public void acceptSuggestion(AcceptSuggestionType type) {
try {
this.document.addPosition(this.triggerPosition);
switch (type) {
case FULL:
this.acceptEntireSuggestion();
break;
case NEXT_WORD:
this.acceptNextWord();
break;
default:
break;
}
this.document.removePosition(this.triggerPosition);
} catch (BadLocationException e) {
CopilotCore.LOGGER.error(e);
return;
}
SwtUtils.invokeOnDisplayThread(() -> {
this.textViewer.getSelectionProvider().setSelection(new TextSelection(this.triggerPosition.offset, 0));
// Since we removed caret listener, we need to manually clear the ghost text when the caret position is changed by
// the entire suggestion acceptance to fix the line indentation not cleared issue.
if (type == AcceptSuggestionType.FULL) {
this.clearGhostTexts();
}
}, this.textViewer.getTextWidget());
}
/**
* Apply the entire completion suggestion to document.
*
* @throws BadLocationException if the offset is invalid.
*/
private void acceptEntireSuggestion() throws BadLocationException {
CompletionItem item = this.suggestionUpdateManager.getCurrentItem();
if (item == null) {
return;
}
int startOffset = LSPEclipseUtils.toOffset(item.getPosition(), this.document);
String text = this.suggestionUpdateManager.getText();
if (StringUtils.isEmpty(text)) {
return;
}
String lineDelimiter = CompletionUtils.getDocumentLineDelimiter(this.document, startOffset);
text = CompletionUtils.normalizeLineEndings(text, lineDelimiter);
int endOffset = LSPEclipseUtils.toOffset(item.getRange().getEnd(), this.document);
this.document.replace(startOffset, endOffset - startOffset, text);
}
/**
* Apply the next word of the completion suggestion to document.
*/
private void acceptNextWord() throws BadLocationException {
CompletionItem item = this.suggestionUpdateManager.getCurrentItem();
if (item == null) {
return;
}
String nextWord = this.suggestionUpdateManager.getNextWord();
if (StringUtils.isEmpty(nextWord)) {
return;
}
int startOffset = LSPEclipseUtils.toOffset(item.getPosition(), this.document);
int length = 0;
while (length < nextWord.length() && startOffset + length < this.document.getLength()) {
char c = this.document.getChar(startOffset + length);
if (c != nextWord.charAt(length)) {
break;
}
length++;
}
this.document.replace(startOffset, length, nextWord);
}
/**
* Get category for the position updater of this document.
*/
protected String getCategory() {
return this.toString();
}
/**
* Disposes the resources of this completion handler.
*/
public void dispose() {
if (this.provider != null) {
this.provider.removeCompletionListener(this);
}
if (this.settingsManager != null) {
this.settingsManager.unregisterPropertyChangeListener(this);
}
// Unsubscribe from event broker
if (this.eventBroker != null && this.featureFlagsChangedEventHandler != null) {
this.eventBroker.unsubscribe(this.featureFlagsChangedEventHandler);
this.featureFlagsChangedEventHandler = null;
}
if (this.document != null && this.documentUri != null) {
try {
this.document.removePositionCategory(this.getCategory());
} catch (BadPositionCategoryException e) {
CopilotCore.LOGGER.error(e);
}
this.document.removePositionUpdater(this.positionUpdater);
}
// put the below dispose logic to a workbench job to avoid blocking shutdown.
WorkbenchJob job = new WorkbenchJob("Dispose Completion Manager") {
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
BaseCompletionManager cm = BaseCompletionManager.this;
if (cm.textViewer != null) {
cm.textViewer.removeTextInputListener(cm);
}
if (cm.styledText != null && !cm.styledText.isDisposed()) {
cm.styledText.removeKeyListener(cm);
cm.styledText.removeMouseListener(cm);
}
return Status.OK_STATUS;
}
};
job.setSystem(true);
job.schedule();
}
public SuggestionUpdateManager getSuggestionUpdateManager() {
return suggestionUpdateManager;
}
/**
* Notify the language server that the completion suggestion is shown. This is used to track the usage of the
* completion suggestions.
*/
protected void notifyShown() {
if (this.lsConnection == null) {
return;
}
if (this.suggestionUpdateManager.getSize() == 0) {
return;
}
CompletionItem item = this.suggestionUpdateManager.getCurrentItem();
if (item == null) {
return;
}
NotifyShownParams params = new NotifyShownParams(item.getUuid());
this.lsConnection.notifyShown(params);
}
public List<ICodeMining> getCodeMinings() {
return codeMinings;
}
/**
* Enable the completion context for the current workbench. This is used to activate the context when the completion
* is available.
*/
protected static void enableContext() {
if (completionContextActivation == null) {
IContextService contextService = PlatformUI.getWorkbench().getService(IContextService.class);
if (contextService != null) {
SwtUtils.invokeOnDisplayThread(() -> {
completionContextActivation = contextService.activateContext(COMPLETION_CONTEXT);
});
}
}
}
/**
* Disable the completion context for the current workbench. This is used to deactivate the context when the
* completion is not available.
*/
protected static void disableContext() {
if (completionContextActivation != null) {
IContextService contextService = PlatformUI.getWorkbench().getService(IContextService.class);
if (contextService != null) {
SwtUtils.invokeOnDisplayThread(() -> {
contextService.deactivateContext(completionContextActivation);
});
completionContextActivation = null;
}
}
}
@Override
public void mouseDoubleClick(MouseEvent e) {
// Do nothing
}
@Override
public void mouseDown(MouseEvent e) {
handleCaretPositionChange();
}
@Override
public void mouseUp(MouseEvent e) {
// Do nothing
}
@Override
public void keyPressed(KeyEvent e) {
// Do nothing
}
@Override
public void keyReleased(KeyEvent e) {
// Skip completion triggering when the key is ESC
if (e.character != SWT.ESC) {
handleCaretPositionChange();
}
}
/**
* Handle caret move, clear and update the ghost text accordingly.
*/
protected void handleCaretPositionChange() {
if (this.lsConnection == null) {
return;
}
// it's guaranteed that the document change event comes earlier than keyReleased
// To verify this behavior, set breakpoints in org.eclipse.lsp4e.DocumentContentSynchronizer
// at the line: changeParamsToSend.getTextDocument().setVersion(++version); and this class's keyReleased method.
// Then trigger completion to verify the event.
int currentVersion = this.lsConnection.getDocumentVersion(this.documentUri);
if (this.documentVersion < 0) {
// initialize the document version and return. This avoids the ghost text
// being rendered when user opens the editor and just clicks in it.
this.documentVersion = currentVersion;
return;
}
int modelOffset = getModelOffsetFromCaretPosition();
if (this.triggerPosition.offset == modelOffset) {
return;
}
this.triggerPosition = new Position(modelOffset);
if (currentVersion == this.documentVersion) {
// if the caret position is changed without document version change, we should remove the ghost text.
clearGhostTexts();
} else {
this.documentVersion = currentVersion;
if (this.autoShowCompletion) {
triggerCompletion();
}
}
redrawBlockLineAtModelOffset(modelOffset);
}
/**
* Gets the model offset from the current caret position using the display thread. This ensures thread safety when
* accessing UI components.
*/
protected int getModelOffsetFromCaretPosition() {
int[] modelOffsetHolder = new int[1];
SwtUtils.invokeOnDisplayThread(() -> {
modelOffsetHolder[0] = UiUtils.widgetOffset2ModelOffset(textViewer, styledText.getCaretOffset());
}, this.styledText);
return modelOffsetHolder[0];
}
/**
* Redraw the block ghost text line at the given model offset. This is used to fix legacy vertical indentation issues
* when the text is outside the visible range or code blocks are collapsed.
*
* @param modelOffset The model offset to redraw the block ghost text line at.
*/
protected void redrawBlockLineAtModelOffset(int modelOffset) {
// Redraw the block ghost text line at both old and new offsets to fix legacy vertical indentation issues when text
// is outside the visible range or code blocks are collapsed.
// Fix issue: https://github.com/microsoft/copilot-eclipse/issues/105
// Fix issue: https://github.com/microsoft/copilot-eclipse/issues/137
if (modelOffset != this.cachedModelOffset) {
// The collapsed code block will cause the model offset to flicker, so we need to redraw the block ghost text line
// at both old and new offsets.
SwtUtils.redrawBlockLineAtModelOffset(textViewer, this.cachedModelOffset, false);
SwtUtils.redrawBlockLineAtModelOffset(textViewer, modelOffset, false);
this.cachedModelOffset = modelOffset;
}
}
private boolean uriMatches(String uriString) {
if (this.documentUri == null || uriString == null) {
return false;
}
// Fast-path: exact string match
if (Objects.equals(uriString, this.documentUri.toASCIIString())) {
return true;
}
try {
URI other = new URI(uriString);
// URI equality
if (other.equals(this.documentUri)) {
return true;
}
} catch (Exception ex) {
return false;
}
return false;
}
}