-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy patheditor.py
1763 lines (1489 loc) · 59.8 KB
/
editor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from __future__ import annotations
import base64
import functools
import html
import itertools
import json
import mimetypes
import os
import re
import urllib.error
import urllib.parse
import urllib.request
import warnings
from collections.abc import Callable
from enum import Enum
from random import randrange
from typing import Any, Iterable, Match, cast
import bs4
import requests
from bs4 import BeautifulSoup
import aqt
import aqt.forms
import aqt.operations
import aqt.sound
from anki._legacy import deprecated
from anki.cards import Card
from anki.collection import Config, SearchNode
from anki.consts import MODEL_CLOZE
from anki.hooks import runFilter
from anki.httpclient import HttpClient
from anki.models import NotetypeDict, NotetypeId, StockNotetype
from anki.notes import Note, NoteFieldsCheckResult, NoteId
from anki.utils import checksum, is_lin, is_mac, is_win, namedtmp
from aqt import AnkiQt, colors, gui_hooks
from aqt.operations import QueryOp
from aqt.operations.note import update_note
from aqt.operations.notetype import update_notetype_legacy
from aqt.qt import *
from aqt.sound import av_player
from aqt.theme import theme_manager
from aqt.utils import (
HelpPage,
KeyboardModifiersPressed,
disable_help_button,
getFile,
openFolder,
openHelp,
qtMenuShortcutWorkaround,
restoreGeom,
saveGeom,
shortcut,
show_in_folder,
showInfo,
showWarning,
tooltip,
tr,
)
from aqt.webview import AnkiWebView, AnkiWebViewKind
pics = ("jpg", "jpeg", "png", "gif", "svg", "webp", "ico", "avif")
audio = (
"3gp",
"aac",
"avi",
"flac",
"flv",
"m4a",
"mkv",
"mov",
"mp3",
"mp4",
"mpeg",
"mpg",
"oga",
"ogg",
"ogv",
"ogx",
"opus",
"spx",
"swf",
"wav",
"webm",
)
class EditorMode(Enum):
ADD_CARDS = 0
EDIT_CURRENT = 1
BROWSER = 2
class EditorState(Enum):
"""
Current input state of the editing UI.
"""
INITIAL = -1
FIELDS = 0
IO_PICKER = 1
IO_MASKS = 2
IO_FIELDS = 3
class Editor:
"""The screen that embeds an editing widget should listen for changes via
the `operation_did_execute` hook, and call set_note() when the editor needs
redrawing.
The editor will cause that hook to be fired when it saves changes. To avoid
an unwanted refresh, the parent widget should check if handler
corresponds to this editor instance, and ignore the change if it does.
"""
def __init__(
self,
mw: AnkiQt,
widget: QWidget,
parentWindow: QWidget,
addMode: bool | None = None,
*,
editor_mode: EditorMode = EditorMode.EDIT_CURRENT,
) -> None:
self.mw = mw
self.widget = widget
self.parentWindow = parentWindow
self.note: Note | None = None
# legacy argument provided?
if addMode is not None:
editor_mode = EditorMode.ADD_CARDS if addMode else EditorMode.EDIT_CURRENT
self.addMode = editor_mode is EditorMode.ADD_CARDS
self.editorMode = editor_mode
self.currentField: int | None = None
# Similar to currentField, but not set to None on a blur. May be
# outside the bounds of the current notetype.
self.last_field_index: int | None = None
# used when creating a copy of an existing note
self.orig_note_id: NoteId | None = None
# current card, for card layout
self.card: Card | None = None
self.state: EditorState = EditorState.INITIAL
self._init_links()
self.setupOuter()
self.add_webview()
self.setupWeb()
self.setupShortcuts()
gui_hooks.editor_did_init(self)
# Initial setup
############################################################
def setupOuter(self) -> None:
l = QVBoxLayout()
l.setContentsMargins(0, 0, 0, 0)
l.setSpacing(0)
self.widget.setLayout(l)
self.outerLayout = l
def add_webview(self) -> None:
self.web = EditorWebView(self.widget, self)
self.web.set_bridge_command(self.onBridgeCmd, self)
self.outerLayout.addWidget(self.web, 1)
def setupWeb(self) -> None:
if self.editorMode == EditorMode.ADD_CARDS:
mode = "add"
elif self.editorMode == EditorMode.BROWSER:
mode = "browse"
else:
mode = "review"
# then load page
self.web.stdHtml(
"",
css=["css/editor.css"],
js=[
"js/mathjax.js",
"js/editor.js",
],
context=self,
default_css=False,
)
self.web.eval(f"setupEditor('{mode}')")
self.web.show()
lefttopbtns: list[str] = []
gui_hooks.editor_did_init_left_buttons(lefttopbtns, self)
lefttopbtns_defs = [
f"uiPromise.then((noteEditor) => noteEditor.toolbar.notetypeButtons.appendButton({{ component: editorToolbar.Raw, props: {{ html: {json.dumps(button)} }} }}, -1));"
for button in lefttopbtns
]
lefttopbtns_js = "\n".join(lefttopbtns_defs)
righttopbtns: list[str] = []
gui_hooks.editor_did_init_buttons(righttopbtns, self)
# legacy filter
righttopbtns = runFilter("setupEditorButtons", righttopbtns, self)
righttopbtns_defs = ", ".join([json.dumps(button) for button in righttopbtns])
righttopbtns_js = (
f"""
require("anki/ui").loaded.then(() => require("anki/NoteEditor").instances[0].toolbar.toolbar.append({{
component: editorToolbar.AddonButtons,
id: "addons",
props: {{ buttons: [ {righttopbtns_defs} ] }},
}}));
"""
if len(righttopbtns) > 0
else ""
)
self.web.eval(f"{lefttopbtns_js} {righttopbtns_js}")
# Top buttons
######################################################################
def resourceToData(self, path: str) -> str:
"""Convert a file (specified by a path) into a data URI."""
if not os.path.exists(path):
raise FileNotFoundError
mime, _ = mimetypes.guess_type(path)
with open(path, "rb") as fp:
data = fp.read()
data64 = b"".join(base64.encodebytes(data).splitlines())
return f"data:{mime};base64,{data64.decode('ascii')}"
def addButton(
self,
icon: str | None,
cmd: str,
func: Callable[[Editor], None],
tip: str = "",
label: str = "",
id: str | None = None,
toggleable: bool = False,
keys: str | None = None,
disables: bool = True,
rightside: bool = True,
) -> str:
"""Assign func to bridge cmd, register shortcut, return button"""
def wrapped_func(editor: Editor) -> None:
self.call_after_note_saved(functools.partial(func, editor), keepFocus=True)
self._links[cmd] = wrapped_func
if keys:
def on_activated() -> None:
wrapped_func(self)
if toggleable:
# generate a random id for triggering toggle
id = id or str(randrange(1_000_000))
def on_hotkey() -> None:
on_activated()
self.web.eval(
f'toggleEditorButton(document.getElementById("{id}"));'
)
else:
on_hotkey = on_activated
QShortcut( # type: ignore
QKeySequence(keys),
self.widget,
activated=on_hotkey,
)
btn = self._addButton(
icon,
cmd,
tip=tip,
label=label,
id=id,
toggleable=toggleable,
disables=disables,
rightside=rightside,
)
return btn
def _addButton(
self,
icon: str | None,
cmd: str,
tip: str = "",
label: str = "",
id: str | None = None,
toggleable: bool = False,
disables: bool = True,
rightside: bool = True,
) -> str:
title_attribute = tip
if icon:
if icon.startswith("qrc:/"):
iconstr = icon
elif os.path.isabs(icon):
iconstr = self.resourceToData(icon)
else:
iconstr = f"/_anki/imgs/{icon}.png"
image_element = f'<img class="topbut" src="{iconstr}">'
else:
image_element = ""
if not label and icon:
label_element = ""
elif label:
label_element = label
else:
label_element = cmd
title_attribute = shortcut(title_attribute)
cmd_to_toggle_button = "toggleEditorButton(this);" if toggleable else ""
id_attribute_assignment = f"id={id}" if id else ""
class_attribute = "linkb" if rightside else "rounded"
if not disables:
class_attribute += " perm"
return f"""<button tabindex=-1
{id_attribute_assignment}
class="{class_attribute}"
type="button"
title="{title_attribute}"
onclick="pycmd('{cmd}');{cmd_to_toggle_button}return false;"
onmousedown="window.event.preventDefault();"
>
{image_element}
{label_element}
</button>"""
def setupShortcuts(self) -> None:
# if a third element is provided, enable shortcut even when no field selected
cuts: list[tuple] = []
gui_hooks.editor_did_init_shortcuts(cuts, self)
for row in cuts:
if len(row) == 2:
keys, fn = row # pylint: disable=unbalanced-tuple-unpacking
fn = self._addFocusCheck(fn)
else:
keys, fn, _ = row
QShortcut(QKeySequence(keys), self.widget, activated=fn) # type: ignore
def _addFocusCheck(self, fn: Callable) -> Callable:
def checkFocus() -> None:
if self.currentField is None:
return
fn()
return checkFocus
def onFields(self) -> None:
self.call_after_note_saved(self._onFields)
def _onFields(self) -> None:
from aqt.fields import FieldDialog
FieldDialog(self.mw, self.note_type(), parent=self.parentWindow)
def onCardLayout(self) -> None:
self.call_after_note_saved(self._onCardLayout)
def _onCardLayout(self) -> None:
from aqt.clayout import CardLayout
if self.card:
ord = self.card.ord
else:
ord = 0
assert self.note is not None
CardLayout(
self.mw,
self.note,
ord=ord,
parent=self.parentWindow,
fill_empty=False,
)
if is_win:
self.parentWindow.activateWindow()
# JS->Python bridge
######################################################################
def onBridgeCmd(self, cmd: str) -> Any:
if not self.note:
# shutdown
return
# focus lost or key/button pressed?
if cmd.startswith("blur") or cmd.startswith("key"):
(type, ord_str, nid_str, txt) = cmd.split(":", 3)
ord = int(ord_str)
try:
nid = int(nid_str)
except ValueError:
nid = 0
if nid != self.note.id:
print("ignored late blur")
return
try:
self.note.fields[ord] = self.mungeHTML(txt)
except IndexError:
print("ignored late blur after notetype change")
return
if not self.addMode:
self._save_current_note()
if type == "blur":
self.currentField = None
# run any filters
if gui_hooks.editor_did_unfocus_field(False, self.note, ord):
# something updated the note; update it after a subsequent focus
# event has had time to fire
self.mw.progress.timer(
100, self.loadNoteKeepingFocus, False, parent=self.widget
)
else:
self._check_and_update_duplicate_display_async()
else:
gui_hooks.editor_did_fire_typing_timer(self.note)
self._check_and_update_duplicate_display_async()
# focused into field?
elif cmd.startswith("focus"):
(type, num) = cmd.split(":", 1)
self.last_field_index = self.currentField = int(num)
gui_hooks.editor_did_focus_field(self.note, self.currentField)
elif cmd.startswith("toggleStickyAll"):
model = self.note_type()
flds = model["flds"]
any_sticky = any([fld["sticky"] for fld in flds])
result = []
for fld in flds:
if not any_sticky or fld["sticky"]:
fld["sticky"] = not fld["sticky"]
result.append(fld["sticky"])
update_notetype_legacy(parent=self.mw, notetype=model).run_in_background(
initiator=self
)
return result
elif cmd.startswith("toggleSticky"):
(type, num) = cmd.split(":", 1)
ord = int(num)
model = self.note_type()
fld = model["flds"][ord]
new_state = not fld["sticky"]
fld["sticky"] = new_state
update_notetype_legacy(parent=self.mw, notetype=model).run_in_background(
initiator=self
)
return new_state
elif cmd.startswith("lastTextColor"):
(_, textColor) = cmd.split(":", 1)
assert self.mw.pm.profile is not None
self.mw.pm.profile["lastTextColor"] = textColor
elif cmd.startswith("lastHighlightColor"):
(_, highlightColor) = cmd.split(":", 1)
assert self.mw.pm.profile is not None
self.mw.pm.profile["lastHighlightColor"] = highlightColor
elif cmd.startswith("saveTags"):
(type, tagsJson) = cmd.split(":", 1)
self.note.tags = json.loads(tagsJson)
gui_hooks.editor_did_update_tags(self.note)
if not self.addMode:
self._save_current_note()
elif cmd.startswith("setTagsCollapsed"):
(type, collapsed_string) = cmd.split(":", 1)
collapsed = collapsed_string == "true"
self.setTagsCollapsed(collapsed)
elif cmd.startswith("editorState"):
(_, new_state_id, old_state_id) = cmd.split(":", 2)
self.signal_state_change(
EditorState(int(new_state_id)), EditorState(int(old_state_id))
)
elif cmd.startswith("ioImageLoaded"):
(_, path_or_nid_data) = cmd.split(":", 1)
path_or_nid = json.loads(path_or_nid_data)
if self.addMode:
gui_hooks.editor_mask_editor_did_load_image(self, path_or_nid)
else:
gui_hooks.editor_mask_editor_did_load_image(
self, NoteId(int(path_or_nid))
)
elif cmd in self._links:
return self._links[cmd](self)
else:
print("uncaught cmd", cmd)
def mungeHTML(self, txt: str) -> str:
return gui_hooks.editor_will_munge_html(txt, self)
def signal_state_change(
self, new_state: EditorState, old_state: EditorState
) -> None:
self.state = new_state
gui_hooks.editor_state_did_change(self, new_state, old_state)
# Setting/unsetting the current note
######################################################################
def set_note(
self,
note: Note | None,
hide: bool = True,
focusTo: int | None = None,
) -> None:
"Make NOTE the current note."
self.note = note
self.currentField = None
if self.note:
self.loadNote(focusTo=focusTo)
elif hide:
self.widget.hide()
def loadNoteKeepingFocus(self) -> None:
self.loadNote(self.currentField)
def loadNote(self, focusTo: int | None = None) -> None:
if not self.note:
return
data = [
(fld, self.mw.col.media.escape_media_filenames(val))
for fld, val in self.note.items()
]
note_type = self.note_type()
flds = note_type["flds"]
collapsed = [fld["collapsed"] for fld in flds]
plain_texts = [fld.get("plainText", False) for fld in flds]
descriptions = [fld.get("description", "") for fld in flds]
notetype_meta = {"id": self.note.mid, "modTime": note_type["mod"]}
self.widget.show()
note_fields_status = self.note.fields_check()
def oncallback(arg: Any) -> None:
if not self.note:
return
self.setupForegroundButton()
# we currently do this synchronously to ensure we load before the
# sidebar on browser startup
self._update_duplicate_display(note_fields_status)
if focusTo is not None:
self.web.setFocus()
gui_hooks.editor_did_load_note(self)
assert self.mw.pm.profile is not None
text_color = self.mw.pm.profile.get("lastTextColor", "#0000ff")
highlight_color = self.mw.pm.profile.get("lastHighlightColor", "#0000ff")
js = f"""
saveSession();
setFields({json.dumps(data)});
setIsImageOcclusion({json.dumps(self.current_notetype_is_image_occlusion())});
setNotetypeMeta({json.dumps(notetype_meta)});
setCollapsed({json.dumps(collapsed)});
setPlainTexts({json.dumps(plain_texts)});
setDescriptions({json.dumps(descriptions)});
setFonts({json.dumps(self.fonts())});
focusField({json.dumps(focusTo)});
setNoteId({json.dumps(self.note.id)});
setColorButtons({json.dumps([text_color, highlight_color])});
setTags({json.dumps(self.note.tags)});
setTagsCollapsed({json.dumps(self.mw.pm.tags_collapsed(self.editorMode))});
setMathjaxEnabled({json.dumps(self.mw.col.get_config("renderMathjax", True))});
setShrinkImages({json.dumps(self.mw.col.get_config("shrinkEditorImages", True))});
setCloseHTMLTags({json.dumps(self.mw.col.get_config("closeHTMLTags", True))});
triggerChanges();
"""
if self.addMode:
sticky = [field["sticky"] for field in self.note_type()["flds"]]
js += " setSticky(%s);" % json.dumps(sticky)
if self.current_notetype_is_image_occlusion():
if self.editorMode is not EditorMode.ADD_CARDS:
io_options = self._create_edit_io_options(note_id=self.note.id)
js += " setupMaskEditor(%s);" % json.dumps(io_options)
elif orig_note_id := self.orig_note_id:
self.orig_note_id = None
io_options = self._create_clone_io_options(orig_note_id)
js += " setupMaskEditor(%s);" % json.dumps(io_options)
js = gui_hooks.editor_will_load_note(js, self.note, self)
self.web.evalWithCallback(
f'require("anki/ui").loaded.then(() => {{ {js} }})', oncallback
)
def _save_current_note(self) -> None:
"Call after note is updated with data from webview."
if not self.note:
return
update_note(parent=self.widget, note=self.note).run_in_background(
initiator=self
)
def fonts(self) -> list[tuple[str, int, bool]]:
return [
(gui_hooks.editor_will_use_font_for_field(f["font"]), f["size"], f["rtl"])
for f in self.note_type()["flds"]
]
def call_after_note_saved(
self, callback: Callable, keepFocus: bool = False
) -> None:
"Save unsaved edits then call callback()."
if not self.note:
# calling code may not expect the callback to fire immediately
self.mw.progress.single_shot(10, callback)
return
self.web.evalWithCallback("saveNow(%d)" % keepFocus, lambda res: callback())
saveNow = call_after_note_saved
def _check_and_update_duplicate_display_async(self) -> None:
note = self.note
if not note:
return
def on_done(result: NoteFieldsCheckResult.V) -> None:
if self.note != note:
return
self._update_duplicate_display(result)
QueryOp(
parent=self.parentWindow,
op=lambda _: note.fields_check(),
success=on_done,
).run_in_background()
checkValid = _check_and_update_duplicate_display_async
def _update_duplicate_display(self, result: NoteFieldsCheckResult.V) -> None:
assert self.note is not None
cols = [""] * len(self.note.fields)
cloze_hint = ""
if result == NoteFieldsCheckResult.DUPLICATE:
cols[0] = "dupe"
elif result == NoteFieldsCheckResult.NOTETYPE_NOT_CLOZE:
cloze_hint = tr.adding_cloze_outside_cloze_notetype()
elif result == NoteFieldsCheckResult.FIELD_NOT_CLOZE:
cloze_hint = tr.adding_cloze_outside_cloze_field()
self.web.eval(
'require("anki/ui").loaded.then(() => {'
f"setBackgrounds({json.dumps(cols)});\n"
f"setClozeHint({json.dumps(cloze_hint)});\n"
"}); "
)
def showDupes(self) -> None:
assert self.note is not None
aqt.dialogs.open(
"Browser",
self.mw,
search=(
SearchNode(
dupe=SearchNode.Dupe(
notetype_id=self.note_type()["id"],
first_field=self.note.fields[0],
)
),
),
)
def fieldsAreBlank(self, previousNote: Note | None = None) -> bool:
if not self.note:
return True
m = self.note_type()
for c, f in enumerate(self.note.fields):
f = f.replace("<br>", "").strip()
notChangedvalues = {"", "<br>"}
if previousNote and m["flds"][c]["sticky"]:
notChangedvalues.add(previousNote.fields[c].replace("<br>", "").strip())
if f not in notChangedvalues:
return False
return True
def cleanup(self) -> None:
av_player.stop_and_clear_queue_if_caller(self.editorMode)
self.set_note(None)
# prevent any remaining evalWithCallback() events from firing after C++ object deleted
if self.web:
self.web.cleanup()
self.web = None # type: ignore
# legacy
setNote = set_note
# Tag handling
######################################################################
def setupTags(self) -> None:
import aqt.tagedit
g = QGroupBox(self.widget)
g.setStyleSheet("border: 0")
tb = QGridLayout()
tb.setSpacing(12)
tb.setContentsMargins(2, 6, 2, 6)
# tags
l = QLabel(tr.editing_tags())
tb.addWidget(l, 1, 0)
self.tags = aqt.tagedit.TagEdit(self.widget)
qconnect(self.tags.lostFocus, self.on_tag_focus_lost)
self.tags.setToolTip(shortcut(tr.editing_jump_to_tags_with_ctrlandshiftandt()))
border = theme_manager.var(colors.BORDER)
self.tags.setStyleSheet(f"border: 1px solid {border}")
tb.addWidget(self.tags, 1, 1)
g.setLayout(tb)
self.outerLayout.addWidget(g)
def updateTags(self) -> None:
if self.tags.col != self.mw.col:
self.tags.setCol(self.mw.col)
if not self.tags.text() or not self.addMode:
assert self.note is not None
self.tags.setText(self.note.string_tags().strip())
def on_tag_focus_lost(self) -> None:
assert self.note is not None
self.note.tags = self.mw.col.tags.split(self.tags.text())
gui_hooks.editor_did_update_tags(self.note)
if not self.addMode:
self._save_current_note()
def blur_tags_if_focused(self) -> None:
if not self.note:
return
if self.tags.hasFocus():
self.widget.setFocus()
def hideCompleters(self) -> None:
self.tags.hideCompleter()
def onFocusTags(self) -> None:
self.tags.setFocus()
# legacy
def saveAddModeVars(self) -> None:
pass
saveTags = blur_tags_if_focused
# Audio/video/images
######################################################################
def onAddMedia(self) -> None:
"""Show a file selection screen, then add the selected media.
This expects initial setup to have been done by TemplateButtons.svelte."""
extension_filter = " ".join(
f"*.{extension}" for extension in sorted(itertools.chain(pics, audio))
)
filter = f"{tr.editing_media()} ({extension_filter})"
def accept(file: str) -> None:
self.resolve_media(file)
file = getFile(
parent=self.widget,
title=tr.editing_add_media(),
cb=cast(Callable[[Any], None], accept),
filter=filter,
key="media",
)
self.parentWindow.activateWindow()
def addMedia(self, path: str, canDelete: bool = False) -> None:
"""Legacy routine used by add-ons to add a media file and update the current field.
canDelete is ignored."""
try:
html = self._addMedia(path)
except Exception as e:
showWarning(str(e))
return
self.web.eval(f"setFormat('inserthtml', {json.dumps(html)});")
def resolve_media(self, path: str) -> None:
"""Finish inserting media into a field.
This expects initial setup to have been done by TemplateButtons.svelte."""
try:
html = self._addMedia(path)
except Exception as e:
showWarning(str(e))
return
self.web.eval(
f'require("anki/TemplateButtons").resolveMedia({json.dumps(html)})'
)
def _addMedia(self, path: str, canDelete: bool = False) -> str:
"""Add to media folder and return local img or sound tag."""
# copy to media folder
fname = self.mw.col.media.add_file(path)
# return a local html link
return self.fnameToLink(fname)
def _addMediaFromData(self, fname: str, data: bytes) -> str:
return self.mw.col.media._legacy_write_data(fname, data)
def onRecSound(self) -> None:
aqt.sound.record_audio(
self.parentWindow,
self.mw,
True,
self.resolve_media,
)
# Media downloads
######################################################################
def urlToLink(self, url: str, allowed_suffixes: Iterable[str] = ()) -> str:
fname = (
self.urlToFile(url, allowed_suffixes)
if allowed_suffixes
else self.urlToFile(url)
)
if not fname:
return '<a href="{}">{}</a>'.format(
url, html.escape(urllib.parse.unquote(url))
)
return self.fnameToLink(fname)
def fnameToLink(self, fname: str) -> str:
ext = fname.split(".")[-1].lower()
if ext in pics:
name = urllib.parse.quote(fname.encode("utf8"))
return f'<img src="{name}">'
else:
av_player.play_file_with_caller(fname, self.editorMode)
return f"[sound:{html.escape(fname, quote=False)}]"
def urlToFile(
self, url: str, allowed_suffixes: Iterable[str] = pics + audio
) -> str | None:
l = url.lower()
for suffix in allowed_suffixes:
if l.endswith(f".{suffix}"):
return self._retrieveURL(url)
# not a supported type
return None
def isURL(self, s: str) -> bool:
s = s.lower()
return (
s.startswith("http://")
or s.startswith("https://")
or s.startswith("ftp://")
or s.startswith("file://")
)
def inlinedImageToFilename(self, txt: str) -> str:
prefix = "data:image/"
suffix = ";base64,"
for ext in ("jpg", "jpeg", "png", "gif"):
fullPrefix = prefix + ext + suffix
if txt.startswith(fullPrefix):
b64data = txt[len(fullPrefix) :].strip()
data = base64.b64decode(b64data, validate=True)
if ext == "jpeg":
ext = "jpg"
return self._addPastedImage(data, ext)
return ""
def inlinedImageToLink(self, src: str) -> str:
fname = self.inlinedImageToFilename(src)
if fname:
return self.fnameToLink(fname)
return ""
def _pasted_image_filename(self, data: bytes, ext: str) -> str:
csum = checksum(data)
return f"paste-{csum}.{ext}"
def _read_pasted_image(self, mime: QMimeData) -> str:
image = QImage(mime.imageData())
buffer = QBuffer()
buffer.open(QBuffer.OpenModeFlag.ReadWrite)
if self.mw.col.get_config_bool(Config.Bool.PASTE_IMAGES_AS_PNG):
ext = "png"
quality = 50
else:
ext = "jpg"
quality = 80
image.save(buffer, ext, quality)
buffer.reset()
data = bytes(buffer.readAll()) # type: ignore
fname = self._pasted_image_filename(data, ext)
path = namedtmp(fname)
with open(path, "wb") as file:
file.write(data)
return path
def _addPastedImage(self, data: bytes, ext: str) -> str:
# hash and write
fname = self._pasted_image_filename(data, ext)
return self._addMediaFromData(fname, data)
def _retrieveURL(self, url: str) -> str | None:
"Download file into media folder and return local filename or None."
local = url.lower().startswith("file://")
# fetch it into a temporary folder
self.mw.progress.start(immediate=not local, parent=self.parentWindow)
content_type = None
error_msg: str | None = None
try:
if local:
# urllib doesn't understand percent-escaped utf8, but requires things like
# '#' to be escaped.
url = urllib.parse.unquote(url)
url = url.replace("%", "%25")
url = url.replace("#", "%23")
req = urllib.request.Request(
url, None, {"User-Agent": "Mozilla/5.0 (compatible; Anki)"}
)
with urllib.request.urlopen(req) as response:
filecontents = response.read()
else:
with HttpClient() as client:
client.timeout = 30
with client.get(url) as response:
if response.status_code != 200:
error_msg = tr.qt_misc_unexpected_response_code(
val=response.status_code,
)
return None
filecontents = response.content
content_type = response.headers.get("content-type")
except (urllib.error.URLError, requests.exceptions.RequestException) as e:
error_msg = tr.editing_an_error_occurred_while_opening(val=str(e))
return None
finally:
self.mw.progress.finish()
if error_msg:
showWarning(error_msg)
# strip off any query string
url = re.sub(r"\?.*?$", "", url)
fname = os.path.basename(urllib.parse.unquote(url))
if not fname.strip():
fname = "paste"
if content_type:
fname = self.mw.col.media.add_extension_based_on_mime(fname, content_type)
return self.mw.col.media.write_data(fname, filecontents)
# Paste/drag&drop
######################################################################
removeTags = ["script", "iframe", "object", "style"]
def _pastePreFilter(self, html: str, internal: bool) -> str:
# https://anki.tenderapp.com/discussions/ankidesktop/39543-anki-is-replacing-the-character-by-when-i-exit-the-html-edit-mode-ctrlshiftx
if html.find(">") < 0:
return html
with warnings.catch_warnings() as w:
warnings.simplefilter("ignore", UserWarning)
doc = BeautifulSoup(html, "html.parser")
tag: bs4.element.Tag
if not internal:
for tag in self.removeTags: