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.
This commit is contained in:
Goffi 2023-04-08 13:54:42 +02:00
commit 6a6f15707a
11 changed files with 9945 additions and 9945 deletions

View file

@ -20,7 +20,7 @@
from sat.core.i18n import _, D_
from sat_frontends.primitivus.constants import Const as C
from sat.core import log_config
log_config.satConfigure(C.LOG_BACKEND_STANDARD, C)
log_config.sat_configure(C.LOG_BACKEND_STANDARD, C)
from sat.core import log as logging
log = logging.getLogger(__name__)
from sat.tools import config as sat_config
@ -45,8 +45,8 @@ import signal
import sys
## bridge handling
# we get bridge name from conf and initialise the right class accordingly
main_config = sat_config.parseMainConf()
bridge_name = sat_config.getConfig(main_config, '', 'bridge', 'dbus')
main_config = sat_config.parse_main_conf()
bridge_name = sat_config.config_get(main_config, '', 'bridge', 'dbus')
if 'dbus' not in bridge_name:
print(u"only D-Bus bridge is currently supported")
sys.exit(3)
@ -63,8 +63,8 @@ class EditBar(sat_widgets.ModalEdit):
a_key['MODE_COMMAND']: (C.MODE_COMMAND, u':')} #XXX: captions *MUST* be unicode
super(EditBar, self).__init__(modes)
self.host = host
self.setCompletionMethod(self._text_completion)
urwid.connect_signal(self, 'click', self.onTextEntered)
self.set_completion_method(self._text_completion)
urwid.connect_signal(self, 'click', self.on_text_entered)
def _text_completion(self, text, completion_data, mode):
if mode == C.MODE_INSERTION:
@ -78,47 +78,47 @@ class EditBar(sat_widgets.ModalEdit):
else:
return text
def onTextEntered(self, editBar):
def on_text_entered(self, editBar):
"""Called when text is entered in the main edit bar"""
if self.mode == C.MODE_INSERTION:
if isinstance(self.host.selected_widget, quick_chat.QuickChat):
chat_widget = self.host.selected_widget
self.host.messageSend(
self.host.message_send(
chat_widget.target,
{'': editBar.get_edit_text()}, # TODO: handle language
mess_type = C.MESS_TYPE_GROUPCHAT if chat_widget.type == C.CHAT_GROUP else C.MESS_TYPE_CHAT, # TODO: put this in QuickChat
errback=lambda failure: self.host.showDialog(_("Error while sending message ({})").format(failure), type="error"),
errback=lambda failure: self.host.show_dialog(_("Error while sending message ({})").format(failure), type="error"),
profile_key=chat_widget.profile
)
editBar.set_edit_text('')
elif self.mode == C.MODE_COMMAND:
self.commandHandler()
self.command_handler()
def commandHandler(self):
def command_handler(self):
#TODO: separate class with auto documentation (with introspection)
# and completion method
tokens = self.get_edit_text().split(' ')
command, args = tokens[0], tokens[1:]
if command == 'quit':
self.host.onExit()
self.host.on_exit()
raise urwid.ExitMainLoop()
elif command == 'messages':
wid = sat_widgets.GenericList(logging.memoryGet())
self.host.selectWidget(wid)
wid = sat_widgets.GenericList(logging.memory_get())
self.host.select_widget(wid)
# FIXME: reactivate the command
# elif command == 'presence':
# values = [value for value in commonConst.PRESENCE.keys()]
# values = [value if value else 'online' for value in values] # the empty value actually means 'online'
# if args and args[0] in values:
# presence = '' if args[0] == 'online' else args[0]
# self.host.status_bar.onChange(user_data=sat_widgets.ClickableText(commonConst.PRESENCE[presence]))
# self.host.status_bar.on_change(user_data=sat_widgets.ClickableText(commonConst.PRESENCE[presence]))
# else:
# self.host.status_bar.onPresenceClick()
# self.host.status_bar.on_presence_click()
# elif command == 'status':
# if args:
# self.host.status_bar.onChange(user_data=sat_widgets.AdvancedEdit(args[0]))
# self.host.status_bar.on_change(user_data=sat_widgets.AdvancedEdit(args[0]))
# else:
# self.host.status_bar.onStatusClick()
# self.host.status_bar.on_status_click()
elif command == 'history':
widget = self.host.selected_widget
if isinstance(widget, quick_chat.QuickChat):
@ -126,22 +126,22 @@ class EditBar(sat_widgets.ModalEdit):
limit = int(args[0])
except (IndexError, ValueError):
limit = 50
widget.updateHistory(size=limit, profile=widget.profile)
widget.update_history(size=limit, profile=widget.profile)
elif command == 'search':
widget = self.host.selected_widget
if isinstance(widget, quick_chat.QuickChat):
pattern = " ".join(args)
if not pattern:
self.host.notif_bar.addMessage(D_("Please specify the globbing pattern to search for"))
self.host.notif_bar.add_message(D_("Please specify the globbing pattern to search for"))
else:
widget.updateHistory(size=C.HISTORY_LIMIT_NONE, filters={'search': pattern}, profile=widget.profile)
widget.update_history(size=C.HISTORY_LIMIT_NONE, filters={'search': pattern}, profile=widget.profile)
elif command == 'filter':
# FIXME: filter is now only for current widget,
# need to be able to set it globally or per widget
widget = self.host.selected_widget
# FIXME: Q&D way, need to be more generic
if isinstance(widget, quick_chat.QuickChat):
widget.setFilter(args)
widget.set_filter(args)
elif command in ('topic', 'suject', 'title'):
try:
new_title = args[0].strip()
@ -149,12 +149,12 @@ class EditBar(sat_widgets.ModalEdit):
new_title = None
widget = self.host.selected_widget
if isinstance(widget, quick_chat.QuickChat) and widget.type == C.CHAT_GROUP:
widget.onSubjectDialog(new_title)
widget.on_subject_dialog(new_title)
else:
return
self.set_edit_text('')
def _historyCb(self, text):
def _history_cb(self, text):
self.set_edit_text(text)
self.set_edit_pos(len(text))
@ -163,25 +163,25 @@ class EditBar(sat_widgets.ModalEdit):
and move the index of the temporary history stack."""
if key == a_key['MODAL_ESCAPE']:
# first save the text to the current mode, then change to NORMAL
self.host._updateInputHistory(self.get_edit_text(), mode=self.mode)
self.host._updateInputHistory(mode=C.MODE_NORMAL)
self.host._update_input_history(self.get_edit_text(), mode=self.mode)
self.host._update_input_history(mode=C.MODE_NORMAL)
if self._mode == C.MODE_NORMAL and key in self._modes:
self.host._updateInputHistory(mode=self._modes[key][0])
self.host._update_input_history(mode=self._modes[key][0])
if key == a_key['HISTORY_PREV']:
self.host._updateInputHistory(self.get_edit_text(), -1, self._historyCb, self.mode)
self.host._update_input_history(self.get_edit_text(), -1, self._history_cb, self.mode)
return
elif key == a_key['HISTORY_NEXT']:
self.host._updateInputHistory(self.get_edit_text(), +1, self._historyCb, self.mode)
self.host._update_input_history(self.get_edit_text(), +1, self._history_cb, self.mode)
return
elif key == a_key['EDIT_ENTER']:
self.host._updateInputHistory(self.get_edit_text(), mode=self.mode)
self.host._update_input_history(self.get_edit_text(), mode=self.mode)
else:
if (self._mode == C.MODE_INSERTION
and isinstance(self.host.selected_widget, quick_chat.QuickChat)
and key not in sat_widgets.FOCUS_KEYS
and key not in (a_key['HISTORY_PREV'], a_key['HISTORY_NEXT'])
and self.host.sync):
self.host.bridge.chatStateComposing(self.host.selected_widget.target, self.host.selected_widget.profile)
self.host.bridge.chat_state_composing(self.host.selected_widget.target, self.host.selected_widget.profile)
return super(EditBar, self).keypress(size, key)
@ -203,12 +203,12 @@ class PrimitivusTopWidget(sat_widgets.FocusPile):
for position in self.positions:
setattr(self,
position,
property(lambda: self, self.widgetGet(position=position),
lambda pos, new_wid: self.widgetSet(new_wid, position=pos))
property(lambda: self, self.widget_get(position=position),
lambda pos, new_wid: self.widget_set(new_wid, position=pos))
)
self.focus_position = len(self.contents)-1
def getVisiblePositions(self, keep=None):
def get_visible_positions(self, keep=None):
"""Return positions that are not hidden in the right order
@param keep: if not None, this position will be keep in the right order, even if it's hidden
@ -241,27 +241,27 @@ class PrimitivusTopWidget(sat_widgets.FocusPile):
if focus in self._hidden:
return
self.focus_position = self.getVisiblePositions().index(focus)
self.focus_position = self.get_visible_positions().index(focus)
return
return super(PrimitivusTopWidget, self).keypress(size, key)
def widgetGet(self, position):
def widget_get(self, position):
if not position in self.positions:
raise ValueError("Unknown position {}".format(position))
return getattr(self, "_{}".format(position))
def widgetSet(self, widget, position):
def widget_set(self, widget, position):
if not position in self.positions:
raise ValueError("Unknown position {}".format(position))
return setattr(self, "_{}".format(position), widget)
def hideSwitch(self, position):
def hide_switch(self, position):
if not position in self.can_hide:
raise ValueError("Can't switch position {}".format(position))
hide = not position in self._hidden
widget = self.widgetGet(position)
idx = self.getVisiblePositions(position).index(position)
widget = self.widget_get(position)
idx = self.get_visible_positions(position).index(position)
if hide:
del self.contents[idx]
self._hidden.add(position)
@ -271,11 +271,11 @@ class PrimitivusTopWidget(sat_widgets.FocusPile):
def show(self, position):
if position in self._hidden:
self.hideSwitch(position)
self.hide_switch(position)
def hide(self, position):
if not position in self._hidden:
self.hideSwitch(position)
self.hide_switch(position)
class PrimitivusApp(QuickApp, InputHistory):
@ -289,33 +289,33 @@ class PrimitivusApp(QuickApp, InputHistory):
sys.exit(3)
else:
log.debug(u"Loading {} bridge".format(bridge_name))
QuickApp.__init__(self, bridge_factory=bridge_module.Bridge, xmlui=xmlui, check_options=quick_utils.check_options, connect_bridge=False)
QuickApp.__init__(self, bridge_factory=bridge_module.bridge, xmlui=xmlui, check_options=quick_utils.check_options, connect_bridge=False)
## main loop setup ##
event_loop = urwid.GLibEventLoop if 'dbus' in bridge_name else urwid.TwistedEventLoop
self.loop = urwid.MainLoop(urwid.SolidFill(), C.PALETTE, event_loop=event_loop(), input_filter=self.inputFilter, unhandled_input=self.keyHandler)
self.loop = urwid.MainLoop(urwid.SolidFill(), C.PALETTE, event_loop=event_loop(), input_filter=self.input_filter, unhandled_input=self.key_handler)
@classmethod
def run(cls):
cls().start()
def onBridgeConnected(self):
def on_bridge_connected(self):
##misc setup##
self._visible_widgets = set()
self.notif_bar = sat_widgets.NotificationBar()
urwid.connect_signal(self.notif_bar, 'change', self.onNotification)
urwid.connect_signal(self.notif_bar, 'change', self.on_notification)
self.progress_wid = self.widgets.getOrCreateWidget(Progress, None, on_new_widget=None)
urwid.connect_signal(self.notif_bar.progress, 'click', lambda x: self.selectWidget(self.progress_wid))
self.progress_wid = self.widgets.get_or_create_widget(Progress, None, on_new_widget=None)
urwid.connect_signal(self.notif_bar.progress, 'click', lambda x: self.select_widget(self.progress_wid))
self.__saved_overlay = None
self.x_notify = Notify()
# we already manage exit with a_key['APP_QUIT'], so we don't want C-c
signal.signal(signal.SIGINT, signal.SIG_IGN)
sat_conf = sat_config.parseMainConf()
sat_conf = sat_config.parse_main_conf()
self._bracketed_paste = C.bool(
sat_config.getConfig(sat_conf, C.CONFIG_SECTION, 'bracketed_paste', 'false')
sat_config.config_get(sat_conf, C.CONFIG_SECTION, 'bracketed_paste', 'false')
)
if self._bracketed_paste:
log.debug("setting bracketed paste mode as requested")
@ -323,7 +323,7 @@ class PrimitivusApp(QuickApp, InputHistory):
self._bracketed_mode_set = True
self.loop.widget = self.main_widget = ProfileManager(self)
self.postInit()
self.post_init()
@property
def visible_widgets(self):
@ -337,7 +337,7 @@ class PrimitivusApp(QuickApp, InputHistory):
def mode(self, value):
self.editBar.mode = value
def modeHint(self, value):
def mode_hint(self, value):
"""Change mode if make sens (i.e.: if there is nothing in the editBar)"""
if not self.editBar.get_edit_text():
self.mode = value
@ -366,22 +366,22 @@ class PrimitivusApp(QuickApp, InputHistory):
pass
def start(self):
self.connectBridge()
self.connect_bridge()
self.loop.run()
def postInit(self):
def post_init(self):
try:
config.applyConfig(self)
config.apply_config(self)
except Exception as e:
log.error(u"configuration error: {}".format(e))
popup = self.alert(_(u"Configuration Error"), _(u"Something went wrong while reading the configuration, please check :messages"))
if self.options.profile:
self._early_popup = popup
else:
self.showPopUp(popup)
super(PrimitivusApp, self).postInit(self.main_widget)
self.show_pop_up(popup)
super(PrimitivusApp, self).post_init(self.main_widget)
def keysToText(self, keys):
def keys_to_text(self, keys):
"""Generator return normal text from urwid keys"""
for k in keys:
if k == 'tab':
@ -391,7 +391,7 @@ class PrimitivusApp(QuickApp, InputHistory):
elif is_wide_char(k,0) or (len(k)==1 and ord(k) >= 32):
yield k
def inputFilter(self, input_, raw):
def input_filter(self, input_, raw):
if self.__saved_overlay and input_ != a_key['OVERLAY_HIDE']:
return
@ -439,7 +439,7 @@ class PrimitivusApp(QuickApp, InputHistory):
if self.main_widget.focus == edit_bar:
# XXX: if a paste is detected, we append it directly to the edit bar text
# so the user can check it and press [enter] if it's OK
buf_paste = u''.join(self.keysToText(input_))
buf_paste = u''.join(self.keys_to_text(input_))
pos = edit_bar.edit_pos
edit_bar.set_edit_text(u'{}{}{}'.format(edit_bar.edit_text[:pos], buf_paste, edit_bar.edit_text[pos:]))
edit_bar.edit_pos+=len(buf_paste)
@ -463,16 +463,16 @@ class PrimitivusApp(QuickApp, InputHistory):
input_[input_.index(i)] = a_key['HISTORY_NEXT']
return input_
def keyHandler(self, input_):
def key_handler(self, input_):
if input_ == a_key['MENU_HIDE']:
"""User want to (un)hide the menu roller"""
try:
self.main_widget.hideSwitch('menu')
self.main_widget.hide_switch('menu')
except AttributeError:
pass
elif input_ == a_key['NOTIFICATION_NEXT']:
"""User wants to see next notification"""
self.notif_bar.showNext()
self.notif_bar.show_next()
elif input_ == a_key['OVERLAY_HIDE']:
"""User wants to (un)hide overlay window"""
if isinstance(self.loop.widget,urwid.Overlay):
@ -483,7 +483,7 @@ class PrimitivusApp(QuickApp, InputHistory):
self.loop.widget = self.__saved_overlay
self.__saved_overlay = None
elif input_ == a_key['DEBUG'] and 'D' in self.bridge.getVersion(): #Debug only for dev versions
elif input_ == a_key['DEBUG'] and 'D' in self.bridge.version_get(): #Debug only for dev versions
self.debug()
elif input_ == a_key['CONTACTS_HIDE']: #user wants to (un)hide the contact lists
try:
@ -507,74 +507,74 @@ class PrimitivusApp(QuickApp, InputHistory):
self.loop.widget = self.save_main_widget
del self.save_main_widget
try:
return self.menu_roller.checkShortcuts(input_)
return self.menu_roller.check_shortcuts(input_)
except AttributeError:
return input_
def addMenus(self, menu, type_filter, menu_data=None):
def add_menus(self, menu, type_filter, menu_data=None):
"""Add cached menus to instance
@param menu: sat_widgets.Menu instance
@param type_filter: menu type like is sat.core.sat_main.importMenu
@param type_filter: menu type like is sat.core.sat_main.import_menu
@param menu_data: data to send with these menus
"""
def add_menu_cb(callback_id):
self.launchAction(callback_id, menu_data, profile=self.current_profile)
for id_, type_, path, path_i18n, extra in self.bridge.menusGet("", C.NO_SECURITY_LIMIT ): # TODO: manage extra
self.action_launch(callback_id, menu_data, profile=self.current_profile)
for id_, type_, path, path_i18n, extra in self.bridge.menus_get("", C.NO_SECURITY_LIMIT ): # TODO: manage extra
if type_ != type_filter:
continue
if len(path) != 2:
raise NotImplementedError("Menu with a path != 2 are not implemented yet")
menu.addMenu(path_i18n[0], path_i18n[1], lambda dummy,id_=id_: add_menu_cb(id_))
menu.add_menu(path_i18n[0], path_i18n[1], lambda dummy,id_=id_: add_menu_cb(id_))
def _buildMenuRoller(self):
def _build_menu_roller(self):
menu = sat_widgets.Menu(self.loop)
general = _("General")
menu.addMenu(general, _("Connect"), self.onConnectRequest)
menu.addMenu(general, _("Disconnect"), self.onDisconnectRequest)
menu.addMenu(general, _("Parameters"), self.onParam)
menu.addMenu(general, _("About"), self.onAboutRequest)
menu.addMenu(general, _("Exit"), self.onExitRequest, a_key['APP_QUIT'])
menu.addMenu(_("Contacts")) # add empty menu to save the place in the menu order
menu.add_menu(general, _("Connect"), self.on_connect_request)
menu.add_menu(general, _("Disconnect"), self.on_disconnect_request)
menu.add_menu(general, _("Parameters"), self.on_param)
menu.add_menu(general, _("About"), self.on_about_request)
menu.add_menu(general, _("Exit"), self.on_exit_request, a_key['APP_QUIT'])
menu.add_menu(_("Contacts")) # add empty menu to save the place in the menu order
groups = _("Groups")
menu.addMenu(groups)
menu.addMenu(groups, _("Join room"), self.onJoinRoomRequest, a_key['ROOM_JOIN'])
menu.add_menu(groups)
menu.add_menu(groups, _("Join room"), self.on_join_room_request, a_key['ROOM_JOIN'])
#additionals menus
#FIXME: do this in a more generic way (in quickapp)
self.addMenus(menu, C.MENU_GLOBAL)
self.add_menus(menu, C.MENU_GLOBAL)
menu_roller = sat_widgets.MenuRoller([(_('Main menu'), menu, C.MENU_ID_MAIN)])
return menu_roller
def _buildMainWidget(self):
def _build_main_widget(self):
self.contact_lists_pile = urwid.Pile([])
#self.center_part = urwid.Columns([('weight',2,self.contact_lists[profile]),('weight',8,Chat('',self))])
self.center_part = urwid.Columns([('weight', 2, self.contact_lists_pile), ('weight', 8, urwid.Filler(urwid.Text('')))])
self.editBar = EditBar(self)
self.menu_roller = self._buildMenuRoller()
self.menu_roller = self._build_menu_roller()
self.main_widget = PrimitivusTopWidget(self.center_part, self.menu_roller, self.notif_bar, self.editBar)
return self.main_widget
def plugging_profiles(self):
self.loop.widget = self._buildMainWidget()
self.loop.widget = self._build_main_widget()
self.redraw()
try:
# if a popup arrived before main widget is build, we need to show it now
self.showPopUp(self._early_popup)
self.show_pop_up(self._early_popup)
except AttributeError:
pass
else:
del self._early_popup
def profilePlugged(self, profile):
QuickApp.profilePlugged(self, profile)
contact_list = self.widgets.getOrCreateWidget(ContactList, None, on_new_widget=None, on_click=self.contactSelected, on_change=lambda w: self.redraw(), profile=profile)
def profile_plugged(self, profile):
QuickApp.profile_plugged(self, profile)
contact_list = self.widgets.get_or_create_widget(ContactList, None, on_new_widget=None, on_click=self.contact_selected, on_change=lambda w: self.redraw(), profile=profile)
self.contact_lists_pile.contents.append((contact_list, ('weight', 1)))
return contact_list
def isHidden(self):
def is_hidden(self):
"""Tells if the frontend window is hidden.
@return bool
@ -590,11 +590,11 @@ class PrimitivusApp(QuickApp, InputHistory):
@return (urwid_satext.Alert): the created Alert instance
"""
popup = sat_widgets.Alert(title, message)
popup.setCallback('ok', lambda dummy: self.removePopUp(popup))
self.showPopUp(popup, width=75, height=20)
popup.set_callback('ok', lambda dummy: self.remove_pop_up(popup))
self.show_pop_up(popup, width=75, height=20)
return popup
def removePopUp(self, widget=None):
def remove_pop_up(self, widget=None):
"""Remove current pop-up, and if there is other in queue, show it
@param widget(None, urwid.Widget): if not None remove this popup from front or queue
@ -607,19 +607,19 @@ class PrimitivusApp(QuickApp, InputHistory):
current_popup = self.loop.widget.top_w
if not current_popup == widget:
try:
self.notif_bar.removePopUp(widget)
self.notif_bar.remove_pop_up(widget)
except ValueError:
log.warning(u"Trying to remove an unknown widget {}".format(widget))
return
self.loop.widget = self.main_widget
next_popup = self.notif_bar.getNextPopup()
next_popup = self.notif_bar.get_next_popup()
if next_popup:
#we still have popup to show, we display it
self.showPopUp(next_popup)
self.show_pop_up(next_popup)
else:
self.redraw()
def showPopUp(self, pop_up_widget, width=None, height=None, align='center',
def show_pop_up(self, pop_up_widget, width=None, height=None, align='center',
valign='middle'):
"""Show a pop-up window if possible, else put it in queue
@ -640,11 +640,11 @@ class PrimitivusApp(QuickApp, InputHistory):
self.loop.widget = display_widget
self.redraw()
else:
self.notif_bar.addPopUp(pop_up_widget)
self.notif_bar.add_pop_up(pop_up_widget)
def barNotify(self, message):
def bar_notify(self, message):
""""Notify message to user via notification bar"""
self.notif_bar.addMessage(message)
self.notif_bar.add_message(message)
self.redraw()
def notify(self, type_, entity=None, message=None, subject=None, callback=None, cb_args=None, widget=None, profile=C.PROF_KEY_NONE):
@ -653,15 +653,15 @@ class PrimitivusApp(QuickApp, InputHistory):
# still do a desktop notification is the X window has not the focus
super(PrimitivusApp, self).notify(type_, entity, message, subject, callback, cb_args, widget, profile)
# we don't want notifications without message on desktop
if message is not None and not self.x_notify.hasFocus():
if message is not None and not self.x_notify.has_focus():
if message is None:
message = _("{app}: a new event has just happened{entity}").format(
app=C.APP_NAME,
entity=u' ({})'.format(entity) if entity else '')
self.x_notify.sendNotification(message)
self.x_notify.send_notification(message)
def newWidget(self, widget, user_action=False):
def new_widget(self, widget, user_action=False):
"""Method called when a new widget is created
if suitable, the widget will be displayed
@ -672,9 +672,9 @@ class PrimitivusApp(QuickApp, InputHistory):
# FIXME: when several widgets are possible (e.g. with :split)
# do not replace current widget when self.selected_widget != None
if user_action or self.selected_widget is None:
self.selectWidget(widget)
self.select_widget(widget)
def selectWidget(self, widget):
def select_widget(self, widget):
"""Display a widget if possible,
else add it in the notification bar queue
@ -684,27 +684,27 @@ class PrimitivusApp(QuickApp, InputHistory):
wid_idx = len(self.center_part.widget_list)-1
self.center_part.widget_list[wid_idx] = widget
try:
self.menu_roller.removeMenu(C.MENU_ID_WIDGET)
self.menu_roller.remove_menu(C.MENU_ID_WIDGET)
except KeyError:
log.debug("No menu to delete")
self.selected_widget = widget
try:
onSelected = self.selected_widget.onSelected
on_selected = self.selected_widget.on_selected
except AttributeError:
pass
else:
onSelected()
on_selected()
self._visible_widgets = set([widget]) # XXX: we can only have one widget visible at the time for now
self.contact_lists.select(None)
for wid in self.visible_widgets: # FIXME: check if widgets.getWidgets is not more appropriate
for wid in self.visible_widgets: # FIXME: check if widgets.get_widgets is not more appropriate
if isinstance(wid, Chat):
contact_list = self.contact_lists[wid.profile]
contact_list.select(wid.target)
self.redraw()
def removeWindow(self):
def remove_window(self):
"""Remove window showed on the right column"""
#TODO: better Window management than this hack
assert len(self.center_part.widget_list) <= 2
@ -713,7 +713,7 @@ class PrimitivusApp(QuickApp, InputHistory):
self.center_part.focus_position = 0
self.redraw()
def addProgress(self, pid, message, profile):
def add_progress(self, pid, message, profile):
"""Follow a SàT progression
@param pid: progression id
@ -721,118 +721,118 @@ class PrimitivusApp(QuickApp, InputHistory):
"""
self.progress_wid.add(pid, message, profile)
def setProgress(self, percentage):
def set_progress(self, percentage):
"""Set the progression shown in notification bar"""
self.notif_bar.setProgress(percentage)
self.notif_bar.set_progress(percentage)
def contactSelected(self, contact_list, entity):
self.clearNotifs(entity, profile=contact_list.profile)
def contact_selected(self, contact_list, entity):
self.clear_notifs(entity, profile=contact_list.profile)
if entity.resource:
# we have clicked on a private MUC conversation
chat_widget = self.widgets.getOrCreateWidget(Chat, entity, on_new_widget=None, force_hash = Chat.getPrivateHash(contact_list.profile, entity), profile=contact_list.profile)
chat_widget = self.widgets.get_or_create_widget(Chat, entity, on_new_widget=None, force_hash = Chat.get_private_hash(contact_list.profile, entity), profile=contact_list.profile)
else:
chat_widget = self.widgets.getOrCreateWidget(Chat, entity, on_new_widget=None, profile=contact_list.profile)
self.selectWidget(chat_widget)
self.menu_roller.addMenu(_('Chat menu'), chat_widget.getMenu(), C.MENU_ID_WIDGET)
chat_widget = self.widgets.get_or_create_widget(Chat, entity, on_new_widget=None, profile=contact_list.profile)
self.select_widget(chat_widget)
self.menu_roller.add_menu(_('Chat menu'), chat_widget.get_menu(), C.MENU_ID_WIDGET)
def _dialogOkCb(self, widget, data):
def _dialog_ok_cb(self, widget, data):
popup, answer_cb, answer_data = data
self.removePopUp(popup)
self.remove_pop_up(popup)
if answer_cb is not None:
answer_cb(True, answer_data)
def _dialogCancelCb(self, widget, data):
def _dialog_cancel_cb(self, widget, data):
popup, answer_cb, answer_data = data
self.removePopUp(popup)
self.remove_pop_up(popup)
if answer_cb is not None:
answer_cb(False, answer_data)
def showDialog(self, message, title="", type="info", answer_cb = None, answer_data = None):
def show_dialog(self, message, title="", type="info", answer_cb = None, answer_data = None):
if type == 'info':
popup = sat_widgets.Alert(title, message, ok_cb=answer_cb)
if answer_cb is None:
popup.setCallback('ok', lambda dummy: self.removePopUp(popup))
popup.set_callback('ok', lambda dummy: self.remove_pop_up(popup))
elif type == 'error':
popup = sat_widgets.Alert(title, message, ok_cb=answer_cb)
if answer_cb is None:
popup.setCallback('ok', lambda dummy: self.removePopUp(popup))
popup.set_callback('ok', lambda dummy: self.remove_pop_up(popup))
elif type == 'yes/no':
popup = sat_widgets.ConfirmDialog(message)
popup.setCallback('yes', self._dialogOkCb, (popup, answer_cb, answer_data))
popup.setCallback('no', self._dialogCancelCb, (popup, answer_cb, answer_data))
popup.set_callback('yes', self._dialog_ok_cb, (popup, answer_cb, answer_data))
popup.set_callback('no', self._dialog_cancel_cb, (popup, answer_cb, answer_data))
else:
popup = sat_widgets.Alert(title, message, ok_cb=answer_cb)
if answer_cb is None:
popup.setCallback('ok', lambda dummy: self.removePopUp(popup))
popup.set_callback('ok', lambda dummy: self.remove_pop_up(popup))
log.error(u'unmanaged dialog type: {}'.format(type))
self.showPopUp(popup)
self.show_pop_up(popup)
def dialogFailure(self, failure):
def dialog_failure(self, failure):
"""Show a failure that has been returned by an asynchronous bridge method.
@param failure (defer.Failure): Failure instance
"""
self.alert(failure.classname, failure.message)
def onNotification(self, notif_bar):
def on_notification(self, notif_bar):
"""Called when a new notification has been received"""
if not isinstance(self.main_widget, PrimitivusTopWidget):
#if we are not in the main configuration, we ignore the notifications bar
return
if self.notif_bar.canHide():
if self.notif_bar.can_hide():
#No notification left, we can hide the bar
self.main_widget.hide('notif_bar')
else:
self.main_widget.show('notif_bar')
self.redraw() # FIXME: invalidate cache in a more efficient way
def _actionManagerUnknownError(self):
def _action_manager_unknown_error(self):
self.alert(_("Error"), _(u"Unmanaged action"))
def roomJoinedHandler(self, room_jid_s, room_nicks, user_nick, subject, profile):
super(PrimitivusApp, self).roomJoinedHandler(room_jid_s, room_nicks, user_nick, subject, profile)
def room_joined_handler(self, room_jid_s, room_nicks, user_nick, subject, profile):
super(PrimitivusApp, self).room_joined_handler(room_jid_s, room_nicks, user_nick, subject, profile)
# if self.selected_widget is None:
# for contact_list in self.widgets.getWidgets(ContactList):
# for contact_list in self.widgets.get_widgets(ContactList):
# if profile in contact_list.profiles:
# contact_list.setFocus(jid.JID(room_jid_s), True)
# contact_list.set_focus(jid.JID(room_jid_s), True)
def progressStartedHandler(self, pid, metadata, profile):
super(PrimitivusApp, self).progressStartedHandler(pid, metadata, profile)
self.addProgress(pid, metadata.get('name', _(u'unkown')), profile)
def progress_started_handler(self, pid, metadata, profile):
super(PrimitivusApp, self).progress_started_handler(pid, metadata, profile)
self.add_progress(pid, metadata.get('name', _(u'unkown')), profile)
def progressFinishedHandler(self, pid, metadata, profile):
def progress_finished_handler(self, pid, metadata, profile):
log.info(u"Progress {} finished".format(pid))
super(PrimitivusApp, self).progressFinishedHandler(pid, metadata, profile)
super(PrimitivusApp, self).progress_finished_handler(pid, metadata, profile)
def progressErrorHandler(self, pid, err_msg, profile):
def progress_error_handler(self, pid, err_msg, profile):
log.warning(u"Progress {pid} error: {err_msg}".format(pid=pid, err_msg=err_msg))
super(PrimitivusApp, self).progressErrorHandler(pid, err_msg, profile)
super(PrimitivusApp, self).progress_error_handler(pid, err_msg, profile)
##DIALOGS CALLBACKS##
def onJoinRoom(self, button, edit):
self.removePopUp()
def on_join_room(self, button, edit):
self.remove_pop_up()
room_jid = jid.JID(edit.get_edit_text())
self.bridge.mucJoin(room_jid, self.profiles[self.current_profile].whoami.node, {}, self.current_profile, callback=lambda dummy: None, errback=self.dialogFailure)
self.bridge.muc_join(room_jid, self.profiles[self.current_profile].whoami.node, {}, self.current_profile, callback=lambda dummy: None, errback=self.dialog_failure)
#MENU EVENTS#
def onConnectRequest(self, menu):
def on_connect_request(self, menu):
QuickApp.connect(self, self.current_profile)
def onDisconnectRequest(self, menu):
def on_disconnect_request(self, menu):
self.disconnect(self.current_profile)
def onParam(self, menu):
def on_param(self, menu):
def success(params):
ui = xmlui.create(self, xml_data=params, profile=self.current_profile)
ui.show()
def failure(error):
self.alert(_("Error"), _("Can't get parameters (%s)") % error)
self.bridge.getParamsUI(app=C.APP_NAME, profile_key=self.current_profile, callback=success, errback=failure)
self.bridge.param_ui_get(app=C.APP_NAME, profile_key=self.current_profile, callback=success, errback=failure)
def onExitRequest(self, menu):
QuickApp.onExit(self)
def on_exit_request(self, menu):
QuickApp.on_exit(self)
try:
if self._bracketed_mode_set: # we don't unset if bracketed paste mode was detected automatically (i.e. not in conf)
log.debug("unsetting bracketed paste mode")
@ -841,21 +841,21 @@ class PrimitivusApp(QuickApp, InputHistory):
pass
raise urwid.ExitMainLoop()
def onJoinRoomRequest(self, menu):
def on_join_room_request(self, menu):
"""User wants to join a MUC room"""
pop_up_widget = sat_widgets.InputDialog(_("Entering a MUC room"), _("Please enter MUC's JID"), default_txt=self.bridge.mucGetDefaultService(), ok_cb=self.onJoinRoom)
pop_up_widget.setCallback('cancel', lambda dummy: self.removePopUp(pop_up_widget))
self.showPopUp(pop_up_widget)
pop_up_widget = sat_widgets.InputDialog(_("Entering a MUC room"), _("Please enter MUC's JID"), default_txt=self.bridge.muc_get_default_service(), ok_cb=self.on_join_room)
pop_up_widget.set_callback('cancel', lambda dummy: self.remove_pop_up(pop_up_widget))
self.show_pop_up(pop_up_widget)
def onAboutRequest(self, menu):
self.alert(_("About"), C.APP_NAME + " v" + self.bridge.getVersion())
def on_about_request(self, menu):
self.alert(_("About"), C.APP_NAME + " v" + self.bridge.version_get())
#MISC CALLBACKS#
def setPresenceStatus(self, show='', status=None, profile=C.PROF_KEY_NONE):
contact_list_wid = self.widgets.getWidget(ContactList, profiles=profile)
def set_presence_status(self, show='', status=None, profile=C.PROF_KEY_NONE):
contact_list_wid = self.widgets.get_widget(ContactList, profiles=profile)
if contact_list_wid is not None:
contact_list_wid.status_bar.setPresenceStatus(show, status)
contact_list_wid.status_bar.set_presence_status(show, status)
else:
log.warning(u"No ContactList widget found for profile {}".format(profile))

View file

@ -53,9 +53,9 @@ class MessageWidget(urwid.WidgetWrap, quick_chat.MessageWidget):
@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 @@ class MessageWidget(urwid.WidgetWrap, quick_chat.MessageWidget):
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 @@ class OccupantWidget(urwid.WidgetWrap):
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 @@ class OccupantWidget(urwid.WidgetWrap):
@property
def markup(self):
return self._generateMarkup()
return self._generate_markup()
@property
def parent(self):
@ -217,7 +217,7 @@ class OccupantWidget(urwid.WidgetWrap):
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 @@ class OccupantsWidget(urwid.WidgetWrap):
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 @@ class OccupantsWidget(urwid.WidgetWrap):
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 @@ class OccupantsWidget(urwid.WidgetWrap):
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 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
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 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
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 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
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 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
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 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
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 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
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 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
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 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
# return
# self.update(entity)
def createMessage(self, message):
def create_message(self, message):
self.appendMessage(message)
def _scrollDown(self):
@ -461,10 +461,10 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
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 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
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 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
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 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
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 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
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 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
## 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 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
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 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
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 @@ class Chat(PrimitivusWidget, quick_chat.QuickChat):
# 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)

View file

@ -24,7 +24,7 @@ from sat_frontends.primitivus.keys import action_key_map
import configparser
def applyConfig(host):
def apply_config(host):
"""Parse configuration and apply found change
raise: can raise various Exceptions if configuration is not good

View file

@ -46,21 +46,21 @@ class ContactList(PrimitivusWidget, QuickContactList):
# we now build the widget
self.status_bar = StatusBar(host)
self.frame = sat_widgets.FocusFrame(self._buildList(), None, self.status_bar)
self.frame = sat_widgets.FocusFrame(self._build_list(), None, self.status_bar)
PrimitivusWidget.__init__(self, self.frame, _("Contacts"))
if on_click:
urwid.connect_signal(self, "click", on_click, user_data)
if on_change:
urwid.connect_signal(self, "change", on_change, user_data)
self.host.addListener("notification", self.onNotification, [self.profile])
self.host.addListener("notificationsClear", self.onNotification, [self.profile])
self.postInit()
self.host.addListener("notification", self.on_notification, [self.profile])
self.host.addListener("notificationsClear", self.on_notification, [self.profile])
self.post_init()
def update(self, entities=None, type_=None, profile=None):
"""Update display, keep focus"""
# FIXME: full update is done each time, must handle entities, type_ and profile
widget, position = self.frame.body.get_focus()
self.frame.body = self._buildList()
self.frame.body = self._build_list()
if position:
try:
self.frame.body.focus_position = position
@ -85,27 +85,27 @@ class ContactList(PrimitivusWidget, QuickContactList):
elif (
key == a_key["DISCONNECTED_HIDE"]
): # user wants to (un)hide disconnected contacts
self.host.bridge.setParam(
self.host.bridge.param_set(
C.SHOW_OFFLINE_CONTACTS,
C.boolConst(not self.contact_list.show_disconnected),
C.bool_const(not self.contact_list.show_disconnected),
"General",
profile_key=self.profile,
)
elif key == a_key["RESOURCES_HIDE"]: # user wants to (un)hide contacts resources
self.contact_list.showResources(not self.contact_list.show_resources)
self.contact_list.show_resources(not self.contact_list.show_resources)
self.update()
return super(ContactList, self).keypress(size, key)
# QuickWidget methods
@staticmethod
def getWidgetHash(target, profiles):
def get_widget_hash(target, profiles):
profiles = sorted(profiles)
return tuple(profiles)
# modify the contact list
def setFocus(self, text, select=False):
def set_focus(self, text, select=False):
"""give focus to the first element that matches the given text. You can also
pass in text a sat_frontends.tools.jid.JID (it's a subclass of unicode).
@ -117,7 +117,7 @@ class ContactList(PrimitivusWidget, QuickContactList):
try:
if isinstance(widget, sat_widgets.ClickableText):
# contact group
value = widget.getValue()
value = widget.get_value()
elif isinstance(widget, sat_widgets.SelectableText):
# contact or muc
value = widget.data
@ -128,36 +128,36 @@ class ContactList(PrimitivusWidget, QuickContactList):
if text.strip() == value.strip():
self.frame.body.focus_position = idx
if select:
self._contactClicked(False, widget, True)
self._contact_clicked(False, widget, True)
return
except AttributeError:
pass
idx += 1
log.debug("Not element found for {} in setFocus".format(text))
log.debug("Not element found for {} in set_focus".format(text))
# events
def _groupClicked(self, group_wid):
group = group_wid.getValue()
data = self.contact_list.getGroupData(group)
def _group_clicked(self, group_wid):
group = group_wid.get_value()
data = self.contact_list.get_group_data(group)
data[C.GROUP_DATA_FOLDED] = not data.setdefault(C.GROUP_DATA_FOLDED, False)
self.setFocus(group)
self.set_focus(group)
self.update()
def _contactClicked(self, use_bare_jid, contact_wid, selected):
def _contact_clicked(self, use_bare_jid, contact_wid, selected):
"""Method called when a contact is clicked
@param use_bare_jid: True if use_bare_jid is set in self._buildEntityWidget.
@param use_bare_jid: True if use_bare_jid is set in self._build_entity_widget.
@param contact_wid: widget of the contact, must have the entity set in data attribute
@param selected: boolean returned by the widget, telling if it is selected
"""
entity = contact_wid.data
self.host.modeHint(C.MODE_INSERTION)
self.host.mode_hint(C.MODE_INSERTION)
self._emit("click", entity)
def onNotification(self, entity, notif, profile):
notifs = list(self.host.getNotifs(C.ENTITY_ALL, profile=self.profile))
def on_notification(self, entity, notif, profile):
notifs = list(self.host.get_notifs(C.ENTITY_ALL, profile=self.profile))
if notifs:
self.title_dynamic = "({})".format(len(notifs))
else:
@ -166,7 +166,7 @@ class ContactList(PrimitivusWidget, QuickContactList):
# Methods to build the widget
def _buildEntityWidget(
def _build_entity_widget(
self,
entity,
keys=None,
@ -222,10 +222,10 @@ class ContactList(PrimitivusWidget, QuickContactList):
entity_attr = "default"
notifs = list(
self.host.getNotifs(entity, exact_jid=special, profile=self.profile)
self.host.get_notifs(entity, exact_jid=special, profile=self.profile)
)
mentions = list(
self.host.getNotifs(entity.bare, C.NOTIFY_MENTION, profile=self.profile)
self.host.get_notifs(entity.bare, C.NOTIFY_MENTION, profile=self.profile)
)
if notifs or mentions:
attr = 'cl_mention' if mentions else 'cl_notifs'
@ -245,11 +245,11 @@ class ContactList(PrimitivusWidget, QuickContactList):
widget.data = entity
widget.comp = entity_txt.lower() # value to use for sorting
urwid.connect_signal(
widget, "change", self._contactClicked, user_args=[use_bare_jid]
widget, "change", self._contact_clicked, user_args=[use_bare_jid]
)
return widget
def _buildEntities(self, content, entities):
def _build_entities(self, content, entities):
"""Add entity representation in widget list
@param content: widget list, e.g. SimpleListWalker
@ -262,7 +262,7 @@ class ContactList(PrimitivusWidget, QuickContactList):
for entity in entities:
if (
entity in self.contact_list._specials
or not self.contact_list.entityVisible(entity)
or not self.contact_list.entity_visible(entity)
):
continue
markup_extra = []
@ -288,7 +288,7 @@ class ContactList(PrimitivusWidget, QuickContactList):
status = self.contact_list.getCache(entity, "status", default=None)
status_disp = ("status", "\n " + status) if status else ""
markup_extra.append(status_disp)
widget = self._buildEntityWidget(
widget = self._build_entity_widget(
entity,
("cache_nick", "cache_name", "node"),
use_bare_jid=True,
@ -301,22 +301,22 @@ class ContactList(PrimitivusWidget, QuickContactList):
for widget in widgets:
content.append(widget)
def _buildSpecials(self, content):
def _build_specials(self, content):
"""Build the special entities"""
specials = sorted(self.contact_list.getSpecials())
specials = sorted(self.contact_list.get_specials())
current = None
for entity in specials:
if current is not None and current.bare == entity.bare:
# nested entity (e.g. MUC private conversations)
widget = self._buildEntityWidget(
widget = self._build_entity_widget(
entity, ("resource",), markup_prepend=" ", special=True
)
else:
# the special widgets
if entity.resource:
widget = self._buildEntityWidget(entity, ("resource",), special=True)
widget = self._build_entity_widget(entity, ("resource",), special=True)
else:
widget = self._buildEntityWidget(
widget = self._build_entity_widget(
entity,
("cache_nick", "cache_name", "node"),
with_show_attr=False,
@ -324,30 +324,30 @@ class ContactList(PrimitivusWidget, QuickContactList):
)
content.append(widget)
def _buildList(self):
def _build_list(self):
"""Build the main contact list widget"""
content = urwid.SimpleListWalker([])
self._buildSpecials(content)
self._build_specials(content)
if self.contact_list._specials:
content.append(urwid.Divider("="))
groups = list(self.contact_list._groups)
groups.sort(key=lambda x: x.lower() if x else '')
for group in groups:
data = self.contact_list.getGroupData(group)
data = self.contact_list.get_group_data(group)
folded = data.get(C.GROUP_DATA_FOLDED, False)
jids = list(data["jids"])
if group is not None and (
self.contact_list.anyEntityVisible(jids)
self.contact_list.any_entity_visible(jids)
or self.contact_list.show_empty_groups
):
header = "[-]" if not folded else "[+]"
widget = sat_widgets.ClickableText(group, header=header + " ")
content.append(widget)
urwid.connect_signal(widget, "click", self._groupClicked)
urwid.connect_signal(widget, "click", self._group_clicked)
if not folded:
self._buildEntities(content, jids)
self._build_entities(content, jids)
not_in_roster = (
set(self.contact_list._cache)
.difference(self.contact_list._roster)
@ -356,7 +356,7 @@ class ContactList(PrimitivusWidget, QuickContactList):
)
if not_in_roster:
content.append(urwid.Divider("-"))
self._buildEntities(content, not_in_roster)
self._build_entities(content, not_in_roster)
return urwid.ListBox(content)

View file

@ -34,7 +34,7 @@ class CardDisplayer(urwid.Text):
def __init__(self, card):
self.__selected = False
self.card = card
urwid.Text.__init__(self, card.getAttrText())
urwid.Text.__init__(self, card.get_attr_text())
def selectable(self):
return True
@ -55,16 +55,16 @@ class CardDisplayer(urwid.Text):
def select(self, state=True):
self.__selected = state
attr, txt = self.card.getAttrText()
attr, txt = self.card.get_attr_text()
if self.__selected:
attr += "_selected"
self.set_text((attr, txt))
self._invalidate()
def isSelected(self):
def is_selected(self):
return self.__selected
def getCard(self):
def get_card(self):
return self.card
def render(self, size, focus=False):
@ -102,12 +102,12 @@ class Hand(urwid.WidgetWrap):
self._emit("click", None)
return key
def getSelected(self):
def get_selected(self):
"""Return a list of selected cards"""
_selected = []
for wid in self.columns.widget_list:
if isinstance(wid, CardDisplayer) and wid.isSelected():
_selected.append(wid.getCard())
if isinstance(wid, CardDisplayer) and wid.is_selected():
_selected.append(wid.get_card())
return _selected
def update(self, hand):
@ -123,11 +123,11 @@ class Hand(urwid.WidgetWrap):
widget = CardDisplayer(card)
self.columns.widget_list.append(widget)
self.columns.column_types.append(("fixed", 3))
urwid.connect_signal(widget, "click", self.__onClick)
urwid.connect_signal(widget, "click", self.__on_click)
self.columns.contents.append((urwid.Text(""), ("weight", 1, False)))
self.columns.focus_position = 1
def __onClick(self, card_wid):
def __on_click(self, card_wid):
self._emit("click", card_wid)
@ -141,7 +141,7 @@ class Card(TarotCard):
"""@param file: path of the PNG file"""
TarotCard.__init__(self, (suit, value))
def getAttrText(self):
def get_attr_text(self):
"""return text representation of the card with attributes"""
try:
value = "%02i" % int(self.value)
@ -169,7 +169,7 @@ class Card(TarotCard):
color = "special"
return ("card_%s" % color, "%s%s" % (value, suit))
def getWidget(self):
def get_widget(self):
"""Return a widget representing the card"""
return CardDisplayer(self)
@ -180,7 +180,7 @@ class Table(urwid.FlowWidget):
def __init__(self):
self.top = self.left = self.bottom = self.right = None
def putCard(self, location, card):
def put_card(self, location, card):
"""Put a card on the table
@param location: where to put the card (top, left, bottom or right)
@param card: Card to play or None"""
@ -208,7 +208,7 @@ class Table(urwid.FlowWidget):
margin_center = max((max_col - Card.SIZE * 2 - len(separator)) / 2, 0) * " "
for location in ["top", "left", "bottom", "right"]:
card = getattr(self, location)
cards[location] = card.getAttrText() if card else Card.SIZE * " "
cards[location] = card.get_attr_text() if card else Card.SIZE * " "
render_wid = [
urwid.Text([margin, cards["top"]]),
urwid.Text([margin_center, cards["left"], separator, cards["right"]]),
@ -222,7 +222,7 @@ class TarotGame(QuickTarotGame, urwid.WidgetWrap):
def __init__(self, parent, referee, players):
QuickTarotGame.__init__(self, parent, referee, players)
self.loadCards()
self.load_cards()
self.top = urwid.Pile([urwid.Padding(urwid.Text(self.top_nick), "center")])
# self.parent.host.debug()
self.table = Table()
@ -244,18 +244,18 @@ class TarotGame(QuickTarotGame, urwid.WidgetWrap):
]),
urwid.Padding(self.bottom_card_wid,'center')
])"""
self.hand_wid = Hand(selectable=True, on_click=self.onClick)
self.hand_wid = Hand(selectable=True, on_click=self.on_click)
self.main_frame = urwid.Frame(
self.center, header=self.top, footer=self.hand_wid, focus_part="footer"
)
urwid.WidgetWrap.__init__(self, self.main_frame)
self.parent.host.bridge.tarotGameReady(
self.parent.host.bridge.tarot_game_ready(
self.player_nick, referee, self.parent.profile
)
def loadCards(self):
def load_cards(self):
"""Load all the cards in memory"""
QuickTarotGame.loadCards(self)
QuickTarotGame.load_cards(self)
for value in list(map(str, list(range(1, 22)))) + ["excuse"]:
card = Card("atout", value)
self.cards[card.suit, card.value] = card
@ -266,22 +266,22 @@ class TarotGame(QuickTarotGame, urwid.WidgetWrap):
self.cards[card.suit, card.value] = card
self.deck.append(card)
def tarotGameNewHandler(self, hand):
def tarot_game_new_handler(self, hand):
"""Start a new game, with given hand"""
if hand is []: # reset the display after the scores have been showed
self.resetRound()
self.reset_round()
for location in ["top", "left", "bottom", "right"]:
self.table.putCard(location, None)
self.table.put_card(location, None)
self.parent.host.redraw()
self.parent.host.bridge.tarotGameReady(
self.parent.host.bridge.tarot_game_ready(
self.player_nick, self.referee, self.parent.profile
)
return
QuickTarotGame.tarotGameNewHandler(self, hand)
QuickTarotGame.tarot_game_new_handler(self, hand)
self.hand_wid.update(self.hand)
self.parent.host.redraw()
def tarotGameChooseContratHandler(self, xml_data):
def tarot_game_choose_contrat_handler(self, xml_data):
"""Called when the player has to select his contrat
@param xml_data: SàT xml representation of the form"""
form = xmlui.create(
@ -293,16 +293,16 @@ class TarotGame(QuickTarotGame, urwid.WidgetWrap):
)
form.show(valign="top")
def tarotGameShowCardsHandler(self, game_stage, cards, data):
def tarot_game_show_cards_handler(self, game_stage, cards, data):
"""Display cards in the middle of the game (to show for e.g. chien ou poignée)"""
QuickTarotGame.tarotGameShowCardsHandler(self, game_stage, cards, data)
QuickTarotGame.tarot_game_show_cards_handler(self, game_stage, cards, data)
self.center.widget_list[1] = urwid.Filler(Hand(self.to_show))
self.parent.host.redraw()
def tarotGameYourTurnHandler(self):
QuickTarotGame.tarotGameYourTurnHandler(self)
def tarot_game_your_turn_handler(self):
QuickTarotGame.tarot_game_your_turn_handler(self)
def tarotGameScoreHandler(self, xml_data, winners, loosers):
def tarot_game_score_handler(self, xml_data, winners, loosers):
"""Called when the round is over, display the scores
@param xml_data: SàT xml representation of the form"""
if not winners and not loosers:
@ -318,23 +318,23 @@ class TarotGame(QuickTarotGame, urwid.WidgetWrap):
)
form.show()
def tarotGameInvalidCardsHandler(self, phase, played_cards, invalid_cards):
def tarot_game_invalid_cards_handler(self, phase, played_cards, invalid_cards):
"""Invalid cards have been played
@param phase: phase of the game
@param played_cards: all the cards played
@param invalid_cards: cards which are invalid"""
QuickTarotGame.tarotGameInvalidCardsHandler(
QuickTarotGame.tarot_game_invalid_cards_handler(
self, phase, played_cards, invalid_cards
)
self.hand_wid.update(self.hand)
if self._autoplay == None: # No dialog if there is autoplay
self.parent.host.barNotify(_("Cards played are invalid !"))
self.parent.host.bar_notify(_("Cards played are invalid !"))
self.parent.host.redraw()
def tarotGameCardsPlayedHandler(self, player, cards):
def tarot_game_cards_played_handler(self, player, cards):
"""A card has been played by player"""
QuickTarotGame.tarotGameCardsPlayedHandler(self, player, cards)
self.table.putCard(self.getPlayerLocation(player), self.played[player])
QuickTarotGame.tarot_game_cards_played_handler(self, player, cards)
self.table.put_card(self.get_player_location(player), self.played[player])
self._checkState()
self.parent.host.redraw()
@ -356,7 +356,7 @@ class TarotGame(QuickTarotGame, urwid.WidgetWrap):
self.hand_wid.update(self.hand)
##EVENTS##
def onClick(self, hand, card_wid):
def on_click(self, hand, card_wid):
"""Called when user do an action on the hand"""
if not self.state in ["play", "ecart", "wait_for_ecart"]:
# it's not our turn, we ignore the click
@ -364,16 +364,16 @@ class TarotGame(QuickTarotGame, urwid.WidgetWrap):
return
self._checkState()
if self.state == "ecart":
if len(self.hand_wid.getSelected()) == 6:
if len(self.hand_wid.get_selected()) == 6:
pop_up_widget = sat_widgets.ConfirmDialog(
_("Do you put these cards in chien ?"),
yes_cb=self.onEcartDone,
no_cb=self.parent.host.removePopUp,
yes_cb=self.on_ecart_done,
no_cb=self.parent.host.remove_pop_up,
)
self.parent.host.showPopUp(pop_up_widget)
self.parent.host.show_pop_up(pop_up_widget)
elif self.state == "play":
card = card_wid.getCard()
self.parent.host.bridge.tarotGamePlayCards(
card = card_wid.get_card()
self.parent.host.bridge.tarot_game_play_cards(
self.player_nick,
self.referee,
[(card.suit, card.value)],
@ -383,15 +383,15 @@ class TarotGame(QuickTarotGame, urwid.WidgetWrap):
self.hand_wid.update(self.hand)
self.state = "wait"
def onEcartDone(self, button):
def on_ecart_done(self, button):
"""Called when player has finished his écart"""
ecart = []
for card in self.hand_wid.getSelected():
for card in self.hand_wid.get_selected():
ecart.append((card.suit, card.value))
self.hand.remove(card)
self.hand_wid.update(self.hand)
self.parent.host.bridge.tarotGamePlayCards(
self.parent.host.bridge.tarot_game_play_cards(
self.player_nick, self.referee, ecart, self.parent.profile
)
self.state = "wait"
self.parent.host.removePopUp()
self.parent.host.remove_pop_up()

View file

@ -33,7 +33,7 @@ class Notify(object):
from Xlib import display as X_display
self.display = X_display.Display()
self.X11_id = self.getFocus()
self.X11_id = self.get_focus()
except:
pass
@ -51,24 +51,24 @@ class Notify(object):
except:
self.freedesktop_int = None
def getFocus(self):
def get_focus(self):
if not self.display:
return 0
return self.display.get_input_focus().focus.id
def hasFocus(self):
return (self.getFocus() == self.X11_id) if self.display else True
def has_focus(self):
return (self.get_focus() == self.X11_id) if self.display else True
def useX11(self):
def use_x11(self):
return bool(self.display)
def sendNotification(self, summ_mess, body_mess=""):
def send_notification(self, summ_mess, body_mess=""):
"""Send notification to the user if possible"""
# TODO: check options before sending notifications
if self.freedesktop_int:
self.sendFDNotification(summ_mess, body_mess)
self.send_fd_notification(summ_mess, body_mess)
def sendFDNotification(self, summ_mess, body_mess=""):
def send_fd_notification(self, summ_mess, body_mess=""):
"""Send notification with the FreeDesktop D-Bus API"""
if self.freedesktop_int:
app_name = "Primitivus"

View file

@ -32,21 +32,21 @@ class ProfileManager(QuickProfileManager, urwid.WidgetWrap):
def __init__(self, host, autoconnect=None):
QuickProfileManager.__init__(self, host, autoconnect)
# login & password box must be created before list because of onProfileChange
# login & password box must be created before list because of on_profile_change
self.login_wid = sat_widgets.AdvancedEdit(_("Login:"), align="center")
self.pass_wid = sat_widgets.Password(_("Password:"), align="center")
style = ["no_first_select"]
profiles = host.bridge.profilesListGet()
profiles = host.bridge.profiles_list_get()
profiles.sort()
self.list_profile = sat_widgets.List(
profiles, style=style, align="center", on_change=self.onProfileChange
profiles, style=style, align="center", on_change=self.on_profile_change
)
# new & delete buttons
buttons = [
urwid.Button(_("New"), self.onNewProfile),
urwid.Button(_("Delete"), self.onDeleteProfile),
urwid.Button(_("New"), self.on_new_profile),
urwid.Button(_("Delete"), self.on_delete_profile),
]
buttons_flow = urwid.GridFlow(
buttons,
@ -61,7 +61,7 @@ class ProfileManager(QuickProfileManager, urwid.WidgetWrap):
# connect button
connect_button = sat_widgets.CustomButton(
_("Connect"), self.onConnectProfiles, align="center"
_("Connect"), self.on_connect_profiles, align="center"
)
# we now build the widget
@ -87,7 +87,7 @@ class ProfileManager(QuickProfileManager, urwid.WidgetWrap):
def keypress(self, size, key):
if key == a_key["APP_QUIT"]:
self.host.onExit()
self.host.on_exit()
raise urwid.ExitMainLoop()
elif key in (a_key["FOCUS_UP"], a_key["FOCUS_DOWN"]):
focus_diff = 1 if key == a_key["FOCUS_DOWN"] else -1
@ -107,122 +107,122 @@ class ProfileManager(QuickProfileManager, urwid.WidgetWrap):
return
return super(ProfileManager, self).keypress(size, key)
def cancelDialog(self, button):
self.host.removePopUp()
def cancel_dialog(self, button):
self.host.remove_pop_up()
def newProfile(self, button, edit):
def new_profile(self, button, edit):
"""Create the profile"""
name = edit.get_edit_text()
self.host.bridge.profileCreate(
self.host.bridge.profile_create(
name,
callback=lambda: self.newProfileCreated(name),
errback=self.profileCreationFailure,
callback=lambda: self.new_profile_created(name),
errback=self.profile_creation_failure,
)
def newProfileCreated(self, profile):
def new_profile_created(self, profile):
# new profile will be selected, and a selected profile assume the session is started
self.host.bridge.profileStartSession(
self.host.bridge.profile_start_session(
"",
profile,
callback=lambda __: self.newProfileSessionStarted(profile),
errback=self.profileCreationFailure,
callback=lambda __: self.new_profile_session_started(profile),
errback=self.profile_creation_failure,
)
def newProfileSessionStarted(self, profile):
self.host.removePopUp()
self.refillProfiles()
self.list_profile.selectValue(profile)
def new_profile_session_started(self, profile):
self.host.remove_pop_up()
self.refill_profiles()
self.list_profile.select_value(profile)
self.current.profile = profile
self.getConnectionParams(profile)
self.get_connection_params(profile)
self.host.redraw()
def profileCreationFailure(self, reason):
self.host.removePopUp()
message = self._getErrorMessage(reason)
def profile_creation_failure(self, reason):
self.host.remove_pop_up()
message = self._get_error_message(reason)
self.host.alert(_("Can't create profile"), message)
def deleteProfile(self, button):
self._deleteProfile()
self.host.removePopUp()
def delete_profile(self, button):
self._delete_profile()
self.host.remove_pop_up()
def onNewProfile(self, e):
def on_new_profile(self, e):
pop_up_widget = sat_widgets.InputDialog(
_("New profile"),
_("Please enter a new profile name"),
cancel_cb=self.cancelDialog,
ok_cb=self.newProfile,
cancel_cb=self.cancel_dialog,
ok_cb=self.new_profile,
)
self.host.showPopUp(pop_up_widget)
self.host.show_pop_up(pop_up_widget)
def onDeleteProfile(self, e):
def on_delete_profile(self, e):
if self.current.profile:
pop_up_widget = sat_widgets.ConfirmDialog(
_("Are you sure you want to delete the profile {} ?").format(
self.current.profile
),
no_cb=self.cancelDialog,
yes_cb=self.deleteProfile,
no_cb=self.cancel_dialog,
yes_cb=self.delete_profile,
)
self.host.showPopUp(pop_up_widget)
self.host.show_pop_up(pop_up_widget)
def onConnectProfiles(self, button):
def on_connect_profiles(self, button):
"""Connect the profiles and start the main widget
@param button: the connect button
"""
self._onConnectProfiles()
self._on_connect_profiles()
def resetFields(self):
def reset_fields(self):
"""Set profile to None, and reset fields"""
super(ProfileManager, self).resetFields()
self.list_profile.unselectAll(invisible=True)
super(ProfileManager, self).reset_fields()
self.list_profile.unselect_all(invisible=True)
def setProfiles(self, profiles):
def set_profiles(self, profiles):
"""Update the list of profiles"""
self.list_profile.changeValues(profiles)
self.list_profile.change_values(profiles)
self.host.redraw()
def getProfiles(self):
return self.list_profile.getSelectedValues()
def get_profiles(self):
return self.list_profile.get_selected_values()
def getJID(self):
def get_jid(self):
return self.login_wid.get_edit_text()
def getPassword(self):
return self.pass_wid.get_edit_text()
def setJID(self, jid_):
def set_jid(self, jid_):
self.login_wid.set_edit_text(jid_)
self.current.login = jid_
self.host.redraw() # FIXME: redraw should be avoided
def setPassword(self, password):
def set_password(self, password):
self.pass_wid.set_edit_text(password)
self.current.password = password
self.host.redraw()
def onProfileChange(self, list_wid, widget=None, selected=None):
def on_profile_change(self, list_wid, widget=None, selected=None):
"""This is called when a profile is selected in the profile list.
@param list_wid: the List widget who sent the event
"""
self.updateConnectionParams()
self.update_connection_params()
focused = list_wid.focus
selected = focused.getState() if focused is not None else False
selected = focused.get_state() if focused is not None else False
if not selected: # profile was just unselected
return
focused.setState(
focused.set_state(
False, invisible=True
) # we don't want the widget to be selected until we are sure we can access it
def authenticate_cb(data, cb_id, profile):
if C.bool(data.pop("validated", C.BOOL_FALSE)):
self.current.profile = profile
focused.setState(True, invisible=True)
self.getConnectionParams(profile)
focused.set_state(True, invisible=True)
self.get_connection_params(profile)
self.host.redraw()
self.host.actionManager(data, callback=authenticate_cb, profile=profile)
self.host.action_manager(data, callback=authenticate_cb, profile=profile)
self.host.launchAction(
self.host.action_launch(
C.AUTHENTICATE_PROFILE_ID, callback=authenticate_cb, profile=focused.text
)

View file

@ -34,8 +34,8 @@ class Progress(urwid.WidgetWrap, quick_widgets.QuickWidget):
self.progress_dict = {}
listbox = urwid.ListBox(self.progress_list)
buttons = []
buttons.append(sat_widgets.CustomButton(_("Clear progress list"), self._onClear))
max_len = max([button.getSize() for button in buttons])
buttons.append(sat_widgets.CustomButton(_("Clear progress list"), self._on_clear))
max_len = max([button.get_size() for button in buttons])
buttons_wid = urwid.GridFlow(buttons, max_len, 1, 0, "center")
main_wid = sat_widgets.FocusFrame(listbox, footer=buttons_wid)
urwid.WidgetWrap.__init__(self, main_wid)
@ -50,11 +50,11 @@ class Progress(urwid.WidgetWrap, quick_widgets.QuickWidget):
"state": "init",
}
self.progress_list.append(column)
self.progressCB(self.host.loop, (progress_id, message, profile))
self.progress_cb(self.host.loop, (progress_id, message, profile))
def progressCB(self, loop, data):
def progress_cb(self, loop, data):
progress_id, message, profile = data
data = self.host.bridge.progressGet(progress_id, profile)
data = self.host.bridge.progress_get(progress_id, profile)
pbar = self.progress_dict[(progress_id, profile)]["progress"]
if data:
if self.progress_dict[(progress_id, profile)]["state"] == "init":
@ -63,33 +63,33 @@ class Progress(urwid.WidgetWrap, quick_widgets.QuickWidget):
pbar.done = float(data["size"])
pbar.set_completion(float(data["position"]))
self.updateNotBar()
self.update_not_bar()
else:
if self.progress_dict[(progress_id, profile)]["state"] == "progress":
self.progress_dict[(progress_id, profile)]["state"] = "done"
pbar.set_completion(pbar.done)
self.updateNotBar()
self.update_not_bar()
return
loop.set_alarm_in(0.2, self.progressCB, (progress_id, message, profile))
loop.set_alarm_in(0.2, self.progress_cb, (progress_id, message, profile))
def _removeBar(self, progress_id, profile):
def _remove_bar(self, progress_id, profile):
wid = self.progress_dict[(progress_id, profile)]["full"]
self.progress_list.remove(wid)
del (self.progress_dict[(progress_id, profile)])
def _onClear(self, button):
def _on_clear(self, button):
to_remove = []
for progress_id, profile in self.progress_dict:
if self.progress_dict[(progress_id, profile)]["state"] == "done":
to_remove.append((progress_id, profile))
for progress_id, profile in to_remove:
self._removeBar(progress_id, profile)
self.updateNotBar()
self._remove_bar(progress_id, profile)
self.update_not_bar()
def updateNotBar(self):
def update_not_bar(self):
if not self.progress_dict:
self.host.setProgress(None)
self.host.set_progress(None)
return
progress = 0
nb_bars = 0
@ -98,4 +98,4 @@ class Progress(urwid.WidgetWrap, quick_widgets.QuickWidget):
progress += pbar.current / pbar.done * 100
nb_bars += 1
av_progress = progress / float(nb_bars)
self.host.setProgress(av_progress)
self.host.set_progress(av_progress)

View file

@ -31,7 +31,7 @@ class StatusBar(urwid.Columns):
status_prefix = urwid.Text("[")
status_suffix = urwid.Text("]")
self.status = sat_widgets.ClickableText("")
self.setPresenceStatus(C.PRESENCE_UNAVAILABLE, "")
self.set_presence_status(C.PRESENCE_UNAVAILABLE, "")
urwid.Columns.__init__(
self,
[
@ -41,25 +41,25 @@ class StatusBar(urwid.Columns):
("weight", 1, status_suffix),
],
)
urwid.connect_signal(self.presence, "click", self.onPresenceClick)
urwid.connect_signal(self.status, "click", self.onStatusClick)
urwid.connect_signal(self.presence, "click", self.on_presence_click)
urwid.connect_signal(self.status, "click", self.on_status_click)
def onPresenceClick(self, sender=None):
if not self.host.bridge.isConnected(
def on_presence_click(self, sender=None):
if not self.host.bridge.is_connected(
self.host.current_profile
): # FIXME: manage multi-profiles
return
options = [commonConst.PRESENCE[presence] for presence in commonConst.PRESENCE]
list_widget = sat_widgets.GenericList(
options=options, option_type=sat_widgets.ClickableText, on_click=self.onChange
options=options, option_type=sat_widgets.ClickableText, on_click=self.on_change
)
decorated = sat_widgets.LabelLine(
list_widget, sat_widgets.SurroundedText(_("Set your presence"))
)
self.host.showPopUp(decorated)
self.host.show_pop_up(decorated)
def onStatusClick(self, sender=None):
if not self.host.bridge.isConnected(
def on_status_click(self, sender=None):
if not self.host.bridge.is_connected(
self.host.current_profile
): # FIXME: manage multi-profiles
return
@ -67,12 +67,12 @@ class StatusBar(urwid.Columns):
_("Set your status"),
_("New status"),
default_txt=self.status.get_text(),
cancel_cb=lambda _: self.host.removePopUp(),
ok_cb=self.onChange,
cancel_cb=lambda _: self.host.remove_pop_up(),
ok_cb=self.on_change,
)
self.host.showPopUp(pop_up_widget)
self.host.show_pop_up(pop_up_widget)
def onChange(self, sender=None, user_data=None):
def on_change(self, sender=None, user_data=None):
new_value = user_data.get_text()
previous = (
[key for key in C.PRESENCE if C.PRESENCE[key][0] == self.presence.get_text()][
@ -100,13 +100,13 @@ class StatusBar(urwid.Columns):
) in (
self.host.profiles
): # FIXME: for now all the profiles share the same status
self.host.bridge.setPresence(
self.host.bridge.presence_set(
show=new[0], statuses=statuses, profile_key=profile
)
self.setPresenceStatus(new[0], new[1])
self.host.removePopUp()
self.set_presence_status(new[0], new[1])
self.host.remove_pop_up()
def setPresenceStatus(self, show, status):
def set_presence_status(self, show, status):
show_icon, show_attr = C.PRESENCE.get(show)
self.presence.set_text(("show_normal", show_icon))
if status is not None:

View file

@ -32,7 +32,7 @@ class PrimitivusWidget(urwid.WidgetWrap):
self._title = title
self._title_dynamic = None
self._original_widget = w
urwid.WidgetWrap.__init__(self, self._getDecoration(w))
urwid.WidgetWrap.__init__(self, self._get_decoration(w))
@property
def title(self):
@ -65,8 +65,8 @@ class PrimitivusWidget(urwid.WidgetWrap):
@title.setter
def title(self, value):
self._title = value
if self.decorationVisible:
self.showDecoration()
if self.decoration_visible:
self.show_decoration()
@property
def title_dynamic(self):
@ -76,29 +76,29 @@ class PrimitivusWidget(urwid.WidgetWrap):
@title_dynamic.setter
def title_dynamic(self, value):
self._title_dynamic = value
if self.decorationVisible:
self.showDecoration()
if self.decoration_visible:
self.show_decoration()
@property
def decorationVisible(self):
def decoration_visible(self):
"""True if the decoration is visible"""
return isinstance(self._w, sat_widgets.LabelLine)
def keypress(self, size, key):
if key == a_key["DECORATION_HIDE"]: # user wants to (un)hide widget decoration
show = not self.decorationVisible
self.showDecoration(show)
show = not self.decoration_visible
self.show_decoration(show)
else:
return super(PrimitivusWidget, self).keypress(size, key)
def _getDecoration(self, widget):
def _get_decoration(self, widget):
return sat_widgets.LabelLine(widget, self.title)
def showDecoration(self, show=True):
def show_decoration(self, show=True):
"""Show/Hide the decoration around the window"""
self._w = (
self._getDecoration(self._original_widget) if show else self._original_widget
self._get_decoration(self._original_widget) if show else self._original_widget
)
def getMenu(self):
def get_menu(self):
raise NotImplementedError

View file

@ -38,7 +38,7 @@ class PrimitivusEvents(object):
"""" Call xmlui callback and ignore any extra argument """
args[-1](ctrl)
def _xmluiOnChange(self, callback):
def _xmlui_on_change(self, callback):
""" Call callback with widget as only argument """
urwid.connect_signal(self, "change", self._event_callback, callback)
@ -93,10 +93,10 @@ class PrimitivusStringWidget(
return False
return super(PrimitivusStringWidget, self).selectable()
def _xmluiSetValue(self, value):
def _xmlui_set_value(self, value):
self.set_edit_text(value)
def _xmluiGetValue(self):
def _xmlui_get_value(self):
return self.get_edit_text()
@ -116,10 +116,10 @@ class PrimitivusPasswordWidget(
return False
return super(PrimitivusPasswordWidget, self).selectable()
def _xmluiSetValue(self, value):
def _xmlui_set_value(self, value):
self.set_edit_text(value)
def _xmluiGetValue(self):
def _xmlui_get_value(self):
return self.get_edit_text()
@ -135,10 +135,10 @@ class PrimitivusTextBoxWidget(
return False
return super(PrimitivusTextBoxWidget, self).selectable()
def _xmluiSetValue(self, value):
def _xmlui_set_value(self, value):
self.set_edit_text(value)
def _xmluiGetValue(self):
def _xmlui_get_value(self):
return self.get_edit_text()
@ -152,10 +152,10 @@ class PrimitivusBoolWidget(xmlui.BoolWidget, urwid.CheckBox, PrimitivusEvents):
return False
return super(PrimitivusBoolWidget, self).selectable()
def _xmluiSetValue(self, value):
def _xmlui_set_value(self, value):
self.set_state(value == "true")
def _xmluiGetValue(self):
def _xmlui_get_value(self):
return C.BOOL_TRUE if self.get_state() else C.BOOL_FALSE
@ -169,10 +169,10 @@ class PrimitivusIntWidget(xmlui.IntWidget, sat_widgets.AdvancedEdit, PrimitivusE
return False
return super(PrimitivusIntWidget, self).selectable()
def _xmluiSetValue(self, value):
def _xmlui_set_value(self, value):
self.set_edit_text(value)
def _xmluiGetValue(self):
def _xmlui_get_value(self):
return self.get_edit_text()
@ -182,38 +182,38 @@ class PrimitivusButtonWidget(
def __init__(self, _xmlui_parent, value, click_callback):
sat_widgets.CustomButton.__init__(self, value, on_press=click_callback)
def _xmluiOnClick(self, callback):
def _xmlui_on_click(self, callback):
urwid.connect_signal(self, "click", callback)
class PrimitivusListWidget(xmlui.ListWidget, sat_widgets.List, PrimitivusEvents):
def __init__(self, _xmlui_parent, options, selected, flags):
sat_widgets.List.__init__(self, options=options, style=flags)
self._xmluiSelectValues(selected)
self._xmlui_select_values(selected)
def _xmluiSelectValue(self, value):
return self.selectValue(value)
def _xmlui_select_value(self, value):
return self.select_value(value)
def _xmluiSelectValues(self, values):
return self.selectValues(values)
def _xmlui_select_values(self, values):
return self.select_values(values)
def _xmluiGetSelectedValues(self):
return [option.value for option in self.getSelectedValues()]
def _xmlui_get_selected_values(self):
return [option.value for option in self.get_selected_values()]
def _xmluiAddValues(self, values, select=True):
current_values = self.getAllValues()
def _xmlui_add_values(self, values, select=True):
current_values = self.get_all_values()
new_values = copy.deepcopy(current_values)
for value in values:
if value not in current_values:
new_values.append(value)
if select:
selected = self._xmluiGetSelectedValues()
self.changeValues(new_values)
selected = self._xmlui_get_selected_values()
self.change_values(new_values)
if select:
for value in values:
if value not in selected:
selected.append(value)
self._xmluiSelectValues(selected)
self._xmlui_select_values(selected)
class PrimitivusJidsListWidget(xmlui.ListWidget, sat_widgets.List, PrimitivusEvents):
@ -224,11 +224,11 @@ class PrimitivusJidsListWidget(xmlui.ListWidget, sat_widgets.List, PrimitivusEve
option_type=lambda txt, align: sat_widgets.AdvancedEdit(
edit_text=txt, align=align
),
on_change=self._onChange,
on_change=self._on_change,
)
self.delete = 0
def _onChange(self, list_widget, jid_widget=None, text=None):
def _on_change(self, list_widget, jid_widget=None, text=None):
if jid_widget is not None:
if jid_widget != list_widget.contents[-1] and not text:
# if a field is empty, we delete the line (except for the last line)
@ -237,9 +237,9 @@ class PrimitivusJidsListWidget(xmlui.ListWidget, sat_widgets.List, PrimitivusEve
# we always want an empty field as last value to be able to add jids
list_widget.contents.append(sat_widgets.AdvancedEdit())
def _xmluiGetSelectedValues(self):
def _xmlui_get_selected_values(self):
# XXX: there is not selection in this list, so we return all non empty values
return [jid_ for jid_ in self.getAllValues() if jid_]
return [jid_ for jid_ in self.get_all_values() if jid_]
class PrimitivusAdvancedListContainer(
@ -253,19 +253,19 @@ class PrimitivusAdvancedListContainer(
self, columns=columns, options=options, row_selectable=selectable != "no"
)
def _xmluiAppend(self, widget):
self.addWidget(widget)
def _xmlui_append(self, widget):
self.add_widget(widget)
def _xmluiAddRow(self, idx):
self.setRowIndex(idx)
def _xmlui_add_row(self, idx):
self.set_row_index(idx)
def _xmluiGetSelectedWidgets(self):
return self.getSelectedWidgets()
def _xmlui_get_selected_widgets(self):
return self.get_selected_widgets()
def _xmluiGetSelectedIndex(self):
return self.getSelectedIndex()
def _xmlui_get_selected_index(self):
return self.get_selected_index()
def _xmluiOnSelect(self, callback):
def _xmlui_on_select(self, callback):
""" Call callback with widget as only argument """
urwid.connect_signal(self, "click", self._event_callback, callback)
@ -277,11 +277,11 @@ class PrimitivusPairsContainer(xmlui.PairsContainer, sat_widgets.TableContainer)
options["FOCUS_ATTR"] = "param_selected"
sat_widgets.TableContainer.__init__(self, columns=2, options=options)
def _xmluiAppend(self, widget):
def _xmlui_append(self, widget):
if isinstance(widget, PrimitivusEmptyWidget):
# we don't want highlight on empty widgets
widget = urwid.AttrMap(widget, "default")
self.addWidget(widget)
self.add_widget(widget)
class PrimitivusLabelContainer(PrimitivusPairsContainer, xmlui.LabelContainer):
@ -292,12 +292,12 @@ class PrimitivusTabsContainer(xmlui.TabsContainer, sat_widgets.TabsContainer):
def __init__(self, _xmlui_parent):
sat_widgets.TabsContainer.__init__(self)
def _xmluiAppend(self, widget):
def _xmlui_append(self, widget):
self.body.append(widget)
def _xmluiAddTab(self, label, selected):
def _xmlui_add_tab(self, label, selected):
tab = PrimitivusVerticalContainer(None)
self.addTab(label, tab, selected)
self.add_tab(label, tab, selected)
return tab
@ -308,7 +308,7 @@ class PrimitivusVerticalContainer(xmlui.VerticalContainer, urwid.ListBox):
urwid.ListBox.__init__(self, urwid.SimpleListWalker([]))
self._last_size = None
def _xmluiAppend(self, widget):
def _xmlui_append(self, widget):
if "flow" not in widget.sizing():
widget = urwid.BoxAdapter(widget, self.BOX_HEIGHT)
self.body.append(widget)
@ -331,11 +331,11 @@ class PrimitivusDialog(object):
def __init__(self, _xmlui_parent):
self.host = _xmlui_parent.host
def _xmluiShow(self):
self.host.showPopUp(self)
def _xmlui_show(self):
self.host.show_pop_up(self)
def _xmluiClose(self):
self.host.removePopUp(self)
def _xmlui_close(self):
self.host.remove_pop_up(self)
class PrimitivusMessageDialog(PrimitivusDialog, xmlui.MessageDialog, sat_widgets.Alert):
@ -343,7 +343,7 @@ class PrimitivusMessageDialog(PrimitivusDialog, xmlui.MessageDialog, sat_widgets
PrimitivusDialog.__init__(self, _xmlui_parent)
xmlui.MessageDialog.__init__(self, _xmlui_parent)
sat_widgets.Alert.__init__(
self, title, message, ok_cb=lambda __: self._xmluiClose()
self, title, message, ok_cb=lambda __: self._xmlui_close()
)
@ -362,8 +362,8 @@ class PrimitivusConfirmDialog(
self,
title,
message,
no_cb=lambda __: self._xmluiCancelled(),
yes_cb=lambda __: self._xmluiValidated(),
no_cb=lambda __: self._xmlui_cancelled(),
yes_cb=lambda __: self._xmlui_validated(),
)
@ -379,8 +379,8 @@ class PrimitivusFileDialog(
style.append("dir")
files_management.FileDialog.__init__(
self,
ok_cb=lambda path: self._xmluiValidated({"path": path}),
cancel_cb=lambda __: self._xmluiCancelled(),
ok_cb=lambda path: self._xmlui_validated({"path": path}),
cancel_cb=lambda __: self._xmlui_cancelled(),
message=message,
title=title,
style=style,
@ -433,7 +433,7 @@ class XMLUIPanel(xmlui.XMLUIPanel, PrimitivusWidget):
PrimitivusWidget.__init__(self, self.main_cont, self.xmlui_title)
def _parseChilds(self, _xmlui_parent, current_node, wanted=("container",), data=None):
def _parse_childs(self, _xmlui_parent, current_node, wanted=("container",), data=None):
# Small hack to always have a VerticalContainer as main container in Primitivus.
# this used to be the default behaviour for all frontends, but now
# TabsContainer can also be the main container.
@ -442,23 +442,23 @@ class XMLUIPanel(xmlui.XMLUIPanel, PrimitivusWidget):
if node.nodeName == "container" and node.getAttribute("type") == "tabs":
_xmlui_parent = self.widget_factory.createVerticalContainer(self)
self.main_cont = _xmlui_parent
return super(XMLUIPanel, self)._parseChilds(_xmlui_parent, current_node, wanted,
return super(XMLUIPanel, self)._parse_childs(_xmlui_parent, current_node, wanted,
data)
def constructUI(self, parsed_dom):
def postTreat():
def construct_ui(self, parsed_dom):
def post_treat():
assert self.main_cont.body
if self.type in ("form", "popup"):
buttons = []
if self.type == "form":
buttons.append(urwid.Button(_("Submit"), self.onFormSubmitted))
buttons.append(urwid.Button(_("Submit"), self.on_form_submitted))
if not "NO_CANCEL" in self.flags:
buttons.append(urwid.Button(_("Cancel"), self.onFormCancelled))
buttons.append(urwid.Button(_("Cancel"), self.on_form_cancelled))
else:
buttons.append(
urwid.Button(_("OK"), on_press=lambda __: self._xmluiClose())
urwid.Button(_("OK"), on_press=lambda __: self._xmlui_close())
)
max_len = max([len(button.get_label()) for button in buttons])
grid_wid = urwid.GridFlow(buttons, max_len + 4, 1, 0, "center")
@ -467,17 +467,17 @@ class XMLUIPanel(xmlui.XMLUIPanel, PrimitivusWidget):
tabs_cont = self.main_cont.body[0].base_widget
assert isinstance(tabs_cont, sat_widgets.TabsContainer)
buttons = []
buttons.append(sat_widgets.CustomButton(_("Save"), self.onSaveParams))
buttons.append(sat_widgets.CustomButton(_("Save"), self.on_save_params))
buttons.append(
sat_widgets.CustomButton(
_("Cancel"), lambda x: self.host.removeWindow()
_("Cancel"), lambda x: self.host.remove_window()
)
)
max_len = max([button.getSize() for button in buttons])
max_len = max([button.get_size() for button in buttons])
grid_wid = urwid.GridFlow(buttons, max_len, 1, 0, "center")
tabs_cont.addFooter(grid_wid)
tabs_cont.add_footer(grid_wid)
xmlui.XMLUIPanel.constructUI(self, parsed_dom, postTreat)
xmlui.XMLUIPanel.construct_ui(self, parsed_dom, post_treat)
urwid.WidgetWrap.__init__(self, self.main_cont)
def show(self, show_type=None, valign="middle"):
@ -501,18 +501,18 @@ class XMLUIPanel(xmlui.XMLUIPanel, PrimitivusWidget):
self._dest = show_type
if show_type == "popup":
self.host.showPopUp(self, valign=valign)
self.host.show_pop_up(self, valign=valign)
elif show_type == "window":
self.host.newWidget(self, user_action=self.user_action)
self.host.new_widget(self, user_action=self.user_action)
else:
assert False
self.host.redraw()
def _xmluiClose(self):
def _xmlui_close(self):
if self._dest == "window":
self.host.removeWindow()
self.host.remove_window()
elif self._dest == "popup":
self.host.removePopUp(self)
self.host.remove_pop_up(self)
else:
raise exceptions.InternalError(
"self._dest unknown, are you sure you have called XMLUI.show ?"
@ -523,6 +523,6 @@ class XMLUIDialog(xmlui.XMLUIDialog):
dialog_factory = GenericFactory()
xmlui.registerClass(xmlui.CLASS_PANEL, XMLUIPanel)
xmlui.registerClass(xmlui.CLASS_DIALOG, XMLUIDialog)
xmlui.register_class(xmlui.CLASS_PANEL, XMLUIPanel)
xmlui.register_class(xmlui.CLASS_DIALOG, XMLUIDialog)
create = xmlui.create