Added Singleton class to inherit as needed

This commit is contained in:
2023-03-27 20:07:17 -05:00
parent 4b69622cc6
commit ca61d5348f
46 changed files with 6455 additions and 97 deletions

View File

@@ -3,11 +3,11 @@
# Lib imports
# Application imports
from .singleton import Singleton
class EndpointRegistry():
class EndpointRegistry(Singleton):
def __init__(self):
self._endpoints = {}

View File

@@ -4,11 +4,11 @@ from collections import defaultdict
# Lib imports
# Application imports
from .singleton import Singleton
class EventSystem:
class EventSystem(Singleton):
""" Create event system. """
def __init__(self):

View File

@@ -8,11 +8,11 @@ from multiprocessing.connection import Listener
from gi.repository import GLib
# Application imports
from .singleton import Singleton
class IPCServer:
class IPCServer(Singleton):
""" Create a listener so that other SolarFM instances send requests back to existing instance. """
def __init__(self, ipc_address: str = '127.0.0.1', conn_type: str = "socket"):
self.is_ipc_alive = False

View File

@@ -7,20 +7,20 @@ gi.require_version('Gdk', '3.0')
from gi.repository import Gdk
# Application imports
from .singleton import Singleton
def err(log = ""):
"""Print an error message"""
def logger(log = ""):
print(log)
class KeymapError(Exception):
"""Custom exception for errors in keybinding configurations"""
""" Custom exception for errors in keybinding configurations """
MODIFIER = re.compile('<([^<]+)>')
class Keybindings:
"""Class to handle loading and lookup of Terminator keybindings"""
class Keybindings(Singleton):
""" Class to handle loading and lookup of Terminator keybindings """
modifiers = {
'ctrl': Gdk.ModifierType.CONTROL_MASK,
@@ -46,7 +46,7 @@ class Keybindings:
print(self.keys)
def append_bindings(self, combos):
"""Accept new binding(s) and reload"""
""" Accept new binding(s) and reload """
for item in combos:
method, keys = item.split(":")
self.keys[method] = keys
@@ -54,12 +54,12 @@ class Keybindings:
self.reload()
def configure(self, bindings):
"""Accept new bindings and reconfigure with them"""
""" Accept new bindings and reconfigure with them """
self.keys = bindings
self.reload()
def reload(self):
"""Parse bindings and mangle into an appropriate form"""
""" Parse bindings and mangle into an appropriate form """
self._lookup = {}
self._masks = 0
@@ -77,9 +77,9 @@ class Keybindings:
try:
keyval, mask = self._parsebinding(binding)
# Does much the same, but with poorer error handling.
#keyval, mask = Gtk.accelerator_parse(binding)
# keyval, mask = Gtk.accelerator_parse(binding)
except KeymapError as e:
err ("keybinding reload failed to parse binding '%s': %s" % (binding, e))
logger(f"Keybinding reload failed to parse binding '{binding}': {e}")
else:
if mask & Gdk.ModifierType.SHIFT_MASK:
if keyval == Gdk.KEY_Tab:
@@ -98,7 +98,7 @@ class Keybindings:
self._masks |= mask
def _parsebinding(self, binding):
"""Parse an individual binding using Gtk's binding function"""
""" Parse an individual binding using Gtk's binding function """
mask = 0
modifiers = re.findall(MODIFIER, binding)
@@ -113,25 +113,25 @@ class Keybindings:
keyval = Gdk.keyval_from_name(key)
if keyval == 0:
raise KeymapError("Key '%s' is unrecognised..." % key)
raise KeymapError(f"Key '{key}' is unrecognised...")
return (keyval, mask)
def _lookup_modifier(self, modifier):
"""Map modifier names to gtk values"""
""" Map modifier names to gtk values """
try:
return self.modifiers[modifier.lower()]
except KeyError:
raise KeymapError("Unhandled modifier '<%s>'" % modifier)
raise KeymapError(f"Unhandled modifier '<{modifier}>'")
def lookup(self, event):
"""Translate a keyboard event into a mapped key"""
""" 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:
err ("Keybinding lookup failed to translate keyboard event: %s" % dir(event))
logger("Keybinding lookup failed to translate keyboard event: {dir(event)}")
return None
mask = (event.get_state() & ~consumed) & self._masks

View File

@@ -3,9 +3,11 @@ import os
import logging
# Application imports
from .singleton import Singleton
class Logger:
class Logger(Singleton):
"""
Create a new logging object and return it.
:note:

View File

@@ -11,11 +11,12 @@ from gi.repository import Gtk
from gi.repository import GLib
# Application imports
from ..singleton import Singleton
from .start_check_mixin import StartCheckMixin
class Settings(StartCheckMixin):
class Settings(StartCheckMixin, Singleton):
def __init__(self):
self._SCRIPT_PTH = os.path.dirname(os.path.realpath(__file__))
self._USER_HOME = path.expanduser('~')
@@ -31,6 +32,12 @@ class Settings(StartCheckMixin):
self._KEY_BINDINGS_FILE = f"{self._HOME_CONFIG_PATH}/key-bindings.json"
self._PID_FILE = f"{self._HOME_CONFIG_PATH}/{app_name.lower()}.pid"
self._WINDOW_ICON = f"{self._DEFAULT_ICONS}/icons/{app_name.lower()}.png"
self._UI_WIDEGTS_PATH = f"{self._HOME_CONFIG_PATH}/ui_widgets"
self._CONTEXT_MENU = f"{self._HOME_CONFIG_PATH}/contexct_menu.json"
self._TRASH_FILES_PATH = f"{GLib.get_user_data_dir()}/Trash/files"
self._TRASH_INFO_PATH = f"{GLib.get_user_data_dir()}/Trash/info"
self._ICON_THEME = Gtk.IconTheme.get_default()
if not os.path.exists(self._HOME_CONFIG_PATH):
os.mkdir(self._HOME_CONFIG_PATH)
@@ -64,23 +71,25 @@ class Settings(StartCheckMixin):
self._WINDOW_ICON = f"{self._USR_PATH}/icons/{app_name.lower()}.png"
if not os.path.exists(self._WINDOW_ICON):
raise MissingConfigError("Unable to find the application icon.")
self._UI_WIDEGTS_PATH = f"{self._USR_PATH}/ui_widgets"
self._CONTEXT_MENU = f"{self._USR_PATH}/contexct_menu.json"
self._TRASH_FILES_PATH = f"{GLib.get_user_data_dir()}/Trash/files"
self._TRASH_INFO_PATH = f"{GLib.get_user_data_dir()}/Trash/info"
self._ICON_THEME = Gtk.IconTheme.get_default()
if not os.path.exists(self._UI_WIDEGTS_PATH):
self._UI_WIDEGTS_PATH = f"{self._USR_PATH}/ui_widgets"
if not os.path.exists(self._CONTEXT_MENU):
self._CONTEXT_MENU = f"{self._USR_PATH}/contexct_menu.json"
with open(self._KEY_BINDINGS_FILE) as file:
bindings = json.load(file)["keybindings"]
keybindings.configure(bindings)
with open(self._CONTEXT_MENU) as file:
self._context_menu_data = json.load(file)
try:
with open(self._KEY_BINDINGS_FILE) as file:
bindings = json.load(file)["keybindings"]
keybindings.configure(bindings)
except Exception as e:
print( f"Settings: {self._KEY_BINDINGS_FILE}\n\t\t{repr(e)}" )
try:
with open(self._CONTEXT_MENU) as file:
self._context_menu_data = json.load(file)
except Exception as e:
print( f"Settings: {self._CONTEXT_MENU}\n\t\t{repr(e)}" )
self._main_window = None
self._main_window_w = 1670
@@ -119,8 +128,8 @@ class Settings(StartCheckMixin):
def set_builder(self, builder) -> any: self._builder = builder
def set_main_window(self, window): self._main_window = window
def get_main_window(self) -> Gtk.ApplicationWindow: return self._main_window
def get_main_window_width(self) -> Gtk.ApplicationWindow: return self._main_window_w
def get_main_window(self) -> Gtk.ApplicationWindow: return self._main_window
def get_main_window_width(self) -> Gtk.ApplicationWindow: return self._main_window_w
def get_main_window_height(self) -> Gtk.ApplicationWindow: return self._main_window_h
def get_builder(self) -> Gtk.Builder: return self._builder
def get_glade_file(self) -> str: return self._GLADE_FILE

View 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