data_forms.py 18.8 KB
Newer Older
louiz’'s avatar
louiz’ committed
1
# Copyright 2010-2011 Florent Le Coz <louiz@louiz.org>
louiz’'s avatar
louiz’ committed
2 3 4 5
#
# This file is part of Poezio.
#
# Poezio is free software: you can redistribute it and/or modify
6
# it under the terms of the zlib license. See the COPYING file.
louiz’'s avatar
louiz’ committed
7 8 9 10 11 12 13 14 15 16 17 18

"""
Defines the data-forms Tab and all the Windows for it.
"""

import logging
log = logging.getLogger(__name__)
import curses

from windows import g_lock
import windows
from tabs import Tab
19
from theming import to_curses_attr, get_theme
louiz’'s avatar
louiz’ committed
20 21 22 23 24 25

class DataFormsTab(Tab):
    """
    A tab contaning various window type, displaying
    a form that the user needs to fill.
    """
mathieui's avatar
mathieui committed
26
    plugin_commands = {}
louiz’'s avatar
louiz’ committed
27 28
    def __init__(self, form, on_cancel, on_send, kwargs):
        Tab.__init__(self)
louiz’'s avatar
louiz’ committed
29 30 31 32
        self._form = form
        self._on_cancel = on_cancel
        self._on_send = on_send
        self._kwargs = kwargs
louiz’'s avatar
louiz’ committed
33
        self.fields = []
louiz’'s avatar
louiz’ committed
34 35 36
        for field in self._form:
            self.fields.append(field)
        self.topic_win = windows.Topic()
louiz’'s avatar
louiz’ committed
37
        self.form_win = FormWin(form, self.height-4, self.width, 1, 0)
louiz’'s avatar
louiz’ committed
38
        self.help_win = windows.HelpText("Ctrl+Y: send form, Ctrl+G: cancel")
louiz’'s avatar
louiz’ committed
39
        self.help_win_dyn = windows.HelpText()
louiz’'s avatar
louiz’ committed
40 41 42 43 44
        self.key_func['KEY_UP'] = self.form_win.go_to_previous_input
        self.key_func['KEY_DOWN'] = self.form_win.go_to_next_input
        self.key_func['^G'] = self.on_cancel
        self.key_func['^Y'] = self.on_send
        self.resize()
mathieui's avatar
mathieui committed
45
        self.update_commands()
louiz’'s avatar
louiz’ committed
46 47 48

    def on_cancel(self):
        self._on_cancel(self._form)
49
        return True
louiz’'s avatar
louiz’ committed
50 51 52 53 54

    def on_send(self):
        self._form.reply()
        self.form_win.reply()
        self._on_send(self._form)
55
        return True
louiz’'s avatar
louiz’ committed
56

louiz’'s avatar
louiz’ committed
57
    def on_input(self, key, raw=False):
louiz’'s avatar
louiz’ committed
58
        if key in self.key_func:
louiz’'s avatar
louiz’ committed
59
            res = self.key_func[key]()
60 61
            if res:
                return res
louiz’'s avatar
louiz’ committed
62
            self.help_win_dyn.refresh(self.form_win.get_help_message())
63
            self.form_win.refresh_current_input()
louiz’'s avatar
louiz’ committed
64 65
        else:
            self.form_win.on_input(key)
louiz’'s avatar
louiz’ committed
66 67

    def resize(self):
68
        self.need_resize = False
louiz’'s avatar
louiz’ committed
69 70
        self.topic_win.resize(1, self.width, 0, 0)
        self.tab_win.resize(1, self.width, self.height-2, 0)
louiz’'s avatar
louiz’ committed
71
        self.form_win.resize(self.height-4, self.width, 1, 0)
louiz’'s avatar
louiz’ committed
72 73
        self.help_win.resize(1, self.width, self.height-1, 0)
        self.help_win_dyn.resize(1, self.width, self.height-3, 0)
louiz’'s avatar
louiz’ committed
74 75
        self.lines = []

