windows.py 52.5 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
#
# 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/>.

17
"""
18 19 20 21
Define all the windows.
A window is a little part of the screen, for example the input window,
the text window, the roster window, etc.
A Tab (see tab.py) is composed of multiple Windows
22 23
"""

24 25
from gettext import (bindtextdomain, textdomain, bind_textdomain_codeset,
                     gettext as _)
26
from os.path import isfile
27

28 29 30
import logging
log = logging.getLogger(__name__)

31 32 33
import locale
locale.setlocale(locale.LC_ALL, '')

34
import shlex
35
import curses
louiz’'s avatar
louiz’ committed
36
import string
37
from config import config
38

39 40
from threading import Lock

41
from contact import Contact, Resource
42
from roster import RosterGroup, roster
43

44
from message import Line
45
from tabs import MIN_WIDTH, MIN_HEIGHT
46

47 48
from sleekxmpp.xmlstream.stanzabase import JID

49
import theme
50

51 52
g_lock = Lock()

53
LINES_NB_LIMIT = 4096
54

55
class Win(object):
56 57
    def __init__(self):
        pass
58

59
    def _resize(self, height, width, y, x, parent_win):
60
        self.height, self.width, self.x, self.y = height, width, x, y
61 62
        if height == 0 or width == 0:
            return
63 64 65 66
        self._win = curses.newwin(height, width, y, x)

    def _refresh(self):
        self._win.noutrefresh()
67

68 69
    def addnstr(self, *args):
        """
70
        Safe call to addnstr
71 72
        """
        try:
73
            self._win.addnstr(*args)
74 75 76 77 78
        except:
            pass

    def addstr(self, *args):
        """
79
        Safe call to addstr
80
        """
81
        try:
82
            self._win.addstr(*args)
83 84
        except:
            pass
85

86 87 88 89
    def finish_line(self, color):
        """
        Write colored spaces until the end of line
        """
90
        (y, x) = self._win.getyx()
91 92 93
        size = self.width-x
        self.addnstr(' '*size, size, curses.color_pair(color))

94
class UserList(Win):
95 96
    def __init__(self):
        Win.__init__(self)
97
        self.pos = 0
98 99 100
        self.color_role = {'moderator': theme.COLOR_USER_MODERATOR,
                           'participant':theme.COLOR_USER_PARTICIPANT,
                           'visitor':theme.COLOR_USER_VISITOR,
101 102
                           'none':theme.COLOR_USER_NONE,
                           '':theme.COLOR_USER_NONE
103
                           }
104
        self.color_show = {'xa':theme.COLOR_STATUS_XA,
105 106
                           'none':theme.COLOR_STATUS_NONE,
                           '':theme.COLOR_STATUS_NONE,
107 108 109
                           'dnd':theme.COLOR_STATUS_DND,
                           'away':theme.COLOR_STATUS_AWAY,
                           'chat':theme.COLOR_STATUS_CHAT
110
                           }
111

112 113 114 115 116 117 118 119 120
    def scroll_up(self):
        self.pos += 4

    def scroll_down(self):
        self.pos -= 4
        if self.pos < 0:
            self.pos = 0

    def draw_plus(self, y):
louiz’'s avatar
louiz’ committed
121
        self.addstr(y, self.width-2, '++', curses.color_pair(theme.COLOR_MORE_INDICATOR))
122

123
    def refresh(self, users):
124
        with g_lock:
125
            self._win.erase()
126
            y = 0
127 128 129 130
            users = sorted(users)
            if self.pos >= len(users) and self.pos != 0:
                self.pos = len(users)-1
            for user in users[self.pos:]:
131 132 133 134 135 136 137 138 139
                if not user.role in self.color_role:
                    role_col = theme.COLOR_USER_NONE
                else:
                    role_col = self.color_role[user.role]
                if not user.show in self.color_show:
                    show_col = theme.COLOR_STATUS_NONE
                else:
                    show_col = self.color_show[user.show]
                self.addstr(y, 0, theme.CHAR_STATUS, curses.color_pair(show_col))
140
                self.addstr(y, 1, user.nick[:self.width-2], curses.color_pair(role_col))
141 142 143
                y += 1
                if y == self.height:
                    break
144 145 146 147 148
            # draw indicators of position in the list
            if self.pos > 0:
                self.draw_plus(0)
            if self.pos + self.height < len(users):
                self.draw_plus(self.height-1)
149
            self._refresh()
150

151 152
    def resize(self, height, width, y, x, stdscr):
        self._resize(height, width, y, x, stdscr)
153 154 155
        self._win.attron(curses.color_pair(theme.COLOR_VERTICAL_SEPARATOR))
        self._win.vline(0, 0, curses.ACS_VLINE, self.height)
        self._win.attroff(curses.color_pair(theme.COLOR_VERTICAL_SEPARATOR))
156

157
class Topic(Win):
158 159
    def __init__(self):
        Win.__init__(self)
160
        self._message = ''
161

162 163
    def resize(self, height, width, y, x, stdscr):
        self._resize(height, width, y, x, stdscr)
164

165
    def refresh(self, topic=None):
166
        with g_lock:
167
            self._win.erase()
168 169 170 171 172
            if topic:
                msg = topic[:self.width-1]
            else:
                msg = self._message[:self.width-1]
            self.addstr(0, 0, msg, curses.color_pair(theme.COLOR_TOPIC_BAR))
173
            (y, x) = self._win.getyx()
174 175 176 177
            remaining_size = self.width - x
            if remaining_size:
                self.addnstr(' '*remaining_size, remaining_size,
                             curses.color_pair(theme.COLOR_INFORMATION_BAR))
178
            self._refresh()
179

180 181 182
    def set_message(self, message):
        self._message = message

183
class GlobalInfoBar(Win):
184 185
    def __init__(self):
        Win.__init__(self)
186

187 188
    def resize(self, height, width, y, x, stdscr):
        self._resize(height, width, y, x, stdscr)
189

190
    def refresh(self, tabs, current):
191 192 193 194
        def compare_room(a):
            # return a.nb - b.nb
            return a.nb
        comp = lambda x: x.nb
195
        with g_lock:
196
            self._win.erase()
197
            self.addstr(0, 0, "[", curses.color_pair(theme.COLOR_INFORMATION_BAR))
198 199 200
            sorted_tabs = sorted(tabs, key=comp)
            for tab in sorted_tabs:
                color = tab.get_color_state()
201 202 203
                if config.get('show_inactive_tabs', 'true') == 'false' and\
                        color == theme.COLOR_TAB_NORMAL:
                    continue
204 205 206 207 208
                try:
                    self.addstr("%s" % str(tab.nb), curses.color_pair(color))
                    self.addstr("|", curses.color_pair(theme.COLOR_INFORMATION_BAR))
                except:             # end of line
                    break
209
            (y, x) = self._win.getyx()
210
            self.addstr(y, x-1, '] ', curses.color_pair(theme.COLOR_INFORMATION_BAR))
211
            (y, x) = self._win.getyx()
212 213 214
            remaining_size = self.width - x
            self.addnstr(' '*remaining_size, remaining_size,
                         curses.color_pair(theme.COLOR_INFORMATION_BAR))
215
            self._refresh()
216

217 218 219 220 221
class InfoWin(Win):
    """
    Base class for all the *InfoWin, used in various tabs. For example
    MucInfoWin, etc. Provides some useful methods.
    """
222 223
    def __init__(self):
        Win.__init__(self)
224

225
    def print_scroll_position(self, window):
226 227 228 229 230
        """
        Print, link in Weechat, a -PLUS(n)- where n
        is the number of available lines to scroll
        down
        """
231 232
        if window.pos > 0:
            plus = ' -PLUS(%s)-' % window.pos
233
            self.addstr(plus, curses.color_pair(theme.COLOR_SCROLLABLE_NUMBER) | curses.A_BOLD)
234 235 236 237 238 239

class PrivateInfoWin(InfoWin):
    """
    The live above the information window, displaying informations
    about the MUC user we are talking to
    """
240 241
    def __init__(self):
        InfoWin.__init__(self)
242

243 244
    def resize(self, height, width, y, x, stdscr):
        self._resize(height, width, y, x, stdscr)
245

246
    def refresh(self, room, window):
247

248
        with g_lock:
249
            self._win.erase()
250
            self.write_room_name(room)
251
            self.print_scroll_position(window)
252
            self.finish_line(theme.COLOR_INFORMATION_BAR)
253
            self._refresh()
254 255

    def write_room_name(self, room):
256 257
        jid = JID(room.name)
        room_name, nick = jid.bare, jid.resource
louiz’'s avatar
louiz’ committed
258
        self.addstr(nick, curses.color_pair(theme.COLOR_PRIVATE_NAME))
259
        txt = ' from room %s' % room_name
260
        self.addstr(txt, curses.color_pair(theme.COLOR_INFORMATION_BAR))
261

262 263 264
class ConversationInfoWin(InfoWin):
    """
    The line above the information window, displaying informations
265
    about the user we are talking to
266
    """
267 268 269 270 271 272 273 274 275 276
    color_show = {'xa':theme.COLOR_STATUS_XA,
                  'none':theme.COLOR_STATUS_ONLINE,
                  '':theme.COLOR_STATUS_ONLINE,
                  'available':theme.COLOR_STATUS_ONLINE,
                  'dnd':theme.COLOR_STATUS_DND,
                  'away':theme.COLOR_STATUS_AWAY,
                  'chat':theme.COLOR_STATUS_CHAT,
                  'unavailable':theme.COLOR_STATUS_UNAVAILABLE
                  }

277 278
    def __init__(self):
        InfoWin.__init__(self)
279

280 281
    def resize(self, height, width, y, x, stdscr):
        self._resize(height, width, y, x, stdscr)
282

283
    def refresh(self, jid, contact, text_buffer, window):
284 285 286
        # contact can be None, if we receive a message
        # from someone not in our roster. In this case, we display
        # only the maximum information from the message we can get.
287 288 289 290 291 292 293 294 295 296 297 298 299
        jid = JID(jid)
        if contact:
            if jid.resource:
                resource = contact.get_resource_by_fulljid(jid.full)
            else:
                resource = contact.get_highest_priority_resource()
        else:
            resource = None
        # if contact is None, then resource is None too: user is not in the roster
        # so we don't know almost anything about it
        # If contact is a Contact, then
        # resource can now be a Resource: user is in the roster and online
        # or resource is None: user is in the roster but offline
300
        with g_lock:
301
            self._win.erase()
302 303 304
            self.write_contact_jid(jid)
            self.write_contact_informations(contact)
            self.write_resource_information(resource)
305
            self.print_scroll_position(window)
306
            self.finish_line(theme.COLOR_INFORMATION_BAR)
307
            self._refresh()
308

309 310 311 312 313 314 315 316 317 318
    def write_resource_information(self, resource):
        """
        Write the informations about the resource
        """
        if not resource:
            presence = "unavailable"
        else:
            presence = resource.get_presence()
        color = RosterWin.color_show[presence]
        self.addstr('[', curses.color_pair(theme.COLOR_INFORMATION_BAR))
louiz’'s avatar
louiz’ committed
319
        self.addstr(" ", curses.color_pair(color))
320 321 322 323 324 325
        self.addstr(']', curses.color_pair(theme.COLOR_INFORMATION_BAR))

    def write_contact_informations(self, contact):
        """
        Write the informations about the contact
        """
326
        if not contact:
327 328 329 330 331 332 333 334 335 336
            self.addstr("(contact not in roster)", curses.color_pair(theme.COLOR_INFORMATION_BAR))
            return
        display_name = contact.get_name() or contact.get_bare_jid()
        self.addstr('%s '%(display_name), curses.color_pair(theme.COLOR_INFORMATION_BAR))

    def write_contact_jid(self, jid):
        """
        Just write the jid that we are talking to
        """
        self.addstr('[', curses.color_pair(theme.COLOR_INFORMATION_BAR))
louiz’'s avatar
louiz’ committed
337
        self.addstr(jid.full, curses.color_pair(theme.COLOR_CONVERSATION_NAME))
338 339 340 341 342 343
        self.addstr('] ', curses.color_pair(theme.COLOR_INFORMATION_BAR))

class ConversationStatusMessageWin(InfoWin):
    """
    The upper bar displaying the status message of the contact
    """
344 345
    def __init__(self):
        InfoWin.__init__(self)
346

347 348
    def resize(self, height, width, y, x, stdscr):
        self._resize(height, width, y, x, stdscr)
349 350 351 352 353 354 355 356

    def refresh(self, jid, contact):
        jid = JID(jid)
        if contact:
            if jid.resource:
                resource = contact.get_resource_by_fulljid(jid.full)
            else:
                resource = contact.get_highest_priority_resource()
357
        else:
358 359 360 361 362 363 364 365 366 367
            resource = None
        with g_lock:
            self._win.erase()
            if resource:
                self.write_status_message(resource)
            self.finish_line(theme.COLOR_INFORMATION_BAR)
            self._refresh()

    def write_status_message(self, resource):
        self.addstr(resource.get_status(), curses.color_pair(theme.COLOR_INFORMATION_BAR))
368

369 370 371 372 373
class MucInfoWin(InfoWin):
    """
    The line just above the information window, displaying informations
    about the MUC we are viewing
    """
374 375
    def __init__(self):
        InfoWin.__init__(self)
376

377 378
    def resize(self, height, width, y, x, stdscr):
        self._resize(height, width, y, x, stdscr)
379

380
    def refresh(self, room, window=None):
381
        with g_lock:
382
            self._win.erase()
383 384 385 386
            self.write_room_name(room)
            self.write_own_nick(room)
            self.write_disconnected(room)
            self.write_role(room)
387 388
            if window:
                self.print_scroll_position(window)
389
            self.finish_line(theme.COLOR_INFORMATION_BAR)
390
            self._refresh()
391 392 393 394

    def write_room_name(self, room):
        """
        """
395
        self.addstr('[', curses.color_pair(theme.COLOR_INFORMATION_BAR))
louiz’'s avatar
louiz’ committed
396
        self.addnstr(room.name, len(room.name), curses.color_pair(theme.COLOR_GROUPCHAT_NAME))
397
        self.addstr('] ', curses.color_pair(theme.COLOR_INFORMATION_BAR))
398 399 400 401 402 403

    def write_disconnected(self, room):
        """
        Shows a message if the room is not joined
        """
        if not room.joined:
404 405
            self.addstr(' -!- Not connected ', curses.color_pair(theme.COLOR_INFORMATION_BAR))

406 407 408 409 410 411 412 413 414
    def write_own_nick(self, room):
        """
        Write our own nick in the info bar
        """
        nick = room.own_nick
        if not nick:
            return
        if len(nick) > 13:
            nick = nick[:13]+'…'
415
        self.addstr(nick, curses.color_pair(theme.COLOR_INFORMATION_BAR))
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431

    def write_role(self, room):
        """
        Write our own role and affiliation
        """
        own_user = None
        for user in room.users:
            if user.nick == room.own_nick:
                own_user = user
                break
        if not own_user:
            return
        txt = ' ('
        if own_user.affiliation != 'none':
            txt += own_user.affiliation+', '
        txt += own_user.role+')'
432
        self.addstr(txt, curses.color_pair(theme.COLOR_INFORMATION_BAR))
433

434
class TextWin(Win):
435 436
    def __init__(self):
        Win.__init__(self)
437 438 439 440 441 442
        self.pos = 0
        self.built_lines = []   # Each new message is built and kept here.
        # on resize, we rebuild all the messages

    def scroll_up(self, dist=14):
        self.pos += dist
443 444 445 446
        if self.pos + self.height > len(self.built_lines):
            self.pos = len(self.built_lines) - self.height
            if self.pos < 0:
                self.pos = 0
447 448 449 450 451 452

    def scroll_down(self, dist=14):
        self.pos -= dist
        if self.pos <= 0:
            self.pos = 0

453 454 455 456 457 458 459 460 461 462 463 464 465 466
    def remove_line_separator(self):
        """
        Remove the line separator
        """
        if None in self.built_lines:
            self.built_lines.remove(None)

    def add_line_separator(self):
        """
        add a line separator at the end of messages list
        """
        if None not in self.built_lines:
            self.built_lines.append(None)

467 468 469 470 471 472 473 474 475 476 477 478
    def build_new_message(self, message):
        """
        Take one message, build it and add it to the list
        Return the number of lines that are built for the given
        message.
        """
        if message == None:  # line separator
            self.built_lines.append(None)
            return 0
        txt = message.txt
        if not txt:
            return 0
479
            # length of the time
480 481 482 483 484 485 486 487 488 489 490
        offset = 9+len(theme.CHAR_TIME_LEFT[:1])+len(theme.CHAR_TIME_RIGHT[:1])
        if message.nickname and len(message.nickname) >= 30:
            nick = message.nickname[:30]+'…'
        else:
            nick = message.nickname
        if nick:
            offset += len(nick) + 2 # + nick + spaces length
        first = True
        this_line_was_broken_by_space = False
        nb = 0
        while txt != '':
louiz’'s avatar
louiz’ committed
491 492
            limit = txt[:self.width-offset].find('\n')
            if limit < 0:
493 494 495 496 497 498
                # break between words if possible
                if len(txt) >= self.width-offset:
                    limit = txt[:self.width-offset].rfind(' ')
                    this_line_was_broken_by_space = True
                    if limit <= 0:
                        limit = self.width-offset
499 500
                        this_line_was_broken_by_space = False
                else:
501 502
                    limit = self.width-offset-1
                    this_line_was_broken_by_space = False
503
            color = message.user.color if message.user else message.nick_color
504 505 506
            if not first:
                nick = None
                time = None
507 508 509 510 511 512 513
            else:               # strftime is VERY slow, improve performance
                                # by calling it only one time here, and
                                # not at each refresh
                time = {'hour': '%s'%(message.time.strftime("%H"),),
                        'minute': '%s'%(message.time.strftime("%M"),),
                        'second': '%s'%(message.time.strftime("%S"),),
                        }
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
            l = Line(nick, color,
                     time,
                     txt[:limit], message.color,
                     offset,
                     message.colorized)
            self.built_lines.append(l)
            nb += 1
            if this_line_was_broken_by_space:
                txt = txt[limit+1:] # jump the space at the start of the line
            else:
                txt = txt[limit:]
            if txt.startswith('\n'):
                txt = txt[1:]
            first = False
        while len(self.built_lines) > LINES_NB_LIMIT:
            self.built_lines.pop(0)
        return nb
531

532
    def refresh(self, room):
533
        """
534 535
        Build the Line objects from the messages, and then write
        them in the text area
536
        """
537
        if self.height <= 0:
538
            return
539
        if self.pos == 0:
540
            lines = self.built_lines[-self.height:]
541 542
        else:
            lines = self.built_lines[-self.height-self.pos:-self.pos]
543
        self._win.move(0, 0)
544
        with g_lock:
545
            self._win.erase()
546 547
            for y, line in enumerate(lines):
                if line is None:
548
                    self.write_line_separator()
549 550 551 552 553 554
                else:
                    if line.time:
                        self.write_time(line.time)
                    if line.nickname:
                        self.write_nickname(line.nickname, line.nickname_color)
                    self.write_text(y, line.text_offset, line.text, line.text_color, line.colorized)
555
                if y != self.height-1 or (not line or line.text_offset+len(line.text) < self.width):
556
                    self.addstr('\n')
557
            self._refresh()
558

559 560 561
    def write_line_separator(self):
        """
        """
