windows.py 51.2 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
36
from config import config
37

38 39
from threading import Lock

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

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

46 47
from sleekxmpp.xmlstream.stanzabase import JID

48
import theme
49

50 51
g_lock = Lock()

52
LINES_NB_LIMIT = 4096
53

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

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

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

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

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

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

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

111 112 113 114 115 116 117 118 119 120 121
    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):
        self.addstr(y, self.width-2, '++', curses.color_pair(42))

122
    def refresh(self, users):
123
        with g_lock:
124
            self._win.erase()
125
            y = 0
126 127 128 129
            users = sorted(users)
            if self.pos >= len(users) and self.pos != 0:
                self.pos = len(users)-1
            for user in users[self.pos:]:
130 131 132 133 134 135 136 137 138
                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))
139
                self.addstr(y, 1, user.nick[:self.width-1], curses.color_pair(role_col))
140 141 142
                y += 1
                if y == self.height:
                    break
143 144 145 146 147
            # 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)
148
            self._refresh()
149

150 151
    def resize(self, height, width, y, x, stdscr):
        self._resize(height, width, y, x, stdscr)
152 153 154
        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))
155

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

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

164
    def refresh(self, topic=None):
165
        with g_lock:
166
            self._win.erase()
167 168 169 170 171
            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))
172
            (y, x) = self._win.getyx()
173 174 175 176
            remaining_size = self.width - x
            if remaining_size:
                self.addnstr(' '*remaining_size, remaining_size,
                             curses.color_pair(theme.COLOR_INFORMATION_BAR))
177
            self._refresh()
178

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

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

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

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

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

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

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

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

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

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

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

261 262 263
class ConversationInfoWin(InfoWin):
    """
    The line above the information window, displaying informations
264
    about the user we are talking to
265
    """
266 267 268 269 270 271 272 273 274 275
    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
                  }

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

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

282
    def refresh(self, jid, contact, text_buffer, window):
283 284 285
        # 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.
286 287 288 289 290 291 292 293 294 295 296 297 298
        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
299
        with g_lock:
300
            self._win.erase()
301 302 303
            self.write_contact_jid(jid)
            self.write_contact_informations(contact)
            self.write_resource_information(resource)
304
            self.print_scroll_position(window)
305
            self.finish_line(theme.COLOR_INFORMATION_BAR)
306
            self._refresh()
307

308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
    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))
        self.addstr(" ", curses.color_pair(color))
        self.addstr(']', curses.color_pair(theme.COLOR_INFORMATION_BAR))

    def write_contact_informations(self, contact):
        """
        Write the informations about the contact
        """
325
        if not contact:
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
            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))
        self.addstr(jid.full, curses.color_pair(10))
        self.addstr('] ', curses.color_pair(theme.COLOR_INFORMATION_BAR))

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

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

    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()
356
        else:
357 358 359 360 361 362 363 364 365 366
            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))
367

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

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

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

    def write_room_name(self, room):
        """
        """
394
        self.addstr('[', curses.color_pair(theme.COLOR_INFORMATION_BAR))
395
        self.addnstr(room.name, len(room.name), curses.color_pair(13))
396
        self.addstr('] ', curses.color_pair(theme.COLOR_INFORMATION_BAR))
397 398 399 400 401 402

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

405 406 407 408 409 410 411 412 413
    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]+'…'
414
        self.addstr(nick, curses.color_pair(theme.COLOR_INFORMATION_BAR))
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430

    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+')'
431
        self.addstr(txt, curses.color_pair(theme.COLOR_INFORMATION_BAR))
432

433
class TextWin(Win):
434 435
    def __init__(self):
        Win.__init__(self)
436 437 438 439 440 441
        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
442 443 444 445
        if self.pos + self.height > len(self.built_lines):
            self.pos = len(self.built_lines) - self.height
            if self.pos < 0:
                self.pos = 0
446 447 448 449 450 451

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

452 453 454 455 456 457 458 459 460 461 462 463 464 465
    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)

466 467 468 469 470 471 472 473 474 475 476 477
    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
478
            # length of the time
479 480 481 482 483 484 485 486 487 488 489
        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
490 491
            limit = txt[:self.width-offset].find('\n')
            if limit < 0:
492 493 494 495 496 497
                # 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
498 499
                        this_line_was_broken_by_space = False
                else:
500 501
                    limit = self.width-offset-1
                    this_line_was_broken_by_space = False
