Remove trailing whitespaces.

This commit is contained in:
Emmanuel Gil Peyrot 2013-01-18 17:55:34 +01:00
commit 27b3592e16
36 changed files with 899 additions and 899 deletions

View file

@ -62,7 +62,7 @@ class BoxSizer:
else:
current_row.append([win, h+y-oriY, w+x-oriX, oriY, oriX])
oriX=oriX+w
if oriX!=0:
oriY=oriY+h
visible_row.append(current_row)

View file

@ -40,7 +40,7 @@ def C(k):
class Chat(Window, QuickChat):
def __init__(self, to_id, host):
QuickChat.__init__(self, to_id, host)
QuickChat.__init__(self, to_id, host)
self.__parent=host.stdscr
self.to_id=JID(to_id)
self.content=[]
@ -88,7 +88,7 @@ class Chat(Window, QuickChat):
att_header=curses.color_pair(1)
else:
att_header=curses.color_pair(2)
while (msg):
if part==0:
hd=header
@ -105,7 +105,7 @@ class Chat(Window, QuickChat):
next = max + 1 #we skip the LF
else:
next = max
content.insert(part,[att,hd, msg[:max]])
msg=msg[next:] #we erase treated part
part=part+1
@ -116,7 +116,7 @@ class Chat(Window, QuickChat):
if self.__scollIdx>0 and len(content)<self.rHeight+self.__scollIdx:
self.__scollIdx=abs(len(content)-self.rHeight) #all the log fit on the screen, we must stop here
idx=0
for line in content[-self.rHeight-self.__scollIdx : -self.__scollIdx or None]:
self.addYXStr(idx, 0, line[1], line[0])
@ -124,12 +124,12 @@ class Chat(Window, QuickChat):
idx=idx+1
self.noutrefresh()
def scrollIdxUp(self):
"""increment scroll index"""
self.__scollIdx = self.__scollIdx + 1
self.update()
def scrollIdxDown(self):
"""decrement scroll index"""
if self.__scollIdx > 0:
@ -144,7 +144,7 @@ class Chat(Window, QuickChat):
return
self.content.append([timestamp,jid.short,msg])
self.update()
def handleKey(self, k):
if k == C('p'):
self.scrollIdxUp()

View file

@ -43,7 +43,7 @@ class EditBox(Window):
self.__replace_mode=False
self.__parent=parent
self.__code=code
Window.__init__(self, self.__parent, 1, self.__parent.getmaxyx()[1], self.__parent.getmaxyx()[0]-1,0, code=code)
self.update()
@ -60,7 +60,7 @@ class EditBox(Window):
"""return the text printed on the edit line"""
width = self.rWidth - len(self.__header) -1
if self.__curs_pos<width:
begin = 0
begin = 0
end = width
else:
begin = self.__curs_pos-width
@ -71,7 +71,7 @@ class EditBox(Window):
Window.update(self)
text = self.__getTextToPrint()
self.addYXStr(0, 0, text, limit=self.rWidth)
self.noutrefresh()
def __dec_cur(self):
@ -83,7 +83,7 @@ class EditBox(Window):
"""move cursor on the right"""
if self.__curs_pos<len(self.__text):
self.__curs_pos = self.__curs_pos + 1
def move_cur(self, x):
pos = x+len(self.__header)
if pos>=self.rWidth:
@ -94,7 +94,7 @@ class EditBox(Window):
"""Clear the text of the edit box"""
self.__text=""
self.__curs_pos=0
def replace_cur(self):
"""must be called earch time the cursor is moved"""
self.move_cur(self.__curs_pos)
@ -136,7 +136,7 @@ class EditBox(Window):
elif k==curses.KEY_HOME or k==C('a'):
self.__curs_pos=0
elif k==curses.KEY_END or k==C('e'):
self.__curs_pos=len(self.__text)

View file

