WIP refactor
This commit is contained in:
3
src/old-src/utils/__init__.py
Normal file
3
src/old-src/utils/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
"""
|
||||
Utils module
|
||||
"""
|
||||
22
src/old-src/utils/endpoint_registry.py
Normal file
22
src/old-src/utils/endpoint_registry.py
Normal file
@@ -0,0 +1,22 @@
|
||||
# Python imports
|
||||
|
||||
# Lib imports
|
||||
|
||||
# Application imports
|
||||
from .singleton import Singleton
|
||||
|
||||
|
||||
|
||||
class EndpointRegistry(Singleton):
|
||||
def __init__(self):
|
||||
self._endpoints = {}
|
||||
|
||||
def register(self, rule, **options):
|
||||
def decorator(f):
|
||||
self._endpoints[rule] = f
|
||||
return f
|
||||
|
||||
return decorator
|
||||
|
||||
def get_endpoints(self):
|
||||
return self._endpoints
|
||||
54
src/old-src/utils/event_system.py
Normal file
54
src/old-src/utils/event_system.py
Normal file
@@ -0,0 +1,54 @@
|
||||
# Python imports
|
||||
from collections import defaultdict
|
||||
|
||||
# Lib imports
|
||||
|
||||
# Application imports
|
||||
from .singleton import Singleton
|
||||
|
||||
|
||||
|
||||
class EventSystem(Singleton):
|
||||
""" Create event system. """
|
||||
|
||||
def __init__(self):
|
||||
self.subscribers = defaultdict(list)
|
||||
|
||||
|
||||
def subscribe(self, event_type, fn):
|
||||
self.subscribers[event_type].append(fn)
|
||||
|
||||
def unsubscribe(self, event_type, fn):
|
||||
self.subscribers[event_type].remove(fn)
|
||||
|
||||
def unsubscribe_all(self, event_type):
|
||||
self.subscribers.pop(event_type, None)
|
||||
|
||||
def emit(self, event_type, data = None):
|
||||
if event_type in self.subscribers:
|
||||
for fn in self.subscribers[event_type]:
|
||||
if data:
|
||||
if hasattr(data, '__iter__') and not type(data) is str:
|
||||
fn(*data)
|
||||
else:
|
||||
fn(data)
|
||||
else:
|
||||
fn()
|
||||
|
||||
def emit_and_await(self, event_type, data = None):
|
||||
""" NOTE: Should be used when signal has only one listener and vis-a-vis """
|
||||
if event_type in self.subscribers:
|
||||
response = None
|
||||
for fn in self.subscribers[event_type]:
|
||||
if data:
|
||||
if hasattr(data, '__iter__') and not type(data) is str:
|
||||
response = fn(*data)
|
||||
else:
|
||||
response = fn(data)
|
||||
else:
|
||||
response = fn()
|
||||
|
||||
if not response in (None, ''):
|
||||
break
|
||||
|
||||
return response
|
||||
91
src/old-src/utils/ipc_server.py
Normal file
91
src/old-src/utils/ipc_server.py
Normal file
@@ -0,0 +1,91 @@
|
||||
# Python imports
|
||||
import os, threading, time
|
||||
from multiprocessing.connection import Listener, Client
|
||||
|
||||
# Lib imports
|
||||
|
||||
# Application imports
|
||||
from .singleton import Singleton
|
||||
|
||||
|
||||
def threaded(fn):
|
||||
def wrapper(*args, **kwargs):
|
||||
threading.Thread(target=fn, args=args, kwargs=kwargs, daemon=True).start()
|
||||
return wrapper
|
||||
|
||||
|
||||
|
||||
|
||||
class IPCServer(Singleton):
|
||||
""" Create a listener so that other SolarFM instances send requests back to existing instance. """
|
||||
def __init__(self, conn_type="socket"):
|
||||
self.is_ipc_alive = False
|
||||
self._conn_type = conn_type
|
||||
self.ipc_authkey = b'mirage2-ipc'
|
||||
self.ipc_timeout = 15.0
|
||||
|
||||
if conn_type == "socket":
|
||||
self.ipc_address = '/tmp/mirage2-ipc.sock'
|
||||
else:
|
||||
self.ipc_address = '127.0.0.1'
|
||||
self.ipc_port = 4848
|
||||
|
||||
|
||||
@threaded
|
||||
def create_ipc_server(self):
|
||||
if self._conn_type == "socket":
|
||||
if os.path.exists(self.ipc_address):
|
||||
return
|
||||
|
||||
listener = Listener(address=self.ipc_address, family="AF_UNIX", authkey=self.ipc_authkey)
|
||||
else:
|
||||
listener = Listener((self.ipc_address, self.ipc_port), authkey=self.ipc_authkey)
|
||||
|
||||
|
||||
self.is_ipc_alive = True
|
||||
while True:
|
||||
conn = listener.accept()
|
||||
start_time = time.time()
|
||||
|
||||
print(f"New Connection: {listener.last_accepted}")
|
||||
while True:
|
||||
msg = conn.recv()
|
||||
if debug:
|
||||
print(msg)
|
||||
|
||||
if "FILE|" in msg:
|
||||
file = msg.split("FILE|")[1].strip()
|
||||
if file:
|
||||
event_system.push_gui_event([None, "handle_file_from_ipc", (file,)])
|
||||
|
||||
conn.close()
|
||||
break
|
||||
|
||||
|
||||
if msg == 'close connection':
|
||||
conn.close()
|
||||
break
|
||||
if msg == 'close server':
|
||||
conn.close()
|
||||
break
|
||||
|
||||
# NOTE: Not perfect but insures we don't lock up the connection for too long.
|
||||
end_time = time.time()
|
||||
if (end - start) > self.ipc_timeout:
|
||||
conn.close()
|
||||
|
||||
listener.close()
|
||||
|
||||
|
||||
def send_ipc_message(self, message="Empty Data..."):
|
||||
try:
|
||||
if self._conn_type == "socket":
|
||||
conn = Client(address=self.ipc_address, family="AF_UNIX", authkey=self.ipc_authkey)
|
||||
else:
|
||||
conn = Client((self.ipc_address, self.ipc_port), authkey=self.ipc_authkey)
|
||||
|
||||
|
||||
conn.send(message)
|
||||
conn.send('close connection')
|
||||
except Exception as e:
|
||||
print(repr(e))
|
||||
138
src/old-src/utils/keybindings.py
Normal file
138
src/old-src/utils/keybindings.py
Normal file
@@ -0,0 +1,138 @@
|
||||
# Python imports
|
||||
import re
|
||||
|
||||
# Gtk imports
|
||||
import gi
|
||||
gi.require_version('Gdk', '3.0')
|
||||
from gi.repository import Gdk
|
||||
|
||||
# Application imports
|
||||
from .singleton import Singleton
|
||||
|
||||
|
||||
|
||||
def logger(log = ""):
|
||||
print(log)
|
||||
|
||||
|
||||
class KeymapError(Exception):
|
||||
""" Custom exception for errors in keybinding configurations """
|
||||
|
||||
MODIFIER = re.compile('<([^<]+)>')
|
||||
class Keybindings(Singleton):
|
||||
""" Class to handle loading and lookup of Terminator keybindings """
|
||||
|
||||
modifiers = {
|
||||
'ctrl': Gdk.ModifierType.CONTROL_MASK,
|
||||
'control': Gdk.ModifierType.CONTROL_MASK,
|
||||
'primary': Gdk.ModifierType.CONTROL_MASK,
|
||||
'shift': Gdk.ModifierType.SHIFT_MASK,
|
||||
'alt': Gdk.ModifierType.MOD1_MASK,
|
||||
'super': Gdk.ModifierType.SUPER_MASK,
|
||||
'hyper': Gdk.ModifierType.HYPER_MASK,
|
||||
'mod2': Gdk.ModifierType.MOD2_MASK
|
||||
}
|
||||
|
||||
empty = {}
|
||||
keys = None
|
||||
_masks = None
|
||||
_lookup = None
|
||||
|
||||
def __init__(self):
|
||||
self.keymap = Gdk.Keymap.get_default()
|
||||
self.configure({})
|
||||
|
||||
def print_keys(self):
|
||||
print(self.keys)
|
||||
|
||||
def append_bindings(self, combos):
|
||||
""" Accept new binding(s) and reload """
|
||||
for item in combos:
|
||||
method, keys = item.split(":")
|
||||
self.keys[method] = keys
|
||||
|
||||
self.reload()
|
||||
|
||||
def configure(self, bindings):
|
||||
""" Accept new bindings and reconfigure with them """
|
||||
self.keys = bindings
|
||||
self.reload()
|
||||
|
||||
def reload(self):
|
||||
""" Parse bindings and mangle into an appropriate form """
|
||||
self._lookup = {}
|
||||
self._masks = 0
|
||||
|
||||
for action, bindings in list(self.keys.items()):
|
||||
if isinstance(bindings, list):
|
||||
bindings = (*bindings,)
|
||||
elif not isinstance(bindings, tuple):
|
||||
bindings = (bindings,)
|
||||
|
||||
|
||||
for binding in bindings:
|
||||
if not binding or binding == "None":
|
||||
continue
|
||||
|
||||
try:
|
||||
keyval, mask = self._parsebinding(binding)
|
||||
# Does much the same, but with poorer error handling.
|
||||
# keyval, mask = Gtk.accelerator_parse(binding)
|
||||
except KeymapError as e:
|
||||
logger(f"Keybinding reload failed to parse binding '{binding}': {e}")
|
||||
else:
|
||||
if mask & Gdk.ModifierType.SHIFT_MASK:
|
||||
if keyval == Gdk.KEY_Tab:
|
||||
keyval = Gdk.KEY_ISO_Left_Tab
|
||||
mask &= ~Gdk.ModifierType.SHIFT_MASK
|
||||
else:
|
||||
keyvals = Gdk.keyval_convert_case(keyval)
|
||||
if keyvals[0] != keyvals[1]:
|
||||
keyval = keyvals[1]
|
||||
mask &= ~Gdk.ModifierType.SHIFT_MASK
|
||||
else:
|
||||
keyval = Gdk.keyval_to_lower(keyval)
|
||||
|
||||
self._lookup.setdefault(mask, {})
|
||||
self._lookup[mask][keyval] = action
|
||||
self._masks |= mask
|
||||
|
||||
def _parsebinding(self, binding):
|
||||
""" Parse an individual binding using Gtk's binding function """
|
||||
mask = 0
|
||||
modifiers = re.findall(MODIFIER, binding)
|
||||
|
||||
if modifiers:
|
||||
for modifier in modifiers:
|
||||
mask |= self._lookup_modifier(modifier)
|
||||
|
||||
key = re.sub(MODIFIER, '', binding)
|
||||
if key == '':
|
||||
raise KeymapError('No key found!')
|
||||
|
||||
keyval = Gdk.keyval_from_name(key)
|
||||
|
||||
if keyval == 0:
|
||||
raise KeymapError(f"Key '{key}' is unrecognised...")
|
||||
return (keyval, mask)
|
||||
|
||||
def _lookup_modifier(self, modifier):
|
||||
""" Map modifier names to gtk values """
|
||||
try:
|
||||
return self.modifiers[modifier.lower()]
|
||||
except KeyError:
|
||||
raise KeymapError(f"Unhandled modifier '<{modifier}>'")
|
||||
|
||||
def lookup(self, event):
|
||||
""" Translate a keyboard event into a mapped key """
|
||||
try:
|
||||
_found, keyval, _egp, _lvl, consumed = self.keymap.translate_keyboard_state(
|
||||
event.hardware_keycode,
|
||||
Gdk.ModifierType(event.get_state() & ~Gdk.ModifierType.LOCK_MASK),
|
||||
event.group)
|
||||
except TypeError:
|
||||
logger("Keybinding lookup failed to translate keyboard event: {dir(event)}")
|
||||
return None
|
||||
|
||||
mask = (event.get_state() & ~consumed) & self._masks
|
||||
return self._lookup.get(mask, self.empty).get(keyval, None)
|
||||
59
src/old-src/utils/logger.py
Normal file
59
src/old-src/utils/logger.py
Normal file
@@ -0,0 +1,59 @@
|
||||
# Python imports
|
||||
import os
|
||||
import logging
|
||||
|
||||
# Application imports
|
||||
from .singleton import Singleton
|
||||
|
||||
|
||||
|
||||
class Logger(Singleton):
|
||||
"""
|
||||
Create a new logging object and return it.
|
||||
:note:
|
||||
NOSET # Don't know the actual log level of this... (defaulting or literally none?)
|
||||
Log Levels (From least to most)
|
||||
Type Value
|
||||
CRITICAL 50
|
||||
ERROR 40
|
||||
WARNING 30
|
||||
INFO 20
|
||||
DEBUG 10
|
||||
:param loggerName: Sets the name of the logger object. (Used in log lines)
|
||||
:param createFile: Whether we create a log file or just pump to terminal
|
||||
|
||||
:return: the logging object we created
|
||||
"""
|
||||
|
||||
def __init__(self, config_path: str, _ch_log_lvl = logging.CRITICAL, _fh_log_lvl = logging.INFO):
|
||||
self._CONFIG_PATH = config_path
|
||||
self.global_lvl = logging.DEBUG # Keep this at highest so that handlers can filter to their desired levels
|
||||
self.ch_log_lvl = _ch_log_lvl # Prety much the only one we ever change
|
||||
self.fh_log_lvl = _fh_log_lvl
|
||||
|
||||
def get_logger(self, loggerName: str = "NO_LOGGER_NAME_PASSED", createFile: bool = True) -> logging.Logger:
|
||||
log = logging.getLogger(loggerName)
|
||||
log.setLevel(self.global_lvl)
|
||||
|
||||
# Set our log output styles
|
||||
fFormatter = logging.Formatter('[%(asctime)s] %(pathname)s:%(lineno)d %(levelname)s - %(message)s', '%m-%d %H:%M:%S')
|
||||
cFormatter = logging.Formatter('%(pathname)s:%(lineno)d] %(levelname)s - %(message)s')
|
||||
|
||||
ch = logging.StreamHandler()
|
||||
ch.setLevel(level=self.ch_log_lvl)
|
||||
ch.setFormatter(cFormatter)
|
||||
log.addHandler(ch)
|
||||
|
||||
if createFile:
|
||||
folder = self._CONFIG_PATH
|
||||
file = f"{folder}/application.log"
|
||||
|
||||
if not os.path.exists(folder):
|
||||
os.mkdir(folder)
|
||||
|
||||
fh = logging.FileHandler(file)
|
||||
fh.setLevel(level=self.fh_log_lvl)
|
||||
fh.setFormatter(fFormatter)
|
||||
log.addHandler(fh)
|
||||
|
||||
return log
|
||||
113
src/old-src/utils/settings.py
Normal file
113
src/old-src/utils/settings.py
Normal file
@@ -0,0 +1,113 @@
|
||||
# Python imports
|
||||
import os
|
||||
|
||||
# Gtk imports
|
||||
import gi, cairo
|
||||
gi.require_version('Gtk', '3.0')
|
||||
gi.require_version('Gdk', '3.0')
|
||||
|
||||
from gi.repository import Gtk
|
||||
from gi.repository import Gdk
|
||||
|
||||
|
||||
# Application imports
|
||||
from .singleton import Singleton
|
||||
from .logger import Logger
|
||||
|
||||
|
||||
|
||||
class Settings(Singleton):
|
||||
def __init__(self):
|
||||
self._SCRIPT_PTH = os.path.dirname(os.path.realpath(__file__))
|
||||
self._USER_HOME = os.path.expanduser('~')
|
||||
self._CONFIG_PATH = f"{self._USER_HOME}/.config/{app_name.lower()}"
|
||||
self._HOME_CONFIG_PATH = f"{self._USER_HOME}/.config/{app_name.lower()}"
|
||||
self._GLADE_FILE = f"{self._CONFIG_PATH}/Main_Window.glade"
|
||||
self._CSS_FILE = f"{self._CONFIG_PATH}/stylesheet.css"
|
||||
self._DEFAULT_ICONS = f"{self._CONFIG_PATH}/icons"
|
||||
self._WINDOW_ICON = f"{self._DEFAULT_ICONS}/{app_name.lower()}.png"
|
||||
self._BLANK_ICON = f"{self._DEFAULT_ICONS}/mirage_blank.png"
|
||||
self._USR_PATH = f"/usr/share/{app_name.lower()}"
|
||||
|
||||
if not os.path.exists(self._CONFIG_PATH):
|
||||
os.mkdir(self._CONFIG_PATH)
|
||||
if not os.path.exists(self._GLADE_FILE):
|
||||
self._GLADE_FILE = f"{self._USR_PATH}/Main_Window.glade"
|
||||
if not os.path.exists(self._CSS_FILE):
|
||||
self._CSS_FILE = f"{self._USR_PATH}/stylesheet.css"
|
||||
if not os.path.exists(self._WINDOW_ICON):
|
||||
self._WINDOW_ICON = f"{self._USR_PATH}/icons/{app_name.lower()}.png"
|
||||
if not os.path.exists(self._BLANK_ICON):
|
||||
self._BLANK_ICON = f"{self._USR_PATH}/icons/mirage_blank.png"
|
||||
if not os.path.exists(self._DEFAULT_ICONS):
|
||||
self.DEFAULT_ICONS = f"{self._USR_PATH}/icons"
|
||||
|
||||
# '_filters'
|
||||
self._images_filter = ('.png', '.jpg', '.jpeg', '.gif', '.ico', '.tga')
|
||||
|
||||
self._success_color = "#88cc27"
|
||||
self._warning_color = "#ffa800"
|
||||
self._error_color = "#ff0000"
|
||||
|
||||
self._main_window = None
|
||||
self._logger = Logger(self._CONFIG_PATH).get_logger()
|
||||
self._builder = Gtk.Builder()
|
||||
self._builder.add_from_file(self._GLADE_FILE)
|
||||
|
||||
|
||||
|
||||
def create_window(self):
|
||||
# Get window and connect signals
|
||||
self._main_window = self._builder.get_object("Main_Window")
|
||||
self.set_window_data()
|
||||
|
||||
def set_window_data(self):
|
||||
self._main_window.set_icon_from_file(self._WINDOW_ICON)
|
||||
screen = self._main_window.get_screen()
|
||||
visual = screen.get_rgba_visual()
|
||||
|
||||
if visual != None and screen.is_composited():
|
||||
self._main_window.set_visual(visual)
|
||||
self._main_window.set_app_paintable(True)
|
||||
self._main_window.connect("draw", self.draw_area)
|
||||
|
||||
# bind css file
|
||||
cssProvider = Gtk.CssProvider()
|
||||
cssProvider.load_from_path(self._CSS_FILE)
|
||||
screen = Gdk.Screen.get_default()
|
||||
styleContext = Gtk.StyleContext()
|
||||
styleContext.add_provider_for_screen(screen, cssProvider, Gtk.STYLE_PROVIDER_PRIORITY_USER)
|
||||
|
||||
def get_monitor_data(self):
|
||||
screen = self._builder.get_object("Main_Window").get_screen()
|
||||
monitors = []
|
||||
for m in range(screen.get_n_monitors()):
|
||||
monitors.append(screen.get_monitor_geometry(m))
|
||||
|
||||
for monitor in monitors:
|
||||
print("{}x{}|{}+{}".format(monitor.width, monitor.height, monitor.x, monitor.y))
|
||||
|
||||
return monitors
|
||||
|
||||
def draw_area(self, widget, cr):
|
||||
cr.set_source_rgba(0, 0, 0, 0.54)
|
||||
cr.set_operator(cairo.OPERATOR_SOURCE)
|
||||
cr.paint()
|
||||
cr.set_operator(cairo.OPERATOR_OVER)
|
||||
|
||||
|
||||
|
||||
|
||||
def get_builder(self): return self._builder
|
||||
def get_logger(self): return self._logger
|
||||
def get_main_window(self): return self._main_window
|
||||
def get_home_path(self): return self._USER_HOME
|
||||
def get_home_config_path(self) -> str: return self._HOME_CONFIG_PATH
|
||||
|
||||
# Filter returns
|
||||
def get_images_filter(self): return self._images_filter
|
||||
|
||||
def get_blank_image(self): return self._BLANK_ICON
|
||||
def get_success_color(self): return self._success_color
|
||||
def get_warning_color(self): return self._warning_color
|
||||
def get_error_color(self): return self._error_color
|
||||
23
src/old-src/utils/singleton.py
Normal file
23
src/old-src/utils/singleton.py
Normal file
@@ -0,0 +1,23 @@
|
||||
# Python imports
|
||||
|
||||
# Lib imports
|
||||
|
||||
# Application imports
|
||||
|
||||
|
||||
class SingletonError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
|
||||
class Singleton:
|
||||
ccount = 0
|
||||
|
||||
def __new__(cls, *args, **kwargs):
|
||||
obj = super(Singleton, cls).__new__(cls)
|
||||
cls.ccount += 1
|
||||
|
||||
if cls.ccount == 2:
|
||||
raise SingletonError(f"Exceeded {cls.__name__} instantiation limit...")
|
||||
|
||||
return obj
|
||||
Reference in New Issue
Block a user