Skip to content

Commit 00b8ead

Browse files
committed
buttons: Add CodeSnippetButton class.
This class inherits urwid.Button and incorporates methods to facilitate the creation of a code snippet button and copying code to the clipboard.
1 parent c8f15e2 commit 00b8ead

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

zulipterminal/ui_tools/buttons.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -666,6 +666,67 @@ def handle_narrow_link(self) -> None:
666666
self.controller.exit_popup()
667667

668668

669+
class CodeSnippetButton(urwid.Button):
670+
def __init__(
671+
self,
672+
*,
673+
controller: Any,
674+
caption: str,
675+
display_code: List[Tuple[str, str]],
676+
copy_code: str,
677+
display_attr: Optional[str],
678+
) -> None:
679+
self.controller = controller
680+
self.model = self.controller.model
681+
self.view = self.controller.view
682+
self.caption = caption
683+
self.display_code = display_code
684+
self.copy_code = copy_code
685+
686+
super().__init__("")
687+
688+
self.update_widget(display_code, display_attr)
689+
urwid.connect_signal(self, "click", self.copy_to_clipboard)
690+
691+
def update_widget(
692+
self, display_code: List[Tuple[str, str]], display_attr: Optional[str] = None
693+
) -> None:
694+
"""
695+
Overrides the existing button widget for custom styling.
696+
"""
697+
# Set cursor position next to len(caption) to avoid the cursor.
698+
icon = urwid.SelectableIcon(
699+
display_code,
700+
cursor_position=len("".join([code[1] for code in display_code])) + 1,
701+
)
702+
self._w = urwid.AttrMap(icon, display_attr, focus_map="selected")
703+
704+
def copy_to_clipboard(self, *_: Any) -> None:
705+
self.controller.copy_to_clipboard(self.copy_code, "Code")
706+
707+
def get_code_from_snippet(
708+
self, snippet_list: List[Tuple[str, str]]
709+
) -> Tuple[List[Tuple[str, str]], str]:
710+
"""
711+
Returns two lines of code from the given snippet list
712+
as to summarize the code and
713+
returns code in text format to be copied.
714+
"""
715+
snippet = snippet_list[:]
716+
no_of_lines = 0
717+
code = "".join(snip[1] for snip in snippet)
718+
for index, snip in enumerate(snippet):
719+
no_of_lines += 1 if "\n" in snip[1] else 0
720+
if no_of_lines == 2:
721+
return snippet[:index] + [("pygments:w", "...")], code
722+
return snippet, code
723+
724+
def keypress(self, size: urwid_Size, key: str) -> Optional[str]:
725+
if is_command_key("COPY_CODE_SNIPPET", key):
726+
urwid.emit_signal(self, "click")
727+
return super().keypress(size, key)
728+
729+
669730
class EditModeButton(urwid.Button):
670731
def __init__(self, *, controller: Any, width: int) -> None:
671732
self.controller = controller

0 commit comments

Comments
 (0)