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,127 @@
1
+ """The clipboard via ctypes (no third-party dependencies): text, and the equations Office copies and pastes.
2
+
3
+ Word / PowerPoint / OneNote exchange equations as MathML: on Windows through the registered clipboard
4
+ format ``"MathML"`` (and ``"MathML Presentation"``), see :mod:`._clipboard_win32`; on macOS through the
5
+ general pasteboard (NSPasteboard) types ``public.mathml`` (and ``public.mathml.presentation``), see
6
+ :mod:`._clipboard_macos`. Where Word copies no MathML, its HTML holds the equations as OMML
7
+ (:func:`read_office_equation`, :mod:`.office_html`).
8
+
9
+ This module is what the app and the CLI use. The platform backend is loaded on first use, not on
10
+ import: importing the GUI never fails because of the clipboard, and a backend that cannot be loaded
11
+ is a ClipboardError where the clipboard is used, which the callers report.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ import sys
17
+ from typing import Dict, List, Optional, Tuple
18
+
19
+
20
+ class ClipboardError(RuntimeError):
21
+ pass
22
+
23
+
24
+ class ClipboardChanged(ClipboardError):
25
+ """Something else was copied after the clipboard was read: it is not overwritten."""
26
+
27
+
28
+ # --- shared by the backends ---------------------------------------------------------
29
+ _XML_DECL = '<?xml version="1.0" encoding="UTF-8"?>\n'
30
+
31
+
32
+ def _decode_text(raw: Optional[bytes]) -> Optional[str]:
33
+ """Text in a registered format: UTF-8 (what Office writes) or, from some other programs,
34
+ UTF-16-LE - recognised by its BOM or by the NUL after the first (ASCII) character."""
35
+ if raw is None:
36
+ return None
37
+ if raw[:2] == b"\xff\xfe" or (raw[1:2] == b"\0" and raw[:1] not in (b"", b"\0")):
38
+ text = raw[:len(raw) & ~1].decode("utf-16-le", "replace")
39
+ return text.lstrip("\ufeff").split("\0", 1)[0]
40
+ return raw.split(b"\0", 1)[0].decode("utf-8-sig", "replace")
41
+
42
+
43
+ _backend_module = None
44
+
45
+
46
+ def _backend():
47
+ global _backend_module
48
+ if _backend_module is None:
49
+ try:
50
+ if sys.platform == "win32":
51
+ from . import _clipboard_win32 as module
52
+ elif sys.platform == "darwin":
53
+ from . import _clipboard_macos as module
54
+ else:
55
+ raise ClipboardError("No clipboard support on %s (Windows and macOS only)" % sys.platform)
56
+ except (OSError, AttributeError) as e: # a system library that cannot be loaded or lacks a function
57
+ raise ClipboardError("Cannot use the clipboard: %s" % e)
58
+ _backend_module = module
59
+ return _backend_module
60
+
61
+
62
+ # --- the API (formats: Win32 format ids on Windows, pasteboard type names on macOS) ----------
63
+ def sequence_number() -> int:
64
+ """Changes whenever the clipboard's contents change (Windows: GetClipboardSequenceNumber,
65
+ macOS: the pasteboard's changeCount)."""
66
+ return _backend().sequence_number()
67
+
68
+
69
+ def set_data(entries: Dict, expect_sequence: Optional[int] = None) -> None:
70
+ """Replace the clipboard contents with the given {format: raw bytes} entries, all at once. With
71
+ `expect_sequence` (a :func:`sequence_number` taken when the clipboard was read), raise
72
+ ClipboardChanged instead if it changed since."""
73
+ _backend().set_data(entries, expect_sequence)
74
+
75
+
76
+ def get_data(fmt) -> Optional[bytes]:
77
+ """Raw bytes stored under `fmt`, or None if that format is not on the clipboard."""
78
+ return _backend().get_data(fmt)
79
+
80
+
81
+ def available_formats() -> List[Tuple[object, str]]:
82
+ """(format, name) of every format currently on the clipboard; `format` is what :func:`get_data` takes."""
83
+ return _backend().available_formats()
84
+
85
+
86
+ def get_text() -> Optional[str]:
87
+ """The clipboard's plain text, or None if it holds none."""
88
+ return _backend().get_text()
89
+
90
+
91
+ def set_text(text: str, expect_sequence: Optional[int] = None) -> None:
92
+ """Replace the clipboard contents with plain text (`expect_sequence`: as for :func:`set_data`)."""
93
+ _backend().set_text(text, expect_sequence)
94
+
95
+
96
+ def copy_mathml_for_office(mathml: str, plain_text: Optional[str] = None, expect_sequence: Optional[int] = None) -> None:
97
+ """Put MathML on the clipboard so that pasting in Word / PowerPoint inserts a native equation;
98
+ `plain_text` (default: the MathML itself, which Word on Windows pastes from) is what a plain-text
99
+ paste receives."""
100
+ _backend().copy_mathml_for_office(mathml, plain_text, expect_sequence)
101
+
102
+
103
+ def read_equation_from_office() -> Optional[str]:
104
+ """MathML of an equation copied from Word / PowerPoint / OneNote, or None if there is none."""
105
+ return _backend().read_equation_from_office()
106
+
107
+
108
+ def read_office_equation() -> Optional[Tuple[str, str]]:
109
+ """What "Paste from Word/PowerPoint" converts: ("mathml", MathML) of an equation copied in Office;
110
+ failing that ("omml", OMML) of the equations in the HTML that Word copies along (a selection of text
111
+ with equations in it, or lines that Mac Word copies without MathML); None if neither is there."""
112
+ from .office_html import omml_from_html
113
+ sequence = sequence_number()
114
+ mathml = read_equation_from_office()
115
+ if mathml:
116
+ # Word's MathML puts the lines of an equation with manual line breaks (Insert Manual Break) on
117
+ # one line; its HTML keeps them (m:brk). The HTML is a second read: if it fails, or something
118
+ # else was copied in between, the MathML is what was copied
119
+ try:
120
+ omml = omml_from_html(_backend().read_office_html())
121
+ except ClipboardError:
122
+ omml = None
123
+ if omml and re.search(r"<m:brk\b", omml) and sequence_number() == sequence:
124
+ return "omml", omml
125
+ return "mathml", mathml
126
+ omml = omml_from_html(_backend().read_office_html())
127
+ return ("omml", omml) if omml else None