chat_control.py 128 KB
Newer Older
roidelapluie's avatar
roidelapluie committed
1
# -*- coding:utf-8 -*-
roidelapluie's avatar
roidelapluie committed
2
## src/chat_control.py
nicfit's avatar
added  
nicfit committed
3
##
roidelapluie's avatar
roidelapluie committed
4
## Copyright (C) 2006 Dimitur Kirov <dkirov AT gmail.com>
Yann Leboulanger's avatar
Yann Leboulanger committed
5 6
## Copyright (C) 2006-2010 Yann Leboulanger <asterix AT lagaule.org>
## Copyright (C) 2006-2008 Jean-Marie Traissard <jim AT lapin.org>
roidelapluie's avatar
roidelapluie committed
7
##                         Nikos Kouremenos <kourem AT gmail.com>
nicfit's avatar
nicfit committed
8
##                         Travis Shirk <travis AT pobox.com>
roidelapluie's avatar
roidelapluie committed
9 10 11 12 13
## Copyright (C) 2007 Lukas Petrovicky <lukas AT petrovicky.net>
##                    Julien Pivotto <roidelapluie AT gmail.com>
## Copyright (C) 2007-2008 Brendan Taylor <whateley AT gmail.com>
##                         Stephan Erb <steve-e AT h3c.de>
## Copyright (C) 2008 Jonathan Schleifer <js-gajim AT webkeks.org>
nicfit's avatar
added  
nicfit committed
14
##
15 16 17
## This file is part of Gajim.
##
## Gajim is free software; you can redistribute it and/or modify
nicfit's avatar
added  
nicfit committed
18
## it under the terms of the GNU General Public License as published
19
## by the Free Software Foundation; version 3 only.
nicfit's avatar
added  
nicfit committed
20
##
21
## Gajim is distributed in the hope that it will be useful,
nicfit's avatar
added  
nicfit committed
22
## but WITHOUT ANY WARRANTY; without even the implied warranty of
roidelapluie's avatar
roidelapluie committed
23
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
nicfit's avatar
added  
nicfit committed
24 25
## GNU General Public License for more details.
##
26
## You should have received a copy of the GNU General Public License
roidelapluie's avatar
roidelapluie committed
27
## along with Gajim. If not, see <http://www.gnu.org/licenses/>.
28
##
nicfit's avatar
added  
nicfit committed
29

nkour's avatar
nkour committed
30
import os
nicfit's avatar
nicfit committed
31
import time
nicfit's avatar
added  
nicfit committed
32 33 34 35
import gtk
import pango
import gobject
import gtkgui_helpers
36
import gui_menu_builder
37
import message_control
nicfit's avatar
nicfit committed
38
import dialogs
39
import history_window
40
import notify
41
import re
nicfit's avatar
added  
nicfit committed
42 43

from common import gajim
nicfit's avatar
nicfit committed
44
from common import helpers
45
from common import exceptions
46
from common import ged
47
from message_control import MessageControl
nicfit's avatar
added  
nicfit committed
48 49
from conversation_textview import ConversationTextview
from message_textview import MessageTextView
50
from common.stanza_session import EncryptedStanzaSession, ArchivingStanzaSession
51
from common.contacts import GC_Contact
52
from common.logger import constants
js's avatar
js committed
53
from common.pep import MOODS, ACTIVITIES
54 55
from common.xmpp.protocol import NS_XHTML, NS_XHTML_IM, NS_FILE, NS_MUC
from common.xmpp.protocol import NS_RECEIPTS, NS_ESESSION
56
from common.xmpp.protocol import NS_JINGLE_RTP_AUDIO, NS_JINGLE_RTP_VIDEO, NS_JINGLE_ICE_UDP
nicfit's avatar
added  
nicfit committed
57

58 59 60 61 62 63 64
from command_system.implementation.middleware import ChatCommandProcessor
from command_system.implementation.middleware import CommandTools
from command_system.implementation.hosts import ChatCommands

# Here we load the module with the standard commands, so they are being detected
# and dispatched.
import command_system.implementation.standard
65

nicfit's avatar
nicfit committed
66
try:
67 68
    import gtkspell
    HAS_GTK_SPELL = True
69
except ImportError:
70
    HAS_GTK_SPELL = False
nicfit's avatar
nicfit committed
71

72
from common import dbus_support
Dicson's avatar
Dicson committed
73
if dbus_support.supported:
74 75 76
    import dbus
    import remote_control

77 78 79
# the next script, executed in the "po" directory,
# generates the following list.
##!/bin/sh
80
#LANG=$(for i in *.po; do j=${i/.po/}; echo -n "_('"$j"')":" '"$j"', " ; done)
81
#echo "{_('en'):'en'",$LANG"}"
82
langs = {_('English'): 'en', _('Belarusian'): 'be', _('Bulgarian'): 'bg', _('Breton'): 'br', _('Czech'): 'cs', _('German'): 'de', _('Greek'): 'el', _('British'): 'en_GB', _('Esperanto'): 'eo', _('Spanish'): 'es', _('Basque'): 'eu', _('French'): 'fr', _('Croatian'): 'hr', _('Italian'): 'it', _('Norwegian (b)'): 'nb', _('Dutch'): 'nl', _('Norwegian'): 'no', _('Polish'): 'pl', _('Portuguese'): 'pt', _('Brazilian Portuguese'): 'pt_BR', _('Russian'): 'ru', _('Serbian'): 'sr', _('Slovak'): 'sk', _('Swedish'): 'sv', _('Chinese (Ch)'): 'zh_CN'}
83

84
if gajim.config.get('use_speller') and HAS_GTK_SPELL:
85 86 87 88 89 90 91 92 93 94 95 96
    # loop removing non-existent dictionaries
    # iterating on a copy
    tv = gtk.TextView()
    spell = gtkspell.Spell(tv)
    for lang in dict(langs):
        try:
            spell.set_language(langs[lang])
        except OSError:
            del langs[lang]
    if spell:
        spell.detach()
    del tv
97

98

99
################################################################################
100
class ChatControlBase(MessageControl, ChatCommandProcessor, CommandTools):
101 102 103 104
    """
    A base class containing a banner, ConversationTextview, MessageTextView
    """

105
    keymap = gtk.gdk.keymap_get_default()
106 107 108 109 110 111 112 113
    try:
        keycode_c = keymap.get_entries_for_keyval(gtk.keysyms.c)[0][0]
    except TypeError:
        keycode_c = 54
    try:
        keycode_ins = keymap.get_entries_for_keyval(gtk.keysyms.Insert)[0][0]
    except TypeError:
        keycode_ins = 118
114

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
    def make_href(self, match):
        url_color = gajim.config.get('urlmsgcolor')
        url = match.group()
        if not '://' in url:
            url = 'http://' + url
        return '<a href="%s"><span color="%s">%s</span></a>' % (url,
                url_color, match.group())

    def get_font_attrs(self):
        """
        Get pango font attributes for banner from theme settings
        """
        theme = gajim.config.get('roster_theme')
        bannerfont = gajim.config.get_per('themes', theme, 'bannerfont')
        bannerfontattrs = gajim.config.get_per('themes', theme, 'bannerfontattrs')

        if bannerfont:
            font = pango.FontDescription(bannerfont)
        else:
            font = pango.FontDescription('Normal')
        if bannerfontattrs:
            # B attribute is set by default
            if 'B' in bannerfontattrs:
                font.set_weight(pango.WEIGHT_HEAVY)
            if 'I' in bannerfontattrs:
                font.set_style(pango.STYLE_ITALIC)

        font_attrs = 'font_desc="%s"' % font.to_string()

        # in case there is no font specified we use x-large font size
        if font.get_size() == 0:
            font_attrs = '%s size="x-large"' % font_attrs
        font.set_weight(pango.WEIGHT_NORMAL)
        font_attrs_small = 'font_desc="%s" size="small"' % font.to_string()
        return (font_attrs, font_attrs_small)

    def get_nb_unread(self):
        jid = self.contact.jid
        if self.resource:
            jid += '/' + self.resource
        type_ = self.type_id
        return len(gajim.events.get_events(self.account, jid, ['printed_' + type_,
                type_]))

    def draw_banner(self):
        """
        Draw the fat line at the top of the window that houses the icon, jid, etc

        Derived types MAY implement this.
        """
        self.draw_banner_text()
        self._update_banner_state_image()
