diff sat_frontends/primitivus/chat.py @ 4037:524856bd7b19

massive refactoring to switch from camelCase to snake_case: historically, Libervia (SàT before) was using camelCase as allowed by PEP8 when using a pre-PEP8 code, to use the same coding style as in Twisted. However, snake_case is more readable and it's better to follow PEP8 best practices, so it has been decided to move on full snake_case. Because Libervia has a huge codebase, this ended with a ugly mix of camelCase and snake_case. To fix that, this patch does a big refactoring by renaming every function and method (including bridge) that are not coming from Twisted or Wokkel, to use fully snake_case. This is a massive change, and may result in some bugs.
author Goffi <goffi@goffi.org>
date Sat, 08 Apr 2023 13:54:42 +0200
parents be6d91572633
children 4b842c1fb686
line wrap: on
line diff
--- a/sat_frontends/primitivus/chat.py	Fri Apr 07 15:18:39 2023 +0200
+++ b/sat_frontends/primitivus/chat.py	Sat Apr 08 13:54:42 2023 +0200
@@ -53,9 +53,9 @@
     @property
     def markup(self):
         return (
-            self._generateInfoMarkup()
+            self._generate_info_markup()
             if self.mess_data.type == C.MESS_TYPE_INFO
-            else self._generateMarkup()
+            else self._generate_markup()
         )
 
     @property
@@ -104,10 +104,10 @@
             canvas.set_cursor(self.get_cursor_coords(size))
         return canvas
 
-    def _generateInfoMarkup(self):
+    def _generate_info_markup(self):
         return ("info_msg", self.message)
 
-    def _generateMarkup(self):
+    def _generate_markup(self):
         """Generate text markup according to message data and Widget options"""
         markup = []
         d = self.mess_data
@@ -163,12 +163,12 @@
     def __init__(self, occupant_data):
         self.occupant_data = occupant_data
         occupant_data.widgets.add(self)
-        markup = self._generateMarkup()
+        markup = self._generate_markup()
         text = sat_widgets.ClickableText(markup)
         urwid.connect_signal(
             text,
             "click",
-            self.occupant_data.parent._occupantsClicked,
+            self.occupant_data.parent._occupants_clicked,
             user_args=[self.occupant_data],
         )
         super(OccupantWidget, self).__init__(text)
@@ -186,7 +186,7 @@
 
     @property
     def markup(self):
-        return self._generateMarkup()
+        return self._generate_markup()
 
     @property
     def parent(self):
@@ -217,7 +217,7 @@
             canvas.set_cursor(self.get_cursor_coords(size))
         return canvas
 
-    def _generateMarkup(self):
+    def _generate_markup(self):
         # TODO: role and affiliation are shown in a Q&D way
         #       should be more intuitive and themable
         o = self.occupant_data
@@ -240,7 +240,7 @@
         self.parent = parent
         self.occupants_walker = urwid.SimpleListWalker([])
         self.occupants_footer = urwid.Text("", align="center")
-        self.updateFooter()
+        self.update_footer()
         occupants_widget = urwid.Frame(
             urwid.ListBox(self.occupants_walker), footer=self.occupants_footer
         )
@@ -253,12 +253,12 @@
     def clear(self):
         del self.occupants_walker[:]
 
-    def updateFooter(self):
+    def update_footer(self):
         """update footer widget"""
         txt = OCCUPANTS_FOOTER.format(len(self.parent.occupants))
         self.occupants_footer.set_text(txt)
 