562
        self.addnstr('- '*(self.width//2-1)+'-', self.width, curses.color_pair(theme.COLOR_NEW_TEXT_SEPARATOR))
563

564
    def write_text(self, y, x, txt, color, colorized):
565
        """
566
        write the text of a line.
567
        """
568
        txt = txt
569 570
        if not colorized:
            if color:
571
                self._win.attron(curses.color_pair(color))
572
            self.addstr(y, x, txt)
573
            if color:
574
                self._win.attroff(curses.color_pair(color))
575 576 577 578 579 580 581

        else:                   # Special messages like join or quit
            special_words = {
                theme.CHAR_JOIN: theme.COLOR_JOIN_CHAR,
                theme.CHAR_QUIT: theme.COLOR_QUIT_CHAR,
                theme.CHAR_KICK: theme.COLOR_KICK_CHAR,
                }
582 583 584
            try:
                splitted = shlex.split(txt)
            except ValueError:
585 586 587 588 589
                # FIXME colors are disabled on too long words
                txt = txt.replace('"[', '').replace(']"', '')\
                    .replace('"{', '').replace('}"', '')\
                    .replace('"(', '').replace(')"', '')
                splitted = txt.split()
590
            for word in splitted:
591
                if word in list(special_words.keys()):
592
                    self.addstr(word, curses.color_pair(special_words[word]))
593
                elif word.startswith('(') and word.endswith(')'):
594 595 596
                    self.addstr('(', curses.color_pair(color))
                    self.addstr(word[1:-1], curses.color_pair(theme.COLOR_CURLYBRACKETED_WORD))
                    self.addstr(')', curses.color_pair(color))
597
                elif word.startswith('{') and word.endswith('}'):
598
                    self.addstr(word[1:-1], curses.color_pair(theme.COLOR_ACCOLADE_WORD))
599
                elif word.startswith('[') and word.endswith(']'):
600
                    self.addstr(word[1:-1], curses.color_pair(theme.COLOR_BRACKETED_WORD))
601
                else:
602
                    self.addstr(word, curses.color_pair(color))
603
                self.addstr(' ')
604

605
    def write_nickname(self, nickname, color):
606 607 608 609
        """
        Write the nickname, using the user's color
        and return the number of written characters
        """
610
        if color:
611
            self._win.attron(curses.color_pair(color))
612
        self.addstr(nickname)
613
        if color:
614
            self._win.attroff(curses.color_pair(color))
615
        self.addstr("> ")
616

617
    def write_time(self, time):
618 619 620
        """
        Write the date on the yth line of the window
        """
621
        self.addstr(theme.CHAR_TIME_LEFT, curses.color_pair(theme.COLOR_TIME_LIMITER))
622
        self.addstr(time['hour'], curses.color_pair(theme.COLOR_TIME_NUMBERS))
623
        self.addstr(':', curses.color_pair(theme.COLOR_TIME_SEPARATOR))
624
        self.addstr(time['minute'], curses.color_pair(theme.COLOR_TIME_NUMBERS))
625
        self.addstr(':', curses.color_pair(theme.COLOR_TIME_SEPARATOR))
626 627
        self.addstr(time['second'], curses.color_pair(theme.COLOR_TIME_NUMBERS))
        self.addstr(theme.CHAR_TIME_RIGHT, curses.color_pair(theme.COLOR_TIME_LIMITER))
628
        self.addstr(' ')
629

630
    def resize(self, height, width, y, x, stdscr, room=None):
631
        self._resize(height, width, y, x, stdscr)
632 633 634 635 636 637 638
        if room:
            self.rebuild_everything(room)

    def rebuild_everything(self, room):
        self.built_lines = []
        for message in room.messages:
            self.build_new_message(message)
639

640 641
class HelpText(Win):
    """
642
    A Window just displaying a read-only message.
643 644 645
    Usually used to replace an Input when the tab is in
    command mode.
    """
646 647
    def __init__(self, text=''):
        Win.__init__(self)
648 649
        self.txt = text

650 651
    def resize(self, height, width, y, x, stdscr):
        self._resize(height, width, y, x, stdscr)
652 653 654 655 656 657 658 659 660 661 662

    def refresh(self):
        with g_lock:
            self._win.erase()
            self.addstr(0, 0, self.txt[:self.width-1], curses.color_pair(theme.COLOR_INFORMATION_BAR))
            self.finish_line(theme.COLOR_INFORMATION_BAR)
            self._refresh()

    def do_command(self, key):
        return False

663 664
class Input(Win):
    """
665 666 667 668 669 670 671 672 673
    The simplest Input possible, provides just a way to edit a single line
    of text. It also has a clipboard, common to all Inputs.
    Doesn't have any history.
    It doesn't do anything when enter is pressed either.
    This should be herited for all kinds of Inputs, for example MessageInput
    or the little inputs in dataforms, etc, adding specific features (completion etc)
    It features two kinds of completion, but they have to be called from outside (the Tab),
    passing the list of items that can be used to complete. The completion can be used
    in a very flexible way.
674
    """
675 676
    clipboard = '' # A common clipboard for all the inputs, this makes
    # it easy cut and paste text between various input
677
    def __init__(self):
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
        self.key_func = {
            "KEY_LEFT": self.key_left,
            "M-D": self.key_left,
            "KEY_RIGHT": self.key_right,
            "M-C": self.key_right,
            "KEY_END": self.key_end,
            "KEY_HOME": self.key_home,
            "KEY_DC": self.key_dc,
            '^D': self.key_dc,
            'M-b': self.jump_word_left,
            '^W': self.delete_word,
            '^K': self.delete_end_of_line,
            '^U': self.delete_begining_of_line,
            '^Y': self.paste_clipboard,
            '^A': self.key_home,
            '^E': self.key_end,
            'M-f': self.jump_word_right,
            "KEY_BACKSPACE": self.key_backspace,
            '^?': self.key_backspace,
            }
698
        Win.__init__(self)
699
        self.text = ''
700 701
        self.pos = 0            # cursor position
        self.line_pos = 0 # position (in self.text) of
louiz’'s avatar
louiz’ committed
702 703 704 705 706 707
        self.on_input = None    # callback called on any key pressed
        self.color = None       # use this color on addstr

    def set_color(self, color):
        self.color = color
        self.rewrite_text()
708

709 710 711
    def is_empty(self):
        return len(self.text) == 0

louiz’'s avatar
louiz’ committed
712
    def resize(self, height, width, y, x, stdscr=None): # TODO remove stdscr
713
        self._resize(height, width, y, x, stdscr)
louiz’'s avatar
louiz’ committed
714 715
        # self._win.erase()
        # self.addnstr(0, 0, self.text, self.width-1)
716

717 718 719 720 721 722
    def jump_word_left(self):
        """
        Move the cursor one word to the left
        """
        if not len(self.text) or self.pos == 0:
            return
louiz’'s avatar
louiz’ committed
723 724 725 726
        separators = string.punctuation+' '
        while self.pos > 0 and self.text[self.pos+self.line_pos-1] in separators:
            self.key_left()
        while self.pos > 0 and self.text[self.pos+self.line_pos-1] not in separators:
727
            self.key_left()
728
        return True
729 730 731 732 733 734 735

    def jump_word_right(self):
        """
        Move the cursor one word to the right
        """
        if len(self.text) == self.pos+self.line_pos or not len(self.text):
            return
louiz’'s avatar
louiz’ committed
736 737 738 739
        separators = string.punctuation+' '
        while len(self.text) != self.pos+self.line_pos and self.text[self.pos+self.line_pos] in separators:
            self.key_right()
        while len(self.text) != self.pos+self.line_pos and self.text[self.pos+self.line_pos] not in separators:
740
            self.key_right()
741
        return True
742 743 744 745 746 747 748

    def delete_word(self):
        """
        Delete the word just before the cursor
        """
        if not len(self.text) or self.pos == 0:
            return
louiz’'s avatar
louiz’ committed
749 750 751 752 753 754
        separators = string.punctuation+' '
        while self.pos > 0 and self.text[self.pos+self.line_pos-1] in separators:
            self.key_backspace()
        while self.pos > 0 and self.text[self.pos+self.line_pos-1] not in separators:
            self.key_backspace()

755
        return True
756 757 758 759 760 761 762

    def delete_end_of_line(self):
        """
        Cut the text from cursor to the end of line
        """
        if len(self.text) == self.pos+self.line_pos:
            return              # nothing to cut
763
        Input.clipboard = self.text[self.pos+self.line_pos:]
764 765
        self.text = self.text[:self.pos+self.line_pos]
        self.key_end()
766
        return True
767 768 769 770 771 772 773

    def delete_begining_of_line(self):
        """
        Cut the text from cursor to the begining of line
        """
        if self.pos+self.line_pos == 0:
            return
774
        Input.clipboard = self.text[:self.pos+self.line_pos]
775 776
        self.text = self.text[self.pos+self.line_pos:]
        self.key_home()
777
        return True
778 779 780 781 782

    def paste_clipboard(self):
        """
        Insert what is in the clipboard at the cursor position
        """
783
        if not Input.clipboard or len(Input.clipboard) == 0:
784
            return
785
        for letter in Input.clipboard:
786
            self.do_command(letter)
787
        return True
788

789
    def key_dc(self):
790 791 792
        """
        delete char just after the cursor
        """
793
        self.reset_completion()
794 795 796 797
        if self.pos + self.line_pos == len(self.text):
            return              # end of line, nothing to delete
        self.text = self.text[:self.pos+self.line_pos]+self.text[self.pos+self.line_pos+1:]
        self.rewrite_text()
798
        return True
799 800

    def key_home(self):
801 802 803
        """
        Go to the begining of line
        """
804
        self.reset_completion()
805
        self.pos = 0
806 807
        self.line_pos = 0
        self.rewrite_text()
808
        return True
809

810 811 812 813 814 815
    def key_end(self, reset=False):
        """
        Go to the end of line
        """
        if reset:
            self.reset_completion()
816
        if len(self.text) >= self.width-1:
817 818
            self.pos = self.width-1
            self.line_pos = len(self.text)-self.pos
819
        else:
820 821 822
            self.pos = len(self.text)
            self.line_pos = 0
        self.rewrite_text()
823
        return True
824 825

    def key_left(self):
826 827 828
        """
        Move the cursor one char to the left
        """
829
        self.reset_completion()
830
        (y, x) = self._win.getyx()
831 832 833
        if self.pos == self.width-1 and self.line_pos > 0:
            self.line_pos -= 1
        elif self.pos >= 1:
834
            self.pos -= 1
835
        self.rewrite_text()
836
        return True
837 838

    def key_right(self):
839 840 841
        """
        Move the cursor one char to the right
        """
842
        self.reset_completion()
843
        (y, x) = self._win.getyx()
844 845 846 847
        if self.pos == self.width-1:
            if self.line_pos + self.width-1 < len(self.text):
                self.line_pos += 1
        elif self.pos < len(self.text):
848
            self.pos += 1
849
        self.rewrite_text()
850
        return True
851

852
    def key_backspace(self, reset=True):
853 854 855
        """
        Delete the char just before the cursor
        """
856
        self.reset_completion()
857
        (y, x) = self._win.getyx()
858 859 860 861
        if self.pos == 0:
            return
        self.text = self.text[:self.pos+self.line_pos-1]+self.text[self.pos+self.line_pos:]
        self.key_left()
862 863
        if reset:
            self.rewrite_text()
864
        return True
865

866
    def auto_completion(self, word_list, add_after):
867
        """
868 869 870 871
        Complete the input, from a list of words
        if add_after is None, we use the value defined in completion
        plus a space, after the completion. If it's a string, we use it after the
        completion (with no additional space)
872
        """
873
        if self.pos+self.line_pos != len(self.text): # or len(self.text) == 0
874
            return # we don't complete if cursor is not at the end of line
875
        completion_type = config.get('completion', 'normal')
876
        if completion_type == 'shell' and self.text != '':
877
            self.shell_completion(word_list, add_after)
878
        else:
879
            self.normal_completion(word_list, add_after)
880
        return True
881 882

    def reset_completion(self):
883 884 885
        """
        Reset the completion list (called on ALL keys except tab)
        """
886
        self.hit_list = []
887
        self.last_completion = None
888

889
    def normal_completion(self, word_list, after):
890 891 892
        """
        Normal completion
        """
893
        (y, x) = self._win.getyx()
894
        if not self.last_completion:
895 896
            # begin is the begining of the word we want to complete
            if self.text.strip() and not self.text.endswith(' '):
897
                begin = self.text.split()[-1].lower()
898 899
            else:
                begin = ''
900
            hit_list = []       # list of matching nicks
901 902 903
            for word in word_list:
                if word.lower().startswith(begin):
                    hit_list.append(word)
904 905 906
            if len(hit_list) == 0:
                return
            self.hit_list = hit_list
907
            end = len(begin)
908
        else:
909 910 911 912
            if after:
                begin = self.text[-len(after)-len(self.last_completion):-len(after)]
            else:
                begin = self.last_completion
913
            self.hit_list.append(self.hit_list.pop(0)) # rotate list
914
            end = len(begin) + len(after)
915 916
        if end:
            self.text = self.text[:-end]
917
        nick = self.hit_list[0] # take the first hit
918 919
        self.last_completion = nick
        self.text += nick +after
920
        self.key_end(False)
921

922
    def shell_completion(self, word_list, after):
923 924 925
        """
        Shell-like completion
        """
926
        if " " in self.text.strip() or add_after is not None:
927 928 929
            after = " " # don't put the "," if it's not the begining of the sentence
        else:
            after = config.get('after_completion', ',')+" "
930
        (y, x) = self._win.getyx()
931
        if self.text != '':
932
            begin = self.text.split()[-1].lower()
933 934
        else:
            begin = ''
935
        hit_list = []       # list of matching nicks
936
        for user in word_list:
937 938
            if user.lower().startswith(begin):
                hit_list.append(user)
939