anki/qt/aqt/clayout.py

665 lines
21 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
2019-02-05 04:59:03 +01:00
# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
2019-12-20 10:19:03 +01:00
import json
import re
from typing import List, Optional
2013-10-20 03:02:29 +02:00
import aqt
from anki.cards import Card
2019-12-20 10:19:03 +01:00
from anki.consts import *
2019-03-04 02:58:34 +01:00
from anki.lang import _, ngettext
2020-05-05 03:10:24 +02:00
from anki.notes import Note
from anki.rsbackend import TemplateError
from anki.template import TemplateRenderContext
from anki.utils import isMac, isWin, joinFields
2020-05-05 03:10:24 +02:00
from aqt import AnkiQt, gui_hooks
2019-12-20 10:19:03 +01:00
from aqt.qt import *
from aqt.sound import av_player, play_clicked_audio
from aqt.theme import theme_manager
2019-12-23 01:34:10 +01:00
from aqt.utils import (
askUser,
downArrow,
getOnlyText,
openHelp,
restoreGeom,
saveGeom,
showInfo,
showWarning,
tooltip,
2019-12-23 01:34:10 +01:00
)
2019-12-20 10:19:03 +01:00
from aqt.webview import AnkiWebView
# fixme: previewing with empty fields
# fixme: deck name on new cards
# fixme: card count when removing
# fixme: i18n
# fixme: change tracking and tooltip in fields
2013-10-20 03:02:29 +02:00
class CardLayout(QDialog):
2020-05-05 03:10:24 +02:00
def __init__(
self, mw: AnkiQt, note: Note, ord=0, parent: Optional[QWidget] = None,
2020-05-05 03:10:24 +02:00
):
QDialog.__init__(self, parent or mw, Qt.Window)
mw.setupDialogGC(self)
self.mw = aqt.mw
self.note = note
self.ord = ord
self.col = self.mw.col.weakref()
self.mm = self.mw.col.models
self.model = note.model()
self.templates = self.model["tmpls"]
self.mm._remove_from_cache(self.model["id"])
self.mw.checkpoint(_("Card Types"))
self.changed = False
self.setupTopArea()
self.setupMainArea()
self.setupButtons()
self.setupShortcuts()
2019-12-23 01:34:10 +01:00
self.setWindowTitle(_("Card Types for %s") % self.model["name"])
v1 = QVBoxLayout()
v1.addWidget(self.topArea)
v1.addWidget(self.mainArea)
v1.addLayout(self.buttons)
2019-12-23 01:34:10 +01:00
v1.setContentsMargins(12, 12, 12, 12)
self.setLayout(v1)
2020-02-28 13:34:54 +01:00
gui_hooks.card_layout_will_show(self)
self.redraw_everything()
restoreGeom(self, "CardLayout")
self.setWindowModality(Qt.ApplicationModal)
self.show()
# take the focus away from the first input area when starting up,
# as users tend to accidentally type into the template
self.setFocus()
def redraw_everything(self):
self.ignore_change_signals = True
self.updateTopArea()
self.updateMainArea()
self.ignore_change_signals = False
self.update_current_ordinal_and_redraw(self.ord)
def update_current_ordinal_and_redraw(self, idx):
if self.ignore_change_signals:
return
self.ord = idx
self.playedAudio = {}
self.fill_fields_from_template()
self.renderPreview()
def _isCloze(self):
return self.model["type"] == MODEL_CLOZE
# Top area
##########################################################################
def setupTopArea(self):
self.topArea = QWidget()
self.topAreaForm = aqt.forms.clayout_top.Ui_Form()
self.topAreaForm.setupUi(self.topArea)
2019-12-23 01:34:10 +01:00
self.topAreaForm.templateOptions.setText(_("Options") + " " + downArrow())
qconnect(self.topAreaForm.templateOptions.clicked, self.onMore)
qconnect(
self.topAreaForm.templatesBox.currentIndexChanged,
self.update_current_ordinal_and_redraw,
)
def updateTopArea(self):
cnt = self.mw.col.models.useCount(self.model)
2019-12-23 01:34:10 +01:00
self.topAreaForm.changesLabel.setText(
ngettext(
"Changes below will affect the %(cnt)d note that uses this card type.",
"Changes below will affect the %(cnt)d notes that use this card type.",
cnt,
)
% dict(cnt=cnt)
)
self.updateCardNames()
def updateCardNames(self):
self.ignore_change_signals = True
combo = self.topAreaForm.templatesBox
combo.clear()
combo.addItems(
self._summarizedName(idx, tmpl) for (idx, tmpl) in enumerate(self.templates)
)
combo.setCurrentIndex(self.ord)
combo.setEnabled(not self._isCloze())
self.ignore_change_signals = False
def _summarizedName(self, idx: int, tmpl: Dict):
2020-01-21 23:42:27 +01:00
return "{}: {}: {} -> {}".format(
idx + 1,
2019-12-23 01:34:10 +01:00
tmpl["name"],
self._fieldsOnTemplate(tmpl["qfmt"]),
self._fieldsOnTemplate(tmpl["afmt"]),
)
def _fieldsOnTemplate(self, fmt):
matches = re.findall("{{[^#/}]+?}}", fmt)
chars_allowed = 30
field_names: List[str] = []
for m in matches:
# strip off mustache
m = re.sub(r"[{}]", "", m)
# strip off modifiers
m = m.split(":")[-1]
# don't show 'FrontSide'
if m == "FrontSide":
continue
field_names.append(m)
chars_allowed -= len(m)
if chars_allowed <= 0:
break
s = "+".join(field_names)
if chars_allowed <= 0:
2020-05-05 03:10:24 +02:00
s += "+..."
return s
def setupShortcuts(self):
for i in range(1, 9):
QShortcut(
QKeySequence("Ctrl+%d" % i),
self,
activated=lambda i=i: self.selectCard(i),
) # type: ignore
def selectCard(self, n):
self.ord = n - 1
self.redraw_everything()
# Main area
##########################################################################
def setupMainArea(self):
w = self.mainArea = QWidget()
l = QHBoxLayout()
2019-12-23 01:34:10 +01:00
l.setContentsMargins(0, 0, 0, 0)
l.setSpacing(3)
left = QWidget()
# template area
tform = self.tform = aqt.forms.template.Ui_Form()
tform.setupUi(left)
tform.label1.setText("")
tform.label2.setText("")
tform.labelc1.setText("")
tform.labelc2.setText("")
if self.style().objectName() == "gtk+":
# gtk+ requires margins in inner layout
tform.tlayout1.setContentsMargins(0, 11, 0, 0)
tform.tlayout2.setContentsMargins(0, 11, 0, 0)
tform.tlayout3.setContentsMargins(0, 11, 0, 0)
2019-12-23 01:34:10 +01:00
tform.groupBox_3.setTitle(_("Styling (shared between cards)"))
qconnect(tform.front.textChanged, self.write_edits_to_template_and_redraw)
qconnect(tform.css.textChanged, self.write_edits_to_template_and_redraw)
qconnect(tform.back.textChanged, self.write_edits_to_template_and_redraw)
l.addWidget(left, 5)
# preview area
right = QWidget()
self.pform: Any = aqt.forms.preview.Ui_Form()
pform = self.pform
pform.setupUi(right)
if self.style().objectName() == "gtk+":
# gtk+ requires margins in inner layout
pform.frontPrevBox.setContentsMargins(0, 11, 0, 0)
pform.backPrevBox.setContentsMargins(0, 11, 0, 0)
self.setupWebviews()
l.addWidget(right, 5)
w.setLayout(l)
def setupWebviews(self):
pform = self.pform
pform.frontWeb = AnkiWebView(title="card layout front")
pform.frontPrevBox.addWidget(pform.frontWeb)
pform.backWeb = AnkiWebView(title="card layout back")
pform.backPrevBox.addWidget(pform.backWeb)
2019-12-23 01:34:10 +01:00
jsinc = [
"jquery.js",
"browsersel.js",
"mathjax/conf.js",
"mathjax/MathJax.js",
"reviewer.js",
2019-12-23 01:34:10 +01:00
]
pform.frontWeb.stdHtml(
self.mw.reviewer.revHtml(), css=["reviewer.css"], js=jsinc, context=self,
2019-12-23 01:34:10 +01:00
)
pform.backWeb.stdHtml(
self.mw.reviewer.revHtml(), css=["reviewer.css"], js=jsinc, context=self,
2019-12-23 01:34:10 +01:00
)
pform.frontWeb.set_bridge_command(self._on_bridge_cmd, self)
pform.backWeb.set_bridge_command(self._on_bridge_cmd, self)
def _on_bridge_cmd(self, cmd: str) -> Any:
if cmd.startswith("play:"):
play_clicked_audio(cmd, self.rendered_card)
def updateMainArea(self):
if self._isCloze():
cnt = len(self.note.cloze_numbers_in_fields())
for g in self.pform.groupBox, self.pform.groupBox_2:
g.setTitle(g.title() + _(" (1 of %d)") % max(cnt, 1))
def ephemeral_card_for_rendering(self) -> Card:
card = Card(self.col)
card.ord = self.ord
output = TemplateRenderContext.from_card_layout(
self.note, card, template=self.current_template()
).render()
card.set_render_output(output)
return card
2019-12-30 09:50:00 +01:00
# Buttons
##########################################################################
def setupButtons(self):
l = self.buttons = QHBoxLayout()
help = QPushButton(_("Help"))
help.setAutoDefault(False)
l.addWidget(help)
qconnect(help.clicked, self.onHelp)
l.addStretch()
addField = QPushButton(_("Add Field"))
addField.setAutoDefault(False)
l.addWidget(addField)
qconnect(addField.clicked, self.onAddField)
if not self._isCloze():
flip = QPushButton(_("Flip"))
flip.setAutoDefault(False)
l.addWidget(flip)
qconnect(flip.clicked, self.onFlip)
l.addStretch()
save = QPushButton(_("Save"))
save.setAutoDefault(False)
l.addWidget(save)
qconnect(save.clicked, self.accept)
close = QPushButton(_("Cancel"))
close.setAutoDefault(False)
l.addWidget(close)
qconnect(close.clicked, self.reject)
# Reading/writing question/answer/css
##########################################################################
def current_template(self) -> Dict:
return self.templates[self.ord]
def fill_fields_from_template(self):
t = self.current_template()
self.ignore_change_signals = True
2019-12-23 01:34:10 +01:00
self.tform.front.setPlainText(t["qfmt"])
self.tform.css.setPlainText(self.model["css"])
self.tform.back.setPlainText(t["afmt"])
self.tform.front.setAcceptRichText(False)
self.tform.css.setAcceptRichText(False)
self.tform.back.setAcceptRichText(False)
if qtminor < 10:
self.tform.front.setTabStopWidth(30)
self.tform.css.setTabStopWidth(30)
self.tform.back.setTabStopWidth(30)
else:
tab_width = self.fontMetrics().width(" " * 4)
self.tform.front.setTabStopDistance(tab_width)
self.tform.css.setTabStopDistance(tab_width)
self.tform.back.setTabStopDistance(tab_width)
self.ignore_change_signals = False
def write_edits_to_template_and_redraw(self):
if self.ignore_change_signals:
return
self.changed = True
t = self.current_template()
t["qfmt"] = self.tform.front.toPlainText()
t["afmt"] = self.tform.back.toPlainText()
self.model["css"] = self.tform.css.toPlainText()
self.renderPreview()
# Preview
##########################################################################
_previewTimer = None
def renderPreview(self):
# schedule a preview when timing stops
self.cancelPreviewTimer()
self._previewTimer = self.mw.progress.timer(200, self._renderPreview, False)
def cancelPreviewTimer(self):
if self._previewTimer:
self._previewTimer.stop()
self._previewTimer = None
def _renderPreview(self) -> None:
self.cancelPreviewTimer()
c = self.rendered_card = self.ephemeral_card_for_rendering()
ti = self.maybeTextInput
2017-12-04 03:20:56 +01:00
bodyclass = theme_manager.body_classes_for_card_ord(c.ord)
q = ti(self.mw.prepare_card_text_for_display(c.q()))
q = gui_hooks.card_will_show(q, c, "clayoutQuestion")
a = ti(self.mw.prepare_card_text_for_display(c.a()), type="a")
a = gui_hooks.card_will_show(a, c, "clayoutAnswer")
# use _showAnswer to avoid the longer delay
self.pform.frontWeb.eval("_showAnswer(%s,'%s');" % (json.dumps(q), bodyclass))
self.pform.backWeb.eval("_showAnswer(%s, '%s');" % (json.dumps(a), bodyclass))
if c.id not in self.playedAudio:
av_player.play_tags(c.question_av_tags() + c.answer_av_tags())
self.playedAudio[c.id] = True
self.updateCardNames()
2019-12-23 01:34:10 +01:00
def maybeTextInput(self, txt, type="q"):
if "[[type:" not in txt:
return txt
origLen = len(txt)
txt = txt.replace("<hr id=answer>", "")
hadHR = origLen != len(txt)
2019-12-23 01:34:10 +01:00
def answerRepl(match):
res = self.mw.reviewer.correct("exomple", "an example")
if hadHR:
res = "<hr id=answer>" + res
return res
2019-12-23 01:34:10 +01:00
2020-05-05 03:10:24 +02:00
repl: Union[str, Callable]
2019-12-23 01:34:10 +01:00
if type == "q":
repl = "<input id='typeans' type=text value='exomple' readonly='readonly'>"
repl = "<center>%s</center>" % repl
else:
repl = answerRepl
2019-03-04 08:03:43 +01:00
return re.sub(r"\[\[type:.+?\]\]", repl, txt)
# Card operations
######################################################################
def onRemove(self):
if len(self.templates) < 2:
return showInfo(_("At least one card type is required."))
template = self.current_template()
msg = _("Delete the '%(a)s' card type, and its %(b)s?") % dict(
a=template["name"], b=_("cards")
)
if not askUser(msg):
return
self.changed = True
self.mm.remTemplate(self.model, template, save=False)
# ensure current ordinal is within bounds
idx = self.ord
if idx >= len(self.templates):
self.ord = len(self.templates) - 1
self.redraw_everything()
def onRename(self):
template = self.current_template()
name = getOnlyText(_("New name:"), default=template["name"])
if not name.strip():
return
self.changed = True
template["name"] = name
self.redraw_everything()
def onReorder(self):
n = len(self.templates)
template = self.current_template()
current_pos = self.templates.index(template) + 1
pos = getOnlyText(
_("Enter new card position (1...%s):") % n, default=str(current_pos)
)
if not pos:
return
try:
pos = int(pos)
except ValueError:
return
if pos < 1 or pos > n:
return
if pos == current_pos:
return
new_idx = pos - 1
self.changed = True
self.mm.moveTemplate(self.model, template, new_idx, save=False)
self.ord = new_idx
self.redraw_everything()
def _newCardName(self):
n = len(self.templates) + 1
while 1:
name = _("Card %d") % n
if name not in [t["name"] for t in self.templates]:
break
n += 1
return name
def onAddCard(self):
cnt = self.mw.col.models.useCount(self.model)
2019-12-23 01:34:10 +01:00
txt = (
ngettext(
"This will create %d card. Proceed?",
"This will create %d cards. Proceed?",
cnt,
)
% cnt
)
if not askUser(txt):
return
self.changed = True
name = self._newCardName()
t = self.mm.newTemplate(name)
old = self.current_template()
2019-12-23 01:34:10 +01:00
t["qfmt"] = old["qfmt"]
t["afmt"] = old["afmt"]
self.mm.addTemplate(self.model, t, save=False)
self.ord = len(self.templates) - 1
self.redraw_everything()
def onFlip(self):
old = self.current_template()
self._flipQA(old, old)
self.redraw_everything()
def _flipQA(self, src, dst):
2019-12-23 01:34:10 +01:00
m = re.match("(?s)(.+)<hr id=answer>(.+)", src["afmt"])
if not m:
2019-12-23 01:34:10 +01:00
showInfo(
_(
"""\
Anki couldn't find the line between the question and answer. Please \
2019-12-23 01:34:10 +01:00
adjust the template manually to switch the question and answer."""
)
)
return
self.changed = True
2019-12-23 01:34:10 +01:00
dst["afmt"] = "{{FrontSide}}\n\n<hr id=answer>\n\n%s" % src["qfmt"]
dst["qfmt"] = m.group(2).strip()
return True
def onMore(self):
m = QMenu(self)
if not self._isCloze():
a = m.addAction(_("Add Card Type..."))
qconnect(a.triggered, self.onAddCard)
a = m.addAction(_("Remove Card Type..."))
qconnect(a.triggered, self.onRemove)
a = m.addAction(_("Rename Card Type..."))
qconnect(a.triggered, self.onRename)
a = m.addAction(_("Reposition Card Type..."))
qconnect(a.triggered, self.onReorder)
m.addSeparator()
t = self.current_template()
2019-12-23 01:34:10 +01:00
if t["did"]:
s = _(" (on)")
else:
s = _(" (off)")
a = m.addAction(_("Deck Override...") + s)
qconnect(a.triggered, self.onTargetDeck)
a = m.addAction(_("Browser Appearance..."))
qconnect(a.triggered, self.onBrowserDisplay)
2019-12-23 01:34:10 +01:00
m.exec_(self.topAreaForm.templateOptions.mapToGlobal(QPoint(0, 0)))
def onBrowserDisplay(self):
d = QDialog()
f = aqt.forms.browserdisp.Ui_Dialog()
f.setupUi(d)
t = self.current_template()
2019-12-23 01:34:10 +01:00
f.qfmt.setText(t.get("bqfmt", ""))
f.afmt.setText(t.get("bafmt", ""))
if t.get("bfont"):
f.overrideFont.setChecked(True)
2019-12-23 01:34:10 +01:00
f.font.setCurrentFont(QFont(t.get("bfont", "Arial")))
f.fontSize.setValue(t.get("bsize", 12))
qconnect(f.buttonBox.accepted, lambda: self.onBrowserDisplayOk(f))
d.exec_()
def onBrowserDisplayOk(self, f):
t = self.current_template()
self.changed = True
2019-12-23 01:34:10 +01:00
t["bqfmt"] = f.qfmt.text().strip()
t["bafmt"] = f.afmt.text().strip()
if f.overrideFont.isChecked():
2019-12-23 01:34:10 +01:00
t["bfont"] = f.font.currentFont().family()
t["bsize"] = f.fontSize.value()
else:
for key in ("bfont", "bsize"):
if key in t:
del t[key]
def onTargetDeck(self):
from aqt.tagedit import TagEdit
2019-12-23 01:34:10 +01:00
t = self.current_template()
d = QDialog(self)
d.setWindowTitle("Anki")
d.setMinimumWidth(400)
l = QVBoxLayout()
2019-12-23 01:34:10 +01:00
lab = QLabel(
_(
"""\
Enter deck to place new %s cards in, or leave blank:"""
)
% self.current_template()["name"]
2019-12-23 01:34:10 +01:00
)
lab.setWordWrap(True)
l.addWidget(lab)
te = TagEdit(d, type=1)
te.setCol(self.col)
l.addWidget(te)
2019-12-23 01:34:10 +01:00
if t["did"]:
te.setText(self.col.decks.get(t["did"])["name"])
te.selectAll()
bb = QDialogButtonBox(QDialogButtonBox.Close)
qconnect(bb.rejected, d.close)
l.addWidget(bb)
d.setLayout(l)
d.exec_()
self.changed = True
if not te.text().strip():
2019-12-23 01:34:10 +01:00
t["did"] = None
else:
2019-12-23 01:34:10 +01:00
t["did"] = self.col.decks.id(te.text())
def onAddField(self):
diag = QDialog(self)
form = aqt.forms.addfield.Ui_Dialog()
form.setupUi(diag)
2019-12-23 01:34:10 +01:00
fields = [f["name"] for f in self.model["flds"]]
form.fields.addItems(fields)
form.font.setCurrentFont(QFont("Arial"))
form.size.setValue(20)
diag.show()
# Work around a Qt bug,
# https://bugreports.qt-project.org/browse/QTBUG-1894
if isMac or isWin:
# No problems on Macs or Windows.
form.fields.showPopup()
else:
# Delay showing the pop-up.
self.mw.progress.timer(200, form.fields.showPopup, False)
if not diag.exec_():
return
if form.radioQ.isChecked():
obj = self.tform.front
else:
obj = self.tform.back
2019-12-23 01:34:10 +01:00
self._addField(
obj,
fields[form.fields.currentIndex()],
form.font.currentFont().family(),
form.size.value(),
)
def _addField(self, widg, field, font, size):
t = widg.toPlainText()
2019-12-23 01:34:10 +01:00
t += "\n<div style='font-family: %s; font-size: %spx;'>{{%s}}</div>\n" % (
font,
size,
field,
)
widg.setPlainText(t)
self.changed = True
self.write_edits_to_template_and_redraw()
# Closing & Help
######################################################################
def accept(self) -> None:
def save():
self.mm.save(self.model)
def on_done(fut):
try:
fut.result()
except TemplateError as e:
showWarning("Unable to save changes: " + str(e))
return
self.mw.reset()
tooltip("Changes saved.", parent=self.mw)
self.cleanup()
return QDialog.accept(self)
self.mw.taskman.with_progress(save, on_done)
def reject(self) -> None:
if self.changed:
if not askUser("Discard changes?"):
return
self.cleanup()
return QDialog.reject(self)
def cleanup(self) -> None:
self.cancelPreviewTimer()
2020-01-20 11:10:38 +01:00
av_player.stop_and_clear_queue()
saveGeom(self, "CardLayout")
2019-03-26 03:31:40 +01:00
self.pform.frontWeb = None
self.pform.backWeb = None
self.model = None
self.rendered_card = None
self.mw = None
def onHelp(self):
openHelp("templates")