Skip to content

An AI Agent that interacts with Windows OS at GUI level.

Python

Apply ruff-format to entire codebase

jeomon8b644a0dbca8
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 991f247..148235d 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -22,7 +22,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- python-version: ["3.10", "3.11", "3.12", "3.13"]
+ python-version: ["3.12", "3.13"]
steps:
- uses: actions/checkout@v4
diff --git a/tests/test_agent_startup.py b/tests/test_agent_startup.py
index 0478d23..6f8a25c 100644
--- a/tests/test_agent_startup.py
+++ b/tests/test_agent_startup.py
@@ -4,6 +4,7 @@ import time
def log(msg):
print(f"[DEBUG] {time.time():.3f}: {msg}", flush=True)
+
log("Starting main.py debug...")
log("Importing load_dotenv...")
@@ -29,10 +30,12 @@ from windows_use.agent import Agent, Browser # noqa: E402
def main():
log("Inside main()...")
log("Initializing ChatGoogle...")
- llm=ChatGoogle(model="gemini-2.5-flash-lite",thinking_budget=0, temperature=0.7)
+ llm = ChatGoogle(model="gemini-2.5-flash-lite", thinking_budget=0, temperature=0.7)
log("Initializing Agent...")
- agent = Agent(llm=llm, browser=Browser.EDGE, use_vision=False,use_annotation=False, auto_minimize=False)
+ agent = Agent(
+ llm=llm, browser=Browser.EDGE, use_vision=False, use_annotation=False, auto_minimize=False
+ )
log("Agent initialized. Calling input()...")
# In a real run, this would be input()
@@ -47,5 +50,6 @@ def main():
agent.print_response(query=query)
log("Done.")
+
if __name__ == "__main__":
main()
diff --git a/tests/test_imports.py b/tests/test_imports.py
index 7552bbe..b68aac7 100644
--- a/tests/test_imports.py
+++ b/tests/test_imports.py
@@ -17,16 +17,20 @@ def check_import(module_name, from_list=None):
print(f"Failed: {e}")
return False
[email protected]("module, from_list", [
- ("dotenv", None),
- ("windows_use.providers.google", ["ChatGoogle"]),
- ("windows_use.providers.anthropic", ["ChatAnthropic"]),
- ("windows_use.providers.ollama", ["ChatOllama"]),
- ("windows_use.providers.mistral", ["ChatMistral"]),
- ("windows_use.providers.azure_openai", ["ChatAzureOpenAI"]),
- ("windows_use.providers.open_router", ["ChatOpenRouter"]),
- ("windows_use.providers.groq", ["ChatGroq"]),
- ("windows_use.agent", ["Agent", "Browser"]),
-])
+
+ "module, from_list",
+ [
+ ("dotenv", None),
+ ("windows_use.providers.google", ["ChatGoogle"]),
+ ("windows_use.providers.anthropic", ["ChatAnthropic"]),
+ ("windows_use.providers.ollama", ["ChatOllama"]),
+ ("windows_use.providers.mistral", ["ChatMistral"]),
+ ("windows_use.providers.azure_openai", ["ChatAzureOpenAI"]),
+ ("windows_use.providers.open_router", ["ChatOpenRouter"]),
+ ("windows_use.providers.groq", ["ChatGroq"]),
+ ("windows_use.agent", ["Agent", "Browser"]),
+ ],
+)
def test_all_imports(module, from_list):
assert check_import(module, from_list)
diff --git a/tests/test_uia_caching_integration.py b/tests/test_uia_caching_integration.py
index 5c2b0af..57d7768 100644
--- a/tests/test_uia_caching_integration.py
+++ b/tests/test_uia_caching_integration.py
@@ -13,12 +13,12 @@ from windows_use.agent.tree.service import Tree
# Configure logging to see cache performance stats
logging.basicConfig(
- level=logging.INFO,
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
+ level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
+
def test_caching_performance():
"""Test Tree.get_state with current API."""
@@ -55,6 +55,7 @@ def test_caching_performance():
logger.error(f"Error during tree test: {e}")
raise e
+
if __name__ == "__main__":
try:
test_caching_performance()
diff --git a/tests/test_uia_implementation.py b/tests/test_uia_implementation.py
index de1dd97..4943c00 100644
--- a/tests/test_uia_implementation.py
+++ b/tests/test_uia_implementation.py
@@ -27,7 +27,9 @@ def test_condition_creation():
assert false_cond is not None, "CreateFalseCondition failed"
# Test property condition
- prop_cond = core.CreatePropertyCondition(PropertyId.ControlTypeProperty, ControlType.WindowControl)
+ prop_cond = core.CreatePropertyCondition(
+ PropertyId.ControlTypeProperty, ControlType.WindowControl
+ )
assert prop_cond is not None, "CreatePropertyCondition failed"
# Test logical conditions
@@ -54,11 +56,14 @@ def test_find_methods():
try:
# Get root element (desktop) properly
from windows_use.uia.core import _AutomationClient
+
root_element = _AutomationClient.instance().IUIAutomation.GetRootElement()
root = Control.CreateControlFromElement(root_element)
# Test FindAll
- condition = core.CreatePropertyCondition(PropertyId.ControlTypeProperty, ControlType.WindowControl)
+ condition = core.CreatePropertyCondition(
+ PropertyId.ControlTypeProperty, ControlType.WindowControl
+ )
windows = root.FindAll(TreeScope.TreeScope_Children, condition)
assert isinstance(windows, list), "FindAll should return a list"
print(f" ✓ FindAll works - found {len(windows)} windows")
@@ -74,6 +79,7 @@ def test_find_methods():
except Exception as e:
print(f" ✗ Find methods failed: {e}")
import traceback
+
traceback.print_exc()
return False
@@ -85,6 +91,7 @@ def test_cache_methods():
try:
# Get root element (desktop) properly
from windows_use.uia.core import _AutomationClient
+
root_element = _AutomationClient.instance().IUIAutomation.GetRootElement()
root = Control.CreateControlFromElement(root_element)
@@ -94,13 +101,17 @@ def test_cache_methods():
cache_request.AddProperty(PropertyId.NameProperty)
# Test FindAllBuildCache
- condition = core.CreatePropertyCondition(PropertyId.ControlTypeProperty, ControlType.WindowControl)
+ condition = core.CreatePropertyCondition(
+ PropertyId.ControlTypeProperty, ControlType.WindowControl
+ )
windows = root.FindAllBuildCache(TreeScope.TreeScope_Children, condition, cache_request)
assert isinstance(windows, list), "FindAllBuildCache should return a list"
print(f" ✓ FindAllBuildCache works - found {len(windows)} windows")
# Test FindFirstBuildCache
- first_window = root.FindFirstBuildCache(TreeScope.TreeScope_Children, condition, cache_request)
+ first_window = root.FindFirstBuildCache(
+ TreeScope.TreeScope_Children, condition, cache_request
+ )
if first_window:
# Try to access cached property
cached_name = first_window.CachedName
@@ -126,6 +137,7 @@ def test_cache_methods():
except Exception as e:
print(f" ✗ Cache methods failed: {e}")
import traceback
+
traceback.print_exc()
return False
diff --git a/tests/test_uia_init.py b/tests/test_uia_init.py
index e606e8c..0a9ff16 100644
--- a/tests/test_uia_init.py
+++ b/tests/test_uia_init.py
@@ -13,7 +13,9 @@ except Exception as e:
print("Attempting to create IUIAutomation object...")
start = time.time()
try:
- IUIAutomation = comtypes.client.CreateObject("{ff48dba4-60ef-4201-aa87-54103eef594e}", interface=UIAutomationCore.IUIAutomation)
+ IUIAutomation = comtypes.client.CreateObject(
+ "{ff48dba4-60ef-4201-aa87-54103eef594e}", interface=UIAutomationCore.IUIAutomation
+ )
print(f"Success in {time.time() - start:.2f}s")
except Exception as e:
print(f"Failed: {e}")
diff --git a/tests/unit/agent/agent_prompt/test_agent_prompt_service.py b/tests/unit/agent/agent_prompt/test_agent_prompt_service.py
index 817e5ec..0f2d373 100644
--- a/tests/unit/agent/agent_prompt/test_agent_prompt_service.py
+++ b/tests/unit/agent/agent_prompt/test_agent_prompt_service.py
@@ -14,6 +14,7 @@ class TestContext:
@pytest.fixture
def context(self):
from unittest.mock import MagicMock
+
return Context(llm=MagicMock())
@pytest.fixture
@@ -74,7 +75,9 @@ class TestContext:
@patch("windows_use.agent.context.service._load_template")
@patch("windows_use.agent.context.service.uia.GetCursorPos", return_value=(100, 200))
- def test_human(self, mock_cursor_pos, mock_load_template, context, mock_desktop, mock_desktop_state):
+ def test_human(
+ self, mock_cursor_pos, mock_load_template, context, mock_desktop, mock_desktop_state
+ ):
mock_desktop_state.screenshot = None
mock_desktop.desktop_state = mock_desktop_state
mock_desktop.get_state.return_value = mock_desktop_state
diff --git a/tests/unit/agent/agent_tools/test_agent_tools_service.py b/tests/unit/agent/agent_tools/test_agent_tools_service.py
index 891ce2e..deae257 100644
--- a/tests/unit/agent/agent_tools/test_agent_tools_service.py
+++ b/tests/unit/agent/agent_tools/test_agent_tools_service.py
@@ -47,14 +47,19 @@ class TestAgentToolsService:
response = "Task done"
assert done_tool.invoke(**{"answer": response}) == response
- @pytest.mark.parametrize("mode, name, loc, size", [
- ("launch", "notepad", None, None),
- ("switch", "chrome", None, None),
- ("resize", None, [0, 0], [100, 100]),
- ])
+ @pytest.mark.parametrize(
+ "mode, name, loc, size",
+ [
+ ("launch", "notepad", None, None),
+ ("switch", "chrome", None, None),
+ ("resize", None, [0, 0], [100, 100]),
+ ],
+ )
def test_app_tool(self, mock_desktop, mode, name, loc, size):
"""Test app_tool delegation."""
- app_tool.invoke(**{"mode": mode, "name": name, "loc": loc, "size": size, "desktop": mock_desktop})
+ app_tool.invoke(
+ **{"mode": mode, "name": name, "loc": loc, "size": size, "desktop": mock_desktop}
+ )
mock_desktop.app.assert_called_once_with(mode, name, loc, size)
def test_shell_tool(self, mock_desktop):
@@ -67,24 +72,39 @@ class TestAgentToolsService:
def test_click_tool(self, mock_desktop):
"""Test click_tool delegation."""
- click_tool.invoke(**{"loc": [10, 20], "button": "right", "clicks": 2, "desktop": mock_desktop})
+ click_tool.invoke(
+ **{"loc": [10, 20], "button": "right", "clicks": 2, "desktop": mock_desktop}
+ )
mock_desktop.click.assert_called_once_with([10, 20], "right", 2)
def test_type_tool(self, mock_desktop):
"""Test type_tool delegation."""
- type_tool.invoke(**{"loc": [10, 20], "text": "hello", "clear": "true", "caret_position": "start", "press_enter": "true", "desktop": mock_desktop})
+ type_tool.invoke(
+ **{
+ "loc": [10, 20],
+ "text": "hello",
+ "clear": "true",
+ "caret_position": "start",
+ "press_enter": "true",
+ "desktop": mock_desktop,
+ }
+ )
mock_desktop.type.assert_called_once_with(
- loc=[10, 20],
- text="hello",
- caret_position="start",
- clear="true",
- press_enter="true"
+ loc=[10, 20], text="hello", caret_position="start", clear="true", press_enter="true"
)
def test_scroll_tool(self, mock_desktop):
"""Test scroll_tool delegation."""
mock_desktop.scroll.return_value = None
- scroll_tool.invoke(**{"loc": [10, 20], "type": "vertical", "direction": "up", "wheel_times": 3, "desktop": mock_desktop})
+ scroll_tool.invoke(
+ **{
+ "loc": [10, 20],
+ "type": "vertical",
+ "direction": "up",
+ "wheel_times": 3,
+ "desktop": mock_desktop,
+ }
+ )
mock_desktop.scroll.assert_called_once_with([10, 20], "vertical", "up", 3)
def test_move_tool_drag(self, mock_desktop):
@@ -105,7 +125,9 @@ class TestAgentToolsService:
def test_multi_select_tool(self, mock_desktop):
"""Test multi_select_tool delegation."""
elements = [[10, 10], [20, 20]]
- multi_select_tool.invoke(**{"elements": elements, "press_ctrl": "true", "desktop": mock_desktop})
+ multi_select_tool.invoke(
+ **{"elements": elements, "press_ctrl": "true", "desktop": mock_desktop}
+ )
mock_desktop.multi_select.assert_called_once_with("true", elements)
def test_multi_edit_tool(self, mock_desktop):
@@ -118,6 +140,7 @@ class TestAgentToolsService:
def test_wait_tool(self, mock_sleep, mock_desktop):
"""Test wait_tool calls asyncio.sleep."""
from unittest.mock import AsyncMock
+
mock_sleep.return_value = AsyncMock()()
wait_tool.invoke(**{"duration": 5, "desktop": mock_desktop})
mock_sleep.assert_called_once_with(5)
@@ -128,7 +151,7 @@ class TestAgentToolsService:
mock_node.text = "Visual Content"
mock_desktop.desktop_state.tree_state.dom_informative_nodes = [mock_node]
mock_dom_node = MagicMock()
- mock_dom_node.metadata = {'vertical_scroll_percent': 0}
+ mock_dom_node.metadata = {"vertical_scroll_percent": 0}
mock_desktop.desktop_state.tree_state.dom_node = mock_dom_node
result = scrape_tool.invoke(**{"url": "http://test", "desktop": mock_desktop})
@@ -139,7 +162,9 @@ class TestAgentToolsService:
def test_desktop_tool_create(self, mock_create, mock_desktop):
"""Test desktop_tool create."""
mock_create.return_value = "NewDesktop"
- result = desktop_tool.invoke(**{"action": "create", "desktop_name": "NewDesktop", "desktop": mock_desktop})
+ result = desktop_tool.invoke(
+ **{"action": "create", "desktop_name": "NewDesktop", "desktop": mock_desktop}
+ )
mock_create.assert_called_once_with("NewDesktop")
assert "Created desktop: 'NewDesktop'" in result
@@ -165,7 +190,9 @@ class TestAgentToolsService:
def test_file_tool_write_read(self, tmp_path):
"""Test file_tool write and read."""
test_file = tmp_path / "test.txt"
- write_result = file_tool.invoke(**{"mode": "write", "path": str(test_file), "content": "hello"})
+ write_result = file_tool.invoke(
+ **{"mode": "write", "path": str(test_file), "content": "hello"}
+ )
assert "Wrote" in write_result
read_result = file_tool.invoke(**{"mode": "read", "path": str(test_file)})
assert "hello" in read_result
diff --git a/tests/unit/agent/agent_tools/test_agent_tools_views.py b/tests/unit/agent/agent_tools/test_agent_tools_views.py
index a9eadb1..d008bcd 100644
--- a/tests/unit/agent/agent_tools/test_agent_tools_views.py
+++ b/tests/unit/agent/agent_tools/test_agent_tools_views.py
@@ -22,6 +22,7 @@ from windows_use.agent.tools.views import SharedBaseModel
THOUGHT = "test thought"
+
class TestAgentToolsViews:
"""
Tests for the Pydantic models in windows_use.agent.tools.views.
@@ -59,7 +60,14 @@ class TestAgentToolsViews:
assert mem.path == "test.md"
assert mem.content == "hello"
- mem_update = Memory(thought=THOUGHT, mode="update", path="test.md", operation="replace", old_str="a", new_str="b")
+ mem_update = Memory(
+ thought=THOUGHT,
+ mode="update",
+ path="test.md",
+ operation="replace",
+ old_str="a",
+ new_str="b",
+ )
assert mem_update.operation == "replace"
with pytest.raises(ValidationError):
@@ -108,14 +116,18 @@ class TestAgentToolsViews:
)
def test_type_model(self, loc, text, clear, caret_position, should_pass):
if should_pass:
- type_obj = Type(thought=THOUGHT, loc=loc, text=text, clear=clear, caret_position=caret_position)
+ type_obj = Type(
+ thought=THOUGHT, loc=loc, text=text, clear=clear, caret_position=caret_position
+ )
assert type_obj.loc == loc
assert type_obj.text == text
assert type_obj.clear == clear
assert type_obj.caret_position == caret_position
else:
with pytest.raises(ValidationError):
- Type(thought=THOUGHT, loc=loc, text=text, clear=clear, caret_position=caret_position)
+ Type(
+ thought=THOUGHT, loc=loc, text=text, clear=clear, caret_position=caret_position
+ )
@pytest.mark.parametrize(
"loc, type_val, direction, wheel_times, should_pass",
@@ -129,14 +141,26 @@ class TestAgentToolsViews:
)
def test_scroll_model(self, loc, type_val, direction, wheel_times, should_pass):
if should_pass:
- scroll = Scroll(thought=THOUGHT, loc=loc, type=type_val, direction=direction, wheel_times=wheel_times)
+ scroll = Scroll(
+ thought=THOUGHT,
+ loc=loc,
+ type=type_val,
+ direction=direction,
+ wheel_times=wheel_times,
+ )
assert scroll.loc == loc
assert scroll.type == type_val
assert scroll.direction == direction
assert scroll.wheel_times == wheel_times
else:
with pytest.raises(ValidationError):
- Scroll(thought=THOUGHT, loc=loc, type=type_val, direction=direction, wheel_times=wheel_times)
+ Scroll(
+ thought=THOUGHT,
+ loc=loc,
+ type=type_val,
+ direction=direction,
+ wheel_times=wheel_times,
+ )
@pytest.mark.parametrize(
"loc, drag, should_pass",
diff --git a/tests/unit/agent/test_agent_service.py b/tests/unit/agent/test_agent_service.py
index 5d3184e..2c433a2 100644
--- a/tests/unit/agent/test_agent_service.py
+++ b/tests/unit/agent/test_agent_service.py
@@ -33,8 +33,12 @@ class TestAgent:
mock_instance.use_accessibility = True
mock_instance.desktop_state.active_window_to_string.return_value = "Active: Notepad"
mock_instance.desktop_state.windows_to_string.return_value = "Windows: [Notepad]"
- mock_instance.desktop_state.tree_state.interactive_elements_to_string.return_value = "elements"
- mock_instance.desktop_state.tree_state.scrollable_elements_to_string.return_value = "scrollable"
+ mock_instance.desktop_state.tree_state.interactive_elements_to_string.return_value = (
+ "elements"
+ )
+ mock_instance.desktop_state.tree_state.scrollable_elements_to_string.return_value = (
+ "scrollable"
+ )
mock_instance.desktop_state.active_desktop_to_string.return_value = "Desktop 1"
mock_instance.desktop_state.desktops_to_string.return_value = "Desktops: [1]"
mock_instance.desktop_state.active_window.handle = 12345
@@ -54,7 +58,9 @@ class TestAgent:
@patch("windows_use.agent.service.Registry")
@patch("windows_use.agent.service.WatchDog")
- def test_invoke_done(self, mock_watchdog, mock_registry_class, mock_llm, mock_desktop, mock_console):
+ def test_invoke_done(
+ self, mock_watchdog, mock_registry_class, mock_llm, mock_desktop, mock_console
+ ):
mock_registry = mock_registry_class.return_value
mock_response = MagicMock()
@@ -64,7 +70,11 @@ class TestAgent:
mock_llm.invoke.return_value = LLMEvent(
type=LLMEventType.TOOL_CALL,
- tool_call=ToolCall(id="call_1", name="done_tool", params={"answer": "Job's done", "thought": "I have finished the task."}),
+ tool_call=ToolCall(
+ id="call_1",
+ name="done_tool",
+ params={"answer": "Job's done", "thought": "I have finished the task."},
+ ),
usage=TokenUsage(),
)
@@ -78,7 +88,9 @@ class TestAgent:
@patch("windows_use.agent.service.Registry")
@patch("windows_use.agent.service.WatchDog")
- def test_invoke_max_steps(self, mock_watchdog, mock_registry_class, mock_llm, mock_desktop, mock_console):
+ def test_invoke_max_steps(
+ self, mock_watchdog, mock_registry_class, mock_llm, mock_desktop, mock_console
+ ):
mock_registry = mock_registry_class.return_value
mock_response = MagicMock()
mock_response.content = "Step result"
@@ -87,7 +99,9 @@ class TestAgent:
mock_llm.invoke.return_value = LLMEvent(
type=LLMEventType.TOOL_CALL,
- tool_call=ToolCall(id="call_1", name="click_tool", params={"loc": [10, 10], "thought": "Keep working"}),
+ tool_call=ToolCall(
+ id="call_1", name="click_tool", params={"loc": [10, 10], "thought": "Keep working"}
+ ),
usage=TokenUsage(),
)
diff --git a/tests/unit/agent/test_agent_utils.py b/tests/unit/agent/test_agent_utils.py
index 4d2eb48..f434a5e 100644
--- a/tests/unit/agent/test_agent_utils.py
+++ b/tests/unit/agent/test_agent_utils.py
@@ -10,11 +10,14 @@ try:
from windows_use.agent.views import Action, AgentData # noqa: F401
from windows_use.messages import AIMessage
+
_UTILS_AVAILABLE = True
except ImportError:
_UTILS_AVAILABLE = False
-pytestmark = pytest.mark.skipif(not _UTILS_AVAILABLE, reason="agent.utils and AgentData/Action not in current codebase")
+pytestmark = pytest.mark.skipif(
+ not _UTILS_AVAILABLE, reason="agent.utils and AgentData/Action not in current codebase"
+)
import json # noqa: E402
from unittest.mock import MagicMock, patch # noqa: E402
@@ -40,7 +43,7 @@ class TestAgentUtils:
"""Test json_parser with valid JSON."""
data = {
"thought": "I will click here.",
- "action": {"name": "click_tool", "params": {"loc": [100, 200]}}
+ "action": {"name": "click_tool", "params": {"loc": [100, 200]}},
}
message = AIMessage(content=json.dumps(data))
agent_data = json_parser(message)
@@ -53,7 +56,7 @@ class TestAgentUtils:
"""Test json_parser with markdown-wrapped JSON."""
data = {
"thought": "Thinking...",
- "action": {"name": "done_tool", "params": {"answer": "Done"}}
+ "action": {"name": "done_tool", "params": {"answer": "Done"}},
}
content = f"Here is the JSON:\n```json\n{json.dumps(data)}\n```"
message = AIMessage(content=content)
diff --git a/tests/unit/desktop/test_desktop_init.py b/tests/unit/desktop/test_desktop_init.py
index 03c71c4..22025b5 100644
--- a/tests/unit/desktop/test_desktop_init.py
+++ b/tests/unit/desktop/test_desktop_init.py
@@ -13,8 +13,13 @@ class TestDesktopService:
@pytest.fixture
def desktop(self):
# Patching dependencies in __init__
- with patch("windows_use.agent.desktop.service.uia.GetVirtualScreenSize", return_value=(1920, 1080)), \
- patch("windows_use.agent.desktop.service.Tree"):
+ with (
+ patch(
+ "windows_use.agent.desktop.service.uia.GetVirtualScreenSize",
+ return_value=(1920, 1080),
+ ),
+ patch("windows_use.agent.desktop.service.Tree"),
+ ):
return Desktop()
def test_init(self, desktop):
@@ -31,6 +36,7 @@ class TestDesktopService:
def side_effect(callback, lparam):
callback(12345, lparam)
return True
+
mock_enum.side_effect = side_effect
handles = desktop.get_controls_handles()
@@ -39,18 +45,30 @@ class TestDesktopService:
def test_get_state(self, desktop):
# Mock dependencies of get_state
mock_window = Window(
- name="Notepad", is_browser=False, depth=0, status=Status.NORMAL,
- bounding_box=BoundingBox(0,0,100,100,100,100), handle=123, process_id=456
+ name="Notepad",
+ is_browser=False,
+ depth=0,
+ status=Status.NORMAL,
+ bounding_box=BoundingBox(0, 0, 100, 100, 100, 100),
+ handle=123,
+ process_id=456,
)
- with patch.object(desktop, 'get_controls_handles', return_value={123, 456}), \
- patch.object(desktop, 'get_windows', return_value=([mock_window], {123})), \
- patch.object(desktop, 'get_active_window', return_value=mock_window), \
- patch.object(desktop.tree, 'get_state', return_value=MagicMock()), \
- patch("windows_use.agent.desktop.service.get_current_desktop", return_value={"name": "Desktop 1"}), \
- patch("windows_use.agent.desktop.service.get_all_desktops", return_value=[{"name": "Desktop 1"}]):
-
- state = desktop.get_state()
+ with (
+ patch.object(desktop, "get_controls_handles", return_value={123, 456}),
+ patch.object(desktop, "get_windows", return_value=([mock_window], {123})),
+ patch.object(desktop, "get_active_window", return_value=mock_window),
+ patch.object(desktop.tree, "get_state", return_value=MagicMock()),
+ patch(
+ "windows_use.agent.desktop.service.get_current_desktop",
+ return_value={"name": "Desktop 1"},
+ ),
+ patch(
+ "windows_use.agent.desktop.service.get_all_desktops",
+ return_value=[{"name": "Desktop 1"}],
+ ),
+ ):
+ state = desktop.get_state()
assert isinstance(state, DesktopState)
assert state.active_window.handle == 123
diff --git a/tests/unit/desktop/test_desktop_views.py b/tests/unit/desktop/test_desktop_views.py
index 963dec5..d64431b 100644
--- a/tests/unit/desktop/test_desktop_views.py
+++ b/tests/unit/desktop/test_desktop_views.py
@@ -15,9 +15,10 @@ def sample_window():
status=Status.NORMAL,
bounding_box=BoundingBox(0, 0, 100, 100, 100, 100),
handle=123,
- process_id=456
+ process_id=456,
)
+
class TestDesktopViews:
def test_window_to_row(self, sample_window):
row = sample_window.to_row()
@@ -32,7 +33,7 @@ class TestDesktopViews:
active_desktop={"name": "Desktop 1"},
all_desktops=[{"name": "Desktop 1"}, {"name": "Desktop 2"}],
windows=[sample_window],
- active_window=sample_window
+ active_window=sample_window,
)
assert "Desktop 1" in state.active_desktop_to_string()
diff --git a/tests/unit/test_llm_events.py b/tests/unit/test_llm_events.py
index 5726848..a588c95 100644
--- a/tests/unit/test_llm_events.py
+++ b/tests/unit/test_llm_events.py
@@ -30,13 +30,14 @@ def create_mock_chunk(content=None, tool_calls=None, reasoning=None):
chunk.usage = None
return chunk
+
def test_stream_text_only():
provider = ChatOpenAI(model="gpt-4o")
mock_chunks = [
create_mock_chunk(content="Hello"),
create_mock_chunk(content=" world"),
- create_mock_chunk(content="!")
+ create_mock_chunk(content="!"),
]
provider.client.chat.completions.create = MagicMock(return_value=mock_chunks)
@@ -50,13 +51,16 @@ def test_stream_text_only():
assert events[3] == LLMStreamEvent(type=LLMStreamEventType.TEXT_DELTA, content="!")
assert events[4] == LLMStreamEvent(type=LLMStreamEventType.TEXT_END)
+
def test_stream_tool_only():
provider = ChatOpenAI(model="gpt-4o")
mock_chunks = [
- create_mock_chunk(tool_calls=[{"id": "call_123", "name": "my_tool", "arguments": '{"arg"'} ]),
- create_mock_chunk(tool_calls=[{"id": None, "name": None, "arguments": ':"val"'} ]),
- create_mock_chunk(tool_calls=[{"id": None, "name": None, "arguments": '}'} ])
+ create_mock_chunk(
+ tool_calls=[{"id": "call_123", "name": "my_tool", "arguments": '{"arg"'}]
+ ),
+ create_mock_chunk(tool_calls=[{"id": None, "name": None, "arguments": ':"val"'}]),
+ create_mock_chunk(tool_calls=[{"id": None, "name": None, "arguments": "}"}]),
]
provider.client.chat.completions.create = MagicMock(return_value=mock_chunks)
@@ -70,6 +74,7 @@ def test_stream_tool_only():
assert events[0].tool_call.name == "my_tool"
assert events[0].tool_call.params == {"arg": "val"}
+
def test_stream_thinking_then_text():
provider = ChatOpenAI(model="o3-mini")
diff --git a/tests/unit/test_openai_events.py b/tests/unit/test_openai_events.py
index 2e07715..3fd704c 100644
--- a/tests/unit/test_openai_events.py
+++ b/tests/unit/test_openai_events.py
@@ -12,11 +12,9 @@ from windows_use.tools import Tool
class DummyToolModel(BaseModel):
dummy: str
-dummy_tool = Tool(
- name="dummy_tool",
- description="A dummy tool for testing",
- model=DummyToolModel
-)
+
+dummy_tool = Tool(name="dummy_tool", description="A dummy tool for testing", model=DummyToolModel)
+
@pytest.mark.asyncio
async def test_streaming_text():
@@ -25,6 +23,7 @@ async def test_streaming_text():
# MOCK OPENAI STREAM
from unittest.mock import MagicMock
+
class MockDelta:
def __init__(self, content=None, reasoning_content=None, tool_calls=None):
self.content = content
@@ -55,7 +54,9 @@ async def test_streaming_text():
messages = [HumanMessage(content="Explain what a computer is in 2 short sentences.")]
for chunk in llm.stream(messages=messages):
- assert isinstance(chunk, LLMStreamEvent), f"Expected LLMStreamEvent, got {type(chunk).__name__}"
+ assert isinstance(chunk, LLMStreamEvent), (
+ f"Expected LLMStreamEvent, got {type(chunk).__name__}"
+ )
print(f"[EVENT] {chunk.type.value}: {chunk.content}")
events_received.append(chunk.type)
@@ -72,6 +73,7 @@ async def test_streaming_tools():
# MOCK OPENAI STREAM
from unittest.mock import MagicMock
+
class MockToolFunction:
def __init__(self, name=None, arguments=None):
self.name = name
@@ -97,7 +99,9 @@ async def test_streaming_tools():
self.usage = usage
def mock_stream(*args, **kwargs):
- t1 = MockToolCall(id="call_abc", function=MockToolFunction(name="dummy_tool", arguments='{"dum'))
+ t1 = MockToolCall(
+ id="call_abc", function=MockToolFunction(name="dummy_tool", arguments='{"dum')
+ )
t2 = MockToolCall(function=MockToolFunction(arguments='my": "hello"}'))
yield MockChunk([MockChoice(MockDelta(tool_calls=[t1]))])
yield MockChunk([MockChoice(MockDelta(tool_calls=[t2]))])
@@ -111,7 +115,9 @@ async def test_streaming_tools():
messages = [HumanMessage(content="Call the dummy tool with the argument 'hello'.")]
for chunk in llm.stream(messages=messages, tools=[dummy_tool]):
- assert isinstance(chunk, LLMStreamEvent), f"Expected LLMStreamEvent, got {type(chunk).__name__}"
+ assert isinstance(chunk, LLMStreamEvent), (
+ f"Expected LLMStreamEvent, got {type(chunk).__name__}"
+ )
print(f"[EVENT] {chunk.type.value}: {chunk.tool_call}")
events_received.append(chunk.type)
@@ -126,6 +132,7 @@ async def test_invoke_text():
# MOCK OPENAI INVOKE
from unittest.mock import MagicMock
+
class MockMessage:
def __init__(self, content=None, tool_calls=None):
self.content = content
@@ -141,7 +148,10 @@ async def test_invoke_text():
self.usage = usage
def mock_create(*args, **kwargs):
- return MockResponse([MockChoice(MockMessage(content="Invoke Hello!"))], usage=MagicMock(prompt_tokens=10, completion_tokens=5, total_tokens=15))
+ return MockResponse(
+ [MockChoice(MockMessage(content="Invoke Hello!"))],
+ usage=MagicMock(prompt_tokens=10, completion_tokens=5, total_tokens=15),
+ )
llm.client.chat.completions.create = mock_create
llm._is_reasoning_model = lambda: False
@@ -149,12 +159,15 @@ async def test_invoke_text():
messages = [HumanMessage(content="Say Hello via invoke")]
result = llm.invoke(messages=messages)
- assert isinstance(result, LLMEvent), f"Expected LLMEvent from invoke, got {type(result).__name__}"
+ assert isinstance(result, LLMEvent), (
+ f"Expected LLMEvent from invoke, got {type(result).__name__}"
+ )
assert result.type == LLMEventType.TEXT
assert result.content == "Invoke Hello!"
print(f"[INVOKE EVENT] {result.type.value}: {result.content}")
print("SUCCESS: Invoke text generated TEXT_END LLMEvent.")
+
@pytest.mark.asyncio
async def test_ainvoke_tools():
print("\n=== Testing Ainvoke Tools ===")
@@ -162,6 +175,7 @@ async def test_ainvoke_tools():
# MOCK OPENAI AINVOKE
from unittest.mock import MagicMock
+
class MockToolFunction:
def __init__(self, name=None, arguments=None):
self.name = name
@@ -187,8 +201,14 @@ async def test_ainvoke_tools():
self.usage = usage
async def mock_acreate(*args, **kwargs):
- t1 = MockToolCall(id="call_123", function=MockToolFunction(name="dummy_tool", arguments='{"dummy": "world"}'))
- return MockResponse([MockChoice(MockMessage(tool_calls=[t1]))], usage=MagicMock(prompt_tokens=10, completion_tokens=5, total_tokens=15))
+ t1 = MockToolCall(
+ id="call_123",
+ function=MockToolFunction(name="dummy_tool", arguments='{"dummy": "world"}'),
+ )
+ return MockResponse(
+ [MockChoice(MockMessage(tool_calls=[t1]))],
+ usage=MagicMock(prompt_tokens=10, completion_tokens=5, total_tokens=15),
+ )
llm.aclient.chat.completions.create = mock_acreate
llm._is_reasoning_model = lambda: False
@@ -196,18 +216,22 @@ async def test_ainvoke_tools():
messages = [HumanMessage(content="Call the dummy tool with 'world'")]
result = await llm.ainvoke(messages=messages, tools=[dummy_tool])
- assert isinstance(result, LLMEvent), f"Expected LLMEvent from ainvoke, got {type(result).__name__}"
+ assert isinstance(result, LLMEvent), (
+ f"Expected LLMEvent from ainvoke, got {type(result).__name__}"
+ )
assert result.type == LLMEventType.TOOL_CALL
assert result.tool_call.name == "dummy_tool"
assert result.tool_call.params.get("dummy") == "world"
print(f"[AINVOKE EVENT] {result.type.value}: {result.tool_call.name} {result.tool_call.params}")
print("SUCCESS: Ainvoke tools generated TOOL_CALL_END LLMEvent.")
+
async def main():
await test_streaming_text()
await test_streaming_tools()
await test_invoke_text()
await test_ainvoke_tools()
+
if __name__ == "__main__":
asyncio.run(main())
diff --git a/tests/unit/tree/test_tree_config.py b/tests/unit/tree/test_tree_config.py
index a0af152..99bef6d 100644
--- a/tests/unit/tree/test_tree_config.py
+++ b/tests/unit/tree/test_tree_config.py
@@ -13,18 +13,40 @@ class TestTreeConfig:
def test_interactive_control_type_names_content(self):
expected_names = {
- 'ButtonControl', 'ListItemControl', 'MenuItemControl', 'EditControl',
- 'CheckBoxControl', 'RadioButtonControl', 'DocumentControl', 'ComboBoxControl',
- 'HyperlinkControl', 'SplitButtonControl', 'TabItemControl',
- 'TreeItemControl', 'DataItemControl', 'HeaderItemControl',
- 'TextBoxControl', 'SpinnerControl', 'ScrollBarControl', 'SliderControl'
+ "ButtonControl",
+ "ListItemControl",
+ "MenuItemControl",
+ "EditControl",
+ "CheckBoxControl",
+ "RadioButtonControl",
+ "DocumentControl",
+ "ComboBoxControl",
+ "HyperlinkControl",
+ "SplitButtonControl",
+ "TabItemControl",
+ "TreeItemControl",
+ "DataItemControl",
+ "HeaderItemControl",
+ "TextBoxControl",
+ "SpinnerControl",
+ "ScrollBarControl",
+ "SliderControl",
}
assert INTERACTIVE_CONTROL_TYPE_NAMES == expected_names
def test_default_actions_content(self):
- expected_actions = {'Click', 'Press', 'Jump', 'Check', 'Uncheck', 'Double Click', 'Expand', 'Collapse'}
+ expected_actions = {
+ "Click",
+ "Press",
+ "Jump",
+ "Check",
+ "Uncheck",
+ "Double Click",
+ "Expand",
+ "Collapse",
+ }
assert DEFAULT_ACTIONS == expected_actions
def test_informative_control_type_names_content(self):
- expected_names = {'TextControl', 'ImageControl', 'StatusBarControl'}
+ expected_names = {"TextControl", "ImageControl", "StatusBarControl"}
assert INFORMATIVE_CONTROL_TYPE_NAMES == expected_names
diff --git a/tests/unit/tree/test_tree_init.py b/tests/unit/tree/test_tree_init.py
index f08fd1e..95b2cf5 100644
--- a/tests/unit/tree/test_tree_init.py
+++ b/tests/unit/tree/test_tree_init.py
@@ -31,16 +31,18 @@ class TestTreeService:
mock_node = MagicMock()
mock_from_handle.return_value = mock_node
- with patch.object(tree, 'tree_traversal') as mock_traversal:
+ with patch.object(tree, "tree_traversal") as mock_traversal:
tree.get_nodes(handle=123)
mock_from_handle.assert_called_once_with(123)
assert mock_traversal.called
@patch("windows_use.agent.tree.service.sleep")
def test_get_state(self, mock_sleep, tree):
- with patch.object(tree, 'get_window_wise_nodes') as mock_window_wise:
+ with patch.object(tree, "get_window_wise_nodes") as mock_window_wise:
mock_window_wise.return_value = ([], [], [], [])
state = tree.get_state(active_window_handle=1, other_windows_handles=[2])
assert isinstance(state, TreeState)
- mock_window_wise.assert_called_once_with(windows_handles=[1, 2], active_window_flag=True)
+ mock_window_wise.assert_called_once_with(
+ windows_handles=[1, 2], active_window_flag=True
+ )
diff --git a/tests/unit/tree/test_tree_views.py b/tests/unit/tree/test_tree_views.py
index 2a3ac70..77b46da 100644
--- a/tests/unit/tree/test_tree_views.py
+++ b/tests/unit/tree/test_tree_views.py
@@ -15,10 +15,12 @@ from windows_use.agent.tree.views import (
def sample_center():
return Center(x=100, y=200)
+
@pytest.fixture
def sample_bbox():
return BoundingBox(left=50, top=150, right=150, bottom=250, width=100, height=100)
+
@pytest.fixture
def sample_interactive_node(sample_bbox, sample_center):
return TreeElementNode(
@@ -26,9 +28,10 @@ def sample_interactive_node(sample_bbox, sample_center):
control_type="Button",
window_name="App",
bounding_box=sample_bbox,
- center=sample_center
+ center=sample_center,
)
+
@pytest.fixture
def sample_scrollable_node(sample_bbox, sample_center):
return ScrollElementNode(
@@ -36,9 +39,10 @@ def sample_scrollable_node(sample_bbox, sample_center):
control_type="Pane",
window_name="App",
bounding_box=sample_bbox,
- center=sample_center
+ center=sample_center,
)
+
class TestTreeViews:
def test_center(self, sample_center):
assert sample_center.to_string() == "(100,200)"
@@ -56,8 +60,7 @@ class TestTreeViews:
def test_tree_state_scrollable_string(self, sample_interactive_node, sample_scrollable_node):
state = TreeState(
- interactive_nodes=[sample_interactive_node],
- scrollable_nodes=[sample_scrollable_node]
+ interactive_nodes=[sample_interactive_node], scrollable_nodes=[sample_scrollable_node]
)
s = state.scrollable_elements_to_string()
# id should be 1 since there is 1 interactive node
@@ -66,8 +69,7 @@ class TestTreeViews:
def test_selector_map(self, sample_interactive_node, sample_scrollable_node):
state = TreeState(
- interactive_nodes=[sample_interactive_node],
- scrollable_nodes=[sample_scrollable_node]
+ interactive_nodes=[sample_interactive_node], scrollable_nodes=[sample_scrollable_node]
)
selector = state.build_selector_map()
assert selector.node_of(0) is sample_interactive_node
diff --git a/windows_use/agent/context/service.py b/windows_use/agent/context/service.py
index 7febc5e..bba0f2c 100644
--- a/windows_use/agent/context/service.py
+++ b/windows_use/agent/context/service.py
@@ -33,11 +33,12 @@ def _load_template(filename: str) -> str:
class Context:
- def __init__(self,llm: BaseChatLLM):
- self.token_usage:TokenUsage=TokenUsage()
+ def __init__(self, llm: BaseChatLLM):
+ self.token_usage: TokenUsage = TokenUsage()
self.llm = llm
- def _build_system_prompt(self,
+ def _build_system_prompt(
+ self,
mode: Literal["flash", "normal"],
desktop: Desktop,
browser: Browser,
@@ -49,12 +50,14 @@ class Context:
case "flash":
template = _load_template("system_flash.md")
os_version = desktop.get_windows_version()
- return template.format(**{
- "max_steps": max_steps,
- "datetime": datetime.now().strftime("%A, %B %d, %Y"),
- "os": os_version,
- "browser": browser.value,
- })
+ return template.format(
+ **{
+ "max_steps": max_steps,
+ "datetime": datetime.now().strftime("%A, %B %d, %Y"),
+ "os": os_version,
+ "browser": browser.value,
+ }
+ )
case "normal":
template = _load_template("system.md")
with ThreadPoolExecutor(max_workers=3) as executor:
@@ -64,66 +67,72 @@ class Context:
os_version = os_future.result()
language = lang_future.result()
user_account_type = user_future.result()
- return template.format(**{
- "datetime": datetime.now().strftime("%A, %B %d, %Y"),
- "instructions": "\n".join(instructions),
- "download_directory": Path.home().joinpath("Downloads").as_posix(),
- "os": os_version,
- "language": language,
- "browser": browser.value,
- "home_dir": Path.home().as_posix(),
- "user": f"{getuser()} ({user_account_type})",
- "resolution": f"Primary Monitor ({width}x{height}) with DPI Scale: {desktop.get_dpi_scaling()}",
- "max_steps": max_steps,
- })
+ return template.format(
+ **{
+ "datetime": datetime.now().strftime("%A, %B %d, %Y"),
+ "instructions": "\n".join(instructions),
+ "download_directory": Path.home().joinpath("Downloads").as_posix(),
+ "os": os_version,
+ "language": language,
+ "browser": browser.value,
+ "home_dir": Path.home().as_posix(),
+ "user": f"{getuser()} ({user_account_type})",
+ "resolution": f"Primary Monitor ({width}x{height}) with DPI Scale: {desktop.get_dpi_scaling()}",
+ "max_steps": max_steps,
+ }
+ )
case _:
raise ValueError(f"Invalid mode: {mode} (must be 'flash' or 'normal')")
- def _format_history_for_compaction(self,messages: list[BaseMessage]) -> str:
- lines=['Following is the conversation that needs to be compacted:']
+ def _format_history_for_compaction(self, messages: list[BaseMessage]) -> str:
+ lines = ["Following is the conversation that needs to be compacted:"]
for message in messages:
- content=message.content[:2000]+'...[TRUNCATED]' if len(message.content)>2000 else message.content
- if isinstance(message,SystemMessage):
+ content = (
+ message.content[:2000] + "...[TRUNCATED]"
+ if len(message.content) > 2000
+ else message.content
+ )
+ if isinstance(message, SystemMessage):
pass
- elif isinstance(message,(HumanMessage)):
- lines.append(f'USER: {content}')
- elif isinstance(message,AIMessage):
- lines.append(f'ASSISTANT: {content}')
- elif isinstance(message,ToolMessage):
- id=message.id
- name=message.name
- params=message.params
- if 'thought' in params:
- lines.append(f'THOUGHT: {params["thought"]}')
+ elif isinstance(message, (HumanMessage)):
+ lines.append(f"USER: {content}")
+ elif isinstance(message, AIMessage):
+ lines.append(f"ASSISTANT: {content}")
+ elif isinstance(message, ToolMessage):
+ id = message.id
+ name = message.name
+ params = message.params
+ if "thought" in params:
+ lines.append(f"THOUGHT: {params['thought']}")
parts = ", ".join(
f"{k}={v[:2000] + '...[TRUNCATED]' if len(v) > 2000 else v}"
for k, v in params.items()
if k not in _NON_TOOL_PARAMS
)
lines.append(f"TOOL CALL {id}: {name}({parts})")
- lines.append(f'TOOL RESULT {id}: {content}')
+ lines.append(f"TOOL RESULT {id}: {content}")
else:
pass
- return '\n\n---\n\n'.join(lines)
+ return "\n\n---\n\n".join(lines)
@property
- def need_compaction(self)->bool:
- metadata=self.llm.get_metadata()
- context_window=metadata.context_window
- total_tokens=self.token_usage.total_tokens
- return total_tokens>context_window*0.8
+ def need_compaction(self) -> bool:
+ metadata = self.llm.get_metadata()
+ context_window = metadata.context_window
+ total_tokens = self.token_usage.total_tokens
+ return total_tokens > context_window * 0.8
def compact(
self,
messages: list[BaseMessage],
- ) -> str|None:
- template=_load_template("compact.md")
- compaction_messages=[
+ ) -> str | None:
+ template = _load_template("compact.md")
+ compaction_messages = [
SystemMessage(content=template),
- HumanMessage(content=self._format_history_for_compaction(messages))
+ HumanMessage(content=self._format_history_for_compaction(messages)),
]
- llm_response=self.llm.invoke(compaction_messages)
- return f'''
+ llm_response = self.llm.invoke(compaction_messages)
+ return f"""
# Context Restoration (Previous Session Compacted)
The previous conversation was compacted due to context window limitations. Below is the detailed summary of work done so far.
@@ -137,7 +146,7 @@ The previous conversation was compacted due to context window limitations. Below
---
Continue work from where the previous session left off. FOCUS only on the remaining tasks.
-'''
+"""
def system(
self,
@@ -183,30 +192,32 @@ Continue work from where the previous session left off. FOCUS only on the remain
cursor_x, cursor_y = uia.GetCursorPos()
template = _load_template("state.md")
loop_warning = f"[Loop Warning]\n{nudge}\n[End of Loop Warning]\n" if nudge else ""
- return template.format(**{
- "steps": step,
- "max_steps": max_steps,
- "loop_warning": loop_warning,
- "active_window": desktop_state.active_window_to_string(),
- "windows": desktop_state.windows_to_string(),
- "cursor_location": f"({cursor_x},{cursor_y})",
- "interactive_elements": (
- desktop_state.tree_state.interactive_elements_to_string()
- if desktop.use_accessibility
- else "No accessibility data is available"
- ),
- "scrollable_elements": (
- desktop_state.tree_state.scrollable_elements_to_string()
- if desktop.use_accessibility
- else "No accessibility data is available"
- ),
- "active_desktop": desktop_state.active_desktop_to_string(),
- "desktops": desktop_state.desktops_to_string(),
- "query": query,
- })
+ return template.format(
+ **{
+ "steps": step,
+ "max_steps": max_steps,
+ "loop_warning": loop_warning,
+ "active_window": desktop_state.active_window_to_string(),
+ "windows": desktop_state.windows_to_string(),
+ "cursor_location": f"({cursor_x},{cursor_y})",
+ "interactive_elements": (
+ desktop_state.tree_state.interactive_elements_to_string()
+ if desktop.use_accessibility
+ else "No accessibility data is available"
+ ),
+ "scrollable_elements": (
+ desktop_state.tree_state.scrollable_elements_to_string()
+ if desktop.use_accessibility
+ else "No accessibility data is available"
+ ),
+ "active_desktop": desktop_state.active_desktop_to_string(),
+ "desktops": desktop_state.desktops_to_string(),
+ "query": query,
+ }
+ )
def task(self, task: str) -> HumanMessage:
return HumanMessage(content=f"TASK: {task}")
- def update_token_usage(self,token_usage:TokenUsage):
- self.token_usage=token_usage
+ def update_token_usage(self, token_usage: TokenUsage):
+ self.token_usage = token_usage
diff --git a/windows_use/agent/desktop/config.py b/windows_use/agent/desktop/config.py
index 079aecf..65f9648 100644
--- a/windows_use/agent/desktop/config.py
+++ b/windows_use/agent/desktop/config.py
@@ -1,4 +1,3 @@
-
# Key name aliases for shortcut keys that differ from UIA SpecialKeyNames
KEY_ALIASES: dict[str, str] = {
"backspace": "Back",
@@ -9,14 +8,14 @@ KEY_ALIASES: dict[str, str] = {
"option": "Alt",
}
-AVOIDED_APPS: set[str] = set([
- 'AgentUI'
-])
+AVOIDED_APPS: set[str] = set(["AgentUI"])
-EXCLUDED_APPS:set[str]=set([
- 'Progman',
- 'Shell_TrayWnd',
- 'Shell_SecondaryTrayWnd',
- 'Microsoft.UI.Content.PopupWindowSiteBridge',
- 'Windows.UI.Core.CoreWindow',
-])
+EXCLUDED_APPS: set[str] = set(
+ [
+ "Progman",
+ "Shell_TrayWnd",
+ "Shell_SecondaryTrayWnd",
+ "Microsoft.UI.Content.PopupWindowSiteBridge",
+ "Windows.UI.Core.CoreWindow",
+ ]
+)
diff --git a/windows_use/agent/desktop/service.py b/windows_use/agent/desktop/service.py
index 34bd857..de0613b 100644
--- a/windows_use/agent/desktop/service.py
+++ b/windows_use/agent/desktop/service.py
@@ -31,13 +31,16 @@ from windows_use.vdm.core import get_all_desktops, get_current_desktop, is_windo
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
+
class Desktop:
- def __init__(self,use_vision:bool=False,use_annotation:bool=False,use_accessibility:bool=True):
- self.use_vision=use_vision
- self.use_annotation=use_annotation
- self.use_accessibility=use_accessibility
- self.tree=Tree(self)
- self.desktop_state=None
+ def __init__(
+ self, use_vision: bool = False, use_annotation: bool = False, use_accessibility: bool = True
+ ):
+ self.use_vision = use_vision
+ self.use_annotation = use_annotation
+ self.use_accessibility = use_accessibility
+ self.tree = Tree(self)
+ self.desktop_state = None
# Cached system info (does not change during session)
self._cached_windows_version: str | None = None
@@ -65,19 +68,22 @@ class Desktop:
executor.submit(self.get_user_account_type)
executor.submit(_warm_uia)
- def get_state(self,as_bytes:bool=False)->DesktopState:
+ def get_state(self, as_bytes: bool = False) -> DesktopState:
start_time = perf_counter()
- controls_handles=self.get_controls_handles() # Taskbar,Program Manager,Apps, Dialogs
- windows,windows_handles=self.get_windows(controls_handles=controls_handles) # Apps
- active_window=self.get_active_window(windows=windows) #Active Window
- active_window_handle=active_window.handle if active_window else None
+ controls_handles = self.get_controls_handles() # Taskbar,Program Manager,Apps, Dialogs
+ windows, windows_handles = self.get_windows(controls_handles=controls_handles) # Apps
+ active_window = self.get_active_window(windows=windows) # Active Window
+ active_window_handle = active_window.handle if active_window else None
try:
- active_desktop=get_current_desktop()
- all_desktops=get_all_desktops()
+ active_desktop = get_current_desktop()
+ all_desktops = get_all_desktops()
except RuntimeError:
- active_desktop = {'id': '00000000-0000-0000-0000-000000000000', 'name': 'Default Desktop'}
+ active_desktop = {
+ "id": "00000000-0000-0000-0000-000000000000",
+ "name": "Default Desktop",
+ }
all_desktops = [active_desktop]
if active_window is not None and active_window in windows:
@@ -86,40 +92,40 @@ class Desktop:
logger.debug(f"Active window: {active_window or 'No Active Window Found'}")
logger.debug(f"Windows: {windows}")
- #Preparing handles for Tree
- other_windows_handles=list(controls_handles-windows_handles)
+ # Preparing handles for Tree
+ other_windows_handles = list(controls_handles - windows_handles)
if self.use_accessibility:
- tree_state=self.tree.get_state(active_window_handle,other_windows_handles)
+ tree_state = self.tree.get_state(active_window_handle, other_windows_handles)
else:
- tree_state=TreeState()
+ tree_state = TreeState()
if self.use_vision:
if self.use_annotation:
- nodes=tree_state.interactive_nodes if tree_state else []
+ nodes = tree_state.interactive_nodes if tree_state else []
if nodes:
- screenshot=self.get_annotated_screenshot(nodes=nodes,as_bytes=as_bytes)
+ screenshot = self.get_annotated_screenshot(nodes=nodes, as_bytes=as_bytes)
else:
- screenshot=self.get_screenshot(as_bytes=as_bytes)
+ screenshot = self.get_screenshot(as_bytes=as_bytes)
else:
- screenshot=self.get_screenshot(as_bytes=as_bytes)
+ screenshot = self.get_screenshot(as_bytes=as_bytes)
else:
- screenshot=None
+ screenshot = None
- self.desktop_state=DesktopState(
+ self.desktop_state = DesktopState(
active_window=active_window,
windows=windows,
active_desktop=active_desktop,
all_desktops=all_desktops,
screenshot=screenshot,
- tree_state=tree_state
+ tree_state=tree_state,
)
end_time = perf_counter()
logger.debug(f"[Desktop] Desktop State capture took {end_time - start_time:.2f} seconds")
return self.desktop_state
- def get_window_status(self,control:uia.Control)->Status:
+ def get_window_status(self, control: uia.Control) -> Status:
if uia.IsIconic(control.NativeWindowHandle):
return Status.MINIMIZED
elif uia.IsZoomed(control.NativeWindowHandle):
@@ -129,14 +135,14 @@ class Desktop:
else:
return Status.HIDDEN
- def get_cursor_location(self)->tuple[int,int]:
+ def get_cursor_location(self) -> tuple[int, int]:
return uia.GetCursorPos()
- def get_element_under_cursor(self)->uia.Control:
+ def get_element_under_cursor(self) -> uia.Control:
return uia.ControlFromCursor()
- def get_apps_from_start_menu(self)->dict[str,str]:
- command='Get-StartApps | ConvertTo-Csv -NoTypeInformation'
+ def get_apps_from_start_menu(self) -> dict[str, str]:
+ command = "Get-StartApps | ConvertTo-Csv -NoTypeInformation"
apps_info, status = self.execute_command(command)
if status != 0 or not apps_info:
@@ -146,62 +152,68 @@ class Desktop:
try:
reader = csv.DictReader(io.StringIO(apps_info.strip()))
return {
- row.get('Name').lower(): row.get('AppID')
+ row.get("Name").lower(): row.get("AppID")
for row in reader
- if row.get('Name') and row.get('AppID')
+ if row.get("Name") and row.get("AppID")
}
except Exception as e:
logger.error(f"Error parsing start menu apps: {e}")
return {}
- def execute_command(self, command: str,timeout:int=10) -> tuple[str, int]:
+ def execute_command(self, command: str, timeout: int = 10) -> tuple[str, int]:
try:
- utf8_command = '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ' + command
+ utf8_command = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; " + command
encoded = base64.b64encode(utf8_command.encode("utf-16le")).decode("ascii")
result = subprocess.run(
- ['powershell', '-NoProfile', '-EncodedCommand', encoded],
+ ["powershell", "-NoProfile", "-EncodedCommand", encoded],
capture_output=True,
timeout=timeout,
- cwd=os.path.expanduser(path='~')
+ cwd=os.path.expanduser(path="~"),
)
- stdout = result.stdout.decode('utf-8', errors='replace') if result.stdout else ''
- stderr = result.stderr.decode('utf-8', errors='replace') if result.stderr else ''
+ stdout = result.stdout.decode("utf-8", errors="replace") if result.stdout else ""
+ stderr = result.stderr.decode("utf-8", errors="replace") if result.stderr else ""
return (stdout or stderr, result.returncode)
except subprocess.TimeoutExpired:
- return ('Command execution timed out', 1)
+ return ("Command execution timed out", 1)
except Exception as e:
- return (f'Command execution failed: {type(e).__name__}: {e}', 1)
+ return (f"Command execution failed: {type(e).__name__}: {e}", 1)
- def is_window_browser(self,node:uia.Control):
- '''Give any node of the app and it will return True if the app is a browser, False otherwise.'''
- process=Process(node.ProcessId)
+ def is_window_browser(self, node: uia.Control):
+ """Give any node of the app and it will return True if the app is a browser, False otherwise."""
+ process = Process(node.ProcessId)
return Browser.has_process(process.name())
- def get_default_language(self)->str:
+ def get_default_language(self) -> str:
if self._cached_default_language is not None:
return self._cached_default_language
- command="Get-Culture | Select-Object Name,DisplayName | ConvertTo-Csv -NoTypeInformation"
- response,_=self.execute_command(command)
- reader=csv.DictReader(io.StringIO(response))
- result = "".join([row.get('DisplayName') for row in reader])
+ command = "Get-Culture | Select-Object Name,DisplayName | ConvertTo-Csv -NoTypeInformation"
+ response, _ = self.execute_command(command)
+ reader = csv.DictReader(io.StringIO(response))
+ result = "".join([row.get("DisplayName") for row in reader])
self._cached_default_language = result
return result
- def _find_window_by_name(self, name: str) -> tuple['Window | None', str]:
+ def _find_window_by_name(self, name: str) -> tuple["Window | None", str]:
"""Find a window by fuzzy name match. Returns (window, error_msg).
If the returned window is None, error_msg describes the failure reason.
"""
- window_list = [w for w in [self.desktop_state.active_window] + self.desktop_state.windows if w is not None]
+ window_list = [
+ w
+ for w in [self.desktop_state.active_window] + self.desktop_state.windows
+ if w is not None
+ ]
if not window_list:
- return None, 'No windows found on the desktop.'
+ return None, "No windows found on the desktop."
windows = {window.name: window for window in window_list}
matched = process.extractOne(name, list(windows.keys()), score_cutoff=70)
if matched is None:
- return None, f'Application {name.title()} not found.'
+ return None, f"Application {name.title()} not found."
window_name, _ = matched
- return windows.get(window_name), ''
+ return windows.get(window_name), ""
- def resize_app(self, name: str | None = None, size: tuple[int, int] = None, loc: tuple[int, int] = None) -> tuple[str, int]:
+ def resize_app(
+ self, name: str | None = None, size: tuple[int, int] = None, loc: tuple[int, int] = None
+ ) -> tuple[str, int]:
if name is not None:
target_app, error = self._find_window_by_name(name)
if target_app is None:
@@ -209,12 +221,12 @@ class Desktop:
else:
target_app = self.desktop_state.active_window
if target_app is None:
- return 'No active app found', 1
+ return "No active app found", 1
if target_app.status == Status.MINIMIZED:
- return f'{target_app.name} is minimized', 1
+ return f"{target_app.name} is minimized", 1
elif target_app.status == Status.MAXIMIZED:
- return f'{target_app.name} is maximized', 1
+ return f"{target_app.name} is maximized", 1
else:
app_control = uia.ControlFromHandle(target_app.handle)
if loc is None:
@@ -228,18 +240,24 @@ class Desktop:
x, y = loc
width, height = size
app_control.MoveWindow(x, y, width, height)
- return (f'{target_app.name} resized to {width}x{height} at {x},{y}.', 0)
+ return (f"{target_app.name} resized to {width}x{height} at {x},{y}.", 0)
- def is_app_running(self,name:str)->bool:
+ def is_app_running(self, name: str) -> bool:
apps, _ = self.get_windows()
apps_dict = {app.name: app for app in apps}
- return process.extractOne(name,list(apps_dict.keys()),score_cutoff=60) is not None
-
- def app(self,mode:Literal['launch','switch','resize'],name:str | None=None,loc:tuple[int, int] | None=None,size:tuple[int, int] | None=None):
+ return process.extractOne(name, list(apps_dict.keys()), score_cutoff=60) is not None
+
+ def app(
+ self,
+ mode: Literal["launch", "switch", "resize"],
+ name: str | None = None,
+ loc: tuple[int, int] | None = None,
+ size: tuple[int, int] | None = None,
+ ):
match mode:
- case 'launch':
- response,status,pid=self.launch_app(name)
- if status!=0:
+ case "launch":
+ response, status, pid = self.launch_app(name)
+ if status != 0:
return response
# Smart wait using UIA Exists (avoids manual Python loops)
@@ -252,7 +270,9 @@ class Desktop:
if not launched:
# Fallback: Regex search for the window title
safe_name = re.escape(name)
- if uia.WindowControl(RegexName=f'(?i).*{safe_name}.*').Exists(maxSearchSeconds=10):
+ if uia.WindowControl(RegexName=f"(?i).*{safe_name}.*").Exists(
+ maxSearchSeconds=10
+ ):
launched = True
except Exception as e:
logger.warning(f"Error verifying app launch (likely transient COM error): {e}")
@@ -261,30 +281,30 @@ class Desktop:
launched = True
if launched:
- return f'{name.title()} launched.'
- return f'Launching {name.title()} sent, but window not detected yet.'
- case 'resize':
- response,status=self.resize_app(name=name,size=size,loc=loc)
- if status!=0:
+ return f"{name.title()} launched."
+ return f"Launching {name.title()} sent, but window not detected yet."
+ case "resize":
+ response, status = self.resize_app(name=name, size=size, loc=loc)
+ if status != 0:
return response
else:
return response
- case 'switch':
- response,status=self.switch_app(name)
- if status!=0:
+ case "switch":
+ response, status = self.switch_app(name)
+ if status != 0:
return response
else:
return response
- def launch_app(self,name:str)->tuple[str,int,int]:
- apps_map=self.get_apps_from_start_menu()
- matched_app=process.extractOne(name,apps_map.keys(),score_cutoff=70)
+ def launch_app(self, name: str) -> tuple[str, int, int]:
+ apps_map = self.get_apps_from_start_menu()
+ matched_app = process.extractOne(name, apps_map.keys(), score_cutoff=70)
if matched_app is None:
- return (f'{name.title()} not found in start menu.',1,0)
- app_name,_=matched_app
- appid=apps_map.get(app_name)
+ return (f"{name.title()} not found in start menu.", 1, 0)
+ app_name, _ = matched_app
+ appid = apps_map.get(app_name)
if appid is None:
- return (name,f'{name.title()} not found in start menu.',1,0)
+ return (name, f"{name.title()} not found in start menu.", 1, 0)
pid = 0
if os.path.exists(appid) or "\\" in appid:
@@ -309,9 +329,9 @@ class Desktop:
was_minimized = uia.IsIconic(target_handle)
self.bring_window_to_top(target_handle)
if was_minimized:
- content = f'{app.name.title()} restored from minimized and switched to it.'
+ content = f"{app.name.title()} restored from minimized and switched to it."
else:
- content = f'Switched to {app.name.title()} window.'
+ content = f"Switched to {app.name.title()} window."
return content, 0
def bring_window_to_top(self, target_handle: int):
@@ -344,8 +364,11 @@ class Desktop:
win32gui.SetWindowPos(
target_handle,
win32con.HWND_TOP,
- 0, 0, 0, 0,
- win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | win32con.SWP_SHOWWINDOW
+ 0,
+ 0,
+ 0,
+ 0,
+ win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | win32con.SWP_SHOWWINDOW,
)
finally:
@@ -355,75 +378,88 @@ class Desktop:
except Exception as e:
logger.exception(f"Failed to bring window to top: {e}")
- def get_element_handle_from_label(self,label:int)->uia.Control:
- tree_state=self.desktop_state.tree_state
- selector=tree_state.build_selector_map()
- element_node=selector.node_of(label)
+ def get_element_handle_from_label(self, label: int) -> uia.Control:
+ tree_state = self.desktop_state.tree_state
+ selector = tree_state.build_selector_map()
+ element_node = selector.node_of(label)
if element_node is None:
- raise ValueError(f'No element found for label {label}')
- control=selector.control_of(label)
+ raise ValueError(f"No element found for label {label}")
+ control = selector.control_of(label)
if control is not None:
return control
if element_node.hwnd:
return uia.ControlFromHandle(element_node.hwnd)
- raise ValueError(f'No live control available for label {label}')
+ raise ValueError(f"No live control available for label {label}")
- def get_coordinates_from_label(self,label:int)->tuple[int,int]:
- element_handle=self.get_element_handle_from_label(label)
- bounding_rectangle=element_handle.BoundingRectangle
- return bounding_rectangle.xcenter(),bounding_rectangle.ycenter()
+ def get_coordinates_from_label(self, label: int) -> tuple[int, int]:
+ element_handle = self.get_element_handle_from_label(label)
+ bounding_rectangle = element_handle.BoundingRectangle
+ return bounding_rectangle.xcenter(), bounding_rectangle.ycenter()
- def click(self,loc:tuple[int,int],button:str='left',clicks:int=2):
- x,y=loc
+ def click(self, loc: tuple[int, int], button: str = "left", clicks: int = 2):
+ x, y = loc
if clicks == 0:
uia.SetCursorPos(x, y)
return
match button:
- case 'left':
+ case "left":
if clicks >= 2:
uia.DoubleClick(x, y)
else:
uia.Click(x, y)
- case 'right':
+ case "right":
for _ in range(clicks):
uia.RightClick(x, y)
- case 'middle':
+ case "middle":
for _ in range(clicks):
uia.MiddleClick(x, y)
- def type(self,loc:tuple[int,int],text:str,caret_position:Literal['start','end','none']='none',clear:Literal['true','false']='false',press_enter:Literal['true','false']='false'):
- x,y=loc
+ def type(
+ self,
+ loc: tuple[int, int],
+ text: str,
+ caret_position: Literal["start", "end", "none"] = "none",
+ clear: Literal["true", "false"] = "false",
+ press_enter: Literal["true", "false"] = "false",
+ ):
+ x, y = loc
uia.Click(x, y)
- if caret_position == 'start':
- uia.SendKeys('{Home}', waitTime=0.05)
- elif caret_position == 'end':
- uia.SendKeys('{End}', waitTime=0.05)
- if clear=='true':
+ if caret_position == "start":
+ uia.SendKeys("{Home}", waitTime=0.05)
+ elif caret_position == "end":
+ uia.SendKeys("{End}", waitTime=0.05)
+ if clear == "true":
sleep(0.5)
- uia.SendKeys('{Ctrl}a', waitTime=0.05)
- uia.SendKeys('{Back}', waitTime=0.05)
+ uia.SendKeys("{Ctrl}a", waitTime=0.05)
+ uia.SendKeys("{Back}", waitTime=0.05)
escaped_text = escape_text_for_sendkeys(text)
uia.SendKeys(escaped_text, interval=0.01, waitTime=0.05)
- if press_enter=='true':
- uia.SendKeys('{Enter}', waitTime=0.05)
-
- def scroll(self,loc:tuple[int,int]=None,type:Literal['horizontal','vertical']='vertical',direction:Literal['up','down','left','right']='down',wheel_times:int=1)->str|None:
+ if press_enter == "true":
+ uia.SendKeys("{Enter}", waitTime=0.05)
+
+ def scroll(
+ self,
+ loc: tuple[int, int] = None,
+ type: Literal["horizontal", "vertical"] = "vertical",
+ direction: Literal["up", "down", "left", "right"] = "down",
+ wheel_times: int = 1,
+ ) -> str | None:
if loc:
self.move(loc)
match type:
- case 'vertical':
+ case "vertical":
match direction:
- case 'up':
+ case "up":
uia.WheelUp(wheel_times)
- case 'down':
+ case "down":
uia.WheelDown(wheel_times)
case _:
return 'Invalid direction. Use "up" or "down".'
- case 'horizontal':
+ case "horizontal":
match direction:
- case 'left':
+ case "left":
uia.WheelLeft(wheel_times)
- case 'right':
+ case "right":
uia.WheelRight(wheel_times)
case _:
return 'Invalid direction. Use "left" or "right".'
@@ -431,18 +467,18 @@ class Desktop:
return 'Invalid type. Use "horizontal" or "vertical".'
return None
- def drag(self,loc:tuple[int,int]):
- x,y=loc
+ def drag(self, loc: tuple[int, int]):
+ x, y = loc
cx, cy = uia.GetCursorPos()
uia.DragTo(cx, cy, x, y)
- def move(self,loc:tuple[int,int]):
- x,y=loc
+ def move(self, loc: tuple[int, int]):
+ x, y = loc
uia.MoveTo(x, y, moveSpeed=10)
- def shortcut(self,shortcut:str):
- keys = shortcut.split('+')
- sendkeys_str = ''
+ def shortcut(self, shortcut: str):
+ keys = shortcut.split("+")
+ sendkeys_str = ""
for key in keys:
key = key.strip()
if len(key) == 1:
@@ -451,93 +487,100 @@ class Desktop:
else:
# Named key - resolve alias then wrap in braces for SendKeys
name = KEY_ALIASES.get(key.lower(), key)
- sendkeys_str += '{' + name + '}'
+ sendkeys_str += "{" + name + "}"
uia.SendKeys(sendkeys_str, interval=0.01)
- def multi_select(self,press_ctrl:Literal['true','false']='false',elements:list[tuple[int,int]|int]=[]):
- if press_ctrl=='true':
+ def multi_select(
+ self,
+ press_ctrl: Literal["true", "false"] = "false",
+ elements: list[tuple[int, int] | int] = [],
+ ):
+ if press_ctrl == "true":
uia.PressKey(uia.Keys.VK_CONTROL, waitTime=0.05)
for element in elements:
- x,y=element
+ x, y = element
uia.Click(x, y, waitTime=0.2)
sleep(0.5)
uia.ReleaseKey(uia.Keys.VK_CONTROL, waitTime=0.05)
- def multi_edit(self,elements:list[tuple[int,int,str]|tuple[int,str]]):
+ def multi_edit(self, elements: list[tuple[int, int, str] | tuple[int, str]]):
for element in elements:
- x,y,text=element
- self.type((x,y),text=text,clear='true')
+ x, y, text = element
+ self.type((x, y), text=text, clear="true")
- def scrape(self,url:str)->str:
- response=requests.get(url,timeout=10)
- html=response.text
- content=markdownify(html=html)
+ def scrape(self, url: str) -> str:
+ response = requests.get(url, timeout=10)
+ html = response.text
+ content = markdownify(html=html)
return content
- def is_window_visible(self,window:uia.Control)->bool:
- is_minimized=self.get_window_status(window)!=Status.MINIMIZED
- size=window.BoundingRectangle
- area=size.width()*size.height()
- is_overlay=self.is_overlay_window(window)
- return not is_overlay and is_minimized and area>10
+ def is_window_visible(self, window: uia.Control) -> bool:
+ is_minimized = self.get_window_status(window) != Status.MINIMIZED
+ size = window.BoundingRectangle
+ area = size.width() * size.height()
+ is_overlay = self.is_overlay_window(window)
+ return not is_overlay and is_minimized and area > 10
- def is_overlay_window(self,element:uia.Control) -> bool:
+ def is_overlay_window(self, element: uia.Control) -> bool:
no_children = element.GetFirstChildControl() is None
is_name = "Overlay" in element.Name.strip()
return no_children or is_name
- def get_controls_handles(self,optimized:bool=False):
+ def get_controls_handles(self, optimized: bool = False):
handles = set()
+
def callback(hwnd, _):
if win32gui.IsWindowVisible(hwnd) and is_window_on_current_desktop(hwnd):
handles.add(hwnd)
win32gui.EnumWindows(callback, None)
- if desktop_hwnd:= win32gui.FindWindow('Progman',None):
+ if desktop_hwnd := win32gui.FindWindow("Progman", None):
handles.add(desktop_hwnd)
- if taskbar_hwnd:= win32gui.FindWindow('Shell_TrayWnd',None):
+ if taskbar_hwnd := win32gui.FindWindow("Shell_TrayWnd", None):
handles.add(taskbar_hwnd)
- if secondary_taskbar_hwnd:= win32gui.FindWindow('Shell_SecondaryTrayWnd',None):
+ if secondary_taskbar_hwnd := win32gui.FindWindow("Shell_SecondaryTrayWnd", None):
handles.add(secondary_taskbar_hwnd)
return handles
- def get_active_window(self,windows:list[Window]|None=None)->Window|None:
+ def get_active_window(self, windows: list[Window] | None = None) -> Window | None:
try:
if windows is None:
- windows,_=self.get_windows()
- active_window=self.get_foreground_window()
- if active_window.ClassName=="Progman":
+ windows, _ = self.get_windows()
+ active_window = self.get_foreground_window()
+ if active_window.ClassName == "Progman":
return None
- active_window_handle=active_window.NativeWindowHandle
+ active_window_handle = active_window.NativeWindowHandle
for window in windows:
- if window.handle!=active_window_handle:
+ if window.handle != active_window_handle:
continue
return window
# In case active window is not present in the windows list
- return Window(**{
- "name":active_window.Name,
- "is_browser":self.is_window_browser(active_window),
- "depth":0,
- "bounding_box":BoundingBox(
- left=active_window.BoundingRectangle.left,
- top=active_window.BoundingRectangle.top,
- right=active_window.BoundingRectangle.right,
- bottom=active_window.BoundingRectangle.bottom,
- width=active_window.BoundingRectangle.width(),
- height=active_window.BoundingRectangle.height()
- ),
- "status":self.get_window_status(active_window),
- "handle":active_window_handle,
- "process_id":active_window.ProcessId,
- })
+ return Window(
+ **{
+ "name": active_window.Name,
+ "is_browser": self.is_window_browser(active_window),
+ "depth": 0,
+ "bounding_box": BoundingBox(
+ left=active_window.BoundingRectangle.left,
+ top=active_window.BoundingRectangle.top,
+ right=active_window.BoundingRectangle.right,
+ bottom=active_window.BoundingRectangle.bottom,
+ width=active_window.BoundingRectangle.width(),
+ height=active_window.BoundingRectangle.height(),
+ ),
+ "status": self.get_window_status(active_window),
+ "handle": active_window_handle,
+ "process_id": active_window.ProcessId,
+ }
+ )
except Exception as ex:
logger.error(f"Error in get_active_window: {ex}")
return None
- def get_foreground_window(self)->uia.Control:
- handle=uia.GetForegroundWindow()
- active_window=self.get_window_from_element_handle(handle)
+ def get_foreground_window(self) -> uia.Control:
+ handle = uia.GetForegroundWindow()
+ active_window = self.get_window_from_element_handle(handle)
return active_window
def get_window_from_element_handle(self, element_handle: int) -> uia.Control:
@@ -550,11 +593,13 @@ class Desktop:
return current
current = parent
- def get_windows(self,controls_handles:set[int]|None=None) -> tuple[list[Window],set[int]]:
+ def get_windows(
+ self, controls_handles: set[int] | None = None
+ ) -> tuple[list[Window], set[int]]:
try:
windows = []
window_handles = set()
- controls_handles=controls_handles or self.get_controls_handles()
+ controls_handles = controls_handles or self.get_controls_handles()
for depth, hwnd in enumerate(controls_handles):
try:
child = uia.ControlFromHandle(hwnd)
@@ -565,53 +610,65 @@ class Desktop:
if self.is_overlay_window(child):
continue
- if isinstance(child,(uia.WindowControl,uia.PaneControl)):
- window_pattern=child.GetPattern(uia.PatternId.WindowPattern)
- if (window_pattern is None):
+ if isinstance(child, (uia.WindowControl, uia.PaneControl)):
+ window_pattern = child.GetPattern(uia.PatternId.WindowPattern)
+ if window_pattern is None:
continue
if window_pattern.CanMinimize and window_pattern.CanMaximize:
status = self.get_window_status(child)
- bounding_rect=child.BoundingRectangle
- if bounding_rect.isempty() and status!=Status.MINIMIZED:
+ bounding_rect = child.BoundingRectangle
+ if bounding_rect.isempty() and status != Status.MINIMIZED:
continue
- windows.append(Window(**{
- "name":child.Name,
- "depth":depth,
- "status":status,
- "bounding_box":BoundingBox(
- left=bounding_rect.left,
- top=bounding_rect.top,
- right=bounding_rect.right,
- bottom=bounding_rect.bottom,
- width=bounding_rect.width(),
- height=bounding_rect.height()
- ),
- "handle":child.NativeWindowHandle,
- "process_id":child.ProcessId,
- "is_browser":self.is_window_browser(child)
- }))
+ windows.append(
+ Window(
+ **{
+ "name": child.Name,
+ "depth": depth,
+ "status": status,
+ "bounding_box": BoundingBox(
+ left=bounding_rect.left,
+ top=bounding_rect.top,
+ right=bounding_rect.right,
+ bottom=bounding_rect.bottom,
+ width=bounding_rect.width(),
+ height=bounding_rect.height(),
+ ),
+ "handle": child.NativeWindowHandle,
+ "process_id": child.ProcessId,
+ "is_browser": self.is_window_browser(child),
+ }
+ )
+ )
window_handles.add(child.NativeWindowHandle)
except Exception as ex:
logger.error(f"Error in get_windows: {ex}")
windows = []
- return windows,window_handles
+ return windows, window_handles
- def get_windows_version(self)->str:
+ def get_windows_version(self) -> str:
if self._cached_windows_version is not None:
return self._cached_windows_version
- response,status=self.execute_command("(Get-CimInstance Win32_OperatingSystem).Caption")
+ response, status = self.execute_command("(Get-CimInstance Win32_OperatingSystem).Caption")
result = response.strip() if status == 0 else "Windows"
self._cached_windows_version = result
return result
- def get_user_account_type(self)->str:
+ def get_user_account_type(self) -> str:
if self._cached_user_account_type is not None:
return self._cached_user_account_type
- response,status=self.execute_command("(Get-LocalUser -Name $env:USERNAME).PrincipalSource")
- result = "Local Account" if response.strip()=='Local' else "Microsoft Account" if status==0 else "Local Account"
+ response, status = self.execute_command(
+ "(Get-LocalUser -Name $env:USERNAME).PrincipalSource"
+ )
+ result = (
+ "Local Account"
+ if response.strip() == "Local"
+ else "Microsoft Account"
+ if status == 0
+ else "Local Account"
+ )
self._cached_user_account_type = result
return result
@@ -620,11 +677,11 @@ class Desktop:
dpi = user32.GetDpiForSystem()
return dpi / 96.0
- def get_screen_size(self)->Size:
+ def get_screen_size(self) -> Size:
width, height = uia.GetVirtualScreenSize()
- return Size(width=width,height=height)
+ return Size(width=width, height=height)
- def get_screenshot(self,as_bytes:bool=False)->bytes|Image.Image:
+ def get_screenshot(self, as_bytes: bool = False) -> bytes | Image.Image:
try:
screenshot = ImageGrab.grab(all_screens=True)
except Exception:
@@ -637,7 +694,9 @@ class Desktop:
buffered.close()
return screenshot
- def get_annotated_screenshot(self, nodes: list[TreeElementNode],as_bytes:bool=False) -> bytes|Image.Image:
+ def get_annotated_screenshot(
+ self, nodes: list[TreeElementNode], as_bytes: bool = False
+ ) -> bytes | Image.Image:
screenshot = self.get_screenshot()
# Add padding
padding = 5
@@ -649,7 +708,7 @@ class Desktop:
draw = ImageDraw.Draw(padded_screenshot)
font_size = 12
try:
- font = ImageFont.truetype('arial.ttf', font_size)
+ font = ImageFont.truetype("arial.ttf", font_size)
except OSError:
font = ImageFont.load_default()
@@ -658,7 +717,7 @@ class Desktop:
left_offset, top_offset, _, _ = uia.GetVirtualScreenRect()
- def draw_annotation(label:int, node: TreeElementNode):
+ def draw_annotation(label: int, node: TreeElementNode):
box = node.bounding_box
color = get_random_color()
@@ -668,7 +727,7 @@ class Desktop:
int(box.left - left_offset) + padding,
int(box.top - top_offset) + padding,
int(box.right - left_offset) + padding,
- int(box.bottom - top_offset) + padding
+ int(box.bottom - top_offset) + padding,
)
# Draw bounding box
draw.rectangle(adjusted_box, outline=color, width=2)
@@ -688,7 +747,7 @@ class Desktop:
draw.rectangle([(label_x1, label_y1), (label_x2, label_y2)], fill=color)
draw.text((label_x1 + 2, label_y1 + 2), str(label), fill=(255, 255, 255), font=font)
- for label,node in enumerate(nodes):
+ for label, node in enumerate(nodes):
draw_annotation(label, node)
if as_bytes:
diff --git a/windows_use/agent/desktop/views.py b/windows_use/agent/desktop/views.py
index a3afc35..313f24f 100644
--- a/windows_use/agent/desktop/views.py
+++ b/windows_use/agent/desktop/views.py
@@ -8,72 +8,82 @@ from windows_use.agent.tree.views import BoundingBox, TreeState
class Browser(Enum):
- CHROME='chrome'
- EDGE='msedge'
- FIREFOX='firefox'
+ CHROME = "chrome"
+ EDGE = "msedge"
+ FIREFOX = "firefox"
@classmethod
def has_process(cls, process_name: str) -> bool:
- if not hasattr(cls, '_process_names'):
- cls._process_names = {f'{b.value}.exe' for b in cls}
+ if not hasattr(cls, "_process_names"):
+ cls._process_names = {f"{b.value}.exe" for b in cls}
return process_name.lower() in cls._process_names
+
class Status(Enum):
- MAXIMIZED='Maximized'
- MINIMIZED='Minimized'
- NORMAL='Normal'
- HIDDEN='Hidden'
+ MAXIMIZED = "Maximized"
+ MINIMIZED = "Minimized"
+ NORMAL = "Normal"
+ HIDDEN = "Hidden"
@dataclass
class Window:
- name:str
- is_browser:bool
- depth:int
- status:Status
- bounding_box:BoundingBox
+ name: str
+ is_browser: bool
+ depth: int
+ status: Status
+ bounding_box: BoundingBox
handle: int
- process_id:int
+ process_id: int
def to_row(self):
- return [self.name, self.depth, self.status.value, self.bounding_box.width, self.bounding_box.height, self.handle]
+ return [
+ self.name,
+ self.depth,
+ self.status.value,
+ self.bounding_box.width,
+ self.bounding_box.height,
+ self.handle,
+ ]
+
@dataclass
class Size:
- width:int
- height:int
+ width: int
+ height: int
def to_string(self):
- return f'({self.width},{self.height})'
+ return f"({self.width},{self.height})"
+
@dataclass
class DesktopState:
- active_desktop:dict
- all_desktops:list[dict]
- windows:list[Window]
- active_window:Window | None
- screenshot:Image | None=None
- tree_state:TreeState | None=None
+ active_desktop: dict
+ all_desktops: list[dict]
+ windows: list[Window]
+ active_window: Window | None
+ screenshot: Image | None = None
+ tree_state: TreeState | None = None
def active_desktop_to_string(self):
- desktop_name=self.active_desktop.get('name')
- headers=["Name"]
+ desktop_name = self.active_desktop.get("name")
+ headers = ["Name"]
return tabulate([[desktop_name]], headers=headers, tablefmt="simple")
def desktops_to_string(self):
- headers=["Name"]
- rows=[[desktop.get("name")] for desktop in self.all_desktops]
+ headers = ["Name"]
+ rows = [[desktop.get("name")] for desktop in self.all_desktops]
return tabulate(rows, headers=headers, tablefmt="simple")
def active_window_to_string(self):
if not self.active_window:
- return 'No active window found'
+ return "No active window found"
headers = ["Name", "Depth", "Status", "Width", "Height", "Handle"]
return tabulate([self.active_window.to_row()], headers=headers, tablefmt="simple")
def windows_to_string(self):
if not self.windows:
- return 'No windows found'
+ return "No windows found"
headers = ["Name", "Depth", "Status", "Width", "Height", "Handle"]
rows = [window.to_row() for window in self.windows]
return tabulate(rows, headers=headers, tablefmt="simple")
diff --git a/windows_use/agent/loop.py b/windows_use/agent/loop.py
index 2a7de09..8cb0395 100644
--- a/windows_use/agent/loop.py
+++ b/windows_use/agent/loop.py
@@ -6,13 +6,13 @@ from collections import Counter, deque
from windows_use.agent.desktop.views import DesktopState
-_EXEMPT = {'done_tool', 'wait_tool'}
-_IGNORE_PARAMS = {'thought'}
+_EXEMPT = {"done_tool", "wait_tool"}
+_IGNORE_PARAMS = {"thought"}
_REPEAT_NUDGES = {
- 3: 'You have repeated the same action {n} times — make sure it is actually making progress.',
- 5: 'Same action repeated {n} times. If you are stuck, try a different approach.',
- 8: 'Same action repeated {n} times. Stop and take a completely different strategy.',
+ 3: "You have repeated the same action {n} times — make sure it is actually making progress.",
+ 5: "Same action repeated {n} times. If you are stuck, try a different approach.",
+ 8: "Same action repeated {n} times. Stop and take a completely different strategy.",
}
@@ -39,19 +39,18 @@ class LoopGuard:
self._stagnant = 0
# State cycle detection
self._visited_states: dict[str, int] = {} # fingerprint → visit count
- self._cycle_warning: str = ''
+ self._cycle_warning: str = ""
# Failed action retry detection
self._last_action_key: str | None = None
self._last_action_failed: bool = False
- self._failed_retry_warning: str = ''
+ self._failed_retry_warning: str = ""
def record_action(self, tool: str, params: dict, is_success: bool = True) -> None:
if tool in _EXEMPT:
return
filtered = {k: v for k, v in params.items() if k not in _IGNORE_PARAMS}
normalised = {
- k: v.strip().lower() if isinstance(v, str) else v
- for k, v in filtered.items()
+ k: v.strip().lower() if isinstance(v, str) else v for k, v in filtered.items()
}
raw = json.dumps({tool: normalised}, sort_keys=True).encode()
key = hashlib.sha256(raw).hexdigest()[:12]
@@ -61,11 +60,11 @@ class LoopGuard:
if not is_success and self._last_action_key == key and self._last_action_failed:
self._failed_retry_warning = (
f"You are retrying '{tool}' with the same parameters after it already failed. "
- 'The same action will produce the same failure — change your approach, '
- 'try different parameters, or use a different tool.'
+ "The same action will produce the same failure — change your approach, "
+ "try different parameters, or use a different tool."
)
else:
- self._failed_retry_warning = ''
+ self._failed_retry_warning = ""
self._last_action_key = key
self._last_action_failed = not is_success
@@ -90,7 +89,7 @@ class LoopGuard:
else:
content_text = "no_content"
- digest = hashlib.sha256(content_text.encode('utf-8', errors='replace')).hexdigest()[:16]
+ digest = hashlib.sha256(content_text.encode("utf-8", errors="replace")).hexdigest()[:16]
state = (window_id, digest)
if state == self._last_state:
@@ -100,23 +99,23 @@ class LoopGuard:
self._last_state = state
# State cycle detection: track all-time visits to this state
- fingerprint = f'{window_id}|{digest}'
+ fingerprint = f"{window_id}|{digest}"
count = self._visited_states.get(fingerprint, 0) + 1
self._visited_states[fingerprint] = count
if count == 2:
self._cycle_warning = (
- 'You have returned to a UI state you already visited. '
- 'You may be cycling between states. Try a completely different approach '
- 'instead of repeating the same steps.'
+ "You have returned to a UI state you already visited. "
+ "You may be cycling between states. Try a completely different approach "
+ "instead of repeating the same steps."
)
elif count >= 3:
self._cycle_warning = (
- f'You have returned to this state {count} times. '
- 'You are stuck in a loop — stop and reconsider your strategy entirely. '
- 'Try an alternative method or approach.'
+ f"You have returned to this state {count} times. "
+ "You are stuck in a loop — stop and reconsider your strategy entirely. "
+ "Try an alternative method or approach."
)
else:
- self._cycle_warning = ''
+ self._cycle_warning = ""
def check(self) -> str | None:
warnings: list[str] = []
@@ -130,10 +129,10 @@ class LoopGuard:
if self._stagnant >= 4:
warnings.append(
- f'The UI has not changed for {self._stagnant} steps. '
- 'Your actions may not be having any effect. '
- 'If waiting for something external (OTP, email, slow load) '
- 'use wait_tool first, then re-check.'
+ f"The UI has not changed for {self._stagnant} steps. "
+ "Your actions may not be having any effect. "
+ "If waiting for something external (OTP, email, slow load) "
+ "use wait_tool first, then re-check."
)
if self._cycle_warning:
@@ -142,14 +141,14 @@ class LoopGuard:
if self._failed_retry_warning:
warnings.append(self._failed_retry_warning)
- return '\n\n'.join(warnings) or None
+ return "\n\n".join(warnings) or None
def reset(self) -> None:
self._hashes.clear()
self._last_state = None
self._stagnant = 0
self._visited_states = {}
- self._cycle_warning = ''
+ self._cycle_warning = ""
self._last_action_key = None
self._last_action_failed = False
- self._failed_retry_warning = ''
+ self._failed_retry_warning = ""
diff --git a/windows_use/agent/registry/service.py b/windows_use/agent/registry/service.py
index 9221fe7..d019018 100644
--- a/windows_use/agent/registry/service.py
+++ b/windows_use/agent/registry/service.py
@@ -4,51 +4,63 @@ from windows_use.agent.tools import Tool
class Registry:
- def __init__(self,tools:list[Tool]=[]):
- self.tools=tools
- self.tools_registry=self.registry()
+ def __init__(self, tools: list[Tool] = []):
+ self.tools = tools
+ self.tools_registry = self.registry()
- def registry(self)->dict[str,Tool]:
+ def registry(self) -> dict[str, Tool]:
return {tool.name: tool for tool in self.tools}
- def get_tools(self,exclude_tools:list[str]=[])->list[Tool]:
+ def get_tools(self, exclude_tools: list[str] = []) -> list[Tool]:
if not exclude_tools:
return self.tools
return [tool for tool in self.tools if tool.name not in exclude_tools]
- def get_tool(self,tool_name:str)->Tool|None:
- return self.tools_registry.get(tool_name,None)
+ def get_tool(self, tool_name: str) -> Tool | None:
+ return self.tools_registry.get(tool_name, None)
def get_tools_schema(self) -> list[dict]:
tools = [tool.json_schema for tool in self.tools]
return tools
- def execute(self, tool_name: str, tool_params: dict, desktop: Desktop|None=None) -> ToolResult:
+ def execute(
+ self, tool_name: str, tool_params: dict, desktop: Desktop | None = None
+ ) -> ToolResult:
tool = self.get_tool(tool_name)
if not tool:
return ToolResult(is_success=False, error=f"Tool '{tool_name}' not found.")
- errors=tool.validate_params(tool_params)
+ errors = tool.validate_params(tool_params)
if errors:
- error_msg="\n".join(errors)
- return ToolResult(is_success=False, error=f"Tool '{tool_name}' validation failed:\n{error_msg}")
+ error_msg = "\n".join(errors)
+ return ToolResult(
+ is_success=False, error=f"Tool '{tool_name}' validation failed:\n{error_msg}"
+ )
try:
- content = tool.invoke(**({'desktop': desktop} | tool_params))
+ content = tool.invoke(**({"desktop": desktop} | tool_params))
return ToolResult(is_success=True, content=content)
except Exception as error:
- error_msg=str(error)
- return ToolResult(is_success=False, error=f"Tool '{tool_name}' execution failed:\n{error_msg}")
+ error_msg = str(error)
+ return ToolResult(
+ is_success=False, error=f"Tool '{tool_name}' execution failed:\n{error_msg}"
+ )
- async def aexecute(self, tool_name: str, tool_params: dict, desktop: Desktop|None=None) -> ToolResult:
+ async def aexecute(
+ self, tool_name: str, tool_params: dict, desktop: Desktop | None = None
+ ) -> ToolResult:
tool = self.get_tool(tool_name)
if not tool:
return ToolResult(is_success=False, error=f"Tool '{tool_name}' not found.")
errors = tool.validate_params(tool_params)
if errors:
error_msg = "\n".join(errors)
- return ToolResult(is_success=False, error=f"Tool '{tool_name}' validation failed:\n{error_msg}")
+ return ToolResult(
+ is_success=False, error=f"Tool '{tool_name}' validation failed:\n{error_msg}"
+ )
try:
- content = await tool.ainvoke(**({'desktop': desktop} | tool_params))
+ content = await tool.ainvoke(**({"desktop": desktop} | tool_params))
return ToolResult(is_success=True, content=content)
except Exception as error:
error_msg = str(error)
- return ToolResult(is_success=False, error=f"Tool '{tool_name}' async execution failed:\n{error_msg}")
+ return ToolResult(
+ is_success=False, error=f"Tool '{tool_name}' async execution failed:\n{error_msg}"
+ )
diff --git a/windows_use/agent/service.py b/windows_use/agent/service.py
index cd8152d..9904ec9 100644
--- a/windows_use/agent/service.py
+++ b/windows_use/agent/service.py
@@ -158,7 +158,8 @@ class Agent(BaseAgent):
query=self.state.task,
step=self.state.step,
max_steps=self.state.max_steps,
- desktop=self.desktop)
+ desktop=self.desktop,
+ )
def loop(self) -> AgentResult:
"""Run the main agent loop.
@@ -178,8 +179,8 @@ class Agent(BaseAgent):
self.state.step = step
if self.context.need_compaction:
- messages=self.state.messages+self.state.error_messages
- if content:=self.context.compact(messages):
+ messages = self.state.messages + self.state.error_messages
+ if content := self.context.compact(messages):
self.state.messages = [self.system_message, HumanMessage(content=content)]
self.state.error_messages.clear()
@@ -194,7 +195,10 @@ class Agent(BaseAgent):
)
if nudge:
self.event.emit(
- AgentEvent(type=EventType.ERROR, data={"step": step, "error": f"Loop detected: {nudge}"})
+ AgentEvent(
+ type=EventType.ERROR,
+ data={"step": step, "error": f"Loop detected: {nudge}"},
+ )
)
self.state.messages.append(state_msg)
@@ -236,9 +240,7 @@ class Agent(BaseAgent):
"error_type": type(llm_event).__name__,
"error": str(llm_event),
}
- self.event.emit(
- AgentEvent(type=EventType.ERROR, data=llm_error_data)
- )
+ self.event.emit(AgentEvent(type=EventType.ERROR, data=llm_error_data))
llm_errors.append(llm_error_data)
continue
except Exception as e:
@@ -252,9 +254,7 @@ class Agent(BaseAgent):
"error_type": type(e).__name__,
"error": str(e),
}
- self.event.emit(
- AgentEvent(type=EventType.ERROR, data=llm_error_data)
- )
+ self.event.emit(AgentEvent(type=EventType.ERROR, data=llm_error_data))
llm_errors.append(llm_error_data)
if attempt < self.state.max_consecutive_failures - 1:
@@ -282,7 +282,7 @@ class Agent(BaseAgent):
"error": error,
"llm_errors": llm_errors,
"error_source": "llm_exhausted_retries",
- }
+ },
)
)
return AgentResult(is_done=False, error=error)
@@ -308,16 +308,16 @@ class Agent(BaseAgent):
"step": step,
"tool_name": tool_name,
"tool_params": {
- k: v
- for k, v in tool_params.items()
- if k not in _NON_TOOL_PARAMS
+ k: v for k, v in tool_params.items() if k not in _NON_TOOL_PARAMS
},
},
)
)
# Act: execute tool via registry
- tool_result = self.registry.execute(tool_name=tool_name, tool_params=tool_params, desktop=self.desktop)
+ tool_result = self.registry.execute(
+ tool_name=tool_name, tool_params=tool_params, desktop=self.desktop
+ )
# Record action for loop detection
if not self.disable_loop_detection:
@@ -380,17 +380,19 @@ class Agent(BaseAgent):
self.watchdog.set_focus_callback(self.desktop.tree.on_focus_change)
with self.watchdog:
result = self.loop()
- self.telemetry.capture(AgentTelemetryEvent(
- query=task,
- steps=self.state.step,
- max_steps=self.state.max_steps,
- model=self.llm.model_name,
- provider=self.llm.provider,
- use_vision=self.desktop.use_vision,
- answer=result.content,
- error=result.error,
- is_success=result.is_done,
- ))
+ self.telemetry.capture(
+ AgentTelemetryEvent(
+ query=task,
+ steps=self.state.step,
+ max_steps=self.state.max_steps,
+ model=self.llm.model_name,
+ provider=self.llm.provider,
+ use_vision=self.desktop.use_vision,
+ answer=result.content,
+ error=result.error,
+ is_success=result.is_done,
+ )
+ )
self.telemetry.flush()
return result
except Exception as e:
@@ -400,21 +402,24 @@ class Agent(BaseAgent):
data={"step": self.state.step, "error": str(e)},
)
)
- self.telemetry.capture(AgentTelemetryEvent(
- query=task,
- steps=self.state.step,
- max_steps=self.state.max_steps,
- model=self.llm.model_name,
- provider=self.llm.provider,
- use_vision=self.desktop.use_vision,
- error=str(e),
- is_success=False,
- ))
+ self.telemetry.capture(
+ AgentTelemetryEvent(
+ query=task,
+ steps=self.state.step,
+ max_steps=self.state.max_steps,
+ model=self.llm.model_name,
+ provider=self.llm.provider,
+ use_vision=self.desktop.use_vision,
+ error=str(e),
+ is_success=False,
+ )
+ )
self.telemetry.flush()
async def aloop(self) -> AgentResult:
"""Run the main agent loop asynchronously."""
import asyncio
+
self.state.messages.insert(0, self.system_message)
self.state.messages.append(self.task_message)
consecutive_failures = 0
@@ -424,8 +429,8 @@ class Agent(BaseAgent):
self.state.step = step
if self.context.need_compaction:
- messages=self.state.messages+self.state.error_messages
- if content:=self.context.compact(messages):
+ messages = self.state.messages + self.state.error_messages
+ if content := self.context.compact(messages):
self.state.messages = [self.system_message, HumanMessage(content=content)]
self.state.error_messages.clear()
@@ -440,7 +445,10 @@ class Agent(BaseAgent):
)
if nudge:
self.event.emit(
- AgentEvent(type=EventType.ERROR, data={"step": step, "error": f"Loop detected: {nudge}"})
+ AgentEvent(
+ type=EventType.ERROR,
+ data={"step": step, "error": f"Loop detected: {nudge}"},
+ )
)
self.state.messages.append(state_msg)
@@ -515,16 +523,16 @@ class Agent(BaseAgent):
"step": step,
"tool_name": tool_name,
"tool_params": {
- k: v
- for k, v in tool_params.items()
- if k not in _NON_TOOL_PARAMS
+ k: v for k, v in tool_params.items() if k not in _NON_TOOL_PARAMS
},
},
)
)
# Act: execute tool via registry asynchronously
- tool_result = await self.registry.aexecute(tool_name=tool_name, tool_params=tool_params, desktop=self.desktop)
+ tool_result = await self.registry.aexecute(
+ tool_name=tool_name, tool_params=tool_params, desktop=self.desktop
+ )
# Record action for loop detection
if not self.disable_loop_detection:
@@ -587,17 +595,19 @@ class Agent(BaseAgent):
self.watchdog.set_focus_callback(self.desktop.tree.on_focus_change)
with self.watchdog:
result = await self.aloop()
- self.telemetry.capture(AgentTelemetryEvent(
- query=task,
- steps=self.state.step,
- max_steps=self.state.max_steps,
- model=self.llm.model_name,
- provider=self.llm.provider,
- use_vision=self.desktop.use_vision,
- answer=result.content,
- error=result.error,
- is_success=result.is_done,
- ))
+ self.telemetry.capture(
+ AgentTelemetryEvent(
+ query=task,
+ steps=self.state.step,
+ max_steps=self.state.max_steps,
+ model=self.llm.model_name,
+ provider=self.llm.provider,
+ use_vision=self.desktop.use_vision,
+ answer=result.content,
+ error=result.error,
+ is_success=result.is_done,
+ )
+ )
self.telemetry.flush()
return result
except Exception as e:
@@ -607,14 +617,16 @@ class Agent(BaseAgent):
data={"step": self.state.step, "error": str(e)},
)
)
- self.telemetry.capture(AgentTelemetryEvent(
- query=task,
- steps=self.state.step,
- max_steps=self.state.max_steps,
- model=self.llm.model_name,
- provider=self.llm.provider,
- use_vision=self.desktop.use_vision,
- error=str(e),
- is_success=False,
- ))
+ self.telemetry.capture(
+ AgentTelemetryEvent(
+ query=task,
+ steps=self.state.step,
+ max_steps=self.state.max_steps,
+ model=self.llm.model_name,
+ provider=self.llm.provider,
+ use_vision=self.desktop.use_vision,
+ error=str(e),
+ is_success=False,
+ )
+ )
self.telemetry.flush()
diff --git a/windows_use/agent/tools/__init__.py b/windows_use/agent/tools/__init__.py
index c3bcba9..3169234 100644
--- a/windows_use/agent/tools/__init__.py
+++ b/windows_use/agent/tools/__init__.py
@@ -28,7 +28,7 @@ BUILTIN_TOOLS = [
move_tool,
wait_tool,
scrape_tool,
- desktop_tool
+ desktop_tool,
]
EXPERIMENTAL_TOOLS = [
diff --git a/windows_use/agent/tools/service.py b/windows_use/agent/tools/service.py
index c386624..a8eb485 100644
--- a/windows_use/agent/tools/service.py
+++ b/windows_use/agent/tools/service.py
@@ -38,10 +38,12 @@ def _format_size(size: int) -> str:
size /= 1024
return f"{size:.1f} PB"
+
WINDOWS_USE_DIR = Path.home() / ".windows-use"
memory_path = WINDOWS_USE_DIR / "memory"
memory_path.mkdir(parents=True, exist_ok=True)
+
def _resolve_memory_path(path: str) -> Path:
"""Resolve a memory file path, always sandboxed within .windows-use/memories directory."""
file_path = (memory_path / path).resolve()
@@ -49,9 +51,10 @@ def _resolve_memory_path(path: str) -> Path:
raise ValueError(f"Path escapes the .windows-use/memories directory: {path}")
return file_path
-@Tool('done_tool',model=Done)
-async def done_tool(answer:str,**kwargs):
- '''
+
+@Tool("done_tool", model=Done)
+async def done_tool(answer: str, **kwargs):
+ """
Delivers a response to the user. This is the ONLY way to communicate with the user.
MUST be called for every type of response:
@@ -61,29 +64,42 @@ async def done_tool(answer:str,**kwargs):
- Error reports: explain what failed and why
The answer should be formatted in clean markdown.
- '''
+ """
return answer
-@Tool('app_tool',model=App)
-async def app_tool(mode:Literal['launch','resize','switch']='launch',name:str | None=None,loc:list[int] | None=None,size:list[int] | None=None,**kwargs)->str:
- '''
+
+@Tool("app_tool", model=App)
+async def app_tool(
+ mode: Literal["launch", "resize", "switch"] = "launch",
+ name: str | None = None,
+ loc: list[int] | None = None,
+ size: list[int] | None = None,
+ **kwargs,
+) -> str:
+ """
Manages application windows: launch new apps, switch between open windows, or resize/reposition the active window.
- launch: Opens an application via the Start Menu. Provide the app name as it appears in Start Menu.
- switch: Brings an already-open window to the foreground. Provide the window title from the Window Info list.
- resize: Moves and resizes the currently active window. Provide loc=[x,y] for position and size=[w,h] for dimensions.
- '''
- desktop:_Desktop=kwargs['desktop']
- return desktop.app(mode,name,loc,size)
+ """
+ desktop: _Desktop = kwargs["desktop"]
+ return desktop.app(mode, name, loc, size)
-
-@Tool('memory_tool', model=Memory)
-async def memory_tool(mode: Literal['view', 'read', 'write', 'delete', 'update'], path: str | None = None,
- content: str | None = None, operation: Literal['replace', 'insert'] | None = 'replace',
- old_str: str | None = None, new_str: str | None = None, line_number: int | None = None,
- read_range: list[int] | None = None, **kwargs) -> str:
- '''
+@Tool("memory_tool", model=Memory)
+async def memory_tool(
+ mode: Literal["view", "read", "write", "delete", "update"],
+ path: str | None = None,
+ content: str | None = None,
+ operation: Literal["replace", "insert"] | None = "replace",
+ old_str: str | None = None,
+ new_str: str | None = None,
+ line_number: int | None = None,
+ read_range: list[int] | None = None,
+ **kwargs,
+) -> str:
+ """
Persistent file-based storage for saving and retrieving information across steps. Files are stored as markdown in the .windows-use/memories directory (user home).
- view: List all stored memory files. Optionally provide a subdirectory path to list only files within it.
@@ -93,101 +109,112 @@ async def memory_tool(mode: Literal['view', 'read', 'write', 'delete', 'update']
- delete: Remove a file by path.
Use for storing intermediate results, research findings, plans, or any data needed in later steps.
- '''
+ """
match mode:
- case 'view':
+ case "view":
search_dir = (memory_path / path).resolve() if path else memory_path
if not str(search_dir).startswith(str(memory_path.resolve())):
return "Error: path escapes the .windows-use/memories directory."
if not search_dir.exists():
return "No memory files found."
- files = search_dir.rglob('*.md')
- result = '\n'.join([f'{i + 1}. {file.relative_to(memory_path).as_posix()}'
- for i, file in enumerate(files)])
+ files = search_dir.rglob("*.md")
+ result = "\n".join(
+ [
+ f"{i + 1}. {file.relative_to(memory_path).as_posix()}"
+ for i, file in enumerate(files)
+ ]
+ )
return result if result else "No memory files found."
- case 'write':
+ case "write":
if not path:
return "Error: path is required for write mode."
- if not path.endswith('.md'):
- path += '.md'
+ if not path.endswith(".md"):
+ path += ".md"
file_path = _resolve_memory_path(path)
file_path.parent.mkdir(parents=True, exist_ok=True)
- file_path.write_text(content, encoding='utf-8')
- return f'{file_path.name} created in {file_path.parent.relative_to(memory_path).as_posix()}.'
+ file_path.write_text(content, encoding="utf-8")
+ return f"{file_path.name} created in {file_path.parent.relative_to(memory_path).as_posix()}."
- case 'read':
+ case "read":
if not path:
return "Error: path is required for read mode."
file_path = _resolve_memory_path(path)
if not file_path.exists():
- return f'Error: {file_path.name} not found.'
+ return f"Error: {file_path.name} not found."
- file_content = file_path.read_text(encoding='utf-8')
+ file_content = file_path.read_text(encoding="utf-8")
if read_range:
start, end = read_range
lines = file_content.splitlines()
if start < 0 or start >= len(lines):
- return f'Error: start line {start} out of range (0-{len(lines) - 1}).'
+ return f"Error: start line {start} out of range (0-{len(lines) - 1})."
if end < start or end > len(lines):
- return f'Error: end line {end} out of range ({start}-{len(lines)}).'
+ return f"Error: end line {end} out of range ({start}-{len(lines)})."
selected_lines = lines[start:end]
- return f"File: {file_path.relative_to(memory_path).as_posix()}\nLines {start}-{end - 1}:\n" + '\n'.join(selected_lines)
+ return (
+ f"File: {file_path.relative_to(memory_path).as_posix()}\nLines {start}-{end - 1}:\n"
+ + "\n".join(selected_lines)
+ )
- return f"File: {file_path.relative_to(memory_path).as_posix()}\nContent:\n{file_content}"
+ return (
+ f"File: {file_path.relative_to(memory_path).as_posix()}\nContent:\n{file_content}"
+ )
- case 'update':
+ case "update":
if not path:
return "Error: path is required for update mode."
file_path = _resolve_memory_path(path)
if not file_path.exists():
return f'Error: {file_path.name} not found. Use "write" mode to create a new file.'
- current_content = file_path.read_text(encoding='utf-8')
+ current_content = file_path.read_text(encoding="utf-8")
match operation:
- case 'replace':
+ case "replace":
if not old_str or not new_str:
- return 'Error: both old_str and new_str are required for replace operation.'
+ return "Error: both old_str and new_str are required for replace operation."
if old_str not in current_content:
return f'Error: "{old_str}" not found in file.'
new_content = current_content.replace(old_str, new_str)
- file_path.write_text(new_content, encoding='utf-8')
+ file_path.write_text(new_content, encoding="utf-8")
old_display = f'"{old_str[:50]}{"..." if len(old_str) > 50 else ""}"'
new_display = f'"{new_str[:50]}{"..." if len(new_str) > 50 else ""}"'
- return f'{file_path.name} updated: replaced {old_display} with {new_display}.'
+ return f"{file_path.name} updated: replaced {old_display} with {new_display}."
- case 'insert':
+ case "insert":
if line_number is None:
- return 'Error: line_number is required for insert operation.'
+ return "Error: line_number is required for insert operation."
if not content:
- return 'Error: content is required for insert operation.'
+ return "Error: content is required for insert operation."
lines = current_content.splitlines(keepends=True)
if line_number < 0 or line_number > len(lines):
- return f'Error: line_number {line_number} out of range (0-{len(lines)}).'
+ return f"Error: line_number {line_number} out of range (0-{len(lines)})."
- lines.insert(line_number, content + '\n' if not content.endswith('\n') else content)
- new_content = ''.join(lines)
- file_path.write_text(new_content, encoding='utf-8')
- return f'{file_path.name} updated: inserted content at line {line_number}.'
+ lines.insert(
+ line_number, content + "\n" if not content.endswith("\n") else content
+ )
+ new_content = "".join(lines)
+ file_path.write_text(new_content, encoding="utf-8")
+ return f"{file_path.name} updated: inserted content at line {line_number}."
case _:
return f'Error: Unknown operation "{operation}".'
- case 'delete':
+ case "delete":
if not path:
return "Error: path is required for delete mode."
file_path = _resolve_memory_path(path)
if not file_path.exists():
- return f'Error: {file_path.name} not found.'
+ return f"Error: {file_path.name} not found."
file_path.unlink()
- return f'{file_path.name} deleted from {file_path.parent.relative_to(memory_path).as_posix()}.'
+ return f"{file_path.name} deleted from {file_path.parent.relative_to(memory_path).as_posix()}."
return "Invalid mode. Use 'view', 'write', 'read', 'update', or 'delete'."
@@ -211,7 +238,7 @@ async def file_tool(
encoding: str = "utf-8",
**kwargs,
) -> str:
- '''
+ """
Performs file system operations: read, write, list, delete, move, copy, or check existence.
- read: Returns file content. Paths are relative to user home directory or absolute.
@@ -223,7 +250,7 @@ async def file_tool(
- exists: Returns whether the path exists.
Use for reading config files, writing outputs, organizing files, or checking file presence.
- '''
+ """
try:
resolved = _resolve_file_path(path)
except ValueError as e:
@@ -238,7 +265,9 @@ async def file_tool(
try:
size = resolved.stat().st_size
if size > MAX_FILE_READ_SIZE:
- return f"Error: File too large to read ({size} bytes, max {MAX_FILE_READ_SIZE})."
+ return (
+ f"Error: File too large to read ({size} bytes, max {MAX_FILE_READ_SIZE})."
+ )
text = resolved.read_text(encoding=encoding)
return f"File: {resolved}\nContent:\n{text}"
except UnicodeDecodeError as e:
@@ -323,20 +352,26 @@ async def file_tool(
return f"Error: Unknown action '{mode}'."
-@Tool('shell_tool',model=Shell)
-async def shell_tool(command: str,timeout:int=10,**kwargs) -> str:
- '''
+@Tool("shell_tool", model=Shell)
+async def shell_tool(command: str, timeout: int = 10, **kwargs) -> str:
+ """
Executes a PowerShell command and returns the output and exit status code. Working directory is the user's HOME.
Use for file operations, system queries, installations, running scripts, and any task better done via command line than GUI. Check the status code in the response: 0 means success, non-zero means failure.
- '''
- desktop:_Desktop=kwargs['desktop']
- response,status=desktop.execute_command(command,timeout=timeout)
- return f'Response: {response}\nStatus Code: {status}'
-
-@Tool('click_tool',model=Click)
-async def click_tool(loc:list[int] | None=None,button:Literal['left','right','middle']='left',clicks:int=1,**kwargs)->str:
- '''
+ """
+ desktop: _Desktop = kwargs["desktop"]
+ response, status = desktop.execute_command(command, timeout=timeout)
+ return f"Response: {response}\nStatus Code: {status}"
+
+
+@Tool("click_tool", model=Click)
+async def click_tool(
+ loc: list[int] | None = None,
+ button: Literal["left", "right", "middle"] = "left",
+ clicks: int = 1,
+ **kwargs,
+) -> str:
+ """
Clicks at the specified pixel coordinates on screen.
- Single left click (clicks=1): Select elements, press buttons, focus fields, follow links.
@@ -345,16 +380,24 @@ async def click_tool(loc:list[int] | None=None,button:Literal['left','right','mi
- Hover only (clicks=0): Move cursor to location without clicking.
Use coordinates from the Interactive Elements list in the Desktop State.
- '''
- x,y=loc
- desktop:_Desktop=kwargs['desktop']
- desktop.click(loc,button,clicks)
- num_clicks={1:'Single',2:'Double',3:'Triple'}
- return f'{num_clicks.get(clicks)} {button} clicked at ({x},{y}).'
-
-@Tool('type_tool',model=Type)
-async def type_tool(loc:list[int] | None=None,text:str='',clear:Literal['true','false']='false',caret_position:Literal['start','idle','end']='idle',press_enter:Literal['true','false']='false',**kwargs):
- '''
+ """
+ x, y = loc
+ desktop: _Desktop = kwargs["desktop"]
+ desktop.click(loc, button, clicks)
+ num_clicks = {1: "Single", 2: "Double", 3: "Triple"}
+ return f"{num_clicks.get(clicks)} {button} clicked at ({x},{y})."
+
+
+@Tool("type_tool", model=Type)
+async def type_tool(
+ loc: list[int] | None = None,
+ text: str = "",
+ clear: Literal["true", "false"] = "false",
+ caret_position: Literal["start", "idle", "end"] = "idle",
+ press_enter: Literal["true", "false"] = "false",
+ **kwargs,
+):
+ """
Clicks an input field and types text into it. Do NOT pre-click with click_tool — this tool handles focusing automatically.
- Set clear=true to replace existing text, or clear=false to append.
@@ -362,139 +405,171 @@ async def type_tool(loc:list[int] | None=None,text:str='',clear:Literal['true','
- Set caret_position to control where typing begins relative to existing text.
Use for search queries, form fields, text editors, address bars, and any text input.
- '''
- x,y=loc
- desktop:_Desktop=kwargs['desktop']
- desktop.type(loc=loc,text=text,caret_position=caret_position,clear=clear,press_enter=press_enter)
- return f'Typed {text} at ({x},{y}).'
-
-@Tool('scroll_tool',model=Scroll)
-async def scroll_tool(loc:list[int] | None=None,type:Literal['horizontal','vertical']='vertical',direction:Literal['up','down','left','right']='down',wheel_times:int=1,**kwargs)->str:
- '''
+ """
+ x, y = loc
+ desktop: _Desktop = kwargs["desktop"]
+ desktop.type(
+ loc=loc, text=text, caret_position=caret_position, clear=clear, press_enter=press_enter
+ )
+ return f"Typed {text} at ({x},{y})."
+
+
+@Tool("scroll_tool", model=Scroll)
+async def scroll_tool(
+ loc: list[int] | None = None,
+ type: Literal["horizontal", "vertical"] = "vertical",
+ direction: Literal["up", "down", "left", "right"] = "down",
+ wheel_times: int = 1,
+ **kwargs,
+) -> str:
+ """
Scrolls content at the specified location or at the current cursor position.
Each wheel increment scrolls roughly 3-5 lines of text. Use wheel_times=3-5 for moderate scrolling, 10+ for large jumps.
Check scroll percentages in the Scrollable Elements list to gauge position before scrolling. If loc is omitted, scrolling occurs at the current cursor location.
- '''
- desktop:_Desktop=kwargs['desktop']
- response=desktop.scroll(loc,type,direction,wheel_times)
+ """
+ desktop: _Desktop = kwargs["desktop"]
+ response = desktop.scroll(loc, type, direction, wheel_times)
if response:
return response
- return f'Scrolled {type} {direction} by {wheel_times} wheel times.'
+ return f"Scrolled {type} {direction} by {wheel_times} wheel times."
-@Tool('move_tool',model=Move)
-async def move_tool(loc:list[int],drag:bool=False,**kwargs)->str:
- '''
+
+@Tool("move_tool", model=Move)
+async def move_tool(loc: list[int], drag: bool = False, **kwargs) -> str:
+ """
Moves the mouse cursor to a target location, or drags from the current position to the target.
- drag=false: Hover over elements to reveal tooltips, dropdown menus, or reposition the cursor.
- drag=true: Hold left mouse button from the current cursor position and drag to the target coordinates. Use for drag-and-drop of files, window resizing, slider adjustment, or reordering items.
- '''
- x,y=loc
- desktop:_Desktop=kwargs['desktop']
+ """
+ x, y = loc
+ desktop: _Desktop = kwargs["desktop"]
if drag:
desktop.drag(loc)
- return f'Dragged the selected element to ({x},{y}).'
+ return f"Dragged the selected element to ({x},{y})."
else:
desktop.move(loc)
- return f'Moved the mouse pointer to ({x},{y}).'
+ return f"Moved the mouse pointer to ({x},{y})."
+
-@Tool('shortcut_tool',model=Shortcut)
-async def shortcut_tool(shortcut:str,**kwargs)->str:
- '''
+@Tool("shortcut_tool", model=Shortcut)
+async def shortcut_tool(shortcut: str, **kwargs) -> str:
+ """
Presses a keyboard shortcut. Use '+' to combine keys (e.g., 'ctrl+c').
Common shortcuts: ctrl+c (copy), ctrl+v (paste), ctrl+z (undo), ctrl+s (save), ctrl+a (select all), ctrl+f (find), ctrl+w (close tab), ctrl+t (new tab), alt+tab (switch window), alt+f4 (close app), enter (confirm), escape (cancel), win (start menu).
Prefer shortcuts over mouse interactions when the operation is unambiguous.
- '''
- desktop:_Desktop=kwargs['desktop']
+ """
+ desktop: _Desktop = kwargs["desktop"]
desktop.shortcut(shortcut)
- return f'Pressed {shortcut}.'
+ return f"Pressed {shortcut}."
-@Tool('multi_select_tool',model=MultiSelect)
-async def multi_select_tool(press_ctrl:Literal['true','false']='true',elements:list[list[int]]=[],**kwargs)->str:
- '''
+
+@Tool("multi_select_tool", model=MultiSelect)
+async def multi_select_tool(
+ press_ctrl: Literal["true", "false"] = "true", elements: list[list[int]] = [], **kwargs
+) -> str:
+ """
Clicks multiple locations in sequence. With press_ctrl=true, holds Ctrl to accumulate a multi-selection (e.g., selecting multiple files, checkboxes, or list items). With press_ctrl=false, clicks each location independently in order.
Provide a list of [x, y] coordinates. Each is clicked once in the order given.
- '''
- desktop:_Desktop=kwargs['desktop']
- desktop.multi_select(press_ctrl,elements)
- elements_str = '\n'.join([f"({x},{y})" for x,y in elements])
- return f'Multi-selected elements at {elements_str}.'
-
-@Tool('multi_edit_tool',model=MultiEdit)
-async def multi_edit_tool(elements:list[list],**kwargs)->str:
- '''
+ """
+ desktop: _Desktop = kwargs["desktop"]
+ desktop.multi_select(press_ctrl, elements)
+ elements_str = "\n".join([f"({x},{y})" for x, y in elements])
+ return f"Multi-selected elements at {elements_str}."
+
+
+@Tool("multi_edit_tool", model=MultiEdit)
+async def multi_edit_tool(elements: list[list], **kwargs) -> str:
+ """
Types text into multiple input fields in one action. Each entry is [x, y, text]: the tool clicks the location and types the text, then moves to the next entry.
Use for filling out forms with multiple fields (name, email, address) or editing several text inputs at once. More efficient than calling type_tool repeatedly.
- '''
- desktop:_Desktop=kwargs['desktop']
+ """
+ desktop: _Desktop = kwargs["desktop"]
desktop.multi_edit(elements)
- elements_str = ','.join([f'({x},{y}) text={text}' for x,y,text in elements])
- return f'Multi-edited elements at {elements_str}.'
+ elements_str = ",".join([f"({x},{y}) text={text}" for x, y, text in elements])
+ return f"Multi-edited elements at {elements_str}."
-@Tool('wait_tool',model=Wait)
-async def wait_tool(duration:int,**kwargs)->str:
- '''
+
+@Tool("wait_tool", model=Wait)
+async def wait_tool(duration: int, **kwargs) -> str:
+ """
Pauses for the specified number of seconds before the next action. Use to wait for applications to launch, pages to load, dialogs to appear, or animations to finish. Typical waits: 2-3s for UI transitions, 5s for app launches, 10s+ for installations or downloads.
- '''
+ """
import asyncio
+
await asyncio.sleep(duration)
- return f'Waited for {duration} seconds.'
+ return f"Waited for {duration} seconds."
-@Tool('scrape_tool',model=Scrape)
-async def scrape_tool(url:str,**kwargs)->str:
- '''
+
+@Tool("scrape_tool", model=Scrape)
+async def scrape_tool(url: str, **kwargs) -> str:
+ """
Extracts visible text content from the webpage currently displayed in the browser and returns it as markdown.
This reads the rendered page content via the accessibility tree — not the raw HTML. Provide the URL of the page currently open in the browser. The output includes scroll position indicators so you know if there is more content above or below.
Use when you need to read, analyze, or extract information from a webpage.
- '''
- desktop:_Desktop=kwargs['desktop']
- desktop_state=desktop.desktop_state
- tree_state=desktop_state.tree_state
+ """
+ desktop: _Desktop = kwargs["desktop"]
+ desktop_state = desktop.desktop_state
+ tree_state = desktop_state.tree_state
if not tree_state.dom_node:
- content=desktop.scrape(url)
- return f'URL:{url}\nContent:\n{content}'
- dom_node=tree_state.dom_node
- vertical_scroll_percent=dom_node.metadata.get('vertical_scroll_percent',0)
- content='\n'.join([node.text for node in tree_state.dom_informative_nodes])
- header_status = "[Reached top]" if vertical_scroll_percent <= 0 else f"[Scroll up ({vertical_scroll_percent*100:.2f}%) to see more content]"
- footer_status = "[Reached bottom]" if vertical_scroll_percent >= 100 else f"[Scroll down ({(1-vertical_scroll_percent)*100:.2f}%) to see more content]"
- return f'URL:{url}\nContent:\n{header_status}\n{content}\n{footer_status}'
-
-@Tool('desktop_tool', model=Desktop)
-async def desktop_tool(action: Literal['create', 'remove', 'rename', 'switch'], desktop_name: str | None = None, new_name: str | None = None, **kwargs) -> str:
- '''
+ content = desktop.scrape(url)
+ return f"URL:{url}\nContent:\n{content}"
+ dom_node = tree_state.dom_node
+ vertical_scroll_percent = dom_node.metadata.get("vertical_scroll_percent", 0)
+ content = "\n".join([node.text for node in tree_state.dom_informative_nodes])
+ header_status = (
+ "[Reached top]"
+ if vertical_scroll_percent <= 0
+ else f"[Scroll up ({vertical_scroll_percent * 100:.2f}%) to see more content]"
+ )
+ footer_status = (
+ "[Reached bottom]"
+ if vertical_scroll_percent >= 100
+ else f"[Scroll down ({(1 - vertical_scroll_percent) * 100:.2f}%) to see more content]"
+ )
+ return f"URL:{url}\nContent:\n{header_status}\n{content}\n{footer_status}"
+
+
+@Tool("desktop_tool", model=Desktop)
+async def desktop_tool(
+ action: Literal["create", "remove", "rename", "switch"],
+ desktop_name: str | None = None,
+ new_name: str | None = None,
+ **kwargs,
+) -> str:
+ """
Manages Windows virtual desktops for workspace organization.
- create: Creates a new virtual desktop. Optionally provide a name via desktop_name.
- remove: Deletes the desktop specified by desktop_name. Ensure no needed windows remain on it.
- rename: Renames desktop_name to new_name.
- switch: Activates the desktop specified by desktop_name. Verify success in the next Desktop State.
- '''
+ """
try:
match action:
- case 'create':
+ case "create":
# create_desktop(name) returns the name
created_name = vdm_create(desktop_name)
return f"Created desktop: '{created_name}'"
- case 'remove':
+ case "remove":
if not desktop_name:
return "Error: desktop_name is required for removal."
vdm_remove(desktop_name)
return f"Removed desktop '{desktop_name}'"
- case 'rename':
+ case "rename":
if not desktop_name or not new_name:
return "Error: desktop_name and new_name are required for rename."
vdm_rename(desktop_name, new_name)
return f"Renamed desktop '{desktop_name}' to '{new_name}'"
- case 'switch':
+ case "switch":
if not desktop_name:
return "Error: desktop_name is required for switching."
vdm_switch(desktop_name)
diff --git a/windows_use/agent/tools/views.py b/windows_use/agent/tools/views.py
index 6d5b284..ea4950b 100644
--- a/windows_use/agent/tools/views.py
+++ b/windows_use/agent/tools/views.py
@@ -4,211 +4,229 @@ from pydantic import BaseModel, ConfigDict, Field
class SharedBaseModel(BaseModel):
-
- model_config = ConfigDict(extra='allow')
+ model_config = ConfigDict(extra="allow")
thought: str = Field(
...,
- description="The rigorous thinking process where you analyze the current state, potential issues, and plan the next steps effectively. (max. 3-5 sentences)"
+ description="The rigorous thinking process where you analyze the current state, potential issues, and plan the next steps effectively. (max. 3-5 sentences)",
)
+
class App(SharedBaseModel):
- mode: Literal['launch', 'resize', 'switch'] = Field(
- 'launch',
+ mode: Literal["launch", "resize", "switch"] = Field(
+ "launch",
description="Operation mode: 'launch' opens the application from Start Menu, 'resize' adjusts the active window's size and position, 'switch' brings a specific open window into the foreground",
- examples=['launch']
+ examples=["launch"],
)
name: str | None = Field(
description="Application name as it appears in Start Menu (for launch) or the window title as shown in the taskbar (for switch/resize). Example: 'Notepad' to launch, 'Untitled - Notepad' to switch.",
- examples=['Notepad', 'Google Chrome', 'Untitled - Notepad'],
- default=None
+ examples=["Notepad", "Google Chrome", "Untitled - Notepad"],
+ default=None,
)
loc: list[int] | None = Field(
description="Target [x, y] pixel coordinates for the window's top-left corner. Required for resize mode only.",
examples=[[0, 0]],
- default=None
+ default=None,
)
size: list[int] | None = Field(
description="Target [width, height] in pixels for the window dimensions. Required for resize mode only.",
examples=[[1920, 1080]],
- default=None
+ default=None,
)
+
class Done(SharedBaseModel):
answer: str = Field(
...,
description="The response to deliver to the user, formatted in markdown. This is the ONLY way to communicate with the user.",
- examples=["## Task Completed\n\nThe file has been saved to Desktop.", "Hello! How can I help you today?", "I was unable to find the file. The Downloads folder is empty."]
+ examples=[
+ "## Task Completed\n\nThe file has been saved to Desktop.",
+ "Hello! How can I help you today?",
+ "I was unable to find the file. The Downloads folder is empty.",
+ ],
)
+
class Memory(SharedBaseModel):
- mode: Literal['view', 'read', 'write', 'delete', 'update'] = Field(
+ mode: Literal["view", "read", "write", "delete", "update"] = Field(
description="Operation mode: 'view' lists all stored files, 'read' retrieves file content, 'write' creates a new file, 'update' modifies an existing file, 'delete' removes a file"
)
path: str | None = Field(
None,
- description="Relative file path from the .windows-use/memories directory (e.g., 'notes.md', 'project/data.md'). Required for read, write, update, and delete."
+ description="Relative file path from the .windows-use/memories directory (e.g., 'notes.md', 'project/data.md'). Required for read, write, update, and delete.",
)
content: str | None = Field(
None,
- description="Text content to write into the file. Required for 'write' mode and 'insert' operation in 'update' mode."
+ description="Text content to write into the file. Required for 'write' mode and 'insert' operation in 'update' mode.",
)
- operation: Literal['replace', 'insert'] | None = Field(
- 'replace',
- description="Update strategy: 'replace' finds old_str and substitutes it with new_str, 'insert' adds content at a specific line number. Only used in 'update' mode."
+ operation: Literal["replace", "insert"] | None = Field(
+ "replace",
+ description="Update strategy: 'replace' finds old_str and substitutes it with new_str, 'insert' adds content at a specific line number. Only used in 'update' mode.",
)
old_str: str | None = Field(
- None,
- description="Exact string to find in the file. Required when operation='replace'."
+ None, description="Exact string to find in the file. Required when operation='replace'."
)
new_str: str | None = Field(
- None,
- description="Replacement string. Required when operation='replace'."
+ None, description="Replacement string. Required when operation='replace'."
)
line_number: int | None = Field(
None,
- description="0-indexed line number where content will be inserted. Required when operation='insert'."
+ description="0-indexed line number where content will be inserted. Required when operation='insert'.",
)
read_range: list[int] | None = Field(
None,
- description="Optional [start, end] line range for partial reads (0-indexed, end exclusive). Example: [0, 10] reads lines 0 through 9."
+ description="Optional [start, end] line range for partial reads (0-indexed, end exclusive). Example: [0, 10] reads lines 0 through 9.",
)
+
class Click(SharedBaseModel):
loc: list[int] = Field(
...,
description="[x, y] pixel coordinates of the target element to click. Use coordinates from the Interactive Elements list.",
- examples=[[640, 360], [100, 200]]
+ examples=[[640, 360], [100, 200]],
)
- button: Literal['left', 'right', 'middle'] = Field(
+ button: Literal["left", "right", "middle"] = Field(
description="Mouse button: 'left' for standard clicks and selection, 'right' for context menus, 'middle' for middle-click actions",
- default='left',
- examples=['left', 'right']
+ default="left",
+ examples=["left", "right"],
)
clicks: Literal[0, 1, 2] = Field(
description="Number of clicks: 1 for single click (select, focus, press buttons), 2 for double click (open files, folders, apps), 0 for hover only (no click performed)",
default=1,
- examples=[1, 2]
+ examples=[1, 2],
)
+
class Shell(SharedBaseModel):
command: str = Field(
...,
description="PowerShell command to execute. Runs in the user's HOME directory. Use for file operations, system queries, installations, and automation tasks.",
examples=[
- 'Get-Process',
- 'ls Desktop',
- 'Get-ChildItem -Path C:\\Users -Recurse',
- 'echo "Hello World"'
- ]
+ "Get-Process",
+ "ls Desktop",
+ "Get-ChildItem -Path C:\\Users -Recurse",
+ 'echo "Hello World"',
+ ],
)
timeout: int | None = Field(
description="Maximum seconds to wait for command completion. Increase for long-running operations.",
default=10,
- examples=[10, 30, 60]
+ examples=[10, 30, 60],
)
+
class Type(SharedBaseModel):
loc: list[int] = Field(
...,
description="[x, y] pixel coordinates of the input field to type into. The tool clicks this location automatically before typing — do not pre-click.",
- examples=[[640, 360], [200, 150]]
+ examples=[[640, 360], [200, 150]],
)
text: str = Field(
...,
description="The text string to type into the element",
- examples=['hello world', '[email protected]', 'search query']
+ examples=["hello world", "[email protected]", "search query"],
)
clear: bool = Field(
description="If true, selects all existing text and replaces it. If false, appends to whatever is already in the field.",
default=False,
- examples=[True, False]
+ examples=[True, False],
)
- caret_position: Literal['start', 'idle', 'end'] = Field(
+ caret_position: Literal["start", "idle", "end"] = Field(
description="Where to position the text cursor before typing: 'start' moves to the beginning of the field, 'end' moves to the end, 'idle' leaves it where it is",
- default='idle',
- examples=['start', 'end', 'idle']
+ default="idle",
+ examples=["start", "end", "idle"],
)
press_enter: bool = Field(
description="If true, presses Enter after typing to submit the input (search, form, dialog). If false, leaves the cursor in the field.",
default=False,
- examples=[True, False]
+ examples=[True, False],
)
+
class MultiSelect(SharedBaseModel):
press_ctrl: bool = Field(
description="If true, holds Ctrl while clicking each element to accumulate a multi-selection (files, checkboxes, list items). If false, clicks each location sequentially without Ctrl.",
default=False,
- examples=[True, False]
+ examples=[True, False],
)
elements: list[list[int]] = Field(
...,
description="List of [x, y] pixel coordinates to click. Each coordinate pair is clicked in order.",
- examples=[[[640, 360], [800, 400]], [[100, 200], [200, 300]]]
+ examples=[[[640, 360], [800, 400]], [[100, 200], [200, 300]]],
)
+
class MultiEdit(SharedBaseModel):
elements: list[list] = Field(
...,
description="List of [x, y, text] entries. For each entry, clicks the location (x, y) and types the text. Use to fill multiple form fields in one action.",
- examples=[[[640, 360, 'hello'], [800, 400, 'world']], [[100, 200, 'John'], [200, 300, 'Doe']]]
+ examples=[
+ [[640, 360, "hello"], [800, 400, "world"]],
+ [[100, 200, "John"], [200, 300, "Doe"]],
+ ],
)
+
class Scroll(SharedBaseModel):
loc: list[int] | None = Field(
description="[x, y] pixel coordinates where scrolling occurs. If omitted, scrolls at the current cursor position.",
default=None,
- examples=[[640, 360], [800, 400]]
+ examples=[[640, 360], [800, 400]],
)
- type: Literal['horizontal', 'vertical'] = Field(
+ type: Literal["horizontal", "vertical"] = Field(
description="Scroll axis: 'vertical' for up/down scrolling, 'horizontal' for left/right scrolling",
- default='vertical',
- examples=['vertical', 'horizontal']
+ default="vertical",
+ examples=["vertical", "horizontal"],
)
- direction: Literal['up', 'down', 'left', 'right'] = Field(
+ direction: Literal["up", "down", "left", "right"] = Field(
description="Scroll direction: 'up' or 'down' for vertical, 'left' or 'right' for horizontal",
- default='down',
- examples=['down', 'up', 'right']
+ default="down",
+ examples=["down", "up", "right"],
)
wheel_times: int = Field(
description="Number of scroll increments. Each increment scrolls roughly 3-5 lines of text. Use 3-5 for moderate scrolling, 10+ for large jumps.",
default=1,
- examples=[1, 3, 5, 10]
+ examples=[1, 3, 5, 10],
)
+
class Move(SharedBaseModel):
loc: list[int] = Field(
...,
description="[x, y] pixel coordinates to move the mouse cursor to",
- examples=[[640, 360], [100, 100]]
+ examples=[[640, 360], [100, 100]],
)
drag: bool = Field(
description="If true, holds the left mouse button and drags from the current position to the target (drag-and-drop). If false, moves the cursor without clicking (hover).",
default=False,
- examples=[True, False]
+ examples=[True, False],
)
+
class Shortcut(SharedBaseModel):
shortcut: str = Field(
...,
description="Keyboard shortcut to press. Use '+' to combine keys for simultaneous press. Examples: 'ctrl+c' for copy, 'alt+tab' for window switch, 'enter' for confirm, 'escape' for cancel.",
- examples=['enter', 'escape', 'ctrl+c', 'ctrl+v', 'alt+tab', 'ctrl+shift+n', 'win']
+ examples=["enter", "escape", "ctrl+c", "ctrl+v", "alt+tab", "ctrl+shift+n", "win"],
)
+
class Wait(SharedBaseModel):
duration: int = Field(
...,
description="Number of seconds to pause. Use to wait for applications to launch, pages to load, or animations to finish before the next action.",
- examples=[2, 5, 10]
+ examples=[2, 5, 10],
)
+
class Scrape(SharedBaseModel):
url: str = Field(
...,
description="URL of the webpage currently open in the browser. The tool extracts visible text content from the rendered page via the accessibility tree and returns it as markdown.",
- examples=['https://google.com', 'https://example.com/page']
+ examples=["https://google.com", "https://example.com/page"],
)
+
class File(SharedBaseModel):
mode: Literal["read", "write", "list", "delete", "move", "copy", "exists"] = Field(
...,
@@ -228,7 +246,7 @@ class File(SharedBaseModel):
content: str | None = Field(
None,
description="Text content to write. Required when action is 'write'.",
- examples=["Hello world", "{\"key\": \"value\"}"],
+ examples=["Hello world", '{"key": "value"}'],
)
encoding: str | None = Field(
"utf-8",
@@ -238,18 +256,18 @@ class File(SharedBaseModel):
class Desktop(SharedBaseModel):
- action: Literal['create', 'remove', 'rename', 'switch'] = Field(
+ action: Literal["create", "remove", "rename", "switch"] = Field(
...,
description="Virtual desktop action: 'create' adds a new desktop, 'remove' deletes a desktop by name, 'rename' changes a desktop's name, 'switch' activates a desktop by name",
- examples=['create', 'switch', 'rename', 'remove']
+ examples=["create", "switch", "rename", "remove"],
)
desktop_name: str | None = Field(
description="Name of the target desktop. Required for remove, rename, and switch. Optional for create (auto-named if omitted).",
default=None,
- examples=["Desktop 1", "Work", "Research"]
+ examples=["Desktop 1", "Work", "Research"],
)
new_name: str | None = Field(
description="New name for the desktop. Required for rename only.",
default=None,
- examples=["My Workspace", "Project Alpha"]
+ examples=["My Workspace", "Project Alpha"],
)
diff --git a/windows_use/agent/tree/cache_utils.py b/windows_use/agent/tree/cache_utils.py
index ce7b790..d4017ef 100644
--- a/windows_use/agent/tree/cache_utils.py
+++ b/windows_use/agent/tree/cache_utils.py
@@ -95,6 +95,7 @@ class CacheRequestFactory:
return cache_request
+
class CachedControlHelper:
"""Helper class for working with cached controls."""
@@ -122,7 +123,9 @@ class CachedControlHelper:
return node
@staticmethod
- def get_cached_children(node: Control, cache_request: CacheRequest | None = None) -> list[Control]:
+ def get_cached_children(
+ node: Control, cache_request: CacheRequest | None = None
+ ) -> list[Control]:
"""
Get children with pre-cached properties.
diff --git a/windows_use/agent/tree/config.py b/windows_use/agent/tree/config.py
index e191632..74b64b4 100644
--- a/windows_use/agent/tree/config.py
+++ b/windows_use/agent/tree/config.py
@@ -1,83 +1,84 @@
-INTERACTIVE_CONTROL_TYPE_NAMES=set([
- 'ButtonControl',
- 'ListItemControl',
- 'MenuItemControl',
- 'EditControl',
- 'CheckBoxControl',
- 'RadioButtonControl',
- 'DocumentControl',
- 'ComboBoxControl',
- 'HyperlinkControl',
- 'SplitButtonControl',
- 'TabItemControl',
- 'TreeItemControl',
- 'DataItemControl',
- 'HeaderItemControl',
- 'TextBoxControl',
- 'SpinnerControl',
- 'ScrollBarControl',
- 'SliderControl'
-])
+INTERACTIVE_CONTROL_TYPE_NAMES = set(
+ [
+ "ButtonControl",
+ "ListItemControl",
+ "MenuItemControl",
+ "EditControl",
+ "CheckBoxControl",
+ "RadioButtonControl",
+ "DocumentControl",
+ "ComboBoxControl",
+ "HyperlinkControl",
+ "SplitButtonControl",
+ "TabItemControl",
+ "TreeItemControl",
+ "DataItemControl",
+ "HeaderItemControl",
+ "TextBoxControl",
+ "SpinnerControl",
+ "ScrollBarControl",
+ "SliderControl",
+ ]
+)
INTERACTIVE_ROLES = {
# Buttons
- 'PushButton', 'SplitButton', 'ButtonDropDown', 'ButtonMenu',
- 'ButtonDropDownGrid', 'OutlineButton',
-
+ "PushButton",
+ "SplitButton",
+ "ButtonDropDown",
+ "ButtonMenu",
+ "ButtonDropDownGrid",
+ "OutlineButton",
# Links
- 'Link',
-
+ "Link",
# Inputs & Selection
- 'Text', 'IpAddress', 'HotkeyField', 'ComboBox', 'DropList',
- 'CheckButton', 'RadioButton',
-
+ "Text",
+ "IpAddress",
+ "HotkeyField",
+ "ComboBox",
+ "DropList",
+ "CheckButton",
+ "RadioButton",
# Menus & Tabs
- 'MenuItem', 'ListItem', 'PageTab',
-
+ "MenuItem",
+ "ListItem",
+ "PageTab",
# Trees
- 'OutlineItem',
-
+ "OutlineItem",
# Values
- 'Slider', 'SpinButton', 'Dial', 'ScrollBar', 'Grip',
-
+ "Slider",
+ "SpinButton",
+ "Dial",
+ "ScrollBar",
+ "Grip",
# Grids
- 'ColumnHeader', 'RowHeader', 'Cell',
-
+ "ColumnHeader",
+ "RowHeader",
+ "Cell",
# Document
- 'Document'
+ "Document",
}
-DOCUMENT_CONTROL_TYPE_NAMES=set([
- 'DocumentControl'
-])
+DOCUMENT_CONTROL_TYPE_NAMES = set(["DocumentControl"])
-STRUCTURAL_CONTROL_TYPE_NAMES = set([
- 'PaneControl',
- 'GroupControl',
- 'CustomControl'
-])
+STRUCTURAL_CONTROL_TYPE_NAMES = set(["PaneControl", "GroupControl", "CustomControl"])
-INFORMATIVE_CONTROL_TYPE_NAMES=set([
- 'TextControl',
- 'ImageControl',
- 'StatusBarControl',
- # 'ProgressBarControl',
- # 'ToolTipControl',
- # 'TitleBarControl',
- # 'SeparatorControl',
- # 'HeaderControl',
- # 'HeaderItemControl',
-])
+INFORMATIVE_CONTROL_TYPE_NAMES = set(
+ [
+ "TextControl",
+ "ImageControl",
+ "StatusBarControl",
+ # 'ProgressBarControl',
+ # 'ToolTipControl',
+ # 'TitleBarControl',
+ # 'SeparatorControl',
+ # 'HeaderControl',
+ # 'HeaderItemControl',
+ ]
+)
-DEFAULT_ACTIONS=set([
- 'Click',
- 'Press',
- 'Jump',
- 'Check',
- 'Uncheck',
- 'Double Click',
- 'Expand',
- 'Collapse'
-])
+DEFAULT_ACTIONS = set(
+ ["Click", "Press", "Jump", "Check", "Uncheck", "Double Click", "Expand", "Collapse"]
+)
THREAD_MAX_RETRIES = 3
diff --git a/windows_use/agent/tree/service.py b/windows_use/agent/tree/service.py
index c6acaa9..9df9756 100644
--- a/windows_use/agent/tree/service.py
+++ b/windows_use/agent/tree/service.py
@@ -51,72 +51,105 @@ logger.setLevel(logging.INFO)
if TYPE_CHECKING:
from windows_use.agent.desktop.service import Desktop
+
class Tree:
- def __init__(self,desktop:'Desktop'):
- self.desktop=weakref.proxy(desktop)
- self.screen_size=desktop.get_screen_size()
- self.dom:Control | None=None
- self.dom_bounding_box:BoundingBox=None
- self.screen_box=BoundingBox(
- top=0, left=0, bottom=self.screen_size.height, right=self.screen_size.width,
- width=self.screen_size.width, height=self.screen_size.height
+ def __init__(self, desktop: "Desktop"):
+ self.desktop = weakref.proxy(desktop)
+ self.screen_size = desktop.get_screen_size()
+ self.dom: Control | None = None
+ self.dom_bounding_box: BoundingBox = None
+ self.screen_box = BoundingBox(
+ top=0,
+ left=0,
+ bottom=self.screen_size.height,
+ right=self.screen_size.width,
+ width=self.screen_size.width,
+ height=self.screen_size.height,
)
- self.tree_state=None
-
+ self.tree_state = None
- def get_state(self,active_window_handle:int|None,other_windows_handles:list[int])->TreeState:
+ def get_state(
+ self, active_window_handle: int | None, other_windows_handles: list[int]
+ ) -> TreeState:
# Reset DOM state to prevent leaks and stale data
self.dom = None
self.dom_bounding_box = None
start_time = perf_counter()
- active_window_flag=False
+ active_window_flag = False
if active_window_handle:
- active_window_flag=True
- windows_handles=[active_window_handle]+other_windows_handles
+ active_window_flag = True
+ windows_handles = [active_window_handle] + other_windows_handles
else:
- windows_handles=other_windows_handles
+ windows_handles = other_windows_handles
- interactive_nodes,scrollable_nodes,dom_informative_nodes,failed_handles=self.get_window_wise_nodes(windows_handles=windows_handles,active_window_flag=active_window_flag)
- root_node=TreeElementNode(
+ interactive_nodes, scrollable_nodes, dom_informative_nodes, failed_handles = (
+ self.get_window_wise_nodes(
+ windows_handles=windows_handles, active_window_flag=active_window_flag
+ )
+ )
+ root_node = TreeElementNode(
name="Desktop",
control_type="PaneControl",
bounding_box=self.screen_box,
center=self.screen_box.get_center(),
window_name="Desktop",
- metadata={}
+ metadata={},
)
if self.dom:
try:
- scroll_pattern:ScrollPattern=self.dom.GetCachedPattern(PatternId.ScrollPattern, True)
- metadata={
- 'horizontal_scrollable':scroll_pattern.HorizontallyScrollable if scroll_pattern else False,
- 'horizontal_scroll_percent':round(scroll_pattern.HorizontalScrollPercent,2) if scroll_pattern and scroll_pattern.HorizontallyScrollable else 0,
- 'vertical_scrollable':scroll_pattern.VerticallyScrollable if scroll_pattern else False,
- 'vertical_scroll_percent':round(scroll_pattern.VerticalScrollPercent,2) if scroll_pattern and scroll_pattern.VerticallyScrollable else 0,
+ scroll_pattern: ScrollPattern = self.dom.GetCachedPattern(
+ PatternId.ScrollPattern, True
+ )
+ metadata = {
+ "horizontal_scrollable": scroll_pattern.HorizontallyScrollable
+ if scroll_pattern
+ else False,
+ "horizontal_scroll_percent": round(scroll_pattern.HorizontalScrollPercent, 2)
+ if scroll_pattern and scroll_pattern.HorizontallyScrollable
+ else 0,
+ "vertical_scrollable": scroll_pattern.VerticallyScrollable
+ if scroll_pattern
+ else False,
+ "vertical_scroll_percent": round(scroll_pattern.VerticalScrollPercent, 2)
+ if scroll_pattern and scroll_pattern.VerticallyScrollable
+ else 0,
}
- dom_node=ScrollElementNode(**{
- 'name':'DOM',
- 'control_type':'DocumentControl',
- 'bounding_box':self.dom_bounding_box,
- 'center':self.dom_bounding_box.get_center(),
- 'window_name':'DOM',
- 'metadata':metadata
- })
+ dom_node = ScrollElementNode(
+ **{
+ "name": "DOM",
+ "control_type": "DocumentControl",
+ "bounding_box": self.dom_bounding_box,
+ "center": self.dom_bounding_box.get_center(),
+ "window_name": "DOM",
+ "metadata": metadata,
+ }
+ )
except Exception as e:
logger.debug(f"Failed to get DOM scroll pattern: {e}")
- dom_node=None
+ dom_node = None
else:
- dom_node=None
+ dom_node = None
# Detect if tree capture failed for any windows
status = len(failed_handles) == 0
if not status:
- logger.warning(f"[Tree] {len(failed_handles)} window(s) failed to capture — UI services may be loading")
+ logger.warning(
+ f"[Tree] {len(failed_handles)} window(s) failed to capture — UI services may be loading"
+ )
end_time = perf_counter()
logger.debug(f"[Tree] Tree State capture took {end_time - start_time:.2f} seconds")
- return TreeState(status=status,root_node=root_node,dom_node=dom_node,interactive_nodes=interactive_nodes,scrollable_nodes=scrollable_nodes,dom_informative_nodes=dom_informative_nodes)
+ return TreeState(
+ status=status,
+ root_node=root_node,
+ dom_node=dom_node,
+ interactive_nodes=interactive_nodes,
+ scrollable_nodes=scrollable_nodes,
+ dom_informative_nodes=dom_informative_nodes,
+ )
- def get_window_wise_nodes(self,windows_handles:list[int],active_window_flag:bool) -> tuple[list[TreeElementNode],list[ScrollElementNode],list[TextElementNode],list[int]]:
+ def get_window_wise_nodes(
+ self, windows_handles: list[int], active_window_flag: bool
+ ) -> tuple[list[TreeElementNode], list[ScrollElementNode], list[TextElementNode], list[int]]:
"""Process windows sequentially to avoid COM apartment threading deadlock.
UI Automation requires STA (Single-Threaded Apartment). Using ThreadPoolExecutor
@@ -144,7 +177,11 @@ class Tree:
for handle, is_browser in task_inputs:
for attempt in range(THREAD_MAX_RETRIES + 1):
try:
- result = self.get_nodes(handle, is_browser, wait_time=0.5 * (2 ** (attempt - 1)) if attempt > 0 else 0)
+ result = self.get_nodes(
+ handle,
+ is_browser,
+ wait_time=0.5 * (2 ** (attempt - 1)) if attempt > 0 else 0,
+ )
if result:
element_nodes, scroll_nodes, info_nodes = result
interactive_nodes.extend(element_nodes)
@@ -165,11 +202,13 @@ class Tree:
f"retry attempt {retry_counts[handle]}/{THREAD_MAX_RETRIES}\nError: {e}"
)
if attempt < THREAD_MAX_RETRIES:
- wait_time = 0.5 * (2 ** attempt)
+ wait_time = 0.5 * (2**attempt)
logger.debug(f"Retrying window {handle} in {wait_time}s...")
sleep(wait_time)
else:
- logger.error(f"Task failed completely for handle {handle} after {THREAD_MAX_RETRIES} retries")
+ logger.error(
+ f"Task failed completely for handle {handle} after {THREAD_MAX_RETRIES} retries"
+ )
failed_handles.append(handle)
break
@@ -184,115 +223,148 @@ class Tree:
right=clipped.right,
bottom=clipped.bottom,
width=clipped.width(),
- height=clipped.height()
+ height=clipped.height(),
)
return BoundingBox(left=0, top=0, right=0, bottom=0, width=0, height=0)
-
-
- def element_has_child_element(self, node:Control,control_type:str,child_control_type:str):
+ def element_has_child_element(self, node: Control, control_type: str, child_control_type: str):
# node is cached — use cached property
- if node.CachedLocalizedControlType==control_type:
- first_child=node.GetFirstChildControl()
+ if node.CachedLocalizedControlType == control_type:
+ first_child = node.GetFirstChildControl()
if first_child is None:
return False
# first_child from GetFirstChildControl() is NOT cached — use live access
- return first_child.LocalizedControlType==child_control_type
-
- def _dom_correction(self, node:Control, dom_interactive_nodes:list[TreeElementNode], window_name:str):
- if self.element_has_child_element(node,'list item','link') or self.element_has_child_element(node,'item','link') or self.element_has_child_element(node,"option","button"):
+ return first_child.LocalizedControlType == child_control_type
+
+ def _dom_correction(
+ self, node: Control, dom_interactive_nodes: list[TreeElementNode], window_name: str
+ ):
+ if (
+ self.element_has_child_element(node, "list item", "link")
+ or self.element_has_child_element(node, "item", "link")
+ or self.element_has_child_element(node, "option", "button")
+ ):
dom_interactive_nodes.pop()
return None
- elif node.CachedControlTypeName=='GroupControl':
- popped=dom_interactive_nodes.pop()
+ elif node.CachedControlTypeName == "GroupControl":
+ popped = dom_interactive_nodes.pop()
# Inlined is_keyboard_focusable logic for correction
control_type_name_check = node.CachedControlTypeName
is_kb_focusable = False
- if control_type_name_check in set(['EditControl','ButtonControl','CheckBoxControl','RadioButtonControl','TabItemControl']):
- is_kb_focusable = True
+ if control_type_name_check in set(
+ [
+ "EditControl",
+ "ButtonControl",
+ "CheckBoxControl",
+ "RadioButtonControl",
+ "TabItemControl",
+ ]
+ ):
+ is_kb_focusable = True
else:
- is_kb_focusable = node.CachedIsKeyboardFocusable
+ is_kb_focusable = node.CachedIsKeyboardFocusable
if is_kb_focusable:
- child=node
+ child = node
try:
while child.GetFirstChildControl() is not None:
# Children from GetFirstChildControl() are NOT cached — use live access
if child.ControlTypeName in INTERACTIVE_CONTROL_TYPE_NAMES:
return None
- child=child.GetFirstChildControl()
+ child = child.GetFirstChildControl()
except Exception:
return None
- if child.ControlTypeName!='TextControl':
+ if child.ControlTypeName != "TextControl":
return None
- metadata:dict[str,Any]={}
+ metadata: dict[str, Any] = {}
# node is cached — use cached properties
element_bounding_box = node.CachedBoundingRectangle
- bounding_box=self.iou_bounding_box(self.dom_bounding_box,element_bounding_box)
+ bounding_box = self.iou_bounding_box(self.dom_bounding_box, element_bounding_box)
center = bounding_box.get_center()
- has_focused=node.CachedHasKeyboardFocus
- accelerator_key=node.CachedAcceleratorKey
- metadata['has_focused']=has_focused
+ has_focused = node.CachedHasKeyboardFocus
+ accelerator_key = node.CachedAcceleratorKey
+ metadata["has_focused"] = has_focused
if accelerator_key:
- metadata['shortcut']=accelerator_key
+ metadata["shortcut"] = accelerator_key
- if isinstance(node,EditControl):
+ if isinstance(node, EditControl):
try:
- value = node.GetCachedPropertyValue(PropertyId.LegacyIAccessibleValueProperty)
- metadata['value']=value.strip() if value else '(empty)'
+ value = node.GetCachedPropertyValue(
+ PropertyId.LegacyIAccessibleValueProperty
+ )
+ metadata["value"] = value.strip() if value else "(empty)"
except Exception:
pass
try:
help_text = node.CachedHelpText
if help_text:
- metadata['help_text']=help_text.encode('ascii', 'ignore').decode('ascii')
+ metadata["help_text"] = help_text.encode("ascii", "ignore").decode(
+ "ascii"
+ )
except Exception:
pass
- dom_interactive_nodes.append(TreeElementNode(**{
- 'name':(child.Name or '').strip(),
- 'control_type':node.CachedLocalizedControlType,
- 'bounding_box':bounding_box,
- 'center':center,
- 'window_name':window_name,
- 'hwnd':popped.hwnd,
- 'control':node,
- 'metadata':metadata
- }))
- elif self.element_has_child_element(node,'link','heading'):
- popped=dom_interactive_nodes.pop()
+ dom_interactive_nodes.append(
+ TreeElementNode(
+ **{
+ "name": (child.Name or "").strip(),
+ "control_type": node.CachedLocalizedControlType,
+ "bounding_box": bounding_box,
+ "center": center,
+ "window_name": window_name,
+ "hwnd": popped.hwnd,
+ "control": node,
+ "metadata": metadata,
+ }
+ )
+ )
+ elif self.element_has_child_element(node, "link", "heading"):
+ popped = dom_interactive_nodes.pop()
# child from GetFirstChildControl() is NOT cached — use live access
- node=node.GetFirstChildControl()
- control_type='link'
- value = node.GetPropertyValue(PropertyId.LegacyIAccessibleValueProperty) or ''
+ node = node.GetFirstChildControl()
+ control_type = "link"
+ value = node.GetPropertyValue(PropertyId.LegacyIAccessibleValueProperty) or ""
element_bounding_box = node.BoundingRectangle
- bounding_box=self.iou_bounding_box(self.dom_bounding_box,element_bounding_box)
+ bounding_box = self.iou_bounding_box(self.dom_bounding_box, element_bounding_box)
center = bounding_box.get_center()
- is_focused=node.HasKeyboardFocus
- metadata:dict[str,Any]={}
- metadata['has_focused']=is_focused
- dom_interactive_nodes.append(TreeElementNode(**{
- 'name':(node.Name or '').strip(),
- 'control_type':control_type,
- 'bounding_box':bounding_box,
- 'center':center,
- 'window_name':window_name,
- 'hwnd':popped.hwnd,
- 'control':node,
- 'metadata':metadata
- }))
-
-
- def tree_traversal(self, node: Control, window_bounding_box:Rect, window_name:str, is_browser:bool,
- interactive_nodes:list[TreeElementNode] | None=None, scrollable_nodes:list[ScrollElementNode] | None=None,
- dom_interactive_nodes:list[TreeElementNode] | None=None, dom_informative_nodes:list[TextElementNode] | None=None,
- is_dom:bool=False, is_dialog:bool=False,
- element_cache_req:Any | None=None, children_cache_req:Any | None=None,
- hwnd:int=0):
+ is_focused = node.HasKeyboardFocus
+ metadata: dict[str, Any] = {}
+ metadata["has_focused"] = is_focused
+ dom_interactive_nodes.append(
+ TreeElementNode(
+ **{
+ "name": (node.Name or "").strip(),
+ "control_type": control_type,
+ "bounding_box": bounding_box,
+ "center": center,
+ "window_name": window_name,
+ "hwnd": popped.hwnd,
+ "control": node,
+ "metadata": metadata,
+ }
+ )
+ )
+
+ def tree_traversal(
+ self,
+ node: Control,
+ window_bounding_box: Rect,
+ window_name: str,
+ is_browser: bool,
+ interactive_nodes: list[TreeElementNode] | None = None,
+ scrollable_nodes: list[ScrollElementNode] | None = None,
+ dom_interactive_nodes: list[TreeElementNode] | None = None,
+ dom_informative_nodes: list[TextElementNode] | None = None,
+ is_dom: bool = False,
+ is_dialog: bool = False,
+ element_cache_req: Any | None = None,
+ children_cache_req: Any | None = None,
+ hwnd: int = 0,
+ ):
try:
# Build cached control if caching is enabled
- if not hasattr(node, '_is_cached') and element_cache_req:
+ if not hasattr(node, "_is_cached") and element_cache_req:
node = CachedControlHelper.build_cached_control(node, element_cache_req)
# Checks to skip the nodes that are not interactive
@@ -302,39 +374,61 @@ class Tree:
# Scrollable check
if scrollable_nodes is not None:
- if (control_type_name not in (INTERACTIVE_CONTROL_TYPE_NAMES|INFORMATIVE_CONTROL_TYPE_NAMES)) and not is_offscreen:
+ if (
+ control_type_name
+ not in (INTERACTIVE_CONTROL_TYPE_NAMES | INFORMATIVE_CONTROL_TYPE_NAMES)
+ ) and not is_offscreen:
try:
- scroll_pattern:ScrollPattern=node.GetCachedPattern(PatternId.ScrollPattern, True)
+ scroll_pattern: ScrollPattern = node.GetCachedPattern(
+ PatternId.ScrollPattern, True
+ )
if scroll_pattern and scroll_pattern.VerticallyScrollable:
box = node.CachedBoundingRectangle
- x,y=random_point_within_bounding_box(node=node,scale_factor=0.8)
- center = Center(x=x,y=y)
+ x, y = random_point_within_bounding_box(node=node, scale_factor=0.8)
+ center = Center(x=x, y=y)
name = node.CachedName
automation_id = node.CachedAutomationId
localized_control_type = node.CachedLocalizedControlType
- metadata:dict[str,Any]={}
- metadata['has_focused']=node.CachedHasKeyboardFocus
- scrollable_nodes.append(ScrollElementNode(**{
- 'name':(name or '').strip() or automation_id or localized_control_type.capitalize() or "''",
- 'control_type':localized_control_type.title(),
- 'bounding_box':BoundingBox(**{
- 'left':box.left,
- 'top':box.top,
- 'right':box.right,
- 'bottom':box.bottom,
- 'width':box.width(),
- 'height':box.height()
- }),
- 'center':center,
- 'horizontal_scrollable':scroll_pattern.HorizontallyScrollable,
- 'horizontal_scroll_percent':round(scroll_pattern.HorizontalScrollPercent,2) if scroll_pattern.HorizontallyScrollable else 0,
- 'vertical_scrollable':scroll_pattern.VerticallyScrollable,
- 'vertical_scroll_percent':round(scroll_pattern.VerticalScrollPercent,2) if scroll_pattern.VerticallyScrollable else 0,
- 'window_name':window_name,
- 'hwnd':hwnd,
- 'control':node,
- 'metadata':metadata
- }))
+ metadata: dict[str, Any] = {}
+ metadata["has_focused"] = node.CachedHasKeyboardFocus
+ scrollable_nodes.append(
+ ScrollElementNode(
+ **{
+ "name": (name or "").strip()
+ or automation_id
+ or localized_control_type.capitalize()
+ or "''",
+ "control_type": localized_control_type.title(),
+ "bounding_box": BoundingBox(
+ **{
+ "left": box.left,
+ "top": box.top,
+ "right": box.right,
+ "bottom": box.bottom,
+ "width": box.width(),
+ "height": box.height(),
+ }
+ ),
+ "center": center,
+ "horizontal_scrollable": scroll_pattern.HorizontallyScrollable,
+ "horizontal_scroll_percent": round(
+ scroll_pattern.HorizontalScrollPercent, 2
+ )
+ if scroll_pattern.HorizontallyScrollable
+ else 0,
+ "vertical_scrollable": scroll_pattern.VerticallyScrollable,
+ "vertical_scroll_percent": round(
+ scroll_pattern.VerticalScrollPercent, 2
+ )
+ if scroll_pattern.VerticallyScrollable
+ else 0,
+ "window_name": window_name,
+ "hwnd": hwnd,
+ "control": node,
+ "metadata": metadata,
+ }
+ )
+ )
except Exception:
pass
@@ -347,227 +441,305 @@ class Tree:
area = width * height
# Is Visible Check
- is_visible = (area > 0) and (not is_offscreen or control_type_name=="EditControl" or (control_type_name=="ListItemControl" and is_browser)) and is_control_element
+ is_visible = (
+ (area > 0)
+ and (
+ not is_offscreen
+ or control_type_name == "EditControl"
+ or (control_type_name == "ListItemControl" and is_browser)
+ )
+ and is_control_element
+ )
if is_visible:
is_enabled = node.CachedIsEnabled
if is_enabled:
# Determine is_keyboard_focusable
- if control_type_name in set(['EditControl','ButtonControl','CheckBoxControl','RadioButtonControl','TabItemControl','ListItemControl']):
+ if control_type_name in set(
+ [
+ "EditControl",
+ "ButtonControl",
+ "CheckBoxControl",
+ "RadioButtonControl",
+ "TabItemControl",
+ "ListItemControl",
+ ]
+ ):
is_keyboard_focusable = True
else:
- #Experimentally, ListItemControl is keyboard focusable
+ # Experimentally, ListItemControl is keyboard focusable
is_keyboard_focusable = node.CachedIsKeyboardFocusable
# Interactive Check
if interactive_nodes is not None:
is_interactive = False
- if is_browser and control_type_name in set(['DataItemControl']) and not is_keyboard_focusable:
+ if (
+ is_browser
+ and control_type_name in set(["DataItemControl"])
+ and not is_keyboard_focusable
+ ):
is_interactive = False
- elif not is_browser and control_type_name == "ImageControl" and is_keyboard_focusable:
+ elif (
+ not is_browser
+ and control_type_name == "ImageControl"
+ and is_keyboard_focusable
+ ):
is_interactive = True
- elif control_type_name in (INTERACTIVE_CONTROL_TYPE_NAMES|DOCUMENT_CONTROL_TYPE_NAMES):
- # Role check
- try:
- role = node.GetCachedPropertyValue(PropertyId.LegacyIAccessibleRoleProperty)
- is_role_interactive = AccessibleRoleNames.get(role, "Default") in INTERACTIVE_ROLES
- except Exception:
+ elif control_type_name in (
+ INTERACTIVE_CONTROL_TYPE_NAMES | DOCUMENT_CONTROL_TYPE_NAMES
+ ):
+ # Role check
+ try:
+ role = node.GetCachedPropertyValue(
+ PropertyId.LegacyIAccessibleRoleProperty
+ )
+ is_role_interactive = (
+ AccessibleRoleNames.get(role, "Default") in INTERACTIVE_ROLES
+ )
+ except Exception:
is_role_interactive = False
- # Image check
- is_image = False
- if control_type_name == 'ImageControl': # approximated
- localized = node.CachedLocalizedControlType
- if localized == 'graphic' or not is_keyboard_focusable:
- is_image = True
+ # Image check
+ is_image = False
+ if control_type_name == "ImageControl": # approximated
+ localized = node.CachedLocalizedControlType
+ if localized == "graphic" or not is_keyboard_focusable:
+ is_image = True
- if is_role_interactive and (not is_image or is_keyboard_focusable):
- is_interactive = True
+ if is_role_interactive and (not is_image or is_keyboard_focusable):
+ is_interactive = True
- elif control_type_name == 'GroupControl':
- if is_browser:
+ elif control_type_name == "GroupControl":
+ if is_browser:
try:
- has_expand_collapse = node.GetCachedPropertyValue(PropertyId.ExpandCollapseExpandCollapseStateProperty)
+ has_expand_collapse = node.GetCachedPropertyValue(
+ PropertyId.ExpandCollapseExpandCollapseStateProperty
+ )
if has_expand_collapse in ExpandCollapseState:
is_interactive = True
except Exception:
pass
try:
- role = node.GetCachedPropertyValue(PropertyId.LegacyIAccessibleRoleProperty)
- is_role_interactive = AccessibleRoleNames.get(role, "Default") in INTERACTIVE_ROLES
+ role = node.GetCachedPropertyValue(
+ PropertyId.LegacyIAccessibleRoleProperty
+ )
+ is_role_interactive = (
+ AccessibleRoleNames.get(role, "Default")
+ in INTERACTIVE_ROLES
+ )
except Exception:
is_role_interactive = False
is_default_action = False
try:
- default_action = node.GetCachedPropertyValue(PropertyId.LegacyIAccessibleDefaultActionProperty)
+ default_action = node.GetCachedPropertyValue(
+ PropertyId.LegacyIAccessibleDefaultActionProperty
+ )
if default_action and default_action.title() in DEFAULT_ACTIONS:
is_default_action = True
except Exception:
pass
- if is_role_interactive and (is_default_action or is_keyboard_focusable):
+ if is_role_interactive and (
+ is_default_action or is_keyboard_focusable
+ ):
is_interactive = True
if is_interactive:
is_focused = node.CachedHasKeyboardFocus
- name = (node.CachedName or '').strip()
+ name = (node.CachedName or "").strip()
localized_control_type = node.CachedLocalizedControlType
accelerator_key = node.CachedAcceleratorKey
- metadata:dict[str,Any]={}
- metadata['has_focused']=is_focused
+ metadata: dict[str, Any] = {}
+ metadata["has_focused"] = is_focused
if accelerator_key:
- metadata['shortcut']=accelerator_key
+ metadata["shortcut"] = accelerator_key
try:
help_text = node.CachedHelpText
if help_text:
- metadata['help_text']=help_text.encode('ascii', 'ignore').decode('ascii')
+ metadata["help_text"] = help_text.encode(
+ "ascii", "ignore"
+ ).decode("ascii")
except Exception:
pass
- if isinstance(node,(ButtonControl,CheckBoxControl)):
+ if isinstance(node, (ButtonControl, CheckBoxControl)):
try:
- toggle_state = node.GetCachedPropertyValue(PropertyId.ToggleToggleStateProperty)
+ toggle_state = node.GetCachedPropertyValue(
+ PropertyId.ToggleToggleStateProperty
+ )
if toggle_state is not None:
match toggle_state:
case ToggleState.On:
- metadata['toggle_state'] = 'on'
+ metadata["toggle_state"] = "on"
case ToggleState.Off:
- metadata['toggle_state'] = 'off'
+ metadata["toggle_state"] = "off"
case _:
pass
except Exception:
pass
- if isinstance(node,EditControl):
+ if isinstance(node, EditControl):
try:
- value = node.GetCachedPropertyValue(PropertyId.LegacyIAccessibleValueProperty)
- metadata['value']=value.strip() if value else '(empty)'
+ value = node.GetCachedPropertyValue(
+ PropertyId.LegacyIAccessibleValueProperty
+ )
+ metadata["value"] = value.strip() if value else "(empty)"
except Exception:
pass
try:
if node.CachedIsPassword:
- metadata['is_password']=True
+ metadata["is_password"] = True
except Exception:
pass
- if isinstance(node,ComboBoxControl):
+ if isinstance(node, ComboBoxControl):
try:
- control_state=node.GetCachedPropertyValue(PropertyId.ExpandCollapseExpandCollapseStateProperty)
+ control_state = node.GetCachedPropertyValue(
+ PropertyId.ExpandCollapseExpandCollapseStateProperty
+ )
match control_state:
case ExpandCollapseState.Expanded:
- metadata['expand_collapse_state']='expanded'
+ metadata["expand_collapse_state"] = "expanded"
case ExpandCollapseState.Collapsed:
- metadata['expand_collapse_state']='collapsed'
+ metadata["expand_collapse_state"] = "collapsed"
case ExpandCollapseState.PartiallyExpanded:
- metadata['expand_collapse_state']='partially expanded'
+ metadata["expand_collapse_state"] = "partially expanded"
case _:
pass
except Exception:
pass
try:
- can_select_multiple=node.GetCachedPropertyValue(PropertyId.SelectionCanSelectMultipleProperty)
- metadata['is_selection_required']=can_select_multiple
+ can_select_multiple = node.GetCachedPropertyValue(
+ PropertyId.SelectionCanSelectMultipleProperty
+ )
+ metadata["is_selection_required"] = can_select_multiple
except Exception:
pass
try:
- is_selection_required=node.GetCachedPropertyValue(PropertyId.SelectionIsSelectionRequiredProperty)
- metadata['is_selection_required']=is_selection_required
+ is_selection_required = node.GetCachedPropertyValue(
+ PropertyId.SelectionIsSelectionRequiredProperty
+ )
+ metadata["is_selection_required"] = is_selection_required
except Exception:
pass
try:
- is_selected=node.GetCachedPropertyValue(PropertyId.SelectionItemIsSelectedProperty)
- metadata['is_selected']=is_selected
+ is_selected = node.GetCachedPropertyValue(
+ PropertyId.SelectionItemIsSelectedProperty
+ )
+ metadata["is_selected"] = is_selected
except Exception:
pass
try:
- selection_raw = node.GetCachedPropertyValue(PropertyId.SelectionSelectionProperty)
- selected_items = Control.CreateControlsFromRawElementArray(selection_raw)
- selected_names = [item.Name for item in selected_items if item.Name]
+ selection_raw = node.GetCachedPropertyValue(
+ PropertyId.SelectionSelectionProperty
+ )
+ selected_items = Control.CreateControlsFromRawElementArray(
+ selection_raw
+ )
+ selected_names = [
+ item.Name for item in selected_items if item.Name
+ ]
if selected_names:
- metadata['selection'] = selected_names
+ metadata["selection"] = selected_names
except Exception:
pass
if isinstance(node, SliderControl):
try:
- value = node.GetCachedPropertyValue(PropertyId.RangeValueValueProperty)
- minimum = node.GetCachedPropertyValue(PropertyId.RangeValueMinimumProperty)
- maximum = node.GetCachedPropertyValue(PropertyId.RangeValueMaximumProperty)
+ value = node.GetCachedPropertyValue(
+ PropertyId.RangeValueValueProperty
+ )
+ minimum = node.GetCachedPropertyValue(
+ PropertyId.RangeValueMinimumProperty
+ )
+ maximum = node.GetCachedPropertyValue(
+ PropertyId.RangeValueMaximumProperty
+ )
if value is not None:
- metadata['value'] = round(value, 2)
+ metadata["value"] = round(value, 2)
if minimum is not None:
- metadata['min'] = round(minimum, 2)
+ metadata["min"] = round(minimum, 2)
if maximum is not None:
- metadata['max'] = round(maximum, 2)
+ metadata["max"] = round(maximum, 2)
except Exception:
pass
if is_browser and is_dom:
- bounding_box=self.iou_bounding_box(self.dom_bounding_box,element_bounding_box)
+ bounding_box = self.iou_bounding_box(
+ self.dom_bounding_box, element_bounding_box
+ )
center = bounding_box.get_center()
- tree_node=TreeElementNode(**{
- 'name':name,
- 'control_type':localized_control_type.title(),
- 'bounding_box':bounding_box,
- 'center':center,
- 'window_name':window_name,
- 'hwnd':hwnd,
- 'control':node,
- 'metadata':metadata
- })
+ tree_node = TreeElementNode(
+ **{
+ "name": name,
+ "control_type": localized_control_type.title(),
+ "bounding_box": bounding_box,
+ "center": center,
+ "window_name": window_name,
+ "hwnd": hwnd,
+ "control": node,
+ "metadata": metadata,
+ }
+ )
dom_interactive_nodes.append(tree_node)
self._dom_correction(node, dom_interactive_nodes, window_name)
else:
- bounding_box=self.iou_bounding_box(window_bounding_box,element_bounding_box)
+ bounding_box = self.iou_bounding_box(
+ window_bounding_box, element_bounding_box
+ )
center = bounding_box.get_center()
- tree_node=TreeElementNode(**{
- 'name':name,
- 'control_type':localized_control_type.title(),
- 'bounding_box':bounding_box,
- 'center':center,
- 'window_name':window_name,
- 'hwnd':hwnd,
- 'control':node,
- 'metadata':metadata
- })
+ tree_node = TreeElementNode(
+ **{
+ "name": name,
+ "control_type": localized_control_type.title(),
+ "bounding_box": bounding_box,
+ "center": center,
+ "window_name": window_name,
+ "hwnd": hwnd,
+ "control": node,
+ "metadata": metadata,
+ }
+ )
interactive_nodes.append(tree_node)
# Informative Check
if dom_informative_nodes is not None:
- # is_element_text check
- is_text = False
- if control_type_name in INFORMATIVE_CONTROL_TYPE_NAMES:
- # is_element_image check
- is_image_check = False
- if control_type_name == 'ImageControl':
- localized = node.CachedLocalizedControlType
-
- if not is_keyboard_focusable:
- if localized == 'graphic':
- is_image_check = True
- else:
- is_image_check = True
- elif localized == 'graphic':
+ # is_element_text check
+ is_text = False
+ if control_type_name in INFORMATIVE_CONTROL_TYPE_NAMES:
+ # is_element_image check
+ is_image_check = False
+ if control_type_name == "ImageControl":
+ localized = node.CachedLocalizedControlType
+
+ if not is_keyboard_focusable:
+ if localized == "graphic":
is_image_check = True
+ else:
+ is_image_check = True
+ elif localized == "graphic":
+ is_image_check = True
- if not is_image_check:
- is_text = True
+ if not is_image_check:
+ is_text = True
- if is_text:
- if is_browser and is_dom:
- name = node.CachedName
- dom_informative_nodes.append(TextElementNode(
- text=(name or '').strip(),
- ))
+ if is_text:
+ if is_browser and is_dom:
+ name = node.CachedName
+ dom_informative_nodes.append(
+ TextElementNode(
+ text=(name or "").strip(),
+ )
+ )
# Phase 3: Cached Children Retrieval
children = CachedControlHelper.get_cached_children(node, children_cache_req)
@@ -579,103 +751,177 @@ class Tree:
for orig_idx, child in traversal:
# Check if the child is a DOM element
- if is_browser and child.CachedAutomationId=="RootWebArea":
- bounding_box=child.CachedBoundingRectangle
- self.dom_bounding_box=BoundingBox(left=bounding_box.left,top=bounding_box.top,
- right=bounding_box.right,bottom=bounding_box.bottom,width=bounding_box.width(),
- height=bounding_box.height())
- self.dom=child
+ if is_browser and child.CachedAutomationId == "RootWebArea":
+ bounding_box = child.CachedBoundingRectangle
+ self.dom_bounding_box = BoundingBox(
+ left=bounding_box.left,
+ top=bounding_box.top,
+ right=bounding_box.right,
+ bottom=bounding_box.bottom,
+ width=bounding_box.width(),
+ height=bounding_box.height(),
+ )
+ self.dom = child
# enter DOM subtree
- self.tree_traversal(child, window_bounding_box, window_name, is_browser, interactive_nodes, scrollable_nodes, dom_interactive_nodes, dom_informative_nodes, is_dom=True, is_dialog=is_dialog, element_cache_req=element_cache_req, children_cache_req=children_cache_req, hwnd=hwnd)
+ self.tree_traversal(
+ child,
+ window_bounding_box,
+ window_name,
+ is_browser,
+ interactive_nodes,
+ scrollable_nodes,
+ dom_interactive_nodes,
+ dom_informative_nodes,
+ is_dom=True,
+ is_dialog=is_dialog,
+ element_cache_req=element_cache_req,
+ children_cache_req=children_cache_req,
+ hwnd=hwnd,
+ )
# Check if the child is a dialog
- elif isinstance(child,WindowControl):
+ elif isinstance(child, WindowControl):
if not child.CachedIsOffscreen:
if is_dom:
- bounding_box=child.CachedBoundingRectangle
- if bounding_box.width() > 0.8*self.dom_bounding_box.width:
+ bounding_box = child.CachedBoundingRectangle
+ if bounding_box.width() > 0.8 * self.dom_bounding_box.width:
# Because this window element covers the majority of the screen
dom_interactive_nodes.clear()
else:
# Inline is_window_modal
is_modal = False
try:
- is_modal = child.GetCachedPropertyValue(PropertyId.WindowIsModalProperty)
+ is_modal = child.GetCachedPropertyValue(
+ PropertyId.WindowIsModalProperty
+ )
except Exception:
is_modal = False
if is_modal:
interactive_nodes.clear()
# enter dialog subtree
- self.tree_traversal(child, window_bounding_box, window_name, is_browser, interactive_nodes, scrollable_nodes, dom_interactive_nodes, dom_informative_nodes, is_dom=is_dom, is_dialog=True, element_cache_req=element_cache_req, children_cache_req=children_cache_req, hwnd=hwnd)
+ self.tree_traversal(
+ child,
+ window_bounding_box,
+ window_name,
+ is_browser,
+ interactive_nodes,
+ scrollable_nodes,
+ dom_interactive_nodes,
+ dom_informative_nodes,
+ is_dom=is_dom,
+ is_dialog=True,
+ element_cache_req=element_cache_req,
+ children_cache_req=children_cache_req,
+ hwnd=hwnd,
+ )
else:
# normal non-dialog children
- self.tree_traversal(child, window_bounding_box, window_name, is_browser, interactive_nodes, scrollable_nodes, dom_interactive_nodes, dom_informative_nodes, is_dom=is_dom, is_dialog=is_dialog, element_cache_req=element_cache_req, children_cache_req=children_cache_req, hwnd=hwnd)
+ self.tree_traversal(
+ child,
+ window_bounding_box,
+ window_name,
+ is_browser,
+ interactive_nodes,
+ scrollable_nodes,
+ dom_interactive_nodes,
+ dom_informative_nodes,
+ is_dom=is_dom,
+ is_dialog=is_dialog,
+ element_cache_req=element_cache_req,
+ children_cache_req=children_cache_req,
+ hwnd=hwnd,
+ )
except UIAException:
raise
except COMError as e:
raise from_com_error(e) from e
- def window_name_correction(self,window_name:str)->str:
+ def window_name_correction(self, window_name: str) -> str:
match window_name:
case "Progman":
return "Desktop"
- case 'Shell_TrayWnd'|'Shell_SecondaryTrayWnd':
+ case "Shell_TrayWnd" | "Shell_SecondaryTrayWnd":
return "Taskbar"
- case 'Microsoft.UI.Content.PopupWindowSiteBridge':
+ case "Microsoft.UI.Content.PopupWindowSiteBridge":
return "Context Menu"
case _:
return window_name
- def get_nodes(self, handle: int, is_browser:bool=False, wait_time:float=0) -> tuple[list[TreeElementNode],list[ScrollElementNode],list[TextElementNode]]:
+ def get_nodes(
+ self, handle: int, is_browser: bool = False, wait_time: float = 0
+ ) -> tuple[list[TreeElementNode], list[ScrollElementNode], list[TextElementNode]]:
if wait_time > 0:
sleep(wait_time)
try:
node = ControlFromHandle(handle)
if not node:
- raise Exception("Failed to create Control from handle")
+ raise Exception("Failed to create Control from handle")
# Create fresh cache requests for this traversal session
element_cache_req = CacheRequestFactory.create_tree_traversal_cache()
element_cache_req.TreeScope = TreeScope.TreeScope_Element
children_cache_req = CacheRequestFactory.create_tree_traversal_cache()
- children_cache_req.TreeScope = TreeScope.TreeScope_Element | TreeScope.TreeScope_Children
-
- window_bounding_box=node.BoundingRectangle
+ children_cache_req.TreeScope = (
+ TreeScope.TreeScope_Element | TreeScope.TreeScope_Children
+ )
- interactive_nodes, dom_interactive_nodes, dom_informative_nodes, scrollable_nodes = [], [], [], []
- window_name=(node.Name or '').strip()
- window_name=self.window_name_correction(window_name)
+ window_bounding_box = node.BoundingRectangle
- self.tree_traversal(node, window_bounding_box, window_name, is_browser, interactive_nodes, scrollable_nodes, dom_interactive_nodes, dom_informative_nodes, is_dom=False, is_dialog=False, element_cache_req=element_cache_req, children_cache_req=children_cache_req, hwnd=handle)
- logger.debug(f'Window name:{window_name}')
- logger.debug(f'Interactive nodes:{len(interactive_nodes)}')
+ interactive_nodes, dom_interactive_nodes, dom_informative_nodes, scrollable_nodes = (
+ [],
+ [],
+ [],
+ [],
+ )
+ window_name = (node.Name or "").strip()
+ window_name = self.window_name_correction(window_name)
+
+ self.tree_traversal(
+ node,
+ window_bounding_box,
+ window_name,
+ is_browser,
+ interactive_nodes,
+ scrollable_nodes,
+ dom_interactive_nodes,
+ dom_informative_nodes,
+ is_dom=False,
+ is_dialog=False,
+ element_cache_req=element_cache_req,
+ children_cache_req=children_cache_req,
+ hwnd=handle,
+ )
+ logger.debug(f"Window name:{window_name}")
+ logger.debug(f"Interactive nodes:{len(interactive_nodes)}")
if is_browser:
- logger.debug(f'DOM interactive nodes:{len(dom_interactive_nodes)}')
- logger.debug(f'DOM informative nodes:{len(dom_informative_nodes)}')
- logger.debug(f'Scrollable nodes:{len(scrollable_nodes)}')
+ logger.debug(f"DOM interactive nodes:{len(dom_interactive_nodes)}")
+ logger.debug(f"DOM informative nodes:{len(dom_informative_nodes)}")
+ logger.debug(f"Scrollable nodes:{len(scrollable_nodes)}")
interactive_nodes.extend(dom_interactive_nodes)
- return (interactive_nodes,scrollable_nodes,dom_informative_nodes)
+ return (interactive_nodes, scrollable_nodes, dom_informative_nodes)
except UIAException:
raise
except COMError as e:
raise from_com_error(e) from e
- def on_focus_change(self, sender:ctypes.POINTER('IUIAutomationElement')):
+ def on_focus_change(self, sender: ctypes.POINTER("IUIAutomationElement")):
"""Handle focus change events."""
# Debounce duplicate events
current_time = perf_counter()
element = Control.CreateControlFromElement(sender)
- runtime_id=element.GetRuntimeId()
+ runtime_id = element.GetRuntimeId()
event_key = tuple(runtime_id)
- if hasattr(self, '_last_focus_event') and self._last_focus_event:
+ if hasattr(self, "_last_focus_event") and self._last_focus_event:
last_key, last_time = self._last_focus_event
if last_key == event_key and (current_time - last_time) < 1.0:
return None
self._last_focus_event = (event_key, current_time)
try:
- logger.debug(f"[WatchDog] Focus changed to: '{element.Name}' ({element.ControlTypeName})")
+ logger.debug(
+ f"[WatchDog] Focus changed to: '{element.Name}' ({element.ControlTypeName})"
+ )
except Exception:
pass
diff --git a/windows_use/agent/tree/views.py b/windows_use/agent/tree/views.py
index 7524d59..8c3c182 100644
--- a/windows_use/agent/tree/views.py
+++ b/windows_use/agent/tree/views.py
@@ -2,21 +2,24 @@ import json
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Optional
-WARNING_MESSAGE="The desktop UI services are temporarily unavailable. Please wait a few seconds and continue."
-EMPTY_MESSAGE="No elements found"
+WARNING_MESSAGE = (
+ "The desktop UI services are temporarily unavailable. Please wait a few seconds and continue."
+)
+EMPTY_MESSAGE = "No elements found"
if TYPE_CHECKING:
from windows_use.uia.controls import Control
from windows_use.uia.core import Rect
+
@dataclass
class TreeState:
- status:bool=True
- root_node:Optional['TreeElementNode']=None
- dom_node:Optional['ScrollElementNode']=None
- interactive_nodes:list['TreeElementNode']|None=field(default_factory=list)
- scrollable_nodes:list['ScrollElementNode']|None=field(default_factory=list)
- dom_informative_nodes:list['TextElementNode']|None=field(default_factory=list)
+ status: bool = True
+ root_node: Optional["TreeElementNode"] = None
+ dom_node: Optional["ScrollElementNode"] = None
+ interactive_nodes: list["TreeElementNode"] | None = field(default_factory=list)
+ scrollable_nodes: list["ScrollElementNode"] | None = field(default_factory=list)
+ dom_informative_nodes: list["TextElementNode"] | None = field(default_factory=list)
def interactive_elements_to_string(self) -> str:
parts = []
@@ -36,7 +39,7 @@ class TreeState:
parts.append("\n".join(rows))
return "\n".join(parts)
- def build_selector_map(self) -> 'SelectorMap':
+ def build_selector_map(self) -> "SelectorMap":
"""Build a SelectorMap from all interactive and scrollable nodes in this tree state."""
nodes: list = list(self.interactive_nodes or []) + list(self.scrollable_nodes or [])
return SelectorMap(enumerate(nodes))
@@ -54,79 +57,94 @@ class TreeState:
rows = [header]
base_index = len(self.interactive_nodes)
for idx, node in enumerate(self.scrollable_nodes):
- row = (f"{base_index + idx}|{node.window_name}|{node.control_type}|{node.name}|"
- f"{node.center.to_string()}|{json.dumps(node.metadata)}")
+ row = (
+ f"{base_index + idx}|{node.window_name}|{node.control_type}|{node.name}|"
+ f"{node.center.to_string()}|{json.dumps(node.metadata)}"
+ )
rows.append(row)
parts.append("\n".join(rows))
return "\n".join(parts)
+
@dataclass
class BoundingBox:
- left:int
- top:int
- right:int
- bottom:int
- width:int
- height:int
+ left: int
+ top: int
+ right: int
+ bottom: int
+ width: int
+ height: int
@classmethod
- def from_bounding_rectangle(cls,bounding_rectangle:'Rect')->'BoundingBox':
+ def from_bounding_rectangle(cls, bounding_rectangle: "Rect") -> "BoundingBox":
return cls(
left=bounding_rectangle.left,
top=bounding_rectangle.top,
right=bounding_rectangle.right,
bottom=bounding_rectangle.bottom,
width=bounding_rectangle.width(),
- height=bounding_rectangle.height()
+ height=bounding_rectangle.height(),
)
- def get_center(self)->'Center':
- return Center(x=self.left+self.width//2,y=self.top+self.height//2)
+ def get_center(self) -> "Center":
+ return Center(x=self.left + self.width // 2, y=self.top + self.height // 2)
def xywh_to_string(self):
- return f'({self.left},{self.top},{self.width},{self.height})'
+ return f"({self.left},{self.top},{self.width},{self.height})"
def xyxy_to_string(self):
- x1,y1,x2,y2=self.convert_xywh_to_xyxy()
- return f'({x1},{y1},{x2},{y2})'
+ x1, y1, x2, y2 = self.convert_xywh_to_xyxy()
+ return f"({x1},{y1},{x2},{y2})"
+
+ def convert_xywh_to_xyxy(self) -> tuple[int, int, int, int]:
+ x1, y1 = self.left, self.top
+ x2, y2 = self.left + self.width, self.top + self.height
+ return x1, y1, x2, y2
- def convert_xywh_to_xyxy(self)->tuple[int,int,int,int]:
- x1,y1=self.left,self.top
- x2,y2=self.left+self.width,self.top+self.height
- return x1,y1,x2,y2
@dataclass
class Center:
- x:int
- y:int
+ x: int
+ y: int
+
+ def to_string(self) -> str:
+ return f"({self.x},{self.y})"
- def to_string(self)->str:
- return f'({self.x},{self.y})'
@dataclass
class TreeElementNode:
bounding_box: BoundingBox
center: Center
- name: str=''
- control_type: str=''
- window_name: str=''
- hwnd: int=0
- control: Optional['Control']=None
- metadata:dict[str,Any]=field(default_factory=dict)
-
- def update_from_node(self,node:'TreeElementNode'):
- self.name=node.name
- self.control_type=node.control_type
- self.window_name=node.window_name
- self.value=node.value
- self.shortcut=node.shortcut
- self.bounding_box=node.bounding_box
- self.center=node.center
- self.metadata=node.metadata
+ name: str = ""
+ control_type: str = ""
+ window_name: str = ""
+ hwnd: int = 0
+ control: Optional["Control"] = None
+ metadata: dict[str, Any] = field(default_factory=dict)
+
+ def update_from_node(self, node: "TreeElementNode"):
+ self.name = node.name
+ self.control_type = node.control_type
+ self.window_name = node.window_name
+ self.value = node.value
+ self.shortcut = node.shortcut
+ self.bounding_box = node.bounding_box
+ self.center = node.center
+ self.metadata = node.metadata
# Legacy method kept for compatibility if needed, but not used in new format
def to_row(self, index: int):
- return [index, self.window_name, self.control_type, self.name, self.value, self.shortcut, self.center.to_string(),self.is_focused]
+ return [
+ index,
+ self.window_name,
+ self.control_type,
+ self.name,
+ self.value,
+ self.shortcut,
+ self.center.to_string(),
+ self.is_focused,
+ ]
+
@dataclass
class ScrollElementNode:
@@ -135,9 +153,9 @@ class ScrollElementNode:
window_name: str
bounding_box: BoundingBox
center: Center
- hwnd: int=0
- control: Optional['Control']=None
- metadata:dict[str,Any]=field(default_factory=dict)
+ hwnd: int = 0
+ control: Optional["Control"] = None
+ metadata: dict[str, Any] = field(default_factory=dict)
# Legacy method kept for compatibility
def to_row(self, index: int, base_index: int):
@@ -147,17 +165,20 @@ class ScrollElementNode:
self.control_type,
self.name,
self.center.to_string(),
- json.dumps(self.metadata)
+ json.dumps(self.metadata),
]
+
@dataclass
class TextElementNode:
- text:str
+ text: str
+
-ElementNode=TreeElementNode|ScrollElementNode|TextElementNode
+ElementNode = TreeElementNode | ScrollElementNode | TextElementNode
_SelectorNode = TreeElementNode | ScrollElementNode
+
class SelectorMap(dict):
"""Maps element index (as shown in the tree output) to its node.
@@ -176,7 +197,7 @@ class SelectorMap(dict):
node = self.get(index)
return node
- def control_of(self, index: int) -> Optional['Control']:
+ def control_of(self, index: int) -> Optional["Control"]:
node = self.node_of(index)
return node.control if node else None
@@ -185,4 +206,4 @@ class SelectorMap(dict):
return node.hwnd if node else None
def __repr__(self) -> str:
- return f'SelectorMap({len(self)} elements)'
+ return f"SelectorMap({len(self)} elements)"
diff --git a/windows_use/agent/views.py b/windows_use/agent/views.py
index 917a3a8..6b27f71 100644
--- a/windows_use/agent/views.py
+++ b/windows_use/agent/views.py
@@ -12,7 +12,7 @@ class AgentResult:
@dataclass
class AgentState:
- task: str|None = None
+ task: str | None = None
messages: list[BaseMessage] = field(default_factory=list)
error_messages: list[BaseMessage] = field(default_factory=list)
step: int = 0
diff --git a/windows_use/agent/watchdog/event_handlers.py b/windows_use/agent/watchdog/event_handlers.py
index feb110b..4214704 100644
--- a/windows_use/agent/watchdog/event_handlers.py
+++ b/windows_use/agent/watchdog/event_handlers.py
@@ -8,6 +8,7 @@ from windows_use.uia.core import _AutomationClient
uia_client = _AutomationClient.instance()
UIA = uia_client.UIAutomationCore
+
class FocusChangedEventHandler(comtypes.COMObject):
_com_interfaces_ = [UIA.IUIAutomationFocusChangedEventHandler]
@@ -22,7 +23,8 @@ class FocusChangedEventHandler(comtypes.COMObject):
parent._focus_callback(sender)
except Exception as e:
print(f"Error in focus callback: {e}")
- return 0 # S_OK
+ return 0 # S_OK
+
class StructureChangedEventHandler(comtypes.COMObject):
_com_interfaces_ = [UIA.IUIAutomationStructureChangedEventHandler]
@@ -38,7 +40,8 @@ class StructureChangedEventHandler(comtypes.COMObject):
parent._structure_callback(sender, changeType, runtimeId)
except Exception as e:
print(f"Error in structure callback: {e}")
- return 0 # S_OK
+ return 0 # S_OK
+
class PropertyChangedEventHandler(comtypes.COMObject):
_com_interfaces_ = [UIA.IUIAutomationPropertyChangedEventHandler]
@@ -54,4 +57,4 @@ class PropertyChangedEventHandler(comtypes.COMObject):
parent._property_callback(sender, propertyId, newValue)
except Exception as e:
print(f"Error in property callback: {e}")
- return 0 # S_OK
+ return 0 # S_OK
diff --git a/windows_use/agent/watchdog/service.py b/windows_use/agent/watchdog/service.py
index 25190d1..e6cc083 100644
--- a/windows_use/agent/watchdog/service.py
+++ b/windows_use/agent/watchdog/service.py
@@ -2,6 +2,7 @@
Unified WatchDog Service for monitoring UI Automation events.
Allows single instantiation to handle multiple monitors (Focus, Structure) safely in one STA thread.
"""
+
import logging
from threading import Event, Thread
@@ -14,6 +15,7 @@ from windows_use.uia.enums import TreeScope
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
+
class WatchDog:
def __init__(self):
self.is_running = Event()
@@ -83,7 +85,9 @@ class WatchDog:
self._property_ids = property_ids
self._config_changed.set()
- def _sync_handlers(self, FocusChangedEventHandler, StructureChangedEventHandler, PropertyChangedEventHandler):
+ def _sync_handlers(
+ self, FocusChangedEventHandler, StructureChangedEventHandler, PropertyChangedEventHandler
+ ):
"""Reconcile desired callback config with active COM handlers."""
# --- Focus Monitoring ---
if self._focus_callback and not self._focus_handler:
@@ -100,13 +104,17 @@ class WatchDog:
self._focus_handler = None
# --- Structure Monitoring ---
- config_changed = (self._structure_element != self._active_structure_element)
- should_be_active = (self._structure_callback is not None)
- is_active = (self._structure_handler is not None)
+ config_changed = self._structure_element != self._active_structure_element
+ should_be_active = self._structure_callback is not None
+ is_active = self._structure_handler is not None
if is_active and (not should_be_active or config_changed):
try:
- target = self._active_structure_element if self._active_structure_element else self.uia.GetRootElement()
+ target = (
+ self._active_structure_element
+ if self._active_structure_element
+ else self.uia.GetRootElement()
+ )
self.uia.RemoveStructureChangedEventHandler(target, self._structure_handler)
except Exception as e:
logger.debug(f"Failed to remove structure handler: {e}")
@@ -116,23 +124,34 @@ class WatchDog:
if should_be_active and not is_active:
try:
- target = self._structure_element if self._structure_element else self.uia.GetRootElement()
+ target = (
+ self._structure_element
+ if self._structure_element
+ else self.uia.GetRootElement()
+ )
scope = TreeScope.TreeScope_Subtree
self._structure_handler = StructureChangedEventHandler(self)
- self.uia.AddStructureChangedEventHandler(target, scope, None, self._structure_handler)
+ self.uia.AddStructureChangedEventHandler(
+ target, scope, None, self._structure_handler
+ )
self._active_structure_element = target
except Exception as e:
logger.debug(f"Failed to add structure handler: {e}")
# --- Property Monitoring ---
- config_changed = (self._property_element != self._active_property_element) or \
- (self._property_ids != self._active_property_ids)
- should_be_active = (self._property_callback is not None)
- is_active = (self._property_handler is not None)
+ config_changed = (self._property_element != self._active_property_element) or (
+ self._property_ids != self._active_property_ids
+ )
+ should_be_active = self._property_callback is not None
+ is_active = self._property_handler is not None
if is_active and (not should_be_active or config_changed):
try:
- target = self._active_property_element if self._active_property_element else self.uia.GetRootElement()
+ target = (
+ self._active_property_element
+ if self._active_property_element
+ else self.uia.GetRootElement()
+ )
self.uia.RemovePropertyChangedEventHandler(target, self._property_handler)
except Exception as e:
logger.error(f"Failed to remove property handler: {e}")
@@ -143,12 +162,16 @@ class WatchDog:
if should_be_active and not is_active:
try:
- target = self._property_element if self._property_element else self.uia.GetRootElement()
+ target = (
+ self._property_element if self._property_element else self.uia.GetRootElement()
+ )
scope = TreeScope.TreeScope_Subtree
# 30005: Name, 30045: Value, 30093: LegacyIAccessibleVal, 30128: ToggleState
p_ids = self._property_ids if self._property_ids else [30005, 30045, 30093, 30128]
self._property_handler = PropertyChangedEventHandler(self)
- self.uia.AddPropertyChangedEventHandler(target, scope, None, self._property_handler, p_ids)
+ self.uia.AddPropertyChangedEventHandler(
+ target, scope, None, self._property_handler, p_ids
+ )
self._active_property_element = target
self._active_property_ids = p_ids
except Exception as e:
@@ -163,6 +186,7 @@ class WatchDog:
PropertyChangedEventHandler,
StructureChangedEventHandler,
)
+
# Initialize UIA inside the thread
uia_client = _AutomationClient.instance()
self.uia = uia_client.IUIAutomation
@@ -170,7 +194,11 @@ class WatchDog:
while self.is_running.is_set():
if self._config_changed.is_set():
self._config_changed.clear()
- self._sync_handlers(FocusChangedEventHandler, StructureChangedEventHandler, PropertyChangedEventHandler)
+ self._sync_handlers(
+ FocusChangedEventHandler,
+ StructureChangedEventHandler,
+ PropertyChangedEventHandler,
+ )
comtypes.client.PumpEvents(0.1)
@@ -188,7 +216,11 @@ class WatchDog:
if self._structure_handler:
try:
- target = self._active_structure_element if self._active_structure_element else self.uia.GetRootElement()
+ target = (
+ self._active_structure_element
+ if self._active_structure_element
+ else self.uia.GetRootElement()
+ )
self.uia.RemoveStructureChangedEventHandler(target, self._structure_handler)
except Exception:
pass
@@ -197,7 +229,11 @@ class WatchDog:
if self._property_handler:
try:
- target = self._active_property_element if self._active_property_element else self.uia.GetRootElement()
+ target = (
+ self._active_property_element
+ if self._active_property_element
+ else self.uia.GetRootElement()
+ )
self.uia.RemovePropertyChangedEventHandler(target, self._property_handler)
except Exception:
pass
diff --git a/windows_use/cli/__main__.py b/windows_use/cli/__main__.py
index 67c0579..5a6a388 100644
--- a/windows_use/cli/__main__.py
+++ b/windows_use/cli/__main__.py
@@ -61,15 +61,18 @@ def _strip_markdown(text: str) -> str:
t = re.sub(r"^\s*\d+\.\s+", "", t, flags=re.MULTILINE)
return re.sub(r"\n{3,}", "\n\n", t).strip()
+
app = typer.Typer(
name="windows-use",
help="Windows-Use: Computer-Use for Windows OS.",
invoke_without_command=True,
)
+
def _version() -> str:
try:
from importlib.metadata import version
+
return version("windows-use")
except Exception:
return "0.0.0"
@@ -217,12 +220,14 @@ def _run_interactive(provider: str, model: str, max_steps: int, debug: bool = Fa
if stt_provider:
try:
from windows_use.speech import STT
+
stt_instance = STT(provider=stt_provider, verbose=False)
except ImportError:
stt_provider = None
if tts_provider:
try:
from windows_use.speech import TTS
+
tts_instance = TTS(provider=tts_provider, verbose=False)
except ImportError:
tts_provider = None
@@ -296,6 +301,7 @@ def _run_interactive(provider: str, model: str, max_steps: int, debug: bool = Fa
if task.lower() in ("key", "\\key"):
try:
from windows_use.cli.setup import run_key_change
+
if run_key_change():
active_config = get_active_config()
base_url = active_config.get("base_url") if active_config else None
@@ -311,7 +317,9 @@ def _run_interactive(provider: str, model: str, max_steps: int, debug: bool = Fa
)
typer.secho("API key updated and applied.", fg="green")
else:
- typer.secho("No providers with API keys configured. Use \\llm first.", fg="yellow")
+ typer.secho(
+ "No providers with API keys configured. Use \\llm first.", fg="yellow"
+ )
except KeyboardInterrupt:
pass
continue
@@ -323,25 +331,34 @@ def _run_interactive(provider: str, model: str, max_steps: int, debug: bool = Fa
create_tts_provider,
run_speech_setup,
)
+
run_speech_setup(initial_setup=False)
stt_provider = create_stt_provider()
tts_provider = create_tts_provider()
if stt_provider:
try:
from windows_use.speech import STT
+
stt_instance = STT(provider=stt_provider, verbose=False)
except ImportError:
stt_instance = None
- typer.secho("Install pyaudio for voice input: uv add windows-use[speech]", fg="yellow")
+ typer.secho(
+ "Install pyaudio for voice input: uv add windows-use[speech]",
+ fg="yellow",
+ )
else:
stt_instance = None
if tts_provider:
try:
from windows_use.speech import TTS
+
tts_instance = TTS(provider=tts_provider, verbose=False)
except ImportError:
tts_instance = None
- typer.secho("Install pyaudio for spoken responses: uv add windows-use[speech]", fg="yellow")
+ typer.secho(
+ "Install pyaudio for spoken responses: uv add windows-use[speech]",
+ fg="yellow",
+ )
else:
tts_instance = None
# Recreate agent so it picks up new TTS callback
@@ -361,7 +378,9 @@ def _run_interactive(provider: str, model: str, max_steps: int, debug: bool = Fa
if task.lower() in ("voice", "\\voice"):
if stt_instance is None:
- typer.secho("Speech-to-Text not configured. Use \\speech to set it up.", fg="yellow")
+ typer.secho(
+ "Speech-to-Text not configured. Use \\speech to set it up.", fg="yellow"
+ )
continue
try:
# Clear the "> \voice" line and show recording on same line
@@ -454,8 +473,10 @@ def _run_interactive(provider: str, model: str, max_steps: int, debug: bool = Fa
event_subscriber=event_subscriber,
)
import asyncio
+
result = asyncio.run(agent.ainvoke(task=task))
+
def main() -> None:
"""Entry point for the console script."""
app()
diff --git a/windows_use/cli/config.py b/windows_use/cli/config.py
index 1b966fa..90adcf7 100644
--- a/windows_use/cli/config.py
+++ b/windows_use/cli/config.py
@@ -30,9 +30,7 @@ def _get_fernet() -> Fernet:
salt=_ENC_SALT,
iterations=480_000,
)
- key = base64.urlsafe_b64encode(
- kdf.derive(Path.home().as_posix().encode("utf-8"))
- )
+ key = base64.urlsafe_b64encode(kdf.derive(Path.home().as_posix().encode("utf-8")))
return Fernet(key)
@@ -214,7 +212,9 @@ def get_tts_config() -> dict[str, Any] | None:
return out
-def save_speech_config(stt: dict[str, Any] | None = None, tts: dict[str, Any] | None = None) -> None:
+def save_speech_config(
+ stt: dict[str, Any] | None = None, tts: dict[str, Any] | None = None
+) -> None:
"""Save speech config. Merges with existing; pass None to leave unchanged."""
cfg = get_speech_config()
if stt is not None:
diff --git a/windows_use/cli/setup.py b/windows_use/cli/setup.py
index 6b7dd5c..c37ceec 100644
--- a/windows_use/cli/setup.py
+++ b/windows_use/cli/setup.py
@@ -40,6 +40,7 @@ from windows_use.cli.speech_registry import (
def _version() -> str:
try:
from importlib.metadata import version
+
return version("windows-use")
except Exception:
return "0.0.0"
@@ -63,13 +64,15 @@ def run_setup() -> dict[str, str]:
# Welcome banner
console.print()
- console.print(Panel.fit(
- f"[bold cyan]Windows-Use[/] v{_version()}\n\n"
- "[dim]Computer-Use for Windows OS[/]\n"
- "[dim]Let's get you set up in a few steps.[/]",
- border_style="cyan",
- padding=(1, 2),
- ))
+ console.print(
+ Panel.fit(
+ f"[bold cyan]Windows-Use[/] v{_version()}\n\n"
+ "[dim]Computer-Use for Windows OS[/]\n"
+ "[dim]Let's get you set up in a few steps.[/]",
+ border_style="cyan",
+ padding=(1, 2),
+ )
+ )
console.print()
# Pick provider
@@ -307,10 +310,7 @@ def run_base_url_change() -> bool:
import questionary
configs = get_providers_config()
- providers_list = [
- (get_provider_display(c["provider"]), c["provider"])
- for c in configs
- ]
+ providers_list = [(get_provider_display(c["provider"]), c["provider"]) for c in configs]
if not providers_list:
return False
@@ -361,45 +361,58 @@ def create_llm(provider: str, model: str, api_key: str | None = None, base_url:
if provider == "groq":
from windows_use.providers.groq import ChatGroq
+
return ChatGroq(model=model, api_key=key, base_url=base_url)
if provider == "openai":
from windows_use.providers.openai import ChatOpenAI
+
return ChatOpenAI(model=model, api_key=key, base_url=base_url)
if provider == "anthropic":
from windows_use.providers.anthropic import ChatAnthropic
+
return ChatAnthropic(model=model, api_key=key, base_url=base_url)
if provider == "google":
from windows_use.providers.google import ChatGoogle
+
return ChatGoogle(model=model, api_key=key, base_url=base_url)
if provider == "ollama":
from windows_use.providers.ollama import ChatOllama
+
return ChatOllama(model=model, host=base_url)
if provider == "mistral":
from windows_use.providers.mistral import ChatMistral
+
return ChatMistral(model=model, api_key=key, base_url=base_url)
if provider == "cerebras":
from windows_use.providers.cerebras import ChatCerebras
+
return ChatCerebras(model=model, api_key=key, base_url=base_url)
if provider == "open_router":
from windows_use.providers.open_router import ChatOpenRouter
+
return ChatOpenRouter(model=model, api_key=key, base_url=base_url)
if provider == "azure_openai":
from windows_use.providers.azure_openai import ChatAzureOpenAI
+
return ChatAzureOpenAI(deployment_name=model, api_key=key)
if provider == "perplexity":
from windows_use.providers.perplexity import ChatPerplexity
+
kwargs = {"model": model, "api_key": key}
if base_url:
kwargs["base_url"] = base_url
return ChatPerplexity(**kwargs)
if provider == "litellm":
from windows_use.providers.litellm import ChatLiteLLM
+
return ChatLiteLLM(model=model, api_key=key, base_url=base_url)
if provider == "deepseek":
from windows_use.providers.deepseek import ChatDeepSeek
+
return ChatDeepSeek(model=model, api_key=key, base_url=base_url)
if provider == "nvidia":
from windows_use.providers.nvidia import ChatNvidia
+
return ChatNvidia(model=model, api_key=key, base_url=base_url)
raise ValueError(f"Unknown provider: {provider}")
@@ -555,13 +568,25 @@ def _configure_tts(console) -> None:
if provider_key == "openai":
voice = questionary.select(
"Pick a voice:",
- choices=["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer"],
+ choices=[
+ "alloy",
+ "ash",
+ "ballad",
+ "coral",
+ "echo",
+ "fable",
+ "onyx",
+ "nova",
+ "sage",
+ "shimmer",
+ ],
default="alloy",
style=_SELECT_STYLE,
).ask()
voice = voice or "alloy"
elif provider_key == "google":
from windows_use.providers.google.tts import GOOGLE_TTS_VOICES
+
voice = questionary.select(
"Pick a voice:",
choices=GOOGLE_TTS_VOICES[:12],
@@ -610,7 +635,7 @@ def _env_api_key_for_speech_provider(provider: str) -> str | None:
"groq": "GROQ_API_KEY",
"elevenlabs": "ELEVENLABS_API_KEY",
"deepgram": "DEEPGRAM_API_KEY",
- "perplexity": "PERPLEXITY_API_KEY"
+ "perplexity": "PERPLEXITY_API_KEY",
}
name = env_map.get(provider)
if not name:
@@ -633,6 +658,7 @@ def create_stt_provider():
api_key = cfg.get("api_key_encrypted")
if api_key:
from windows_use.cli.config import decrypt_secret
+
api_key = decrypt_secret(api_key)
if not api_key:
api_key = get_api_key(provider_key)
@@ -641,22 +667,27 @@ def create_stt_provider():
if provider_key == "openai":
from windows_use.providers.openai import STTOpenAI
+
return STTOpenAI(model=model, api_key=api_key)
if provider_key == "google":
from windows_use.providers.google import STTGoogle
+
return STTGoogle(model=model, api_key=api_key)
if provider_key == "groq":
from windows_use.providers.groq import STTGroq
+
return STTGroq(model=model, api_key=api_key)
if provider_key == "elevenlabs":
try:
from windows_use.providers.elevenlabs import STTElevenLabs
+
return STTElevenLabs(api_key=api_key)
except ImportError:
return None
if provider_key == "deepgram":
try:
from windows_use.providers.deepgram import STTDeepgram
+
return STTDeepgram(model=model, api_key=api_key)
except ImportError:
return None
@@ -679,6 +710,7 @@ def create_tts_provider():
api_key = cfg.get("api_key_encrypted")
if api_key:
from windows_use.cli.config import decrypt_secret
+
api_key = decrypt_secret(api_key)
if not api_key:
api_key = get_api_key(provider_key)
@@ -687,22 +719,27 @@ def create_tts_provider():
if provider_key == "openai":
from windows_use.providers.openai import TTSOpenAI
+
return TTSOpenAI(model=model, voice=voice, api_key=api_key)
if provider_key == "google":
from windows_use.providers.google import TTSGoogle
+
return TTSGoogle(model=model, voice=voice, api_key=api_key)
if provider_key == "groq":
from windows_use.providers.groq import TTSGroq
+
return TTSGroq(model=model, voice=voice, api_key=api_key)
if provider_key == "elevenlabs":
try:
from windows_use.providers.elevenlabs import TTSElevenLabs
+
return TTSElevenLabs(model=model, api_key=api_key)
except ImportError:
return None
if provider_key == "deepgram":
try:
from windows_use.providers.deepgram import TTSDeepgram
+
return TTSDeepgram(model=model, api_key=api_key)
except ImportError:
return None
diff --git a/windows_use/cli/speech_registry.py b/windows_use/cli/speech_registry.py
index c4bd865..e26166a 100644
--- a/windows_use/cli/speech_registry.py
+++ b/windows_use/cli/speech_registry.py
@@ -74,7 +74,18 @@ TTS_MODELS: dict[str, list[tuple[str, str]]] = {
}
# OpenAI TTS voices
-OPENAI_TTS_VOICES = ["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer"]
+OPENAI_TTS_VOICES = [
+ "alloy",
+ "ash",
+ "ballad",
+ "coral",
+ "echo",
+ "fable",
+ "onyx",
+ "nova",
+ "sage",
+ "shimmer",
+]
# Groq TTS voices (Orpheus)
GROQ_TTS_VOICES = ["autumn", "diana", "hannah", "austin", "daniel", "troy"]
@@ -88,7 +99,9 @@ SPEECH_PROVIDERS_OWN_KEY: set[str] = {"elevenlabs", "deepgram"}
def speech_provider_requires_api_key(provider_key: str) -> bool:
"""Return True if the speech provider needs an API key."""
- return provider_key in SPEECH_PROVIDERS_SHARING_LLM_KEY or provider_key in SPEECH_PROVIDERS_OWN_KEY
+ return (
+ provider_key in SPEECH_PROVIDERS_SHARING_LLM_KEY or provider_key in SPEECH_PROVIDERS_OWN_KEY
+ )
def get_stt_providers() -> list[tuple[str, str]]:
diff --git a/windows_use/messages/service.py b/windows_use/messages/service.py
index 1186ad2..1fca654 100644
--- a/windows_use/messages/service.py
+++ b/windows_use/messages/service.py
@@ -73,7 +73,9 @@ class ImageMessage(BaseMessage):
@staticmethod
def _compress_image(img, mime_type: str, max_bytes: int = 4_800_000) -> tuple[bytes, str]:
if Image is None:
- raise ImportError("Pillow is required for ImageMessage. Install with: pip install pillow")
+ raise ImportError(
+ "Pillow is required for ImageMessage. Install with: pip install pillow"
+ )
def _save(image, fmt: str, quality: int) -> bytes:
buf = BytesIO()
diff --git a/windows_use/providers/anthropic/llm.py b/windows_use/providers/anthropic/llm.py
index f97565d..b5018ea 100644
--- a/windows_use/providers/anthropic/llm.py
+++ b/windows_use/providers/anthropic/llm.py
@@ -29,6 +29,7 @@ from windows_use.tools import Tool
logger = logging.getLogger(__name__)
+
class ChatAnthropic(BaseChatLLM):
"""
Anthropic LLM implementation following the BaseChatLLM protocol.
@@ -48,7 +49,7 @@ class ChatAnthropic(BaseChatLLM):
cache_system_prompt: bool = True,
cache_tools: bool = True,
cache_recent_messages: int = 2, # Number of recent messages to cache
- **kwargs
+ **kwargs,
):
"""
Initialize the Anthropic LLM with prompt caching and extended thinking support.
@@ -125,7 +126,9 @@ class ChatAnthropic(BaseChatLLM):
def provider(self) -> str:
return "anthropic"
- def _convert_messages(self, messages: list[BaseMessage]) -> tuple[str | list[dict] | None, list[dict]]:
+ def _convert_messages(
+ self, messages: list[BaseMessage]
+ ) -> tuple[str | list[dict] | None, list[dict]]:
"""
Convert BaseMessage objects to Anthropic-compatible message dictionaries.
Returns (system_prompt, messages).
@@ -147,86 +150,85 @@ class ChatAnthropic(BaseChatLLM):
b64_imgs = msg.convert_images(format="base64")
for b64 in b64_imgs:
- content.append({
- "type": "image",
- "source": {
- "type": "base64",
- "media_type": msg.mime_type,
- "data": b64
+ content.append(
+ {
+ "type": "image",
+ "source": {"type": "base64", "media_type": msg.mime_type, "data": b64},
}
- })
+ )
anthropic_messages.append({"role": "user", "content": content})
elif isinstance(msg, AIMessage):
content = []
if msg.thinking:
- content.append({
- "type": "thinking",
- "thinking": msg.thinking,
- "signature": msg.thinking_signature
- })
+ content.append(
+ {
+ "type": "thinking",
+ "thinking": msg.thinking,
+ "signature": msg.thinking_signature,
+ }
+ )
if msg.content:
content.append({"type": "text", "text": msg.content})
- anthropic_messages.append({"role": "assistant", "content": content if content else ""})
+ anthropic_messages.append(
+ {"role": "assistant", "content": content if content else ""}
+ )
elif isinstance(msg, ToolMessage):
# Build content blocks for the assistant turn
content_blocks = []
if msg.thinking:
- content_blocks.append({
- "type": "thinking",
- "thinking": msg.thinking,
- "signature": msg.thinking_signature
- })
- content_blocks.append({
- "type": "tool_use",
- "id": msg.id,
- "name": msg.name,
- "input": msg.params
- })
+ content_blocks.append(
+ {
+ "type": "thinking",
+ "thinking": msg.thinking,
+ "signature": msg.thinking_signature,
+ }
+ )
+ content_blocks.append(
+ {"type": "tool_use", "id": msg.id, "name": msg.name, "input": msg.params}
+ )
# Anthropic requires a tool_use block followed by a tool_result block
if anthropic_messages and anthropic_messages[-1]["role"] == "assistant":
last_content = anthropic_messages[-1]["content"]
if isinstance(last_content, str):
- last_content = [{"type": "text", "text": last_content}] if last_content else []
+ last_content = (
+ [{"type": "text", "text": last_content}] if last_content else []
+ )
if isinstance(last_content, list):
last_content.extend(content_blocks)
anthropic_messages[-1]["content"] = last_content
else:
- anthropic_messages.append({
- "role": "assistant",
- "content": content_blocks
- })
+ anthropic_messages.append({"role": "assistant", "content": content_blocks})
# Add the tool result
- anthropic_messages.append({
- "role": "user",
- "content": [{
- "type": "tool_result",
- "tool_use_id": msg.id,
- "content": msg.content or ""
- }]
- })
+ anthropic_messages.append(
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": msg.id,
+ "content": msg.content or "",
+ }
+ ],
+ }
+ )
# Apply prompt caching to system prompt
if system_prompt and self.enable_prompt_caching and self.cache_system_prompt:
system_prompt = [
- {
- "type": "text",
- "text": system_prompt,
- "cache_control": {"type": "ephemeral"}
- }
+ {"type": "text", "text": system_prompt, "cache_control": {"type": "ephemeral"}}
]
# Apply prompt caching to recent messages
if self.enable_prompt_caching and self.cache_recent_messages > 0 and anthropic_messages:
# Cache the last N user messages (caching works best on user turns)
user_message_indices = [
- i for i, msg in enumerate(anthropic_messages)
- if msg["role"] == "user"
+ i for i, msg in enumerate(anthropic_messages) if msg["role"] == "user"
]
# Get the indices to cache (last N user messages)
- indices_to_cache = user_message_indices[-self.cache_recent_messages:]
+ indices_to_cache = user_message_indices[-self.cache_recent_messages :]
for idx in indices_to_cache:
msg = anthropic_messages[idx]
@@ -244,13 +246,15 @@ class ChatAnthropic(BaseChatLLM):
return system_prompt, anthropic_messages
- def _build_params(self, anthropic_messages: list[dict], system_prompt: Any, anthropic_tools: list[dict] | None) -> dict:
+ def _build_params(
+ self, anthropic_messages: list[dict], system_prompt: Any, anthropic_tools: list[dict] | None
+ ) -> dict:
"""Build the common API parameters for all invoke/stream methods."""
params = {
"model": self._model,
"messages": anthropic_messages,
"max_tokens": self.max_tokens,
- **self.kwargs
+ **self.kwargs,
}
if system_prompt is not None:
@@ -280,7 +284,7 @@ class ChatAnthropic(BaseChatLLM):
{
"name": tool.name,
"description": tool.description,
- "input_schema": tool.json_schema["parameters"]
+ "input_schema": tool.json_schema["parameters"],
}
for tool in tools
]
@@ -300,8 +304,8 @@ class ChatAnthropic(BaseChatLLM):
usage_data = response.usage
# Extract cache metrics
- cache_creation_tokens = getattr(usage_data, 'cache_creation_input_tokens', None) or 0
- cache_read_tokens = getattr(usage_data, 'cache_read_input_tokens', None) or 0
+ cache_creation_tokens = getattr(usage_data, "cache_creation_input_tokens", None) or 0
+ cache_read_tokens = getattr(usage_data, "cache_read_input_tokens", None) or 0
usage = TokenUsage(
prompt_tokens=usage_data.input_tokens,
@@ -316,7 +320,9 @@ class ChatAnthropic(BaseChatLLM):
if cache_creation_tokens > 0:
logger.debug(f"Cache created: {cache_creation_tokens} tokens")
if cache_read_tokens > 0:
- logger.debug(f"Cache hit: {cache_read_tokens} tokens (saved ~{cache_read_tokens * 0.9:.0f} tokens worth of cost)")
+ logger.debug(
+ f"Cache hit: {cache_read_tokens} tokens (saved ~{cache_read_tokens * 0.9:.0f} tokens worth of cost)"
+ )
text_content = ""
thinking_parts: list[str] = []
@@ -333,32 +339,49 @@ class ChatAnthropic(BaseChatLLM):
# Take the first tool use as per Agent logic
if not tool_message:
tool_message = True
- thinking = Thinking(
- content="\n".join(thinking_parts) if thinking_parts else None,
- signature=thinking_signature,
- ) if thinking_parts or thinking_signature else None
+ thinking = (
+ Thinking(
+ content="\n".join(thinking_parts) if thinking_parts else None,
+ signature=thinking_signature,
+ )
+ if thinking_parts or thinking_signature
+ else None
+ )
return LLMEvent(
type=LLMEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=block.id,
- name=block.name,
- params=block.input
- ),
+ tool_call=ToolCall(id=block.id, name=block.name, params=block.input),
thinking=thinking,
- usage=usage
+ usage=usage,
)
- thinking = Thinking(
- content="\n".join(thinking_parts) if thinking_parts else None,
- signature=thinking_signature,
- ) if thinking_parts or thinking_signature else None
- return LLMEvent(type=LLMEventType.TEXT, content=text_content, thinking=thinking, usage=usage)
+ thinking = (
+ Thinking(
+ content="\n".join(thinking_parts) if thinking_parts else None,
+ signature=thinking_signature,
+ )
+ if thinking_parts or thinking_signature
+ else None
+ )
+ return LLMEvent(
+ type=LLMEventType.TEXT, content=text_content, thinking=thinking, usage=usage
+ )
@overload
- def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
- ...
+ def invoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent: ...
- def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
+ def invoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent:
system_prompt, anthropic_messages = self._convert_messages(messages)
anthropic_tools = self._convert_tools(tools) if tools else None
params = self._build_params(anthropic_messages, system_prompt, anthropic_tools)
@@ -368,7 +391,7 @@ class ChatAnthropic(BaseChatLLM):
structured_tool = {
"name": "record_result",
"description": f"Record the structured result: {structured_output.__name__}",
- "input_schema": structured_output.model_json_schema()
+ "input_schema": structured_output.model_json_schema(),
}
# Add cache control to structured output tool if caching enabled
@@ -385,8 +408,10 @@ class ChatAnthropic(BaseChatLLM):
parsed = structured_output(**tool_use.input)
# Extract cache metrics
- cache_creation_tokens = getattr(response.usage, 'cache_creation_input_tokens', None) or 0
- cache_read_tokens = getattr(response.usage, 'cache_read_input_tokens', None) or 0
+ cache_creation_tokens = (
+ getattr(response.usage, "cache_creation_input_tokens", None) or 0
+ )
+ cache_read_tokens = getattr(response.usage, "cache_read_input_tokens", None) or 0
usage = TokenUsage(
prompt_tokens=response.usage.input_tokens,
@@ -398,16 +423,31 @@ class ChatAnthropic(BaseChatLLM):
)
content = parsed.model_dump() if hasattr(parsed, "model_dump") else str(parsed)
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content) if isinstance(content, dict) else content, usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content) if isinstance(content, dict) else content,
+ usage=usage,
+ )
response = self.client.messages.create(**params)
return self._process_response(response)
@overload
- async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
- ...
+ async def ainvoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent: ...
- async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
+ async def ainvoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent:
system_prompt, anthropic_messages = self._convert_messages(messages)
anthropic_tools = self._convert_tools(tools) if tools else None
params = self._build_params(anthropic_messages, system_prompt, anthropic_tools)
@@ -416,7 +456,7 @@ class ChatAnthropic(BaseChatLLM):
structured_tool = {
"name": "record_result",
"description": f"Record the structured result: {structured_output.__name__}",
- "input_schema": structured_output.model_json_schema()
+ "input_schema": structured_output.model_json_schema(),
}
if self.enable_prompt_caching and self.cache_tools:
@@ -431,8 +471,10 @@ class ChatAnthropic(BaseChatLLM):
tool_use = next(b for b in response.content if b.type == "tool_use")
parsed = structured_output(**tool_use.input)
- cache_creation_tokens = getattr(response.usage, 'cache_creation_input_tokens', None) or 0
- cache_read_tokens = getattr(response.usage, 'cache_read_input_tokens', None) or 0
+ cache_creation_tokens = (
+ getattr(response.usage, "cache_creation_input_tokens", None) or 0
+ )
+ cache_read_tokens = getattr(response.usage, "cache_read_input_tokens", None) or 0
usage = TokenUsage(
prompt_tokens=response.usage.input_tokens,
@@ -444,16 +486,31 @@ class ChatAnthropic(BaseChatLLM):
)
content = parsed.model_dump() if hasattr(parsed, "model_dump") else str(parsed)
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content) if isinstance(content, dict) else content, usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content) if isinstance(content, dict) else content,
+ usage=usage,
+ )
response = await self.aclient.messages.create(**params)
return self._process_response(response)
@overload
- def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
- ...
+ def stream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> Iterator[LLMStreamEvent]: ...
- def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
+ def stream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> Iterator[LLMStreamEvent]:
system_prompt, anthropic_messages = self._convert_messages(messages)
anthropic_tools = self._convert_tools(tools) if tools else None
params = self._build_params(anthropic_messages, system_prompt, anthropic_tools)
@@ -468,7 +525,9 @@ class ChatAnthropic(BaseChatLLM):
if not think_started:
think_started = True
yield LLMStreamEvent(type=LLMStreamEventType.THINK_START)
- yield LLMStreamEvent(type=LLMStreamEventType.THINK_DELTA, content=event.thinking)
+ yield LLMStreamEvent(
+ type=LLMStreamEventType.THINK_DELTA, content=event.thinking
+ )
elif event.type == "text":
if think_started:
yield LLMStreamEvent(type=LLMStreamEventType.THINK_END)
@@ -484,12 +543,15 @@ class ChatAnthropic(BaseChatLLM):
# Extract usage and thinking (with signature) from final message
final_message = stream.get_final_message()
if final_message.usage:
- cache_creation = getattr(final_message.usage, 'cache_creation_input_tokens', None) or 0
- cache_read = getattr(final_message.usage, 'cache_read_input_tokens', None) or 0
+ cache_creation = (
+ getattr(final_message.usage, "cache_creation_input_tokens", None) or 0
+ )
+ cache_read = getattr(final_message.usage, "cache_read_input_tokens", None) or 0
usage = TokenUsage(
prompt_tokens=final_message.usage.input_tokens,
completion_tokens=final_message.usage.output_tokens,
- total_tokens=final_message.usage.input_tokens + final_message.usage.output_tokens,
+ total_tokens=final_message.usage.input_tokens
+ + final_message.usage.output_tokens,
thinking_tokens=getattr(final_message.usage, "thinking_tokens", None),
cache_creation_input_tokens=cache_creation or None,
cache_read_input_tokens=cache_read or None,
@@ -501,20 +563,29 @@ class ChatAnthropic(BaseChatLLM):
type=LLMStreamEventType.TOOL_CALL,
tool_call=final_content.tool_call,
thinking=final_content.thinking,
- usage=final_content.usage
+ usage=final_content.usage,
)
elif text_started:
yield LLMStreamEvent(
- type=LLMStreamEventType.TEXT_END,
- thinking=final_content.thinking,
- usage=usage
+ type=LLMStreamEventType.TEXT_END, thinking=final_content.thinking, usage=usage
)
@overload
- async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
- ...
+ async def astream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> AsyncIterator[LLMStreamEvent]: ...
- async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
+ async def astream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> AsyncIterator[LLMStreamEvent]:
system_prompt, anthropic_messages = self._convert_messages(messages)
anthropic_tools = self._convert_tools(tools) if tools else None
params = self._build_params(anthropic_messages, system_prompt, anthropic_tools)
@@ -529,7 +600,9 @@ class ChatAnthropic(BaseChatLLM):
if not think_started:
think_started = True
yield LLMStreamEvent(type=LLMStreamEventType.THINK_START)
- yield LLMStreamEvent(type=LLMStreamEventType.THINK_DELTA, content=event.thinking)
+ yield LLMStreamEvent(
+ type=LLMStreamEventType.THINK_DELTA, content=event.thinking
+ )
elif event.type == "text":
if think_started:
yield LLMStreamEvent(type=LLMStreamEventType.THINK_END)
@@ -545,12 +618,15 @@ class ChatAnthropic(BaseChatLLM):
# Extract usage from final message
final_message = await stream.get_final_message()
if final_message.usage:
- cache_creation = getattr(final_message.usage, 'cache_creation_input_tokens', None) or 0
- cache_read = getattr(final_message.usage, 'cache_read_input_tokens', None) or 0
+ cache_creation = (
+ getattr(final_message.usage, "cache_creation_input_tokens", None) or 0
+ )
+ cache_read = getattr(final_message.usage, "cache_read_input_tokens", None) or 0
usage = TokenUsage(
prompt_tokens=final_message.usage.input_tokens,
completion_tokens=final_message.usage.output_tokens,
- total_tokens=final_message.usage.input_tokens + final_message.usage.output_tokens,
+ total_tokens=final_message.usage.input_tokens
+ + final_message.usage.output_tokens,
thinking_tokens=getattr(final_message.usage, "thinking_tokens", None),
cache_creation_input_tokens=cache_creation or None,
cache_read_input_tokens=cache_read or None,
@@ -562,21 +638,15 @@ class ChatAnthropic(BaseChatLLM):
type=LLMStreamEventType.TOOL_CALL,
tool_call=final_content.tool_call,
thinking=final_content.thinking,
- usage=final_content.usage
+ usage=final_content.usage,
)
elif text_started:
yield LLMStreamEvent(
- type=LLMStreamEventType.TEXT_END,
- thinking=final_content.thinking,
- usage=usage
+ type=LLMStreamEventType.TEXT_END, thinking=final_content.thinking, usage=usage
)
def get_metadata(self) -> Metadata:
- return Metadata(
- name=self._model,
- context_window=200000,
- owned_by="anthropic"
- )
+ return Metadata(name=self._model, context_window=200000, owned_by="anthropic")
def get_cache_stats(self) -> dict:
"""
@@ -590,5 +660,5 @@ class ChatAnthropic(BaseChatLLM):
"cache_system_prompt": self.cache_system_prompt,
"cache_tools": self.cache_tools,
"cache_recent_messages": self.cache_recent_messages,
- "model": self._model
+ "model": self._model,
}
diff --git a/windows_use/providers/azure_openai/llm.py b/windows_use/providers/azure_openai/llm.py
index 90c2f52..2008358 100644
--- a/windows_use/providers/azure_openai/llm.py
+++ b/windows_use/providers/azure_openai/llm.py
@@ -29,6 +29,7 @@ from windows_use.tools import Tool
logger = logging.getLogger(__name__)
+
class ChatAzureOpenAI(BaseChatLLM):
"""
Azure OpenAI LLM implementation following the BaseChatLLM protocol.
@@ -43,7 +44,7 @@ class ChatAzureOpenAI(BaseChatLLM):
timeout: float = 600.0,
max_retries: int = 2,
temperature: float | None = None,
- **kwargs
+ **kwargs,
):
"""
Initialize the Azure OpenAI LLM.
@@ -108,10 +109,12 @@ class ChatAzureOpenAI(BaseChatLLM):
b64_imgs = msg.convert_images(format="base64")
for b64 in b64_imgs:
- content_list.append({
- "type": "image_url",
- "image_url": {"url": f"data:{msg.mime_type};base64,{b64}"}
- })
+ content_list.append(
+ {
+ "type": "image_url",
+ "image_url": {"url": f"data:{msg.mime_type};base64,{b64}"},
+ }
+ )
openai_messages.append({"role": "user", "content": content_list})
elif isinstance(msg, AIMessage):
msg_dict: dict = {"role": "assistant", "content": msg.content or ""}
@@ -123,34 +126,21 @@ class ChatAzureOpenAI(BaseChatLLM):
tool_call = {
"id": msg.id,
"type": "function",
- "function": {
- "name": msg.name,
- "arguments": json.dumps(msg.params)
- }
+ "function": {"name": msg.name, "arguments": json.dumps(msg.params)},
}
- openai_messages.append({
- "role": "assistant",
- "content": None,
- "tool_calls": [tool_call]
- })
- openai_messages.append({
- "role": "tool",
- "tool_call_id": msg.id,
- "content": msg.content or ""
- })
+ openai_messages.append(
+ {"role": "assistant", "content": None, "tool_calls": [tool_call]}
+ )
+ openai_messages.append(
+ {"role": "tool", "tool_call_id": msg.id, "content": msg.content or ""}
+ )
return openai_messages
def _convert_tools(self, tools: list[Tool]) -> list[dict]:
"""
Convert Tool objects to Azure-compatible tool definitions.
"""
- return [
- {
- "type": "function",
- "function": tool.json_schema
- }
- for tool in tools
- ]
+ return [{"type": "function", "function": tool.json_schema} for tool in tools]
def _process_response(self, response: Any) -> LLMEvent:
"""
@@ -162,12 +152,13 @@ class ChatAzureOpenAI(BaseChatLLM):
# Capture reasoning tokens if available (o-series models)
thinking_tokens = None
- if hasattr(usage_data, "completion_tokens_details") and usage_data.completion_tokens_details:
+ if (
+ hasattr(usage_data, "completion_tokens_details")
+ and usage_data.completion_tokens_details
+ ):
thinking_tokens = getattr(
usage_data.completion_tokens_details, "reasoning_tokens", None
- ) or getattr(
- usage_data.completion_tokens_details, "thinking_tokens", None
- )
+ ) or getattr(usage_data.completion_tokens_details, "thinking_tokens", None)
usage = TokenUsage(
prompt_tokens=usage_data.prompt_tokens,
@@ -179,15 +170,15 @@ class ChatAzureOpenAI(BaseChatLLM):
# Extract thinking/reasoning content (for o-series models)
thinking = None
if self._is_reasoning_model():
- if hasattr(message, 'reasoning_content'):
+ if hasattr(message, "reasoning_content"):
thinking = message.reasoning_content
- elif hasattr(choice, 'reasoning_content'):
+ elif hasattr(choice, "reasoning_content"):
thinking = choice.reasoning_content
thinking_obj = Thinking(content=thinking, signature=None) if thinking else None
content = None
- if hasattr(message, 'tool_calls') and message.tool_calls:
+ if hasattr(message, "tool_calls") and message.tool_calls:
tool_call = message.tool_calls[0]
try:
params = json.loads(tool_call.function.arguments)
@@ -196,15 +187,16 @@ class ChatAzureOpenAI(BaseChatLLM):
content = LLMEvent(
type=LLMEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call.id,
- name=tool_call.function.name,
- params=params
- ),
- usage=usage
+ tool_call=ToolCall(id=tool_call.id, name=tool_call.function.name, params=params),
+ usage=usage,
)
else:
- content = LLMEvent(type=LLMEventType.TEXT, content=message.content or "", thinking=thinking_obj, usage=usage)
+ content = LLMEvent(
+ type=LLMEventType.TEXT,
+ content=message.content or "",
+ thinking=thinking_obj,
+ usage=usage,
+ )
# Optional: We could pass thinking back in the event if we want, but currently TEXT_END is just content.
# If we need thinking attached to the final message, we might need a THINK_END event before this, or just attach it.
@@ -213,18 +205,25 @@ class ChatAzureOpenAI(BaseChatLLM):
return content
@overload
- def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
- ...
+ def invoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent: ...
- def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
+ def invoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
- params = {
- "model": self._deployment,
- "messages": openai_messages,
- **self.kwargs
- }
+ params = {"model": self._deployment, "messages": openai_messages, **self.kwargs}
# Only add tools if they exist
if openai_tools:
@@ -237,17 +236,17 @@ class ChatAzureOpenAI(BaseChatLLM):
if structured_output:
# Use beta parse endpoint for structured outputs
response = self.client.beta.chat.completions.parse(
- **params,
- response_format=structured_output
+ **params, response_format=structured_output
)
thinking_tokens = None
- if hasattr(response.usage, "completion_tokens_details") and response.usage.completion_tokens_details:
+ if (
+ hasattr(response.usage, "completion_tokens_details")
+ and response.usage.completion_tokens_details
+ ):
thinking_tokens = getattr(
response.usage.completion_tokens_details, "reasoning_tokens", None
- ) or getattr(
- response.usage.completion_tokens_details, "thinking_tokens", None
- )
+ ) or getattr(response.usage.completion_tokens_details, "thinking_tokens", None)
TokenUsage(
prompt_tokens=response.usage.prompt_tokens,
completion_tokens=response.usage.completion_tokens,
@@ -257,7 +256,12 @@ class ChatAzureOpenAI(BaseChatLLM):
parsed = response.choices[0].message.parsed
content_dump = parsed.model_dump()
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content_dump) if isinstance(content_dump, dict) else str(content_dump))
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content_dump)
+ if isinstance(content_dump, dict)
+ else str(content_dump),
+ )
if json_mode:
params["response_format"] = {"type": "json_object"}
@@ -266,18 +270,25 @@ class ChatAzureOpenAI(BaseChatLLM):
return self._process_response(response)
@overload
- async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
- ...
+ async def ainvoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent: ...
- async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
+ async def ainvoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
- params = {
- "model": self._deployment,
- "messages": openai_messages,
- **self.kwargs
- }
+ params = {"model": self._deployment, "messages": openai_messages, **self.kwargs}
if openai_tools:
params["tools"] = openai_tools
@@ -288,17 +299,17 @@ class ChatAzureOpenAI(BaseChatLLM):
if structured_output:
response = await self.aclient.beta.chat.completions.parse(
- **params,
- response_format=structured_output
+ **params, response_format=structured_output
)
thinking_tokens = None
- if hasattr(response.usage, "completion_tokens_details") and response.usage.completion_tokens_details:
+ if (
+ hasattr(response.usage, "completion_tokens_details")
+ and response.usage.completion_tokens_details
+ ):
thinking_tokens = getattr(
response.usage.completion_tokens_details, "reasoning_tokens", None
- ) or getattr(
- response.usage.completion_tokens_details, "thinking_tokens", None
- )
+ ) or getattr(response.usage.completion_tokens_details, "thinking_tokens", None)
usage = TokenUsage(
prompt_tokens=response.usage.prompt_tokens,
completion_tokens=response.usage.completion_tokens,
@@ -308,7 +319,13 @@ class ChatAzureOpenAI(BaseChatLLM):
parsed = response.choices[0].message.parsed
content_dump = parsed.model_dump()
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content_dump) if isinstance(content_dump, dict) else str(content_dump), usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content_dump)
+ if isinstance(content_dump, dict)
+ else str(content_dump),
+ usage=usage,
+ )
if json_mode:
params["response_format"] = {"type": "json_object"}
@@ -317,10 +334,21 @@ class ChatAzureOpenAI(BaseChatLLM):
return self._process_response(response)
@overload
- def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
- ...
+ def stream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> Iterator[LLMStreamEvent]: ...
- def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
+ def stream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> Iterator[LLMStreamEvent]:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
@@ -329,7 +357,7 @@ class ChatAzureOpenAI(BaseChatLLM):
"messages": openai_messages,
"stream": True,
"stream_options": {"include_usage": True},
- **self.kwargs
+ **self.kwargs,
}
if openai_tools:
@@ -357,12 +385,13 @@ class ChatAzureOpenAI(BaseChatLLM):
if not chunk.choices:
if chunk.usage:
thinking_tokens = None
- if hasattr(chunk.usage, "completion_tokens_details") and chunk.usage.completion_tokens_details:
+ if (
+ hasattr(chunk.usage, "completion_tokens_details")
+ and chunk.usage.completion_tokens_details
+ ):
thinking_tokens = getattr(
chunk.usage.completion_tokens_details, "reasoning_tokens", None
- ) or getattr(
- chunk.usage.completion_tokens_details, "thinking_tokens", None
- )
+ ) or getattr(chunk.usage.completion_tokens_details, "thinking_tokens", None)
usage = TokenUsage(
prompt_tokens=chunk.usage.prompt_tokens,
completion_tokens=chunk.usage.completion_tokens,
@@ -374,11 +403,17 @@ class ChatAzureOpenAI(BaseChatLLM):
delta = chunk.choices[0].delta
# Handle reasoning content for o-series models
- if self._is_reasoning_model() and hasattr(delta, 'reasoning_content') and delta.reasoning_content:
+ if (
+ self._is_reasoning_model()
+ and hasattr(delta, "reasoning_content")
+ and delta.reasoning_content
+ ):
if not think_started:
think_started = True
yield LLMStreamEvent(type=LLMStreamEventType.THINK_START)
- yield LLMStreamEvent(type=LLMStreamEventType.THINK_DELTA, content=delta.reasoning_content)
+ yield LLMStreamEvent(
+ type=LLMStreamEventType.THINK_DELTA, content=delta.reasoning_content
+ )
if delta.content:
if think_started:
@@ -390,7 +425,7 @@ class ChatAzureOpenAI(BaseChatLLM):
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_DELTA, content=delta.content)
# Accumulate tool call deltas
- if hasattr(delta, 'tool_calls') and delta.tool_calls:
+ if hasattr(delta, "tool_calls") and delta.tool_calls:
tc_delta = delta.tool_calls[0]
if tc_delta.id:
tool_call_id = tc_delta.id
@@ -409,11 +444,7 @@ class ChatAzureOpenAI(BaseChatLLM):
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call_id,
- name=tool_call_name,
- params=params
- )
+ tool_call=ToolCall(id=tool_call_id, name=tool_call_name, params=params),
)
else:
if think_started:
@@ -422,10 +453,21 @@ class ChatAzureOpenAI(BaseChatLLM):
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_END, usage=usage)
@overload
- async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
- ...
+ async def astream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> AsyncIterator[LLMStreamEvent]: ...
- async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
+ async def astream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> AsyncIterator[LLMStreamEvent]:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
@@ -434,7 +476,7 @@ class ChatAzureOpenAI(BaseChatLLM):
"messages": openai_messages,
"stream": True,
"stream_options": {"include_usage": True},
- **self.kwargs
+ **self.kwargs,
}
if openai_tools:
@@ -462,12 +504,13 @@ class ChatAzureOpenAI(BaseChatLLM):
if not chunk.choices:
if chunk.usage:
thinking_tokens = None
- if hasattr(chunk.usage, "completion_tokens_details") and chunk.usage.completion_tokens_details:
+ if (
+ hasattr(chunk.usage, "completion_tokens_details")
+ and chunk.usage.completion_tokens_details
+ ):
thinking_tokens = getattr(
chunk.usage.completion_tokens_details, "reasoning_tokens", None
- ) or getattr(
- chunk.usage.completion_tokens_details, "thinking_tokens", None
- )
+ ) or getattr(chunk.usage.completion_tokens_details, "thinking_tokens", None)
usage = TokenUsage(
prompt_tokens=chunk.usage.prompt_tokens,
completion_tokens=chunk.usage.completion_tokens,
@@ -478,11 +521,17 @@ class ChatAzureOpenAI(BaseChatLLM):
delta = chunk.choices[0].delta
- if self._is_reasoning_model() and hasattr(delta, 'reasoning_content') and delta.reasoning_content:
+ if (
+ self._is_reasoning_model()
+ and hasattr(delta, "reasoning_content")
+ and delta.reasoning_content
+ ):
if not think_started:
think_started = True
yield LLMStreamEvent(type=LLMStreamEventType.THINK_START)
- yield LLMStreamEvent(type=LLMStreamEventType.THINK_DELTA, content=delta.reasoning_content)
+ yield LLMStreamEvent(
+ type=LLMStreamEventType.THINK_DELTA, content=delta.reasoning_content
+ )
if delta.content:
if think_started:
@@ -494,7 +543,7 @@ class ChatAzureOpenAI(BaseChatLLM):
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_DELTA, content=delta.content)
# Accumulate tool call deltas
- if hasattr(delta, 'tool_calls') and delta.tool_calls:
+ if hasattr(delta, "tool_calls") and delta.tool_calls:
tc_delta = delta.tool_calls[0]
if tc_delta.id:
tool_call_id = tc_delta.id
@@ -513,12 +562,8 @@ class ChatAzureOpenAI(BaseChatLLM):
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call_id,
- name=tool_call_name,
- params=params
- ),
- usage=usage
+ tool_call=ToolCall(id=tool_call_id, name=tool_call_name, params=params),
+ usage=usage,
)
else:
if think_started:
@@ -527,8 +572,4 @@ class ChatAzureOpenAI(BaseChatLLM):
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_END, usage=usage)
def get_metadata(self) -> Metadata:
- return Metadata(
- name=self._deployment,
- context_window=128000,
- owned_by="azure_openai"
- )
+ return Metadata(name=self._deployment, context_window=128000, owned_by="azure_openai")
diff --git a/windows_use/providers/base.py b/windows_use/providers/base.py
index f4b78a0..4879788 100644
--- a/windows_use/providers/base.py
+++ b/windows_use/providers/base.py
@@ -11,7 +11,6 @@ from windows_use.tools import Tool
@runtime_checkable
class BaseChatLLM(Protocol):
-
def sanitize_schema(self, tool_schema: dict) -> dict:
"""Convert full JSON schema into a minimal function schema.
@@ -55,32 +54,49 @@ class BaseChatLLM(Protocol):
}
@property
- def model_name(self) -> str:
- ...
+ def model_name(self) -> str: ...
@property
- def provider(self) -> str:
- ...
+ def provider(self) -> str: ...
@overload
- def invoke(self, messages: list[BaseMessage]|Iterable[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
- ...
+ def invoke(
+ self,
+ messages: list[BaseMessage] | Iterable[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent: ...
@overload
- async def ainvoke(self, messages: list[BaseMessage]|Iterable[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
- ...
+ async def ainvoke(
+ self,
+ messages: list[BaseMessage] | Iterable[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent: ...
@overload
- def stream(self, messages: list[BaseMessage]|Iterable[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
- ...
+ def stream(
+ self,
+ messages: list[BaseMessage] | Iterable[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> Iterator[LLMStreamEvent]: ...
@overload
- async def astream(self, messages: list[BaseMessage]|Iterable[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
- ...
+ async def astream(
+ self,
+ messages: list[BaseMessage] | Iterable[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> AsyncIterator[LLMStreamEvent]: ...
@overload
- def get_metadata(self) -> Metadata:
- ...
+ def get_metadata(self) -> Metadata: ...
@runtime_checkable
diff --git a/windows_use/providers/cerebras/llm.py b/windows_use/providers/cerebras/llm.py
index 1331aa4..3787861 100644
--- a/windows_use/providers/cerebras/llm.py
+++ b/windows_use/providers/cerebras/llm.py
@@ -29,6 +29,7 @@ from windows_use.tools import Tool
logger = logging.getLogger(__name__)
+
class ChatCerebras(BaseChatLLM):
"""
Cerebras LLM implementation following the BaseChatLLM protocol.
@@ -42,7 +43,7 @@ class ChatCerebras(BaseChatLLM):
timeout: float = 60.0,
max_retries: int = 2,
temperature: float | None = None,
- **kwargs
+ **kwargs,
):
"""
Initialize the Cerebras LLM.
@@ -115,10 +116,12 @@ class ChatCerebras(BaseChatLLM):
b64_imgs = msg.convert_images(format="base64")
for b64 in b64_imgs:
- content_list.append({
- "type": "image_url",
- "image_url": {"url": f"data:{msg.mime_type};base64,{b64}"}
- })
+ content_list.append(
+ {
+ "type": "image_url",
+ "image_url": {"url": f"data:{msg.mime_type};base64,{b64}"},
+ }
+ )
cerebras_messages.append({"role": "user", "content": content_list})
elif isinstance(msg, AIMessage):
thinking = getattr(msg, "thinking", None)
@@ -129,34 +132,21 @@ class ChatCerebras(BaseChatLLM):
tool_call = {
"id": msg.id,
"type": "function",
- "function": {
- "name": msg.name,
- "arguments": json.dumps(msg.params)
- }
+ "function": {"name": msg.name, "arguments": json.dumps(msg.params)},
}
- cerebras_messages.append({
- "role": "assistant",
- "content": None,
- "tool_calls": [tool_call]
- })
- cerebras_messages.append({
- "role": "tool",
- "tool_call_id": msg.id,
- "content": msg.content or ""
- })
+ cerebras_messages.append(
+ {"role": "assistant", "content": None, "tool_calls": [tool_call]}
+ )
+ cerebras_messages.append(
+ {"role": "tool", "tool_call_id": msg.id, "content": msg.content or ""}
+ )
return cerebras_messages
def _convert_tools(self, tools: list[Tool]) -> list[dict]:
"""
Convert Tool objects to Cerebras-compatible tool definitions.
"""
- return [
- {
- "type": "function",
- "function": tool.json_schema
- }
- for tool in tools
- ]
+ return [{"type": "function", "function": tool.json_schema} for tool in tools]
def _process_response(self, response: Any) -> LLMEvent:
"""
@@ -174,7 +164,8 @@ class ChatCerebras(BaseChatLLM):
getattr(usage_data, "completion_tokens_details", None),
"reasoning_tokens",
None,
- ) or getattr(
+ )
+ or getattr(
getattr(usage_data, "completion_tokens_details", None),
"thinking_tokens",
None,
@@ -185,7 +176,7 @@ class ChatCerebras(BaseChatLLM):
thinking_obj = Thinking(content=thinking, signature=None) if thinking else None
content = None
- if hasattr(message, 'tool_calls') and message.tool_calls:
+ if hasattr(message, "tool_calls") and message.tool_calls:
tool_call = message.tool_calls[0]
try:
params = json.loads(tool_call.function.arguments)
@@ -194,31 +185,39 @@ class ChatCerebras(BaseChatLLM):
content = LLMEvent(
type=LLMEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call.id,
- name=tool_call.function.name,
- params=params
- ),
- usage=usage
+ tool_call=ToolCall(id=tool_call.id, name=tool_call.function.name, params=params),
+ usage=usage,
)
else:
- content = LLMEvent(type=LLMEventType.TEXT, content=message.content or "", thinking=thinking_obj, usage=usage)
+ content = LLMEvent(
+ type=LLMEventType.TEXT,
+ content=message.content or "",
+ thinking=thinking_obj,
+ usage=usage,
+ )
return content
@overload
- def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
- ...
+ def invoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent: ...
- def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
+ def invoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent:
cerebras_messages = self._convert_messages(messages)
cerebras_tools = self._convert_tools(tools) if tools else None
- params = {
- "model": self._model,
- "messages": cerebras_messages,
- **self.kwargs
- }
+ params = {"model": self._model, "messages": cerebras_messages, **self.kwargs}
# Only add tools if they exist
if cerebras_tools:
@@ -255,7 +254,13 @@ class ChatCerebras(BaseChatLLM):
total_tokens=response.usage.total_tokens,
thinking_tokens=thinking_tokens,
)
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content_dump) if isinstance(content_dump, dict) else str(content_dump), usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content_dump)
+ if isinstance(content_dump, dict)
+ else str(content_dump),
+ usage=usage,
+ )
except (json.JSONDecodeError, ValueError) as e:
logger.error(f"Failed to parse structured output: {e}")
# Fall through to normal response processing
@@ -263,18 +268,25 @@ class ChatCerebras(BaseChatLLM):
return self._process_response(response)
@overload
- async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
- ...
+ async def ainvoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent: ...
- async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
+ async def ainvoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent:
cerebras_messages = self._convert_messages(messages)
cerebras_tools = self._convert_tools(tools) if tools else None
- params = {
- "model": self._model,
- "messages": cerebras_messages,
- **self.kwargs
- }
+ params = {"model": self._model, "messages": cerebras_messages, **self.kwargs}
if cerebras_tools:
params["tools"] = cerebras_tools
@@ -300,17 +312,34 @@ class ChatCerebras(BaseChatLLM):
completion_tokens=response.usage.completion_tokens,
total_tokens=response.usage.total_tokens,
)
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content_dump) if isinstance(content_dump, dict) else str(content_dump), usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content_dump)
+ if isinstance(content_dump, dict)
+ else str(content_dump),
+ usage=usage,
+ )
except (json.JSONDecodeError, ValueError) as e:
logger.error(f"Failed to parse structured output: {e}")
return self._process_response(response)
@overload
- def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
- ...
+ def stream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> Iterator[LLMStreamEvent]: ...
- def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
+ def stream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> Iterator[LLMStreamEvent]:
cerebras_messages = self._convert_messages(messages)
cerebras_tools = self._convert_tools(tools) if tools else None
@@ -318,7 +347,7 @@ class ChatCerebras(BaseChatLLM):
"model": self._model,
"messages": cerebras_messages,
"stream": True,
- **self.kwargs
+ **self.kwargs,
}
if cerebras_tools:
@@ -383,7 +412,7 @@ class ChatCerebras(BaseChatLLM):
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_DELTA, content=delta.content)
# Accumulate tool call deltas
- if hasattr(delta, 'tool_calls') and delta.tool_calls:
+ if hasattr(delta, "tool_calls") and delta.tool_calls:
tc_delta = delta.tool_calls[0]
if tc_delta.id:
tool_call_id = tc_delta.id
@@ -402,12 +431,8 @@ class ChatCerebras(BaseChatLLM):
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call_id,
- name=tool_call_name,
- params=params
- ),
- usage=usage
+ tool_call=ToolCall(id=tool_call_id, name=tool_call_name, params=params),
+ usage=usage,
)
else:
if think_started:
@@ -416,10 +441,21 @@ class ChatCerebras(BaseChatLLM):
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_END, usage=usage)
@overload
- async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
- ...
+ async def astream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> AsyncIterator[LLMStreamEvent]: ...
- async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
+ async def astream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> AsyncIterator[LLMStreamEvent]:
cerebras_messages = self._convert_messages(messages)
cerebras_tools = self._convert_tools(tools) if tools else None
@@ -427,7 +463,7 @@ class ChatCerebras(BaseChatLLM):
"model": self._model,
"messages": cerebras_messages,
"stream": True,
- **self.kwargs
+ **self.kwargs,
}
if cerebras_tools:
@@ -492,7 +528,7 @@ class ChatCerebras(BaseChatLLM):
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_DELTA, content=delta.content)
# Accumulate tool call deltas
- if hasattr(delta, 'tool_calls') and delta.tool_calls:
+ if hasattr(delta, "tool_calls") and delta.tool_calls:
tc_delta = delta.tool_calls[0]
if tc_delta.id:
tool_call_id = tc_delta.id
@@ -511,12 +547,8 @@ class ChatCerebras(BaseChatLLM):
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call_id,
- name=tool_call_name,
- params=params
- ),
- usage=usage
+ tool_call=ToolCall(id=tool_call_id, name=tool_call_name, params=params),
+ usage=usage,
)
else:
if think_started:
@@ -528,5 +560,5 @@ class ChatCerebras(BaseChatLLM):
return Metadata(
name=self._model,
context_window=8192, # Typical for llama3 on Cerebras, can be adjusted
- owned_by="cerebras"
+ owned_by="cerebras",
)
diff --git a/windows_use/providers/deepgram/stt.py b/windows_use/providers/deepgram/stt.py
index 5759ec9..9622f07 100644
--- a/windows_use/providers/deepgram/stt.py
+++ b/windows_use/providers/deepgram/stt.py
@@ -103,9 +103,7 @@ class STTDeepgram(BaseSTT):
with open(file_path, "rb") as audio:
source = {"buffer": audio}
options = self._build_options()
- response = await self.client.listen.asyncrest.v("1").transcribe_file(
- source, options
- )
+ response = await self.client.listen.asyncrest.v("1").transcribe_file(source, options)
text = response.results.channels[0].alternatives[0].transcript
logger.debug(f"[STTDeepgram] Async transcription complete: {len(text)} chars")
diff --git a/windows_use/providers/deepgram/tts.py b/windows_use/providers/deepgram/tts.py
index 9c56e2a..a587eb5 100644
--- a/windows_use/providers/deepgram/tts.py
+++ b/windows_use/providers/deepgram/tts.py
@@ -116,13 +116,9 @@ class TTSDeepgram(BaseTTS):
speak_input = {"text": text}
if self.encoding == "linear16":
- response = await self.client.speak.asyncrest.v("1").stream(
- speak_input, options
- )
+ response = await self.client.speak.asyncrest.v("1").stream(speak_input, options)
self._save_pcm_as_wav(response.stream.read(), output_path)
else:
- await self.client.speak.asyncrest.v("1").save(
- output_path, speak_input, options
- )
+ await self.client.speak.asyncrest.v("1").save(output_path, speak_input, options)
logger.debug(f"[TTSDeepgram] Async audio saved to {output_path}")
diff --git a/windows_use/providers/elevenlabs/tts.py b/windows_use/providers/elevenlabs/tts.py
index e26f0aa..1b40cad 100644
--- a/windows_use/providers/elevenlabs/tts.py
+++ b/windows_use/providers/elevenlabs/tts.py
@@ -123,9 +123,7 @@ class TTSElevenLabs(BaseTTS):
audio_iterator = self.client.text_to_speech.convert(**kwargs)
# Collect all audio bytes from the iterator
- audio_bytes = b"".join(
- chunk for chunk in audio_iterator if isinstance(chunk, bytes)
- )
+ audio_bytes = b"".join(chunk for chunk in audio_iterator if isinstance(chunk, bytes))
if self.output_format.startswith("pcm_"):
self._save_pcm_as_wav(audio_bytes, output_path)
@@ -155,9 +153,7 @@ class TTSElevenLabs(BaseTTS):
audio_iterator = await self.aclient.text_to_speech.convert(**kwargs)
# Collect all audio bytes from the async iterator
- audio_bytes = b"".join(
- chunk for chunk in audio_iterator if isinstance(chunk, bytes)
- )
+ audio_bytes = b"".join(chunk for chunk in audio_iterator if isinstance(chunk, bytes))
if self.output_format.startswith("pcm_"):
self._save_pcm_as_wav(audio_bytes, output_path)
diff --git a/windows_use/providers/events.py b/windows_use/providers/events.py
index fe6a979..dae1e30 100644
--- a/windows_use/providers/events.py
+++ b/windows_use/providers/events.py
@@ -15,22 +15,26 @@ class LLMStreamEventType(str, Enum):
THINK_END = "think_end"
ERROR = "error"
+
class LLMEventType(str, Enum):
TEXT = "text"
TOOL_CALL = "tool_call"
ERROR = "error"
+
class Thinking(BaseModel):
"""Thinking/reasoning content with optional cryptographic signature (Anthropic)."""
content: str | None = None
signature: str | bytes | None = None
+
class ToolCall(BaseModel):
id: str
name: str
params: dict
+
class LLMStreamEvent(BaseModel):
type: LLMStreamEventType
thinking: Thinking | None = None
diff --git a/windows_use/providers/google/llm.py b/windows_use/providers/google/llm.py
index 22c285b..2c1e739 100644
--- a/windows_use/providers/google/llm.py
+++ b/windows_use/providers/google/llm.py
@@ -66,7 +66,9 @@ class ChatGoogle(BaseChatLLM):
**kwargs: Additional arguments for GenerateContentConfig.
"""
self._model = model
- self.api_key = api_key or os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")
+ self.api_key = (
+ api_key or os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")
+ )
self.base_url = base_url or os.environ.get("GOOGLE_BASE_URL")
self.temperature = temperature
self.thinking_budget = thinking_budget
@@ -124,9 +126,7 @@ class ChatGoogle(BaseChatLLM):
img_bytes_list = msg.convert_images(format="bytes")
for img_bytes in img_bytes_list:
- parts.append(
- types.Part.from_bytes(data=img_bytes, mime_type=msg.mime_type)
- )
+ parts.append(types.Part.from_bytes(data=img_bytes, mime_type=msg.mime_type))
raw_contents.append(types.Content(role="user", parts=parts))
elif isinstance(msg, AIMessage):
parts = []
@@ -141,9 +141,7 @@ class ChatGoogle(BaseChatLLM):
model_parts: list[types.Part] = []
if msg.thinking:
model_parts.append(types.Part(thought=True, text=msg.thinking))
- model_parts.append(
- types.Part.from_function_call(name=msg.name, args=msg.params)
- )
+ model_parts.append(types.Part.from_function_call(name=msg.name, args=msg.params))
raw_contents.append(types.Content(role="model", parts=model_parts))
# Function response
@@ -225,8 +223,8 @@ class ChatGoogle(BaseChatLLM):
if tools:
config_params["tools"] = tools
- config_params["automatic_function_calling"] = (
- types.AutomaticFunctionCallingConfig(disable=True)
+ config_params["automatic_function_calling"] = types.AutomaticFunctionCallingConfig(
+ disable=True
)
if self.temperature is not None:
@@ -326,12 +324,8 @@ class ChatGoogle(BaseChatLLM):
fc_id = getattr(fc, "id", None) or f"call_{uuid.uuid4().hex[:8]}"
return LLMEvent(
type=LLMEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=fc_id,
- name=fc.name,
- params=dict(fc.args) if fc.args else {}
- ),
- usage=usage
+ tool_call=ToolCall(id=fc_id, name=fc.name, params=dict(fc.args) if fc.args else {}),
+ usage=usage,
)
# Handle regular text response (use _extract_text to avoid SDK warning
@@ -339,8 +333,12 @@ class ChatGoogle(BaseChatLLM):
text_content = self._extract_text(response)
thinking_content = self._extract_thinking(response)
- thinking_obj = Thinking(content=thinking_content, signature=None) if thinking_content else None
- return LLMEvent(type=LLMEventType.TEXT, content=text_content, thinking=thinking_obj, usage=usage)
+ thinking_obj = (
+ Thinking(content=thinking_content, signature=None) if thinking_content else None
+ )
+ return LLMEvent(
+ type=LLMEventType.TEXT, content=text_content, thinking=thinking_obj, usage=usage
+ )
@overload
def invoke(
@@ -373,7 +371,11 @@ class ChatGoogle(BaseChatLLM):
parsed = structured_output.model_validate_json(text)
usage = self._extract_usage(response.usage_metadata)
content = parsed.model_dump() if hasattr(parsed, "model_dump") else str(parsed)
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content) if isinstance(content, dict) else content, usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content) if isinstance(content, dict) else content,
+ usage=usage,
+ )
return self._process_response(response)
@@ -408,7 +410,11 @@ class ChatGoogle(BaseChatLLM):
parsed = structured_output.model_validate_json(text)
usage = self._extract_usage(response.usage_metadata)
content = parsed.model_dump() if hasattr(parsed, "model_dump") else str(parsed)
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content) if isinstance(content, dict) else content, usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content) if isinstance(content, dict) else content,
+ usage=usage,
+ )
return self._process_response(response)
@@ -450,21 +456,23 @@ class ChatGoogle(BaseChatLLM):
if not think_started:
think_started = True
yield LLMStreamEvent(type=LLMStreamEventType.THINK_START)
- yield LLMStreamEvent(type=LLMStreamEventType.THINK_DELTA, content=part.text)
+ yield LLMStreamEvent(
+ type=LLMStreamEventType.THINK_DELTA, content=part.text
+ )
# Detect function calls in stream
fc = getattr(part, "function_call", None)
if fc:
fc_id = f"call_{uuid.uuid4().hex[:8]}"
tool_params = dict(fc.args) if fc.args else {}
- chunk_usage = self._extract_usage(chunk.usage_metadata) if hasattr(chunk, "usage_metadata") and chunk.usage_metadata else usage
+ chunk_usage = (
+ self._extract_usage(chunk.usage_metadata)
+ if hasattr(chunk, "usage_metadata") and chunk.usage_metadata
+ else usage
+ )
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=fc_id,
- name=fc.name,
- params=tool_params
- ),
- usage=chunk_usage
+ tool_call=ToolCall(id=fc_id, name=fc.name, params=tool_params),
+ usage=chunk_usage,
)
except (AttributeError, IndexError):
pass
@@ -526,21 +534,23 @@ class ChatGoogle(BaseChatLLM):
if not think_started:
think_started = True
yield LLMStreamEvent(type=LLMStreamEventType.THINK_START)
- yield LLMStreamEvent(type=LLMStreamEventType.THINK_DELTA, content=part.text)
+ yield LLMStreamEvent(
+ type=LLMStreamEventType.THINK_DELTA, content=part.text
+ )
# Detect function calls in stream
fc = getattr(part, "function_call", None)
if fc:
fc_id = f"call_{uuid.uuid4().hex[:8]}"
tool_params = dict(fc.args) if fc.args else {}
- chunk_usage = self._extract_usage(chunk.usage_metadata) if hasattr(chunk, "usage_metadata") and chunk.usage_metadata else usage
+ chunk_usage = (
+ self._extract_usage(chunk.usage_metadata)
+ if hasattr(chunk, "usage_metadata") and chunk.usage_metadata
+ else usage
+ )
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=fc_id,
- name=fc.name,
- params=tool_params
- ),
- usage=chunk_usage
+ tool_call=ToolCall(id=fc_id, name=fc.name, params=tool_params),
+ usage=chunk_usage,
)
except (AttributeError, IndexError):
pass
diff --git a/windows_use/providers/google/stt.py b/windows_use/providers/google/stt.py
index 33a097c..b8765fd 100644
--- a/windows_use/providers/google/stt.py
+++ b/windows_use/providers/google/stt.py
@@ -47,9 +47,7 @@ class STTGoogle(BaseSTT):
):
self._model = model
self.api_key = (
- api_key
- or os.environ.get("GEMINI_API_KEY")
- or os.environ.get("GOOGLE_API_KEY")
+ api_key or os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")
)
self.prompt = prompt
self.language = language
diff --git a/windows_use/providers/google/tts.py b/windows_use/providers/google/tts.py
index c632cd5..3ee7721 100644
--- a/windows_use/providers/google/tts.py
+++ b/windows_use/providers/google/tts.py
@@ -22,11 +22,36 @@ logger = logging.getLogger(__name__)
# Sulafat (Warm)
GOOGLE_TTS_VOICES = [
- "Zephyr", "Puck", "Charon", "Kore", "Fenrir", "Leda", "Orus",
- "Aoede", "Callirrhoe", "Autonoe", "Enceladus", "Iapetus", "Umbriel",
- "Algieba", "Despina", "Erinome", "Algenib", "Rasalgethi", "Laomedeia",
- "Achernar", "Alnilam", "Schedar", "Gacrux", "Pulcherrima", "Achird",
- "Zubenelgenubi", "Vindemiatrix", "Sadachbia", "Sadaltager", "Sulafat",
+ "Zephyr",
+ "Puck",
+ "Charon",
+ "Kore",
+ "Fenrir",
+ "Leda",
+ "Orus",
+ "Aoede",
+ "Callirrhoe",
+ "Autonoe",
+ "Enceladus",
+ "Iapetus",
+ "Umbriel",
+ "Algieba",
+ "Despina",
+ "Erinome",
+ "Algenib",
+ "Rasalgethi",
+ "Laomedeia",
+ "Achernar",
+ "Alnilam",
+ "Schedar",
+ "Gacrux",
+ "Pulcherrima",
+ "Achird",
+ "Zubenelgenubi",
+ "Vindemiatrix",
+ "Sadachbia",
+ "Sadaltager",
+ "Sulafat",
]
@@ -72,9 +97,7 @@ class TTSGoogle(BaseTTS):
self.voice = voice
self.sample_rate = sample_rate
self.api_key = (
- api_key
- or os.environ.get("GEMINI_API_KEY")
- or os.environ.get("GOOGLE_API_KEY")
+ api_key or os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")
)
self.client = genai.Client(api_key=self.api_key)
diff --git a/windows_use/providers/groq/llm.py b/windows_use/providers/groq/llm.py
index 0a2b871..4c13d16 100644
--- a/windows_use/providers/groq/llm.py
+++ b/windows_use/providers/groq/llm.py
@@ -29,6 +29,7 @@ from windows_use.tools import Tool
logger = logging.getLogger(__name__)
+
class ChatGroq(BaseChatLLM):
"""
Groq LLM implementation following the BaseChatLLM protocol.
@@ -47,7 +48,7 @@ class ChatGroq(BaseChatLLM):
timeout: float = 60.0,
max_retries: int = 2,
temperature: float | None = None,
- **kwargs
+ **kwargs,
):
"""
Initialize the Groq LLM.
@@ -90,9 +91,7 @@ class ChatGroq(BaseChatLLM):
def _is_reasoning_model(self) -> bool:
"""Check if the model supports reasoning (gpt-oss, qwen3, etc.)."""
m = self._model.lower()
- return any(
- p in m for p in ("gpt-oss", "qwen3-32b", "qwen/qwen3")
- )
+ return any(p in m for p in ("gpt-oss", "qwen3-32b", "qwen/qwen3"))
def _convert_messages(self, messages: list[BaseMessage]) -> list[dict]:
"""
@@ -112,10 +111,12 @@ class ChatGroq(BaseChatLLM):
b64_imgs = msg.convert_images(format="base64")
for b64 in b64_imgs:
- content_list.append({
- "type": "image_url",
- "image_url": {"url": f"data:{msg.mime_type};base64,{b64}"}
- })
+ content_list.append(
+ {
+ "type": "image_url",
+ "image_url": {"url": f"data:{msg.mime_type};base64,{b64}"},
+ }
+ )
groq_messages.append({"role": "user", "content": content_list})
elif isinstance(msg, AIMessage):
msg_dict: dict = {"role": "assistant", "content": msg.content or ""}
@@ -127,34 +128,21 @@ class ChatGroq(BaseChatLLM):
tool_call = {
"id": msg.id,
"type": "function",
- "function": {
- "name": msg.name,
- "arguments": json.dumps(msg.params)
- }
+ "function": {"name": msg.name, "arguments": json.dumps(msg.params)},
}
- groq_messages.append({
- "role": "assistant",
- "content": None,
- "tool_calls": [tool_call]
- })
- groq_messages.append({
- "role": "tool",
- "tool_call_id": msg.id,
- "content": msg.content or ""
- })
+ groq_messages.append(
+ {"role": "assistant", "content": None, "tool_calls": [tool_call]}
+ )
+ groq_messages.append(
+ {"role": "tool", "tool_call_id": msg.id, "content": msg.content or ""}
+ )
return groq_messages
def _convert_tools(self, tools: list[Tool]) -> list[dict]:
"""
Convert Tool objects to Groq-compatible tool definitions.
"""
- return [
- {
- "type": "function",
- "function": tool.json_schema
- }
- for tool in tools
- ]
+ return [{"type": "function", "function": tool.json_schema} for tool in tools]
def _process_response(self, response: Any) -> LLMEvent:
"""Process Groq API response into AIMessage or ToolMessage."""
@@ -170,14 +158,17 @@ class ChatGroq(BaseChatLLM):
getattr(usage_data, "completion_tokens_details", None),
"reasoning_tokens",
None,
- ) or getattr(
+ )
+ or getattr(
getattr(usage_data, "completion_tokens_details", None),
"thinking_tokens",
None,
),
)
- thinking = getattr(message, "reasoning", None) or getattr(message, "reasoning_content", None)
+ thinking = getattr(message, "reasoning", None) or getattr(
+ message, "reasoning_content", None
+ )
thinking_obj = Thinking(content=thinking, signature=None) if thinking else None
if hasattr(message, "tool_calls") and message.tool_calls:
@@ -189,28 +180,36 @@ class ChatGroq(BaseChatLLM):
params = {}
return LLMEvent(
type=LLMEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call.id,
- name=tool_call.function.name,
- params=params
- ),
- usage=usage
+ tool_call=ToolCall(id=tool_call.id, name=tool_call.function.name, params=params),
+ usage=usage,
)
- return LLMEvent(type=LLMEventType.TEXT, content=message.content or "", thinking=thinking_obj, usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=message.content or "",
+ thinking=thinking_obj,
+ usage=usage,
+ )
@overload
- def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
- ...
+ def invoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent: ...
- def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
+ def invoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent:
groq_messages = self._convert_messages(messages)
groq_tools = self._convert_tools(tools) if tools else None
- params = {
- "model": self._model,
- "messages": groq_messages,
- **self.kwargs
- }
+ params = {"model": self._model, "messages": groq_messages, **self.kwargs}
# Only add tools if they exist
if groq_tools:
@@ -245,19 +244,25 @@ class ChatGroq(BaseChatLLM):
content = parsed.model_dump() if hasattr(parsed, "model_dump") else str(parsed)
thinking_tokens = None
- if response.usage and hasattr(response.usage, "completion_tokens_details") and response.usage.completion_tokens_details:
+ if (
+ response.usage
+ and hasattr(response.usage, "completion_tokens_details")
+ and response.usage.completion_tokens_details
+ ):
thinking_tokens = getattr(
response.usage.completion_tokens_details, "reasoning_tokens", None
- ) or getattr(
- response.usage.completion_tokens_details, "thinking_tokens", None
- )
+ ) or getattr(response.usage.completion_tokens_details, "thinking_tokens", None)
usage = TokenUsage(
prompt_tokens=response.usage.prompt_tokens if response.usage else 0,
completion_tokens=response.usage.completion_tokens if response.usage else 0,
total_tokens=response.usage.total_tokens if response.usage else 0,
thinking_tokens=thinking_tokens,
)
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content) if isinstance(content, dict) else content, usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content) if isinstance(content, dict) else content,
+ usage=usage,
+ )
except (json.JSONDecodeError, ValueError) as e:
logger.error(f"Failed to parse structured output: {e}")
# Fall through to normal response processing
@@ -265,18 +270,25 @@ class ChatGroq(BaseChatLLM):
return self._process_response(response)
@overload
- async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
- ...
+ async def ainvoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent: ...
- async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
+ async def ainvoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent:
groq_messages = self._convert_messages(messages)
groq_tools = self._convert_tools(tools) if tools else None
- params = {
- "model": self._model,
- "messages": groq_messages,
- **self.kwargs
- }
+ params = {"model": self._model, "messages": groq_messages, **self.kwargs}
if groq_tools:
params["tools"] = groq_tools
@@ -306,38 +318,50 @@ class ChatGroq(BaseChatLLM):
content = parsed.model_dump() if hasattr(parsed, "model_dump") else str(parsed)
thinking_tokens = None
- if response.usage and hasattr(response.usage, "completion_tokens_details") and response.usage.completion_tokens_details:
+ if (
+ response.usage
+ and hasattr(response.usage, "completion_tokens_details")
+ and response.usage.completion_tokens_details
+ ):
thinking_tokens = getattr(
response.usage.completion_tokens_details, "reasoning_tokens", None
- ) or getattr(
- response.usage.completion_tokens_details, "thinking_tokens", None
- )
+ ) or getattr(response.usage.completion_tokens_details, "thinking_tokens", None)
usage = TokenUsage(
prompt_tokens=response.usage.prompt_tokens if response.usage else 0,
completion_tokens=response.usage.completion_tokens if response.usage else 0,
total_tokens=response.usage.total_tokens if response.usage else 0,
thinking_tokens=thinking_tokens,
)
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content) if isinstance(content, dict) else content, usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content) if isinstance(content, dict) else content,
+ usage=usage,
+ )
except (json.JSONDecodeError, ValueError) as e:
logger.error(f"Failed to parse structured output: {e}")
return self._process_response(response)
@overload
- def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
- ...
+ def stream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> Iterator[LLMStreamEvent]: ...
- def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
+ def stream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> Iterator[LLMStreamEvent]:
groq_messages = self._convert_messages(messages)
groq_tools = self._convert_tools(tools) if tools else None
- params = {
- "model": self._model,
- "messages": groq_messages,
- "stream": True,
- **self.kwargs
- }
+ params = {"model": self._model, "messages": groq_messages, "stream": True, **self.kwargs}
if groq_tools:
params["tools"] = groq_tools
@@ -386,7 +410,9 @@ class ChatGroq(BaseChatLLM):
delta = chunk.choices[0].delta
- reasoning_delta = getattr(delta, "reasoning", None) or getattr(delta, "reasoning_content", None)
+ reasoning_delta = getattr(delta, "reasoning", None) or getattr(
+ delta, "reasoning_content", None
+ )
if reasoning_delta:
if not think_started:
think_started = True
@@ -421,12 +447,8 @@ class ChatGroq(BaseChatLLM):
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call_id,
- name=tool_call_name,
- params=params
- ),
- usage=usage
+ tool_call=ToolCall(id=tool_call_id, name=tool_call_name, params=params),
+ usage=usage,
)
else:
if think_started:
@@ -435,19 +457,25 @@ class ChatGroq(BaseChatLLM):
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_END, usage=usage)
@overload
- async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
- ...
+ async def astream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> AsyncIterator[LLMStreamEvent]: ...
- async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
+ async def astream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> AsyncIterator[LLMStreamEvent]:
groq_messages = self._convert_messages(messages)
groq_tools = self._convert_tools(tools) if tools else None
- params = {
- "model": self._model,
- "messages": groq_messages,
- "stream": True,
- **self.kwargs
- }
+ params = {"model": self._model, "messages": groq_messages, "stream": True, **self.kwargs}
if groq_tools:
params["tools"] = groq_tools
@@ -496,7 +524,9 @@ class ChatGroq(BaseChatLLM):
delta = chunk.choices[0].delta
- reasoning_delta = getattr(delta, "reasoning", None) or getattr(delta, "reasoning_content", None)
+ reasoning_delta = getattr(delta, "reasoning", None) or getattr(
+ delta, "reasoning_content", None
+ )
if reasoning_delta:
if not think_started:
think_started = True
@@ -531,12 +561,8 @@ class ChatGroq(BaseChatLLM):
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call_id,
- name=tool_call_name,
- params=params
- ),
- usage=usage
+ tool_call=ToolCall(id=tool_call_id, name=tool_call_name, params=params),
+ usage=usage,
)
else:
if think_started:
@@ -555,8 +581,4 @@ class ChatGroq(BaseChatLLM):
elif "gemma-2" in self._model:
context_window = 8192
- return Metadata(
- name=self._model,
- context_window=context_window,
- owned_by="groq"
- )
+ return Metadata(name=self._model, context_window=context_window, owned_by="groq")
diff --git a/windows_use/providers/litellm/llm.py b/windows_use/providers/litellm/llm.py
index c57fe2a..6678971 100644
--- a/windows_use/providers/litellm/llm.py
+++ b/windows_use/providers/litellm/llm.py
@@ -109,10 +109,12 @@ class ChatLiteLLM(BaseChatLLM):
b64_imgs = msg.convert_images(format="base64")
for b64 in b64_imgs:
- content_list.append({
- "type": "image_url",
- "image_url": {"url": f"data:{msg.mime_type};base64,{b64}"},
- })
+ content_list.append(
+ {
+ "type": "image_url",
+ "image_url": {"url": f"data:{msg.mime_type};base64,{b64}"},
+ }
+ )
converted.append({"role": "user", "content": content_list})
elif isinstance(msg, AIMessage):
msg_dict: dict = {"role": "assistant", "content": msg.content or ""}
@@ -149,11 +151,13 @@ class ChatLiteLLM(BaseChatLLM):
{"type": "thinking", "thinking": thinking, "signature": sig}
]
converted.append(asst_msg)
- converted.append({
- "role": "tool",
- "tool_call_id": msg.id,
- "content": msg.content or "",
- })
+ converted.append(
+ {
+ "role": "tool",
+ "tool_call_id": msg.id,
+ "content": msg.content or "",
+ }
+ )
return converted
def _convert_tools(self, tools: list[Tool]) -> list[dict]:
@@ -212,12 +216,13 @@ class ChatLiteLLM(BaseChatLLM):
# Extract reasoning/thinking tokens if available
thinking_tokens = None
- if hasattr(usage_data, "completion_tokens_details") and usage_data.completion_tokens_details:
+ if (
+ hasattr(usage_data, "completion_tokens_details")
+ and usage_data.completion_tokens_details
+ ):
thinking_tokens = getattr(
usage_data.completion_tokens_details, "reasoning_tokens", None
- ) or getattr(
- usage_data.completion_tokens_details, "thinking_tokens", None
- )
+ ) or getattr(usage_data.completion_tokens_details, "thinking_tokens", None)
# Extract cache tokens if available
cache_creation = None
@@ -262,15 +267,16 @@ class ChatLiteLLM(BaseChatLLM):
content = LLMEvent(
type=LLMEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call.id,
- name=tool_call.function.name,
- params=params
- ),
- usage=usage
+ tool_call=ToolCall(id=tool_call.id, name=tool_call.function.name, params=params),
+ usage=usage,
)
else:
- content = LLMEvent(type=LLMEventType.TEXT, content=message.content or "", thinking=thinking_obj, usage=usage)
+ content = LLMEvent(
+ type=LLMEventType.TEXT,
+ content=message.content or "",
+ thinking=thinking_obj,
+ usage=usage,
+ )
return content
@@ -295,9 +301,7 @@ class ChatLiteLLM(BaseChatLLM):
if structured_output:
# Use JSON mode and parse the output into the structured model
- params = self._build_params(
- converted_messages, converted_tools, json_mode=True
- )
+ params = self._build_params(converted_messages, converted_tools, json_mode=True)
response = litellm.completion(**params)
try:
@@ -307,7 +311,13 @@ class ChatLiteLLM(BaseChatLLM):
content_dump = parsed_obj.model_dump()
usage = self._extract_usage(response.usage) if response.usage else None
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content_dump) if isinstance(content_dump, dict) else str(content_dump), usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content_dump)
+ if isinstance(content_dump, dict)
+ else str(content_dump),
+ usage=usage,
+ )
except (json.JSONDecodeError, TypeError, ValueError) as e:
logger.error(f"Failed to parse structured output: {e}")
# Fall through to normal processing
@@ -336,9 +346,7 @@ class ChatLiteLLM(BaseChatLLM):
converted_tools = self._convert_tools(tools) if tools else None
if structured_output:
- params = self._build_params(
- converted_messages, converted_tools, json_mode=True
- )
+ params = self._build_params(converted_messages, converted_tools, json_mode=True)
response = await litellm.acompletion(**params)
try:
@@ -348,7 +356,13 @@ class ChatLiteLLM(BaseChatLLM):
content_dump = parsed_obj.model_dump()
usage = self._extract_usage(response.usage) if response.usage else None
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content_dump) if isinstance(content_dump, dict) else str(content_dump), usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content_dump)
+ if isinstance(content_dump, dict)
+ else str(content_dump),
+ usage=usage,
+ )
except (json.JSONDecodeError, TypeError, ValueError) as e:
logger.error(f"Failed to parse structured output: {e}")
@@ -402,7 +416,9 @@ class ChatLiteLLM(BaseChatLLM):
if not think_started:
think_started = True
yield LLMStreamEvent(type=LLMStreamEventType.THINK_START)
- yield LLMStreamEvent(type=LLMStreamEventType.THINK_DELTA, content=delta.reasoning_content)
+ yield LLMStreamEvent(
+ type=LLMStreamEventType.THINK_DELTA, content=delta.reasoning_content
+ )
if hasattr(delta, "content") and delta.content:
if think_started:
@@ -433,11 +449,7 @@ class ChatLiteLLM(BaseChatLLM):
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call_id,
- name=tool_call_name,
- params=params
- )
+ tool_call=ToolCall(id=tool_call_id, name=tool_call_name, params=params),
)
else:
if think_started:
@@ -491,7 +503,9 @@ class ChatLiteLLM(BaseChatLLM):
if not think_started:
think_started = True
yield LLMStreamEvent(type=LLMStreamEventType.THINK_START)
- yield LLMStreamEvent(type=LLMStreamEventType.THINK_DELTA, content=delta.reasoning_content)
+ yield LLMStreamEvent(
+ type=LLMStreamEventType.THINK_DELTA, content=delta.reasoning_content
+ )
if hasattr(delta, "content") and delta.content:
if think_started:
@@ -522,12 +536,8 @@ class ChatLiteLLM(BaseChatLLM):
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call_id,
- name=tool_call_name,
- params=params
- ),
- usage=usage
+ tool_call=ToolCall(id=tool_call_id, name=tool_call_name, params=params),
+ usage=usage,
)
else:
if think_started:
diff --git a/windows_use/providers/mistral/llm.py b/windows_use/providers/mistral/llm.py
index bc2c115..673e8fb 100644
--- a/windows_use/providers/mistral/llm.py
+++ b/windows_use/providers/mistral/llm.py
@@ -56,7 +56,7 @@ class ChatMistral(BaseChatLLM):
base_url: str | None = None,
timeout: int | None = None,
temperature: float | None = None,
- **kwargs
+ **kwargs,
):
"""
Initialize the Mistral LLM.
@@ -100,15 +100,19 @@ class ChatMistral(BaseChatLLM):
b64_imgs = msg.convert_images(format="base64")
for b64 in b64_imgs:
- content.append({
- "type": "image_url",
- "image_url": {"url": f"data:{msg.mime_type};base64,{b64}"},
- })
+ content.append(
+ {
+ "type": "image_url",
+ "image_url": {"url": f"data:{msg.mime_type};base64,{b64}"},
+ }
+ )
mistral_messages.append({"role": "user", "content": content})
elif isinstance(msg, AIMessage):
if getattr(msg, "thinking", None):
# Magistral models: pass thinking as content chunks for multi-turn continuity
- content = [{"type": "thinking", "thinking": [{"type": "text", "text": msg.thinking}]}]
+ content = [
+ {"type": "thinking", "thinking": [{"type": "text", "text": msg.thinking}]}
+ ]
if msg.content:
content.append({"type": "text", "text": msg.content})
mistral_messages.append({"role": "assistant", "content": content})
@@ -118,37 +122,34 @@ class ChatMistral(BaseChatLLM):
# Mistral requires assistant message with tool_calls followed by tool message
# API expects 9 alphanumeric chars; model returns long IDs (toolu_...)
tool_id = _mistral_tool_call_id(msg.id)
- mistral_messages.append({
- "role": "assistant",
- "content": "",
- "tool_calls": [{
- "id": tool_id,
- "type": "function",
- "function": {
- "name": msg.name,
- "arguments": json.dumps(msg.params)
- }
- }]
- })
- mistral_messages.append({
- "role": "tool",
- "tool_call_id": tool_id,
- "name": msg.name,
- "content": msg.content or ""
- })
+ mistral_messages.append(
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": tool_id,
+ "type": "function",
+ "function": {"name": msg.name, "arguments": json.dumps(msg.params)},
+ }
+ ],
+ }
+ )
+ mistral_messages.append(
+ {
+ "role": "tool",
+ "tool_call_id": tool_id,
+ "name": msg.name,
+ "content": msg.content or "",
+ }
+ )
return mistral_messages
def _convert_tools(self, tools: list[Tool]) -> list[dict]:
"""
Convert Tool objects to Mistral-compatible tool definitions.
"""
- return [
- {
- "type": "function",
- "function": tool.json_schema
- }
- for tool in tools
- ]
+ return [{"type": "function", "function": tool.json_schema} for tool in tools]
def _extract_content(self, raw_content: Any) -> tuple[str, str | None]:
"""
@@ -198,12 +199,13 @@ class ChatMistral(BaseChatLLM):
# Mistral API doesn't expose thinking_tokens; check usage.prompt_tokens_details
# or estimate from thinking content when available
thinking_tokens = None
- if hasattr(usage_data, "completion_tokens_details") and usage_data.completion_tokens_details:
+ if (
+ hasattr(usage_data, "completion_tokens_details")
+ and usage_data.completion_tokens_details
+ ):
thinking_tokens = getattr(
usage_data.completion_tokens_details, "reasoning_tokens", None
- ) or getattr(
- usage_data.completion_tokens_details, "thinking_tokens", None
- )
+ ) or getattr(usage_data.completion_tokens_details, "thinking_tokens", None)
if hasattr(usage_data, "prompt_tokens_details") and usage_data.prompt_tokens_details:
thinking_tokens = thinking_tokens or getattr(
usage_data.prompt_tokens_details, "reasoning_tokens", None
@@ -219,7 +221,7 @@ class ChatMistral(BaseChatLLM):
content = None
thinking = None
- if hasattr(message, 'tool_calls') and message.tool_calls:
+ if hasattr(message, "tool_calls") and message.tool_calls:
# Extract thinking from content if present (Magistral thinking models)
if message.content:
_, thinking = self._extract_content(message.content)
@@ -239,12 +241,8 @@ class ChatMistral(BaseChatLLM):
content = LLMEvent(
type=LLMEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call.id,
- name=tool_call.function.name,
- params=params
- ),
- usage=usage
+ tool_call=ToolCall(id=tool_call.id, name=tool_call.function.name, params=params),
+ usage=usage,
)
else:
text, thinking = self._extract_content(message.content)
@@ -257,23 +255,32 @@ class ChatMistral(BaseChatLLM):
total_tokens=usage.total_tokens,
thinking_tokens=max(1, len(thinking) // 4), # ~4 chars per token
)
- content = LLMEvent(type=LLMEventType.TEXT, content=text or "", thinking=thinking_obj, usage=usage)
+ content = LLMEvent(
+ type=LLMEventType.TEXT, content=text or "", thinking=thinking_obj, usage=usage
+ )
return content
@overload
- def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
- ...
+ def invoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent: ...
- def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
+ def invoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent:
mistral_messages = self._convert_messages(messages)
mistral_tools = self._convert_tools(tools) if tools else None
- params = {
- "model": self._model,
- "messages": mistral_messages,
- **self.kwargs
- }
+ params = {"model": self._model, "messages": mistral_messages, **self.kwargs}
# Only add tools if they exist
if mistral_tools:
@@ -298,19 +305,24 @@ class ChatMistral(BaseChatLLM):
content = parsed.model_dump() if hasattr(parsed, "model_dump") else str(parsed)
thinking_tokens = None
- if hasattr(response.usage, "completion_tokens_details") and response.usage.completion_tokens_details:
+ if (
+ hasattr(response.usage, "completion_tokens_details")
+ and response.usage.completion_tokens_details
+ ):
thinking_tokens = getattr(
response.usage.completion_tokens_details, "reasoning_tokens", None
- ) or getattr(
- response.usage.completion_tokens_details, "thinking_tokens", None
- )
+ ) or getattr(response.usage.completion_tokens_details, "thinking_tokens", None)
usage = TokenUsage(
prompt_tokens=response.usage.prompt_tokens,
completion_tokens=response.usage.completion_tokens,
total_tokens=response.usage.total_tokens,
thinking_tokens=thinking_tokens,
)
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content) if isinstance(content, dict) else content, usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content) if isinstance(content, dict) else content,
+ usage=usage,
+ )
except (json.JSONDecodeError, ValueError) as e:
logger.error(f"Failed to parse structured output: {e}")
# Fall through to normal processing
@@ -318,18 +330,25 @@ class ChatMistral(BaseChatLLM):
return self._process_response(response)
@overload
- async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
- ...
+ async def ainvoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent: ...
- async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
+ async def ainvoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent:
mistral_messages = self._convert_messages(messages)
mistral_tools = self._convert_tools(tools) if tools else None
- params = {
- "model": self._model,
- "messages": mistral_messages,
- **self.kwargs
- }
+ params = {"model": self._model, "messages": mistral_messages, **self.kwargs}
if mistral_tools:
params["tools"] = mistral_tools
@@ -352,37 +371,49 @@ class ChatMistral(BaseChatLLM):
content = parsed.model_dump() if hasattr(parsed, "model_dump") else str(parsed)
thinking_tokens = None
- if hasattr(response.usage, "completion_tokens_details") and response.usage.completion_tokens_details:
+ if (
+ hasattr(response.usage, "completion_tokens_details")
+ and response.usage.completion_tokens_details
+ ):
thinking_tokens = getattr(
response.usage.completion_tokens_details, "reasoning_tokens", None
- ) or getattr(
- response.usage.completion_tokens_details, "thinking_tokens", None
- )
+ ) or getattr(response.usage.completion_tokens_details, "thinking_tokens", None)
usage = TokenUsage(
prompt_tokens=response.usage.prompt_tokens,
completion_tokens=response.usage.completion_tokens,
total_tokens=response.usage.total_tokens,
thinking_tokens=thinking_tokens,
)
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content) if isinstance(content, dict) else content, usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content) if isinstance(content, dict) else content,
+ usage=usage,
+ )
except (json.JSONDecodeError, ValueError) as e:
logger.error(f"Failed to parse structured output: {e}")
return self._process_response(response)
@overload
- def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
- ...
+ def stream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> Iterator[LLMStreamEvent]: ...
- def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
+ def stream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> Iterator[LLMStreamEvent]:
mistral_messages = self._convert_messages(messages)
mistral_tools = self._convert_tools(tools) if tools else None
- params = {
- "model": self._model,
- "messages": mistral_messages,
- **self.kwargs
- }
+ params = {"model": self._model, "messages": mistral_messages, **self.kwargs}
if mistral_tools:
params["tools"] = mistral_tools
@@ -405,9 +436,9 @@ class ChatMistral(BaseChatLLM):
think_started = False
for chunk in response:
- if hasattr(chunk, 'data') and hasattr(chunk.data, 'choices') and chunk.data.choices:
+ if hasattr(chunk, "data") and hasattr(chunk.data, "choices") and chunk.data.choices:
delta = chunk.data.choices[0].delta
- if hasattr(delta, 'content') and delta.content:
+ if hasattr(delta, "content") and delta.content:
text, thinking = self._extract_content(delta.content)
if thinking:
if not think_started:
@@ -424,26 +455,27 @@ class ChatMistral(BaseChatLLM):
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_DELTA, content=text)
# Accumulate tool call deltas
- if hasattr(delta, 'tool_calls') and delta.tool_calls:
+ if hasattr(delta, "tool_calls") and delta.tool_calls:
tc_delta = delta.tool_calls[0]
- if hasattr(tc_delta, 'id') and tc_delta.id:
+ if hasattr(tc_delta, "id") and tc_delta.id:
tool_call_id = tc_delta.id
- if hasattr(tc_delta, 'function') and tc_delta.function:
+ if hasattr(tc_delta, "function") and tc_delta.function:
if tc_delta.function.name:
tool_call_name = tc_delta.function.name
if tc_delta.function.arguments:
tool_call_args += tc_delta.function.arguments
# Track usage
- if hasattr(chunk, 'data') and hasattr(chunk.data, 'usage') and chunk.data.usage:
+ if hasattr(chunk, "data") and hasattr(chunk.data, "usage") and chunk.data.usage:
usage_data = chunk.data.usage
thinking_tokens = None
- if hasattr(usage_data, "completion_tokens_details") and usage_data.completion_tokens_details:
+ if (
+ hasattr(usage_data, "completion_tokens_details")
+ and usage_data.completion_tokens_details
+ ):
thinking_tokens = getattr(
usage_data.completion_tokens_details, "reasoning_tokens", None
- ) or getattr(
- usage_data.completion_tokens_details, "thinking_tokens", None
- )
+ ) or getattr(usage_data.completion_tokens_details, "thinking_tokens", None)
usage = TokenUsage(
prompt_tokens=usage_data.prompt_tokens,
completion_tokens=usage_data.completion_tokens,
@@ -460,12 +492,8 @@ class ChatMistral(BaseChatLLM):
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call_id,
- name=tool_call_name,
- params=params
- ),
- usage=usage
+ tool_call=ToolCall(id=tool_call_id, name=tool_call_name, params=params),
+ usage=usage,
)
else:
if think_started:
@@ -474,18 +502,25 @@ class ChatMistral(BaseChatLLM):
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_END, usage=usage)
@overload
- async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
- ...
+ async def astream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> AsyncIterator[LLMStreamEvent]: ...
- async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
+ async def astream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> AsyncIterator[LLMStreamEvent]:
mistral_messages = self._convert_messages(messages)
mistral_tools = self._convert_tools(tools) if tools else None
- params = {
- "model": self._model,
- "messages": mistral_messages,
- **self.kwargs
- }
+ params = {"model": self._model, "messages": mistral_messages, **self.kwargs}
if mistral_tools:
params["tools"] = mistral_tools
@@ -508,9 +543,9 @@ class ChatMistral(BaseChatLLM):
think_started = False
async for chunk in response:
- if hasattr(chunk, 'data') and hasattr(chunk.data, 'choices') and chunk.data.choices:
+ if hasattr(chunk, "data") and hasattr(chunk.data, "choices") and chunk.data.choices:
delta = chunk.data.choices[0].delta
- if hasattr(delta, 'content') and delta.content:
+ if hasattr(delta, "content") and delta.content:
text, thinking = self._extract_content(delta.content)
if thinking:
if not think_started:
@@ -527,26 +562,27 @@ class ChatMistral(BaseChatLLM):
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_DELTA, content=text)
# Accumulate tool call deltas
- if hasattr(delta, 'tool_calls') and delta.tool_calls:
+ if hasattr(delta, "tool_calls") and delta.tool_calls:
tc_delta = delta.tool_calls[0]
- if hasattr(tc_delta, 'id') and tc_delta.id:
+ if hasattr(tc_delta, "id") and tc_delta.id:
tool_call_id = tc_delta.id
- if hasattr(tc_delta, 'function') and tc_delta.function:
+ if hasattr(tc_delta, "function") and tc_delta.function:
if tc_delta.function.name:
tool_call_name = tc_delta.function.name
if tc_delta.function.arguments:
tool_call_args += tc_delta.function.arguments
# Track usage
- if hasattr(chunk, 'data') and hasattr(chunk.data, 'usage') and chunk.data.usage:
+ if hasattr(chunk, "data") and hasattr(chunk.data, "usage") and chunk.data.usage:
usage_data = chunk.data.usage
thinking_tokens = None
- if hasattr(usage_data, "completion_tokens_details") and usage_data.completion_tokens_details:
+ if (
+ hasattr(usage_data, "completion_tokens_details")
+ and usage_data.completion_tokens_details
+ ):
thinking_tokens = getattr(
usage_data.completion_tokens_details, "reasoning_tokens", None
- ) or getattr(
- usage_data.completion_tokens_details, "thinking_tokens", None
- )
+ ) or getattr(usage_data.completion_tokens_details, "thinking_tokens", None)
usage = TokenUsage(
prompt_tokens=usage_data.prompt_tokens,
completion_tokens=usage_data.completion_tokens,
@@ -563,11 +599,7 @@ class ChatMistral(BaseChatLLM):
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call_id,
- name=tool_call_name,
- params=params
- )
+ tool_call=ToolCall(id=tool_call_id, name=tool_call_name, params=params),
)
else:
if think_started:
@@ -588,8 +620,4 @@ class ChatMistral(BaseChatLLM):
elif "codestral" in self._model:
context_window = 32000
- return Metadata(
- name=self._model,
- context_window=context_window,
- owned_by="mistral"
- )
+ return Metadata(name=self._model, context_window=context_window, owned_by="mistral")
diff --git a/windows_use/providers/nvidia/llm.py b/windows_use/providers/nvidia/llm.py
index d7cbc63..d24a3d0 100644
--- a/windows_use/providers/nvidia/llm.py
+++ b/windows_use/providers/nvidia/llm.py
@@ -25,7 +25,9 @@ class ChatNvidia(ChatOpenAI):
temperature: float | None = None,
**kwargs,
):
- api_key = api_key or os.environ.get("NVIDIA_NIM_API_KEY") or os.environ.get("NVIDIA_API_KEY")
+ api_key = (
+ api_key or os.environ.get("NVIDIA_NIM_API_KEY") or os.environ.get("NVIDIA_API_KEY")
+ )
base_url = base_url or os.environ.get("NVIDIA_NIM_API_BASE") or NVIDIA_NIM_BASE_URL
super().__init__(
model=model,
diff --git a/windows_use/providers/ollama/llm.py b/windows_use/providers/ollama/llm.py
index e05033e..a5b3b4a 100644
--- a/windows_use/providers/ollama/llm.py
+++ b/windows_use/providers/ollama/llm.py
@@ -30,6 +30,7 @@ from windows_use.tools import Tool
logger = logging.getLogger(__name__)
+
class ChatOllama(BaseChatLLM):
"""
Ollama LLM implementation following the BaseChatLLM protocol.
@@ -41,7 +42,7 @@ class ChatOllama(BaseChatLLM):
host: str | None = None,
timeout: float = 600.0,
temperature: float | None = None,
- **kwargs
+ **kwargs,
):
"""
Initialize the Ollama LLM.
@@ -72,10 +73,7 @@ class ChatOllama(BaseChatLLM):
def _is_thinking_model(self) -> bool:
"""Check if the model supports thinking (qwen3, deepseek-r1, deepseek-v3, gpt-oss, etc.)."""
m = self._model.lower()
- return any(
- m.startswith(p)
- for p in ("qwen3", "deepseek-r1", "deepseek-v3", "gpt-oss")
- )
+ return any(m.startswith(p) for p in ("qwen3", "deepseek-r1", "deepseek-v3", "gpt-oss"))
def _convert_messages(self, messages: list[BaseMessage]) -> list[dict]:
"""
@@ -89,11 +87,9 @@ class ChatOllama(BaseChatLLM):
ollama_messages.append({"role": "user", "content": msg.content})
elif isinstance(msg, ImageMessage):
b64_imgs = msg.convert_images(format="base64")
- ollama_messages.append({
- "role": "user",
- "content": msg.content or "",
- "images": b64_imgs
- })
+ ollama_messages.append(
+ {"role": "user", "content": msg.content or "", "images": b64_imgs}
+ )
elif isinstance(msg, AIMessage):
msg_dict: dict = {"role": "assistant", "content": msg.content or ""}
if getattr(msg, "thinking", None):
@@ -102,33 +98,21 @@ class ChatOllama(BaseChatLLM):
elif isinstance(msg, ToolMessage):
# Ollama expects assistant message with tool_calls followed by tool message
# Reconstruct for history consistency
- ollama_messages.append({
- "role": "assistant",
- "content": "",
- "tool_calls": [{
- "function": {
- "name": msg.name,
- "arguments": msg.params
- }
- }]
- })
- ollama_messages.append({
- "role": "tool",
- "content": msg.content or ""
- })
+ ollama_messages.append(
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [{"function": {"name": msg.name, "arguments": msg.params}}],
+ }
+ )
+ ollama_messages.append({"role": "tool", "content": msg.content or ""})
return ollama_messages
def _convert_tools(self, tools: list[Tool]) -> list[dict]:
"""
Convert Tool objects to Ollama-compatible tool definitions.
"""
- return [
- {
- "type": "function",
- "function": tool.json_schema
- }
- for tool in tools
- ]
+ return [{"type": "function", "function": tool.json_schema} for tool in tools]
def _process_response(self, response: Any) -> LLMEvent:
"""Process Ollama API response into AIMessage or ToolMessage."""
@@ -161,26 +145,38 @@ class ChatOllama(BaseChatLLM):
tool_call=ToolCall(
id=f"call_{uuid.uuid4().hex[:8]}", # Ollama doesn't return tool call ID consistently
name=func.get("name"),
- params=args
+ params=args,
),
- usage=usage
+ usage=usage,
)
thinking_obj = Thinking(content=thinking, signature=None) if thinking else None
- return LLMEvent(type=LLMEventType.TEXT, content=message.get("content", ""), thinking=thinking_obj, usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=message.get("content", ""),
+ thinking=thinking_obj,
+ usage=usage,
+ )
@overload
- def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
- ...
+ def invoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent: ...
- def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
+ def invoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent:
ollama_messages = self._convert_messages(messages)
ollama_tools = self._convert_tools(tools) if tools else None
- params = {
- "model": self._model,
- "messages": ollama_messages,
- **self.kwargs
- }
+ params = {"model": self._model, "messages": ollama_messages, **self.kwargs}
if ollama_tools:
params["tools"] = ollama_tools
@@ -193,7 +189,9 @@ class ChatOllama(BaseChatLLM):
params["options"]["temperature"] = self.temperature
if json_mode or structured_output:
- params["format"] = "json" if not structured_output else structured_output.model_json_schema()
+ params["format"] = (
+ "json" if not structured_output else structured_output.model_json_schema()
+ )
response = self.client.chat(**params)
@@ -204,10 +202,15 @@ class ChatOllama(BaseChatLLM):
usage = TokenUsage(
prompt_tokens=response.get("prompt_eval_count", 0),
completion_tokens=response.get("eval_count", 0),
- total_tokens=response.get("prompt_eval_count", 0) + response.get("eval_count", 0),
+ total_tokens=response.get("prompt_eval_count", 0)
+ + response.get("eval_count", 0),
thinking_tokens=None,
)
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content) if isinstance(content, dict) else content, usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content) if isinstance(content, dict) else content,
+ usage=usage,
+ )
except (json.JSONDecodeError, ValueError) as e:
logger.error(f"Failed to parse structured output: {e}")
# Fall through to normal response processing
@@ -215,18 +218,25 @@ class ChatOllama(BaseChatLLM):
return self._process_response(response)
@overload
- async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
- ...
+ async def ainvoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent: ...
- async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
+ async def ainvoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent:
ollama_messages = self._convert_messages(messages)
ollama_tools = self._convert_tools(tools) if tools else None
- params = {
- "model": self._model,
- "messages": ollama_messages,
- **self.kwargs
- }
+ params = {"model": self._model, "messages": ollama_messages, **self.kwargs}
if ollama_tools:
params["tools"] = ollama_tools
@@ -239,7 +249,9 @@ class ChatOllama(BaseChatLLM):
params["options"]["temperature"] = self.temperature
if json_mode or structured_output:
- params["format"] = "json" if not structured_output else structured_output.model_json_schema()
+ params["format"] = (
+ "json" if not structured_output else structured_output.model_json_schema()
+ )
response = await self.aclient.chat(**params)
@@ -250,29 +262,40 @@ class ChatOllama(BaseChatLLM):
usage = TokenUsage(
prompt_tokens=response.get("prompt_eval_count", 0),
completion_tokens=response.get("eval_count", 0),
- total_tokens=response.get("prompt_eval_count", 0) + response.get("eval_count", 0),
+ total_tokens=response.get("prompt_eval_count", 0)
+ + response.get("eval_count", 0),
thinking_tokens=None,
)
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content) if isinstance(content, dict) else content, usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content) if isinstance(content, dict) else content,
+ usage=usage,
+ )
except (json.JSONDecodeError, ValueError) as e:
logger.error(f"Failed to parse structured output: {e}")
return self._process_response(response)
@overload
- def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
- ...
+ def stream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> Iterator[LLMStreamEvent]: ...
- def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
+ def stream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> Iterator[LLMStreamEvent]:
ollama_messages = self._convert_messages(messages)
ollama_tools = self._convert_tools(tools) if tools else None
- params = {
- "model": self._model,
- "messages": ollama_messages,
- "stream": True,
- **self.kwargs
- }
+ params = {"model": self._model, "messages": ollama_messages, "stream": True, **self.kwargs}
if ollama_tools:
params["tools"] = ollama_tools
@@ -309,7 +332,9 @@ class ChatOllama(BaseChatLLM):
if not think_started:
think_started = True
yield LLMStreamEvent(type=LLMStreamEventType.THINK_START)
- yield LLMStreamEvent(type=LLMStreamEventType.THINK_DELTA, content=message["thinking"])
+ yield LLMStreamEvent(
+ type=LLMStreamEventType.THINK_DELTA, content=message["thinking"]
+ )
if "content" in message and message["content"]:
if think_started:
yield LLMStreamEvent(type=LLMStreamEventType.THINK_END)
@@ -333,11 +358,9 @@ class ChatOllama(BaseChatLLM):
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
tool_call=ToolCall(
- id=f"call_{uuid.uuid4().hex[:8]}",
- name=func.get("name"),
- params=args
+ id=f"call_{uuid.uuid4().hex[:8]}", name=func.get("name"), params=args
),
- usage=usage
+ usage=usage,
)
if think_started:
@@ -346,19 +369,25 @@ class ChatOllama(BaseChatLLM):
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_END, usage=usage)
@overload
- async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
- ...
+ async def astream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> AsyncIterator[LLMStreamEvent]: ...
- async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
+ async def astream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> AsyncIterator[LLMStreamEvent]:
ollama_messages = self._convert_messages(messages)
ollama_tools = self._convert_tools(tools) if tools else None
- params = {
- "model": self._model,
- "messages": ollama_messages,
- "stream": True,
- **self.kwargs
- }
+ params = {"model": self._model, "messages": ollama_messages, "stream": True, **self.kwargs}
if ollama_tools:
params["tools"] = ollama_tools
@@ -395,7 +424,9 @@ class ChatOllama(BaseChatLLM):
if not think_started:
think_started = True
yield LLMStreamEvent(type=LLMStreamEventType.THINK_START)
- yield LLMStreamEvent(type=LLMStreamEventType.THINK_DELTA, content=message["thinking"])
+ yield LLMStreamEvent(
+ type=LLMStreamEventType.THINK_DELTA, content=message["thinking"]
+ )
if "content" in message and message["content"]:
if think_started:
yield LLMStreamEvent(type=LLMStreamEventType.THINK_END)
@@ -419,11 +450,9 @@ class ChatOllama(BaseChatLLM):
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
tool_call=ToolCall(
- id=f"call_{uuid.uuid4().hex[:8]}",
- name=func.get("name"),
- params=args
+ id=f"call_{uuid.uuid4().hex[:8]}", name=func.get("name"), params=args
),
- usage=usage
+ usage=usage,
)
if think_started:
@@ -434,6 +463,6 @@ class ChatOllama(BaseChatLLM):
def get_metadata(self) -> Metadata:
return Metadata(
name=self._model,
- context_window=32768, # Common default for llama3
- owned_by="ollama"
+ context_window=32768, # Common default for llama3
+ owned_by="ollama",
)
diff --git a/windows_use/providers/open_router/llm.py b/windows_use/providers/open_router/llm.py
index c698e25..f9afe8c 100644
--- a/windows_use/providers/open_router/llm.py
+++ b/windows_use/providers/open_router/llm.py
@@ -29,6 +29,7 @@ from windows_use.tools import Tool
logger = logging.getLogger(__name__)
+
class ChatOpenRouter(BaseChatLLM):
"""
OpenRouter LLM implementation following the BaseChatLLM protocol.
@@ -46,7 +47,7 @@ class ChatOpenRouter(BaseChatLLM):
max_retries: int = 2,
temperature: float | None = None,
default_headers: dict | None = None,
- **kwargs
+ **kwargs,
):
"""
Initialize the OpenRouter LLM.
@@ -72,14 +73,14 @@ class ChatOpenRouter(BaseChatLLM):
base_url=base_url,
timeout=timeout,
max_retries=max_retries,
- default_headers=headers
+ default_headers=headers,
)
self.aclient = AsyncOpenAI(
api_key=self.api_key,
base_url=base_url,
timeout=timeout,
max_retries=max_retries,
- default_headers=headers
+ default_headers=headers,
)
self.kwargs = kwargs
@@ -108,10 +109,12 @@ class ChatOpenRouter(BaseChatLLM):
b64_imgs = msg.convert_images(format="base64")
for b64 in b64_imgs:
- content_list.append({
- "type": "image_url",
- "image_url": {"url": f"data:{msg.mime_type};base64,{b64}"}
- })
+ content_list.append(
+ {
+ "type": "image_url",
+ "image_url": {"url": f"data:{msg.mime_type};base64,{b64}"},
+ }
+ )
openai_messages.append({"role": "user", "content": content_list})
elif isinstance(msg, AIMessage):
msg_dict: dict = {"role": "assistant", "content": msg.content or ""}
@@ -123,34 +126,21 @@ class ChatOpenRouter(BaseChatLLM):
tool_call = {
"id": msg.id,
"type": "function",
- "function": {
- "name": msg.name,
- "arguments": json.dumps(msg.params)
- }
+ "function": {"name": msg.name, "arguments": json.dumps(msg.params)},
}
- openai_messages.append({
- "role": "assistant",
- "content": None,
- "tool_calls": [tool_call]
- })
- openai_messages.append({
- "role": "tool",
- "tool_call_id": msg.id,
- "content": msg.content or ""
- })
+ openai_messages.append(
+ {"role": "assistant", "content": None, "tool_calls": [tool_call]}
+ )
+ openai_messages.append(
+ {"role": "tool", "tool_call_id": msg.id, "content": msg.content or ""}
+ )
return openai_messages
def _convert_tools(self, tools: list[Tool]) -> list[dict]:
"""
Convert Tool objects to OpenRouter-compatible tool definitions.
"""
- return [
- {
- "type": "function",
- "function": tool.json_schema
- }
- for tool in tools
- ]
+ return [{"type": "function", "function": tool.json_schema} for tool in tools]
def _process_response(self, response: Any) -> LLMEvent:
"""Process OpenRouter API response into AIMessage or ToolMessage."""
@@ -166,7 +156,8 @@ class ChatOpenRouter(BaseChatLLM):
getattr(usage_data, "completion_tokens_details", None),
"reasoning_tokens",
None,
- ) or getattr(
+ )
+ or getattr(
getattr(usage_data, "completion_tokens_details", None),
"thinking_tokens",
None,
@@ -187,28 +178,36 @@ class ChatOpenRouter(BaseChatLLM):
params = {}
return LLMEvent(
type=LLMEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call.id,
- name=tool_call.function.name,
- params=params
- ),
- usage=usage
+ tool_call=ToolCall(id=tool_call.id, name=tool_call.function.name, params=params),
+ usage=usage,
)
- return LLMEvent(type=LLMEventType.TEXT, content=message.content or "", thinking=thinking_obj, usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=message.content or "",
+ thinking=thinking_obj,
+ usage=usage,
+ )
@overload
- def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
- ...
+ def invoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent: ...
- def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
+ def invoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
- params = {
- "model": self._model,
- "messages": openai_messages,
- **self.kwargs
- }
+ params = {"model": self._model, "messages": openai_messages, **self.kwargs}
# Only add tools if they exist
if openai_tools:
@@ -222,7 +221,9 @@ class ChatOpenRouter(BaseChatLLM):
# Note: OpenRouter doesn't support structured_output via beta.parse
if structured_output:
- logger.warning("OpenRouter does not support structured_output via beta.parse. Using json_mode instead.")
+ logger.warning(
+ "OpenRouter does not support structured_output via beta.parse. Using json_mode instead."
+ )
params["response_format"] = {"type": "json_object"}
response = self.client.chat.completions.create(**params)
@@ -243,14 +244,22 @@ class ChatOpenRouter(BaseChatLLM):
"thinking_tokens",
None,
)
- content = parsed_obj.model_dump() if hasattr(parsed_obj, "model_dump") else str(parsed_obj)
+ content = (
+ parsed_obj.model_dump()
+ if hasattr(parsed_obj, "model_dump")
+ else str(parsed_obj)
+ )
usage = TokenUsage(
prompt_tokens=getattr(response.usage, "prompt_tokens", 0),
completion_tokens=getattr(response.usage, "completion_tokens", 0),
total_tokens=getattr(response.usage, "total_tokens", 0),
thinking_tokens=thinking_tokens,
)
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content) if isinstance(content, dict) else content, usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content) if isinstance(content, dict) else content,
+ usage=usage,
+ )
except (json.JSONDecodeError, TypeError, ValueError) as e:
logger.error(f"Failed to parse structured output: {e}")
# Fall through to normal response processing
@@ -258,18 +267,25 @@ class ChatOpenRouter(BaseChatLLM):
return self._process_response(response)
@overload
- async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
- ...
+ async def ainvoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent: ...
- async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
+ async def ainvoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
- params = {
- "model": self._model,
- "messages": openai_messages,
- **self.kwargs
- }
+ params = {"model": self._model, "messages": openai_messages, **self.kwargs}
if openai_tools:
params["tools"] = openai_tools
@@ -281,7 +297,9 @@ class ChatOpenRouter(BaseChatLLM):
params["response_format"] = {"type": "json_object"}
if structured_output:
- logger.warning("OpenRouter does not support structured_output via beta.parse. Using json_mode instead.")
+ logger.warning(
+ "OpenRouter does not support structured_output via beta.parse. Using json_mode instead."
+ )
params["response_format"] = {"type": "json_object"}
response = await self.aclient.chat.completions.create(**params)
@@ -301,24 +319,43 @@ class ChatOpenRouter(BaseChatLLM):
"thinking_tokens",
None,
)
- content = parsed_obj.model_dump() if hasattr(parsed_obj, "model_dump") else str(parsed_obj)
+ content = (
+ parsed_obj.model_dump()
+ if hasattr(parsed_obj, "model_dump")
+ else str(parsed_obj)
+ )
usage = TokenUsage(
prompt_tokens=getattr(response.usage, "prompt_tokens", 0),
completion_tokens=getattr(response.usage, "completion_tokens", 0),
total_tokens=getattr(response.usage, "total_tokens", 0),
thinking_tokens=thinking_tokens,
)
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content) if isinstance(content, dict) else content, usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content) if isinstance(content, dict) else content,
+ usage=usage,
+ )
except (json.JSONDecodeError, TypeError, ValueError) as e:
logger.error(f"Failed to parse structured output: {e}")
return self._process_response(response)
@overload
- def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
- ...
+ def stream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> Iterator[LLMStreamEvent]: ...
- def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
+ def stream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> Iterator[LLMStreamEvent]:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
@@ -327,7 +364,7 @@ class ChatOpenRouter(BaseChatLLM):
"messages": openai_messages,
"stream": True,
"stream_options": {"include_usage": True},
- **self.kwargs
+ **self.kwargs,
}
if openai_tools:
@@ -376,7 +413,9 @@ class ChatOpenRouter(BaseChatLLM):
if not think_started:
think_started = True
yield LLMStreamEvent(type=LLMStreamEventType.THINK_START)
- yield LLMStreamEvent(type=LLMStreamEventType.THINK_DELTA, content=delta.reasoning_content)
+ yield LLMStreamEvent(
+ type=LLMStreamEventType.THINK_DELTA, content=delta.reasoning_content
+ )
if delta.content:
if think_started:
yield LLMStreamEvent(type=LLMStreamEventType.THINK_END)
@@ -387,7 +426,7 @@ class ChatOpenRouter(BaseChatLLM):
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_DELTA, content=delta.content)
# Accumulate tool call deltas
- if hasattr(delta, 'tool_calls') and delta.tool_calls:
+ if hasattr(delta, "tool_calls") and delta.tool_calls:
tc_delta = delta.tool_calls[0]
if tc_delta.id:
tool_call_id = tc_delta.id
@@ -406,12 +445,8 @@ class ChatOpenRouter(BaseChatLLM):
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call_id,
- name=tool_call_name,
- params=params
- ),
- usage=usage
+ tool_call=ToolCall(id=tool_call_id, name=tool_call_name, params=params),
+ usage=usage,
)
else:
if think_started:
@@ -420,10 +455,21 @@ class ChatOpenRouter(BaseChatLLM):
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_END, usage=usage)
@overload
- async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
- ...
+ async def astream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> AsyncIterator[LLMStreamEvent]: ...
- async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
+ async def astream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> AsyncIterator[LLMStreamEvent]:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
@@ -432,7 +478,7 @@ class ChatOpenRouter(BaseChatLLM):
"messages": openai_messages,
"stream": True,
"stream_options": {"include_usage": True},
- **self.kwargs
+ **self.kwargs,
}
if openai_tools:
@@ -481,7 +527,9 @@ class ChatOpenRouter(BaseChatLLM):
if not think_started:
think_started = True
yield LLMStreamEvent(type=LLMStreamEventType.THINK_START)
- yield LLMStreamEvent(type=LLMStreamEventType.THINK_DELTA, content=delta.reasoning_content)
+ yield LLMStreamEvent(
+ type=LLMStreamEventType.THINK_DELTA, content=delta.reasoning_content
+ )
if delta.content:
if think_started:
yield LLMStreamEvent(type=LLMStreamEventType.THINK_END)
@@ -492,7 +540,7 @@ class ChatOpenRouter(BaseChatLLM):
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_DELTA, content=delta.content)
# Accumulate tool call deltas
- if hasattr(delta, 'tool_calls') and delta.tool_calls:
+ if hasattr(delta, "tool_calls") and delta.tool_calls:
tc_delta = delta.tool_calls[0]
if tc_delta.id:
tool_call_id = tc_delta.id
@@ -511,12 +559,8 @@ class ChatOpenRouter(BaseChatLLM):
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call_id,
- name=tool_call_name,
- params=params
- ),
- usage=usage
+ tool_call=ToolCall(id=tool_call_id, name=tool_call_name, params=params),
+ usage=usage,
)
else:
if think_started:
@@ -528,5 +572,5 @@ class ChatOpenRouter(BaseChatLLM):
return Metadata(
name=self._model,
context_window=128000, # Varies by model, this is a safe default
- owned_by="open_router"
+ owned_by="open_router",
)
diff --git a/windows_use/providers/openai/llm.py b/windows_use/providers/openai/llm.py
index a4ffd94..5289230 100644
--- a/windows_use/providers/openai/llm.py
+++ b/windows_use/providers/openai/llm.py
@@ -29,6 +29,7 @@ from windows_use.tools import Tool
logger = logging.getLogger(__name__)
+
class ChatOpenAI(BaseChatLLM):
"""
OpenAI LLM implementation following the BaseChatLLM protocol.
@@ -50,7 +51,7 @@ class ChatOpenAI(BaseChatLLM):
timeout: float = 600.0,
max_retries: int = 2,
temperature: float | None = None,
- **kwargs
+ **kwargs,
):
"""
Initialize the OpenAI LLM.
@@ -112,10 +113,12 @@ class ChatOpenAI(BaseChatLLM):
b64_imgs = msg.convert_images(format="base64")
for b64 in b64_imgs:
- content_list.append({
- "type": "image_url",
- "image_url": {"url": f"data:{msg.mime_type};base64,{b64}"}
- })
+ content_list.append(
+ {
+ "type": "image_url",
+ "image_url": {"url": f"data:{msg.mime_type};base64,{b64}"},
+ }
+ )
openai_messages.append({"role": "user", "content": content_list})
elif isinstance(msg, AIMessage):
# Handle AIMessage with potential thinking content
@@ -131,34 +134,21 @@ class ChatOpenAI(BaseChatLLM):
tool_call = {
"id": msg.id,
"type": "function",
- "function": {
- "name": msg.name,
- "arguments": json.dumps(msg.params)
- }
+ "function": {"name": msg.name, "arguments": json.dumps(msg.params)},
}
- openai_messages.append({
- "role": "assistant",
- "content": None,
- "tool_calls": [tool_call]
- })
- openai_messages.append({
- "role": "tool",
- "tool_call_id": msg.id,
- "content": msg.content or ""
- })
+ openai_messages.append(
+ {"role": "assistant", "content": None, "tool_calls": [tool_call]}
+ )
+ openai_messages.append(
+ {"role": "tool", "tool_call_id": msg.id, "content": msg.content or ""}
+ )
return openai_messages
def _convert_tools(self, tools: list[Tool]) -> list[dict]:
"""
Convert Tool objects to OpenAI-compatible tool definitions.
"""
- return [
- {
- "type": "function",
- "function": tool.json_schema
- }
- for tool in tools
- ]
+ return [{"type": "function", "function": tool.json_schema} for tool in tools]
def _process_response(self, response: Any) -> LLMEvent:
"""
@@ -170,12 +160,13 @@ class ChatOpenAI(BaseChatLLM):
# Capture reasoning tokens if available (o1 models)
thinking_tokens = None
- if hasattr(usage_data, "completion_tokens_details") and usage_data.completion_tokens_details:
+ if (
+ hasattr(usage_data, "completion_tokens_details")
+ and usage_data.completion_tokens_details
+ ):
thinking_tokens = getattr(
usage_data.completion_tokens_details, "reasoning_tokens", None
- ) or getattr(
- usage_data.completion_tokens_details, "thinking_tokens", None
- )
+ ) or getattr(usage_data.completion_tokens_details, "thinking_tokens", None)
if thinking_tokens is not None:
logger.debug(f"Reasoning tokens used: {thinking_tokens}")
@@ -204,28 +195,36 @@ class ChatOpenAI(BaseChatLLM):
params = {}
return LLMEvent(
type=LLMEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call.id,
- name=tool_call.function.name,
- params=params
- ),
- usage=usage
+ tool_call=ToolCall(id=tool_call.id, name=tool_call.function.name, params=params),
+ usage=usage,
)
- return LLMEvent(type=LLMEventType.TEXT, content=message.content or "", thinking=thinking_obj, usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=message.content or "",
+ thinking=thinking_obj,
+ usage=usage,
+ )
@overload
- def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
- ...
+ def invoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent: ...
- def invoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
+ def invoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
- params = {
- "model": self._model,
- "messages": openai_messages,
- **self.kwargs
- }
+ params = {"model": self._model, "messages": openai_messages, **self.kwargs}
# Only add tools if they exist
if openai_tools:
@@ -243,12 +242,13 @@ class ChatOpenAI(BaseChatLLM):
)
thinking_tokens = None
- if hasattr(response.usage, "completion_tokens_details") and response.usage.completion_tokens_details:
+ if (
+ hasattr(response.usage, "completion_tokens_details")
+ and response.usage.completion_tokens_details
+ ):
thinking_tokens = getattr(
response.usage.completion_tokens_details, "reasoning_tokens", None
- ) or getattr(
- response.usage.completion_tokens_details, "thinking_tokens", None
- )
+ ) or getattr(response.usage.completion_tokens_details, "thinking_tokens", None)
TokenUsage(
prompt_tokens=response.usage.prompt_tokens,
@@ -258,7 +258,10 @@ class ChatOpenAI(BaseChatLLM):
)
parsed = response.choices[0].message.parsed
content = parsed.model_dump() if hasattr(parsed, "model_dump") else str(parsed)
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content) if isinstance(content, dict) else content)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content) if isinstance(content, dict) else content,
+ )
if json_mode:
params["response_format"] = {"type": "json_object"}
@@ -267,18 +270,25 @@ class ChatOpenAI(BaseChatLLM):
return self._process_response(response)
@overload
- async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
- ...
+ async def ainvoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent: ...
- async def ainvoke(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> LLMEvent:
+ async def ainvoke(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> LLMEvent:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
- params = {
- "model": self._model,
- "messages": openai_messages,
- **self.kwargs
- }
+ params = {"model": self._model, "messages": openai_messages, **self.kwargs}
if openai_tools:
params["tools"] = openai_tools
@@ -293,12 +303,13 @@ class ChatOpenAI(BaseChatLLM):
)
thinking_tokens = None
- if hasattr(response.usage, "completion_tokens_details") and response.usage.completion_tokens_details:
+ if (
+ hasattr(response.usage, "completion_tokens_details")
+ and response.usage.completion_tokens_details
+ ):
thinking_tokens = getattr(
response.usage.completion_tokens_details, "reasoning_tokens", None
- ) or getattr(
- response.usage.completion_tokens_details, "thinking_tokens", None
- )
+ ) or getattr(response.usage.completion_tokens_details, "thinking_tokens", None)
usage = TokenUsage(
prompt_tokens=response.usage.prompt_tokens,
@@ -308,7 +319,11 @@ class ChatOpenAI(BaseChatLLM):
)
parsed = response.choices[0].message.parsed
content = parsed.model_dump() if hasattr(parsed, "model_dump") else str(parsed)
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content) if isinstance(content, dict) else content, usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content) if isinstance(content, dict) else content,
+ usage=usage,
+ )
if json_mode:
params["response_format"] = {"type": "json_object"}
@@ -317,10 +332,21 @@ class ChatOpenAI(BaseChatLLM):
return self._process_response(response)
@overload
- def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
- ...
+ def stream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> Iterator[LLMStreamEvent]: ...
- def stream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> Iterator[LLMStreamEvent]:
+ def stream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> Iterator[LLMStreamEvent]:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
@@ -329,7 +355,7 @@ class ChatOpenAI(BaseChatLLM):
"messages": openai_messages,
"stream": True,
"stream_options": {"include_usage": True},
- **self.kwargs
+ **self.kwargs,
}
if openai_tools:
@@ -358,12 +384,13 @@ class ChatOpenAI(BaseChatLLM):
# Final chunk with usage
if chunk.usage:
thinking_tokens = None
- if hasattr(chunk.usage, "completion_tokens_details") and chunk.usage.completion_tokens_details:
+ if (
+ hasattr(chunk.usage, "completion_tokens_details")
+ and chunk.usage.completion_tokens_details
+ ):
thinking_tokens = getattr(
chunk.usage.completion_tokens_details, "reasoning_tokens", None
- ) or getattr(
- chunk.usage.completion_tokens_details, "thinking_tokens", None
- )
+ ) or getattr(chunk.usage.completion_tokens_details, "thinking_tokens", None)
usage = TokenUsage(
prompt_tokens=chunk.usage.prompt_tokens,
@@ -375,11 +402,17 @@ class ChatOpenAI(BaseChatLLM):
delta = chunk.choices[0].delta
- if self._is_reasoning_model() and hasattr(delta, "reasoning_content") and delta.reasoning_content:
+ if (
+ self._is_reasoning_model()
+ and hasattr(delta, "reasoning_content")
+ and delta.reasoning_content
+ ):
if not think_started:
think_started = True
yield LLMStreamEvent(type=LLMStreamEventType.THINK_START)
- yield LLMStreamEvent(type=LLMStreamEventType.THINK_DELTA, content=delta.reasoning_content)
+ yield LLMStreamEvent(
+ type=LLMStreamEventType.THINK_DELTA, content=delta.reasoning_content
+ )
if delta.content:
if think_started:
@@ -391,7 +424,7 @@ class ChatOpenAI(BaseChatLLM):
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_DELTA, content=delta.content)
# Accumulate tool call deltas
- if hasattr(delta, 'tool_calls') and delta.tool_calls:
+ if hasattr(delta, "tool_calls") and delta.tool_calls:
tc_delta = delta.tool_calls[0]
if tc_delta.id:
tool_call_id = tc_delta.id
@@ -416,19 +449,26 @@ class ChatOpenAI(BaseChatLLM):
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call_id,
- name=tool_call_name,
- params=params
- ),
- usage=usage
+ tool_call=ToolCall(id=tool_call_id, name=tool_call_name, params=params),
+ usage=usage,
)
@overload
- async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
- ...
+ async def astream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> AsyncIterator[LLMStreamEvent]: ...
- async def astream(self, messages: list[BaseMessage], tools: list[Tool] = [], structured_output: BaseModel | None = None, json_mode: bool = False) -> AsyncIterator[LLMStreamEvent]:
+ async def astream(
+ self,
+ messages: list[BaseMessage],
+ tools: list[Tool] = [],
+ structured_output: BaseModel | None = None,
+ json_mode: bool = False,
+ ) -> AsyncIterator[LLMStreamEvent]:
openai_messages = self._convert_messages(messages)
openai_tools = self._convert_tools(tools) if tools else None
@@ -437,7 +477,7 @@ class ChatOpenAI(BaseChatLLM):
"messages": openai_messages,
"stream": True,
"stream_options": {"include_usage": True},
- **self.kwargs
+ **self.kwargs,
}
if openai_tools:
@@ -465,12 +505,13 @@ class ChatOpenAI(BaseChatLLM):
# Final chunk with usage
if chunk.usage:
thinking_tokens = None
- if hasattr(chunk.usage, "completion_tokens_details") and chunk.usage.completion_tokens_details:
+ if (
+ hasattr(chunk.usage, "completion_tokens_details")
+ and chunk.usage.completion_tokens_details
+ ):
thinking_tokens = getattr(
chunk.usage.completion_tokens_details, "reasoning_tokens", None
- ) or getattr(
- chunk.usage.completion_tokens_details, "thinking_tokens", None
- )
+ ) or getattr(chunk.usage.completion_tokens_details, "thinking_tokens", None)
usage = TokenUsage(
prompt_tokens=chunk.usage.prompt_tokens,
@@ -482,11 +523,17 @@ class ChatOpenAI(BaseChatLLM):
delta = chunk.choices[0].delta
- if self._is_reasoning_model() and hasattr(delta, "reasoning_content") and delta.reasoning_content:
+ if (
+ self._is_reasoning_model()
+ and hasattr(delta, "reasoning_content")
+ and delta.reasoning_content
+ ):
if not think_started:
think_started = True
yield LLMStreamEvent(type=LLMStreamEventType.THINK_START)
- yield LLMStreamEvent(type=LLMStreamEventType.THINK_DELTA, content=delta.reasoning_content)
+ yield LLMStreamEvent(
+ type=LLMStreamEventType.THINK_DELTA, content=delta.reasoning_content
+ )
if delta.content:
if think_started:
@@ -498,7 +545,7 @@ class ChatOpenAI(BaseChatLLM):
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_DELTA, content=delta.content)
# Accumulate tool call deltas
- if hasattr(delta, 'tool_calls') and delta.tool_calls:
+ if hasattr(delta, "tool_calls") and delta.tool_calls:
tc_delta = delta.tool_calls[0]
if tc_delta.id:
tool_call_id = tc_delta.id
@@ -523,12 +570,8 @@ class ChatOpenAI(BaseChatLLM):
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call_id,
- name=tool_call_name,
- params=params
- ),
- usage=usage
+ tool_call=ToolCall(id=tool_call_id, name=tool_call_name, params=params),
+ usage=usage,
)
def get_metadata(self) -> Metadata:
@@ -544,8 +587,4 @@ class ChatOpenAI(BaseChatLLM):
elif self._model.startswith("o1"):
context_window = 200000 # o1 models have larger context
- return Metadata(
- name=self._model,
- context_window=context_window,
- owned_by="openai"
- )
+ return Metadata(name=self._model, context_window=context_window, owned_by="openai")
diff --git a/windows_use/providers/perplexity/llm.py b/windows_use/providers/perplexity/llm.py
index 36c6221..8885c62 100644
--- a/windows_use/providers/perplexity/llm.py
+++ b/windows_use/providers/perplexity/llm.py
@@ -94,41 +94,51 @@ class ChatPerplexity:
if msg.content:
content_parts.append({"type": "input_text", "text": msg.content})
for b64 in msg.convert_images("base64"):
- content_parts.append({
- "type": "input_image",
- "image_url": f"data:{msg.mime_type};base64,{b64}",
- })
+ content_parts.append(
+ {
+ "type": "input_image",
+ "image_url": f"data:{msg.mime_type};base64,{b64}",
+ }
+ )
input_msgs.append({"role": "user", "content": content_parts})
elif isinstance(msg, HumanMessage):
- input_msgs.append({
- "role": "user",
- "content": [{"type": "input_text", "text": msg.content or ""}],
- })
+ input_msgs.append(
+ {
+ "role": "user",
+ "content": [{"type": "input_text", "text": msg.content or ""}],
+ }
+ )
elif isinstance(msg, AIMessage):
text = msg.content if isinstance(msg.content, str) else json.dumps(msg.content)
- input_msgs.append({
- "role": "assistant",
- "content": [{"type": "output_text", "text": text or ""}],
- })
+ input_msgs.append(
+ {
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": text or ""}],
+ }
+ )
elif isinstance(msg, ToolMessage):
# A ToolMessage represents a prior tool call + its result.
# In the Responses API format this is two items:
# 1. function_call (the model's call)
# 2. function_call_output (the tool's result)
- input_msgs.append({
- "type": "function_call",
- "name": msg.name,
- "arguments": json.dumps(msg.params),
- "call_id": msg.id,
- })
- input_msgs.append({
- "type": "function_call_output",
- "call_id": msg.id,
- "output": msg.content or "",
- })
+ input_msgs.append(
+ {
+ "type": "function_call",
+ "name": msg.name,
+ "arguments": json.dumps(msg.params),
+ "call_id": msg.id,
+ }
+ )
+ input_msgs.append(
+ {
+ "type": "function_call_output",
+ "call_id": msg.id,
+ "output": msg.content or "",
+ }
+ )
return instructions, input_msgs
@@ -143,12 +153,14 @@ class ChatPerplexity:
result = []
for tool in tools:
schema = self.sanitize_schema(tool.json_schema)
- result.append({
- "type": "function",
- "name": schema["name"],
- "description": schema.get("description", ""),
- "parameters": schema["parameters"],
- })
+ result.append(
+ {
+ "type": "function",
+ "name": schema["name"],
+ "description": schema.get("description", ""),
+ "parameters": schema["parameters"],
+ }
+ )
return result
def sanitize_schema(self, tool_schema: dict) -> dict:
@@ -217,9 +229,7 @@ class ChatPerplexity:
data["tools"] = self._convert_tools(tools)
if self._model_info.get("reasoning_support", False):
- data["reasoning"] = {
- "effort": self._model_info.get("reasoning_effort", "low")
- }
+ data["reasoning"] = {"effort": self._model_info.get("reasoning_effort", "low")}
return data
@@ -308,7 +318,9 @@ class ChatPerplexity:
# Perplexity Agent API: fall back to non-streaming
event = self.invoke(messages, tools, structured_output, json_mode)
if event.type == LLMEventType.TOOL_CALL:
- yield LLMStreamEvent(type=LLMStreamEventType.TOOL_CALL, tool_call=event.tool_call, usage=event.usage)
+ yield LLMStreamEvent(
+ type=LLMStreamEventType.TOOL_CALL, tool_call=event.tool_call, usage=event.usage
+ )
else:
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_START, content="")
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_DELTA, content=event.content or "")
@@ -323,7 +335,9 @@ class ChatPerplexity:
) -> AsyncIterator[LLMStreamEvent]:
event = await self.ainvoke(messages, tools, structured_output, json_mode)
if event.type == LLMEventType.TOOL_CALL:
- yield LLMStreamEvent(type=LLMStreamEventType.TOOL_CALL, tool_call=event.tool_call, usage=event.usage)
+ yield LLMStreamEvent(
+ type=LLMStreamEventType.TOOL_CALL, tool_call=event.tool_call, usage=event.usage
+ )
else:
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_START, content="")
yield LLMStreamEvent(type=LLMStreamEventType.TEXT_DELTA, content=event.content or "")
diff --git a/windows_use/providers/views.py b/windows_use/providers/views.py
index 35beac7..0b47d0a 100644
--- a/windows_use/providers/views.py
+++ b/windows_use/providers/views.py
@@ -1,4 +1,3 @@
-
from pydantic import BaseModel
diff --git a/windows_use/providers/vllm/llm.py b/windows_use/providers/vllm/llm.py
index ed80765..28c4680 100644
--- a/windows_use/providers/vllm/llm.py
+++ b/windows_use/providers/vllm/llm.py
@@ -114,10 +114,12 @@ class ChatVLLM(BaseChatLLM):
b64_imgs = msg.convert_images(format="base64")
for b64 in b64_imgs:
- content_list.append({
- "type": "image_url",
- "image_url": {"url": f"data:{msg.mime_type};base64,{b64}"},
- })
+ content_list.append(
+ {
+ "type": "image_url",
+ "image_url": {"url": f"data:{msg.mime_type};base64,{b64}"},
+ }
+ )
openai_messages.append({"role": "user", "content": content_list})
elif isinstance(msg, AIMessage):
msg_dict: dict = {"role": "assistant", "content": msg.content or ""}
@@ -133,16 +135,20 @@ class ChatVLLM(BaseChatLLM):
"arguments": json.dumps(msg.params),
},
}
- openai_messages.append({
- "role": "assistant",
- "content": None,
- "tool_calls": [tool_call],
- })
- openai_messages.append({
- "role": "tool",
- "tool_call_id": msg.id,
- "content": msg.content or "",
- })
+ openai_messages.append(
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [tool_call],
+ }
+ )
+ openai_messages.append(
+ {
+ "role": "tool",
+ "tool_call_id": msg.id,
+ "content": msg.content or "",
+ }
+ )
return openai_messages
def _convert_tools(self, tools: list[Tool]) -> list[dict]:
@@ -169,14 +175,17 @@ class ChatVLLM(BaseChatLLM):
getattr(usage_data, "completion_tokens_details", None),
"reasoning_tokens",
None,
- ) or getattr(
+ )
+ or getattr(
getattr(usage_data, "completion_tokens_details", None),
"thinking_tokens",
None,
),
)
- thinking = getattr(message, "reasoning", None) or getattr(message, "reasoning_content", None)
+ thinking = getattr(message, "reasoning", None) or getattr(
+ message, "reasoning_content", None
+ )
thinking_obj = Thinking(content=thinking, signature=None) if thinking else None
if message.tool_calls:
@@ -188,16 +197,17 @@ class ChatVLLM(BaseChatLLM):
content = LLMEvent(
type=LLMEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call.id,
- name=tool_call.function.name,
- params=params
- ),
+ tool_call=ToolCall(id=tool_call.id, name=tool_call.function.name, params=params),
thinking=thinking_obj,
- usage=usage
+ usage=usage,
)
else:
- content = LLMEvent(type=LLMEventType.TEXT, content=message.content or "", thinking=thinking_obj, usage=usage)
+ content = LLMEvent(
+ type=LLMEventType.TEXT,
+ content=message.content or "",
+ thinking=thinking_obj,
+ usage=usage,
+ )
return content
@@ -262,11 +272,15 @@ class ChatVLLM(BaseChatLLM):
)
try:
- parsed = structured_output.model_validate_json(
- response.choices[0].message.content
- )
+ parsed = structured_output.model_validate_json(response.choices[0].message.content)
content_dump = parsed.model_dump()
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content_dump) if isinstance(content_dump, dict) else str(content_dump), usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content_dump)
+ if isinstance(content_dump, dict)
+ else str(content_dump),
+ usage=usage,
+ )
except (json.JSONDecodeError, ValueError) as e:
logger.error(f"Failed to parse structured output: {e}")
return LLMEvent(
@@ -341,11 +355,15 @@ class ChatVLLM(BaseChatLLM):
)
try:
- parsed = structured_output.model_validate_json(
- response.choices[0].message.content
- )
+ parsed = structured_output.model_validate_json(response.choices[0].message.content)
content_dump = parsed.model_dump()
- return LLMEvent(type=LLMEventType.TEXT, content=json.dumps(content_dump) if isinstance(content_dump, dict) else str(content_dump), usage=usage)
+ return LLMEvent(
+ type=LLMEventType.TEXT,
+ content=json.dumps(content_dump)
+ if isinstance(content_dump, dict)
+ else str(content_dump),
+ usage=usage,
+ )
except (json.JSONDecodeError, ValueError) as e:
logger.error(f"Failed to parse structured output: {e}")
return LLMEvent(
@@ -424,7 +442,9 @@ class ChatVLLM(BaseChatLLM):
delta = chunk.choices[0].delta
- reasoning_delta = getattr(delta, "reasoning", None) or getattr(delta, "reasoning_content", None)
+ reasoning_delta = getattr(delta, "reasoning", None) or getattr(
+ delta, "reasoning_content", None
+ )
if reasoning_delta:
if not think_started:
think_started = True
@@ -462,12 +482,8 @@ class ChatVLLM(BaseChatLLM):
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call_id,
- name=tool_call_name,
- params=params
- ),
- usage=usage
+ tool_call=ToolCall(id=tool_call_id, name=tool_call_name, params=params),
+ usage=usage,
)
else:
if think_started:
@@ -539,7 +555,9 @@ class ChatVLLM(BaseChatLLM):
delta = chunk.choices[0].delta
- reasoning_delta = getattr(delta, "reasoning", None) or getattr(delta, "reasoning_content", None)
+ reasoning_delta = getattr(delta, "reasoning", None) or getattr(
+ delta, "reasoning_content", None
+ )
if reasoning_delta:
if not think_started:
think_started = True
@@ -577,12 +595,8 @@ class ChatVLLM(BaseChatLLM):
yield LLMStreamEvent(
type=LLMStreamEventType.TOOL_CALL,
- tool_call=ToolCall(
- id=tool_call_id,
- name=tool_call_name,
- params=params
- ),
- usage=usage
+ tool_call=ToolCall(id=tool_call_id, name=tool_call_name, params=params),
+ usage=usage,
)
else:
if think_started:
diff --git a/windows_use/speech/service.py b/windows_use/speech/service.py
index a4041a5..84789b8 100644
--- a/windows_use/speech/service.py
+++ b/windows_use/speech/service.py
@@ -171,7 +171,9 @@ class STT:
def process_audio(self) -> str:
"""Process the recorded audio through the STT provider."""
if self.audio_bytes is None:
- raise RuntimeError("[STT] No audio recorded. Call start_recording/stop_recording first.")
+ raise RuntimeError(
+ "[STT] No audio recorded. Call start_recording/stop_recording first."
+ )
if self.provider is None:
raise RuntimeError("[STT] No STT provider configured.")
@@ -188,7 +190,9 @@ class STT:
async def aprocess_audio(self) -> str:
"""Asynchronously process the recorded audio through the STT provider."""
if self.audio_bytes is None:
- raise RuntimeError("[STT] No audio recorded. Call start_recording/stop_recording first.")
+ raise RuntimeError(
+ "[STT] No audio recorded. Call start_recording/stop_recording first."
+ )
if self.provider is None:
raise RuntimeError("[STT] No STT provider configured.")
diff --git a/windows_use/telemetry/service.py b/windows_use/telemetry/service.py
index ed1ad80..020c7ac 100644
--- a/windows_use/telemetry/service.py
+++ b/windows_use/telemetry/service.py
@@ -10,9 +10,10 @@ from windows_use.telemetry.views import BaseTelemetryEvent
load_dotenv()
+
class ProductTelemetry:
- PROJECT_API_KEY = 'phc_uxdCItyVTjXNU0sMPr97dq3tcz39scQNt3qjTYw5vLV'
- HOST = 'https://us.i.posthog.com'
+ PROJECT_API_KEY = "phc_uxdCItyVTjXNU0sMPr97dq3tcz39scQNt3qjTYw5vLV"
+ HOST = "https://us.i.posthog.com"
def __init__(self):
self._client = None
@@ -29,7 +30,7 @@ class ProductTelemetry:
disable_geoip=False,
enable_exception_autocapture=True,
flush_at=10,
- flush_interval=5.0
+ flush_interval=5.0,
)
# Unregister Posthog's atexit join handler to prevent hanging on exit
try:
@@ -46,26 +47,27 @@ class ProductTelemetry:
return self._user_id
import tempfile
- temp_dir = Path(os.path.join(tempfile.gettempdir(), '.windows-use'))
+
+ temp_dir = Path(os.path.join(tempfile.gettempdir(), ".windows-use"))
temp_dir.mkdir(parents=True, exist_ok=True)
- user_id_file = temp_dir / '.windows-use-user-id'
+ user_id_file = temp_dir / ".windows-use-user-id"
if user_id_file.exists():
try:
- self._user_id = user_id_file.read_text(encoding='utf-8').strip()
+ self._user_id = user_id_file.read_text(encoding="utf-8").strip()
except Exception:
pass
if not self._user_id:
self._user_id = uuid7str()
try:
- user_id_file.write_text(self._user_id, encoding='utf-8')
+ user_id_file.write_text(self._user_id, encoding="utf-8")
except Exception:
pass
return self._user_id
- def capture(self, event:BaseTelemetryEvent):
+ def capture(self, event: BaseTelemetryEvent):
client = self.client
if not client:
return
@@ -73,7 +75,7 @@ class ProductTelemetry:
client.capture(
distinct_id=self.user_id,
event=event.event_name,
- properties={**event.properties,'process_person_profile': True}
+ properties={**event.properties, "process_person_profile": True},
)
except Exception:
pass
diff --git a/windows_use/telemetry/views.py b/windows_use/telemetry/views.py
index f946a9f..4afbec8 100644
--- a/windows_use/telemetry/views.py
+++ b/windows_use/telemetry/views.py
@@ -11,19 +11,19 @@ class BaseTelemetryEvent(ABC):
pass
@property
- def properties(self) -> dict[str,Any]:
+ def properties(self) -> dict[str, Any]:
return {k: v for k, v in asdict(self).items()}
+
@dataclass
class AgentTelemetryEvent(BaseTelemetryEvent):
query: str
steps: int
max_steps: int
- model:str
- provider:str
- use_vision:bool=False
- answer: str | None=None
- error: str | None=None
+ model: str
+ provider: str
+ use_vision: bool = False
+ answer: str | None = None
+ error: str | None = None
event_name: str = "agent_event"
- is_success:bool=False
-
+ is_success: bool = False
diff --git a/windows_use/tools/__init__.py b/windows_use/tools/__init__.py
index a6e0c1f..9c0bc7e 100644
--- a/windows_use/tools/__init__.py
+++ b/windows_use/tools/__init__.py
@@ -1,3 +1,3 @@
from .service import MAX_TOOL_OUTPUT_LENGTH, Tool, ToolResult
-__all__ = ["Tool","ToolResult","MAX_TOOL_OUTPUT_LENGTH"]
+__all__ = ["Tool", "ToolResult", "MAX_TOOL_OUTPUT_LENGTH"]
diff --git a/windows_use/tools/service.py b/windows_use/tools/service.py
index cb305b5..56be067 100644
--- a/windows_use/tools/service.py
+++ b/windows_use/tools/service.py
@@ -12,23 +12,30 @@ MAX_TOOL_OUTPUT_LENGTH = 10000
logger = logging.getLogger(__name__)
+
@dataclass
class ToolResult:
- success: bool=False
- output:str|None=None
- error:str|None=None
- metadata:dict[str,Any]=field(default_factory=dict)
+ success: bool = False
+ output: str | None = None
+ error: str | None = None
+ metadata: dict[str, Any] = field(default_factory=dict)
@classmethod
- def success_result(cls,output:str,metadata:dict[str,Any]=None) -> "ToolResult":
- return cls(success=True,output=output,metadata=metadata)
+ def success_result(cls, output: str, metadata: dict[str, Any] = None) -> "ToolResult":
+ return cls(success=True, output=output, metadata=metadata)
@classmethod
- def error_result(cls,error:str,metadata:dict[str,Any]=None) -> "ToolResult":
- return cls(success=False,error=error,metadata=metadata)
+ def error_result(cls, error: str, metadata: dict[str, Any] = None) -> "ToolResult":
+ return cls(success=False, error=error, metadata=metadata)
+
class Tool(ABC):
- def __init__(self, name: str|None=None, description: str|None=None, model: BaseModel|None=None):
+ def __init__(
+ self,
+ name: str | None = None,
+ description: str | None = None,
+ model: BaseModel | None = None,
+ ):
self.name = name
self.description = description
self.model = model
@@ -43,9 +50,7 @@ class Tool(ABC):
def exclude_properties(obj):
if isinstance(obj, dict):
return {
- k: exclude_properties(v)
- for k, v in obj.items()
- if k not in EXCLUDED_PROPERTIES
+ k: exclude_properties(v) for k, v in obj.items() if k not in EXCLUDED_PROPERTIES
}
elif isinstance(obj, list):
return [exclude_properties(item) for item in obj]
@@ -63,12 +68,12 @@ class Tool(ABC):
"parameters": parameters,
}
- def validate_params(self, args: dict[str,Any])->list[str]:
+ def validate_params(self, args: dict[str, Any]) -> list[str]:
try:
self.model(**args)
return []
except ValidationError as e:
- errors=[]
+ errors = []
for error in e.errors():
field = "".join([str(loc) for loc in error["loc"]])
msg = error["msg"]
diff --git a/windows_use/uia/controls.py b/windows_use/uia/controls.py
index 3ebbed5..8cee6de 100644
--- a/windows_use/uia/controls.py
+++ b/windows_use/uia/controls.py
@@ -1,4 +1,4 @@
-'''
+"""
uiautomation for Python 3.
Author: yinkaisheng
Source: https://github.com/yinkaisheng/Python-UIAutomation-for-Windows
@@ -9,7 +9,7 @@ Run 'automation.py -h' for help.
uiautomation is shared under the Apache Licene 2.0.
This means that the code can be freely copied and distributed, and costs nothing to use.
-'''
+"""
import ctypes
import datetime
@@ -27,7 +27,7 @@ from .core import IUIAutomationElement, _AutomationClient
from .enums import *
from .patterns import *
-METRO_WINDOW_CLASS_NAME = 'Windows.UI.Core.CoreWindow' # for Windows 8 and 8.1
+METRO_WINDOW_CLASS_NAME = "Windows.UI.Core.CoreWindow" # for Windows 8 and 8.1
SEARCH_INTERVAL = 0.5 # search control interval seconds
MAX_MOVE_SECOND = 1 # simulate mouse move or drag max seconds
TIME_OUT_SECOND = 10
@@ -44,20 +44,38 @@ ProcessTime = time.perf_counter # this returns nearly 0 when first call it if p
ProcessTime() # need to call it once if python version <= 3.6
TreeNode = Any
+
class Control:
- ValidKeys = set(['ControlType', 'ClassName', 'AutomationId', 'Name', 'SubName', 'RegexName', 'Depth', 'Compare'])
-
- def __init__(self, searchFromControl: Optional['Control'] = None, searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL, foundIndex: int = 1, element=None,
- ControlType: int | None = None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
+ ValidKeys = set(
+ [
+ "ControlType",
+ "ClassName",
+ "AutomationId",
+ "Name",
+ "SubName",
+ "RegexName",
+ "Depth",
+ "Compare",
+ ]
+ )
+
+ def __init__(
+ self,
+ searchFromControl: Optional["Control"] = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ ControlType: int | None = None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
"""
searchFromControl: `Control` or its subclass, if it is None, search from root control(Desktop).
searchDepth: int, max search depth from searchFromControl.
@@ -89,33 +107,33 @@ class Control:
self.foundIndex = foundIndex
self.searchProperties = searchProperties
if Name is not None:
- searchProperties['Name'] = Name
+ searchProperties["Name"] = Name
if SubName is not None:
- searchProperties['SubName'] = SubName
+ searchProperties["SubName"] = SubName
if RegexName is not None:
- searchProperties['RegexName'] = RegexName
+ searchProperties["RegexName"] = RegexName
self.regexName = re.compile(RegexName)
else:
self.regexName = None
if ClassName is not None:
- searchProperties['ClassName'] = ClassName
+ searchProperties["ClassName"] = ClassName
if AutomationId is not None:
- searchProperties['AutomationId'] = AutomationId
+ searchProperties["AutomationId"] = AutomationId
if ControlType is not None:
- searchProperties['ControlType'] = ControlType
+ searchProperties["ControlType"] = ControlType
if Depth is not None:
- searchProperties['Depth'] = Depth
+ searchProperties["Depth"] = Depth
if Compare is not None:
- searchProperties['Compare'] = Compare
+ searchProperties["Compare"] = Compare
self._supportedPatterns = {}
def __str__(self) -> str:
- return f'ControlType: {self.ControlTypeName} ClassName: {self.ClassName} AutomationId: {self.AutomationId} Rect: {self.BoundingRectangle} Name: {self.Name} Handle: 0x{self.NativeWindowHandle:X}({self.NativeWindowHandle})'
+ return f"ControlType: {self.ControlTypeName} ClassName: {self.ClassName} AutomationId: {self.AutomationId} Rect: {self.BoundingRectangle} Name: {self.Name} Handle: 0x{self.NativeWindowHandle:X}({self.NativeWindowHandle})"
def __repr__(self) -> str:
- return f'<{self.__class__.__name__} ClassName={self.ClassName!r} AutomationId={self.AutomationId} Rect={self.BoundingRectangle} Name={self.Name!r} Handle=0x{self.NativeWindowHandle:X}({self.NativeWindowHandle})>'
+ return f"<{self.__class__.__name__} ClassName={self.ClassName!r} AutomationId={self.AutomationId} Rect={self.BoundingRectangle} Name={self.Name!r} Handle=0x{self.NativeWindowHandle:X}({self.NativeWindowHandle})>"
- def __getitem__(self, pos: int) -> Optional['Control']:
+ def __getitem__(self, pos: int) -> Optional["Control"]:
if pos == 1:
return self.GetFirstChildControl()
elif pos == -1:
@@ -138,7 +156,9 @@ class Control:
raise ValueError
@staticmethod
- def CreateControlFromElement(element: ctypes.POINTER(IUIAutomationElement)) -> Optional["Control"]:
+ def CreateControlFromElement(
+ element: ctypes.POINTER(IUIAutomationElement),
+ ) -> Optional["Control"]:
"""
Create a concreate `Control` from a com type `IUIAutomationElement`.
element: `ctypes.POINTER(IUIAutomationElement)`.
@@ -151,7 +171,7 @@ class Control:
return None
@staticmethod
- def CreateControlsFromRawElementArray(raw_pointer) -> list['Control']:
+ def CreateControlsFromRawElementArray(raw_pointer) -> list["Control"]:
"""
Convert a raw POINTER(IUnknown) to a list of Control subclasses.
@@ -179,7 +199,7 @@ class Control:
return []
@staticmethod
- def CreateControlFromControl(control: 'Control') -> Optional['Control']:
+ def CreateControlFromControl(control: "Control") -> Optional["Control"]:
"""
Create a concreate `Control` from a control instance, copy it.
control: `Control` or its subclass.
@@ -189,7 +209,7 @@ class Control:
newControl = Control.CreateControlFromElement(control.Element)
return newControl
- def SetSearchFromControl(self, searchFromControl: 'Control') -> None:
+ def SetSearchFromControl(self, searchFromControl: "Control") -> None:
"""searchFromControl: `Control` or its subclass"""
self.searchFromControl = searchFromControl
@@ -202,10 +222,10 @@ class Control:
searchProperties: dict, same as searchProperties in `Control.__init__`.
"""
self.searchProperties.update(searchProperties)
- if 'Depth' in searchProperties:
- self.searchDepth = searchProperties['Depth']
- if 'RegexName' in searchProperties:
- regName = searchProperties['RegexName']
+ if "Depth" in searchProperties:
+ self.searchDepth = searchProperties["Depth"]
+ if "RegexName" in searchProperties:
+ regName = searchProperties["RegexName"]
self.regexName = re.compile(regName) if regName else None
def RemoveSearchProperties(self, **searchProperties) -> None:
@@ -214,20 +234,30 @@ class Control:
"""
for key in searchProperties:
del self.searchProperties[key]
- if key == 'RegexName':
+ if key == "RegexName":
self.regexName = None
def GetSearchPropertiesStr(self) -> str:
- strs = ['{}: {}'.format(k, ControlTypeNames[v] if k == 'ControlType' else repr(v)) for k, v in self.searchProperties.items()]
- return '{' + ', '.join(strs) + '}'
+ strs = [
+ "{}: {}".format(k, ControlTypeNames[v] if k == "ControlType" else repr(v))
+ for k, v in self.searchProperties.items()
+ ]
+ return "{" + ", ".join(strs) + "}"
- def GetColorfulSearchPropertiesStr(self, keyColor='DarkGreen', valueColor='DarkCyan') -> str:
+ def GetColorfulSearchPropertiesStr(self, keyColor="DarkGreen", valueColor="DarkCyan") -> str:
"""keyColor, valueColor: str, color name in class ConsoleColor"""
- strs = ['<Color={}>{}</Color>: <Color={}>{}</Color>'.format(keyColor if k in Control.ValidKeys else 'DarkYellow', k, valueColor,
- ControlTypeNames[v] if k == 'ControlType' else repr(v)) for k, v in self.searchProperties.items()]
- return '{' + ', '.join(strs) + '}'
+ strs = [
+ "<Color={}>{}</Color>: <Color={}>{}</Color>".format(
+ keyColor if k in Control.ValidKeys else "DarkYellow",
+ k,
+ valueColor,
+ ControlTypeNames[v] if k == "ControlType" else repr(v),
+ )
+ for k, v in self.searchProperties.items()
+ ]
+ return "{" + ", ".join(strs) + "}"
- def BuildUpdatedCache(self, cacheRequest: 'CacheRequest') -> 'Control':
+ def BuildUpdatedCache(self, cacheRequest: "CacheRequest") -> "Control":
"""
Retrieves a new UI Automation element with an updated cache.
cacheRequest: CacheRequest.
@@ -464,7 +494,7 @@ class Control:
rect = self.Element.CurrentBoundingRectangle
return Rect(rect.left, rect.top, rect.right, rect.bottom)
- def contains(self, other: 'Control') -> bool:
+ def contains(self, other: "Control") -> bool:
"""Return True if `other` is the same element or fully enclosed within this control.
Uses bounding rectangle intersection: if clipping `other` to this control's
@@ -502,7 +532,7 @@ class Control:
# @property
# def ControllerFor(self):
- # return self.Element.CurrentControllerFor
+ # return self.Element.CurrentControllerFor
@property
def Culture(self) -> int:
@@ -515,11 +545,11 @@ class Control:
# @property
# def DescribedBy(self):
- # return self.Element.CurrentDescribedBy
+ # return self.Element.CurrentDescribedBy
# @property
# def FlowsTo(self):
- # return self.Element.CurrentFlowsTo
+ # return self.Element.CurrentFlowsTo
@property
def FrameworkId(self) -> str:
@@ -641,7 +671,7 @@ class Control:
# @property
# def LabeledBy(self):
- # return self.Element.CurrentLabeledBy
+ # return self.Element.CurrentLabeledBy
@property
def LocalizedControlType(self) -> str:
@@ -659,7 +689,7 @@ class Control:
Call IUIAutomationElement::get_CurrentName.
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-get_currentname
"""
- return self.Element.CurrentName or '' # CurrentName may be None
+ return self.Element.CurrentName or "" # CurrentName may be None
@property
def NativeWindowHandle(self) -> int:
@@ -702,7 +732,7 @@ class Control:
"""
return self.Element.CurrentProviderDescription
- def FindAll(self, scope: int, condition) -> list['Control']:
+ def FindAll(self, scope: int, condition) -> list["Control"]:
"""
Find all UI Automation elements that satisfy the specified condition.
Call IUIAutomationElement::FindAll.
@@ -726,7 +756,9 @@ class Control:
controls.append(control)
return controls
- def FindAllBuildCache(self, scope: int, condition, cacheRequest: 'CacheRequest') -> list['Control']:
+ def FindAllBuildCache(
+ self, scope: int, condition, cacheRequest: "CacheRequest"
+ ) -> list["Control"]:
"""
Find all UI Automation elements that satisfy the specified condition, and cache properties and patterns.
Call IUIAutomationElement::FindAllBuildCache.
@@ -751,7 +783,7 @@ class Control:
controls.append(control)
return controls
- def FindFirst(self, scope: int, condition) -> Optional['Control']:
+ def FindFirst(self, scope: int, condition) -> Optional["Control"]:
"""
Find the first UI Automation element that satisfies the specified condition.
Call IUIAutomationElement::FindFirst.
@@ -765,7 +797,9 @@ class Control:
element = self.Element.FindFirst(scope, condition)
return Control.CreateControlFromElement(element)
- def FindFirstBuildCache(self, scope: int, condition, cacheRequest: 'CacheRequest') -> Optional['Control']:
+ def FindFirstBuildCache(
+ self, scope: int, condition, cacheRequest: "CacheRequest"
+ ) -> Optional["Control"]:
"""
Find the first UI Automation element that satisfies the specified condition, and cache properties and patterns.
Call IUIAutomationElement::FindFirstBuildCache.
@@ -780,7 +814,7 @@ class Control:
element = self.Element.FindFirstBuildCache(scope, condition, cacheRequest.check_request)
return Control.CreateControlFromElement(element)
- def GetCachedChildren(self) -> list['Control']:
+ def GetCachedChildren(self) -> list["Control"]:
"""
Retrieve the cached child elements of this UI Automation element.
Call IUIAutomationElement::GetCachedChildren.
@@ -807,7 +841,7 @@ class Control:
except comtypes.COMError:
return []
- def GetCachedParent(self) -> Optional['Control']:
+ def GetCachedParent(self) -> Optional["Control"]:
"""
Retrieve the cached parent of this UI Automation element.
Call IUIAutomationElement::GetCachedParent.
@@ -1020,7 +1054,10 @@ class Control:
"""
Return the UI Automation pattern names currently supported by this control.
"""
- return [PatternIdNames.get(pattern_id, str(pattern_id)) for pattern_id in self.AvailablePatternIds]
+ return [
+ PatternIdNames.get(pattern_id, str(pattern_id))
+ for pattern_id in self.AvailablePatternIds
+ ]
def GetLegacyIAccessiblePattern(self) -> LegacyIAccessiblePattern:
"""
@@ -1028,7 +1065,9 @@ class Control:
"""
return self.GetPattern(PatternId.LegacyIAccessiblePattern)
- def GetAncestorControl(self, condition: Callable[['Control', int], bool]) -> Optional['Control']:
+ def GetAncestorControl(
+ self, condition: Callable[["Control", int], bool]
+ ) -> Optional["Control"]:
"""
Get an ancestor control that matches the condition.
condition: Callable[[Control, int], bool], function(control: Control, depth: int) -> bool,
@@ -1045,42 +1084,44 @@ class Control:
return ancestor
return None
- def GetParentControl(self) -> Optional['Control']:
+ def GetParentControl(self) -> Optional["Control"]:
"""
Return `Control` subclass or None.
"""
ele = _AutomationClient.instance().ViewWalker.GetParentElement(self.Element)
return Control.CreateControlFromElement(ele)
- def GetFirstChildControl(self) -> Optional['Control']:
+ def GetFirstChildControl(self) -> Optional["Control"]:
"""
Return `Control` subclass or None.
"""
ele = _AutomationClient.instance().ViewWalker.GetFirstChildElement(self.Element)
return Control.CreateControlFromElement(ele)
- def GetLastChildControl(self) -> Optional['Control']:
+ def GetLastChildControl(self) -> Optional["Control"]:
"""
Return `Control` subclass or None.
"""
ele = _AutomationClient.instance().ViewWalker.GetLastChildElement(self.Element)
return Control.CreateControlFromElement(ele)
- def GetNextSiblingControl(self) -> Optional['Control']:
+ def GetNextSiblingControl(self) -> Optional["Control"]:
"""
Return `Control` subclass or None.
"""
ele = _AutomationClient.instance().ViewWalker.GetNextSiblingElement(self.Element)
return Control.CreateControlFromElement(ele)
- def GetPreviousSiblingControl(self) -> Optional['Control']:
+ def GetPreviousSiblingControl(self) -> Optional["Control"]:
"""
Return `Control` subclass or None.
"""
ele = _AutomationClient.instance().ViewWalker.GetPreviousSiblingElement(self.Element)
return Control.CreateControlFromElement(ele)
- def GetSiblingControl(self, condition: Callable[['Control'], bool], forward: bool = True) -> Optional['Control']:
+ def GetSiblingControl(
+ self, condition: Callable[["Control"], bool], forward: bool = True
+ ) -> Optional["Control"]:
"""
Get a sibling control that matches the condition.
forward: bool, if True, only search next siblings, if False, search pervious siblings first, then search next siblings.
@@ -1105,7 +1146,7 @@ class Control:
else:
break
- def GetChildren(self) -> list['Control']:
+ def GetChildren(self) -> list["Control"]:
"""
Return List[Control], a list of `Control` subclasses.
"""
@@ -1116,7 +1157,7 @@ class Control:
child = child.GetNextSiblingControl()
return children
- def _CompareFunction(self, control: 'Control', depth: int) -> bool:
+ def _CompareFunction(self, control: "Control", depth: int) -> bool:
"""
Define how to search.
control: `Control` or its subclass.
@@ -1125,35 +1166,40 @@ class Control:
"""
compareFunc = None
for key, value in self.searchProperties.items():
- if 'ControlType' == key:
+ if "ControlType" == key:
if value != control.ControlType:
return False
- elif 'ClassName' == key:
+ elif "ClassName" == key:
if value != control.ClassName:
return False
- elif 'AutomationId' == key:
+ elif "AutomationId" == key:
if value != control.AutomationId:
return False
- elif 'Depth' == key:
+ elif "Depth" == key:
if value != depth:
return False
- elif 'Name' == key:
+ elif "Name" == key:
if value != control.Name:
return False
- elif 'SubName' == key:
+ elif "SubName" == key:
if value not in control.Name:
return False
- elif 'RegexName' == key:
+ elif "RegexName" == key:
if not self.regexName.match(control.Name):
return False
- elif 'Compare' == key:
+ elif "Compare" == key:
compareFunc = value
# use Compare at last
if compareFunc and not compareFunc(control, depth):
return False
return True
- def Exists(self, maxSearchSeconds: float = 5, searchIntervalSeconds: float = SEARCH_INTERVAL, printIfNotExist: bool = False) -> bool:
+ def Exists(
+ self,
+ maxSearchSeconds: float = 5,
+ searchIntervalSeconds: float = SEARCH_INTERVAL,
+ printIfNotExist: bool = False,
+ ) -> bool:
"""
maxSearchSeconds: float
searchIntervalSeconds: float
@@ -1164,10 +1210,14 @@ class Control:
# if element is directly assigned, not by searching, just check whether self._element is valid
# but I can't find an API in UIAutomation that can directly check
rootElement = _AutomationClient.instance().IUIAutomation.GetRootElement()
- if _AutomationClient.instance().IUIAutomation.CompareElements(self._element, rootElement):
+ if _AutomationClient.instance().IUIAutomation.CompareElements(
+ self._element, rootElement
+ ):
return True
else:
- parentElement = _AutomationClient.instance().ViewWalker.GetParentElement(self._element)
+ parentElement = _AutomationClient.instance().ViewWalker.GetParentElement(
+ self._element
+ )
if parentElement:
return True
else:
@@ -1185,7 +1235,13 @@ class Control:
if DEBUG_SEARCH_TIME:
datetime.datetime.now()
while True:
- control = FindControl(self.searchFromControl, self._CompareFunction, self.searchDepth, False, self.foundIndex)
+ control = FindControl(
+ self.searchFromControl,
+ self._CompareFunction,
+ self.searchDepth,
+ False,
+ self.foundIndex,
+ )
if control:
self._element = control.Element
control._element = 0 # control will be destroyed, but the element needs to be stored in self._element
@@ -1197,7 +1253,12 @@ class Control:
else:
return False
- def Disappears(self, maxSearchSeconds: float = 5, searchIntervalSeconds: float = SEARCH_INTERVAL, printIfNotDisappear: bool = False) -> bool:
+ def Disappears(
+ self,
+ maxSearchSeconds: float = 5,
+ searchIntervalSeconds: float = SEARCH_INTERVAL,
+ printIfNotDisappear: bool = False,
+ ) -> bool:
"""
maxSearchSeconds: float
searchIntervalSeconds: float
@@ -1219,7 +1280,12 @@ class Control:
else:
return False
- def Refind(self, maxSearchSeconds: float = TIME_OUT_SECOND, searchIntervalSeconds: float = SEARCH_INTERVAL, raiseException: bool = True) -> bool:
+ def Refind(
+ self,
+ maxSearchSeconds: float = TIME_OUT_SECOND,
+ searchIntervalSeconds: float = SEARCH_INTERVAL,
+ raiseException: bool = True,
+ ) -> bool:
"""
Refind the control every searchIntervalSeconds seconds in maxSearchSeconds seconds.
maxSearchSeconds: float.
@@ -1227,9 +1293,15 @@ class Control:
raiseException: bool, if True, raise a LookupError if timeout.
Return bool, True if find.
"""
- if not self.Exists(maxSearchSeconds, searchIntervalSeconds, False if raiseException else DEBUG_EXIST_DISAPPEAR):
+ if not self.Exists(
+ maxSearchSeconds,
+ searchIntervalSeconds,
+ False if raiseException else DEBUG_EXIST_DISAPPEAR,
+ ):
if raiseException:
- raise LookupError(f'Find Control Timeout({maxSearchSeconds}s): {self.GetSearchPropertiesStr()}')
+ raise LookupError(
+ f"Find Control Timeout({maxSearchSeconds}s): {self.GetSearchPropertiesStr()}"
+ )
else:
return False
return True
@@ -1248,7 +1320,14 @@ class Control:
y = rect.top + int(rect.height() * ratioY)
return x, y
- def MoveCursorToInnerPos(self, x: int | None = None, y: int | None = None, ratioX: float = 0.5, ratioY: float = 0.5, simulateMove: bool = True) -> Tuple[int, int] | None:
+ def MoveCursorToInnerPos(
+ self,
+ x: int | None = None,
+ y: int | None = None,
+ ratioX: float = 0.5,
+ ratioY: float = 0.5,
+ simulateMove: bool = True,
+ ) -> Tuple[int, int] | None:
"""
Move cursor to control's internal position, default to center.
x: int, if < 0, move to self.BoundingRectangle.right + x, if not None, ignore ratioX.
@@ -1283,7 +1362,15 @@ class Control:
"""
return self.MoveCursorToInnerPos(simulateMove=simulateMove)
- def Click(self, x: int | None = None, y: int | None = None, ratioX: float = 0.5, ratioY: float = 0.5, simulateMove: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> None:
+ def Click(
+ self,
+ x: int | None = None,
+ y: int | None = None,
+ ratioX: float = 0.5,
+ ratioY: float = 0.5,
+ simulateMove: bool = True,
+ waitTime: float = OPERATION_WAIT_TIME,
+ ) -> None:
"""
x: int, if < 0, click self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, click self.BoundingRectangle.bottom + y, if not None, ignore ratioY.
@@ -1300,7 +1387,15 @@ class Control:
if point:
Click(point[0], point[1], waitTime)
- def MiddleClick(self, x: int | None = None, y: int | None = None, ratioX: float = 0.5, ratioY: float = 0.5, simulateMove: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> None:
+ def MiddleClick(
+ self,
+ x: int | None = None,
+ y: int | None = None,
+ ratioX: float = 0.5,
+ ratioY: float = 0.5,
+ simulateMove: bool = True,
+ waitTime: float = OPERATION_WAIT_TIME,
+ ) -> None:
"""
x: int, if < 0, middle click self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, middle click self.BoundingRectangle.bottom + y, if not None, ignore ratioY.
@@ -1317,7 +1412,15 @@ class Control:
if point:
MiddleClick(point[0], point[1], waitTime)
- def RightClick(self, x: int | None = None, y: int | None = None, ratioX: float = 0.5, ratioY: float = 0.5, simulateMove: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> None:
+ def RightClick(
+ self,
+ x: int | None = None,
+ y: int | None = None,
+ ratioX: float = 0.5,
+ ratioY: float = 0.5,
+ simulateMove: bool = True,
+ waitTime: float = OPERATION_WAIT_TIME,
+ ) -> None:
"""
x: int, if < 0, right click self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, right click self.BoundingRectangle.bottom + y, if not None, ignore ratioY.
@@ -1334,7 +1437,15 @@ class Control:
if point:
RightClick(point[0], point[1], waitTime)
- def DoubleClick(self, x: int | None = None, y: int | None = None, ratioX: float = 0.5, ratioY: float = 0.5, simulateMove: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> None:
+ def DoubleClick(
+ self,
+ x: int | None = None,
+ y: int | None = None,
+ ratioX: float = 0.5,
+ ratioY: float = 0.5,
+ simulateMove: bool = True,
+ waitTime: float = OPERATION_WAIT_TIME,
+ ) -> None:
"""
x: int, if < 0, right click self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, right click self.BoundingRectangle.bottom + y, if not None, ignore ratioY.
@@ -1351,7 +1462,15 @@ class Control:
Click(x, y, GetDoubleClickTime() * 1.0 / 2000)
Click(x, y, waitTime)
- def DragDrop(self, x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None:
+ def DragDrop(
+ self,
+ x1: int,
+ y1: int,
+ x2: int,
+ y2: int,
+ moveSpeed: float = 1,
+ waitTime: float = OPERATION_WAIT_TIME,
+ ) -> None:
rect = self.BoundingRectangle
if rect.width() == 0 or rect.height() == 0:
return
@@ -1361,7 +1480,15 @@ class Control:
y2 = (rect.top if y2 >= 0 else rect.bottom) + y2
DragDrop(x1, y1, x2, y2, moveSpeed, waitTime)
- def RightDragDrop(self, x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None:
+ def RightDragDrop(
+ self,
+ x1: int,
+ y1: int,
+ x2: int,
+ y2: int,
+ moveSpeed: float = 1,
+ waitTime: float = OPERATION_WAIT_TIME,
+ ) -> None:
rect = self.BoundingRectangle
if rect.width() == 0 or rect.height() == 0:
return
@@ -1371,7 +1498,16 @@ class Control:
y2 = (rect.top if y2 >= 0 else rect.bottom) + y2
RightDragDrop(x1, y1, x2, y2, moveSpeed, waitTime)
- def WheelDown(self, x: int | None = None, y: int | None = None, ratioX: float = 0.5, ratioY: float = 0.5, wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME) -> None:
+ def WheelDown(
+ self,
+ x: int | None = None,
+ y: int | None = None,
+ ratioX: float = 0.5,
+ ratioY: float = 0.5,
+ wheelTimes: int = 1,
+ interval: float = 0.05,
+ waitTime: float = OPERATION_WAIT_TIME,
+ ) -> None:
"""
Make control have focus first, move cursor to the specified position and mouse wheel down.
x: int, if < 0, move x cursor to self.BoundingRectangle.right + x, if not None, ignore ratioX.
@@ -1389,7 +1525,16 @@ class Control:
WheelDown(wheelTimes, interval, waitTime)
SetCursorPos(cursorX, cursorY)
- def WheelUp(self, x: int | None = None, y: int | None = None, ratioX: float = 0.5, ratioY: float = 0.5, wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME) -> None:
+ def WheelUp(
+ self,
+ x: int | None = None,
+ y: int | None = None,
+ ratioX: float = 0.5,
+ ratioY: float = 0.5,
+ wheelTimes: int = 1,
+ interval: float = 0.05,
+ waitTime: float = OPERATION_WAIT_TIME,
+ ) -> None:
"""
Make control have focus first, move cursor to the specified position and mouse wheel up.
x: int, if < 0, move x cursor to self.BoundingRectangle.right + x, if not None, ignore ratioX.
@@ -1489,7 +1634,13 @@ class Control:
time.sleep(waitTime)
SendKey(key, waitTime)
- def SendKeys(self, text: str, interval: float = 0.01, waitTime: float = OPERATION_WAIT_TIME, charMode: bool = True) -> None:
+ def SendKeys(
+ self,
+ text: str,
+ interval: float = 0.01,
+ waitTime: float = OPERATION_WAIT_TIME,
+ charMode: bool = True,
+ ) -> None:
"""
Make control have focus first and type keys.
`self.SetFocus` may not work for some controls, you may need to click it to make it have focus.
@@ -1509,7 +1660,7 @@ class Control:
return GetAncestor(handle, GAFlag.Root) == handle
return False
- def GetTopLevelControl(self) -> Optional['Control']:
+ def GetTopLevelControl(self) -> Optional["Control"]:
"""
Get the top level control which current control lays.
If current control is top level, return self.
@@ -1539,877 +1690,1348 @@ class Control:
return ControlFromHandle(topHandle)
return None
- def Control(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'Control':
- return Control(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def ButtonControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'ButtonControl':
- return ButtonControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def CalendarControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'CalendarControl':
- return CalendarControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def CheckBoxControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'CheckBoxControl':
- return CheckBoxControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def ComboBoxControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'ComboBoxControl':
- return ComboBoxControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def CustomControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'CustomControl':
- return CustomControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def DataGridControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'DataGridControl':
- return DataGridControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def DataItemControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'DataItemControl':
- return DataItemControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def DocumentControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'DocumentControl':
- return DocumentControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def EditControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'EditControl':
- return EditControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def GroupControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'GroupControl':
- return GroupControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def HeaderControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'HeaderControl':
- return HeaderControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def HeaderItemControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'HeaderItemControl':
- return HeaderItemControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def HyperlinkControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'HyperlinkControl':
- return HyperlinkControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def ImageControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'ImageControl':
- return ImageControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def ListControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'ListControl':
- return ListControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def ListItemControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'ListItemControl':
- return ListItemControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def MenuControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'MenuControl':
- return MenuControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def MenuBarControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'MenuBarControl':
- return MenuBarControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def MenuItemControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'MenuItemControl':
- return MenuItemControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def PaneControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'PaneControl':
- return PaneControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def ProgressBarControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'ProgressBarControl':
- return ProgressBarControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def RadioButtonControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'RadioButtonControl':
- return RadioButtonControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def ScrollBarControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'ScrollBarControl':
- return ScrollBarControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def SemanticZoomControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'SemanticZoomControl':
- return SemanticZoomControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def SeparatorControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'SeparatorControl':
- return SeparatorControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def SliderControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'SliderControl':
- return SliderControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def SpinnerControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'SpinnerControl':
- return SpinnerControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def SplitButtonControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'SplitButtonControl':
- return SplitButtonControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def StatusBarControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'StatusBarControl':
- return StatusBarControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def TabControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'TabControl':
- return TabControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def TabItemControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'TabItemControl':
- return TabItemControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def TableControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'TableControl':
- return TableControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def TextControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'TextControl':
- return TextControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def ThumbControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'ThumbControl':
- return ThumbControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def TitleBarControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'TitleBarControl':
- return TitleBarControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def ToolBarControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'ToolBarControl':
- return ToolBarControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def ToolTipControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'ToolTipControl':
- return ToolTipControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def TreeControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'TreeControl':
- return TreeControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def TreeItemControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'TreeItemControl':
- return TreeItemControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
-
- def WindowControl(self, searchDepth=0xFFFFFFFF, searchInterval=SEARCH_INTERVAL, foundIndex=1, element=0,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties) -> 'WindowControl':
- return WindowControl(searchFromControl=self, searchDepth=searchDepth, searchInterval=searchInterval,
- foundIndex=foundIndex, element=element,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def Control(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "Control":
+ return Control(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def ButtonControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "ButtonControl":
+ return ButtonControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def CalendarControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "CalendarControl":
+ return CalendarControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def CheckBoxControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "CheckBoxControl":
+ return CheckBoxControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def ComboBoxControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "ComboBoxControl":
+ return ComboBoxControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def CustomControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "CustomControl":
+ return CustomControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def DataGridControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "DataGridControl":
+ return DataGridControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def DataItemControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "DataItemControl":
+ return DataItemControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def DocumentControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "DocumentControl":
+ return DocumentControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def EditControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "EditControl":
+ return EditControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def GroupControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "GroupControl":
+ return GroupControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def HeaderControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "HeaderControl":
+ return HeaderControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def HeaderItemControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "HeaderItemControl":
+ return HeaderItemControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def HyperlinkControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "HyperlinkControl":
+ return HyperlinkControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def ImageControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "ImageControl":
+ return ImageControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def ListControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "ListControl":
+ return ListControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def ListItemControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "ListItemControl":
+ return ListItemControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def MenuControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "MenuControl":
+ return MenuControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def MenuBarControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "MenuBarControl":
+ return MenuBarControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def MenuItemControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "MenuItemControl":
+ return MenuItemControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def PaneControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "PaneControl":
+ return PaneControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def ProgressBarControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "ProgressBarControl":
+ return ProgressBarControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def RadioButtonControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "RadioButtonControl":
+ return RadioButtonControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def ScrollBarControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "ScrollBarControl":
+ return ScrollBarControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def SemanticZoomControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "SemanticZoomControl":
+ return SemanticZoomControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def SeparatorControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "SeparatorControl":
+ return SeparatorControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def SliderControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "SliderControl":
+ return SliderControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def SpinnerControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "SpinnerControl":
+ return SpinnerControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def SplitButtonControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "SplitButtonControl":
+ return SplitButtonControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def StatusBarControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "StatusBarControl":
+ return StatusBarControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def TabControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "TabControl":
+ return TabControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def TabItemControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "TabItemControl":
+ return TabItemControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def TableControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "TableControl":
+ return TableControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def TextControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "TextControl":
+ return TextControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def ThumbControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "ThumbControl":
+ return ThumbControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def TitleBarControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "TitleBarControl":
+ return TitleBarControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def ToolBarControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "ToolBarControl":
+ return ToolBarControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def ToolTipControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "ToolTipControl":
+ return ToolTipControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def TreeControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "TreeControl":
+ return TreeControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def TreeItemControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "TreeItemControl":
+ return TreeItemControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
+
+ def WindowControl(
+ self,
+ searchDepth=0xFFFFFFFF,
+ searchInterval=SEARCH_INTERVAL,
+ foundIndex=1,
+ element=0,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ) -> "WindowControl":
+ return WindowControl(
+ searchFromControl=self,
+ searchDepth=searchDepth,
+ searchInterval=searchInterval,
+ foundIndex=foundIndex,
+ element=element,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
class AppBarControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.AppBarControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.AppBarControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
class ButtonControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.ButtonControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.ButtonControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetExpandCollapsePattern(self) -> ExpandCollapsePattern:
"""
@@ -2431,29 +3053,39 @@ class ButtonControl(Control):
class CalendarControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.CalendarControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.CalendarControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetGridPattern(self) -> GridPattern:
"""
@@ -2481,29 +3113,39 @@ class CalendarControl(Control):
class CheckBoxControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.CheckBoxControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.CheckBoxControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetTogglePattern(self) -> TogglePattern:
"""
@@ -2512,7 +3154,7 @@ class CheckBoxControl(Control):
return self.GetPattern(PatternId.TogglePattern)
def SetChecked(self, checked: bool) -> bool:
- '''Return True if set successfully'''
+ """Return True if set successfully"""
tp = self.GetTogglePattern()
if tp:
return tp.SetToggleState(ToggleState.On if checked else ToggleState.Off)
@@ -2520,29 +3162,39 @@ class CheckBoxControl(Control):
class ComboBoxControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.ComboBoxControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.ComboBoxControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetExpandCollapsePattern(self) -> ExpandCollapsePattern:
"""
@@ -2562,7 +3214,13 @@ class ComboBoxControl(Control):
"""
return self.GetPattern(PatternId.ValuePattern)
- def Select(self, itemName: str = '', condition: Callable[[str], bool] | None = None, simulateMove: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> bool:
+ def Select(
+ self,
+ itemName: str = "",
+ condition: Callable[[str], bool] | None = None,
+ simulateMove: bool = True,
+ waitTime: float = OPERATION_WAIT_TIME,
+ ) -> bool:
"""
Show combobox's popup menu and select a item by name.
itemName: str.
@@ -2595,7 +3253,9 @@ class ComboBoxControl(Control):
listControl = ListControl(searchDepth=1)
if listControl.Exists(1):
if condition:
- listItemControl = listControl.ListItemControl(Compare=lambda c, d: condition(c.Name))
+ listItemControl = listControl.ListItemControl(
+ Compare=lambda c, d: condition(c.Name)
+ )
else:
listItemControl = listControl.ListItemControl(Name=itemName)
if listItemControl.Exists(0, 0):
@@ -2613,55 +3273,75 @@ class ComboBoxControl(Control):
class CustomControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.CustomControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.CustomControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
class DataGridControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.DataGridControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.DataGridControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetGridPattern(self) -> GridPattern:
"""
@@ -2689,29 +3369,39 @@ class DataGridControl(Control):
class DataItemControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.DataItemControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.DataItemControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetSelectionItemPattern(self) -> SelectionItemPattern:
"""
@@ -2757,29 +3447,39 @@ class DataItemControl(Control):
class DocumentControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.DocumentControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.DocumentControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetTextPattern(self) -> TextPattern:
"""
@@ -2801,29 +3501,39 @@ class DocumentControl(Control):
class EditControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.EditControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.EditControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetRangeValuePattern(self) -> RangeValuePattern:
"""
@@ -2845,29 +3555,39 @@ class EditControl(Control):
class GroupControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.GroupControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.GroupControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetExpandCollapsePattern(self) -> ExpandCollapsePattern:
"""
@@ -2877,29 +3597,39 @@ class GroupControl(Control):
class HeaderControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.HeaderControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.HeaderControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetTransformPattern(self) -> TransformPattern:
"""
@@ -2909,29 +3639,39 @@ class HeaderControl(Control):
class HeaderItemControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.HeaderItemControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.HeaderItemControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetInvokePattern(self) -> InvokePattern:
"""
@@ -2947,29 +3687,39 @@ class HeaderItemControl(Control):
class HyperlinkControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.HyperlinkControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.HyperlinkControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetInvokePattern(self) -> InvokePattern:
"""
@@ -2985,29 +3735,39 @@ class HyperlinkControl(Control):
class ImageControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.ImageControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.ImageControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetGridItemPattern(self) -> GridItemPattern:
"""
@@ -3023,29 +3783,39 @@ class ImageControl(Control):
class ListControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.ListControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.ListControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetGridPattern(self) -> GridPattern:
"""
@@ -3073,29 +3843,39 @@ class ListControl(Control):
class ListItemControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.ListItemControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.ListItemControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetSelectionItemPattern(self) -> SelectionItemPattern:
"""
@@ -3141,55 +3921,75 @@ class ListItemControl(Control):
class MenuControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.MenuControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.MenuControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
class MenuBarControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.MenuBarControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.MenuBarControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetDockPattern(self) -> DockPattern:
"""
@@ -3211,29 +4011,39 @@ class MenuBarControl(Control):
class MenuItemControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.MenuItemControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.MenuItemControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetExpandCollapsePattern(self) -> ExpandCollapsePattern:
"""
@@ -3341,36 +4151,48 @@ class TopLevel:
ret = ShowWindow(handle, SW.Restore)
elif not IsWindowVisible(handle):
ret = ShowWindow(handle, SW.Show)
- ret = SetForegroundWindow(handle) # may fail if foreground windows's process is not python
+ ret = SetForegroundWindow(
+ handle
+ ) # may fail if foreground windows's process is not python
time.sleep(waitTime)
return ret
return False
class PaneControl(Control, TopLevel):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.PaneControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.PaneControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetDockPattern(self) -> DockPattern:
"""
@@ -3392,29 +4214,39 @@ class PaneControl(Control, TopLevel):
class ProgressBarControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.ProgressBarControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.ProgressBarControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetRangeValuePattern(self) -> RangeValuePattern:
"""
@@ -3430,29 +4262,39 @@ class ProgressBarControl(Control):
class RadioButtonControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.RadioButtonControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.RadioButtonControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetSelectionItemPattern(self) -> SelectionItemPattern:
"""
@@ -3462,29 +4304,39 @@ class RadioButtonControl(Control):
class ScrollBarControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.ScrollBarControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.ScrollBarControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetRangeValuePattern(self) -> RangeValuePattern:
"""
@@ -3494,81 +4346,111 @@ class ScrollBarControl(Control):
class SemanticZoomControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.SemanticZoomControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.SemanticZoomControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
class SeparatorControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.SeparatorControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.SeparatorControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
class SliderControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.SliderControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.SliderControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetRangeValuePattern(self) -> RangeValuePattern:
"""
@@ -3590,29 +4472,39 @@ class SliderControl(Control):
class SpinnerControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.SpinnerControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.SpinnerControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetRangeValuePattern(self) -> RangeValuePattern:
"""
@@ -3634,29 +4526,39 @@ class SpinnerControl(Control):
class SplitButtonControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.SplitButtonControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.SplitButtonControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetExpandCollapsePattern(self) -> ExpandCollapsePattern:
"""
@@ -3672,29 +4574,39 @@ class SplitButtonControl(Control):
class StatusBarControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.StatusBarControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.StatusBarControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetGridPattern(self) -> GridPattern:
"""
@@ -3704,29 +4616,39 @@ class StatusBarControl(Control):
class TabControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.TabControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.TabControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetSelectionPattern(self) -> SelectionPattern:
"""
@@ -3742,29 +4664,39 @@ class TabControl(Control):
class TabItemControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.TabItemControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.TabItemControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetSelectionItemPattern(self) -> SelectionItemPattern:
"""
@@ -3774,29 +4706,39 @@ class TabItemControl(Control):
class TableControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.TableControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.TableControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetGridPattern(self) -> GridPattern:
"""
@@ -3842,29 +4784,39 @@ class TableControl(Control):
class TextControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.TextControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.TextControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetGridItemPattern(self) -> GridItemPattern:
"""
@@ -3886,29 +4838,39 @@ class TextControl(Control):
class ThumbControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.ThumbControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.ThumbControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetTransformPattern(self) -> TransformPattern:
"""
@@ -3918,55 +4880,75 @@ class ThumbControl(Control):
class TitleBarControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.TitleBarControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.TitleBarControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
class ToolBarControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.ToolBarControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.ToolBarControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetDockPattern(self) -> DockPattern:
"""
@@ -3988,29 +4970,39 @@ class ToolBarControl(Control):
class ToolTipControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.ToolTipControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.ToolTipControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetTextPattern(self) -> TextPattern:
"""
@@ -4026,29 +5018,39 @@ class ToolTipControl(Control):
class TreeControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.TreeControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.TreeControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetScrollPattern(self) -> ScrollPattern:
"""
@@ -4064,29 +5066,39 @@ class TreeControl(Control):
class TreeItemControl(Control):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.TreeItemControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.TreeItemControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
def GetExpandCollapsePattern(self) -> ExpandCollapsePattern:
"""
@@ -4120,29 +5132,39 @@ class TreeItemControl(Control):
class WindowControl(Control, TopLevel):
- def __init__(self, searchFromControl: Control | None = None,
- searchDepth: int = 0xFFFFFFFF,
- searchInterval: float = SEARCH_INTERVAL,
- foundIndex: int = 1,
- element=None,
- Name: str | None = None,
- SubName: str | None = None,
- RegexName: str | None = None,
- ClassName: str | None = None,
- AutomationId: str | None = None,
- Depth: int | None = None,
- Compare: Callable[[TreeNode], bool] | None = None,
- **searchProperties):
- Control.__init__(self, searchFromControl, searchDepth, searchInterval, foundIndex, element,
- ControlType=ControlType.WindowControl,
- Name=Name,
- SubName=SubName,
- RegexName=RegexName,
- ClassName=ClassName,
- AutomationId=AutomationId,
- Depth=Depth,
- Compare=Compare,
- **searchProperties)
+ def __init__(
+ self,
+ searchFromControl: Control | None = None,
+ searchDepth: int = 0xFFFFFFFF,
+ searchInterval: float = SEARCH_INTERVAL,
+ foundIndex: int = 1,
+ element=None,
+ Name: str | None = None,
+ SubName: str | None = None,
+ RegexName: str | None = None,
+ ClassName: str | None = None,
+ AutomationId: str | None = None,
+ Depth: int | None = None,
+ Compare: Callable[[TreeNode], bool] | None = None,
+ **searchProperties,
+ ):
+ Control.__init__(
+ self,
+ searchFromControl,
+ searchDepth,
+ searchInterval,
+ foundIndex,
+ element,
+ ControlType=ControlType.WindowControl,
+ Name=Name,
+ SubName=SubName,
+ RegexName=RegexName,
+ ClassName=ClassName,
+ AutomationId=AutomationId,
+ Depth=Depth,
+ Compare=Compare,
+ **searchProperties,
+ )
self._DockPattern = None
self._TransformPattern = None
@@ -4251,9 +5273,15 @@ def WaitForDisappear(control: Control, timeout: float) -> bool:
return control.Disappears(timeout, 1)
-def WalkTree(top, getChildren: Callable[[TreeNode], list[TreeNode]] | None = None,
- getFirstChild: Callable[[TreeNode], TreeNode] | None = None, getNextSibling: Callable[[TreeNode], TreeNode] | None = None,
- yieldCondition: Callable[[TreeNode, int], bool] | None = None, includeTop: bool = False, maxDepth: int = 0xFFFFFFFF):
+def WalkTree(
+ top,
+ getChildren: Callable[[TreeNode], list[TreeNode]] | None = None,
+ getFirstChild: Callable[[TreeNode], TreeNode] | None = None,
+ getNextSibling: Callable[[TreeNode], TreeNode] | None = None,
+ yieldCondition: Callable[[TreeNode, int], bool] | None = None,
+ includeTop: bool = False,
+ maxDepth: int = 0xFFFFFFFF,
+):
"""
Walk a tree not using recursive algorithm.
top: a tree node.
@@ -4328,41 +5356,47 @@ def GetRootControl() -> PaneControl:
Get root control, the Desktop window.
Return `PaneControl`.
"""
- control = Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.GetRootElement())
+ control = Control.CreateControlFromElement(
+ _AutomationClient.instance().IUIAutomation.GetRootElement()
+ )
if isinstance(control, PaneControl):
return control
if control is None:
- raise AssertionError('Expected valid root element')
- raise AssertionError(f'Expected root element to be a PaneControl. Found: {type(control)} ({control})')
+ raise AssertionError("Expected valid root element")
+ raise AssertionError(
+ f"Expected root element to be a PaneControl. Found: {type(control)} ({control})"
+ )
def GetFocusedControl() -> Control | None:
"""Return `Control` subclass."""
- return Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.GetFocusedElement())
+ return Control.CreateControlFromElement(
+ _AutomationClient.instance().IUIAutomation.GetFocusedElement()
+ )
def GetForegroundControl() -> Control:
"""Return `Control` subclass."""
return ControlFromHandle(GetForegroundWindow())
# another implement
- #focusedControl = GetFocusedControl()
- #parentControl = focusedControl
- #controlList = []
+ # focusedControl = GetFocusedControl()
+ # parentControl = focusedControl
+ # controlList = []
# while parentControl:
- #controlList.insert(0, parentControl)
- #parentControl = parentControl.GetParentControl()
+ # controlList.insert(0, parentControl)
+ # parentControl = parentControl.GetParentControl()
# if len(controlList) == 1:
- #parentControl = controlList[0]
+ # parentControl = controlList[0]
# else:
- #parentControl = controlList[1]
+ # parentControl = controlList[1]
# return parentControl
def GetConsoleWindow() -> WindowControl | None:
"""Return `WindowControl` or None, a console window that runs python."""
consoleWindow = ControlFromHandle(ctypes.windll.kernel32.GetConsoleWindow())
- if consoleWindow and consoleWindow.ClassName == 'PseudoConsoleWindow':
+ if consoleWindow and consoleWindow.ClassName == "PseudoConsoleWindow":
# Windows Terminal
consoleWindow = consoleWindow.GetParentControl()
return consoleWindow
@@ -4373,7 +5407,9 @@ def ControlFromPoint(x: int, y: int) -> Control | None:
Call IUIAutomation ElementFromPoint x,y. May return None if mouse is over cmd's title bar icon.
Return `Control` subclass or None.
"""
- element = _AutomationClient.instance().IUIAutomation.ElementFromPoint(ctypes.wintypes.POINT(x, y))
+ element = _AutomationClient.instance().IUIAutomation.ElementFromPoint(
+ ctypes.wintypes.POINT(x, y)
+ )
return Control.CreateControlFromElement(element)
@@ -4382,7 +5418,9 @@ def ControlFromPoint2(x: int, y: int) -> Control | None:
Get a native handle from point x,y and call IUIAutomation.ElementFromHandle.
Return `Control` subclass.
"""
- return Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.ElementFromHandle(WindowFromPoint(x, y)))
+ return Control.CreateControlFromElement(
+ _AutomationClient.instance().IUIAutomation.ElementFromHandle(WindowFromPoint(x, y))
+ )
def ControlFromCursor() -> Control | None:
@@ -4410,7 +5448,9 @@ def ControlFromHandle(handle: int) -> Control | None:
Return `Control` subclass or None.
"""
if handle:
- return Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.ElementFromHandle(handle))
+ return Control.CreateControlFromElement(
+ _AutomationClient.instance().IUIAutomation.ElementFromHandle(handle)
+ )
return None
@@ -4420,10 +5460,16 @@ def ControlsAreSame(control1: Control, control2: Control) -> bool:
control2: `Control` or its subclass.
Return bool, True if control1 and control2 represent the same control otherwise False.
"""
- return bool(_AutomationClient.instance().IUIAutomation.CompareElements(control1.Element, control2.Element))
+ return bool(
+ _AutomationClient.instance().IUIAutomation.CompareElements(
+ control1.Element, control2.Element
+ )
+ )
-def WalkControl(control: Control, includeTop: bool = False, maxDepth: int = 0xFFFFFFFF) -> Generator[Tuple[Control, int], None, None]:
+def WalkControl(
+ control: Control, includeTop: bool = False, maxDepth: int = 0xFFFFFFFF
+) -> Generator[Tuple[Control, int], None, None]:
"""
control: `Control` or its subclass.
includeTop: bool, if True, yield (control, 0) first.
@@ -4453,7 +5499,9 @@ def WalkControl(control: Control, includeTop: bool = False, maxDepth: int = 0xFF
depth -= 1
-def LogControl(control: Control, depth: int = 0, showAllName: bool = True, showPid: bool = False) -> None:
+def LogControl(
+ control: Control, depth: int = 0, showAllName: bool = True, showPid: bool = False
+) -> None:
"""
Print and log control's properties.
control: `Control` or its subclass.
@@ -4463,7 +5511,13 @@ def LogControl(control: Control, depth: int = 0, showAllName: bool = True, showP
pass
-def EnumAndLogControl(control: Control, maxDepth: int = 0xFFFFFFFF, showAllName: bool = True, showPid: bool = False, startDepth: int = 0) -> None:
+def EnumAndLogControl(
+ control: Control,
+ maxDepth: int = 0xFFFFFFFF,
+ showAllName: bool = True,
+ showPid: bool = False,
+ startDepth: int = 0,
+) -> None:
"""
Print and log control and its descendants' propertyies.
control: `Control` or its subclass.
@@ -4475,7 +5529,9 @@ def EnumAndLogControl(control: Control, maxDepth: int = 0xFFFFFFFF, showAllName:
LogControl(c, d + startDepth, showAllName, showPid)
-def EnumAndLogControlAncestors(control: Control, showAllName: bool = True, showPid: bool = False) -> None:
+def EnumAndLogControlAncestors(
+ control: Control, showAllName: bool = True, showPid: bool = False
+) -> None:
"""
Print and log control and its ancestors' propertyies.
control: `Control` or its subclass.
@@ -4490,7 +5546,13 @@ def EnumAndLogControlAncestors(control: Control, showAllName: bool = True, showP
LogControl(curr, i, showAllName, showPid)
-def FindControl(control: Control | None, compare: Callable[[Control, int], bool], maxDepth: int = 0xFFFFFFFF, findFromSelf: bool = False, foundIndex: int = 1) -> Control | None:
+def FindControl(
+ control: Control | None,
+ compare: Callable[[Control, int], bool],
+ maxDepth: int = 0xFFFFFFFF,
+ findFromSelf: bool = False,
+ foundIndex: int = 1,
+) -> Control | None:
"""
control: `Control` or its subclass.
compare: Callable[[Control, int], bool], function(control: Control, depth: int) -> bool.
@@ -4515,24 +5577,25 @@ def FindControl(control: Control | None, compare: Callable[[Control, int], bool]
def ShowDesktop(waitTime: float = 1) -> None:
"""Show Desktop by pressing win + d"""
- SendKeys('{Win}d', waitTime=waitTime)
+ SendKeys("{Win}d", waitTime=waitTime)
# another implement
- #paneTray = PaneControl(searchDepth = 1, ClassName = 'Shell_TrayWnd')
+ # paneTray = PaneControl(searchDepth = 1, ClassName = 'Shell_TrayWnd')
# if paneTray.Exists():
- #WM_COMMAND = 0x111
- #MIN_ALL = 419
- #MIN_ALL_UNDO = 416
- #PostMessage(paneTray.NativeWindowHandle, WM_COMMAND, MIN_ALL, 0)
- # time.sleep(1)
+ # WM_COMMAND = 0x111
+ # MIN_ALL = 419
+ # MIN_ALL_UNDO = 416
+ # PostMessage(paneTray.NativeWindowHandle, WM_COMMAND, MIN_ALL, 0)
+ # time.sleep(1)
def WaitHotKeyReleased(hotkey: Tuple[int, int], waitTime: float = OPERATION_WAIT_TIME) -> None:
"""hotkey: Tuple[int, int], two ints tuple (modifierKey, key)"""
- mod = {ModifierKey.Alt: Keys.VK_MENU,
- ModifierKey.Control: Keys.VK_CONTROL,
- ModifierKey.Shift: Keys.VK_SHIFT,
- ModifierKey.Win: Keys.VK_LWIN
- }
+ mod = {
+ ModifierKey.Alt: Keys.VK_MENU,
+ ModifierKey.Control: Keys.VK_CONTROL,
+ ModifierKey.Shift: Keys.VK_SHIFT,
+ ModifierKey.Win: Keys.VK_LWIN,
+ }
while True:
time.sleep(waitTime)
if IsKeyPressed(hotkey[1]):
diff --git a/windows_use/uia/core.py b/windows_use/uia/core.py
index b9d7900..e5ce1d4 100644
--- a/windows_use/uia/core.py
+++ b/windows_use/uia/core.py
@@ -1,4 +1,4 @@
-'''
+"""
uiautomation for Python 3.
Author: yinkaisheng
Source: https://github.com/yinkaisheng/Python-UIAutomation-for-Windows
@@ -9,7 +9,7 @@ Run 'automation.py -h' for help.
uiautomation is shared under the Apache Licene 2.0.
This means that the code can be freely copied and distributed, and costs nothing to use.
-'''
+"""
import ctypes
import ctypes.wintypes
@@ -25,7 +25,7 @@ from typing import Any
import comtypes
import comtypes.client
-METRO_WINDOW_CLASS_NAME = 'Windows.UI.Core.CoreWindow' # for Windows 8 and 8.1
+METRO_WINDOW_CLASS_NAME = "Windows.UI.Core.CoreWindow" # for Windows 8 and 8.1
SEARCH_INTERVAL = 0.5 # search control interval seconds
MAX_MOVE_SECOND = 1 # simulate mouse move or drag max seconds
TIME_OUT_SECOND = 10
@@ -47,18 +47,23 @@ from .enums import *
def IsTopLevelWindow(handle: int) -> bool:
return ctypes.windll.user32.GetParent(handle) == 0
+
def IsIconic(handle: int) -> bool:
return bool(ctypes.windll.user32.IsIconic(handle))
+
def IsZoomed(handle: int) -> bool:
return bool(ctypes.windll.user32.IsZoomed(handle))
+
def IsWindowVisible(handle: int) -> bool:
return bool(ctypes.windll.user32.IsWindowVisible(handle))
+
def ShowWindow(handle: int, cmdShow: int) -> bool:
return bool(ctypes.windll.user32.ShowWindow(handle, cmdShow))
+
def GetForegroundWindow() -> int:
return ctypes.windll.user32.GetForegroundWindow()
@@ -67,7 +72,7 @@ class _AutomationClient:
_instance = None
@classmethod
- def instance(cls) -> '_AutomationClient':
+ def instance(cls) -> "_AutomationClient":
"""Singleton instance (this prevents com creation on import)."""
if cls._instance is None:
cls._instance = cls()
@@ -82,16 +87,18 @@ class _AutomationClient:
for retry in range(tryCount):
try:
self.UIAutomationCore = comtypes.client.GetModule("UIAutomationCore.dll")
- self.IUIAutomation = comtypes.client.CreateObject("{ff48dba4-60ef-4201-aa87-54103eef594e}", interface=self.UIAutomationCore.IUIAutomation)
+ self.IUIAutomation = comtypes.client.CreateObject(
+ "{ff48dba4-60ef-4201-aa87-54103eef594e}",
+ interface=self.UIAutomationCore.IUIAutomation,
+ )
self.ViewWalker = self.IUIAutomation.RawViewWalker
- #self.ViewWalker = self.IUIAutomation.ControlViewWalker
+ # self.ViewWalker = self.IUIAutomation.ControlViewWalker
break
except Exception as ex:
if retry + 1 == tryCount:
raise ex
-
# set Windows dll restype
ctypes.windll.user32.GetAncestor.restype = ctypes.c_void_p
ctypes.windll.user32.GetClipboardData.restype = ctypes.c_void_p
@@ -111,7 +118,10 @@ ctypes.windll.kernel32.GlobalLock.restype = ctypes.c_void_p
ctypes.windll.kernel32.OpenProcess.restype = ctypes.c_void_p
ctypes.windll.ntdll.NtQueryInformationProcess.restype = ctypes.c_uint32
-def _GetDictKeyName(theDict: dict[str, Any], theValue: Any, keyCondition: Callable[[str], bool] | None = None) -> str:
+
+def _GetDictKeyName(
+ theDict: dict[str, Any], theValue: Any, keyCondition: Callable[[str], bool] | None = None
+) -> str:
for key, value in theDict.items():
if keyCondition:
if keyCondition(key) and theValue == value:
@@ -119,7 +129,7 @@ def _GetDictKeyName(theDict: dict[str, Any], theValue: Any, keyCondition: Callab
else:
if theValue == value:
return key
- return ''
+ return ""
_StdOutputHandle = -11
@@ -137,13 +147,19 @@ def SetConsoleColor(color: int) -> bool:
global _DefaultConsoleColor
if not _DefaultConsoleColor:
if not _ConsoleOutputHandle:
- _ConsoleOutputHandle = ctypes.c_void_p(ctypes.windll.kernel32.GetStdHandle(_StdOutputHandle))
+ _ConsoleOutputHandle = ctypes.c_void_p(
+ ctypes.windll.kernel32.GetStdHandle(_StdOutputHandle)
+ )
bufferInfo = ConsoleScreenBufferInfo()
- ctypes.windll.kernel32.GetConsoleScreenBufferInfo(_ConsoleOutputHandle, ctypes.byref(bufferInfo))
+ ctypes.windll.kernel32.GetConsoleScreenBufferInfo(
+ _ConsoleOutputHandle, ctypes.byref(bufferInfo)
+ )
_DefaultConsoleColor = int(bufferInfo.wAttributes & 0xFF)
if sys.stdout:
sys.stdout.flush()
- return bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, ctypes.c_ushort(color)))
+ return bool(
+ ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, ctypes.c_ushort(color))
+ )
def ResetConsoleColor() -> bool:
@@ -153,8 +169,12 @@ def ResetConsoleColor() -> bool:
"""
if sys.stdout:
sys.stdout.flush()
- assert _DefaultConsoleColor is not None, 'SetConsoleColor not previously called.'
- return bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, ctypes.c_ushort(_DefaultConsoleColor)))
+ assert _DefaultConsoleColor is not None, "SetConsoleColor not previously called."
+ return bool(
+ ctypes.windll.kernel32.SetConsoleTextAttribute(
+ _ConsoleOutputHandle, ctypes.c_ushort(_DefaultConsoleColor)
+ )
+ )
def WindowFromPoint(x: int, y: int) -> int:
@@ -162,7 +182,9 @@ def WindowFromPoint(x: int, y: int) -> int:
WindowFromPoint from Win32.
Return int, a native window handle.
"""
- return ctypes.windll.user32.WindowFromPoint(ctypes.wintypes.POINT(x, y)) # or ctypes.windll.user32.WindowFromPoint(x, y)
+ return ctypes.windll.user32.WindowFromPoint(
+ ctypes.wintypes.POINT(x, y)
+ ) # or ctypes.windll.user32.WindowFromPoint(x, y)
def GetCursorPos() -> tuple[int, int]:
@@ -221,7 +243,14 @@ def PostMessage(handle: int, msg: int, wParam: int, lParam: int) -> bool:
PostMessage from Win32.
Return bool, True if succeed otherwise False.
"""
- return bool(ctypes.windll.user32.PostMessageW(ctypes.c_void_p(handle), ctypes.c_uint(msg), ctypes.wintypes.WPARAM(wParam), ctypes.wintypes.LPARAM(lParam)))
+ return bool(
+ ctypes.windll.user32.PostMessageW(
+ ctypes.c_void_p(handle),
+ ctypes.c_uint(msg),
+ ctypes.wintypes.WPARAM(wParam),
+ ctypes.wintypes.LPARAM(lParam),
+ )
+ )
def SendMessage(handle: int, msg: int, wParam: int, lParam: int) -> int:
@@ -230,7 +259,12 @@ def SendMessage(handle: int, msg: int, wParam: int, lParam: int) -> int:
Return int, the return value specifies the result of the message processing;
it depends on the message sent.
"""
- return ctypes.windll.user32.SendMessageW(ctypes.c_void_p(handle), ctypes.c_uint(msg), ctypes.wintypes.WPARAM(wParam), ctypes.wintypes.LPARAM(lParam))
+ return ctypes.windll.user32.SendMessageW(
+ ctypes.c_void_p(handle),
+ ctypes.c_uint(msg),
+ ctypes.wintypes.WPARAM(wParam),
+ ctypes.wintypes.LPARAM(lParam),
+ )
def Click(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None:
@@ -242,9 +276,21 @@ def Click(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
SetCursorPos(x, y)
screenWidth, screenHeight = GetScreenSize()
- mouse_event(MouseEventFlag.LeftDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0)
+ mouse_event(
+ MouseEventFlag.LeftDown | MouseEventFlag.Absolute,
+ x * 65535 // screenWidth,
+ y * 65535 // screenHeight,
+ 0,
+ 0,
+ )
time.sleep(0.05)
- mouse_event(MouseEventFlag.LeftUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0)
+ mouse_event(
+ MouseEventFlag.LeftUp | MouseEventFlag.Absolute,
+ x * 65535 // screenWidth,
+ y * 65535 // screenHeight,
+ 0,
+ 0,
+ )
time.sleep(waitTime)
@@ -257,9 +303,21 @@ def MiddleClick(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
SetCursorPos(x, y)
screenWidth, screenHeight = GetScreenSize()
- mouse_event(MouseEventFlag.MiddleDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0)
+ mouse_event(
+ MouseEventFlag.MiddleDown | MouseEventFlag.Absolute,
+ x * 65535 // screenWidth,
+ y * 65535 // screenHeight,
+ 0,
+ 0,
+ )
time.sleep(0.05)
- mouse_event(MouseEventFlag.MiddleUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0)
+ mouse_event(
+ MouseEventFlag.MiddleUp | MouseEventFlag.Absolute,
+ x * 65535 // screenWidth,
+ y * 65535 // screenHeight,
+ 0,
+ 0,
+ )
time.sleep(waitTime)
@@ -272,9 +330,21 @@ def RightClick(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
SetCursorPos(x, y)
screenWidth, screenHeight = GetScreenSize()
- mouse_event(MouseEventFlag.RightDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0)
+ mouse_event(
+ MouseEventFlag.RightDown | MouseEventFlag.Absolute,
+ x * 65535 // screenWidth,
+ y * 65535 // screenHeight,
+ 0,
+ 0,
+ )
time.sleep(0.05)
- mouse_event(MouseEventFlag.RightUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0)
+ mouse_event(
+ MouseEventFlag.RightUp | MouseEventFlag.Absolute,
+ x * 65535 // screenWidth,
+ y * 65535 // screenHeight,
+ 0,
+ 0,
+ )
time.sleep(waitTime)
@@ -297,7 +367,13 @@ def PressMouse(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
SetCursorPos(x, y)
screenWidth, screenHeight = GetScreenSize()
- mouse_event(MouseEventFlag.LeftDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0)
+ mouse_event(
+ MouseEventFlag.LeftDown | MouseEventFlag.Absolute,
+ x * 65535 // screenWidth,
+ y * 65535 // screenHeight,
+ 0,
+ 0,
+ )
time.sleep(waitTime)
@@ -308,7 +384,13 @@ def ReleaseMouse(waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
x, y = GetCursorPos()
screenWidth, screenHeight = GetScreenSize()
- mouse_event(MouseEventFlag.LeftUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0)
+ mouse_event(
+ MouseEventFlag.LeftUp | MouseEventFlag.Absolute,
+ x * 65535 // screenWidth,
+ y * 65535 // screenHeight,
+ 0,
+ 0,
+ )
time.sleep(waitTime)
@@ -321,7 +403,13 @@ def RightPressMouse(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> No
"""
SetCursorPos(x, y)
screenWidth, screenHeight = GetScreenSize()
- mouse_event(MouseEventFlag.RightDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0)
+ mouse_event(
+ MouseEventFlag.RightDown | MouseEventFlag.Absolute,
+ x * 65535 // screenWidth,
+ y * 65535 // screenHeight,
+ 0,
+ 0,
+ )
time.sleep(waitTime)
@@ -332,7 +420,13 @@ def RightReleaseMouse(waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
x, y = GetCursorPos()
screenWidth, screenHeight = GetScreenSize()
- mouse_event(MouseEventFlag.RightUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0)
+ mouse_event(
+ MouseEventFlag.RightUp | MouseEventFlag.Absolute,
+ x * 65535 // screenWidth,
+ y * 65535 // screenHeight,
+ 0,
+ 0,
+ )
time.sleep(waitTime)
@@ -345,7 +439,13 @@ def MiddlePressMouse(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> N
"""
SetCursorPos(x, y)
screenWidth, screenHeight = GetScreenSize()
- mouse_event(MouseEventFlag.MiddleDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0)
+ mouse_event(
+ MouseEventFlag.MiddleDown | MouseEventFlag.Absolute,
+ x * 65535 // screenWidth,
+ y * 65535 // screenHeight,
+ 0,
+ 0,
+ )
time.sleep(waitTime)
@@ -356,7 +456,13 @@ def MiddleReleaseMouse(waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
x, y = GetCursorPos()
screenWidth, screenHeight = GetScreenSize()
- mouse_event(MouseEventFlag.MiddleUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0)
+ mouse_event(
+ MouseEventFlag.MiddleUp | MouseEventFlag.Absolute,
+ x * 65535 // screenWidth,
+ y * 65535 // screenHeight,
+ 0,
+ 0,
+ )
time.sleep(waitTime)
@@ -369,7 +475,7 @@ def MoveTo(x: int, y: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAI
waitTime: float.
"""
if moveSpeed <= 0:
- moveTime = 0.
+ moveTime = 0.0
else:
moveTime = MAX_MOVE_SECOND / moveSpeed
curX, curY = GetCursorPos()
@@ -400,7 +506,9 @@ def MoveTo(x: int, y: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAI
time.sleep(waitTime)
-def DragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None:
+def DragDrop(
+ x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME
+) -> None:
"""
Simulate mouse left button drag from point x1, y1 drop to point x2, y2.
x1: int.
@@ -415,7 +523,9 @@ def DragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime:
ReleaseMouse(waitTime)
-def RightDragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None:
+def RightDragDrop(
+ x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME
+) -> None:
"""
Simulate mouse right button drag from point x1, y1 drop to point x2, y2.
x1: int.
@@ -430,7 +540,9 @@ def RightDragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, wait
RightReleaseMouse(waitTime)
-def MiddleDragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None:
+def MiddleDragDrop(
+ x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME
+) -> None:
"""
Simulate mouse middle button drag from point x1, y1 drop to point x2, y2.
x1: int.
@@ -445,7 +557,9 @@ def MiddleDragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, wai
MiddleReleaseMouse(waitTime)
-def WheelDown(wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME) -> None:
+def WheelDown(
+ wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME
+) -> None:
"""
Simulate mouse wheel down.
wheelTimes: int.
@@ -458,7 +572,9 @@ def WheelDown(wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPE
time.sleep(waitTime)
-def WheelUp(wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME) -> None:
+def WheelUp(
+ wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME
+) -> None:
"""
Simulate mouse wheel up.
wheelTimes: int.
@@ -471,7 +587,9 @@ def WheelUp(wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERA
time.sleep(waitTime)
-def WheelLeft(wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME) -> None:
+def WheelLeft(
+ wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME
+) -> None:
"""
Simulate horizontal scroll left.
Uses Shift+wheel on Windows.
@@ -484,7 +602,9 @@ def WheelLeft(wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPE
time.sleep(waitTime)
-def WheelRight(wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME) -> None:
+def WheelRight(
+ wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME
+) -> None:
"""
Simulate horizontal scroll right.
Uses Shift+wheel on Windows.
@@ -497,8 +617,9 @@ def WheelRight(wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OP
time.sleep(waitTime)
-def DragTo(start_x: int, start_y: int, end_x: int, end_y: int,
- duration: float = 0.5, steps: int = 20) -> None:
+def DragTo(
+ start_x: int, start_y: int, end_x: int, end_y: int, duration: float = 0.5, steps: int = 20
+) -> None:
"""
Perform a smooth mouse drag from (start_x, start_y) to (end_x, end_y).
More predictable than DragDrop for short distances and UI drag operations.
@@ -539,14 +660,18 @@ def SetScreenSize(width: int, height: int) -> bool:
DM_PELSHEIGHT = 0x00100000
DISP_CHANGE_SUCCESSFUL = 0
devMode = bytearray(devModeSize)
- devMode[dmSizeOffset:dmSizeOffset+2] = struct.pack("<H", devModeSize)
- cDevMode = (ctypes.c_byte*devModeSize).from_buffer(devMode)
+ devMode[dmSizeOffset : dmSizeOffset + 2] = struct.pack("<H", devModeSize)
+ cDevMode = (ctypes.c_byte * devModeSize).from_buffer(devMode)
if ctypes.windll.user32.EnumDisplaySettingsW(None, ctypes.wintypes.DWORD(-1), cDevMode):
- curWidth, curHeight = struct.unpack("<II", devMode[dmPelsWidthOffset:dmPelsWidthOffset+8])
+ curWidth, curHeight = struct.unpack(
+ "<II", devMode[dmPelsWidthOffset : dmPelsWidthOffset + 8]
+ )
if curWidth == width and curHeight == height:
return True
- devMode[dmFieldsOffset:dmFieldsOffset+4] = struct.pack("<I", DM_PELSWIDTH | DM_PELSHEIGHT)
- devMode[dmPelsWidthOffset:dmPelsWidthOffset+8] = struct.pack("<II", width, height)
+ devMode[dmFieldsOffset : dmFieldsOffset + 4] = struct.pack(
+ "<I", DM_PELSWIDTH | DM_PELSHEIGHT
+ )
+ devMode[dmPelsWidthOffset : dmPelsWidthOffset + 8] = struct.pack("<II", width, height)
if ctypes.windll.user32.ChangeDisplaySettingsW(cDevMode, 0) == DISP_CHANGE_SUCCESSFUL:
return True
return False
@@ -573,24 +698,42 @@ def GetVirtualScreenRect() -> tuple[int, int, int, int]:
ctypes.windll.user32.GetSystemMetrics(SM_XVIRTUALSCREEN),
ctypes.windll.user32.GetSystemMetrics(SM_YVIRTUALSCREEN),
ctypes.windll.user32.GetSystemMetrics(SM_CXVIRTUALSCREEN),
- ctypes.windll.user32.GetSystemMetrics(SM_CYVIRTUALSCREEN)
+ ctypes.windll.user32.GetSystemMetrics(SM_CYVIRTUALSCREEN),
)
-
def GetMonitorsRect() -> list[Rect]:
"""
Get monitors' rect.
Return List[Rect].
"""
- MonitorEnumProc = ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.c_size_t, ctypes.c_size_t, ctypes.POINTER(ctypes.wintypes.RECT), ctypes.c_size_t)
+ MonitorEnumProc = ctypes.WINFUNCTYPE(
+ ctypes.c_int,
+ ctypes.c_size_t,
+ ctypes.c_size_t,
+ ctypes.POINTER(ctypes.wintypes.RECT),
+ ctypes.c_size_t,
+ )
rects = []
- def MonitorCallback(hMonitor: int, hdcMonitor: int, lprcMonitor: ctypes.POINTER(ctypes.wintypes.RECT), dwData: int):
- rect = Rect(lprcMonitor.contents.left, lprcMonitor.contents.top, lprcMonitor.contents.right, lprcMonitor.contents.bottom)
+ def MonitorCallback(
+ hMonitor: int,
+ hdcMonitor: int,
+ lprcMonitor: ctypes.POINTER(ctypes.wintypes.RECT),
+ dwData: int,
+ ):
+ rect = Rect(
+ lprcMonitor.contents.left,
+ lprcMonitor.contents.top,
+ lprcMonitor.contents.right,
+ lprcMonitor.contents.bottom,
+ )
rects.append(rect)
return 1
- ctypes.windll.user32.EnumDisplayMonitors(ctypes.c_void_p(0), ctypes.c_void_p(0), MonitorEnumProc(MonitorCallback), 0)
+
+ ctypes.windll.user32.EnumDisplayMonitors(
+ ctypes.c_void_p(0), ctypes.c_void_p(0), MonitorEnumProc(MonitorCallback), 0
+ )
return rects
@@ -624,7 +767,9 @@ def MessageBox(content: str, title: str, flags: int = MB.Ok) -> int:
flags: int, a value or some combined values in class `MB`.
Return int, a value in MB whose name starts with Id, such as MB.IdOk
"""
- return ctypes.windll.user32.MessageBoxW(ctypes.c_void_p(0), ctypes.c_wchar_p(content), ctypes.c_wchar_p(title), ctypes.c_uint(flags))
+ return ctypes.windll.user32.MessageBoxW(
+ ctypes.c_void_p(0), ctypes.c_wchar_p(content), ctypes.c_wchar_p(title), ctypes.c_uint(flags)
+ )
def SetForegroundWindow(handle: int) -> bool:
@@ -650,7 +795,9 @@ def SwitchToThisWindow(handle: int) -> None:
SwitchToThisWindow from Win32.
handle: int, the handle of a native window.
"""
- ctypes.windll.user32.SwitchToThisWindow(ctypes.c_void_p(handle), ctypes.c_int(1)) # void function, no return
+ ctypes.windll.user32.SwitchToThisWindow(
+ ctypes.c_void_p(handle), ctypes.c_int(1)
+ ) # void function, no return
def GetAncestor(handle: int, flag: int) -> int:
@@ -743,10 +890,21 @@ def MoveWindow(handle: int, x: int, y: int, width: int, height: int, repaint: in
repaint: int, use 1 or 0.
Return bool, True if succeed otherwise False.
"""
- return bool(ctypes.windll.user32.MoveWindow(ctypes.c_void_p(handle), ctypes.c_int(x), ctypes.c_int(y), ctypes.c_int(width), ctypes.c_int(height), ctypes.c_int(repaint)))
+ return bool(
+ ctypes.windll.user32.MoveWindow(
+ ctypes.c_void_p(handle),
+ ctypes.c_int(x),
+ ctypes.c_int(y),
+ ctypes.c_int(width),
+ ctypes.c_int(height),
+ ctypes.c_int(repaint),
+ )
+ )
-def SetWindowPos(handle: int, hWndInsertAfter: int, x: int, y: int, width: int, height: int, flags: int) -> bool:
+def SetWindowPos(
+ handle: int, hWndInsertAfter: int, x: int, y: int, width: int, height: int, flags: int
+) -> bool:
"""
SetWindowPos from Win32.
handle: int, the handle of a native window.
@@ -758,7 +916,17 @@ def SetWindowPos(handle: int, hWndInsertAfter: int, x: int, y: int, width: int,
flags: int, values whose name starts with 'SWP' in class `SWP`.
Return bool, True if succeed otherwise False.
"""
- return bool(ctypes.windll.user32.SetWindowPos(ctypes.c_void_p(handle), ctypes.c_void_p(hWndInsertAfter), ctypes.c_int(x), ctypes.c_int(y), ctypes.c_int(width), ctypes.c_int(height), ctypes.c_uint(flags)))
+ return bool(
+ ctypes.windll.user32.SetWindowPos(
+ ctypes.c_void_p(handle),
+ ctypes.c_void_p(hWndInsertAfter),
+ ctypes.c_int(x),
+ ctypes.c_int(y),
+ ctypes.c_int(width),
+ ctypes.c_int(height),
+ ctypes.c_uint(flags),
+ )
+ )
def SetWindowTopmost(handle: int, isTopmost: bool) -> bool:
@@ -790,7 +958,9 @@ def SetWindowText(handle: int, text: str) -> bool:
text: str.
Return bool, True if succeed otherwise False.
"""
- return bool(ctypes.windll.user32.SetWindowTextW(ctypes.c_void_p(handle), ctypes.c_wchar_p(text)))
+ return bool(
+ ctypes.windll.user32.SetWindowTextW(ctypes.c_void_p(handle), ctypes.c_wchar_p(text))
+ )
def GetEditText(handle: int) -> str:
@@ -818,7 +988,7 @@ def GetConsoleOriginalTitle() -> str:
ctypes.windll.kernel32.GetConsoleOriginalTitleW(values, ctypes.c_uint(MAX_PATH))
return values.value
else:
- raise RuntimeError('GetConsoleOriginalTitle is not supported on Windows XP or lower.')
+ raise RuntimeError("GetConsoleOriginalTitle is not supported on Windows XP or lower.")
def GetConsoleTitle() -> str:
@@ -855,7 +1025,7 @@ def DwmIsCompositionEnabled() -> bool:
Return bool.
"""
try:
- dwmapi = ctypes.WinDLL('dwmapi')
+ dwmapi = ctypes.WinDLL("dwmapi")
dwmapi.DwmIsCompositionEnabled.restype = ctypes.HRESULT
isEnabled = ctypes.wintypes.BOOL()
hr = dwmapi.DwmIsCompositionEnabled(ctypes.byref(isEnabled))
@@ -874,14 +1044,14 @@ def DwmGetWindowExtendFrameBounds(handle: int) -> Rect | None:
"""
try:
DWMWA_EXTENDED_FRAME_BOUNDS = 9
- dwmapi = ctypes.WinDLL('dwmapi')
+ dwmapi = ctypes.WinDLL("dwmapi")
dwmapi.DwmGetWindowAttribute.restype = ctypes.HRESULT
rect = ctypes.wintypes.RECT()
hr = dwmapi.DwmGetWindowAttribute(
ctypes.c_void_p(handle),
DWMWA_EXTENDED_FRAME_BOUNDS,
ctypes.byref(rect),
- ctypes.sizeof(ctypes.wintypes.RECT)
+ ctypes.sizeof(ctypes.wintypes.RECT),
)
if hr == S_OK:
return Rect(rect.left, rect.top, rect.right, rect.bottom)
@@ -910,14 +1080,18 @@ def IsDesktopLocked() -> bool:
Desktop is locked if press Win+L, Ctrl+Alt+Del or in remote desktop mode.
"""
isLocked = False
- desk = ctypes.windll.user32.OpenDesktopW(ctypes.c_wchar_p('Default'), ctypes.c_uint(0), ctypes.c_int(0), ctypes.c_uint(0x0100)) # DESKTOP_SWITCHDESKTOP = 0x0100
+ desk = ctypes.windll.user32.OpenDesktopW(
+ ctypes.c_wchar_p("Default"), ctypes.c_uint(0), ctypes.c_int(0), ctypes.c_uint(0x0100)
+ ) # DESKTOP_SWITCHDESKTOP = 0x0100
if desk:
isLocked = not ctypes.windll.user32.SwitchDesktop(ctypes.c_void_p(desk))
ctypes.windll.user32.CloseDesktop(ctypes.c_void_p(desk))
return isLocked
-def PlayWaveFile(filePath: str = r'C:\Windows\Media\notify.wav', isAsync: bool = False, isLoop: bool = False) -> bool:
+def PlayWaveFile(
+ filePath: str = r"C:\Windows\Media\notify.wav", isAsync: bool = False, isLoop: bool = False
+) -> bool:
"""
Call PlaySound from Win32.
filePath: str, if emtpy, stop playing the current sound.
@@ -936,9 +1110,17 @@ def PlayWaveFile(filePath: str = r'C:\Windows\Media\notify.wav', isAsync: bool =
if isLoop:
flags |= SND_LOOP
flags |= SND_ASYNC
- return bool(ctypes.windll.winmm.PlaySoundW(ctypes.c_wchar_p(filePath), ctypes.c_void_p(0), ctypes.c_uint(flags)))
+ return bool(
+ ctypes.windll.winmm.PlaySoundW(
+ ctypes.c_wchar_p(filePath), ctypes.c_void_p(0), ctypes.c_uint(flags)
+ )
+ )
else:
- return bool(ctypes.windll.winmm.PlaySoundW(ctypes.c_wchar_p(0), ctypes.c_void_p(0), ctypes.c_uint(0)))
+ return bool(
+ ctypes.windll.winmm.PlaySoundW(
+ ctypes.c_wchar_p(0), ctypes.c_void_p(0), ctypes.c_uint(0)
+ )
+ )
def IsProcess64Bit(processId: int) -> bool | None:
@@ -951,7 +1133,9 @@ def IsProcess64Bit(processId: int) -> bool | None:
IsWow64Process = ctypes.windll.kernel32.IsWow64Process
except Exception:
return False
- hProcess = ctypes.windll.kernel32.OpenProcess(0x1000, 0, processId) # PROCESS_QUERY_INFORMATION=0x0400,PROCESS_QUERY_LIMITED_INFORMATION=0x1000
+ hProcess = ctypes.windll.kernel32.OpenProcess(
+ 0x1000, 0, processId
+ ) # PROCESS_QUERY_INFORMATION=0x0400,PROCESS_QUERY_LIMITED_INFORMATION=0x1000
if hProcess:
hProcess = ctypes.c_void_p(hProcess)
isWow64 = ctypes.wintypes.BOOL()
@@ -972,7 +1156,9 @@ def IsUserAnAdmin() -> bool:
return bool(ctypes.windll.shell32.IsUserAnAdmin()) if IsNT6orHigher else True
-def RunScriptAsAdmin(argv: list[str], workingDirectory: str = None, showFlag: int = SW.ShowNormal) -> bool:
+def RunScriptAsAdmin(
+ argv: list[str], workingDirectory: str = None, showFlag: int = SW.ShowNormal
+) -> bool:
"""
Run a python script as administrator.
System will show a popup dialog askes you whether to elevate as administrator if UAC is enabled.
@@ -982,7 +1168,12 @@ def RunScriptAsAdmin(argv: list[str], workingDirectory: str = None, showFlag: in
Return bool, True if succeed.
"""
args = shlex.join(argv)
- return ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, args, workingDirectory, showFlag) > 32
+ return (
+ ctypes.windll.shell32.ShellExecuteW(
+ None, "runas", sys.executable, args, workingDirectory, showFlag
+ )
+ > 32
+ )
def SendKey(key: int, waitTime: float = OPERATION_WAIT_TIME) -> None:
@@ -1035,10 +1226,12 @@ def _CreateInput(structure) -> INPUT:
return INPUT(InputType.Keyboard, INPUTUnion(ki=structure))
if isinstance(structure, HARDWAREINPUT):
return INPUT(InputType.Hardware, INPUTUnion(hi=structure))
- raise TypeError('Cannot create INPUT structure!')
+ raise TypeError("Cannot create INPUT structure!")
-def MouseInput(dx: int, dy: int, mouseData: int = 0, dwFlags: int = MouseEventFlag.LeftDown, time_: int = 0) -> INPUT:
+def MouseInput(
+ dx: int, dy: int, mouseData: int = 0, dwFlags: int = MouseEventFlag.LeftDown, time_: int = 0
+) -> INPUT:
"""
Create Win32 struct `MOUSEINPUT` for `SendInput`.
Return `INPUT`.
@@ -1046,7 +1239,9 @@ def MouseInput(dx: int, dy: int, mouseData: int = 0, dwFlags: int = MouseEventFl
return _CreateInput(MOUSEINPUT(dx, dy, mouseData, dwFlags, time_, None))
-def KeyboardInput(wVk: int, wScan: int, dwFlags: int = KeyboardEventFlag.KeyDown, time_: int = 0) -> INPUT:
+def KeyboardInput(
+ wVk: int, wScan: int, dwFlags: int = KeyboardEventFlag.KeyDown, time_: int = 0
+) -> INPUT:
"""Create Win32 struct `KEYBDINPUT` for `SendInput`."""
return _CreateInput(KEYBDINPUT(wVk, wScan, dwFlags, time_, None))
@@ -1068,10 +1263,10 @@ def SendInput(*inputs) -> int:
ret = ctypes.windll.user32.SendInput(1, ctypes.byref(ip), cbSize)
return ret
# or one call
- #nInputs = len(inputs)
- #LPINPUT = INPUT * nInputs
- #pInputs = LPINPUT(*inputs)
- #cbSize = ctypes.c_int(ctypes.sizeof(INPUT))
+ # nInputs = len(inputs)
+ # LPINPUT = INPUT * nInputs
+ # pInputs = LPINPUT(*inputs)
+ # cbSize = ctypes.c_int(ctypes.sizeof(INPUT))
# return ctypes.windll.user32.SendInput(nInputs, ctypes.byref(pInputs), cbSize)
@@ -1097,8 +1292,10 @@ def SendUnicodeChar(char: str, charMode: bool = True) -> int:
vk = 0
scan = ord(char)
flag = KeyboardEventFlag.KeyUnicode
- return SendInput(KeyboardInput(vk, scan, flag | KeyboardEventFlag.KeyDown),
- KeyboardInput(vk, scan, flag | KeyboardEventFlag.KeyUp))
+ return SendInput(
+ KeyboardInput(vk, scan, flag | KeyboardEventFlag.KeyDown),
+ KeyboardInput(vk, scan, flag | KeyboardEventFlag.KeyUp),
+ )
_SCKeys = {
@@ -1146,7 +1343,13 @@ def _VKtoSC(key: int) -> int:
return scanCode
-def SendKeys(text: str, interval: float = 0.01, waitTime: float = OPERATION_WAIT_TIME, charMode: bool = True, debug: bool = False) -> None:
+def SendKeys(
+ text: str,
+ interval: float = 0.01,
+ waitTime: float = OPERATION_WAIT_TIME,
+ charMode: bool = True,
+ debug: bool = False,
+) -> None:
"""
Simulate typing keys on keyboard.
text: str, keys to type.
@@ -1167,7 +1370,23 @@ def SendKeys(text: str, interval: float = 0.01, waitTime: float = OPERATION_WAIT
SendKeys('`~!@#$%^&*()-_=+{Enter}')
SendKeys('[]{{}{}}\\|;:\'\",<.>/?{Enter}')
"""
- holdKeys = ('WIN', 'LWIN', 'RWIN', 'SHIFT', 'LSHIFT', 'RSHIFT', 'CTRL', 'CONTROL', 'LCTRL', 'RCTRL', 'LCONTROL', 'LCONTROL', 'ALT', 'LALT', 'RALT')
+ holdKeys = (
+ "WIN",
+ "LWIN",
+ "RWIN",
+ "SHIFT",
+ "LSHIFT",
+ "RSHIFT",
+ "CTRL",
+ "CONTROL",
+ "LCTRL",
+ "RCTRL",
+ "LCONTROL",
+ "LCONTROL",
+ "ALT",
+ "LALT",
+ "RALT",
+ )
keys = []
printKeys = []
i = 0
@@ -1177,18 +1396,20 @@ def SendKeys(text: str, interval: float = 0.01, waitTime: float = OPERATION_WAIT
include = False
lastKeyValue = None
while True:
- if text[i] == '{':
- rindex = text.find('}', i)
+ if text[i] == "{":
+ rindex = text.find("}", i)
if rindex == i + 1: # {}}
- rindex = text.find('}', i + 2)
+ rindex = text.find("}", i + 2)
if rindex == -1:
raise ValueError('"{" or "{}" is not valid, use "{{}" for "{", use "{}}" for "}"')
- keyStr = text[i + 1:rindex]
- key = [it for it in keyStr.split(' ') if it]
+ keyStr = text[i + 1 : rindex]
+ key = [it for it in keyStr.split(" ") if it]
if not key:
- raise ValueError(f'"{text[i:rindex + 1]}" is not valid, use "{{Space}}" or " " for " "')
+ raise ValueError(
+ f'"{text[i : rindex + 1]}" is not valid, use "{{Space}}" or " " for " "'
+ )
if (len(key) == 2 and not key[1].isdigit()) or len(key) > 2:
- raise ValueError(f'"{text[i:rindex + 1]}" is not valid')
+ raise ValueError(f'"{text[i : rindex + 1]}" is not valid')
upperKey = key[0].upper()
count = 1
if len(key) > 1:
@@ -1199,23 +1420,35 @@ def SendKeys(text: str, interval: float = 0.01, waitTime: float = OPERATION_WAIT
keyValue = SpecialKeyNames[upperKey]
if type(lastKeyValue) == type(keyValue) and lastKeyValue == keyValue:
insertIndex += 1
- printKeys.insert(insertIndex, (key[0], 'KeyDown | ExtendedKey'))
- printKeys.insert(insertIndex + 1, (key[0], 'KeyUp | ExtendedKey'))
- keys.insert(insertIndex, (keyValue, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey))
- keys.insert(insertIndex + 1, (keyValue, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey))
+ printKeys.insert(insertIndex, (key[0], "KeyDown | ExtendedKey"))
+ printKeys.insert(insertIndex + 1, (key[0], "KeyUp | ExtendedKey"))
+ keys.insert(
+ insertIndex,
+ (keyValue, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey),
+ )
+ keys.insert(
+ insertIndex + 1,
+ (keyValue, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey),
+ )
lastKeyValue = keyValue
elif key[0] in CharacterCodes:
keyValue = CharacterCodes[key[0]]
if type(lastKeyValue) == type(keyValue) and lastKeyValue == keyValue:
insertIndex += 1
- printKeys.insert(insertIndex, (key[0], 'KeyDown | ExtendedKey'))
- printKeys.insert(insertIndex + 1, (key[0], 'KeyUp | ExtendedKey'))
- keys.insert(insertIndex, (keyValue, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey))
- keys.insert(insertIndex + 1, (keyValue, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey))
+ printKeys.insert(insertIndex, (key[0], "KeyDown | ExtendedKey"))
+ printKeys.insert(insertIndex + 1, (key[0], "KeyUp | ExtendedKey"))
+ keys.insert(
+ insertIndex,
+ (keyValue, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey),
+ )
+ keys.insert(
+ insertIndex + 1,
+ (keyValue, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey),
+ )
lastKeyValue = keyValue
else:
- printKeys.insert(insertIndex, (key[0], 'UnicodeChar'))
- keys.insert(insertIndex, (key[0], 'UnicodeChar'))
+ printKeys.insert(insertIndex, (key[0], "UnicodeChar"))
+ keys.insert(insertIndex, (key[0], "UnicodeChar"))
lastKeyValue = key[0]
if include:
insertIndex += 1
@@ -1227,10 +1460,14 @@ def SendKeys(text: str, interval: float = 0.01, waitTime: float = OPERATION_WAIT
else:
if upperKey in SpecialKeyNames:
keyValue = SpecialKeyNames[upperKey]
- printKeys.append((key[0], 'KeyDown | ExtendedKey'))
- printKeys.append((key[0], 'KeyUp | ExtendedKey'))
- keys.append((keyValue, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey))
- keys.append((keyValue, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey))
+ printKeys.append((key[0], "KeyDown | ExtendedKey"))
+ printKeys.append((key[0], "KeyUp | ExtendedKey"))
+ keys.append(
+ (keyValue, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey)
+ )
+ keys.append(
+ (keyValue, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey)
+ )
lastKeyValue = keyValue
if upperKey in holdKeys:
hold = True
@@ -1238,56 +1475,66 @@ def SendKeys(text: str, interval: float = 0.01, waitTime: float = OPERATION_WAIT
else:
hold = False
else:
- printKeys.append((key[0], 'UnicodeChar'))
- keys.append((key[0], 'UnicodeChar'))
+ printKeys.append((key[0], "UnicodeChar"))
+ keys.append((key[0], "UnicodeChar"))
lastKeyValue = key[0]
i = rindex + 1
- elif text[i] == '(':
+ elif text[i] == "(":
if hold:
include = True
else:
- printKeys.append((text[i], 'UnicodeChar'))
- keys.append((text[i], 'UnicodeChar'))
+ printKeys.append((text[i], "UnicodeChar"))
+ keys.append((text[i], "UnicodeChar"))
lastKeyValue = text[i]
i += 1
- elif text[i] == ')':
+ elif text[i] == ")":
if hold:
include = False
hold = False
else:
- printKeys.append((text[i], 'UnicodeChar'))
- keys.append((text[i], 'UnicodeChar'))
+ printKeys.append((text[i], "UnicodeChar"))
+ keys.append((text[i], "UnicodeChar"))
lastKeyValue = text[i]
i += 1
else:
if hold:
if text[i] in CharacterCodes:
keyValue = CharacterCodes[text[i]]
- if include and type(lastKeyValue) == type(keyValue) and lastKeyValue == keyValue:
+ if (
+ include
+ and type(lastKeyValue) == type(keyValue)
+ and lastKeyValue == keyValue
+ ):
insertIndex += 1
- printKeys.insert(insertIndex, (text[i], 'KeyDown | ExtendedKey'))
- printKeys.insert(insertIndex + 1, (text[i], 'KeyUp | ExtendedKey'))
- keys.insert(insertIndex, (keyValue, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey))
- keys.insert(insertIndex + 1, (keyValue, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey))
+ printKeys.insert(insertIndex, (text[i], "KeyDown | ExtendedKey"))
+ printKeys.insert(insertIndex + 1, (text[i], "KeyUp | ExtendedKey"))
+ keys.insert(
+ insertIndex,
+ (keyValue, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey),
+ )
+ keys.insert(
+ insertIndex + 1,
+ (keyValue, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey),
+ )
lastKeyValue = keyValue
else:
- printKeys.append((text[i], 'UnicodeChar'))
- keys.append((text[i], 'UnicodeChar'))
+ printKeys.append((text[i], "UnicodeChar"))
+ keys.append((text[i], "UnicodeChar"))
lastKeyValue = text[i]
if include:
insertIndex += 1
else:
hold = False
else:
- printKeys.append((text[i], 'UnicodeChar'))
- keys.append((text[i], 'UnicodeChar'))
+ printKeys.append((text[i], "UnicodeChar"))
+ keys.append((text[i], "UnicodeChar"))
lastKeyValue = text[i]
i += 1
if i >= length:
break
hotkeyInterval = 0.01
for i, key in enumerate(keys):
- if key[1] == 'UnicodeChar':
+ if key[1] == "UnicodeChar":
SendUnicodeChar(key[0], charMode)
time.sleep(interval)
else:
@@ -1297,10 +1544,15 @@ def SendKeys(text: str, interval: float = 0.01, waitTime: float = OPERATION_WAIT
time.sleep(interval)
else:
if key[1] & KeyboardEventFlag.KeyUp:
- if keys[i + 1][1] == 'UnicodeChar' or keys[i + 1][1] & KeyboardEventFlag.KeyUp == 0:
+ if (
+ keys[i + 1][1] == "UnicodeChar"
+ or keys[i + 1][1] & KeyboardEventFlag.KeyUp == 0
+ ):
time.sleep(interval)
else:
- time.sleep(hotkeyInterval) # must sleep for a while, otherwise combined keys may not be caught
+ time.sleep(
+ hotkeyInterval
+ ) # must sleep for a while, otherwise combined keys may not be caught
else: # KeyboardEventFlag.KeyDown
time.sleep(hotkeyInterval)
time.sleep(waitTime)
@@ -1315,7 +1567,9 @@ def SetThreadDpiAwarenessContext(dpiAwarenessContext: int):
# https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setthreaddpiawarenesscontext
# Windows 10 1607+
ctypes.windll.user32.SetThreadDpiAwarenessContext.restype = ctypes.c_void_p
- oldContext = ctypes.windll.user32.SetThreadDpiAwarenessContext(ctypes.c_void_p(dpiAwarenessContext))
+ oldContext = ctypes.windll.user32.SetThreadDpiAwarenessContext(
+ ctypes.c_void_p(dpiAwarenessContext)
+ )
return oldContext
except Exception:
pass
@@ -1366,25 +1620,27 @@ if not SetProcessDpiAwarenessContext(DpiAwarenessContext.PerMonitorAwareV2):
class tagPROCESSENTRY32(ctypes.Structure):
_fields_ = [
- ('dwSize', ctypes.wintypes.DWORD),
- ('cntUsage', ctypes.wintypes.DWORD),
- ('th32ProcessID', ctypes.wintypes.DWORD),
- ('th32DefaultHeapID', ctypes.POINTER(ctypes.wintypes.ULONG)),
- ('th32ModuleID', ctypes.wintypes.DWORD),
- ('cntThreads', ctypes.wintypes.DWORD),
- ('th32ParentProcessID', ctypes.wintypes.DWORD),
- ('pcPriClassBase', ctypes.wintypes.LONG),
- ('dwFlags', ctypes.wintypes.DWORD),
- ('szExeFile', ctypes.c_wchar * MAX_PATH)
+ ("dwSize", ctypes.wintypes.DWORD),
+ ("cntUsage", ctypes.wintypes.DWORD),
+ ("th32ProcessID", ctypes.wintypes.DWORD),
+ ("th32DefaultHeapID", ctypes.POINTER(ctypes.wintypes.ULONG)),
+ ("th32ModuleID", ctypes.wintypes.DWORD),
+ ("cntThreads", ctypes.wintypes.DWORD),
+ ("th32ParentProcessID", ctypes.wintypes.DWORD),
+ ("pcPriClassBase", ctypes.wintypes.LONG),
+ ("dwFlags", ctypes.wintypes.DWORD),
+ ("szExeFile", ctypes.c_wchar * MAX_PATH),
]
class ProcessInfo:
- def __init__(self, exeName: str, pid: int, ppid: int = -1, exePath: str = '', cmdLine: str = ''):
+ def __init__(
+ self, exeName: str, pid: int, ppid: int = -1, exePath: str = "", cmdLine: str = ""
+ ):
self.pid = pid
- self.ppid = ppid # ppid is -1 if failed
+ self.ppid = ppid # ppid is -1 if failed
self.exeName = exeName # such as explorer.exe
- self.is64Bit = None # True if is 64 bit, False if 32 bit, None if failed
+ self.is64Bit = None # True if is 64 bit, False if 32 bit, None if failed
self.exePath = exePath # such as C:\Windows\explorer.exe, empty if failed
self.cmdLine = cmdLine # empty if failed
@@ -1392,17 +1648,20 @@ class ProcessInfo:
return f"ProcessInfo(pid={self.pid}, ppid={self.ppid}, exeName='{self.exeName}', is64Bit={self.is64Bit}, exePath='{self.exePath}', cmdLine='{self.cmdLine}'"
def __repr__(self):
- return '<{} object at 0x{:08X} {}>'.format(self.__class__.__name__, id(self),
- ', '.join(f'{k}={v}' for k, v in self.__dict__.items()))
+ return "<{} object at 0x{:08X} {}>".format(
+ self.__class__.__name__,
+ id(self),
+ ", ".join(f"{k}={v}" for k, v in self.__dict__.items()),
+ )
def GetProcesses(detailedInfo: bool = True) -> list[ProcessInfo]:
- '''
+ """
Enum process by Win32 API.
detailedInfo: bool, only get pid and exeName if False.
You should run python as administrator to call this function.
Can not get some system processes' info.
- '''
+ """
if detailedInfo:
try:
IsWow64Process = ctypes.windll.kernel32.IsWow64Process
@@ -1412,18 +1671,22 @@ def GetProcesses(detailedInfo: bool = True) -> list[ProcessInfo]:
processEntry32 = tagPROCESSENTRY32()
processEntry32.dwSize = ctypes.sizeof(processEntry32)
processList = []
- processNext = ctypes.windll.kernel32.Process32FirstW(ctypes.c_void_p(hSnapshot), ctypes.byref(processEntry32))
+ processNext = ctypes.windll.kernel32.Process32FirstW(
+ ctypes.c_void_p(hSnapshot), ctypes.byref(processEntry32)
+ )
cPointerSize = ctypes.sizeof(ctypes.c_void_p)
while processNext:
pinfo = ProcessInfo(processEntry32.szExeFile, processEntry32.th32ProcessID)
if detailedInfo:
- #PROCESS_QUERY_INFORMATION=0x0400, PROCESS_QUERY_LIMITED_INFORMATION=0x1000, PROCESS_VM_READ=0x0010
+ # PROCESS_QUERY_INFORMATION=0x0400, PROCESS_QUERY_LIMITED_INFORMATION=0x1000, PROCESS_VM_READ=0x0010
queryType = (0x1000 if IsNT6orHigher else 0x0400) | 0x0010
hProcess = ctypes.windll.kernel32.OpenProcess(queryType, 0, pinfo.pid)
if hProcess:
hProcess = ctypes.c_void_p(hProcess)
processBasicInformationAddr = 0
- processBasicInformation = (ctypes.c_size_t * 6)()#sizeof PROCESS_BASIC_INFORMATION
+ processBasicInformation = (
+ ctypes.c_size_t * 6
+ )() # sizeof PROCESS_BASIC_INFORMATION
outLen = ctypes.c_ulong(0)
ctypes.windll.ntdll.NtQueryInformationProcess.restype = ctypes.c_uint32
if IsWow64Process:
@@ -1433,56 +1696,98 @@ def GetProcesses(detailedInfo: bool = True) -> list[ProcessInfo]:
else:
pinfo.is64Bit = False
ntStatus = ctypes.windll.ntdll.NtQueryInformationProcess(
- hProcess, processBasicInformationAddr, processBasicInformation, ctypes.sizeof(processBasicInformation), ctypes.byref(outLen))
- if ntStatus == 0: #STATUS_SUCCESS=0
+ hProcess,
+ processBasicInformationAddr,
+ processBasicInformation,
+ ctypes.sizeof(processBasicInformation),
+ ctypes.byref(outLen),
+ )
+ if ntStatus == 0: # STATUS_SUCCESS=0
pinfo.ppid = processBasicInformation[5]
pebBaseAddress = processBasicInformation[1]
if pebBaseAddress:
- pebSize = 712 if CurrentProcessIs64Bit else 472 #sizeof PEB
+ pebSize = 712 if CurrentProcessIs64Bit else 472 # sizeof PEB
peb = (ctypes.c_size_t * (pebSize // cPointerSize))()
outLen.value = 0
- isok = ctypes.windll.kernel32.ReadProcessMemory(hProcess, ctypes.c_void_p(pebBaseAddress), peb, pebSize, ctypes.byref(outLen))
+ isok = ctypes.windll.kernel32.ReadProcessMemory(
+ hProcess,
+ ctypes.c_void_p(pebBaseAddress),
+ peb,
+ pebSize,
+ ctypes.byref(outLen),
+ )
if isok:
processParametersAddr = ctypes.c_void_p(peb[4])
- uppSize = 128 if CurrentProcessIs64Bit else 72 #sizeof RTL_USER_PROCESS_PARAMETERS
+ uppSize = (
+ 128 if CurrentProcessIs64Bit else 72
+ ) # sizeof RTL_USER_PROCESS_PARAMETERS
upp = (ctypes.c_ubyte * uppSize)()
outLen.value = 0
- isok = ctypes.windll.kernel32.ReadProcessMemory(hProcess, processParametersAddr, upp, uppSize, ctypes.byref(outLen))
+ isok = ctypes.windll.kernel32.ReadProcessMemory(
+ hProcess, processParametersAddr, upp, uppSize, ctypes.byref(outLen)
+ )
if isok:
offset = 16 + 10 * cPointerSize
- imgPathSize, imgPathSizeMax, imgPathAddr, cmdLineSize, cmdLineSizeMax, cmdLineAddr = struct.unpack('@HHNHHN', bytes(upp[offset:]))
+ (
+ imgPathSize,
+ imgPathSizeMax,
+ imgPathAddr,
+ cmdLineSize,
+ cmdLineSizeMax,
+ cmdLineAddr,
+ ) = struct.unpack("@HHNHHN", bytes(upp[offset:]))
exePath = (ctypes.c_wchar * imgPathSizeMax)()
outLen.value = 0
- isok = ctypes.windll.kernel32.ReadProcessMemory(hProcess, ctypes.c_void_p(imgPathAddr), exePath, ctypes.sizeof(exePath), ctypes.byref(outLen))
+ isok = ctypes.windll.kernel32.ReadProcessMemory(
+ hProcess,
+ ctypes.c_void_p(imgPathAddr),
+ exePath,
+ ctypes.sizeof(exePath),
+ ctypes.byref(outLen),
+ )
if isok:
pinfo.exePath = exePath.value
cmdLine = (ctypes.c_wchar * cmdLineSizeMax)()
outLen.value = 0
- isok = ctypes.windll.kernel32.ReadProcessMemory(hProcess, ctypes.c_void_p(cmdLineAddr), cmdLine, ctypes.sizeof(cmdLine), ctypes.byref(outLen))
+ isok = ctypes.windll.kernel32.ReadProcessMemory(
+ hProcess,
+ ctypes.c_void_p(cmdLineAddr),
+ cmdLine,
+ ctypes.sizeof(cmdLine),
+ ctypes.byref(outLen),
+ )
if isok:
pinfo.cmdLine = cmdLine.value
if not pinfo.exePath:
exePath = (ctypes.c_wchar * MAX_PATH)()
if IsNT6orHigher:
- win32PathFormat = 0 #nativeSystemPathFormat = 1
+ win32PathFormat = 0 # nativeSystemPathFormat = 1
outLen.value = len(exePath)
- isok = ctypes.windll.kernel32.QueryFullProcessImageNameW(hProcess, win32PathFormat, exePath, ctypes.byref(outLen))
+ isok = ctypes.windll.kernel32.QueryFullProcessImageNameW(
+ hProcess, win32PathFormat, exePath, ctypes.byref(outLen)
+ )
else:
hModule = None
try:
- #strlen =
- ctypes.windll.psapi.GetModuleFileNameExW(hProcess, hModule, exePath, len(exePath))
+ # strlen =
+ ctypes.windll.psapi.GetModuleFileNameExW(
+ hProcess, hModule, exePath, len(exePath)
+ )
except:
- #strlen =
- ctypes.windll.kernel32.GetModuleFileNameExW(hProcess, hModule, exePath, len(exePath))
- #exePath is nativeSystemPathFormat
- #strlen = ctypes.windll.psapi.GetProcessImageFileNameW(hProcess, exePath, len(exePath))
- #if exePath.value:
- #strlen = ctypes.windll.kernel32.QueryDosDeviceW(ctypes.c_wchar_p(exePath.value), exePath, len(exePath))
+ # strlen =
+ ctypes.windll.kernel32.GetModuleFileNameExW(
+ hProcess, hModule, exePath, len(exePath)
+ )
+ # exePath is nativeSystemPathFormat
+ # strlen = ctypes.windll.psapi.GetProcessImageFileNameW(hProcess, exePath, len(exePath))
+ # if exePath.value:
+ # strlen = ctypes.windll.kernel32.QueryDosDeviceW(ctypes.c_wchar_p(exePath.value), exePath, len(exePath))
pinfo.exePath = exePath.value
ctypes.windll.kernel32.CloseHandle(hProcess)
processList.append(pinfo)
- processNext = ctypes.windll.kernel32.Process32NextW(ctypes.c_void_p(hSnapshot), ctypes.byref(processEntry32))
+ processNext = ctypes.windll.kernel32.Process32NextW(
+ ctypes.c_void_p(hSnapshot), ctypes.byref(processEntry32)
+ )
ctypes.windll.kernel32.CloseHandle(ctypes.c_void_p(hSnapshot))
return processList
@@ -1498,10 +1803,10 @@ def TerminateProcess(pid: int) -> bool:
def TerminateProcessByName(exeName: str, killAll: bool = True) -> int:
- '''
+ """
exeName: str, such as notepad.exe
return int, process count that was terminated
- '''
+ """
count = 0
for pinfo in GetProcesses(detailedInfo=False):
if pinfo.exeName == exeName:
@@ -1512,8 +1817,6 @@ def TerminateProcessByName(exeName: str, killAll: bool = True) -> int:
return count
-
-
_ClipboardLock = threading.Lock()
@@ -1527,11 +1830,11 @@ def _OpenClipboard(value):
def GetClipboardFormats() -> dict[int, str]:
- '''
+ """
Get clipboard formats that system clipboard has currently.
Return Dict[int, str].
The key is a int value in class `ClipboardFormat` or othes values that apps registered by ctypes.windll.user32.RegisterClipboardFormatW
- '''
+ """
formats = {}
with _ClipboardLock:
if _OpenClipboard(0):
@@ -1545,7 +1848,9 @@ def GetClipboardFormats() -> dict[int, str]:
ctypes.windll.user32.GetClipboardFormatNameW(formatType, values, len(values))
formatName = values.value
if not formatName:
- formatName = _GetDictKeyName(ClipboardFormat.__dict__, formatType, lambda key: key.startswith('CF_'))
+ formatName = _GetDictKeyName(
+ ClipboardFormat.__dict__, formatType, lambda key: key.startswith("CF_")
+ )
formats[formatType] = formatName
ctypes.windll.user32.CloseClipboard()
return formats
@@ -1555,15 +1860,17 @@ def GetClipboardText() -> str:
with _ClipboardLock:
if _OpenClipboard(0):
if ctypes.windll.user32.IsClipboardFormatAvailable(ClipboardFormat.CF_UNICODETEXT):
- hClipboardData = ctypes.windll.user32.GetClipboardData(ClipboardFormat.CF_UNICODETEXT)
+ hClipboardData = ctypes.windll.user32.GetClipboardData(
+ ClipboardFormat.CF_UNICODETEXT
+ )
hText = ctypes.windll.kernel32.GlobalLock(ctypes.c_void_p(hClipboardData))
text = ctypes.c_wchar_p(hText).value
ctypes.windll.kernel32.GlobalUnlock(ctypes.c_void_p(hClipboardData))
ctypes.windll.user32.CloseClipboard()
if text is None:
- return ''
+ return ""
return text
- return ''
+ return ""
def SetClipboardText(text: str) -> bool:
@@ -1577,11 +1884,17 @@ def SetClipboardText(text: str) -> bool:
textByteLen = (len(text) + 1) * 2
hClipboardData = ctypes.windll.kernel32.GlobalAlloc(0x2, textByteLen) # GMEM_MOVEABLE
hDestText = ctypes.windll.kernel32.GlobalLock(ctypes.c_void_p(hClipboardData))
- ctypes.cdll.msvcrt.wcsncpy(ctypes.c_wchar_p(hDestText), ctypes.c_wchar_p(text), ctypes.c_size_t(textByteLen // 2))
+ ctypes.cdll.msvcrt.wcsncpy(
+ ctypes.c_wchar_p(hDestText),
+ ctypes.c_wchar_p(text),
+ ctypes.c_size_t(textByteLen // 2),
+ )
ctypes.windll.kernel32.GlobalUnlock(ctypes.c_void_p(hClipboardData))
# system owns hClipboardData after calling SetClipboardData,
# application can not write to or free the data once ownership has been transferred to the system
- if ctypes.windll.user32.SetClipboardData(ctypes.c_uint(ClipboardFormat.CF_UNICODETEXT), ctypes.c_void_p(hClipboardData)):
+ if ctypes.windll.user32.SetClipboardData(
+ ctypes.c_uint(ClipboardFormat.CF_UNICODETEXT), ctypes.c_void_p(hClipboardData)
+ ):
ret = True
else:
ctypes.windll.kernel32.GlobalFree(ctypes.c_void_p(hClipboardData))
@@ -1605,9 +1918,9 @@ def GetClipboardHtml() -> str:
ctypes.windll.kernel32.GlobalUnlock(ctypes.c_void_p(hClipboardData))
ctypes.windll.user32.CloseClipboard()
if v is None:
- return ''
- return v.decode('utf-8')
- return ''
+ return ""
+ return v.decode("utf-8")
+ return ""
def SetClipboardHtml(htmlText: str) -> bool:
@@ -1616,28 +1929,38 @@ def SetClipboardHtml(htmlText: str) -> bool:
Return bool, True if succeed otherwise False.
Refer: https://docs.microsoft.com/en-us/troubleshoot/cpp/add-html-code-clipboard
"""
- u8Html = htmlText.encode('utf-8')
- formatBytes = b'Version:0.9\r\nStartHTML:00000000\r\nEndHTML:00000000\r\nStartFragment:00000000\r\nEndFragment:00000000\r\n<html>\r\n<body>\r\n<!--StartFragment-->{}<!--EndFragment-->\r\n</body>\r\n</html>'
- startHtml = formatBytes.find(b'<html>')
+ u8Html = htmlText.encode("utf-8")
+ formatBytes = b"Version:0.9\r\nStartHTML:00000000\r\nEndHTML:00000000\r\nStartFragment:00000000\r\nEndFragment:00000000\r\n<html>\r\n<body>\r\n<!--StartFragment-->{}<!--EndFragment-->\r\n</body>\r\n</html>"
+ startHtml = formatBytes.find(b"<html>")
endHtml = len(formatBytes) + len(u8Html) - 2
- startFragment = formatBytes.find(b'{}')
- endFragment = formatBytes.find(b'<!--EndFragment-->') + len(u8Html) - 2
- formatBytes = formatBytes.replace(b'StartHTML:00000000', f'StartHTML:{startHtml:08}'.encode())
- formatBytes = formatBytes.replace(b'EndHTML:00000000', f'EndHTML:{endHtml:08}'.encode())
- formatBytes = formatBytes.replace(b'StartFragment:00000000', f'StartFragment:{startFragment:08}'.encode())
- formatBytes = formatBytes.replace(b'EndFragment:00000000', f'EndFragment:{endFragment:08}'.encode())
- u8Result = formatBytes.replace(b'{}', u8Html)
+ startFragment = formatBytes.find(b"{}")
+ endFragment = formatBytes.find(b"<!--EndFragment-->") + len(u8Html) - 2
+ formatBytes = formatBytes.replace(b"StartHTML:00000000", f"StartHTML:{startHtml:08}".encode())
+ formatBytes = formatBytes.replace(b"EndHTML:00000000", f"EndHTML:{endHtml:08}".encode())
+ formatBytes = formatBytes.replace(
+ b"StartFragment:00000000", f"StartFragment:{startFragment:08}".encode()
+ )
+ formatBytes = formatBytes.replace(
+ b"EndFragment:00000000", f"EndFragment:{endFragment:08}".encode()
+ )
+ u8Result = formatBytes.replace(b"{}", u8Html)
ret = False
with _ClipboardLock:
if _OpenClipboard(0):
ctypes.windll.user32.EmptyClipboard()
- hClipboardData = ctypes.windll.kernel32.GlobalAlloc(0x2002, len(u8Result) + 4) # GMEM_MOVEABLE |GMEM_DDESHARE
+ hClipboardData = ctypes.windll.kernel32.GlobalAlloc(
+ 0x2002, len(u8Result) + 4
+ ) # GMEM_MOVEABLE |GMEM_DDESHARE
hDestText = ctypes.windll.kernel32.GlobalLock(ctypes.c_void_p(hClipboardData))
- ctypes.cdll.msvcrt.strncpy(ctypes.c_char_p(hDestText), ctypes.c_char_p(u8Result), len(u8Result))
+ ctypes.cdll.msvcrt.strncpy(
+ ctypes.c_char_p(hDestText), ctypes.c_char_p(u8Result), len(u8Result)
+ )
ctypes.windll.kernel32.GlobalUnlock(ctypes.c_void_p(hClipboardData))
# system owns hClipboardData after calling SetClipboardData,
# application can not write to or free the data once ownership has been transferred to the system
- if ctypes.windll.user32.SetClipboardData(ctypes.c_uint(ClipboardFormat.CF_HTML), ctypes.c_void_p(hClipboardData)):
+ if ctypes.windll.user32.SetClipboardData(
+ ctypes.c_uint(ClipboardFormat.CF_HTML), ctypes.c_void_p(hClipboardData)
+ ):
ret = True
else:
ctypes.windll.kernel32.GlobalFree(ctypes.c_void_p(hClipboardData))
@@ -1645,7 +1968,6 @@ def SetClipboardHtml(htmlText: str) -> bool:
return ret
-
def Input(prompt: str, consoleColor: int = ConsoleColor.Default) -> str:
print(prompt, end="")
return input()
@@ -1654,6 +1976,8 @@ def Input(prompt: str, consoleColor: int = ConsoleColor.Default) -> str:
def InputColorfully(prompt: str, consoleColor: int = ConsoleColor.Default) -> str:
print(prompt, end="")
return input()
+
+
class Rect:
"""
class Rect, like `ctypes.wintypes.RECT`.
@@ -1683,8 +2007,13 @@ class Rect:
def contains(self, x: int, y: int) -> bool:
return self.left <= x < self.right and self.top <= y < self.bottom
- def intersect(self, rect: 'Rect') -> 'Rect':
- left, top, right, bottom = max(self.left, rect.left), max(self.top, rect.top), min(self.right, rect.right), min(self.bottom, rect.bottom)
+ def intersect(self, rect: "Rect") -> "Rect":
+ left, top, right, bottom = (
+ max(self.left, rect.left),
+ max(self.top, rect.top),
+ min(self.right, rect.right),
+ min(self.bottom, rect.bottom),
+ )
return Rect(left, top, right, bottom)
def offset(self, x: int, y: int) -> None:
@@ -1694,13 +2023,20 @@ class Rect:
self.bottom += y
def __eq__(self, rect):
- return self.left == rect.left and self.top == rect.top and self.right == rect.right and self.bottom == rect.bottom
+ return (
+ self.left == rect.left
+ and self.top == rect.top
+ and self.right == rect.right
+ and self.bottom == rect.bottom
+ )
def __str__(self) -> str:
- return f'({self.left},{self.top},{self.right},{self.bottom})[{self.width()}x{self.height()}]'
+ return (
+ f"({self.left},{self.top},{self.right},{self.bottom})[{self.width()}x{self.height()}]"
+ )
def __repr__(self) -> str:
- return f'{self.__class__.__name__}({self.left},{self.top},{self.right},{self.bottom})[{self.width()}x{self.height()}]'
+ return f"{self.__class__.__name__}({self.left},{self.top},{self.right},{self.bottom})[{self.width()}x{self.height()}]"
class ClipboardFormat:
@@ -1728,10 +2064,11 @@ class ClipboardFormat:
# TODO: Failed to parse structure ACCESSTIMEOUT
class ExtendedProperty(ctypes.Structure):
_fields_ = [
- ('PropertyName', ctypes.c_wchar_p),
- ('PropertyValue', ctypes.c_wchar_p),
+ ("PropertyName", ctypes.c_wchar_p),
+ ("PropertyValue", ctypes.c_wchar_p),
]
+
# TODO: Failed to parse structure FILTERKEYS
# TODO: Failed to parse structure HIGHCONTRASTA
# TODO: Failed to parse structure HIGHCONTRASTW
@@ -1745,218 +2082,244 @@ class ExtendedProperty(ctypes.Structure):
# TODO: Failed to parse structure TOGGLEKEYS
class UIAutomationEventInfo(ctypes.Structure):
_fields_ = [
- ('guid', ctypes.c_void_p),
- ('pProgrammaticName', ctypes.wintypes.LPCWSTR),
+ ("guid", ctypes.c_void_p),
+ ("pProgrammaticName", ctypes.wintypes.LPCWSTR),
]
+
class UIAutomationMethodInfo(ctypes.Structure):
_fields_ = [
- ('pProgrammaticName', ctypes.wintypes.LPCWSTR),
- ('doSetFocus', ctypes.wintypes.BOOL),
- ('cInParameters', ctypes.wintypes.UINT),
- ('cOutParameters', ctypes.wintypes.UINT),
- ('pParameterTypes', ctypes.c_void_p),
- ('pParameterNames', ctypes.c_void_p),
+ ("pProgrammaticName", ctypes.wintypes.LPCWSTR),
+ ("doSetFocus", ctypes.wintypes.BOOL),
+ ("cInParameters", ctypes.wintypes.UINT),
+ ("cOutParameters", ctypes.wintypes.UINT),
+ ("pParameterTypes", ctypes.c_void_p),
+ ("pParameterNames", ctypes.c_void_p),
]
+
class UIAutomationParameter(ctypes.Structure):
_fields_ = [
- ('type', ctypes.c_void_p),
- ('pData', ctypes.c_void_p),
+ ("type", ctypes.c_void_p),
+ ("pData", ctypes.c_void_p),
]
+
class UIAutomationPatternInfo(ctypes.Structure):
_fields_ = [
- ('guid', ctypes.c_void_p),
- ('pProgrammaticName', ctypes.wintypes.LPCWSTR),
- ('providerInterfaceId', ctypes.c_void_p),
- ('clientInterfaceId', ctypes.c_void_p),
- ('cProperties', ctypes.wintypes.UINT),
- ('UIAutomationPropertyInfo', ctypes.c_void_p),
- ('cMethods', ctypes.wintypes.UINT),
- ('UIAutomationMethodInfo', ctypes.c_void_p),
- ('cEvents', ctypes.wintypes.UINT),
- ('UIAutomationEventInfo', ctypes.c_void_p),
- ('pPatternHandler', ctypes.c_void_p),
+ ("guid", ctypes.c_void_p),
+ ("pProgrammaticName", ctypes.wintypes.LPCWSTR),
+ ("providerInterfaceId", ctypes.c_void_p),
+ ("clientInterfaceId", ctypes.c_void_p),
+ ("cProperties", ctypes.wintypes.UINT),
+ ("UIAutomationPropertyInfo", ctypes.c_void_p),
+ ("cMethods", ctypes.wintypes.UINT),
+ ("UIAutomationMethodInfo", ctypes.c_void_p),
+ ("cEvents", ctypes.wintypes.UINT),
+ ("UIAutomationEventInfo", ctypes.c_void_p),
+ ("pPatternHandler", ctypes.c_void_p),
]
+
class UIAutomationPropertyInfo(ctypes.Structure):
_fields_ = [
- ('guid', ctypes.c_void_p),
- ('pProgrammaticName', ctypes.wintypes.LPCWSTR),
- ('type', ctypes.c_void_p),
+ ("guid", ctypes.c_void_p),
+ ("pProgrammaticName", ctypes.wintypes.LPCWSTR),
+ ("type", ctypes.c_void_p),
]
+
class UiaAndOrCondition(ctypes.Structure):
_fields_ = [
- ('ConditionType', ctypes.c_void_p),
- ('ppConditions', ctypes.c_void_p),
- ('UiaCondition', ctypes.c_void_p),
- ('cConditions', ctypes.c_int),
+ ("ConditionType", ctypes.c_void_p),
+ ("ppConditions", ctypes.c_void_p),
+ ("UiaCondition", ctypes.c_void_p),
+ ("cConditions", ctypes.c_int),
]
class UiaAsyncContentLoadedEventArgs(ctypes.Structure):
_fields_ = [
- ('Type', ctypes.c_void_p),
- ('EventId', ctypes.c_int),
- ('AsyncContentLoadedState', ctypes.c_void_p),
- ('PercentComplete', ctypes.c_double),
+ ("Type", ctypes.c_void_p),
+ ("EventId", ctypes.c_int),
+ ("AsyncContentLoadedState", ctypes.c_void_p),
+ ("PercentComplete", ctypes.c_double),
]
+
class UiaCacheRequest(ctypes.Structure):
_fields_ = [
- ('UiaCondition', ctypes.c_void_p),
- ('Scope', ctypes.c_int),
- ('pProperties', ctypes.c_void_p),
- ('cProperties', ctypes.c_int),
- ('pPatterns', ctypes.c_void_p),
- ('cPatterns', ctypes.c_int),
- ('automationElementMode', ctypes.c_int),
+ ("UiaCondition", ctypes.c_void_p),
+ ("Scope", ctypes.c_int),
+ ("pProperties", ctypes.c_void_p),
+ ("cProperties", ctypes.c_int),
+ ("pPatterns", ctypes.c_void_p),
+ ("cPatterns", ctypes.c_int),
+ ("automationElementMode", ctypes.c_int),
]
+
class UiaChangeInfo(ctypes.Structure):
_fields_ = [
- ('uiaId', ctypes.c_int),
- ('payload', ctypes.c_void_p),
- ('extraInfo', ctypes.c_void_p),
+ ("uiaId", ctypes.c_int),
+ ("payload", ctypes.c_void_p),
+ ("extraInfo", ctypes.c_void_p),
]
+
class UiaCondition(ctypes.Structure):
_fields_ = [
- ('ConditionType', ctypes.c_void_p),
+ ("ConditionType", ctypes.c_void_p),
]
+
class UiaEventArgs(ctypes.Structure):
_fields_ = [
- ('Type', ctypes.c_void_p),
- ('EventId', ctypes.c_int),
+ ("Type", ctypes.c_void_p),
+ ("EventId", ctypes.c_int),
]
+
class UiaFindParams(ctypes.Structure):
_fields_ = [
- ('MaxDepth', ctypes.c_int),
- ('FindFirst', ctypes.wintypes.BOOL),
- ('ExcludeRoot', ctypes.wintypes.BOOL),
- ('UiaCondition', ctypes.c_void_p),
+ ("MaxDepth", ctypes.c_int),
+ ("FindFirst", ctypes.wintypes.BOOL),
+ ("ExcludeRoot", ctypes.wintypes.BOOL),
+ ("UiaCondition", ctypes.c_void_p),
]
+
class UiaNotCondition(ctypes.Structure):
_fields_ = [
- ('ConditionType', ctypes.c_void_p),
- ('UiaCondition', ctypes.c_void_p),
+ ("ConditionType", ctypes.c_void_p),
+ ("UiaCondition", ctypes.c_void_p),
]
+
class UiaPoint(ctypes.Structure):
_fields_ = [
- ('x', ctypes.c_double),
- ('y', ctypes.c_double),
+ ("x", ctypes.c_double),
+ ("y", ctypes.c_double),
]
+
class UiaPropertyChangedEventArgs(ctypes.Structure):
_fields_ = [
- ('Type', ctypes.c_void_p),
- ('EventId', ctypes.c_int),
- ('PropertyId', ctypes.c_int),
- ('OldValue', ctypes.c_void_p),
- ('NewValue', ctypes.c_void_p),
+ ("Type", ctypes.c_void_p),
+ ("EventId", ctypes.c_int),
+ ("PropertyId", ctypes.c_int),
+ ("OldValue", ctypes.c_void_p),
+ ("NewValue", ctypes.c_void_p),
]
+
class UiaPropertyCondition(ctypes.Structure):
_fields_ = [
- ('ConditionType', ctypes.c_void_p),
- ('PropertyId', ctypes.c_int),
- ('Value', ctypes.c_void_p),
- ('Flags', ctypes.c_void_p),
+ ("ConditionType", ctypes.c_void_p),
+ ("PropertyId", ctypes.c_int),
+ ("Value", ctypes.c_void_p),
+ ("Flags", ctypes.c_void_p),
]
+
class UiaRect(ctypes.Structure):
_fields_ = [
- ('left', ctypes.c_double),
- ('top', ctypes.c_double),
- ('width', ctypes.c_double),
- ('height', ctypes.c_double),
+ ("left", ctypes.c_double),
+ ("top", ctypes.c_double),
+ ("width", ctypes.c_double),
+ ("height", ctypes.c_double),
]
+
class UiaStructureChangedEventArgs(ctypes.Structure):
_fields_ = [
- ('Type', ctypes.c_void_p),
- ('EventId', ctypes.c_int),
- ('StructureChangeType', ctypes.c_void_p),
- ('pRuntimeId', ctypes.c_void_p),
- ('cRuntimeIdLen', ctypes.c_int),
+ ("Type", ctypes.c_void_p),
+ ("EventId", ctypes.c_int),
+ ("StructureChangeType", ctypes.c_void_p),
+ ("pRuntimeId", ctypes.c_void_p),
+ ("cRuntimeIdLen", ctypes.c_int),
]
+
class UiaWindowClosedEventArgs(ctypes.Structure):
_fields_ = [
- ('Type', ctypes.c_void_p),
- ('EventId', ctypes.c_int),
- ('pRuntimeId', ctypes.c_void_p),
- ('cRuntimeIdLen', ctypes.c_int),
+ ("Type", ctypes.c_void_p),
+ ("EventId", ctypes.c_int),
+ ("pRuntimeId", ctypes.c_void_p),
+ ("cRuntimeIdLen", ctypes.c_int),
]
+
class ExtendedProperty(ctypes.Structure):
_fields_ = [
- ('PropertyName', ctypes.c_wchar_p),
- ('PropertyValue', ctypes.c_wchar_p),
+ ("PropertyName", ctypes.c_wchar_p),
+ ("PropertyValue", ctypes.c_wchar_p),
]
+
class UIAutomationEventInfo(ctypes.Structure):
_fields_ = [
- ('guid', ctypes.c_void_p),
- ('pProgrammaticName', ctypes.wintypes.LPCWSTR),
+ ("guid", ctypes.c_void_p),
+ ("pProgrammaticName", ctypes.wintypes.LPCWSTR),
]
+
class UIAutomationMethodInfo(ctypes.Structure):
_fields_ = [
- ('pProgrammaticName', ctypes.wintypes.LPCWSTR),
- ('doSetFocus', ctypes.wintypes.BOOL),
- ('cInParameters', ctypes.wintypes.UINT),
- ('cOutParameters', ctypes.wintypes.UINT),
- ('pParameterTypes', ctypes.c_void_p),
- ('pParameterNames', ctypes.c_void_p),
+ ("pProgrammaticName", ctypes.wintypes.LPCWSTR),
+ ("doSetFocus", ctypes.wintypes.BOOL),
+ ("cInParameters", ctypes.wintypes.UINT),
+ ("cOutParameters", ctypes.wintypes.UINT),
+ ("pParameterTypes", ctypes.c_void_p),
+ ("pParameterNames", ctypes.c_void_p),
]
+
class UIAutomationParameter(ctypes.Structure):
_fields_ = [
- ('type', ctypes.c_void_p),
- ('pData', ctypes.c_void_p),
+ ("type", ctypes.c_void_p),
+ ("pData", ctypes.c_void_p),
]
+
class UIAutomationPatternInfo(ctypes.Structure):
_fields_ = [
- ('guid', ctypes.c_void_p),
- ('pProgrammaticName', ctypes.wintypes.LPCWSTR),
- ('providerInterfaceId', ctypes.c_void_p),
- ('clientInterfaceId', ctypes.c_void_p),
- ('cProperties', ctypes.wintypes.UINT),
- ('UIAutomationPropertyInfo', ctypes.c_void_p),
- ('cMethods', ctypes.wintypes.UINT),
- ('UIAutomationMethodInfo', ctypes.c_void_p),
- ('cEvents', ctypes.wintypes.UINT),
- ('UIAutomationEventInfo', ctypes.c_void_p),
- ('pPatternHandler', ctypes.c_void_p),
+ ("guid", ctypes.c_void_p),
+ ("pProgrammaticName", ctypes.wintypes.LPCWSTR),
+ ("providerInterfaceId", ctypes.c_void_p),
+ ("clientInterfaceId", ctypes.c_void_p),
+ ("cProperties", ctypes.wintypes.UINT),
+ ("UIAutomationPropertyInfo", ctypes.c_void_p),
+ ("cMethods", ctypes.wintypes.UINT),
+ ("UIAutomationMethodInfo", ctypes.c_void_p),
+ ("cEvents", ctypes.wintypes.UINT),
+ ("UIAutomationEventInfo", ctypes.c_void_p),
+ ("pPatternHandler", ctypes.c_void_p),
]
+
class UIAutomationPropertyInfo(ctypes.Structure):
_fields_ = [
- ('guid', ctypes.c_void_p),
- ('pProgrammaticName', ctypes.wintypes.LPCWSTR),
- ('type', ctypes.c_void_p),
+ ("guid", ctypes.c_void_p),
+ ("pProgrammaticName", ctypes.wintypes.LPCWSTR),
+ ("type", ctypes.c_void_p),
]
+
class UiaAndOrCondition(ctypes.Structure):
_fields_ = [
- ('ConditionType', ctypes.c_void_p),
- ('ppConditions', ctypes.c_void_p),
- ('UiaCondition', ctypes.c_void_p),
- ('cConditions', ctypes.c_int),
+ ("ConditionType", ctypes.c_void_p),
+ ("ppConditions", ctypes.c_void_p),
+ ("UiaCondition", ctypes.c_void_p),
+ ("cConditions", ctypes.c_int),
]
+
class CacheRequest:
"""
Wrapper for IUIAutomationCacheRequest.
"""
+
def __init__(self, cache_request=None):
if cache_request:
self.check_request = cache_request
@@ -2001,34 +2364,45 @@ class CacheRequest:
"""
self.check_request.AddPattern(patternId)
- def Clone(self) -> 'CacheRequest':
+ def Clone(self) -> "CacheRequest":
"""
Clones the cache request.
"""
cloned = self.check_request.Clone()
return CacheRequest(cloned)
+
def CreateCacheRequest() -> CacheRequest:
"""
Creates a new CacheRequest.
"""
return CacheRequest()
+
# Event Handling Implementations for core.py
+
def AddAutomationEventHandler(eventId: int, element, scope: int, cacheRequest, handler) -> None:
"""
Registers a method that handles Microsoft UI Automation events.
"""
- _AutomationClient.instance().IUIAutomation.AddAutomationEventHandler(eventId, element, scope, cacheRequest, handler)
+ _AutomationClient.instance().IUIAutomation.AddAutomationEventHandler(
+ eventId, element, scope, cacheRequest, handler
+ )
+
def RemoveAutomationEventHandler(eventId: int, element, handler) -> None:
"""
Removes the specified Microsoft UI Automation event handler.
"""
- _AutomationClient.instance().IUIAutomation.RemoveAutomationEventHandler(eventId, element, handler)
+ _AutomationClient.instance().IUIAutomation.RemoveAutomationEventHandler(
+ eventId, element, handler
+ )
-def AddPropertyChangedEventHandler(element, scope: int, cacheRequest, handler, propertyArray: list[int]) -> None:
+
+def AddPropertyChangedEventHandler(
+ element, scope: int, cacheRequest, handler, propertyArray: list[int]
+) -> None:
"""
Registers a method that handles UI Automation property-changed events.
"""
@@ -2040,7 +2414,10 @@ def AddPropertyChangedEventHandler(element, scope: int, cacheRequest, handler, p
# We might need to manually convert list to SAFEARRAY or rely on comtypes.
# For now, let's pass a tuple/list and see if comtypes marshals it.
- _AutomationClient.instance().IUIAutomation.AddPropertyChangedEventHandler(element, scope, cacheRequest, handler, propertyArray)
+ _AutomationClient.instance().IUIAutomation.AddPropertyChangedEventHandler(
+ element, scope, cacheRequest, handler, propertyArray
+ )
+
def RemovePropertyChangedEventHandler(element, handler) -> None:
"""
@@ -2048,11 +2425,15 @@ def RemovePropertyChangedEventHandler(element, handler) -> None:
"""
_AutomationClient.instance().IUIAutomation.RemovePropertyChangedEventHandler(element, handler)
+
def AddStructureChangedEventHandler(element, scope: int, cacheRequest, handler) -> None:
"""
Registers a method that handles UI Automation structure-changed events.
"""
- _AutomationClient.instance().IUIAutomation.AddStructureChangedEventHandler(element, scope, cacheRequest, handler)
+ _AutomationClient.instance().IUIAutomation.AddStructureChangedEventHandler(
+ element, scope, cacheRequest, handler
+ )
+
def RemoveStructureChangedEventHandler(element, handler) -> None:
"""
@@ -2060,18 +2441,21 @@ def RemoveStructureChangedEventHandler(element, handler) -> None:
"""
_AutomationClient.instance().IUIAutomation.RemoveStructureChangedEventHandler(element, handler)
+
def AddFocusChangedEventHandler(cacheRequest, handler) -> None:
"""
Registers a method that handles UI Automation focus-changed events.
"""
_AutomationClient.instance().IUIAutomation.AddFocusChangedEventHandler(cacheRequest, handler)
+
def RemoveFocusChangedEventHandler(handler) -> None:
"""
Removes the specified focus-changed event handler.
"""
_AutomationClient.instance().IUIAutomation.RemoveFocusChangedEventHandler(handler)
+
def RemoveAllEventHandlers() -> None:
"""
Removes all registered Microsoft UI Automation event handlers.
@@ -2081,6 +2465,7 @@ def RemoveAllEventHandlers() -> None:
# Condition creation helper functions
+
def CreateTrueCondition():
"""
Create a condition that is always true. This matches all elements.
diff --git a/windows_use/uia/enums.py b/windows_use/uia/enums.py
index 0676a56..c3d0af5 100644
--- a/windows_use/uia/enums.py
+++ b/windows_use/uia/enums.py
@@ -19,7 +19,7 @@ import time
from enum import IntEnum, IntFlag
from typing import Any
-METRO_WINDOW_CLASS_NAME = 'Windows.UI.Core.CoreWindow' # for Windows 8 and 8.1
+METRO_WINDOW_CLASS_NAME = "Windows.UI.Core.CoreWindow" # for Windows 8 and 8.1
SEARCH_INTERVAL = 0.5 # search control interval seconds
MAX_MOVE_SECOND = 1 # simulate mouse move or drag max seconds
TIME_OUT_SECOND = 10
@@ -36,11 +36,13 @@ ProcessTime = time.perf_counter # this returns nearly 0 when first call it if p
ProcessTime() # need to call it once if python version <= 3.6
TreeNode = Any
+
class ControlType(IntEnum):
"""
ControlType from IUIAutomation.
Refer https://docs.microsoft.com/en-us/windows/win32/winauto/uiauto-controltype-ids
"""
+
AppBarControl = 50040
ButtonControl = 50000
CalendarControl = 50001
@@ -85,47 +87,47 @@ class ControlType(IntEnum):
ControlTypeNames = {
- ControlType.AppBarControl: 'AppBarControl',
- ControlType.ButtonControl: 'ButtonControl',
- ControlType.CalendarControl: 'CalendarControl',
- ControlType.CheckBoxControl: 'CheckBoxControl',
- ControlType.ComboBoxControl: 'ComboBoxControl',
- ControlType.CustomControl: 'CustomControl',
- ControlType.DataGridControl: 'DataGridControl',
- ControlType.DataItemControl: 'DataItemControl',
- ControlType.DocumentControl: 'DocumentControl',
- ControlType.EditControl: 'EditControl',
- ControlType.GroupControl: 'GroupControl',
- ControlType.HeaderControl: 'HeaderControl',
- ControlType.HeaderItemControl: 'HeaderItemControl',
- ControlType.HyperlinkControl: 'HyperlinkControl',
- ControlType.ImageControl: 'ImageControl',
- ControlType.ListControl: 'ListControl',
- ControlType.ListItemControl: 'ListItemControl',
- ControlType.MenuBarControl: 'MenuBarControl',
- ControlType.MenuControl: 'MenuControl',
- ControlType.MenuItemControl: 'MenuItemControl',
- ControlType.PaneControl: 'PaneControl',
- ControlType.ProgressBarControl: 'ProgressBarControl',
- ControlType.RadioButtonControl: 'RadioButtonControl',
- ControlType.ScrollBarControl: 'ScrollBarControl',
- ControlType.SemanticZoomControl: 'SemanticZoomControl',
- ControlType.SeparatorControl: 'SeparatorControl',
- ControlType.SliderControl: 'SliderControl',
- ControlType.SpinnerControl: 'SpinnerControl',
- ControlType.SplitButtonControl: 'SplitButtonControl',
- ControlType.StatusBarControl: 'StatusBarControl',
- ControlType.TabControl: 'TabControl',
- ControlType.TabItemControl: 'TabItemControl',
- ControlType.TableControl: 'TableControl',
- ControlType.TextControl: 'TextControl',
- ControlType.ThumbControl: 'ThumbControl',
- ControlType.TitleBarControl: 'TitleBarControl',
- ControlType.ToolBarControl: 'ToolBarControl',
- ControlType.ToolTipControl: 'ToolTipControl',
- ControlType.TreeControl: 'TreeControl',
- ControlType.TreeItemControl: 'TreeItemControl',
- ControlType.WindowControl: 'WindowControl',
+ ControlType.AppBarControl: "AppBarControl",
+ ControlType.ButtonControl: "ButtonControl",
+ ControlType.CalendarControl: "CalendarControl",
+ ControlType.CheckBoxControl: "CheckBoxControl",
+ ControlType.ComboBoxControl: "ComboBoxControl",
+ ControlType.CustomControl: "CustomControl",
+ ControlType.DataGridControl: "DataGridControl",
+ ControlType.DataItemControl: "DataItemControl",
+ ControlType.DocumentControl: "DocumentControl",
+ ControlType.EditControl: "EditControl",
+ ControlType.GroupControl: "GroupControl",
+ ControlType.HeaderControl: "HeaderControl",
+ ControlType.HeaderItemControl: "HeaderItemControl",
+ ControlType.HyperlinkControl: "HyperlinkControl",
+ ControlType.ImageControl: "ImageControl",
+ ControlType.ListControl: "ListControl",
+ ControlType.ListItemControl: "ListItemControl",
+ ControlType.MenuBarControl: "MenuBarControl",
+ ControlType.MenuControl: "MenuControl",
+ ControlType.MenuItemControl: "MenuItemControl",
+ ControlType.PaneControl: "PaneControl",
+ ControlType.ProgressBarControl: "ProgressBarControl",
+ ControlType.RadioButtonControl: "RadioButtonControl",
+ ControlType.ScrollBarControl: "ScrollBarControl",
+ ControlType.SemanticZoomControl: "SemanticZoomControl",
+ ControlType.SeparatorControl: "SeparatorControl",
+ ControlType.SliderControl: "SliderControl",
+ ControlType.SpinnerControl: "SpinnerControl",
+ ControlType.SplitButtonControl: "SplitButtonControl",
+ ControlType.StatusBarControl: "StatusBarControl",
+ ControlType.TabControl: "TabControl",
+ ControlType.TabItemControl: "TabItemControl",
+ ControlType.TableControl: "TableControl",
+ ControlType.TextControl: "TextControl",
+ ControlType.ThumbControl: "ThumbControl",
+ ControlType.TitleBarControl: "TitleBarControl",
+ ControlType.ToolBarControl: "ToolBarControl",
+ ControlType.ToolTipControl: "ToolTipControl",
+ ControlType.TreeControl: "TreeControl",
+ ControlType.TreeItemControl: "TreeItemControl",
+ ControlType.WindowControl: "WindowControl",
}
@@ -134,6 +136,7 @@ class PatternId(IntEnum):
PatternId from IUIAutomation.
Refer https://docs.microsoft.com/en-us/windows/win32/winauto/uiauto-controlpattern-ids
"""
+
AnnotationPattern = 10023
CustomNavigationPattern = 10033
DockPattern = 10011
@@ -172,41 +175,41 @@ class PatternId(IntEnum):
PatternIdNames = {
- PatternId.AnnotationPattern: 'AnnotationPattern',
- PatternId.CustomNavigationPattern: 'CustomNavigationPattern',
- PatternId.DockPattern: 'DockPattern',
- PatternId.DragPattern: 'DragPattern',
- PatternId.DropTargetPattern: 'DropTargetPattern',
- PatternId.ExpandCollapsePattern: 'ExpandCollapsePattern',
- PatternId.GridItemPattern: 'GridItemPattern',
- PatternId.GridPattern: 'GridPattern',
- PatternId.InvokePattern: 'InvokePattern',
- PatternId.ItemContainerPattern: 'ItemContainerPattern',
- PatternId.LegacyIAccessiblePattern: 'LegacyIAccessiblePattern',
- PatternId.MultipleViewPattern: 'MultipleViewPattern',
- PatternId.ObjectModelPattern: 'ObjectModelPattern',
- PatternId.RangeValuePattern: 'RangeValuePattern',
- PatternId.ScrollItemPattern: 'ScrollItemPattern',
- PatternId.ScrollPattern: 'ScrollPattern',
- PatternId.SelectionItemPattern: 'SelectionItemPattern',
- PatternId.SelectionPattern: 'SelectionPattern',
- PatternId.SpreadsheetItemPattern: 'SpreadsheetItemPattern',
- PatternId.SpreadsheetPattern: 'SpreadsheetPattern',
- PatternId.StylesPattern: 'StylesPattern',
- PatternId.SynchronizedInputPattern: 'SynchronizedInputPattern',
- PatternId.TableItemPattern: 'TableItemPattern',
- PatternId.TablePattern: 'TablePattern',
- PatternId.TextChildPattern: 'TextChildPattern',
- PatternId.TextEditPattern: 'TextEditPattern',
- PatternId.TextPattern: 'TextPattern',
- PatternId.TextPattern2: 'TextPattern2',
- PatternId.TogglePattern: 'TogglePattern',
- PatternId.TransformPattern: 'TransformPattern',
- PatternId.TransformPattern2: 'TransformPattern2',
- PatternId.ValuePattern: 'ValuePattern',
- PatternId.VirtualizedItemPattern: 'VirtualizedItemPattern',
- PatternId.WindowPattern: 'WindowPattern',
- PatternId.SelectionPattern2: 'SelectionPattern2',
+ PatternId.AnnotationPattern: "AnnotationPattern",
+ PatternId.CustomNavigationPattern: "CustomNavigationPattern",
+ PatternId.DockPattern: "DockPattern",
+ PatternId.DragPattern: "DragPattern",
+ PatternId.DropTargetPattern: "DropTargetPattern",
+ PatternId.ExpandCollapsePattern: "ExpandCollapsePattern",
+ PatternId.GridItemPattern: "GridItemPattern",
+ PatternId.GridPattern: "GridPattern",
+ PatternId.InvokePattern: "InvokePattern",
+ PatternId.ItemContainerPattern: "ItemContainerPattern",
+ PatternId.LegacyIAccessiblePattern: "LegacyIAccessiblePattern",
+ PatternId.MultipleViewPattern: "MultipleViewPattern",
+ PatternId.ObjectModelPattern: "ObjectModelPattern",
+ PatternId.RangeValuePattern: "RangeValuePattern",
+ PatternId.ScrollItemPattern: "ScrollItemPattern",
+ PatternId.ScrollPattern: "ScrollPattern",
+ PatternId.SelectionItemPattern: "SelectionItemPattern",
+ PatternId.SelectionPattern: "SelectionPattern",
+ PatternId.SpreadsheetItemPattern: "SpreadsheetItemPattern",
+ PatternId.SpreadsheetPattern: "SpreadsheetPattern",
+ PatternId.StylesPattern: "StylesPattern",
+ PatternId.SynchronizedInputPattern: "SynchronizedInputPattern",
+ PatternId.TableItemPattern: "TableItemPattern",
+ PatternId.TablePattern: "TablePattern",
+ PatternId.TextChildPattern: "TextChildPattern",
+ PatternId.TextEditPattern: "TextEditPattern",
+ PatternId.TextPattern: "TextPattern",
+ PatternId.TextPattern2: "TextPattern2",
+ PatternId.TogglePattern: "TogglePattern",
+ PatternId.TransformPattern: "TransformPattern",
+ PatternId.TransformPattern2: "TransformPattern2",
+ PatternId.ValuePattern: "ValuePattern",
+ PatternId.VirtualizedItemPattern: "VirtualizedItemPattern",
+ PatternId.WindowPattern: "WindowPattern",
+ PatternId.SelectionPattern2: "SelectionPattern2",
}
@@ -216,6 +219,7 @@ class PropertyId(IntEnum):
Refer https://docs.microsoft.com/en-us/windows/win32/winauto/uiauto-automation-element-propids
Refer https://docs.microsoft.com/en-us/windows/win32/winauto/uiauto-control-pattern-propids
"""
+
AcceleratorKeyProperty = 30006
AccessKeyProperty = 30007
AnnotationAnnotationTypeIdProperty = 30113
@@ -392,179 +396,179 @@ class PropertyId(IntEnum):
PropertyIdNames = {
- PropertyId.AcceleratorKeyProperty: 'AcceleratorKeyProperty',
- PropertyId.AccessKeyProperty: 'AccessKeyProperty',
- PropertyId.AnnotationAnnotationTypeIdProperty: 'AnnotationAnnotationTypeIdProperty',
- PropertyId.AnnotationAnnotationTypeNameProperty: 'AnnotationAnnotationTypeNameProperty',
- PropertyId.AnnotationAuthorProperty: 'AnnotationAuthorProperty',
- PropertyId.AnnotationDateTimeProperty: 'AnnotationDateTimeProperty',
- PropertyId.AnnotationObjectsProperty: 'AnnotationObjectsProperty',
- PropertyId.AnnotationTargetProperty: 'AnnotationTargetProperty',
- PropertyId.AnnotationTypesProperty: 'AnnotationTypesProperty',
- PropertyId.AriaPropertiesProperty: 'AriaPropertiesProperty',
- PropertyId.AriaRoleProperty: 'AriaRoleProperty',
- PropertyId.AutomationIdProperty: 'AutomationIdProperty',
- PropertyId.BoundingRectangleProperty: 'BoundingRectangleProperty',
- PropertyId.CenterPointProperty: 'CenterPointProperty',
- PropertyId.ClassNameProperty: 'ClassNameProperty',
- PropertyId.ClickablePointProperty: 'ClickablePointProperty',
- PropertyId.ControlTypeProperty: 'ControlTypeProperty',
- PropertyId.ControllerForProperty: 'ControllerForProperty',
- PropertyId.CultureProperty: 'CultureProperty',
- PropertyId.DescribedByProperty: 'DescribedByProperty',
- PropertyId.DockDockPositionProperty: 'DockDockPositionProperty',
- PropertyId.DragDropEffectProperty: 'DragDropEffectProperty',
- PropertyId.DragDropEffectsProperty: 'DragDropEffectsProperty',
- PropertyId.DragGrabbedItemsProperty: 'DragGrabbedItemsProperty',
- PropertyId.DragIsGrabbedProperty: 'DragIsGrabbedProperty',
- PropertyId.DropTargetDropTargetEffectProperty: 'DropTargetDropTargetEffectProperty',
- PropertyId.DropTargetDropTargetEffectsProperty: 'DropTargetDropTargetEffectsProperty',
- PropertyId.ExpandCollapseExpandCollapseStateProperty: 'ExpandCollapseExpandCollapseStateProperty',
- PropertyId.FillColorProperty: 'FillColorProperty',
- PropertyId.FillTypeProperty: 'FillTypeProperty',
- PropertyId.FlowsFromProperty: 'FlowsFromProperty',
- PropertyId.FlowsToProperty: 'FlowsToProperty',
- PropertyId.FrameworkIdProperty: 'FrameworkIdProperty',
- PropertyId.FullDescriptionProperty: 'FullDescriptionProperty',
- PropertyId.GridColumnCountProperty: 'GridColumnCountProperty',
- PropertyId.GridItemColumnProperty: 'GridItemColumnProperty',
- PropertyId.GridItemColumnSpanProperty: 'GridItemColumnSpanProperty',
- PropertyId.GridItemContainingGridProperty: 'GridItemContainingGridProperty',
- PropertyId.GridItemRowProperty: 'GridItemRowProperty',
- PropertyId.GridItemRowSpanProperty: 'GridItemRowSpanProperty',
- PropertyId.GridRowCountProperty: 'GridRowCountProperty',
- PropertyId.HasKeyboardFocusProperty: 'HasKeyboardFocusProperty',
- PropertyId.HelpTextProperty: 'HelpTextProperty',
- PropertyId.IsAnnotationPatternAvailableProperty: 'IsAnnotationPatternAvailableProperty',
- PropertyId.IsContentElementProperty: 'IsContentElementProperty',
- PropertyId.IsControlElementProperty: 'IsControlElementProperty',
- PropertyId.IsCustomNavigationPatternAvailableProperty: 'IsCustomNavigationPatternAvailableProperty',
- PropertyId.IsDataValidForFormProperty: 'IsDataValidForFormProperty',
- PropertyId.IsDockPatternAvailableProperty: 'IsDockPatternAvailableProperty',
- PropertyId.IsDragPatternAvailableProperty: 'IsDragPatternAvailableProperty',
- PropertyId.IsDropTargetPatternAvailableProperty: 'IsDropTargetPatternAvailableProperty',
- PropertyId.IsEnabledProperty: 'IsEnabledProperty',
- PropertyId.IsExpandCollapsePatternAvailableProperty: 'IsExpandCollapsePatternAvailableProperty',
- PropertyId.IsGridItemPatternAvailableProperty: 'IsGridItemPatternAvailableProperty',
- PropertyId.IsGridPatternAvailableProperty: 'IsGridPatternAvailableProperty',
- PropertyId.IsInvokePatternAvailableProperty: 'IsInvokePatternAvailableProperty',
- PropertyId.IsItemContainerPatternAvailableProperty: 'IsItemContainerPatternAvailableProperty',
- PropertyId.IsKeyboardFocusableProperty: 'IsKeyboardFocusableProperty',
- PropertyId.IsLegacyIAccessiblePatternAvailableProperty: 'IsLegacyIAccessiblePatternAvailableProperty',
- PropertyId.IsMultipleViewPatternAvailableProperty: 'IsMultipleViewPatternAvailableProperty',
- PropertyId.IsObjectModelPatternAvailableProperty: 'IsObjectModelPatternAvailableProperty',
- PropertyId.IsOffscreenProperty: 'IsOffscreenProperty',
- PropertyId.IsPasswordProperty: 'IsPasswordProperty',
- PropertyId.IsPeripheralProperty: 'IsPeripheralProperty',
- PropertyId.IsRangeValuePatternAvailableProperty: 'IsRangeValuePatternAvailableProperty',
- PropertyId.IsRequiredForFormProperty: 'IsRequiredForFormProperty',
- PropertyId.IsScrollItemPatternAvailableProperty: 'IsScrollItemPatternAvailableProperty',
- PropertyId.IsScrollPatternAvailableProperty: 'IsScrollPatternAvailableProperty',
- PropertyId.IsSelectionItemPatternAvailableProperty: 'IsSelectionItemPatternAvailableProperty',
- PropertyId.IsSelectionPattern2AvailableProperty: 'IsSelectionPattern2AvailableProperty',
- PropertyId.IsSelectionPatternAvailableProperty: 'IsSelectionPatternAvailableProperty',
- PropertyId.IsSpreadsheetItemPatternAvailableProperty: 'IsSpreadsheetItemPatternAvailableProperty',
- PropertyId.IsSpreadsheetPatternAvailableProperty: 'IsSpreadsheetPatternAvailableProperty',
- PropertyId.IsStylesPatternAvailableProperty: 'IsStylesPatternAvailableProperty',
- PropertyId.IsSynchronizedInputPatternAvailableProperty: 'IsSynchronizedInputPatternAvailableProperty',
- PropertyId.IsTableItemPatternAvailableProperty: 'IsTableItemPatternAvailableProperty',
- PropertyId.IsTablePatternAvailableProperty: 'IsTablePatternAvailableProperty',
- PropertyId.IsTextChildPatternAvailableProperty: 'IsTextChildPatternAvailableProperty',
- PropertyId.IsTextEditPatternAvailableProperty: 'IsTextEditPatternAvailableProperty',
- PropertyId.IsTextPattern2AvailableProperty: 'IsTextPattern2AvailableProperty',
- PropertyId.IsTextPatternAvailableProperty: 'IsTextPatternAvailableProperty',
- PropertyId.IsTogglePatternAvailableProperty: 'IsTogglePatternAvailableProperty',
- PropertyId.IsTransformPattern2AvailableProperty: 'IsTransformPattern2AvailableProperty',
- PropertyId.IsTransformPatternAvailableProperty: 'IsTransformPatternAvailableProperty',
- PropertyId.IsValuePatternAvailableProperty: 'IsValuePatternAvailableProperty',
- PropertyId.IsVirtualizedItemPatternAvailableProperty: 'IsVirtualizedItemPatternAvailableProperty',
- PropertyId.IsWindowPatternAvailableProperty: 'IsWindowPatternAvailableProperty',
- PropertyId.ItemStatusProperty: 'ItemStatusProperty',
- PropertyId.ItemTypeProperty: 'ItemTypeProperty',
- PropertyId.LabeledByProperty: 'LabeledByProperty',
- PropertyId.LandmarkTypeProperty: 'LandmarkTypeProperty',
- PropertyId.LegacyIAccessibleChildIdProperty: 'LegacyIAccessibleChildIdProperty',
- PropertyId.LegacyIAccessibleDefaultActionProperty: 'LegacyIAccessibleDefaultActionProperty',
- PropertyId.LegacyIAccessibleDescriptionProperty: 'LegacyIAccessibleDescriptionProperty',
- PropertyId.LegacyIAccessibleHelpProperty: 'LegacyIAccessibleHelpProperty',
- PropertyId.LegacyIAccessibleKeyboardShortcutProperty: 'LegacyIAccessibleKeyboardShortcutProperty',
- PropertyId.LegacyIAccessibleNameProperty: 'LegacyIAccessibleNameProperty',
- PropertyId.LegacyIAccessibleRoleProperty: 'LegacyIAccessibleRoleProperty',
- PropertyId.LegacyIAccessibleSelectionProperty: 'LegacyIAccessibleSelectionProperty',
- PropertyId.LegacyIAccessibleStateProperty: 'LegacyIAccessibleStateProperty',
- PropertyId.LegacyIAccessibleValueProperty: 'LegacyIAccessibleValueProperty',
- PropertyId.LevelProperty: 'LevelProperty',
- PropertyId.LiveSettingProperty: 'LiveSettingProperty',
- PropertyId.LocalizedControlTypeProperty: 'LocalizedControlTypeProperty',
- PropertyId.LocalizedLandmarkTypeProperty: 'LocalizedLandmarkTypeProperty',
- PropertyId.MultipleViewCurrentViewProperty: 'MultipleViewCurrentViewProperty',
- PropertyId.MultipleViewSupportedViewsProperty: 'MultipleViewSupportedViewsProperty',
- PropertyId.NameProperty: 'NameProperty',
- PropertyId.NativeWindowHandleProperty: 'NativeWindowHandleProperty',
- PropertyId.OptimizeForVisualContentProperty: 'OptimizeForVisualContentProperty',
- PropertyId.OrientationProperty: 'OrientationProperty',
- PropertyId.OutlineColorProperty: 'OutlineColorProperty',
- PropertyId.OutlineThicknessProperty: 'OutlineThicknessProperty',
- PropertyId.PositionInSetProperty: 'PositionInSetProperty',
- PropertyId.ProcessIdProperty: 'ProcessIdProperty',
- PropertyId.ProviderDescriptionProperty: 'ProviderDescriptionProperty',
- PropertyId.RangeValueIsReadOnlyProperty: 'RangeValueIsReadOnlyProperty',
- PropertyId.RangeValueLargeChangeProperty: 'RangeValueLargeChangeProperty',
- PropertyId.RangeValueMaximumProperty: 'RangeValueMaximumProperty',
- PropertyId.RangeValueMinimumProperty: 'RangeValueMinimumProperty',
- PropertyId.RangeValueSmallChangeProperty: 'RangeValueSmallChangeProperty',
- PropertyId.RangeValueValueProperty: 'RangeValueValueProperty',
- PropertyId.RotationProperty: 'RotationProperty',
- PropertyId.RuntimeIdProperty: 'RuntimeIdProperty',
- PropertyId.ScrollHorizontalScrollPercentProperty: 'ScrollHorizontalScrollPercentProperty',
- PropertyId.ScrollHorizontalViewSizeProperty: 'ScrollHorizontalViewSizeProperty',
- PropertyId.ScrollHorizontallyScrollableProperty: 'ScrollHorizontallyScrollableProperty',
- PropertyId.ScrollVerticalScrollPercentProperty: 'ScrollVerticalScrollPercentProperty',
- PropertyId.ScrollVerticalViewSizeProperty: 'ScrollVerticalViewSizeProperty',
- PropertyId.ScrollVerticallyScrollableProperty: 'ScrollVerticallyScrollableProperty',
- PropertyId.Selection2CurrentSelectedItemProperty: 'Selection2CurrentSelectedItemProperty',
- PropertyId.Selection2FirstSelectedItemProperty: 'Selection2FirstSelectedItemProperty',
- PropertyId.Selection2ItemCountProperty: 'Selection2ItemCountProperty',
- PropertyId.Selection2LastSelectedItemProperty: 'Selection2LastSelectedItemProperty',
- PropertyId.SelectionCanSelectMultipleProperty: 'SelectionCanSelectMultipleProperty',
- PropertyId.SelectionIsSelectionRequiredProperty: 'SelectionIsSelectionRequiredProperty',
- PropertyId.SelectionItemIsSelectedProperty: 'SelectionItemIsSelectedProperty',
- PropertyId.SelectionItemSelectionContainerProperty: 'SelectionItemSelectionContainerProperty',
- PropertyId.SelectionSelectionProperty: 'SelectionSelectionProperty',
- PropertyId.SizeOfSetProperty: 'SizeOfSetProperty',
- PropertyId.SizeProperty: 'SizeProperty',
- PropertyId.SpreadsheetItemAnnotationObjectsProperty: 'SpreadsheetItemAnnotationObjectsProperty',
- PropertyId.SpreadsheetItemAnnotationTypesProperty: 'SpreadsheetItemAnnotationTypesProperty',
- PropertyId.SpreadsheetItemFormulaProperty: 'SpreadsheetItemFormulaProperty',
- PropertyId.StylesExtendedPropertiesProperty: 'StylesExtendedPropertiesProperty',
- PropertyId.StylesFillColorProperty: 'StylesFillColorProperty',
- PropertyId.StylesFillPatternColorProperty: 'StylesFillPatternColorProperty',
- PropertyId.StylesFillPatternStyleProperty: 'StylesFillPatternStyleProperty',
- PropertyId.StylesShapeProperty: 'StylesShapeProperty',
- PropertyId.StylesStyleIdProperty: 'StylesStyleIdProperty',
- PropertyId.StylesStyleNameProperty: 'StylesStyleNameProperty',
- PropertyId.TableColumnHeadersProperty: 'TableColumnHeadersProperty',
- PropertyId.TableItemColumnHeaderItemsProperty: 'TableItemColumnHeaderItemsProperty',
- PropertyId.TableItemRowHeaderItemsProperty: 'TableItemRowHeaderItemsProperty',
- PropertyId.TableRowHeadersProperty: 'TableRowHeadersProperty',
- PropertyId.TableRowOrColumnMajorProperty: 'TableRowOrColumnMajorProperty',
- PropertyId.ToggleToggleStateProperty: 'ToggleToggleStateProperty',
- PropertyId.Transform2CanZoomProperty: 'Transform2CanZoomProperty',
- PropertyId.Transform2ZoomLevelProperty: 'Transform2ZoomLevelProperty',
- PropertyId.Transform2ZoomMaximumProperty: 'Transform2ZoomMaximumProperty',
- PropertyId.Transform2ZoomMinimumProperty: 'Transform2ZoomMinimumProperty',
- PropertyId.TransformCanMoveProperty: 'TransformCanMoveProperty',
- PropertyId.TransformCanResizeProperty: 'TransformCanResizeProperty',
- PropertyId.TransformCanRotateProperty: 'TransformCanRotateProperty',
- PropertyId.ValueIsReadOnlyProperty: 'ValueIsReadOnlyProperty',
- PropertyId.ValueValueProperty: 'ValueValueProperty',
- PropertyId.VisualEffectsProperty: 'VisualEffectsProperty',
- PropertyId.WindowCanMaximizeProperty: 'WindowCanMaximizeProperty',
- PropertyId.WindowCanMinimizeProperty: 'WindowCanMinimizeProperty',
- PropertyId.WindowIsModalProperty: 'WindowIsModalProperty',
- PropertyId.WindowIsTopmostProperty: 'WindowIsTopmostProperty',
- PropertyId.WindowWindowInteractionStateProperty: 'WindowWindowInteractionStateProperty',
- PropertyId.WindowWindowVisualStateProperty: 'WindowWindowVisualStateProperty',
+ PropertyId.AcceleratorKeyProperty: "AcceleratorKeyProperty",
+ PropertyId.AccessKeyProperty: "AccessKeyProperty",
+ PropertyId.AnnotationAnnotationTypeIdProperty: "AnnotationAnnotationTypeIdProperty",
+ PropertyId.AnnotationAnnotationTypeNameProperty: "AnnotationAnnotationTypeNameProperty",
+ PropertyId.AnnotationAuthorProperty: "AnnotationAuthorProperty",
+ PropertyId.AnnotationDateTimeProperty: "AnnotationDateTimeProperty",
+ PropertyId.AnnotationObjectsProperty: "AnnotationObjectsProperty",
+ PropertyId.AnnotationTargetProperty: "AnnotationTargetProperty",
+ PropertyId.AnnotationTypesProperty: "AnnotationTypesProperty",
+ PropertyId.AriaPropertiesProperty: "AriaPropertiesProperty",
+ PropertyId.AriaRoleProperty: "AriaRoleProperty",
+ PropertyId.AutomationIdProperty: "AutomationIdProperty",
+ PropertyId.BoundingRectangleProperty: "BoundingRectangleProperty",
+ PropertyId.CenterPointProperty: "CenterPointProperty",
+ PropertyId.ClassNameProperty: "ClassNameProperty",
+ PropertyId.ClickablePointProperty: "ClickablePointProperty",
+ PropertyId.ControlTypeProperty: "ControlTypeProperty",
+ PropertyId.ControllerForProperty: "ControllerForProperty",
+ PropertyId.CultureProperty: "CultureProperty",
+ PropertyId.DescribedByProperty: "DescribedByProperty",
+ PropertyId.DockDockPositionProperty: "DockDockPositionProperty",
+ PropertyId.DragDropEffectProperty: "DragDropEffectProperty",
+ PropertyId.DragDropEffectsProperty: "DragDropEffectsProperty",
+ PropertyId.DragGrabbedItemsProperty: "DragGrabbedItemsProperty",
+ PropertyId.DragIsGrabbedProperty: "DragIsGrabbedProperty",
+ PropertyId.DropTargetDropTargetEffectProperty: "DropTargetDropTargetEffectProperty",
+ PropertyId.DropTargetDropTargetEffectsProperty: "DropTargetDropTargetEffectsProperty",
+ PropertyId.ExpandCollapseExpandCollapseStateProperty: "ExpandCollapseExpandCollapseStateProperty",
+ PropertyId.FillColorProperty: "FillColorProperty",
+ PropertyId.FillTypeProperty: "FillTypeProperty",
+ PropertyId.FlowsFromProperty: "FlowsFromProperty",
+ PropertyId.FlowsToProperty: "FlowsToProperty",
+ PropertyId.FrameworkIdProperty: "FrameworkIdProperty",
+ PropertyId.FullDescriptionProperty: "FullDescriptionProperty",
+ PropertyId.GridColumnCountProperty: "GridColumnCountProperty",
+ PropertyId.GridItemColumnProperty: "GridItemColumnProperty",
+ PropertyId.GridItemColumnSpanProperty: "GridItemColumnSpanProperty",
+ PropertyId.GridItemContainingGridProperty: "GridItemContainingGridProperty",
+ PropertyId.GridItemRowProperty: "GridItemRowProperty",
+ PropertyId.GridItemRowSpanProperty: "GridItemRowSpanProperty",
+ PropertyId.GridRowCountProperty: "GridRowCountProperty",
+ PropertyId.HasKeyboardFocusProperty: "HasKeyboardFocusProperty",
+ PropertyId.HelpTextProperty: "HelpTextProperty",
+ PropertyId.IsAnnotationPatternAvailableProperty: "IsAnnotationPatternAvailableProperty",
+ PropertyId.IsContentElementProperty: "IsContentElementProperty",
+ PropertyId.IsControlElementProperty: "IsControlElementProperty",
+ PropertyId.IsCustomNavigationPatternAvailableProperty: "IsCustomNavigationPatternAvailableProperty",
+ PropertyId.IsDataValidForFormProperty: "IsDataValidForFormProperty",
+ PropertyId.IsDockPatternAvailableProperty: "IsDockPatternAvailableProperty",
+ PropertyId.IsDragPatternAvailableProperty: "IsDragPatternAvailableProperty",
+ PropertyId.IsDropTargetPatternAvailableProperty: "IsDropTargetPatternAvailableProperty",
+ PropertyId.IsEnabledProperty: "IsEnabledProperty",
+ PropertyId.IsExpandCollapsePatternAvailableProperty: "IsExpandCollapsePatternAvailableProperty",
+ PropertyId.IsGridItemPatternAvailableProperty: "IsGridItemPatternAvailableProperty",
+ PropertyId.IsGridPatternAvailableProperty: "IsGridPatternAvailableProperty",
+ PropertyId.IsInvokePatternAvailableProperty: "IsInvokePatternAvailableProperty",
+ PropertyId.IsItemContainerPatternAvailableProperty: "IsItemContainerPatternAvailableProperty",
+ PropertyId.IsKeyboardFocusableProperty: "IsKeyboardFocusableProperty",
+ PropertyId.IsLegacyIAccessiblePatternAvailableProperty: "IsLegacyIAccessiblePatternAvailableProperty",
+ PropertyId.IsMultipleViewPatternAvailableProperty: "IsMultipleViewPatternAvailableProperty",
+ PropertyId.IsObjectModelPatternAvailableProperty: "IsObjectModelPatternAvailableProperty",
+ PropertyId.IsOffscreenProperty: "IsOffscreenProperty",
+ PropertyId.IsPasswordProperty: "IsPasswordProperty",
+ PropertyId.IsPeripheralProperty: "IsPeripheralProperty",
+ PropertyId.IsRangeValuePatternAvailableProperty: "IsRangeValuePatternAvailableProperty",
+ PropertyId.IsRequiredForFormProperty: "IsRequiredForFormProperty",
+ PropertyId.IsScrollItemPatternAvailableProperty: "IsScrollItemPatternAvailableProperty",
+ PropertyId.IsScrollPatternAvailableProperty: "IsScrollPatternAvailableProperty",
+ PropertyId.IsSelectionItemPatternAvailableProperty: "IsSelectionItemPatternAvailableProperty",
+ PropertyId.IsSelectionPattern2AvailableProperty: "IsSelectionPattern2AvailableProperty",
+ PropertyId.IsSelectionPatternAvailableProperty: "IsSelectionPatternAvailableProperty",
+ PropertyId.IsSpreadsheetItemPatternAvailableProperty: "IsSpreadsheetItemPatternAvailableProperty",
+ PropertyId.IsSpreadsheetPatternAvailableProperty: "IsSpreadsheetPatternAvailableProperty",
+ PropertyId.IsStylesPatternAvailableProperty: "IsStylesPatternAvailableProperty",
+ PropertyId.IsSynchronizedInputPatternAvailableProperty: "IsSynchronizedInputPatternAvailableProperty",
+ PropertyId.IsTableItemPatternAvailableProperty: "IsTableItemPatternAvailableProperty",
+ PropertyId.IsTablePatternAvailableProperty: "IsTablePatternAvailableProperty",
+ PropertyId.IsTextChildPatternAvailableProperty: "IsTextChildPatternAvailableProperty",
+ PropertyId.IsTextEditPatternAvailableProperty: "IsTextEditPatternAvailableProperty",
+ PropertyId.IsTextPattern2AvailableProperty: "IsTextPattern2AvailableProperty",
+ PropertyId.IsTextPatternAvailableProperty: "IsTextPatternAvailableProperty",
+ PropertyId.IsTogglePatternAvailableProperty: "IsTogglePatternAvailableProperty",
+ PropertyId.IsTransformPattern2AvailableProperty: "IsTransformPattern2AvailableProperty",
+ PropertyId.IsTransformPatternAvailableProperty: "IsTransformPatternAvailableProperty",
+ PropertyId.IsValuePatternAvailableProperty: "IsValuePatternAvailableProperty",
+ PropertyId.IsVirtualizedItemPatternAvailableProperty: "IsVirtualizedItemPatternAvailableProperty",
+ PropertyId.IsWindowPatternAvailableProperty: "IsWindowPatternAvailableProperty",
+ PropertyId.ItemStatusProperty: "ItemStatusProperty",
+ PropertyId.ItemTypeProperty: "ItemTypeProperty",
+ PropertyId.LabeledByProperty: "LabeledByProperty",
+ PropertyId.LandmarkTypeProperty: "LandmarkTypeProperty",
+ PropertyId.LegacyIAccessibleChildIdProperty: "LegacyIAccessibleChildIdProperty",
+ PropertyId.LegacyIAccessibleDefaultActionProperty: "LegacyIAccessibleDefaultActionProperty",
+ PropertyId.LegacyIAccessibleDescriptionProperty: "LegacyIAccessibleDescriptionProperty",
+ PropertyId.LegacyIAccessibleHelpProperty: "LegacyIAccessibleHelpProperty",
+ PropertyId.LegacyIAccessibleKeyboardShortcutProperty: "LegacyIAccessibleKeyboardShortcutProperty",
+ PropertyId.LegacyIAccessibleNameProperty: "LegacyIAccessibleNameProperty",
+ PropertyId.LegacyIAccessibleRoleProperty: "LegacyIAccessibleRoleProperty",
+ PropertyId.LegacyIAccessibleSelectionProperty: "LegacyIAccessibleSelectionProperty",
+ PropertyId.LegacyIAccessibleStateProperty: "LegacyIAccessibleStateProperty",
+ PropertyId.LegacyIAccessibleValueProperty: "LegacyIAccessibleValueProperty",
+ PropertyId.LevelProperty: "LevelProperty",
+ PropertyId.LiveSettingProperty: "LiveSettingProperty",
+ PropertyId.LocalizedControlTypeProperty: "LocalizedControlTypeProperty",
+ PropertyId.LocalizedLandmarkTypeProperty: "LocalizedLandmarkTypeProperty",
+ PropertyId.MultipleViewCurrentViewProperty: "MultipleViewCurrentViewProperty",
+ PropertyId.MultipleViewSupportedViewsProperty: "MultipleViewSupportedViewsProperty",
+ PropertyId.NameProperty: "NameProperty",
+ PropertyId.NativeWindowHandleProperty: "NativeWindowHandleProperty",
+ PropertyId.OptimizeForVisualContentProperty: "OptimizeForVisualContentProperty",
+ PropertyId.OrientationProperty: "OrientationProperty",
+ PropertyId.OutlineColorProperty: "OutlineColorProperty",
+ PropertyId.OutlineThicknessProperty: "OutlineThicknessProperty",
+ PropertyId.PositionInSetProperty: "PositionInSetProperty",
+ PropertyId.ProcessIdProperty: "ProcessIdProperty",
+ PropertyId.ProviderDescriptionProperty: "ProviderDescriptionProperty",
+ PropertyId.RangeValueIsReadOnlyProperty: "RangeValueIsReadOnlyProperty",
+ PropertyId.RangeValueLargeChangeProperty: "RangeValueLargeChangeProperty",
+ PropertyId.RangeValueMaximumProperty: "RangeValueMaximumProperty",
+ PropertyId.RangeValueMinimumProperty: "RangeValueMinimumProperty",
+ PropertyId.RangeValueSmallChangeProperty: "RangeValueSmallChangeProperty",
+ PropertyId.RangeValueValueProperty: "RangeValueValueProperty",
+ PropertyId.RotationProperty: "RotationProperty",
+ PropertyId.RuntimeIdProperty: "RuntimeIdProperty",
+ PropertyId.ScrollHorizontalScrollPercentProperty: "ScrollHorizontalScrollPercentProperty",
+ PropertyId.ScrollHorizontalViewSizeProperty: "ScrollHorizontalViewSizeProperty",
+ PropertyId.ScrollHorizontallyScrollableProperty: "ScrollHorizontallyScrollableProperty",
+ PropertyId.ScrollVerticalScrollPercentProperty: "ScrollVerticalScrollPercentProperty",
+ PropertyId.ScrollVerticalViewSizeProperty: "ScrollVerticalViewSizeProperty",
+ PropertyId.ScrollVerticallyScrollableProperty: "ScrollVerticallyScrollableProperty",
+ PropertyId.Selection2CurrentSelectedItemProperty: "Selection2CurrentSelectedItemProperty",
+ PropertyId.Selection2FirstSelectedItemProperty: "Selection2FirstSelectedItemProperty",
+ PropertyId.Selection2ItemCountProperty: "Selection2ItemCountProperty",
+ PropertyId.Selection2LastSelectedItemProperty: "Selection2LastSelectedItemProperty",
+ PropertyId.SelectionCanSelectMultipleProperty: "SelectionCanSelectMultipleProperty",
+ PropertyId.SelectionIsSelectionRequiredProperty: "SelectionIsSelectionRequiredProperty",
+ PropertyId.SelectionItemIsSelectedProperty: "SelectionItemIsSelectedProperty",
+ PropertyId.SelectionItemSelectionContainerProperty: "SelectionItemSelectionContainerProperty",
+ PropertyId.SelectionSelectionProperty: "SelectionSelectionProperty",
+ PropertyId.SizeOfSetProperty: "SizeOfSetProperty",
+ PropertyId.SizeProperty: "SizeProperty",
+ PropertyId.SpreadsheetItemAnnotationObjectsProperty: "SpreadsheetItemAnnotationObjectsProperty",
+ PropertyId.SpreadsheetItemAnnotationTypesProperty: "SpreadsheetItemAnnotationTypesProperty",
+ PropertyId.SpreadsheetItemFormulaProperty: "SpreadsheetItemFormulaProperty",
+ PropertyId.StylesExtendedPropertiesProperty: "StylesExtendedPropertiesProperty",
+ PropertyId.StylesFillColorProperty: "StylesFillColorProperty",
+ PropertyId.StylesFillPatternColorProperty: "StylesFillPatternColorProperty",
+ PropertyId.StylesFillPatternStyleProperty: "StylesFillPatternStyleProperty",
+ PropertyId.StylesShapeProperty: "StylesShapeProperty",
+ PropertyId.StylesStyleIdProperty: "StylesStyleIdProperty",
+ PropertyId.StylesStyleNameProperty: "StylesStyleNameProperty",
+ PropertyId.TableColumnHeadersProperty: "TableColumnHeadersProperty",
+ PropertyId.TableItemColumnHeaderItemsProperty: "TableItemColumnHeaderItemsProperty",
+ PropertyId.TableItemRowHeaderItemsProperty: "TableItemRowHeaderItemsProperty",
+ PropertyId.TableRowHeadersProperty: "TableRowHeadersProperty",
+ PropertyId.TableRowOrColumnMajorProperty: "TableRowOrColumnMajorProperty",
+ PropertyId.ToggleToggleStateProperty: "ToggleToggleStateProperty",
+ PropertyId.Transform2CanZoomProperty: "Transform2CanZoomProperty",
+ PropertyId.Transform2ZoomLevelProperty: "Transform2ZoomLevelProperty",
+ PropertyId.Transform2ZoomMaximumProperty: "Transform2ZoomMaximumProperty",
+ PropertyId.Transform2ZoomMinimumProperty: "Transform2ZoomMinimumProperty",
+ PropertyId.TransformCanMoveProperty: "TransformCanMoveProperty",
+ PropertyId.TransformCanResizeProperty: "TransformCanResizeProperty",
+ PropertyId.TransformCanRotateProperty: "TransformCanRotateProperty",
+ PropertyId.ValueIsReadOnlyProperty: "ValueIsReadOnlyProperty",
+ PropertyId.ValueValueProperty: "ValueValueProperty",
+ PropertyId.VisualEffectsProperty: "VisualEffectsProperty",
+ PropertyId.WindowCanMaximizeProperty: "WindowCanMaximizeProperty",
+ PropertyId.WindowCanMinimizeProperty: "WindowCanMinimizeProperty",
+ PropertyId.WindowIsModalProperty: "WindowIsModalProperty",
+ PropertyId.WindowIsTopmostProperty: "WindowIsTopmostProperty",
+ PropertyId.WindowWindowInteractionStateProperty: "WindowWindowInteractionStateProperty",
+ PropertyId.WindowWindowVisualStateProperty: "WindowWindowVisualStateProperty",
}
@@ -573,6 +577,7 @@ class AccessibleRole:
AccessibleRole from IUIAutomation.
Refer https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.accessiblerole?view=netframework-4.8
"""
+
TitleBar = 0x1
MenuBar = 0x2
ScrollBar = 0x3
@@ -582,12 +587,12 @@ class AccessibleRole:
Caret = 0x7
Alert = 0x8
Window = 0x9
- Client = 0xa
- MenuPopup = 0xb
- MenuItem = 0xc
- ToolTip = 0xd
- Application = 0xe
- Document = 0xf
+ Client = 0xA
+ MenuPopup = 0xB
+ MenuItem = 0xC
+ ToolTip = 0xD
+ Application = 0xE
+ Document = 0xF
Pane = 0x10
Chart = 0x11
Dialog = 0x12
@@ -598,12 +603,12 @@ class AccessibleRole:
StatusBar = 0x17
Table = 0x18
ColumnHeader = 0x19
- RowHeader = 0x1a
- Column = 0x1b
- Row = 0x1c
- Cell = 0x1d
- Link = 0x1e
- HelpBalloon = 0x1f
+ RowHeader = 0x1A
+ Column = 0x1B
+ Row = 0x1C
+ Cell = 0x1D
+ Link = 0x1E
+ HelpBalloon = 0x1F
Character = 0x20
List = 0x21
ListItem = 0x22
@@ -614,12 +619,12 @@ class AccessibleRole:
Indicator = 0x27
Graphic = 0x28
StaticText = 0x29
- Text = 0x2a
- PushButton = 0x2b
- CheckButton = 0x2c
- RadioButton = 0x2d
- ComboBox = 0x2e
- DropList = 0x2f
+ Text = 0x2A
+ PushButton = 0x2B
+ CheckButton = 0x2C
+ RadioButton = 0x2D
+ ComboBox = 0x2E
+ DropList = 0x2F
ProgressBar = 0x30
Dial = 0x31
HotkeyField = 0x32
@@ -630,15 +635,16 @@ class AccessibleRole:
Equation = 0x37
ButtonDropDown = 0x38
ButtonMenu = 0x39
- ButtonDropDownGrid = 0x3a
- WhiteSpace = 0x3b
- PageTabList = 0x3c
- Clock = 0x3d
- SplitButton = 0x3e
- IpAddress = 0x3f
+ ButtonDropDownGrid = 0x3A
+ WhiteSpace = 0x3B
+ PageTabList = 0x3C
+ Clock = 0x3D
+ SplitButton = 0x3E
+ IpAddress = 0x3F
OutlineButton = 0x40
-AccessibleRoleNames = {v: k for k, v in AccessibleRole.__dict__.items() if not k.startswith('_')}
+
+AccessibleRoleNames = {v: k for k, v in AccessibleRole.__dict__.items() if not k.startswith("_")}
class AccessibleState:
@@ -646,6 +652,7 @@ class AccessibleState:
AccessibleState from IUIAutomation.
Refer https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.accessiblestates?view=netframework-4.8
"""
+
Normal = 0
Unavailable = 0x1
Selected = 0x2
@@ -678,7 +685,7 @@ class AccessibleState:
AlertMedium = 0x8000000
AlertHigh = 0x10000000
Protected = 0x20000000
- Valid = 0x7fffffff
+ Valid = 0x7FFFFFFF
HasPopup = 0x40000000
@@ -687,6 +694,7 @@ class AccessibleSelection:
AccessibleSelection from IUIAutomation.
Refer https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.accessibleselection?view=netframework-4.8
"""
+
None_ = 0
TakeFocus = 0x1
TakeSelection = 0x2
@@ -700,6 +708,7 @@ class AnnotationType:
AnnotationType from IUIAutomation.
Refer https://docs.microsoft.com/en-us/windows/win32/winauto/uiauto-annotation-type-identifiers
"""
+
AdvancedProofingIssue = 60020
Author = 60019
CircularReferenceError = 60022
@@ -731,6 +740,7 @@ class NavigateDirection:
NavigateDirection from IUIAutomation.
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationcore/ne-uiautomationcore-navigatedirection
"""
+
Parent = 0
NextSibling = 1
PreviousSibling = 2
@@ -743,6 +753,7 @@ class DockPosition:
DockPosition from IUIAutomation.
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationcore/ne-uiautomationcore-dockposition
"""
+
Top = 0
Left = 1
Bottom = 2
@@ -756,6 +767,7 @@ class ScrollAmount:
ScrollAmount from IUIAutomation.
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationcore/ne-uiautomationcore-scrollamount
"""
+
LargeDecrement = 0
SmallDecrement = 1
NoAmount = 2
@@ -768,6 +780,7 @@ class StyleId:
StyleId from IUIAutomation.
Refer https://docs.microsoft.com/en-us/windows/win32/winauto/uiauto-style-identifiers
"""
+
Custom = 70000
Heading1 = 70001
Heading2 = 70002
@@ -792,6 +805,7 @@ class RowOrColumnMajor:
RowOrColumnMajor from IUIAutomation.
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationcore/ne-uiautomationcore-roworcolumnmajor
"""
+
RowMajor = 0
ColumnMajor = 1
Indeterminate = 2
@@ -802,6 +816,7 @@ class ExpandCollapseState:
ExpandCollapseState from IUIAutomation.
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationcore/ne-uiautomationcore-expandcollapsestate
"""
+
Collapsed = 0
Expanded = 1
PartiallyExpanded = 2
@@ -813,6 +828,7 @@ class OrientationType:
OrientationType from IUIAutomation.
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationcore/ne-uiautomationcore-orientationtype
"""
+
None_ = 0
Horizontal = 1
Vertical = 2
@@ -823,6 +839,7 @@ class ToggleState:
ToggleState from IUIAutomation.
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationcore/ne-uiautomationcore-togglestate
"""
+
Off = 0
On = 1
Indeterminate = 2
@@ -833,6 +850,7 @@ class TextPatternRangeEndpoint:
TextPatternRangeEndpoint from IUIAutomation.
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationcore/ne-uiautomationcore-textpatternrangeendpoint
"""
+
Start = 0
End = 1
@@ -842,6 +860,7 @@ class TextAttributeId:
TextAttributeId from IUIAutomation.
Refer https://docs.microsoft.com/en-us/windows/win32/winauto/uiauto-textattribute-ids
"""
+
AfterParagraphSpacingAttribute = 40042
AnimationStyleAttribute = 40000
AnnotationObjectsAttribute = 40032
@@ -893,6 +912,7 @@ class TextUnit:
TextUnit from IUIAutomation.
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationcore/ne-uiautomationcore-textunit
"""
+
Character = 0
Format = 1
Word = 2
@@ -907,6 +927,7 @@ class ZoomUnit:
ZoomUnit from IUIAutomation.
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationcore/ne-uiautomationcore-zoomunit
"""
+
NoAmount = 0
LargeDecrement = 1
SmallDecrement = 2
@@ -919,6 +940,7 @@ class WindowInteractionState:
WindowInteractionState from IUIAutomation.
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationcore/ne-uiautomationcore-windowinteractionstate
"""
+
Running = 0
Closing = 1
ReadyForUserInteraction = 2
@@ -931,6 +953,7 @@ class WindowVisualState:
WindowVisualState from IUIAutomation.
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationcore/ne-uiautomationcore-windowvisualstate
"""
+
Normal = 0
Maximized = 1
Minimized = 2
@@ -938,6 +961,7 @@ class WindowVisualState:
class ConsoleColor:
"""ConsoleColor from Win32."""
+
Default = -1
Black = 0
DarkBlue = 1
@@ -959,6 +983,7 @@ class ConsoleColor:
class GAFlag:
"""GAFlag from Win32."""
+
Parent = 1
Root = 2
RootOwner = 3
@@ -966,6 +991,7 @@ class GAFlag:
class MouseEventFlag:
"""MouseEventFlag from Win32."""
+
Move = 0x0001
LeftDown = 0x0002
LeftUp = 0x0004
@@ -984,6 +1010,7 @@ class MouseEventFlag:
class KeyboardEventFlag:
"""KeyboardEventFlag from Win32."""
+
KeyDown = 0x0000
ExtendedKey = 0x0001
KeyUp = 0x0002
@@ -993,6 +1020,7 @@ class KeyboardEventFlag:
class InputType:
"""InputType from Win32"""
+
Mouse = 0
Keyboard = 1
Hardware = 2
@@ -1000,6 +1028,7 @@ class InputType:
class ModifierKey:
"""ModifierKey from Win32."""
+
Alt = 0x0001
Control = 0x0002
Shift = 0x0004
@@ -1009,6 +1038,7 @@ class ModifierKey:
class SW:
"""ShowWindow params from Win32."""
+
Hide = 0
ShowNormal = 1
Normal = 1
@@ -1028,6 +1058,7 @@ class SW:
class SWP:
"""SetWindowPos params from Win32."""
+
HWND_Top = 0
HWND_Bottom = 1
HWND_Topmost = -1
@@ -1051,6 +1082,7 @@ class SWP:
class MB:
"""MessageBox flags from Win32."""
+
Ok = 0x00000000
OkCancel = 0x00000001
AbortRetryIgnore = 0x00000002
@@ -1084,11 +1116,11 @@ class MB:
ServiceNotification = 0x00200000
ServiceNotificationNT3X = 0x00040000
- TypeMask = 0x0000000f
- IconMask = 0x000000f0
- DefMask = 0x00000f00
+ TypeMask = 0x0000000F
+ IconMask = 0x000000F0
+ DefMask = 0x00000F00
ModeMask = 0x00003000
- MiscMask = 0x0000c000
+ MiscMask = 0x0000C000
IdOk = 1
IdCancel = 2
@@ -1130,467 +1162,473 @@ class DpiAwarenessContext:
class Keys:
"""Key codes from Win32."""
- VK_LBUTTON = 0x01 #Left mouse button
- VK_RBUTTON = 0x02 #Right mouse button
- VK_CANCEL = 0x03 #Control-break processing
- VK_MBUTTON = 0x04 #Middle mouse button (three-button mouse)
- VK_XBUTTON1 = 0x05 #X1 mouse button
- VK_XBUTTON2 = 0x06 #X2 mouse button
- VK_BACK = 0x08 #BACKSPACE key
- VK_TAB = 0x09 #TAB key
- VK_CLEAR = 0x0C #CLEAR key
- VK_RETURN = 0x0D #ENTER key
+
+ VK_LBUTTON = 0x01 # Left mouse button
+ VK_RBUTTON = 0x02 # Right mouse button
+ VK_CANCEL = 0x03 # Control-break processing
+ VK_MBUTTON = 0x04 # Middle mouse button (three-button mouse)
+ VK_XBUTTON1 = 0x05 # X1 mouse button
+ VK_XBUTTON2 = 0x06 # X2 mouse button
+ VK_BACK = 0x08 # BACKSPACE key
+ VK_TAB = 0x09 # TAB key
+ VK_CLEAR = 0x0C # CLEAR key
+ VK_RETURN = 0x0D # ENTER key
VK_ENTER = 0x0D
- VK_SHIFT = 0x10 #SHIFT key
- VK_CONTROL = 0x11 #CTRL key
- VK_MENU = 0x12 #ALT key
- VK_PAUSE = 0x13 #PAUSE key
- VK_CAPITAL = 0x14 #CAPS LOCK key
- VK_KANA = 0x15 #IME Kana mode
- VK_HANGUEL = 0x15 #IME Hanguel mode (maintained for compatibility; use VK_HANGUL)
- VK_HANGUL = 0x15 #IME Hangul mode
- VK_JUNJA = 0x17 #IME Junja mode
- VK_FINAL = 0x18 #IME final mode
- VK_HANJA = 0x19 #IME Hanja mode
- VK_KANJI = 0x19 #IME Kanji mode
- VK_ESCAPE = 0x1B #ESC key
- VK_CONVERT = 0x1C #IME convert
- VK_NONCONVERT = 0x1D #IME nonconvert
- VK_ACCEPT = 0x1E #IME accept
- VK_MODECHANGE = 0x1F #IME mode change request
- VK_SPACE = 0x20 #SPACEBAR
- VK_PRIOR = 0x21 #PAGE UP key
+ VK_SHIFT = 0x10 # SHIFT key
+ VK_CONTROL = 0x11 # CTRL key
+ VK_MENU = 0x12 # ALT key
+ VK_PAUSE = 0x13 # PAUSE key
+ VK_CAPITAL = 0x14 # CAPS LOCK key
+ VK_KANA = 0x15 # IME Kana mode
+ VK_HANGUEL = 0x15 # IME Hanguel mode (maintained for compatibility; use VK_HANGUL)
+ VK_HANGUL = 0x15 # IME Hangul mode
+ VK_JUNJA = 0x17 # IME Junja mode
+ VK_FINAL = 0x18 # IME final mode
+ VK_HANJA = 0x19 # IME Hanja mode
+ VK_KANJI = 0x19 # IME Kanji mode
+ VK_ESCAPE = 0x1B # ESC key
+ VK_CONVERT = 0x1C # IME convert
+ VK_NONCONVERT = 0x1D # IME nonconvert
+ VK_ACCEPT = 0x1E # IME accept
+ VK_MODECHANGE = 0x1F # IME mode change request
+ VK_SPACE = 0x20 # SPACEBAR
+ VK_PRIOR = 0x21 # PAGE UP key
VK_PAGEUP = 0x21
- VK_NEXT = 0x22 #PAGE DOWN key
+ VK_NEXT = 0x22 # PAGE DOWN key
VK_PAGEDOWN = 0x22
- VK_END = 0x23 #END key
- VK_HOME = 0x24 #HOME key
- VK_LEFT = 0x25 #LEFT ARROW key
- VK_UP = 0x26 #UP ARROW key
- VK_RIGHT = 0x27 #RIGHT ARROW key
- VK_DOWN = 0x28 #DOWN ARROW key
- VK_SELECT = 0x29 #SELECT key
- VK_PRINT = 0x2A #PRINT key
- VK_EXECUTE = 0x2B #EXECUTE key
- VK_SNAPSHOT = 0x2C #PRINT SCREEN key
- VK_INSERT = 0x2D #INS key
- VK_DELETE = 0x2E #DEL key
- VK_HELP = 0x2F #HELP key
- VK_0 = 0x30 #0 key
- VK_1 = 0x31 #1 key
- VK_2 = 0x32 #2 key
- VK_3 = 0x33 #3 key
- VK_4 = 0x34 #4 key
- VK_5 = 0x35 #5 key
- VK_6 = 0x36 #6 key
- VK_7 = 0x37 #7 key
- VK_8 = 0x38 #8 key
- VK_9 = 0x39 #9 key
- VK_A = 0x41 #A key
- VK_B = 0x42 #B key
- VK_C = 0x43 #C key
- VK_D = 0x44 #D key
- VK_E = 0x45 #E key
- VK_F = 0x46 #F key
- VK_G = 0x47 #G key
- VK_H = 0x48 #H key
- VK_I = 0x49 #I key
- VK_J = 0x4A #J key
- VK_K = 0x4B #K key
- VK_L = 0x4C #L key
- VK_M = 0x4D #M key
- VK_N = 0x4E #N key
- VK_O = 0x4F #O key
- VK_P = 0x50 #P key
- VK_Q = 0x51 #Q key
- VK_R = 0x52 #R key
- VK_S = 0x53 #S key
- VK_T = 0x54 #T key
- VK_U = 0x55 #U key
- VK_V = 0x56 #V key
- VK_W = 0x57 #W key
- VK_X = 0x58 #X key
- VK_Y = 0x59 #Y key
- VK_Z = 0x5A #Z key
- VK_LWIN = 0x5B #Left Windows key (Natural keyboard)
- VK_RWIN = 0x5C #Right Windows key (Natural keyboard)
- VK_APPS = 0x5D #Applications key (Natural keyboard)
- VK_SLEEP = 0x5F #Computer Sleep key
- VK_NUMPAD0 = 0x60 #Numeric keypad 0 key
- VK_NUMPAD1 = 0x61 #Numeric keypad 1 key
- VK_NUMPAD2 = 0x62 #Numeric keypad 2 key
- VK_NUMPAD3 = 0x63 #Numeric keypad 3 key
- VK_NUMPAD4 = 0x64 #Numeric keypad 4 key
- VK_NUMPAD5 = 0x65 #Numeric keypad 5 key
- VK_NUMPAD6 = 0x66 #Numeric keypad 6 key
- VK_NUMPAD7 = 0x67 #Numeric keypad 7 key
- VK_NUMPAD8 = 0x68 #Numeric keypad 8 key
- VK_NUMPAD9 = 0x69 #Numeric keypad 9 key
- VK_MULTIPLY = 0x6A #Multiply key
- VK_ADD = 0x6B #Add key
- VK_SEPARATOR = 0x6C #Separator key
- VK_SUBTRACT = 0x6D #Subtract key
- VK_DECIMAL = 0x6E #Decimal key
- VK_DIVIDE = 0x6F #Divide key
- VK_F1 = 0x70 #F1 key
- VK_F2 = 0x71 #F2 key
- VK_F3 = 0x72 #F3 key
- VK_F4 = 0x73 #F4 key
- VK_F5 = 0x74 #F5 key
- VK_F6 = 0x75 #F6 key
- VK_F7 = 0x76 #F7 key
- VK_F8 = 0x77 #F8 key
- VK_F9 = 0x78 #F9 key
- VK_F10 = 0x79 #F10 key
- VK_F11 = 0x7A #F11 key
- VK_F12 = 0x7B #F12 key
- VK_F13 = 0x7C #F13 key
- VK_F14 = 0x7D #F14 key
- VK_F15 = 0x7E #F15 key
- VK_F16 = 0x7F #F16 key
- VK_F17 = 0x80 #F17 key
- VK_F18 = 0x81 #F18 key
- VK_F19 = 0x82 #F19 key
- VK_F20 = 0x83 #F20 key
- VK_F21 = 0x84 #F21 key
- VK_F22 = 0x85 #F22 key
- VK_F23 = 0x86 #F23 key
- VK_F24 = 0x87 #F24 key
- VK_NUMLOCK = 0x90 #NUM LOCK key
- VK_SCROLL = 0x91 #SCROLL LOCK key
- VK_LSHIFT = 0xA0 #Left SHIFT key
- VK_RSHIFT = 0xA1 #Right SHIFT key
- VK_LCONTROL = 0xA2 #Left CONTROL key
- VK_RCONTROL = 0xA3 #Right CONTROL key
- VK_LMENU = 0xA4 #Left MENU key
- VK_RMENU = 0xA5 #Right MENU key
- VK_BROWSER_BACK = 0xA6 #Browser Back key
- VK_BROWSER_FORWARD = 0xA7 #Browser Forward key
- VK_BROWSER_REFRESH = 0xA8 #Browser Refresh key
- VK_BROWSER_STOP = 0xA9 #Browser Stop key
- VK_BROWSER_SEARCH = 0xAA #Browser Search key
- VK_BROWSER_FAVORITES = 0xAB #Browser Favorites key
- VK_BROWSER_HOME = 0xAC #Browser Start and Home key
- VK_VOLUME_MUTE = 0xAD #Volume Mute key
- VK_VOLUME_DOWN = 0xAE #Volume Down key
- VK_VOLUME_UP = 0xAF #Volume Up key
- VK_MEDIA_NEXT_TRACK = 0xB0 #Next Track key
- VK_MEDIA_PREV_TRACK = 0xB1 #Previous Track key
- VK_MEDIA_STOP = 0xB2 #Stop Media key
- VK_MEDIA_PLAY_PAUSE = 0xB3 #Play/Pause Media key
- VK_LAUNCH_MAIL = 0xB4 #Start Mail key
- VK_LAUNCH_MEDIA_SELECT = 0xB5 #Select Media key
- VK_LAUNCH_APP1 = 0xB6 #Start Application 1 key
- VK_LAUNCH_APP2 = 0xB7 #Start Application 2 key
- VK_OEM_1 = 0xBA #Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the ';:' key
- VK_OEM_PLUS = 0xBB #For any country/region, the '+' key
- VK_OEM_COMMA = 0xBC #For any country/region, the ',' key
- VK_OEM_MINUS = 0xBD #For any country/region, the '-' key
- VK_OEM_PERIOD = 0xBE #For any country/region, the '.' key
- VK_OEM_2 = 0xBF #Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the '/?' key
- VK_OEM_3 = 0xC0 #Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the '`~' key
- VK_OEM_4 = 0xDB #Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the '[{' key
- VK_OEM_5 = 0xDC #Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the '\|' key
- VK_OEM_6 = 0xDD #Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the ']}' key
- VK_OEM_7 = 0xDE #Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the 'single-quote/double-quote' key
- VK_OEM_8 = 0xDF #Used for miscellaneous characters; it can vary by keyboard.
- VK_OEM_102 = 0xE2 #Either the angle bracket key or the backslash key on the RT 102-key keyboard
- VK_PROCESSKEY = 0xE5 #IME PROCESS key
- VK_PACKET = 0xE7 #Used to pass Unicode characters as if they were keystrokes. The VK_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, see Remark in KEYBDINPUT, SendInput, WM_KEYDOWN, and WM_KeyUp
- VK_ATTN = 0xF6 #Attn key
- VK_CRSEL = 0xF7 #CrSel key
- VK_EXSEL = 0xF8 #ExSel key
- VK_EREOF = 0xF9 #Erase EOF key
- VK_PLAY = 0xFA #Play key
- VK_ZOOM = 0xFB #Zoom key
- VK_NONAME = 0xFC #Reserved
- VK_PA1 = 0xFD #PA1 key
- VK_OEM_CLEAR = 0xFE #Clear key
+ VK_END = 0x23 # END key
+ VK_HOME = 0x24 # HOME key
+ VK_LEFT = 0x25 # LEFT ARROW key
+ VK_UP = 0x26 # UP ARROW key
+ VK_RIGHT = 0x27 # RIGHT ARROW key
+ VK_DOWN = 0x28 # DOWN ARROW key
+ VK_SELECT = 0x29 # SELECT key
+ VK_PRINT = 0x2A # PRINT key
+ VK_EXECUTE = 0x2B # EXECUTE key
+ VK_SNAPSHOT = 0x2C # PRINT SCREEN key
+ VK_INSERT = 0x2D # INS key
+ VK_DELETE = 0x2E # DEL key
+ VK_HELP = 0x2F # HELP key
+ VK_0 = 0x30 # 0 key
+ VK_1 = 0x31 # 1 key
+ VK_2 = 0x32 # 2 key
+ VK_3 = 0x33 # 3 key
+ VK_4 = 0x34 # 4 key
+ VK_5 = 0x35 # 5 key
+ VK_6 = 0x36 # 6 key
+ VK_7 = 0x37 # 7 key
+ VK_8 = 0x38 # 8 key
+ VK_9 = 0x39 # 9 key
+ VK_A = 0x41 # A key
+ VK_B = 0x42 # B key
+ VK_C = 0x43 # C key
+ VK_D = 0x44 # D key
+ VK_E = 0x45 # E key
+ VK_F = 0x46 # F key
+ VK_G = 0x47 # G key
+ VK_H = 0x48 # H key
+ VK_I = 0x49 # I key
+ VK_J = 0x4A # J key
+ VK_K = 0x4B # K key
+ VK_L = 0x4C # L key
+ VK_M = 0x4D # M key
+ VK_N = 0x4E # N key
+ VK_O = 0x4F # O key
+ VK_P = 0x50 # P key
+ VK_Q = 0x51 # Q key
+ VK_R = 0x52 # R key
+ VK_S = 0x53 # S key
+ VK_T = 0x54 # T key
+ VK_U = 0x55 # U key
+ VK_V = 0x56 # V key
+ VK_W = 0x57 # W key
+ VK_X = 0x58 # X key
+ VK_Y = 0x59 # Y key
+ VK_Z = 0x5A # Z key
+ VK_LWIN = 0x5B # Left Windows key (Natural keyboard)
+ VK_RWIN = 0x5C # Right Windows key (Natural keyboard)
+ VK_APPS = 0x5D # Applications key (Natural keyboard)
+ VK_SLEEP = 0x5F # Computer Sleep key
+ VK_NUMPAD0 = 0x60 # Numeric keypad 0 key
+ VK_NUMPAD1 = 0x61 # Numeric keypad 1 key
+ VK_NUMPAD2 = 0x62 # Numeric keypad 2 key
+ VK_NUMPAD3 = 0x63 # Numeric keypad 3 key
+ VK_NUMPAD4 = 0x64 # Numeric keypad 4 key
+ VK_NUMPAD5 = 0x65 # Numeric keypad 5 key
+ VK_NUMPAD6 = 0x66 # Numeric keypad 6 key
+ VK_NUMPAD7 = 0x67 # Numeric keypad 7 key
+ VK_NUMPAD8 = 0x68 # Numeric keypad 8 key
+ VK_NUMPAD9 = 0x69 # Numeric keypad 9 key
+ VK_MULTIPLY = 0x6A # Multiply key
+ VK_ADD = 0x6B # Add key
+ VK_SEPARATOR = 0x6C # Separator key
+ VK_SUBTRACT = 0x6D # Subtract key
+ VK_DECIMAL = 0x6E # Decimal key
+ VK_DIVIDE = 0x6F # Divide key
+ VK_F1 = 0x70 # F1 key
+ VK_F2 = 0x71 # F2 key
+ VK_F3 = 0x72 # F3 key
+ VK_F4 = 0x73 # F4 key
+ VK_F5 = 0x74 # F5 key
+ VK_F6 = 0x75 # F6 key
+ VK_F7 = 0x76 # F7 key
+ VK_F8 = 0x77 # F8 key
+ VK_F9 = 0x78 # F9 key
+ VK_F10 = 0x79 # F10 key
+ VK_F11 = 0x7A # F11 key
+ VK_F12 = 0x7B # F12 key
+ VK_F13 = 0x7C # F13 key
+ VK_F14 = 0x7D # F14 key
+ VK_F15 = 0x7E # F15 key
+ VK_F16 = 0x7F # F16 key
+ VK_F17 = 0x80 # F17 key
+ VK_F18 = 0x81 # F18 key
+ VK_F19 = 0x82 # F19 key
+ VK_F20 = 0x83 # F20 key
+ VK_F21 = 0x84 # F21 key
+ VK_F22 = 0x85 # F22 key
+ VK_F23 = 0x86 # F23 key
+ VK_F24 = 0x87 # F24 key
+ VK_NUMLOCK = 0x90 # NUM LOCK key
+ VK_SCROLL = 0x91 # SCROLL LOCK key
+ VK_LSHIFT = 0xA0 # Left SHIFT key
+ VK_RSHIFT = 0xA1 # Right SHIFT key
+ VK_LCONTROL = 0xA2 # Left CONTROL key
+ VK_RCONTROL = 0xA3 # Right CONTROL key
+ VK_LMENU = 0xA4 # Left MENU key
+ VK_RMENU = 0xA5 # Right MENU key
+ VK_BROWSER_BACK = 0xA6 # Browser Back key
+ VK_BROWSER_FORWARD = 0xA7 # Browser Forward key
+ VK_BROWSER_REFRESH = 0xA8 # Browser Refresh key
+ VK_BROWSER_STOP = 0xA9 # Browser Stop key
+ VK_BROWSER_SEARCH = 0xAA # Browser Search key
+ VK_BROWSER_FAVORITES = 0xAB # Browser Favorites key
+ VK_BROWSER_HOME = 0xAC # Browser Start and Home key
+ VK_VOLUME_MUTE = 0xAD # Volume Mute key
+ VK_VOLUME_DOWN = 0xAE # Volume Down key
+ VK_VOLUME_UP = 0xAF # Volume Up key
+ VK_MEDIA_NEXT_TRACK = 0xB0 # Next Track key
+ VK_MEDIA_PREV_TRACK = 0xB1 # Previous Track key
+ VK_MEDIA_STOP = 0xB2 # Stop Media key
+ VK_MEDIA_PLAY_PAUSE = 0xB3 # Play/Pause Media key
+ VK_LAUNCH_MAIL = 0xB4 # Start Mail key
+ VK_LAUNCH_MEDIA_SELECT = 0xB5 # Select Media key
+ VK_LAUNCH_APP1 = 0xB6 # Start Application 1 key
+ VK_LAUNCH_APP2 = 0xB7 # Start Application 2 key
+ VK_OEM_1 = 0xBA # Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the ';:' key
+ VK_OEM_PLUS = 0xBB # For any country/region, the '+' key
+ VK_OEM_COMMA = 0xBC # For any country/region, the ',' key
+ VK_OEM_MINUS = 0xBD # For any country/region, the '-' key
+ VK_OEM_PERIOD = 0xBE # For any country/region, the '.' key
+ VK_OEM_2 = 0xBF # Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the '/?' key
+ VK_OEM_3 = 0xC0 # Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the '`~' key
+ VK_OEM_4 = 0xDB # Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the '[{' key
+ VK_OEM_5 = 0xDC # Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the '\|' key
+ VK_OEM_6 = 0xDD # Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the ']}' key
+ VK_OEM_7 = 0xDE # Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the 'single-quote/double-quote' key
+ VK_OEM_8 = 0xDF # Used for miscellaneous characters; it can vary by keyboard.
+ VK_OEM_102 = (
+ 0xE2 # Either the angle bracket key or the backslash key on the RT 102-key keyboard
+ )
+ VK_PROCESSKEY = 0xE5 # IME PROCESS key
+ VK_PACKET = 0xE7 # Used to pass Unicode characters as if they were keystrokes. The VK_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, see Remark in KEYBDINPUT, SendInput, WM_KEYDOWN, and WM_KeyUp
+ VK_ATTN = 0xF6 # Attn key
+ VK_CRSEL = 0xF7 # CrSel key
+ VK_EXSEL = 0xF8 # ExSel key
+ VK_EREOF = 0xF9 # Erase EOF key
+ VK_PLAY = 0xFA # Play key
+ VK_ZOOM = 0xFB # Zoom key
+ VK_NONAME = 0xFC # Reserved
+ VK_PA1 = 0xFD # PA1 key
+ VK_OEM_CLEAR = 0xFE # Clear key
SpecialKeyNames = {
- 'LBUTTON': Keys.VK_LBUTTON, #Left mouse button
- 'RBUTTON': Keys.VK_RBUTTON, #Right mouse button
- 'CANCEL': Keys.VK_CANCEL, #Control-break processing
- 'MBUTTON': Keys.VK_MBUTTON, #Middle mouse button (three-button mouse)
- 'XBUTTON1': Keys.VK_XBUTTON1, #X1 mouse button
- 'XBUTTON2': Keys.VK_XBUTTON2, #X2 mouse button
- 'BACK': Keys.VK_BACK, #BACKSPACE key
- 'TAB': Keys.VK_TAB, #TAB key
- 'CLEAR': Keys.VK_CLEAR, #CLEAR key
- 'RETURN': Keys.VK_RETURN, #ENTER key
- 'ENTER': Keys.VK_RETURN, #ENTER key
- 'SHIFT': Keys.VK_SHIFT, #SHIFT key
- 'CTRL': Keys.VK_CONTROL, #CTRL key
- 'CONTROL': Keys.VK_CONTROL, #CTRL key
- 'ALT': Keys.VK_MENU, #ALT key
- 'PAUSE': Keys.VK_PAUSE, #PAUSE key
- 'CAPITAL': Keys.VK_CAPITAL, #CAPS LOCK key
- 'KANA': Keys.VK_KANA, #IME Kana mode
- 'HANGUEL': Keys.VK_HANGUEL, #IME Hanguel mode (maintained for compatibility; use VK_HANGUL)
- 'HANGUL': Keys.VK_HANGUL, #IME Hangul mode
- 'JUNJA': Keys.VK_JUNJA, #IME Junja mode
- 'FINAL': Keys.VK_FINAL, #IME final mode
- 'HANJA': Keys.VK_HANJA, #IME Hanja mode
- 'KANJI': Keys.VK_KANJI, #IME Kanji mode
- 'ESC': Keys.VK_ESCAPE, #ESC key
- 'ESCAPE': Keys.VK_ESCAPE, #ESC key
- 'CONVERT': Keys.VK_CONVERT, #IME convert
- 'NONCONVERT': Keys.VK_NONCONVERT, #IME nonconvert
- 'ACCEPT': Keys.VK_ACCEPT, #IME accept
- 'MODECHANGE': Keys.VK_MODECHANGE, #IME mode change request
- 'SPACE': Keys.VK_SPACE, #SPACEBAR
- 'PRIOR': Keys.VK_PRIOR, #PAGE UP key
- 'PAGEUP': Keys.VK_PRIOR, #PAGE UP key
- 'NEXT': Keys.VK_NEXT, #PAGE DOWN key
- 'PAGEDOWN': Keys.VK_NEXT, #PAGE DOWN key
- 'END': Keys.VK_END, #END key
- 'HOME': Keys.VK_HOME, #HOME key
- 'LEFT': Keys.VK_LEFT, #LEFT ARROW key
- 'UP': Keys.VK_UP, #UP ARROW key
- 'RIGHT': Keys.VK_RIGHT, #RIGHT ARROW key
- 'DOWN': Keys.VK_DOWN, #DOWN ARROW key
- 'SELECT': Keys.VK_SELECT, #SELECT key
- 'PRINT': Keys.VK_PRINT, #PRINT key
- 'EXECUTE': Keys.VK_EXECUTE, #EXECUTE key
- 'SNAPSHOT': Keys.VK_SNAPSHOT, #PRINT SCREEN key
- 'PRINTSCREEN': Keys.VK_SNAPSHOT, #PRINT SCREEN key
- 'INSERT': Keys.VK_INSERT, #INS key
- 'INS': Keys.VK_INSERT, #INS key
- 'DELETE': Keys.VK_DELETE, #DEL key
- 'DEL': Keys.VK_DELETE, #DEL key
- 'HELP': Keys.VK_HELP, #HELP key
- 'WIN': Keys.VK_LWIN, #Left Windows key (Natural keyboard)
- 'LWIN': Keys.VK_LWIN, #Left Windows key (Natural keyboard)
- 'RWIN': Keys.VK_RWIN, #Right Windows key (Natural keyboard)
- 'APPS': Keys.VK_APPS, #Applications key (Natural keyboard)
- 'SLEEP': Keys.VK_SLEEP, #Computer Sleep key
- 'NUMPAD0': Keys.VK_NUMPAD0, #Numeric keypad 0 key
- 'NUMPAD1': Keys.VK_NUMPAD1, #Numeric keypad 1 key
- 'NUMPAD2': Keys.VK_NUMPAD2, #Numeric keypad 2 key
- 'NUMPAD3': Keys.VK_NUMPAD3, #Numeric keypad 3 key
- 'NUMPAD4': Keys.VK_NUMPAD4, #Numeric keypad 4 key
- 'NUMPAD5': Keys.VK_NUMPAD5, #Numeric keypad 5 key
- 'NUMPAD6': Keys.VK_NUMPAD6, #Numeric keypad 6 key
- 'NUMPAD7': Keys.VK_NUMPAD7, #Numeric keypad 7 key
- 'NUMPAD8': Keys.VK_NUMPAD8, #Numeric keypad 8 key
- 'NUMPAD9': Keys.VK_NUMPAD9, #Numeric keypad 9 key
- 'MULTIPLY': Keys.VK_MULTIPLY, #Multiply key
- 'ADD': Keys.VK_ADD, #Add key
- 'SEPARATOR': Keys.VK_SEPARATOR, #Separator key
- 'SUBTRACT': Keys.VK_SUBTRACT, #Subtract key
- 'DECIMAL': Keys.VK_DECIMAL, #Decimal key
- 'DIVIDE': Keys.VK_DIVIDE, #Divide key
- 'F1': Keys.VK_F1, #F1 key
- 'F2': Keys.VK_F2, #F2 key
- 'F3': Keys.VK_F3, #F3 key
- 'F4': Keys.VK_F4, #F4 key
- 'F5': Keys.VK_F5, #F5 key
- 'F6': Keys.VK_F6, #F6 key
- 'F7': Keys.VK_F7, #F7 key
- 'F8': Keys.VK_F8, #F8 key
- 'F9': Keys.VK_F9, #F9 key
- 'F10': Keys.VK_F10, #F10 key
- 'F11': Keys.VK_F11, #F11 key
- 'F12': Keys.VK_F12, #F12 key
- 'F13': Keys.VK_F13, #F13 key
- 'F14': Keys.VK_F14, #F14 key
- 'F15': Keys.VK_F15, #F15 key
- 'F16': Keys.VK_F16, #F16 key
- 'F17': Keys.VK_F17, #F17 key
- 'F18': Keys.VK_F18, #F18 key
- 'F19': Keys.VK_F19, #F19 key
- 'F20': Keys.VK_F20, #F20 key
- 'F21': Keys.VK_F21, #F21 key
- 'F22': Keys.VK_F22, #F22 key
- 'F23': Keys.VK_F23, #F23 key
- 'F24': Keys.VK_F24, #F24 key
- 'NUMLOCK': Keys.VK_NUMLOCK, #NUM LOCK key
- 'SCROLL': Keys.VK_SCROLL, #SCROLL LOCK key
- 'LSHIFT': Keys.VK_LSHIFT, #Left SHIFT key
- 'RSHIFT': Keys.VK_RSHIFT, #Right SHIFT key
- 'LCONTROL': Keys.VK_LCONTROL, #Left CONTROL key
- 'LCTRL': Keys.VK_LCONTROL, #Left CONTROL key
- 'RCONTROL': Keys.VK_RCONTROL, #Right CONTROL key
- 'RCTRL': Keys.VK_RCONTROL, #Right CONTROL key
- 'LALT': Keys.VK_LMENU, #Left MENU key
- 'RALT': Keys.VK_RMENU, #Right MENU key
- 'BROWSER_BACK': Keys.VK_BROWSER_BACK, #Browser Back key
- 'BROWSER_FORWARD': Keys.VK_BROWSER_FORWARD, #Browser Forward key
- 'BROWSER_REFRESH': Keys.VK_BROWSER_REFRESH, #Browser Refresh key
- 'BROWSER_STOP': Keys.VK_BROWSER_STOP, #Browser Stop key
- 'BROWSER_SEARCH': Keys.VK_BROWSER_SEARCH, #Browser Search key
- 'BROWSER_FAVORITES': Keys.VK_BROWSER_FAVORITES, #Browser Favorites key
- 'BROWSER_HOME': Keys.VK_BROWSER_HOME, #Browser Start and Home key
- 'VOLUME_MUTE': Keys.VK_VOLUME_MUTE, #Volume Mute key
- 'VOLUME_DOWN': Keys.VK_VOLUME_DOWN, #Volume Down key
- 'VOLUME_UP': Keys.VK_VOLUME_UP, #Volume Up key
- 'MEDIA_NEXT_TRACK': Keys.VK_MEDIA_NEXT_TRACK, #Next Track key
- 'MEDIA_PREV_TRACK': Keys.VK_MEDIA_PREV_TRACK, #Previous Track key
- 'MEDIA_STOP': Keys.VK_MEDIA_STOP, #Stop Media key
- 'MEDIA_PLAY_PAUSE': Keys.VK_MEDIA_PLAY_PAUSE, #Play/Pause Media key
- 'LAUNCH_MAIL': Keys.VK_LAUNCH_MAIL, #Start Mail key
- 'LAUNCH_MEDIA_SELECT': Keys.VK_LAUNCH_MEDIA_SELECT,#Select Media key
- 'LAUNCH_APP1': Keys.VK_LAUNCH_APP1, #Start Application 1 key
- 'LAUNCH_APP2': Keys.VK_LAUNCH_APP2, #Start Application 2 key
- 'OEM_1': Keys.VK_OEM_1, #Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the ';:' key
- 'OEM_PLUS': Keys.VK_OEM_PLUS, #For any country/region, the '+' key
- 'OEM_COMMA': Keys.VK_OEM_COMMA, #For any country/region, the ',' key
- 'OEM_MINUS': Keys.VK_OEM_MINUS, #For any country/region, the '-' key
- 'OEM_PERIOD': Keys.VK_OEM_PERIOD, #For any country/region, the '.' key
- 'OEM_2': Keys.VK_OEM_2, #Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the '/?' key
- 'OEM_3': Keys.VK_OEM_3, #Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the '`~' key
- 'OEM_4': Keys.VK_OEM_4, #Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the '[{' key
- 'OEM_5': Keys.VK_OEM_5, #Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the '\|' key
- 'OEM_6': Keys.VK_OEM_6, #Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the ']}' key
- 'OEM_7': Keys.VK_OEM_7, #Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the 'single-quote/double-quote' key
- 'OEM_8': Keys.VK_OEM_8, #Used for miscellaneous characters; it can vary by keyboard.
- 'OEM_102': Keys.VK_OEM_102, #Either the angle bracket key or the backslash key on the RT 102-key keyboard
- 'PROCESSKEY': Keys.VK_PROCESSKEY, #IME PROCESS key
- 'PACKET': Keys.VK_PACKET, #Used to pass Unicode characters as if they were keystrokes. The VK_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, see Remark in KEYBDINPUT, SendInput, WM_KEYDOWN, and WM_KeyUp
- 'ATTN': Keys.VK_ATTN, #Attn key
- 'CRSEL': Keys.VK_CRSEL, #CrSel key
- 'EXSEL': Keys.VK_EXSEL, #ExSel key
- 'EREOF': Keys.VK_EREOF, #Erase EOF key
- 'PLAY': Keys.VK_PLAY, #Play key
- 'ZOOM': Keys.VK_ZOOM, #Zoom key
- 'NONAME': Keys.VK_NONAME, #Reserved
- 'PA1': Keys.VK_PA1, #PA1 key
- 'OEM_CLEAR': Keys.VK_OEM_CLEAR, #Clear key
+ "LBUTTON": Keys.VK_LBUTTON, # Left mouse button
+ "RBUTTON": Keys.VK_RBUTTON, # Right mouse button
+ "CANCEL": Keys.VK_CANCEL, # Control-break processing
+ "MBUTTON": Keys.VK_MBUTTON, # Middle mouse button (three-button mouse)
+ "XBUTTON1": Keys.VK_XBUTTON1, # X1 mouse button
+ "XBUTTON2": Keys.VK_XBUTTON2, # X2 mouse button
+ "BACK": Keys.VK_BACK, # BACKSPACE key
+ "TAB": Keys.VK_TAB, # TAB key
+ "CLEAR": Keys.VK_CLEAR, # CLEAR key
+ "RETURN": Keys.VK_RETURN, # ENTER key
+ "ENTER": Keys.VK_RETURN, # ENTER key
+ "SHIFT": Keys.VK_SHIFT, # SHIFT key
+ "CTRL": Keys.VK_CONTROL, # CTRL key
+ "CONTROL": Keys.VK_CONTROL, # CTRL key
+ "ALT": Keys.VK_MENU, # ALT key
+ "PAUSE": Keys.VK_PAUSE, # PAUSE key
+ "CAPITAL": Keys.VK_CAPITAL, # CAPS LOCK key
+ "KANA": Keys.VK_KANA, # IME Kana mode
+ "HANGUEL": Keys.VK_HANGUEL, # IME Hanguel mode (maintained for compatibility; use VK_HANGUL)
+ "HANGUL": Keys.VK_HANGUL, # IME Hangul mode
+ "JUNJA": Keys.VK_JUNJA, # IME Junja mode
+ "FINAL": Keys.VK_FINAL, # IME final mode
+ "HANJA": Keys.VK_HANJA, # IME Hanja mode
+ "KANJI": Keys.VK_KANJI, # IME Kanji mode
+ "ESC": Keys.VK_ESCAPE, # ESC key
+ "ESCAPE": Keys.VK_ESCAPE, # ESC key
+ "CONVERT": Keys.VK_CONVERT, # IME convert
+ "NONCONVERT": Keys.VK_NONCONVERT, # IME nonconvert
+ "ACCEPT": Keys.VK_ACCEPT, # IME accept
+ "MODECHANGE": Keys.VK_MODECHANGE, # IME mode change request
+ "SPACE": Keys.VK_SPACE, # SPACEBAR
+ "PRIOR": Keys.VK_PRIOR, # PAGE UP key
+ "PAGEUP": Keys.VK_PRIOR, # PAGE UP key
+ "NEXT": Keys.VK_NEXT, # PAGE DOWN key
+ "PAGEDOWN": Keys.VK_NEXT, # PAGE DOWN key
+ "END": Keys.VK_END, # END key
+ "HOME": Keys.VK_HOME, # HOME key
+ "LEFT": Keys.VK_LEFT, # LEFT ARROW key
+ "UP": Keys.VK_UP, # UP ARROW key
+ "RIGHT": Keys.VK_RIGHT, # RIGHT ARROW key
+ "DOWN": Keys.VK_DOWN, # DOWN ARROW key
+ "SELECT": Keys.VK_SELECT, # SELECT key
+ "PRINT": Keys.VK_PRINT, # PRINT key
+ "EXECUTE": Keys.VK_EXECUTE, # EXECUTE key
+ "SNAPSHOT": Keys.VK_SNAPSHOT, # PRINT SCREEN key
+ "PRINTSCREEN": Keys.VK_SNAPSHOT, # PRINT SCREEN key
+ "INSERT": Keys.VK_INSERT, # INS key
+ "INS": Keys.VK_INSERT, # INS key
+ "DELETE": Keys.VK_DELETE, # DEL key
+ "DEL": Keys.VK_DELETE, # DEL key
+ "HELP": Keys.VK_HELP, # HELP key
+ "WIN": Keys.VK_LWIN, # Left Windows key (Natural keyboard)
+ "LWIN": Keys.VK_LWIN, # Left Windows key (Natural keyboard)
+ "RWIN": Keys.VK_RWIN, # Right Windows key (Natural keyboard)
+ "APPS": Keys.VK_APPS, # Applications key (Natural keyboard)
+ "SLEEP": Keys.VK_SLEEP, # Computer Sleep key
+ "NUMPAD0": Keys.VK_NUMPAD0, # Numeric keypad 0 key
+ "NUMPAD1": Keys.VK_NUMPAD1, # Numeric keypad 1 key
+ "NUMPAD2": Keys.VK_NUMPAD2, # Numeric keypad 2 key
+ "NUMPAD3": Keys.VK_NUMPAD3, # Numeric keypad 3 key
+ "NUMPAD4": Keys.VK_NUMPAD4, # Numeric keypad 4 key
+ "NUMPAD5": Keys.VK_NUMPAD5, # Numeric keypad 5 key
+ "NUMPAD6": Keys.VK_NUMPAD6, # Numeric keypad 6 key
+ "NUMPAD7": Keys.VK_NUMPAD7, # Numeric keypad 7 key
+ "NUMPAD8": Keys.VK_NUMPAD8, # Numeric keypad 8 key
+ "NUMPAD9": Keys.VK_NUMPAD9, # Numeric keypad 9 key
+ "MULTIPLY": Keys.VK_MULTIPLY, # Multiply key
+ "ADD": Keys.VK_ADD, # Add key
+ "SEPARATOR": Keys.VK_SEPARATOR, # Separator key
+ "SUBTRACT": Keys.VK_SUBTRACT, # Subtract key
+ "DECIMAL": Keys.VK_DECIMAL, # Decimal key
+ "DIVIDE": Keys.VK_DIVIDE, # Divide key
+ "F1": Keys.VK_F1, # F1 key
+ "F2": Keys.VK_F2, # F2 key
+ "F3": Keys.VK_F3, # F3 key
+ "F4": Keys.VK_F4, # F4 key
+ "F5": Keys.VK_F5, # F5 key
+ "F6": Keys.VK_F6, # F6 key
+ "F7": Keys.VK_F7, # F7 key
+ "F8": Keys.VK_F8, # F8 key
+ "F9": Keys.VK_F9, # F9 key
+ "F10": Keys.VK_F10, # F10 key
+ "F11": Keys.VK_F11, # F11 key
+ "F12": Keys.VK_F12, # F12 key
+ "F13": Keys.VK_F13, # F13 key
+ "F14": Keys.VK_F14, # F14 key
+ "F15": Keys.VK_F15, # F15 key
+ "F16": Keys.VK_F16, # F16 key
+ "F17": Keys.VK_F17, # F17 key
+ "F18": Keys.VK_F18, # F18 key
+ "F19": Keys.VK_F19, # F19 key
+ "F20": Keys.VK_F20, # F20 key
+ "F21": Keys.VK_F21, # F21 key
+ "F22": Keys.VK_F22, # F22 key
+ "F23": Keys.VK_F23, # F23 key
+ "F24": Keys.VK_F24, # F24 key
+ "NUMLOCK": Keys.VK_NUMLOCK, # NUM LOCK key
+ "SCROLL": Keys.VK_SCROLL, # SCROLL LOCK key
+ "LSHIFT": Keys.VK_LSHIFT, # Left SHIFT key
+ "RSHIFT": Keys.VK_RSHIFT, # Right SHIFT key
+ "LCONTROL": Keys.VK_LCONTROL, # Left CONTROL key
+ "LCTRL": Keys.VK_LCONTROL, # Left CONTROL key
+ "RCONTROL": Keys.VK_RCONTROL, # Right CONTROL key
+ "RCTRL": Keys.VK_RCONTROL, # Right CONTROL key
+ "LALT": Keys.VK_LMENU, # Left MENU key
+ "RALT": Keys.VK_RMENU, # Right MENU key
+ "BROWSER_BACK": Keys.VK_BROWSER_BACK, # Browser Back key
+ "BROWSER_FORWARD": Keys.VK_BROWSER_FORWARD, # Browser Forward key
+ "BROWSER_REFRESH": Keys.VK_BROWSER_REFRESH, # Browser Refresh key
+ "BROWSER_STOP": Keys.VK_BROWSER_STOP, # Browser Stop key
+ "BROWSER_SEARCH": Keys.VK_BROWSER_SEARCH, # Browser Search key
+ "BROWSER_FAVORITES": Keys.VK_BROWSER_FAVORITES, # Browser Favorites key
+ "BROWSER_HOME": Keys.VK_BROWSER_HOME, # Browser Start and Home key
+ "VOLUME_MUTE": Keys.VK_VOLUME_MUTE, # Volume Mute key
+ "VOLUME_DOWN": Keys.VK_VOLUME_DOWN, # Volume Down key
+ "VOLUME_UP": Keys.VK_VOLUME_UP, # Volume Up key
+ "MEDIA_NEXT_TRACK": Keys.VK_MEDIA_NEXT_TRACK, # Next Track key
+ "MEDIA_PREV_TRACK": Keys.VK_MEDIA_PREV_TRACK, # Previous Track key
+ "MEDIA_STOP": Keys.VK_MEDIA_STOP, # Stop Media key
+ "MEDIA_PLAY_PAUSE": Keys.VK_MEDIA_PLAY_PAUSE, # Play/Pause Media key
+ "LAUNCH_MAIL": Keys.VK_LAUNCH_MAIL, # Start Mail key
+ "LAUNCH_MEDIA_SELECT": Keys.VK_LAUNCH_MEDIA_SELECT, # Select Media key
+ "LAUNCH_APP1": Keys.VK_LAUNCH_APP1, # Start Application 1 key
+ "LAUNCH_APP2": Keys.VK_LAUNCH_APP2, # Start Application 2 key
+ "OEM_1": Keys.VK_OEM_1, # Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the ';:' key
+ "OEM_PLUS": Keys.VK_OEM_PLUS, # For any country/region, the '+' key
+ "OEM_COMMA": Keys.VK_OEM_COMMA, # For any country/region, the ',' key
+ "OEM_MINUS": Keys.VK_OEM_MINUS, # For any country/region, the '-' key
+ "OEM_PERIOD": Keys.VK_OEM_PERIOD, # For any country/region, the '.' key
+ "OEM_2": Keys.VK_OEM_2, # Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the '/?' key
+ "OEM_3": Keys.VK_OEM_3, # Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the '`~' key
+ "OEM_4": Keys.VK_OEM_4, # Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the '[{' key
+ "OEM_5": Keys.VK_OEM_5, # Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the '\|' key
+ "OEM_6": Keys.VK_OEM_6, # Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the ']}' key
+ "OEM_7": Keys.VK_OEM_7, # Used for miscellaneous characters; it can vary by keyboard.For the US standard keyboard, the 'single-quote/double-quote' key
+ "OEM_8": Keys.VK_OEM_8, # Used for miscellaneous characters; it can vary by keyboard.
+ "OEM_102": Keys.VK_OEM_102, # Either the angle bracket key or the backslash key on the RT 102-key keyboard
+ "PROCESSKEY": Keys.VK_PROCESSKEY, # IME PROCESS key
+ "PACKET": Keys.VK_PACKET, # Used to pass Unicode characters as if they were keystrokes. The VK_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, see Remark in KEYBDINPUT, SendInput, WM_KEYDOWN, and WM_KeyUp
+ "ATTN": Keys.VK_ATTN, # Attn key
+ "CRSEL": Keys.VK_CRSEL, # CrSel key
+ "EXSEL": Keys.VK_EXSEL, # ExSel key
+ "EREOF": Keys.VK_EREOF, # Erase EOF key
+ "PLAY": Keys.VK_PLAY, # Play key
+ "ZOOM": Keys.VK_ZOOM, # Zoom key
+ "NONAME": Keys.VK_NONAME, # Reserved
+ "PA1": Keys.VK_PA1, # PA1 key
+ "OEM_CLEAR": Keys.VK_OEM_CLEAR, # Clear key
}
CharacterCodes = {
- '0': Keys.VK_0, #0 key
- '1': Keys.VK_1, #1 key
- '2': Keys.VK_2, #2 key
- '3': Keys.VK_3, #3 key
- '4': Keys.VK_4, #4 key
- '5': Keys.VK_5, #5 key
- '6': Keys.VK_6, #6 key
- '7': Keys.VK_7, #7 key
- '8': Keys.VK_8, #8 key
- '9': Keys.VK_9, #9 key
- 'a': Keys.VK_A, #A key
- 'A': Keys.VK_A, #A key
- 'b': Keys.VK_B, #B key
- 'B': Keys.VK_B, #B key
- 'c': Keys.VK_C, #C key
- 'C': Keys.VK_C, #C key
- 'd': Keys.VK_D, #D key
- 'D': Keys.VK_D, #D key
- 'e': Keys.VK_E, #E key
- 'E': Keys.VK_E, #E key
- 'f': Keys.VK_F, #F key
- 'F': Keys.VK_F, #F key
- 'g': Keys.VK_G, #G key
- 'G': Keys.VK_G, #G key
- 'h': Keys.VK_H, #H key
- 'H': Keys.VK_H, #H key
- 'i': Keys.VK_I, #I key
- 'I': Keys.VK_I, #I key
- 'j': Keys.VK_J, #J key
- 'J': Keys.VK_J, #J key
- 'k': Keys.VK_K, #K key
- 'K': Keys.VK_K, #K key
- 'l': Keys.VK_L, #L key
- 'L': Keys.VK_L, #L key
- 'm': Keys.VK_M, #M key
- 'M': Keys.VK_M, #M key
- 'n': Keys.VK_N, #N key
- 'N': Keys.VK_N, #N key
- 'o': Keys.VK_O, #O key
- 'O': Keys.VK_O, #O key
- 'p': Keys.VK_P, #P key
- 'P': Keys.VK_P, #P key
- 'q': Keys.VK_Q, #Q key
- 'Q': Keys.VK_Q, #Q key
- 'r': Keys.VK_R, #R key
- 'R': Keys.VK_R, #R key
- 's': Keys.VK_S, #S key
- 'S': Keys.VK_S, #S key
- 't': Keys.VK_T, #T key
- 'T': Keys.VK_T, #T key
- 'u': Keys.VK_U, #U key
- 'U': Keys.VK_U, #U key
- 'v': Keys.VK_V, #V key
- 'V': Keys.VK_V, #V key
- 'w': Keys.VK_W, #W key
- 'W': Keys.VK_W, #W key
- 'x': Keys.VK_X, #X key
- 'X': Keys.VK_X, #X key
- 'y': Keys.VK_Y, #Y key
- 'Y': Keys.VK_Y, #Y key
- 'z': Keys.VK_Z, #Z key
- 'Z': Keys.VK_Z, #Z key
- ' ': Keys.VK_SPACE, #Space key
- '`': Keys.VK_OEM_3, #` key
+ "0": Keys.VK_0, # 0 key
+ "1": Keys.VK_1, # 1 key
+ "2": Keys.VK_2, # 2 key
+ "3": Keys.VK_3, # 3 key
+ "4": Keys.VK_4, # 4 key
+ "5": Keys.VK_5, # 5 key
+ "6": Keys.VK_6, # 6 key
+ "7": Keys.VK_7, # 7 key
+ "8": Keys.VK_8, # 8 key
+ "9": Keys.VK_9, # 9 key
+ "a": Keys.VK_A, # A key
+ "A": Keys.VK_A, # A key
+ "b": Keys.VK_B, # B key
+ "B": Keys.VK_B, # B key
+ "c": Keys.VK_C, # C key
+ "C": Keys.VK_C, # C key
+ "d": Keys.VK_D, # D key
+ "D": Keys.VK_D, # D key
+ "e": Keys.VK_E, # E key
+ "E": Keys.VK_E, # E key
+ "f": Keys.VK_F, # F key
+ "F": Keys.VK_F, # F key
+ "g": Keys.VK_G, # G key
+ "G": Keys.VK_G, # G key
+ "h": Keys.VK_H, # H key
+ "H": Keys.VK_H, # H key
+ "i": Keys.VK_I, # I key
+ "I": Keys.VK_I, # I key
+ "j": Keys.VK_J, # J key
+ "J": Keys.VK_J, # J key
+ "k": Keys.VK_K, # K key
+ "K": Keys.VK_K, # K key
+ "l": Keys.VK_L, # L key
+ "L": Keys.VK_L, # L key
+ "m": Keys.VK_M, # M key
+ "M": Keys.VK_M, # M key
+ "n": Keys.VK_N, # N key
+ "N": Keys.VK_N, # N key
+ "o": Keys.VK_O, # O key
+ "O": Keys.VK_O, # O key
+ "p": Keys.VK_P, # P key
+ "P": Keys.VK_P, # P key
+ "q": Keys.VK_Q, # Q key
+ "Q": Keys.VK_Q, # Q key
+ "r": Keys.VK_R, # R key
+ "R": Keys.VK_R, # R key
+ "s": Keys.VK_S, # S key
+ "S": Keys.VK_S, # S key
+ "t": Keys.VK_T, # T key
+ "T": Keys.VK_T, # T key
+ "u": Keys.VK_U, # U key
+ "U": Keys.VK_U, # U key
+ "v": Keys.VK_V, # V key
+ "V": Keys.VK_V, # V key
+ "w": Keys.VK_W, # W key
+ "W": Keys.VK_W, # W key
+ "x": Keys.VK_X, # X key
+ "X": Keys.VK_X, # X key
+ "y": Keys.VK_Y, # Y key
+ "Y": Keys.VK_Y, # Y key
+ "z": Keys.VK_Z, # Z key
+ "Z": Keys.VK_Z, # Z key
+ " ": Keys.VK_SPACE, # Space key
+ "`": Keys.VK_OEM_3, # ` key
#'~' : Keys.VK_OEM_3, #~ key
- '-': Keys.VK_OEM_MINUS, #- key
+ "-": Keys.VK_OEM_MINUS, # - key
#'_' : Keys.VK_OEM_MINUS, #_ key
- '=': Keys.VK_OEM_PLUS, #= key
+ "=": Keys.VK_OEM_PLUS, # = key
#'+' : Keys.VK_OEM_PLUS, #+ key
- '[': Keys.VK_OEM_4, #[ key
+ "[": Keys.VK_OEM_4, # [ key
#'{' : Keys.VK_OEM_4, #{ key
- ']': Keys.VK_OEM_6, #] key
+ "]": Keys.VK_OEM_6, # ] key
#'}' : Keys.VK_OEM_6, #} key
- '\\': Keys.VK_OEM_5, #\ key
+ "\\": Keys.VK_OEM_5, # \ key
#'|' : Keys.VK_OEM_5, #| key
- ';': Keys.VK_OEM_1, #; key
+ ";": Keys.VK_OEM_1, # ; key
#':' : Keys.VK_OEM_1, #: key
- '\'': Keys.VK_OEM_7, #' key
+ "'": Keys.VK_OEM_7, #' key
#'"' : Keys.VK_OEM_7, #" key
- ',': Keys.VK_OEM_COMMA, #, key
+ ",": Keys.VK_OEM_COMMA, # , key
#'<' : Keys.VK_OEM_COMMA, #< key
- '.': Keys.VK_OEM_PERIOD, #. key
+ ".": Keys.VK_OEM_PERIOD, # . key
#'>' : Keys.VK_OEM_PERIOD, #> key
- '/': Keys.VK_OEM_2, #/ key
+ "/": Keys.VK_OEM_2, # / key
#'?' : Keys.VK_OEM_2, #? key
}
class ConsoleScreenBufferInfo(ctypes.Structure):
_fields_ = [
- ('dwSize', ctypes.wintypes._COORD),
- ('dwCursorPosition', ctypes.wintypes._COORD),
- ('wAttributes', ctypes.c_uint),
- ('srWindow', ctypes.wintypes.SMALL_RECT),
- ('dwMaximumWindowSize', ctypes.wintypes._COORD),
+ ("dwSize", ctypes.wintypes._COORD),
+ ("dwCursorPosition", ctypes.wintypes._COORD),
+ ("wAttributes", ctypes.c_uint),
+ ("srWindow", ctypes.wintypes.SMALL_RECT),
+ ("dwMaximumWindowSize", ctypes.wintypes._COORD),
]
class MOUSEINPUT(ctypes.Structure):
- _fields_ = (('dx', ctypes.wintypes.LONG),
- ('dy', ctypes.wintypes.LONG),
- ('mouseData', ctypes.wintypes.DWORD),
- ('dwFlags', ctypes.wintypes.DWORD),
- ('time', ctypes.wintypes.DWORD),
- ('dwExtraInfo', ctypes.wintypes.PULONG))
+ _fields_ = (
+ ("dx", ctypes.wintypes.LONG),
+ ("dy", ctypes.wintypes.LONG),
+ ("mouseData", ctypes.wintypes.DWORD),
+ ("dwFlags", ctypes.wintypes.DWORD),
+ ("time", ctypes.wintypes.DWORD),
+ ("dwExtraInfo", ctypes.wintypes.PULONG),
+ )
class KEYBDINPUT(ctypes.Structure):
- _fields_ = (('wVk', ctypes.wintypes.WORD),
- ('wScan', ctypes.wintypes.WORD),
- ('dwFlags', ctypes.wintypes.DWORD),
- ('time', ctypes.wintypes.DWORD),
- ('dwExtraInfo', ctypes.wintypes.PULONG))
+ _fields_ = (
+ ("wVk", ctypes.wintypes.WORD),
+ ("wScan", ctypes.wintypes.WORD),
+ ("dwFlags", ctypes.wintypes.DWORD),
+ ("time", ctypes.wintypes.DWORD),
+ ("dwExtraInfo", ctypes.wintypes.PULONG),
+ )
class HARDWAREINPUT(ctypes.Structure):
- _fields_ = (('uMsg', ctypes.wintypes.DWORD),
- ('wParamL', ctypes.wintypes.WORD),
- ('wParamH', ctypes.wintypes.WORD))
+ _fields_ = (
+ ("uMsg", ctypes.wintypes.DWORD),
+ ("wParamL", ctypes.wintypes.WORD),
+ ("wParamH", ctypes.wintypes.WORD),
+ )
class INPUTUnion(ctypes.Union):
- _fields_ = (('mi', MOUSEINPUT),
- ('ki', KEYBDINPUT),
- ('hi', HARDWAREINPUT))
+ _fields_ = (("mi", MOUSEINPUT), ("ki", KEYBDINPUT), ("hi", HARDWAREINPUT))
class INPUT(ctypes.Structure):
- _fields_ = (('type', ctypes.wintypes.DWORD),
- ('union', INPUTUnion))
+ _fields_ = (("type", ctypes.wintypes.DWORD), ("union", INPUTUnion))
class Rect:
@@ -1622,8 +1660,13 @@ class Rect:
def contains(self, x: int, y: int) -> bool:
return self.left <= x < self.right and self.top <= y < self.bottom
- def intersect(self, rect: 'Rect') -> 'Rect':
- left, top, right, bottom = max(self.left, rect.left), max(self.top, rect.top), min(self.right, rect.right), min(self.bottom, rect.bottom)
+ def intersect(self, rect: "Rect") -> "Rect":
+ left, top, right, bottom = (
+ max(self.left, rect.left),
+ max(self.top, rect.top),
+ min(self.right, rect.right),
+ min(self.bottom, rect.bottom),
+ )
return Rect(left, top, right, bottom)
def offset(self, x: int, y: int) -> None:
@@ -1633,13 +1676,20 @@ class Rect:
self.bottom += y
def __eq__(self, rect):
- return self.left == rect.left and self.top == rect.top and self.right == rect.right and self.bottom == rect.bottom
+ return (
+ self.left == rect.left
+ and self.top == rect.top
+ and self.right == rect.right
+ and self.bottom == rect.bottom
+ )
def __str__(self) -> str:
- return f'({self.left},{self.top},{self.right},{self.bottom})[{self.width()}x{self.height()}]'
+ return (
+ f"({self.left},{self.top},{self.right},{self.bottom})[{self.width()}x{self.height()}]"
+ )
def __repr__(self) -> str:
- return f'{self.__class__.__name__}({self.left},{self.top},{self.right},{self.bottom})[{self.width()}x{self.height()}]'
+ return f"{self.__class__.__name__}({self.left},{self.top},{self.right},{self.bottom})[{self.width()}x{self.height()}]"
class ClipboardFormat:
@@ -1663,11 +1713,13 @@ class ClipboardFormat:
CF_MAX = 18
CF_HTML = ctypes.windll.user32.RegisterClipboardFormatW("HTML Format")
+
class ActiveEnd(IntEnum):
ActiveEnd_None = 0
ActiveEnd_Start = 1
ActiveEnd_End = 2
+
class AnimationStyle(IntEnum):
AnimationStyle_None = 0
AnimationStyle_LasVegasLights = 1
@@ -1678,15 +1730,18 @@ class AnimationStyle(IntEnum):
AnimationStyle_Shimmer = 6
AnimationStyle_Other = -1
+
class AsyncContentLoadedState(IntEnum):
AsyncContentLoadedState_Beginning = 0
AsyncContentLoadedState_Progress = 1
AsyncContentLoadedState_Completed = 2
+
class AutomationElementMode(IntEnum):
AutomationElementMode_None = 0
AutomationElementMode_Full = 1
+
class AutomationIdentifierType(IntEnum):
AutomationIdentifierType_Property = 0
AutomationIdentifierType_Pattern = 1
@@ -1698,6 +1753,7 @@ class AutomationIdentifierType(IntEnum):
AutomationIdentifierType_Changes = 7
AutomationIdentifierType_Style = 8
+
class BulletStyle(IntEnum):
BulletStyle_None = 0
BulletStyle_HollowRoundBullet = 1
@@ -1707,6 +1763,7 @@ class BulletStyle(IntEnum):
BulletStyle_DashBullet = 5
BulletStyle_Other = -1
+
class CapStyle(IntEnum):
CapStyle_None = 0
CapStyle_SmallCap = 1
@@ -1717,19 +1774,23 @@ class CapStyle(IntEnum):
CapStyle_Titling = 6
CapStyle_Other = -1
+
class CaretBidiMode(IntEnum):
CaretBidiMode_LTR = 0
CaretBidiMode_RTL = 1
+
class CaretPosition(IntEnum):
CaretPosition_Unknown = 0
CaretPosition_EndOfLine = 1
CaretPosition_BeginningOfLine = 2
+
class CoalesceEventsOptions(IntFlag):
CoalesceEventsOptions_Disabled = 0
CoalesceEventsOptions_Enabled = 1
+
class ConditionType(IntEnum):
ConditionType_True = 0
ConditionType_False = 1
@@ -1738,10 +1799,12 @@ class ConditionType(IntEnum):
ConditionType_Or = 4
ConditionType_Not = 5
+
class ConnectionRecoveryBehaviorOptions(IntFlag):
ConnectionRecoveryBehaviorOptions_Disabled = 0
ConnectionRecoveryBehaviorOptions_Enabled = 1
+
class EventArgsType(IntEnum):
EventArgsType_Simple = 0
EventArgsType_PropertyChanged = 1
@@ -1754,6 +1817,7 @@ class EventArgsType(IntEnum):
EventArgsType_ActiveTextPositionChanged = 8
EventArgsType_StructuredMarkup = 9
+
class FillType(IntEnum):
FillType_None = 0
FillType_Color = 1
@@ -1761,22 +1825,26 @@ class FillType(IntEnum):
FillType_Picture = 3
FillType_Pattern = 4
+
class FlowDirections(IntEnum):
FlowDirections_Default = 0
FlowDirections_RightToLeft = 1
FlowDirections_BottomToTop = 2
FlowDirections_Vertical = 4
+
class LiveSetting(IntEnum):
Off = 0
Polite = 1
Assertive = 2
+
class NormalizeState(IntEnum):
NormalizeState_None = 0
NormalizeState_View = 1
NormalizeState_Custom = 2
+
class NotificationKind(IntEnum):
NotificationKind_ItemAdded = 0
NotificationKind_ItemRemoved = 1
@@ -1784,6 +1852,7 @@ class NotificationKind(IntEnum):
NotificationKind_ActionAborted = 3
NotificationKind_Other = 4
+
class NotificationProcessing(IntEnum):
NotificationProcessing_ImportantAll = 0
NotificationProcessing_ImportantMostRecent = 1
@@ -1792,6 +1861,7 @@ class NotificationProcessing(IntEnum):
NotificationProcessing_CurrentThenMostRecent = 4
NotificationProcessing_ImportantCurrentThenMostRecent = 5
+
class OutlineStyles(IntEnum):
OutlineStyles_None = 0
OutlineStyles_Outline = 1
@@ -1799,11 +1869,13 @@ class OutlineStyles(IntEnum):
OutlineStyles_Engraved = 4
OutlineStyles_Embossed = 8
+
class PropertyConditionFlags(IntFlag):
PropertyConditionFlags_None = 0
PropertyConditionFlags_IgnoreCase = 1
PropertyConditionFlags_MatchSubstring = 2
+
class ProviderOptions(IntFlag):
ProviderOptions_ClientSideProvider = 1
ProviderOptions_ServerSideProvider = 2
@@ -1815,11 +1887,13 @@ class ProviderOptions(IntFlag):
ProviderOptions_HasNativeIAccessible = 128
ProviderOptions_UseClientCoordinates = 256
+
class ProviderType(IntEnum):
ProviderType_BaseHwnd = 0
ProviderType_Proxy = 1
ProviderType_NonClientArea = 2
+
class SayAsInterpretAs(IntEnum):
SayAsInterpretAs_None = 0
SayAsInterpretAs_Spell = 1
@@ -1849,6 +1923,7 @@ class SayAsInterpretAs(IntEnum):
SayAsInterpretAs_Time_HoursMinutesSeconds24 = 25
SayAsInterpretAs_Time_HoursMinutes24 = 26
+
class StructureChangeType(IntEnum):
StructureChangeType_ChildAdded = 0
StructureChangeType_ChildRemoved = 1
@@ -1857,11 +1932,13 @@ class StructureChangeType(IntEnum):
StructureChangeType_ChildrenBulkRemoved = 4
StructureChangeType_ChildrenReordered = 5
+
class SupportedTextSelection(IntEnum):
SupportedTextSelection_None = 0
SupportedTextSelection_Single = 1
SupportedTextSelection_Multiple = 2
+
class SynchronizedInputType(IntEnum):
SynchronizedInputType_KeyUp = 1
SynchronizedInputType_KeyDown = 2
@@ -1870,6 +1947,7 @@ class SynchronizedInputType(IntEnum):
SynchronizedInputType_RightMouseUp = 16
SynchronizedInputType_RightMouseDown = 32
+
class TextDecorationLineStyle(IntEnum):
TextDecorationLineStyle_None = 0
TextDecorationLineStyle_Single = 1
@@ -1891,6 +1969,7 @@ class TextDecorationLineStyle(IntEnum):
TextDecorationLineStyle_ThickLongDash = 18
TextDecorationLineStyle_Other = -1
+
class TextEditChangeType(IntEnum):
TextEditChangeType_None = 0
TextEditChangeType_AutoCorrect = 1
@@ -1898,6 +1977,7 @@ class TextEditChangeType(IntEnum):
TextEditChangeType_CompositionFinalized = 3
TextEditChangeType_AutoComplete = 4
+
class TreeScope(IntEnum):
TreeScope_None = 0
TreeScope_Element = 1
@@ -1907,11 +1987,13 @@ class TreeScope(IntEnum):
TreeScope_Ancestors = 16
TreeScope_Subtree = 7
+
class TreeTraversalOptions(IntFlag):
TreeTraversalOptions_Default = 0
TreeTraversalOptions_PostOrder = 1
TreeTraversalOptions_LastToFirstOrder = 2
+
class UIAutomationType(IntEnum):
UIAutomationType_Int = 1
UIAutomationType_Bool = 2
@@ -1944,6 +2026,7 @@ class UIAutomationType(IntEnum):
UIAutomationType_OutRectArray = 131092
UIAutomationType_OutElementArray = 131093
+
class VisualEffects(IntEnum):
VisualEffects_None = 0
VisualEffects_Shadow = 1
@@ -1967,57 +2050,63 @@ class UIAError(IntEnum):
"""
# --- UIA-specific (UIAutomationCoreApi.h) ---
- UIA_E_ELEMENTNOTENABLED = -2147220992 # 0x80040200 — method called on disabled element
- UIA_E_ELEMENTNOTAVAILABLE = -2147220991 # 0x80040201 — element destroyed or virtualized
- UIA_E_NOCLICKABLEPOINT = -2147220990 # 0x80040202 — element has no clickable point
- UIA_E_PROXYASSEMBLYNOTLOADED= -2147220989 # 0x80040203 — client-side proxy provider failed to load
- UIA_E_NOTSUPPORTED = -2147220988 # 0x80040204 — property/pattern not supported by provider
- UIA_E_INVALIDOPERATION = -2146233079 # 0x80131509 — operation not valid in current state
- UIA_E_TIMEOUT = -2146233083 # 0x80131505 — UIA operation timed out
+ UIA_E_ELEMENTNOTENABLED = -2147220992 # 0x80040200 — method called on disabled element
+ UIA_E_ELEMENTNOTAVAILABLE = -2147220991 # 0x80040201 — element destroyed or virtualized
+ UIA_E_NOCLICKABLEPOINT = -2147220990 # 0x80040202 — element has no clickable point
+ UIA_E_PROXYASSEMBLYNOTLOADED = (
+ -2147220989
+ ) # 0x80040203 — client-side proxy provider failed to load
+ UIA_E_NOTSUPPORTED = -2147220988 # 0x80040204 — property/pattern not supported by provider
+ UIA_E_INVALIDOPERATION = -2146233079 # 0x80131509 — operation not valid in current state
+ UIA_E_TIMEOUT = -2146233083 # 0x80131505 — UIA operation timed out
# --- COM+ Event system (Winerror.h) — same hex range as UIA_E, easy to confuse ---
- EVENT_E_ALL_SUBSCRIBERS_FAILED = -2147220991 # 0x80040201 — same code as UIA_E_ELEMENTNOTAVAILABLE; "unable to invoke any subscribers"
- EVENT_E_INTERNALEXCEPTION = -2147220987 # 0x80040205 — unexpected exception in event system
- EVENT_E_USER_EXCEPTION = -2147220984 # 0x80040208 — a subscriber raised an exception
+ EVENT_E_ALL_SUBSCRIBERS_FAILED = (
+ -2147220991
+ ) # 0x80040201 — same code as UIA_E_ELEMENTNOTAVAILABLE; "unable to invoke any subscribers"
+ EVENT_E_INTERNALEXCEPTION = -2147220987 # 0x80040205 — unexpected exception in event system
+ EVENT_E_USER_EXCEPTION = -2147220984 # 0x80040208 — a subscriber raised an exception
# --- Windows Runtime object lifecycle (Winerror.h) ---
- RO_E_CLOSED = -2147483629 # 0x80000013 — object has been closed/disposed
+ RO_E_CLOSED = -2147483629 # 0x80000013 — object has been closed/disposed
# --- COM RPC transport & threading (Winerror.h) ---
- RPC_E_CALL_REJECTED = -2147418111 # 0x80010001 — callee rejected the call (app busy, may retry)
- RPC_E_CALL_CANCELED = -2147418110 # 0x80010002 — call canceled by message filter
- RPC_E_CONNECTION_TERMINATED = -2147418106 # 0x80010006 — connection terminated or in bogus state
- RPC_E_SERVER_DIED = -2147418105 # 0x80010007 — server gone, call may have executed
- RPC_E_SERVER_DIED_DNE = -2147418094 # 0x80010012 — server gone, call did NOT execute
- RPC_E_SYS_CALL_FAILED = -2147417854 # 0x80010100 — underlying system call failed
- RPC_E_OUT_OF_RESOURCES = -2147417855 # 0x80010101 — could not allocate required resource
+ RPC_E_CALL_REJECTED = -2147418111 # 0x80010001 — callee rejected the call (app busy, may retry)
+ RPC_E_CALL_CANCELED = -2147418110 # 0x80010002 — call canceled by message filter
+ RPC_E_CONNECTION_TERMINATED = (
+ -2147418106
+ ) # 0x80010006 — connection terminated or in bogus state
+ RPC_E_SERVER_DIED = -2147418105 # 0x80010007 — server gone, call may have executed
+ RPC_E_SERVER_DIED_DNE = -2147418094 # 0x80010012 — server gone, call did NOT execute
+ RPC_E_SYS_CALL_FAILED = -2147417854 # 0x80010100 — underlying system call failed
+ RPC_E_OUT_OF_RESOURCES = -2147417855 # 0x80010101 — could not allocate required resource
RPC_E_ATTEMPTED_MULTITHREAD = -2147417854 # 0x80010102 — multiple threads in STA mode
- RPC_E_SERVERFAULT = -2147417851 # 0x80010105 — server threw an exception
- RPC_E_CHANGED_MODE = -2147417850 # 0x80010106 — STA/MTA mode conflict on thread
- RPC_E_DISCONNECTED = -2147418360 # 0x80010108 — object invoked has disconnected from clients
+ RPC_E_SERVERFAULT = -2147417851 # 0x80010105 — server threw an exception
+ RPC_E_CHANGED_MODE = -2147417850 # 0x80010106 — STA/MTA mode conflict on thread
+ RPC_E_DISCONNECTED = -2147418360 # 0x80010108 — object invoked has disconnected from clients
RPC_E_SERVERCALL_RETRYLATER = -2147417846 # 0x8001010A — app busy, retry later
- RPC_E_SERVERCALL_REJECTED = -2147417845 # 0x8001010B — message filter rejected the call
- RPC_E_WRONG_THREAD = -2147417842 # 0x8001010E — interface marshalled for a different thread
- RPC_E_THREAD_NOT_INIT = -2147417841 # 0x8001010F — CoInitialize not called on current thread
- RPC_E_TIMEOUT = -2147417825 # 0x8001011F — RPC-level operation timed out
- RPC_E_UNEXPECTED = -2147352577 # 0x8001FFFF — internal RPC error
+ RPC_E_SERVERCALL_REJECTED = -2147417845 # 0x8001010B — message filter rejected the call
+ RPC_E_WRONG_THREAD = -2147417842 # 0x8001010E — interface marshalled for a different thread
+ RPC_E_THREAD_NOT_INIT = -2147417841 # 0x8001010F — CoInitialize not called on current thread
+ RPC_E_TIMEOUT = -2147417825 # 0x8001011F — RPC-level operation timed out
+ RPC_E_UNEXPECTED = -2147352577 # 0x8001FFFF — internal RPC error
# --- COM object state (Winerror.h) ---
- CO_E_OBJNOTCONNECTED = -2147220995 # 0x800401FD — object not connected to server
- CO_E_RELEASED = -2147220993 # 0x800401FF — object has been released
- CO_E_NOTINITIALIZED = -2147220496 # 0x800401F0 — CoInitialize not called
+ CO_E_OBJNOTCONNECTED = -2147220995 # 0x800401FD — object not connected to server
+ CO_E_RELEASED = -2147220993 # 0x800401FF — object has been released
+ CO_E_NOTINITIALIZED = -2147220496 # 0x800401F0 — CoInitialize not called
# --- Generic COM (Winerror.h) ---
- E_NOTIMPL = -2147467263 # 0x80004001 — not implemented
- E_NOINTERFACE = -2147467262 # 0x80004002 — interface not supported
- E_ABORT = -2147467260 # 0x80004004 — operation aborted
- E_FAIL = -2147467259 # 0x80004005 — unspecified failure
- RPC_E_ACCESS_DENIED = -2147417829 # 0x8001011B — RPC-level access denied
- E_ACCESSDENIED = -2147024891 # 0x80070005 — access denied
- E_OUTOFMEMORY = -2147024882 # 0x8007000E — out of memory
- E_INVALIDARG = -2147024809 # 0x80070057 — invalid argument
- E_UNEXPECTED = -2147418113 # 0x8000FFFF — catastrophic/unexpected failure
- E_POINTER = -2147467261 # 0x80004003 — invalid pointer
+ E_NOTIMPL = -2147467263 # 0x80004001 — not implemented
+ E_NOINTERFACE = -2147467262 # 0x80004002 — interface not supported
+ E_ABORT = -2147467260 # 0x80004004 — operation aborted
+ E_FAIL = -2147467259 # 0x80004005 — unspecified failure
+ RPC_E_ACCESS_DENIED = -2147417829 # 0x8001011B — RPC-level access denied
+ E_ACCESSDENIED = -2147024891 # 0x80070005 — access denied
+ E_OUTOFMEMORY = -2147024882 # 0x8007000E — out of memory
+ E_INVALIDARG = -2147024809 # 0x80070057 — invalid argument
+ E_UNEXPECTED = -2147418113 # 0x8000FFFF — catastrophic/unexpected failure
+ E_POINTER = -2147467261 # 0x80004003 — invalid pointer
def is_dead_element_error(code: int) -> bool:
@@ -2041,4 +2130,3 @@ def is_retryable_error(code: int) -> bool:
UIAError.RPC_E_SERVERCALL_RETRYLATER,
UIAError.RPC_E_SERVERCALL_REJECTED,
}
-
diff --git a/windows_use/uia/events.py b/windows_use/uia/events.py
index a44e539..c5c23af 100644
--- a/windows_use/uia/events.py
+++ b/windows_use/uia/events.py
@@ -1,9 +1,9 @@
-
class EventId:
"""
EventId from IUIAutomation.
Refer https://docs.microsoft.com/en-us/windows/win32/winauto/uiauto-event-ids
"""
+
UIA_ToolTipOpenedEventId = 20000
UIA_ToolTipClosedEventId = 20001
UIA_StructureChangedEventId = 20002
@@ -42,42 +42,43 @@ class EventId:
UIA_NotificationEventId = 20035
UIA_ActiveTextPositionChangedEventId = 20036
+
EventIdNames = {
- EventId.UIA_ToolTipOpenedEventId: 'UIA_ToolTipOpenedEventId',
- EventId.UIA_ToolTipClosedEventId: 'UIA_ToolTipClosedEventId',
- EventId.UIA_StructureChangedEventId: 'UIA_StructureChangedEventId',
- EventId.UIA_MenuOpenedEventId: 'UIA_MenuOpenedEventId',
- EventId.UIA_AutomationPropertyChangedEventId: 'UIA_AutomationPropertyChangedEventId',
- EventId.UIA_AutomationFocusChangedEventId: 'UIA_AutomationFocusChangedEventId',
- EventId.UIA_AsyncContentLoadedEventId: 'UIA_AsyncContentLoadedEventId',
- EventId.UIA_MenuClosedEventId: 'UIA_MenuClosedEventId',
- EventId.UIA_LayoutInvalidatedEventId: 'UIA_LayoutInvalidatedEventId',
- EventId.UIA_Invoke_InvokedEventId: 'UIA_Invoke_InvokedEventId',
- EventId.UIA_SelectionItem_ElementAddedToSelectionEventId: 'UIA_SelectionItem_ElementAddedToSelectionEventId',
- EventId.UIA_SelectionItem_ElementRemovedFromSelectionEventId: 'UIA_SelectionItem_ElementRemovedFromSelectionEventId',
- EventId.UIA_SelectionItem_ElementSelectedEventId: 'UIA_SelectionItem_ElementSelectedEventId',
- EventId.UIA_Selection_InvalidatedEventId: 'UIA_Selection_InvalidatedEventId',
- EventId.UIA_Text_TextSelectionChangedEventId: 'UIA_Text_TextSelectionChangedEventId',
- EventId.UIA_Text_TextChangedEventId: 'UIA_Text_TextChangedEventId',
- EventId.UIA_Window_WindowOpenedEventId: 'UIA_Window_WindowOpenedEventId',
- EventId.UIA_Window_WindowClosedEventId: 'UIA_Window_WindowClosedEventId',
- EventId.UIA_MenuModeStartEventId: 'UIA_MenuModeStartEventId',
- EventId.UIA_MenuModeEndEventId: 'UIA_MenuModeEndEventId',
- EventId.UIA_InputReachedTargetEventId: 'UIA_InputReachedTargetEventId',
- EventId.UIA_InputReachedOtherElementEventId: 'UIA_InputReachedOtherElementEventId',
- EventId.UIA_InputDiscardedEventId: 'UIA_InputDiscardedEventId',
- EventId.UIA_SystemAlertEventId: 'UIA_SystemAlertEventId',
- EventId.UIA_LiveRegionChangedEventId: 'UIA_LiveRegionChangedEventId',
- EventId.UIA_HostedFragmentRootsInvalidatedEventId: 'UIA_HostedFragmentRootsInvalidatedEventId',
- EventId.UIA_Drag_DragStartEventId: 'UIA_Drag_DragStartEventId',
- EventId.UIA_Drag_DragCancelEventId: 'UIA_Drag_DragCancelEventId',
- EventId.UIA_Drag_DragCompleteEventId: 'UIA_Drag_DragCompleteEventId',
- EventId.UIA_DropTarget_DragEnterEventId: 'UIA_DropTarget_DragEnterEventId',
- EventId.UIA_DropTarget_DragLeaveEventId: 'UIA_DropTarget_DragLeaveEventId',
- EventId.UIA_DropTarget_DroppedEventId: 'UIA_DropTarget_DroppedEventId',
- EventId.UIA_TextEdit_TextChangedEventId: 'UIA_TextEdit_TextChangedEventId',
- EventId.UIA_TextEdit_ConversionTargetChangedEventId: 'UIA_TextEdit_ConversionTargetChangedEventId',
- EventId.UIA_ChangesEventId: 'UIA_ChangesEventId',
- EventId.UIA_NotificationEventId: 'UIA_NotificationEventId',
- EventId.UIA_ActiveTextPositionChangedEventId: 'UIA_ActiveTextPositionChangedEventId',
+ EventId.UIA_ToolTipOpenedEventId: "UIA_ToolTipOpenedEventId",
+ EventId.UIA_ToolTipClosedEventId: "UIA_ToolTipClosedEventId",
+ EventId.UIA_StructureChangedEventId: "UIA_StructureChangedEventId",
+ EventId.UIA_MenuOpenedEventId: "UIA_MenuOpenedEventId",
+ EventId.UIA_AutomationPropertyChangedEventId: "UIA_AutomationPropertyChangedEventId",
+ EventId.UIA_AutomationFocusChangedEventId: "UIA_AutomationFocusChangedEventId",
+ EventId.UIA_AsyncContentLoadedEventId: "UIA_AsyncContentLoadedEventId",
+ EventId.UIA_MenuClosedEventId: "UIA_MenuClosedEventId",
+ EventId.UIA_LayoutInvalidatedEventId: "UIA_LayoutInvalidatedEventId",
+ EventId.UIA_Invoke_InvokedEventId: "UIA_Invoke_InvokedEventId",
+ EventId.UIA_SelectionItem_ElementAddedToSelectionEventId: "UIA_SelectionItem_ElementAddedToSelectionEventId",
+ EventId.UIA_SelectionItem_ElementRemovedFromSelectionEventId: "UIA_SelectionItem_ElementRemovedFromSelectionEventId",
+ EventId.UIA_SelectionItem_ElementSelectedEventId: "UIA_SelectionItem_ElementSelectedEventId",
+ EventId.UIA_Selection_InvalidatedEventId: "UIA_Selection_InvalidatedEventId",
+ EventId.UIA_Text_TextSelectionChangedEventId: "UIA_Text_TextSelectionChangedEventId",
+ EventId.UIA_Text_TextChangedEventId: "UIA_Text_TextChangedEventId",
+ EventId.UIA_Window_WindowOpenedEventId: "UIA_Window_WindowOpenedEventId",
+ EventId.UIA_Window_WindowClosedEventId: "UIA_Window_WindowClosedEventId",
+ EventId.UIA_MenuModeStartEventId: "UIA_MenuModeStartEventId",
+ EventId.UIA_MenuModeEndEventId: "UIA_MenuModeEndEventId",
+ EventId.UIA_InputReachedTargetEventId: "UIA_InputReachedTargetEventId",
+ EventId.UIA_InputReachedOtherElementEventId: "UIA_InputReachedOtherElementEventId",
+ EventId.UIA_InputDiscardedEventId: "UIA_InputDiscardedEventId",
+ EventId.UIA_SystemAlertEventId: "UIA_SystemAlertEventId",
+ EventId.UIA_LiveRegionChangedEventId: "UIA_LiveRegionChangedEventId",
+ EventId.UIA_HostedFragmentRootsInvalidatedEventId: "UIA_HostedFragmentRootsInvalidatedEventId",
+ EventId.UIA_Drag_DragStartEventId: "UIA_Drag_DragStartEventId",
+ EventId.UIA_Drag_DragCancelEventId: "UIA_Drag_DragCancelEventId",
+ EventId.UIA_Drag_DragCompleteEventId: "UIA_Drag_DragCompleteEventId",
+ EventId.UIA_DropTarget_DragEnterEventId: "UIA_DropTarget_DragEnterEventId",
+ EventId.UIA_DropTarget_DragLeaveEventId: "UIA_DropTarget_DragLeaveEventId",
+ EventId.UIA_DropTarget_DroppedEventId: "UIA_DropTarget_DroppedEventId",
+ EventId.UIA_TextEdit_TextChangedEventId: "UIA_TextEdit_TextChangedEventId",
+ EventId.UIA_TextEdit_ConversionTargetChangedEventId: "UIA_TextEdit_ConversionTargetChangedEventId",
+ EventId.UIA_ChangesEventId: "UIA_ChangesEventId",
+ EventId.UIA_NotificationEventId: "UIA_NotificationEventId",
+ EventId.UIA_ActiveTextPositionChangedEventId: "UIA_ActiveTextPositionChangedEventId",
}
diff --git a/windows_use/uia/exceptions.py b/windows_use/uia/exceptions.py
index edae008..9bda18c 100644
--- a/windows_use/uia/exceptions.py
+++ b/windows_use/uia/exceptions.py
@@ -9,7 +9,9 @@ class UIAException(Exception):
def __init__(self, code: int, original: Exception | None = None):
self.code = code
self.original = original
- name = UIAError(code).name if code in UIAError._value2member_map_ else hex(code & 0xFFFFFFFF)
+ name = (
+ UIAError(code).name if code in UIAError._value2member_map_ else hex(code & 0xFFFFFFFF)
+ )
super().__init__(f"{name} ({code})")
@property
@@ -86,32 +88,28 @@ _RETRYABLE_CODES = {
}
_CODE_TO_EXCEPTION: dict[int, type[UIAException]] = {
- UIAError.UIA_E_ELEMENTNOTAVAILABLE: UIADeadElementError,
- UIAError.RO_E_CLOSED: UIADeadElementError,
- UIAError.RPC_E_DISCONNECTED: UIADeadElementError,
- UIAError.RPC_E_SERVER_DIED: UIADeadElementError,
- UIAError.RPC_E_SERVER_DIED_DNE: UIADeadElementError,
+ UIAError.UIA_E_ELEMENTNOTAVAILABLE: UIADeadElementError,
+ UIAError.RO_E_CLOSED: UIADeadElementError,
+ UIAError.RPC_E_DISCONNECTED: UIADeadElementError,
+ UIAError.RPC_E_SERVER_DIED: UIADeadElementError,
+ UIAError.RPC_E_SERVER_DIED_DNE: UIADeadElementError,
UIAError.RPC_E_CONNECTION_TERMINATED: UIADeadElementError,
- UIAError.CO_E_OBJNOTCONNECTED: UIADeadElementError,
- UIAError.CO_E_RELEASED: UIADeadElementError,
-
- UIAError.RPC_E_CALL_REJECTED: UIARetryableError,
+ UIAError.CO_E_OBJNOTCONNECTED: UIADeadElementError,
+ UIAError.CO_E_RELEASED: UIADeadElementError,
+ UIAError.RPC_E_CALL_REJECTED: UIARetryableError,
UIAError.RPC_E_SERVERCALL_RETRYLATER: UIARetryableError,
- UIAError.RPC_E_SERVERCALL_REJECTED: UIARetryableError,
-
- UIAError.UIA_E_ELEMENTNOTENABLED: UIANotEnabledError,
- UIAError.UIA_E_NOTSUPPORTED: UIANotSupportedError,
- UIAError.UIA_E_NOCLICKABLEPOINT: UIANoClickablePointError,
- UIAError.UIA_E_TIMEOUT: UIATimeoutError,
- UIAError.RPC_E_TIMEOUT: UIATimeoutError,
- UIAError.UIA_E_INVALIDOPERATION: UIAInvalidOperationError,
-
- UIAError.RPC_E_WRONG_THREAD: UIAThreadError,
- UIAError.RPC_E_THREAD_NOT_INIT: UIAThreadError,
- UIAError.RPC_E_CHANGED_MODE: UIAThreadError,
-
- UIAError.E_ACCESSDENIED: UIAAccessDeniedError,
- UIAError.RPC_E_ACCESS_DENIED: UIAAccessDeniedError,
+ UIAError.RPC_E_SERVERCALL_REJECTED: UIARetryableError,
+ UIAError.UIA_E_ELEMENTNOTENABLED: UIANotEnabledError,
+ UIAError.UIA_E_NOTSUPPORTED: UIANotSupportedError,
+ UIAError.UIA_E_NOCLICKABLEPOINT: UIANoClickablePointError,
+ UIAError.UIA_E_TIMEOUT: UIATimeoutError,
+ UIAError.RPC_E_TIMEOUT: UIATimeoutError,
+ UIAError.UIA_E_INVALIDOPERATION: UIAInvalidOperationError,
+ UIAError.RPC_E_WRONG_THREAD: UIAThreadError,
+ UIAError.RPC_E_THREAD_NOT_INIT: UIAThreadError,
+ UIAError.RPC_E_CHANGED_MODE: UIAThreadError,
+ UIAError.E_ACCESSDENIED: UIAAccessDeniedError,
+ UIAError.RPC_E_ACCESS_DENIED: UIAAccessDeniedError,
}
diff --git a/windows_use/uia/patterns.py b/windows_use/uia/patterns.py
index 6f0f299..a975d26 100644
--- a/windows_use/uia/patterns.py
+++ b/windows_use/uia/patterns.py
@@ -1,4 +1,4 @@
-'''
+"""
uiautomation for Python 3.
Author: yinkaisheng
Source: https://github.com/yinkaisheng/Python-UIAutomation-for-Windows
@@ -9,7 +9,7 @@ Run 'automation.py -h' for help.
uiautomation is shared under the Apache Licene 2.0.
This means that the code can be freely copied and distributed, and costs nothing to use.
-'''
+"""
import ctypes
import os
@@ -25,7 +25,7 @@ if TYPE_CHECKING:
from .controls import Control
-METRO_WINDOW_CLASS_NAME = 'Windows.UI.Core.CoreWindow' # for Windows 8 and 8.1
+METRO_WINDOW_CLASS_NAME = "Windows.UI.Core.CoreWindow" # for Windows 8 and 8.1
SEARCH_INTERVAL = 0.5 # search control interval seconds
MAX_MOVE_SECOND = 1 # simulate mouse move or drag max seconds
TIME_OUT_SECOND = 10
@@ -92,55 +92,81 @@ def GetPatternIdInterface(patternId: int):
}
# the following patterns doesn't exist on Windows 7 or lower
try:
- _PatternIdInterfaces[PatternId.AnnotationPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationAnnotationPattern
+ _PatternIdInterfaces[PatternId.AnnotationPattern] = (
+ _AutomationClient.instance().UIAutomationCore.IUIAutomationAnnotationPattern
+ )
except:
pass
try:
- _PatternIdInterfaces[PatternId.CustomNavigationPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationCustomNavigationPattern
+ _PatternIdInterfaces[PatternId.CustomNavigationPattern] = (
+ _AutomationClient.instance().UIAutomationCore.IUIAutomationCustomNavigationPattern
+ )
except:
pass
try:
- _PatternIdInterfaces[PatternId.DragPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationDragPattern
+ _PatternIdInterfaces[PatternId.DragPattern] = (
+ _AutomationClient.instance().UIAutomationCore.IUIAutomationDragPattern
+ )
except:
pass
try:
- _PatternIdInterfaces[PatternId.DropTargetPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationDropTargetPattern
+ _PatternIdInterfaces[PatternId.DropTargetPattern] = (
+ _AutomationClient.instance().UIAutomationCore.IUIAutomationDropTargetPattern
+ )
except:
pass
try:
- _PatternIdInterfaces[PatternId.ObjectModelPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationObjectModelPattern
+ _PatternIdInterfaces[PatternId.ObjectModelPattern] = (
+ _AutomationClient.instance().UIAutomationCore.IUIAutomationObjectModelPattern
+ )
except:
pass
try:
- _PatternIdInterfaces[PatternId.SpreadsheetItemPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationSpreadsheetItemPattern
+ _PatternIdInterfaces[PatternId.SpreadsheetItemPattern] = (
+ _AutomationClient.instance().UIAutomationCore.IUIAutomationSpreadsheetItemPattern
+ )
except:
pass
try:
- _PatternIdInterfaces[PatternId.SpreadsheetPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationSpreadsheetPattern
+ _PatternIdInterfaces[PatternId.SpreadsheetPattern] = (
+ _AutomationClient.instance().UIAutomationCore.IUIAutomationSpreadsheetPattern
+ )
except:
pass
try:
- _PatternIdInterfaces[PatternId.StylesPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationStylesPattern
+ _PatternIdInterfaces[PatternId.StylesPattern] = (
+ _AutomationClient.instance().UIAutomationCore.IUIAutomationStylesPattern
+ )
except:
pass
try:
- _PatternIdInterfaces[PatternId.SelectionPattern2] = _AutomationClient.instance().UIAutomationCore.IUIAutomationSelectionPattern2
+ _PatternIdInterfaces[PatternId.SelectionPattern2] = (
+ _AutomationClient.instance().UIAutomationCore.IUIAutomationSelectionPattern2
+ )
except:
pass
try:
- _PatternIdInterfaces[PatternId.TextChildPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationTextChildPattern
+ _PatternIdInterfaces[PatternId.TextChildPattern] = (
+ _AutomationClient.instance().UIAutomationCore.IUIAutomationTextChildPattern
+ )
except:
pass
try:
- _PatternIdInterfaces[PatternId.TextEditPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationTextEditPattern
+ _PatternIdInterfaces[PatternId.TextEditPattern] = (
+ _AutomationClient.instance().UIAutomationCore.IUIAutomationTextEditPattern
+ )
except:
pass
try:
- _PatternIdInterfaces[PatternId.TextPattern2] = _AutomationClient.instance().UIAutomationCore.IUIAutomationTextPattern2
+ _PatternIdInterfaces[PatternId.TextPattern2] = (
+ _AutomationClient.instance().UIAutomationCore.IUIAutomationTextPattern2
+ )
except:
pass
try:
- _PatternIdInterfaces[PatternId.TransformPattern2] = _AutomationClient.instance().UIAutomationCore.IUIAutomationTransformPattern2
+ _PatternIdInterfaces[PatternId.TransformPattern2] = (
+ _AutomationClient.instance().UIAutomationCore.IUIAutomationTransformPattern2
+ )
except:
pass
return _PatternIdInterfaces[patternId]
@@ -195,7 +221,7 @@ class AnnotationPattern:
return self.pattern.CurrentDateTime
@property
- def Target(self) -> 'Control':
+ def Target(self) -> "Control":
"""
Property Target.
Call IUIAutomationAnnotationPattern::get_CurrentTarget.
@@ -211,7 +237,7 @@ class CustomNavigationPattern:
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationcustomnavigationpattern"""
self.pattern = pattern
- def Navigate(self, direction: int) -> 'Control':
+ def Navigate(self, direction: int) -> "Control":
"""
Call IUIAutomationCustomNavigationPattern::Navigate.
Get the next control in the specified direction within the logical UI tree.
@@ -287,7 +313,7 @@ class DragPattern:
"""
return bool(self.pattern.CurrentIsGrabbed)
- def GetGrabbedItems(self) -> list['Control']:
+ def GetGrabbedItems(self) -> list["Control"]:
"""
Call IUIAutomationDragPattern::GetCurrentGrabbedItems.
Return List[Control], a list of `Control` subclasses that represent the full set of items
@@ -407,7 +433,7 @@ class GridItemPattern:
return self.pattern.CurrentColumnSpan
@property
- def ContainingGrid(self) -> 'Control':
+ def ContainingGrid(self) -> "Control":
"""
Property ContainingGrid.
Call IUIAutomationGridItemPattern::get_CurrentContainingGrid.
@@ -462,7 +488,7 @@ class GridPattern:
"""
return self.pattern.CurrentRowCount
- def GetItem(self, row: int, column: int) -> 'Control':
+ def GetItem(self, row: int, column: int) -> "Control":
"""
Call IUIAutomationGridPattern::GetItem.
Return `Control` subclass, a control representing an item in the grid.
@@ -494,7 +520,7 @@ class ItemContainerPattern:
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationitemcontainerpattern"""
self.pattern = pattern
- def FindItemByProperty(self, control: 'Control', propertyId: int, propertyValue) -> 'Control':
+ def FindItemByProperty(self, control: "Control", propertyId: int, propertyValue) -> "Control":
"""
Call IUIAutomationItemContainerPattern::FindItemByProperty.
control: `Control` or its subclass.
@@ -570,7 +596,7 @@ class LegacyIAccessiblePattern:
Return str, the Microsoft Active Accessibility name property of the element.
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationlegacyiaccessiblepattern-get_currentname
"""
- return self.pattern.CurrentName or '' # CurrentName may be None
+ return self.pattern.CurrentName or "" # CurrentName may be None
@property
def Role(self) -> int:
@@ -614,7 +640,7 @@ class LegacyIAccessiblePattern:
time.sleep(waitTime)
return ret
- def GetSelection(self) -> list['Control']:
+ def GetSelection(self) -> list["Control"]:
"""
Call IUIAutomationLegacyIAccessiblePattern::GetCurrentSelection.
Return List[Control], a list of `Control` subclasses,
@@ -890,7 +916,9 @@ class ScrollPattern:
"""
return self.pattern.CurrentVerticalViewSize
- def Scroll(self, horizontalAmount: int, verticalAmount: int, waitTime: float = OPERATION_WAIT_TIME) -> bool:
+ def Scroll(
+ self, horizontalAmount: int, verticalAmount: int, waitTime: float = OPERATION_WAIT_TIME
+ ) -> bool:
"""
Call IUIAutomationScrollPattern::Scroll.
Scroll the visible region of the content area horizontally and vertically.
@@ -904,7 +932,12 @@ class ScrollPattern:
time.sleep(waitTime)
return ret
- def SetScrollPercent(self, horizontalPercent: float, verticalPercent: float, waitTime: float = OPERATION_WAIT_TIME) -> bool:
+ def SetScrollPercent(
+ self,
+ horizontalPercent: float,
+ verticalPercent: float,
+ waitTime: float = OPERATION_WAIT_TIME,
+ ) -> bool:
"""
Call IUIAutomationScrollPattern::SetScrollPercent.
Set the horizontal and vertical scroll positions as a percentage of the total content area within the UI Automation element.
@@ -947,7 +980,7 @@ class SelectionItemPattern:
return bool(self.pattern.CurrentIsSelected)
@property
- def SelectionContainer(self) -> 'Control':
+ def SelectionContainer(self) -> "Control":
"""
Property SelectionContainer.
Call IUIAutomationScrollPattern::get_CurrentSelectionContainer.
@@ -1007,7 +1040,7 @@ class SelectionPattern:
"""
return bool(self.pattern.CurrentIsSelectionRequired)
- def GetSelection(self) -> list['Control']:
+ def GetSelection(self) -> list["Control"]:
"""
Call IUIAutomationSelectionPattern::GetCurrentSelection.
Return List[Control], a list of `Control` subclasses, the selected elements in the container..
@@ -1029,6 +1062,7 @@ class SelectionPattern2(SelectionPattern):
"""
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationselectionpattern2
"""
+
def __init__(self, pattern=None):
super().__init__(pattern)
@@ -1086,7 +1120,7 @@ class SpreadsheetItemPattern:
"""
return self.pattern.CurrentFormula
- def GetAnnotationObjects(self) -> list['Control']:
+ def GetAnnotationObjects(self) -> list["Control"]:
"""
Call IUIAutomationSelectionPattern::GetCurrentAnnotationObjects.
Return List[Control], a list of `Control` subclasses representing the annotations associated with this spreadsheet cell.
@@ -1118,7 +1152,7 @@ class SpreadsheetPattern:
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationspreadsheetpattern"""
self.pattern = pattern
- def GetItemByName(self, name: str) -> 'Control':
+ def GetItemByName(self, name: str) -> "Control":
"""
Call IUIAutomationSpreadsheetPattern::GetItemByName.
name: str.
@@ -1224,7 +1258,7 @@ class TableItemPattern:
"""Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nn-uiautomationclient-iuiautomationtableitempattern"""
self.pattern = pattern
- def GetColumnHeaderItems(self) -> list['Control']:
+ def GetColumnHeaderItems(self) -> list["Control"]:
"""
Call IUIAutomationTableItemPattern::GetCurrentColumnHeaderItems.
Return List[Control], a list of `Control` subclasses, the column headers associated with a table item or cell.
@@ -1241,7 +1275,7 @@ class TableItemPattern:
return controls
return []
- def GetRowHeaderItems(self) -> list['Control']:
+ def GetRowHeaderItems(self) -> list["Control"]:
"""
Call IUIAutomationTableItemPattern::GetCurrentRowHeaderItems.
Return List[Control], a list of `Control` subclasses, the row headers associated with a table item or cell.
@@ -1274,7 +1308,7 @@ class TablePattern:
"""
return self.pattern.CurrentRowOrColumnMajor
- def GetColumnHeaders(self) -> list['Control']:
+ def GetColumnHeaders(self) -> list["Control"]:
"""
Call IUIAutomationTablePattern::GetCurrentColumnHeaders.
Return List[Control], a list of `Control` subclasses, representing all the column headers in a table..
@@ -1291,7 +1325,7 @@ class TablePattern:
return controls
return []
- def GetRowHeaders(self) -> list['Control']:
+ def GetRowHeaders(self) -> list["Control"]:
"""
Call IUIAutomationTablePattern::GetCurrentRowHeaders.
Return List[Control], a list of `Control` subclasses, representing all the row headers in a table.
@@ -1328,7 +1362,7 @@ class TextRange:
time.sleep(waitTime)
return ret
- def Clone(self) -> 'TextRange':
+ def Clone(self) -> "TextRange":
"""
Call IUIAutomationTextRange::Clone.
return `TextRange`, identical to the original and inheriting all properties of the original.
@@ -1336,7 +1370,7 @@ class TextRange:
"""
return TextRange(textRange=self.textRange.Clone())
- def Compare(self, textRange: 'TextRange') -> bool:
+ def Compare(self, textRange: "TextRange") -> bool:
"""
Call IUIAutomationTextRange::Compare.
textRange: `TextRange`.
@@ -1345,7 +1379,9 @@ class TextRange:
"""
return bool(self.textRange.Compare(textRange.textRange))
- def CompareEndpoints(self, srcEndPoint: int, textRange: 'TextRange', targetEndPoint: int) -> int:
+ def CompareEndpoints(
+ self, srcEndPoint: int, textRange: "TextRange", targetEndPoint: int
+ ) -> int:
"""
Call IUIAutomationTextRange::CompareEndpoints.
srcEndPoint: int, a value in class `TextPatternRangeEndpoint`.
@@ -1373,7 +1409,7 @@ class TextRange:
time.sleep(waitTime)
return ret
- def FindAttribute(self, textAttributeId: int, val, backward: bool) -> Optional['TextRange']:
+ def FindAttribute(self, textAttributeId: int, val, backward: bool) -> Optional["TextRange"]:
"""
Call IUIAutomationTextRange::FindAttribute.
textAttributeID: int, a value in class `TextAttributeId`.
@@ -1387,7 +1423,7 @@ class TextRange:
return TextRange(textRange=textRange)
return None
- def FindText(self, text: str, backward: bool, ignoreCase: bool) -> Optional['TextRange']:
+ def FindText(self, text: str, backward: bool, ignoreCase: bool) -> Optional["TextRange"]:
"""
Call IUIAutomationTextRange::FindText.
text: str,
@@ -1424,12 +1460,16 @@ class TextRange:
floats = self.textRange.GetBoundingRectangles()
rects = []
for i in range(len(floats) // 4):
- rect = Rect(int(floats[i * 4]), int(floats[i * 4 + 1]),
- int(floats[i * 4]) + int(floats[i * 4 + 2]), int(floats[i * 4 + 1]) + int(floats[i * 4 + 3]))
+ rect = Rect(
+ int(floats[i * 4]),
+ int(floats[i * 4 + 1]),
+ int(floats[i * 4]) + int(floats[i * 4 + 2]),
+ int(floats[i * 4 + 1]) + int(floats[i * 4 + 3]),
+ )
rects.append(rect)
return rects
- def GetChildren(self) -> list['Control']:
+ def GetChildren(self) -> list["Control"]:
"""
Call IUIAutomationTextRange::GetChildren.
textAttributeId: int, a value in class `TextAttributeId`.
@@ -1447,7 +1487,7 @@ class TextRange:
return controls
return []
- def GetEnclosingControl(self) -> 'Control':
+ def GetEnclosingControl(self) -> "Control":
"""
Call IUIAutomationTextRange::GetEnclosingElement.
Return `Control` subclass, the innermost UI Automation element that encloses the text range.
@@ -1480,7 +1520,13 @@ class TextRange:
time.sleep(waitTime)
return ret
- def MoveEndpointByRange(self, srcEndPoint: int, textRange: 'TextRange', targetEndPoint: int, waitTime: float = OPERATION_WAIT_TIME) -> bool:
+ def MoveEndpointByRange(
+ self,
+ srcEndPoint: int,
+ textRange: "TextRange",
+ targetEndPoint: int,
+ waitTime: float = OPERATION_WAIT_TIME,
+ ) -> bool:
"""
Call IUIAutomationTextRange::MoveEndpointByRange.
Move one endpoint of the current text range to the specified endpoint of a second text range.
@@ -1491,11 +1537,16 @@ class TextRange:
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange-moveendpointbyrange
"""
- ret = self.textRange.MoveEndpointByRange(srcEndPoint, textRange.textRange, targetEndPoint) == S_OK
+ ret = (
+ self.textRange.MoveEndpointByRange(srcEndPoint, textRange.textRange, targetEndPoint)
+ == S_OK
+ )
time.sleep(waitTime)
return ret
- def MoveEndpointByUnit(self, endPoint: int, unit: int, count: int, waitTime: float = OPERATION_WAIT_TIME) -> int:
+ def MoveEndpointByUnit(
+ self, endPoint: int, unit: int, count: int, waitTime: float = OPERATION_WAIT_TIME
+ ) -> int:
"""
Call IUIAutomationTextRange::MoveEndpointByUnit.
Move one endpoint of the text range the specified number of text units within the document range.
@@ -1558,7 +1609,7 @@ class TextChildPattern:
self.pattern = pattern
@property
- def TextContainer(self) -> 'Control':
+ def TextContainer(self) -> "Control":
"""
Property TextContainer.
Call IUIAutomationSelectionContainer::get_TextContainer.
@@ -2027,14 +2078,14 @@ class WindowPattern:
return ret
def WaitForInputIdle(self, milliseconds: int) -> bool:
- '''
+ """
Call IUIAutomationWindowPattern::WaitForInputIdle.
Cause the calling code to block for the specified time or
until the associated process enters an idle state, whichever completes first.
milliseconds: int.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationwindowpattern-waitforinputidle
- '''
+ """
return self.pattern.WaitForInputIdle(milliseconds) == S_OK
@@ -2081,5 +2132,3 @@ def CreatePattern(patternId: int, pattern: ctypes.POINTER(comtypes.IUnknown)):
subPattern = pattern.QueryInterface(GetPatternIdInterface(patternId))
if subPattern:
return PatternConstructors[patternId](pattern=subPattern)
-
-
diff --git a/windows_use/vdm/core.py b/windows_use/vdm/core.py
index 6ea42a4..d629b35 100644
--- a/windows_use/vdm/core.py
+++ b/windows_use/vdm/core.py
@@ -423,9 +423,7 @@ class IVirtualDesktopManagerInternal(IUnknown):
(["out"], POINTER(POINTER(IVirtualDesktop)), "pDesktop"),
),
# 11: MoveDesktop(desktop, hMon, index)
- STDMETHOD(
- HRESULT, "MoveDesktop", (POINTER(IVirtualDesktop), HWND, UINT)
- ),
+ STDMETHOD(HRESULT, "MoveDesktop", (POINTER(IVirtualDesktop), HWND, UINT)),
# 12: RemoveDesktop
COMMETHOD(
[],
@@ -526,9 +524,7 @@ class IVirtualDesktopManagerInternal(IUnknown):
(["out"], POINTER(POINTER(IVirtualDesktop)), "pDesktop"),
),
# 12: MoveDesktop(desktop, hMon, index)
- STDMETHOD(
- HRESULT, "MoveDesktop", (POINTER(IVirtualDesktop), HWND, UINT)
- ),
+ STDMETHOD(HRESULT, "MoveDesktop", (POINTER(IVirtualDesktop), HWND, UINT)),
# 13: RemoveDesktop
COMMETHOD(
[],
@@ -777,13 +773,9 @@ class VirtualDesktopManager:
byref(CLSID_VirtualDesktopManagerInternal),
byref(IVirtualDesktopManagerInternal._iid_),
)
- self._internal_manager = unk.QueryInterface(
- IVirtualDesktopManagerInternal
- )
+ self._internal_manager = unk.QueryInterface(IVirtualDesktopManagerInternal)
except Exception as e:
- logger.warning(
- f"Failed to initialize VirtualDesktopManagerInternal: {e}"
- )
+ logger.warning(f"Failed to initialize VirtualDesktopManagerInternal: {e}")
self._internal_manager = None
except Exception as e: