diff --git a/plugin/src/software/aws/toolkits/eclipse/amazonq/handlers/QAcceptSuggestionsHandler.java b/plugin/src/software/aws/toolkits/eclipse/amazonq/handlers/QAcceptSuggestionsHandler.java index e49c2917..817a0063 100644 --- a/plugin/src/software/aws/toolkits/eclipse/amazonq/handlers/QAcceptSuggestionsHandler.java +++ b/plugin/src/software/aws/toolkits/eclipse/amazonq/handlers/QAcceptSuggestionsHandler.java @@ -23,6 +23,7 @@ public final boolean isEnabled() { public final Object execute(final ExecutionEvent event) throws ExecutionException { var suggestion = QInvocationSession.getInstance().getCurrentSuggestion(); var widget = QInvocationSession.getInstance().getViewer().getTextWidget(); + QInvocationSession.getInstance().transitionToDecisionMade(); Display display = widget.getDisplay(); display.syncExec(() -> this.insertSuggestion(suggestion.getInsertText())); return null; @@ -36,7 +37,6 @@ private void insertSuggestion(final String suggestion) { var insertOffset = widget.getCaretOffset(); doc.replace(insertOffset, 0, suggestion); widget.setCaretOffset(insertOffset + suggestion.length()); - QInvocationSession.getInstance().transitionToDecisionMade(); QInvocationSession.getInstance().getViewer().getTextWidget().redraw(); QInvocationSession.getInstance().executeCallbackForCodeReference(); QInvocationSession.getInstance().end(); diff --git a/plugin/src/software/aws/toolkits/eclipse/amazonq/util/QInlineCaretListener.java b/plugin/src/software/aws/toolkits/eclipse/amazonq/util/QInlineCaretListener.java index 3646ef01..e9eb6c61 100644 --- a/plugin/src/software/aws/toolkits/eclipse/amazonq/util/QInlineCaretListener.java +++ b/plugin/src/software/aws/toolkits/eclipse/amazonq/util/QInlineCaretListener.java @@ -24,11 +24,7 @@ public void caretMoved(final CaretEvent event) { return; } - // There are instances where the caret movement was induced by sources other than user input - // Under these instances, it is observed that the caret would revert back to a position that was last - // placed by the user in the same rendering cycle. - // We want to preserve the preview state and prevent it from terminating by these non-user instructed movements - if (event.caretOffset != widget.getCaretOffset() && qInvocationSessionInstance.isPreviewingSuggestions()) { + if (qInvocationSessionInstance.isPreviewingSuggestions()) { qInvocationSessionInstance.transitionToDecisionMade(); qInvocationSessionInstance.end(); } diff --git a/plugin/src/software/aws/toolkits/eclipse/amazonq/util/QInlineInputListener.java b/plugin/src/software/aws/toolkits/eclipse/amazonq/util/QInlineInputListener.java new file mode 100644 index 00000000..9e6bb8d2 --- /dev/null +++ b/plugin/src/software/aws/toolkits/eclipse/amazonq/util/QInlineInputListener.java @@ -0,0 +1,220 @@ +// Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +package software.aws.toolkits.eclipse.amazonq.util; + +import org.eclipse.core.runtime.preferences.IEclipsePreferences; +import org.eclipse.core.runtime.preferences.InstanceScope; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.custom.VerifyKeyListener; +import org.eclipse.swt.events.VerifyEvent; +import org.eclipse.swt.events.VerifyListener; + +public final class QInlineInputListener implements VerifyListener, VerifyKeyListener { + private StyledText widget = null; + private int distanceTraversed = 0; + private boolean isAutoClosingEnabled = true; + private LastKeyStrokeType lastKeyStrokeType = LastKeyStrokeType.NORMAL_INPUT; + + private enum LastKeyStrokeType { + NORMAL_INPUT, BACKSPACE, NORMAL_BRACKET, CURLY_BRACES, OPEN_CURLY, OPEN_CURLY_FOLLOWED_BY_NEW_LINE, + } + + public QInlineInputListener(final StyledText widget) { + IEclipsePreferences preferences = InstanceScope.INSTANCE.getNode("org.eclipse.jdt.ui"); + // This needs to be defaulted to true. This key is only present in the + // preference store if it is set to false. + // Therefore if you can't find it, it has been set to true. + this.isAutoClosingEnabled = preferences.getBoolean("closeBrackets", true); + this.widget = widget; + } + + @Override + public void verifyKey(final VerifyEvent event) { + var qInvocationSessionInstance = QInvocationSession.getInstance(); + if (qInvocationSessionInstance == null || !qInvocationSessionInstance.isPreviewingSuggestions()) { + return; + } + + // We need to provide the reason for the caret movement. This way we can perform + // subsequent actions accordingly: + // - If the caret has been moved due to traversals (i.e. arrow keys or mouse + // click) we would want to end the invocation session since that signifies the + // user no longer has the intent for text input at its original location. + if (event.keyCode == SWT.ARROW_UP || event.keyCode == SWT.ARROW_DOWN || event.keyCode == SWT.ARROW_LEFT + || event.keyCode == SWT.ARROW_RIGHT) { + qInvocationSessionInstance.setCaretMovementReason(CaretMovementReason.MOVEMENT_KEY); + return; + } + + qInvocationSessionInstance.setCaretMovementReason(CaretMovementReason.TEXT_INPUT); + + // Here we examine all other relevant keystrokes that may be relevant to the + // preview's lifetime: + // - CR (new line) + // - BS (backspace) + String currentSuggestion = qInvocationSessionInstance.getCurrentSuggestion().getInsertText().trim(); + switch (event.keyCode) { + case SWT.CR: + if (lastKeyStrokeType == LastKeyStrokeType.OPEN_CURLY && isAutoClosingEnabled) { + lastKeyStrokeType = LastKeyStrokeType.OPEN_CURLY_FOLLOWED_BY_NEW_LINE; + // we need to unset the vertical indent prior to new line otherwise the line + // inserted by + // eclipse with the closing curly braces would inherit the extra vertical + // indent. + qInvocationSessionInstance.unsetVerticalIndent(); + } else { + lastKeyStrokeType = LastKeyStrokeType.NORMAL_INPUT; + } + return; + case SWT.BS: + if (--distanceTraversed < 0) { + qInvocationSessionInstance.transitionToDecisionMade(); + qInvocationSessionInstance.end(); + return; + } + lastKeyStrokeType = LastKeyStrokeType.BACKSPACE; + return; + case SWT.ESC: + qInvocationSessionInstance.transitionToDecisionMade(); + qInvocationSessionInstance.end(); + return; + default: + } + + // If auto closing of brackets are not enabled we can just treat them as normal + // inputs + // Another scenario + if (!isAutoClosingEnabled) { + return; + } + + // If auto cloising of brackets are enabled, SWT will treat the open bracket + // differently. + // Input of the brackets will not trigger a call to verifyText. + // Thus we have to do the typeahead verification here. + // Note that '{' is excluded because + switch (event.character) { + case '<': + if (currentSuggestion.charAt(distanceTraversed++) != '<') { + qInvocationSessionInstance.transitionToDecisionMade(); + qInvocationSessionInstance.end(); + return; + } + lastKeyStrokeType = LastKeyStrokeType.NORMAL_BRACKET; + return; + case '>': + if (currentSuggestion.charAt(distanceTraversed++) != '>') { + qInvocationSessionInstance.transitionToDecisionMade(); + qInvocationSessionInstance.end(); + return; + } + lastKeyStrokeType = LastKeyStrokeType.NORMAL_BRACKET; + return; + case '(': + if (currentSuggestion.charAt(distanceTraversed++) != '(') { + qInvocationSessionInstance.transitionToDecisionMade(); + qInvocationSessionInstance.end(); + return; + } + lastKeyStrokeType = LastKeyStrokeType.NORMAL_BRACKET; + return; + case ')': + if (currentSuggestion.charAt(distanceTraversed++) != ')') { + qInvocationSessionInstance.transitionToDecisionMade(); + qInvocationSessionInstance.end(); + return; + } + lastKeyStrokeType = LastKeyStrokeType.NORMAL_BRACKET; + return; + case '[': + if (currentSuggestion.charAt(distanceTraversed++) != '[') { + qInvocationSessionInstance.transitionToDecisionMade(); + qInvocationSessionInstance.end(); + return; + } + lastKeyStrokeType = LastKeyStrokeType.NORMAL_BRACKET; + return; + case ']': + if (currentSuggestion.charAt(distanceTraversed++) != ']') { + qInvocationSessionInstance.transitionToDecisionMade(); + qInvocationSessionInstance.end(); + return; + } + lastKeyStrokeType = LastKeyStrokeType.NORMAL_BRACKET; + return; + case '{': + if (currentSuggestion.charAt(distanceTraversed++) != '{') { + qInvocationSessionInstance.transitionToDecisionMade(); + qInvocationSessionInstance.end(); + return; + } + lastKeyStrokeType = LastKeyStrokeType.OPEN_CURLY; + return; + case '}': + if (currentSuggestion.charAt(distanceTraversed++) != '}') { + qInvocationSessionInstance.transitionToDecisionMade(); + qInvocationSessionInstance.end(); + return; + } + lastKeyStrokeType = LastKeyStrokeType.CURLY_BRACES; + return; + case '"': + if (currentSuggestion.charAt(distanceTraversed++) != '"') { + qInvocationSessionInstance.transitionToDecisionMade(); + qInvocationSessionInstance.end(); + return; + } + lastKeyStrokeType = LastKeyStrokeType.NORMAL_BRACKET; + default: + } + + lastKeyStrokeType = LastKeyStrokeType.NORMAL_INPUT; + } + + @Override + public void verifyText(final VerifyEvent event) { + String input = event.text; + switch (lastKeyStrokeType) { + case NORMAL_INPUT: + break; + case OPEN_CURLY_FOLLOWED_BY_NEW_LINE: + input = '\n' + event.text.split("\\R")[1]; + break; + default: + return; + } + + var qInvocationSessionInstance = QInvocationSession.getInstance(); + if (qInvocationSessionInstance == null || !qInvocationSessionInstance.isPreviewingSuggestions()) { + return; + } + + String currentSuggestion = qInvocationSessionInstance.getCurrentSuggestion().getInsertText().trim(); + int currentOffset = widget.getCaretOffset(); + qInvocationSessionInstance + .setHasBeenTypedahead(currentOffset - qInvocationSessionInstance.getInvocationOffset() > 0); + + boolean isOutOfBounds = distanceTraversed >= currentSuggestion.length() || distanceTraversed < 0; + if (!isOutOfBounds) { + System.out.println("current char in suggestion: " + currentSuggestion.charAt(distanceTraversed)); + } + if (isOutOfBounds || !isInputAMatch(currentSuggestion, distanceTraversed, input)) { + qInvocationSessionInstance.transitionToDecisionMade(); + qInvocationSessionInstance.end(); + return; + } + distanceTraversed += input.length(); + } + + private boolean isInputAMatch(final String currentSuggestion, final int startIdx, final String input) { + boolean res; + if (input.length() > 1) { + res = currentSuggestion.substring(startIdx, startIdx + input.length()).equals(input); + System.out.println("This is a match: " + res); + } else { + res = String.valueOf(currentSuggestion.charAt(startIdx)).equals(input); + } + return res; + } +} diff --git a/plugin/src/software/aws/toolkits/eclipse/amazonq/util/QInlineVerifyKeyListener.java b/plugin/src/software/aws/toolkits/eclipse/amazonq/util/QInlineVerifyKeyListener.java deleted file mode 100644 index 461f3d31..00000000 --- a/plugin/src/software/aws/toolkits/eclipse/amazonq/util/QInlineVerifyKeyListener.java +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -package software.aws.toolkits.eclipse.amazonq.util; - -import java.util.Stack; - -import org.eclipse.core.runtime.preferences.IEclipsePreferences; -import org.eclipse.core.runtime.preferences.InstanceScope; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.custom.VerifyKeyListener; -import org.eclipse.swt.events.VerifyEvent; - -public final class QInlineVerifyKeyListener implements VerifyKeyListener { - private StyledText widget = null; - - public QInlineVerifyKeyListener(final StyledText widget) { - this.widget = widget; - } - - @Override - public void verifyKey(final VerifyEvent event) { - var qInvocationSessionInstance = QInvocationSession.getInstance(); - if (qInvocationSessionInstance == null || qInvocationSessionInstance.getState() != QInvocationSessionState.SUGGESTION_PREVIEWING) { - return; - } - // We need to provide the reason for the caret movement. This way we can perform - // subsequent actions accordingly: - // - If the caret has been moved due to traversals (i.e. arrow keys or mouse - // click) we would want to end the invocation session since that signifies the - // user no longer has the intent for text input at its original location. - // - And if the caret has been moved due to typing, we will need to determine if - // it's appropriate to perform a "typeahead". - // - // In effect, we would need to fulfill the following responsibilities. - // - We identify whether text is being entered and update a state that - // accessible by other listeners. - // - We shall also examine said text to see if it matches the beginning of the - // suggestion (if there is one) so we can fulfill "typeahead" functionality. - if (event.keyCode == SWT.ARROW_UP || event.keyCode == SWT.ARROW_DOWN || event.keyCode == SWT.ARROW_LEFT || event.keyCode == SWT.ARROW_RIGHT) { - System.out.println("Movement key registered"); - qInvocationSessionInstance.setCaretMovementReason(CaretMovementReason.MOVEMENT_KEY); - } else { - qInvocationSessionInstance.setCaretMovementReason(CaretMovementReason.TEXT_INPUT); - - // Here we conduct typeahead logic - String currentSuggestion = qInvocationSessionInstance.getCurrentSuggestion().getInsertText().trim(); - int currentOffset = widget.getCaretOffset(); - qInvocationSessionInstance - .setHasBeenTypedahead(currentOffset - qInvocationSessionInstance.getInvocationOffset() > 0); - IEclipsePreferences preferences = InstanceScope.INSTANCE.getNode("org.eclipse.jdt.ui"); - // This needs to be defaulted to true. This key is only present in the - // preference store if it is set to false. - // Therefore if you can't find it, it has been set to true. - boolean isAutoClosingEnabled = preferences.getBoolean("closeBrackets", true); - - // We are deliberately leaving out curly braces here (i.e. '{') because eclipse - // does not auto close curly braces unless there is a new line entered. - boolean isInputClosingBracket = (event.character == ')' || event.character == ']' || event.character == '"' || event.character == '>'); - boolean isInputOpeningBracket = (event.character == '(' || event.character == '[' || event.character == '"' || event.character == '<'); - Stack closingBrackets = qInvocationSessionInstance.getClosingBrackets(); - - if (isAutoClosingEnabled) { - if (closingBrackets == null) { - closingBrackets = new Stack<>(); - } - if (event.character == '(') { - closingBrackets.push(')'); - } else if (event.character == '[') { - closingBrackets.push(']'); - } else if (event.character == '"') { - closingBrackets.push('"'); - } else if (event.character == '<') { - closingBrackets.push('>'); - } else if (isInputClosingBracket) { - Character topClosingBracket = closingBrackets.pop(); - if (!topClosingBracket.equals(event.character)) { - System.out.println("Session terminated due to mismatching closing bracket"); - qInvocationSessionInstance.transitionToDecisionMade(); - qInvocationSessionInstance.end(); - } - } - } - - int distanceAdjustedForAutoClosingBrackets = (isAutoClosingEnabled && (isInputOpeningBracket || isInputClosingBracket)) ? 1 : 0; - // Note that distanceTraversed here is the zero-based index - // We need to subtract from leading whitespace skipped the indent the editor had - // placed the caret after at the new line. - int newLineOffset = 0; - boolean isLastKeyNewLine = qInvocationSessionInstance.isLastKeyNewLine(); - int leadingWhitespaceSkipped = qInvocationSessionInstance.getLeadingWhitespaceSkipped(); - int invocationOffset = qInvocationSessionInstance.getInvocationOffset(); - if (isLastKeyNewLine) { - int currentLineInEditor = widget.getLineAtOffset(currentOffset); - newLineOffset = currentOffset - widget.getOffsetAtLine(currentLineInEditor); - leadingWhitespaceSkipped -= newLineOffset; - qInvocationSessionInstance.setLeadingWhitespaceSkipped(leadingWhitespaceSkipped); - qInvocationSessionInstance.setIsLastKeyNewLine(false); - } - int distanceTraversed = currentOffset - invocationOffset + leadingWhitespaceSkipped - distanceAdjustedForAutoClosingBrackets; - - // If we are traversing backwards, we need to undo the adjustments we had done - // for the following items as we come across them: - // - whitespace - // - brackets (?) - if (event.keyCode == SWT.BS && distanceTraversed > 0 - && currentOffset - 1 <= qInvocationSessionInstance.getHeadOffsetAtLine(widget.getLineAtOffset(currentOffset)) - ) { - qInvocationSessionInstance.setLeadingWhitespaceSkipped(leadingWhitespaceSkipped - 1); - return; - } -// System.out.println("Distance traversed: " + distanceTraversed); -// System.out.println("Leading whitespace skipped: " + leadingWhitespaceSkipped); -// System.out.println("Distance adjusted for auto closing brackets: " + distanceAdjustedForAutoClosingBrackets); -// System.out.println("Character typed: " + event.character); -// System.out.println("Current caret offset: " + currentOffset); -// System.out.println("Is auto closing brackets enabled: " + isAutoClosingEnabled); - - // Terminate the session under the right conditions. These are: - // - If what has been typed does not match what has been suggested (we are going - // to assume the user does not want the suggestion) - // We are excluding modifier keys that do not produce text on the screen (e.g. - // shift, ctrl, option). - // - If the caret position has exceeded the invocation offset leftwards. - // - If the caret position has exceeded that of the end of the suggestion. - // - If the user has typehead to the end of the suggest (we would not just - // terminate the - if (event.character == '\0' || event.keyCode == SWT.ESC) { - // We have ESC mapped to reject command. We'll let the command take care of it. - return; - } - if (distanceTraversed >= currentSuggestion.length() || distanceTraversed < 0) { - qInvocationSessionInstance.transitionToDecisionMade(); - qInvocationSessionInstance.end(); - return; - } - - char currentCharInSuggestion = currentSuggestion.charAt(distanceTraversed); - if ((distanceTraversed <= 0 && event.keyCode == SWT.BS) || distanceTraversed > currentSuggestion.length() - || ((event.keyCode != SWT.BS && event.keyCode != SWT.CR) && currentCharInSuggestion != event.character) - || (event.keyCode == SWT.CR && (currentCharInSuggestion != '\n' && currentCharInSuggestion != '\r'))) { - qInvocationSessionInstance.transitionToDecisionMade(); - qInvocationSessionInstance.end(); - } - - if (event.keyCode == SWT.CR) { - qInvocationSessionInstance.setIsLastKeyNewLine(true); - } - - // We would also need to consider scenarios where the suggestion contains - // formatting whitespace. - // Should we come across them, we would need to do the following: - // - Examine if the last key registered was a CR, if it isn't we treat it as - // normal and examine the input verbatim - // - Otherwise, we shall skip ahead until the first non-whitespace character in - // the suggestion and increment `leadingWhitespaceSkipped` accordingly. - if (event.keyCode == SWT.CR && distanceTraversed < currentSuggestion.length() - 1 - && Character.isWhitespace(currentSuggestion.charAt(distanceTraversed + 1)) - && currentSuggestion.charAt(distanceTraversed + 1) != '\n' && currentSuggestion.charAt(distanceTraversed + 1) != '\r') { - int newWs = 0; - while (Character.isWhitespace(currentSuggestion.charAt(distanceTraversed + 1 + newWs))) { - newWs++; - if ((distanceTraversed + 1 + newWs) > currentSuggestion.length()) { - break; - } - } - leadingWhitespaceSkipped += newWs; - qInvocationSessionInstance.setLeadingWhitespaceSkipped(leadingWhitespaceSkipped); - } - } - } -} - diff --git a/plugin/src/software/aws/toolkits/eclipse/amazonq/util/QInvocationSession.java b/plugin/src/software/aws/toolkits/eclipse/amazonq/util/QInvocationSession.java index 3bf81d23..28f70741 100644 --- a/plugin/src/software/aws/toolkits/eclipse/amazonq/util/QInvocationSession.java +++ b/plugin/src/software/aws/toolkits/eclipse/amazonq/util/QInvocationSession.java @@ -8,7 +8,6 @@ import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CaretListener; import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.custom.VerifyKeyListener; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.widgets.Display; @@ -41,10 +40,8 @@ public final class QInvocationSession extends QResource { private long invocationTimeInMs = -1L; private QInlineRendererListener paintListener = null; private CaretListener caretListener = null; - private VerifyKeyListener verifyKeyListener = null; - private int leadingWhitespaceSkipped = 0; - private Stack closingBrackets = new Stack<>(); - private boolean isLastKeyNewLine = false; + private QInlineInputListener inputListener = null; + private Stack closingBrackets = new Stack<>(); private int[] headOffsetAtLine = new int[500]; private boolean hasBeenTypedahead = false; private CodeReferenceAcceptanceCallback codeReferenceAcceptanceCallback = null; @@ -95,8 +92,9 @@ public synchronized boolean start(final ITextEditor editor) { widget.addPaintListener(paintListener); } - verifyKeyListener = new QInlineVerifyKeyListener(widget); - widget.addVerifyKeyListener(verifyKeyListener); + inputListener = new QInlineInputListener(widget); + widget.addVerifyListener(inputListener); + widget.addVerifyKeyListener(inputListener); caretListener = new QInlineCaretListener(widget); widget.addCaretListener(caretListener); @@ -228,14 +226,6 @@ public void setCaretMovementReason(final CaretMovementReason reason) { this.caretMovementReason = reason; } - public void setLeadingWhitespaceSkipped(final int numSkipped) { - this.leadingWhitespaceSkipped = numSkipped; - } - - public void setIsLastKeyNewLine(final boolean isLastKeyNewLine) { - this.isLastKeyNewLine = isLastKeyNewLine; - } - public void setHeadOffsetAtLine(final int lineNum, final int offSet) throws IllegalArgumentException { if (lineNum >= headOffsetAtLine.length || lineNum < 0) { throw new IllegalArgumentException("Problematic index given"); @@ -267,18 +257,10 @@ public CaretMovementReason getCaretMovementReason() { return caretMovementReason; } - public Stack getClosingBrackets() { + public Stack getClosingBrackets() { return closingBrackets; } - public int getLeadingWhitespaceSkipped() { - return leadingWhitespaceSkipped; - } - - public boolean isLastKeyNewLine() { - return isLastKeyNewLine; - } - public int getHeadOffsetAtLine(final int lineNum) throws IllegalArgumentException { if (lineNum >= headOffsetAtLine.length || lineNum < 0) { throw new IllegalArgumentException("Problematic index given"); @@ -365,17 +347,16 @@ public void dispose() { inlineTextFont.dispose(); inlineTextFont = null; closingBrackets = null; - leadingWhitespaceSkipped = 0; - isLastKeyNewLine = false; caretMovementReason = CaretMovementReason.UNEXAMINED; hasBeenTypedahead = false; QInvocationSession.getInstance().getViewer().getTextWidget().redraw(); widget.removePaintListener(paintListener); widget.removeCaretListener(caretListener); - widget.removeVerifyKeyListener(verifyKeyListener); + widget.removeVerifyListener(inputListener); + widget.removeVerifyKeyListener(inputListener); paintListener = null; caretListener = null; - verifyKeyListener = null; + inputListener = null; invocationOffset = -1; invocationTimeInMs = -1L; editor = null;