Merge pull request #781 from hgiesel/leftbtns

Refactor Buttons in editor and add editor_did_init_left_buttons gui_hook
This commit is contained in:
Damien Elmes 2020-10-05 13:14:52 +10:00 committed by GitHub
commit 8fa865e8f4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 93 additions and 56 deletions

View file

@ -118,6 +118,27 @@ class Editor:
self.web.set_bridge_command(self.onBridgeCmd, self) self.web.set_bridge_command(self.onBridgeCmd, self)
self.outerLayout.addWidget(self.web, 1) self.outerLayout.addWidget(self.web, 1)
lefttopbtns: List[str] = [
self._addButton(
None,
"fields",
_("Customize Fields"),
_("Fields") + "...",
disables=False,
rightside=False,
),
self._addButton(
None,
"cards",
_("Customize Card Templates (Ctrl+L)"),
_("Cards") + "...",
disables=False,
rightside=False,
),
]
gui_hooks.editor_did_init_left_buttons(lefttopbtns, self)
righttopbtns: List[str] = [ righttopbtns: List[str] = [
self._addButton("text_bold", "bold", _("Bold text (Ctrl+B)"), id="bold"), self._addButton("text_bold", "bold", _("Bold text (Ctrl+B)"), id="bold"),
self._addButton( self._addButton(
@ -131,68 +152,47 @@ class Editor:
), ),
self._addButton("text_sub", "sub", _("Subscript (Ctrl+=)"), id="subscript"), self._addButton("text_sub", "sub", _("Subscript (Ctrl+=)"), id="subscript"),
self._addButton("text_clear", "clear", _("Remove formatting (Ctrl+R)")), self._addButton("text_clear", "clear", _("Remove formatting (Ctrl+R)")),
] self._addButton(
# The color selection buttons do not use an icon so the HTML must be specified manually None,
tip = _("Set foreground colour (F7)") "colour",
righttopbtns.append( _("Set foreground colour (F7)"),
""" <button tabindex=-1 """
class=linkb <div id="forecolor"
title="{}" style="display: inline-block; background: #000; border-radius: 5px;"
type="button" class="topbut"
onclick="pycmd('colour'); return false;" >""",
>
<div id=forecolor
style="display:inline-block; background: #000;border-radius: 5px;"
class=topbut
>
</div>
</button>""".format(
tip
)
)
tip = _("Change colour (F8)")
righttopbtns.extend(
[
"""<button tabindex=-1
class=linkb
title="{}"
type="button"
onclick="pycmd('changeCol');return false;"
>
<div style="display:inline-block; border-radius: 5px;"
class="topbut rainbow"
>
</div>
</button>""".format(
tip
), ),
self._addButton( self._addButton(
"text_cloze", "cloze", _("Cloze deletion (Ctrl+Shift+C)") None,
"changeCol",
_("Change colour (F8)"),
"""
<div style="display: inline-block; border-radius: 5px;"
class="topbut rainbow"
>""",
), ),
self._addButton("text_cloze", "cloze", _("Cloze deletion (Ctrl+Shift+C)")),
self._addButton( self._addButton(
"paperclip", "attach", _("Attach pictures/audio/video (F3)") "paperclip", "attach", _("Attach pictures/audio/video (F3)")
), ),
self._addButton("media-record", "record", _("Record audio (F5)")), self._addButton("media-record", "record", _("Record audio (F5)")),
self._addButton("more", "more"), self._addButton("more", "more"),
] ]
)
gui_hooks.editor_did_init_buttons(righttopbtns, self) gui_hooks.editor_did_init_buttons(righttopbtns, self)
# legacy filter # legacy filter
righttopbtns = runFilter("setupEditorButtons", righttopbtns, self) righttopbtns = runFilter("setupEditorButtons", righttopbtns, self)
topbuts = """ topbuts = """
<div id="topbutsleft" style="float:left;"> <div id="topbutsleft" style="float:left;">
<button title='%(fldsTitle)s' onclick="pycmd('fields')">%(flds)s...</button> %(leftbts)s
<button title='%(cardsTitle)s' onclick="pycmd('cards')">%(cards)s...</button>
</div> </div>
<div id="topbutsright" style="float:right;"> <div id="topbutsright" style="float:right;">
%(rightbts)s %(rightbts)s
</div> </div>
""" % dict( """ % dict(
flds=_("Fields"), leftbts="".join(lefttopbtns),
cards=_("Cards"),
rightbts="".join(righttopbtns), rightbts="".join(righttopbtns),
fldsTitle=_("Customize Fields"),
cardsTitle=shortcut(_("Customize Card Templates (Ctrl+L)")),
) )
bgcol = self.mw.app.palette().window().color().name() # type: ignore bgcol = self.mw.app.palette().window().color().name() # type: ignore
# then load page # then load page
@ -218,7 +218,7 @@ class Editor:
def addButton( def addButton(
self, self,
icon: str, icon: Optional[str],
cmd: str, cmd: str,
func: Callable[["Editor"], None], func: Callable[["Editor"], None],
tip: str = "", tip: str = "",
@ -227,6 +227,7 @@ class Editor:
toggleable: bool = False, toggleable: bool = False,
keys: str = None, keys: str = None,
disables: bool = True, disables: bool = True,
rightside: bool = True,
): ):
"""Assign func to bridge cmd, register shortcut, return button""" """Assign func to bridge cmd, register shortcut, return button"""
if func: if func:
@ -245,18 +246,20 @@ class Editor:
id=id, id=id,
toggleable=toggleable, toggleable=toggleable,
disables=disables, disables=disables,
rightside=rightside,
) )
return btn return btn
def _addButton( def _addButton(
self, self,
icon: str, icon: Optional[str],
cmd: str, cmd: str,
tip: str = "", tip: str = "",
label: str = "", label: str = "",
id: Optional[str] = None, id: Optional[str] = None,
toggleable: bool = False, toggleable: bool = False,
disables: bool = True, disables: bool = True,
rightside: bool = True,
) -> str: ) -> str:
if icon: if icon:
if icon.startswith("qrc:/"): if icon.startswith("qrc:/"):
@ -281,12 +284,15 @@ class Editor:
else: else:
toggleScript = "" toggleScript = ""
tip = shortcut(tip) tip = shortcut(tip)
theclass = "linkb" if rightside:
class_ = "linkb"
else:
class_ = ""
if not disables: if not disables:
theclass += " perm" class_ += " perm"
return """ <button tabindex=-1 return """ <button tabindex=-1
{id} {id}
class="{theclass}" class="{class_}"
type="button" type="button"
title="{tip}" title="{tip}"
onclick="pycmd('{cmd}');{togglesc}return false;" onclick="pycmd('{cmd}');{togglesc}return false;"
@ -300,7 +306,7 @@ class Editor:
labelelm=labelelm, labelelm=labelelm,
id=idstr, id=idstr,
togglesc=toggleScript, togglesc=toggleScript,
theclass=theclass, class_=class_,
) )
def setupShortcuts(self) -> None: def setupShortcuts(self) -> None:

