restructured manifest and plugins loading; updated plugins

This commit is contained in:
2025-12-29 22:50:05 -06:00
parent c74f97aca7
commit 21120cd61e
324 changed files with 18088 additions and 15974 deletions

View File

@@ -44,6 +44,8 @@ class GridMixin:
def update_store(self, store, icons):
for i, icon in enumerate(icons):
if not icon: continue
try:
itr = store.get_iter(i)
store.set_value(itr, 0, icon)

View File

@@ -0,0 +1,3 @@
"""
Gtk Plugins DTO Module
"""

View File

@@ -0,0 +1,26 @@
# Python imports
from dataclasses import dataclass, field
from dataclasses import asdict
# Gtk imports
# Application imports
from .requests import Requests
@dataclass
class Manifest:
name: str = ""
author: str = ""
version: str = "0.0.1"
support: str = "support@mail.com"
pre_launch: bool = False
requests: Requests = field(default_factory = lambda: Requests())
def __post_init__(self):
if isinstance(self.requests, dict):
self.requests = Requests(**self.requests)
def as_dict(self):
return asdict(self)

View File

@@ -0,0 +1,19 @@
# Python imports
from dataclasses import dataclass, field
from dataclasses import asdict
# Gtk imports
# Application imports
from .manifest import Manifest
@dataclass
class ManifestMeta:
folder: str = ""
path: str = ""
manifest: Manifest = field(default_factory = lambda: Manifest())
def as_dict(self):
return asdict(self)

View File

@@ -0,0 +1,16 @@
# Python imports
from dataclasses import dataclass, field
# Lib imports
# Application imports
@dataclass
class Requests:
ui_target: str = ""
ui_target_id: str = ""
pass_events: bool = False
pass_fm_events: bool = False
pass_ui_objects: list = field(default_factory = lambda: [])
bind_keys: list = field(default_factory = lambda: [])

View File

@@ -1,101 +0,0 @@
# Python imports
import os
import json
from os.path import join
from dataclasses import dataclass
# Lib imports
# Application imports
class ManifestProcessorException(Exception):
...
@dataclass(slots = True)
class PluginInfo:
path: str = None
name: str = None
author: str = None
version: str = None
support: str = None
requests:{} = None
reference: type = None
pre_launch: bool = False
class ManifestProcessor:
def __init__(self, path, builder):
manifest_pth = join(path, "manifest.json")
if not os.path.exists(manifest_pth):
raise ManifestProcessorException("Invalid Plugin Structure: Plugin doesn't have 'manifest.json'. Aboarting load...")
self._path = path
self._builder = builder
with open(manifest_pth) as f:
data = json.load(f)
self._manifest = data["manifest"]
self._plugin = self.collect_info()
def is_pre_launch(self) -> bool:
return self._plugin.pre_launch
def collect_info(self) -> PluginInfo:
plugin = PluginInfo()
plugin.path = self._path
plugin.name = self._manifest["name"]
plugin.author = self._manifest["author"]
plugin.version = self._manifest["version"]
plugin.support = self._manifest["support"]
plugin.requests = self._manifest["requests"]
if "pre_launch" in self._manifest.keys():
plugin.pre_launch = True if self._manifest["pre_launch"] == "true" else False
return plugin
def get_loading_data(self):
loading_data = {}
requests = self._plugin.requests
if "ui_target" in requests:
if requests["ui_target"] in [
"none", "other", "main_Window", "main_menu_bar",
"main_menu_bttn_box_bar", "path_menu_bar", "plugin_control_list",
"context_menu", "context_menu_plugins", "window_1",
"window_2", "window_3", "window_4"
]:
if requests["ui_target"] == "other":
if "ui_target_id" in requests:
loading_data["ui_target"] = self._builder.get_object(requests["ui_target_id"])
if loading_data["ui_target"] == None:
raise ManifestProcessorException('Invalid "ui_target_id" given in requests. Must have one if setting "ui_target" to "other"...')
else:
raise ManifestProcessorException('Invalid "ui_target_id" given in requests. Must have one if setting "ui_target" to "other"...')
else:
loading_data["ui_target"] = self._builder.get_object(requests["ui_target"])
else:
raise ManifestProcessorException('Unknown "ui_target" given in requests.')
if "pass_fm_events" in requests:
if requests["pass_fm_events"] in ["true"]:
loading_data["pass_fm_events"] = True
if "pass_ui_objects" in requests:
if len(requests["pass_ui_objects"]) > 0:
loading_data["pass_ui_objects"] = []
for ui_id in requests["pass_ui_objects"]:
try:
loading_data["pass_ui_objects"].append( self._builder.get_object(ui_id) )
except ManifestProcessorException as e:
logger.error(repr(e))
if "bind_keys" in requests:
if isinstance(requests["bind_keys"], list):
loading_data["bind_keys"] = requests["bind_keys"]
return self._plugin, loading_data

View File

@@ -0,0 +1,68 @@
# Python imports
import os
import json
from os.path import join
# Lib imports
# Application imports
from .dto.manifest_meta import ManifestMeta
from .dto.manifest import Manifest
class ManifestMapperException(Exception):
...
class ManifestManager:
def __init__(self):
self._plugins_path = settings_manager.get_plugins_path()
self.pre_launch_manifests = []
self.post_launch_manifests = []
self.load_manifests()
def load_manifests(self):
logger.info(f"Loading manifests...")
for path, folder in [
[join(self._plugins_path, item), item]
if
os.path.isdir( join(self._plugins_path, item) )
else
None
for item in os.listdir(self._plugins_path)
]:
self.load(folder, path)
def load(self, folder, path):
manifest_pth = join(path, "manifest.json")
if not os.path.exists(manifest_pth):
raise ManifestMapperException("Invalid Plugin Structure: Plugin doesn't have 'manifest.json'. Aboarting load...")
with open(manifest_pth) as f:
data = json.load(f)
manifest = Manifest(**data)
manifest_meta = ManifestMeta()
manifest_meta.folder = folder
manifest_meta.path = path
manifest_meta.manifest = manifest
if manifest.pre_launch:
self.pre_launch_manifests.append(manifest_meta)
else:
self.post_launch_manifests.append(manifest_meta)
def get_pre_launch_manifests(self) -> dict:
return self.pre_launch_manifests
def get_post_launch_plugins(self) -> None:
return self.post_launch_manifests

View File