-    def getNicks(self, start=""):
+    def get_nicks(self, start=""):
         """Return nicks of all occupants
 
         @param start(unicode): only return nicknames which start with this text
@@ -272,14 +272,14 @@
     def addUser(self, occupant_data):
         """add a user to the list"""
         bisect.insort(self.occupants_walker, OccupantWidget(occupant_data))
-        self.updateFooter()
+        self.update_footer()
         self.parent.host.redraw()  # FIXME: should not be necessary
 
     def removeUser(self, occupant_data):
         """remove a user from the list"""
         for widget in occupant_data.widgets:
             self.occupants_walker.remove(widget)
-        self.updateFooter()
+        self.update_footer()
         self.parent.host.redraw()  # FIXME: should not be necessary
 
 
@@ -305,8 +305,8 @@
                 self.occupants_panel = sat_widgets.VerticalSeparator(
                     self.occupants_widget
                 )
-                self._appendOccupantsPanel()
-                self.host.addListener("presence", self.presenceListener, [profiles])
+                self._append_occupants_panel()
+                self.host.addListener("presence", self.presence_listener, [profiles])
 
         # focus marker is a separator indicated last visible message before focus was lost
         self.focus_marker = None  # link to current marker
@@ -314,7 +314,7 @@
         self.show_timestamp = True
         self.show_short_nick = False
         self.show_title = 1  # 0: clip title; 1: full title; 2: no title
-        self.postInit()
+        self.post_init()
 
     @property
     def message_widgets_rev(self):
@@ -325,9 +325,9 @@
             if self.type == C.CHAT_GROUP:
                 widgets = [widget for (widget, options) in self.chat_colums.contents]
                 if self.occupants_panel in widgets:
-                    self._removeOccupantsPanel()
+                    self._remove_occupants_panel()
                 else:
-                    self._appendOccupantsPanel()
+                    self._append_occupants_panel()
         elif key == a_key["TIMESTAMP_HIDE"]:  # user wants to (un)hide timestamp
             self.show_timestamp = not self.show_timestamp
             self.redraw()
@@ -339,9 +339,9 @@
             if self.subject:
                 self.show_title = (self.show_title + 1) % 3
                 if self.show_title == 0:
-                    self.setSubject(self.subject, "clip")
+                    self.set_subject(self.subject, "clip")
                 elif self.show_title == 1:
-                    self.setSubject(self.subject, "space")
+                    self.set_subject(self.subject, "space")
                 elif self.show_title == 2:
                     self.chat_widget.header = None
                 self._invalidate()
@@ -360,7 +360,7 @@
 
         space = text.rfind(" ")
         start = text[space + 1 :]
-        words = self.occupants_widget.getNicks(start)
+        words = self.occupants_widget.get_nicks(start)
         if not words:
             return text
         try:
@@ -373,24 +373,24 @@
         word = completion_data["last_word"] = words[word_idx]
         return "{}{}{}".format(text[: space + 1], word, ": " if space < 0 else "")
 
-    def getMenu(self):
+    def get_menu(self):
         """Return Menu bar"""
         menu = sat_widgets.Menu(self.host.loop)
         if self.type == C.CHAT_GROUP:
-            self.host.addMenus(menu, C.MENU_ROOM, {"room_jid": self.target.bare})
+            self.host.add_menus(menu, C.MENU_ROOM, {"room_jid": self.target.bare})
             game = _("Game")
-            menu.addMenu(game, "Tarot", self.onTarotRequest)
+            menu.add_menu(game, "Tarot", self.on_tarot_request)
         elif self.type == C.CHAT_ONE2ONE:
             # FIXME: self.target is a bare jid, we need to check that
             contact_list = self.host.contact_lists[self.profile]
             if not self.target.resource:
-                full_jid = contact_list.getFullJid(self.target)
+                full_jid = contact_list.get_full_jid(self.target)
             else:
                 full_jid = self.target
-            self.host.addMenus(menu, C.MENU_SINGLE, {"jid": full_jid})
+            self.host.add_menus(menu, C.MENU_SINGLE, {"jid": full_jid})
         return menu
 
-    def setFilter(self, args):
+    def set_filter(self, args):
         """set filtering of messages
 
         @param args(list[unicode]): filters following syntax "[filter]=[value]"
@@ -403,9 +403,9 @@
                 lang = args[0][5:].strip()
                 self.filters.append(lambda mess_data: lang in mess_data.message)
 
-        self.printMessages()
+        self.print_messages()
 
