diff frontends/src/primitivus/profile_manager.py @ 1367:f71a0fc26886

merged branch frontends_multi_profiles
author Goffi <goffi@goffi.org>
date Wed, 18 Mar 2015 10:52:28 +0100
parents 948dc273ad93
children 069ad98b360d
line wrap: on
line diff
--- a/frontends/src/primitivus/profile_manager.py	Thu Feb 05 11:59:26 2015 +0100
+++ b/frontends/src/primitivus/profile_manager.py	Wed Mar 18 10:52:28 2015 +0100
@@ -18,29 +18,28 @@
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 from sat.core.i18n import _
+from sat.core import log as logging
+log = logging.getLogger(__name__)
+from sat_frontends.quick_frontend.quick_profile_manager import QuickProfileManager
 from sat_frontends.primitivus.constants import Const as C
+from sat_frontends.primitivus.keys import action_key_map as a_key
+from urwid_satext import sat_widgets
 import urwid
-from urwid_satext.sat_widgets import AdvancedEdit, Password, List, InputDialog, ConfirmDialog, Alert
-from sat_frontends.primitivus.keys import action_key_map as a_key
 
 
-class ProfileManager(urwid.WidgetWrap):
+class ProfileManager(QuickProfileManager, urwid.WidgetWrap):
 
-    def __init__(self, host):
-        self.host = host
-        #profiles list
-        profiles = self.host.bridge.getProfilesList()
-        profiles.sort()
+    def __init__(self, host, autoconnect=None):
+        QuickProfileManager.__init__(self, host, autoconnect)
 
         #login & password box must be created before list because of onProfileChange
-        self.login_wid = AdvancedEdit(_('Login:'), align='center')
-        self.pass_wid = Password(_('Password:'), align='center')
+        self.login_wid = sat_widgets.AdvancedEdit(_('Login:'), align='center')
+        self.pass_wid = sat_widgets.Password(_('Password:'), align='center')
 
-        self.selected_profile = None  # allow to reselect the previous selection until the profile is authenticated
-        style = ['single']
-        if self.host.options.profile:
-            style.append('no_first_select')
-        self.list_profile = List(profiles, style=style, align='center', on_change=self.onProfileChange)
+        style = ['no_first_select']
+        profiles = host.bridge.getProfilesList()
+        profiles.sort()
+        self.list_profile = sat_widgets.List(profiles, style=style, align='center', on_change=self.onProfileChange)
 
         #new & delete buttons
         buttons = [urwid.Button(_("New"), self.onNewProfile),
@@ -51,15 +50,18 @@
         divider = urwid.Divider('-')
 
         #connect button
-        connect_button = urwid.Button(_("Connect"), self.onConnectProfile)
+        connect_button = sat_widgets.CustomButton(_("Connect"), self.onConnectProfiles, align='center')
 
         #we now build the widget
-        list_walker = urwid.SimpleFocusListWalker([buttons_flow,self.list_profile,divider,self.login_wid, self.pass_wid, connect_button])
+        list_walker = urwid.SimpleFocusListWalker([buttons_flow,self.list_profile, divider, self.login_wid, self.pass_wid, connect_button])
         frame_body = urwid.ListBox(list_walker)
         frame = urwid.Frame(frame_body,urwid.AttrMap(urwid.Text(_("Profile Manager"),align='center'),'title'))
         self.main_widget = urwid.LineBox(frame)
         urwid.WidgetWrap.__init__(self, self.main_widget)
 
+        self.go(autoconnect)
+
+
     def keypress(self, size, key):
         if key == a_key['APP_QUIT']:
             self.host.onExit()
@@ -80,117 +82,96 @@
                     return
         return super(ProfileManager, self).keypress(size, key)
 
-    def __refillProfiles(self):
-        """Update the list of profiles"""
-        profiles = self.host.bridge.getProfilesList()
-        profiles.sort()
-        self.list_profile.changeValues(profiles)
-
     def cancelDialog(self, button):
         self.host.removePopUp()
 
     def newProfile(self, button, edit):
         """Create the profile"""
         name = edit.get_edit_text()
-        self.host.bridge.asyncCreateProfile(name, callback=lambda: self._newProfileCreated(name), errback=self._profileCreationFailure)
+        self.host.bridge.asyncCreateProfile(name, callback=lambda: self.newProfileCreated(name), errback=self.profileCreationFailure)
 
-    def _newProfileCreated(self, name):
-        self.__refillProfiles()
-        #We select the profile created in the list
-        self.list_profile.selectValue(name)
+    def newProfileCreated(self, profile):
         self.host.removePopUp()
+        self.refillProfiles()
+        self.list_profile.selectValue(profile)
+        self.current.profile=profile
+        self.getConnectionParams(profile)
         self.host.redraw()
 
-    def _profileCreationFailure(self, reason):
+    def profileCreationFailure(self, reason):
         self.host.removePopUp()
-        if reason == "ConflictError":
-            message = _("A profile with this name already exists")
-        elif reason == "CancelError":
-            message = _("Profile creation cancelled by backend")
-        else:
-            message = _("Unknown reason (%s)") % reason
-        popup = Alert(_("Can't create profile"), message, ok_cb=self.host.removePopUp)
-        self.host.showPopUp(popup)
+        message = self._getErrorMessage(reason)
+        self.alert(_("Can't create profile"), message)
 
     def deleteProfile(self, button):
-        profile_name = self.list_profile.getSelectedValue()
-        if profile_name:
-            self.host.bridge.asyncDeleteProfile(profile_name, callback=self.__refillProfiles)
+        self._deleteProfile()
         self.host.removePopUp()
 
     def onNewProfile(self, e):
-        pop_up_widget = InputDialog(_("New profile"), _("Please enter a new profile name"), cancel_cb=self.cancelDialog, ok_cb=self.newProfile)
+        pop_up_widget = sat_widgets.InputDialog(_("New profile"), _("Please enter a new profile name"), cancel_cb=self.cancelDialog, ok_cb=self.newProfile)
         self.host.showPopUp(pop_up_widget)
 
     def onDeleteProfile(self, e):
-        pop_up_widget = ConfirmDialog(_("Are you sure you want to delete the profile %s ?") % self.list_profile.getSelectedValue(), no_cb=self.cancelDialog, yes_cb=self.deleteProfile)
-        self.host.showPopUp(pop_up_widget)
+        if self.current.profile:
+            pop_up_widget = sat_widgets.ConfirmDialog(_("Are you sure you want to delete the profile {} ?").format(self.current.profile), no_cb=self.cancelDialog, yes_cb=self.deleteProfile)
+            self.host.showPopUp(pop_up_widget)
 
-    def getXMPPParams(self, profile):
-        """This is called from PrimitivusApp.launchAction when the profile has been authenticated.
+    def onConnectProfiles(self, button):
+        """Connect the profiles and start the main widget
 
-        @param profile: %(doc_profile)s
+        @param button: the connect button
         """
-        def setJID(jabberID):
-            self.login_wid.set_edit_text(jabberID)
-            self.host.redraw()
+        self._onConnectProfiles()
+
+    def resetFields(self):
+        """Set profile to None, and reset fields"""
+        super(ProfileManager, self).resetFields()
+        self.list_profile.unselectAll(invisible=True)
+
+    def setProfiles(self, profiles):
+        """Update the list of profiles"""
+        self.list_profile.changeValues(profiles)
+        self.host.redraw()
+
+    def getProfiles(self):
+        return self.list_profile.getSelectedValues()
 
-        def setPassword(password):
-            self.pass_wid.set_edit_text(password)
-            self.host.redraw()
+    def getJID(self):
+        return self.login_wid.get_edit_text()
+
+    def getPassword(self):
+        return self.pass_wid.get_edit_text()
 
-        self.list_profile.selectValue(profile, move_focus=False)
-        self.selected_profile = profile
-        self.host.bridge.asyncGetParamA("JabberID", "Connection", profile_key=profile, callback=setJID, errback=self.getParamError)
-        self.host.bridge.asyncGetParamA("Password", "Connection", profile_key=profile, callback=setPassword, errback=self.getParamError)
+    def setJID(self, jid_):
+        self.login_wid.set_edit_text(jid_)
+        self.current.login = jid_
+        self.host.redraw() # FIXME: redraw should be avoided
+
+    def setPassword(self, password):
+        self.pass_wid.set_edit_text(password)
+        self.current.password = password
+        self.host.redraw()
+
+    def alert(self, title, message):
+        popup = sat_widgets.Alert(title, message, ok_cb=self.host.removePopUp)
+        self.host.showPopUp(popup)
 
     def onProfileChange(self, list_wid):
         """This is called when a profile is selected in the profile list.
 
         @param list_wid: the List widget who sent the event
         """
-        profile_name = list_wid.getSelectedValue()
-        if not profile_name or profile_name == self.selected_profile:
-            return  # avoid infinite loop
-        if self.selected_profile:
-            list_wid.selectValue(self.selected_profile, move_focus=False)
-        else:
-            list_wid.unselectAll(invisible=True)
-        self.host.redraw()
-        self.host.profile = profile_name  # FIXME: EXTREMELY DIRTY, needed for sat_frontends.tools.xmlui.XMLUI._xmluiLaunchAction
-        self.host.launchAction(C.AUTHENTICATE_PROFILE_ID, {'caller': 'profile_manager'}, profile_key=profile_name)
+        self.updateConnectionParams()
+        focused = list_wid.focus
+        selected = focused.getState()
+        if not selected: # profile was just unselected
+            return
+        focused.setState(False, invisible=True) # we don't want the widget to be selected until we are sure we can access it
+        def authenticate_cb(callback_id, data, profile):
+            if C.bool(data['validated']):
+                self.current.profile = profile
+                focused.setState(True, invisible=True)
+                self.getConnectionParams(profile)
+                self.host.redraw()
+        self.host.launchAction(C.AUTHENTICATE_PROFILE_ID, callback=authenticate_cb, profile=focused.text)
 
-    def onConnectProfile(self, button):
-        profile_name = self.list_profile.getSelectedValue()
-        assert(profile_name == self.selected_profile)  # if not, there's a bug somewhere...
-        if not profile_name:
-            pop_up_widget = Alert(_('No profile selected'), _('You need to create and select a profile before connecting'), ok_cb=self.cancelDialog)
-            self.host.showPopUp(pop_up_widget)
-        elif profile_name[0] == '@':
-            pop_up_widget = Alert(_('Bad profile name'), _("A profile name can't start with a @"), ok_cb=self.cancelDialog)
-            self.host.showPopUp(pop_up_widget)
-        else:
-            profile = self.host.bridge.getProfileName(profile_name)
-            assert(profile)
-            #TODO: move this to quick_app
-            self.host.bridge.asyncGetParamA("JabberID", "Connection", profile_key=profile,
-                                            callback=lambda old_jid: self.__old_jidReceived(old_jid, profile), errback=self.getParamError)
-
-    def __old_jidReceived(self, old_jid, profile):
-        self.host.bridge.asyncGetParamA("Password", "Connection", profile_key=profile,
-                                        callback=lambda old_pass: self.__old_passReceived(old_jid, old_pass, profile), errback=self.getParamError)
-
-    def __old_passReceived(self, old_jid, old_pass, profile):
-        """Check if we have new jid/pass, save them if it is the case, and plug profile"""
-        new_jid = self.login_wid.get_edit_text()
-        new_pass = self.pass_wid.get_edit_text()
-
-        if old_jid != new_jid:
-            self.host.bridge.setParam("JabberID", new_jid, "Connection", profile_key=profile)
-        if old_pass != new_pass:
-            self.host.bridge.setParam("Password", new_pass, "Connection", profile_key=profile)
-        self.host.plug_profile(profile)
-
-    def getParamError(self, ignore):
-        popup = Alert("Error", _("Can't get profile parameter"), ok_cb=self.host.removePopUp)
-        self.host.showPopUp(popup)