tabs.py 49.9 KB
Newer Older
1
# Copyright 2010-2011 Le Coz Florent <louiz@louiz.org>
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#
# This file is part of Poezio.
#
# Poezio 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, version 3 of the License.
#
# Poezio 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 Poezio.  If not, see <http://www.gnu.org/licenses/>.

"""
18
a Tab object is a way to organize various Windows (see windows.py)
19
around the screen at once.
20 21 22
A tab is then composed of multiple Buffer.
Each Tab object has different refresh() and resize() methods, defining how its
Buffer are displayed, resized, etc
23 24 25
"""

MIN_WIDTH = 50
26
MIN_HEIGHT = 16
27

28 29 30
from gettext import (bindtextdomain, textdomain, bind_textdomain_codeset,
                     gettext as _)

31 32 33
import logging
log = logging.getLogger(__name__)

34
import windows
35
import theme
36
import curses
37
import difflib
38
import shlex
39
import text_buffer
louiz’'s avatar
louiz’ committed
40
import string
41 42

from sleekxmpp.xmlstream.stanzabase import JID
43
from config import config
44
from roster import RosterGroup, roster
45
from contact import Contact, Resource
46
from logger import logger
47
import multiuserchat as muc
48 49 50 51

class Tab(object):
    number = 0

52
    def __init__(self, core):
53
        self.core = core        # a pointer to core, to access its attributes (ugly?)
louiz’'s avatar
louiz’ committed
54
        self._color_state = theme.COLOR_TAB_NORMAL
55 56
        self.nb = Tab.number
        Tab.number += 1
57
        self.size = (self.height, self.width) = self.core.stdscr.getmaxyx()
58 59 60 61
        if self.height < MIN_HEIGHT or self.width < MIN_WIDTH:
            self.visible = False
        else:
            self.visible = True
62 63
        self.key_func = {}      # each tab should add their keys in there
                                # and use them in on_input
64
        self.commands = {}      # and their own commands
65

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
    def complete_commands(self, the_input):
        """
        Does command completion on the specified input for both global and tab-specific
        commands.
        This should be called from the completion method (on tab, for example), passing
        the input where completion is to be made.
        It can completion the command name itself or an argument of the command.
        Returns True if a completion was made, False else.
        """
        txt = the_input.get_text()
        # check if this is a command
        if txt.startswith('/') and not txt.startswith('//'):
            # check if we are in the middle of the command name
            if len(txt.split()) > 1 or\
                    (txt.endswith(' ') and not the_input.last_completion):
                command_name = txt.split()[0][1:]
                if command_name in self.core.commands:
                    command = self.core.commands[command_name]
                elif command_name in self.commands:
                    command = self.commands[command_name]
                else:           # Unknown command, cannot complete
                    return False
                if command[2] is None:
                    return False # There's no completion functio
                else:
                    return command[2](the_input)
            else:
                # complete the command's name
                words = ['/%s'%(name) for name in list(self.core.commands.keys())] +\
                    ['/%s'% (name) for name in list(self.commands.keys())]
                the_input.auto_completion(words, '')
                return True
        return False
99

100
    def execute_command(self, provided_text):
louiz’'s avatar
louiz’ committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
        """
        Execute the command in the input and return False if
        the input didn't contain a command
        """
        txt = provided_text or self.input.key_enter()
        if txt.startswith('/') and not txt.startswith('//') and\
                not txt.startswith('/me '):
            command = txt.strip().split()[0][1:]
            arg = txt[2+len(command):] # jump the '/' and the ' '
            if command in self.core.commands: # check global commands
                self.core.commands[command][0](arg)
            elif command in self.commands: # check tab-specific commands
                self.commands[command][0](arg)
            else:
                self.core.information(_("Unknown command (%s)") % (command), _('Error'))
            return True
        else:
            return False

120 121
    def resize(self):
        self.size = (self.height, self.width) = self.core.stdscr.getmaxyx()
122 123 124 125 126
        if self.height < MIN_HEIGHT or self.width < MIN_WIDTH:
            self.visible = False
        else:
            self.visible = True

127 128 129 130 131 132
    def refresh(self, tabs, informations, roster):
        """
        Called on each screen refresh (when something has changed)
        """
        raise NotImplementedError

133 134 135 136
    def get_color_state(self):
        """
        returns the color that should be used in the GlobalInfoBar
        """
louiz’'s avatar
louiz’ committed
137
        return self._color_state
138 139 140 141 142

    def set_color_state(self, color):
        """
        set the color state
        """
143
        pass
144 145 146 147 148

    def get_name(self):
        """
        get the name of the tab
        """
149
        return self.__class__.__name__
150

151 152 153 154 155 156
    def get_text_window(self):
        """
        Returns the principal TextWin window, if there's one
        """
        return None

157
    def on_input(self, key):
158
        pass
159 160 161 162 163

    def on_lose_focus(self):
        """
        called when this tab loses the focus.
        """
louiz’'s avatar
louiz’ committed
164
        self._color_state = theme.COLOR_TAB_NORMAL
165 166 167 168 169

    def on_gain_focus(self):
        """
        called when this tab gains the focus.
        """
louiz’'s avatar
louiz’ committed
170
        self._color_state = theme.COLOR_TAB_CURRENT
171 172 173 174 175 176 177 178

    def add_message(self):
        """
        Adds a message in the tab.
        If the tab cannot add a message in itself (for example
        FormTab, where text is not intented to be appened), it returns False.
        If the tab can, it returns True
        """
