added stderr for error messages, config parser, sample configuration file. STILL A WIP. THE PROGRAM WILL JUST SPIT OUT THE EVENTS AND NOT ACTUALLY USE YOUR DEFINED EVENTS.

main
Shinyzenith 3 years ago
parent 5813eeb6ee
commit f7da66a1a7
No known key found for this signature in database
GPG Key ID: 6DD485917B553B7B

@ -1,38 +1,32 @@
#!/usr/bin/python3 #!/usr/bin/python3
import asyncio import asyncio
import getpass import getpass
import grp import grp
import os
import pwd import pwd
import signal import signal
import sys import sys
from utils.log import LOG_UTILS from utils.log import LOG_UTILS
from utils.input import INPUT_UTILS from utils.input import INPUT_UTILS
from utils.config import CONFIG_PARSER
class SWHKD: class SWHKD:
"""
Main Class.
"""
def __init__(self): def __init__(self):
signal.signal(signal.SIGINT, self.signalhandler) signal.signal(signal.SIGINT, self.signalhandler)
signal.signal(signal.SIGTERM, self.signalhandler) signal.signal(signal.SIGTERM, self.signalhandler)
self.log_util = LOG_UTILS() self.log_util = LOG_UTILS()
self.input_util = INPUT_UTILS() self.input_util = INPUT_UTILS()
self.user = getpass.getuser() self.user = getpass.getuser()
self.config_parser = CONFIG_PARSER()
def signalhandler(self,sig,frame): def signalhandler(self,sig,frame):
"""
Signal handler for SIGINT and SIGTERM.
"""
print('\033[1;31mEXIT: Quitting SWHKD.\033[0m') print('\033[1;31mEXIT: Quitting SWHKD.\033[0m')
sys.exit(0) sys.exit(0)
async def run_swhkd(self): async def run_swhkd(self):
""" # Permission check
Runner class.
"""
groups = [g.gr_name for g in grp.getgrall() if self.user in g.gr_mem] groups = [g.gr_name for g in grp.getgrall() if self.user in g.gr_mem]
gid = pwd.getpwnam(self.user).pw_gid gid = pwd.getpwnam(self.user).pw_gid
groups.append(grp.getgrgid(gid).gr_name) groups.append(grp.getgrgid(gid).gr_name)
@ -41,8 +35,20 @@ class SWHKD:
await self.log_util.log_warn("User is in input group, proceeding.") await self.log_util.log_warn("User is in input group, proceeding.")
break; break;
# Config parsing
try:
config = await self.config_parser.parse("{0}swhkd/config.json".format(os.environ.get("XDG_CONFIG_HOME")))
except FileNotFoundError:
try:
config = await self.config_parser.parse("~/.config/swhkd/config.json")
except FileNotFoundError:
await self.log_util.log_error("Failed to parse config files.")
sys.exit(1)
# Fetch events
keyboards = await self.input_util.get_keyboard_devices() keyboards = await self.input_util.get_keyboard_devices()
for keyboard in keyboards: for keyboard in keyboards:
await self.input_util.get_keyboard_events(keyboard) await self.input_util.get_keyboard_events(keyboard)
asyncio.run(SWHKD().run_swhkd()) if __name__ == "__main__":
asyncio.run(SWHKD().run_swhkd())

@ -0,0 +1,14 @@
SAMPLE JSON CONFIG
First XDG_CONFIG_HOME/swhkd/config.json is checked
and then ~/.config/swhkd/config.kson
Delete the first 4 lines before using this file.
[
{
"combo": ["KEY_ENTER", "KEY_LEFTMETA"],
"action": "foot -e ranger"
},
{
"combo": ["KEY_ENTER", "KEY_LEFTCTRL"],
"action": "pcmanfm"
}
]

@ -0,0 +1,18 @@
#!/usr/bin/python3
import json
from . log import LOG_UTILS
class CONFIG_PARSER:
def __init__(self):
self.LOG_UTILS = LOG_UTILS()
async def parse(self,config_file):
output=[]
with open(config_file, 'r') as file:
contents = json.loads(file.read())
for arr in contents:
pair=[]
for key, value in arr.items():
pair.append(value)
output.append(pair)
return output

@ -1,7 +1,6 @@
#!/usr/bin/python3
import glob import glob
import libevdev import libevdev
import os
from . log import LOG_UTILS from . log import LOG_UTILS
class INPUT_UTILS: class INPUT_UTILS:
@ -9,12 +8,8 @@ class INPUT_UTILS:
self.log_util=LOG_UTILS() self.log_util=LOG_UTILS()
async def check_keyboard(self,device_path) -> bool : async def check_keyboard(self,device_path) -> bool :
""" with open(device_path, 'rb') as fd:
Check if the device is a keyboard. device = libevdev.Device(fd)
"""
fd = open(device_path, 'rb')
device = libevdev.Device(fd)
fd.close()
if device.has(libevdev.EV_KEY.KEY_ENTER): if device.has(libevdev.EV_KEY.KEY_ENTER):
await self.log_util.log_info("Device {} is a keyboard".format(device_path)) await self.log_util.log_info("Device {} is a keyboard".format(device_path))
return True return True
@ -23,9 +18,6 @@ class INPUT_UTILS:
return False return False
async def get_keyboard_devices(self): async def get_keyboard_devices(self):
"""
Get all keyboard devices.
"""
devices = glob.glob('/dev/input/event*') devices = glob.glob('/dev/input/event*')
keyboards = [] keyboards = []
for device in devices: for device in devices:
@ -34,13 +26,15 @@ class INPUT_UTILS:
keyboards.append(device) keyboards.append(device)
return keyboards return keyboards
async def run_system_command(self,command:str) -> None:
os.system(f"setsid -f {command} 1>/dev/null 2>/dev/null")
async def get_keyboard_events(self,device_path:str) -> None: async def get_keyboard_events(self,device_path:str) -> None:
"""
Get all device events.
"""
with open(device_path, 'rb') as fd: with open(device_path, 'rb') as fd:
device = libevdev.Device(fd) device = libevdev.Device(fd)
for event in device.events(): for event in device.events():
if event.matches(libevdev.EV_MSC): if event.matches(libevdev.EV_MSC):
continue continue
print(event) if event.matches(libevdev.EV_SYN.SYN_REPORT):
continue
await self.log_util.log_info(event)

@ -1,9 +1,7 @@
import sys
import time import time
class LOG_UTILS(): class LOG_UTILS():
"""
Helper Functions.
"""
def __init__(self): def __init__(self):
self.COLOR_RED="\033[1;31m" self.COLOR_RED="\033[1;31m"
self.COLOR_GREEN="\033[1;32m" self.COLOR_GREEN="\033[1;32m"
@ -15,7 +13,7 @@ class LOG_UTILS():
print(f"{self.COLOR_GREEN}[{time.ctime()}] INFO:{self.COLOR_RESET} {message}") print(f"{self.COLOR_GREEN}[{time.ctime()}] INFO:{self.COLOR_RESET} {message}")
async def log_error(self, message:str): async def log_error(self, message:str):
print(f"{self.COLOR_RED}[{time.ctime()}] ERROR:{self.COLOR_RESET} {message}") print(f"{self.COLOR_RED}[{time.ctime()}] ERROR:{self.COLOR_RESET} {message}", file=sys.stderr)
async def log_warn(self, message:str): async def log_warn(self, message:str):
print(f"{self.COLOR_YELLOW}[{time.ctime()}] WARN:{self.COLOR_RESET} {message}") print(f"{self.COLOR_YELLOW}[{time.ctime()}] WARN:{self.COLOR_RESET} {message}")

Loading…
Cancel
Save