changeset 210:3092f6b1710c

browser side: make the OK button title for group selector configureable + few "cosmetic" changes (PEP 8...) fix bug 15 fix bug 33
author souliane <souliane@mailoo.org>
date Fri, 06 Sep 2013 15:40:33 +0200
parents 4564c7bc06a7
children 49920d76aa6a
files browser_side/base_widget.py browser_side/dialog.py browser_side/menu.py browser_side/panels.py libervia.py
diffstat 5 files changed, 81 insertions(+), 75 deletions(-) [+]
line wrap: on
line diff
--- a/browser_side/base_widget.py	Fri Jun 28 00:06:31 2013 +0200
+++ b/browser_side/base_widget.py	Fri Sep 06 15:40:33 2013 +0200
@@ -155,9 +155,10 @@
         self.addStyleName('widgetHeader')
         LiberviaDragWidget.__init__(self, "", "WIDGET", parent)
 
+
 class LiberviaWidget(DropCell, VerticalPanel, ClickHandler):
     """Libervia's widget which can replace itself with a dropped widget on DnD"""
-    
+
     def __init__(self, host, title='', selectable=False):
         """Init the widget
         @param host: SatWebFrontend object
@@ -258,11 +259,11 @@
             rowspan_setter.setValue(1)
             width_setter.setValue(0)
             height_setter.setValue(0)
-        
+
         reset_bt = Button("Reset", onReset)
         body.add(reset_bt)
         body.setCellHorizontalAlignment(reset_bt, HasAlignment.ALIGN_CENTER)
-        
+
         _dialog = dialog.GenericDialog("Widget setting", body)
         _dialog.show()
 
--- a/browser_side/dialog.py	Fri Jun 28 00:06:31 2013 +0200
+++ b/browser_side/dialog.py	Fri Sep 06 15:40:33 2013 +0200
@@ -65,8 +65,8 @@
         button_panel.add(Button("Cancel", self.onCancel))
         content.add(button_panel)
         self.setHTML(text)
-        self.setWidget(content)	
-    
+        self.setWidget(content)
+
     def onChange(self, sender):
         if self.nb_contact:
             if len(self.contacts_list.getSelectedValues()) == self.nb_contact:
@@ -111,8 +111,8 @@
         button_panel.add(Button("Cancel", self.onCancel))
         content.add(button_panel)
         self.setHTML(title)
-        self.setWidget(content)	
-    
+        self.setWidget(content)
+
     def onConfirm(self, sender):
         self.hide()
         self.callback(True)
@@ -121,15 +121,17 @@
         self.hide()
         self.callback(False)
 
+
 class ConfirmDialog(GenericConfirmDialog):
 
     def __init__(self, callback, text='Are you sure ?', title='Confirmation'):
-        GenericConfirmDialog.__init__(self,[HTML(text)], callback, title)
+        GenericConfirmDialog.__init__(self, [HTML(text)], callback, title)
+
 
 class GenericDialog(DialogBox):
     """Dialog which just show a widget and a close button"""
 
-    def __init__(self, title, main_widget, callback = None, options = None):
+    def __init__(self, title, main_widget, callback=None, options=None):
         """Simple notice dialog box
         @param title: HTML put in the header
         @param main_widget: widget put in the body
@@ -199,7 +201,8 @@
 
 class GroupSelector(DialogBox):
     
-    def __init__(self, top_widgets, initial_groups, selected_groups, ok_cb = None, cancel_cb = None):
+    def __init__(self, top_widgets, initial_groups, selected_groups,
+                 ok_title, ok_cb = None, cancel_cb = None):
         DialogBox.__init__(self, centered = True)
         main_panel = VerticalPanel()
         self.ok_cb = ok_cb
@@ -226,7 +229,7 @@
         main_panel.add(add_group_panel)
         
         button_panel = HorizontalPanel()
-        button_panel.add(Button("Add", self.onOK))
+        button_panel.add(Button(ok_title, self.onOK))
         button_panel.add(Button("Cancel", self.onCancel))
         main_panel.add(button_panel)
         
@@ -261,12 +264,12 @@
         sender.setText('')
         self.list_box.setItemSelected(self.list_box.getItemCount()-1, "selected")
 
+
 class WheelTextBox(TextBox, MouseWheelHandler):
 
     def __init__(self, *args, **kwargs):
         TextBox.__init__(self, *args, **kwargs)
         MouseWheelHandler.__init__(self)
-    
 
 
 class IntSetter(HorizontalPanel):
--- a/browser_side/menu.py	Fri Jun 28 00:06:31 2013 +0200
+++ b/browser_side/menu.py	Fri Sep 06 15:40:33 2013 +0200
@@ -147,9 +147,9 @@
         menu_help = MenuBar(vertical=True)
         menu_help.addItem("Social contract", MenuCmd(self, "onSocialContract"))
         menu_help.addItem("About", MenuCmd(self, "onAbout"))
-        
+    
         menu_settings = MenuBar(vertical=True)
-        #menu_settings.addItem("Parameters", MenuCmd(self, "onParameters"))
+        menu_settings.addItem("Parameters", MenuCmd(self, "onParameters"))
         menu_settings.addItem("Upload avatar", MenuCmd(self, "onAvatarUpload")) # XXX: temporary, will change when a full profile will be managed in SàT
         
         menubar = LiberviaMenuBar()
@@ -220,7 +220,8 @@
         label = Label("new contact identifier (JID):")
         edit.setText('@libervia.org')
         edit.setWidth('100%')
-        _dialog = dialog.GroupSelector([label, edit], self.host.contact_panel.getGroups(), [], addContactCb)
+        _dialog = dialog.GroupSelector([label, edit], self.host.contact_panel.getGroups(), [],
+                                       "Add", addContactCb)
         _dialog.setHTML('Adding contact')
         _dialog.show()
 
@@ -243,7 +244,8 @@
         _jid = _contacts_list.getValue(_contacts_list.getSelectedIndex())
         _selected_groups = self.host.contact_panel.getContactGroups(_jid)
         _dialog = dialog.GroupSelector([Label('Which contact do you want to update ?'), _contacts_list],
-                                       self.host.contact_panel.getGroups(), _selected_groups, updateContactCb)
+                                       self.host.contact_panel.getGroups(), _selected_groups,
+                                       "Update", updateContactCb)
         _dialog.setHTML('Updating contact')
         _dialog.show()
 
@@ -329,7 +331,6 @@
             body.setCloseCb(_dialog.close) 
             _dialog.setSize('80%', '80%')
             _dialog.show()
-
         self.host.bridge.call('getParamsUI', gotParams)
 
     def onAvatarUpload(self):
@@ -337,6 +338,4 @@
         _dialog = dialog.GenericDialog("Avatar upload", body, options=['NO_CLOSE'])
         body.setCloseCb(_dialog.close)
         _dialog.setSize('40%', '40%')
-        
         _dialog.show()
-
--- a/browser_side/panels.py	Fri Jun 28 00:06:31 2013 +0200
+++ b/browser_side/panels.py	Fri Sep 06 15:40:33 2013 +0200
@@ -48,6 +48,7 @@
 from pyjamas import Window
 from __pyjamas__ import doc
 
+
 class UniBoxPanel(SimplePanel):
     """Panel containing the UniBox"""
 
@@ -58,13 +59,14 @@
         self.unibox.setWidth('100%')
         self.add(self.unibox)
 
+
 class UniBox(TextArea, MouseHandler): #AutoCompleteTextBox):
     """This text box is used as a main typing point, for message, microblog, etc"""
 
     def __init__(self, host):
         TextArea.__init__(self)
         #AutoCompleteTextBox.__init__(self)
-        self.__size = (0,0)
+        self.__size = (0, 0)
         self._popup = None
         self._timer = Timer(notify=self._timeCb)
         self.host = host
@@ -85,7 +87,6 @@
         except KeyError:
             print "WARNING: trying to remove an unknown key"
 
-
     def showWarning(self, target_data):
         target_hook, _type, msg = target_data
         if _type == "NONE":
@@ -115,7 +116,7 @@
             self._popup.addStyleName(style)
 
         left = 0