167
        gajim.plugin_manager.gui_extension_point('chat_control_base_draw_banner',
Yann Leboulanger's avatar
Yann Leboulanger committed
168
            self)
169

170 171 172 173 174 175 176 177
    def update_toolbar(self):
        """
        update state of buttons in toolbar
        """
        self._update_toolbar()
        gajim.plugin_manager.gui_extension_point(
            'chat_control_base_update_toolbar', self)

178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
    def draw_banner_text(self):
        """
        Derived types SHOULD implement this
        """
        pass

    def update_ui(self):
        """
        Derived types SHOULD implement this
        """
        self.draw_banner()

    def repaint_themed_widgets(self):
        """
        Derived types MAY implement this
        """
        self._paint_banner()
        self.draw_banner()

    def _update_banner_state_image(self):
        """
        Derived types MAY implement this
        """
        pass

203 204 205 206 207 208
    def _update_toolbar(self):
        """
        Derived types MAY implement this
        """
        pass

209 210 211 212 213 214 215 216 217 218 219 220 221
    def _nec_our_status(self, obj):
        if self.account != obj.conn.name:
            return
        if obj.show == 'offline' or (obj.show == 'invisible' and \
        obj.conn.is_zeroconf):
            self.got_disconnected()
        else:
            # Other code rejoins all GCs, so we don't do it here
            if not self.type_id == message_control.TYPE_GC:
                self.got_connected()
        if self.parent_win:
            self.parent_win.redraw_tab(self)

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
    def _nec_ping_sent(self, obj):
        if self.contact != obj.contact:
            return
        self.print_conversation(_('Ping?'), 'status')

    def _nec_ping_reply(self, obj):
        if self.contact != obj.contact:
            return
        self.print_conversation(_('Pong! (%s s.)') % obj.seconds, 'status')

    def _nec_ping_error(self, obj):
        if self.contact != obj.contact:
            return
        self.print_conversation(_('Error.'), 'status')

237
    def handle_message_textview_mykey_press(self, widget, event_keyval,
238
    event_keymod):
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
        """
        Derives types SHOULD implement this, rather than connection to the even
        itself
        """
        event = gtk.gdk.Event(gtk.gdk.KEY_PRESS)
        event.keyval = event_keyval
        event.state = event_keymod
        event.time = 0

        _buffer = widget.get_buffer()
        start, end = _buffer.get_bounds()

        if event.keyval -- gtk.keysyms.Tab:
            position = _buffer.get_insert()
            end = _buffer.get_iter_at_mark(position)

            text = _buffer.get_text(start, end, False)
            text = text.decode('utf8')

            splitted = text.split()

            if (text.startswith(self.COMMAND_PREFIX) and not
                    text.startswith(self.COMMAND_PREFIX * 2) and len(splitted) == 1):

                text = splitted[0]
                bare = text.lstrip(self.COMMAND_PREFIX)

                if len(text) == 1:
                    self.command_hits = []
                    for command in self.list_commands():
                        for name in command.names:
                            self.command_hits.append(name)
                else:
                    if (self.last_key_tabs and self.command_hits and
                            self.command_hits[0].startswith(bare)):
                        self.command_hits.append(self.command_hits.pop(0))
                    else:
                        self.command_hits = []
                        for command in self.list_commands():
                            for name in command.names:
                                if name.startswith(bare):
                                    self.command_hits.append(name)

                if self.command_hits:
                    _buffer.delete(start, end)
                    _buffer.insert_at_cursor(self.COMMAND_PREFIX + self.command_hits[0] + ' ')
                    self.last_key_tabs = True

                return True

            self.last_key_tabs = False

    def status_url_clicked(self, widget, url):
        helpers.launch_browser_mailer('url', url)

294 295 296 297 298 299 300
    def setup_seclabel(self, combo):
        self.seclabel_combo = combo
        self.seclabel_combo.hide()
        self.seclabel_combo.set_no_show_all(True)
        lb = gtk.ListStore(str)
        self.seclabel_combo.set_model(lb)
        cell = gtk.CellRendererText()
301
        cell.set_property('xpad', 5)  # padding for status text
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
        self.seclabel_combo.pack_start(cell, True)
        # text to show is in in first column of liststore
        self.seclabel_combo.add_attribute(cell, 'text', 0)
        if gajim.connections[self.account].seclabel_supported:
            gajim.connections[self.account].seclabel_catalogue(self.contact.jid, self.on_seclabels_ready)

    def on_seclabels_ready(self):
        lb = self.seclabel_combo.get_model()
        lb.clear()
        for label in gajim.connections[self.account].seclabel_catalogues[self.contact.jid][2]:
            lb.append([label])
        self.seclabel_combo.set_active(0)
        self.seclabel_combo.set_no_show_all(False)
        self.seclabel_combo.show_all()

317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
    def __init__(self, type_id, parent_win, widget_name, contact, acct,
    resource=None):
        # Undo needs this variable to know if space has been pressed.
        # Initialize it to True so empty textview is saved in undo list
        self.space_pressed = True

        if resource is None:
            # We very likely got a contact with a random resource.
            # This is bad, we need the highest for caps etc.
            c = gajim.contacts.get_contact_with_highest_priority(
                    acct, contact.jid)
            if c and not isinstance(c, GC_Contact):
                contact = c

        MessageControl.__init__(self, type_id, parent_win, widget_name,
                contact, acct, resource=resource)

        widget = self.xml.get_object('history_button')
        id_ = widget.connect('clicked', self._on_history_menuitem_activate)
        self.handlers[id_] = widget

        # when/if we do XHTML we will put formatting buttons back
        widget = self.xml.get_object('emoticons_button')
        id_ = widget.connect('clicked', self.on_emoticons_button_clicked)
        self.handlers[id_] = widget

        # Create banner and connect signals
        widget = self.xml.get_object('banner_eventbox')
        id_ = widget.connect('button-press-event',
                self._on_banner_eventbox_button_press_event)
        self.handlers[id_] = widget

        self.urlfinder = re.compile(
                r"(www\.(?!\.)|[a-z][a-z0-9+.-]*://)[^\s<>'\"]+[^!,\.\s<>\)'\"\]]")

        self.banner_status_label = self.xml.get_object('banner_label')
        id_ = self.banner_status_label.connect('populate_popup',
                self.on_banner_label_populate_popup)
        self.handlers[id_] = self.banner_status_label

        # Init DND
        self.TARGET_TYPE_URI_LIST = 80
