mathshuttle 0.8.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,199 @@
1
+ """Win32 clipboard access via ctypes (no third-party dependencies); used through :mod:`.clipboard`.
2
+
3
+ Word / PowerPoint / OneNote exchange equations through the registered clipboard
4
+ format ``"MathML"`` (and ``"MathML Presentation"``): data placed there is pasted as
5
+ a native, editable equation, and copying an equation from Office puts its MathML
6
+ there.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import ctypes
11
+ import ctypes.wintypes as wt
12
+ import re
13
+ import time
14
+ from typing import Dict, List, Optional, Tuple
15
+
16
+ # shared by the platform backends: the exceptions the app catches, the decoding of registered formats
17
+ from .clipboard import _XML_DECL, ClipboardChanged, ClipboardError, _decode_text
18
+
19
+ _user32 = ctypes.windll.user32
20
+ _kernel32 = ctypes.windll.kernel32
21
+
22
+ CF_UNICODETEXT = 13
23
+ _GMEM_MOVEABLE = 0x0002
24
+
25
+ # --- prototypes (explicit types matter on 64-bit) ------------------------------
26
+ _user32.OpenClipboard.argtypes = [wt.HWND]
27
+ _user32.OpenClipboard.restype = wt.BOOL
28
+ _user32.CloseClipboard.restype = wt.BOOL
29
+ _user32.EmptyClipboard.restype = wt.BOOL
30
+ _user32.GetClipboardData.argtypes = [wt.UINT]
31
+ _user32.GetClipboardData.restype = wt.HANDLE
32
+ _user32.SetClipboardData.argtypes = [wt.UINT, wt.HANDLE]
33
+ _user32.SetClipboardData.restype = wt.HANDLE
34
+ _user32.RegisterClipboardFormatW.argtypes = [wt.LPCWSTR]
35
+ _user32.RegisterClipboardFormatW.restype = wt.UINT
36
+ _user32.EnumClipboardFormats.argtypes = [wt.UINT]
37
+ _user32.EnumClipboardFormats.restype = wt.UINT
38
+ _user32.GetClipboardFormatNameW.argtypes = [wt.UINT, wt.LPWSTR, ctypes.c_int]
39
+ _user32.GetClipboardFormatNameW.restype = ctypes.c_int
40
+ _user32.IsClipboardFormatAvailable.argtypes = [wt.UINT]
41
+ _user32.IsClipboardFormatAvailable.restype = wt.BOOL
42
+ _kernel32.GlobalAlloc.argtypes = [wt.UINT, ctypes.c_size_t]
43
+ _kernel32.GlobalAlloc.restype = wt.HGLOBAL
44
+ _kernel32.GlobalLock.argtypes = [wt.HGLOBAL]
45
+ _kernel32.GlobalLock.restype = wt.LPVOID
46
+ _kernel32.GlobalUnlock.argtypes = [wt.HGLOBAL]
47
+ _kernel32.GlobalUnlock.restype = wt.BOOL
48
+ _kernel32.GlobalSize.argtypes = [wt.HGLOBAL]
49
+ _kernel32.GlobalSize.restype = ctypes.c_size_t
50
+ _kernel32.GlobalFree.argtypes = [wt.HGLOBAL]
51
+ _kernel32.GlobalFree.restype = wt.HGLOBAL
52
+ _user32.GetClipboardSequenceNumber.restype = wt.DWORD
53
+
54
+
55
+ def sequence_number() -> int:
56
+ """Changes whenever the clipboard's contents change (GetClipboardSequenceNumber)."""
57
+ return _user32.GetClipboardSequenceNumber()
58
+
59
+
60
+ def register_format(name: str) -> int:
61
+ fmt = _user32.RegisterClipboardFormatW(name)
62
+ if not fmt:
63
+ raise ClipboardError(f"RegisterClipboardFormat({name!r}) failed")
64
+ return fmt
65
+
66
+
67
+ CF_MATHML = register_format("MathML")
68
+ CF_MATHML_PRESENTATION = register_format("MathML Presentation")
69
+ CF_HTML = register_format("HTML Format") # UTF-8, after a header of byte offsets
70
+
71
+
72
+ class _Open:
73
+ """Context manager that opens the clipboard, retrying while another app holds it."""
74
+
75
+ def __enter__(self):
76
+ for attempt in range(20):
77
+ if _user32.OpenClipboard(None):
78
+ return self
79
+ time.sleep(0.05)
80
+ raise ClipboardError("Could not open the clipboard (another application is holding it)")
81
+
82
+ def __exit__(self, *exc):
83
+ _user32.CloseClipboard()
84
+ return False
85
+
86
+
87
+ def set_data(entries: Dict[int, bytes], expect_sequence: Optional[int] = None) -> None:
88
+ """Replace the clipboard contents with the given {format_id: raw bytes} entries. With
89
+ `expect_sequence` (a :func:`sequence_number` taken when the clipboard was read), raise
90
+ ClipboardChanged instead if it changed since - checked while the clipboard is held open."""
91
+ with _Open():
92
+ if expect_sequence is not None and sequence_number() != expect_sequence:
93
+ raise ClipboardChanged("The clipboard changed meanwhile (something else was copied): left as it is")
94
+ if not _user32.EmptyClipboard():
95
+ raise ClipboardError("EmptyClipboard failed")
96
+ for fmt, data in entries.items():
97
+ handle = _kernel32.GlobalAlloc(_GMEM_MOVEABLE, len(data))
98
+ if not handle:
99
+ raise ClipboardError("GlobalAlloc failed")
100
+ ptr = _kernel32.GlobalLock(handle)
101
+ if not ptr:
102
+ _kernel32.GlobalFree(handle)
103
+ raise ClipboardError("GlobalLock failed")
104
+ ctypes.memmove(ptr, data, len(data))
105
+ _kernel32.GlobalUnlock(handle)
106
+ if not _user32.SetClipboardData(fmt, handle):
107
+ _kernel32.GlobalFree(handle)
108
+ raise ClipboardError(f"SetClipboardData(format {fmt}) failed")
109
+ # ownership of `handle` passed to the system
110
+
111
+
112
+ def get_data(fmt: int) -> Optional[bytes]:
113
+ """Raw bytes stored under `fmt`, or None if that format is not on the clipboard."""
114
+ with _Open():
115
+ handle = _user32.GetClipboardData(fmt)
116
+ if not handle:
117
+ return None
118
+ ptr = _kernel32.GlobalLock(handle)
119
+ if not ptr:
120
+ raise ClipboardError("GlobalLock failed")
121
+ try:
122
+ size = _kernel32.GlobalSize(handle)
123
+ return ctypes.string_at(ptr, size)
124
+ finally:
125
+ _kernel32.GlobalUnlock(handle)
126
+
127
+
128
+ def available_formats() -> List[Tuple[int, str]]:
129
+ """(id, name) of every format currently on the clipboard."""
130
+ out: List[Tuple[int, str]] = []
131
+ buf = ctypes.create_unicode_buffer(256)
132
+ with _Open():
133
+ fmt = 0
134
+ while True:
135
+ fmt = _user32.EnumClipboardFormats(fmt)
136
+ if not fmt:
137
+ break
138
+ n = _user32.GetClipboardFormatNameW(fmt, buf, 256)
139
+ out.append((fmt, buf.value if n else _STANDARD_NAMES.get(fmt, f"#{fmt}")))
140
+ return out
141
+
142
+
143
+ _STANDARD_NAMES = {1: "CF_TEXT", 2: "CF_BITMAP", 7: "CF_OEMTEXT", 8: "CF_DIB", 13: "CF_UNICODETEXT",
144
+ 16: "CF_LOCALE", 17: "CF_DIBV5"}
145
+
146
+
147
+ # --- text helpers ---------------------------------------------------------------
148
+ def get_text() -> Optional[str]:
149
+ raw = get_data(CF_UNICODETEXT)
150
+ if raw is None:
151
+ return None
152
+ text = raw.decode("utf-16-le", "replace")
153
+ return text.split("\0", 1)[0]
154
+
155
+
156
+ def set_text(text: str, expect_sequence: Optional[int] = None) -> None:
157
+ set_data({CF_UNICODETEXT: text.encode("utf-16-le") + b"\0\0"}, expect_sequence)
158
+
159
+
160
+ # --- Office equation exchange -----------------------------------------------------
161
+ def copy_mathml_for_office(mathml: str, plain_text: Optional[str] = None, expect_sequence: Optional[int] = None) -> None:
162
+ """Put MathML on the clipboard so that Ctrl+V in Word/PowerPoint inserts a native equation.
163
+
164
+ `plain_text` (default: the MathML itself) is what a plain-text paste receives. Keep the default
165
+ for Office: Word (16.0.20527, checked 2026-11-22) pastes from the plain-text format, not from the
166
+ registered "MathML" ones - with ``x`` there it inserts the text x and no equation, and with LaTeX
167
+ there it runs its own LaTeX import (Microsoft 365 >= 2606) instead of using this MathML.
168
+ """
169
+ body = mathml.strip()
170
+ if not body.startswith("<?xml"):
171
+ body = _XML_DECL + body
172
+ payload = body.encode("utf-8") + b"\0"
173
+ text = plain_text if plain_text is not None else mathml
174
+ set_data({
175
+ CF_MATHML: payload,
176
+ CF_MATHML_PRESENTATION: payload,
177
+ CF_UNICODETEXT: text.encode("utf-16-le") + b"\0\0",
178
+ }, expect_sequence)
179
+
180
+
181
+ def read_equation_from_office() -> Optional[str]:
182
+ """MathML of an equation copied from Word/PowerPoint/OneNote, or None if there is none.
183
+
184
+ Office puts the equation on the clipboard under the "MathML" and
185
+ "MathML Presentation" formats (UTF-8 XML).
186
+ """
187
+ for fmt in (CF_MATHML, CF_MATHML_PRESENTATION):
188
+ mathml = _decode_text(get_data(fmt))
189
+ if mathml and re.search(r"<(\w+:)?math\b", mathml): # other programs may write <mml:math>
190
+ return mathml
191
+ return None
192
+
193
+
194
+ def read_office_html() -> Optional[str]:
195
+ """The copied fragment of the clipboard's "HTML Format" (Word writes its equations into it as OMML;
196
+ the rest of the document is context, which may hold other equations), or None."""
197
+ from .office_html import cf_html_fragment
198
+ raw = get_data(CF_HTML)
199
+ return _decode_text(cf_html_fragment(raw)) if raw is not None else None
@@ -0,0 +1,137 @@
1
+ """The system-wide hotkey on macOS: Carbon's RegisterEventHotKey through ctypes (no PyObjC, and no
2
+ Accessibility permission: a registered hot key is not a keyboard monitor).
3
+
4
+ Registration happens on Tk's main thread. macOS delivers each press as a Carbon event to the
5
+ application's event target while the app's event loop runs (Tk's), and the handler puts it into the
6
+ queue that the app polls, as the Windows listener does (see :mod:`.hotkeys`).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import ctypes
11
+ import itertools
12
+ import queue
13
+ from typing import Optional
14
+
15
+ _carbon = ctypes.CDLL("/System/Library/Frameworks/Carbon.framework/Carbon")
16
+
17
+
18
+ def _fourcc(code: str) -> int:
19
+ return int.from_bytes(code.encode("ascii"), "big")
20
+
21
+
22
+ class _EventTypeSpec(ctypes.Structure):
23
+ _fields_ = [("eventClass", ctypes.c_uint32), ("eventKind", ctypes.c_uint32)]
24
+
25
+
26
+ class _EventHotKeyID(ctypes.Structure):
27
+ _fields_ = [("signature", ctypes.c_uint32), ("id", ctypes.c_uint32)]
28
+
29
+
30
+ _HANDLER = ctypes.CFUNCTYPE(ctypes.c_int32, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p)
31
+ _p = ctypes.c_void_p
32
+ for name, restype, argtypes in (
33
+ ("GetApplicationEventTarget", _p, []),
34
+ ("InstallEventHandler", ctypes.c_int32, [_p, _HANDLER, ctypes.c_ulong, ctypes.POINTER(_EventTypeSpec), _p,
35
+ ctypes.POINTER(_p)]),
36
+ ("RemoveEventHandler", ctypes.c_int32, [_p]),
37
+ ("RegisterEventHotKey", ctypes.c_int32, [ctypes.c_uint32, ctypes.c_uint32, _EventHotKeyID, _p, ctypes.c_uint32,
38
+ ctypes.POINTER(_p)]),
39
+ ("UnregisterEventHotKey", ctypes.c_int32, [_p]),
40
+ ("GetEventParameter", ctypes.c_int32, [_p, ctypes.c_uint32, ctypes.c_uint32, _p, ctypes.c_ulong, _p, _p]),
41
+ ("SetEventParameter", ctypes.c_int32, [_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_ulong, _p]),
42
+ ("CreateEvent", ctypes.c_int32, [_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_double, ctypes.c_uint32,
43
+ ctypes.POINTER(_p)]),
44
+ ("SendEventToEventTarget", ctypes.c_int32, [_p, _p]),
45
+ ("GetMainEventQueue", _p, []),
46
+ ("PostEventToQueue", ctypes.c_int32, [_p, _p, ctypes.c_int16]),
47
+ ("ReleaseEvent", None, [_p])):
48
+ fn = getattr(_carbon, name)
49
+ fn.restype, fn.argtypes = restype, argtypes
50
+
51
+ kEventClassKeyboard = _fourcc("keyb")
52
+ kEventHotKeyPressed = 5
53
+ kEventParamDirectObject = _fourcc("----")
54
+ typeEventHotKeyID = _fourcc("hkid")
55
+ eventNotHandledErr = -9874
56
+ eventHotKeyExistsErr = -9878
57
+ _SIGNATURE = _fourcc("MSht")
58
+ _IDS = itertools.count(1)
59
+
60
+
61
+ class MacHotkeyListener:
62
+ """Listens for one hotkey; each press is put into `presses`. Same interface as the Windows
63
+ listener: start_and_wait() returns None once registered, else why not; stop(); simulate_press()."""
64
+
65
+ def __init__(self, hotkey: str, mods: int, keycode: int) -> None:
66
+ self.hotkey = hotkey
67
+ self.mods, self.keycode = mods, keycode
68
+ self.presses: "queue.Queue[str]" = queue.Queue()
69
+ self.error: Optional[str] = None
70
+ self._id = next(_IDS)
71
+ self._hotkey_ref = _p()
72
+ self._handler_ref = _p()
73
+ self._callback = _HANDLER(self._on_event) # kept alive: Carbon holds only the pointer
74
+
75
+ def _on_event(self, call_ref, event, user_data) -> int:
76
+ hkid = _EventHotKeyID()
77
+ status = _carbon.GetEventParameter(event, kEventParamDirectObject, typeEventHotKeyID, None,
78
+ ctypes.sizeof(hkid), None, ctypes.byref(hkid))
79
+ if status == 0 and hkid.signature == _SIGNATURE and hkid.id == self._id:
80
+ self.presses.put(self.hotkey)
81
+ return 0
82
+ return eventNotHandledErr # another listener's key
83
+
84
+ def start_and_wait(self, timeout: float = 2.0) -> Optional[str]:
85
+ target = _carbon.GetApplicationEventTarget()
86
+ spec = _EventTypeSpec(kEventClassKeyboard, kEventHotKeyPressed)
87
+ status = _carbon.InstallEventHandler(target, self._callback, 1, ctypes.byref(spec), None,
88
+ ctypes.byref(self._handler_ref))
89
+ if status:
90
+ self.error = "could not listen for the hotkey (Carbon error %d)" % status
91
+ return self.error
92
+ status = _carbon.RegisterEventHotKey(self.keycode, self.mods, _EventHotKeyID(_SIGNATURE, self._id), target, 0,
93
+ ctypes.byref(self._hotkey_ref))
94
+ if status:
95
+ self.stop()
96
+ # (macOS reports a clash within this process only; another program may hold it unnoticed)
97
+ self.error = ("%s is already in use" % self.hotkey if status == eventHotKeyExistsErr
98
+ else "could not register %s (Carbon error %d)" % (self.hotkey, status))
99
+ return self.error
100
+
101
+ def is_alive(self) -> bool:
102
+ return bool(self._hotkey_ref.value)
103
+
104
+ def stop(self) -> None:
105
+ if self._hotkey_ref.value:
106
+ _carbon.UnregisterEventHotKey(self._hotkey_ref)
107
+ self._hotkey_ref = _p()
108
+ if self._handler_ref.value:
109
+ _carbon.RemoveEventHandler(self._handler_ref)
110
+ self._handler_ref = _p()
111
+
112
+ def _event(self) -> _p:
113
+ event = _p()
114
+ if _carbon.CreateEvent(None, kEventClassKeyboard, kEventHotKeyPressed, 0.0, 0, ctypes.byref(event)):
115
+ raise OSError("CreateEvent failed")
116
+ hkid = _EventHotKeyID(_SIGNATURE, self._id)
117
+ _carbon.SetEventParameter(event, kEventParamDirectObject, typeEventHotKeyID, ctypes.sizeof(hkid),
118
+ ctypes.byref(hkid))
119
+ return event
120
+
121
+ def simulate_press(self) -> None:
122
+ """Deliver a hot key event of this listener to the application target, as a press would (for
123
+ tests: no keystroke is sent anywhere, the event stays in this process)."""
124
+ event = self._event()
125
+ try:
126
+ _carbon.SendEventToEventTarget(event, _carbon.GetApplicationEventTarget())
127
+ finally:
128
+ _carbon.ReleaseEvent(event)
129
+
130
+ def post_press(self) -> None:
131
+ """Post a hot key event of this listener to the main event queue, from which the app's event loop
132
+ (Tk's) dispatches it as it does a real press (for tests; stays in this process)."""
133
+ event = self._event()
134
+ try:
135
+ _carbon.PostEventToQueue(_carbon.GetMainEventQueue(), event, 1) # kEventPriorityStandard
136
+ finally:
137
+ _carbon.ReleaseEvent(event)