@@ -15,9 +15,9 @@ class PluginBaseException(Exception):
class PluginBase:
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.name = "Example Plugin" # NOTE: Need to remove after establishing private bidirectional 1-1 message bus
# where self.name should not be needed for message comms
self._builder = None
self._ui_objects = None
self._fm_state = None
@@ -47,6 +47,16 @@ class PluginBase:
"""
self._ui_objects = ui_objects
def set_event_system(self, event_system):
"""
Requests Key: 'pass_events': "true"
Must define in plugin if "pass_events" is set to "true" string.
"""
self._event_system = event_system
def subscribe_to_events(self):
self._event_system.subscribe("update_state_info_plugins", self._update_fm_state_info)
def set_fm_event_system(self, fm_event_system):
"""
Requests Key: 'pass_fm_events': "true"
@@ -54,9 +64,6 @@ class PluginBase:
"""
self._event_system = fm_event_system
def subscribe_to_events(self):
self._event_system.subscribe("update_state_info_plugins", self._update_fm_state_info)
def _update_fm_state_info(self, state):
self._fm_state = state

View File

@@ -0,0 +1,36 @@
# Python imports
# Lib imports
import gi
from gi.repository import Gio
# Application imports
class PluginReloadMixin:
_plugins_dir_watcher = None
def _set_plugins_watcher(self) -> None:
self._plugins_dir_watcher = Gio.File.new_for_path(
self._plugins_path
).monitor_directory(
Gio.FileMonitorFlags.WATCH_MOVES,
Gio.Cancellable()
)
self._plugins_dir_watcher.connect("changed", self._on_plugins_changed, ())
def _on_plugins_changed(self,
file_monitor, file,
other_file = None,
eve_type = None,
data = None
):
if eve_type in [Gio.FileMonitorEvent.CREATED, Gio.FileMonitorEvent.DELETED,
Gio.FileMonitorEvent.RENAMED, Gio.FileMonitorEvent.MOVED_IN,
Gio.FileMonitorEvent.MOVED_OUT]:
self.reload_plugins(file)
def reload_plugins(self, file: str = None) -> None:
logger.info(f"Reloading plugins... stub.")

View File

@@ -8,15 +8,12 @@ from os.path import isdir
# Lib imports
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import GLib
from gi.repository import Gio
# Application imports
from .manifest import PluginInfo
from .manifest import ManifestProcessor
from .dto.manifest_meta import ManifestMeta
from .plugin_reload_mixin import PluginReloadMixin
from .manifest_manager import ManifestManager
@@ -24,95 +21,62 @@ class InvalidPluginException(Exception):
...
class PluginsController:
class PluginsController(PluginReloadMixin):
"""PluginsController controller"""
def __init__(self):
path = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, path) # NOTE: I think I'm not using this correctly...
self._builder = settings_manager.get_builder()
self._plugins_path = settings_manager.get_plugins_path()
self._plugins_dir_watcher = None
self._plugin_collection = []
self._plugin_manifests = {}
self._load_manifests()
def _load_manifests(self):
logger.info(f"Loading manifests...")
for path, folder in [[join(self._plugins_path, item), item] if os.path.isdir(join(self._plugins_path, item)) else None for item in os.listdir(self._plugins_path)]:
manifest = ManifestProcessor(path, self._builder)
self._plugin_manifests[path] = {
"path": path,
"folder": folder,
"manifest": manifest
}
self._plugins_path = settings_manager.get_plugins_path()
self._builder = settings_manager.get_builder()
self._manifest_manager = ManifestManager()
self._load_plugins_path_to_sys()
self._set_plugins_watcher()
def _set_plugins_watcher(self) -> None:
self._plugins_dir_watcher = Gio.File.new_for_path(self._plugins_path) \
.monitor_directory(Gio.FileMonitorFlags.WATCH_MOVES, Gio.Cancellable())
self._plugins_dir_watcher.connect("changed", self._on_plugins_changed, ())
def _on_plugins_changed(self, file_monitor, file, other_file = None, eve_type = None, data = None):
if eve_type in [Gio.FileMonitorEvent.CREATED, Gio.FileMonitorEvent.DELETED,
Gio.FileMonitorEvent.RENAMED, Gio.FileMonitorEvent.MOVED_IN,
Gio.FileMonitorEvent.MOVED_OUT]:
self.reload_plugins(file)
def _load_plugins_path_to_sys(self) -> None:
path = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, path)
def pre_launch_plugins(self) -> None:
logger.info(f"Loading pre-launch plugins...")
plugin_manifests: {} = {}
for key in self._plugin_manifests:
target_manifest = self._plugin_manifests[key]["manifest"]
if target_manifest.is_pre_launch():
plugin_manifests[key] = self._plugin_manifests[key]
self._load_plugins(plugin_manifests, is_pre_launch = True)
manifest_metas: [] = self._manifest_manager.get_pre_launch_manifests()
self._load_plugins(manifest_metas, is_pre_launch = True)
def post_launch_plugins(self) -> None:
logger.info(f"Loading post-launch plugins...")
plugin_manifests: {} = {}
manifest_metas: [] = self._manifest_manager.get_post_launch_plugins()
self._load_plugins(manifest_metas)
for key in self._plugin_manifests:
target_manifest = self._plugin_manifests[key]["manifest"]
if not target_manifest.is_pre_launch():
plugin_manifests[key] = self._plugin_manifests[key]
self._load_plugins(plugin_manifests)
def _load_plugins(self, plugin_manifests: {} = {}, is_pre_launch: bool = False) -> None:
def _load_plugins(
self,
manifest_metas: [] = [],
is_pre_launch: bool = False
) -> None:
parent_path = os.getcwd()
for key in plugin_manifests:
target_manifest = plugin_manifests[key]
path, folder, manifest = target_manifest["path"], target_manifest["folder"], target_manifest["manifest"]
for manifest_meta in manifest_metas:
path, folder, manifest = manifest_meta.path, manifest_meta.folder, manifest_meta.manifest
try:
target = join(path, "plugin.py")
if not os.path.exists(target):
raise FileNotFoundError("Invalid Plugin Structure: Plugin doesn't have 'plugin.py'. Aboarting load...")
raise InvalidPluginException("Invalid Plugin Structure: Plugin doesn't have 'plugin.py'. Aboarting load...")
plugin, loading_data = manifest.get_loading_data()
module = self.load_plugin_module(path, folder, target)
module = self.load_plugin_module(path, folder, target)
if is_pre_launch:
self.execute_plugin(module, plugin, loading_data)
self.execute_plugin(module, manifest_meta)
else:
GLib.idle_add(self.execute_plugin, *(module, plugin, loading_data))
except InvalidPluginException as e:
GLib.idle_add(self.execute_plugin, module, manifest_meta)
except Exception as e:
logger.info(f"Malformed Plugin: Not loading -->: '{folder}' !")
logger.debug("Trace: ", traceback.print_exc())
os.chdir(parent_path)
def load_plugin_module(self, path, folder, target):
os.chdir(path)
@@ -126,41 +90,52 @@ class PluginsController:
return module
def collect_search_locations(self, path, locations):
def collect_search_locations(self, path: str, locations: list):
locations.append(path)
for file in os.listdir(path):
_path = os.path.join(path, file)
if os.path.isdir(_path):
self.collect_search_locations(_path, locations)
def execute_plugin(self, module: type, plugin: PluginInfo, loading_data: []):
plugin.reference = module.Plugin()
def execute_plugin(self, module: type, manifest_meta: ManifestMeta):
manifest_meta.instance = module.Plugin()
manifest = manifest_meta.manifest
if "ui_target" in loading_data:
loading_data["ui_target"].add( plugin.reference.generate_reference_ui_element() )
loading_data["ui_target"].show_all()
if manifest.requests.ui_target:
ui_target = manifest.requests.ui_target
ui_target_id = manifest.requests.ui_target_id
if "pass_ui_objects" in loading_data:
plugin.reference.set_ui_object_collection( loading_data["pass_ui_objects"] )
if not ui_target == "other":
ui_target = self._builder.get_object(ui_target)
else:
if not ui_target_id:
raise InvalidPluginException('Invalid "ui_target_id" given in requests. Must have one if setting "ui_target" to "other"...')
if "pass_fm_events" in loading_data:
plugin.reference.set_fm_event_system(event_system)
plugin.reference.subscribe_to_events()
ui_target = self._builder.get_object(ui_target_id)
if "bind_keys" in loading_data:
keybindings.append_bindings( loading_data["bind_keys"] )
if not ui_target:
raise InvalidPluginException('Unknown "ui_target" given in requests.')
plugin.reference.run()
self._plugin_collection.append(plugin)
ui_element = manifest_meta.instance.generate_reference_ui_element()
return False
ui_target.add(ui_element)
ui_target.show_all()
def reload_plugins(self, file: str = None) -> None:
logger.info(f"Reloading plugins...")
parent_path = os.getcwd()
if manifest.requests.pass_ui_objects:
manifest_meta.instance.set_ui_object_collection(
[ self._builder.get_object(obj) for obj in manifest.requests.pass_ui_objects ]
)
for plugin in self._plugin_collection:
os.chdir(plugin.path)
plugin.reference.reload_package(f"{plugin.path}/plugin.py")
if manifest.requests.pass_events:
manifest_meta.instance.set_event_system(event_system)
manifest_meta.instance.subscribe_to_events()
os.chdir(parent_path)
if manifest.requests.pass_fm_events:
manifest_meta.instance.set_event_system(event_system)
manifest_meta.instance.subscribe_to_events()
if manifest.requests.bind_keys:
keybindings.append_bindings( manifest.requests.bind_keys )
manifest_meta.instance.run()
self._plugin_collection.append(manifest_meta)