502
            color = message.user.color if message.user else message.nick_color
503 504 505
            if not first:
                nick = None
                time = None
506 507 508 509 510 511 512
            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"),),
                        }
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
            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
530

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

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

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

        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,
                }
581 582 583
            try:
                splitted = shlex.split(txt)
            except ValueError:
584 585 586 587 588
                # FIXME colors are disabled on too long words
                txt = txt.replace('"[', '').replace(']"', '')\
                    .replace('"{', '').replace('}"', '')\
                    .replace('"(', '').replace(')"', '')
                splitted = txt.split()
589
            for word in splitted:
590
                if word in list(special_words.keys()):
591
                    self.addstr(word, curses.color_pair(special_words[word]))
592
                elif word.startswith('(') and word.endswith(')'):
593 594 595
                    self.addstr('(', curses.color_pair(color))
                    self.addstr(word[1:-1], curses.color_pair(theme.COLOR_CURLYBRACKETED_WORD))
                    self.addstr(')', curses.color_pair(color))
596
                elif word.startswith('{') and word.endswith('}'):
597
                    self.addstr(word[1:-1], curses.color_pair(theme.COLOR_ACCOLADE_WORD))
598
                elif word.startswith('[') and word.endswith(']'):
599
                    self.addstr(word[1:-1], curses.color_pair(theme.COLOR_BRACKETED_WORD))
600
                else:
601
                    self.addstr(word, curses.color_pair(color))
602
                self.addstr(' ')
603

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

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

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

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

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

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

    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

662 663
class Input(Win):
    """
664 665 666 667 668 669 670 671 672
    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.
673
    """
674 675
    clipboard = '' # A common clipboard for all the inputs, this makes
    # it easy cut and paste text between various input
676
    def __init__(self):
677 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
702

703 704 705
    def is_empty(self):
        return len(self.text) == 0

706 707
    def resize(self, height, width, y, x, stdscr):
        self._resize(height, width, y, x, stdscr)
708
        self._win.erase()
709
        self.addnstr(0, 0, self.text, self.width-1)
710

711 712 713 714 715 716 717 718 719 720
    def jump_word_left(self):
        """
        Move the cursor one word to the left
        """
        if not len(self.text) or self.pos == 0:
            return
        previous_space = self.text[:self.pos+self.line_pos].rfind(' ')
        if previous_space == -1:
            previous_space = 0
        diff = self.pos+self.line_pos-previous_space
721
        for i in range(diff):
722
            self.key_left()
723
        return True
724 725 726 727 728 729 730 731 732 733 734

    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
        next_space = self.text.find(' ', self.pos+self.line_pos+1)
        if next_space == -1:
            next_space = len(self.text)
        diff = next_space - (self.pos+self.line_pos)
735
        for i in range(diff):
736
            self.key_right()
737
        return True
738 739 740 741 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
        previous_space = self.text[:self.pos+self.line_pos].rfind(' ')
        if previous_space == -1:
            previous_space = 0
        diff = self.pos+self.line_pos-previous_space
749
        for i in range(diff):
750 751
            self.key_backspace(False)
        self.rewrite_text()
752
        return True
753 754 755 756 757 758 759

    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
760
        Input.clipboard = self.text[self.pos+self.line_pos:]
761 762
        self.text = self.text[:self.pos+self.line_pos]
        self.key_end()
763
        return True
764 765 766 767 768 769 770

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

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

786
    def key_dc(self):
787 788 789
        """
        delete char just after the cursor
        """
790
        self.reset_completion()
791 792 793 794
        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()
795
        return True
796 797

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

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

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

    def key_right(self):
836 837 838
        """
        Move the cursor one char to the right
        """
839
        self.reset_completion()
840
        (y, x) = self._win.getyx()
841 842 843 844
        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):
845
            self.pos += 1
846
        self.rewrite_text()
847
        return True
848

849
    def key_backspace(self, reset=True):
850 851 852
        """
        Delete the char just before the cursor
        """
853
        self.reset_completion()
854
        (y, x) = self._win.getyx()
855 856 857 858
        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()
859 860
        if reset:
            self.rewrite_text()
861
        return True
862

863
    def auto_completion(self, word_list, add_after):
864
        """
865 866 867 868
        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)
869
        """
870
        if self.pos+self.line_pos != len(self.text): # or len(self.text) == 0
871
            return # we don't complete if cursor is not at the end of line
872
        completion_type = config.get('completion', 'normal')