tabs.py 38.1 KB
Newer Older
1
# Copyright 2010 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 40

from sleekxmpp.xmlstream.stanzabase import JID
41
from config import config
42
from roster import RosterGroup, roster
43
from contact import Contact, Resource
44
import multiuserchat as muc
45 46 47 48

class Tab(object):
    number = 0

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

62 63 64 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
    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
95

96 97
    def resize(self):
        self.size = (self.height, self.width) = self.core.stdscr.getmaxyx()
98 99 100 101 102
        if self.height < MIN_HEIGHT or self.width < MIN_WIDTH:
            self.visible = False
        else:
            self.visible = True

103 104 105 106 107 108
    def refresh(self, tabs, informations, roster):
        """
        Called on each screen refresh (when something has changed)
        """
        raise NotImplementedError

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    def get_color_state(self):
        """
        returns the color that should be used in the GlobalInfoBar
        """
        raise NotImplementedError

    def set_color_state(self, color):
        """
        set the color state
        """
        raise NotImplementedError

    def get_name(self):
        """
        get the name of the tab
        """
        raise NotImplementedError

127 128 129 130 131 132
    def get_text_window(self):
        """
        Returns the principal TextWin window, if there's one
        """
        return None

133
    def on_input(self, key):
134
        pass
135 136 137 138 139

    def on_lose_focus(self):
        """
        called when this tab loses the focus.
        """
140
        pass
141 142 143 144 145

    def on_gain_focus(self):
        """
        called when this tab gains the focus.
        """
146
        pass
147 148 149 150 151 152 153 154

    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
        """
155
        return False
156 157 158 159 160

    def on_scroll_down(self):
        """
        Defines what happens when we scrol down
        """
161
        pass
162 163 164 165 166

    def on_scroll_up(self):
        """
        Defines what happens when we scrol down
        """
167
        pass
168

169
    def on_info_win_size_changed(self):
170 171 172
        """
        Called when the window with the informations is resized
        """
173
        pass
174

175 176 177 178 179 180
    def just_before_refresh(self):
        """
        Method called just before the screen refresh.
        Particularly useful to move the cursor at the
        correct position.
        """
181
        pass
182

183 184 185 186
    def on_close(self):
        """
        Called when the tab is to be closed
        """
187
        pass
188

189 190 191 192 193
class InfoTab(Tab):
    """
    The information tab, used to display global informations
    when using a anonymous account
    """
194 195
    def __init__(self, core, name):
        Tab.__init__(self, core)
196 197 198
        self.tab_win = windows.GlobalInfoBar()
        self.text_win = windows.TextWin()
        self.input = windows.Input()
199 200
        self.name = name
        self.color_state = theme.COLOR_TAB_NORMAL
201
        self.resize()
202

203 204
    def resize(self):
        Tab.resize(self)
205 206 207
        self.tab_win.resize(1, self.width, self.height-2, 0, self.core.stdscr)
        self.tab_win.resize(1, self.width, self.height-2, 0, self.core.stdscr)
        self.text_win.resize(self.height-2, self.width, 0, 0, self.core.stdscr)
208
        self.text_win.rebuild_everything(self._room)
209
        self.input.resize(1, self.width, self.height-1, 0, self.core.stdscr)
210

211
    def refresh(self, tabs, informations, _):
212 213
        if not self.visible:
            return
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
        self.text_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):
        return

    def on_input(self, key):
        return self.input.do_command(key)

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

    def on_gain_focus(self):
        self.color_state = theme.COLOR_TAB_CURRENT
235
        curses.curs_set(0)
236 237 238 239 240 241 242

    def on_scroll_up(self):
        pass

    def on_scroll_down(self):
        pass

243
    def on_info_win_size_changed(self):
244 245
        return

246 247 248
    def just_before_refresh(self):
        return

249 250 251
    def on_close(self):
        return

252 253
class ChatTab(Tab):
    """
254 255 256
    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
257
    And also, add the /say command
258
    """
259 260 261 262 263 264 265
    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
266 267
        self.commands['say'] =  (self.command_say,
                                 _("""Usage: /say <message>\nSay: Just send the message.
268
                                        Useful if you want your message to begin with a '/'"""), None)
269 270 271 272 273 274 275 276 277 278 279 280

    def last_words_completion(self):
        """
        Complete the input with words recently said
        """
        # build the list of the recent words
        char_we_dont_want = [',', '(', ')', '.', '"', '\'', ' ', # The last one is nbsp
                             '’', '“', '”', ':', ';', '[', ']', '{', '}']
        words = list()
        for msg in self._room.messages[:-40:-1]:
            if not msg:
                continue
281
            txt = msg.txt
282
            for char in char_we_dont_want:
283 284
                txt = txt.replace(char, ' ')
            for word in txt.split():
285 286
                if len(word) >= 4 and word not in words:
                    words.append(word)
287
        self.input.auto_completion(words, ' ')
288 289

    def on_enter(self):
290 291 292 293 294 295 296 297 298 299 300 301
        txt = 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'))
        else:
302 303
            if txt.startswith('//'):
                txt = txt[1:]
304 305 306
            self.command_say(txt)

    def command_say(self, line):
307 308 309
        raise NotImplementedError

class MucTab(ChatTab):
310 311 312 313
    """
    The tab containing a multi-user-chat room.
    It contains an userlist, an input, a topic, an information and a chat zone
    """
314
    def __init__(self, core, room):
315
        ChatTab.__init__(self, core, room)
316 317
        self.topic_win = windows.Topic()
        self.text_win = windows.TextWin()
318
        room.add_window(self.text_win)
319 320 321 322
        self.v_separator = windows.VerticalSeparator()
        self.user_win = windows.UserList()
        self.info_header = windows.MucInfoWin()
        self.info_win = windows.TextWin()
323
        self.core.information_buffer.add_window(self.info_win)
324 325
        self.tab_win = windows.GlobalInfoBar()
        self.input = windows.MessageInput()
326 327
        self.ignores = []       # set of Users
        # keys
328 329
        self.key_func['^I'] = self.completion
        self.key_func['M-i'] = self.completion
330
        # commands
331 332 333 334 335 336 337 338
        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)
339
        self.resize()
340

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
    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]
            i+= 1
357
        self.text_win.rebuild_everything(self.get_room())
358 359 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 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
        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)

490
    def resize(self):
491 492 493
        """
        Resize the whole window. i.e. all its sub-windows
        """
494
        Tab.resize(self)
495
        text_width = (self.width//10)*9
496 497
        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)
498
        self.text_win.rebuild_everything(self._room)
499 500 501
        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)
502
        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)
503 504
        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)
505

506
    def refresh(self, tabs, informations, _):
507 508
        if not self.visible:
            return
509 510 511 512
        self.topic_win.refresh(self._room.topic)
        self.text_win.refresh(self._room)
        self.v_separator.refresh()
        self.user_win.refresh(self._room.users)
513
        self.info_header.refresh(self._room, self.text_win)
514
        self.tab_win.refresh(tabs, tabs[0])
515
        self.info_win.refresh(informations)
516 517 518
        self.input.refresh()

    def on_input(self, key):
519 520
        if key in self.key_func:
            self.key_func[key]()
521 522 523
            return False
        self.input.do_command(key)
        return False
524 525 526 527 528

    def completion(self):
        """
        Called when Tab is pressed, complete the nickname in the input
        """
529 530
        if self.complete_commands(self.input):
            return
531
        compare_users = lambda x: x.last_talked
532 533 534 535 536 537 538 539
        word_list = [user.nick for user in sorted(self._room.users, key=compare_users, reverse=True)]
        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)
540 541 542 543 544 545 546 547 548 549

    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

550 551 552
    def get_text_window(self):
        return self.text_win

553 554 555 556 557
    def get_room(self):
        return self._room

    def on_lose_focus(self):
        self._room.set_color_state(theme.COLOR_TAB_NORMAL)
558 559
        self.text_win.remove_line_separator()
        self.text_win.add_line_separator()
560 561 562

    def on_gain_focus(self):
        self._room.set_color_state(theme.COLOR_TAB_CURRENT)
563
        curses.curs_set(1)
564 565

    def on_scroll_up(self):
566
        self.text_win.scroll_up(self.text_win.height-1)
567 568

    def on_scroll_down(self):
569
        self.text_win.scroll_down(self.text_win.height-1)
570

571
    def on_info_win_size_changed(self):
572
        text_width = (self.width//10)*9
573 574 575
        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)
576

577
    def just_before_refresh(self):
578
        return
579

580 581 582
    def on_close(self):
        return

583
class PrivateTab(ChatTab):
584 585 586
    """
    The tab containg a private conversation (someone from a MUC)
    """
587
    def __init__(self, core, room):
588
        ChatTab.__init__(self, core, room)
589
        self.text_win = windows.TextWin()
590
        room.add_window(self.text_win)
591 592
        self.info_header = windows.PrivateInfoWin()
        self.info_win = windows.TextWin()
593
        self.core.information_buffer.add_window(self.info_win)
594 595
        self.tab_win = windows.GlobalInfoBar()
        self.input = windows.MessageInput()
596 597 598 599 600 601
        # 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)
602
        self.resize()
603

604 605 606
    def completion(self):
        self.complete_commands(self.input)

607 608 609 610 611 612 613 614 615 616
    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)

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

617 618
    def resize(self):
        Tab.resize(self)
619
        self.text_win.resize(self.height-3-self.core.information_win_size, self.width, 0, 0, self.core.stdscr)
620
        self.text_win.rebuild_everything(self._room)
621
        self.info_header.resize(1, self.width, self.height-3-self.core.information_win_size, 0, self.core.stdscr)
622
        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)
623 624
        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)
625

626
    def refresh(self, tabs, informations, _):
627 628
        if not self.visible:
            return
629
        self.text_win.refresh(self._room)
630
        self.info_header.refresh(self._room, self.text_win)
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
        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):
648 649
        if key in self.key_func:
            self.key_func[key]()
650
            return False
651 652
        self.input.do_command(key)
        return False
653 654 655

    def on_lose_focus(self):
        self._room.set_color_state(theme.COLOR_TAB_NORMAL)
656 657
        self.text_win.remove_line_separator()
        self.text_win.add_line_separator()
658 659 660

    def on_gain_focus(self):
        self._room.set_color_state(theme.COLOR_TAB_CURRENT)
661
        curses.curs_set(1)
662 663

    def on_scroll_up(self):
664
        self.text_win.scroll_up(self.text_win.height-1)
665 666

    def on_scroll_down(self):
667
        self.text_win.scroll_down(self.text_win.height-1)
668

669
    def on_info_win_size_changed(self):
670 671
        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)
672
        self.info_win.resize(self.core.information_win_size, self.width, self.height-2-self.core.information_win_size, 0, self.core.stdscr, None)
673 674 675

    def get_room(self):
        return self._room
676

677 678 679
    def get_text_window(self):
        return self.text_win

680 681 682
    def just_before_refresh(self):
        return

683 684 685
    def on_close(self):
        return

686 687
class RosterInfoTab(Tab):
    """
