- first public release, initial commit
This commit is contained in:
goffi 2009-08-29 13:34:59 +02:00
commit d005c1b9a8
22 changed files with 4704 additions and 0 deletions

253
frontends/jp/jp Executable file
View file

@ -0,0 +1,253 @@
#! /usr/bin/python
# -*- coding: utf-8 -*-
"""
jp: a SAT command line tool
Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
#consts
name = "jp"
version = "0.0.1"
about = name+" v"+version+""" (c) Jérôme Poisson (aka Goffi) 2009
---
"""+name+""" Copyright (C) 2009 Jérôme Poisson (aka Goffi)
This program comes with ABSOLUTELY NO WARRANTY;
This is free software, and you are welcome to redistribute it
under certain conditions.
---
This software is a command line tool for jabber
Get the latest version at http://www.goffi.org
"""
global pbar_available
pbar_available = True #checked before using ProgressBar
### logging ###
import logging
from logging import debug, info, error, warning
logging.basicConfig(level=logging.DEBUG,
format='%(message)s')
###
import sys
import os
from os.path import abspath, basename, dirname
from optparse import OptionParser
import pdb
from tools.jid import JID
import gobject
from sat_bridge_frontend.DBus import DBusBridgeFrontend
import tarfile
try:
from progressbar import ProgressBar, Percentage, Bar, ETA, FileTransferSpeed
except ImportError, e:
info ('ProgressBar not available, please download it at http://pypi.python.org/pypi/progressbar')
info ('Progress bar deactivated\n--\n')
pbar_available=False
class JP():
def __init__(self):
self.bridge=DBusBridgeFrontend()
self.transfert_id = None
def check_options(self):
"""Check command line options"""
usage="""
%prog [options] [FILE1 FILE2 ...] JID
%prog -w [options] [JID1 JID2 ...]
%prog --help for options list
"""
parser = OptionParser(usage=usage,version=about)
parser.add_option("-b", "--bz2", action="store_true", default=False,
help="Make a bzip2 tarball")
parser.add_option("-w", "--wait-file", action="store_true", default=False,
help="Wait for a file to be sent by a contact")
parser.add_option("-m", "--multiple", action="store_true", default=False,
help="Accept multiple files (you'll have to stop manually)")
parser.add_option("-f", "--force", action="store_true", default=False,
help="Force overwritting of existing files")
parser.add_option("-p", "--progress", action="store_true", default=False,
help="Show progress bar")
parser.add_option("-s", "--separate", action="store_true", default=False,
help="Separate xmpp messages: send one message per line instead of one message alone.")
parser.add_option("-n", "--new-line", action="store_true", default=False,
help="Add a new line at the beginning of the input (usefull for ascii art ;))")
(self.options, args) = parser.parse_args()
if len(args) < 1 and not self.options.wait_file:
parser.error("You must specify the destination JID (Jabber ID)")
if self.options.wait_file:
#several jid
self.dest_jids = args
else:
#one dest_jid, other args are files
self.dest_jid = JID(args[-1])
if not self.dest_jid.is_valid:
error ("%s is not a valid JID !", self.dest_jid)
exit(1)
self.files = args[:-1]
if not pbar_available and self.options.progress:
self.options.progress = False
error ("Option progress is not available, deactivated.")
if self.options.progress or self.options.wait_file:
self.start_loop = True #We have to use loop for these options
else:
self.start_loop = False
return args
def check_jabber_status(self):
"""Check that jabber status is allright"""
if not self.bridge.isConnected():
error("SAT is not conneted, please connect before using jp")
exit(1)
def send_stdin(self):
"""Send incomming data on stdin to jabber contact"""
header = "\n" if self.options.new_line else ""
if self.options.separate: #we send stdin in several messages
if header:
self.bridge.sendMessage(self.dest_jid, header)
while (True):
line = sys.stdin.readline()
if not line:
break
self.bridge.sendMessage(self.dest_jid, line.replace("\n",""))
else:
self.bridge.sendMessage(self.dest_jid, header + "".join(sys.stdin.readlines()))
def send_files(self):
"""Send files to jabber contact"""
for file in self.files:
if not os.path.exists(file):
error ("File [%s] doesn't exist !" % file)
exit(1)
if not self.options.bz2 and os.path.isdir(file):
error ("[%s] is a dir ! Please send files inside or use compression" % file)
exit(1)
if self.options.bz2:
tmpfile = (basename(self.files[0]) or basename(dirname(self.files[0])) ) + '.tar.bz2' #FIXME: tmp, need an algorithm to find a good name/path
if os.path.exists(tmpfile):
error ("tmp file (%s) already exists ! Please remove it", tmpfile)
exit(1)
warning("bz2 is an experimental option at an early dev stage, use with caution")
#FIXME: check free space, writting perm, tmp dir, filename (watch for OS used)
info("Starting compression, please wait...")
sys.stdout.flush()
bz2=tarfile.open(tmpfile, "w:bz2")
for file in self.files:
info("Adding %s", file)
bz2.add(file)
bz2.close()
info("OK !")
path = abspath(tmpfile)
self.transfert_id = self.bridge.sendFile(self.dest_jid, path)
else:
for file in self.files:
path = abspath(file)
self.transfert_id = self.bridge.sendFile(self.dest_jid, path) #FIXME: show progress only for last transfert_id
#TODO: manage ProgressBar
def askConfirmation(self, type, id, data):
"""CB used for file transfert, accept files depending on parameters"""
answer_data={}
if type == "FILE_TRANSFERT":
if self.dest_jids and not data['from'] 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"]):
self.bridge.confirmationAnswer(id, True, answer_data)
info("Accepted file [%s] from %s", data['filename'], data['from'])
self.transfert_id = id
else:
self.bridge.confirmationAnswer(id, False, answer_data)
warning("Refused file [%s] from %s: a file with the same name already exist", data['filename'], data['from'])
if not self.options.multiple and not self.options.progress:
#we just accept one file
self.loop.quit()
def wait_file(self):
"""Wait for a file and write it on local dir"""
self.bridge.register("askConfirmation", self.askConfirmation, "request")
def progressCB(self):
if self.transfert_id:
data = self.bridge.getProgress(self.transfert_id)
if data:
if not data['position']:
data['position'] = '0'
if not self.pbar:
#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()
if not self.options.multiple:
self.loop.quit()
return False
return True
def go(self):
self.check_options()
self.check_jabber_status()
if self.options.wait_file:
self.wait_file()
else:
if not self.files: #we send message only if there are no files to send
self.send_stdin()
else:
self.send_files()
if self.start_loop:
self.loop = gobject.MainLoop()
if self.options.progress:
self.pbar = None
gobject.timeout_add(10, self.progressCB)
try:
self.loop.run()
except KeyboardInterrupt:
info("User interruption: good bye")
if __name__ == "__main__":
jp = JP()
jp.go()

View file

View file

@ -0,0 +1,159 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
helper class for making a SAT frontend
Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from logging import debug, info, error
from tools.jid import JID
from sat_bridge_frontend.DBus import DBusBridgeFrontend
from quick_frontend.quick_contact_management import QuickContactManagement
class QuickApp():
"""This class contain the main methods needed for the frontend"""
def __init__(self):
self.rosterList = {}
self.CM = QuickContactManagement() #a short name if more handy
## bridge ##
self.bridge=DBusBridgeFrontend()
self.bridge.register("newContact", self.newContact)
self.bridge.register("newMessage", self.newMessage)
self.bridge.register("presenceUpdate", self.presenceUpdate)
self.bridge.register("paramUpdate", self.paramUpdate)
self.bridge.register("contactDeleted", self.contactDeleted)
self.bridge.register("askConfirmation", self.askConfirmation, "request")
###now we get the essential params###
self.whoami=JID(self.bridge.getParam("JabberID","Connection")[0])
self.watched=self.bridge.getParam("Watched", "Misc")[0].split() #TODO: put this in a plugin
## misc ##
self.onlineContact = set() #FIXME: temporary
if self.bridge.isConnected():
self.setStatusOnline(True)
### now we fill the contact list ###
for contact in self.bridge.getContacts():
self.newContact(contact[0], contact[1], contact[2])
for status in self.bridge.getPresenceStatus():
self.presenceUpdate(status[0], status[1], status[2], status[3], status[4])
def newContact(self, JabberId, attributes, groups):
jid=JID(JabberId)
self.rosterList[jid.short]=(dict(attributes), list(groups))
def newMessage(self, from_jid, msg, type, to_jid):
sender=JID(from_jid)
addr=JID(to_jid)
win = addr if sender.short == self.whoami.short else sender
self.chat_wins[win.short].printMessage(sender, msg)
def setStatusOnline(self, online=True):
pass
def presenceUpdate(self, jabber_id, type, show, status, priority):
debug ("presence update for %s (type=%s, show=%s, status=%s)", jabber_id, type, show, status);
jid=JID(jabber_id)
debug ("jid.short=%s whoami.short=%s", jid.short, self.whoami.short)
### subscription management ###
if type=="subscribed":
# this is a subscription confirmation, we just have to inform user
self.showDialog("The contact %s has accepted your subscription" % jid.short, 'Subscription confirmation')
return
elif type=="unsubscribed":
# this is a subscription refusal, we just have to inform user
self.showDialog("The contact %s has refused your subscription" % jid.short, 'Subscription refusal', 'error')
return
elif type=="subscribe":
# this is a subscrition request, we have to ask for user confirmation
answer = self.showDialog("The contact %s wants to subscribe to your presence.\nDo you accept ?" % jid.short, 'Subscription confirmation', 'question')
if answer:
self.bridge.setPresence(type="subscribed", to=jid.short)
else:
self.bridge.setPresence(type="unsubscribed", to=jid.short)
return
### subscription management end ###
if jid.short==self.whoami.short:
if not type:
self.setStatusOnline(True)
elif type=="unavailable":
self.setStatusOnline(False)
return
if not type:
name=""
group=""
if self.rosterList.has_key(jid.short):
if self.rosterList[jid.short][0].has_key("name"):
name=self.rosterList[jid.short][0]["name"]
if self.rosterList[jid.short][0].has_key("show"):
name=self.rosterList[jid.short][0]["show"]
if self.rosterList[jid.short][0].has_key("status"):
name=self.rosterList[jid.short][0]["status"]
if len(self.rosterList[jid.short][1]):
group=self.rosterList[jid.short][1][0]
#FIXME: must be moved in a plugin
if jid.short in self.watched and not jid.short in self.onlineContact:
self.showAlert("Watched jid [%s] is connected !" % jid.short)
self.onlineContact.add(jid) #FIXME onlineContact is useless with CM, must be removed
self.CM.add(jid)
self.contactList.replace(jid, show=show, status=status, name=name, group=group)
if type=="unavailable" and jid.short in self.onlineContact:
self.onlineContact.remove(jid.short)
self.CM.remove(jid)
self.contactList.remove(jid)
def showDialog(self, message, title, type="info"):
raise NotImplementedError
def showAlert(self, message):
pass #FIXME
def paramUpdate(self, name, value, namespace):
debug("param update: [%s] %s = %s", namespace, name, value)
if (namespace,name) == ("Connection", "JabberID"):
debug ("Changing ID to %s", value)
self.whoami=JID(value)
elif (namespace,name) == ("Misc", "Watched"):
self.watched=value.split()
def contactDeleted(self, jid):
target = JID(jid)
try:
self.onlineContact.remove(target.short)
except KeyError:
pass
self.contactList.remove(self.CM.get_full(jid))
self.CM.remove(target)
def askConfirmation(self, type, id, data):
raise NotImplementedError

View file

@ -0,0 +1,47 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
helper class for making a SAT frontend
Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from logging import debug, info, error
from tools.jid import JID
class QuickChat():
def __init__(self, to_jid, host):
self.to_jid = to_jid
self.host = host
def historyPrint(self, size=20, keep_last=False):
"""Print the initial history"""
debug ("now we print history")
history=self.host.bridge.getHistory(self.host.whoami.short, self.to_jid, 20)
stamps=history.keys()
stamps.sort()
for stamp in stamps:
self.printMessage(JID(history[stamp][0]), history[stamp][1], stamp)
if keep_last: ##FIXME hack for sortilege
self.last_history = stamps[-1] if stamps else None
def printMessage(self, from_jid, msg, timestamp):
"""Print message in chat window. Must be implemented by child class"""
raise NotImplementedError

View file

@ -0,0 +1,41 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
helper class for making a SAT frontend
Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from tools.jid import JID
class QuickChatList(dict):
"""This class is used to manage the list of chat windows.
It act as a dict, but create a chat window when the name is found for the first time."""
def __init__(self, host):
dict.__init__(self)
self.host = host
def __getitem__(self,name_param):
name=JID(name_param).short
if not self.has_key(name):
#we have to create the chat win
self[name] = self.createChat(name)
return dict.__getitem__(self,name)
def createChat(self, name):
raise NotImplementedError

View file

@ -0,0 +1,42 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
helper class for making a SAT frontend
Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from logging import debug, info, error
from tools.jid import JID
class QuickContactList():
def __init__(self):
debug("Contact List init")
self.jid_ids={}
def replace(self, jid, name="", show="", status="", group=""):
"""add a contact to the list"""
raise NotImplementedError
def remove(self, jid):
"""remove a contact from the list"""
raise NotImplementedError
def add(self, jid, name="", show="", status="", group=""):
"""add a contact to the list"""
raise NotImplementedError

View file

@ -0,0 +1,47 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
helper class for making a SAT frontend
Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from logging import debug, info, error
from tools.jid import JID
import pdb
class QuickContactManagement():
"""This helper class manage the contacts and ease the use of nicknames and shortcuts"""
def __init__(self):
self.__contactlist = {}
def add(self, jid_param):
jid=JID(jid_param)
self.__contactlist[jid.short] = {'name':jid, 'last_resource':jid.resource}
def remove(self, jid_param):
jid=JID(jid_param)
try:
del self.__contactlist[jid.short]
except KeyError:
pass
def get_full(self, jid_param):
jid=JID(jid_param)
return jid.short+'/'+self.__contactlist[jid.short]['last_resource']

View file

@ -0,0 +1,89 @@
#!/usr/bin/python
#-*- coding: utf-8 -*-
"""
SAT communication bridge
Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from bridge_frontend import BridgeFrontend
import dbus, dbus.glib
class DBusBridgeFrontend(BridgeFrontend):
def __init__(self):
self.sessions_bus = dbus.SessionBus()
self.db_object = self.sessions_bus.get_object('org.goffi.SAT',
'/org/goffi/SAT/bridge')
self.db_comm_iface = dbus.Interface(self.db_object,
dbus_interface='org.goffi.SAT.communication')
self.db_req_iface = dbus.Interface(self.db_object,
dbus_interface='org.goffi.SAT.request')
#props = self.db_comm_iface.getProperties()
def register(self, functionName, handler, iface="communication"):
if iface == "communication":
self.db_comm_iface.connect_to_signal(functionName, handler)
elif iface == "request":
self.db_req_iface.connect_to_signal(functionName, handler)
def connect(self):
return self.db_comm_iface.connect()
def getContacts(self):
return self.db_comm_iface.getContacts()
def getPresenceStatus(self):
return self.db_comm_iface.getPresenceStatus()
def sendMessage(self, to, message):
return self.db_comm_iface.sendMessage(to, message)
def sendFile(self, to, path):
return self.db_comm_iface.sendFile(to, path)
def setPresence(self, to="", type="", show="", status="", priority=0):
return self.db_comm_iface.setPresence(to, type, show, status, priority)
def setParam(self, name, value, namespace="default"):
return self.db_comm_iface.setParam(name, value, namespace)
def getParam(self, name, namespace="default"):
return self.db_comm_iface.getParam(name, namespace)
def getParams(self, namespace="default"):
return self.db_comm_iface.getParams(namespace)
def getParamsCategories(self):
return self.db_comm_iface.getParamsCategories()
def getHistory(self, from_jid, to_jid, size):
return self.db_comm_iface.getHistory(from_jid, to_jid, size)
def addContact(self, jid):
return self.db_comm_iface.addContact(jid)
def delContact(self, jid):
return self.db_comm_iface.delContact(jid)
def isConnected(self):
return self.db_comm_iface.isConnected()
def confirmationAnswer(self, id, accepted, data):
return self.db_req_iface.confirmationAnswer(id, accepted, data)
def getProgress(self, id):
return self.db_req_iface.getProgress(id)