View file

@ -1401,6 +1401,33 @@ class _EditorDidInitButtonsHook:
editor_did_init_buttons = _EditorDidInitButtonsHook() editor_did_init_buttons = _EditorDidInitButtonsHook()
class _EditorDidInitLeftButtonsHook:
_hooks: List[Callable[[List[str], "aqt.editor.Editor"], None]] = []
def append(self, cb: Callable[[List[str], "aqt.editor.Editor"], None]) -> None:
"""(buttons: List[str], editor: aqt.editor.Editor)"""
self._hooks.append(cb)
def remove(self, cb: Callable[[List[str], "aqt.editor.Editor"], None]) -> None:
if cb in self._hooks:
self._hooks.remove(cb)
def count(self) -> int:
return len(self._hooks)
def __call__(self, buttons: List[str], editor: aqt.editor.Editor) -> None:
for hook in self._hooks:
try:
hook(buttons, editor)
except:
# if the hook fails, remove it
self._hooks.remove(hook)
raise
editor_did_init_left_buttons = _EditorDidInitLeftButtonsHook()
class _EditorDidInitShortcutsHook: class _EditorDidInitShortcutsHook:
_hooks: List[Callable[[List[Tuple], "aqt.editor.Editor"], None]] = [] _hooks: List[Callable[[List[Tuple], "aqt.editor.Editor"], None]] = []

View file

@ -606,6 +606,10 @@ gui_hooks.webview_did_inject_style_into_page.append(mytest)
), ),
# Editing # Editing
################### ###################
Hook(
name="editor_did_init_left_buttons",
args=["buttons: List[str]", "editor: aqt.editor.Editor"],
),
Hook( Hook(
name="editor_did_init_buttons", name="editor_did_init_buttons",
args=["buttons: List[str]", "editor: aqt.editor.Editor"], args=["buttons: List[str]", "editor: aqt.editor.Editor"],