-        top  = 0 #max(0, self.getAbsoluteTop() - contents.getOffsetHeight() - 2)
+        top = 0 #max(0, self.getAbsoluteTop() - contents.getOffsetHeight() - 2)
         self._popup.setPopupPosition(left, top)
         self._popup.show()
 
@@ -221,15 +222,16 @@
         #XXX: fixed directly on pyjamas, if the patch is accepted, no need to walk around this
         return AutoCompleteTextBox.complete(self)"""
 
+
 class MicroblogItem():
     #XXX: should be moved in a separated module
 
     def __init__(self, data):
         self.id = data['id']
-        self.type = data.get('type','main_item')
+        self.type = data.get('type', 'main_item')
         self.content = data['content']
         self.author = data['author']
-        self.timestamp = float(data.get('timestamp',0)) #XXX: int doesn't work here
+        self.timestamp = float(data.get('timestamp', 0)) #XXX: int doesn't work here
         self.comments = data.get('comments', False)
         if self.comments:
             try:
@@ -244,6 +246,7 @@
             self.node = data["node"]
             self.hash = (self.service, self.node)
 
+
 class MicroblogEntry(SimplePanel, ClickHandler):
 
     def __init__(self, blog_panel, mblog_entry):
@@ -334,7 +337,7 @@
         else:
             # we only accept one group at the moment
             # FIXME: manage several groups
-            return ("GROUP", self.warning_msg_group %  self.accepted_groups[0])
+            return ("GROUP", self.warning_msg_group % self.accepted_groups[0])
 
     def onTextEntered(self, text):
         if self.selected_entry:
@@ -383,7 +386,7 @@
             mblog_item = MicroblogItem(mblog)
             self.addEntry(mblog_item)
 
-    def _chronoInsert(self, vpanel, entry, reverse = True):
+    def _chronoInsert(self, vpanel, entry, reverse=True):
         """ Insert an entry in chronological order
         @param vpanel: VerticalPanel instance
         @param entry: MicroblogEntry
@@ -395,7 +398,7 @@
 
         for child in vpanel.children:
             if not isinstance(child, MicroblogEntry):
-                idx+=1
+                idx += 1
                 continue
             if reverse:
                 if child.timestamp < entry.timestamp:
@@ -403,7 +406,7 @@
             else:
                 if child.timestamp > entry.timestamp:
                     break
-            idx+=1
+            idx += 1
 
         vpanel.insert(entry, idx)
 
@@ -455,7 +458,6 @@
             entry.addStyleName('selected_entry')
         self.selected_entry = entry
 
-
     def updateValue(self, type, jid, value):
         """Update a jid value in entries
         @param type: one of 'avatar', 'nick'
@@ -467,7 +469,7 @@
                     child.updateAvatar(value)
                 elif isinstance(child, VerticalPanel):
                     updateVPanel(child)
-        if type=='avatar':
+        if type == 'avatar':
             updateVPanel(self.vpanel)
 
     def setAcceptedGroup(self, group):
@@ -490,6 +492,7 @@
                 return True
         return False
 
+
 class StatusPanel(HTMLPanel, ClickHandler):
     def __init__(self, host, status=''):
         self.host = host
@@ -500,7 +503,7 @@
         self.addClickListener(self)
 
     def __getContent(self):
-        return "<span class='status'>%(status)s</span>" % {'status':html_sanitize(self.status)}
+        return "<span class='status'>%(status)s</span>" % {'status': html_sanitize(self.status)}
 
     def changeStatus(self, new_status):
         self.status = new_status or '&nbsp;'
@@ -510,6 +513,7 @@
         #As status is the default target of uniBar, we don't want to select anything if click on it
         self.host.setSelected(None)
 
+
 class ChatText(HTMLPanel):
 
     def __init__(self, timestamp, nick, mymess, msg):
@@ -518,13 +522,14 @@
         if mymess:
             _msg_class.append("chat_text_mymess")
         HTMLPanel.__init__(self, "<span class='chat_text_timestamp'>%(timestamp)s</span> <span class='chat_text_nick'>%(nick)s</span> <span class='%(msg_class)s'>%(msg)s</span>" %
-            {"timestamp": _date.strftime("%H:%M"),
-            "nick": "[%s]" % html_sanitize(nick),
-            "msg_class": ' '.join(_msg_class),
-            "msg": html_sanitize(msg)}
-            )
+                           {"timestamp": _date.strftime("%H:%M"),
+                            "nick": "[%s]" % html_sanitize(nick),
+                            "msg_class": ' '.join(_msg_class),
+                            "msg": html_sanitize(msg)}
+                           )
         self.setStyleName('chatText')
 
+
 class Occupant(HTML):
     """Occupant of a MUC room"""
 
@@ -535,6 +540,7 @@
     def __str__(self):
         return self.nick
 
+
 class OccupantsList(AbsolutePanel):
     """Panel user to show occupants of a room"""
 
@@ -558,6 +564,7 @@
         self.occupants_list.clear()
         AbsolutePanel.clear(self)
 
+
 class ChatPanel(base_widget.LiberviaWidget):
 
     def __init__(self, host, target, type_='one2one'):
@@ -565,9 +572,9 @@
         @param host: SatWebFrontend instance
         @param target: entity (JID) with who we have a conversation (contact's jid for one 2 one chat, or MUC room)
         @param type: one2one for simple conversation, group for MUC"""