View file

@ -0,0 +1,28 @@
#!/usr/bin/python
#-*- coding: utf-8 -*-
"""
SAT communication bridge
Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
class BridgeFrontend:
def __init__(self):
print "Bridge frontend initialization"
def register(self, functionName, handler):
raise NotImplementedError

View file

View file

@ -0,0 +1,88 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
sortilege: a SAT frontend
Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from window import Window
import os,pdb
def echo(message):
return
os.system('echo "'+str(message)+'" >> /tmp/toto')
class BoxSizer:
"""This class manage the position of the window like boxes."""
def __init__(self, parent):
self.__parent=parent
self.boxes=[]
def appendRow(self, win):
self.boxes.append([win])
def appendColum(self, index, win):
if len(self.boxes)<=index:
#TODO: throw an error here
return
self.boxes[index].append(win)
def update(self):
"""Resize boxes"""
oriY=0
visible_row=[]
for row in self.boxes:
current_row=[]
oriX=0
for win in row:
x=win.getOriX()
y=win.getOriY()
w=win.getOriWidth()
h=win.getOriHeight()
if win.isHidden():
if len(current_row)>1 and win is row[-1]:
#if the last win is hidden, we expand previous visible one
current_row[-1][2] = current_row[-1][2] + (win.getX() - oriX)+win.getWidth()
else:
echo ("ajout de %s à current row" % (win.__class__.__name__))
current_row.append([win, h+y-oriY, w+x-oriX, oriY, oriX])
oriX=oriX+w
if oriX!=0:
echo ("ligne visible (dernier: %s)" % win.__class__.__name__)
oriY=oriY+h
visible_row.append(current_row)
elif visible_row:
#if all the row is empty, we take the space
for box in visible_row[-1]:
echo ("on augmente %s de %d" % (box[0].__class__.__name__, h))
box[1]=box[1]+h
oriY=oriY+h #this only happen if it's not the first visible row
else:
echo ("ligne invisible")
for row in visible_row:
for win in row:
win[0].resize(win[1], win[2], win[3], win[4])

154
frontends/sortilege/chat.py Normal file
View file

@ -0,0 +1,154 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
sortilege: a SAT frontend
Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import os.path
import pdb
from logging import debug, info, error
from window import Window
import os
from time import time, localtime, strftime
import curses
import curses.ascii as ascii
from tools.jid import JID
from quick_frontend.quick_chat import QuickChat
def C(k):
"""return the value of Ctrl+key"""
return ord(ascii.ctrl(k))
class Chat(Window, QuickChat):
def __init__(self, to_id, host):
QuickChat.__init__(self, to_id, host)
self.__parent=host.stdscr
self.to_id=JID(to_id)
self.content=[]
self.__scollIdx=0
Window.__init__(self, self.__parent, self.__parent.getmaxyx()[0]-2, self.__parent.getmaxyx()[1]-30, 0,30, code=host.code)
#history
self.historyPrint(50, True)
self.hide()
def resize(self, height, width, y, x):
Window.resize(self, height, width, y, x)
self.update()
def resizeAdapt(self):
"""Adapt window size to self.__parent size.
Must be called when self.__parent is resized."""
self.resize(self.__parent.getmaxyx()[0]-2, self.__parent.getmaxyx()[1]-30, 0,30)
self.update()
def __getHeader(self, line):
"""Return the header of a line (eg: "[12:34] <toto> ")."""
header=''
if self.host.chatParams["timestamp"]:
header = header + '[%s] ' % strftime("%H:%M", localtime(float(line[0])))
if self.host.chatParams['short_nick']:
header = header + ('> ' if line[1]==self.host.whoami.short else '** ')
else:
header = header + '<%s> ' % line[1]
return header
def update(self):
if self.isHidden():
echo ("fenetre cachee")
return
Window.update(self)
content=[] #what is really printed
irange=range(len(self.content))
irange.reverse() #we print the text upward
for idx in irange:
header=self.__getHeader(self.content[idx])
msg=self.content[idx][2]
part=0 #part of the text
if JID(self.content[idx][1]).short==self.host.whoami.short:
att_header=curses.color_pair(1)
else:
att_header=curses.color_pair(2)
while (msg):
if part==0:
hd=header
att=att_header
max=self.rWidth-len(header)
else:
hd=""
att=0
max=self.rWidth
LF = msg.find('\n') #we look for Line Feed
if LF != -1 and LF < max:
max = LF
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
if len(content)>=self.rHeight+self.__scollIdx:
#all the screen is filled, we can continue
break
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])
self.addYXStr(idx, len(line[1]), line[2])
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:
self.__scollIdx = self.__scollIdx - 1
self.update()
def printMessage(self, jid, msg, timestamp=""):
if timestamp=="":
current_time=time()
timestamp=str(current_time)
if self.last_history and current_time - float(self.last_history) < 5: #FIXME: Q&D fix to avoid double print on new chat window
return
self.content.append([timestamp,jid.short,msg])
self.update()
def handleKey(self, k):
if k == C('p'):
self.scrollIdxUp()
elif k == C('n'):
self.scrollIdxDown()

View file

@ -0,0 +1,176 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
sortilege: a SAT frontend
Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import curses
from curses import ascii
from window import Window
def C(k):
"""return the value of Ctrl+key"""
return ord(ascii.ctrl(k))
def A(k):
"""return the value of Alt+key"""
return ord(ascii.alt(k))
class EditBox(Window):
"""This class manage the edition of text"""
def __init__(self, parent, header, code="utf-8"):
self.__header=header
self.__text = unicode()
self.__curs_pos=0
self.__buffer=str()
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()
def registerEnterCB(self, CB):
self.__enterCB=CB
def resizeAdapt(self):
"""Adapt window size to self.__parent size.
Must be called when self.__parent is resized."""
self.resize(1, self.__parent.getmaxyx()[1], self.__parent.getmaxyx()[0]-1,0)
self.update()
def __getTextToPrint(self):
"""return the text printed on the edit line"""
width = self.rWidth - len(self.__header) -1
if self.__curs_pos<width:
begin = 0
end = width
else:
begin = self.__curs_pos-width
end = self.__curs_pos
return self.__header+self.__text[begin:end]
def update(self):
Window.update(self)
text = self.__getTextToPrint()
self.addYXStr(0, 0, text, limit=self.rWidth)
self.noutrefresh()
def __dec_cur(self):
"""move cursor on the left"""
if self.__curs_pos>0:
self.__curs_pos = self.__curs_pos - 1
def __inc_cur(self):
"""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:
pos=self.rWidth-1
self.move(0, pos)
def clear_text(self):
"""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)
self.noutrefresh()
def activate(self, state=True):
cursor_mode = 1 if state else 0
curses.curs_set(cursor_mode)
Window.activate(self,state)
def handleKey(self, k):
if ascii.isgraph(k) or ascii.isblank(k):
pacman = 0 if not self.__replace_mode else 1
self.__text = self.__text[:self.__curs_pos] + chr(k) + self.__text[self.__curs_pos + pacman:]
self.__curs_pos = self.__curs_pos + 1
elif k==ascii.NL:
try:
self.__enterCB(self.__text)
except NameError:
pass # TODO: thrown an error here
self.clear_text()
elif k==curses.KEY_BACKSPACE:
self.__text = self.__text[:self.__curs_pos-1]+self.__text[self.__curs_pos:]
self.__dec_cur()
elif k==curses.KEY_DC:
self.__text = self.__text[:self.__curs_pos]+self.__text[self.__curs_pos+1:]
elif k==curses.KEY_IC:
self.__replace_mode = not self.__replace_mode
elif k==curses.KEY_LEFT:
self.__dec_cur()
elif k==curses.KEY_RIGHT:
self.__inc_cur()
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)
elif k==C('k'):
self.__text = self.__text[:self.__curs_pos]
elif k==C('w'):
before = self.__text[:self.__curs_pos]
pos = before.rstrip().rfind(" ")+1
self.__text = before[:pos] + self.__text[self.__curs_pos:]
self.__curs_pos = pos
elif k>255:
self.__buffer=""
else: ## FIXME: dangerous code, must be checked ! (specialy buffer overflow) ##
#We now manage unicode
self.__buffer = self.__buffer+chr(k)
decoded=unicode()
if len(self.__buffer)>4:
self.__buffer=""
return
try:
decoded = self.__buffer.decode(self.__code)
except UnicodeDecodeError, e:
if e.reason!="unexpected end of data":
self.__buffer=""
return
if len(self.__buffer)==1: ## FIXME: awful ! only for test !
self.__buffer=""
return
self.__text = self.__text + decoded
self.__curs_pos = self.__curs_pos + 1
self.__buffer=""
self.update()

379
frontends/sortilege/sortilege.py Executable file
View file

@ -0,0 +1,379 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
sortilege: a SAT frontend
Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import curses
import pdb
from window import Window
from editbox import EditBox
from statusbar import StatusBar
from chat import Chat
from tools.jid import JID
import logging
from logging import debug, info, error
import locale
import sys, os
import gobject
import time
from curses import ascii
import locale
from signal import signal, SIGWINCH
import fcntl
import struct
import termios
from boxsizer import BoxSizer
from quick_frontend.quick_chat_list import QuickChatList
from quick_frontend.quick_contact_list import QuickContactList
from quick_frontend.quick_app import QuickApp
### logging configuration FIXME: put this elsewhere ###
logging.basicConfig(level=logging.CRITICAL, #TODO: configure it top put messages in a log file
format='%(message)s')
###
const_APP_NAME = "Sortilège"
const_CONTACT_WIDTH = 30
def ttysize():
"""This function return term size.
Comes from Donn Cave from python list mailing list"""
buf = 'abcdefgh'
buf = fcntl.ioctl(0, termios.TIOCGWINSZ, buf)
row, col, rpx, cpx = struct.unpack('hhhh', buf)
return row, col
def C(k):
"""return the value of Ctrl+key"""
return ord(ascii.ctrl(k))
class ChatList(QuickChatList):
"""This class manage the list of chat windows"""
def __init__(self, host):
QuickChatList.__init__(self, host)
self.sizer=host.sizer
def createChat(self, name):
chat = Chat(name, self.host)
self.sizer.appendColum(0,chat)
self.sizer.update()
return chat
class ContactList(Window, QuickContactList):
def __init__(self):
QuickContactList.__init__(self)
self.__index=0 #indicate which contact is selected (ie: where we are)
Window.__init__(self, stdscr, stdscr.getmaxyx()[0]-2,const_CONTACT_WIDTH,0,0, True, "Contact List", code=code)
def resize(self, height, width, y, x):
Window.resize(self, height, width, y, x)
self.update()
def resizeAdapt(self):
"""Adapt window size to stdscr size.
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
def replace(self, jid, name="", show="", status="", group=""):
"""add a contact to the list"""
self.jid_ids[jid] = name or jid
self.update()
def indexUp(self):
"""increment select contact index"""
if self.__index < len(self.jid_ids)-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:
self.__index = self.__index - 1
self.update()
def remove(self, jid):
"""remove a contact from the list"""
del self.jid_ids[jid]
if self.__index >= len(self.jid_ids) and self.__index > 0: #if select index is out of border, we put it on the last contact
self.__index = len(self.jid_ids)-1
self.update()
def update(self):
"""redraw all the window"""
if self.isHidden():
return
Window.update(self)
viewList=[]
for jid in self.jid_ids:
viewList.append(self.jid_ids[jid])
viewList.sort()
begin=0 if self.__index<self.rHeight else self.__index-self.rHeight+1
idx=0
for item in viewList[begin:self.rHeight+begin]:
attr = curses.A_REVERSE if ( self.isActive() and (idx+begin) == self.__index ) else 0
centered = item.center(self.rWidth) ## it's nicer in the center :)
self.addYXStr(idx, 0, centered, attr)
idx = idx + 1
self.noutrefresh()
def handleKey(self, k):
if k == curses.KEY_UP:
self.indexDown()
elif k == curses.KEY_DOWN:
self.indexUp()
elif k == ascii.NL:
if not self.jid_ids:
return
try:
self.__enterCB(self.jid_ids.keys()[self.__index])
except NameError:
pass # TODO: thrown an error here
class SortilegeApp(QuickApp):
def __init__(self):
#debug(const_APP_NAME+" init...")
## unicode support ##
locale.setlocale(locale.LC_ALL, '')
global code
code = locale.getpreferredencoding()
self.code=code
## main loop setup ##
self.loop=gobject.MainLoop()
gobject.io_add_watch(0, gobject.IO_IN, self.loopCB)
## misc init stuff ##
self.listWins=[]
self.chatParams={'timestamp':True,
'color':True,
'short_nick':False}
def start(self):
curses.wrapper(self.start_curses)
def start_curses(self, win):
global stdscr
stdscr = win
self.stdscr = stdscr
curses.raw() #we handle everything ourself
curses.curs_set(False)
stdscr.nodelay(True)
## colours ##
self.color(True)
## windows ##
self.contactList = ContactList()
self.editBar = EditBox(stdscr, "> ", self.code)
self.editBar.activate(False)
self.statusBar = StatusBar(stdscr, self.code)
self.statusBar.hide(True)
self.addWin(self.contactList)
self.addWin(self.editBar)
self.addWin(self.statusBar)
self.sizer=BoxSizer(stdscr)
self.sizer.appendRow(self.contactList)
self.sizer.appendRow(self.statusBar)
self.sizer.appendRow(self.editBar)
self.currentChat=None
self.contactList.registerEnterCB(self.onContactChoosed)
self.editBar.registerEnterCB(self.onTextEntered)
self.chat_wins=ChatList(self)
QuickApp.__init__(self) #XXX: yes it's an unusual place for the constructor of a parent class, but the init order is important
signal (SIGWINCH, self.onResize) #we manage SIGWINCH ourselves, because the loop is not called otherwise
#last but not least, we adapt windows' sizes
self.sizer.update()
self.editBar.replace_cur()
curses.doupdate()
self.loop.run()
def addWin(self, win):
self.listWins.append(win)
def color(self, activate=True):
if activate:
debug ("Activation des couleurs")
curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)
else:
debug ("Desactivation des couleurs")
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")
if self.currentChat:
debug ("hide de %s", self.currentChat)
self.chat_wins[self.currentChat].hide()
self.currentChat=chat
debug ("show de %s", self.currentChat)
self.chat_wins[self.currentChat].show()
self.chat_wins[self.currentChat].update()
### EVENTS ###
def onContactChoosed(self, jid_txt):
"""Called when a contact is selected in contact list."""
jid=JID(jid_txt)
debug ("contact choose: %s", jid)
self.showChat(jid.short)
self.statusBar.remove_item(jid.short)
if len(self.statusBar)==0:
self.statusBar.hide()
self.sizer.update()
def onTextEntered(self, text):
jid=JID(self.whoami)
self.bridge.sendMessage(self.currentChat, text)
def showDialog(self, message, title, type="info"):
if type==question:
raise NotImplementedError
pass
def presenceUpdate(self, jabber_id, type, show, status, priority):
QuickApp.presenceUpdate(self, jabber_id, type, show, status, priority)
self.editBar.replace_cur()
curses.doupdate()
def newMessage(self, from_jid, msg, type, to_jid):
QuickApp.newMessage(self, from_jid, msg, type, to_jid)
sender=JID(from_jid)
addr=JID(to_jid)
win = addr if sender.short == self.whoami.short else sender #FIXME: duplicate code with 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)
self.statusBar.show()
self.sizer.update()
self.statusBar.update()
self.editBar.replace_cur()
curses.doupdate()
def onResize(self, sig, stack):
"""Called on SIGWINCH.
resize the screen and launch the loop"""
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"""
self.loopCB()
return False
def __key_handling(self, k):
"""Handle key and transmit to active window."""
### General keys, handled _everytime_ ###
if k == C('x'):
if os.getenv('TERM')=='screen':
os.system('screen -X remove')
else:
self.loop.quit()
## windows navigation
elif k == C('l') and not self.contactList.isHidden():
"""We go to the contact list"""
self.contactList.activate(not self.contactList.isActive())
if self.currentChat:
self.editBar.activate(not self.contactList.isActive())
elif k == curses.KEY_F2:
self.contactList.hide(not self.contactList.isHidden())
if self.contactList.isHidden():
self.contactList.activate(False) #TODO: auto deactivation when hiding ?
if self.currentChat:
self.editBar.activate(True)
self.sizer.update()
## Chat Params ##
elif k == C('c'):
self.chatParams["color"] = not self.chatParams["color"]
self.color(self.chatParams["color"])
elif k == C('t'):
self.chatParams["timestamp"] = not self.chatParams["timestamp"]
self.chat_wins[self.currentChat].update()
elif k == C('s'):
self.chatParams["short_nick"] = not self.chatParams["short_nick"]
self.chat_wins[self.currentChat].update()
## misc ##
elif k == curses.KEY_RESIZE:
stdscr.erase()
height, width = stdscr.getmaxyx()
if height<5 and width<35:
stdscr.addstr("Pleeeeasse, I can't even breathe !")
else:
for win in self.listWins:
win.resizeAdapt()
for win in self.chat_wins.keys():
self.chat_wins[win].resizeAdapt()
self.sizer.update() # FIXME: everything need to be managed by the sizer
## we now throw the key to win handlers ##
else:
for win in self.listWins:
if win.isActive():
win.handleKey(k)
if self.currentChat:
self.chat_wins[self.currentChat].handleKey(k)
def loopCB(self, source="", cb_condition=""):
"""This callback is called by the main loop"""
#pressed = self.contactList.window.getch()
pressed = stdscr.getch()
if pressed != curses.ERR:
self.__key_handling(pressed)
self.editBar.replace_cur()
curses.doupdate()
return True
sat = SortilegeApp()
sat.start()

View file

@ -0,0 +1,77 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
sortilege: a SAT frontend
Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import curses
from window import Window
import os
def echo(message):
return
os.system('echo "'+str(message)+'" >> /tmp/toto')
class StatusBar(Window):
"""This class manage the edition of text"""
def __init__(self, parent, code="utf-8"):
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):
return len(self.__items)
def resizeAdapt(self):
"""Adapt window size to self.__parent size.
Must be called when self.__parent is resized."""
self.resize(1, self.__parent.getmaxyx()[1], self.__parent.getmaxyx()[0]-2,0)
self.update()
def update(self):
if self.isHidden():
echo ("status bar hidden")
return
echo ("update status bar")
Window.update(self)
x=0
for item in self.__items:
pitem="[%s] " % item
self.addYXStr(0, x, pitem, curses.A_REVERSE)
x = x + len(pitem)
if x>=self.rWidth:
break
self.addYXStr(0, x, (self.rWidth-x)*" ", curses.A_REVERSE)
self.noutrefresh()
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)
self.update()

View file

@ -0,0 +1,164 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
sortilege: a SAT frontend
Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import curses
import os
import pdb
def echo(message):
return
os.system('echo "'+str(message)+'" >> /tmp/toto')
class Window():
def __init__(self, parent, height, width, y, x, border=False, title="", code="utf-8"):
self.__border=border
self.__title=title
self.__active=False
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
def hide(self, hide=True):
self.__hide=hide
def show(self):
self.__hide=False
def isHidden(self):
return self.__hide
def getY(self):
return self.__coords[2]
def getX(self):
return self.__coords[3]
def getHeight(self):
return self.__coords[0]
def getWidth(self):
return self.__coords[1]
#FIXME: tres moche, a faire en plus joli
def getOriY(self):
return self.oriCoords[2]
def getOriX(self):
return self.oriCoords[3]
def getOriHeight(self):
return self.oriCoords[0]
def getOriWidth(self):
return self.oriCoords[1]
def defInsideCoord(self):
"""define the inside coordinates (win coordinates minus decorations)"""
height,width,y,x=self.__coords
self.oriX = x if not self.__border else x+1
self.oriY = y if not self.__border else y+1
self.endX = x+width if not self.__border else x+width-2
self.endY = y+height if not self.__border else y+height-2
self.rWidth = width if not self.__border else width-2
self.rHeight = height if not self.__border else height-2
def resize(self, height, width, y, x):
self.__coords=[height, width, y, x]
# we check that coordinates are under limits
self.__coordAdjust(self.__coords)
height,width,y,x=self.__coords
echo ("newwin %d %d %d %d" % (height, width, y, x))
self.window = self.__parent.subwin(height, width, y, x)
self.defInsideCoord()
def __coordAdjust(self, coords):
"""Check that coordinates are under limits, adjust them else otherwise"""
height,width,y,x=coords
parentY, parentX = self.__parent.getbegyx()
parentHeight, parentWidth = self.__parent.getmaxyx()
if y < parentY:
y = parentY
if x < parentX:
x = parentX
if height > parentHeight - y:
height = parentHeight - y
if width > parentWidth - x:
width = parentWidth - x
coords[0], coords[1], coords[2], coords[3] = [height, width, y, x]
def activate(self,state=True):
"""Declare this window as current active one"""
self.__active=state
self.update()
def isActive(self):
return self.__active
def addYXStr(self, y, x, text, attr = 0, limit=0):
if self.__border:
x=x+1
y=y+1
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)
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()
def update(self):
"""redraw all the window"""
if self.__hide:
return
self.clear()
def border(self):
"""redraw the border and title"""
y,x = self.window.getbegyx()
width = self.window.getmaxyx()[1]
if self.__border:
self.window.border()
if self.__title:
if len(self.__title)>width:
self.__title=""
else:
self.window.addstr(y,x+(width-len(self.__title))/2, self.__title)
def clear(self):
self.window.clear()
self.border()

View file

118
frontends/wix/chat.py Normal file
View file

@ -0,0 +1,118 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
wix: a SAT frontend
Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import wx
import os.path
import pdb
from logging import debug, info, error
from tools.jid import JID
from quick_frontend.quick_chat import QuickChat
idSEND = 1
class Chat(wx.Frame, QuickChat):
"""The chat Window for one to one conversations"""
def __init__(self, to_jid, host):
wx.Frame.__init__(self, None, title=to_jid, pos=(0,0), size=(400,200))
QuickChat.__init__(self, to_jid, host)
self.chatWindow = wx.TextCtrl(self, -1, style = wx.TE_MULTILINE | wx.TE_RICH | wx.TE_READONLY)
self.textBox = wx.TextCtrl(self, -1, style = wx.TE_PROCESS_ENTER)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.chatWindow, 1, flag=wx.EXPAND)
self.sizer.Add(self.textBox, flag=wx.EXPAND)
self.SetSizer(self.sizer)
self.SetAutoLayout(True)
self.createMenus()
#events
self.Bind(wx.EVT_CLOSE, self.onClose, self)
self.Bind(wx.EVT_TEXT_ENTER, self.onEnterPressed, self.textBox)
#fonts
self.font={}
self.font["points"] = self.chatWindow.GetFont().GetPointSize()
self.font["family"] = self.chatWindow.GetFont().GetFamily()
self.historyPrint()
#misc
self.textBox.SetFocus()
self.Hide() #We hide because of the show toggle
def createMenus(self):
info("Creating menus")
actionMenu = wx.Menu()
actionMenu.Append(idSEND, "&SendFile CTRL-s"," Send a file to contact")
menuBar = wx.MenuBar()
menuBar.Append(actionMenu,"&Action")
self.SetMenuBar(menuBar)
#events
wx.EVT_MENU(self, idSEND, self.onSendFile)
def __del__(self):
debug ("Chat window destructor")
wx.Frame.__del__(self)
def onClose(self, event):
"""Close event: we only hide the frame."""
event.Veto()
self.Show() ## this is a workaround to a wxpython bug:
## with Raise on hidden frame, Hide doesn't work anymore
## TODO: check this and repport bug to wxpython devs
self.Hide()
def onEnterPressed(self, event):
"""Behaviour when enter pressed in send line."""
self.host.bridge.sendMessage(self.to_jid, event.GetString())
self.textBox.Clear()
def printMessage(self, from_jid, msg, timestamp=""): #FIXME: factorize with printDistantMessage
"""Print the message with differents colors depending on where it comes from."""
jid=JID(from_jid)
mymess = (jid.short == self.host.whoami.short) #mymess = True if message comes from local user
_font = wx.Font(self.font["points"], self.font["family"], wx.NORMAL, wx.BOLD)
self.chatWindow.SetDefaultStyle(wx.TextAttr( "BLACK" if mymess else "BLUE", font=_font))
self.chatWindow.AppendText("[%s] " % jid)
_font = wx.Font(self.font["points"], self.font["family"], wx.ITALIC if mymess else wx.NORMAL, wx.NORMAL)
self.chatWindow.SetDefaultStyle(wx.TextAttr("BLACK", font=_font))
self.chatWindow.AppendText("%s\n" % msg)
if not mymess:
self.Raise() #FIXME: too intrusive
### events ###
def onSendFile(self, e):
debug("Send File")
filename = wx.FileSelector("Choose a file to send", flags = wx.FD_FILE_MUST_EXIST)
if filename:
debug("filename: %s",filename)
full_jid = self.host.CM.get_full(self.to_jid)
id = self.host.bridge.sendFile(full_jid, filename)
self.host.waitProgress(id, "File Transfer", "Copying %s" % os.path.basename(filename))

View file

@ -0,0 +1,377 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
wix: a SAT frontend
Copyright (C) 2009 Jérôme Poisson (goffi@goffi.org)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import wx
from chat import Chat
from param import Param
import gobject
import os.path
import pdb
from tools.jid import JID
from logging import debug, info, error
from quick_frontend.quick_chat_list import QuickChatList
from quick_frontend.quick_contact_list import QuickContactList
from quick_frontend.quick_app import QuickApp
msgOFFLINE = "offline"
msgONLINE = "online"
idCONNECT = 1
idEXIT = 2
idPARAM = 3
idADD_CONTACT = 4
idREMOVE_CONTACT = 5
const_DEFAULT_GROUP = "Unclassed"
const_STATUS = {"Online":"",
"Want to discuss":"chat",
"AFK":"away",
"Do Not Disturb":"dnd",
"Away":"xa"}
class ChatList(QuickChatList):
"""This class manage the list of chat windows"""
def __init__(self, host):
QuickChatList.__init__(self, host)
def createChat(self, name):
return Chat(name, self.host)
class ContactList(wx.TreeCtrl, QuickContactList):
"""Customized control to manage contacts."""
def __init__(self, parent):
wx.TreeCtrl.__init__(self, parent, style = wx.TR_HIDE_ROOT | wx.TR_HAS_BUTTONS)
QuickContactList.__init__(self)
self.jid_ids={}
self.groups={}
self.root=self.AddRoot("")
self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.onActivated, self)
#icons
isz = (16,16)
il = wx.ImageList(isz[0], isz[1])
self.icon_online = il.Add(wx.ArtProvider_GetBitmap(wx.ART_TICK_MARK, wx.ART_OTHER, isz))
self.icon_unavailable = il.Add(wx.ArtProvider_GetBitmap(wx.ART_CROSS_MARK, wx.ART_OTHER, isz))
self.AssignImageList(il)
self.__addNode(const_DEFAULT_GROUP)
def __addNode(self, label):
"""Add an item container"""
ret=self.AppendItem(self.root, label)
self.SetPyData(ret, "[node]")
self.SetItemBold(ret)
self.groups[label]=ret
def replace(self, jid, name="", show="", status="", group=""):
debug("status = %s show = %s",status, show)
if not self.jid_ids.has_key(jid):
self.add(jid, name, show, status, group)
else:
debug ("updating %s",jid)
self.__presentItem(jid, name, show, status, group)
def __presentItem(self, jid, name, show, status, group):
"""Make a nice presentation of the contact in the list."""
id=self.jid_ids[jid]
label= "%s [%s] \n %s" % ((name or jid), (show or "online"), status)
self.SetItemText(id, label)
# icon
if not show or show=="chat":
self.SetItemImage(id, self.icon_online)
else:
self.SetItemImage(id, self.icon_unavailable)
#colour
if not show:
self.SetItemTextColour(id, wx.BLACK)
elif show=="chat":
self.SetItemTextColour(id, wx.GREEN)
elif show=="away":
self.SetItemTextColour(id, wx.BLUE)
else:
self.SetItemTextColour(id, wx.RED)
def add(self, jid, name="", show="", status="", group=""):
"""add a contact to the list"""
debug ("adding %s",jid)
dest_group=group or const_DEFAULT_GROUP
if not self.groups.has_key(dest_group):
self.__addNode(dest_group)
self.jid_ids[jid]=self.AppendItem(self.groups[dest_group], "")
self.__presentItem(jid, name, show, status, group)
self.SetPyData(self.jid_ids[jid], "[contact]"+jid)
self.EnsureVisible(self.jid_ids[jid])
self.Refresh() #FIXME: Best way ?
def remove(self, jid):
"""remove a contact from the list"""
debug ("removing %s",jid)
self.Delete(self.jid_ids[jid])
del self.jid_ids[jid]
self.Refresh() #FIXME: Best way ?
def onActivated(self, event):
"""Called when a contact is clicked or activated with keyboard."""
if self.GetPyData(event.GetItem()).startswith("[contact]"):
self.onActivatedCB(self.GetPyData(event.GetItem())[9:])
else:
event.Skip()
def getSelection(self):
"""Return the selected contact, or an empty string if there is not"""
data = self.GetPyData(self.GetSelection())
if not data or not data.startswith("[contact]"):
return ""
return JID(data[9:])
def registerActivatedCB(self, cb):
"""Register a callback with manage contact activation."""
self.onActivatedCB=cb
class MainWindow(wx.Frame, QuickApp):
"""main app window"""
def __init__(self):
wx.Frame.__init__(self,None, title="SAT Wix", size=(400,200))
#Frame elements
self.contactList = ContactList(self)
self.contactList.registerActivatedCB(self.onContactActivated)
self.chat_wins=ChatList(self)
self.CreateStatusBar()
self.SetStatusText(msgOFFLINE)
self.createMenus()
#ToolBar
self.tools=self.CreateToolBar()
self.statusBox = wx.ComboBox(self.tools, -1, "Online", choices=const_STATUS.keys(),
style=wx.CB_DROPDOWN | wx.CB_READONLY)
self.tools.AddControl(self.statusBox)
self.tools.AddSeparator()
self.statusTxt=wx.TextCtrl(self.tools, -1, style = wx.TE_PROCESS_ENTER)
self.tools.AddControl(self.statusTxt)
self.Bind(wx.EVT_COMBOBOX, self.onStatusChange, self.statusBox)
self.Bind(wx.EVT_TEXT_ENTER, self.onStatusChange, self.statusTxt)
self.tools.Disable()
#events
self.Bind(wx.EVT_CLOSE, self.onClose, self)
QuickApp.__init__(self)
self.Show()
def createMenus(self):
info("Creating menus")
connectMenu = wx.Menu()
connectMenu.Append(idCONNECT, "&Connect CTRL-c"," Connect to the server")
connectMenu.Append(idPARAM,"&Parameters"," Configure the program")
connectMenu.AppendSeparator()
connectMenu.Append(idEXIT,"E&xit"," Terminate the program")
contactMenu = wx.Menu()
contactMenu.Append(idADD_CONTACT, "&Add contact"," Add a contact to your list")
contactMenu.Append(idREMOVE_CONTACT, "&Remove contact"," Remove the selected contact from your list")
menuBar = wx.MenuBar()
menuBar.Append(connectMenu,"&General")
menuBar.Append(contactMenu,"&Contacts")
self.SetMenuBar(menuBar)
#events
wx.EVT_MENU(self, idCONNECT, self.onConnectRequest)
wx.EVT_MENU(self, idPARAM, self.onParam)
wx.EVT_MENU(self, idEXIT, self.onExit)
wx.EVT_MENU(self, idADD_CONTACT, self.onAddContact)
wx.EVT_MENU(self, idREMOVE_CONTACT, self.onRemoveContact)
def newMessage(self, from_jid, msg, type, to_jid):
QuickApp.newMessage(self, from_jid, msg, type, to_jid)
def showAlert(self, message):
# TODO: place this in a separate class
popup=wx.PopupWindow(self)
### following code come from wxpython demo
popup.SetBackgroundColour("CADET BLUE")
st = wx.StaticText(popup, -1, message, pos=(10,10))
sz = st.GetBestSize()
popup.SetSize( (sz.width+20, sz.height+20) )
x=(wx.DisplaySize()[0]-popup.GetSize()[0])/2
popup.SetPosition((x,0))
popup.Show()
wx.CallLater(5000,popup.Destroy)
def showDialog(self, message, title="", type="info"):
if type == 'info':
flags = wx.OK | wx.ICON_INFORMATION
elif type == 'error':
flags = wx.OK | wx.ICON_ERROR
elif type == 'question':
flags = wx.OK | wx.ICON_QUESTION
else:
flags = wx.OK | wx.ICON_INFORMATION
dlg = wx.MessageDialog(self, message, title, flags)
answer = dlg.ShowModal()
dlg.Destroy()
return True if (answer == wx.ID_YES or answer == wx.ID_OK) else False
def setStatusOnline(self, online=True):
"""enable/disable controls, must be called when local user online status change"""
if online:
self.SetStatusText(msgONLINE)
self.tools.Enable()
else:
self.SetStatusText(msgOFFLINE)
self.tools.Disable()
return
def presenceUpdate(self, jabber_id, type, show, status, priority):
QuickApp.presenceUpdate(self, jabber_id, type, show, status, priority)
def askConfirmation(self, type, id, data):
#TODO: refactor this in QuickApp
debug ("Confirmation asked")
answer_data={}
if type == "FILE_TRANSFERT":
debug ("File transfert confirmation asked")
dlg = wx.MessageDialog(self, "The contact %s wants to send you the file %s\nDo you accept ?" % (data["from"], data["filename"]),
'File Request',
wx.YES_NO | wx.ICON_QUESTION
)
answer=dlg.ShowModal()
if answer==wx.ID_YES:
filename = wx.FileSelector("Where do you want to save the file ?", flags = wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
if filename:
answer_data["dest_path"] = filename
self.bridge.confirmationAnswer(id, True, answer_data)
self.waitProgress(id, "File Transfer", "Copying %s" % os.path.basename(filename))
else:
answer = wx.ID_NO
if answer==wx.ID_NO:
self.bridge.confirmationAnswer(id, False, answer_data)
dlg.Destroy()
def progressCB(self, id, title, message):
data = self.bridge.getProgress(id)
if data:
if not data['position']:
data['position'] = '0'
if not self.pbar:
#first answer, we must construct the bar
self.pbar = wx.ProgressDialog(title, message, int(data['size']), None,
wx.PD_SMOOTH | wx.PD_ELAPSED_TIME | wx.PD_ESTIMATED_TIME | wx.PD_REMAINING_TIME)
self.pbar.finish_value = int(data['size'])
self.pbar.Update(int(data['position']))
elif self.pbar:
self.pbar.Update(self.pbar.finish_value)
return
wx.CallLater(10, self.progressCB, id, title, message)
def waitProgress (self, id, title, message):
self.pbar = None
wx.CallLater(10, self.progressCB, id, title, message)
### events ###
def onContactActivated(self, jid):
debug ("onContactActivated: %s", jid)
if self.chat_wins[jid].IsShown():
self.chat_wins[jid].Hide()
else:
self.chat_wins[jid].Show()
def onConnectRequest(self, e):
self.bridge.connect()
def __updateStatus(self):
show = const_STATUS[self.statusBox.GetValue()]
status = self.statusTxt.GetValue()
self.bridge.setPresence(show=show, status=status)
def onStatusChange(self, e):
debug("Status change request")
self.__updateStatus()
def onParam(self, e):
debug("Param request")
param=Param(self.bridge.setParam, self.bridge.getParam, self.bridge.getParams, self.bridge.getParamsCategories)
def onExit(self, e):
self.Close()
def onAddContact(self, e):
debug("Add contact request")
dlg = wx.TextEntryDialog(
self, 'Please enter new contact JID',
'Adding a contact', 'name@server.ext')
if dlg.ShowModal() == wx.ID_OK:
jid=JID(dlg.GetValue())
if jid.is_valid():
self.bridge.addContact(jid.short)
else:
error ("'%s' is an invalid JID !", jid)
#TODO: notice the user
dlg.Destroy()
def onRemoveContact(self, e):
debug("Remove contact request")
target = self.contactList.getSelection()
if not target:
dlg = wx.MessageDialog(self, "You haven't selected any contact !",
'Error',
wx.OK | wx.ICON_ERROR
)
dlg.ShowModal()
dlg.Destroy()
return
dlg = wx.MessageDialog(self, "Are you sure you want to delete %s from your roster list ?" % target.short,
'Contact suppression',
wx.YES_NO | wx.ICON_QUESTION
)
if dlg.ShowModal() == wx.ID_YES:
info("Unsubsribing %s presence", target.short)
self.bridge.delContact(target.short)
dlg.Destroy()
def onClose(self, e):
info("Exiting...")
e.Skip()

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