view frontends/wix/chat.py @ 78:ace2af8abc5a

Added method to know which MUC are joined, and which subjects were received. - plugin xep-0045: new methods getRoomJoined and getRoomSubjects - wix: room joined are openned and subjects are set on profile plug
author Goffi <goffi@goffi.org>
date Wed, 31 Mar 2010 17:16:27 +1100
parents 1ae680f9682e
children db0a0f000e37
line wrap: on
line source

#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
wix: a SAT frontend
Copyright (C) 2009, 2010  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
from contact_list import ContactList


idSEND           = 1

class Chat(wx.Frame, QuickChat):
    """The chat Window for one to one conversations"""

    def __init__(self, target, host, type='one2one'):
        wx.Frame.__init__(self, None, title=target, pos=(0,0), size=(400,200))
        QuickChat.__init__(self, target, host, type) 

        self.splitter = wx.SplitterWindow(self, -1)
        
        self.conv_panel = wx.Panel(self.splitter)
        self.conv_panel.sizer = wx.BoxSizer(wx.VERTICAL)
        self.subjectBox = wx.TextCtrl(self.conv_panel, -1, style = wx.TE_READONLY)
        self.chatWindow = wx.TextCtrl(self.conv_panel, -1, style = wx.TE_MULTILINE | wx.TE_RICH | wx.TE_READONLY)
        self.textBox = wx.TextCtrl(self.conv_panel, -1, style = wx.TE_PROCESS_ENTER)
        self.conv_panel.sizer.Add(self.subjectBox, flag=wx.EXPAND)
        self.conv_panel.sizer.Add(self.chatWindow, 1, flag=wx.EXPAND)
        self.conv_panel.sizer.Add(self.textBox, flag=wx.EXPAND)
        self.conv_panel.SetSizer(self.conv_panel.sizer)
        self.splitter.Initialize(self.conv_panel)
        self.SetMenuBar(wx.MenuBar())
        self.setType(self.type)
        
        #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(profile=self.host.profile)

        #misc
        self.textBox.SetFocus()
        self.Hide() #We hide because of the show toggle
   
    def __createPresents(self):
        """Create a list of present people in a group chat"""
        self.present_panel = wx.Panel(self.splitter)
        self.present_panel.sizer = wx.BoxSizer(wx.VERTICAL)
        self.present_panel.SetBackgroundColour(wx.BLUE)
        self.present_panel.presents = ContactList(self.present_panel, self.host, type='nicks')
        self.present_panel.presents.SetMinSize(wx.Size(80,20))
        self.present_panel.sizer.Add(self.present_panel.presents, 1, wx.EXPAND)
        self.present_panel.SetSizer(self.present_panel.sizer)
        self.splitter.SplitVertically(self.present_panel, self.conv_panel, 80)

    def setType(self, type):
        QuickChat.setType(self, type)
        if type is 'group' and not self.splitter.IsSplit():
            self.__createPresents()
            self.subjectBox.Show()
            self.__eraseMenus()

        elif type is 'one2one' and self.splitter.IsSplit():
            self.splitter.Unsplit(self.present_panel)
            del self.present_panel
            self.GetMenuBar().Show()
            self.subjectBox.Hide()
            self.__createMenus_O2O()
        else:
            self.subjectBox.Hide()
            self.__createMenus_O2O()

    def setPresents(self, nicks):
        """Set the users presents in the contact list for a group chat
        @param nicks: list of nicknames
        """
        debug (_("Adding users %s to room") % nicks)
        if self.type != "group":
            error (_("[INTERNAL] trying to set presents nicks for a non group chat window"))
            return
        for nick in nicks:
           self.present_panel.presents.replace(nick)
    
    
    def replaceUser(self, nick):
        """Add user if it is not in the group list"""
        debug (_("Replacing user %s") % nick)
        if self.type != "group":
            error (_("[INTERNAL] trying to replace user for a non group chat window"))
            return
        self.present_panel.presents.replace(nick)
      
    def removeUser(self, nick):
        """Remove a user from the group list"""
        debug(_("Removing user %s") % nick)
        if self.type != "group":
            error (_("[INTERNAL] trying to remove user for a non group chat window"))
            return
        self.present_panel.presents.remove(nick)

    def setSubject(self, subject):
        """Set title for a group chat"""
        debug(_("Setting subject to %s") % subject)
        if self.type != "group":
            error (_("[INTERNAL] trying to set subject for a non group chat window"))
            return
        self.subjectBox.SetValue(subject)


    def __eraseMenus(self):
        """erase all menus"""
        menuBar = self.GetMenuBar()
        for i in range(menuBar.GetMenuCount()):
            menuBar.Remove(i)
    
    def __createMenus_O2O(self):
        """create menu bar for one 2 one chat"""
        info("Creating menus")
        self.__eraseMenus()
        menuBar = self.GetMenuBar()
        actionMenu = wx.Menu()
        actionMenu.Append(idSEND, _("&SendFile	CTRL-s"),_(" Send a file to contact"))
        menuBar.Append(actionMenu,_("&Action"))

        #events
        wx.EVT_MENU(self, idSEND, self.onSendFile)

    def __del__(self):
        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.target.short if self.type=='group' else self.target,
                                     event.GetString(), 
                                     type = "groupchat" if self.type=='group' else "chat",
                                     profile_key=self.host.profile)
        self.textBox.Clear()

        

    def printMessage(self, from_jid, msg, profile, timestamp=""):
        """Print the message with differents colors depending on where it comes from."""
        jid=JID(from_jid)
        nick = jid.resource if self.type == "group" else (self.host.CM.getAttr(jid,'nick') or self.host.CM.getAttr(jid,'name') or jid)
        mymess = (jid.short == self.host.profiles[profile]['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] " % nick)
        _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.target)
            id = self.host.bridge.sendFile(full_jid, filename)
            self.host.waitProgress(id, _("File Transfer"), _("Copying %s") % os.path.basename(filename))