76
    def refresh(self):
louiz’'s avatar
louiz’ committed
77
        self.topic_win.refresh(self._form['title'])
78
        self.refresh_tab_win()
louiz’'s avatar
louiz’ committed
79
        self.help_win.refresh()
louiz’'s avatar
louiz’ committed
80
        self.help_win_dyn.refresh(self.form_win.get_help_message())
louiz’'s avatar
louiz’ committed
81 82 83 84 85 86 87 88 89 90
        self.form_win.refresh()

class FieldInput(object):
    """
    All input type in a data form should inherite this class,
    in addition with windows.Input or any relevant class from the
    'windows' library.
    """
    def __init__(self, field):
        self._field = field
91
        self.color = get_theme().COLOR_NORMAL_TEXT
louiz’'s avatar
louiz’ committed
92 93 94 95 96 97 98 99 100

    def set_color(self, color):
        self.color = color
        self.refresh()

    def update_field_value(self, value):
        raise NotImplementedError

    def resize(self, height, width, y, x):
louiz’'s avatar
louiz’ committed
101
        self._resize(height, width, y, x)
louiz’'s avatar
louiz’ committed
102 103 104 105 106 107 108 109 110 111

    def is_dummy(self):
        return False

    def reply(self):
        """
        Set the correct response value in the field
        """
        raise NotImplementedError

louiz’'s avatar
louiz’ committed
112 113 114 115 116 117 118
    def get_help_message(self):
        """
        Should return a string explaining the keys of the input.
        Will be displayed at each refresh on a line at the bottom of the tab.
        """
        return ''

119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
class ColoredLabel(windows.Win):
    def __init__(self, text):
        self.text = text
        self.color = get_theme().COLOR_NORMAL_TEXT
        windows.Win.__init__(self)

    def resize(self, height, width, y, x):
        self._resize(height, width, y, x)

    def set_color(self, color):
        self.color = color
        self.refresh()

    def refresh(self):
        with g_lock:
134
            self._win.erase()
135 136 137 138 139 140
            self._win.attron(to_curses_attr(self.color))
            self.addstr(0, 0, self.text)
            self._win.attroff(to_curses_attr(self.color))
            self._refresh()


louiz’'s avatar
louiz’ committed
141
class DummyInput(FieldInput, windows.Win):
louiz’'s avatar
louiz’ committed
142 143 144
    """
    Used for fields that do not require any input ('fixed')
    """
louiz’'s avatar
louiz’ committed
145 146 147 148 149 150 151 152 153 154 155 156 157
    def __init__(self, field):
        FieldInput.__init__(self, field)
        windows.Win.__init__(self)

    def do_command(self):
        return

    def refresh(self):
        return

    def is_dummy(self):
        return True

158 159 160
class ColoredLabel(windows.Win):
    def __init__(self, text):
        self.text = text
161
        self.color = get_theme().COLOR_NORMAL_TEXT
162 163 164 165 166 167 168 169 170 171 172
        windows.Win.__init__(self)

    def resize(self, height, width, y, x):
        self._resize(height, width, y, x)

    def set_color(self, color):
        self.color = color
        self.refresh()

    def refresh(self):
        with g_lock:
173
            self._win.erase()
mathieui's avatar
mathieui committed
174
            self._win.attron(to_curses_attr(self.color))
175
            self.addstr(0, 0, self.text)
mathieui's avatar
mathieui committed
176
            self._win.attroff(to_curses_attr(self.color))
177 178
            self._refresh()

louiz’'s avatar
louiz’ committed
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
class BooleanWin(FieldInput, windows.Win):
    def __init__(self, field):
        FieldInput.__init__(self, field)
        windows.Win.__init__(self)
        self.last_key = 'KEY_RIGHT'
        self.value = bool(field.getValue())

    def do_command(self, key):
        if key == 'KEY_LEFT' or key == 'KEY_RIGHT':
            self.value = not self.value
            self.last_key = key
        self.refresh()

    def refresh(self):
        with g_lock:
194
            self._win.erase()
195
            self._win.attron(to_curses_attr(self.color))
louiz’'s avatar
louiz’ committed
196 197 198 199 200 201 202 203
            self.addnstr(0, 0, ' '*(8), self.width)
            self.addstr(0, 2, "%s"%self.value)
            self.addstr(0, 8, '→')
            self.addstr(0, 0, '←')
            if self.last_key == 'KEY_RIGHT':
                self.addstr(0, 8, '')
            else:
                self.addstr(0, 0, '')
204
            self._win.attroff(to_curses_attr(self.color))
louiz’'s avatar
louiz’ committed
205 206 207 208 209 210
            self._refresh()

    def reply(self):
        self._field['label'] = ''
        self._field.setAnswer(self.value)

louiz’'s avatar
louiz’ committed
211 212 213
    def get_help_message(self):
        return '← and →: change the value between True and False'

214 215 216 217 218 219 220 221
class TextMultiWin(FieldInput, windows.Win):
    def __init__(self, field):
        FieldInput.__init__(self, field)
        windows.Win.__init__(self)
        self.options = field.getValue()
        self.val_pos = 0
        self.edition_input = None
        if not isinstance(self.options, list):
222 223 224 225
            if isinstance(self.options, str):
                self.options = [self.options]
            else:
                self.options = []
226 227 228 229 230 231 232 233 234 235
        self.options.append('')

    def do_command(self, key):
        if not self.edition_input:
            if key == 'KEY_LEFT':
                if self.val_pos > 0:
                    self.val_pos -= 1
            elif key == 'KEY_RIGHT':
                if self.val_pos < len(self.options)-1:
                    self.val_pos += 1
236
            elif key == '^M':
237 238 239 240 241 242
                self.edition_input = windows.Input()
                self.edition_input.color = self.color
                self.edition_input.resize(self.height, self.width, self.y, self.x)
                self.edition_input.text = self.options[self.val_pos]
                self.edition_input.key_end()
        else:
243
            if key == '^M':
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
                self.options[self.val_pos] = self.edition_input.get_text()
                if not self.options[self.val_pos] and self.val_pos != len(self.options) -1:
                    del self.options[self.val_pos]
                    if self.val_pos == len(self.options) -1:
                        self.val_pos -= 1
                self.edition_input = None
                if not self.options or self.options[-1] != '':
                    self.options.append('')
            else:
                self.edition_input.do_command(key)
        self.refresh()

    def refresh(self):
        if not self.edition_input:
            with g_lock:
259
                self._win.erase()
260
                self._win.attron(to_curses_attr(self.color))
261 262 263 264 265 266 267
                self.addnstr(0, 0, ' '*self.width, self.width)
                option = self.options[self.val_pos]
                self.addstr(0, self.width//2-len(option)//2, option)
                if self.val_pos > 0:
                    self.addstr(0, 0, '←')
                if self.val_pos < len(self.options)-1:
                    self.addstr(0, self.width-1, '→')
268
                self._win.attroff(to_curses_attr(self.color))
269 270 271 272 273 274 275 276
                self._refresh()
        else:
            self.edition_input.refresh()

    def reply(self):
        values = [val for val in self.options if val]
        self._field.setAnswer(values)

louiz’'s avatar
louiz’ committed
277 278 279 280 281 282 283 284 285 286 287
    def get_help_message(self):
        if not self.edition_input:
            help_msg = '← and →: browse the available entries. '
            if self.val_pos == len(self.options)-1:
                help_msg += 'Enter: add an entry'
            else:
                help_msg += 'Enter: edit this entry'
        else:
            help_msg = 'Enter: finish editing this entry.'
        return help_msg

louiz’'s avatar
louiz’ committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
class ListMultiWin(FieldInput, windows.Win):
    def __init__(self, field):
        FieldInput.__init__(self, field)
        windows.Win.__init__(self)
        values = field.getValue()
        self.options = [[option, True if option['value'] in values else False]\
                            for option in field.getOptions()]
        self.val_pos = 0

    def do_command(self, key):
        if key == 'KEY_LEFT':
            if self.val_pos > 0:
                self.val_pos -= 1
        elif key == 'KEY_RIGHT':
            if self.val_pos < len(self.options)-1:
                self.val_pos += 1
        elif key == ' ':
            self.options[self.val_pos][1] = not self.options[self.val_pos][1]
        else:
            return
        self.refresh()

    def refresh(self):
        with g_lock:
312
            self._win.erase()
313
            self._win.attron(to_curses_attr(self.color))
louiz’'s avatar
louiz’ committed
314 315 316 317 318 319 320 321
            self.addnstr(0, 0, ' '*self.width, self.width)
            if self.val_pos > 0:
                self.addstr(0, 0, '←')
            if self.val_pos < len(self.options)-1:
                self.addstr(0, self.width-1, '→')
            option = self.options[self.val_pos]
            self.addstr(0, self.width//2-len(option)//2, option[0]['label'])
            self.addstr(0, 2, '✔' if option[1] else '☐')
322
            self._win.attroff(to_curses_attr(self.color))
louiz’'s avatar
louiz’ committed
323 324 325 326 327 328 329 330
            self._refresh()

    def reply(self):
        self._field['label'] = ''
        self._field.delOptions()
        values = [option[0]['value'] for option in self.options if option[1] is True]
        self._field.setAnswer(values)

louiz’'s avatar
louiz’ committed
331 332 333
    def get_help_message(self):
        return '←, →: Switch between the value. Space: select or unselect a value'

louiz’'s avatar
louiz’ committed
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
class ListSingleWin(FieldInput, windows.Win):
    def __init__(self, field):
        FieldInput.__init__(self, field)
        windows.Win.__init__(self)
        # the option list never changes
        self.options = field.getOptions()
        # val_pos is the position of the currently selected option
        self.val_pos = 0
        for i, option in enumerate(self.options):
            if field.getValue() == option['value']:
                self.val_pos = i

    def do_command(self, key):
        if key == 'KEY_LEFT':
            if self.val_pos > 0:
                self.val_pos -= 1
        elif key == 'KEY_RIGHT':
            if self.val_pos < len(self.options)-1:
                self.val_pos += 1
        else:
            return
        self.refresh()

    def refresh(self):
        with g_lock:
359
            self._win.erase()
360
            self._win.attron(to_curses_attr(self.color))
louiz’'s avatar
louiz’ committed
361 362 363 364 365 366 367
            self.addnstr(0, 0, ' '*self.width, self.width)
            if self.val_pos > 0:
                self.addstr(0, 0, '←')
            if self.val_pos < len(self.options)-1:
                self.addstr(0, self.width-1, '→')
            option = self.options[self.val_pos]['label']
            self.addstr(0, self.width//2-len(option)//2, option)
368
            self._win.attroff(to_curses_attr(self.color))
louiz’'s avatar
louiz’ committed
369 370 371 372 373 374 375
            self._refresh()

    def reply(self):
        self._field['label'] = ''
        self._field.delOptions()
        self._field.setAnswer(self.options[self.val_pos]['value'])

louiz’'s avatar
louiz’ committed
376 377 378
    def get_help_message(self):
        return '←, →: Select a value amongst the others'

louiz’'s avatar
louiz’ committed
379 380 381 382 383 384 385
class TextSingleWin(FieldInput, windows.Input):
    def __init__(self, field):
        FieldInput.__init__(self, field)
        windows.Input.__init__(self)
        self.text = field.getValue() if isinstance(field.getValue(), str)\
            else ""
        self.pos = len(self.text)
386
        self.color = get_theme().COLOR_NORMAL_TEXT
louiz’'s avatar
louiz’ committed
387 388 389 390 391

    def reply(self):
        self._field['label'] = ''
        self._field.setAnswer(self.get_text())

louiz’'s avatar
louiz’ committed
392 393 394
    def get_help_message(self):
        return 'Edit the text'

louiz’'s avatar
louiz’ committed
395 396 397 398 399 400 401 402
class TextPrivateWin(TextSingleWin):
    def __init__(self, field):
        TextSingleWin.__init__(self, field)

    def rewrite_text(self):
        with g_lock:
            self._win.erase()
            if self.color:
403
                self._win.attron(to_curses_attr(self.color))
louiz’'s avatar
louiz’ committed
404 405 406 407
            self.addstr('*'*len(self.text[self.line_pos:self.line_pos+self.width-1]))
            if self.color:
                (y, x) = self._win.getyx()
                size = self.width-x
408
                self.addnstr(' '*size, size, to_curses_attr(self.color))
louiz’'s avatar
louiz’ committed
409 410
            self.addstr(0, self.pos, '')
            if self.color:
411
                self._win.attroff(to_curses_attr(self.color))
louiz’'s avatar
louiz’ committed
412 413
            self._refresh()

louiz’'s avatar
louiz’ committed
414 415 416
    def get_help_message(self):
        return 'Edit the secret text'

louiz’'s avatar
louiz’ committed
417 418 419 420 421 422 423 424
class FormWin(object):
    """
    A window, with some subwins (the various inputs).
    On init, create all the subwins.
    On resize, move and resize all the subwin and define how the text will be written
    On refresh, write all the text, and refresh all the subwins
    """
    input_classes = {'boolean': BooleanWin,
louiz’'s avatar
louiz’ committed
425
                     'fixed': DummyInput,
426
                     'jid-multi': TextMultiWin,
louiz’'s avatar
louiz’ committed
427
                     'jid-single': TextSingleWin,
louiz’'s avatar
louiz’ committed
428 429
                     'list-multi': ListMultiWin,
                     'list-single': ListSingleWin,
430
                     'text-multi': TextMultiWin,
louiz’'s avatar
louiz’ committed
431
                     'text-private': TextPrivateWin,
louiz’'s avatar
louiz’ committed
432 433
                     'text-single': TextSingleWin,
                     }
louiz’'s avatar
louiz’ committed
434 435
    def __init__(self, form, height, width, y, x):
        self._form = form
436
        self._win = windows.Win._tab_win.derwin(height, width, y, x)
louiz’'s avatar
louiz’ committed
437 438
        self.current_input = 0
        self.inputs = []        # dict list
mathieui's avatar
mathieui committed
439
        for (name, field) in self._form.getFields().items():
louiz’'s avatar
louiz’ committed
440 441 442 443
            if field['type'] == 'hidden':
                continue
            try:
                input_class = self.input_classes[field['type']]
louiz’'s avatar
louiz’ committed
444
            except IndexError:
445
                continue
louiz’'s avatar
louiz’ committed
446
            label = field['label']
447
            desc = field['desc']
louiz’'s avatar
louiz’ committed
448 449 450
            if field['type'] == 'fixed':
                label = field.getValue()
            inp = input_class(field)
451
            self.inputs.append({'label':ColoredLabel(label),
452
                                'description': desc,
louiz’'s avatar
louiz’ committed
453 454 455 456 457 458
                                'input':inp})

    def resize(self, height, width, y, x):
        self._win.resize(height, width)
        self.height = height
        self.width = width
459 460
        if self.current_input >= self.height-2:
            self.current_input = self.height-1
louiz’'s avatar
louiz’ committed
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477

    def reply(self):
        """
        Set the response values in the form, for each field
        from the corresponding input
        """
        for inp in self.inputs:
            if inp['input'].is_dummy():
                continue
            else:
                inp['input'].reply()
        self._form['title'] = ''
        self._form['instructions'] = ''

    def go_to_next_input(self):
        if not self.inputs:
            return
478
        if self.current_input == len(self.inputs) - 1 or self.current_input >= self.height-1:
louiz’'s avatar
louiz’ committed
479
            return
480 481
        self.inputs[self.current_input]['input'].set_color(get_theme().COLOR_NORMAL_TEXT)
        self.inputs[self.current_input]['label'].set_color(get_theme().COLOR_NORMAL_TEXT)
louiz’'s avatar
louiz’ committed
482 483 484 485 486 487 488
        self.current_input += 1
        jump = 0
        while self.current_input+jump != len(self.inputs) - 1 and self.inputs[self.current_input+jump]['input'].is_dummy():
            jump += 1
        if self.inputs[self.current_input+jump]['input'].is_dummy():
            return
        self.current_input += jump
489 490
        self.inputs[self.current_input]['input'].set_color(get_theme().COLOR_SELECTED_ROW)
        self.inputs[self.current_input]['label'].set_color(get_theme().COLOR_SELECTED_ROW)
louiz’'s avatar
louiz’ committed
491 492 493 494 495 496

    def go_to_previous_input(self):
        if not self.inputs:
            return
        if self.current_input == 0:
            return
497 498
        self.inputs[self.current_input]['input'].set_color(get_theme().COLOR_NORMAL_TEXT)
        self.inputs[self.current_input]['label'].set_color(get_theme().COLOR_NORMAL_TEXT)
louiz’'s avatar
louiz’ committed
499 500 501 502 503 504 505
        self.current_input -= 1
        jump = 0
        while self.current_input-jump > 0 and self.inputs[self.current_input+jump]['input'].is_dummy():
            jump += 1
        if self.inputs[self.current_input+jump]['input'].is_dummy():
            return
        self.current_input -= jump
506 507
        self.inputs[self.current_input]['input'].set_color(get_theme().COLOR_SELECTED_ROW)
        self.inputs[self.current_input]['label'].set_color(get_theme().COLOR_SELECTED_ROW)
louiz’'s avatar
louiz’ committed
508 509 510 511 512 513 514 515 516 517 518

    def on_input(self, key):
        if not self.inputs:
            return
        self.inputs[self.current_input]['input'].do_command(key)

    def refresh(self):
        with g_lock:
            self._win.erase()
            y = 0
            i = 0
mathieui's avatar
mathieui committed
519
            for name, field in self._form.getFields().items():
louiz’'s avatar
louiz’ committed
520 521
                if field['type'] == 'hidden':
                    continue
522
                self.inputs[i]['label'].resize(1, self.width//3, y + 1, 0)
louiz’'s avatar
louiz’ committed
523
                self.inputs[i]['input'].resize(1, self.width//3, y+1, 2*self.width//3)
louiz’'s avatar
louiz’ committed
524
                # TODO: display the field description
louiz’'s avatar
louiz’ committed
525 526
                y += 1
                i += 1
527 528
                if y >= self.height:
                    break
louiz’'s avatar
louiz’ committed
529
            self._win.refresh()
530 531 532
        for i, inp in enumerate(self.inputs):
            if i >= self.height:
                break
533
            inp['label'].refresh()
louiz’'s avatar
louiz’ committed
534
            inp['input'].refresh()
535
            inp['label'].refresh()
536
        if self.current_input < self.height-1:
537
            self.inputs[self.current_input]['input'].set_color(get_theme().COLOR_SELECTED_ROW)
538
            self.inputs[self.current_input]['input'].refresh()
539
            self.inputs[self.current_input]['label'].set_color(get_theme().COLOR_SELECTED_ROW)
540
            self.inputs[self.current_input]['label'].refresh()
541 542

    def refresh_current_input(self):
louiz’'s avatar
louiz’ committed
543
        self.inputs[self.current_input]['input'].refresh()
louiz’'s avatar
louiz’ committed
544 545

    def get_help_message(self):
546
        if self.current_input < self.height-1 and self.inputs[self.current_input]['input']:
louiz’'s avatar
louiz’ committed
547 548
            return self.inputs[self.current_input]['input'].get_help_message()
        return ''