-    def presenceListener(self, entity, show, priority, statuses, profile):
+    def presence_listener(self, entity, show, priority, statuses, profile):
         """Update entity's presence status
 
         @param entity (jid.JID): entity updated
@@ -421,7 +421,7 @@
         #     return
         # self.update(entity)
 
-    def createMessage(self, message):
+    def create_message(self, message):
         self.appendMessage(message)
 
     def _scrollDown(self):
@@ -461,10 +461,10 @@
             if not all([f(message) for f in self.filters]):
                 return
 
-        if self.handleUserMoved(message):
+        if self.handle_user_moved(message):
             return
 
-        if ((self.host.selected_widget != self or not self.host.x_notify.hasFocus())
+        if ((self.host.selected_widget != self or not self.host.x_notify.has_focus())
             and self.focus_marker_set is not None):
             if not self.focus_marker_set and not self._locked and self.mess_walker:
                 if self.focus_marker is not None:
@@ -486,7 +486,7 @@
         wid = MessageWidget(message)
         self.mess_walker.append(wid)
         self._scrollDown()
-        if self.isUserMoved(message):
+        if self.is_user_moved(message):
             return  # no notification for moved messages
 
         # notifications
@@ -528,33 +528,33 @@
         if occupant is not None:
             self.occupants_widget.removeUser(occupant)
 
-    def occupantsClear(self):
-        super(Chat, self).occupantsClear()
+    def occupants_clear(self):
+        super(Chat, self).occupants_clear()
         self.occupants_widget.clear()
 
-    def _occupantsClicked(self, occupant, clicked_wid):
+    def _occupants_clicked(self, occupant, clicked_wid):
         assert self.type == C.CHAT_GROUP
         contact_list = self.host.contact_lists[self.profile]
 
         # we have a click on a nick, we need to create the widget if it doesn't exists
-        self.getOrCreatePrivateWidget(occupant.jid)
+        self.get_or_create_private_widget(occupant.jid)
 
         # now we select the new window
-        for contact_list in self.host.widgets.getWidgets(
+        for contact_list in self.host.widgets.get_widgets(
             ContactList, profiles=(self.profile,)
         ):
-            contact_list.setFocus(occupant.jid, True)
+            contact_list.set_focus(occupant.jid, True)
 
-    def _appendOccupantsPanel(self):
+    def _append_occupants_panel(self):
         self.chat_colums.contents.append((self.occupants_panel, ("weight", 2, False)))
 
-    def _removeOccupantsPanel(self):
+    def _remove_occupants_panel(self):
         for widget, options in self.chat_colums.contents:
             if widget is self.occupants_panel:
                 self.chat_colums.contents.remove((widget, options))
                 break
 
-    def addGamePanel(self, widget):
+    def add_game_panel(self, widget):
         """Insert a game panel to this Chat dialog.
 
         @param widget (Widget): the game panel
@@ -564,7 +564,7 @@
         self.pile.contents.insert(1, (urwid.Filler(urwid.Divider("-"), ("fixed", 1))))
         self.host.redraw()
 
-    def removeGamePanel(self, widget):
+    def remove_game_panel(self, widget):
         """Remove the game panel from this Chat dialog.
 
         @param widget (Widget): the game panel
@@ -573,9 +573,9 @@
         del self.pile.contents[0]
         self.host.redraw()
 
-    def setSubject(self, subject, wrap="space"):
+    def set_subject(self, subject, wrap="space"):
         """Set title for a group chat"""
-        quick_chat.QuickChat.setSubject(self, subject)
+        quick_chat.QuickChat.set_subject(self, subject)
         self.subj_wid = urwid.Text(
             str(subject.replace("\n", "|") if wrap == "clip" else subject),
             align="left" if wrap == "clip" else "center",
@@ -586,7 +586,7 @@
 
     ## Messages
 
-    def printMessages(self, clear=True):
+    def print_messages(self, clear=True):
         """generate message widgets
 
         @param clear(bool): clear message before printing if true
@@ -604,7 +604,7 @@
             except AttributeError:
                 pass
 
