nvda-voicemeeter/src/nvda_voicemeeter/window.py

414 lines
20 KiB
Python
Raw Normal View History

import logging
import pickle
from pathlib import Path
2023-08-22 02:04:00 +01:00
import PySimpleGUI as psg
from .builder import Builder
2023-08-26 21:55:39 +01:00
from .models import _make_bus_mode_cache, _make_output_cache
2023-08-22 02:04:00 +01:00
from .nvda import Nvda
from .parser import Parser
2023-08-25 20:23:21 +01:00
from .util import (
2023-08-26 21:55:39 +01:00
_patch_insert_channels,
2023-08-25 20:23:21 +01:00
get_asio_checkbox_index,
get_insert_checkbox_index,
get_patch_composite_list,
open_context_menu_for_buttonmenu,
2023-08-25 20:23:21 +01:00
)
2023-08-22 02:04:00 +01:00
logger = logging.getLogger(__name__)
psg.theme("Dark Blue 3")
2023-08-24 18:02:53 +01:00
2023-08-22 02:04:00 +01:00
2023-08-25 20:23:21 +01:00
class NVDAVMWindow(psg.Window):
"""Represents the main window of the Voicemeeter NVDA application"""
DEFAULT_BIN = "default.bin"
2023-08-22 02:04:00 +01:00
def __init__(self, title, vm):
self.vm = vm
self.kind = self.vm.kind
self.logger = logger.getChild(type(self).__name__)
self.cache = {"outputs": _make_output_cache(self.vm), "busmode": _make_bus_mode_cache(self.vm)}
2023-08-22 02:04:00 +01:00
self.nvda = Nvda()
self.parser = Parser()
2023-08-26 00:11:05 +01:00
self.builder = Builder(self)
layout = self.builder.run()
super().__init__(title, layout, return_keyboard_events=True, finalize=True)
buttonmenu_opts = {"takefocus": 1, "highlightthickness": 1}
for i in range(self.kind.phys_out):
self[f"HARDWARE OUT||A{i + 1}"].Widget.config(**buttonmenu_opts)
2023-08-26 10:42:18 +01:00
if self.kind.name != "basic":
[self[f"PATCH COMPOSITE||PC{i + 1}"].Widget.config(**buttonmenu_opts) for i in range(self.kind.phys_out)]
2023-08-28 21:21:26 +01:00
self["ASIO BUFFER"].Widget.config(**buttonmenu_opts)
self.register_events()
2023-08-22 02:04:00 +01:00
def __enter__(self):
default_config = Path.cwd() / self.DEFAULT_BIN
if default_config.exists():
try:
with open(default_config, "rb") as f:
if config := pickle.load(f):
self.vm.set("command.load", config)
self.logger.debug(f"config {config} loaded")
self.TKroot.after(
200,
self.nvda.speak,
f"config {Path(config).stem} has been loaded",
)
except EOFError:
self.logger.debug("no data in default bin. silently continuing...")
2023-08-22 02:04:00 +01:00
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def register_events(self):
2023-08-25 20:23:21 +01:00
"""Registers events for widgets"""
2023-08-25 22:53:48 +01:00
# TABS
self["tabs"].bind("<FocusIn>", "||FOCUS IN")
self.bind("<Control-KeyPress-Tab>", "CTRL-TAB")
self.bind("<Control-Shift-KeyPress-Tab>", "CTRL-SHIFT-TAB")
2023-08-25 22:53:48 +01:00
2023-08-25 20:23:21 +01:00
# Hardware Out
for i in range(self.vm.kind.phys_out):
self[f"HARDWARE OUT||A{i + 1}"].bind("<FocusIn>", "||FOCUS IN")
self[f"HARDWARE OUT||A{i + 1}"].bind("<space>", "||KEY SPACE", propagate=False)
self[f"HARDWARE OUT||A{i + 1}"].bind("<Return>", "||KEY ENTER", propagate=False)
2023-08-25 20:23:21 +01:00
# Patch ASIO
if self.kind.name != "basic":
for i in range(self.kind.phys_out):
self[f"ASIO CHECKBOX||IN{i + 1} 0"].bind("<FocusIn>", "||FOCUS IN")
self[f"ASIO CHECKBOX||IN{i + 1} 1"].bind("<FocusIn>", "||FOCUS IN")
2023-08-25 20:23:21 +01:00
# Patch Composite
2023-08-26 10:42:18 +01:00
if self.kind.name != "basic":
for i in range(self.vm.kind.phys_out):
self[f"PATCH COMPOSITE||PC{i + 1}"].bind("<FocusIn>", "||FOCUS IN")
self[f"PATCH COMPOSITE||PC{i + 1}"].bind("<space>", "||KEY SPACE", propagate=False)
self[f"PATCH COMPOSITE||PC{i + 1}"].bind("<Return>", "||KEY ENTER", propagate=False)
2023-08-25 20:23:21 +01:00
# Patch Insert
if self.kind.name != "basic":
for i in range(self.kind.num_strip):
2023-08-26 17:29:24 +01:00
if i < self.kind.phys_in:
self[f"INSERT CHECKBOX||IN{i + 1} 0"].bind("<FocusIn>", "||FOCUS IN")
self[f"INSERT CHECKBOX||IN{i + 1} 1"].bind("<FocusIn>", "||FOCUS IN")
else:
[self[f"INSERT CHECKBOX||IN{i + 1} {j}"].bind("<FocusIn>", "||FOCUS IN") for j in range(8)]
# Strip Outputs
for i in range(self.kind.num_strip):
for j in range(self.kind.phys_out):
self[f"STRIP {i}||A{j + 1}"].bind("<FocusIn>", "||FOCUS IN")
self[f"STRIP {i}||A{j + 1}"].bind("<Return>", "||KEY ENTER")
for j in range(self.kind.virt_out):
self[f"STRIP {i}||B{j + 1}"].bind("<FocusIn>", "||FOCUS IN")
self[f"STRIP {i}||B{j + 1}"].bind("<Return>", "||KEY ENTER")
2023-08-28 21:21:26 +01:00
# Bus Modes
for i in range(self.kind.num_bus):
2023-08-28 21:21:26 +01:00
self[f"BUS {i}||MODE"].bind("<FocusIn>", "||FOCUS IN")
2023-08-26 21:55:39 +01:00
# ASIO Buffer
2023-08-28 21:21:26 +01:00
if self.kind.name != "basic":
self["ASIO BUFFER"].bind("<FocusIn>", "||FOCUS IN")
self["ASIO BUFFER"].bind("<space>", "||KEY SPACE", propagate=False)
self["ASIO BUFFER"].bind("<Return>", "||KEY ENTER", propagate=False)
2023-08-26 21:55:39 +01:00
2023-08-22 02:04:00 +01:00
def run(self):
2023-08-22 05:16:43 +01:00
"""
Parses the event string and matches it to events
Main thread will shutdown once a close or exit event occurs
"""
2023-08-25 20:23:21 +01:00
2023-08-22 02:04:00 +01:00
while True:
event, values = self.read()
self.logger.debug(f"event::{event}")
self.logger.debug(f"values::{values}")
2023-08-22 02:04:00 +01:00
if event in (psg.WIN_CLOSED, "Exit"):
break
2023-08-25 22:33:28 +01:00
elif event == "tabs":
2023-08-25 22:53:48 +01:00
self.nvda.speak(f"tab {values['tabs']}")
2023-08-25 22:33:28 +01:00
match parsed_cmd := self.parser.match.parseString(event):
2023-08-29 02:58:13 +01:00
# Focus tabgroup
case ["CTRL-TAB"] | ["CTRL-SHIFT-TAB"]:
self["tabs"].set_focus()
# Menus
case [["Restart", "Audio", "Engine"], ["MENU"]]:
self.perform_long_operation(self.vm.command.restart, "ENGINE RESTART||END")
case [["ENGINE", "RESTART"], ["END"]]:
self.TKroot.after(
200,
self.nvda.speak,
"Audio Engine restarted",
)
case [["Save", "Settings"], ["MENU"]]:
def popup_get_text(message, title=None):
layout = [
[psg.Text(message)],
[psg.Input(key="Text Input")],
[psg.Button("Ok"), psg.Button("Cancel")],
]
window = psg.Window(title, layout, finalize=True)
window["Text Input"].bind("<FocusIn>", "||FOCUS IN")
window["Ok"].bind("<FocusIn>", "||FOCUS IN")
window["Cancel"].bind("<FocusIn>", "||FOCUS IN")
filename = None
while True:
event, values = window.read()
if event in (psg.WIN_CLOSED, "Cancel"):
break
if event.endswith("||FOCUS IN"):
label = event.split("||")[0]
self.TKroot.after(
200 if label == "Text Input" else 1,
self.nvda.speak,
label,
)
elif event == "Ok":
filename = values["Text Input"]
break
window.close()
return filename
filename = popup_get_text("Filename", title="Save As")
if filename:
configpath = Path.home() / "Documents" / "Voicemeeter" / f"{filename.removesuffix('xml')}.xml"
self.vm.set("command.save", str(configpath))
self.logger.debug(f"saving config file to {configpath}")
self.TKroot.after(
200,
self.nvda.speak,
f"config file {filename} has been saved",
)
case [["Load", "Settings"], ["MENU"]]:
def popup_get_file(message, title=None):
layout = [
[psg.Text(message)],
[psg.Input(key="Text Input"), psg.FilesBrowse("Browse")],
[psg.Button("Ok"), psg.Button("Cancel")],
]
window = psg.Window(title, layout, finalize=True)
window["Text Input"].bind("<FocusIn>", "||FOCUS IN")
window["Browse"].bind("<FocusIn>", "||FOCUS IN")
window["Ok"].bind("<FocusIn>", "||FOCUS IN")
window["Cancel"].bind("<FocusIn>", "||FOCUS IN")
filename = None
while True:
event, values = window.read()
if event in (psg.WIN_CLOSED, "Cancel"):
break
if event.endswith("||FOCUS IN"):
label = event.split("||")[0]
self.TKroot.after(
200 if label == "Text Input" else 1,
self.nvda.speak,
label,
)
elif event == "Ok":
filename = values["Text Input"]
break
window.close()
return filename
configpath = Path.home() / "Documents" / "Voicemeeter"
filename = popup_get_file("Filename", title="Load Settings")
if filename:
configpath = configpath / filename
self.vm.set("command.load", str(configpath))
self.logger.debug(f"loading config file from {configpath}")
self.TKroot.after(
200,
self.nvda.speak,
f"config file {Path(filename).stem} has been loaded",
)
case [["Load", "Settings", "on", "Startup"], ["MENU"]]:
def popup_get_text(message, title=None):
layout = [
[psg.Text(message)],
[psg.Input(key="Text Input")],
[psg.Button("Ok"), psg.Button("Cancel")],
]
window = psg.Window(title, layout, finalize=True)
window["Text Input"].bind("<FocusIn>", "||FOCUS IN")
window["Ok"].bind("<FocusIn>", "||FOCUS IN")
window["Cancel"].bind("<FocusIn>", "||FOCUS IN")
filename = None
while True:
event, values = window.read()
if event in (psg.WIN_CLOSED, "Cancel"):
break
if event.endswith("||FOCUS IN"):
label = event.split("||")[0]
self.TKroot.after(
200 if label == "Text Input" else 1,
self.nvda.speak,
label,
)
elif event == "Ok":
filename = values["Text Input"]
break
window.close()
return filename
filename = popup_get_text("Filename", title="Load on startup")
if filename:
configpath = Path.home() / "Documents" / "Voicemeeter" / f"{filename.removesuffix('xml')}.xml"
with open(self.DEFAULT_BIN, "wb") as f:
pickle.dump(str(configpath), f)
self.TKroot.after(
200,
self.nvda.speak,
f"config {filename} set as default on startup",
)
else:
with open(self.DEFAULT_BIN, "wb") as f:
f.truncate()
self.logger.debug("default bin was truncated")
2023-08-25 22:53:48 +01:00
# Tabs
case [["tabs"], ["FOCUS", "IN"]]:
self.nvda.speak(f"tab {values['tabs']}")
2023-08-25 20:23:21 +01:00
# Hardware out
case [["HARDWARE", "OUT"], [key]]:
selection = values[f"HARDWARE OUT||{key}"]
index = int(key[1]) - 1
2023-08-22 05:37:06 +01:00
match selection.split(":"):
case [device_name]:
setattr(self.vm.bus[index].device, "wdm", "")
self.TKroot.after(200, self.nvda.speak, f"HARDWARE OUT {key} device selection removed")
2023-08-22 05:37:06 +01:00
case [driver, device_name]:
setattr(self.vm.bus[index].device, driver, device_name.strip())
phonetic = {"mme": "em em e"}
self.TKroot.after(
200,
self.nvda.speak,
f"HARDWARE OUT {key} set {phonetic.get(driver, driver)} {device_name}",
)
case [["HARDWARE", "OUT"], [key], ["FOCUS", "IN"]]:
self.nvda.speak(f"HARDWARE OUT {key} {self.vm.bus[int(key[-1]) - 1].device.name}")
case [["HARDWARE", "OUT"], [key], ["KEY", "SPACE" | "ENTER"]]:
open_context_menu_for_buttonmenu(self, f"HARDWARE OUT||{key}")
2023-08-25 20:23:21 +01:00
# Patch ASIO
2023-08-22 20:41:44 +01:00
case [["ASIO", "CHECKBOX"], [in_num, channel]]:
2023-08-23 00:27:12 +01:00
index = get_asio_checkbox_index(int(channel), int(in_num[-1]))
2023-08-22 20:41:44 +01:00
val = values[f"ASIO CHECKBOX||{in_num} {channel}"]
2023-08-22 05:16:43 +01:00
self.vm.patch.asio[index].set(val)
2023-08-22 20:41:44 +01:00
channel = ("left", "right")[int(channel)]
self.nvda.speak(f"Patch ASIO {in_num} {channel} set to {val}")
case [["ASIO", "CHECKBOX"], [in_num, channel], ["FOCUS", "IN"]]:
val = values[f"ASIO CHECKBOX||{in_num} {channel}"]
2023-08-22 20:41:44 +01:00
channel = ("left", "right")[int(channel)]
2023-08-22 05:16:43 +01:00
num = int(in_num[-1])
self.nvda.speak(f"Patch ASIO inputs to strips IN#{num} {channel} {val}")
2023-08-25 20:23:21 +01:00
# Patch COMPOSITE
case [["PATCH", "COMPOSITE"], [key]]:
val = values[f"PATCH COMPOSITE||{key}"]
index = int(key[-1]) - 1
self.vm.patch.composite[index].set(get_patch_composite_list(self.kind).index(val) + 1)
self.TKroot.after(200, self.nvda.speak, f"PATCH COMPOSITE {key[-1]} set {val}")
case [["PATCH", "COMPOSITE"], [key], ["FOCUS", "IN"]]:
if values[f"PATCH COMPOSITE||{key}"]:
val = values[f"PATCH COMPOSITE||{key}"]
else:
index = int(key[-1]) - 1
val = get_patch_composite_list(self.kind)[self.vm.patch.composite[index].get() - 1]
self.nvda.speak(f"Patch COMPOSITE {key[-1]} {val}")
case [["PATCH", "COMPOSITE"], [key], ["KEY", "SPACE" | "ENTER"]]:
open_context_menu_for_buttonmenu(self, f"PATCH COMPOSITE||{key}")
2023-08-25 20:23:21 +01:00
# Patch INSERT
2023-08-22 20:41:44 +01:00
case [["INSERT", "CHECKBOX"], [in_num, channel]]:
2023-08-23 00:27:12 +01:00
index = get_insert_checkbox_index(
self.kind,
int(channel),
int(in_num[-1]),
)
2023-08-22 20:41:44 +01:00
val = values[f"INSERT CHECKBOX||{in_num} {channel}"]
self.vm.patch.insert[index].on = val
self.nvda.speak(
f"PATCH INSERT {in_num} {_patch_insert_channels[int(channel)]} set to {'on' if val else 'off'}"
)
case [["INSERT", "CHECKBOX"], [in_num, channel], ["FOCUS", "IN"]]:
index = get_insert_checkbox_index(
self.kind,
int(channel),
int(in_num[-1]),
)
val = values[f"INSERT CHECKBOX||{in_num} {channel}"]
2023-08-22 20:41:44 +01:00
channel = _patch_insert_channels[int(channel)]
num = int(in_num[-1])
self.nvda.speak(f"Patch INSERT IN#{num} {channel} {'on' if val else 'off'}")
2023-08-26 00:11:05 +01:00
2023-08-26 21:55:39 +01:00
# ASIO Buffer
case ["ASIO BUFFER"]:
if values[event] == "Default":
val = 0
else:
val = values[event]
self.vm.option.buffer("asio", val)
self.TKroot.after(200, self.nvda.speak, f"ASIO BUFFER {val if val else 'default'}")
case [["ASIO", "BUFFER"], ["FOCUS", "IN"]]:
val = int(self.vm.get("option.buffer.asio"))
self.nvda.speak(f"ASIO BUFFER {val if val else 'default'}")
case [["ASIO", "BUFFER"], ["KEY", "SPACE" | "ENTER"]]:
open_context_menu_for_buttonmenu(self, "ASIO BUFFER")
2023-08-26 21:55:39 +01:00
2023-08-26 00:11:05 +01:00
# Strip outputs
case [["STRIP", index], [output]]:
2023-08-26 00:11:05 +01:00
val = not self.cache["outputs"][f"STRIP {index}||{output}"]
setattr(self.vm.strip[int(index)], output, val)
self.cache["outputs"][f"STRIP {index}||{output}"] = val
2023-08-26 17:29:24 +01:00
self.nvda.speak(f"STRIP {index} {output} {label if label else ''} {'on' if val else 'off'}")
2023-08-26 00:11:05 +01:00
case [["STRIP", index], [output], ["FOCUS", "IN"]]:
val = self.cache["outputs"][f"STRIP {index}||{output}"]
label = self.vm.strip[int(index)].label
self.nvda.speak(f"STRIP {index} {output} {label if label else ''} {'on' if val else 'off'}")
case [["STRIP", index], [output], ["KEY", "ENTER"]]:
self.find_element_with_focus().click()
2023-08-28 21:21:26 +01:00
# Bus modes
case [["BUS", index], ["MODE"]]:
val = self.cache["busmode"][event]
if val != "normal":
self.vm.bus[int(index)].mode.normal = True
self.cache["busmode"][event] = "normal"
else:
self.vm.bus[int(index)].mode.composite = True
self.cache["busmode"][event] = "composite"
label = self.vm.bus[int(index)].label
self.TKroot.after(
200,
self.nvda.speak,
f"BUS {index} {label if label else ''} bus mode {self.cache['busmode'][event]}",
)
2023-08-28 21:21:26 +01:00
case [["BUS", index], ["MODE"], ["FOCUS", "IN"]]:
label = self.vm.bus[int(index)].label
self.nvda.speak(
2023-08-28 21:21:26 +01:00
f"BUS {index} {label if label else ''} bus mode {self.cache['busmode'][f'BUS {index}||MODE']}"
)
# Unknown
2023-08-22 02:04:00 +01:00
case _:
2023-08-22 05:16:43 +01:00
self.logger.error(f"Unknown event {event}")
self.logger.debug(f"parsed::{parsed_cmd}")
2023-08-22 02:04:00 +01:00
2023-08-28 03:25:39 +01:00
def request_window_object(kind_id, vm):
2023-08-25 20:23:21 +01:00
NVDAVMWindow_cls = NVDAVMWindow
2023-08-28 03:25:39 +01:00
return NVDAVMWindow_cls(f"Voicemeeter {kind_id.capitalize()} NVDA", vm)