@ -39,7 +39,7 @@ import gobject
import time
from curses import ascii
import locale
from signal import signal, SIGWINCH
from signal import signal, SIGWINCH
import fcntl
import struct
import termios
@ -68,7 +68,7 @@ def C(k):
class ChatList(QuickChatList):
"""This class manage the list of chat windows"""
def __init__(self, host):
QuickChatList.__init__(self, host)
self.sizer=host.sizer
@ -77,10 +77,10 @@ class ChatList(QuickChatList):
chat = Chat(name, self.host)
self.sizer.appendColum(0,chat)
self.sizer.update()
return chat
return chat
class ContactList(Window, QuickContactList):
def __init__(self, host, CM):
QuickContactList.__init__(self, CM)
self.host = host
@ -97,7 +97,7 @@ class ContactList(Window, QuickContactList):
Must be called when stdscr is resized."""
self.resize(stdscr.getmaxyx()[0]-2,const_CONTACT_WIDTH,0,0)
self.update()
def registerEnterCB(self, CB):
self.__enterCB=CB
@ -118,7 +118,7 @@ class ContactList(Window, QuickContactList):
if self.__index < len(self.jid_list)-1: #we dont want to select a missing contact
self.__index = self.__index + 1
self.update()
def indexDown(self):
"""decrement select contact index"""
if self.__index > 0:
@ -142,7 +142,7 @@ class ContactList(Window, QuickContactList):
return
Window.update(self)
self.jid_list.sort()
begin=0 if self.__index<self.rHeight else self.__index-self.rHeight+1
begin=0 if self.__index<self.rHeight else self.__index-self.rHeight+1
idx=0
for item in self.jid_list[begin:self.rHeight+begin]:
attr = curses.A_REVERSE if ( self.isActive() and (idx+begin) == self.__index ) else 0
@ -164,9 +164,9 @@ class ContactList(Window, QuickContactList):
self.__enterCB(self.jid_list[self.__index])
except NameError:
pass # TODO: thrown an error here
class SortilegeApp(QuickApp):
def __init__(self):
#debug(const_APP_NAME+" init...")
@ -245,7 +245,7 @@ class SortilegeApp(QuickApp):
debug (_("Deactivating colors"))
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLACK)
def showChat(self, chat):
debug (_("show chat"))
@ -256,7 +256,7 @@ class SortilegeApp(QuickApp):
debug (_("showing %s"), self.currentChat)
self.chat_wins[self.currentChat].show()
self.chat_wins[self.currentChat].update()
### EVENTS ###
@ -302,7 +302,7 @@ class SortilegeApp(QuickApp):
if (self.currentChat==None):
self.currentChat=win.short
self.showChat(win.short)
# we show the window in the status bar
if not self.currentChat == win.short:
self.statusBar.add_item(win.short)
@ -319,7 +319,7 @@ class SortilegeApp(QuickApp):
height, width = ttysize()
curses.resizeterm(height, width)
gobject.idle_add(self.callOnceLoop)
def callOnceLoop(self):
"""Call the loop and return false (for not being called again by gobject mainloop).
Usefull for calling loop when there is no input in stdin"""
@ -351,7 +351,7 @@ class SortilegeApp(QuickApp):
self.editBar.activate(True)
self.sizer.update()
## Chat Params ##
## Chat Params ##
elif k == C('c'):
self.chatParams["color"] = not self.chatParams["color"]
self.color(self.chatParams["color"])
@ -376,7 +376,7 @@ class SortilegeApp(QuickApp):
self.sizer.update() # FIXME: everything need to be managed by the sizer
## we now throw the key to win handlers ##
else:
else:
for win in self.listWins:
if win.isActive():
win.handleKey(k)
@ -391,7 +391,7 @@ class SortilegeApp(QuickApp):
self.__key_handling(pressed)
self.editBar.replace_cur()
curses.doupdate()
return True

View file

@ -31,7 +31,7 @@ class StatusBar(Window):
self.__parent=parent
self.__code=code
self.__items=set()
Window.__init__(self, self.__parent, 1, self.__parent.getmaxyx()[1], self.__parent.getmaxyx()[0]-2,0, code=code)
def __len__(self):
@ -60,11 +60,11 @@ class StatusBar(Window):
def clear_text(self):
"""Clear the text of the edit box"""
del(self.__items[:])
def add_item(self, item):
self.__items.add(item)
self.update()
def remove_item(self, item):
if item in self.__items:
self.__items.remove(item)

View file

@ -33,7 +33,7 @@ class Window():
self.__parent=parent
self.__code=code
self.__hide=False
self.resize(height, width, y, x)
self.oriCoords=self.__coords #FIXME: tres moche, a faire en mieux
@ -88,7 +88,7 @@ class Window():
# we check that coordinates are under limits
self.__coordAdjust(self.__coords)
height,width,y,x=self.__coords
self.window = self.__parent.subwin(height, width, y, x)
self.defInsideCoord()
@ -124,15 +124,15 @@ class Window():
n = self.rWidth-x if not limit else limit
encoded = text.encode(self.__code)
adjust = len(encoded) - len(text) # hack because addnstr doesn't manage unicode
try:
self.window.addnstr(y, x, encoded, n + adjust, attr)
try:
self.window.addnstr(y, x, encoded, n + adjust, attr)
except:
#We have to catch error to write on last line last col FIXME: is there a better way ?
pass
def move(self, y, x):
self.window.move(y,x)
def noutrefresh(self):
self.window.noutrefresh()

View file

@ -73,7 +73,7 @@ class DBusBridgeFrontend(BridgeFrontend):
# - or if the last two arguments are callable
async = False
if kwargs:
if 'callback' in kwargs and 'errback' in kwargs:
async = True
@ -84,15 +84,15 @@ class DBusBridgeFrontend(BridgeFrontend):
args = list(args)
_errback = args.pop()
_callback = args.pop()
method = getattr(self.db_plugin_iface, name)
if async:
kwargs['reply_handler'] = _callback
kwargs['error_handler'] = lambda err:_errback(err._dbus_error_name[len(const_ERROR_PREFIX)+1:])
return method(*args, **kwargs)
return getPluginMethod
def addContact(self, entity_jid, profile_key="@DEFAULT@"):
@ -214,12 +214,12 @@ class DBusBridgeFrontend(BridgeFrontend):
#methods from plugins
def joinMUC(self, room_jid, nick, options, profile_key):
if options == None:
options = [('', '')] #XXX: we have to do this awful hack because python dbus need to guess the signature
return self.db_plugin_iface.joinMUC(room_jid, nick, options, profile_key)
def gatewayRegister(self, action, target, data, profile_key):
if data == None:
data = [('', '')] #XXX: we have to do this awful hack because python dbus need to guess the signature

View file

@ -135,8 +135,8 @@ class JP():
self.start_loop = True #We have to use loop for these options
else:
self.start_loop = False
return args
def check_jabber_status(self):
@ -145,7 +145,7 @@ class JP():
error(_(u"Can't connect profile"))
exit(1)
self.profile = self.bridge.getProfileName(self.options.profile)
if not self.profile:
error(_("The profile asked doesn't exist"))
@ -293,7 +293,7 @@ class JP():
return
if self.dest_jids and not JID(data['from']).short in [JID(_jid).short for _jid in self.dest_jids]:
return #file is not sent by a filtered jid
answer_data["dest_path"] = os.getcwd()+'/'+data['filename']
if self.options.force or not os.path.exists(answer_data["dest_path"]):
@ -303,7 +303,7 @@ class JP():
else:
self.bridge.confirmationAnswer(confirm_id, False, answer_data, profile)
warning(_("Refused file [%(filename)s] from %(sender)s: a file with the same name already exist") % {'filename':data['filename'], 'sender':data['from']})
if not self.options.multiple and not self.options.progress:
#we just accept one file
@ -313,7 +313,7 @@ class JP():
return
if self.dest_jids and not JID(data['from']).short in [JID(_jid).short for _jid in self.dest_jids]:
return #pipe stream is not sent by a filtered jid
tmp_dir = tempfile.mkdtemp()
fifopath = os.path.join(tmp_dir,"pipe_in")
answer_data["dest_path"] = fifopath
@ -323,8 +323,8 @@ class JP():
shutil.copyfileobj(f, sys.stdout)
shutil.rmtree(tmp_dir)
self.loop.quit()
def actionResult(self, action_type, action_id, data, profile):
#FIXME
info (_("FIXME: actionResult not implemented"))
@ -333,7 +333,7 @@ class JP():
"""Auto reply to confirmations requests"""
#we register incoming confirmation
self.bridge.register("askConfirmation", self.askConfirmation)
#and we ask those we have missed
for confirm_id, confirm_type, data in self.bridge.getWaitingConf(self.profile):
self.askConfirmation(confirm_id, confirm_type, data, self.profile)
@ -349,7 +349,7 @@ class JP():
#first answer, we must construct the bar
self.pbar = ProgressBar(int(data['size']),[_("Progress: "),Percentage()," ",Bar()," ",FileTransferSpeed()," ",ETA()])
self.pbar.start()
self.pbar.update(int(data['position']))
elif self.pbar:
self.pbar.finish()

View file

@ -48,9 +48,9 @@ class CardDisplayer(urwid.Text):
self.select(not self.__selected)
self._emit('click')
return True
return False
def select(self, state=True):
self.__selected = state
attr,txt = self.card.getAttrText()
@ -183,7 +183,7 @@ class Table(urwid.FlowWidget):
self.top = self.left = self.bottom = self.right = None
setattr(self, location, card)
self._invalidate()
def rows(self,size,focus=False):
return self.display_widget(size, focus).rows(size, focus)
@ -203,11 +203,11 @@ class Table(urwid.FlowWidget):
urwid.Text([margin_center,cards['left'],separator,cards['right']]),
urwid.Text([margin,cards['bottom']])]
return urwid.Pile(render_wid)
class CardGame(QuickCardGame,urwid.WidgetWrap):
"""Widget for card games"""
def __init__(self, parent, referee, players, player_nick):
QuickCardGame.__init__(self, parent, referee, players, player_nick)
self.loadCards()
@ -248,13 +248,13 @@ class CardGame(QuickCardGame,urwid.WidgetWrap):
QuickCardGame.newGame(self, hand)
self.hand_wid.update(self.hand)
self.parent.host.redraw()
def contratSelected(self, data):
"""Called when the contrat has been choosed
@param data: form result"""
contrat = data[0][1]
QuickCardGame.contratSelected(self, contrat)
def chooseContrat(self, xml_data):
"""Called when the player as to select his contrat
@param xml_data: SàT xml representation of the form"""
@ -297,14 +297,14 @@ class CardGame(QuickCardGame,urwid.WidgetWrap):
if self._autoplay==None: #No dialog if there is autoplay
self.parent.host.notify(_('Cards played are invalid !'))
self.parent.host.redraw()
def cardsPlayed(self, player, cards):
"""A card has been played by player"""
QuickCardGame.cardsPlayed(self, player, cards)
self.table.putCard(self.getPlayerLocation(player),self.played[player])
self._checkState()
self.parent.host.redraw()
def _checkState(self):
if isinstance(self.center.widget_list[1].original_widget, Hand): #if we have a hand displayed
self.center.widget_list[1] = urwid.Filler(self.table) #we show again the table
@ -317,7 +317,7 @@ class CardGame(QuickCardGame,urwid.WidgetWrap):
self.hand.sort()
self.to_show = []
self.hand_wid.update(self.hand)
##EVENTS##
def onClick(self, hand, card_wid):

View file

@ -31,7 +31,7 @@ from sat.tools.jid import JID
class ChatText(urwid.FlowWidget):
"""Manage the printing of chat message"""
def __init__(self, parent, timestamp, nick, my_mess, message, align='left', is_info=False):
self.parent = parent
self.timestamp = time.localtime(timestamp)
@ -124,8 +124,8 @@ class Chat(urwid.WidgetWrap, QuickChat):
self._invalidate()
return super(Chat, self).keypress(size, key)
return super(Chat, self).keypress(size, key)
def getMenu(self):
"""Return Menu bar"""
menu = sat_widgets.Menu(self.host.loop)
@ -145,7 +145,7 @@ class Chat(urwid.WidgetWrap, QuickChat):
present_widget = self.__buildPresentList()
self.present_panel = sat_widgets.VerticalSeparator(present_widget)
self.__appendPresentPanel()
def __getDecoration(self, widget):
return sat_widgets.LabelLine(widget, sat_widgets.SurroundedText(unicode(unescapePrivate(self.target))))
@ -175,16 +175,16 @@ class Chat(urwid.WidgetWrap, QuickChat):
def __buildPresentList(self):
self.present_wid = sat_widgets.GenericList([],option_type = sat_widgets.ClickableText, on_click=self._presentClicked)
return self.present_wid
def __appendPresentPanel(self):
self.chat_colums.widget_list.append(self.present_panel)
self.chat_colums.widget_list.append(self.present_panel)
self.chat_colums.column_types.append(('weight', 2))
def __removePresentPanel(self):
self.chat_colums.set_focus(0) #necessary as the focus change to the next object, we can go out of range if we are on the last object of self.chat_colums
self.chat_colums.widget_list.remove(self.present_panel)
del self.chat_colums.column_types[-1]
def __appendGamePanel(self, widget):
assert (len(self.pile.widget_list) == 1)
self.pile.widget_list.insert(0,widget)
@ -245,13 +245,13 @@ class Chat(urwid.WidgetWrap, QuickChat):
return
new_text = ChatText(self, timestamp or None, nick, mymess, msg)
if timestamp and self.content:
for idx in range(len(self.content)-1,-1,-1):
current_text = self.content[idx]
if new_text.timestamp < current_text.timestamp and idx > 0:
continue #the new message is older, we need to insert it upper
#we discard double messages, to avoid backlog / history conflict
if ((idx and self.content[idx-1].message == msg) or
(self.content[idx].message == msg) or
@ -262,7 +262,7 @@ class Chat(urwid.WidgetWrap, QuickChat):
break
else:
self.content.append(new_text)
if self.text_list.get_focus()[1] == len(self.content)-2:
#we don't change focus if user is not at the bottom
#as that mean that he is probably watching discussion history
@ -271,9 +271,9 @@ class Chat(urwid.WidgetWrap, QuickChat):
if not self.host.x_notify.hasFocus():
if self.type=="one2one":
self.host.x_notify.sendNotification(_("Primitivus: %s is talking to you") % from_jid)
elif self.getUserNick().lower() in msg.lower():
elif self.getUserNick().lower() in msg.lower():
self.host.x_notify.sendNotification(_("Primitivus: Somebody pinged your name in %s room") % self.target)
def printInfo(self, msg, type='normal', timestamp=""):
"""Print general info
@param msg: message to print
@ -292,28 +292,28 @@ class Chat(urwid.WidgetWrap, QuickChat):
if not self.host.x_notify.hasFocus():
if self.type=="one2one":
self.host.x_notify.sendNotification(_("Primitivus: there is a message about you"))
elif self.getUserNick().lower() in msg.lower():
elif self.getUserNick().lower() in msg.lower():
self.host.x_notify.sendNotification(_("Primitivus: Somebody is talking about you in %s room") % self.target)
def startGame(self, game_type, referee, players):
"""Configure the chat window to start a game"""
if game_type=="Tarot":
self.tarot_wid = CardGame(self, referee, players, self.nick)
self.__appendGamePanel(self.tarot_wid)
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":
return self.tarot_wid
return self.tarot_wid
#MENU EVENTS#
def onTarotRequest(self, menu):
if len(self.occupants) != 4:
self.host.showPopUp(sat_widgets.Alert(_("Can't start game"), _("You need to be exactly 4 peoples in the room to start a Tarot game"), ok_cb=self.host.removePopUp))
self.host.showPopUp(sat_widgets.Alert(_("Can't start game"), _("You need to be exactly 4 peoples in the room to start a Tarot game"), ok_cb=self.host.removePopUp))
else:
self.host.bridge.tarotGameCreate(self.id, list(self.occupants), self.host.profile)
def onSendFileRequest(self, menu):
dialog = FileDialog(ok_cb=self.onFileSelected, cancel_cb=self.host.removePopUp)
self.host.showPopUp(dialog, 80, 80)
@ -328,4 +328,4 @@ class Chat(urwid.WidgetWrap, QuickChat):
else:
full_jid = self.target
progress_id = self.host.bridge.sendFile(full_jid, filepath, {}, self.host.profile)
self.host.addProgress(progress_id,filepath)
self.host.addProgress(progress_id,filepath)

