define exception hierarchy

allow is_running to return values x>=0
This commit is contained in:
onyx-and-iris 2023-08-22 16:11:00 +01:00
parent 740cf1ac02
commit a2af0e704c
2 changed files with 19 additions and 4 deletions

View File

@ -0,0 +1,11 @@
class NVDAVMError(Exception):
"""Base NVDAVM error class"""
class NVDAVMCAPIError(NVDAVMError):
"""Exception raised when the NVDA C-API returns an error code"""
def __init__(self, fn_name, code):
self.fn_name = fn_name
self.code = code
super().__init__(f"{self.fn_name} returned {self.code}")

View File

@ -1,4 +1,5 @@
from .cdll import libc from .cdll import libc
from .errors import NVDAVMCAPIError
class CBindings: class CBindings:
@ -7,17 +8,20 @@ class CBindings:
bind_cancel_speech = libc.nvdaController_cancelSpeech bind_cancel_speech = libc.nvdaController_cancelSpeech
bind_braille_message = libc.nvdaController_brailleMessage bind_braille_message = libc.nvdaController_brailleMessage
def call(self, fn, *args, ok=(0,)): def call(self, fn, *args, ok=(0,), ok_exp=None):
retval = fn(*args) retval = fn(*args)
if ok_exp is None:
if retval not in ok: if retval not in ok:
raise RuntimeError(f"{fn.__name__} returned {retval}") raise NVDAVMCAPIError(fn.__name__, retval)
elif not ok_exp(retval) and retval not in ok:
raise NVDAVMCAPIError(fn.__name__, retval)
return retval return retval
class Nvda(CBindings): class Nvda(CBindings):
@property @property
def is_running(self): def is_running(self):
return self.call(self.bind_test_if_running, ok=(0, 1)) == 0 return self.call(self.bind_test_if_running, ok_exp=lambda x: x >= 0) == 0
def speak(self, text): def speak(self, text):
self.call(self.bind_speak_text, text) self.call(self.bind_speak_text, text)