-        base_widget.LiberviaWidget.__init__(self, host, target.bare, selectable = True)
+        base_widget.LiberviaWidget.__init__(self, host, target.bare, selectable=True)
         self.vpanel = VerticalPanel()
-        self.vpanel.setSize('100%','100%')
+        self.vpanel.setSize('100%', '100%')
         self.type = type_
         self.nick = None
         if not target:
@@ -623,7 +630,7 @@
         return ("ONE2ONE" if self.type == "one2one" else "GROUP", msg)
 
     def onTextEntered(self, text):
-        mess_type = "groupchat" if self.type=='group' else "chat"
+        mess_type = "groupchat" if self.type == 'group' else "chat"
         self.host.bridge.call('sendMessage', None, str(self.target), text, '', mess_type)
 
     def onQuit(self):
@@ -631,7 +638,6 @@
         if self.type == 'group':
             self.host.bridge.call('mucLeave', None, self.target.bare)
 
-
     def setUserNick(self, nick):
         """Set the nick of the user, usefull for e.g. change the color of the user"""
         self.nick = nick
@@ -675,27 +681,26 @@
             _wid.setStyleName('chatTextInfo')
         self.content.add(_wid)
 
-
     def printMessage(self, from_jid, msg, timestamp=None):
         """Print message in chat window. Must be implemented by child class"""
-        _jid=JID(from_jid)
-        nick = _jid.node if self.type=='one2one' else _jid.resource
-        mymess = _jid.resource == self.nick if self.type == "group" else  _jid.bare == self.host.whoami.bare #mymess = True if message comes from local user
+        _jid = JID(from_jid)
+        nick = _jid.node if self.type == 'one2one' else _jid.resource
+        mymess = _jid.resource == self.nick if self.type == "group" else _jid.bare == self.host.whoami.bare #mymess = True if message comes from local user
         if msg.startswith('/me '):
-            self.printInfo('* %s %s' % (nick, msg[4:]),type='me')
+            self.printInfo('* %s %s' % (nick, msg[4:]), type='me')
             return
         self.content.add(ChatText(timestamp, nick, mymess, msg))
         self.content_scroll.scrollToBottom()
 
     def startGame(self, game_type, referee, players):
         """Configure the chat window to start a game"""
-        if game_type=="Tarot":
+        if game_type == "Tarot":
             if hasattr(self, "tarot_panel"):
                 return
             self.tarot_panel = CardPanel(self, referee, players, self.nick)
             self.vpanel.insert(self.tarot_panel, 0)
             self.vpanel.setCellHeight(self.tarot_panel, self.tarot_panel.getHeight())
-        elif game_type=="RadioCol":
+        elif game_type == "RadioCol":
             #XXX: We can have double panel if we join quickly enough to have the group chat start signal
             #     on invitation + the one triggered on room join
             if hasattr(self, "radiocol_panel"):