View file

@ -68,7 +68,7 @@ __builtin__.__dict__['const_PALETTE'] = [
('status', 'yellow', 'default'),
('status_focus', 'yellow, bold', 'default'),
]
__builtin__.__dict__['const_SHOW_ICON'] = {"unavailable": (u'⨯', "show_disconnected"),
__builtin__.__dict__['const_SHOW_ICON'] = {"unavailable": (u'⨯', "show_disconnected"),
"": (u'✔', "show_normal"),
"chat": (u'✆', "show_chat"),
"away": (u'✈', "show_away"),

View file

@ -37,7 +37,7 @@ class ContactList(urwid.WidgetWrap, QuickContactList):
self.alert_jid=set()
self.show_status = False
self.show_disconnected = False
#we now build the widget
self.frame = urwid.Frame(self.__buildList())
self.main_widget = sat_widgets.LabelLine(self.frame, sat_widgets.SurroundedText(_("Contacts")))
@ -65,8 +65,8 @@ class ContactList(urwid.WidgetWrap, QuickContactList):
elif key == "meta d": #user wants to (un)hide disconnected contacts
self.show_disconnected = not self.show_disconnected
self.update()
return super(ContactList, self).keypress(size, key)
return super(ContactList, self).keypress(size, key)
def __contains__(self, jid):
for group in self.groups:
if jid.short in self.groups[group][1]:
@ -116,9 +116,9 @@ class ContactList(urwid.WidgetWrap, QuickContactList):
@param content: widget list, e.g. SimpleListWalker
@param contacts: list of JID"""
contacts = list(param_contacts)
widgets = [] #list of built widgets
for contact in contacts:
if contact.startswith(const_PRIVATE_PREFIX):
contact_disp = ('alert' if contact in self.alert_jid else "show_normal", unescapePrivate(contact))
@ -148,7 +148,7 @@ class ContactList(urwid.WidgetWrap, QuickContactList):
widget.data = contact
widget.comp = contact_disp[1].lower() #value to use for sorting
widgets.append(widget)
widgets.sort(key=lambda widget: widget.comp)
for widget in widgets:
@ -160,7 +160,7 @@ class ContactList(urwid.WidgetWrap, QuickContactList):
specials = self.specials.keys()
specials.sort()
for special in specials:
jid=JID(special)
jid=JID(special)
name = self.getCache(jid, 'name')
nick = self.getCache(jid, 'nick')
special_disp = ('alert' if special in self.alert_jid else 'default', nick or name or jid.node or jid.short)
@ -176,7 +176,7 @@ class ContactList(urwid.WidgetWrap, QuickContactList):
def __buildList(self):
"""Build the main contact list widget"""
content = urwid.SimpleListWalker([])
self.__buildSpecials(content)
if self.specials:
content.append(urwid.Divider('='))
@ -205,7 +205,7 @@ class ContactList(urwid.WidgetWrap, QuickContactList):
def getContact(self):
"""Return contact currently selected"""
return self.selected
def clearContacts(self):
"""clear all the contact list"""
QuickContactList.clearContacts(self)
@ -238,7 +238,7 @@ class ContactList(urwid.WidgetWrap, QuickContactList):
contacts.sort()
self.list_wid.changeValues(contacts)
self._emit('change')"""
def remove(self, jid):
"""remove a contact from the list"""
QuickContactList.remove(self, jid)
@ -252,7 +252,7 @@ class ContactList(urwid.WidgetWrap, QuickContactList):
for group in groups_to_remove:
del self.groups[group]
self.update()
def add(self, jid, param_groups=[None]):
"""add a contact to the list"""
self.replace(jid,param_groups)

View file

@ -44,7 +44,7 @@ class GatewaysManager(urwid.WidgetWrap, QuickGatewaysManager):
list_wid = urwid.ListBox(widget_list)
decorated = sat_widgets.LabelLine(list_wid, sat_widgets.SurroundedText(title))
urwid.WidgetWrap.__init__(self, decorated)
def browseExternalServer(self, button):
"""Open the gateway manager on given server"""
server = self.ext_serv.get_edit_text()
@ -58,15 +58,15 @@ class GatewaysManager(urwid.WidgetWrap, QuickGatewaysManager):
self.host.removeWindow()
def addGateway(self, widget_list, gateway, param):
widget_col = []
widget_col.append(('weight',4,urwid.Text(unicode(param['name'])))) #FIXME: unicode to be remove when DBus bridge will not give dbus.String anymore
#Then the transport type message
widget_col.append(('weight',6,urwid.Text(self.getGatewayDesc(param['type']))))
#The buttons
reg_button = sat_widgets.CustomButton( _("Register"), self.onRegister)
reg_button.gateway_jid = JID(gateway)
widget_col.append(('fixed',reg_button.getSize(),reg_button))
@ -74,7 +74,7 @@ class GatewaysManager(urwid.WidgetWrap, QuickGatewaysManager):
unreg_button.gateway_jid = JID(gateway)
widget_col.append(('fixed',unreg_button.getSize(),unreg_button))
widget_list.append(urwid.Columns(widget_col,1))
def onRegister(self, button):
"""Called when register button is clicked"""
gateway_jid = button.gateway_jid

View file

@ -23,13 +23,13 @@ import dbus
class Notify:
"""Used to send notification and detect if we have focus"""
def __init__(self):
#X11 stuff
self.display = None
self.X11_id = -1
try:
from Xlib import display as X_display
self.display = X_display.Display()
@ -44,7 +44,7 @@ class Notify:
self.freedesktop_int = dbus.Interface(db_object, dbus_interface='org.freedesktop.Notifications')
except:
self.freedesktop_int = None
def getFocus(self):
if not self.display:
@ -62,15 +62,15 @@ class Notify:
#TODO: check options before sending notifications
if self.freedesktop_int:
self.sendFDNotification(summ_mess, body_mess)
def sendFDNotification(self, summ_mess, body_mess=""):
"""Send notification with the FreeDesktop D-Bus API"""
if self.freedesktop_int:
app_name = "Primitivus"
app_name = "Primitivus"
replaces_id = 0
app_icon = ""
summary = summ_mess
body = body_mess
body = body_mess
actions = dbus.Array(signature='s')
hints = dbus.Dictionary(signature='sv')
expire_timeout = -1

View file

@ -44,18 +44,18 @@ from os.path import join
logging.basicConfig(level=logging.CRITICAL, #TODO: configure it to put messages in a log file
format='%(message)s')
###
class ChatList(QuickChatList):
"""This class manage the list of chat windows"""
def createChat(self, target):
return Chat(target, self.host)
class PrimitivusApp(QuickApp):
def __init__(self):
QuickApp.__init__(self)
## main loop setup ##
self.main_widget = ProfileManager(self)
self.loop = urwid.MainLoop(self.main_widget, const_PALETTE, event_loop=urwid.GLibEventLoop(), input_filter=self.inputFilter, unhandled_input=self.keyHandler)
@ -82,7 +82,7 @@ class PrimitivusApp(QuickApp):
"""Change mode if make sens (i.e.: if there is nothing in the editBar"""
if not self.editBar.get_edit_text():
self.mode = value
def debug(self):
"""convenient method to reset screen and launch p(u)db"""
try:
@ -209,9 +209,9 @@ class PrimitivusApp(QuickApp):
category,item,type = new_menu
assert(type=="NORMAL") #TODO: manage other types
menu.addMenu(unicode(category), unicode(item), add_menu_cb)
menu_roller = sat_widgets.MenuRoller([(_('Main menu'),menu)])
return menu_roller
return menu_roller
def __buildMainWidget(self):
self.contact_list = ContactList(self, on_click = self.contactSelected, on_change=lambda w: self.redraw())
@ -257,14 +257,14 @@ class PrimitivusApp(QuickApp):
completion_data['last_nick'] = nicks[idx]
return text[:space+1] + nicks[idx] + (': ' if space < 0 else '')
return text
def plug_profile(self, profile_key='@DEFAULT@'):
self.loop.widget = self.__buildMainWidget()
self.redraw()
QuickApp.plug_profile(self, profile_key)
def removePopUp(self, widget=None):
"Remove current pop-up, and if there is other in queue, show it"
self.loop.widget = self.main_widget
@ -305,7 +305,7 @@ class PrimitivusApp(QuickApp):
self.center_part.widget_list[wid_idx] = urwid.Filler(urwid.Text(''))
self.center_part.set_focus(0)
self.redraw()
def addProgress (self, id, message):
"""Follow a SàT progress bar
@param id: SàT id of the progression
@ -342,13 +342,13 @@ class PrimitivusApp(QuickApp):
def newMessage(self, from_jid, to_jid, msg, _type, extra, profile):
QuickApp.newMessage(self, from_jid, to_jid, msg, _type, extra, profile)
if not from_jid in self.contact_list and from_jid.short != self.profiles[profile]['whoami'].short:
#XXX: needed to show entities which haven't sent any
# presence information and which are not in roster
#TODO: put these entities in a "not in roster" list
self.contact_list.replace(from_jid)
if JID(self.contact_list.selected).short != from_jid.short:
self.contact_list.putAlert(from_jid)
@ -363,22 +363,22 @@ class PrimitivusApp(QuickApp):
answer_cb = data[0]
answer_data = [data[1]] if data[1] else []
answer_cb(False, *answer_data)
def showDialog(self, message, title="", type="info", answer_cb = None, answer_data = None):
if type == 'info':
popup = sat_widgets.Alert(unicode(title), unicode(message), ok_cb=answer_cb or self.removePopUp) #FIXME: remove unicode here when DBus Bridge will no return dbus.String anymore
popup = sat_widgets.Alert(unicode(title), unicode(message), ok_cb=answer_cb or self.removePopUp) #FIXME: remove unicode here when DBus Bridge will no return dbus.String anymore
elif type == 'error':
popup = sat_widgets.Alert(unicode(title), unicode(message), ok_cb=answer_cb or self.removePopUp) #FIXME: remove unicode here when DBus Bridge will no return dbus.String anymore
popup = sat_widgets.Alert(unicode(title), unicode(message), ok_cb=answer_cb or self.removePopUp) #FIXME: remove unicode here when DBus Bridge will no return dbus.String anymore
elif type == 'yes/no':
popup = sat_widgets.ConfirmDialog(unicode(message),
yes_cb=self._dialogOkCb, yes_value = (answer_cb, answer_data),
no_cb=self._dialogCancelCb, no_value = (answer_cb, answer_data))
else:
popup = sat_widgets.Alert(unicode(title), unicode(message), ok_cb=answer_cb or self.removePopUp) #FIXME: remove unicode here when DBus Bridge will no return dbus.String anymore
popup = sat_widgets.Alert(unicode(title), unicode(message), ok_cb=answer_cb or self.removePopUp) #FIXME: remove unicode here when DBus Bridge will no return dbus.String anymore
error(_('unmanaged dialog type: %s'), type)
self.showPopUp(popup)
def onNotification(self, notBar):
"""Called when a new notification has been received"""
if not isinstance(self.main_widget, sat_widgets.FocusFrame):
@ -401,26 +401,26 @@ class PrimitivusApp(QuickApp):
if not self.check_profile(profile):
return
answer_data={}
def dir_selected_cb(path):
dest_path = join(path, data['filename'])
answer_data["dest_path"] = getNewPath(dest_path)
self.addProgress(confirmation_id, dest_path)
answer_data["dest_path"] = getNewPath(dest_path)
self.addProgress(confirmation_id, dest_path)
accept_cb(None)
def accept_file_transfer_cb(widget):
self.removePopUp()
pop_up_widget = FileDialog(dir_selected_cb, refuse_cb, title=_(u"Where do you want to save the file ?"), style=['dir'])
pop_up_widget = FileDialog(dir_selected_cb, refuse_cb, title=_(u"Where do you want to save the file ?"), style=['dir'])
self.showPopUp(pop_up_widget)
def accept_cb(widget):
self.removePopUp()
self.bridge.confirmationAnswer(confirmation_id, True, answer_data, profile)
def refuse_cb(widget):
self.removePopUp()
self.bridge.confirmationAnswer(confirmation_id, False, answer_data, profile)
if confirmation_type == "FILE_TRANSFER":
pop_up_widget = sat_widgets.ConfirmDialog(_("The contact %(jid)s wants to send you the file %(filename)s\nDo you accept ?") % {'jid':data["from"], 'filename':data["filename"]}, no_cb=refuse_cb, yes_cb=accept_file_transfer_cb)
self.showPopUp(pop_up_widget)
@ -432,7 +432,7 @@ class PrimitivusApp(QuickApp):
def actionResult(self, type, id, data, profile):
if not self.check_profile(profile):
return
if not id in self.current_action_ids:
debug (_('unknown id, ignoring'))
return
@ -455,7 +455,7 @@ class PrimitivusApp(QuickApp):
ui.show('window')
elif type == "ERROR":
self.current_action_ids.remove(id)
self.showPopUp(sat_widgets.Alert(_("Error"), unicode(data["message"]), ok_cb=self.removePopUp)) #FIXME: remove unicode here when DBus Bridge will no return dbus.String anymore
self.showPopUp(sat_widgets.Alert(_("Error"), unicode(data["message"]), ok_cb=self.removePopUp)) #FIXME: remove unicode here when DBus Bridge will no return dbus.String anymore
elif type == "RESULT":
self.current_action_ids.remove(id)
if self.current_action_ids_cb.has_key(id):
@ -481,7 +481,7 @@ class PrimitivusApp(QuickApp):
else:
message = _("'%s' is an invalid JID !") % room_jid
error (message)
self.showPopUp(sat_widgets.Alert(_("Error"), message, ok_cb=self.removePopUp))
self.showPopUp(sat_widgets.Alert(_("Error"), message, ok_cb=self.removePopUp))
def onAddContact(self, button, edit):
self.removePopUp()
@ -511,7 +511,7 @@ class PrimitivusApp(QuickApp):
def failure(error):
self.showPopUp(sat_widgets.Alert(_("Error"), _("Can't get parameters"), ok_cb=self.removePopUp))
self.bridge.getParamsUI(self.profile, callback=success, errback=failure)
def onExitRequest(self, menu):
QuickApp.onExit(self)
@ -541,8 +541,8 @@ class PrimitivusApp(QuickApp):
self.showPopUp(pop_up_widget)
def onAboutRequest(self, menu):
self.showPopUp(sat_widgets.Alert(_("About"), const_APP_NAME + " v" + self.bridge.getVersion(), ok_cb=self.removePopUp))
self.showPopUp(sat_widgets.Alert(_("About"), const_APP_NAME + " v" + self.bridge.getVersion(), ok_cb=self.removePopUp))
#MISC CALLBACKS#
def onGatewaysFound(self, data):

View file

@ -31,11 +31,11 @@ class ProfileManager(urwid.WidgetWrap):
#profiles list
profiles = self.host.bridge.getProfilesList()
profiles.sort()
#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.list_profile = List(profiles, style=['single'], align='center', on_change=self.onProfileChange)
#new & delete buttons
@ -96,7 +96,7 @@ class ProfileManager(urwid.WidgetWrap):
self.host.bridge.deleteProfile(profile_name)
self.__refillProfiles()
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)
self.host.showPopUp(pop_up_widget)
@ -117,7 +117,7 @@ class ProfileManager(urwid.WidgetWrap):
if profile_name:
self.host.bridge.asyncGetParamA("JabberID", "Connection", profile_key=profile_name, callback=setJID, errback=self.getParamError)
self.host.bridge.asyncGetParamA("Password", "Connection", profile_key=profile_name, callback=setPassword, errback=self.getParamError)
def onConnectProfile(self, button):
profile_name = self.list_profile.getSelectedValue()
if not profile_name:
@ -136,7 +136,7 @@ class ProfileManager(urwid.WidgetWrap):
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()
@ -148,7 +148,7 @@ class ProfileManager(urwid.WidgetWrap):
if old_pass != new_pass:
self.host.bridge.setParam("Password", new_pass, "Connection", 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)

View file

@ -55,7 +55,7 @@ class Progress(urwid.WidgetWrap):
#first answer, we must construct the bar
self.progress_dict[(progress_id, profile)]['state'] = 'progress'
pbar.done = float(data['size'])
pbar.set_completion(float(data['position']))
self.updateNotBar()
else:
@ -93,4 +93,4 @@ class Progress(urwid.WidgetWrap):
nb_bars+=1
av_progress = progress/float(nb_bars)
self.host.setProgress(av_progress)

View file

@ -44,12 +44,12 @@ class Pairs(urwid.WidgetWrap):
pile.widget_list.append(widget)
pile.item_types.append(('weight',getattr(self,'weight_'+str(self.idx))))
self.idx = (self.idx + 1) % 2
class InvalidXMLUI(Exception):
pass
class XMLUI(urwid.WidgetWrap):
def __init__(self, host, xml_data, title = None, options = None, misc = None):
self.host = host
self.title = title
@ -72,7 +72,7 @@ class XMLUI(urwid.WidgetWrap):
type = elem.getAttribute("type")
value = elem.getAttribute("value") if elem.hasAttribute('value') else u''
if type=="empty":
ctrl = urwid.Text('')
ctrl = urwid.Text('')
elif type=="text":
try:
value = elem.childNodes[0].wholeText
@ -135,10 +135,10 @@ class XMLUI(urwid.WidgetWrap):
warning(_("Unknown layout, using default one"))
self.__parseElems(node, current)
elif node.nodeName == "category":
name = node.getAttribute('name')
label = node.getAttribute('label')
name = node.getAttribute('name')
label = node.getAttribute('label')
if not name or not isinstance(data,sat_widgets.TabsContainer):
raise InvalidXMLUI
raise InvalidXMLUI
if self.type == 'param':
self._current_category = name #XXX: awful hack because params need category and we don't keep parent
tab_cont = data
@ -150,9 +150,9 @@ class XMLUI(urwid.WidgetWrap):
raise NotImplementedError
def constructUI(self, xml_data):
ret_wid = urwid.ListBox(urwid.SimpleListWalker([]))
cat_dom = minidom.parseString(xml_data.encode('utf-8'))
top=cat_dom.documentElement
self.type = top.getAttribute("type")
@ -166,11 +166,11 @@ class XMLUI(urwid.WidgetWrap):
self.__parseChilds(ret_wid.body, cat_dom.documentElement)
assert ret_wid.body
if isinstance(ret_wid.body[0],sat_widgets.TabsContainer):
ret_wid = ret_wid.body[0] #xxx: awfull hack cause TabsContainer is a BoxWidget, can't be inside a ListBox
if self.type == 'form':
buttons = []
buttons.append(urwid.Button(_('Submit'),self.onFormSubmitted))
@ -195,7 +195,7 @@ class XMLUI(urwid.WidgetWrap):
- popup
- window"""
self.__dest = "popup"
decorated = sat_widgets.LabelLine(self, sat_widgets.SurroundedText(self.title or ''))
decorated = sat_widgets.LabelLine(self, sat_widgets.SurroundedText(self.title or ''))
if show_type == 'popup':
self.host.showPopUp(decorated)
elif show_type == 'window':
@ -244,7 +244,7 @@ class XMLUI(urwid.WidgetWrap):
else:
warning (_("The form data is not sent back, the type is not managed properly"))
self.host.removePopUp()
def onFormCancelled(self, button):
if self.__dest == 'window':
self.host.removeWindow()

View file

@ -37,7 +37,7 @@ class QuickApp(object):
self.profiles = {}
self.single_profile = single_profile
self.check_options()
## bridge ##
try:
self.bridge=DBusBridgeFrontend()
@ -81,11 +81,11 @@ class QuickApp(object):
self.bridge.register("quizGameAnswerResult", self.quizGameAnswerResult, "plugin")
self.bridge.register("quizGameTimerExpired", self.quizGameTimerExpired, "plugin")
self.bridge.register("quizGameTimerRestarted", self.quizGameTimerRestarted, "plugin")
self.current_action_ids = set()
self.current_action_ids_cb = {}
self.media_dir = self.bridge.getConfig('','media_dir')
def check_profile(self, profile):
"""Tell if the profile is currently followed by the application"""
return profile in self.profiles.keys()
@ -93,7 +93,7 @@ class QuickApp(object):
def postInit(self):
"""Must be called after initialization is done, do all automatic task (auto plug profile)"""
if self.options.profile:
if not self.bridge.getProfileName(self.options.profile):
if not self.bridge.getProfileName(self.options.profile):
error(_("Trying to plug an unknown profile (%s)" % self.options.profile))
else:
self.plug_profile(self.options.profile)
@ -116,7 +116,7 @@ class QuickApp(object):
def _getParamError(self, ignore):
error(_("Can't get profile parameter"))
def plug_profile(self, profile_key='@DEFAULT@'):
"""Tell application which profile must be used"""
if self.single_profile and self.profiles:
@ -132,11 +132,11 @@ class QuickApp(object):
self.profiles[profile]={}
if self.single_profile:
self.profile = profile
###now we get the essential params###
self.bridge.asyncGetParamA("JabberID","Connection", profile_key=profile,
callback=lambda _jid: self.plug_profile_2(_jid, profile), errback=self._getParamError)
def plug_profile_2(self, _jid, profile):
self.profiles[profile]['whoami'] = JID(_jid)
self.bridge.asyncGetParamA("autoconnect","Connection", profile_key=profile,
@ -152,7 +152,7 @@ class QuickApp(object):
self.bridge.asyncConnect(profile, callback=lambda: self.plug_profile_5(watched, autoconnect, profile), errback=lambda ignore: error(_('Error during autoconnection')))
else:
self.plug_profile_5(watched, autoconnect, profile)
def plug_profile_5(self, watched, autoconnect, profile):
self.profiles[profile]['watched'] = watched.split() #TODO: put this in a plugin
@ -198,7 +198,7 @@ class QuickApp(object):
for confirm_id, confirm_type, data in self.bridge.getWaitingConf(profile):
self.askConfirmation(confirm_id, confirm_type, data, profile)
def unplug_profile(self, profile):
"""Tell the application to not follow anymore the profile"""
@ -224,7 +224,7 @@ class QuickApp(object):
debug(_("Disconnected"))
self.contact_list.clearContacts()
self.setStatusOnline(False)
def connectionError(self, error_type, profile):
"""called when something goest wrong with the connection"""
if not self.check_profile(profile):
@ -250,15 +250,15 @@ class QuickApp(object):
return
from_jid = JID(from_jid_s)
to_jid = JID(to_jid_s)
from_me = from_jid.short == self.profiles[profile]['whoami'].short
win = to_jid if from_me else from_jid
if _type != "groupchat" and self.contact_list.getSpecial(win) == "MUC":
#we have a private message in a MUC room
#XXX: normaly we use bare jid as key, here we need the full jid
# so we cheat by replacing the "/" before the resource by
# a "@", so the jid is invalid,
# a "@", so the jid is invalid,
new_jid = escapePrivate(win)
if from_me:
to_jid = new_jid
@ -268,11 +268,11 @@ class QuickApp(object):
self.contact_list.add(new_jid)
self.newMessage(from_jid, to_jid, msg, _type, extra, profile)
def newMessage(self, from_jid, to_jid, msg, _type, extra, profile):
from_me = from_jid.short == self.profiles[profile]['whoami'].short
win = to_jid if from_me else from_jid
self.current_action_ids = set()
self.current_action_ids_cb = {}
@ -291,7 +291,7 @@ class QuickApp(object):
assert alert_type in ['INFO','ERROR']
self.showDialog(unicode(msg),unicode(title),alert_type.lower())
def setStatusOnline(self, online=True):
pass
@ -309,21 +309,21 @@ class QuickApp(object):
self.setStatusOnline(False)
return
self.contact_list.updatePresence(from_jid, show, priority, statuses)
self.contact_list.updatePresence(from_jid, show, priority, statuses)
if show != 'unavailable':
#FIXME: must be moved in a plugin
if from_jid.short in self.profiles[profile]['watched'] and not from_jid.short in self.profiles[profile]['onlineContact']:
self.showAlert(_("Watched jid [%s] is connected !") % from_jid.short)
self.profiles[profile]['onlineContact'].add(from_jid) #FIXME onlineContact is useless with CM, must be removed
#TODO: vcard data (avatar)
if show=="unavailable" and from_jid in self.profiles[profile]['onlineContact']:
self.profiles[profile]['onlineContact'].remove(from_jid)
def roomJoined(self, room_jid, room_nicks, user_nick, profile):
"""Called when a MUC room is joined"""
if not self.check_profile(profile):
@ -374,7 +374,7 @@ class QuickApp(object):
if self.chat_wins.has_key(room_jid):
self.chat_wins[room_jid].setSubject(subject)
debug (_("new subject for room [%(room_jid)s]: %(subject)s") % {'room_jid':room_jid, "subject":subject})
def tarotGameStarted(self, room_jid, referee, players, profile):
if not self.check_profile(profile):
return
@ -382,7 +382,7 @@ class QuickApp(object):
if self.chat_wins.has_key(room_jid):
self.chat_wins[room_jid].startGame("Tarot", referee, players)
debug (_("new Tarot game started by [%(referee)s] in room [%(room_jid)s] with %(players)s") % {'referee':referee, 'room_jid':room_jid, 'players':[str(player) for player in players]})
def tarotGameNew(self, room_jid, hand, profile):
if not self.check_profile(profile):
return
@ -411,8 +411,8 @@ class QuickApp(object):
debug (_("My turn to play"))
if self.chat_wins.has_key(room_jid):
self.chat_wins[room_jid].getGame("Tarot").myTurn()
def tarotScore(self, room_jid, xml_data, winners, loosers, profile):
def tarotScore(self, room_jid, xml_data, winners, loosers, profile):
"""Called when the game is finished and the score are updated"""
if not self.check_profile(profile):
return
@ -426,14 +426,14 @@ class QuickApp(object):
debug (_("Card(s) played (%(player)s): %(cards)s") % {"player":player, "cards":cards})
if self.chat_wins.has_key(room_jid):
self.chat_wins[room_jid].getGame("Tarot").cardsPlayed(player, cards)
def tarotInvalidCards(self, room_jid, phase, played_cards, invalid_cards, profile):
if not self.check_profile(profile):
return
debug (_("Cards played are not valid: %s") % invalid_cards)
if self.chat_wins.has_key(room_jid):
self.chat_wins[room_jid].getGame("Tarot").invalidCards(phase, played_cards, invalid_cards)
def quizGameStarted(self, room_jid, referee, players, profile):
if not self.check_profile(profile):
return
@ -441,7 +441,7 @@ class QuickApp(object):
if self.chat_wins.has_key(room_jid):
self.chat_wins[room_jid].startGame("Quiz", referee, players)
debug (_("new Quiz game started by [%(referee)s] in room [%(room_jid)s] with %(players)s") % {'referee':referee, 'room_jid':room_jid, 'players':[str(player) for player in players]})
def quizGameNew(self, room_jid, data, profile):
if not self.check_profile(profile):
return
@ -477,7 +477,7 @@ class QuickApp(object):
return
if self.chat_wins.has_key(room_jid):
self.chat_wins[room_jid].getGame("Quiz").quizGameAnswerResult(player, good_answer, score)
def quizGameTimerExpired(self, room_jid, profile):
"""Called when nobody answered the question in time"""
if not self.check_profile(profile):
@ -516,10 +516,10 @@ class QuickApp(object):
def showDialog(self, message, title, type="info", answer_cb = None):
raise NotImplementedError
def showAlert(self, message):
pass #FIXME
def paramUpdate(self, name, value, namespace, profile):
if not self.check_profile(profile):
return
@ -556,7 +556,7 @@ class QuickApp(object):
def askConfirmation(self, confirm_id, confirm_type, data, profile):
raise NotImplementedError
def actionResult(self, type, id, data):
raise NotImplementedError

View file

@ -25,7 +25,7 @@ from sat.tools.jid import JID
class QuickCardGame():
def __init__(self, parent, referee, players, player_nick):
self._autoplay = None #XXX: use 0 to activate fake play, None else
self.parent = parent
@ -58,7 +58,7 @@ class QuickCardGame():
self.state = None
for pl in self.played:
self.played[pl] = None
def getPlayerLocation(self, nick):
"""return player location (top,bottom,left or right)"""
for location in ['top','left','bottom','right']:
@ -76,7 +76,7 @@ class QuickCardGame():
self.cards["coeur"]={} #heart
self.cards["carreau"]={} #diamond
self.cards["trefle"]={} #club
def newGame(self, hand):
"""Start a new game, with given hand"""
assert (len(self.hand) == 0)
@ -84,7 +84,7 @@ class QuickCardGame():
self.hand.append(self.cards[suit, value])
self.hand.sort()
self.state = "init"
def contratSelected(self, contrat):
"""Called when the contrat has been choosed
@param data: form result"""
@ -94,7 +94,7 @@ class QuickCardGame():
"""Called when the player as to select his contrat
@param xml_data: SàT xml representation of the form"""
raise NotImplementedError
def showCards(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 = []
@ -111,7 +111,7 @@ class QuickCardGame():
self.to_show = []
self.state = "play"
self.__fakePlay()
def __fakePlay(self):
"""Convenience method for stupid autoplay
/!\ don't forgot to comment any interactive dialog for invalid card"""
@ -131,7 +131,7 @@ class QuickCardGame():
@param winners: list of winners' nicks
@param loosers: list of loosers' nicks"""
raise NotImplementedError
def cardsPlayed(self, player, cards):
"""A card has been played by player"""
if self.to_show:
@ -143,7 +143,7 @@ class QuickCardGame():
for suit, value in cards:
pl_cards.append(self.cards[suit, value])
self.played[player] = pl_cards[0]
def invalidCards(self, phase, played_cards, invalid_cards):
"""Invalid cards have been played
@param phase: phase of the game
@ -156,10 +156,10 @@ class QuickCardGame():
self.state = "ecart"
else:
error ('INTERNAL ERROR: unmanaged game phase')
for suit, value in played_cards:
self.hand.append(self.cards[suit, value])
self.hand.sort()
self.__fakePlay()

Some files were not shown because too many files have changed in this diff Show more