359
        self.dnd_list = [('text/uri-list', 0, self.TARGET_TYPE_URI_LIST),
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
                        ('MY_TREE_MODEL_ROW', gtk.TARGET_SAME_APP, 0)]
        id_ = self.widget.connect('drag_data_received',
                self._on_drag_data_received)
        self.handlers[id_] = self.widget
        self.widget.drag_dest_set(gtk.DEST_DEFAULT_MOTION |
                gtk.DEST_DEFAULT_HIGHLIGHT |
                gtk.DEST_DEFAULT_DROP,
                self.dnd_list, gtk.gdk.ACTION_COPY)

        # Create textviews and connect signals
        self.conv_textview = ConversationTextview(self.account)
        id_ = self.conv_textview.connect('quote', self.on_quote)
        self.handlers[id_] = self.conv_textview.tv
        id_ = self.conv_textview.tv.connect('key_press_event',
                self._conv_textview_key_press_event)
        self.handlers[id_] = self.conv_textview.tv
        # FIXME: DND on non editable TextView, find a better way
        self.drag_entered = False
        id_ = self.conv_textview.tv.connect('drag_data_received',
                self._on_drag_data_received)
        self.handlers[id_] = self.conv_textview.tv
        id_ = self.conv_textview.tv.connect('drag_motion', self._on_drag_motion)
        self.handlers[id_] = self.conv_textview.tv
        id_ = self.conv_textview.tv.connect('drag_leave', self._on_drag_leave)
        self.handlers[id_] = self.conv_textview.tv
        self.conv_textview.tv.drag_dest_set(gtk.DEST_DEFAULT_MOTION |
                gtk.DEST_DEFAULT_HIGHLIGHT |
                gtk.DEST_DEFAULT_DROP,
                self.dnd_list, gtk.gdk.ACTION_COPY)

        self.conv_scrolledwindow = self.xml.get_object(
                'conversation_scrolledwindow')
        self.conv_scrolledwindow.add(self.conv_textview.tv)
        widget = self.conv_scrolledwindow.get_vadjustment()
        id_ = widget.connect('value-changed',
                self.on_conversation_vadjustment_value_changed)
        self.handlers[id_] = widget
        id_ = widget.connect('changed',
                self.on_conversation_vadjustment_changed)
        self.handlers[id_] = widget
        self.scroll_to_end_id = None
        self.was_at_the_end = True

        # add MessageTextView to UI and connect signals
        self.msg_scrolledwindow = self.xml.get_object('message_scrolledwindow')
        self.msg_textview = MessageTextView()
        id_ = self.msg_textview.connect('mykeypress',
                self._on_message_textview_mykeypress_event)
        self.handlers[id_] = self.msg_textview
        self.msg_scrolledwindow.add(self.msg_textview)
        id_ = self.msg_textview.connect('key_press_event',
                self._on_message_textview_key_press_event)
        self.handlers[id_] = self.msg_textview
        id_ = self.msg_textview.connect('size-request', self.size_request)
        self.handlers[id_] = self.msg_textview
        id_ = self.msg_textview.connect('populate_popup',
                self.on_msg_textview_populate_popup)
        self.handlers[id_] = self.msg_textview
        # Setup DND
        id_ = self.msg_textview.connect('drag_data_received',
                self._on_drag_data_received)
        self.handlers[id_] = self.msg_textview
        self.msg_textview.drag_dest_set(gtk.DEST_DEFAULT_MOTION |
                gtk.DEST_DEFAULT_HIGHLIGHT,
                self.dnd_list, gtk.gdk.ACTION_COPY)

        self.update_font()

        # Hook up send button
        widget = self.xml.get_object('send_button')
        id_ = widget.connect('clicked', self._on_send_button_clicked)
        self.handlers[id_] = widget

        widget = self.xml.get_object('formattings_button')
        id_ = widget.connect('clicked', self.on_formattings_button_clicked)
        self.handlers[id_] = widget

        # the following vars are used to keep history of user's messages
        self.sent_history = []
        self.sent_history_pos = 0
440 441
        self.received_history = []
        self.received_history_pos = 0
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
        self.orig_msg = None

        # Emoticons menu
        # set image no matter if user wants at this time emoticons or not
        # (so toggle works ok)
        img = self.xml.get_object('emoticons_button_image')
        img.set_from_file(os.path.join(gajim.DATA_DIR, 'emoticons', 'static',
                'smile.png'))
        self.toggle_emoticons()

        # Attach speller
        if gajim.config.get('use_speller') and HAS_GTK_SPELL:
            self.set_speller()
        self.conv_textview.tv.show()
        self._paint_banner()

        # For XEP-0172
        self.user_nick = None

        self.smooth = True
        self.msg_textview.grab_focus()

        self.command_hits = []
        self.last_key_tabs = False

467 468 469 470
        # PluginSystem: adding GUI extension point for ChatControlBase
        # instance object (also subclasses, eg. ChatControl or GroupchatControl)
        gajim.plugin_manager.gui_extension_point('chat_control_base', self)

471 472
        gajim.ged.register_event_handler('our-show', ged.GUI1,
            self._nec_our_status)
473 474 475 476 477 478
        gajim.ged.register_event_handler('ping-sent', ged.GUI1,
            self._nec_ping_sent)
        gajim.ged.register_event_handler('ping-reply', ged.GUI1,
            self._nec_ping_reply)
        gajim.ged.register_event_handler('ping-error', ged.GUI1,
            self._nec_ping_error)
479

480 481 482 483
        # This is bascially a very nasty hack to surpass the inability
        # to properly use the super, because of the old code.
        CommandTools.__init__(self)

484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
    def set_speller(self):
        # now set the one the user selected
        per_type = 'contacts'
        if self.type_id == message_control.TYPE_GC:
            per_type = 'rooms'
        lang = gajim.config.get_per(per_type, self.contact.jid,
                'speller_language')
        if not lang:
            # use the default one
            lang = gajim.config.get('speller_language')
            if not lang:
                lang = gajim.LANG
        if lang:
            try:
                gtkspell.Spell(self.msg_textview, lang)
                self.msg_textview.lang = lang
            except (gobject.GError, RuntimeError, TypeError, OSError):
                dialogs.AspellDictError(lang)

    def on_banner_label_populate_popup(self, label, menu):
        """
        Override the default context menu and add our own menutiems
        """
        item = gtk.SeparatorMenuItem()
        menu.prepend(item)

        menu2 = self.prepare_context_menu()
        i = 0
        for item in menu2:
            menu2.remove(item)
            menu.prepend(item)
            menu.reorder_child(item, i)
            i += 1
        menu.show_all()

519 520 521 522 523
    def shutdown(self):
        # PluginSystem: removing GUI extension points connected with ChatControlBase
        # instance object
        gajim.plugin_manager.remove_gui_extension_point('chat_control_base', self)
        gajim.plugin_manager.remove_gui_extension_point('chat_control_base_draw_banner', self)
524 525
        gajim.ged.remove_event_handler('our-show', ged.GUI1,
            self._nec_our_status)
526

527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
    def on_msg_textview_populate_popup(self, textview, menu):
        """
        Override the default context menu and we prepend an option to switch
        languages
        """
        def _on_select_dictionary(widget, lang):
            per_type = 'contacts'
            if self.type_id == message_control.TYPE_GC:
                per_type = 'rooms'
            if not gajim.config.get_per(per_type, self.contact.jid):
                gajim.config.add_per(per_type, self.contact.jid)
            gajim.config.set_per(per_type, self.contact.jid, 'speller_language',
                    lang)
            spell = gtkspell.get_from_text_view(self.msg_textview)
            self.msg_textview.lang = lang
            spell.set_language(lang)
            widget.set_active(True)

        item = gtk.ImageMenuItem(gtk.STOCK_UNDO)
        menu.prepend(item)
        id_ = item.connect('activate', self.msg_textview.undo)
        self.handlers[id_] = item

        item = gtk.SeparatorMenuItem()
        menu.prepend(item)

        item = gtk.ImageMenuItem(gtk.STOCK_CLEAR)
        menu.prepend(item)
        id_ = item.connect('activate', self.msg_textview.clear)
        self.handlers[id_] = item

        if gajim.config.get('use_speller') and HAS_GTK_SPELL:
            item = gtk.MenuItem(_('Spelling language'))
            menu.prepend(item)
            submenu = gtk.Menu()
            item.set_submenu(submenu)
            for lang in sorted(langs):
                item = gtk.CheckMenuItem(lang)
                if langs[lang] == self.msg_textview.lang:
                    item.set_active(True)
                submenu.append(item)
                id_ = item.connect('activate', _on_select_dictionary, langs[lang])
                self.handlers[id_] = item

        menu.show_all()

    def on_quote(self, widget, text):
        text = '>' + text.replace('\n', '\n>') + '\n'
        message_buffer = self.msg_textview.get_buffer()
        message_buffer.insert_at_cursor(text)

    # moved from ChatControl
    def _on_banner_eventbox_button_press_event(self, widget, event):
        """
        If right-clicked, show popup
        """
