Moved code up one level post build folder creation
This commit is contained in:
3
src/plugins/__init__.py
Normal file
3
src/plugins/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
"""
|
||||
Gtk Bound Plugins Module
|
||||
"""
|
||||
3
src/plugins/dto/__init__.py
Normal file
3
src/plugins/dto/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
"""
|
||||
Gtk Plugins DTO Module
|
||||
"""
|
||||
26
src/plugins/dto/manifest.py
Normal file
26
src/plugins/dto/manifest.py
Normal 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)
|
||||
19
src/plugins/dto/manifest_meta.py
Normal file
19
src/plugins/dto/manifest_meta.py
Normal 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)
|
||||
16
src/plugins/dto/requests.py
Normal file
16
src/plugins/dto/requests.py
Normal 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: [])
|
||||
68
src/plugins/manifest_manager.py
Normal file
68
src/plugins/manifest_manager.py
Normal 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
|
||||
|
||||
103
src/plugins/plugin_base.py
Normal file
103
src/plugins/plugin_base.py
Normal file
@@ -0,0 +1,103 @@
|
||||
# Python imports
|
||||
import os
|
||||
import time
|
||||
import inspect
|
||||
|
||||
# Lib imports
|
||||
|
||||
# Application imports
|
||||
|
||||
|
||||
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
|
||||
self._event_system = None
|
||||
|
||||
|
||||
def run(self):
|
||||
"""
|
||||
Must define regardless if needed and can 'pass' if plugin doesn't need it.
|
||||
Is intended to be used to setup internal signals or custom Gtk Builders/UI logic.
|
||||
"""
|
||||
raise PluginBaseException("Method hasn't been overriden...")
|
||||
|
||||
def generate_reference_ui_element(self):
|
||||
"""
|
||||
Requests Key: 'ui_target': "plugin_control_list",
|
||||
Must define regardless if needed and can 'pass' if plugin doesn't use it.
|
||||
Must return a widget if "ui_target" is set.
|
||||
"""
|
||||
raise PluginBaseException("Method hasn't been overriden...")
|
||||
|
||||
def set_ui_object_collection(self, ui_objects):
|
||||
"""
|
||||
Requests Key: "pass_ui_objects": [""]
|
||||
Request reference to a UI component. Will be passed back as array to plugin.
|
||||
Must define in plugin if set and an array of valid glade UI IDs is given.
|
||||
"""
|
||||
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"
|
||||
Must define in plugin if "pass_fm_events" is set to "true" string.
|
||||
"""
|
||||
self._event_system = fm_event_system
|
||||
|
||||
def _update_fm_state_info(self, state):
|
||||
self._fm_state = state
|
||||
|
||||
def _connect_builder_signals(self, caller_class, builder):
|
||||
classes = [caller_class]
|
||||
handlers = {}
|
||||
for c in classes:
|
||||
methods = None
|
||||
try:
|
||||
methods = inspect.getmembers(c, predicate=inspect.ismethod)
|
||||
handlers.update(methods)
|
||||
except Exception as e:
|
||||
logger.debug(repr(e))
|
||||
|
||||
builder.connect_signals(handlers)
|
||||
|
||||
def reload_package(self, plugin_path, module_dict_main=locals()):
|
||||
import importlib
|
||||
from pathlib import Path
|
||||
|
||||
def reload_package_recursive(current_dir, module_dict):
|
||||
for path in current_dir.iterdir():
|
||||
if "__init__" in str(path) or path.stem not in module_dict:
|
||||
continue
|
||||
|
||||
if path.is_file() and path.suffix == ".py":
|
||||
importlib.reload(module_dict[path.stem])
|
||||
elif path.is_dir():
|
||||
reload_package_recursive(path, module_dict[path.stem].__dict__)
|
||||
|
||||
reload_package_recursive(Path(plugin_path).parent, module_dict_main["module_dict_main"])
|
||||
|
||||
|
||||
def clear_children(self, widget: type) -> None:
|
||||
""" Clear children of a gtk widget. """
|
||||
for child in widget.get_children():
|
||||
widget.remove(child)
|
||||
36
src/plugins/plugin_reload_mixin.py
Normal file
36
src/plugins/plugin_reload_mixin.py
Normal 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.")
|
||||
141
src/plugins/plugins_controller.py
Normal file
141
src/plugins/plugins_controller.py
Normal file
@@ -0,0 +1,141 @@
|
||||
# Python imports
|
||||
import os
|
||||
import sys
|
||||
import importlib
|
||||
import traceback
|
||||
from os.path import join
|
||||
from os.path import isdir
|
||||
|
||||
# Lib imports
|
||||
import gi
|
||||
from gi.repository import GLib
|
||||
|
||||
# Application imports
|
||||
from .dto.manifest_meta import ManifestMeta
|
||||
from .plugin_reload_mixin import PluginReloadMixin
|
||||
from .manifest_manager import ManifestManager
|
||||
|
||||
|
||||
|
||||
class InvalidPluginException(Exception):
|
||||
...
|
||||
|
||||
|
||||
|
||||
class PluginsController(PluginReloadMixin):
|
||||
"""PluginsController controller"""
|
||||
|
||||
def __init__(self):
|
||||
self._plugin_collection = []
|
||||
|
||||
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 _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...")
|
||||
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...")
|
||||
manifest_metas: [] = self._manifest_manager.get_post_launch_plugins()
|
||||
self._load_plugins(manifest_metas)
|
||||
|
||||
def _load_plugins(
|
||||
self,
|
||||
manifest_metas: [] = [],
|
||||
is_pre_launch: bool = False
|
||||
) -> None:
|
||||
parent_path = os.getcwd()
|
||||
|
||||
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 InvalidPluginException("Invalid Plugin Structure: Plugin doesn't have 'plugin.py'. Aboarting load...")
|
||||
|
||||
module = self.load_plugin_module(path, folder, target)
|
||||
|
||||
if is_pre_launch:
|
||||
self.execute_plugin(module, manifest_meta)
|
||||
else:
|
||||
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)
|
||||
|
||||
locations = []
|
||||
self.collect_search_locations(path, locations)
|
||||
|
||||
spec = importlib.util.spec_from_file_location(folder, target, submodule_search_locations = locations)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules[folder] = module
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
return module
|
||||
|
||||
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, manifest_meta: ManifestMeta):
|
||||
manifest_meta.instance = module.Plugin()
|
||||
manifest = manifest_meta.manifest
|
||||
|
||||
if manifest.requests.ui_target:
|
||||
ui_target = manifest.requests.ui_target
|
||||
ui_target_id = manifest.requests.ui_target_id
|
||||
|
||||
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"...')
|
||||
|
||||
ui_target = self._builder.get_object(ui_target_id)
|
||||
|
||||
if not ui_target:
|
||||
raise InvalidPluginException('Unknown "ui_target" given in requests.')
|
||||
|
||||
ui_element = manifest_meta.instance.generate_reference_ui_element()
|
||||
|
||||
ui_target.add(ui_element)
|
||||
ui_target.show_all()
|
||||
|
||||
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 ]
|
||||
)
|
||||
|
||||
if manifest.requests.pass_events:
|
||||
manifest_meta.instance.set_event_system(event_system)
|
||||
manifest_meta.instance.subscribe_to_events()
|
||||
|
||||
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)
|
||||
Reference in New Issue
Block a user