better handling of duplicate services

This commit is contained in:
sezanzeb 2020-12-04 15:31:32 +01:00 committed by sezanzeb
parent a449755049
commit 6b43e66bdd
4 changed files with 27 additions and 19 deletions

View File

@ -32,7 +32,7 @@ from gi.repository import GLib
from pydbus import SessionBus
from keymapper.logger import update_verbosity, log_info, \
add_filehandler
add_filehandler, logger
from keymapper.daemon import Daemon, BUS_NAME
from keymapper.dev.permissions import can_read_devices
@ -61,8 +61,15 @@ if __name__ == '__main__':
bus = SessionBus()
loop = GLib.MainLoop()
daemon = Daemon(True, loop)
bus.publish(BUS_NAME, daemon)
daemon = Daemon(loop)
try:
bus.publish(BUS_NAME, daemon)
except RuntimeError:
logger.error('The service is already running')
sys.exit(1)
daemon.autoload()
atexit.register(lambda: daemon.stop(True))

View File

@ -26,6 +26,7 @@ https://github.com/LEW21/pydbus/tree/cc407c8b1d25b7e28a6d661a29f9e661b1c9b964/ex
import subprocess
import sys
from pydbus import SessionBus
@ -54,7 +55,7 @@ def get_dbus_interface():
'The daemon "key-mapper-service" is not running, mapping keys '
'only works as long as the window is open.'
)
return Daemon(autoload=False)
return Daemon()
bus = SessionBus()
interface = bus.get(BUS_NAME)
@ -99,21 +100,23 @@ class Daemon:
</node>
"""
def __init__(self, autoload=True, loop=None):
def __init__(self, loop=None):
"""Constructs the daemon. You still need to run the GLib mainloop."""
logger.debug('Creating daemon')
self.injectors = {}
self.loop = loop
if autoload:
for device, preset in config.iterate_autoload_presets():
mapping = Mapping()
mapping.load(device, preset)
try:
injector = KeycodeInjector(device, mapping)
injector.start_injecting()
self.injectors[device] = injector
except OSError as error:
logger.error(error)
def autoload(self):
"""Runs all autoloaded presets."""
for device, preset in config.iterate_autoload_presets():
mapping = Mapping()
mapping.load(device, preset)
try:
injector = KeycodeInjector(device, mapping)
injector.start_injecting()
self.injectors[device] = injector
except OSError as error:
logger.error(error)
def stop_injecting(self, device):
"""Stop injecting the mapping for a single device."""

View File

@ -136,9 +136,7 @@ class Window:
GLib.source_remove(timeout)
self.timeouts = []
keycode_reader.stop_reading()
self.window.destroy()
gtk_iteration()
sys.exit(0)
Gtk.main_quit()
def check_add_row(self):
"""Ensure that one empty row is available at all times."""

View File

@ -101,7 +101,7 @@ class TestDaemon(unittest.TestCase):
]
self.daemon = Daemon()
# starts mapping right after creation
self.daemon.autoload()
self.assertTrue(self.daemon.is_injecting('device 2'))
self.assertFalse(self.daemon.is_injecting('device 1'))