179
        return False
180 181 182 183 184

    def on_scroll_down(self):
        """
        Defines what happens when we scrol down
        """
185
        pass
186 187 188 189 190

    def on_scroll_up(self):
        """
        Defines what happens when we scrol down
        """
191
        pass
192

193
    def on_info_win_size_changed(self):
194 195 196
        """
        Called when the window with the informations is resized
        """
197
        pass
198

199 200 201 202 203 204
    def just_before_refresh(self):
        """
        Method called just before the screen refresh.
        Particularly useful to move the cursor at the
        correct position.
        """
205
        pass
206

207 208 209 210
    def on_close(self):
        """
        Called when the tab is to be closed
        """
211
        pass
212

213 214
class ChatTab(Tab):
    """
215 216 217
    A tab containing a chat of any type.
    Just use this class instead of Tab if the tab needs a recent-words completion
    Also, \n, ^J and ^M are already bound to on_enter
218
    And also, add the /say command
219
    """
220 221 222 223 224 225 226
    def __init__(self, core, room):
        Tab.__init__(self, core)
        self._room = room
        self.key_func['M-/'] = self.last_words_completion
        self.key_func['^J'] = self.on_enter
        self.key_func['^M'] = self.on_enter
        self.key_func['\n'] = self.on_enter
227 228
        self.commands['say'] =  (self.command_say,
                                 _("""Usage: /say <message>\nSay: Just send the message.
229
                                        Useful if you want your message to begin with a '/'"""), None)
230 231 232 233 234 235

    def last_words_completion(self):
        """
        Complete the input with words recently said
        """
        # build the list of the recent words
louiz’'s avatar
louiz’ committed
236
        char_we_dont_want = string.punctuation+' '
237 238 239 240
        words = list()
        for msg in self._room.messages[:-40:-1]:
            if not msg:
                continue
241
            txt = msg.txt
242
            for char in char_we_dont_want:
243 244
                txt = txt.replace(char, ' ')
            for word in txt.split():
245 246
                if len(word) >= 4 and word not in words:
                    words.append(word)
247
        self.input.auto_completion(words, ' ')
248 249

    def on_enter(self):
250
        txt = self.input.key_enter()
251
        if not self.execute_command(txt):
louiz’'s avatar
louiz’ committed
252 253
            if txt.startswith('//'):
                txt = txt[1:]
254 255 256
            self.command_say(txt)

    def command_say(self, line):
257 258
        raise NotImplementedError

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
class InfoTab(ChatTab):
    """
    The information tab, used to display global informations
    when using a anonymous account
    """
    def __init__(self, core):
        Tab.__init__(self, core)
        self.tab_win = windows.GlobalInfoBar()
        self.info_win = windows.TextWin()
        self.core.information_buffer.add_window(self.info_win)
        self.input = windows.Input()
        self.name = "Info"
        self.color_state = theme.COLOR_TAB_NORMAL
        self.key_func['^J'] = self.on_enter
        self.key_func['^M'] = self.on_enter
        self.key_func['\n'] = self.on_enter
        self.key_func['^I'] = self.completion
        self.key_func['M-i'] = self.completion
        self.resize()

    def resize(self):
        Tab.resize(self)
281 282
        if not self.visible:
            return
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
        self.tab_win.resize(1, self.width, self.height-2, 0, self.core.stdscr)
        self.info_win.resize(self.height-2, self.width, 0, 0, self.core.stdscr)
        self.input.resize(1, self.width, self.height-1, 0, self.core.stdscr)

    def refresh(self, tabs, informations, _):
        if not self.visible:
            return
        self.info_win.refresh(informations)
        self.tab_win.refresh(tabs, tabs[0])
        self.input.refresh()

    def completion(self):
        self.complete_commands(self.input)

    def get_name(self):
        return self.name

    def get_color_state(self):
        return self.color_state

    def set_color_state(self, color):
        return

    def on_input(self, key):
        if key in self.key_func:
            self.key_func[key]()
            return False
        self.input.do_command(key)
        return False

313
    def on_enter(self):
louiz’'s avatar
louiz’ committed
314
        self.execute_command(self.input.key_enter())
315

316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
    def on_lose_focus(self):
        self.color_state = theme.COLOR_TAB_NORMAL

    def on_gain_focus(self):
        self.color_state = theme.COLOR_TAB_CURRENT
        curses.curs_set(1)

    def on_scroll_up(self):
        pass

    def on_scroll_down(self):
        pass

    def on_info_win_size_changed(self):
        return

    def just_before_refresh(self):
        return

    def on_close(self):
        return

338
class MucTab(ChatTab):
339 340 341 342
    """
    The tab containing a multi-user-chat room.
    It contains an userlist, an input, a topic, an information and a chat zone
    """
343
    def __init__(self, core, room):
344
        ChatTab.__init__(self, core, room)
345 346
        self.topic_win = windows.Topic()
        self.text_win = windows.TextWin()
347
        room.add_window(self.text_win)
348 349 350 351
        self.v_separator = windows.VerticalSeparator()
        self.user_win = windows.UserList()
        self.info_header = windows.MucInfoWin()
        self.info_win = windows.TextWin()
352
        self.core.information_buffer.add_window(self.info_win)
353 354
        self.tab_win = windows.GlobalInfoBar()
        self.input = windows.MessageInput()
355 356
        self.ignores = []       # set of Users
        # keys
357 358
        self.key_func['^I'] = self.completion
        self.key_func['M-i'] = self.completion
359 360
        self.key_func['M-u'] = self.scroll_user_list_down
        self.key_func['M-y'] = self.scroll_user_list_up
361
        # commands
362 363 364 365 366 367 368 369
        self.commands['ignore'] = (self.command_ignore, _("Usage: /ignore <nickname> \nIgnore: Ignore a specified nickname."), None)
        self.commands['unignore'] = (self.command_unignore, _("Usage: /unignore <nickname>\nUnignore: Remove the specified nickname from the ignore list."), None)
        self.commands['kick'] =  (self.command_kick, _("Usage: /kick <nick> [reason]\nKick: Kick the user with the specified nickname. You also can give an optional reason."), None)
        self.commands['topic'] = (self.command_topic, _("Usage: /topic <subject>\nTopic: Change the subject of the room"), None)
        self.commands['query'] = (self.command_query, _('Usage: /query <nick> [message]\nQuery: Open a private conversation with <nick>. This nick has to be present in the room you\'re currently in. If you specified a message after the nickname, it will immediately be sent to this user'), None)
        self.commands['part'] = (self.command_part, _("Usage: /part [message]\n Part: disconnect from a room. You can specify an optional message."), None)
        self.commands['nick'] = (self.command_nick, _("Usage: /nick <nickname>\nNick: Change your nickname in the current room"), None)
        self.commands['recolor'] = (self.command_recolor, _('Usage: /recolor\nRecolor: Re-assign a color to all participants of the current room, based on the last time they talked. Use this if the participants currently talking have too many identical colors.'), None)
370
        self.commands['cycle'] = (self.command_cycle, _('Usage: /cycle [message]\nCycle: Leaves the current room and rejoin it immediately'), None)
louiz’'s avatar
louiz’ committed
371 372
        self.commands['info'] = (self.command_info, _('Usage: /info <nickname>\nInfo: Display some information about the user in the MUC: his/here role, affiliation, status and status message.'), None)
        self.commands['configure'] = (self.command_configure, _('Usage: /configure\nConfigure: Configure the current room, through a form.'), None)
373
        self.resize()
374

375 376 377 378 379 380 381 382
    def scroll_user_list_up(self):
        self.user_win.scroll_up()
        self.core.refresh_window()

    def scroll_user_list_down(self):
        self.user_win.scroll_down()
        self.core.refresh_window()

383 384 385 386 387 388 389 390 391 392
    def command_info(self, arg):
        try:
            args = shlex.split(arg)
        except ValueError as error:
            return self.core.information(str(error), _("Error"))
        if len(args) != 1:
            return self.core.information("Info command takes only 1 argument")
        user = self.get_room().get_user_by_name(args[0])
        if not user:
            return self.core.information("Unknown user: %s" % args[0])
louiz’'s avatar
louiz’ committed
393
        self.get_room().add_message("%s%s: show: %s, affiliation: %s, role: %s\n%s"% (args[0], user.user.show or 'Available', user.role or 'None', user.affiliation or 'None', user.status))
394 395
        self.core.refresh_window()

louiz’'s avatar
louiz’ committed
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
    def command_configure(self, arg):
        form = self.core.xmpp.plugin['xep_0045'].getRoomForm(self.get_name())
        self.core.information('%s' % form)
        self.core.open_new_form(form, self.cancel_config, self.send_config)

    def cancel_config(self, form):
        """
        The user do not want to send his/her config, send an iq cancel
        """
        self.core.xmpp.plugin['xep_0045'].cancelConfig(self.get_name())
        self.core.close_tab()

    def send_config(self, form):
        """
        The user sends his/her config to the server
        """
        self.core.xmpp.plugin['xep_0045'].configureRoom(self.get_name(), form)
        self.core.close_tab()

415 416
    def command_cycle(self, arg):
        if self.get_room().joined:
417
            muc.leave_groupchat(self.core.xmpp, self.get_name(), self.get_room().own_nick, arg)
418
        self.get_room().joined = False
419
        self.core.command_join('/', "0")
420

421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    def command_recolor(self, arg):
        """
        Re-assign color to the participants of the room
        """
        room = self.get_room()
        i = 0
        compare_users = lambda x: x.last_talked
        users = list(room.users)
        # search our own user, to remove it from the room
        for user in users:
            if user.nick == room.own_nick:
                users.remove(user)
        nb_color = len(theme.LIST_COLOR_NICKNAMES)
        for user in sorted(users, key=compare_users, reverse=True):
            user.color = theme.LIST_COLOR_NICKNAMES[i % nb_color]
436
            i += 1
437
        self.text_win.rebuild_everything(self.get_room())
