-
-
Notifications
You must be signed in to change notification settings - Fork 836
Add TextCursor tool for precise caret-level text control #351
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
JezaChen
wants to merge
5
commits into
CursorTouch:main
Choose a base branch
from
JezaChen:feat/text-cursor-tool
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
64ee880
feat: Add TextCursor Tool
JezaChen bc81f15
refactor(text_cursor): split monolith into focused modules with a thi…
JezaChen 74a5b54
docs(text_cursor): document the TextCursor tool
JezaChen 9809277
fix(text_cursor): pass client context to analytics
JezaChen 100ec45
refactor(text_cursor): reuse windows_mcp.uia instead of a parallel CO…
JezaChen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| #!/usr/bin/env python3 | ||
| # -*- coding: utf-8 -*- | ||
| """ | ||
| Inspect and manipulate the caret/selection of the currently focused Windows | ||
| text control through UI Automation. | ||
|
|
||
| The caret/selection is discovered via IUIAutomationTextPattern.GetSelection() | ||
| on the focused element, walking up to its ancestors when needed. | ||
| IUIAutomationTextPattern2.GetCaretRange() is intentionally not used; see | ||
| discovery.try_get_caret_on_element for the rationale. | ||
|
|
||
| Supported modes: | ||
| - get_info | ||
| - move_relative | ||
| - move_absolute | ||
| - select_relative | ||
| - select_absolute | ||
| - select_all | ||
| - collapse_selection | ||
|
|
||
| Important: | ||
| - IUIAutomationTextRange.Move() only moves a client-side range. | ||
| - Select() asks the provider to apply that range as the real caret/selection. | ||
| - Write operations verify the applied range by reading it back. | ||
| - Some providers expose TextPattern but do not support moving the real caret. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from .errors import TextCursorError, TextCursorVerificationError | ||
| from .models import ( | ||
| CollapseSelectionAction, | ||
| CursorAction, | ||
| CursorSnapshot, | ||
| CursorToolResult, | ||
| GetInfoAction, | ||
| MoveAbsoluteAction, | ||
| MoveRelativeAction, | ||
| SelectAbsoluteAction, | ||
| SelectAllAction, | ||
| SelectRelativeAction, | ||
| ) | ||
| from .service import run_tool | ||
|
|
||
| __all__ = [ | ||
| "CollapseSelectionAction", | ||
| "CursorAction", | ||
| "CursorSnapshot", | ||
| "CursorToolResult", | ||
| "GetInfoAction", | ||
| "MoveAbsoluteAction", | ||
| "MoveRelativeAction", | ||
| "SelectAbsoluteAction", | ||
| "SelectAllAction", | ||
| "SelectRelativeAction", | ||
| "TextCursorError", | ||
| "TextCursorVerificationError", | ||
| "run_tool", | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| """Constants used by the text cursor implementation.""" | ||
|
|
||
| MAX_TEXT_UNIT_MOVE = 2_147_483_647 | ||
|
|
||
| # Upper bound on the selected-text string embedded in a snapshot. Unlike the | ||
| # surrounding context (capped by context_chars), the selection can be the whole | ||
| # document (e.g. after select_all), so cap it here to keep the MCP payload small. | ||
| MAX_SELECTED_TEXT_CHARS = 4096 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| """Locate the focused UIA control that exposes the caret/selection TextPattern. | ||
|
|
||
| Runs on the server's main-thread STA and reuses the shared `windows_mcp.uia` | ||
| client, so it can use `GetFocusedControl` and `Control` navigation directly. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from dataclasses import dataclass | ||
|
|
||
| from comtypes import COMError | ||
| from windows_mcp.uia import Control, GetFocusedControl, PatternId, TextPattern, TextRange | ||
|
|
||
|
|
||
| @dataclass | ||
| class UIACaretInfo: | ||
| """UIA provider and text range that describe the current caret or selection.""" | ||
|
|
||
| element: Control | ||
| text_pattern: TextPattern | ||
| text_range: TextRange | ||
| source: str | ||
| exact_caret: bool | ||
| selection_count: int = 1 | ||
|
|
||
|
|
||
| def try_get_caret_on_element(control: Control) -> UIACaretInfo | None: | ||
| # Use TextPattern.GetSelection rather than TextPattern2.GetCaretRange: | ||
| # GetCaretRange does not expose the actual selection range, so handling it | ||
| # separately is not worth the effort. The first selection is kept as-is: | ||
| # a degenerate range is treated as a caret (exact_caret=True), and a | ||
| # non-empty one as a range whose active caret endpoint is unknown. | ||
| text_pattern = control.GetPattern(PatternId.TextPattern) | ||
|
|
||
| if text_pattern is not None: | ||
| try: | ||
| selections = text_pattern.GetSelection() | ||
| except (COMError, AttributeError, TypeError, ValueError): | ||
| selections = [] | ||
|
|
||
| if selections: | ||
| selection = selections[0] | ||
| return UIACaretInfo( | ||
| element=control, | ||
| text_pattern=text_pattern, | ||
| text_range=selection, | ||
| source="TextPattern.GetSelection", | ||
| exact_caret=selection.IsDegenerate(), | ||
| selection_count=len(selections), | ||
| ) | ||
|
|
||
| return None | ||
|
|
||
|
|
||
| def find_caret_provider(max_parent_levels: int = 8) -> UIACaretInfo: | ||
| """ | ||
| Start at the focused UIA control and walk up RawView parents. | ||
| Some controls expose TextPattern on an ancestor rather than on the exact | ||
| focused child. | ||
| """ | ||
| control = GetFocusedControl() | ||
|
|
||
| if control is None: | ||
| raise RuntimeError("UI Automation returned no focused element.") | ||
|
|
||
| try: | ||
| element_name = control.Name | ||
| except COMError: | ||
| element_name = "" | ||
|
|
||
| tried_cnt = 0 | ||
| while control is not None and tried_cnt < max_parent_levels + 1: | ||
| tried_cnt += 1 | ||
| result = try_get_caret_on_element(control) | ||
|
|
||
| if result is not None: | ||
| return result | ||
|
|
||
| try: | ||
| control = control.GetParentControl() | ||
| except COMError: | ||
| control = None | ||
|
|
||
| raise RuntimeError( | ||
| f"The focused element {f'"{element_name}" ' if element_name else ''}and " | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 2. Single-quoted strings in discovery.py The new f-string in find_caret_provider() uses single-quoted string literals ('' and `f'"{...}"
'`) which violates the double-quote-only string literal style requirement. This creates inconsistent
string quoting style within the new TextCursor implementation.
Agent Prompt
|
||
| f"its inspected parents do not expose TextPattern." | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| """Errors raised by text cursor operations.""" | ||
|
|
||
|
|
||
| class TextCursorError(RuntimeError): | ||
| """Base error raised by TextCursor operations.""" | ||
|
|
||
|
|
||
| class TextCursorVerificationError(TextCursorError): | ||
| """Raised when a TextCursor write cannot be verified.""" |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
1. Overlong textcursor description line
📘 Rule violation✧ QualityAgent Prompt
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools