aboutsummaryrefslogtreecommitdiffstats
path: root/libmproxy/console/kveditor.py
blob: 2997cf7f8de57156f261b14b3bfb43a1b6d924aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
import copy
import urwid
import common
from .. import utils


def _mkhelp():
    text = []
    keys = [
        ("A", "insert row before cursor"),
        ("a", "add row after cursor"),
        ("d", "delete row"),
        ("e", "spawn external editor on current field"),
        ("q", "return to flow view"),
        ("esc", "return to flow view/exit field edit mode"),
        ("tab", "next field"),
        ("enter", "edit field"),
    ]
    text.extend(common.format_keyvals(keys, key="key", val="text", indent=4))
    return text
help_context = _mkhelp()


class SText(common.WWrap):
    def __init__(self, txt, focused):
        w = urwid.Text(txt, wrap="any")
        if focused:
            w = urwid.AttrWrap(w, "focusfield")
        common.WWrap.__init__(self, w)

    def get_text(self):
        return self.w.get_text()[0]

    def keypress(self, size, key):
        return key

    def selectable(self):
        return True


class SEdit(common.WWrap):
    def __init__(self, txt):
        w = urwid.Edit(edit_text=txt, wrap="any", multiline=True)
        w = urwid.AttrWrap(w, "editfield")
        common.WWrap.__init__(self, w)

    def get_text(self):
        return self.w.get_text()[0]

    def selectable(self):
        return True


class KVItem(common.WWrap):
    def __init__(self, focused, editing, maxk, k, v):
        self.focused, self.editing, self.maxk = focused, editing, maxk
        if focused == 0 and editing:
            self.editing = self.kf = SEdit(k)
        else:
            self.kf = SText(k, True if focused == 0 else False)

        if focused == 1 and editing:
            self.editing = self.vf = SEdit(v)
        else:
            self.vf = SText(v, True if focused == 1 else False)

        w = urwid.Columns(
            [
                ("fixed", maxk + 2, self.kf),
                self.vf
            ],
            dividechars = 2
        )
        if focused is not None:
            w.set_focus_column(focused)
        common.WWrap.__init__(self, w)

    def get_kv(self):
        return (self.kf.get_text(), self.vf.get_text())

    def keypress(self, s, k):
        if self.editing:
            k = self.editing.keypress((s[0]-self.maxk-4,), k)
        return k

    def selectable(self):
        return True


KEY_MAX = 30
class KVWalker(urwid.ListWalker):
    def __init__(self, lst, editor):
        self.lst, self.editor = lst, editor
        self.maxk = min(max(len(v[0]) for v in lst), KEY_MAX) if lst else 20
        if self.maxk < 20:
            self.maxk = 20
        self.focus = 0
        self.focus_col = 0
        self.editing = False

    def _modified(self):
        self.editor.show_empty_msg()
        return urwid.ListWalker._modified(self)

    def get_current_value(self):
        if self.lst:
            return self.lst[self.focus][self.focus_col]

    def set_current_value(self, val):
        row = list(self.lst[self.focus])
        row[self.focus_col] = val
        self.lst[self.focus] = tuple(row)

    def delete_focus(self):
        if self.lst:
            del self.lst[self.focus]
            self.focus = min(len(self.lst)-1, self.focus)
            self._modified()

    def _insert(self, pos):
        self.focus = pos
        self.lst.insert(self.focus, ("", ""))
        self.focus_col = 0
        self.start_edit()

    def insert(self):
        return self._insert(self.focus)

    def add(self):
        return self._insert(min(self.focus + 1, len(self.lst)))

    def start_edit(self):
        if self.lst:
            self.editing = KVItem(self.focus_col, True, self.maxk, *self.lst[self.focus])
            self._modified()

    def stop_edit(self):
        if self.editing:
            self.lst[self.focus] = self.editing.get_kv()
            self.editing = False
            self._modified()

    def left(self):
        self.focus_col = 0
        self._modified()

    def right(self):
        self.focus_col = 1
        self._modified()

    def tab_next(self):
        self.stop_edit()
        if self.focus_col == 0:
            self.focus_col = 1
        elif self.focus != len(self.lst)-1:
            self.focus_col = 0
            self.focus += 1
        self._modified()

    def get_focus(self):
        if self.editing:
            return self.editing, self.focus
        elif self.lst:
            return KVItem(self.focus_col, False, self.maxk, *self.lst[self.focus]), self.focus
        else:
            return None, None

    def set_focus(self, focus):
        self.stop_edit()
        self.focus = focus

    def get_next(self, pos):
        if pos+1 >= len(self.lst):
            return None, None
        return KVItem(None, False, self.maxk, *self.lst[pos+1]), pos+1

    def get_prev(self, pos):
        if pos-1 < 0:
            return None, None
        return KVItem(None, False, self.maxk, *self.lst[pos-1]), pos-1


class KVListBox(urwid.ListBox):
    def __init__(self, lw):
        urwid.ListBox.__init__(self, lw)


class KVEditor(common.WWrap):
    def __init__(self, master, title, value, callback, *cb_args, **cb_kwargs):
        value = copy.deepcopy(value)
        self.master, self.title, self.value, self.callback = master, title, value, callback
        self.cb_args, self.cb_kwargs = cb_args, cb_kwargs
        p = urwid.Text(title)
        p = urwid.Padding(p, align="left", width=("relative", 100))
        p = urwid.AttrWrap(p, "heading")
        self.walker = KVWalker(self.value, self)
        self.lb = KVListBox(self.walker)
        self.w = urwid.Frame(self.lb, header = p)
        self.master.statusbar.update("")
        self.show_empty_msg()

    def show_empty_msg(self):
        if self.walker.lst:
            self.w.set_footer(None)
        else:
            self.w.set_footer(
                urwid.Text(
                    [
                        ("highlight", "No values. Press "),
                        ("key", "a"),
                        ("highlight", " to add some."),
                    ]
                )
            )

    def keypress(self, size, key):
        if self.walker.editing:
            if key in ["esc", "enter"]:
                self.walker.stop_edit()
            elif key == "tab":
                pf, pfc = self.walker.focus, self.walker.focus_col
                self.walker.tab_next()
                if self.walker.focus == pf and self.walker.focus_col != pfc:
                    self.walker.start_edit()
            else:
                self.w.keypress(size, key)
            return None

        key = common.shortcuts(key)
        if key in ["q", "esc"]:
            self.callback(self.walker.lst, *self.cb_args, **self.cb_kwargs)
            self.master.pop_view()
        elif key in ["h", "left"]:
            self.walker.left()
        elif key in ["l", "right"]:
            self.walker.right()
        elif key == "tab":
            self.walker.tab_next()
        elif key == "a":
            self.walker.add()
        elif key == "A":
            self.walker.insert()
        elif key == "d":
            self.walker.delete_focus()
        elif key == "e":
            o = self.walker.get_current_value()
            if o is not None:
                n = self.master.spawn_editor(o)
                n = utils.clean_hanging_newline(n)
                self.walker.set_current_value(n)
                self.walker._modified()
        elif key in ["enter"]:
            self.walker.start_edit()
        else:
            return self.w.keypress(size, key)