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
12 changed files with 9945 additions and 9945 deletions

View file

@ -103,13 +103,13 @@ class Const(constants.Const):
"notificationsClear",
"widgetNew",
"widgetDeleted",
"profilePlugged",
"profile_plugged",
"contactsFilled",
"disconnect",
"gotMenus",
"menu",
"progressFinished",
"progressError",
"progress_finished",
"progress_error",
}
# Notifications

View file

@ -63,23 +63,23 @@ class ProfileManager(object):
def plug(self):
"""Plug the profile to the host"""
# first of all we create the contact lists
self.host.contact_lists.addProfile(self.profile)
self.host.contact_lists.add_profile(self.profile)
# we get the essential params
self.bridge.asyncGetParamA(
self.bridge.param_get_a_async(
"JabberID",
"Connection",
profile_key=self.profile,
callback=self._plug_profile_jid,
errback=self._getParamError,
errback=self._get_param_error,
)
def _plug_profile_jid(self, jid_s):
self.whoami = jid.JID(jid_s) # resource might change after the connection
log.info(f"Our current jid is: {self.whoami}")
self.bridge.isConnected(self.profile, callback=self._plug_profile_isconnected)
self.bridge.is_connected(self.profile, callback=self._plug_profile_isconnected)
def _autodisconnectEb(self, failure_):
def _autodisconnect_eb(self, failure_):
# XXX: we ignore error on this parameter, as Libervia can't access it
log.warning(
_("Error while trying to get autodisconnect param, ignoring: {}").format(
@ -91,24 +91,24 @@ class ProfileManager(object):
def _plug_profile_isconnected(self, connected):
self.connected = connected
if connected:
self.host.profileConnected(self.profile)
self.bridge.asyncGetParamA(
self.host.profile_connected(self.profile)
self.bridge.param_get_a_async(
"autodisconnect",
"Connection",
profile_key=self.profile,
callback=self._plug_profile_autodisconnect,
errback=self._autodisconnectEb,
errback=self._autodisconnect_eb,
)
def _plug_profile_autodisconnect(self, autodisconnect):
if C.bool(autodisconnect):
self._autodisconnect = True
self.bridge.asyncGetParamA(
self.bridge.param_get_a_async(
"autoconnect",
"Connection",
profile_key=self.profile,
callback=self._plug_profile_autoconnect,
errback=self._getParamError,
errback=self._get_param_error,
)
def _plug_profile_autoconnect(self, value_str):
@ -124,79 +124,79 @@ class ProfileManager(object):
# Profile can be connected or not
# we get cached data
self.connected = True
self.host.bridge.getFeatures(
self.host.bridge.features_get(
profile_key=self.profile,
callback=self._plug_profile_getFeaturesCb,
errback=self._plug_profile_getFeaturesEb,
callback=self._plug_profile_get_features_cb,
errback=self._plug_profile_get_features_eb,
)
def _plug_profile_getFeaturesEb(self, failure):
def _plug_profile_get_features_eb(self, failure):
log.error("Couldn't get features: {}".format(failure))
self._plug_profile_getFeaturesCb({})
self._plug_profile_get_features_cb({})
def _plug_profile_getFeaturesCb(self, features):
def _plug_profile_get_features_cb(self, features):
self.host.features = features
self.host.bridge.getEntitiesData([], ProfileManager.cache_keys_to_get,
self.host.bridge.entities_data_get([], ProfileManager.cache_keys_to_get,
profile=self.profile,
callback=self._plug_profile_gotCachedValues,
errback=self._plug_profile_failedCachedValues)
callback=self._plug_profile_got_cached_values,
errback=self._plug_profile_failed_cached_values)
def _plug_profile_failedCachedValues(self, failure):
def _plug_profile_failed_cached_values(self, failure):
log.error("Couldn't get cached values: {}".format(failure))
self._plug_profile_gotCachedValues({})
self._plug_profile_got_cached_values({})
def _plug_profile_gotCachedValues(self, cached_values):
def _plug_profile_got_cached_values(self, cached_values):
contact_list = self.host.contact_lists[self.profile]
# add the contact list and its listener
for entity_s, data in cached_values.items():
for key, value in data.items():
self.host.entityDataUpdatedHandler(entity_s, key, value, self.profile)
self.host.entity_data_updated_handler(entity_s, key, value, self.profile)
if not self.connected:
self.host.setPresenceStatus(C.PRESENCE_UNAVAILABLE, "", profile=self.profile)
self.host.set_presence_status(C.PRESENCE_UNAVAILABLE, "", profile=self.profile)
else:
contact_list.fill()
self.host.setPresenceStatus(profile=self.profile)
self.host.set_presence_status(profile=self.profile)
# The waiting subscription requests
self.bridge.getWaitingSub(
self.profile, callback=self._plug_profile_gotWaitingSub
self.bridge.sub_waiting_get(
self.profile, callback=self._plug_profile_got_waiting_sub
)
def _plug_profile_gotWaitingSub(self, waiting_sub):
def _plug_profile_got_waiting_sub(self, waiting_sub):
for sub in waiting_sub:
self.host.subscribeHandler(waiting_sub[sub], sub, self.profile)
self.host.subscribe_handler(waiting_sub[sub], sub, self.profile)
self.bridge.mucGetRoomsJoined(
self.profile, callback=self._plug_profile_gotRoomsJoined
self.bridge.muc_get_rooms_joined(
self.profile, callback=self._plug_profile_got_rooms_joined
)
def _plug_profile_gotRoomsJoined(self, rooms_args):
def _plug_profile_got_rooms_joined(self, rooms_args):
# Now we open the MUC window where we already are:
for room_args in rooms_args:
self.host.mucRoomJoinedHandler(*room_args, profile=self.profile)
self.host.muc_room_joined_handler(*room_args, profile=self.profile)
# Presence must be requested after rooms are filled
self.host.bridge.getPresenceStatuses(
self.profile, callback=self._plug_profile_gotPresences
self.host.bridge.presence_statuses_get(
self.profile, callback=self._plug_profile_got_presences
)
def _plug_profile_gotPresences(self, presences):
def _plug_profile_got_presences(self, presences):
for contact in presences:
for res in presences[contact]:
jabber_id = ("%s/%s" % (jid.JID(contact).bare, res)) if res else contact
show = presences[contact][res][0]
priority = presences[contact][res][1]
statuses = presences[contact][res][2]
self.host.presenceUpdateHandler(
self.host.presence_update_handler(
jabber_id, show, priority, statuses, self.profile
)
# At this point, profile should be fully plugged
# and we launch frontend specific method
self.host.profilePlugged(self.profile)
self.host.profile_plugged(self.profile)
def _getParamError(self, failure):
def _get_param_error(self, failure):
log.error(_("Can't get profile parameter: {msg}").format(msg=failure))
@ -242,7 +242,7 @@ class ProfilesManager(object):
del self._profiles[profile]
def chooseOneProfile(self):
def choose_one_profile(self):
return list(self._profiles.keys())[0]
@ -260,7 +260,7 @@ class QuickApp(object):
def __init__(self, bridge_factory, xmlui, check_options=None, connect_bridge=True):
"""Create a frontend application
@param bridge_factory: method to use to create the Bridge
@param bridge_factory: method to use to create the bridge
@param xmlui: xmlui module
@param check_options: method to call to check options (usually command line
arguments)
@ -297,7 +297,7 @@ class QuickApp(object):
self.bridge = bridge_factory()
ProfileManager.bridge = self.bridge
if connect_bridge:
self.connectBridge()
self.connect_bridge()
# frontend notifications
self._notif_id = 0
@ -314,58 +314,58 @@ class QuickApp(object):
# state of synchronisation with backend
self._sync = True
def connectBridge(self):
self.bridge.bridgeConnect(callback=self._bridgeCb, errback=self._bridgeEb)
def connect_bridge(self):
self.bridge.bridge_connect(callback=self._bridge_cb, errback=self._bridge_eb)
def _namespacesGetCb(self, ns_map):
def _namespaces_get_cb(self, ns_map):
self.ns_map = ns_map
def _namespacesGetEb(self, failure_):
def _namespaces_get_eb(self, failure_):
log.error(_("Can't get namespaces map: {msg}").format(msg=failure_))
def _encryptionPluginsGetCb(self, plugins_ser):
def _encryption_plugins_get_cb(self, plugins_ser):
self.encryption_plugins = data_format.deserialise(plugins_ser, type_check=list)
def _encryptionPluginsGetEb(self, failure_):
def _encryption_plugins_get_eb(self, failure_):
log.warning(_("Can't retrieve encryption plugins: {msg}").format(msg=failure_))
def onBridgeConnected(self):
self.bridge.getReady(self.onBackendReady)
def on_bridge_connected(self):
self.bridge.ready_get(self.on_backend_ready)
def _bridgeCb(self):
self.registerSignal("connected")
self.registerSignal("disconnected")
self.registerSignal("actionNew")
self.registerSignal("newContact")
self.registerSignal("messageNew")
def _bridge_cb(self):
self.register_signal("connected")
self.register_signal("disconnected")
self.register_signal("action_new")
self.register_signal("contact_new")
self.register_signal("message_new")
if self.ENCRYPTION_HANDLERS:
self.registerSignal("messageEncryptionStarted")
self.registerSignal("messageEncryptionStopped")
self.registerSignal("presenceUpdate")
self.registerSignal("subscribe")
self.registerSignal("paramUpdate")
self.registerSignal("contactDeleted")
self.registerSignal("entityDataUpdated")
self.registerSignal("progressStarted")
self.registerSignal("progressFinished")
self.registerSignal("progressError")
self.registerSignal("mucRoomJoined", iface="plugin")
self.registerSignal("mucRoomLeft", iface="plugin")
self.registerSignal("mucRoomUserChangedNick", iface="plugin")
self.registerSignal("mucRoomNewSubject", iface="plugin")
self.registerSignal("chatStateReceived", iface="plugin")
self.registerSignal("messageState", iface="plugin")
self.registerSignal("psEvent", iface="plugin")
self.register_signal("message_encryption_started")
self.register_signal("message_encryption_stopped")
self.register_signal("presence_update")
self.register_signal("subscribe")
self.register_signal("param_update")
self.register_signal("contact_deleted")
self.register_signal("entity_data_updated")
self.register_signal("progress_started")
self.register_signal("progress_finished")
self.register_signal("progress_error")
self.register_signal("muc_room_joined", iface="plugin")
self.register_signal("muc_room_left", iface="plugin")
self.register_signal("muc_room_user_changed_nick", iface="plugin")
self.register_signal("muc_room_new_subject", iface="plugin")
self.register_signal("chat_state_received", iface="plugin")
self.register_signal("message_state", iface="plugin")
self.register_signal("ps_event", iface="plugin")
# useful for debugging
self.registerSignal("_debug", iface="core")
self.register_signal("_debug", iface="core")
# FIXME: do it dynamically
quick_games.Tarot.registerSignals(self)
quick_games.Quiz.registerSignals(self)
quick_games.Radiocol.registerSignals(self)
self.onBridgeConnected()
quick_games.Tarot.register_signals(self)
quick_games.Quiz.register_signals(self)
quick_games.Radiocol.register_signals(self)
self.on_bridge_connected()
def _bridgeEb(self, failure):
def _bridge_eb(self, failure):
if isinstance(failure, exceptions.BridgeExceptionNoService):
print((_("Can't connect to SàT backend, are you sure it's launched ?")))
sys.exit(C.EXIT_BACKEND_NOT_FOUND)
@ -375,15 +375,15 @@ class QuickApp(object):
else:
print((_("Error while initialising bridge: {}".format(failure))))
def onBackendReady(self):
def on_backend_ready(self):
log.info("backend is ready")
self.bridge.namespacesGet(
callback=self._namespacesGetCb, errback=self._namespacesGetEb)
self.bridge.namespaces_get(
callback=self._namespaces_get_cb, errback=self._namespaces_get_eb)
# we cache available encryption plugins, as we'll use them on each
# new chat widget
self.bridge.encryptionPluginsGet(
callback=self._encryptionPluginsGetCb,
errback=self._encryptionPluginsGetEb)
self.bridge.encryption_plugins_get(
callback=self._encryption_plugins_get_cb,
errback=self._encryption_plugins_get_eb)
@property
@ -392,7 +392,7 @@ class QuickApp(object):
try:
return self.selected_widget.profile
except (TypeError, AttributeError):
return self.profiles.chooseOneProfile()
return self.profiles.choose_one_profile()
@property
def visible_widgets(self):
@ -434,13 +434,13 @@ class QuickApp(object):
return
self._selected_widget = wid
try:
onSelected = wid.onSelected
on_selected = wid.on_selected
except AttributeError:
pass
else:
onSelected()
on_selected()
self.callListeners("selected", wid)
self.call_listeners("selected", wid)
# backend state management
@ -486,7 +486,7 @@ class QuickApp(object):
except AttributeError:
pass
def registerSignal(
def register_signal(
self, function_name, handler=None, iface="core", with_profile=True
):
"""Register a handler for a signal
@ -500,12 +500,12 @@ class QuickApp(object):
"""
log.debug("registering signal {name}".format(name=function_name))
if handler is None:
handler = getattr(self, "{}{}".format(function_name, "Handler"))
handler = getattr(self, "{}{}".format(function_name, "_handler"))
if not with_profile:
self.bridge.register_signal(function_name, handler, iface)
return
def signalReceived(*args, **kwargs):
def signal_received(*args, **kwargs):
profile = kwargs.get("profile")
if profile is None:
if not args:
@ -522,7 +522,7 @@ class QuickApp(object):
return # we ignore signal for profiles we don't manage
handler(*args, **kwargs)
self.bridge.register_signal(function_name, signalReceived, iface)
self.bridge.register_signal(function_name, signal_received, iface)
def addListener(self, type_, callback, profiles_filter=None):
"""Add a listener for an event
@ -551,15 +551,15 @@ class QuickApp(object):
args: (widget_deleted,)
- menu: called when a menu item is added or removed
args: (type_, path, path_i18n, item) were values are:
type_: same as in [sat.core.sat_main.SAT.importMenu]
path: same as in [sat.core.sat_main.SAT.importMenu]
type_: same as in [sat.core.sat_main.SAT.import_menu]
path: same as in [sat.core.sat_main.SAT.import_menu]
path_i18n: translated path (or None if the item is removed)
item: instance of quick_menus.MenuItemBase or None if the item is
removed
- gotMenus: called only once when menu are available (no arg)
- progressFinished: called when a progressing action has just finished
- progress_finished: called when a progressing action has just finished
args: (progress_id, metadata, profile)
- progressError: called when a progressing action failed
- progress_error: called when a progressing action failed
args: (progress_id, error_msg, profile):
@param callback: method to call on event
@param profiles_filter (set[unicode]): if set and not empty, the
@ -585,7 +585,7 @@ class QuickApp(object):
f"Trying to remove an inexisting listener (type = {type_}): "
f"{callback}")
def callListeners(self, type_, *args, **kwargs):
def call_listeners(self, type_, *args, **kwargs):
"""Call the methods which listen type_ event. If a profiles filter has
been register with a listener and profile argument is not None, the
listener will be called only if profile is in the profiles filter list.
@ -609,7 +609,7 @@ class QuickApp(object):
"""Tell if the profile is currently followed by the application, and ready"""
return profile in self.ready_profiles
def postInit(self, profile_manager):
def post_init(self, profile_manager):
"""Must be called after initialization is done, do all automatic task
(auto plug profile)
@ -619,7 +619,7 @@ class QuickApp(object):
if self.options and self.options.profile:
profile_manager.autoconnect([self.options.profile])
def profilePlugged(self, profile):
def profile_plugged(self, profile):
"""Method called when the profile is fully plugged
This will launch frontend specific workflow
@ -641,15 +641,15 @@ class QuickApp(object):
)
handler(*args, **kwargs)
self.callListeners("profilePlugged", profile=profile)
self.call_listeners("profile_plugged", profile=profile)
if not self._plugs_in_progress:
self.contact_lists.lockUpdate(False)
self.contact_lists.lock_update(False)
def profileConnected(self, profile):
def profile_connected(self, profile):
"""Called when a plugged profile is connected
it is called independently of profilePlugged (may be called before or after
profilePlugged)
it is called independently of profile_plugged (may be called before or after
profile_plugged)
"""
pass
@ -676,9 +676,9 @@ class QuickApp(object):
module.startswith("twisted.words.protocols.jabber")
and failure.condition == "not-authorized"
):
self.launchAction(C.CHANGE_XMPP_PASSWD_ID, {}, profile=profile)
self.action_launch(C.CHANGE_XMPP_PASSWD_ID, {}, profile=profile)
else:
self.showDialog(message, fullname, "error")
self.show_dialog(message, fullname, "error")
self.bridge.connect(profile, callback=callback, errback=errback)
@ -687,7 +687,7 @@ class QuickApp(object):
@param profiles: list of valid profile names
"""
self.contact_lists.lockUpdate()
self.contact_lists.lock_update()
self._plugs_in_progress.update(profiles)
self.plugging_profiles()
for profile in profiles:
@ -709,12 +709,12 @@ class QuickApp(object):
def clear_profile(self):
self.profiles.clear()
def newWidget(self, widget):
def new_widget(self, widget):
raise NotImplementedError
# bridge signals hanlers
def connectedHandler(self, jid_s, profile):
def connected_handler(self, jid_s, profile):
"""Called when the connection is made.
@param jid_s (unicode): the JID that we were assigned by the server,
@ -722,7 +722,7 @@ class QuickApp(object):
"""
log.debug(_("Connected"))
self.profiles[profile].whoami = jid.JID(jid_s)
self.setPresenceStatus(profile=profile)
self.set_presence_status(profile=profile)
# FIXME: fill() is already called for all profiles when doing self.sync = True
# a per-profile fill() should be done once, see below note
self.contact_lists[profile].fill()
@ -732,25 +732,25 @@ class QuickApp(object):
# A mechanism similar to sync should be available
# on a per-profile basis
self.sync = True
self.profileConnected(profile)
self.profile_connected(profile)
def disconnectedHandler(self, profile):
def disconnected_handler(self, profile):
"""called when the connection is closed"""
log.debug(_("Disconnected"))
self.contact_lists[profile].disconnect()
# FIXME: see note on connectedHandler
# FIXME: see note on connected_handler
self.sync = False
self.setPresenceStatus(C.PRESENCE_UNAVAILABLE, "", profile=profile)
self.set_presence_status(C.PRESENCE_UNAVAILABLE, "", profile=profile)
def actionNewHandler(self, action_data, id_, security_limit, profile):
self.actionManager(action_data, user_action=False, profile=profile)
def action_new_handler(self, action_data, id_, security_limit, profile):
self.action_manager(action_data, user_action=False, profile=profile)
def newContactHandler(self, jid_s, attributes, groups, profile):
def contact_new_handler(self, jid_s, attributes, groups, profile):
entity = jid.JID(jid_s)
groups = list(groups)
self.contact_lists[profile].setContact(entity, groups, attributes, in_roster=True)
self.contact_lists[profile].set_contact(entity, groups, attributes, in_roster=True)
def messageNewHandler(
def message_new_handler(
self, uid, timestamp, from_jid_s, to_jid_s, msg, subject, type_, extra_s,
profile):
from_jid = jid.JID(from_jid_s)
@ -767,7 +767,7 @@ class QuickApp(object):
contact_list = self.contact_lists[profile]
try:
is_room = contact_list.isRoom(target)
is_room = contact_list.is_room(target)
except exceptions.NotFound:
is_room = False
@ -776,7 +776,7 @@ class QuickApp(object):
# messages
target = target
# we want to be sure to have at least one QuickChat instance
self.widgets.getOrCreateWidget(
self.widgets.get_or_create_widget(
quick_chat.QuickChat,
target,
type_ = C.CHAT_GROUP if is_room else C.CHAT_ONE2ONE,
@ -790,36 +790,36 @@ class QuickApp(object):
):
# XXX: needed to show entities which haven't sent any
# presence information and which are not in roster
contact_list.setContact(from_jid)
contact_list.set_contact(from_jid)
# we dispatch the message in the widgets
for widget in self.widgets.getWidgets(
for widget in self.widgets.get_widgets(
quick_chat.QuickChat, target=target, profiles=(profile,)
):
widget.messageNew(
widget.message_new(
uid, timestamp, from_jid, mess_to_jid, msg, subject, type_, extra, profile
)
def messageEncryptionStartedHandler(self, destinee_jid_s, plugin_data, profile):
def message_encryption_started_handler(self, destinee_jid_s, plugin_data, profile):
destinee_jid = jid.JID(destinee_jid_s)
plugin_data = data_format.deserialise(plugin_data)
for widget in self.widgets.getWidgets(quick_chat.QuickChat,
for widget in self.widgets.get_widgets(quick_chat.QuickChat,
target=destinee_jid.bare,
profiles=(profile,)):
widget.messageEncryptionStarted(plugin_data)
widget.message_encryption_started(plugin_data)
def messageEncryptionStoppedHandler(self, destinee_jid_s, plugin_data, profile):
def message_encryption_stopped_handler(self, destinee_jid_s, plugin_data, profile):
destinee_jid = jid.JID(destinee_jid_s)
for widget in self.widgets.getWidgets(quick_chat.QuickChat,
for widget in self.widgets.get_widgets(quick_chat.QuickChat,
target=destinee_jid.bare,
profiles=(profile,)):
widget.messageEncryptionStopped(plugin_data)
widget.message_encryption_stopped(plugin_data)
def messageStateHandler(self, uid, status, profile):
for widget in self.widgets.getWidgets(quick_chat.QuickChat, profiles=(profile,)):
widget.onMessageState(uid, status, profile)
def message_state_handler(self, uid, status, profile):
for widget in self.widgets.get_widgets(quick_chat.QuickChat, profiles=(profile,)):
widget.on_message_state(uid, status, profile)
def messageSend(self, to_jid, message, subject=None, mess_type="auto", extra=None, callback=None, errback=None, profile_key=C.PROF_KEY_NONE):
def message_send(self, to_jid, message, subject=None, mess_type="auto", extra=None, callback=None, errback=None, profile_key=C.PROF_KEY_NONE):
if not subject and not extra and (not message or message == {'': ''}):
log.debug("Not sending empty message")
return
@ -834,14 +834,14 @@ class QuickApp(object):
) # FIXME: optional argument is here because pyjamas doesn't support callback
# without arg with json proxy
if errback is None:
errback = lambda failure: self.showDialog(
errback = lambda failure: self.show_dialog(
message=failure.message, title=failure.fullname, type="error"
)
if not self.trigger.point("messageSendTrigger", to_jid, message, subject, mess_type, extra, callback, errback, profile_key=profile_key):
return
self.bridge.messageSend(
self.bridge.message_send(
str(to_jid),
message,
subject,
@ -852,10 +852,10 @@ class QuickApp(object):
errback=errback,
)
def setPresenceStatus(self, show="", status=None, profile=C.PROF_KEY_NONE):
def set_presence_status(self, show="", status=None, profile=C.PROF_KEY_NONE):
raise NotImplementedError
def presenceUpdateHandler(self, entity_s, show, priority, statuses, profile):
def presence_update_handler(self, entity_s, show, priority, statuses, profile):
# XXX: this log is commented because it's really too verbose even for DEBUG logs
# but it is kept here as it may still be useful for troubleshooting
# log.debug(
@ -875,16 +875,16 @@ class QuickApp(object):
if entity == self.profiles[profile].whoami:
if show == C.PRESENCE_UNAVAILABLE:
self.setPresenceStatus(C.PRESENCE_UNAVAILABLE, "", profile=profile)
self.set_presence_status(C.PRESENCE_UNAVAILABLE, "", profile=profile)
else:
# FIXME: try to retrieve user language status before fallback to default
status = statuses.get(C.PRESENCE_STATUSES_DEFAULT, None)
self.setPresenceStatus(show, status, profile=profile)
self.set_presence_status(show, status, profile=profile)
return
self.callListeners("presence", entity, show, priority, statuses, profile=profile)
self.call_listeners("presence", entity, show, priority, statuses, profile=profile)
def mucRoomJoinedHandler(
def muc_room_joined_handler(
self, room_jid_s, occupants, user_nick, subject, statuses, profile):
"""Called when a MUC room is joined"""
log.debug(
@ -893,8 +893,8 @@ class QuickApp(object):
)
)
room_jid = jid.JID(room_jid_s)
self.contact_lists[profile].setSpecial(room_jid, C.CONTACT_SPECIAL_GROUP)
self.widgets.getOrCreateWidget(
self.contact_lists[profile].set_special(room_jid, C.CONTACT_SPECIAL_GROUP)
self.widgets.get_or_create_widget(
quick_chat.QuickChat,
room_jid,
type_=C.CHAT_GROUP,
@ -905,44 +905,44 @@ class QuickApp(object):
profile=profile,
)
def mucRoomLeftHandler(self, room_jid_s, profile):
def muc_room_left_handler(self, room_jid_s, profile):
"""Called when a MUC room is left"""
log.debug(
"Room [%(room_jid)s] left by %(profile)s"
% {"room_jid": room_jid_s, "profile": profile}
)
room_jid = jid.JID(room_jid_s)
chat_widget = self.widgets.getWidget(quick_chat.QuickChat, room_jid, profile)
chat_widget = self.widgets.get_widget(quick_chat.QuickChat, room_jid, profile)
if chat_widget:
self.widgets.deleteWidget(
self.widgets.delete_widget(
chat_widget, all_instances=True, explicit_close=True)
self.contact_lists[profile].removeContact(room_jid)
self.contact_lists[profile].remove_contact(room_jid)
def mucRoomUserChangedNickHandler(self, room_jid_s, old_nick, new_nick, profile):
def muc_room_user_changed_nick_handler(self, room_jid_s, old_nick, new_nick, profile):
"""Called when an user joined a MUC room"""
room_jid = jid.JID(room_jid_s)
chat_widget = self.widgets.getOrCreateWidget(
chat_widget = self.widgets.get_or_create_widget(
quick_chat.QuickChat, room_jid, type_=C.CHAT_GROUP, profile=profile
)
chat_widget.changeUserNick(old_nick, new_nick)
chat_widget.change_user_nick(old_nick, new_nick)
log.debug(
"user [%(old_nick)s] is now known as [%(new_nick)s] in room [%(room_jid)s]"
% {"old_nick": old_nick, "new_nick": new_nick, "room_jid": room_jid}
)
def mucRoomNewSubjectHandler(self, room_jid_s, subject, profile):
def muc_room_new_subject_handler(self, room_jid_s, subject, profile):
"""Called when subject of MUC room change"""
room_jid = jid.JID(room_jid_s)
chat_widget = self.widgets.getOrCreateWidget(
chat_widget = self.widgets.get_or_create_widget(
quick_chat.QuickChat, room_jid, type_=C.CHAT_GROUP, profile=profile
)
chat_widget.setSubject(subject)
chat_widget.set_subject(subject)
log.debug(
"new subject for room [%(room_jid)s]: %(subject)s"
% {"room_jid": room_jid, "subject": subject}
)
def chatStateReceivedHandler(self, from_jid_s, state, profile):
def chat_state_received_handler(self, from_jid_s, state, profile):
"""Called when a new chat state (XEP-0085) is received.
@param from_jid_s (unicode): JID of a contact or C.ENTITY_ALL
@ -950,9 +950,9 @@ class QuickApp(object):
@param profile (unicode): current profile
"""
from_jid = jid.JID(from_jid_s)
for widget in self.widgets.getWidgets(quick_chat.QuickChat, target=from_jid.bare,
for widget in self.widgets.get_widgets(quick_chat.QuickChat, target=from_jid.bare,
profiles=(profile,)):
widget.onChatState(from_jid, state, profile)
widget.on_chat_state(from_jid, state, profile)
def notify(self, type_, entity=None, message=None, subject=None, callback=None,
cb_args=None, widget=None, profile=C.PROF_KEY_NONE):
@ -986,9 +986,9 @@ class QuickApp(object):
type_notifs.append(notif_data)
self._notifications[self._notif_id] = notif_data
self._notif_id += 1
self.callListeners("notification", entity, notif_data, profile=profile)
self.call_listeners("notification", entity, notif_data, profile=profile)
def getNotifs(self, entity=None, type_=None, exact_jid=None, profile=C.PROF_KEY_NONE):
def get_notifs(self, entity=None, type_=None, exact_jid=None, profile=C.PROF_KEY_NONE):
"""return notifications for given entity
@param entity(jid.JID, None, C.ENTITY_ALL): jid of the entity to check
@ -1032,7 +1032,7 @@ class QuickApp(object):
continue
yield notif
def clearNotifs(self, entity, type_=None, profile=C.PROF_KEY_NONE):
def clear_notifs(self, entity, type_=None, profile=C.PROF_KEY_NONE):
"""return notifications for given entity
@param entity(jid.JID, None): bare jid of the entity to check
@ -1050,9 +1050,9 @@ class QuickApp(object):
del notif_dict[key][type_]
except KeyError:
return
self.callListeners("notificationsClear", entity, type_, profile=profile)
self.call_listeners("notificationsClear", entity, type_, profile=profile)
def psEventHandler(self, category, service_s, node, event_type, data, profile):
def ps_event_handler(self, category, service_s, node, event_type, data, profile):
"""Called when a PubSub event is received.
@param category(unicode): event category (e.g. "PEP", "MICROBLOG")
@ -1073,8 +1073,8 @@ class QuickApp(object):
# FIXME: check if [] make sense (instead of None)
_groups = data.get("group")
for wid in self.widgets.getWidgets(quick_blog.QuickBlog):
wid.addEntryIfAccepted(service_s, node, data, _groups, profile)
for wid in self.widgets.get_widgets(quick_blog.QuickBlog):
wid.add_entry_if_accepted(service_s, node, data, _groups, profile)
try:
comments_node, comments_service = (
@ -1084,7 +1084,7 @@ class QuickApp(object):
except KeyError:
pass
else:
self.bridge.mbGet(
self.bridge.mb_get(
comments_service,
comments_node,
C.NO_LIMIT,
@ -1093,13 +1093,13 @@ class QuickApp(object):
profile=profile,
)
elif event_type == C.PS_RETRACT:
for wid in self.widgets.getWidgets(quick_blog.QuickBlog):
wid.deleteEntryIfPresent(service_s, node, data["id"], profile)
for wid in self.widgets.get_widgets(quick_blog.QuickBlog):
wid.delete_entry_if_present(service_s, node, data["id"], profile)
pass
else:
log.warning("Unmanaged PubSub event type {}".format(event_type))
def registerProgressCbs(self, progress_id, callback, errback):
def register_progress_cbs(self, progress_id, callback, errback):
"""Register progression callbacks
@param progress_id(unicode): id of the progression to check
@ -1112,10 +1112,10 @@ class QuickApp(object):
callbacks = self._progress_ids.setdefault(progress_id, [])
callbacks.append((callback, errback))
def progressStartedHandler(self, pid, metadata, profile):
def progress_started_handler(self, pid, metadata, profile):
log.info("Progress {} started".format(pid))
def progressFinishedHandler(self, pid, metadata, profile):
def progress_finished_handler(self, pid, metadata, profile):
log.info("Progress {} finished".format(pid))
try:
callbacks = self._progress_ids.pop(pid)
@ -1125,9 +1125,9 @@ class QuickApp(object):
for callback, __ in callbacks:
if callback is not None:
callback(metadata, profile=profile)
self.callListeners("progressFinished", pid, metadata, profile=profile)
self.call_listeners("progress_finished", pid, metadata, profile=profile)
def progressErrorHandler(self, pid, err_msg, profile):
def progress_error_handler(self, pid, err_msg, profile):
log.warning("Progress {pid} error: {err_msg}".format(pid=pid, err_msg=err_msg))
try:
callbacks = self._progress_ids.pop(pid)
@ -1137,20 +1137,20 @@ class QuickApp(object):
for __, errback in callbacks:
if errback is not None:
errback(err_msg, profile=profile)
self.callListeners("progressError", pid, err_msg, profile=profile)
self.call_listeners("progress_error", pid, err_msg, profile=profile)
def _subscribe_cb(self, answer, data):
entity, profile = data
type_ = "subscribed" if answer else "unsubscribed"
self.bridge.subscription(type_, str(entity.bare), profile_key=profile)
def subscribeHandler(self, type, raw_jid, profile):
def subscribe_handler(self, type, raw_jid, profile):
"""Called when a subsciption management signal is received"""
entity = jid.JID(raw_jid)
if type == "subscribed":
# this is a subscription confirmation, we just have to inform user
# TODO: call self.getEntityMBlog to add the new contact blogs
self.showDialog(
self.show_dialog(
_("The contact {contact} has accepted your subscription").format(
contact=entity.bare
),
@ -1158,7 +1158,7 @@ class QuickApp(object):
)
elif type == "unsubscribed":
# this is a subscription refusal, we just have to inform user
self.showDialog(
self.show_dialog(
_("The contact {contact} has refused your subscription").format(
contact=entity.bare
),
@ -1168,7 +1168,7 @@ class QuickApp(object):
elif type == "subscribe":
# this is a subscriptionn request, we have to ask for user confirmation
# TODO: use sat.stdui.ui_contact_list to display the groups selector
self.showDialog(
self.show_dialog(
_(
"The contact {contact} wants to subscribe to your presence"
".\nDo you accept ?"
@ -1179,7 +1179,7 @@ class QuickApp(object):
answer_data=(entity, profile),
)
def _debugHandler(self, action, parameters, profile):
def _debug_handler(self, action, parameters, profile):
if action == "widgets_dump":
from pprint import pformat
log.info("Widgets dump:\n{data}".format(data=pformat(self.widgets._widgets)))
@ -1187,7 +1187,7 @@ class QuickApp(object):
log.warning("Unknown debug action: {action}".format(action=action))
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):
"""Show a dialog to user
Frontends must override this method
@ -1206,25 +1206,25 @@ class QuickApp(object):
# FIXME: misnamed method + types are not well chosen. Need to be rethought
raise NotImplementedError
def showAlert(self, message):
def show_alert(self, message):
# FIXME: doesn't seems used anymore, to remove?
pass # FIXME
def dialogFailure(self, failure):
def dialog_failure(self, failure):
log.warning("Failure: {}".format(failure))
def progressIdHandler(self, progress_id, profile):
def progress_id_handler(self, progress_id, profile):
"""Callback used when an action result in a progress id"""
log.info("Progress ID received: {}".format(progress_id))
def isHidden(self):
def is_hidden(self):
"""Tells if the frontend window is hidden.
@return bool
"""
raise NotImplementedError
def paramUpdateHandler(self, name, value, namespace, profile):
def param_update_handler(self, name, value, namespace, profile):
log.debug(
_("param update: [%(namespace)s] %(name)s = %(value)s")
% {"namespace": namespace, "name": name, "value": value}
@ -1233,37 +1233,37 @@ class QuickApp(object):
log.debug(_("Changing JID to %s") % value)
self.profiles[profile].whoami = jid.JID(value)
elif (namespace, name) == ("General", C.SHOW_OFFLINE_CONTACTS):
self.contact_lists[profile].showOfflineContacts(C.bool(value))
self.contact_lists[profile].show_offline_contacts(C.bool(value))
elif (namespace, name) == ("General", C.SHOW_EMPTY_GROUPS):
self.contact_lists[profile].showEmptyGroups(C.bool(value))
self.contact_lists[profile].show_empty_groups(C.bool(value))
def contactDeletedHandler(self, jid_s, profile):
def contact_deleted_handler(self, jid_s, profile):
target = jid.JID(jid_s)
self.contact_lists[profile].removeContact(target)
self.contact_lists[profile].remove_contact(target)
def entityDataUpdatedHandler(self, entity_s, key, value_raw, profile):
def entity_data_updated_handler(self, entity_s, key, value_raw, profile):
entity = jid.JID(entity_s)
value = data_format.deserialise(value_raw, type_check=None)
if key == "nicknames":
assert isinstance(value, list) or value is None
if entity in self.contact_lists[profile]:
self.contact_lists[profile].setCache(entity, "nicknames", value)
self.callListeners("nicknames", entity, value, profile=profile)
self.contact_lists[profile].set_cache(entity, "nicknames", value)
self.call_listeners("nicknames", entity, value, profile=profile)
elif key == "avatar" and self.AVATARS_HANDLER:
assert isinstance(value, dict) or value is None
self.contact_lists[profile].setCache(entity, "avatar", value)
self.callListeners("avatar", entity, value, profile=profile)
self.contact_lists[profile].set_cache(entity, "avatar", value)
self.call_listeners("avatar", entity, value, profile=profile)
def actionManager(self, action_data, callback=None, ui_show_cb=None, user_action=True,
def action_manager(self, action_data, callback=None, ui_show_cb=None, user_action=True,
progress_cb=None, progress_eb=None, profile=C.PROF_KEY_NONE):
"""Handle backend action
@param action_data(dict): action dict as sent by launchAction or returned by an
@param action_data(dict): action dict as sent by action_launch or returned by an
UI action
@param callback(None, callback): if not None, callback to use on XMLUI answer
@param ui_show_cb(None, callback): if not None, method to call to show the XMLUI
@param user_action(bool): if True, the action is a result of a user interaction
else the action come from backend direclty (i.e. actionNew).
else the action come from backend direclty (i.e. action_new).
This is useful to know if the frontend can display a popup immediately (if
True) or if it should add it to a queue that the user can activate later.
@param progress_cb(None, callable): method to call when progression is finished.
@ -1295,8 +1295,8 @@ class QuickApp(object):
pass
else:
if progress_cb or progress_eb:
self.registerProgressCbs(progress_id, progress_cb, progress_eb)
self.progressIdHandler(progress_id, profile)
self.register_progress_cbs(progress_id, progress_cb, progress_eb)
self.progress_id_handler(progress_id, profile)
# we ignore metadata
action_data = {
@ -1310,13 +1310,13 @@ class QuickApp(object):
)
)
def _actionCb(self, data, callback, callback_id, profile):
def _action_cb(self, data, callback, callback_id, profile):
if callback is None:
self.actionManager(data, profile=profile)
self.action_manager(data, profile=profile)
else:
callback(data=data, cb_id=callback_id, profile=profile)
def launchAction(
def action_launch(
self, callback_id, data=None, callback=None, profile=C.PROF_KEY_NONE
):
"""Launch a dynamic action
@ -1324,7 +1324,7 @@ class QuickApp(object):
@param callback_id: id of the action to launch
@param data: data needed only for certain actions
@param callback(callable, None): will be called with the resut
if None, self.actionManager will be called
if None, self.action_manager will be called
else the callable will be called with the following kw parameters:
- data: action_data
- cb_id: callback id
@ -1334,12 +1334,12 @@ class QuickApp(object):
"""
if data is None:
data = dict()
action_cb = lambda data: self._actionCb(data, callback, callback_id, profile)
self.bridge.launchAction(
callback_id, data, profile, callback=action_cb, errback=self.dialogFailure
action_cb = lambda data: self._action_cb(data, callback, callback_id, profile)
self.bridge.action_launch(
callback_id, data, profile, callback=action_cb, errback=self.dialog_failure
)
def launchMenu(
def launch_menu(
self,
menu_type,
path,
@ -1354,7 +1354,7 @@ class QuickApp(object):
@param path(iterable[unicode]): path to the menu
@param data: data needed only for certain actions
@param callback(callable, None): will be called with the resut
if None, self.actionManager will be called
if None, self.action_manager will be called
else the callable will be called with the following kw parameters:
- data: action_data
- cb_id: (menu_type, path) tuple
@ -1364,25 +1364,25 @@ class QuickApp(object):
"""
if data is None:
data = dict()
action_cb = lambda data: self._actionCb(
action_cb = lambda data: self._action_cb(
data, callback, (menu_type, path), profile
)
self.bridge.menuLaunch(
self.bridge.menu_launch(
menu_type,
path,
data,
security_limit,
profile,
callback=action_cb,
errback=self.dialogFailure,
errback=self.dialog_failure,
)
def disconnect(self, profile):
log.info("disconnecting")
self.callListeners("disconnect", profile=profile)
self.call_listeners("disconnect", profile=profile)
self.bridge.disconnect(profile)
def onExit(self):
def on_exit(self):
"""Must be called when the frontend is terminating"""
to_unplug = []
for profile, profile_manager in self.profiles.items():

View file

@ -125,27 +125,27 @@ class EntriesManager(object):
manager = manager.manager
return level
def _addMBItems(self, items_tuple, service=None, node=None):
def _add_mb_items(self, items_tuple, service=None, node=None):
"""Add Microblog items to this panel
update is NOT called after addition
@param items_tuple(tuple): (items_data,items_metadata) tuple as returned by mbGet
@param items_tuple(tuple): (items_data,items_metadata) tuple as returned by mb_get
"""
items, metadata = items_tuple
for item in items:
self.addEntry(item, service=service, node=node, with_update=False)
self.add_entry(item, service=service, node=node, with_update=False)
def _addMBItemsWithComments(self, items_tuple, service=None, node=None):
def _add_mb_items_with_comments(self, items_tuple, service=None, node=None):
"""Add Microblog items to this panel
update is NOT called after addition
@param items_tuple(tuple): (items_data,items_metadata) tuple as returned by mbGet
@param items_tuple(tuple): (items_data,items_metadata) tuple as returned by mb_get
"""
items, metadata = items_tuple
for item, comments in items:
self.addEntry(item, comments, service=service, node=node, with_update=False)
self.add_entry(item, comments, service=service, node=node, with_update=False)
def addEntry(self, item=None, comments=None, service=None, node=None,
def add_entry(self, item=None, comments=None, service=None, node=None,
with_update=True, editable=False, edit_entry=False):
"""Add a microblog entry
@ -160,7 +160,7 @@ class EntriesManager(object):
entry regardless of sorting)
"""
new_entry = ENTRY_CLS(self, item, comments, service=service, node=node)
new_entry.setEditable(editable)
new_entry.set_editable(editable)
if edit_entry:
self.edit_entry = new_entry
else:
@ -175,7 +175,7 @@ class EntriesManager(object):
@param entry (Entry, None): if not None, must be the new entry.
If None, all the items will be checked to update the display
"""
# update is separated from addEntry to allow adding
# update is separated from add_entry to allow adding
# several entries at once, and updating at the end
raise NotImplementedError
@ -232,7 +232,7 @@ class Entry(EntriesManager):
"""Refresh the display when data have been modified"""
pass
def setEditable(self, editable=True):
def set_editable(self, editable=True):
"""tell if the entry can be edited or not
@param editable(bool): True if the entry can be edited
@ -240,17 +240,17 @@ class Entry(EntriesManager):
# XXX: we don't use @property as property setter doesn't play well with pyjamas
raise NotImplementedError
def addComments(self, comments_data):
"""Add comments to this entry by calling addEntry repeatidly
def add_comments(self, comments_data):
"""Add comments to this entry by calling add_entry repeatidly
@param comments_data(tuple): data as returned by mbGetFromMany*RTResults
@param comments_data(tuple): data as returned by mb_get_from_many*RTResults
"""
# TODO: manage seperator between comments of coming from different services/nodes
for data in comments_data:
service, node, failure, comments, metadata = data
for comment in comments:
if not failure:
self.addEntry(comment, service=jid.JID(service), node=node)
self.add_entry(comment, service=jid.JID(service), node=node)
else:
log.warning("getting comment failed: {}".format(failure))
self.update()
@ -286,7 +286,7 @@ class Entry(EntriesManager):
if self.blog.new_message_target == C.GROUP:
mb_data['groups'] = list(self.blog.targets)
self.blog.host.bridge.mbSend(
self.blog.host.bridge.mb_send(
str(self.service or ""),
self.node or "",
data_format.serialise(mb_data),
@ -327,12 +327,12 @@ class Entry(EntriesManager):
"""
# TODO: manage several comments nodes case.
if self.item.comments:
self.blog.host.bridge.psNodeDelete(
self.blog.host.bridge.ps_node_delete(
str(self.item.comments_service) or "",
self.item.comments_node,
profile=self.blog.profile,
)
self.blog.host.bridge.mbRetract(
self.blog.host.bridge.mb_retract(
str(self.service or ""),
self.node or "",
self.item.id,
@ -362,7 +362,7 @@ class QuickBlog(EntriesManager, quick_widgets.QuickWidget):
quick_widgets.QuickWidget.__init__(self, host, targets[0], C.PROF_KEY_NONE)
for target in targets[1:]:
assert isinstance(target, str)
self.addTarget(target)
self.add_target(target)
self._targets_type = C.GROUP
@property
@ -379,7 +379,7 @@ class QuickBlog(EntriesManager, quick_widgets.QuickWidget):
", ".join(self.targets), self.profile
)
def _getResultsCb(self, data, rt_session):
def _get_results_cb(self, data, rt_session):
remaining, results = data
log.debug(
"Got {got_len} results, {rem_len} remaining".format(
@ -393,37 +393,37 @@ class QuickBlog(EntriesManager, quick_widgets.QuickWidget):
for item_metadata in item_data[1]:
item_metadata[3] = [data_format.deserialise(i) for i in item_metadata[3]]
if not failure:
self._addMBItemsWithComments((items_data, metadata),
self._add_mb_items_with_comments((items_data, metadata),
service=jid.JID(service))
self.update()
if remaining:
self._getResults(rt_session)
self._get_results(rt_session)
def _getResultsEb(self, failure):
log.warning("microblog getFromMany error: {}".format(failure))
def _get_results_eb(self, failure):
log.warning("microblog get_from_many error: {}".format(failure))
def _getResults(self, rt_session):
"""Manage results from mbGetFromMany RT Session
def _get_results(self, rt_session):
"""Manage results from mb_get_from_many RT Session
@param rt_session(str): session id as returned by mbGetFromMany
@param rt_session(str): session id as returned by mb_get_from_many
"""
self.host.bridge.mbGetFromManyWithCommentsRTResult(
self.host.bridge.mb_get_from_many_with_comments_rt_result(
rt_session,
profile=self.profile,
callback=lambda data: self._getResultsCb(data, rt_session),
errback=self._getResultsEb,
callback=lambda data: self._get_results_cb(data, rt_session),
errback=self._get_results_eb,
)
def getAll(self):
def get_all(self):
"""Get all (micro)blogs from self.targets"""
def gotSession(rt_session):
self._getResults(rt_session)
def got_session(rt_session):
self._get_results(rt_session)
if self._targets_type in (C.ALL, C.GROUP):
targets = tuple(self.targets) if self._targets_type is C.GROUP else ()
self.host.bridge.mbGetFromManyWithComments(
self.host.bridge.mb_get_from_many_with_comments(
self._targets_type,
targets,
10,
@ -431,10 +431,10 @@ class QuickBlog(EntriesManager, quick_widgets.QuickWidget):
{},
{"subscribe": C.BOOL_TRUE},
profile=self.profile,
callback=gotSession,
callback=got_session,
)
own_pep = self.host.whoami.bare
self.host.bridge.mbGetFromManyWithComments(
self.host.bridge.mb_get_from_many_with_comments(
C.JID,
(str(own_pep),),
10,
@ -442,14 +442,14 @@ class QuickBlog(EntriesManager, quick_widgets.QuickWidget):
{},
{},
profile=self.profile,
callback=gotSession,
callback=got_session,
)
else:
raise NotImplementedError(
"{} target type is not managed".format(self._targets_type)
)
def isJidAccepted(self, jid_):
def is_jid_accepted(self, jid_):
"""Tell if a jid is actepted and must be shown in this panel
@param jid_(jid.JID): jid to check
@ -459,11 +459,11 @@ class QuickBlog(EntriesManager, quick_widgets.QuickWidget):
return True
assert self._targets_type is C.GROUP # we don't manage other types for now
for group in self.targets:
if self.host.contact_lists[self.profile].isEntityInGroup(jid_, group):
if self.host.contact_lists[self.profile].is_entity_in_group(jid_, group):
return True
return False
def addEntryIfAccepted(self, service, node, mb_data, groups, profile):
def add_entry_if_accepted(self, service, node, mb_data, groups, profile):
"""add entry to this panel if it's acceptable
This method check if the entry is new or an update,
@ -485,24 +485,24 @@ class QuickBlog(EntriesManager, quick_widgets.QuickWidget):
# The node is unknown,
# we need to check that we can accept the entry
if (
self.isJidAccepted(service)
self.is_jid_accepted(service)
or (
groups is None
and service == self.host.profiles[self.profile].whoami.bare
)
or (groups and groups.intersection(self.targets))
):
self.addEntry(mb_data, service=service, node=node)
self.add_entry(mb_data, service=service, node=node)
else:
# the entry is a comment in a known node
for parent_entry in parent_entries:
parent_entry.addEntry(mb_data, service=service, node=node)
parent_entry.add_entry(mb_data, service=service, node=node)
else:
# The entry exist, it's an update
entry.reset(mb_data)
entry.refresh()
def deleteEntryIfPresent(self, service, node, item_id, profile):
def delete_entry_if_present(self, service, node, item_id, profile):
"""Delete and entry if present in this QuickBlog
@param sender(jid.JID): jid of the entry sender
@ -518,7 +518,7 @@ class QuickBlog(EntriesManager, quick_widgets.QuickWidget):
entry.delete()
def registerClass(type_, cls):
def register_class(type_, cls):
global ENTRY_CLS, COMMENTS_CLS
if type_ == "ENTRY":
ENTRY_CLS = cls

View file

@ -55,7 +55,7 @@ class Message:
self.subject = subject
self.type = type_
self.extra = extra
self.nick = self.getNick(from_jid)
self.nick = self.get_nick(from_jid)
self._status = None
# own_mess is True if message was sent by profile's jid
self.own_mess = (
@ -69,7 +69,7 @@ class Message:
if self.parent.nick.lower() in m.lower():
self._mention = True
break
self.handleMe()
self.handle_me()
self.widgets = set() # widgets linked to this message
def __str__(self):
@ -147,14 +147,14 @@ class Message:
return contact_list.getCache(entity, "avatar")
except (exceptions.NotFound, KeyError):
# we don't check the result as the avatar listener will be called
self.host.bridge.avatarGet(entity, True, self.profile)
self.host.bridge.avatar_get(entity, True, self.profile)
return None
@property
def encrypted(self):
return self.extra.get("encrypted", False)
def getNick(self, entity):
def get_nick(self, entity):
"""Return nick of an entity when possible"""
contact_list = self.host.contact_lists[self.profile]
if self.type == C.MESS_TYPE_INFO and self.info_type in ROOM_USER_MOVED:
@ -163,9 +163,9 @@ class Message:
except KeyError:
log.error("extra data is missing user nick for uid {}".format(self.uid))
return ""
# FIXME: converted getSpecials to list for pyjamas
# FIXME: converted get_specials to list for pyjamas
if self.parent.type == C.CHAT_GROUP or entity in list(
contact_list.getSpecials(C.CONTACT_SPECIAL_GROUP)
contact_list.get_specials(C.CONTACT_SPECIAL_GROUP)
):
return entity.resource or ""
if entity.bare in contact_list:
@ -174,7 +174,7 @@ class Message:
nicknames = contact_list.getCache(entity, "nicknames")
except (exceptions.NotFound, KeyError):
# we check result as listener will be called
self.host.bridge.identityGet(
self.host.bridge.identity_get(
entity.bare, ["nicknames"], True, self.profile)
return entity.node or entity
@ -200,7 +200,7 @@ class Message:
for w in self.widgets:
w.update({"status": status})
def handleMe(self):
def handle_me(self):
"""Check if messages starts with "/me " and change them if it is the case
if several messages (different languages) are presents, they all need to start with "/me "
@ -306,7 +306,7 @@ class QuickChat(quick_widgets.QuickWidget):
# True when resync is in progress, avoid resynchronising twice when resync is called
# and history is still being updated. For internal use only
self._resync_lock = False
self.setLocked()
self.set_locked()
if type_ == C.CHAT_GROUP:
if target.resource:
raise exceptions.InternalError(
@ -317,7 +317,7 @@ class QuickChat(quick_widgets.QuickWidget):
self.nick = nick
self.occupants = {}
self.setOccupants(occupants)
self.set_occupants(occupants)
else:
if occupants is not None or nick is not None:
raise exceptions.InternalError(
@ -340,9 +340,9 @@ class QuickChat(quick_widgets.QuickWidget):
lt.tm_isdst,
) # struct_time of day changing time
if self.host.AVATARS_HANDLER:
self.host.addListener("avatar", self.onAvatar, profiles)
self.host.addListener("avatar", self.on_avatar, profiles)
def setLocked(self):
def set_locked(self):
"""Set locked flag
To be set when we are waiting for history/search
@ -353,37 +353,37 @@ class QuickChat(quick_widgets.QuickWidget):
log.warning("{wid} is already locked!".format(wid=self))
return
self._locked = True
# messageNew signals are cached when locked
# message_new signals are cached when locked
self._cache = OrderedDict()
log.debug("{wid} is now locked".format(wid=self))
def setUnlocked(self):
def set_unlocked(self):
if not self._locked:
log.debug("{wid} was already unlocked".format(wid=self))
return
self._locked = False
for uid, data in self._cache.items():
if uid not in self.messages:
self.messageNew(*data)
self.message_new(*data)
else:
log.debug("discarding message already in history: {data}, ".format(data=data))
del self._cache
log.debug("{wid} is now unlocked".format(wid=self))
def postInit(self):
def post_init(self):
"""Method to be called by frontend after widget is initialised
handle the display of history and subject
"""
self.historyPrint(profile=self.profile)
self.history_print(profile=self.profile)
if self.subject is not None:
self.setSubject(self.subject)
self.set_subject(self.subject)
if self.host.ENCRYPTION_HANDLERS:
self.getEncryptionState()
self.get_encryption_state()
def onDelete(self):
def on_delete(self):
if self.host.AVATARS_HANDLER:
self.host.removeListener("avatar", self.onAvatar)
self.host.removeListener("avatar", self.on_avatar)
@property
def contact_list(self):
@ -403,13 +403,13 @@ class QuickChat(quick_widgets.QuickWidget):
def sync(self, state):
quick_widgets.QuickWidget.sync.fset(self, state)
if not state:
self.setLocked()
self.set_locked()
def _resyncComplete(self):
def _resync_complete(self):
self.sync = True
self._resync_lock = False
def occupantsClear(self):
def occupants_clear(self):
"""Remove all occupants
Must be overridden by frontends to clear their own representations of occupants
@ -428,17 +428,17 @@ class QuickChat(quick_widgets.QuickWidget):
break
else:
# we have no message yet, we can get normal history
self.historyPrint(callback=self._resyncComplete, profile=self.profile)
self.history_print(callback=self._resync_complete, profile=self.profile)
return
if self.type == C.CHAT_GROUP:
self.occupantsClear()
self.host.bridge.mucOccupantsGet(
str(self.target), self.profile, callback=self.updateOccupants,
self.occupants_clear()
self.host.bridge.muc_occupants_get(
str(self.target), self.profile, callback=self.update_occupants,
errback=log.error)
self.historyPrint(
self.history_print(
size=C.HISTORY_LIMIT_NONE,
filters={'timestamp_start': last_message.timestamp},
callback=self._resyncComplete,
callback=self._resync_complete,
profile=self.profile)
## Widget management ##
@ -449,26 +449,26 @@ class QuickChat(quick_widgets.QuickWidget):
)
@staticmethod
def getWidgetHash(target, profiles):
def get_widget_hash(target, profiles):
profile = list(profiles)[0]
return profile + "\n" + str(target.bare)
@staticmethod
def getPrivateHash(target, profile):
def get_private_hash(target, profile):
"""Get unique hash for private conversations
This method should be used with force_hash to get unique widget for private MUC conversations
"""
return (str(profile), target)
def addTarget(self, target):
super(QuickChat, self).addTarget(target)
def add_target(self, target):
super(QuickChat, self).add_target(target)
if target.resource:
self.current_target = (
target
) # FIXME: tmp, must use resource priority throught contactList instead
def recreateArgs(self, args, kwargs):
def recreate_args(self, args, kwargs):
"""copy important attribute for a new widget"""
kwargs["type_"] = self.type
if self.type == C.CHAT_GROUP:
@ -479,21 +479,21 @@ class QuickChat(quick_widgets.QuickWidget):
except AttributeError:
pass
def onPrivateCreated(self, widget):
def on_private_created(self, widget):
"""Method called when a new widget for private conversation (MUC) is created"""
raise NotImplementedError
def getOrCreatePrivateWidget(self, entity):
def get_or_create_private_widget(self, entity):
"""Create a widget for private conversation, or get it if it already exists
@param entity: full jid of the target
"""
return self.host.widgets.getOrCreateWidget(
return self.host.widgets.get_or_create_widget(
QuickChat,
entity,
type_=C.CHAT_ONE2ONE,
force_hash=self.getPrivateHash(self.profile, entity),
on_new_widget=self.onPrivateCreated,
force_hash=self.get_private_hash(self.profile, entity),
on_new_widget=self.on_private_created,
profile=self.profile,
) # we force hash to have a new widget, not this one again
@ -505,7 +505,7 @@ class QuickChat(quick_widgets.QuickWidget):
## occupants ##
def setOccupants(self, occupants):
def set_occupants(self, occupants):
"""Set the whole list of occupants"""
assert len(self.occupants) == 0
for nick, data in occupants.items():
@ -515,10 +515,10 @@ class QuickChat(quick_widgets.QuickWidget):
# nick=nick, room=self.target))
self.occupants[nick] = Occupant(self, data, self.profile)
def updateOccupants(self, occupants):
def update_occupants(self, occupants):
"""Update occupants list
In opposition to setOccupants, this only add missing occupants and remove
In opposition to set_occupants, this only add missing occupants and remove
occupants who have left
"""
# FIXME: occupants with modified status are not handled
@ -553,11 +553,11 @@ class QuickChat(quick_widgets.QuickWidget):
else:
return occupant
def setUserNick(self, nick):
def set_user_nick(self, nick):
"""Set the nick of the user, usefull for e.g. change the color of the user"""
self.nick = nick
def changeUserNick(self, old_nick, new_nick):
def change_user_nick(self, old_nick, new_nick):
"""Change nick of a user in group list"""
log.info("{old} is now known as {new} in room {room_jid}".format(
old = old_nick,
@ -566,11 +566,11 @@ class QuickChat(quick_widgets.QuickWidget):
## Messages ##
def manageMessage(self, entity, mess_type):
def manage_message(self, entity, mess_type):
"""Tell if this chat widget manage an entity and message type couple
@param entity (jid.JID): (full) jid of the sending entity
@param mess_type (str): message type as given by messageNew
@param mess_type (str): message type as given by message_new
@return (bool): True if this Chat Widget manage this couple
"""
if self.type == C.CHAT_GROUP:
@ -584,32 +584,32 @@ class QuickChat(quick_widgets.QuickWidget):
return True
return False
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@"):
"""Called when history need to be recreated
Remove all message from history then call historyPrint
Remove all message from history then call history_print
Must probably be overriden by frontend to clear widget
@param size (int): number of messages
@param filters (str): patterns to filter the history results
@param profile (str): %(doc_profile)s
"""
self.setLocked()
self.set_locked()
self.messages.clear()
self.historyPrint(size, filters, profile=profile)
self.history_print(size, filters, profile=profile)
def _onHistoryPrinted(self):
def _on_history_printed(self):
"""Method called when history is printed (or failed)
unlock the widget, and can be used to refresh or scroll down
the focus after the history is printed
"""
self.setUnlocked()
self.set_unlocked()
def historyPrint(self, size=C.HISTORY_LIMIT_DEFAULT, filters=None, callback=None,
def history_print(self, size=C.HISTORY_LIMIT_DEFAULT, filters=None, callback=None,
profile="@NONE@"):
"""Print the current history
Note: self.setUnlocked will be called once history is printed
Note: self.set_unlocked will be called once history is printed
@param size (int): number of messages
@param search (str): pattern to filter the history results
@param callback(callable, None): method to call when history has been printed
@ -619,7 +619,7 @@ class QuickChat(quick_widgets.QuickWidget):
filters = {}
if size == 0:
log.debug("Empty history requested, skipping")
self._onHistoryPrinted()
self._on_history_printed()
return
log_msg = _("now we print the history")
if size != C.HISTORY_LIMIT_DEFAULT:
@ -647,12 +647,12 @@ class QuickChat(quick_widgets.QuickWidget):
self.history_filters = filters
def _historyGetCb(history):
def _history_get_cb(history):
# day_format = "%A, %d %b %Y" # to display the day change
# previous_day = datetime.now().strftime(day_format)
# message_day = datetime.fromtimestamp(timestamp).strftime(self.day_format)
# if previous_day != message_day:
# self.printDayChange(message_day)
# self.print_day_change(message_day)
# previous_day = message_day
for data in history:
uid, timestamp, from_jid, to_jid, message, subject, type_, extra_s = data
@ -675,49 +675,49 @@ class QuickChat(quick_widgets.QuickWidget):
extra,
profile,
)
self._onHistoryPrinted()
self._on_history_printed()
if callback is not None:
callback()
def _historyGetEb(err):
def _history_get_eb(err):
log.error(_("Can't get history: {}").format(err))
self._onHistoryPrinted()
self._on_history_printed()
if callback is not None:
callback()
self.host.bridge.historyGet(
self.host.bridge.history_get(
str(self.host.profiles[profile].whoami.bare),
str(target),
size,
True,
{k: str(v) for k,v in filters.items()},
profile,
callback=_historyGetCb,
errback=_historyGetEb,
callback=_history_get_cb,
errback=_history_get_eb,
)
def messageEncryptionGetCb(self, session_data):
def message_encryption_get_cb(self, session_data):
if session_data:
session_data = data_format.deserialise(session_data)
self.messageEncryptionStarted(session_data)
self.message_encryption_started(session_data)
def messageEncryptionGetEb(self, failure_):
def message_encryption_get_eb(self, failure_):
log.error(_("Can't get encryption state: {reason}").format(reason=failure_))
def getEncryptionState(self):
def get_encryption_state(self):
"""Retrieve encryption state with current target.
Once state is retrieved, default messageEncryptionStarted will be called if
Once state is retrieved, default message_encryption_started will be called if
suitable
"""
if self.type == C.CHAT_GROUP:
return
self.host.bridge.messageEncryptionGet(str(self.target.bare), self.profile,
callback=self.messageEncryptionGetCb,
errback=self.messageEncryptionGetEb)
self.host.bridge.message_encryption_get(str(self.target.bare), self.profile,
callback=self.message_encryption_get_cb,
errback=self.message_encryption_get_eb)
def messageNew(self, uid, timestamp, from_jid, to_jid, msg, subject, type_, extra,
def message_new(self, uid, timestamp, from_jid, to_jid, msg, subject, type_, extra,
profile):
if self._locked:
self._cache[uid] = (
@ -742,8 +742,8 @@ class QuickChat(quick_widgets.QuickWidget):
if to_jid.resource and type_ != C.MESS_TYPE_GROUPCHAT:
# we have a private message, we forward it to a private conversation
# widget
chat_widget = self.getOrCreatePrivateWidget(to_jid)
chat_widget.messageNew(
chat_widget = self.get_or_create_private_widget(to_jid)
chat_widget.message_new(
uid, timestamp, from_jid, to_jid, msg, subject, type_, extra, profile
)
return
@ -768,28 +768,28 @@ class QuickChat(quick_widgets.QuickWidget):
if "received_timestamp" in extra:
log.warning("Delayed message received after history, this should not happen")
self.createMessage(message)
self.create_message(message)
def messageEncryptionStarted(self, session_data):
def message_encryption_started(self, session_data):
self.encrypted = True
log.debug(_("message encryption started with {target} using {encryption}").format(
target=self.target, encryption=session_data['name']))
def messageEncryptionStopped(self, session_data):
def message_encryption_stopped(self, session_data):
self.encrypted = False
log.debug(_("message encryption stopped with {target} (was using {encryption})")
.format(target=self.target, encryption=session_data['name']))
def createMessage(self, message, append=False):
def create_message(self, message, append=False):
"""Must be implemented by frontend to create and show a new message widget
This is only called on messageNew, not on history.
You need to override historyPrint to handle the later
This is only called on message_new, not on history.
You need to override history_print to handle the later
@param message(Message): message data
"""
raise NotImplementedError
def isUserMoved(self, message):
def is_user_moved(self, message):
"""Return True if message is a user left/joined message
@param message(Message): message to check
@ -804,7 +804,7 @@ class QuickChat(quick_widgets.QuickWidget):
else:
return info_type in ROOM_USER_MOVED
def handleUserMoved(self, message):
def handle_user_moved(self, message):
"""Check if this message is a UserMoved one, and merge it when possible
"merge it" means that info message indicating a user joined/left will be
@ -813,7 +813,7 @@ class QuickChat(quick_widgets.QuickWidget):
@return (bool): True if this message has been merged
if True, a new MessageWidget must not be created and appended to history
"""
if self.isUserMoved(message):
if self.is_user_moved(message):
for wid in self.message_widgets_rev:
# we merge in/out messages if no message was sent meanwhile
if not isinstance(wid, MessageWidget):
@ -841,7 +841,7 @@ class QuickChat(quick_widgets.QuickWidget):
return True
return False
def printDayChange(self, day):
def print_day_change(self, day):
"""Display the day on a new line.
@param day(unicode): day to display (or not if this method is not overwritten)
@ -851,7 +851,7 @@ class QuickChat(quick_widgets.QuickWidget):
## Room ##
def setSubject(self, subject):
def set_subject(self, subject):
"""Set title for a group chat"""
if self.type != C.CHAT_GROUP:
raise exceptions.InternalError(
@ -859,22 +859,22 @@ class QuickChat(quick_widgets.QuickWidget):
)
self.subject = subject
def changeSubject(self, new_subject):
def change_subject(self, new_subject):
"""Change the subject of the room
This change the subject on the room itself (i.e. via XMPP),
while setSubject change the subject of this widget
while set_subject change the subject of this widget
"""
self.host.bridge.mucSubject(str(self.target), new_subject, self.profile)
self.host.bridge.muc_subject(str(self.target), new_subject, self.profile)
def addGamePanel(self, widget):
def add_game_panel(self, widget):
"""Insert a game panel to this Chat dialog.
@param widget (Widget): the game panel
"""
raise NotImplementedError
def removeGamePanel(self, widget):
def remove_game_panel(self, widget):
"""Remove the game panel from this Chat dialog.
@param widget (Widget): the game panel
@ -891,7 +891,7 @@ class QuickChat(quick_widgets.QuickWidget):
## events ##
def onChatState(self, from_jid, state, profile):
def on_chat_state(self, from_jid, state, profile):
"""A chat state has been received"""
if self.type == C.CHAT_GROUP:
nick = from_jid.resource
@ -904,7 +904,7 @@ class QuickChat(quick_widgets.QuickWidget):
)
)
def onMessageState(self, uid, status, profile):
def on_message_state(self, uid, status, profile):
try:
mess_data = self.messages[uid]
except KeyError:
@ -912,7 +912,7 @@ class QuickChat(quick_widgets.QuickWidget):
else:
mess_data.status = status
def onAvatar(self, entity, avatar_data, profile):
def on_avatar(self, entity, avatar_data, profile):
if self.type == C.CHAT_GROUP:
if entity.bare == self.target:
try:

View file

@ -83,7 +83,7 @@ class ProfileContactList(object):
# options
self.show_disconnected = False
self.show_empty_groups = True
self._show_empty_groups = True
self.show_resources = False
self.show_status = False
# do we show entities with notifications?
@ -91,45 +91,45 @@ class ProfileContactList(object):
# (e.g. not in contact list) if they have notifications attached
self.show_entities_with_notifs = True
self.host.bridge.asyncGetParamA(
self.host.bridge.param_get_a_async(
C.SHOW_EMPTY_GROUPS,
"General",
profile_key=profile,
callback=self._showEmptyGroups,
callback=self._show_empty_groups_cb,
)
self.host.bridge.asyncGetParamA(
self.host.bridge.param_get_a_async(
C.SHOW_OFFLINE_CONTACTS,
"General",
profile_key=profile,
callback=self._showOfflineContacts,
callback=self._show_offline_contacts,
)
self.host.addListener("presence", self.onPresenceUpdate, [self.profile])
self.host.addListener("nicknames", self.onNicknamesUpdate, [self.profile])
self.host.addListener("notification", self.onNotification, [self.profile])
# onNotification only updates the entity, so we can re-use it
self.host.addListener("notificationsClear", self.onNotification, [self.profile])
self.host.addListener("presence", self.on_presence_update, [self.profile])
self.host.addListener("nicknames", self.on_nicknames_update, [self.profile])
self.host.addListener("notification", self.on_notification, [self.profile])
# on_notification only updates the entity, so we can re-use it
self.host.addListener("notificationsClear", self.on_notification, [self.profile])
@property
def whoami(self):
return self.host.profiles[self.profile].whoami
def _showEmptyGroups(self, show_str):
def _show_empty_groups_cb(self, show_str):
# Called only by __init__
# self.update is not wanted here, as it is done by
# handler when all profiles are ready
self.showEmptyGroups(C.bool(show_str))
self.show_empty_groups(C.bool(show_str))
def _showOfflineContacts(self, show_str):
# same comments as for _showEmptyGroups
self.showOfflineContacts(C.bool(show_str))
def _show_offline_contacts(self, show_str):
# same comments as for _show_empty_groups
self.show_offline_contacts(C.bool(show_str))
def __contains__(self, entity):
"""Check if entity is in contact list
An entity can be in contact list even if not in roster
use isInRoster to check if entity is in roster.
use is_in_roster to check if entity is in roster.
@param entity (jid.JID): jid of the entity (resource is not ignored,
use bare jid if needed)
"""
@ -209,10 +209,10 @@ class ProfileContactList(object):
return {
jid_: cache
for jid_, cache in self._cache.items()
if self.entityVisible(jid_)
if self.entity_visible(jid_)
}
def getItem(self, entity):
def get_item(self, entity):
"""Return item representation of requested entity
@param entity(jid.JID): bare jid of entity
@ -220,7 +220,7 @@ class ProfileContactList(object):
"""
return self._cache[entity]
def _gotContacts(self, contacts):
def _got_contacts(self, contacts):
"""Add contacts and notice parent that contacts are filled
Called during initial contact list filling
@ -235,16 +235,16 @@ class ProfileContactList(object):
"Roster entities with resources are not managed, ignoring {entity}"
.format(entity=entity))
continue
self.host.newContactHandler(*contact, profile=self.profile)
handler._contactsFilled(self.profile)
self.host.contact_new_handler(*contact, profile=self.profile)
handler._contacts_filled(self.profile)
def _fill(self):
"""Get all contacts from backend
Contacts will be cleared before refilling them
"""
self.clearContacts(keep_cache=True)
self.host.bridge.getContacts(self.profile, callback=self._gotContacts)
self.clear_contacts(keep_cache=True)
self.host.bridge.contacts_get(self.profile, callback=self._got_contacts)
def fill(self):
handler.fill(self.profile)
@ -285,7 +285,7 @@ class ProfileContactList(object):
cache = self._cache[entity.bare]
except KeyError:
if create_if_not_found:
self.setContact(entity)
self.set_contact(entity)
cache = self._cache[entity.bare]
else:
raise exceptions.NotFound
@ -319,7 +319,7 @@ class ProfileContactList(object):
return cache[C.CONTACT_RESOURCES][entity.resource][name]
except KeyError as e:
if bare_default is None:
bare_default = not self.isRoom(entity.bare)
bare_default = not self.is_room(entity.bare)
if not bare_default:
if default is Exception:
raise e
@ -334,15 +334,15 @@ class ProfileContactList(object):
else:
return default
def setCache(self, entity, name, value):
def set_cache(self, entity, name, value):
"""Set or update value for one data in cache
@param entity(JID): entity to update
@param name(str): value to set or update
"""
self.setContact(entity, attributes={name: value})
self.set_contact(entity, attributes={name: value})
def getFullJid(self, entity):
def get_full_jid(self, entity):
"""Get full jid from a bare jid
@param entity(jid.JID): must be a bare jid
@ -350,11 +350,11 @@ class ProfileContactList(object):
@raise ValueError: the entity is not bare
"""
if entity.resource:
raise ValueError("getFullJid must be used with a bare jid")
raise ValueError("get_full_jid must be used with a bare jid")
main_resource = self.getCache(entity, C.CONTACT_MAIN_RESOURCE)
return jid.JID("{}/{}".format(entity, main_resource))
def setGroupData(self, group, name, value):
def set_group_data(self, group, name, value):
"""Register a data for a group
@param group: a valid (existing) group name
@ -364,7 +364,7 @@ class ProfileContactList(object):
assert name != "jids"
self._groups[group][name] = value
def getGroupData(self, group, name=None):
def get_group_data(self, group, name=None):
"""Return value associated to group data
@param group: a valid (existing) group name
@ -375,7 +375,7 @@ class ProfileContactList(object):
return self._groups[group]
return self._groups[group][name]
def isInRoster(self, entity):
def is_in_roster(self, entity):
"""Tell if an entity is in roster
@param entity(jid.JID): jid of the entity
@ -383,7 +383,7 @@ class ProfileContactList(object):
"""
return entity.bare in self._roster
def isRoom(self, entity):
def is_room(self, entity):
"""Helper method to know if entity is a MUC room
@param entity(jid.JID): jid of the entity
@ -391,9 +391,9 @@ class ProfileContactList(object):
@return (bool): True if entity is a room
"""
assert entity.resource is None # FIXME: this may change when MIX will be handled
return self.isSpecial(entity, C.CONTACT_SPECIAL_GROUP)
return self.is_special(entity, C.CONTACT_SPECIAL_GROUP)
def isSpecial(self, entity, special_type):
def is_special(self, entity, special_type):
"""Tell if an entity is of a specialy _type
@param entity(jid.JID): jid of the special entity
@ -403,7 +403,7 @@ class ProfileContactList(object):
"""
return self.getCache(entity, C.CONTACT_SPECIAL, default=None) == special_type
def setSpecial(self, entity, special_type):
def set_special(self, entity, special_type):
"""Set special flag on an entity
@param entity(jid.JID): jid of the special entity
@ -412,9 +412,9 @@ class ProfileContactList(object):
or None to remove special flag
"""
assert special_type in C.CONTACT_SPECIAL_ALLOWED + (None,)
self.setCache(entity, C.CONTACT_SPECIAL, special_type)
self.set_cache(entity, C.CONTACT_SPECIAL, special_type)
def getSpecials(self, special_type=None, bare=False):
def get_specials(self, special_type=None, bare=False):
"""Return all the bare JIDs of the special roster entities of with given type.
@param special_type(unicode, None): if not None, filter by special type
@ -434,9 +434,9 @@ class ProfileContactList(object):
def disconnect(self):
# for now we just clear contacts on disconnect
self.clearContacts()
self.clear_contacts()
def clearContacts(self, keep_cache=False):
def clear_contacts(self, keep_cache=False):
"""Clear all the contact list
@param keep_cache: if True, don't reset the cache
@ -449,7 +449,7 @@ class ProfileContactList(object):
self._roster.clear()
self.update()
def setContact(self, entity, groups=None, attributes=None, in_roster=False):
def set_contact(self, entity, groups=None, attributes=None, in_roster=False):
"""Add a contact to the list if it doesn't exist, else update it.
This method can be called with groups=None for the purpose of updating
@ -473,7 +473,7 @@ class ProfileContactList(object):
# we check if the entity is visible before changing anything
# this way we know if we need to do an UPDATE_ADD, UPDATE_MODIFY
# or an UPDATE_DELETE
was_visible = self.entityVisible(entity_bare)
was_visible = self.entity_visible(entity_bare)
if in_roster:
self._roster.add(entity_bare)
@ -526,7 +526,7 @@ class ProfileContactList(object):
else cache
)
for attribute, value in attributes.items():
if attribute == "nicknames" and self.isSpecial(
if attribute == "nicknames" and self.is_special(
entity, C.CONTACT_SPECIAL_GROUP
):
# we don't want to keep nicknames for MUC rooms
@ -540,7 +540,7 @@ class ProfileContactList(object):
cache_attr[attribute] = value
# we can update the display if needed
if self.entityVisible(entity_bare):
if self.entity_visible(entity_bare):
# if the contact was not visible, we need to add a widget
# else we just update id
update_type = C.UPDATE_MODIFY if was_visible else C.UPDATE_ADD
@ -549,7 +549,7 @@ class ProfileContactList(object):
# the entity was visible and is not anymore, we remove it
self.update([entity], C.UPDATE_DELETE, self.profile)
def entityVisible(self, entity, check_resource=False):
def entity_visible(self, entity, check_resource=False):
"""Tell if the contact should be showed or hidden.
@param entity (jid.JID): jid of the contact
@ -571,12 +571,12 @@ class ProfileContactList(object):
or entity in selected
or (
self.show_entities_with_notifs
and next(self.host.getNotifs(entity.bare, profile=self.profile), None)
and next(self.host.get_notifs(entity.bare, profile=self.profile), None)
)
or entity.resource is None and self.isRoom(entity.bare)
or entity.resource is None and self.is_room(entity.bare)
)
def anyEntityVisible(self, entities, check_resources=False):
def any_entity_visible(self, entities, check_resources=False):
"""Tell if in a list of entities, at least one should be shown
@param entities (list[jid.JID]): list of jids
@ -585,26 +585,26 @@ class ProfileContactList(object):
"""
# FIXME: looks inefficient, really needed?
for entity in entities:
if self.entityVisible(entity, check_resources):
if self.entity_visible(entity, check_resources):
return True
return False
def isEntityInGroup(self, entity, group):
def is_entity_in_group(self, entity, group):
"""Tell if an entity is in a roster group
@param entity(jid.JID): jid of the entity
@param group(unicode): group to check
@return (bool): True if the entity is in the group
"""
return entity in self.getGroupData(group, "jids")
return entity in self.get_group_data(group, "jids")
def removeContact(self, entity):
def remove_contact(self, entity):
"""remove a contact from the list
@param entity(jid.JID): jid of the entity to remove (bare jid is used)
"""
entity_bare = entity.bare
was_visible = self.entityVisible(entity_bare)
was_visible = self.entity_visible(entity_bare)
try:
groups = self._cache[entity_bare].get(C.CONTACT_GROUPS, set())
except KeyError:
@ -629,7 +629,7 @@ class ProfileContactList(object):
if was_visible:
self.update([entity], C.UPDATE_DELETE, self.profile)
def onPresenceUpdate(self, entity, show, priority, statuses, profile):
def on_presence_update(self, entity, show, priority, statuses, profile):
"""Update entity's presence status
@param entity(jid.JID): entity updated
@ -638,9 +638,9 @@ class ProfileContactList(object):
@param statuses: dict of statuses
@param profile: %(doc_profile)s
"""
# FIXME: cache modification should be done with setContact
# FIXME: cache modification should be done with set_contact
# the resources/presence handling logic should be moved there
was_visible = self.entityVisible(entity.bare)
was_visible = self.entity_visible(entity.bare)
cache = self.getCache(entity, create_if_not_found=True)
if show == C.PRESENCE_UNAVAILABLE:
if not entity.resource:
@ -680,13 +680,13 @@ class ProfileContactList(object):
),
)
cache[C.CONTACT_MAIN_RESOURCE] = priority_resource
if self.entityVisible(entity.bare):
if self.entity_visible(entity.bare):
update_type = C.UPDATE_MODIFY if was_visible else C.UPDATE_ADD
self.update([entity], update_type, self.profile)
elif was_visible:
self.update([entity], C.UPDATE_DELETE, self.profile)
def onNicknamesUpdate(self, entity, nicknames, profile):
def on_nicknames_update(self, entity, nicknames, profile):
"""Update entity's nicknames
@param entity(jid.JID): entity updated
@ -694,9 +694,9 @@ class ProfileContactList(object):
@param profile: %(doc_profile)s
"""
assert profile == self.profile
self.setCache(entity, "nicknames", nicknames)
self.set_cache(entity, "nicknames", nicknames)
def onNotification(self, entity, notif, profile):
def on_notification(self, entity, notif, profile):
"""Update entity with notification
@param entity(jid.JID): entity updated
@ -704,7 +704,7 @@ class ProfileContactList(object):
@param profile: %(doc_profile)s
"""
assert profile == self.profile
if entity is not None and self.entityVisible(entity):
if entity is not None and self.entity_visible(entity):
self.update([entity], C.UPDATE_MODIFY, profile)
def unselect(self, entity):
@ -747,7 +747,7 @@ class ProfileContactList(object):
self._selected.add(entity)
self.update([entity], C.UPDATE_SELECTION, profile=self.profile)
def showOfflineContacts(self, show):
def show_offline_contacts(self, show):
"""Tell if offline contacts should be shown
@param show(bool): True if offline contacts should be shown
@ -758,14 +758,14 @@ class ProfileContactList(object):
self.show_disconnected = show
self.update(type_=C.UPDATE_STRUCTURE, profile=self.profile)
def showEmptyGroups(self, show):
def show_empty_groups(self, show):
assert isinstance(show, bool)
if self.show_empty_groups == show:
if self._show_empty_groups == show:
return
self.show_empty_groups = show
self._show_empty_groups = show
self.update(type_=C.UPDATE_STRUCTURE, profile=self.profile)
def showResources(self, show):
def show_resources(self, show):
assert isinstance(show, bool)
if self.show_resources == show:
return
@ -773,10 +773,10 @@ class ProfileContactList(object):
self.update(type_=C.UPDATE_STRUCTURE, profile=self.profile)
def plug(self):
handler.addProfile(self.profile)
handler.add_profile(self.profile)
def unplug(self):
handler.removeProfile(self.profile)
handler.remove_profile(self.profile)
def update(self, entities=None, type_=None, profile=None):
handler.update(entities, type_, profile)
@ -930,7 +930,7 @@ class QuickContactListHandler(object):
"""
self._widgets.remove(widget)
def addProfiles(self, profiles):
def add_profiles(self, profiles):
"""Add a contact list for plugged profiles
@param profile(iterable[unicode]): plugged profiles
@ -940,10 +940,10 @@ class QuickContactListHandler(object):
self._clist[profile] = ProfileContactList(profile)
return [self._clist[profile] for profile in profiles]
def addProfile(self, profile):
return self.addProfiles([profile])[0]
def add_profile(self, profile):
return self.add_profiles([profile])[0]
def removeProfiles(self, profiles):
def remove_profiles(self, profiles):
"""Remove given unplugged profiles from contact list
@param profile(iterable[unicode]): unplugged profiles
@ -951,10 +951,10 @@ class QuickContactListHandler(object):
for profile in profiles:
del self._clist[profile]
def removeProfile(self, profile):
self.removeProfiles([profile])
def remove_profile(self, profile):
self.remove_profiles([profile])
def getSpecialExtras(self, special_type=None):
def get_special_extras(self, special_type=None):
"""Return special extras with given type
If special_type is None, return all special extras.
@ -966,16 +966,16 @@ class QuickContactListHandler(object):
"""
entities = set()
for contact_list in self._clist.values():
entities.update(contact_list.getSpecialExtras(special_type))
entities.update(contact_list.get_special_extras(special_type))
return entities
def _contactsFilled(self, profile):
def _contacts_filled(self, profile):
self._to_fill.remove(profile)
if not self._to_fill:
del self._to_fill
# we need a full update when all contacts are filled
self.update()
self.host.callListeners("contactsFilled", profile=profile)
self.host.call_listeners("contactsFilled", profile=profile)
def fill(self, profile=None):
"""Get all contacts from backend, and fill the widget
@ -1009,13 +1009,13 @@ class QuickContactListHandler(object):
for profile in remaining:
self._clist[profile]._fill()
def clearContacts(self, keep_cache=False):
def clear_contacts(self, keep_cache=False):
"""Clear all the contact list
@param keep_cache: if True, don't reset the cache
"""
for contact_list in self._clist.values():
contact_list.clearContacts(keep_cache)
contact_list.clear_contacts(keep_cache)
# we need a full update
self.update()
@ -1027,7 +1027,7 @@ class QuickContactListHandler(object):
for contact_list in self._clist.values():
contact_list.select(entity)
def lockUpdate(self, locked=True, do_update=True):
def lock_update(self, locked=True, do_update=True):
"""Forbid contact list updates
Used mainly while profiles are plugged, as many updates can occurs, causing
@ -1067,11 +1067,11 @@ class QuickContactList(QuickWidget):
# for next values, None means use indivual value per profile
# True or False mean override these values for all profiles
self.show_disconnected = None # TODO
self.show_empty_groups = None # TODO
self._show_empty_groups = None # TODO
self.show_resources = None # TODO
self.show_status = None # TODO
def postInit(self):
def post_init(self):
"""Method to be called by frontend after widget is initialised"""
handler.register(self)
@ -1108,6 +1108,6 @@ class QuickContactList(QuickWidget):
"""
raise NotImplementedError
def onDelete(self):
QuickWidget.onDelete(self)
def on_delete(self):
QuickWidget.on_delete(self)
handler.unregister(self)

View file

@ -49,7 +49,7 @@ class QuickContactManagement(object):
self.__contactlist[entity.bare]["resources"].remove(entity.resource)
self.__contactlist[entity.bare]["resources"].append(entity.resource)
def getContFromGroup(self, group):
def get_cont_from_group(self, group):
"""Return all contacts which are in given group"""
result = []
for contact in self.__contactlist:
@ -58,7 +58,7 @@ class QuickContactManagement(object):
result.append(JID(contact))
return result
def getAttr(self, entity, name):
def get_attr(self, entity, name):
"""Return a specific attribute of contact, or all attributes
@param entity: jid of the contact
@param name: name of the attribute
@ -73,7 +73,7 @@ class QuickContactManagement(object):
log.debug(_("Trying to get attribute for an unknown contact"))
return None
def isConnected(self, entity):
def is_connected(self, entity):
"""Tell if the contact is online"""
return entity.bare in self.__contactlist

View file

@ -48,7 +48,7 @@ class QuickTarotGame(object):
self.to_show = []
self.state = None
def resetRound(self):
def reset_round(self):
"""Reset the game's variables to be reatty to start the next round"""
del self.selected[:]
del self.hand[:]
@ -57,14 +57,14 @@ class QuickTarotGame(object):
for pl in self.played:
self.played[pl] = None
def getPlayerLocation(self, nick):
def get_player_location(self, nick):
"""return player location (top,bottom,left or right)"""
for location in ["top", "left", "bottom", "right"]:
if getattr(self, "%s_nick" % location) == nick:
return location
assert False
def loadCards(self):
def load_cards(self):
"""Load all the cards in memory
@param dir: directory where the PNG files are"""
self.cards = {}
@ -77,7 +77,7 @@ class QuickTarotGame(object):
self.cards["carreau"] = {} # diamond
self.cards["trefle"] = {} # club
def tarotGameNewHandler(self, hand):
def tarot_game_new_handler(self, hand):
"""Start a new game, with given hand"""
assert len(self.hand) == 0
for suit, value in hand:
@ -85,12 +85,12 @@ class QuickTarotGame(object):
self.hand.sort()
self.state = "init"
def tarotGameChooseContratHandler(self, xml_data):
def tarot_game_choose_contrat_handler(self, xml_data):
"""Called when the player as to select his contrat
@param xml_data: SàT xml representation of the form"""
raise NotImplementedError
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)"""
self.to_show = []
for suit, value in cards:
@ -100,14 +100,14 @@ class QuickTarotGame(object):
else:
self.state = "chien"
def tarotGameYourTurnHandler(self):
def tarot_game_your_turn_handler(self):
"""Called when we have to play :)"""
if self.state == "chien":
self.to_show = []
self.state = "play"
self.__fakePlay()
self.__fake_play()
def __fakePlay(self):
def __fake_play(self):
"""Convenience method for stupid autoplay
/!\ don't forgot to comment any interactive dialog for invalid card"""
if self._autoplay == None:
@ -115,21 +115,21 @@ class QuickTarotGame(object):
if self._autoplay >= len(self.hand):
self._autoplay = 0
card = self.hand[self._autoplay]
self.parent.host.bridge.tarotGamePlayCards(
self.parent.host.bridge.tarot_game_play_cards(
self.player_nick, self.referee, [(card.suit, card.value)], self.parent.profile
)
del self.hand[self._autoplay]
self.state = "wait"
self._autoplay += 1
def tarotGameScoreHandler(self, xml_data, winners, loosers):
def tarot_game_score_handler(self, xml_data, winners, loosers):
"""Called at the end of a game
@param xml_data: SàT xml representation of the scores
@param winners: list of winners' nicks
@param loosers: list of loosers' nicks"""
raise NotImplementedError
def tarotGameCardsPlayedHandler(self, player, cards):
def tarot_game_cards_played_handler(self, player, cards):
"""A card has been played by player"""
if self.to_show:
self.to_show = []
@ -141,7 +141,7 @@ class QuickTarotGame(object):
pl_cards.append(self.cards[suit, value])
self.played[player] = pl_cards[0]
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
@ -158,4 +158,4 @@ class QuickTarotGame(object):
self.hand.append(self.cards[suit, value])
self.hand.sort()
self.__fakePlay()
self.__fake_play()

View file

@ -36,26 +36,26 @@ class RoomGame(object):
_signal_suffixes = None
@classmethod
def registerSignals(cls, host):
def register_signals(cls, host):
def make_handler(suffix, signal):
def handler(*args):
if suffix in ("Started", "Players"):
return cls.startedHandler(host, suffix, *args)
return cls.genericHandler(host, signal, *args)
return cls.started_handler(host, suffix, *args)
return cls.generic_handler(host, signal, *args)
return handler
for suffix in cls._signal_suffixes:
signal = cls._signal_prefix + suffix
host.registerSignal(
host.register_signal(
signal, handler=make_handler(suffix, signal), iface="plugin"
)
@classmethod
def startedHandler(cls, host, suffix, *args):
def started_handler(cls, host, suffix, *args):
room_jid, args, profile = jid.JID(args[0]), args[1:-1], args[-1]
referee, players, args = args[0], args[1], args[2:]
chat_widget = host.widgets.getOrCreateWidget(
chat_widget = host.widgets.get_or_create_widget(
quick_chat.QuickChat, room_jid, type_=C.CHAT_GROUP, profile=profile
)
@ -66,8 +66,8 @@ class RoomGame(object):
index = 0
contact_list = host.contact_lists[profile]
for occupant in chat_widget.occupants:
occupant_jid = jid.newResource(room_jid, occupant)
contact_list.setCache(
occupant_jid = jid.new_resource(room_jid, occupant)
contact_list.set_cache(
occupant_jid,
cls._game_name,
symbols[index % len(symbols)] if occupant in players else None,
@ -78,9 +78,9 @@ class RoomGame(object):
return # waiting for other players to join, or not playing
if cls._game_name in chat_widget.games:
return # game panel is already there
real_class = host.widgets.getRealClass(cls)
real_class = host.widgets.get_real_class(cls)
if real_class == cls:
host.showDialog(
host.show_dialog(
_(
"A {game} activity between {players} has been started, but you couldn't take part because your client doesn't support it."
).format(game=cls._game_name, players=", ".join(players)),
@ -89,12 +89,12 @@ class RoomGame(object):
return
panel = real_class(chat_widget, referee, players, *args)
chat_widget.games[cls._game_name] = panel
chat_widget.addGamePanel(panel)
chat_widget.add_game_panel(panel)
@classmethod
def genericHandler(cls, host, signal, *args):
def generic_handler(cls, host, signal, *args):
room_jid, args, profile = jid.JID(args[0]), args[1:-1], args[-1]
chat_widget = host.widgets.getWidget(quick_chat.QuickChat, room_jid, profile)
chat_widget = host.widgets.get_widget(quick_chat.QuickChat, room_jid, profile)
if chat_widget:
try:
game_panel = chat_widget.games[cls._game_name]

View file

@ -27,7 +27,7 @@ except (
str = str
from sat.core.log import getLogger
from sat.core.i18n import _, languageSwitch
from sat.core.i18n import _, language_switch
log = getLogger(__name__)
from sat_frontends.quick_frontend.constants import Const as C
@ -43,10 +43,10 @@ class MenuBase(object):
def __init__(self, name, extra=None):
"""
@param name(unicode): canonical name of the item
@param extra(dict[unicode, unicode], None): same as in [addMenus]
@param extra(dict[unicode, unicode], None): same as in [add_menus]
"""
self._name = name
self.setExtra(extra)
self.set_extra(extra)
@property
def canonical(self):
@ -58,7 +58,7 @@ class MenuBase(object):
"""Return the name of the container, can be translated"""
return self._name
def setExtra(self, extra):
def set_extra(self, extra):
if extra is None:
extra = {}
self.icon = extra.get("icon")
@ -73,8 +73,8 @@ class MenuItem(MenuBase):
"""
@param name(unicode): canonical name of the item
@param name_i18n(unicode): translated name of the item
@param extra(dict[unicode, unicode], None): same as in [addMenus]
@param type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
@param extra(dict[unicode, unicode], None): same as in [add_menus]
@param type_(unicode): same as in [sat.core.sat_main.SAT.import_menu]
"""
MenuBase.__init__(self, name, extra)
self._name_i18n = name_i18n if name_i18n else name
@ -84,13 +84,13 @@ class MenuItem(MenuBase):
def name(self):
return self._name_i18n
def collectData(self, caller):
def collect_data(self, caller):
"""Get data according to data_collector
@param caller: Menu caller
"""
assert self.type is not None # if data collector are used, type must be set
data_collector = QuickMenusManager.getDataCollector(self.type)
data_collector = QuickMenusManager.get_data_collector(self.type)
if data_collector is None:
return {}
@ -124,20 +124,20 @@ class MenuItemDistant(MenuItem):
def __init__(self, host, type_, name, name_i18n, id_, extra=None):
"""
@param host: %(doc_host)s
@param type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
@param type_(unicode): same as in [sat.core.sat_main.SAT.import_menu]
@param name(unicode): canonical name of the item
@param name_i18n(unicode): translated name of the item
@param id_(unicode): id of the distant callback
@param extra(dict[unicode, unicode], None): same as in [addMenus]
@param extra(dict[unicode, unicode], None): same as in [add_menus]
"""
MenuItem.__init__(self, name, name_i18n, extra, type_)
self.host = host
self.id = id_
def call(self, caller, profile=C.PROF_KEY_NONE):
data = self.collectData(caller)
data = self.collect_data(caller)
log.debug("data collected: %s" % data)
self.host.launchAction(self.id, data, profile=profile)
self.host.action_launch(self.id, data, profile=profile)
class MenuItemLocal(MenuItem):
@ -147,24 +147,24 @@ class MenuItemLocal(MenuItem):
def __init__(self, type_, name, name_i18n, callback, extra=None):
"""
@param type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
@param type_(unicode): same as in [sat.core.sat_main.SAT.import_menu]
@param name(unicode): canonical name of the item
@param name_i18n(unicode): translated name of the item
@param callback(callable): local callback.
Will be called with no argument if data_collector is None
and with caller, profile, and requested data otherwise
@param extra(dict[unicode, unicode], None): same as in [addMenus]
@param extra(dict[unicode, unicode], None): same as in [add_menus]
"""
MenuItem.__init__(self, name, name_i18n, extra, type_)
self.callback = callback
def call(self, caller, profile=C.PROF_KEY_NONE):
data_collector = QuickMenusManager.getDataCollector(self.type)
data_collector = QuickMenusManager.get_data_collector(self.type)
if data_collector is None:
# FIXME: would not it be better if caller and profile where used as arguments?
self.callback()
else:
self.callback(caller, self.collectData(caller), profile)
self.callback(caller, self.collect_data(caller), profile)
class MenuHook(MenuItemLocal):
@ -216,9 +216,9 @@ class MenuContainer(MenuBase):
except KeyError:
raise KeyError(item)
def getOrCreate(self, item):
def get_or_create(self, item):
log.debug(
"MenuContainer getOrCreate: item=%s name=%s\nlist=%s"
"MenuContainer get_or_create: item=%s name=%s\nlist=%s"
% (item, item.canonical, list(self._items.keys()))
)
try:
@ -227,7 +227,7 @@ class MenuContainer(MenuBase):
self.append(item)
return item
def getActiveMenus(self):
def get_active_menus(self):
"""Return an iterator on active children"""
for child in self._items.values():
if child.ACTIVE:
@ -284,50 +284,50 @@ class QuickMenusManager(object):
def __init__(self, host, menus=None, language=None):
"""
@param host: %(doc_host)s
@param menus(iterable): menus as in [addMenus]
@param language: same as in [i18n.languageSwitch]
@param menus(iterable): menus as in [add_menus]
@param language: same as in [i18n.language_switch]
"""
self.host = host
MenuBase.host = host
self.language = language
self.menus = {}
if menus is not None:
self.addMenus(menus)
self.add_menus(menus)
def _getPathI18n(self, path):
def _get_path_i_1_8_n(self, path):
"""Return translated version of path"""
languageSwitch(self.language)
language_switch(self.language)
path_i18n = [_(elt) for elt in path]
languageSwitch()
language_switch()
return path_i18n
def _createCategories(self, type_, path, path_i18n=None, top_extra=None):
def _create_categories(self, type_, path, path_i18n=None, top_extra=None):
"""Create catogories of the path
@param type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
@param path(list[unicode]): same as in [sat.core.sat_main.SAT.importMenu]
@param type_(unicode): same as in [sat.core.sat_main.SAT.import_menu]
@param path(list[unicode]): same as in [sat.core.sat_main.SAT.import_menu]
@param path_i18n(list[unicode], None): translated menu path (same lenght as path) or None to get deferred translation of path
@param top_extra: extra data to use on the first element of path only. If the first element already exists and is reused, top_extra will be ignored (you'll have to manually change it if you really want to).
@return (MenuContainer): last category created, or MenuType if path is empty
"""
if path_i18n is None:
path_i18n = self._getPathI18n(path)
path_i18n = self._get_path_i_1_8_n(path)
assert len(path) == len(path_i18n)
menu_container = self.menus.setdefault(type_, MenuType(type_))
for idx, category in enumerate(path):
menu_category = MenuCategory(category, path_i18n[idx], extra=top_extra)
menu_container = menu_container.getOrCreate(menu_category)
menu_container = menu_container.get_or_create(menu_category)
top_extra = None
return menu_container
@staticmethod
def addDataCollector(type_, data_collector):
def add_data_collector(type_, data_collector):
"""Associate a data collector to a menu type
A data collector is a method or a map which allow to collect context data to construct the dictionnary which will be sent to the bridge method managing the menu item.
@param type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
@param type_(unicode): same as in [sat.core.sat_main.SAT.import_menu]
@param data_collector(dict[unicode,unicode], callable, None): can be:
- a dict which map data name to local name.
The attribute named after the dict values will be getted from caller, and put in data.
@ -338,10 +338,10 @@ class QuickMenusManager(object):
QuickMenusManager._data_collectors[type_] = data_collector
@staticmethod
def getDataCollector(type_):
def get_data_collector(type_):
"""Get data_collector associated to type_
@param type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
@param type_(unicode): same as in [sat.core.sat_main.SAT.import_menu]
@return (callable, dict, None): data_collector
"""
try:
@ -350,20 +350,20 @@ class QuickMenusManager(object):
log.error("No data collector registered for {}".format(type_))
return None
def addMenuItem(self, type_, path, item, path_i18n=None, top_extra=None):
def add_menu_item(self, type_, path, item, path_i18n=None, top_extra=None):
"""Add a MenuItemBase instance
@param type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
@param path(list[unicode]): same as in [sat.core.sat_main.SAT.importMenu], stop at the last parent category
@param type_(unicode): same as in [sat.core.sat_main.SAT.import_menu]
@param path(list[unicode]): same as in [sat.core.sat_main.SAT.import_menu], stop at the last parent category
@param item(MenuItem): a instancied item
@param path_i18n(list[unicode],None): translated menu path (same lenght as path) or None to use deferred translation of path
@param top_extra: same as in [_createCategories]
@param top_extra: same as in [_create_categories]
"""
if path_i18n is None:
path_i18n = self._getPathI18n(path)
path_i18n = self._get_path_i_1_8_n(path)
assert path and len(path) == len(path_i18n)
menu_container = self._createCategories(type_, path, path_i18n, top_extra)
menu_container = self._create_categories(type_, path, path_i18n, top_extra)
if item in menu_container:
if isinstance(item, MenuHook):
@ -384,9 +384,9 @@ class QuickMenusManager(object):
else:
log.debug("Adding menu [{type_}] {path}".format(type_=type_, path=path))
menu_container.append(item)
self.host.callListeners("menu", type_, path, path_i18n, item)
self.host.call_listeners("menu", type_, path, path_i18n, item)
def addMenu(
def add_menu(
self,
type_,
path,
@ -398,16 +398,16 @@ class QuickMenusManager(object):
):
"""Add a menu item
@param type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
@param path(list[unicode]): same as in [sat.core.sat_main.SAT.importMenu]
@param type_(unicode): same as in [sat.core.sat_main.SAT.import_menu]
@param path(list[unicode]): same as in [sat.core.sat_main.SAT.import_menu]
@param path_i18n(list[unicode], None): translated menu path (same lenght as path), or None to get deferred translation
@param extra(dict[unicode, unicode], None): same as in [addMenus]
@param top_extra: same as in [_createCategories]
@param extra(dict[unicode, unicode], None): same as in [add_menus]
@param top_extra: same as in [_create_categories]
@param id_(unicode): callback id (mutually exclusive with callback)
@param callback(callable): local callback (mutually exclusive with id_)
"""
if path_i18n is None:
path_i18n = self._getPathI18n(path)
path_i18n = self._get_path_i_1_8_n(path)
assert bool(id_) ^ bool(callback) # we must have id_ xor callback defined
if id_:
menu_item = MenuItemDistant(
@ -417,71 +417,71 @@ class QuickMenusManager(object):
menu_item = MenuItemLocal(
type_, path[-1], path_i18n[-1], callback=callback, extra=extra
)
self.addMenuItem(type_, path[:-1], menu_item, path_i18n[:-1], top_extra)
self.add_menu_item(type_, path[:-1], menu_item, path_i18n[:-1], top_extra)
def addMenus(self, menus, top_extra=None):
def add_menus(self, menus, top_extra=None):
"""Add several menus at once
@param menus(iterable): iterable with:
id_(unicode,callable): id of distant callback or local callback
type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
path(iterable[unicode]): same as in [sat.core.sat_main.SAT.importMenu]
type_(unicode): same as in [sat.core.sat_main.SAT.import_menu]
path(iterable[unicode]): same as in [sat.core.sat_main.SAT.import_menu]
path_i18n(iterable[unicode]): translated menu path (same lenght as path)
extra(dict[unicode,unicode]): dictionary of extra data (used on the leaf menu), can be:
- "icon": icon name
@param top_extra: same as in [_createCategories]
@param top_extra: same as in [_create_categories]
"""
# TODO: manage icons
for id_, type_, path, path_i18n, extra in menus:
if callable(id_):
self.addMenu(
self.add_menu(
type_, path, path_i18n, callback=id_, extra=extra, top_extra=top_extra
)
else:
self.addMenu(
self.add_menu(
type_, path, path_i18n, id_=id_, extra=extra, top_extra=top_extra
)
def addMenuHook(
def add_menu_hook(
self, type_, path, path_i18n=None, extra=None, top_extra=None, callback=None
):
"""Helper method to add a menu hook
Menu hooks are local menus which override menu given by backend
@param type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
@param path(list[unicode]): same as in [sat.core.sat_main.SAT.importMenu]
@param type_(unicode): same as in [sat.core.sat_main.SAT.import_menu]
@param path(list[unicode]): same as in [sat.core.sat_main.SAT.import_menu]
@param path_i18n(list[unicode], None): translated menu path (same lenght as path), or None to get deferred translation
@param extra(dict[unicode, unicode], None): same as in [addMenus]
@param top_extra: same as in [_createCategories]
@param extra(dict[unicode, unicode], None): same as in [add_menus]
@param top_extra: same as in [_create_categories]
@param callback(callable): local callback (mutually exclusive with id_)
"""
if path_i18n is None:
path_i18n = self._getPathI18n(path)
path_i18n = self._get_path_i_1_8_n(path)
menu_item = MenuHook(
type_, path[-1], path_i18n[-1], callback=callback, extra=extra
)
self.addMenuItem(type_, path[:-1], menu_item, path_i18n[:-1], top_extra)
self.add_menu_item(type_, path[:-1], menu_item, path_i18n[:-1], top_extra)
log.info("Menu hook set on {path} ({type_})".format(path=path, type_=type_))
def addCategory(self, type_, path, path_i18n=None, extra=None, top_extra=None):
def add_category(self, type_, path, path_i18n=None, extra=None, top_extra=None):
"""Create a category with all parents, and set extra on the last one
@param type_(unicode): same as in [sat.core.sat_main.SAT.importMenu]
@param path(list[unicode]): same as in [sat.core.sat_main.SAT.importMenu]
@param type_(unicode): same as in [sat.core.sat_main.SAT.import_menu]
@param path(list[unicode]): same as in [sat.core.sat_main.SAT.import_menu]
@param path_i18n(list[unicode], None): translated menu path (same lenght as path), or None to get deferred translation of path
@param extra(dict[unicode, unicode], None): same as in [addMenus] (added on the leaf category only)
@param top_extra: same as in [_createCategories]
@param extra(dict[unicode, unicode], None): same as in [add_menus] (added on the leaf category only)
@param top_extra: same as in [_create_categories]
@return (MenuCategory): last category add
"""
if path_i18n is None:
path_i18n = self._getPathI18n(path)
last_container = self._createCategories(
path_i18n = self._get_path_i_1_8_n(path)
last_container = self._create_categories(
type_, path, path_i18n, top_extra=top_extra
)
last_container.setExtra(extra)
last_container.set_extra(extra)
return last_container
def getMainContainer(self, type_):
def get_main_container(self, type_):
"""Get a main MenuType container
@param type_: a C.MENU_* constant

View file

@ -106,38 +106,38 @@ class QuickProfileManager(object):
else:
# a profile is not validated, we go to manual mode
self._autoconnect = False
self.host.actionManager(data, callback=authenticate_cb, profile=profile)
self.host.action_manager(data, callback=authenticate_cb, profile=profile)
def getProfileNameCb(profile):
def get_profile_name_cb(profile):
if not profile:
# FIXME: this method is not handling manual mode correclty anymore
# must be thought to be handled asynchronously
self._autoconnect = False # manual mode
msg = _("Trying to plug an unknown profile key ({})".format(profile_key))
log.warning(msg)
self.host.showDialog(_("Profile plugging in error"), msg, "error")
self.host.show_dialog(_("Profile plugging in error"), msg, "error")
else:
self.host.launchAction(
self.host.action_launch(
C.AUTHENTICATE_PROFILE_ID, callback=authenticate_cb, profile=profile
)
def getProfileNameEb(failure):
def get_profile_name_eb(failure):
log.error("Can't retrieve profile name: {}".format(failure))
for profile_key in profile_keys:
self.host.bridge.profileNameGet(
profile_key, callback=getProfileNameCb, errback=getProfileNameEb
self.host.bridge.profile_name_get(
profile_key, callback=get_profile_name_cb, errback=get_profile_name_eb
)
def getParamError(self, __):
self.host.showDialog(_("Error"), _("Can't get profile parameter"), "error")
def get_param_error(self, __):
self.host.show_dialog(_("Error"), _("Can't get profile parameter"), "error")
## Helping methods ##
def _getErrorMessage(self, reason):
def _get_error_message(self, reason):
"""Return an error message corresponding to profile creation error
@param reason (str): reason as returned by profileCreate
@param reason (str): reason as returned by profile_create
@return (unicode): human readable error message
"""
if reason == "ConflictError":
@ -152,31 +152,31 @@ class QuickProfileManager(object):
message = _("Can't create profile ({})").format(reason)
return message
def _deleteProfile(self):
def _delete_profile(self):
"""Delete the currently selected profile"""
if self.current.profile:
self.host.bridge.asyncDeleteProfile(
self.current.profile, callback=self.refillProfiles
self.host.bridge.profile_delete_async(
self.current.profile, callback=self.refill_profiles
)
self.resetFields()
self.reset_fields()
## workflow methods (events occuring during the profiles selection) ##
# These methods must be called by the frontend at some point
def _onConnectProfiles(self):
def _on_connect_profiles(self):
"""Connect the profiles and start the main widget"""
if self._autoconnect:
self.host.showDialog(
self.host.show_dialog(
_("Internal error"),
_("You can't connect manually and automatically at the same time"),
"error",
)
return
self.updateConnectionParams()
profiles = self.getProfiles()
self.update_connection_params()
profiles = self.get_profiles()
if not profiles:
self.host.showDialog(
self.host.show_dialog(
_("No profile selected"),
_("You need to create and select at least one profile before connecting"),
"error",
@ -185,40 +185,40 @@ class QuickProfileManager(object):
# All profiles in the list are already validated, so we can plug them directly
self.host.plug_profiles(profiles)
def getConnectionParams(self, profile):
def get_connection_params(self, profile):
"""Get login and password and display them
@param profile: %(doc_profile)s
"""
self.host.bridge.asyncGetParamA(
self.host.bridge.param_get_a_async(
"JabberID",
"Connection",
profile_key=profile,
callback=self.setJID,
errback=self.getParamError,
callback=self.set_jid,
errback=self.get_param_error,
)
self.host.bridge.asyncGetParamA(
self.host.bridge.param_get_a_async(
"Password",
"Connection",
profile_key=profile,
callback=self.setPassword,
errback=self.getParamError,
callback=self.set_password,
errback=self.get_param_error,
)
def updateConnectionParams(self):
def update_connection_params(self):
"""Check if connection parameters have changed, and update them if so"""
if self.current.profile:
login = self.getJID()
login = self.get_jid()
password = self.getPassword()
if login != self.current.login and self.current.login is not None:
self.current.login = login
self.host.bridge.setParam(
self.host.bridge.param_set(
"JabberID", login, "Connection", profile_key=self.current.profile
)
log.info("login updated for profile [{}]".format(self.current.profile))
if password != self.current.password and self.current.password is not None:
self.current.password = password
self.host.bridge.setParam(
self.host.bridge.param_set(
"Password", password, "Connection", profile_key=self.current.profile
)
log.info(
@ -227,23 +227,23 @@ class QuickProfileManager(object):
## graphic updates (should probably be overriden in frontends) ##
def resetFields(self):
def reset_fields(self):
"""Set profile to None, and reset fields"""
self.current.profile = None
self.setJID("")
self.setPassword("")
self.set_jid("")
self.set_password("")
def refillProfiles(self):
def refill_profiles(self):
"""Rebuild the list of profiles"""
profiles = self.host.bridge.profilesListGet()
profiles = self.host.bridge.profiles_list_get()
profiles.sort()
self.setProfiles(profiles)
self.set_profiles(profiles)
## Method which must be implemented by frontends ##
# get/set data
def getProfiles(self):
def get_profiles(self):
"""Return list of selected profiles
Must be implemented by frontends
@ -251,11 +251,11 @@ class QuickProfileManager(object):
"""
raise NotImplementedError
def setProfiles(self, profiles):
def set_profiles(self, profiles):
"""Update the list of profiles"""
raise NotImplementedError
def getJID(self):
def get_jid(self):
"""Get current jid
Must be implemented by frontends
@ -271,7 +271,7 @@ class QuickProfileManager(object):
"""
raise NotImplementedError
def setJID(self, jid_):
def set_jid(self, jid_):
"""Set current jid
Must be implemented by frontends
@ -279,7 +279,7 @@ class QuickProfileManager(object):
"""
raise NotImplementedError
def setPassword(self, password):
def set_password(self, password):
"""Set current password
Must be implemented by frontends

View file

@ -22,7 +22,7 @@ from os.path import exists, splitext
from optparse import OptionParser
def getNewPath(path):
def get_new_path(path):
""" Check if path exists, and find a non existant path if needed """
idx = 2
if not exists(path):

View file

@ -68,7 +68,7 @@ class QuickWidgetsManager(object):
for widget in widget_instances:
yield widget
def getRealClass(self, class_):
def get_real_class(self, class_):
"""Return class registered for given class_
@param class_: subclass of QuickWidget
@ -86,20 +86,20 @@ class QuickWidgetsManager(object):
)
return cls
def getWidgetInstances(self, widget):
def get_widget_instances(self, widget):
"""Get all instance of a widget
This is a helper method which call getWidgets
This is a helper method which call get_widgets
@param widget(QuickWidget): retrieve instances of this widget
@return: iterator on widgets
"""
return self.getWidgets(widget.__class__, widget.target, widget.profiles)
return self.get_widgets(widget.__class__, widget.target, widget.profiles)
def getWidgets(self, class_, target=None, profiles=None, with_duplicates=True):
def get_widgets(self, class_, target=None, profiles=None, with_duplicates=True):
"""Get all subclassed widgets instances
@param class_: subclass of QuickWidget, same parameter as used in
[getOrCreateWidget]
[get_or_create_widget]
@param target: if not None, construct a hash with this target and filter
corresponding widgets
recreated widgets are handled
@ -109,14 +109,14 @@ class QuickWidgetsManager(object):
returned
@return: iterator on widgets
"""
class_ = self.getRealClass(class_)
class_ = self.get_real_class(class_)
try:
widgets_map = self._widgets[class_.__name__]
except KeyError:
return
else:
if target is not None:
filter_hash = str(class_.getWidgetHash(target, profiles))
filter_hash = str(class_.get_widget_hash(target, profiles))
else:
filter_hash = None
if filter_hash is not None:
@ -133,11 +133,11 @@ class QuickWidgetsManager(object):
# we only return the first widget of the list
break
def getWidget(self, class_, target=None, profiles=None):
def get_widget(self, class_, target=None, profiles=None):
"""Get a widget without creating it if it doesn't exist.
if several instances of widgets with this hash exist, the first one is returned
@param class_: subclass of QuickWidget, same parameter as used in [getOrCreateWidget]
@param class_: subclass of QuickWidget, same parameter as used in [get_or_create_widget]
@param target: target depending of the widget, usually a JID instance
@param profiles (unicode, iterable[unicode], None): profile(s) to use (may or may not be
used, depending of the widget class)
@ -146,17 +146,17 @@ class QuickWidgetsManager(object):
assert (target is not None) or (profiles is not None)
if profiles is not None and isinstance(profiles, str):
profiles = [profiles]
class_ = self.getRealClass(class_)
hash_ = class_.getWidgetHash(target, profiles)
class_ = self.get_real_class(class_)
hash_ = class_.get_widget_hash(target, profiles)
try:
return self._widgets[class_.__name__][hash_][0]
except KeyError:
return None
def getOrCreateWidget(self, class_, target, *args, **kwargs):
def get_or_create_widget(self, class_, target, *args, **kwargs):
"""Get an existing widget or create a new one when necessary
If the widget is new, self.host.newWidget will be called with it.
If the widget is new, self.host.new_widget will be called with it.
@param class_(class): class of the widget to create
@param target: target depending of the widget, usually a JID instance
@param args(list): optional args to create a new instance of class_
@ -164,22 +164,22 @@ class QuickWidgetsManager(object):
if 'profile' key is present, it will be popped and put in 'profiles'
if there is neither 'profile' nor 'profiles', None will be used for 'profiles'
if 'on_new_widget' is present it can have the following values:
C.WIDGET_NEW [default]: self.host.newWidget will be called on widget creation
[callable]: this method will be called instead of self.host.newWidget
C.WIDGET_NEW [default]: self.host.new_widget will be called on widget creation
[callable]: this method will be called instead of self.host.new_widget
None: do nothing
if 'on_existing_widget' is present it can have the following values:
C.WIDGET_KEEP [default]: return the existing widget
C.WIDGET_RAISE: raise WidgetAlreadyExistsError
C.WIDGET_RECREATE: create a new widget
if the existing widget has a "recreateArgs" method, it will be called with args list and kwargs dict
if the existing widget has a "recreate_args" method, it will be called with args list and kwargs dict
so the values can be completed to create correctly the new instance
[callable]: this method will be called with existing widget as argument, the widget to use must be returned
if 'force_hash' is present, the hash given in value will be used instead of the one returned by class_.getWidgetHash
if 'force_hash' is present, the hash given in value will be used instead of the one returned by class_.get_widget_hash
other keys will be used to instanciate class_ if the case happen (e.g. if type_ is present and class_ is a QuickChat subclass,
it will be used to create a new QuickChat instance).
@return: a class_ instance, either new or already existing
"""
cls = self.getRealClass(class_)
cls = self.get_real_class(class_)
## arguments management ##
_args = [self.host, target] + list(
@ -212,7 +212,7 @@ class QuickWidgetsManager(object):
try:
hash_ = _kwargs.pop("force_hash")
except KeyError:
hash_ = cls.getWidgetHash(target, _kwargs["profiles"])
hash_ = cls.get_widget_hash(target, _kwargs["profiles"])
## widget creation or retrieval ##
@ -227,17 +227,17 @@ class QuickWidgetsManager(object):
except KeyError:
widget = None
else:
widget.addTarget(target)
widget.add_target(target)
if widget is None:
# we need to create a new widget
log.debug(f"Creating new widget for target {target} {cls}")
widget = cls(*_args, **_kwargs)
widgets_map.setdefault(hash_, []).append(widget)
self.host.callListeners("widgetNew", widget)
self.host.call_listeners("widgetNew", widget)
if on_new_widget == C.WIDGET_NEW:
self.host.newWidget(widget)
self.host.new_widget(widget)
elif callable(on_new_widget):
on_new_widget(widget)
else:
@ -250,11 +250,11 @@ class QuickWidgetsManager(object):
raise WidgetAlreadyExistsError(hash_)
elif on_existing_widget == C.WIDGET_RECREATE:
try:
recreateArgs = widget.recreateArgs
recreate_args = widget.recreate_args
except AttributeError:
pass
else:
recreateArgs(_args, _kwargs)
recreate_args(_args, _kwargs)
widget = cls(*_args, **_kwargs)
widgets_map[hash_].append(widget)
log.debug("widget <{wid}> already exists, a new one has been recreated"
@ -274,22 +274,22 @@ class QuickWidgetsManager(object):
return widget
def deleteWidget(self, widget_to_delete, *args, **kwargs):
def delete_widget(self, widget_to_delete, *args, **kwargs):
"""Delete a widget instance
this method must be called by frontends when a widget is deleted
widget's onDelete method will be called before deletion, and deletion will be
widget's on_delete method will be called before deletion, and deletion will be
stopped if it returns False.
@param widget_to_delete(QuickWidget): widget which need to deleted
@param *args: extra arguments to pass to onDelete
@param *kwargs: extra keywords arguments to pass to onDelete
@param *args: extra arguments to pass to on_delete
@param *kwargs: extra keywords arguments to pass to on_delete
the extra arguments are not used by QuickFrontend, it's is up to
the frontend to use them or not.
following extra arguments are well known:
- "all_instances" can be used as kwarg, if it evaluate to True,
all instances of the widget will be deleted (if onDelete is
all instances of the widget will be deleted (if on_delete is
not returning False for any of the instance). This arguments
is not sent to onDelete methods.
is not sent to on_delete methods.
- "explicit_close" is used when the deletion is requested by
the user or a leave signal, "all_instances" is usually set at
the same time.
@ -299,26 +299,26 @@ class QuickWidgetsManager(object):
all_instances = kwargs.get('all_instances', False)
if all_instances:
for w in self.getWidgetInstances(widget_to_delete):
if w.onDelete(**kwargs) == False:
for w in self.get_widget_instances(widget_to_delete):
if w.on_delete(**kwargs) == False:
log.debug(
f"Deletion of {widget_to_delete} cancelled by widget itself")
return
else:
if widget_to_delete.onDelete(**kwargs) == False:
if widget_to_delete.on_delete(**kwargs) == False:
log.debug(f"Deletion of {widget_to_delete} cancelled by widget itself")
return
if self.host.selected_widget == widget_to_delete:
self.host.selected_widget = None
class_ = self.getRealClass(widget_to_delete.__class__)
class_ = self.get_real_class(widget_to_delete.__class__)
try:
widgets_map = self._widgets[class_.__name__]
except KeyError:
log.error("no widgets_map found for class {cls}".format(cls=class_))
return
widget_hash = str(class_.getWidgetHash(widget_to_delete.target,
widget_hash = str(class_.get_widget_hash(widget_to_delete.target,
widget_to_delete.profiles))
try:
widget_instances = widgets_map[widget_hash]
@ -342,7 +342,7 @@ class QuickWidgetsManager(object):
del widgets_map[widget_hash]
log.debug("All instances of {cls} with hash {widget_hash!r} have been deleted"
.format(cls=class_, widget_hash=widget_hash))
self.host.callListeners("widgetDeleted", widget_to_delete)
self.host.call_listeners("widgetDeleted", widget_to_delete)
class QuickWidget(object):
@ -368,17 +368,17 @@ class QuickWidget(object):
"""
self.host = host
self.targets = set()
self.addTarget(target)
self.add_target(target)
self.profiles = set()
self._sync = True
if isinstance(profiles, str):
self.addProfile(profiles)
self.add_profile(profiles)
elif profiles is None:
if not self.PROFILES_ALLOW_NONE:
raise ValueError("profiles can't have a value of None")
else:
for profile in profiles:
self.addProfile(profile)
self.add_profile(profile)
if not self.profiles:
raise ValueError("no profile found, use None for no profile classes")
@ -402,7 +402,7 @@ class QuickWidget(object):
@property
def widget_hash(self):
"""Return quick widget hash"""
return self.getWidgetHash(self.target, self.profiles)
return self.get_widget_hash(self.target, self.profiles)
# synchronisation state
@ -429,14 +429,14 @@ class QuickWidget(object):
# target/profile
def addTarget(self, target):
def add_target(self, target):
"""Add a target if it doesn't already exists
@param target: target to add
"""
self.targets.add(target)
def addProfile(self, profile):
def add_profile(self, profile):
"""Add a profile is if doesn't already exists
@param profile: profile to add
@ -448,7 +448,7 @@ class QuickWidget(object):
# widget identitication
@staticmethod
def getWidgetHash(target, profiles):
def get_widget_hash(target, profiles):
"""Return the hash associated with this target for this widget class
some widget classes can manage several target on the same instance
@ -465,7 +465,7 @@ class QuickWidget(object):
# widget life events
def onDelete(self, *args, **kwargs):
def on_delete(self, *args, **kwargs):
"""Called when a widget is being deleted
@return (boot, None): False to cancel deletion
@ -473,6 +473,6 @@ class QuickWidget(object):
"""
return True
def onSelected(self):
def on_selected(self):
"""Called when host.selected_widget is this instance"""
pass