438 439 440 441 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 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 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 519 520 521 522 523 524 525 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
        self.core.refresh_window()

    def command_nick(self, arg):
        """
        /nick <nickname>
        """
        try:
            args = shlex.split(arg)
        except ValueError as error:
            return self.core.information(str(error), _("Error"))
        if len(args) != 1:
            return
        nick = args[0]
        room = self.get_room()
        if not room.joined:
            return
        muc.change_nick(self.core.xmpp, room.name, nick)

    def command_part(self, arg):
        """
        /part [msg]
        """
        args = arg.split()
        reason = None
        room = self.get_room()
        if len(args):
            msg = ' '.join(args)
        else:
            msg = None
        if self.get_room().joined:
            muc.leave_groupchat(self.core.xmpp, room.name, room.own_nick, arg)
        self.core.close_tab()

    def command_query(self, arg):
        """
        /query <nick> [message]
        """
        try:
            args = shlex.split(arg)
        except ValueError as error:
            return self.core.information(str(error), _("Error"))
        if len(args) < 1:
            return
        nick = args[0]
        room = self.get_room()
        r = None
        for user in room.users:
            if user.nick == nick:
                r = self.core.open_private_window(room.name, user.nick)
        if r and len(args) > 1:
            msg = arg[len(nick)+1:]
            muc.send_private_message(self.core.xmpp, r.name, msg)
            self.core.add_message_to_text_buffer(r, msg, None, r.own_nick)

    def command_topic(self, arg):
        """
        /topic [new topic]
        """
        if not arg.strip():
            self.core.add_message_to_text_buffer(self.get_room(),
                                                 _("The subject of the room is: %s") % self.get_room().topic)
            return
        subject = arg
        muc.change_subject(self.core.xmpp, self.get_room().name, subject)

    def command_kick(self, arg):
        """
        /kick <nick> [reason]
        """
        try:
            args = shlex.split(arg)
        except ValueError as error:
            return self.core.information(str(error), _("Error"))
        if len(args) < 1:
            self.core.command_help('kick')
            return
        nick = args[0]
        if len(args) >= 2:
            reason = ' '.join(args[1:])
        else:
            reason = ''
        if not self.get_room().joined:
            return
        res = muc.eject_user(self.core.xmpp, self.get_name(), nick, reason)
        if res['type'] == 'error':
            self.core.room_error(res, self.get_name())

    def command_say(self, line):
        muc.send_groupchat_message(self.core.xmpp, self.get_name(), line)

    def command_ignore(self, arg):
        """
        /ignore <nick>
        """
        try:
            args = shlex.split(arg)
        except ValueError as error:
            return self.core.information(str(error), _("Error"))
        if len(args) != 1:
            self.core.command_help('ignore')
            return
        nick = args[0]
        user = self._room.get_user_by_name(nick)
        if not user:
            self.core.information(_('%s is not in the room') % nick)
        elif user in self.ignores:
            self.core.information(_('%s is already ignored') % nick)
        else:
            self.ignores.append(user)
            self.core.information(_("%s is now ignored") % nick, 'info')

    def command_unignore(self, arg):
        """
        /unignore <nick>
        """
        try:
            args = shlex.split(arg)
        except ValueError as error:
            return self.core.information(str(error), _("Error"))
        if len(args) != 1:
            self.core.command_help('unignore')
            return
        nick = args[0]
        user = self._room.get_user_by_name(nick)
        if not user:
            self.core.information(_('%s is not in the room') % nick)
        elif user not in self.ignores:
            self.core.information(_('%s is not ignored') % nick)
        else:
            self.ignores.remove(user)
            self.core.information(_('%s is now unignored') % nick)

570
    def resize(self):
571 572 573
        """
        Resize the whole window. i.e. all its sub-windows
        """
574
        Tab.resize(self)
575 576
        if not self.visible:
            return
577
        text_width = (self.width//10)*9
578 579
        self.topic_win.resize(1, self.width, 0, 0, self.core.stdscr)
        self.text_win.resize(self.height-4-self.core.information_win_size, text_width, 1, 0, self.core.stdscr)
580
        self.text_win.rebuild_everything(self._room)
581 582 583
        self.v_separator.resize(self.height-3, 1, 1, 9*(self.width//10), self.core.stdscr)
        self.user_win.resize(self.height-3, self.width-text_width-1, 1, text_width+1, self.core.stdscr)
        self.info_header.resize(1, (self.width//10)*9, self.height-3-self.core.information_win_size, 0, self.core.stdscr)
584
        self.info_win.resize(self.core.information_win_size, (self.width//10)*9, self.height-2-self.core.information_win_size, 0, self.core.stdscr, self.core.information_buffer)
585 586
        self.tab_win.resize(1, self.width, self.height-2, 0, self.core.stdscr)
        self.input.resize(1, self.width, self.height-1, 0, self.core.stdscr)
587

588
    def refresh(self, tabs, informations, _):
589 590
        if not self.visible:
            return
591 592 593 594
        self.topic_win.refresh(self._room.topic)
        self.text_win.refresh(self._room)
        self.v_separator.refresh()
        self.user_win.refresh(self._room.users)
595
        self.info_header.refresh(self._room, self.text_win)
596
        self.tab_win.refresh(tabs, tabs[0])
597
        self.info_win.refresh(informations)
598 599 600
        self.input.refresh()

    def on_input(self, key):
601 602
        if key in self.key_func:
            self.key_func[key]()
603 604 605
            return False
        self.input.do_command(key)
        return False
606 607 608 609 610

    def completion(self):
        """
        Called when Tab is pressed, complete the nickname in the input
        """
611 612
        if self.complete_commands(self.input):
            return
613
        # If we are not completing a command or a command's argument, complete a nick
614
        compare_users = lambda x: x.last_talked
615 616
        word_list = [user.nick for user in sorted(self._room.users, key=compare_users, reverse=True)\
                         if user.nick != self._room.own_nick]
617 618 619 620 621 622 623
        after = config.get('after_completion', ',')+" "
        if ' ' not in self.input.get_text() or (self.input.last_completion and\
                     self.input.get_text()[:-len(after)] == self.input.last_completion):
            add_after = after
        else:
            add_after = ' '
        self.input.auto_completion(word_list, add_after)
624 625 626 627 628 629 630 631 632 633

    def get_color_state(self):
        return self._room.color_state

    def set_color_state(self, color):
        self._room.set_color_state(color)

    def get_name(self):
        return self._room.name

634 635 636
    def get_text_window(self):
        return self.text_win

637 638 639 640 641
    def get_room(self):
        return self._room

    def on_lose_focus(self):
        self._room.set_color_state(theme.COLOR_TAB_NORMAL)
642 643
        self.text_win.remove_line_separator()
        self.text_win.add_line_separator()
644 645 646

    def on_gain_focus(self):
        self._room.set_color_state(theme.COLOR_TAB_CURRENT)
647
        if self.text_win.built_lines and self.text_win.built_lines[-1] is None:
648
            self.text_win.remove_line_separator()
649
        curses.curs_set(1)
650 651

    def on_scroll_up(self):
652
        self.text_win.scroll_up(self.text_win.height-1)
653 654

    def on_scroll_down(self):
655
        self.text_win.scroll_down(self.text_win.height-1)
656

657
    def on_info_win_size_changed(self):
658
        text_width = (self.width//10)*9
659 660 661
        self.text_win.resize(self.height-4-self.core.information_win_size, text_width, 1, 0, self.core.stdscr)
        self.info_header.resize(1, (self.width//10)*9, self.height-3-self.core.information_win_size, 0, self.core.stdscr)
        self.info_win.resize(self.core.information_win_size, (self.width//10)*9, self.height-2-self.core.information_win_size, 0, self.core.stdscr)
662

663
    def just_before_refresh(self):
664
        return
665

666 667 668
    def on_close(self):
        return

669
class PrivateTab(ChatTab):
670 671 672
    """
    The tab containg a private conversation (someone from a MUC)
    """
673
    def __init__(self, core, room):
674
        ChatTab.__init__(self, core, room)
675
        self.text_win = windows.TextWin()
676
        room.add_window(self.text_win)
677 678
        self.info_header = windows.PrivateInfoWin()
        self.info_win = windows.TextWin()
679
        self.core.information_buffer.add_window(self.info_win)
680 681
        self.tab_win = windows.GlobalInfoBar()
        self.input = windows.MessageInput()
682 683 684 685 686 687
        # keys
        self.key_func['^I'] = self.completion
        self.key_func['M-i'] = self.completion
        # commands
        self.commands['unquery'] = (self.command_unquery, _("Usage: /unquery\nUnquery: close the tab"), None)
        self.commands['part'] = (self.command_unquery, _("Usage: /part\Part: close the tab"), None)
688
        self.resize()
689

690 691 692
    def completion(self):
        self.complete_commands(self.input)

693 694 695
    def command_say(self, line):
        muc.send_private_message(self.core.xmpp, self.get_name(), line)
        self.core.add_message_to_text_buffer(self.get_room(), line, None, self.get_room().own_nick)
696
        logger.log_message(self.get_name().replace('/', '\\'), self.get_room().own_nick, line)
697 698 699 700 701 702 703

    def command_unquery(self, arg):
        """
        /unquery
        """
        self.core.close_tab()

704 705
    def resize(self):
        Tab.resize(self)
706 707
        if not self.visible:
            return
708
        self.text_win.resize(self.height-3-self.core.information_win_size, self.width, 0, 0, self.core.stdscr)
709
        self.text_win.rebuild_everything(self._room)
710
        self.info_header.resize(1, self.width, self.height-3-self.core.information_win_size, 0, self.core.stdscr)
711
        self.info_win.resize(self.core.information_win_size, self.width, self.height-2-self.core.information_win_size, 0, self.core.stdscr, self.core.information_buffer)
712 713
        self.tab_win.resize(1, self.width, self.height-2, 0, self.core.stdscr)
        self.input.resize(1, self.width, self.height-1, 0, self.core.stdscr)
714

715
    def refresh(self, tabs, informations, _):
716 717
        if not self.visible:
            return
718
        self.text_win.refresh(self._room)
719
        self.info_header.refresh(self._room, self.text_win)
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
        self.info_win.refresh(informations)
        self.tab_win.refresh(tabs, tabs[0])
        self.input.refresh()

    def get_color_state(self):
        if self._room.color_state == theme.COLOR_TAB_NORMAL or\
                self._room.color_state == theme.COLOR_TAB_CURRENT:
            return self._room.color_state
        return theme.COLOR_TAB_PRIVATE

    def set_color_state(self, color):
        self._room.color_state = color

    def get_name(self):
        return self._room.name

    def on_input(self, key):
737 738
        if key in self.key_func:
            self.key_func[key]()
739
            return False
740 741
        self.input.do_command(key)
        return False
742 743 744

    def on_lose_focus(self):
        self._room.set_color_state(theme.COLOR_TAB_NORMAL)
745 746
        self.text_win.remove_line_separator()
        self.text_win.add_line_separator()
747 748 749

    def on_gain_focus(self):
        self._room.set_color_state(theme.COLOR_TAB_CURRENT)
750
        curses.curs_set(1)
751 752

    def on_scroll_up(self):
753
        self.text_win.scroll_up(self.text_win.height-1)
754 755

    def on_scroll_down(self):
756
        self.text_win.scroll_down(self.text_win.height-1)
757

758
    def on_info_win_size_changed(self):
759 760
        self.text_win.resize(self.height-3-self.core.information_win_size, self.width, 0, 0, self.core.stdscr)
        self.info_header.resize(1, self.width, self.height-3-self.core.information_win_size, 0, self.core.stdscr)
761
        self.info_win.resize(self.core.information_win_size, self.width, self.height-2-self.core.information_win_size, 0, self.core.stdscr, None)
762 763 764

    def get_room(self):
        return self._room
765

766 767 768
    def get_text_window(self):
        return self.text_win

769 770 771
    def just_before_refresh(self):
        return

772 773 774
    def on_close(self):
        return

775 776
class RosterInfoTab(Tab):
    """
777
    A tab, splitted in two, containing the roster and infos
778
    """
779 780
    def __init__(self, core):
        Tab.__init__(self, core)
781
        self.name = "Roster"
782 783 784
        self.v_separator = windows.VerticalSeparator()
        self.tab_win = windows.GlobalInfoBar()
        self.info_win = windows.TextWin()
785
        self.core.information_buffer.add_window(self.info_win)
786 787 788
        self.roster_win = windows.RosterWin()
        self.contact_info_win = windows.ContactInfoWin()
        self.default_help_message = windows.HelpText("Enter commands with “/”. “o”: toggle offline show")
789
        self.input = self.default_help_message
790
        self.set_color_state(theme.COLOR_TAB_NORMAL)
791 792 793 794 795 796 797 798 799
        self.key_func['^I'] = self.completion
        self.key_func['M-i'] = self.completion
        self.key_func["^J"] = self.on_enter
        self.key_func["^M"] = self.on_enter
        self.key_func[' '] = self.on_space
        self.key_func["/"] = self.on_slash
        self.key_func["KEY_UP"] = self.move_cursor_up
        self.key_func["KEY_DOWN"] = self.move_cursor_down
        self.key_func["o"] = self.toggle_offline_show
800 801
        self.key_func["s"] = self.start_search
        self.key_func["S"] = self.start_search_slow
802
        self.commands['deny'] = (self.command_deny, _("Usage: /deny [jid]\nDeny: Use this command to remove and deny your presence to the provided JID (or the selected contact in your roster), who is asking you to be in his/here roster"), self.completion_deny)
louiz’'s avatar
louiz’ committed
803 804 805
        self.commands['accept'] = (self.command_accept, _("Usage: /accept [jid]\nAccept: Use this command to authorize the provided JID (or the selected contact in your roster), to see your presence, and to ask to subscribe to it (mutual presence subscription)."), self.completion_deny)
        self.commands['add'] = (self.command_add, _("Usage: /add <jid>\Add: Use this command to add the specified JID to your roster. The reverse authorization will automatically be accepted if the remote JID accepts your subscription, leading to a mutual presence subscription."), None)
        self.commands['remove'] = (self.command_remove, _("Usage: /remove [jid]\Remove: Use this command to remove the specified JID from your roster. This wil unsubscribe you from its presence, cancel its subscription to yours, and remove the item from your roster"), self.completion_remove)
806
        self.resize()
807

808 809
    def resize(self):
        Tab.resize(self)
810 811
        if not self.visible:
            return
812 813
        roster_width = self.width//2
        info_width = self.width-roster_width-1
814 815
        self.v_separator.resize(self.height-2, 1, 0, roster_width, self.core.stdscr)
        self.tab_win.resize(1, self.width, self.height-2, 0, self.core.stdscr)
816 817 818
        self.info_win.resize(self.height-2-4, info_width, 0, roster_width+1, self.core.stdscr, self.core.information_buffer)
        self.roster_win.resize(self.height-2, roster_width, 0, 0, self.core.stdscr)
        self.contact_info_win.resize(4, info_width, self.height-2-4, roster_width+1, self.core.stdscr)
819
        self.input.resize(1, self.width, self.height-1, 0, self.core.stdscr)
820

821 822 823 824 825
    def completion(self):
        # Check if we are entering a command (with the '/' key)
        if isinstance(self.input, windows.CommandInput) and\
                not self.input.help_message:
            self.complete_commands(self.input)
826

827 828 829 830
    def command_deny(self, args):
        """
        Denies a JID from our roster
        """
louiz’'s avatar
louiz’ committed
831 832 833 834 835 836 837 838 839
        args = args.split()
        if not args:
            item = self.roster_win.selected_row
            if isinstance(item, Contact) and item.get_ask() == 'asked':
                jid = item.get_bare_jid()
            else:
                self.core.information('No subscription to deny')
                return
        else:
louiz’'s avatar
louiz’ committed
840
            jid = JID(args[0]).bare
louiz’'s avatar
louiz’ committed
841 842 843 844
        self.core.xmpp.sendPresence(pto=jid, ptype='unsubscribed')
        if self.core.xmpp.update_roster(jid, subscription='remove'):
            roster.remove_contact(jid)

louiz’'s avatar
louiz’ committed
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
    def command_add(self, args):
        """
        Add the specified JID to the roster, and set automatically
        accept the reverse subscription
        """
        jid = JID(args.strip()).bare
        if not jid:
            return
        self.core.xmpp.sendPresence(pto=jid, ptype='subscribe')

    def command_remove(self, args):
        """
        Remove the specified JID from the roster. i.e. : unsubscribe
        from its presence, and cancel its subscription to our.
        """
        if args.strip():
            jid = JID(args.strip()).bare
        else:
            item = self.roster_win.selected_row
            if isinstance(item, Contact):
                jid = item.get_bare_jid()
            else:
                self.core.information('No roster item to remove')
                return
        self.core.xmpp.sendPresence(pto=jid, ptype='unsubscribe')
        self.core.xmpp.sendPresence(pto=jid, ptype='unsubscribed')
        self.core.xmpp.del_roster_item(jid=jid)

    def completion_remove(self, the_input):
        """
        From with any JID presence in the roster
        """
        jids = [contact.get_bare_jid() for contact in roster.get_contacts()]
        the_input.auto_completion(jids, '')

louiz’'s avatar
louiz’ committed
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
    def completion_deny(self, the_input):
        """
        Complete the first argument from the list of the
        contact with ask=='subscribe'
        """
        jids = [contact.get_bare_jid() for contact in roster.get_contacts()\
             if contact.get_ask() == 'asked']
        the_input.auto_completion(jids, '')

    def command_accept(self, args):
        """
        Accept a JID from in roster. Authorize it AND subscribe to it
        """
        args = args.split()
        if not args:
            item = self.roster_win.selected_row
            if isinstance(item, Contact) and item.get_ask() == 'asked':
                jid = item.get_bare_jid()
            else:
                self.core.information('No subscription to deny')
                return
        else:
            jid = args[0]
        self.core.xmpp.sendPresence(pto=jid, ptype='subscribed')
        self.core.xmpp.sendPresence(pto=jid, ptype='subscribe')

906
    def refresh(self, tabs, informations, roster):
907 908
        if not self.visible:
            return
909
        self.v_separator.refresh()
910
        self.roster_win.refresh(roster)
911
        self.contact_info_win.refresh(self.roster_win.get_selected_row())
912
        # self.core.global_information_win.refresh(informations)
913 914 915 916 917 918 919 920 921 922 923 924 925 926
        self.info_win.refresh(informations)
        self.tab_win.refresh(tabs, tabs[0])
        self.input.refresh()

    def get_name(self):
        return self.name

    def get_color_state(self):
        return self._color_state

    def set_color_state(self, color):
        self._color_state = color

    def on_input(self, key):
927 928
        res = self.input.do_command(key)
        if res:
929
            return True
930 931
        if key in self.key_func:
            return self.key_func[key]()
932 933 934 935 936 937 938 939 940 941 942

    def toggle_offline_show(self):
        """
        Show or hide offline contacts
        """
        option = 'roster_show_offline'
        if config.get(option, 'false') == 'false':
            config.set_and_save(option, 'true')
        else:
            config.set_and_save(option, 'false')
        return True
943

944 945 946 947 948
    def on_slash(self):
        """
        '/' is pressed, we enter "input mode"
        """
        curses.curs_set(1)
949 950
        self.input = windows.CommandInput("", self.reset_help_message, self.execute_slash_command)
        self.input.resize(1, self.width, self.height-1, 0, self.core.stdscr)
951 952 953 954 955
        self.input.do_command("/") # we add the slash

    def reset_help_message(self, _=None):
        curses.curs_set(0)
        self.input = self.default_help_message
956
        self.core.refresh_window()
957 958 959 960
        return True

    def execute_slash_command(self, txt):
        if txt.startswith('/'):
961
            self.execute_command(txt)
962
        return self.reset_help_message()
963 964 965 966 967 968

    def on_lose_focus(self):
        self._color_state = theme.COLOR_TAB_NORMAL

    def on_gain_focus(self):
        self._color_state = theme.COLOR_TAB_CURRENT
969 970 971 972
        if isinstance(self.input, windows.HelpText):
            curses.curs_set(0)
        else:
            curses.curs_set(1)
973 974 975 976

    def add_message(self):
        return False

977
    def move_cursor_down(self):
978
        self.roster_win.move_cursor_down()
979
        return True
980

981
    def move_cursor_up(self):
982
        self.roster_win.move_cursor_up()
983 984 985 986 987 988 989 990 991
        return True

    def on_scroll_down(self):
        # Scroll info win
        pass

    def on_scroll_up(self):
        # Scroll info down
        pass
992

993
    def on_info_win_size_changed(self):
994 995
        pass

996 997 998 999 1000 1001
    def on_space(self):
        selected_row = self.roster_win.get_selected_row()
        if isinstance(selected_row, RosterGroup) or\
                isinstance(selected_row, Contact):
            selected_row.toggle_folded()
            return True
1002

1003
    def on_enter(self):
1004
        selected_row = self.roster_win.get_selected_row()
1005
        self.core.on_roster_enter_key(selected_row)
1006
        return selected_row
1007

1008 1009 1010 1011 1012 1013
    def start_search(self):
        """
        Start the search. The input should appear with a short instruction
        in it.
        """
        curses.curs_set(1)
1014 1015
        self.input = windows.CommandInput("[Search]", self.on_search_terminate, self.on_search_terminate, self.set_roster_filter)
        self.input.resize(1, self.width, self.height-1, 0, self.core.stdscr)
1016 1017
        return True

1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
    def start_search_slow(self):
        curses.curs_set(1)
        self.input = windows.CommandInput("[Search]", self.on_search_terminate, self.on_search_terminate, self.set_roster_filter_slow)
        self.input.resize(1, self.width, self.height-1, 0, self.core.stdscr)
        return True

    def set_roster_filter_slow(self, txt):
        roster._contact_filter = (jid_and_name_match_slow, txt)
        self.roster_win.refresh(roster)
        return False

1029 1030
    def set_roster_filter(self, txt):
        roster._contact_filter = (jid_and_name_match, txt)
1031 1032
        self.roster_win.refresh(roster)
        return False
1033

1034 1035 1036
    def on_search_terminate(self, txt):
        curses.curs_set(0)
        roster._contact_filter = None
1037
        self.reset_help_message()
1038
        return False
1039

1040 1041 1042
    def just_before_refresh(self):
        return

1043 1044 1045
    def on_close(self):
        return

1046
class ConversationTab(ChatTab):
1047
    """
1048
    The tab containg a normal conversation (not from a MUC)
1049
    """
1050
    def __init__(self, core, jid):
1051 1052
        txt_buff = text_buffer.TextBuffer()
        ChatTab.__init__(self, core, txt_buff)
1053 1054
        self.color_state = theme.COLOR_TAB_NORMAL
        self._name = jid        # a conversation tab is linked to one specific full jid OR bare jid
1055
        self.text_win = windows.TextWin()
1056
        txt_buff.add_window(self.text_win)
1057 1058 1059
        self.upper_bar = windows.ConversationStatusMessageWin()
        self.info_header = windows.ConversationInfoWin()
        self.info_win = windows.TextWin()
1060
        self.core.information_buffer.add_window(self.info_win)
1061 1062
        self.tab_win = windows.GlobalInfoBar()
        self.input = windows.MessageInput()
1063 1064 1065 1066 1067 1068
        # keys
        self.key_func['^I'] = self.completion
        self.key_func['M-i'] = self.completion
        # commands
        self.commands['unquery'] = (self.command_unquery, _("Usage: /unquery\nUnquery: close the tab"), None)
        self.commands['part'] = (self.command_unquery, _("Usage: /part\Part: close the tab"), None)
1069
        self.resize()
1070

1071 1072 1073
    def completion(self):
        self.complete_commands(self.input)

1074 1075 1076
    def command_say(self, line):
        muc.send_private_message(self.core.xmpp, self.get_name(), line)
        self.core.add_message_to_text_buffer(self.get_room(), line, None, self.core.own_nick)
1077
        logger.log_message(JID(self.get_name()).bare, self.core.own_nick, line)
1078 1079 1080 1081

    def command_unquery(self, arg):
        self.core.close_tab()

1082 1083
    def resize(self):
        Tab.resize(self)
1084 1085
        if not self.visible:
            return
1086
        self.text_win.resize(self.height-4-self.core.information_win_size, self.width, 1, 0, self.core.stdscr)
1087
        self.text_win.rebuild_everything(self._room)
1088 1089
        self.upper_bar.resize(1, self.width, 0, 0, self.core.stdscr)
        self.info_header.resize(1, self.width, self.height-3-self.core.information_win_size, 0, self.core.stdscr)
1090
        self.info_win.resize(self.core.information_win_size, self.width, self.height-2-self.core.information_win_size, 0, self.core.stdscr, self.core.information_buffer)
1091 1092
        self.tab_win.resize(1, self.width, self.height-2, 0, self.core.stdscr)
        self.input.resize(1, self.width, self.height-1, 0, self.core.stdscr)
1093

1094
    def refresh(self, tabs, informations, roster):
1095 1096
        if not self.visible:
            return
1097
        self.text_win.refresh(self._room)
1098
        self.upper_bar.refresh(self.get_name(), roster.get_contact_by_jid(self.get_name()))
1099
        self.info_header.refresh(self.get_name(), roster.get_contact_by_jid(self.get_name()), self._room, self.text_win)
1100 1101 1102 1103 1104
        self.info_win.refresh(informations)
        self.tab_win.refresh(tabs, tabs[0])
        self.input.refresh()

    def get_color_state(self):
1105 1106 1107
        if self.color_state == theme.COLOR_TAB_NORMAL or\
                self.color_state == theme.COLOR_TAB_CURRENT:
            return self.color_state
1108 1109 1110
        return theme.COLOR_TAB_PRIVATE

    def set_color_state(self, color):
1111
        self.color_state = color
1112 1113

    def get_name(self):
1114
        return self._name
1115 1116

    def on_input(self, key):
1117 1118
        if key in self.key_func:
            self.key_func[key]()
1119
            return False
1120
        self.input.do_command(key)
1121
        return False
1122 1123

    def on_lose_focus(self):
1124
        self.set_color_state(theme.COLOR_TAB_NORMAL)
1125 1126
        self.text_win.remove_line_separator()
        self.text_win.add_line_separator()
1127 1128

    def on_gain_focus(self):
1129 1130
        self.set_color_state(theme.COLOR_TAB_CURRENT)
        curses.curs_set(1)
1131 1132

    def on_scroll_up(self):
1133
        self.text_win.scroll_up(self.text_win.height-1)
1134 1135

    def on_scroll_down(self):
1136
        self.text_win.scroll_down(self.text_win.height-1)
1137

1138
    def on_info_win_size_changed(self):
1139 1140 1141
        self.text_win.resize(self.height-3-self.core.information_win_size, self.width, 0, 0, self.core.stdscr)
        self.info_header.resize(1, self.width, self.height-3-self.core.information_win_size, 0, self.core.stdscr)
        self.info_win.resize(self.core.information_win_size, self.width, self.height-2-self.core.information_win_size, 0, self.core.stdscr)
1142 1143

    def get_room(self):
1144
        return self._room