Mercurial > libervia-backend
diff sat_frontends/primitivus/chat.py @ 2624:56f94936df1e
code style reformatting using black
author | Goffi <goffi@goffi.org> |
---|---|
date | Wed, 27 Jun 2018 20:14:46 +0200 |
parents | 26edcf3a30eb |
children | df2bc2e704bc |
line wrap: on
line diff
--- a/sat_frontends/primitivus/chat.py Wed Jun 27 07:51:29 2018 +0200 +++ b/sat_frontends/primitivus/chat.py Wed Jun 27 20:14:46 2018 +0200 @@ -19,6 +19,7 @@ from sat.core.i18n import _ from sat.core import log as logging + log = logging.getLogger(__name__) import urwid from urwid_satext import sat_widgets @@ -36,8 +37,8 @@ OCCUPANTS_FOOTER = _(u"{} occupants") + class MessageWidget(urwid.WidgetWrap): - def __init__(self, mess_data): """ @param mess_data(quick_chat.Message, None): message data @@ -49,7 +50,11 @@ @property def markup(self): - return self._generateInfoMarkup() if self.mess_data.type == C.MESS_TYPE_INFO else self._generateMarkup() + return ( + self._generateInfoMarkup() + if self.mess_data.type == C.MESS_TYPE_INFO + else self._generateMarkup() + ) @property def info_type(self): @@ -66,7 +71,7 @@ @message.setter def message(self, value): - self.mess_data.message = {'':value} + self.mess_data.message = {"": value} self.redraw() @property @@ -98,7 +103,7 @@ return canvas def _generateInfoMarkup(self): - return ('info_msg', self.message) + return ("info_msg", self.message) def _generateMarkup(self): """Generate text markup according to message data and Widget options""" @@ -108,25 +113,29 @@ # message status if d.status is None: - markup.append(u' ') + markup.append(u" ") elif d.status == "delivered": - markup.append(('msg_status_received', u'✔')) + markup.append(("msg_status_received", u"✔")) else: log.warning(u"Unknown status: {}".format(d.status)) # timestamp if self.parent.show_timestamp: - attr = 'msg_mention' if mention else 'date' + attr = "msg_mention" if mention else "date" markup.append((attr, u"[{}]".format(d.time_text))) else: if mention: - markup.append(('msg_mention', '[*]')) + markup.append(("msg_mention", "[*]")) # nickname if self.parent.show_short_nick: - markup.append(('my_nick' if d.own_mess else 'other_nick', "**" if d.own_mess else "*")) + markup.append( + ("my_nick" if d.own_mess else "other_nick", "**" if d.own_mess else "*") + ) else: - markup.append(('my_nick' if d.own_mess else 'other_nick', u"[{}] ".format(d.nick or ''))) + markup.append( + ("my_nick" if d.own_mess else "other_nick", u"[{}] ".format(d.nick or "")) + ) msg = self.message # needed to generate self.selected_lang @@ -146,18 +155,20 @@ """ self.redraw() + @total_ordering class OccupantWidget(urwid.WidgetWrap): - def __init__(self, occupant_data): self.occupant_data = occupant_data occupant_data.widgets.add(self) markup = self._generateMarkup() text = sat_widgets.ClickableText(markup) - urwid.connect_signal(text, - 'click', + urwid.connect_signal( + text, + "click", self.occupant_data.parent._occupantsClicked, - user_args=[self.occupant_data]) + user_args=[self.occupant_data], + ) super(OccupantWidget, self).__init__(text) def __eq__(self, other): @@ -206,13 +217,12 @@ # should be more intuitive and themable o = self.occupant_data markup = [] - markup.append(('info_msg', u'{}{} '.format( - o.role[0].upper(), - o.affiliation[0].upper(), - ))) + markup.append( + ("info_msg", u"{}{} ".format(o.role[0].upper(), o.affiliation[0].upper())) + ) markup.append(o.nick) if o.state is not None: - markup.append(u' {}'.format(C.CHAT_STATE_ICON[o.state])) + markup.append(u" {}".format(C.CHAT_STATE_ICON[o.state])) return markup # events @@ -221,15 +231,16 @@ class OccupantsWidget(urwid.WidgetWrap): - def __init__(self, parent): self.parent = parent self.occupants_walker = urwid.SimpleListWalker([]) - self.occupants_footer = urwid.Text('', align='center') + self.occupants_footer = urwid.Text("", align="center") self.updateFooter() - occupants_widget = urwid.Frame(urwid.ListBox(self.occupants_walker), footer=self.occupants_footer) + occupants_widget = urwid.Frame( + urwid.ListBox(self.occupants_walker), footer=self.occupants_footer + ) super(OccupantsWidget, self).__init__(occupants_widget) - occupants_list = sorted(self.parent.occupants.keys(), key=lambda o:o.lower()) + occupants_list = sorted(self.parent.occupants.keys(), key=lambda o: o.lower()) for occupant in occupants_list: occupant_data = self.parent.occupants[occupant] self.occupants_walker.append(OccupantWidget(occupant_data)) @@ -239,12 +250,16 @@ txt = OCCUPANTS_FOOTER.format(len(self.parent.occupants)) self.occupants_footer.set_text(txt) - def getNicks(self, start=u''): + def getNicks(self, start=u""): """Return nicks of all occupants @param start(unicode): only return nicknames which start with this text """ - return [w.nick for w in self.occupants_walker if isinstance(w, OccupantWidget) and w.nick.startswith(start)] + return [ + w.nick + for w in self.occupants_walker + if isinstance(w, OccupantWidget) and w.nick.startswith(start) + ] def addUser(self, occupant_data): """add a user to the list""" @@ -261,14 +276,24 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat): - - def __init__(self, host, target, type_=C.CHAT_ONE2ONE, nick=None, occupants=None, subject=None, profiles=None): - quick_chat.QuickChat.__init__(self, host, target, type_, nick, occupants, subject, profiles=profiles) + def __init__( + self, + host, + target, + type_=C.CHAT_ONE2ONE, + nick=None, + occupants=None, + subject=None, + profiles=None, + ): + quick_chat.QuickChat.__init__( + self, host, target, type_, nick, occupants, subject, profiles=profiles + ) self.filters = [] # list of filter callbacks to apply self.mess_walker = urwid.SimpleListWalker([]) self.mess_widgets = urwid.ListBox(self.mess_walker) self.chat_widget = urwid.Frame(self.mess_widgets) - self.chat_colums = urwid.Columns([('weight', 8, self.chat_widget)]) + self.chat_colums = urwid.Columns([("weight", 8, self.chat_widget)]) self.pile = urwid.Pile([self.chat_colums]) PrimitivusWidget.__init__(self, self.pile, self.target) @@ -276,9 +301,11 @@ if type_ == C.CHAT_GROUP: if len(self.chat_colums.contents) == 1: self.occupants_widget = OccupantsWidget(self) - self.occupants_panel = sat_widgets.VerticalSeparator(self.occupants_widget) + self.occupants_panel = sat_widgets.VerticalSeparator( + self.occupants_widget + ) self._appendOccupantsPanel() - self.host.addListener('presence', self.presenceListener, [profiles]) + self.host.addListener("presence", self.presenceListener, [profiles]) # focus marker is a separator indicated last visible message before focus was lost self.focus_marker = None # link to current marker @@ -289,30 +316,32 @@ self.postInit() def keypress(self, size, key): - if key == a_key['OCCUPANTS_HIDE']: # user wants to (un)hide the occupants panel + if key == a_key["OCCUPANTS_HIDE"]: # user wants to (un)hide the occupants panel if self.type == C.CHAT_GROUP: widgets = [widget for (widget, options) in self.chat_colums.contents] if self.occupants_panel in widgets: self._removeOccupantsPanel() else: self._appendOccupantsPanel() - elif key == a_key['TIMESTAMP_HIDE']: # user wants to (un)hide timestamp + elif key == a_key["TIMESTAMP_HIDE"]: # user wants to (un)hide timestamp self.show_timestamp = not self.show_timestamp self.redraw() - elif key == a_key['SHORT_NICKNAME']: # user wants to (not) use short nick + elif key == a_key["SHORT_NICKNAME"]: # user wants to (not) use short nick self.show_short_nick = not self.show_short_nick self.redraw() - elif key == a_key['SUBJECT_SWITCH']: # user wants to (un)hide group's subject or change its apperance + elif ( + key == a_key["SUBJECT_SWITCH"] + ): # user wants to (un)hide group's subject or change its apperance if self.subject: self.show_title = (self.show_title + 1) % 3 if self.show_title == 0: - self.setSubject(self.subject, 'clip') + self.setSubject(self.subject, "clip") elif self.show_title == 1: - self.setSubject(self.subject, 'space') + self.setSubject(self.subject, "space") elif self.show_title == 2: self.chat_widget.header = None self._invalidate() - elif key == a_key['GOTO_BOTTOM']: # user wants to focus last message + elif key == a_key["GOTO_BOTTOM"]: # user wants to focus last message self.mess_widgets.focus_position = len(self.mess_walker) - 1 return super(Chat, self).keypress(size, key) @@ -326,25 +355,25 @@ return text space = text.rfind(" ") - start = text[space + 1:] + start = text[space + 1 :] words = self.occupants_widget.getNicks(start) if not words: return text try: - word_idx = words.index(completion_data['last_word']) + 1 + word_idx = words.index(completion_data["last_word"]) + 1 except (KeyError, ValueError): word_idx = 0 else: if word_idx == len(words): word_idx = 0 - word = completion_data['last_word'] = words[word_idx] - return u"{}{}{}".format(text[:space + 1], word, ': ' if space < 0 else '') + word = completion_data["last_word"] = words[word_idx] + return u"{}{}{}".format(text[: space + 1], word, ": " if space < 0 else "") def getMenu(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.addMenus(menu, C.MENU_ROOM, {"room_jid": self.target.bare}) game = _("Game") menu.addMenu(game, "Tarot", self.onTarotRequest) elif self.type == C.CHAT_ONE2ONE: @@ -354,7 +383,7 @@ full_jid = contact_list.getFullJid(self.target) else: full_jid = self.target - self.host.addMenus(menu, C.MENU_SINGLE, {'jid': full_jid}) + self.host.addMenus(menu, C.MENU_SINGLE, {"jid": full_jid}) return menu def setFilter(self, args): @@ -399,7 +428,7 @@ if message.type != C.MESS_TYPE_INFO: return False try: - info_type = message.extra['info_type'] + info_type = message.extra["info_type"] except KeyError: return False else: @@ -429,25 +458,33 @@ continue if wid.mess_data.type != C.MESS_TYPE_INFO: break - if wid.info_type in quick_chat.ROOM_USER_MOVED and wid.mess_data.nick == message.nick: + if ( + wid.info_type in quick_chat.ROOM_USER_MOVED + and wid.mess_data.nick == message.nick + ): try: count = wid.reentered_count except AttributeError: count = wid.reentered_count = 1 nick = wid.mess_data.nick if message.info_type == quick_chat.ROOM_USER_LEFT: - wid.message = _(u"<= {nick} has left the room ({count})").format(nick=nick, count=count) + wid.message = _(u"<= {nick} has left the room ({count})").format( + nick=nick, count=count + ) else: - wid.message = _(u"<=> {nick} re-entered the room ({count})") .format(nick=nick, count=count) - wid.reentered_count+=1 + wid.message = _( + u"<=> {nick} re-entered the room ({count})" + ).format(nick=nick, count=count) + wid.reentered_count += 1 return - if ((self.host.selected_widget != self or not self.host.x_notify.hasFocus()) - and self.focus_marker_set is not None): + if ( + self.host.selected_widget != self or not self.host.x_notify.hasFocus() + ) 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: self.mess_walker.remove(self.focus_marker) - self.focus_marker = urwid.Divider('—') + self.focus_marker = urwid.Divider("—") self.mess_walker.append(self.focus_marker) self.focus_marker_set = True self._scrollDown() @@ -473,20 +510,24 @@ if wid.mess_data.mention: from_jid = wid.mess_data.from_jid - msg = _(u'You have been mentioned by {nick} in {room}'.format( - nick=wid.mess_data.nick, - room=self.target, - )) - self.host.notify(C.NOTIFY_MENTION, from_jid, msg, widget=self, profile=self.profile) + msg = _( + u"You have been mentioned by {nick} in {room}".format( + nick=wid.mess_data.nick, room=self.target + ) + ) + self.host.notify( + C.NOTIFY_MENTION, from_jid, msg, widget=self, profile=self.profile + ) elif self.type == C.CHAT_ONE2ONE: from_jid = wid.mess_data.from_jid - msg = _(u'{entity} is talking to you'.format( - entity=from_jid, - )) - self.host.notify(C.NOTIFY_MESSAGE, from_jid, msg, widget=self, profile=self.profile) + msg = _(u"{entity} is talking to you".format(entity=from_jid)) + self.host.notify( + C.NOTIFY_MESSAGE, from_jid, msg, widget=self, profile=self.profile + ) else: - self.host.notify(C.NOTIFY_MESSAGE, self.target, widget=self, profile=self.profile) - + self.host.notify( + C.NOTIFY_MESSAGE, self.target, widget=self, profile=self.profile + ) def addUser(self, nick): occupant = super(Chat, self).addUser(nick) @@ -505,11 +546,13 @@ self.getOrCreatePrivateWidget(occupant.jid) # now we select the new window - for contact_list in self.host.widgets.getWidgets(ContactList, profiles=(self.profile,)): + for contact_list in self.host.widgets.getWidgets( + ContactList, profiles=(self.profile,) + ): contact_list.setFocus(occupant.jid, True) def _appendOccupantsPanel(self): - self.chat_colums.contents.append((self.occupants_panel, ('weight', 2, False))) + self.chat_colums.contents.append((self.occupants_panel, ("weight", 2, False))) def _removeOccupantsPanel(self): for widget, options in self.chat_colums.contents: @@ -522,9 +565,9 @@ @param widget (Widget): the game panel """ - assert (len(self.pile.contents) == 1) - self.pile.contents.insert(0, (widget, ('weight', 1))) - self.pile.contents.insert(1, (urwid.Filler(urwid.Divider('-'), ('fixed', 1)))) + assert len(self.pile.contents) == 1 + self.pile.contents.insert(0, (widget, ("weight", 1))) + self.pile.contents.insert(1, (urwid.Filler(urwid.Divider("-"), ("fixed", 1)))) self.host.redraw() def removeGamePanel(self, widget): @@ -532,16 +575,19 @@ @param widget (Widget): the game panel """ - assert (len(self.pile.contents) == 3) + assert len(self.pile.contents) == 3 del self.pile.contents[0] self.host.redraw() - def setSubject(self, subject, wrap='space'): + def setSubject(self, subject, wrap="space"): """Set title for a group chat""" quick_chat.QuickChat.setSubject(self, subject) - self.subj_wid = urwid.Text(unicode(subject.replace('\n', '|') if wrap == 'clip' else subject), - align='left' if wrap == 'clip' else 'center', wrap=wrap) - self.chat_widget.header = urwid.AttrMap(self.subj_wid, 'title') + self.subj_wid = urwid.Text( + unicode(subject.replace("\n", "|") if wrap == "clip" else subject), + align="left" if wrap == "clip" else "center", + wrap=wrap, + ) + self.chat_widget.header = urwid.AttrMap(self.subj_wid, "title") self.host.redraw() ## Messages @@ -564,11 +610,19 @@ except AttributeError: pass - def updateHistory(self, size=C.HISTORY_LIMIT_DEFAULT, filters=None, profile='@NONE@'): + def updateHistory(self, size=C.HISTORY_LIMIT_DEFAULT, filters=None, profile="@NONE@"): del self.mess_walker[:] - if filters and 'search' in filters: - self.mess_walker.append(urwid.Text(_(u"Results for searching the globbing pattern: {}").format(filters['search']))) - self.mess_walker.append(urwid.Text(_(u"Type ':history <lines>' to reset the chat history"))) + if filters and "search" in filters: + self.mess_walker.append( + urwid.Text( + _(u"Results for searching the globbing pattern: {}").format( + filters["search"] + ) + ) + ) + self.mess_walker.append( + urwid.Text(_(u"Type ':history <lines>' to reset the chat history")) + ) super(Chat, self).updateHistory(size, filters, profile) def _onHistoryPrinted(self): @@ -577,7 +631,9 @@ super(Chat, self)._onHistoryPrinted() def onPrivateCreated(self, widget): - self.host.contact_lists[widget.profile].setSpecial(widget.target, C.CONTACT_SPECIAL_GROUP) + self.host.contact_lists[widget.profile].setSpecial( + widget.target, C.CONTACT_SPECIAL_GROUP + ) def onSelected(self): self.focus_marker_set = False @@ -598,17 +654,32 @@ self.host.redraw() if not self.host.x_notify.hasFocus(): if self.type == C.CHAT_ONE2ONE: - self.host.x_notify.sendNotification(_("Primitivus: %s is talking to you") % contact) + self.host.x_notify.sendNotification( + _("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(_("Primitivus: %(user)s mentioned you in room '%(room)s'") % {'user': contact, 'room': self.target}) + self.host.x_notify.sendNotification( + _("Primitivus: %(user)s mentioned you in room '%(room)s'") + % {"user": contact, "room": self.target} + ) # MENU EVENTS # def onTarotRequest(self, menu): # TODO: move this to plugin_misc_tarot with dynamic menu if len(self.occupants) != 4: - self.host.showPopUp(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)) + self.host.showPopUp( + 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, + ) + ) else: - self.host.bridge.tarotGameCreate(self.target, list(self.occupants), self.profile) + self.host.bridge.tarotGameCreate( + self.target, list(self.occupants), self.profile + ) # MISC EVENTS # @@ -616,7 +687,7 @@ # FIXME: to be checked after refactoring super(Chat, self).onDelete() if self.type == C.CHAT_GROUP: - self.host.removeListener('presence', self.presenceListener) + self.host.removeListener("presence", self.presenceListener) def onChatState(self, from_jid, state, profile): super(Chat, self).onChatState(from_jid, state, profile) @@ -630,12 +701,14 @@ def onSubjectDialog(self, new_subject=None): dialog = sat_widgets.InputDialog( - _(u'Change title'), - _(u'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 dummy: self.host.removePopUp(dialog)) + _(u"Change title"), + _(u"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 dummy: self.host.removePopUp(dialog)) self.host.showPopUp(dialog) + quick_widgets.register(quick_chat.QuickChat, Chat) quick_widgets.register(quick_games.Tarot, game_tarot.TarotGame)