583
        if event.button == 3:  # right click
584 585 586 587 588 589
            self.parent_win.popup_menu(event)

    def _on_send_button_clicked(self, widget):
        """
        When send button is pressed: send the current message
        """
590
        if gajim.connections[self.account].connected < 2:  # we are not connected
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
            dialogs.ErrorDialog(_('A connection is not available'),
                    _('Your message can not be sent until you are connected.'))
            return
        message_buffer = self.msg_textview.get_buffer()
        start_iter = message_buffer.get_start_iter()
        end_iter = message_buffer.get_end_iter()
        message = message_buffer.get_text(start_iter, end_iter, 0).decode('utf-8')
        xhtml = self.msg_textview.get_xhtml()

        # send the message
        self.send_message(message, xhtml=xhtml)

    def _paint_banner(self):
        """
        Repaint banner with theme color
        """
        theme = gajim.config.get('roster_theme')
        bgcolor = gajim.config.get_per('themes', theme, 'bannerbgcolor')
        textcolor = gajim.config.get_per('themes', theme, 'bannertextcolor')
        # the backgrounds are colored by using an eventbox by
        # setting the bg color of the eventbox and the fg of the name_label
        banner_eventbox = self.xml.get_object('banner_eventbox')
        banner_name_label = self.xml.get_object('banner_name_label')
        self.disconnect_style_event(banner_name_label)
        self.disconnect_style_event(self.banner_status_label)
        if bgcolor:
            banner_eventbox.modify_bg(gtk.STATE_NORMAL,
                    gtk.gdk.color_parse(bgcolor))
            default_bg = False
        else:
            default_bg = True
        if textcolor:
            banner_name_label.modify_fg(gtk.STATE_NORMAL,
                    gtk.gdk.color_parse(textcolor))
            self.banner_status_label.modify_fg(gtk.STATE_NORMAL,
                    gtk.gdk.color_parse(textcolor))
            default_fg = False
        else:
            default_fg = True
        if default_bg or default_fg:
            self._on_style_set_event(banner_name_label, None, default_fg,
                    default_bg)
            if self.banner_status_label.flags() & gtk.REALIZED:
                # Widget is realized
                self._on_style_set_event(self.banner_status_label, None, default_fg,
                        default_bg)

    def disconnect_style_event(self, widget):
        # Try to find the event_id
        for id_ in self.handlers.keys():
            if self.handlers[id_] == widget:
                widget.disconnect(id_)
                del self.handlers[id_]
                break

646
    def connect_style_event(self, widget, set_fg=False, set_bg=False):
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
        self.disconnect_style_event(widget)
        id_ = widget.connect('style-set', self._on_style_set_event, set_fg,
                set_bg)
        self.handlers[id_] = widget

    def _on_style_set_event(self, widget, style, *opts):
        """
        Set style of widget from style class *.Frame.Eventbox
                opts[0] == True -> set fg color
                opts[1] == True -> set bg color
        """
        banner_eventbox = self.xml.get_object('banner_eventbox')
        self.disconnect_style_event(widget)
        if opts[1]:
            bg_color = widget.style.bg[gtk.STATE_SELECTED]
            banner_eventbox.modify_bg(gtk.STATE_NORMAL, bg_color)
        if opts[0]:
            fg_color = widget.style.fg[gtk.STATE_SELECTED]
            widget.modify_fg(gtk.STATE_NORMAL, fg_color)
        self.connect_style_event(widget, opts[0], opts[1])

    def _conv_textview_key_press_event(self, widget, event):
669 670
        # translate any layout to latin_layout
        keymap = gtk.gdk.keymap_get_default()
671
        keycode = keymap.get_entries_for_keyval(event.keyval)[0][0]
672 673
        if (event.state & gtk.gdk.CONTROL_MASK and keycode in (self.keycode_c,
        self.keycode_ins)) or (event.state & gtk.gdk.SHIFT_MASK and \
674 675 676 677 678 679 680 681
        event.keyval in (gtk.keysyms.Page_Down, gtk.keysyms.Page_Up)):
            return False
        self.parent_win.notebook.emit('key_press_event', event)
        return True

    def show_emoticons_menu(self):
        if not gajim.config.get('emoticons_theme'):
            return
682 683

        def set_emoticons_menu_position(w, msg_tv=self.msg_textview):
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
            window = msg_tv.get_window(gtk.TEXT_WINDOW_WIDGET)
            # get the window position
            origin = window.get_origin()
            size = window.get_size()
            buf = msg_tv.get_buffer()
            # get the cursor position
            cursor = msg_tv.get_iter_location(buf.get_iter_at_mark(
                    buf.get_insert()))
            cursor = msg_tv.buffer_to_window_coords(gtk.TEXT_WINDOW_TEXT,
                    cursor.x, cursor.y)
            x = origin[0] + cursor[0]
            y = origin[1] + size[1]
            menu_height = gajim.interface.emoticons_menu.size_request()[1]
            #FIXME: get_line_count is not so good
            #get the iter of cursor, then tv.get_line_yrange
            # so we know in which y we are typing (not how many lines we have
            # then go show just above the current cursor line for up
            # or just below the current cursor line for down
            #TEST with having 3 lines and writing in the 2nd
            if y + menu_height > gtk.gdk.screen_height():
                # move menu just above cursor
                y -= menu_height + (msg_tv.allocation.height / buf.get_line_count())
            #else: # move menu just below cursor
            #       y -= (msg_tv.allocation.height / buf.get_line_count())
708
            return (x, y, True)  # push_in True
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
        gajim.interface.emoticon_menuitem_clicked = self.append_emoticon
        gajim.interface.emoticons_menu.popup(None, None,
                set_emoticons_menu_position, 1, 0)

    def _on_message_textview_key_press_event(self, widget, event):
        if event.keyval == gtk.keysyms.space:
            self.space_pressed = True

        elif (self.space_pressed or self.msg_textview.undo_pressed) and \
        event.keyval not in (gtk.keysyms.Control_L, gtk.keysyms.Control_R) and \
        not (event.keyval == gtk.keysyms.z and event.state & gtk.gdk.CONTROL_MASK):
            # If the space key has been pressed and now it hasnt,
            # we save the buffer into the undo list. But be carefull we're not
            # pressiong Control again (as in ctrl+z)
            _buffer = widget.get_buffer()
            start_iter, end_iter = _buffer.get_bounds()
            self.msg_textview.save_undo(_buffer.get_text(start_iter, end_iter))
            self.space_pressed = False

        # Ctrl [+ Shift] + Tab are not forwarded to notebook. We handle it here
        if self.widget_name == 'groupchat_control':
            if event.keyval not in (gtk.keysyms.ISO_Left_Tab, gtk.keysyms.Tab):
                self.last_key_tabs = False
        if event.state & gtk.gdk.SHIFT_MASK:
            # CTRL + SHIFT + TAB
            if event.state & gtk.gdk.CONTROL_MASK and \
                            event.keyval == gtk.keysyms.ISO_Left_Tab:
                self.parent_win.move_to_next_unread_tab(False)
                return True
            # SHIFT + PAGE_[UP|DOWN]: send to conv_textview
            elif event.keyval == gtk.keysyms.Page_Down or \
                            event.keyval == gtk.keysyms.Page_Up:
                self.conv_textview.tv.emit('key_press_event', event)
                return True
        elif event.state & gtk.gdk.CONTROL_MASK:
744
            if event.keyval == gtk.keysyms.Tab:  # CTRL + TAB
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
                self.parent_win.move_to_next_unread_tab(True)
                return True
        return False

    def _on_message_textview_mykeypress_event(self, widget, event_keyval,
    event_keymod):
        """
        When a key is pressed: if enter is pressed without the shift key, message
        (if not empty) is sent and printed in the conversation
        """
        # NOTE: handles mykeypress which is custom signal connected to this
        # CB in new_tab(). for this singal see message_textview.py
        message_textview = widget
        message_buffer = message_textview.get_buffer()
        start_iter, end_iter = message_buffer.get_bounds()
        message = message_buffer.get_text(start_iter, end_iter, False).decode(
                'utf-8')
        xhtml = self.msg_textview.get_xhtml()

        # construct event instance from binding
765
        event = gtk.gdk.Event(gtk.gdk.KEY_PRESS)  # it's always a key-press here
766 767
        event.keyval = event_keyval
        event.state = event_keymod
768
        event.time = 0  # assign current time
769 770

        if event.keyval == gtk.keysyms.Up:
771 772 773 774 775
            if event.state == gtk.gdk.CONTROL_MASK:  # Ctrl+UP
                self.scroll_messages('up', message_buffer, 'sent')
            # Ctrl+Shift+UP
            elif event.state == (gtk.gdk.CONTROL_MASK | gtk.gdk.SHIFT_MASK):
                self.scroll_messages('up', message_buffer, 'received')
776
        elif event.keyval == gtk.keysyms.Down:
777 778 779 780 781
            if event.state == gtk.gdk.CONTROL_MASK:  # Ctrl+Down
                self.scroll_messages('down', message_buffer, 'sent')
            # Ctrl+Shift+Down
            elif event.state == (gtk.gdk.CONTROL_MASK | gtk.gdk.SHIFT_MASK):
                self.scroll_messages('down', message_buffer, 'received')
782
        elif event.keyval == gtk.keysyms.Return or \
783
                event.keyval == gtk.keysyms.KP_Enter:  # ENTER
784 785 786 787 788 789 790
            # NOTE: SHIFT + ENTER is not needed to be emulated as it is not
            # binding at all (textview's default action is newline)

            if gajim.config.get('send_on_ctrl_enter'):
                # here, we emulate GTK default action on ENTER (add new line)
                # normally I would add in keypress but it gets way to complex
                # to get instant result on changing this advanced setting
791
                if event.state == 0:  # no ctrl, no shift just ENTER add newline
792 793 794
                    end_iter = message_buffer.get_end_iter()
                    message_buffer.insert_at_cursor('\n')
                    send_message = False
795
                elif event.state & gtk.gdk.CONTROL_MASK:  # CTRL + ENTER
796 797
                    send_message = True
            else: # send on Enter, do newline on Ctrl Enter
798
                if event.state & gtk.gdk.CONTROL_MASK:  # Ctrl + ENTER
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
                    end_iter = message_buffer.get_end_iter()
                    message_buffer.insert_at_cursor('\n')
                    send_message = False
                else: # ENTER
                    send_message = True

            if gajim.connections[self.account].connected < 2 and send_message:
                # we are not connected
                dialogs.ErrorDialog(_('A connection is not available'),
                        _('Your message can not be sent until you are connected.'))
                send_message = False

            if send_message:
                self.send_message(message, xhtml=xhtml) # send the message
        elif event.keyval == gtk.keysyms.z: # CTRL+z
            if event.state & gtk.gdk.CONTROL_MASK:
                self.msg_textview.undo()
        else:
            # Give the control itself a chance to process
            self.handle_message_textview_mykey_press(widget, event_keyval,
                    event_keymod)

    def _on_drag_data_received(self, widget, context, x, y, selection,
                    target_type, timestamp):
        """
        Derived types SHOULD implement this
        """
        pass

    def _on_drag_leave(self, widget, context, time):
        # FIXME: DND on non editable TextView, find a better way
        self.drag_entered = False
        self.conv_textview.tv.set_editable(False)

    def _on_drag_motion(self, widget, context, x, y, time):
        # FIXME: DND on non editable TextView, find a better way
        if not self.drag_entered:
            # We drag new data over the TextView, make it editable to catch dnd
            self.drag_entered_conv = True
            self.conv_textview.tv.set_editable(True)

840 841 842 843 844 845 846 847 848 849
    def get_seclabel(self):
        label = None
        if self.seclabel_combo is not None:
            idx = self.seclabel_combo.get_active()
            if idx != -1:
                cat = gajim.connections[self.account].seclabel_catalogues[self.contact.jid]
                lname = cat[2][idx]
                label = cat[1][lname]
        return label

850 851 852 853 854 855 856 857 858 859 860 861
    def send_message(self, message, keyID='', type_='chat', chatstate=None,
                    msg_id=None, composing_xep=None, resource=None, xhtml=None,
                    callback=None, callback_args=[], process_commands=True):
        """
        Send the given message to the active tab. Doesn't return None if error
        """
        if not message or message == '\n':
            return None

        if process_commands and self.process_as_command(message):
            return

862
        label = self.get_seclabel()
863 864 865
        MessageControl.send_message(self, message, keyID, type_=type_,
                chatstate=chatstate, msg_id=msg_id, composing_xep=composing_xep,
                resource=resource, user_nick=self.user_nick, xhtml=xhtml,
866
                label=label,
867 868
                callback=callback, callback_args=callback_args)

869 870
        # Record the history of sent messages
        self.save_message(message, 'sent')
871 872 873 874 875 876 877 878

        # Be sure to send user nickname only once according to JEP-0172
        self.user_nick = None

        # Clear msg input
        message_buffer = self.msg_textview.get_buffer()
        message_buffer.set_text('') # clear message buffer (and tv of course)

879
    def save_message(self, message, msg_type):
880
        # save the message, so user can scroll though the list with key up/down
881 882
        if msg_type == 'sent':
            history = self.sent_history
883
            pos = self.sent_history_pos
884 885
        else:
            history = self.received_history
886 887 888
            pos = self.received_history_pos
        size = len(history)
        scroll = False if pos == size else True # are we scrolling?
889 890
        # we don't want size of the buffer to grow indefinately
        max_size = gajim.config.get('key_up_lines')
891
        for i in xrange(size - max_size + 1):
892 893
            if pos == 0:
                break
894
            history.pop(0)
895
            pos -= 1
896
        history.append(message)
897 898
        if not scroll or msg_type == 'sent':
            pos = len(history)
899
        if msg_type == 'sent':
900 901
            self.sent_history_pos = pos
            self.orig_msg = None
902
        else:
903
            self.received_history_pos = pos
904 905 906 907 908

    def print_conversation_line(self, text, kind, name, tim,
                    other_tags_for_name=[], other_tags_for_time=[],
                    other_tags_for_text=[], count_as_new=True, subject=None,
                    old_kind=None, xhtml=None, simple=False, xep0184_id=None,
909
                    graphics=True, displaymarking=None):
910 911 912 913 914 915 916 917 918 919 920
        """
        Print 'chat' type messages
        """
        jid = self.contact.jid
        full_jid = self.get_full_jid()
        textview = self.conv_textview
        end = False
        if self.was_at_the_end or kind == 'outgoing':
            end = True
        textview.print_conversation_line(text, jid, kind, name, tim,
                other_tags_for_name, other_tags_for_time, other_tags_for_text,
921 922
                subject, old_kind, xhtml, simple=simple, graphics=graphics,
                displaymarking=displaymarking)
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937

        if xep0184_id is not None:
            textview.show_xep0184_warning(xep0184_id)

        if not count_as_new:
            return
        if kind == 'incoming':
            if not self.type_id == message_control.TYPE_GC or \
            gajim.config.get('notify_on_all_muc_messages') or \
            'marked' in other_tags_for_text:
                # it's a normal message, or a muc message with want to be
                # notified about if quitting just after
                # other_tags_for_text == ['marked'] --> highlighted gc message
                gajim.last_message_time[self.account][full_jid] = time.time()

938 939 940 941
        if kind in ('incoming', 'incoming_queue'):
            # Record the history of received messages
            self.save_message(text, 'received')

942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
        if kind in ('incoming', 'incoming_queue', 'error'):
            gc_message = False
            if self.type_id == message_control.TYPE_GC:
                gc_message = True

            if ((self.parent_win and (not self.parent_win.get_active_control() or \
            self != self.parent_win.get_active_control() or \
            not self.parent_win.is_active() or not end)) or \
            (gc_message and \
            jid in gajim.interface.minimized_controls[self.account])) and \
            kind in ('incoming', 'incoming_queue', 'error'):
                # we want to have save this message in events list
                # other_tags_for_text == ['marked'] --> highlighted gc message
                if gc_message:
                    if 'marked' in other_tags_for_text:
                        type_ = 'printed_marked_gc_msg'
                    else:
                        type_ = 'printed_gc_msg'
                    event = 'gc_message_received'
                else:
                    type_ = 'printed_' + self.type_id
                    event = 'message_received'
                show_in_roster = notify.get_show_in_roster(event,
                        self.account, self.contact, self.session)
                show_in_systray = notify.get_show_in_systray(event,
                        self.account, self.contact, type_)

                event = gajim.events.create_event(type_, (self,),
970 971
                    show_in_roster=show_in_roster,
                    show_in_systray=show_in_systray)
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
                gajim.events.add_event(self.account, full_jid, event)
                # We need to redraw contact if we show in roster
                if show_in_roster:
                    gajim.interface.roster.draw_contact(self.contact.jid,
                            self.account)

        if not self.parent_win:
            return

        if (not self.parent_win.get_active_control() or \
        self != self.parent_win.get_active_control() or \
        not self.parent_win.is_active() or not end) and \
        kind in ('incoming', 'incoming_queue', 'error'):
            self.parent_win.redraw_tab(self)
            if not self.parent_win.is_active():
                self.parent_win.show_title(True, self) # Enabled Urgent hint
            else:
                self.parent_win.show_title(False, self) # Disabled Urgent hint

    def toggle_emoticons(self):
        """
        Hide show emoticons_button and make sure emoticons_menu is always there
        when needed
        """
        emoticons_button = self.xml.get_object('emoticons_button')
        if gajim.config.get('emoticons_theme'):
            emoticons_button.show()
            emoticons_button.set_no_show_all(False)
        else:
            emoticons_button.hide()
            emoticons_button.set_no_show_all(True)

    def append_emoticon(self, str_):
        buffer_ = self.msg_textview.get_buffer()
        if buffer_.get_char_count():
            buffer_.insert_at_cursor(' %s ' % str_)
        else: # we are the beginning of buffer
            buffer_.insert_at_cursor('%s ' % str_)
        self.msg_textview.grab_focus()

    def on_emoticons_button_clicked(self, widget):
        """
        Popup emoticons menu
        """
        gajim.interface.emoticon_menuitem_clicked = self.append_emoticon
        gajim.interface.popup_emoticons_under_button(widget, self.parent_win)

    def on_formattings_button_clicked(self, widget):
        """
        Popup formattings menu
        """
        menu = gtk.Menu()

        menuitems = ((_('Bold'), 'bold'),
        (_('Italic'), 'italic'),
        (_('Underline'), 'underline'),
        (_('Strike'), 'strike'))

        active_tags = self.msg_textview.get_active_tags()

        for menuitem in menuitems:
            item = gtk.CheckMenuItem(menuitem[0])
            if menuitem[1] in active_tags:
                item.set_active(True)
            else:
                item.set_active(False)
            item.connect('activate', self.msg_textview.set_tag,
                    menuitem[1])
            menu.append(item)

        item = gtk.SeparatorMenuItem() # separator
        menu.append(item)

        item = gtk.ImageMenuItem(_('Color'))
        icon = gtk.image_new_from_stock(gtk.STOCK_SELECT_COLOR, gtk.ICON_SIZE_MENU)
        item.set_image(icon)
        item.connect('activate', self.on_color_menuitem_activale)
        menu.append(item)

        item = gtk.ImageMenuItem(_('Font'))
        icon = gtk.image_new_from_stock(gtk.STOCK_SELECT_FONT, gtk.ICON_SIZE_MENU)
        item.set_image(icon)
        item.connect('activate', self.on_font_menuitem_activale)
        menu.append(item)

        item = gtk.SeparatorMenuItem() # separator
        menu.append(item)

        item = gtk.ImageMenuItem(_('Clear formating'))
        icon = gtk.image_new_from_stock(gtk.STOCK_CLEAR, gtk.ICON_SIZE_MENU)
        item.set_image(icon)
        item.connect('activate', self.msg_textview.clear_tags)
        menu.append(item)

        menu.show_all()
        gtkgui_helpers.popup_emoticons_under_button(menu, widget,
                self.parent_win)

    def on_color_menuitem_activale(self, widget):
        color_dialog = gtk.ColorSelectionDialog('Select a color')
        color_dialog.connect('response', self.msg_textview.color_set,
                color_dialog.colorsel)
        color_dialog.show_all()

    def on_font_menuitem_activale(self, widget):
        font_dialog = gtk.FontSelectionDialog('Select a font')
        font_dialog.connect('response', self.msg_textview.font_set,
                font_dialog.fontsel)
        font_dialog.show_all()

    def on_actions_button_clicked(self, widget):
        """
        Popup action menu
        """
        menu = self.prepare_context_menu(hide_buttonbar_items=True)
        menu.show_all()
        gtkgui_helpers.popup_emoticons_under_button(menu, widget,
                self.parent_win)

    def update_font(self):
        font = pango.FontDescription(gajim.config.get('conversation_font'))
        self.conv_textview.tv.modify_font(font)
        self.msg_textview.modify_font(font)

    def update_tags(self):
        self.conv_textview.update_tags()

    def clear(self, tv):
        buffer_ = tv.get_buffer()
        start, end = buffer_.get_bounds()
        buffer_.delete(start, end)

1104
    def _on_history_menuitem_activate(self, widget=None, jid=None):
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
        """
        When history menuitem is pressed: call history window
        """
        if not jid:
            jid = self.contact.jid

        if 'logs' in gajim.interface.instances:
            gajim.interface.instances['logs'].window.present()
            gajim.interface.instances['logs'].open_history(jid, self.account)
        else:
            gajim.interface.instances['logs'] = \
                    history_window.HistoryWindow(jid, self.account)

    def _on_send_file(self, gc_contact=None):
        """
        gc_contact can be set when we are in a groupchat control
        """
        def _on_ok(c):
            gajim.interface.instances['file_transfers'].show_file_send_request(
                    self.account, c)
        if self.TYPE_ID == message_control.TYPE_PM:
            gc_contact = self.gc_contact
        if gc_contact:
            # gc or pm
            gc_control = gajim.interface.msg_win_mgr.get_gc_control(
                    gc_contact.room_jid, self.account)
            self_contact = gajim.contacts.get_gc_contact(self.account,
                    gc_control.room_jid, gc_control.nick)
            if gc_control.is_anonymous and gc_contact.affiliation not in ['admin',
            'owner'] and self_contact.affiliation in ['admin', 'owner']:
                contact = gajim.contacts.get_contact(self.account, gc_contact.jid)
                if not contact or contact.sub not in ('both', 'to'):
                    prim_text = _('Really send file?')
                    sec_text = _('If you send a file to %s, he/she will know your '
                            'real Jabber ID.') % gc_contact.name
1140 1141
                    dialog = dialogs.NonModalConfirmationDialog(prim_text,
                        sec_text, on_response_ok=(_on_ok, gc_contact))
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
                    dialog.popup()
                    return
            _on_ok(gc_contact)
            return
        _on_ok(self.contact)

    def on_minimize_menuitem_toggled(self, widget):
        """
        When a grouchat is minimized, unparent the tab, put it in roster etc
        """
        old_value = False
        minimized_gc = gajim.config.get_per('accounts', self.account,
                'minimized_gc').split()
        if self.contact.jid in minimized_gc:
            old_value = True
        minimize = widget.get_active()
        if minimize and not self.contact.jid in minimized_gc:
            minimized_gc.append(self.contact.jid)
        if not minimize and self.contact.jid in minimized_gc:
            minimized_gc.remove(self.contact.jid)
        if old_value != minimize:
            gajim.config.set_per('accounts', self.account, 'minimized_gc',
                    ' '.join(minimized_gc))

    def set_control_active(self, state):
        if state:
            jid = self.contact.jid
            if self.was_at_the_end:
                # we are at the end
                type_ = ['printed_' + self.type_id]
                if self.type_id == message_control.TYPE_GC:
                    type_ = ['printed_gc_msg', 'printed_marked_gc_msg']
                if not gajim.events.remove_events(self.account, self.get_full_jid(),
1175
                types=type_):
1176 1177 1178
                    # There were events to remove
                    self.redraw_after_event_removed(jid)

1179
    def bring_scroll_to_end(self, textview, diff_y=0):
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
        """
        Scroll to the end of textview if end is not visible
        """
        if self.scroll_to_end_id:
            # a scroll is already planned
            return
        buffer_ = textview.get_buffer()
        end_iter = buffer_.get_end_iter()
        end_rect = textview.get_iter_location(end_iter)
        visible_rect = textview.get_visible_rect()
        # scroll only if expected end is not visible
        if end_rect.y >= (visible_rect.y + visible_rect.height + diff_y):
            self.scroll_to_end_id = gobject.idle_add(self.scroll_to_end_iter,
                    textview)

    def scroll_to_end_iter(self, textview):
        buffer_ = textview.get_buffer()
        end_iter = buffer_.get_end_iter()
        textview.scroll_to_iter(end_iter, 0, False, 1, 1)
        self.scroll_to_end_id = None
        return False

1202
    def size_request(self, msg_textview, requisition):
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
        """
        When message_textview changes its size: if the new height will enlarge
        the window, enable the scrollbar automatic policy.  Also enable scrollbar
        automatic policy for horizontal scrollbar if message we have in
        message_textview is too big
        """
        if msg_textview.window is None:
            return

        min_height = self.conv_scrolledwindow.get_property('height-request')
        conversation_height = self.conv_textview.tv.window.get_size()[1]
        message_height = msg_textview.window.get_size()[1]
        message_width = msg_textview.window.get_size()[0]
        # new tab is not exposed yet
        if conversation_height < 2:
            return

        if conversation_height < min_height:
            min_height = conversation_height

        # we don't want to always resize in height the message_textview
        # so we have minimum on conversation_textview's scrolled window
        # but we also want to avoid window resizing so if we reach that
        # minimum for conversation_textview and maximum for message_textview
        # we set to automatic the scrollbar policy
        diff_y = message_height - requisition.height
        if diff_y != 0:
            if conversation_height + diff_y < min_height:
                if message_height + conversation_height - min_height > min_height:
                    policy = self.msg_scrolledwindow.get_property(
                            'vscrollbar-policy')
                    if policy != gtk.POLICY_AUTOMATIC:
                        self.msg_scrolledwindow.set_property('vscrollbar-policy',
                                gtk.POLICY_AUTOMATIC)
                        self.msg_scrolledwindow.set_property('height-request',
                                message_height + conversation_height - min_height)
            else:
                self.msg_scrolledwindow.set_property('vscrollbar-policy',
                        gtk.POLICY_NEVER)
                self.msg_scrolledwindow.set_property('height-request', -1)
1243

1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
        self.smooth = True # reinit the flag
        # enable scrollbar automatic policy for horizontal scrollbar
        # if message we have in message_textview is too big
        if requisition.width > message_width:
            self.msg_scrolledwindow.set_property('hscrollbar-policy',
                    gtk.POLICY_AUTOMATIC)
        else:
            self.msg_scrolledwindow.set_property('hscrollbar-policy',
                    gtk.POLICY_NEVER)

        return True

    def on_conversation_vadjustment_changed(self, adjustment):
        # used to stay at the end of the textview when we shrink conversation
        # textview.
        if self.was_at_the_end:
            self.conv_textview.bring_scroll_to_end(-18)
        self.was_at_the_end = (adjustment.upper - adjustment.value - adjustment.page_size) < 18

    def on_conversation_vadjustment_value_changed(self, adjustment):
        # stop automatic scroll when we manually scroll
        if not self.conv_textview.auto_scrolling:
            self.conv_textview.stop_scrolling()
        self.was_at_the_end = (adjustment.upper - adjustment.value - adjustment.page_size) < 18
        if self.resource:
            jid = self.contact.get_full_jid()
        else:
            jid = self.contact.jid
        types_list = []
        type_ = self.type_id
        if type_ == message_control.TYPE_GC:
            type_ = 'gc_msg'
            types_list = ['printed_' + type_, type_, 'printed_marked_gc_msg']
        else: # Not a GC
            types_list = ['printed_' + type_, type_]

        if not len(gajim.events.get_events(self.account, jid, types_list)):
            return
        if not self.parent_win:
            return
        if self.conv_textview.at_the_end() and \
        self.parent_win.get_active_control() == self and \
        self.parent_win.window.is_active():
            # we are at the end
            if self.type_id == message_control.TYPE_GC:
                if not gajim.events.remove_events(self.account, jid,
                types=types_list):
                    self.redraw_after_event_removed(jid)
            elif self.session and self.session.remove_events(types_list):
                # There were events to remove
                self.redraw_after_event_removed(jid)

    def redraw_after_event_removed(self, jid):
        """
        We just removed a 'printed_*' event, redraw contact in roster or
        gc_roster and titles in roster and msg_win
        """
        self.parent_win.redraw_tab(self)
        self.parent_win.show_title()
        # TODO : get the contact and check notify.get_show_in_roster()
        if self.type_id == message_control.TYPE_PM:
            room_jid, nick = gajim.get_room_and_nick_from_fjid(jid)
            groupchat_control = gajim.interface.msg_win_mgr.get_gc_control(
                    room_jid, self.account)
            if room_jid in gajim.interface.minimized_controls[self.account]:
                groupchat_control = \
                        gajim.interface.minimized_controls[self.account][room_jid]
            contact = \
                    gajim.contacts.get_contact_with_highest_priority(self.account, \
                    room_jid)
            if contact:
                gajim.interface.roster.draw_contact(room_jid, self.account)
            if groupchat_control:
                groupchat_control.draw_contact(nick)
                if groupchat_control.parent_win:
                    groupchat_control.parent_win.redraw_tab(groupchat_control)
        else:
            gajim.interface.roster.draw_contact(jid, self.account)
            gajim.interface.roster.show_title()

1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
    def scroll_messages(self, direction, msg_buf, msg_type):
        if msg_type == 'sent':
            history = self.sent_history
            pos = self.sent_history_pos
            self.received_history_pos = len(self.received_history)
        else:
            history = self.received_history
            pos = self.received_history_pos
            self.sent_history_pos = len(self.sent_history)
        size = len(history)
1334 1335 1336
        if self.orig_msg is None:
            # user was typing something and then went into history, so save
            # whatever is already typed
1337 1338 1339
            start_iter = msg_buf.get_start_iter()
            end_iter = msg_buf.get_end_iter()
            self.orig_msg = msg_buf.get_text(start_iter, end_iter, 0).decode(
1340
                    'utf-8')
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
        pos += -1 if direction == 'up' else +1
        if pos == -1:
            return
        if pos >= size:
            pos = size
            message = self.orig_msg
            self.orig_msg = None
        else:
            message = history[pos]
        if msg_type == 'sent':
            self.sent_history_pos = pos
        else:
            self.received_history_pos = pos
            if self.orig_msg is not None:
                message = '> %s\n' % message.replace('\n', '\n> ')
        msg_buf.set_text(message)
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398

    def lighten_color(self, color):
        p = 0.4
        mask = 0
        color.red = int((color.red * p) + (mask * (1 - p)))
        color.green = int((color.green * p) + (mask * (1 - p)))
        color.blue = int((color.blue * p) + (mask * (1 - p)))
        return color

    def widget_set_visible(self, widget, state):
        """
        Show or hide a widget
        """
        # make the last message visible, when changing to "full view"
        if not state:
            gobject.idle_add(self.conv_textview.scroll_to_end_iter)

        widget.set_no_show_all(state)
        if state:
            widget.hide()
        else:
            widget.show_all()

    def chat_buttons_set_visible(self, state):
        """
        Toggle chat buttons
        """
        MessageControl.chat_buttons_set_visible(self, state)
        self.widget_set_visible(self.xml.get_object('actions_hbox'), state)

    def got_connected(self):
        self.msg_textview.set_sensitive(True)
        self.msg_textview.set_editable(True)
        # FIXME: Set sensitivity for toolbar

    def got_disconnected(self):
        self.msg_textview.set_sensitive(False)
        self.msg_textview.set_editable(False)
        self.conv_textview.tv.grab_focus()

        self.no_autonegotiation = False
        # FIXME: Set sensitivity for toolbar
nicfit's avatar
nicfit committed
1399

1400

1401
################################################################################
1402
class ChatControl(ChatControlBase):
1403 1404 1405 1406
    """
    A control for standard 1-1 chat
    """
    (
1407
            JINGLE_STATE_NULL,
1408 1409 1410 1411
            JINGLE_STATE_CONNECTING,
            JINGLE_STATE_CONNECTION_RECEIVED,
            JINGLE_STATE_CONNECTED,
            JINGLE_STATE_ERROR
1412
    ) = range(5)
1413 1414 1415 1416 1417 1418 1419 1420

    TYPE_ID = message_control.TYPE_CHAT
    old_msg_kind = None # last kind of the printed message

    # Set a command host to bound to. Every command given through a chat will be
    # processed with this command host.
    COMMAND_HOST = ChatCommands

1421
    def __init__(self, parent_win, contact, acct, session, resource=None):
1422 1423 1424
        ChatControlBase.__init__(self, self.TYPE_ID, parent_win,
                'chat_control', contact, acct, resource)

1425
        self._dbus_message_sent_match = None
Dicson's avatar
Dicson committed
1426
        if dbus_support.supported:
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
            bus = dbus_support.session_bus.bus()
            try:
                obj = bus.get_object(remote_control.SERVICE, remote_control.OBJ_PATH)
            except:
                # likely dbus service not started
                pass
            else:
                iface = dbus.Interface(obj, remote_control.INTERFACE)
                self._dbus_message_sent_match = iface.connect_to_signal("MessageSent", self.on_message_sent)

1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
        self.gpg_is_active = False
        # for muc use:
        # widget = self.xml.get_object('muc_window_actions_button')
        self.actions_button = self.xml.get_object('message_window_actions_button')
        id_ = self.actions_button.connect('clicked',
                self.on_actions_button_clicked)
        self.handlers[id_] = self.actions_button

        self._formattings_button = self.xml.get_object('formattings_button')

        self._add_to_roster_button = self.xml.get_object(
                'add_to_roster_button')
        id_ = self._add_to_roster_button.connect('clicked',
                self._on_add_to_roster_menuitem_activate)
        self.handlers[id_] = self._add_to_roster_button

        self._audio_button = self.xml.get_object('audio_togglebutton')
        id_ = self._audio_button.connect('toggled', self.on_audio_button_toggled)
        self.handlers[id_] = self._audio_button
        # add a special img
        gtkgui_helpers.add_image_to_button(self._audio_button,
                'gajim-mic_inactive')

        self._video_button = self.xml.get_object('video_togglebutton')
        id_ = self._video_button.connect('toggled', self.on_video_button_toggled)
        self.handlers[id_] = self._video_button
        # add a special img
        gtkgui_helpers.add_image_to_button(self._video_button,
                'gajim-cam_inactive')

        self._send_file_button = self.xml.get_object('send_file_button')
        # add a special img for send file button
        path_to_upload_img = gtkgui_helpers.get_icon_path('gajim-upload')
        img = gtk.Image()
        img.set_from_file(path_to_upload_img)
        self._send_file_button.set_image(img)
        id_ = self._send_file_button.connect('clicked',
                self._on_send_file_menuitem_activate)
        self.handlers[id_] = self._send_file_button

        self._convert_to_gc_button = self.xml.get_object(
                'convert_to_gc_button')
        id_ = self._convert_to_gc_button.connect('clicked',
                self._on_convert_to_gc_menuitem_activate)
        self.handlers[id_] = self._convert_to_gc_button

        contact_information_button = self.xml.get_object(
                'contact_information_button')
        id_ = contact_information_button.connect('clicked',
                self._on_contact_information_menuitem_activate)
        self.handlers[id_] = contact_information_button

        compact_view = gajim.config.get('compact_view')
        self.chat_buttons_set_visible(compact_view)
        self.widget_set_visible(self.xml.get_object('banner_eventbox'),
                gajim.config.get('hide_chat_banner'))

        self.authentication_button = self.xml.get_object(
                'authentication_button')
        id_ = self.authentication_button.connect('clicked',
                self._on_authentication_button_clicked)
        self.handlers[id_] = self.authentication_button

        # Add lock image to show chat encryption
        self.lock_image = self.xml.get_object('lock_image')

        # Convert to GC icon
        img = self.xml.get_object('convert_to_gc_button_image')
        img.set_from_pixbuf(gtkgui_helpers.load_icon(
                'muc_active').get_pixbuf())

        self._audio_banner_image = self.xml.get_object('audio_banner_image')
        self._video_banner_image = self.xml.get_object('video_banner_image')
        self.audio_sid = None
1511 1512
        self.audio_state = self.JINGLE_STATE_NULL
        self.audio_available = False
1513
        self.video_sid = None
1514 1515
        self.video_state = self.JINGLE_STATE_NULL
        self.video_available = False
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565