|
| 1 | +from talon import Context, Module, actions |
| 2 | + |
| 3 | +from .cursorless_everywhere_types import ( |
| 4 | + EditorEdit, |
| 5 | + EditorState, |
| 6 | + SelectionOffsets, |
| 7 | +) |
| 8 | + |
| 9 | +mod = Module() |
| 10 | + |
| 11 | +mod.tag( |
| 12 | + "cursorless_everywhere_talon_browser", |
| 13 | + desc="Enable RPC to browser extension when using cursorless everywhere in Talon", |
| 14 | +) |
| 15 | + |
| 16 | +ctx = Context() |
| 17 | +ctx.matches = r""" |
| 18 | +tag: user.cursorless_everywhere_talon_browser |
| 19 | +""" |
| 20 | + |
| 21 | +RPC_COMMAND = "talonCommand" |
| 22 | + |
| 23 | + |
| 24 | +@ctx.action_class("user") |
| 25 | +class Actions: |
| 26 | + def cursorless_everywhere_get_editor_state() -> EditorState: |
| 27 | + command = { |
| 28 | + "id": "getEditorState", |
| 29 | + } |
| 30 | + res = rpc_get(command) |
| 31 | + if use_fallback(res): |
| 32 | + return actions.next() |
| 33 | + return res |
| 34 | + |
| 35 | + def cursorless_everywhere_set_selections( |
| 36 | + selections: list[SelectionOffsets], # pyright: ignore [reportGeneralTypeIssues] |
| 37 | + ): |
| 38 | + command = { |
| 39 | + "id": "setSelections", |
| 40 | + "selections": [ |
| 41 | + js_object_to_python_dict(s, ["anchor", "active"]) |
| 42 | + for s in js_array_to_python_list(selections) |
| 43 | + ], |
| 44 | + } |
| 45 | + res = rpc_get(command) |
| 46 | + if use_fallback(res): |
| 47 | + actions.next(selections) |
| 48 | + |
| 49 | + def cursorless_everywhere_edit_text( |
| 50 | + edit: EditorEdit, # pyright: ignore [reportGeneralTypeIssues] |
| 51 | + ): |
| 52 | + command = { |
| 53 | + "id": "editText", |
| 54 | + "text": edit["text"], |
| 55 | + "changes": [ |
| 56 | + js_object_to_python_dict(c, ["text", "rangeOffset", "rangeLength"]) |
| 57 | + for c in js_array_to_python_list(edit["changes"]) |
| 58 | + ], |
| 59 | + } |
| 60 | + res = rpc_get(command) |
| 61 | + if use_fallback(res): |
| 62 | + actions.next(edit) |
| 63 | + |
| 64 | + |
| 65 | +def rpc_get(command: dict): |
| 66 | + return actions.user.run_rpc_command_get(RPC_COMMAND, command) |
| 67 | + |
| 68 | + |
| 69 | +def use_fallback(result: dict) -> bool: |
| 70 | + return result.get("fallback", False) |
| 71 | + |
| 72 | + |
| 73 | +def js_array_to_python_list(array) -> list: |
| 74 | + result = [] |
| 75 | + for i in range(array.length): |
| 76 | + result.append(array[i]) |
| 77 | + return result |
| 78 | + |
| 79 | + |
| 80 | +def js_object_to_python_dict(object, keys: list[str]) -> dict: |
| 81 | + result = {} |
| 82 | + for key in keys: |
| 83 | + result[key] = object[key] |
| 84 | + return result |
0 commit comments