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.
mathshuttle/app.py ADDED
@@ -0,0 +1,1483 @@
1
+ """tkinter desktop UI: a local stand-in for https://johnmacfarlane.net/texmath.html
2
+ with direct Word / PowerPoint clipboard exchange."""
3
+ from __future__ import annotations
4
+
5
+ import ctypes
6
+ import json
7
+ import os
8
+ import queue
9
+ import re
10
+ import sys
11
+ import threading
12
+ import tkinter as tk
13
+ import traceback
14
+ from tkinter import filedialog
15
+ from tkinter import font as tkfont
16
+ from tkinter import ttk
17
+ from typing import Optional
18
+
19
+ from . import __version__, clipboard, compat, hotkeys, latex_wrap, preview, theme
20
+ from .convert import FORMAT_LABELS, MODES, Result, convert, input_equations, macro_notes, office_copy
21
+ from .latex_wrap import WRAPPERS
22
+ from .pandoc_engine import (INSTALL_HINT, READ_FORMATS, WRITE_FORMATS, ConversionError, Equation, PandocNotFound,
23
+ engine_description, engine_report)
24
+
25
+ SAMPLE = "\\begin{align}\n \\nabla \\cdot \\mathbf{E} &= \\frac{\\rho}{\\varepsilon_0} \\\\\n \\nabla \\times \\mathbf{B} - \\frac{1}{c^2}\\frac{\\partial \\mathbf{E}}{\\partial t} &= \\mu_0 \\mathbf{J}\n\\end{align}"
26
+
27
+ MAC = sys.platform == "darwin"
28
+ # the modifier of the app's own shortcuts, and of copy / paste in Office, as the user knows it
29
+ KEY = "Cmd" if MAC else "Ctrl"
30
+ APP_DATA = (os.path.join(os.path.expanduser("~"), "Library", "Application Support") if MAC
31
+ else os.environ.get("APPDATA", os.path.expanduser("~")))
32
+ SETTINGS_PATH = os.path.join(APP_DATA, "MathShuttle", "settings.json")
33
+ # where the tool kept them under its former name (Equation Tool): read once if there are no settings yet
34
+ OLD_SETTINGS_PATH = os.path.join(APP_DATA, "EquationTool", "settings.json")
35
+ DEFAULT_GEOMETRY = "1200x720"
36
+ DEBOUNCE_MS = 450
37
+ MAX_SAVED_INPUT = 200_000 # characters of input kept for the next start
38
+
39
+ _HOTKEY_HELP = """\
40
+ Hotkey (Control+Option+Shift+M, works in any program while MathShuttle runs, even minimised):
41
+ an equation copied in Word / PowerPoint becomes LaTeX text on the clipboard;
42
+ LaTeX text on the clipboard becomes an equation - then Cmd+V in Office. The key
43
+ is "hotkey" in the settings file (~/Library/Application Support/MathShuttle/
44
+ settings.json), written with Windows' names: Alt there is Option, Cmd Command.
45
+ macOS may ask once whether MathShuttle may paste from Word (paste privacy).""" if MAC else """\
46
+ Hotkey (Ctrl+Alt+Shift+M, works in any program while MathShuttle runs, even minimised):
47
+ an equation copied in Word / PowerPoint becomes LaTeX text on the clipboard;
48
+ LaTeX text on the clipboard becomes an equation - then Ctrl+V in Office. The key
49
+ is "hotkey" in the settings file (%APPDATA%\\MathShuttle\\settings.json)."""
50
+
51
+ HELP = """MathShuttle %(version)s - texmath (via pandoc) running locally
52
+
53
+ INPUT (From)
54
+ LaTeX Any delimiters are recognised: bare, $...$, \\(...\\), $$...$$, \\[...\\],
55
+ equation / align / gather / multline / eqnarray / alignat (+ starred),
56
+ \\label, \\tag, \\nonumber, \\newcommand definitions, and several equations
57
+ mixed with prose (each one is converted). Input without any delimiter is
58
+ one bare equation (even with $...$ inside \\text{} / \\mbox{}); it uses the Mode box.
59
+ Plain-TeX font switches ({\\rm OOD}, \\cal L), \\notag, \\def / \\let macros,
60
+ \\mathbbm, dcases, \\smash ... are rewritten for texmath, which does not know them.
61
+ Macros... your papers' macro files (math_commands.tex, a preamble) and extra
62
+ definitions: \\newcommand, \\def, \\let, \\DeclareMathOperator,
63
+ \\DeclarePairedDelimiter. Every LaTeX input may then use those macros;
64
+ LaTeX -> LaTeX output keeps them as you wrote them; with Expand macros
65
+ ticked it writes them out (for a place without your macro file).
66
+ MathML <math> element(s), with or without the xmlns / XML prolog, also prefixed
67
+ (<mml:math>) and with named entities (&InvisibleTimes;).
68
+ OMML <m:oMath> or <m:oMathPara>, alone or inside any Word XML.
69
+
70
+ OUTPUT (To)
71
+ LaTeX The "LaTeX wrapper" box picks the delimiters / environment. Auto keeps
72
+ the input's environment and otherwise uses \\[ \\] (display) or $ $ (inline).
73
+ align <-> aligned, gather <-> gathered are converted as needed.
74
+ Tidy LaTeX (MathML / OMML input): writes what an author would - \\mathrm{OOD},
75
+ \\operatorname{softmax}, \\boldsymbol{\\theta}, \\binom, cases, a & = b - instead of
76
+ texmath's literal rendering.
77
+ MathML / OMML / eqn / Typst Mode = Auto follows the input; Display / Inline force it.
78
+
79
+ WORD / POWERPOINT
80
+ Copy for Word/PowerPoint converts the input to MathML and places it on the clipboard
81
+ in the "MathML" clipboard format; %(key)s+V in Word, PowerPoint or OneNote then
82
+ inserts a native, editable equation (%(key)s+Shift+C). align / aligned / split
83
+ blocks arrive as an Office equation array, lined up at the = signs. With several
84
+ equations in the input, a menu lets you pick one; its first item, Next, is the
85
+ one after the equation copied last (keys: N or a number; on the Mac, then Return).
86
+ Paste from Word/PowerPoint reads the equation you copied in Word / PowerPoint
87
+ (select the equation, %(key)s+C) and converts it to LaTeX (%(key)s+Shift+V).
88
+ A copied sentence with equations in it gives the LaTeX of each.
89
+ %(hotkey)s
90
+ Open file... every equation of a .docx / .pptx / .tex / .md file, with where it is.
91
+
92
+ LaTeX preview: the LaTeX side of the conversion as LaTeX sets it (needs latex + dvipng on PATH).
93
+
94
+ %(key)s+Enter converts; Auto-convert re-runs the conversion as you type.
95
+ """ % {"version": __version__, "key": KEY, "hotkey": _HOTKEY_HELP}
96
+
97
+
98
+ class _POINT(ctypes.Structure):
99
+ _fields_ = [("x", ctypes.c_long), ("y", ctypes.c_long)]
100
+
101
+
102
+ class _CGPoint(ctypes.Structure):
103
+ _fields_ = [("x", ctypes.c_double), ("y", ctypes.c_double)]
104
+
105
+
106
+ def _on_a_display_macos(x: int, y: int) -> bool:
107
+ """CGGetDisplaysWithPoint; Quartz's global coordinates are Tk's on macOS (from the top left corner
108
+ of the main display, growing downwards)."""
109
+ try:
110
+ displays_with_point = ctypes.CDLL("/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics").CGGetDisplaysWithPoint
111
+ except (OSError, AttributeError):
112
+ return True
113
+ displays_with_point.argtypes = [_CGPoint, ctypes.c_uint32, ctypes.c_void_p, ctypes.POINTER(ctypes.c_uint32)]
114
+ displays_with_point.restype = ctypes.c_int32 # CGError, 0 = success
115
+ count = ctypes.c_uint32(0)
116
+ error = displays_with_point(_CGPoint(x, y), 0, None, ctypes.byref(count))
117
+ return error != 0 or count.value > 0 # if Quartz cannot tell, trust the saved position
118
+
119
+
120
+ def _on_a_monitor(x: int, y: int) -> bool:
121
+ if MAC:
122
+ return _on_a_display_macos(x, y)
123
+ try:
124
+ monitor_from_point = ctypes.windll.user32.MonitorFromPoint
125
+ except AttributeError: # neither Windows nor macOS: on the X screen (all its monitors) as Tk sees it
126
+ root = tk._default_root
127
+ return root is None or (0 <= x < root.winfo_screenwidth() and 0 <= y < root.winfo_screenheight())
128
+ monitor_from_point.argtypes = [_POINT, ctypes.c_uint32]
129
+ monitor_from_point.restype = ctypes.c_void_p # HMONITOR
130
+ return bool(monitor_from_point(_POINT(x, y), 0)) # 0 = MONITOR_DEFAULTTONULL
131
+
132
+
133
+ def _enable_dpi_awareness() -> None:
134
+ try:
135
+ ctypes.windll.shcore.SetProcessDpiAwareness(1)
136
+ except Exception:
137
+ try:
138
+ ctypes.windll.user32.SetProcessDPIAware()
139
+ except Exception:
140
+ pass
141
+
142
+
143
+ class App(tk.Tk):
144
+ def __init__(self) -> None:
145
+ super().__init__()
146
+ self.title("MathShuttle")
147
+ self._seq = 0
148
+ self._after_id: Optional[str] = None
149
+ self._results: "queue.Queue[tuple]" = queue.Queue()
150
+ self._polling = False
151
+ self._running = 0 # conversion threads whose result has not been collected yet
152
+ self._shown_args: Optional[tuple] = None # conversion arguments of the result in the output pane
153
+ self._last_copy: "tuple[Optional[tuple], int]" = (None, -1) # (_copy_key, index) of the one copied last
154
+ self._recalled: Optional[tuple] = None # (pasted MathML, (LaTeX, display) it was copied from, or None)
155
+ self._copy_menu: Optional[tk.Menu] = None
156
+ self.settings = self._load_settings()
157
+ # Tk's native macOS windowing, which has the Command modifier and the tk::mac:: hooks
158
+ self.aqua = self.tk.call("tk", "windowingsystem") == "aqua"
159
+
160
+ self._scale_fonts()
161
+ self._build()
162
+ self._apply_settings()
163
+ self._bind_keys()
164
+ self.protocol("WM_DELETE_WINDOW", self._on_close)
165
+ self.after(50, self._startup_check)
166
+
167
+ # ---- UI construction --------------------------------------------------------------------
168
+ def _scale_fonts(self) -> None:
169
+ try:
170
+ dpi = self.winfo_fpixels("1i")
171
+ self.tk.call("tk", "scaling", dpi / 72.0)
172
+ except Exception:
173
+ pass
174
+ ui = tkfont.nametofont("TkDefaultFont")
175
+ if MAC:
176
+ # Tk's default font there is the system font at the system size, which is 13 at Tk 8.6's 72 dpi
177
+ # and 10 at Tk 9's 96 dpi: it stays as it is, and the monospace font (Menlo comes with every
178
+ # macOS; Consolas does not) gets the same size
179
+ self.mono = tkfont.Font(family="Menlo", size=abs(int(ui.actual("size"))) or 13)
180
+ else:
181
+ self.mono = tkfont.Font(family="Consolas", size=11)
182
+ ui.configure(size=10)
183
+ self.option_add("*Font", ui)
184
+ self.theme_mode = theme.apply(self, self.settings.get("theme"))
185
+ self.palette = theme.palette(self.theme_mode)
186
+ style = ttk.Style(self)
187
+ style.configure("TButton", padding=(10, 4))
188
+ style.configure("Accent.TButton", padding=(12, 4))
189
+ style.configure("Caption.TLabel", foreground=self.palette["muted"])
190
+ style.configure("Status.TLabel", padding=(10, 3))
191
+ style.configure("Engine.TLabel", padding=(10, 3), foreground=self.palette["muted"])
192
+ if self.theme_mode == "dark":
193
+ theme.dark_title_bar(self, True)
194
+
195
+ def _build(self) -> None:
196
+ pad = {"padx": 4, "pady": 3}
197
+ self.src_var = tk.StringVar(value="latex")
198
+ self.dst_var = tk.StringVar(value="omml")
199
+ self.mode_var = tk.StringVar(value="auto")
200
+ self.wrapper_var = tk.StringVar(value="auto")
201
+ self.annotate_var = tk.BooleanVar(value=False)
202
+ self.tidy_var = tk.BooleanVar(value=True)
203
+ self.expand_var = tk.BooleanVar(value=False)
204
+ self.auto_var = tk.BooleanVar(value=True)
205
+ self.hotkey_var = tk.BooleanVar(value=True)
206
+ self.preview_var = tk.BooleanVar(value=True)
207
+ self._latex_found: Optional[bool] = None # unknown until the startup check
208
+ self.hotkey = hotkeys.DEFAULT
209
+ self._listener: Optional[hotkeys.HotkeyListener] = None
210
+ self.macro_files: list = [] # macro files and extra definitions for LaTeX input (Macros...)
211
+ self.macro_text = ""
212
+
213
+ # --- formats and options (fixed height) ---
214
+ top = ttk.Frame(self, padding=(10, 8, 10, 0))
215
+ top.pack(fill="x")
216
+ self._top = top
217
+ formats = ttk.Frame(top)
218
+ formats.pack(fill="x")
219
+ ttk.Label(formats, text="From").pack(side="left")
220
+ self.src_box = self._combo(formats, [(k, FORMAT_LABELS[k]) for k in READ_FORMATS], self.src_var, 18)
221
+ self.src_box.pack(side="left", padx=(8, 6))
222
+ ttk.Button(formats, text="⇄", width=3, command=self.swap).pack(side="left")
223
+ ttk.Label(formats, text="To").pack(side="left", padx=(10, 0))
224
+ self.dst_box = self._combo(formats, [(k, FORMAT_LABELS[k]) for k in WRITE_FORMATS], self.dst_var, 18)
225
+ self.dst_box.pack(side="left", padx=(8, 20))
226
+ ttk.Label(formats, text="Mode").pack(side="left")
227
+ self.mode_box = self._combo(formats, MODES, self.mode_var, 9)
228
+ self.mode_box.pack(side="left", padx=(8, 0))
229
+ ttk.Button(formats, text="?", width=3, command=self.show_help).pack(side="right")
230
+ self.macros_button = ttk.Button(formats, text="Macros...", command=self.edit_macros)
231
+ self.macros_button.pack(side="right", padx=(0, 8))
232
+
233
+ # what the conversion does: the LaTeX wrapper and the options of one direction or format
234
+ conversion = ttk.Frame(top)
235
+ conversion.pack(fill="x", pady=(8, 0))
236
+ ttk.Label(conversion, text="LaTeX wrapper").pack(side="left")
237
+ self.wrapper_box = self._combo(conversion, WRAPPERS, self.wrapper_var, 34)
238
+ self.wrapper_box.pack(side="left", padx=(8, 14))
239
+ self.expand_chk = ttk.Checkbutton(conversion, text="Expand macros", variable=self.expand_var,
240
+ command=self._schedule)
241
+ self.expand_chk.pack(side="left", padx=(0, 10))
242
+ self.tidy_chk = ttk.Checkbutton(conversion, text="Tidy LaTeX from Office", variable=self.tidy_var,
243
+ command=self._schedule)
244
+ self.tidy_chk.pack(side="left", padx=(0, 10))
245
+ self.annotate_chk = ttk.Checkbutton(conversion, text="TeX annotation", variable=self.annotate_var,
246
+ command=self._schedule)
247
+ self.annotate_chk.pack(side="left")
248
+
249
+ # how the app works (the button bar below keeps only actions, so that it fits)
250
+ switches = ttk.Frame(top)
251
+ switches.pack(fill="x", pady=(2, 0))
252
+ ttk.Checkbutton(switches, text="Auto-convert", variable=self.auto_var, command=self._schedule).pack(side="left")
253
+ self.preview_chk = ttk.Checkbutton(switches, text="LaTeX preview", variable=self.preview_var,
254
+ command=self._toggle_preview, state="disabled")
255
+ self.preview_chk.pack(side="left", padx=(10, 0))
256
+ self.hotkey_chk = ttk.Checkbutton(switches, variable=self.hotkey_var, command=self._toggle_hotkey)
257
+ self.hotkey_chk.pack(side="left", padx=(10, 0))
258
+
259
+ # --- status bar and button bar are packed before the panes so they always stay visible ---
260
+ # Two panes: conversion progress / messages on the left, the engine version (pandoc +
261
+ # texmath) permanently on the right, so the messages never hide it.
262
+ bar = ttk.Frame(self)
263
+ bar.pack(fill="x", side="bottom")
264
+ ttk.Separator(bar).pack(fill="x", side="top")
265
+ self.engine_var = tk.StringVar(value="")
266
+ ttk.Label(bar, textvariable=self.engine_var, style="Engine.TLabel").pack(side="right")
267
+ self.status_var = tk.StringVar(value="")
268
+ self.status_label = ttk.Label(bar, textvariable=self.status_var, anchor="w", style="Status.TLabel")
269
+ self.status_label.pack(side="left", fill="x", expand=True)
270
+
271
+ bottom = ttk.Frame(self, padding=(10, 4, 10, 8))
272
+ bottom.pack(fill="x", side="bottom")
273
+ self._bottom_bar = bottom
274
+ ttk.Button(bottom, text="Open file...", command=self.open_document).pack(side="left")
275
+ ttk.Button(bottom, text="Save as Word...", command=self.save_as_word).pack(side="left", padx=(6, 0))
276
+ ttk.Button(bottom, text="Clear", command=self.clear).pack(side="left", padx=(6, 0))
277
+
278
+ # --- the LaTeX preview (above the buttons; shown when a LaTeX installation is found) ---
279
+ paper = self.palette["preview"]
280
+ self.preview_frame = tk.Frame(self, bg=paper, height=10, highlightthickness=1,
281
+ highlightbackground=self.palette["border"])
282
+ self.preview_label = tk.Label(self.preview_frame, bg=paper, anchor="w", justify="left", padx=10, pady=6)
283
+ self.preview_label.pack(fill="x")
284
+ self._preview_image = None # keeps the PhotoImage alive
285
+ self._preview_seq = 0
286
+ self._last_result: Optional[tuple] = None # (Result, conversion args) of the output on show
287
+ ttk.Button(bottom, text="Paste from Word/PowerPoint", command=self.paste_from_office,
288
+ style=self._accent()).pack(side="right")
289
+ self.copy_button = ttk.Button(bottom, text="Copy for Word/PowerPoint", command=self.copy_for_office,
290
+ style=self._accent())
291
+ self.copy_button.pack(side="right", padx=(0, 6))
292
+ ttk.Button(bottom, text="Copy output", command=self.copy_output).pack(side="right", padx=(0, 6))
293
+ ttk.Button(bottom, text="Convert", command=self.convert_now).pack(side="right", padx=(0, 6))
294
+
295
+ # --- input / output panes (take the remaining space) ---
296
+ paned = ttk.PanedWindow(self, orient="horizontal")
297
+ paned.pack(fill="both", expand=True, padx=10, pady=(8, 6))
298
+ self.input_caption = tk.StringVar(value="Input")
299
+ self.output_caption = tk.StringVar(value="Output")
300
+ self.input = self._text(paned, self.input_caption)
301
+ self.output = self._text(paned, self.output_caption)
302
+ paned.add(self.input.master, weight=1)
303
+ paned.add(self.output.master, weight=1)
304
+ self.output.tag_configure("error", foreground=self.palette["error"])
305
+
306
+ for var in (self.src_var, self.dst_var, self.mode_var, self.wrapper_var):
307
+ var.trace_add("write", lambda *_: self._on_option_change())
308
+ self.input.bind("<<Modified>>", self._on_input_modified)
309
+
310
+ def _accent(self) -> str:
311
+ """The style of the main actions: the theme's accent button (Tk's own look has none)."""
312
+ return "Accent.TButton" if self.theme_mode in ("light", "dark") else "TButton"
313
+
314
+ def _combo(self, parent, items, var, width):
315
+ keys = [k for k, _ in items]
316
+ labels = [lbl for _, lbl in items]
317
+ box = ttk.Combobox(parent, values=labels, state="readonly", width=width)
318
+
319
+ def sync_from_var(*_):
320
+ key = var.get()
321
+ if key in keys:
322
+ box.current(keys.index(key))
323
+
324
+ box.bind("<<ComboboxSelected>>", lambda e: var.set(keys[box.current()]))
325
+ var.trace_add("write", sync_from_var)
326
+ sync_from_var()
327
+ return box
328
+
329
+ def _text(self, parent, caption: Optional[tk.StringVar] = None) -> tk.Text:
330
+ frame = ttk.Frame(parent, padding=(0, 0, 4, 0))
331
+ if caption is not None:
332
+ ttk.Label(frame, textvariable=caption, style="Caption.TLabel").pack(side="top", anchor="w", pady=(0, 4))
333
+ text = tk.Text(frame, wrap="word", undo=True, font=self.mono, padx=8, pady=8, width=40, height=8)
334
+ theme.style_text(text, self.theme_mode)
335
+ scroll = ttk.Scrollbar(frame, command=text.yview)
336
+ text.configure(yscrollcommand=scroll.set)
337
+ scroll.pack(side="right", fill="y")
338
+ text.pack(side="left", fill="both", expand=True)
339
+ text.bind("<Control-a>", lambda e: (text.tag_add("sel", "1.0", "end-1c"), "break")[1])
340
+ if self.aqua:
341
+ text.bind("<Command-a>", lambda e: (text.tag_add("sel", "1.0", "end-1c"), "break")[1])
342
+ return text
343
+
344
+ def _bind_keys(self) -> None:
345
+ self.bind_all("<Control-Return>", lambda e: self.convert_now())
346
+ for w in (self.input, self.output): # do not also insert a newline
347
+ w.bind("<Control-Return>", lambda e: (self.convert_now(), "break")[1])
348
+ self.bind_all("<Control-Shift-C>", lambda e: self.copy_for_office())
349
+ self.bind_all("<Control-Shift-c>", lambda e: self.copy_for_office())
350
+ self.bind_all("<Control-Shift-V>", lambda e: self.paste_from_office())
351
+ self.bind_all("<Control-Shift-v>", lambda e: self.paste_from_office())
352
+ self.bind_all("<F1>", lambda e: self.show_help())
353
+ if self.aqua: # the Command key too: what Mac users press (the Control keys above keep working)
354
+ self.bind_all("<Command-Return>", lambda e: self.convert_now())
355
+ for w in (self.input, self.output):
356
+ w.bind("<Command-Return>", lambda e: (self.convert_now(), "break")[1])
357
+ self.bind_all("<Command-Shift-C>", lambda e: self.copy_for_office())
358
+ self.bind_all("<Command-Shift-c>", lambda e: self.copy_for_office())
359
+ self.bind_all("<Command-Shift-V>", lambda e: self.paste_from_office())
360
+ self.bind_all("<Command-Shift-v>", lambda e: self.paste_from_office())
361
+ # Quit in the application menu (Cmd+Q) would end Tk without WM_DELETE_WINDOW, losing the
362
+ # settings and the input; Help in the Help menu opens this app's help
363
+ self.createcommand("tk::mac::Quit", self._on_close)
364
+ self.createcommand("tk::mac::ShowHelp", self.show_help)
365
+
366
+ # ---- settings -----------------------------------------------------------------------------
367
+ def _load_settings(self) -> dict:
368
+ path = SETTINGS_PATH
369
+ if not os.path.exists(path) and SETTINGS_PATH.endswith(os.path.join("MathShuttle", "settings.json")):
370
+ path = OLD_SETTINGS_PATH # first start after the rename; they are saved under the new name on exit
371
+ try:
372
+ with open(path, encoding="utf-8") as f:
373
+ data = json.load(f)
374
+ except Exception:
375
+ return {}
376
+ return data if isinstance(data, dict) else {}
377
+
378
+ def _restore_geometry(self, geometry) -> None:
379
+ """Apply a saved geometry; drop a position that is on no monitor any more (a disconnected
380
+ second screen), and ignore a malformed value rather than failing to start."""
381
+ m = re.fullmatch(r"(\d+)x(\d+)([+-])(-?\d+)([+-])(-?\d+)", geometry) if isinstance(geometry, str) else None
382
+ # An offset from the right / bottom edge (-X-Y: only from an edited settings file, Tk reports a
383
+ # position the app set itself as +X+Y) cannot be checked against the monitors: keep the size only.
384
+ if m and ("-" in m.group(3, 5) or not _on_a_monitor(int(m.group(4)) + 60, int(m.group(6)) + 15)):
385
+ geometry = "%sx%s" % m.group(1, 2) # (x + 60, y + 15) is a point in the title bar
386
+ try:
387
+ self.geometry(geometry)
388
+ except tk.TclError:
389
+ self.geometry(DEFAULT_GEOMETRY)
390
+
391
+ def _apply_settings(self) -> None:
392
+ s = self.settings
393
+ for var, key, allowed in ((self.src_var, "src", READ_FORMATS), (self.dst_var, "dst", WRITE_FORMATS),
394
+ (self.mode_var, "mode", [k for k, _ in MODES]),
395
+ (self.wrapper_var, "wrapper", [k for k, _ in WRAPPERS])):
396
+ if s.get(key) in allowed:
397
+ var.set(s[key])
398
+ self.auto_var.set(bool(s.get("auto_convert", True)))
399
+ self.annotate_var.set(bool(s.get("annotate", False)))
400
+ self.tidy_var.set(bool(s.get("tidy", True)))
401
+ self.expand_var.set(bool(s.get("expand_macros", False)))
402
+ self.hotkey_var.set(bool(s.get("hotkey_enabled", True)))
403
+ self.preview_var.set(bool(s.get("preview", True)))
404
+ if isinstance(s.get("hotkey"), str):
405
+ try:
406
+ hotkeys.parse(s["hotkey"])
407
+ self.hotkey = s["hotkey"]
408
+ except ValueError:
409
+ pass # keep the default; the settings file was edited by hand
410
+ self.hotkey_chk.configure(text="Hotkey %s" % hotkeys.display(self.hotkey))
411
+ if hotkeys.UNAVAILABLE:
412
+ self.hotkey_var.set(False)
413
+ self.hotkey_chk.configure(text="Hotkey (%s)" % hotkeys.UNAVAILABLE, state="disabled")
414
+ files = s.get("macro_files")
415
+ self.macro_files = [f for f in files if isinstance(f, str)] if isinstance(files, list) else []
416
+ self.macro_text = s.get("macro_text") if isinstance(s.get("macro_text"), str) else ""
417
+ self._update_macros_label()
418
+ self._restore_geometry(s.get("geometry", DEFAULT_GEOMETRY))
419
+ # as wide as the rows of options and buttons need (on a 150 % screen that is more than 960 pixels),
420
+ # but never wider than the screen
421
+ self.update_idletasks()
422
+ self.minsize(min(max(960, self.winfo_reqwidth()), self.winfo_screenwidth() - 40), 420)
423
+ self.input.insert("1.0", s.get("input") or SAMPLE)
424
+ self.input.edit_modified(False)
425
+ self._update_option_states()
426
+
427
+ def _save_settings(self) -> None:
428
+ text = self.input.get("1.0", "end-1c")
429
+ data = {"src": self.src_var.get(), "dst": self.dst_var.get(), "mode": self.mode_var.get(),
430
+ "wrapper": self.wrapper_var.get(), "auto_convert": self.auto_var.get(),
431
+ "annotate": self.annotate_var.get(), "tidy": self.tidy_var.get(),
432
+ "expand_macros": self.expand_var.get(),
433
+ "hotkey": self.hotkey,
434
+ # where there is no hotkey, the box is off without the user's say: keep their choice
435
+ "hotkey_enabled": (bool(self.settings.get("hotkey_enabled", True)) if hotkeys.UNAVAILABLE
436
+ else self.hotkey_var.get()),
437
+ "preview": self.preview_var.get(),
438
+ "macro_files": self.macro_files, "macro_text": self.macro_text, "geometry": self.geometry(),
439
+ # whole or not at all: a cut could land inside an equation, and a very large input
440
+ # (a whole document.xml) would be reloaded and converted again at every start
441
+ "input": text if len(text) <= MAX_SAVED_INPUT else ""}
442
+ if self.settings.get("theme") in theme.CHOICES: # set by hand in the file: kept
443
+ data["theme"] = self.settings["theme"]
444
+ try:
445
+ os.makedirs(os.path.dirname(SETTINGS_PATH), exist_ok=True)
446
+ with open(SETTINGS_PATH, "w", encoding="utf-8") as f:
447
+ json.dump(data, f, indent=1)
448
+ except Exception:
449
+ pass
450
+
451
+ def _on_close(self) -> None:
452
+ self._save_settings()
453
+ self._stop_hotkey()
454
+ if getattr(self, "_fetching", False): # a pandoc download: stopped, its part file removed
455
+ self._fetch_cancel.set()
456
+ self._fetch_thread.join(timeout=5)
457
+ self.destroy()
458
+
459
+ # ---- events ---------------------------------------------------------------------------------
460
+ def _startup_check(self) -> None:
461
+ try:
462
+ self.engine_var.set(engine_description())
463
+ except PandocNotFound as e:
464
+ self.engine_var.set("pandoc not found")
465
+ self._set_status("pandoc, the conversion engine, is not installed", error=True)
466
+ self._show_pandoc_banner(str(e))
467
+ return
468
+ except Exception as e: # pragma: no cover
469
+ self.engine_var.set("engine check failed")
470
+ self._set_status("pandoc check failed: %s" % e, error=True)
471
+ return
472
+ self._set_status("Ready")
473
+ self._toggle_hotkey()
474
+ self._in_background(preview.tools, self._latex_checked) # latex --version takes a moment
475
+ self._schedule()
476
+
477
+ # ---- pandoc missing: offer to download it -----------------------------------------------------
478
+ def _show_pandoc_banner(self, reason: str) -> None:
479
+ """A strip at the top of the window: pandoc is missing, Download installs pandoc's own release
480
+ (checked against its SHA-256) for this user. Not offered when MATHSHUTTLE_PANDOC names a file
481
+ that is not there: that setting would still win over the download."""
482
+ from . import pandoc_engine, pandoc_fetch
483
+ if getattr(self, "_banner", None) is not None:
484
+ self._banner.destroy()
485
+ banner = ttk.Frame(self, padding=(12, 10), style="Card.TFrame" if self.theme_mode != "native" else "TFrame")
486
+ banner.pack(side="top", fill="x", padx=10, pady=(10, 0), before=self._top)
487
+ self._banner = banner
488
+ env_name, env_value = pandoc_engine._env_pandoc()
489
+ self._banner_text = tk.StringVar(self)
490
+ ttk.Label(banner, textvariable=self._banner_text, wraplength=760, justify="left").pack(side="left", fill="x",
491
+ expand=True)
492
+ buttons = ttk.Frame(banner)
493
+ buttons.pack(side="right")
494
+ if env_value:
495
+ self._banner_text.set(reason)
496
+ return
497
+ try:
498
+ size = " (%d MB)" % round(pandoc_fetch._release_asset().size / 1e6)
499
+ except pandoc_fetch.FetchError as e: # no release for this system: only the manual way
500
+ self._banner_text.set(str(e))
501
+ return
502
+ self._banner_text.set("MathShuttle needs pandoc, the conversion engine, and it is not installed. "
503
+ "Download pandoc %s%s from pandoc's own release (checked before it is used), "
504
+ "or install it yourself with %s." % (pandoc_fetch.PANDOC_VERSION, size, INSTALL_HINT))
505
+ self._fetch_progress = ttk.Progressbar(buttons, length=160, mode="determinate", maximum=100)
506
+ self._fetch_button = ttk.Button(buttons, text="Download pandoc", style=self._accent(),
507
+ command=self._download_pandoc)
508
+ self._fetch_button.pack(side="right")
509
+
510
+ def _download_pandoc(self) -> None:
511
+ from . import pandoc_engine, pandoc_fetch
512
+ cancel = threading.Event()
513
+ state = {"done": 0, "total": None}
514
+
515
+ def progress(done, total): # (in the download thread: only numbers are handed over)
516
+ state["done"], state["total"] = done, total
517
+
518
+ def cancel_download():
519
+ cancel.set()
520
+ self._fetch_button.configure(state="disabled")
521
+
522
+ def tick():
523
+ # (after the end, a tick still queued must not put the progress back over the message)
524
+ if not self._fetching or not self._fetch_progress.winfo_exists() or cancel.is_set():
525
+ return
526
+ if state["total"]:
527
+ self._fetch_progress.configure(value=100 * state["done"] / state["total"])
528
+ self._banner_text.set("Downloading pandoc %s: %d of %d MB" % (
529
+ pandoc_fetch.PANDOC_VERSION, state["done"] // 1_000_000, state["total"] // 1_000_000))
530
+ if self._fetching:
531
+ self.after(150, tick)
532
+
533
+ def finished(path, error):
534
+ self._fetching = False
535
+ if error is None:
536
+ pandoc_engine.reset_pandoc()
537
+ self._banner.destroy()
538
+ self._banner = None
539
+ self._startup_check()
540
+ self._set_status("pandoc %s installed: %s" % (pandoc_fetch.PANDOC_VERSION, path))
541
+ return
542
+ self._fetch_progress.pack_forget()
543
+ self._fetch_button.configure(text="Try again", state="normal", style=self._accent(),
544
+ command=self._download_pandoc)
545
+ if isinstance(error, pandoc_fetch.FetchCancelled):
546
+ self._banner_text.set("The download was cancelled. Nothing was installed.")
547
+ else:
548
+ message = str(error) if isinstance(error, pandoc_fetch.FetchError) else repr(error)
549
+ self._banner_text.set(message)
550
+
551
+ self._fetching = True
552
+ self._fetch_cancel = cancel # closing the window stops the download (its part file is removed)
553
+ self._fetch_progress.configure(value=0)
554
+ self._fetch_progress.pack(side="right", padx=(0, 10))
555
+ self._fetch_button.configure(text="Cancel", style="TButton", command=cancel_download)
556
+ self._banner_text.set("Downloading pandoc %s..." % pandoc_fetch.PANDOC_VERSION)
557
+ self._fetch_thread = self._in_background(lambda: pandoc_fetch.install(progress=progress, cancel=cancel),
558
+ finished)
559
+ self.after(150, tick)
560
+
561
+ def _update_option_states(self) -> None:
562
+ src, dst = self.src_var.get(), self.dst_var.get()
563
+ self.wrapper_box.configure(state="readonly" if dst == "latex" else "disabled")
564
+ self.annotate_chk.configure(state="normal" if dst == "mathml" else "disabled")
565
+ self.tidy_chk.configure(state="normal" if src != "latex" else "disabled")
566
+ self.expand_chk.configure(state="normal" if src == dst == "latex" else "disabled")
567
+ self.input_caption.set("Input: %s" % FORMAT_LABELS.get(src, src))
568
+ self.output_caption.set("Output: %s" % FORMAT_LABELS.get(dst, dst))
569
+
570
+ def _macro_key(self) -> tuple:
571
+ """The macro files (with their modification times: an edited file gives another result), the text."""
572
+ return (tuple(self.macro_files), self.macro_text, compat.file_stamps(self.macro_files))
573
+
574
+ def _macros(self, key: Optional[tuple] = None) -> Optional[compat.Macros]:
575
+ files, text, _ = key or self._macro_key()
576
+ return compat.load_macros(files, text)
577
+
578
+ def _update_macros_label(self) -> None:
579
+ macros = self._macros()
580
+ self.macros_button.configure(text="Macros (%d)..." % len(macros) if macros is not None else "Macros...")
581
+
582
+ def _on_option_change(self) -> None:
583
+ self._update_option_states()
584
+ self._schedule()
585
+
586
+ def _on_input_modified(self, _event=None) -> None:
587
+ if self.input.edit_modified():
588
+ self.input.edit_modified(False)
589
+ self._schedule()
590
+
591
+ def _schedule(self) -> None:
592
+ if self._after_id:
593
+ self.after_cancel(self._after_id)
594
+ self._after_id = None
595
+ if self.auto_var.get():
596
+ self._after_id = self.after(DEBOUNCE_MS, self.convert_now)
597
+
598
+ # ---- actions --------------------------------------------------------------------------------
599
+ def _conversion_args(self) -> tuple:
600
+ """(text, src, dst, mode, wrapper, annotate, tidy, macro key, expand macros): everything a result
601
+ depends on."""
602
+ return (self.input.get("1.0", "end-1c"), self.src_var.get(), self.dst_var.get(), self.mode_var.get(),
603
+ self.wrapper_var.get(), self.annotate_var.get(), self.tidy_var.get(), self._macro_key(),
604
+ self.expand_var.get())
605
+
606
+ def _new_conversion(self) -> None:
607
+ """Results of conversions still running are stale from now on, and so is a pending debounced
608
+ one (typing, option change): the conversion about to start replaces them."""
609
+ if self._after_id:
610
+ self.after_cancel(self._after_id)
611
+ self._after_id = None
612
+ self._seq += 1
613
+
614
+ def convert_now(self) -> None:
615
+ self._new_conversion()
616
+ args = self._conversion_args()
617
+ if not args[0].strip():
618
+ self._set_output("")
619
+ self._set_status("")
620
+ self._clear_preview()
621
+ return
622
+ self._start(args)
623
+
624
+ def _start(self, args, swap: bool = False) -> None:
625
+ """Convert `args` in a background thread; with `swap`, the result completes a Swap."""
626
+ self._set_status("Converting...")
627
+ self._running += 1
628
+ threading.Thread(target=self._worker, args=(self._seq, args, swap), daemon=True).start()
629
+ if not self._polling:
630
+ self._polling = True
631
+ self.after(30, self._poll_results)
632
+
633
+ def _worker(self, seq: int, args, swap: bool) -> None:
634
+ """Runs in a background thread; only ever touches the queue."""
635
+ try:
636
+ result: object = convert(*args[:6], macros=self._macros(args[7]), tidy=args[6], expand_macros=args[8])
637
+ recalled = self._recalled
638
+ if (recalled and recalled[1] and recalled[0] == args[0] and args[1] == "mathml" and args[2] == "latex"
639
+ and args[6] and isinstance(result, Result)):
640
+ # pasted from Office unedited: the LaTeX it was copied from, as written (recall); not
641
+ # when Tidy is off, which asks for texmath's own LaTeX
642
+ from . import recall
643
+ tex, display = recalled[1]
644
+ display = display if args[3] == "auto" else args[3] == "display"
645
+ display = not latex_wrap.wrapper_is_inline(args[4], display)
646
+ notes = [recall.NOTE]
647
+ if latex_wrap.numbering_conflict(tex, args[4], display):
648
+ notes.append("\\tag / \\label commands were kept, but LaTeX allows no \\tag and at most one "
649
+ "\\label in this wrapper - edit them, or choose the align wrapper.")
650
+ result = Result([Equation(tex, latex_wrap.output_is_display(tex, args[4], display))],
651
+ [latex_wrap.wrap(tex, args[4], display)], notes)
652
+ except (ConversionError, PandocNotFound) as e:
653
+ result = e
654
+ except Exception: # pragma: no cover
655
+ result = ConversionError("Unexpected error:\n" + traceback.format_exc())
656
+ self._results.put((seq, args, result, swap))
657
+
658
+ def _poll_results(self) -> None:
659
+ while True:
660
+ try:
661
+ seq, args, result, swap = self._results.get_nowait()
662
+ except queue.Empty:
663
+ break
664
+ self._running -= 1
665
+ self._finish(seq, args, result, swap)
666
+ if self._running:
667
+ self.after(30, self._poll_results)
668
+ else:
669
+ self._polling = False
670
+
671
+ def _finish(self, seq: int, args, result, swap: bool = False) -> None:
672
+ if seq != self._seq:
673
+ return # a newer conversion has been started, or the input was cleared
674
+ if swap and self._conversion_args() != args:
675
+ # input or options changed while converting (auto-convert off: no newer conversion)
676
+ self._set_status("Swap cancelled: the input or the options changed", error=True)
677
+ return
678
+ if isinstance(result, Exception):
679
+ self._clear_preview() # the picture of the previous result no longer applies
680
+ self._set_output(str(result), error=True)
681
+ self._set_status("Cannot swap: the input does not convert" if swap else "Conversion failed", error=True)
682
+ return
683
+ assert isinstance(result, Result)
684
+ if swap:
685
+ self._swap_with(args, result.text)
686
+ return
687
+ self._set_output(result.text)
688
+ self._shown_args = args
689
+ self._last_result = (result, args)
690
+ self._start_preview(result, args)
691
+ n = len(result.equations)
692
+ mode = "display" if result.equations[0].display else "inline"
693
+ summary = "%s \u2192 %s (%s%s)" % (FORMAT_LABELS[args[1]], FORMAT_LABELS[args[2]],
694
+ "%d equations, " % n if n > 1 else "", mode)
695
+ self._set_status(" ".join([summary] + result.notes))
696
+
697
+ def copy_output(self) -> None:
698
+ text = self.output.get("1.0", "end-1c")
699
+ if not text.strip():
700
+ self._set_status("Nothing to copy", error=True)
701
+ return
702
+ self.clipboard_clear()
703
+ self.clipboard_append(text)
704
+ self._set_status("Output copied to the clipboard as text")
705
+
706
+ def copy_for_office(self) -> None:
707
+ """Word and PowerPoint paste one equation at a time: with several in the input, a menu lists
708
+ them, after a first item "Next", the equation after the one copied last. Keys: N (Windows; on the
709
+ Mac N, then Return) copies the next one, 1-9 the one with that number."""
710
+ text = self.input.get("1.0", "end-1c")
711
+ if not text.strip():
712
+ self._set_status("Nothing to copy", error=True)
713
+ return
714
+ # what the menu shows is what its items copy: input, settings and macros as they are now
715
+ key = self._copy_key(text)
716
+ macros = self._macros(key[4])
717
+ try:
718
+ eqs = input_equations(text, key[1], key[2], key[3])
719
+ except (ConversionError, PandocNotFound) as e:
720
+ self._set_output(str(e), error=True)
721
+ self._set_status("Could not copy the equation", error=True)
722
+ return
723
+ if len(eqs) <= 1:
724
+ self.copy_equation(0, key, eqs, macros)
725
+ return
726
+ labels = []
727
+ for i, eq in enumerate(eqs):
728
+ label = " ".join(eq.tex.split())
729
+ labels.append("%d %s" % (i + 1, label if len(label) <= 70 else label[:67] + "..."))
730
+ last = self._last_copy[1] if self._last_copy[0] == key else -1
731
+ nxt = (last + 1) % len(eqs)
732
+ if self._copy_menu is not None:
733
+ self._copy_menu.destroy() # the menu of the copy before (and the commands it holds)
734
+ menu = tk.Menu(self, tearoff=False)
735
+
736
+ def item(i: int):
737
+ return lambda: self.copy_equation(i, key, eqs, macros)
738
+ # native menus highlight nothing when they open: the next equation is an item of its own, first
739
+ menu.add_command(label="Next: " + labels[nxt], underline=0, command=item(nxt))
740
+ menu.add_separator()
741
+ for i, label in enumerate(labels):
742
+ menu.add_command(label=label, underline=0 if i < 9 else -1, command=item(i))
743
+ self._copy_menu = menu
744
+ button = self.copy_button
745
+ menu.tk_popup(button.winfo_rootx(), button.winfo_rooty() + button.winfo_height())
746
+
747
+ def _copy_key(self, text: str) -> tuple:
748
+ """What decides the equations of the input: the text, the source format, the mode, Tidy, the macros
749
+ (files with their modification times: an edited file starts Next again)."""
750
+ return (text, self.src_var.get(), self.mode_var.get(), self.tidy_var.get(), self._macro_key())
751
+
752
+ def copy_equation(self, index: int, key: Optional[tuple] = None, eqs=None, macros=None) -> None:
753
+ """Copy equation `index` (0: the first) of the input for Word / PowerPoint; with `key`, `eqs` and
754
+ `macros` as the menu took them (else the input and settings as they are now)."""
755
+ if key is None:
756
+ key, eqs = self._copy_key(self.input.get("1.0", "end-1c")), None
757
+ macros = self._macros(key[4])
758
+ text, src, mode, tidy = key[:4]
759
+ try:
760
+ copy = office_copy(text, src, mode, macros, tidy, index=index, eqs=eqs)
761
+ clipboard.copy_mathml_for_office(copy.mathml) # the plain text must be the MathML too (see there)
762
+ except (ConversionError, PandocNotFound, clipboard.ClipboardError) as e:
763
+ self._set_output(str(e), error=True)
764
+ self._set_status("Could not copy the equation", error=True)
765
+ return
766
+ copy.remember()
767
+ self._last_copy = (key, index)
768
+ msg = "Equation copied - press %s+V in Word / PowerPoint / OneNote to insert it as a native equation" % KEY
769
+ self._set_status(" ".join([msg] + copy.notes))
770
+
771
+ def paste_from_office(self) -> None:
772
+ try:
773
+ found = clipboard.read_office_equation()
774
+ except clipboard.ClipboardError as e:
775
+ self._set_status(str(e), error=True)
776
+ return
777
+ if not found:
778
+ self._set_status("No equation on the clipboard - select an equation in Word / PowerPoint and press %s+C first"
779
+ % KEY, error=True)
780
+ return
781
+ src, text = found # MathML, or OMML from the HTML that Word copies with a selection of text
782
+ self.src_var.set(src)
783
+ if self.dst_var.get() == src:
784
+ self.dst_var.set("latex")
785
+ # an equation copied from here that comes back unedited: its LaTeX as written (recall); the
786
+ # conversion of exactly this input gives that
787
+ from . import recall
788
+ recalled = recall.recall(text) if src == "mathml" else None
789
+ self.input.delete("1.0", "end")
790
+ self.input.insert("1.0", text)
791
+ self.input.edit_modified(False)
792
+ # (the input as the widget gives it back, which is what the conversion reads)
793
+ self._recalled = (self.input.get("1.0", "end-1c"), recalled) if recalled else None
794
+ self.convert_now()
795
+
796
+ def swap(self) -> None:
797
+ dst = self.dst_var.get()
798
+ if dst not in READ_FORMATS:
799
+ self._set_status("Cannot swap: %s cannot be used as input" % FORMAT_LABELS[dst], error=True)
800
+ return
801
+ args = self._conversion_args()
802
+ if self._shown_args == args:
803
+ self._swap_with(args, self.output.get("1.0", "end-1c")) # the current result (possibly edited by hand)
804
+ elif args[0].strip():
805
+ # The output pane is stale (auto-convert off, or a conversion still pending) or shows an
806
+ # error: it must not become input in the new format. Convert the current input first, in
807
+ # the background like any conversion; _finish completes the swap.
808
+ self._new_conversion()
809
+ self._start(args, swap=True)
810
+ else:
811
+ self._swap_with(args, "")
812
+
813
+ def _swap_with(self, args, output: str) -> None:
814
+ """Swap From and To of `args`; `output` (their result) becomes the input."""
815
+ self.src_var.set(args[2])
816
+ self.dst_var.set(args[1])
817
+ if output.strip():
818
+ self.input.delete("1.0", "end")
819
+ self.input.insert("1.0", output)
820
+ self.input.edit_modified(False)
821
+ self.convert_now()
822
+
823
+ def clear(self) -> None:
824
+ self._seq += 1 # drop the result of a conversion that is still running
825
+ self.input.delete("1.0", "end")
826
+ self.input.edit_modified(False)
827
+ self._set_output("")
828
+ self._set_status("")
829
+ self._clear_preview()
830
+ self.input.focus_set()
831
+
832
+ # ---- the LaTeX preview ------------------------------------------------------------------------
833
+ PREVIEW_MAX_HEIGHT = 240
834
+
835
+ def _latex_checked(self, found, error) -> None:
836
+ self._latex_found = bool(found) and error is None
837
+ if self._latex_found:
838
+ self.preview_chk.configure(state="normal")
839
+ preview.prune()
840
+ else:
841
+ self.preview_chk.configure(state="disabled", text="LaTeX preview (no LaTeX installation found)")
842
+ self._toggle_preview()
843
+
844
+ def _toggle_preview(self) -> None:
845
+ if self._latex_found and self.preview_var.get():
846
+ if not self.preview_frame.winfo_ismapped():
847
+ # packed after the button bar (both at the bottom): it sits above the buttons
848
+ self.preview_frame.pack(fill="x", side="bottom", padx=10, pady=(0, 2), after=self._bottom_bar)
849
+ if self._last_result is not None and self._shown_args == self._last_result[1]:
850
+ self._start_preview(*self._last_result) # the result on show (not converted again: it may be edited)
851
+ else:
852
+ self._clear_preview()
853
+ self.preview_frame.pack_forget()
854
+
855
+ def _clear_preview(self) -> None:
856
+ """No picture (Clear, an empty input, an error); renders still running are stale."""
857
+ self._preview_seq += 1
858
+ self._preview_image = None
859
+ self.preview_label.configure(image="", text="")
860
+
861
+ def _start_preview(self, result, args) -> None:
862
+ """Draw the LaTeX side of a result in the background: the input when converting from LaTeX,
863
+ else the LaTeX the input reads as (tidied, as Paste from Office gives it)."""
864
+ if not (self._latex_found and self.preview_var.get()):
865
+ return
866
+ self._preview_seq += 1
867
+ seq = self._preview_seq
868
+ src, tidy, macros = args[1], args[6], self._macros(args[7])
869
+ if src == "latex": # with the definitions written into the input that pandoc does not apply, as converted
870
+ from .convert import _MARKDOWN_NOTE, input_macros
871
+ macros = input_macros(macros, args[0], src, _MARKDOWN_NOTE in result.notes)
872
+ equations = list(result.equations[:6])
873
+ dpi = max(96, int(self.winfo_fpixels("1i") * 1.15))
874
+
875
+ def work():
876
+ from . import packs
877
+ from .convert import tidied
878
+ eqs = [tidied(eq) if src != "latex" and tidy else eq for eq in equations]
879
+ tex = " ".join(e.tex for e in eqs)
880
+ definitions = preview.definitions_for(tex, macros if src == "latex" else None)
881
+ needed: list = []
882
+ if src == "latex": # per equation (one equation's own \def\abs is not another's)
883
+ defined = set(macros.definitions) if macros is not None else set()
884
+ loaded = macros.packages if macros is not None else set()
885
+ for e in eqs:
886
+ needed += [p for p in packs.packages_for(e.tex, defined, loaded) if p not in needed]
887
+ if {"physics", "braket"} <= set(needed):
888
+ needed.remove("physics" if "braket" in loaded and "physics" not in loaded else "braket")
889
+ return preview.render(eqs, definitions, dpi=dpi, packages=needed), len(result.equations)
890
+
891
+ self._in_background(work, lambda value, error: self._show_preview(seq, value, error))
892
+
893
+ def _show_preview(self, seq, value, error) -> None:
894
+ if seq != self._preview_seq:
895
+ return # a newer result is being drawn
896
+ if error is not None:
897
+ self._preview_image = None
898
+ message = str(error) if isinstance(error, (preview.PreviewError, ConversionError)) else repr(error)
899
+ self.preview_label.configure(image="", text="Preview: " + message.splitlines()[0], fg="#8b1a1a")
900
+ return
901
+ path, total = value
902
+ try:
903
+ image = tk.PhotoImage(file=path)
904
+ except tk.TclError as e:
905
+ self.preview_label.configure(image="", text="Preview: %s" % e, fg="#8b1a1a")
906
+ return
907
+ width = max(200, self.winfo_width() - 40)
908
+ factor = max(1, -(-image.width() // width), -(-image.height() // self.PREVIEW_MAX_HEIGHT))
909
+ if factor > 1:
910
+ image = image.subsample(factor)
911
+ self._preview_image = image
912
+ more = " (first 6 of %d equations)" % total if total > 6 else ""
913
+ self.preview_label.configure(image=image, text=more, compound="left", fg="#555555")
914
+
915
+ # ---- the hotkey: shuttle the clipboard ------------------------------------------------------
916
+ def _toggle_hotkey(self) -> None:
917
+ """Listen for the hotkey while the box is ticked (and the app runs, even minimised)."""
918
+ self._stop_hotkey()
919
+ if not self.hotkey_var.get() or hotkeys.UNAVAILABLE:
920
+ return
921
+ listener = hotkeys.HotkeyListener(self.hotkey)
922
+ error = listener.start_and_wait()
923
+ if error:
924
+ self.hotkey_var.set(False)
925
+ self._set_status("Hotkey off: %s (change \"hotkey\" in %s)" % (error, SETTINGS_PATH), error=True)
926
+ return
927
+ self._listener = listener
928
+ self._poll_hotkey(listener)
929
+
930
+ def _stop_hotkey(self) -> None:
931
+ if self._listener is not None:
932
+ self._listener.stop()
933
+ self._listener = None
934
+
935
+ def _poll_hotkey(self, listener) -> None:
936
+ if listener is not self._listener:
937
+ return # replaced or stopped
938
+ pressed = False
939
+ while True:
940
+ try:
941
+ listener.presses.get_nowait()
942
+ pressed = True
943
+ except queue.Empty:
944
+ break
945
+ if pressed:
946
+ self.shuttle_clipboard()
947
+ self.after(120, self._poll_hotkey, listener)
948
+
949
+ def shuttle_clipboard(self, done=None) -> None:
950
+ """The hotkey: an equation copied in Office (or MathML / OMML text) becomes LaTeX text; LaTeX text
951
+ becomes an equation to paste into Office. Uses the Mode, LaTeX wrapper, Macros and Tidy settings."""
952
+ mode, wrapper, tidy, macros = self.mode_var.get(), self.wrapper_var.get(), self.tidy_var.get(), self._macros()
953
+
954
+ def work():
955
+ # what was copied: if something else is copied while this converts, it is not overwritten
956
+ sequence = clipboard.sequence_number()
957
+ found = clipboard.read_office_equation()
958
+ if found:
959
+ src, text = found
960
+ else:
961
+ text = clipboard.get_text() or ""
962
+ src = ("mathml" if re.search(r"<(\w+:)?math\b", text) else
963
+ "omml" if re.search(r"<m:oMath", text) else "latex")
964
+ if src != "latex":
965
+ from . import recall
966
+ recalled = recall.latex_for(text, wrapper, mode) if src == "mathml" and tidy else None
967
+ latex = recalled or convert(text, src, "latex", mode, wrapper, tidy=tidy).text
968
+ clipboard.set_text(latex, expect_sequence=sequence)
969
+ return "LaTeX copied%s: %s" % (" (as it was copied, unedited)" if recalled else "",
970
+ " ".join(latex.split())[:70]), False
971
+ if not text.strip():
972
+ return "Nothing to convert: copy LaTeX, or an equation in Word / PowerPoint, first", True
973
+ copy = office_copy(text, "latex", mode, macros)
974
+ clipboard.copy_mathml_for_office(copy.mathml, expect_sequence=sequence)
975
+ copy.remember()
976
+ return " ".join(["Equation ready: press %s+V in Word / PowerPoint" % KEY] + copy.notes), False
977
+
978
+ def finished(value, error):
979
+ if error is not None:
980
+ lines = str(error).strip().splitlines() or [repr(error)]
981
+ message, failed = "Could not convert the clipboard: %s" % lines[-1], True
982
+ else:
983
+ message, failed = value
984
+ self._set_status(message, error=failed)
985
+ Toast(self, message, error=failed)
986
+ if done:
987
+ done(message, failed)
988
+
989
+ self._in_background(work, finished)
990
+
991
+ # ---- documents ------------------------------------------------------------------------------
992
+ def _in_background(self, work, done, daemon: bool = True) -> threading.Thread:
993
+ """Run `work()` in a thread; call `done(value, error)` in the Tk thread when it ends. Not a daemon:
994
+ work (a file being written) that the program finishes even when its window closes first."""
995
+ result: dict = {}
996
+
997
+ def run():
998
+ try:
999
+ result["value"] = work()
1000
+ except Exception as e: # reported by `done`
1001
+ result["error"] = e
1002
+
1003
+ thread = threading.Thread(target=run, daemon=daemon)
1004
+ thread.start()
1005
+
1006
+ def poll():
1007
+ try:
1008
+ if thread.is_alive():
1009
+ self.after(50, poll)
1010
+ else:
1011
+ done(result.get("value"), result.get("error"))
1012
+ except tk.TclError:
1013
+ pass # the window closed meanwhile (the thread still finishes its work)
1014
+
1015
+ self.after(50, poll)
1016
+ return thread
1017
+
1018
+ def save_as_word(self, path: Optional[str] = None) -> None:
1019
+ """The input as a Word document: a chat answer, notes or LaTeX text with its prose, and each
1020
+ equation a native Word equation (wordexport.passage_to_word)."""
1021
+ text = self.input.get("1.0", "end-1c")
1022
+ if self.src_var.get() != "latex":
1023
+ self._set_status("Save as Word takes LaTeX or Markdown input (a chat answer, notes)", error=True)
1024
+ return
1025
+ if not text.strip():
1026
+ self._set_status("Nothing to save: the input is empty", error=True)
1027
+ return
1028
+ path = path or filedialog.asksaveasfilename(
1029
+ parent=self, title="Save the input as a Word document", defaultextension=".docx",
1030
+ initialfile="equations.docx", filetypes=[("Word document", "*.docx"), ("All files", "*.*")])
1031
+ if not path:
1032
+ return
1033
+ from .wordexport import passage_to_word
1034
+ macros = self._macros()
1035
+ self._set_status("Writing %s..." % os.path.basename(path))
1036
+
1037
+ def done(notes, error) -> None:
1038
+ if error is not None:
1039
+ if not isinstance(error, (ConversionError, PandocNotFound)):
1040
+ raise error
1041
+ self._set_status(str(error).splitlines()[0] if str(error).strip() else "Could not save", error=True)
1042
+ return
1043
+ self._set_status(" ".join(["Written: %s" % os.path.basename(path)] + (notes or [])))
1044
+ self._in_background(lambda: passage_to_word(text, path, macros), done, daemon=False)
1045
+
1046
+ def open_document(self, path: Optional[str] = None) -> None:
1047
+ """List the equations of a .docx / .pptx / .tex / .md file (Open file...)."""
1048
+ from .documents import FILE_TYPES, read_document
1049
+ path = path or filedialog.askopenfilename(parent=self, title="Open a document with equations",
1050
+ filetypes=FILE_TYPES + [("All files", "*.*")])
1051
+ if not path:
1052
+ return
1053
+ self._set_status("Reading %s..." % os.path.basename(path))
1054
+
1055
+ def done(doc, error):
1056
+ if error is not None:
1057
+ message = str(error) if isinstance(error, (ConversionError, PandocNotFound)) else repr(error)
1058
+ self._set_status("Could not read %s: %s" % (os.path.basename(path), message.splitlines()[0]), error=True)
1059
+ return
1060
+ self._set_status("%d equations in %s" % (len(doc.found), os.path.basename(path)))
1061
+ self._show_equations(doc)
1062
+
1063
+ self._in_background(lambda: read_document(path), done)
1064
+
1065
+ def _show_equations(self, doc) -> "EquationList":
1066
+ return EquationList(self, doc)
1067
+
1068
+ def edit_macros(self) -> None:
1069
+ """Macro files and extra definitions applied to every LaTeX input."""
1070
+ win = self._dialog("MathShuttle macros")
1071
+ pad = {"padx": 10, "pady": 4}
1072
+ ttk.Label(win, text="Macro files (definitions are read from them; everything else is ignored):").pack(anchor="w", **pad)
1073
+ files = list(self.macro_files)
1074
+ listbox = tk.Listbox(win, height=5, width=90, font=self.mono)
1075
+ theme.style_text(listbox, self.theme_mode)
1076
+ listbox.pack(fill="x", **pad)
1077
+ for f in files:
1078
+ listbox.insert("end", f)
1079
+ row = ttk.Frame(win)
1080
+ row.pack(fill="x", **pad)
1081
+
1082
+ def add():
1083
+ for path in filedialog.askopenfilenames(parent=win, title="Macro files",
1084
+ filetypes=[("LaTeX", "*.tex *.sty *.cls"), ("All files", "*.*")]):
1085
+ path = os.path.normpath(path)
1086
+ if path not in files:
1087
+ files.append(path)
1088
+ listbox.insert("end", path)
1089
+ refresh()
1090
+
1091
+ def remove():
1092
+ for i in reversed(listbox.curselection()):
1093
+ del files[i]
1094
+ listbox.delete(i)
1095
+ refresh()
1096
+
1097
+ ttk.Button(row, text="Add files...", command=add).pack(side="left")
1098
+ ttk.Button(row, text="Remove", command=remove).pack(side="left", padx=6)
1099
+ ttk.Label(win, text="More definitions (\\newcommand, \\def, \\let, \\DeclareMathOperator, \\DeclarePairedDelimiter):").pack(anchor="w", **pad)
1100
+ text = tk.Text(win, height=8, width=90, font=self.mono, undo=True, padx=6, pady=6)
1101
+ theme.style_text(text, self.theme_mode)
1102
+ text.insert("1.0", self.macro_text)
1103
+ text.pack(fill="both", expand=True, **pad)
1104
+ info = tk.StringVar()
1105
+ ttk.Label(win, textvariable=info, wraplength=700, justify="left").pack(anchor="w", **pad)
1106
+
1107
+ def refresh(*_):
1108
+ macros = compat.load_macros(files, text.get("1.0", "end-1c"))
1109
+ if macros is None:
1110
+ info.set("No macros: LaTeX input uses only what it defines itself.")
1111
+ return
1112
+ names = sorted(macros.definitions)
1113
+ shown = ", ".join(names[:30]) + (" ..." if len(names) > 30 else "")
1114
+ info.set("\n".join(["%d definitions: %s" % (len(names), shown)] + macro_notes(macros)))
1115
+
1116
+ text.bind("<KeyRelease>", refresh)
1117
+ refresh()
1118
+
1119
+ def ok():
1120
+ self.macro_files = list(files)
1121
+ self.macro_text = text.get("1.0", "end-1c")
1122
+ self._update_macros_label()
1123
+ self._save_settings()
1124
+ win.destroy()
1125
+ self._schedule()
1126
+
1127
+ buttons = ttk.Frame(win)
1128
+ buttons.pack(fill="x", **pad)
1129
+ ttk.Button(buttons, text="Cancel", command=win.destroy).pack(side="right")
1130
+ ttk.Button(buttons, text="OK", command=ok).pack(side="right", padx=6)
1131
+
1132
+ def show_help(self) -> None:
1133
+ try:
1134
+ engine = engine_report()
1135
+ except (PandocNotFound, ConversionError) as e:
1136
+ engine = str(e)
1137
+ win = self._dialog("MathShuttle help")
1138
+ buttons = ttk.Frame(win, padding=(10, 6, 10, 10))
1139
+ buttons.pack(fill="x", side="bottom")
1140
+ txt = tk.Text(win, wrap="word", font=self.mono, padx=12, pady=10, width=92, height=32)
1141
+ theme.style_text(txt, self.theme_mode)
1142
+ txt.insert("1.0", HELP + "\nENGINE\n" + "".join(" %s\n" % line for line in engine.splitlines()))
1143
+ txt.configure(state="disabled")
1144
+ txt.pack(fill="both", expand=True, padx=10, pady=(10, 0))
1145
+
1146
+ def copy_details():
1147
+ self.clipboard_clear()
1148
+ self.clipboard_append(bug_report_details(self))
1149
+ done.set("Copied: paste it into the issue on GitHub.")
1150
+
1151
+ done = tk.StringVar(win)
1152
+ ttk.Button(buttons, text="Close", command=win.destroy).pack(side="right")
1153
+ ttk.Button(buttons, text="Copy details for a bug report", command=copy_details).pack(side="left")
1154
+ ttk.Label(buttons, textvariable=done, style="Caption.TLabel").pack(side="left", padx=10)
1155
+
1156
+ def _dialog(self, title: str) -> tk.Toplevel:
1157
+ """A window of the app's own (help, macros): in front of the main window, in its colours."""
1158
+ win = tk.Toplevel(self)
1159
+ win.title(title)
1160
+ win.transient(self)
1161
+ if self.theme_mode == "dark":
1162
+ theme.dark_title_bar(win, True)
1163
+ return win
1164
+
1165
+ # ---- helpers --------------------------------------------------------------------------------
1166
+ def _set_output(self, text: str, error: bool = False) -> None:
1167
+ self._shown_args = None
1168
+ self.output.delete("1.0", "end")
1169
+ self.output.insert("1.0", text, ("error",) if error else ())
1170
+
1171
+ def _set_status(self, text: str, error: bool = False) -> None:
1172
+ self.status_var.set(text)
1173
+ self.status_label.configure(foreground=self.palette["error"] if error else "")
1174
+
1175
+
1176
+ def bug_report_details(app: Optional["App"] = None) -> str:
1177
+ """What an issue on GitHub needs to know: versions of MathShuttle, the system, Python, Tk and the
1178
+ engine. Paths under the home folder are written from ~, so the user name stays out of a public issue."""
1179
+ import platform
1180
+ lines = ["MathShuttle %s (%s)" % (__version__, "app" if getattr(sys, "frozen", False) else "Python source")]
1181
+ if MAC:
1182
+ lines.append("macOS %s (%s)" % (platform.mac_ver()[0], platform.machine()))
1183
+ else:
1184
+ lines.append("%s (%s)" % (platform.platform(), platform.machine()))
1185
+ tk_version = app.tk.call("info", "patchlevel") if app is not None else tk.TkVersion
1186
+ lines.append("Python %s, Tk %s%s" % (platform.python_version(), tk_version,
1187
+ ", %s look" % app.theme_mode if app is not None else ""))
1188
+ try:
1189
+ lines += engine_report().splitlines()
1190
+ except (PandocNotFound, ConversionError) as e:
1191
+ lines.append("pandoc: %s" % str(e).splitlines()[0])
1192
+ if app is not None:
1193
+ lines.append("LaTeX preview: %s" % {True: "on", False: "no LaTeX installation found",
1194
+ None: "not checked"}[app._latex_found])
1195
+ lines.append("Word / PowerPoint version: (please add: File > Account > About)")
1196
+ home = os.path.expanduser("~")
1197
+ text = "\n".join(lines)
1198
+ if len(home) > 3: # not a bare drive or "/"
1199
+ # as written in paths, in Python's repr (C:\\Users\\...), with forward slashes; any case on Windows
1200
+ for form in dict.fromkeys((home, home.replace("\\", "\\\\"), home.replace("\\", "/"))):
1201
+ text = re.sub(re.escape(form), "~", text, flags=re.IGNORECASE if sys.platform == "win32" else 0)
1202
+ return text + "\n"
1203
+
1204
+
1205
+ class Toast(tk.Toplevel):
1206
+ """A short message at the bottom right of the screen that does not take the focus (the user is
1207
+ working in Word / PowerPoint when the hotkey is pressed)."""
1208
+
1209
+ def __init__(self, app: App, text: str, error: bool = False, ms: int = 2600) -> None:
1210
+ super().__init__(app)
1211
+ self.withdraw()
1212
+ self.overrideredirect(True)
1213
+ tk.Label(self, text="MathShuttle: " + text, padx=14, pady=9, wraplength=520, justify="left",
1214
+ bg="#8b1a1a" if error else "#202124", fg="white").pack()
1215
+ self.update_idletasks()
1216
+ self.geometry("+%d+%d" % (self.winfo_screenwidth() - self.winfo_reqwidth() - 24,
1217
+ self.winfo_screenheight() - self.winfo_reqheight() - 72))
1218
+ try:
1219
+ user32 = ctypes.windll.user32
1220
+ user32.GetParent.restype = ctypes.c_void_p
1221
+ user32.GetParent.argtypes = [ctypes.c_void_p]
1222
+ user32.GetWindowLongW.argtypes = [ctypes.c_void_p, ctypes.c_int]
1223
+ user32.SetWindowLongW.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_long]
1224
+ hwnd = user32.GetParent(self.winfo_id()) or self.winfo_id()
1225
+ # WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW: never the active window, no taskbar button
1226
+ user32.SetWindowLongW(hwnd, -20, user32.GetWindowLongW(hwnd, -20) | 0x08000000 | 0x80)
1227
+ except (AttributeError, OSError):
1228
+ pass
1229
+ self.attributes("-topmost", True)
1230
+ self.deiconify() # (a program in the background cannot take the foreground from Word anyway)
1231
+ self.after(ms, self.destroy)
1232
+
1233
+
1234
+ def _written(count: int, path: str) -> str:
1235
+ return "%d equation%s written to %s" % (count, "" if count == 1 else "s", path)
1236
+
1237
+
1238
+ class EquationList(tk.Toplevel):
1239
+ """Browse and filter a document's equations, or export a selection."""
1240
+
1241
+ def __init__(self, app: App, doc) -> None:
1242
+ super().__init__(app)
1243
+ self.app, self.doc = app, doc
1244
+ self.title("Equations in %s" % os.path.basename(doc.path))
1245
+ self.transient(app)
1246
+ if app.theme_mode == "dark":
1247
+ theme.dark_title_bar(self, True)
1248
+ pad = {"padx": 6, "pady": 4}
1249
+ self.info = tk.StringVar(self)
1250
+ ttk.Label(self, textvariable=self.info, wraplength=900, justify="left").pack(anchor="w", **pad)
1251
+
1252
+ filters = ttk.Frame(self)
1253
+ filters.pack(fill="x", **pad)
1254
+ self.filter_var = tk.StringVar(self)
1255
+ self.display_var = tk.BooleanVar(self, value=len(doc.found) > 200)
1256
+ self.distinct_var = tk.BooleanVar(self, value=False)
1257
+ ttk.Label(filters, text="Filter").pack(side="left")
1258
+ ttk.Entry(filters, textvariable=self.filter_var).pack(side="left", fill="x", expand=True, padx=6)
1259
+ ttk.Checkbutton(filters, text="Display only", variable=self.display_var).pack(side="left")
1260
+ ttk.Checkbutton(filters, text="Distinct only", variable=self.distinct_var).pack(side="left")
1261
+
1262
+ style = ttk.Style(self)
1263
+ style.configure("Equations.Treeview", rowheight=int(app.mono.metrics("linespace") * 1.35), font=app.mono)
1264
+ frame = ttk.Frame(self)
1265
+ frame.pack(fill="both", expand=True, **pad)
1266
+ self.tree = ttk.Treeview(frame, columns=("where", "equation", "context"), show="headings",
1267
+ selectmode="extended", style="Equations.Treeview", height=14)
1268
+ for column, title, width in (("where", "Where", 220), ("equation", "Equation (LaTeX)", 520),
1269
+ ("context", "Context", 300)):
1270
+ self.tree.heading(column, text=title, anchor="w")
1271
+ self.tree.column(column, width=width, anchor="w")
1272
+ scroll = ttk.Scrollbar(frame, command=self.tree.yview)
1273
+ self.tree.configure(yscrollcommand=scroll.set)
1274
+ scroll.pack(side="right", fill="y")
1275
+ self.tree.pack(side="left", fill="both", expand=True)
1276
+ self._locations = {}
1277
+ self._refresh_id = None
1278
+ self._refresh()
1279
+ self._traces = [(var, var.trace_add("write", self._schedule_refresh))
1280
+ for var in (self.filter_var, self.display_var, self.distinct_var)]
1281
+ self.tree.bind("<Double-1>", lambda e: self.use())
1282
+ self.tree.bind("<Return>", lambda e: self.use())
1283
+
1284
+ buttons = ttk.Frame(self)
1285
+ buttons.pack(fill="x", **pad)
1286
+ ttk.Button(buttons, text="Use as input", command=self.use).pack(side="left")
1287
+ ttk.Button(buttons, text="Copy for Word/PowerPoint", command=self.copy_for_office).pack(side="left", padx=6)
1288
+ ttk.Button(buttons, text="Copy LaTeX", command=self.copy_latex).pack(side="left")
1289
+ ttk.Button(buttons, text="Export all as .tex...", command=self.export).pack(side="left", padx=6)
1290
+ ttk.Button(buttons, text="as .docx...", command=self.export_docx).pack(side="left")
1291
+ ttk.Button(buttons, text="Export selected as .tex...", command=self.export_selected).pack(side="left", padx=6)
1292
+ if os.path.splitext(doc.path)[1].lower() in (".tex", ".md"): # the text too (wordexport)
1293
+ ttk.Button(buttons, text="Whole file as Word...", command=self.save_document_as_word).pack(side="left")
1294
+ ttk.Button(buttons, text="Close", command=self.destroy).pack(side="right")
1295
+
1296
+ def destroy(self):
1297
+ if self._refresh_id is not None:
1298
+ self.after_cancel(self._refresh_id)
1299
+ for var, callback in self._traces:
1300
+ var.trace_remove("write", callback)
1301
+ super().destroy()
1302
+
1303
+ def _schedule_refresh(self, *_):
1304
+ if self._refresh_id is None:
1305
+ self._refresh_id = self.after_idle(self._refresh)
1306
+
1307
+ def _refresh(self):
1308
+ self._refresh_id = None
1309
+ rows = self.doc.rows(self.display_var.get(), self.distinct_var.get(), self.filter_var.get())
1310
+ self._visible = {str(row.number - 1): row for row in rows}
1311
+ selection = self.tree.selection()
1312
+ for iid, row in self._visible.items():
1313
+ location = row.location
1314
+ if iid not in self._locations:
1315
+ self.tree.insert("", "end", iid=iid, values=(
1316
+ location, " ".join(row.found.equation.tex.split()), row.found.context))
1317
+ elif self._locations[iid] != location:
1318
+ self.tree.set(iid, "where", location)
1319
+ self._locations[iid] = location
1320
+ # Reattach cached items in one Tk call. Filtering never deletes and rebuilds thousands of rows.
1321
+ self.tree.set_children("", *self._visible)
1322
+ selected = [iid for iid in selection if iid in self._visible]
1323
+ if not selected and rows:
1324
+ selected = [next(iter(self._visible))]
1325
+ self.tree.selection_set(selected)
1326
+ if selected:
1327
+ self.tree.focus(selected[0])
1328
+ total = len(self.doc.found)
1329
+ summary = f"{total} equation{'s' if total != 1 else ''}"
1330
+ if len(rows) != total:
1331
+ summary += f", {len(rows)} shown"
1332
+ self.info.set(" ".join([summary] + self.doc.notes))
1333
+
1334
+ def _selected(self):
1335
+ selection = self.tree.selection()
1336
+ if not selection:
1337
+ self.info.set("Select an equation first")
1338
+ return None
1339
+ return self.doc.found[int(selection[0])]
1340
+
1341
+ @staticmethod
1342
+ def _latex(found) -> str:
1343
+ return latex_wrap.wrap(found.equation.tex, "auto", found.equation.display)
1344
+
1345
+ def _macros(self):
1346
+ """The user's macros, plus a .tex file's own definitions for its equations."""
1347
+ user = self.app._macros()
1348
+ return self.doc.macros(user) if self.doc.source == "latex" else user
1349
+
1350
+ def _with_definitions(self, found) -> str:
1351
+ """The equation as LaTeX, after the document's own definitions it needs that pandoc left
1352
+ (\\DeclarePairedDelimiter...): in the main window they then apply as definitions in the input."""
1353
+ latex = self._latex(found)
1354
+ own = self.doc.macros(None) if self.doc.source == "latex" else None
1355
+ if own is None:
1356
+ return latex
1357
+ # (all of them: in the window they then win over the user's macros, as for the document), and the
1358
+ # packages that decide what pack commands mean (braket's \braket{a} is not physics')
1359
+ from .packs import PACKS
1360
+ packages = {p for p, _, _ in PACKS.values()} & own.packages
1361
+ needed = [d.source for d in own.needed(found.equation.tex)]
1362
+ return "\n".join(["\\usepackage{%s}" % p for p in sorted(packages)] + needed + [latex])
1363
+
1364
+ def use(self) -> None:
1365
+ found = self._selected()
1366
+ if found is None:
1367
+ return
1368
+ app = self.app
1369
+ app.src_var.set("latex")
1370
+ app.input.delete("1.0", "end")
1371
+ app.input.insert("1.0", self._with_definitions(found))
1372
+ app.input.edit_modified(False)
1373
+ app.convert_now()
1374
+ app.lift()
1375
+
1376
+ def copy_for_office(self) -> None:
1377
+ found = self._selected()
1378
+ if found is None:
1379
+ return
1380
+ try:
1381
+ copy = office_copy(self._latex(found), "latex", self.app.mode_var.get(), self._macros())
1382
+ clipboard.copy_mathml_for_office(copy.mathml)
1383
+ except (ConversionError, PandocNotFound, clipboard.ClipboardError) as e:
1384
+ self.info.set("Could not copy: %s" % str(e).splitlines()[0])
1385
+ return
1386
+ copy.remember()
1387
+ self.info.set(" ".join(["Copied: press %s+V in Word / PowerPoint" % KEY] + copy.notes))
1388
+
1389
+ def copy_latex(self) -> None:
1390
+ found = self._selected()
1391
+ if found is None:
1392
+ return
1393
+ self.clipboard_clear()
1394
+ self.clipboard_append(self._latex(found))
1395
+ self.info.set("LaTeX copied")
1396
+
1397
+ def export(self, path: Optional[str] = None) -> None:
1398
+ self._export_rows(self.doc.rows(), path)
1399
+
1400
+ def export_selected(self, path: Optional[str] = None) -> None:
1401
+ selected = self.tree.selection()
1402
+ if not selected:
1403
+ self.info.set("Select an equation first")
1404
+ return
1405
+ self._export_rows([self._visible[i] for i in selected], path)
1406
+
1407
+ def _export_rows(self, rows, path: Optional[str]) -> None:
1408
+ path = path or filedialog.asksaveasfilename(
1409
+ parent=self, title="Export the equations", defaultextension=".tex",
1410
+ initialfile=os.path.splitext(os.path.basename(self.doc.path))[0] + "-equations.tex",
1411
+ filetypes=[("LaTeX", "*.tex"), ("All files", "*.*")])
1412
+ if not path:
1413
+ return
1414
+ text = "".join("%% [%d] %s\n%s\n\n" % (row.number, row.location, self._latex(row.found)) for row in rows)
1415
+ try:
1416
+ with open(path, "w", encoding="utf-8", newline="\n") as f:
1417
+ f.write("%% equations of %s (MathShuttle)\n\n%s" % (os.path.basename(self.doc.path), text))
1418
+ except OSError as e:
1419
+ self.info.set("Could not write %s: %s" % (path, e.strerror or e))
1420
+ return
1421
+ self.info.set(_written(len(rows), path))
1422
+
1423
+ def export_docx(self, path: Optional[str] = None) -> None:
1424
+ """All the equations as native equations in a Word document, each under where it was."""
1425
+ path = path or filedialog.asksaveasfilename(
1426
+ parent=self, title="Export the equations to Word", defaultextension=".docx",
1427
+ initialfile=os.path.splitext(os.path.basename(self.doc.path))[0] + "-equations.docx",
1428
+ filetypes=[("Word document", "*.docx"), ("All files", "*.*")])
1429
+ if not path:
1430
+ return
1431
+ from .documents import write_docx
1432
+ macros = self.app._macros() # (write_docx adds the document's own definitions)
1433
+ self.info.set("Writing %s..." % os.path.basename(path))
1434
+
1435
+ def done(notes, error) -> None:
1436
+ if not self.winfo_exists():
1437
+ return
1438
+ if error is not None:
1439
+ if not isinstance(error, (ConversionError, PandocNotFound)):
1440
+ raise error
1441
+ self.info.set(str(error).splitlines()[-1] if str(error).strip() else "Could not export")
1442
+ return
1443
+ self.info.set(" ".join([_written(len(self.doc.found), path)] + notes))
1444
+ self.app._in_background(lambda: write_docx(self.doc, path, macros), done, daemon=False)
1445
+
1446
+ def save_document_as_word(self, path: Optional[str] = None) -> None:
1447
+ """The whole .tex / .md file as a Word document: its text, headings and lists, each equation a
1448
+ native Word equation, numbered and referenced as in the paper (wordexport.document_to_word)."""
1449
+ path = path or filedialog.asksaveasfilename(
1450
+ parent=self, title="Save the whole file as a Word document", defaultextension=".docx",
1451
+ initialfile=os.path.splitext(os.path.basename(self.doc.path))[0] + ".docx",
1452
+ filetypes=[("Word document", "*.docx"), ("All files", "*.*")])
1453
+ if not path:
1454
+ return
1455
+ if os.path.normcase(os.path.abspath(path)) == os.path.normcase(os.path.abspath(self.doc.path)):
1456
+ self.info.set("Choose another file name: that is the file being read")
1457
+ return
1458
+ from .wordexport import document_to_word
1459
+ macros = self.app._macros() # (document_to_word adds the file's own definitions)
1460
+ source = self.doc.path
1461
+ self.info.set("Writing %s..." % os.path.basename(path))
1462
+
1463
+ def done(notes, error) -> None:
1464
+ if not self.winfo_exists():
1465
+ return
1466
+ if error is not None:
1467
+ if not isinstance(error, (ConversionError, PandocNotFound)):
1468
+ raise error
1469
+ self.info.set(str(error).splitlines()[-1] if str(error).strip() else "Could not save")
1470
+ return
1471
+ self.info.set(" ".join(["Written: %s" % os.path.basename(path)] + (notes or [])))
1472
+ self.app._in_background(lambda: document_to_word(source, path, macros), done, daemon=False)
1473
+
1474
+
1475
+ def main() -> int:
1476
+ _enable_dpi_awareness()
1477
+ app = App()
1478
+ app.mainloop()
1479
+ return 0
1480
+
1481
+
1482
+ if __name__ == "__main__": # pragma: no cover
1483
+ sys.exit(main())