def test_set_footer_text_specific_text(self, view: View, text: str = "blah") -> None: view.set_footer_text([text]) view.frame.footer.set_text.assert_called_once_with([text]) view.controller.update_screen.assert_called_once_with()
def test_set_footer_text_same_test(self, view: View, mocker: MockerFixture, text: List[str] = ["heya"]) -> None: view._w.footer.text = text view.set_footer_text(text) view._w.footer.set_text.assert_not_called()
def test_set_footer_text_default(self, view: View, mocker: MockerFixture) -> None: mocker.patch(VIEW + ".get_random_help", return_value=["some help text"]) view.set_footer_text() view.frame.footer.set_text.assert_called_once_with(["some help text"]) view.controller.update_screen.assert_called_once_with()
def test_set_typeahead_footer( self, mocker: MockerFixture, view: View, state: Optional[int], suggestions: List[str], truncated: bool, footer_text: List[Any], ) -> None: set_footer_text = mocker.patch(VIEW + ".set_footer_text") view.set_typeahead_footer(suggestions, state, truncated) set_footer_text.assert_called_once_with(footer_text)
def __init__( self, *, config_file: str, maximum_footlinks: int, theme_name: str, theme: ThemeSpec, color_depth: int, debug_path: Optional[str], in_explore_mode: bool, autohide: bool, notify: bool, ) -> None: self.theme_name = theme_name self.theme = theme self.color_depth = color_depth self.in_explore_mode = in_explore_mode self.autohide = autohide self.notify_enabled = notify self.maximum_footlinks = maximum_footlinks self.debug_path = debug_path self._editor: Optional[Any] = None self.active_conversation_info: Dict[str, Any] = {} self.is_typing_notification_in_progress = False self.show_loading() client_identifier = f"ZulipTerminal/{ZT_VERSION} {platform()}" self.client = zulip.Client(config_file=config_file, client=client_identifier) self.model = Model(self) self.view = View(self) # Start polling for events after view is rendered. self.model.poll_for_events() screen = Screen() screen.set_terminal_properties(colors=self.color_depth) self.loop = urwid.MainLoop(self.view, self.theme, screen=screen) # urwid pipe for concurrent screen update handling self._update_pipe = self.loop.watch_pipe(self._draw_screen) # data and urwid pipe for inter-thread exception handling self._exception_info: Optional[ExceptionInfo] = None self._critical_exception = False self._exception_pipe = self.loop.watch_pipe(self._raise_exception) # Register new ^C handler signal.signal(signal.SIGINT, self.exit_handler)
def test_keypress_ALL_MENTIONS( self, view: View, mocker: MockerFixture, key: str, widget_size: Callable[[Widget], urwid_Box], ) -> None: view.mentioned_button = mocker.Mock() view.mentioned_button.activate = mocker.Mock() view.controller.is_in_editor_mode = lambda: False size = widget_size(view) view.keypress(size, key) view.mentioned_button.activate.assert_called_once_with(key)
def test_left_column_view(self, mocker: MockerFixture, view: View) -> None: left_view = mocker.patch(MODULE + ".LeftColumnView") left_tab = mocker.patch(MODULE + ".TabView") return_value = view.left_column_view() assert return_value == (left_view(view), left_tab())
def test_main_window(self, mocker, monkeypatch): left = mocker.patch("zulipterminal.ui.View.left_column_view") # NOTE: Use monkeypatch not patch, as view doesn't exist until later def just_set_message_view(self): self.message_view = mocker.Mock(read_message=lambda: None) monkeypatch.setattr(View, "middle_column_view", just_set_message_view) right = mocker.patch("zulipterminal.ui.View.right_column_view") col = mocker.patch("zulipterminal.ui.urwid.Columns") frame = mocker.patch("zulipterminal.ui.urwid.Frame") title_divider = mocker.patch("zulipterminal.ui.urwid.Divider") text = mocker.patch("zulipterminal.ui.urwid.Text") footer_view = mocker.patch("zulipterminal.ui.View.footer_view") full_name = "Bob James" email = "*****@*****.**" server = "https://chat.zulip.zulip/" server_name = "Test Organization" self.controller.model = self.model self.model.user_full_name = full_name self.model.user_email = email self.model.server_url = server self.model.server_name = server_name title_length = len(email) + len(full_name) + len(server) + len( server_name) + 11 view = View(self.controller) left.assert_called_once_with() # NOTE: Don't check center here, as we're monkeypatching it right.assert_called_once_with() expected_column_calls = [ mocker.call( [ (View.LEFT_WIDTH, left()), ("weight", 10, mocker.ANY), # ANY is a center (0, right()), ], focus_column=0, ), mocker.call()._contents.set_focus_changed_callback( view.message_view.read_message), mocker.call([ title_divider(), (title_length, text()), title_divider(), ]), ] col.assert_has_calls(expected_column_calls) assert view.body == col() frame.assert_called_once_with(view.body, col(), focus_part="body", footer=footer_view())
def test_set_footer_text_with_duration( self, view: View, mocker: MockerFixture, custom_text: str = "custom", duration: Optional[float] = 5.3, ) -> None: mocker.patch(VIEW + ".get_random_help", return_value=["some help text"]) mock_sleep = mocker.patch("time.sleep") view.set_footer_text([custom_text], duration=duration) view.frame.footer.set_text.assert_has_calls( [mocker.call([custom_text]), mocker.call(["some help text"])]) mock_sleep.assert_called_once_with(duration) assert view.controller.update_screen.call_count == 2
def test_middle_column_view(self, view: View, mocker: MockerFixture) -> None: middle_view = mocker.patch(MODULE + ".MiddleColumnView") line_box = mocker.patch(MODULE + ".urwid.LineBox") return_value = view.middle_column_view() middle_view.assert_called_once_with(view, view.model, view.write_box, view.search_box) assert view.middle_column == middle_view() assert return_value == line_box()
def test_init(self, mocker): main_window = mocker.patch('zulipterminal.ui.View.main_window') view = View(self.controller) assert view.controller == self.controller assert view.model == self.model assert view.pinned_streams == self.model.pinned_streams assert view.unpinned_streams == self.model.unpinned_streams self.write_box.assert_called_once_with(view) self.search_box.assert_called_once_with(self.controller) main_window.assert_called_once_with()
def test_right_column_view(self, view: View, mocker: MockerFixture) -> None: right_view = mocker.patch(MODULE + ".RightColumnView") right_tab = mocker.patch(MODULE + ".TabView") line_box = mocker.patch(MODULE + ".urwid.LineBox") return_value = view.right_column_view() right_view.assert_called_once_with(view) assert view.users_view == right_view() assert return_value == (line_box(), right_tab())
def test_keypress_edit_mode( self, view: View, mocker: MockerFixture, key: str, widget_size: Callable[[Widget], urwid_Box], ) -> None: view.users_view = mocker.Mock() view.body = mocker.Mock() view.user_search = mocker.Mock() super_view = mocker.patch(MODULE + ".urwid.WidgetWrap.keypress") view.controller.is_in_editor_mode = lambda: True size = widget_size(view) view.keypress(size, key) view.controller.current_editor().keypress.assert_called_once_with( (size[1], ), key)
def __init__(self, config_file: str, theme: str) -> None: self.client = zulip.Client(config_file=config_file, client='ZulipTerminal/0.1.0 ' + platform()) # Register to the queue before initializing Model or View # so that we don't lose any updates while messages are being fetched. self.register() self.model = Model(self) self.view = View(self) # Start polling for events after view is rendered. self.model.poll_for_events() self.theme = theme
def test_init(self, mocker): main_window = mocker.patch(VIEW + ".main_window") view = View(self.controller) assert view.controller == self.controller assert view.model == self.model assert view.pinned_streams == self.model.pinned_streams assert view.unpinned_streams == self.model.unpinned_streams assert view.message_view is None self.write_box.assert_called_once_with(view) self.search_box.assert_called_once_with(self.controller) main_window.assert_called_once_with()
def test_keypress_normal_mode_navigation( self, view: View, mocker: MockerFixture, # TODO: Improve `widget_size`'s return type, likely via Protocols. widget_size: Callable[[Widget], urwid_Box], navigation_key: str, ) -> None: view.users_view = mocker.Mock() view.body = mocker.Mock() view.user_search = mocker.Mock() size = widget_size(view) super_keypress = mocker.patch(MODULE + ".urwid.WidgetWrap.keypress") view.controller.is_in_editor_mode = lambda: False view.keypress(size, navigation_key) super_keypress.assert_called_once_with(size, navigation_key)
def test_main_window(self, mocker): left = mocker.patch('zulipterminal.ui.View.left_column_view') center = mocker.patch('zulipterminal.ui.View.message_view') right = mocker.patch('zulipterminal.ui.View.right_column_view') col = mocker.patch("zulipterminal.ui.urwid.Columns") frame = mocker.patch('zulipterminal.ui.urwid.Frame') title_divider = mocker.patch('zulipterminal.ui.urwid.Divider') text = mocker.patch('zulipterminal.ui.urwid.Text') footer_view = mocker.patch('zulipterminal.ui.View.footer_view') full_name = "Bob James" email = "*****@*****.**" server = "https://chat.zulip.zulip/" server_name = "Test Organization" self.controller.model = self.model self.model.user_full_name = full_name self.model.user_email = email self.model.server_url = server self.model.server_name = server_name title_length = (len(email) + len(full_name) + len(server) + len(server_name) + 11) view = View(self.controller) left.assert_called_once_with() center.assert_called_once_with() right.assert_called_once_with() expected_column_calls = [ mocker.call([ (View.LEFT_WIDTH, left()), ('weight', 10, center()), (0, right()), ], focus_column=0), mocker.call()._contents.set_focus_changed_callback( view.model.msg_list.read_message), mocker.call([ title_divider(), (title_length, text()), title_divider(), ]) ] col.assert_has_calls(expected_column_calls) assert view.body == col() frame.assert_called_once_with(view.body, col(), focus_part='body', footer=footer_view())
def __init__(self, config_file: str, theme: ThemeSpec, autohide: bool) -> None: self.theme = theme self.autohide = autohide self.editor_mode = False # type: bool self.editor = None # type: Any self.show_loading() self.client = zulip.Client(config_file=config_file, client='ZulipTerminal/{} {}'.format( ZT_VERSION, platform())) self.model = Model(self) self.view = View(self) # Start polling for events after view is rendered. self.model.poll_for_events()
def test_keypress_STREAM_MESSAGE( self, view: View, mocker: MockerFixture, key: str, autohide: bool, widget_size: Callable[[Widget], urwid_Box], ) -> None: mocked_middle_column = mocker.patch.object(view, "middle_column", create=True) view.body = mocker.Mock() view.controller.autohide = autohide view.body.contents = ["streams", "messages", "users"] view.left_panel = mocker.Mock() view.right_panel = mocker.Mock() view.controller.is_in_editor_mode = lambda: False size = widget_size(view) returned_key = view.keypress(size, key) mocked_middle_column.keypress.assert_called_once_with(size, key) assert returned_key == key assert view.body.focus_col == 1
def test_keypress_autohide_users( self, view: View, mocker: MockerFixture, autohide: bool, key: str, widget_size: Callable[[Widget], urwid_Box], ) -> None: mocked_users_view = mocker.patch.object(view, "users_view", create=True) view.body = mocker.Mock() view.controller.autohide = autohide view.body.contents = ["streams", "messages", mocker.Mock()] view.left_panel = mocker.Mock() view.right_panel = mocker.Mock() size = widget_size(view) view.controller.is_in_editor_mode = lambda: False view.body.focus_position = None view.keypress(size, key) mocked_users_view.keypress.assert_called_once_with(size, key) assert view.body.focus_position == 2
def __init__(self, config_file: str, theme: ThemeSpec, color_depth: int, autohide: bool, notify: bool) -> None: self.theme = theme self.color_depth = color_depth self.autohide = autohide self.notify_enabled = notify self._editor = None # type: Optional[Any] self.show_loading() self.client = zulip.Client(config_file=config_file, client='ZulipTerminal/{} {}'.format( ZT_VERSION, platform())) self.model = Model(self) self.view = View(self) # Start polling for events after view is rendered. self.model.poll_for_events()
def test_main_window(self, mocker): left = mocker.patch('zulipterminal.ui.View.left_column_view') center = mocker.patch('zulipterminal.ui.View.message_view') right = mocker.patch('zulipterminal.ui.View.right_column_view') col = mocker.patch("zulipterminal.ui.urwid.Columns") frame = mocker.patch('zulipterminal.ui.urwid.Frame') title_divider = mocker.patch('zulipterminal.ui.urwid.Divider') text = mocker.patch('zulipterminal.ui.urwid.Text') footer_view = mocker.patch('zulipterminal.ui.View.footer_view') full_name = "Bob James" email = "*****@*****.**" server = "https://chat.zulip.zulip" mocker.patch('zulipterminal.core.Controller.client.get_profile', return_value=dict(full_name=full_name, email=email)) self.controller.client.base_url = server title_length = (len(email) + len(full_name) + len(server) + 9) view = View(self.controller) left.assert_called_once_with() center.assert_called_once_with() right.assert_called_once_with() expected_column_calls = [ mocker.call([ (View.LEFT_WIDTH, left()), ('weight', 10, center()), (0, right()), ], focus_column=0), mocker.call([ title_divider(), (title_length, text()), title_divider(), ]) ] col.assert_has_calls(expected_column_calls) assert view.body == col() frame.assert_called_once_with(view.body, col(), focus_part='body', footer=footer_view())
def test_keypress_OPEN_DRAFT( self, view: View, mocker: MockerFixture, draft: Composition, key: str, autohide: bool, widget_size: Callable[[Widget], urwid_Box], ) -> None: view.body = mocker.Mock() view.body.contents = ["streams", "messages", "users"] view.left_panel = mocker.Mock() view.middle_column = mocker.Mock() view.right_panel = mocker.Mock() view.controller.autohide = autohide view.controller.report_error = mocker.Mock() view.controller.is_in_editor_mode = lambda: False view.model.stream_id_from_name.return_value = 10 view.model.session_draft_message.return_value = draft view.model.user_id_email_dict = { 1: "*****@*****.**", 2: "*****@*****.**" } mocked_stream_box_view = mocker.patch.object(view.write_box, "stream_box_view") mocked_private_box_view = mocker.patch.object(view.write_box, "private_box_view") size = widget_size(view) view.keypress(size, key) if draft: if draft["type"] == "stream": mocked_stream_box_view.assert_called_once_with( caption=draft["to"], title=draft["subject"], stream_id=10) else: mocked_private_box_view.assert_called_once_with( recipient_user_ids=draft["to"], ) assert view.body.focus_col == 1 assert view.write_box.msg_write_box.edit_text == draft["content"] assert view.write_box.msg_write_box.edit_pos == len( draft["content"]) view.middle_column.set_focus.assert_called_once_with("footer") else: view.controller.report_error.assert_called_once_with( "No draft message was saved in this session.")
def __init__(self, config_file: str, theme_name: str, theme: ThemeSpec, color_depth: int, in_explore_mode: bool, autohide: bool, notify: bool, footlinks: bool) -> None: self.theme_name = theme_name self.theme = theme self.color_depth = color_depth self.in_explore_mode = in_explore_mode self.autohide = autohide self.notify_enabled = notify self.footlinks_enabled = footlinks self._editor = None # type: Optional[Any] self.show_loading() self.client = zulip.Client(config_file=config_file, client='ZulipTerminal/{} {}'.format( ZT_VERSION, platform())) self.model = Model(self) self.view = View(self) # Start polling for events after view is rendered. self.model.poll_for_events() screen = Screen() screen.set_terminal_properties(colors=self.color_depth) self.loop = urwid.MainLoop(self.view, self.theme, screen=screen) # urwid pipe for concurrent screen update handling self._update_pipe = self.loop.watch_pipe(self._draw_screen) # data and urwid pipe for inter-thread exception handling self._exception_info = None # type: Optional[ExceptionInfo] self._critical_exception = False self._exception_pipe = self.loop.watch_pipe(self._raise_exception) # Register new ^C handler signal.signal(signal.SIGINT, self.exit_handler)
def test_show_panel_methods( self, mocker: MockerFixture, visible: bool, autohide: bool, test_method: str, ) -> None: self.controller.autohide = autohide view = View(self.controller) view.frame.body = view.body tail = [None, 0, 0, "top", None, "relative", 100, None, 0, 0] if test_method == "left_panel": expected_overlay_options = ["left", None, "given", LEFT_WIDTH + 1 ] + tail expected_tab = view.left_tab expected_panel = view.left_panel view.show_left_panel(visible=visible) else: expected_overlay_options = [ "right", None, "given", RIGHT_WIDTH + 1 ] + tail expected_tab = view.right_tab expected_panel = view.right_panel view.show_right_panel(visible=visible) if autohide: if visible: assert (expected_panel, mocker.ANY) in view.frame.body.top_w.contents assert view.frame.body.bottom_w == view.body assert view.frame.body.contents[1][1] == tuple( expected_overlay_options) else: assert (expected_tab, mocker.ANY) in view.frame.body.contents assert view.body.focus_position == 1 else: # No change assert view.frame.body.contents[0][0] == view.left_panel assert view.frame.body.contents[2][0] == view.right_panel
def view(self, mocker): main_window = mocker.patch('zulipterminal.ui.View.main_window') return View(self.controller)
def view(self, mocker): main_window = mocker.patch('zulipterminal.ui.View.main_window') # View is an urwid.Frame instance, a Box widget. mocker.patch('zulipterminal.ui.View.sizing', return_value=frozenset({'box'})) return View(self.controller)
def view(self, mocker: MockerFixture) -> View: # View is an urwid.Frame instance, a Box widget. mocker.patch(VIEW + ".sizing", return_value=frozenset({"box"})) return View(self.controller)
class Controller: """ A class responsible for setting up the model and view and running the application. """ def __init__( self, config_file: str, maximum_footlinks: int, theme_name: str, theme: ThemeSpec, color_depth: int, in_explore_mode: bool, autohide: bool, notify: bool, ) -> None: self.theme_name = theme_name self.theme = theme self.color_depth = color_depth self.in_explore_mode = in_explore_mode self.autohide = autohide self.notify_enabled = notify self.maximum_footlinks = maximum_footlinks self._editor: Optional[Any] = None self.show_loading() client_identifier = f"ZulipTerminal/{ZT_VERSION} {platform()}" self.client = zulip.Client(config_file=config_file, client=client_identifier) self.model = Model(self) self.view = View(self) # Start polling for events after view is rendered. self.model.poll_for_events() screen = Screen() screen.set_terminal_properties(colors=self.color_depth) self.loop = urwid.MainLoop(self.view, self.theme, screen=screen) # urwid pipe for concurrent screen update handling self._update_pipe = self.loop.watch_pipe(self._draw_screen) # data and urwid pipe for inter-thread exception handling self._exception_info: Optional[ExceptionInfo] = None self._critical_exception = False self._exception_pipe = self.loop.watch_pipe(self._raise_exception) # Register new ^C handler signal.signal(signal.SIGINT, self.exit_handler) def raise_exception_in_main_thread(self, exc_info: ExceptionInfo, *, critical: bool) -> None: """ Sets an exception from another thread, which is cleanly handled from within the Controller thread via _raise_exception """ # Exceptions shouldn't occur before the pipe is set assert hasattr(self, "_exception_pipe") if isinstance(exc_info, tuple): self._exception_info = exc_info self._critical_exception = critical else: self._exception_info = ( RuntimeError, f"Invalid cross-thread exception info '{exc_info}'", None, ) self._critical_exception = True os.write(self._exception_pipe, b"1") def is_in_editor_mode(self) -> bool: return self._editor is not None def enter_editor_mode_with(self, editor: Any) -> None: assert self._editor is None, "Already in editor mode" self._editor = editor def exit_editor_mode(self) -> None: self._editor = None def current_editor(self) -> Any: assert self._editor is not None, "Current editor is None" return self._editor @asynch def show_loading(self) -> None: def spinning_cursor() -> Any: while True: yield from "|/-\\" spinner = spinning_cursor() sys.stdout.write("\033[92mWelcome to Zulip.\033[0m\n") while not hasattr(self, "view"): next_spinner = "Loading " + next(spinner) sys.stdout.write(next_spinner) sys.stdout.flush() time.sleep(0.1) sys.stdout.write("\b" * len(next_spinner)) self.capture_stdout() def capture_stdout(self, path: str = "debug.log") -> None: if hasattr(self, "_stdout"): return self._stdout = sys.stdout sys.stdout = open(path, "a") def restore_stdout(self) -> None: if not hasattr(self, "_stdout"): return sys.stdout.flush() sys.stdout.close() sys.stdout = self._stdout sys.stdout.write("\n") del self._stdout def update_screen(self) -> None: # Update should not happen until pipe is set assert hasattr(self, "_update_pipe") # Write something to update pipe to trigger draw_screen os.write(self._update_pipe, b"1") def _draw_screen(self, *args: Any, **kwargs: Any) -> Literal[True]: self.loop.draw_screen() return True # Always retain pipe def maximum_popup_dimensions(self) -> Tuple[int, int]: """ Returns 3/4th of the screen estate's columns if columns are greater than 100 (MAX_LINEAR_SCALING_WIDTH) else scales accordingly untill popup width becomes full width at 80 (MIN_SUPPORTED_POPUP_WIDTH) below which popup width remains full width. The screen estate's rows are always scaled by 3/4th to get the popup rows. """ MIN_SUPPORTED_POPUP_WIDTH = 80 MAX_LINEAR_SCALING_WIDTH = 100 def clamp(n: int, minn: int, maxn: int) -> int: return max(min(maxn, n), minn) max_cols, max_rows = self.loop.screen.get_cols_rows() min_width = MIN_SUPPORTED_POPUP_WIDTH max_width = MAX_LINEAR_SCALING_WIDTH # Scale Width width = clamp(max_cols, min_width, max_width) scaling = 1 - ((width - min_width) / (4 * (max_width - min_width))) max_popup_cols = int(scaling * max_cols) # Scale Height max_popup_rows = 3 * max_rows // 4 return max_popup_cols, max_popup_rows def show_pop_up(self, to_show: Any, style: str) -> None: border_lines = dict( tlcorner="▛", tline="▀", trcorner="▜", rline="▐", lline="▌", blcorner="▙", bline="▄", brcorner="▟", ) text = urwid.Text(to_show.title, align="center") title_map = urwid.AttrMap(urwid.Filler(text), style) title_box_adapter = urwid.BoxAdapter(title_map, height=1) title_box = urwid.LineBox( title_box_adapter, tlcorner="▄", tline="▄", trcorner="▄", rline="", lline="", blcorner="", bline="", brcorner="", ) title = urwid.AttrMap(title_box, "popup_border") content = urwid.LineBox(to_show, **border_lines) self.loop.widget = urwid.Overlay( urwid.AttrMap(urwid.Frame(header=title, body=content), "popup_border"), self.view, align="center", valign="middle", # +2 to both of the following, due to LineBox # +2 to height, due to title enhancement width=to_show.width + 2, height=to_show.height + 4, ) def exit_popup(self) -> None: self.loop.widget = self.view def show_help(self) -> None: help_view = HelpView(self, "Help Menu (up/down scrolls)") self.show_pop_up(help_view, "area:help") def show_topic_edit_mode(self, button: Any) -> None: self.show_pop_up(EditModeView(self, button), "area:msg") def show_msg_info( self, msg: Message, topic_links: "OrderedDict[str, Tuple[str, int, bool]]", message_links: "OrderedDict[str, Tuple[str, int, bool]]", time_mentions: List[Tuple[str, str]], ) -> None: msg_info_view = MsgInfoView( self, msg, "Message Information (up/down scrolls)", topic_links, message_links, time_mentions, ) self.show_pop_up(msg_info_view, "area:msg") def show_stream_info(self, stream_id: int) -> None: show_stream_view = StreamInfoView(self, stream_id) self.show_pop_up(show_stream_view, "area:stream") def show_stream_members(self, stream_id: int) -> None: stream_members_view = StreamMembersView(self, stream_id) self.show_pop_up(stream_members_view, "area:stream") def popup_with_message(self, text: str, width: int) -> None: self.show_pop_up(NoticeView(self, text, width, "NOTICE"), "area:error") def show_about(self) -> None: self.show_pop_up( AboutView( self, "About", zt_version=ZT_VERSION, server_version=self.model.server_version, server_feature_level=self.model.server_feature_level, theme_name=self.theme_name, color_depth=self.color_depth, notify_enabled=self.notify_enabled, autohide_enabled=self.autohide, maximum_footlinks=self.maximum_footlinks, ), "area:help", ) def show_user_info(self, user_id: int) -> None: self.show_pop_up( UserInfoView(self, user_id, "User Information (up/down scrolls)"), "area:user", ) def show_edit_history( self, message: Message, topic_links: "OrderedDict[str, Tuple[str, int, bool]]", message_links: "OrderedDict[str, Tuple[str, int, bool]]", time_mentions: List[Tuple[str, str]], ) -> None: self.show_pop_up( EditHistoryView( self, message, topic_links, message_links, time_mentions, "Edit History (up/down scrolls)", ), "area:msg", ) def open_in_browser(self, url: str) -> None: """ Opens any provided URL in a graphical browser, if found, else prints an appropriate error message. """ # Don't try to open web browser if running without a GUI # TODO: Explore and eventually support opening links in text-browsers. if LINUX and not os.environ.get("DISPLAY") and os.environ.get("TERM"): self.report_error( "No DISPLAY environment variable specified. This could " "likely mean the ZT host is running without a GUI.") return try: # Checks for a runnable browser in the system and returns # its browser controller, if found, else reports an error browser_controller = webbrowser.get() # Suppress stdout and stderr when opening browser with suppress_output(): browser_controller.open(url) self.report_success( f"The link was successfully opened using {browser_controller.name}" ) except webbrowser.Error as e: # Set a footer text if no runnable browser is located self.report_error(f"ERROR: {e}") def report_error(self, text: str) -> None: """ Helper to show an error message in footer """ self.view.set_footer_text(text, "task:error", 3) def report_success(self, text: str) -> None: """ Helper to show a success message in footer """ self.view.set_footer_text(text, "task:success", 3) def report_warning(self, text: str) -> None: """ Helper to show a warning message in footer """ self.view.set_footer_text(text, "task:warning", 3) def search_messages(self, text: str) -> None: # Search for a text in messages self.model.index["search"].clear() self.model.set_search_narrow(text) self.model.get_messages(num_after=0, num_before=30, anchor=10000000000) msg_id_list = self.model.get_message_ids_in_current_narrow() w_list = create_msg_box_list(self.model, msg_id_list) self.view.message_view.log.clear() self.view.message_view.log.extend(w_list) focus_position = 0 if 0 <= focus_position < len(w_list): self.view.message_view.set_focus(focus_position) def save_draft_confirmation_popup(self, draft: Composition) -> None: question = urwid.Text( "Save this message as a draft? (This will overwrite the existing draft.)" ) save_draft = partial(self.model.save_draft, draft) self.loop.widget = PopUpConfirmationView(self, question, save_draft) def stream_muting_confirmation_popup(self, stream_id: int, stream_name: str) -> None: currently_muted = self.model.is_muted_stream(stream_id) type_of_action = "unmuting" if currently_muted else "muting" question = urwid.Text( ("bold", f"Confirm {type_of_action} of stream '{stream_name}' ?"), "center", ) mute_this_stream = partial(self.model.toggle_stream_muted_status, stream_id) self.loop.widget = PopUpConfirmationView(self, question, mute_this_stream) def _narrow_to(self, anchor: Optional[int], **narrow: Any) -> None: already_narrowed = self.model.set_narrow(**narrow) if already_narrowed and anchor is None: return msg_id_list = self.model.get_message_ids_in_current_narrow() # If no messages are found in the current narrow # OR, given anchor is not present in msg_id_list # then, get more messages. if len(msg_id_list) == 0 or (anchor is not None and anchor not in msg_id_list): self.model.get_messages(num_before=30, num_after=10, anchor=anchor) msg_id_list = self.model.get_message_ids_in_current_narrow() w_list = create_msg_box_list(self.model, msg_id_list, focus_msg_id=anchor) focus_position = self.model.get_focus_in_current_narrow() if focus_position == set(): # No available focus; set to end focus_position = len(w_list) - 1 assert not isinstance(focus_position, set) self.view.message_view.log.clear() if 0 <= focus_position < len(w_list): self.view.message_view.log.extend(w_list, focus_position) else: self.view.message_view.log.extend(w_list) self.exit_editor_mode() def narrow_to_stream(self, *, stream_name: str, contextual_message_id: Optional[int] = None) -> None: self._narrow_to(anchor=contextual_message_id, stream=stream_name) def narrow_to_topic( self, *, stream_name: str, topic_name: str, contextual_message_id: Optional[int] = None, ) -> None: self._narrow_to( anchor=contextual_message_id, stream=stream_name, topic=topic_name, ) def narrow_to_user( self, *, recipient_emails: List[str], contextual_message_id: Optional[int] = None, ) -> None: self._narrow_to( anchor=contextual_message_id, pm_with=", ".join(recipient_emails), ) def narrow_to_all_messages(self, *, contextual_message_id: Optional[int] = None ) -> None: self._narrow_to(anchor=contextual_message_id) def narrow_to_all_pm(self, *, contextual_message_id: Optional[int] = None) -> None: self._narrow_to(anchor=contextual_message_id, pms=True) def narrow_to_all_starred(self) -> None: # NOTE: Should we allow maintaining anchor focus here? # (nothing currently requires narrowing around a message id) self._narrow_to(anchor=None, starred=True) def narrow_to_all_mentions(self) -> None: # NOTE: Should we allow maintaining anchor focus here? # (nothing currently requires narrowing around a message id) self._narrow_to(anchor=None, mentioned=True) def deregister_client(self) -> None: queue_id = self.model.queue_id self.client.deregister(queue_id, 1.0) def exit_handler(self, signum: int, frame: Any) -> None: self.deregister_client() sys.exit(0) def _raise_exception(self, *args: Any, **kwargs: Any) -> Literal[True]: if self._exception_info is not None: exc = self._exception_info if self._critical_exception: raise exc[0].with_traceback(exc[1], exc[2]) else: import traceback exception_logfile = "zulip-terminal-thread-exceptions.log" with open(exception_logfile, "a") as logfile: traceback.print_exception(*exc, file=logfile) message = ( "An exception occurred:" + "\n\n" + "".join(traceback.format_exception_only(exc[0], exc[1])) + "\n" + "The application should continue functioning, but you " + "may notice inconsistent behavior in this session." + "\n\n" + "Please report this to us either in" + "\n" + "* the #zulip-terminal stream" + "\n" + " (https://chat.zulip.org/#narrow/stream/" + "206-zulip-terminal in the webapp)" + "\n" + "* an issue at " + "https://github.com/zulip/zulip-terminal/issues" + "\n\n" + "Details of the exception can be found in " + exception_logfile) self.popup_with_message(message, width=80) self._exception_info = None return True # If don't raise, retain pipe def main(self) -> None: try: # TODO: Enable resuming? (in which case, remove ^Z below) disabled_keys = { "susp": "undefined", # Disable ^Z - no suspending "stop": "undefined", # Disable ^S - enabling shortcut key use "quit": "undefined", # Disable ^\, ^4 } old_signal_list = self.loop.screen.tty_signal_keys(**disabled_keys) self.loop.run() except Exception: self.restore_stdout() self.loop.screen.tty_signal_keys(*old_signal_list) raise finally: self.restore_stdout() self.loop.screen.tty_signal_keys(*old_signal_list)
def view(self, mocker): main_window = mocker.patch(VIEW + ".main_window") # View is an urwid.Frame instance, a Box widget. mocker.patch(VIEW + ".sizing", return_value=frozenset({"box"})) return View(self.controller)