aboutsummaryrefslogtreecommitdiff
path: root/inter.py
blob: a2f3456fafccdc1c76882df95f476ab730dce297 (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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
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
359
360
361
362
363
364
365
366
367
368
369
import sys, os, atexit
from pacmd import PacmdError
import pa
try:
    sys.path.append(os.path.dirname(os.path.realpath(__file__)))
    import termio as T
except Exception as e:
    print("Place termio.py and libtermio.so from the github.com/tomsmeding/termio project in this directory")
    print(e)
    sys.exit(1)

__all__ = ["start", "end", "mainloop", "update"]

class Section:
    def __init__(self, title, keys, updater):
        self.items = None
        self.title = title
        self.keys = keys
        self.link_section = None  # sinks for sink-inputs, sources for source-outputs
        self._updater = updater
        self.update()

    def update(self):
        self.items = (self._updater)()

class Selection:
    def __init__(self, section, item):
        self.section = section
        self.item = item

sections = [
    Section("Sink Inputs",    "qvm", lambda: pa.list_sink_inputs()),
    Section("Sinks",          "qvd", lambda: pa.list_sinks()),
    Section("Source Outputs", "qvm", lambda: pa.list_source_outputs()),
    Section("Sources",        "qvd", lambda: pa.list_sources()),
]
sections[0].link_section = sections[1]
sections[2].link_section = sections[3]

sel = Selection(0, 0)
prompt_y = 0  # updated by redraw()

MENU_MAIN, MENU_VOLUME, NUM_MENUS = range(3)
menu = MENU_MAIN

menutext = [0] * NUM_MENUS
menuopts = [0] * NUM_MENUS

menutext[MENU_MAIN] = ""
menuopts[MENU_MAIN] = {
    "q": "(q)uit",
    "v": "(v)olume",
    "d": "(d)efault",
    "m": "(m)ove",
}

menutext[MENU_VOLUME] = "Change volume: <- / -> (alt: 1%)  (m)ute  [q/esc: return]"
menuopts[MENU_VOLUME] = {}


def start():
    T.initscreen()
    atexit.register(T.endscreen)
    T.initkeyboard(False)
    atexit.register(T.endkeyboard)

    redraw()

def end():
    T.endkeyboard()
    atexit.unregister(T.endkeyboard)
    T.endscreen()
    atexit.unregister(T.endscreen)

def mainloop():
    global sel, menu
    while True:
        update()

        sel.item = max(0, min(len(sections[sel.section].items) - 1, sel.item))
        if len(sections[sel.section].items) == 0:
            for i, s in enumerate(sections):
                if len(s.items) != 0:
                    sel.section = i
                    sel.item = 0
                    break
            else:
                sel = Selection(0, 0)

            # We changed the selection, let's return to the main menu
            menu = MENU_MAIN

        redraw()

        key = T.tgetkey()

        if menu != MENU_MAIN and (key == T.KEY_ESC or key == ord("q")):
            menu = MENU_MAIN

        elif menu == MENU_MAIN:
            if key == T.KEY_DOWN:
                sel = selection_down(sel)

            elif key == T.KEY_UP:
                sel = selection_up(sel)

            elif key == ord('q'):
                break

            elif "v" in sections[sel.section].keys and key == ord("v"):
                thing = get_selected()
                kind = thing.kind()
                vol = thing.volume()
                if len(vol) >= 2 and vol[0] != vol[1]:
                    show_message(
                        "Warning: current volume of this " + kind + " is asymmetric!")

                menu = MENU_VOLUME

            elif "d" in sections[sel.section].keys and key == ord("d"):
                wrap_pacmd(lambda: get_selected().set_default())

            elif "m" in sections[sel.section].keys and key == ord("m"):
                thing = get_selected()
                idx = show_prompt(
                        "Enter {} number to link {} {} to"
                            .format(thing.linked_kind(), thing.kind(), thing.index()))

                if idx is None:
                    continue

                try:
                    idx = int(idx)
                except:
                    show_message("Invalid number!")
                    continue

                link_section = sections[sel.section].link_section

                for i in range(len(link_section.items)):
                    if link_section.items[i].index() == idx:
                        wrap_pacmd(lambda: thing.move_to(idx))
                        break
                else:
                    show_message("No {} found with that index!"
                                    .format(thing.linked_kind()))

        elif menu == MENU_VOLUME:
            thing = get_selected()

            incr = 0
            if key == T.KEY_RIGHT:
                incr = 0.05
            elif key == T.KEY_LEFT:
                incr = -0.05
            elif key == T.KEY_ALT + T.KEY_RIGHT:
                incr = 0.01
            elif key == T.KEY_ALT + T.KEY_LEFT:
                incr = -0.01
            elif key == ord("m"):
                thing.set_muted(not thing.muted())
                continue
            else:
                T.bel()
                continue

            vol = thing.volume()
            vol = sum(vol) / len(vol)
            vol = min(1, max(0, vol + incr))
            wrap_pacmd(lambda: thing.set_volume(vol))

        else:
            assert False

def selection_down(sel):
    if sel.item >= len(sections[sel.section].items) - 1:
        if sel.section >= len(sections) - 1:
            T.bel()
            return sel
        else:
            i = sel.section + 1
            while i < len(sections) and len(sections[i].items) == 0:
                i += 1
            if i < len(sections):
                return Selection(i, 0)
            else:
                T.bel()
                return sel
    else:
        return Selection(sel.section, sel.item + 1)

def selection_up(sel):
    if sel.item <= 0:
        if sel.section <= 0:
            T.bel()
            return sel
        else:
            i = sel.section - 1
            while i >= 0 and len(sections[i].items) == 0:
                i -= 1
            if i >= 0:
                return Selection(i, len(sections[i].items) - 1)
            else:
                T.bel()
                return sel
    else:
        return Selection(sel.section, sel.item - 1)

def get_selected():
    return sections[sel.section].items[sel.item]

def wrap_pacmd(lam):
    try:
        lam()
    except pacmd.PacmdError as e:
        show_message("An error occurred:\n" + str(e))

def show_message(msg):
    sz = T.gettermsize()
    T.fillrect(0, prompt_y, sz.w, sz.h - prompt_y, ' ')
    T.moveto(0, prompt_y)
    T.tprint("! " + msg + "\n[press return]")
    T.redraw()

    while True:
        key = T.tgetkey()
        if key == T.KEY_CR or key == T.KEY_LF:
            break

    T.fillrect(0, prompt_y, sz.w, sz.h - prompt_y, ' ')

def show_prompt(msg):
    sz = T.gettermsize()
    T.fillrect(0, prompt_y, sz.w, sz.h - prompt_y, ' ')
    T.moveto(0, prompt_y)
    T.tprint(msg + "\n> ")
    T.redraw()

    line = T.tgetline()

    T.fillrect(0, prompt_y, sz.w, sz.h - prompt_y, ' ')
    return line

# Returns y after end of section on screen
def draw_section(y, items, title, section_selected):
    T.moveto(0, y)
    T.setbold(True)
    T.tprint(title)
    T.setbold(False)
    y += 1

    for i, item in enumerate(items):
        T.moveto(1, y)
        print_item(item, section_selected and sel.item == i)
        y += 1

    return y

def redraw():
    global prompt_y
    if sections[0].items is None:
        update()

    sz = T.gettermsize()
    T.fillrect(0, 0, sz.w, sz.h, ' ')

    T.setstyle(T.Style(9, 9, False, False))

    y = 0
    for i, section in enumerate(sections):
        y = draw_section(y, section.items, section.title, sel.section == i)
        y += 1

    y += 1

    prompt_y = y

    T.moveto(0, y)
    T.tprint(menutext[menu])
    first = True
    for key in sections[sel.section].keys:
        if key not in menuopts[menu]:
            continue
        if first: first = False
        else: T.tprint(" ")
        T.tprint(menuopts[menu][key])

    y += 1

    T.moveto(0, y)
    T.tprint("> ")

    T.redraw()

def print_prefix(thing, selected):
    if selected:
        T.setbold(True)
        T.tprint("> ")
        T.setbold(False)
    else:
        T.tprint("  ")

def fmt_volume(vol):
    res = [str(round(100 * value)) + "%" for value in vol]
    if len(vol) > 2:
        return res[0] + "/" + res[1] + " (? len(vol)==" + str(len(vol)) + ")"
    elif len(vol) == 2:
        if vol[0] == vol[1]:
            return res[0]
        else:
            return res[0] + "/" + res[1]
    elif len(vol) == 1:
        return res[0] + " (mono)"
    else:
        return "? (len(vol)==0)"

def print_volume(thing):
    T.setfg(6)
    T.tprint("(vol: {}{})".format(
        fmt_volume(thing.volume()),
        " (MUTED)" if thing.muted() else ""))
    T.setfg(9)

def print_item(item, selected):
    print_prefix(item, selected)

    T.setfg(3)
    T.tprint("[{}]".format(item.index()))
    T.setfg(9)

    T.tprint(" ")
    T.tprint(item.name())

    if isinstance(item, pa.SinkSource):
        T.tprint("  ")
        print_state(item)

    T.tprint("  ")
    print_volume(item)

    if isinstance(item, pa.SinkSource):
        if item.default():
            T.tprint("  ")
            T.setbold(True)
            T.tprint("[default]")
            T.setbold(False)
    else:
        T.setfg(3)
        T.tprint("  -> " if isinstance(item, pa.SinkInput) else "  <- ")
        T.tprint("[{}]".format(item.linked_index()))
        T.setfg(9)

def print_state(thing):
    T.setfg(6)
    T.tprint("({})".format(thing.state()))
    T.setfg(9)

def update():
    for section in sections:
        section.update()


orig_excepthook = sys.excepthook
def excepthook(exctype, value, traceback):
    T.endkeyboard()
    T.endscreen()
    orig_excepthook(exctype, value, traceback)

sys.excepthook = excepthook