@@ -707,11 +712,12 @@
     def getGame(self, game_type):
         """Return class managing the game type"""
         #TODO: check that the game is launched, and manage errors
-        if game_type=="Tarot":
+        if game_type == "Tarot":
             return self.tarot_panel
-        elif game_type=="RadioCol":
+        elif game_type == "RadioCol":
             return self.radiocol_panel
 
+
 class WebPanel(base_widget.LiberviaWidget):
     """ (mini)browser like widget """
 
@@ -722,7 +728,7 @@
         base_widget.LiberviaWidget.__init__(self, host)
         self._vpanel = VerticalPanel()
         self._vpanel.setSize('100%', '100%')
-        self._url = dialog.ExtTextBox(enter_cb = self.onUrlClick)
+        self._url = dialog.ExtTextBox(enter_cb=self.onUrlClick)
         self._url.setText(url or "")
         self._url.setWidth('100%')
         hpanel = HorizontalPanel()
@@ -743,10 +749,11 @@
     def onUrlClick(self, sender):
         self._frame.setUrl(self._url.getText())
 
+
 class MainPanel(AbsolutePanel):
 
     def __init__(self, host):
-        self.host=host
+        self.host = host
         AbsolutePanel.__init__(self)
 
         #menu
@@ -773,7 +780,7 @@
         self.tab_panel.add(self.discuss_panel, "Discussions")
         self.tab_panel.selectTab(0)
 
-        header=AbsolutePanel()
+        header = AbsolutePanel()
         header.add(menu)
         header.add(unibox_panel)
         header.add(status)
@@ -802,5 +809,4 @@
         else:
             tab_bar_h = _elts.item(0).offsetHeight
         ideal_height = Window.getClientHeight() - tab_bar_h
-        self.setHeight("%s%s" % (ideal_height, "px"));
-
+        self.setHeight("%s%s" % (ideal_height, "px"))
--- a/libervia.py	Fri Jun 28 00:06:31 2013 +0200
+++ b/libervia.py	Fri Sep 06 15:40:33 2013 +0200
@@ -69,7 +69,7 @@
             del self.cb[request_info.id]
             if request_info.id in self.eb:
                 del self.eb[request_info.id]