-    def updateHistory(self, size=C.HISTORY_LIMIT_DEFAULT, filters=None, profile="@NONE@"):
+    def update_history(self, size=C.HISTORY_LIMIT_DEFAULT, filters=None, profile="@NONE@"):
         del self.mess_walker[:]
         if filters and "search" in filters:
             self.mess_walker.append(
@@ -617,19 +617,19 @@
             self.mess_walker.append(
                 urwid.Text(_("Type ':history <lines>' to reset the chat history"))
             )
-        super(Chat, self).updateHistory(size, filters, profile)
+        super(Chat, self).update_history(size, filters, profile)
 
-    def _onHistoryPrinted(self):
+    def _on_history_printed(self):
         """Refresh or scroll down the focus after the history is printed"""
-        self.printMessages(clear=False)
-        super(Chat, self)._onHistoryPrinted()
+        self.print_messages(clear=False)
+        super(Chat, self)._on_history_printed()
 
-    def onPrivateCreated(self, widget):
-        self.host.contact_lists[widget.profile].setSpecial(
+    def on_private_created(self, widget):
+        self.host.contact_lists[widget.profile].set_special(
             widget.target, C.CONTACT_SPECIAL_GROUP
         )
 
-    def onSelected(self):
+    def on_selected(self):
         self.focus_marker_set = False
 
     def notify(self, contact="somebody", msg=""):
@@ -646,62 +646,62 @@
             # as that mean that he is probably watching discussion history
             self.mess_widgets.focus_position = len(self.mess_walker) - 1
         self.host.redraw()
-        if not self.host.x_notify.hasFocus():
+        if not self.host.x_notify.has_focus():
             if self.type == C.CHAT_ONE2ONE:
-                self.host.x_notify.sendNotification(
+                self.host.x_notify.send_notification(
                     _("Primitivus: %s is talking to you") % contact
                 )
             elif self.nick is not None and self.nick.lower() in msg.lower():
-                self.host.x_notify.sendNotification(
+                self.host.x_notify.send_notification(
                     _("Primitivus: %(user)s mentioned you in room '%(room)s'")
                     % {"user": contact, "room": self.target}
                 )
 
     # MENU EVENTS #
-    def onTarotRequest(self, menu):
+    def on_tarot_request(self, menu):
         # TODO: move this to plugin_misc_tarot with dynamic menu
         if len(self.occupants) != 4:
-            self.host.showPopUp(
+            self.host.show_pop_up(
                 sat_widgets.Alert(
                     _("Can't start game"),
                     _(
                         "You need to be exactly 4 peoples in the room to start a Tarot game"
                     ),
-                    ok_cb=self.host.removePopUp,
+                    ok_cb=self.host.remove_pop_up,
                 )
             )
         else:
-            self.host.bridge.tarotGameCreate(
+            self.host.bridge.tarot_game_create(
                 self.target, list(self.occupants), self.profile
             )
 
     # MISC EVENTS #
 
-    def onDelete(self):
+    def on_delete(self):
         # FIXME: to be checked after refactoring
-        super(Chat, self).onDelete()
+        super(Chat, self).on_delete()
         if self.type == C.CHAT_GROUP:
-            self.host.removeListener("presence", self.presenceListener)
+            self.host.removeListener("presence", self.presence_listener)
 
-    def onChatState(self, from_jid, state, profile):
-        super(Chat, self).onChatState(from_jid, state, profile)
+    def on_chat_state(self, from_jid, state, profile):
+        super(Chat, self).on_chat_state(from_jid, state, profile)
         if self.type == C.CHAT_ONE2ONE:
             self.title_dynamic = C.CHAT_STATE_ICON[state]
             self.host.redraw()  # FIXME: should not be necessary
 
-    def _onSubjectDialogCb(self, button, dialog):
-        self.changeSubject(dialog.text)
-        self.host.removePopUp(dialog)
+    def _on_subject_dialog_cb(self, button, dialog):
+        self.change_subject(dialog.text)
+        self.host.remove_pop_up(dialog)
 
-    def onSubjectDialog(self, new_subject=None):
+    def on_subject_dialog(self, new_subject=None):
         dialog = sat_widgets.InputDialog(
             _("Change title"),
             _("Enter the new title"),
             default_txt=new_subject if new_subject is not None else self.subject,
         )
-        dialog.setCallback("ok", self._onSubjectDialogCb, dialog)
-        dialog.setCallback("cancel", lambda __: self.host.removePopUp(dialog))
-        self.host.showPopUp(dialog)
+        dialog.set_callback("ok", self._on_subject_dialog_cb, dialog)
+        dialog.set_callback("cancel", lambda __: self.host.remove_pop_up(dialog))
+        self.host.show_pop_up(dialog)
 
 
 quick_widgets.register(quick_chat.QuickChat, Chat)