688
    A tab, splitted in two, containing the roster and infos
689
    """
690 691
    def __init__(self, core):
        Tab.__init__(self, core)
692
        self.name = "Roster"
693 694 695
        self.v_separator = windows.VerticalSeparator()
        self.tab_win = windows.GlobalInfoBar()
        self.info_win = windows.TextWin()
696
        self.core.information_buffer.add_window(self.info_win)
697 698 699
        self.roster_win = windows.RosterWin()
        self.contact_info_win = windows.ContactInfoWin()
        self.default_help_message = windows.HelpText("Enter commands with “/”. “o”: toggle offline show")
700
        self.input = self.default_help_message
701
        self.set_color_state(theme.COLOR_TAB_NORMAL)
702 703 704 705 706 707 708 709 710 711
        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
        self.key_func["^F"] = self.start_search
712
        self.resize()
713

714 715
    def resize(self):
        Tab.resize(self)
716 717
        roster_width = self.width//2
        info_width = self.width-roster_width-1
718 719
        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)
720
        self.info_win.resize(self.height-2, info_width, 0, roster_width+1, self.core.stdscr, self.core.information_buffer)
721 722 723
        self.roster_win.resize(self.height-2-3, roster_width, 0, 0, self.core.stdscr)
        self.contact_info_win.resize(3, roster_width, self.height-2-3, 0, self.core.stdscr)
        self.input.resize(1, self.width, self.height-1, 0, self.core.stdscr)
724

725 726 727 728 729
    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)
730
            
731
    def refresh(self, tabs, informations, roster):
732 733
        if not self.visible:
            return
734
        self.v_separator.refresh()
735
        self.roster_win.refresh(roster)
736
        self.contact_info_win.refresh(self.roster_win.get_selected_row())
737
        # self.core.global_information_win.refresh(informations)
738 739 740 741 742 743 744 745 746 747 748 749 750 751
        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):
752 753
        res = self.input.do_command(key)
        if res:
754
            return True
755 756
        if key in self.key_func:
            return self.key_func[key]()
757 758 759 760 761 762 763 764 765 766 767

    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
768

769 770 771 772 773
    def on_slash(self):
        """
        '/' is pressed, we enter "input mode"
        """
        curses.curs_set(1)
774 775
        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)
776 777 778 779 780 781 782 783 784 785 786
        self.input.do_command("/") # we add the slash

    def reset_help_message(self, _=None):
        curses.curs_set(0)
        self.input = self.default_help_message
        return True

    def execute_slash_command(self, txt):
        if txt.startswith('/'):
            self.core.execute(txt)
        return self.reset_help_message()
787 788 789 790 791 792

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

    def on_gain_focus(self):
        self._color_state = theme.COLOR_TAB_CURRENT
793
        curses.curs_set(0)
794 795 796 797

    def add_message(self):
        return False

798
    def move_cursor_down(self):
799
        self.roster_win.move_cursor_down()
800
        return True
801

802
    def move_cursor_up(self):
803
        self.roster_win.move_cursor_up()
804 805 806 807 808 809 810 811 812
        return True

    def on_scroll_down(self):
        # Scroll info win
        pass

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

814
    def on_info_win_size_changed(self):
815 816
        pass

817 818 819 820 821 822
    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
823

824
    def on_enter(self):
825
        selected_row = self.roster_win.get_selected_row()
826
        self.core.on_roster_enter_key(selected_row)
827
        return selected_row
828

829 830 831 832 833 834
    def start_search(self):
        """
        Start the search. The input should appear with a short instruction
        in it.
        """
        curses.curs_set(1)
835 836
        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)
837 838
        return True

839 840
    def set_roster_filter(self, txt):
        roster._contact_filter = (jid_and_name_match, txt)
841 842
        self.roster_win.refresh(roster)
        return False
843

844 845 846
    def on_search_terminate(self, txt):
        curses.curs_set(0)
        roster._contact_filter = None
847
        self.reset_help_message()
848
        return True
849

850 851 852
    def just_before_refresh(self):
        return

853 854 855
    def on_close(self):
        return

856
class ConversationTab(ChatTab):
857 858 859
    """
    The tab containg a normal conversation (someone from our roster)
    """
860
    def __init__(self, core, text_buffer, jid):
861
        ChatTab.__init__(self, core, text_buffer)
862 863
        self.color_state = theme.COLOR_TAB_NORMAL
        self._name = jid        # a conversation tab is linked to one specific full jid OR bare jid
864
        self.text_win = windows.TextWin()
865
        text_buffer.add_window(self.text_win)
866 867 868
        self.upper_bar = windows.ConversationStatusMessageWin()
        self.info_header = windows.ConversationInfoWin()
        self.info_win = windows.TextWin()
869
        self.core.information_buffer.add_window(self.info_win)
870 871
        self.tab_win = windows.GlobalInfoBar()
        self.input = windows.MessageInput()
872 873 874 875 876 877
        # 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)
878
        self.resize()
879

880 881 882
    def completion(self):
        self.complete_commands(self.input)

883 884 885 886 887 888 889 890 891 892
    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)

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

893 894
    def resize(self):
        Tab.resize(self)
895
        self.text_win.resize(self.height-3-self.core.information_win_size, self.width, 1, 0, self.core.stdscr)
896
        self.text_win.rebuild_everything(self._room)
897 898
        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)
899
        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)
900 901
        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)
902

903
    def refresh(self, tabs, informations, roster):
904 905
        if not self.visible:
            return
906
        self.text_win.refresh(self._room)
907
        self.upper_bar.refresh(self.get_name(), roster.get_contact_by_jid(self.get_name()))
908
        self.info_header.refresh(self.get_name(), roster.get_contact_by_jid(self.get_name()), self._room)
909 910 911 912 913
        self.info_win.refresh(informations)
        self.tab_win.refresh(tabs, tabs[0])
        self.input.refresh()

    def get_color_state(self):
914 915 916
        if self.color_state == theme.COLOR_TAB_NORMAL or\
                self.color_state == theme.COLOR_TAB_CURRENT:
            return self.color_state
917 918 919
        return theme.COLOR_TAB_PRIVATE

    def set_color_state(self, color):
920
        self.color_state = color
921 922

    def get_name(self):
923
        return self._name
924 925

    def on_input(self, key):
926 927
        if key in self.key_func:
            self.key_func[key]()
928
            return False
929
        self.input.do_command(key)
930
        return False
931 932

    def on_lose_focus(self):
933
        self.set_color_state(theme.COLOR_TAB_NORMAL)
934 935
        self.text_win.remove_line_separator()
        self.text_win.add_line_separator()
936 937

    def on_gain_focus(self):
938 939
        self.set_color_state(theme.COLOR_TAB_CURRENT)
        curses.curs_set(1)
940 941

    def on_scroll_up(self):
942
        self.text_win.scroll_up(self.text_win.height-1)
943 944

    def on_scroll_down(self):
945
        self.text_win.scroll_down(self.text_win.height-1)
946

947
    def on_info_win_size_changed(self):
948 949 950
        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)
951 952

    def get_room(self):
953
        return self._room
954

955 956 957
    def get_text_window(self):
        return self.text_win

958 959
    def just_before_refresh(self):
        return
960

961 962 963
    def on_close(self):
        return

964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
class MucListTab(Tab):
    """
    A tab listing rooms from a specific server, displaying various information,
    scrollable, and letting the user join them, etc
    """
    def __init__(self, core, server):
        Tab.__init__(self, core)
        self._color_state = theme.COLOR_TAB_NORMAL
        self.name = server
        self.upper_message = windows.Topic()
        columns = ('node-part','name', 'users')
        self.list_header = windows.ColumnHeaderWin(columns)
        self.listview = windows.ListWin(columns)
        self.tab_win = windows.GlobalInfoBar()
        self.default_help_message = windows.HelpText("“j”: join room. “i”: information")
        self.input = self.default_help_message
        self.key_func["KEY_DOWN"] = self.listview.move_cursor_down
        self.key_func["KEY_UP"] = self.listview.move_cursor_up
        self.key_func["/"] = self.on_slash
        self.key_func['j'] = self.join_selected
        self.key_func['J'] = self.join_selected_no_focus
985 986
        self.key_func['^J'] = self.join_selected
        self.key_func['^M'] = self.join_selected
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
        self.resize()

    def refresh(self, tabs, informations, roster):
        self.upper_message.refresh('Chatroom list on server %s' % self.name)
        self.list_header.refresh()
        self.listview.refresh()
        self.tab_win.refresh(tabs, tabs[0])
        self.input.refresh()

    def resize(self):
        Tab.resize(self)
        self.upper_message.resize(1, self.width, 0, 0, self.core.stdscr)
        column_size = {'node-part': (self.width-5)//4,
                       'name': (self.width-5)//4*3,
                       'users': 5}
        self.list_header.resize_columns(column_size)
        self.list_header.resize(1, self.width, 1, 0, self.core.stdscr)
        self.listview.resize_columns(column_size)
        self.listview.resize(self.height-4, self.width, 2, 0, self.core.stdscr)
        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)

    def on_slash(self):
        """
        '/' is pressed, activate the input
        """
        curses.curs_set(1)
        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)
        self.input.do_command("/") # we add the slash

    def join_selected_no_focus(self):
        return

    def join_selected(self):
1022 1023 1024 1025
        row = self.listview.get_selected_row()
        if not row:
            return
        self.core.command_join(row['jid'])
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

    def reset_help_message(self, _=None):
        curses.curs_set(0)
        self.input = self.default_help_message
        return True

    def execute_slash_command(self, txt):
        if txt.startswith('/'):
            self.core.execute(txt)
        return self.reset_help_message()

    def get_color_state(self):
        return theme.COLOR_TAB_NORMAL

    def set_color_state(self, color):
        pass

    def get_name(self):
        return self.name

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

    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(0)

    def get_color_state(self):
        return self._color_state

1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
def diffmatch(search, string):
    """
    Use difflib and a loop to check if search_pattern can
    be 'almost' found INSIDE a string.
    'almost' being defined by difflib
    """
    l = len(search)
    ratio = 0.7
    for i in range(len(string) - l + 1):
        if difflib.SequenceMatcher(None, search, string[i:i+l]).ratio() >= ratio:
            return True
    return False

1076 1077 1078 1079 1080
def jid_and_name_match(contact, txt):
    """
    A function used to know if a contact in the roster should
    be shown in the roster
    """
1081 1082 1083 1084 1085 1086 1087
    ratio = 0.7
    if not txt:
        return True             # Everything matches when search is empty
    user = JID(contact.get_bare_jid()).user
    if diffmatch(txt, user):
        return True
    if contact.get_name() and diffmatch(txt, contact.get_name()):
1088 1089
        return True
    return False