-        
+    
     def onRemoteError(self, code, errobj, request_info):
         """def dump(obj):
             print "\n\nDUMPING %s\n\n" % obj
@@ -114,12 +114,12 @@
         self.retry_delay = self.RETRY_BASE_DELAY 
         LiberviaJsonProxy.__init__(self, "/json_signal_api",
                         ["getSignals"])
-    
+
     def onRemoteResponse(self, response, request_info):
         self.retry_delay = self.RETRY_BASE_DELAY 
         LiberviaJsonProxy.onRemoteResponse(self, response, request_info)
-    
-    
+
+
     def onRemoteError(self, code, errobj, request_info):
         if errobj['message'] == 'Empty Response':
             Window.getLocation().reload() # XXX: reset page in case of session ended.
@@ -187,12 +187,12 @@
 
         if selected == widget:
             return
-        
+
         if selected:
             selected.removeStyleName('selected_widget')
-        
+    
         widgets_panel.selected = widget
-        
+    
         if widget:
             widgets_panel.selected.addStyleName('selected_widget')
 
@@ -227,7 +227,7 @@
         def avatarError(error_data):
             # The jid is maybe not in our roster, we ask for the VCard
             self.bridge.call("getCard", None, jid_str)
-        
+    
         if jid_str not in self.avatars_cache:
             self.bridge.call('getEntityData', (dataReceived, avatarError), jid_str, ['avatar'])
             self.avatars_cache[jid_str] = "/media/misc/empty_avatar"
@@ -242,7 +242,7 @@
             self.libervia_widgets.remove(wid)
         except KeyError:
             print ('WARNING: trying to remove a non registered Widget:', wid)
-    
+
     def setUniBox(self, unibox):
         """register the unibox widget"""
         self.uni_box = unibox
@@ -281,13 +281,12 @@
         if self._register_box:
             self._register_box.hide()
             del self._register_box # don't work if self._register_box is None
-        
+
         #it's time to fill the page
         self.bridge.call('getContacts', self._getContactsCB)
         self.bridge_signals.call('getSignals', self._getSignalsCB)
         #We want to know our own jid
         self.bridge.call('getProfileJid', self._getProfileJidCB)
-        
 
     def _getContactsCB(self, contacts_data):
         for contact in contacts_data:
@@ -354,7 +353,7 @@
                     _groups=None
                 mblog_entry = MicroblogItem(mblog)
                 self.mblog_cache.append((_groups, mblog_entry))
-        
+    
         if len(self.mblog_cache) > MAX_MBLOG_CACHE:
             del self.mblog_cache[0:len(self.mblog_cache-MAX_MBLOG_CACHE)]
         for lib_wid in self.libervia_widgets:
@@ -380,7 +379,7 @@
                     self.bridge.call('getMassiveLastMblogs', lib_wid.massiveInsert, 'ALL', [], 10)
                 else:
                     self.bridge.call('getMassiveLastMblogs', lib_wid.massiveInsert, 'GROUP', lib_wid.accepted_groups, 10)
-        
+    
         #we ask for our own microblogs:
         self.bridge.call('getMassiveLastMblogs', self._ownBlogsFills, 'JID', [self.whoami.bare], 10)
 
@@ -399,7 +398,7 @@
             else:
                 _groups=None
             mblog_entry = MicroblogItem(data)
-            
+        
             for lib_wid in self.libervia_widgets:
                 if isinstance(lib_wid, panels.MicroblogPanel):
                     self.addBlogEntry(lib_wid, sender, _groups, mblog_entry) 
@@ -448,7 +447,7 @@
             #The message has not been showed, we must indicate it
             other = _to if _from.bare == self.whoami.bare else _from
             self.contact_panel.setContactMessageWaiting(other.bare, True)
-            
+        
     def _presenceUpdateCb(self, entity, show, priority, statuses):
         _entity = JID(entity)
         #XXX: QnD way to get our status
@@ -480,7 +479,7 @@
         for lib_wid in self.libervia_widgets:
             if isinstance(lib_wid,panels.ChatPanel) and lib_wid.type == 'group' and lib_wid.target.bare == room_jid_s:
                 lib_wid.userLeft(user_nick, user_data)
-        
+    
     def _tarotGameStartedCb(self, room_jid_s, referee, players):
         print ("Tarot Game Started \o/")
         for lib_wid in self.libervia_widgets:
@@ -496,13 +495,13 @@
         for lib_wid in self.libervia_widgets:
             if isinstance(lib_wid,panels.ChatPanel) and lib_wid.type == 'group' and lib_wid.target.bare == room_jid_s:
                 lib_wid.startGame("RadioCol", referee)
-    
+
     def _radioColGenericCb(self, event_name, room_jid_s, args):
         for lib_wid in self.libervia_widgets:
             if isinstance(lib_wid,panels.ChatPanel) and lib_wid.type == 'group' and lib_wid.target.bare == room_jid_s:
                 getattr(lib_wid.getGame("RadioCol"), event_name)(*args) 
 
-    
+
     def _getPresenceStatusCb(self, presence_data):
         for entity in presence_data:
             for resource in presence_data[entity]:
@@ -535,7 +534,7 @@
                 self.bridge.call('subscription', None, "subscribed", entity, '', _dialog.getSelectedGroups())
             def cancel_cb(ignore):
                 self.bridge.call('subscription', None, "unsubscribed", entity, '', '')
-            
+    
             _dialog = dialog.GroupSelector([msg], self.contact_panel.getGroups(), [], ok_cb, cancel_cb)
             _dialog.setHTML('<b>Add contact request</b>')
             _dialog.show()
@@ -556,7 +555,6 @@
                 if isinstance(lib_wid, panels.MicroblogPanel):
                     if lib_wid.isJidAccepted(entity_jid_s) or (self.whoami and entity_jid_s == self.whoami.bare):
                         lib_wid.updateValue('avatar', entity_jid_s, avatar)
-                        
 
 
 if __name__ == '__main__':
@@ -564,4 +562,3 @@
     app = SatWebFrontend()
     app.onModuleLoad()
     pyjd.run()
-