First structure #3

This commit is contained in:
Linuxero committed 2026-11-15 16:08:57 +01:00
commit 828534c1f5
15 files changed
+646

No files matched your search

+86
View File
@@ -0,0 +1,86 @@
# This file is used to ignore files which are generated
# ----------------------------------------------------------------------------
*~
*.autosave
*.a
*.core
*.moc
*.o
*.obj
*.orig
*.rej
*.so
*.so.*
*_pch.h.cpp
*_resource.rc
*.qm
.#*
*.*#
core
!core/
tags
.DS_Store
.directory
*.debug
Makefile*
*.prl
*.app
moc_*.cpp
ui_*.h
qrc_*.cpp
Thumbs.db
*.res
*.rc
/.qmake.cache
/.qmake.stash
# qtcreator generated files
*.pro.user*
*.qbs.user*
CMakeLists.txt.user*
.qtcreator/
.venv/
.pytest_cache
uv.lock
# xemacs temporary files
*.flc
# Vim temporary files
.*.swp
# Visual Studio generated files
*.ib_pdb_index
*.idb
*.ilk
*.pdb
*.sln
*.suo
*.vcproj
*vcproj.*.*.user
*.ncb
*.sdf
*.opensdf
*.vcxproj
*vcxproj.*
# MinGW generated files
*.Debug
*.Release
# Python byte code
*.pyc
# Binaries
# --------
*.dll
*.exe
# Directories with generated files
.moc/
.obj/
.pch/
.rcc/
.uic/
/build*/
+16
View File
@@ -0,0 +1,16 @@
PROJECT_NAME = "Mageia Linux Control Center"
PROJECT_BRIEF = "GUI and TUI system control center for Mageia Linux"
OUTPUT_DIRECTORY = build/docs
INPUT = src docs
FILE_PATTERNS = *.py *.md
RECURSIVE = YES
EXTRACT_ALL = YES
EXTRACT_PRIVATE = YES
HIDE_UNDOC_MEMBERS = NO
WARNINGS = YES
WARN_IF_UNDOCUMENTED = YES
GENERATE_HTML = YES
GENERATE_LATEX = NO
MARKDOWN_SUPPORT = YES
PYTHON_DOCSTRING = YES
QUIET = NO
+101
View File
@@ -0,0 +1,101 @@
# Mageia Linux Control Center — Project Plan
## Goals
Build a Mageia-focused control center with:
- A GUI using QML and PySide6
- A compact TUI using Textual
- Shared core logic, plugin metadata, and system-operation interfaces
- Package-managed plugin discovery without scanning directories
- Narrowly authorized system changes through D-Bus and PolicyKit
- Localization, RTL support, accessibility, and an ASCII-safe TUI mode
## Architecture
### Shared core
Provide common interfaces for:
- Plugin metadata and registry
- Navigation state
- Localization
- Authorization client
- System-operation client
- Validation and error reporting
Keep frontend views separate: share business logic and APIs, not QML and Textual widgets.
### GUI
Use QML for presentation and PySide6 for application logic. The main window should have:
- A persistent header with back navigation and page title
- A resizable left category panel and right content panel
- A landing view organized as Category → Subcategory → Plugin
- Plugin content that fills the right panel while the header and category panel remain
- Light and dark palettes, keyboard navigation, visible focus, and accessible labels
- Layouts that use logical leading/trailing alignment for RTL
### TUI
Use Textual in a bounded, panel-style interface rather than assuming it can take over the entire terminal. Include category navigation, plugin content, back navigation, and a clear exit action.
Provide two display modes:
- **Unicode mode:** normal translated text and supported Unicode decoration.
- **ASCII mode:** ASCII-only borders, arrows, bullets, status markers, and fallback icons.
Allow users to force ASCII mode. If terminal encoding or glyph support is uncertain, prefer ASCII decoration. Do not make color or special characters the only way to convey information. Test narrow terminals, ASCII locales, no-color environments, and Unicode/RTL text.
## Security and PolicyKit
Keep the GUI and TUI unprivileged. Use a small system D-Bus service for privileged operations.
- Define distinct PolicyKit actions for specific operations.
- Enforce authorization and validate inputs in the service, not only in the UI.
- Configure any root or `wheel` access explicitly in policy; do not assume group membership grants permission.
- Avoid arbitrary shell commands and user-controlled paths.
- Keep the privileged service and its dependencies minimal.
- Never load plugin code from user-writable locations into the privileged service.
## Plugin model
Use package-managed manifests registered through a well-known system registry. The application queries that registry rather than scanning plugin directories.
A manifest should include:
- Stable plugin ID and API version
- Name and description
- Category and subcategory IDs
- Supported frontends
- Package/version compatibility
- Declared capabilities and required operations
Mageia packages should install, upgrade, and remove plugins and their dependencies. Begin with trusted Mageia-packaged plugins. Define signing, provenance, and permission rules before considering third-party plugins.
## Packaging and Python
- Provide a locked virtual environment for development.
- Use Mageia packages for system deployment and dependencies.
- Package the core, frontends, D-Bus service, PolicyKit actions, and plugins as clearly scoped components.
- Do not run privileged code from a mutable virtual environment or user-writable plugin path.
## Localization and resources
- Keep images, icons, and translation catalogs in package-owned resources.
- Establish a translation workflow covering QML, Python, and Textual strings.
- Keep stable IDs separate from translated labels.
- Test RTL layout, navigation, alignment, and back behavior in both frontends.
## Delivery phases
1. **Design:** threat model, privilege boundaries, plugin API, registry choice, and UI flows.
2. **Skeleton:** shared core, registry prototype, package layout, and mock plugins.
3. **Security path:** D-Bus service, PolicyKit actions, input validation, and authorization tests.
4. **GUI shell:** navigation, splitter, themes, and plugin content container.
5. **TUI shell:** bounded layout, ASCII/Unicode modes, and keyboard navigation.
6. **Initial plugins:** start with read-only modules, then add narrowly scoped write operations.
7. **Quality:** localization, RTL, accessibility, failure handling, and integration tests.
8. **Release:** Mageia packages, documentation, and upgrade/removal validation.
## Acceptance checks
- Plugin discovery works through the registry without directory scanning.
- Authorization is enforced by the privileged service for every protected operation.
- GUI resizing, back navigation, keyboard access, themes, localization, and RTL work.
- TUI remains understandable in ASCII mode, without color, and at narrow widths.
- Plugin installation, upgrade, and removal leave the registry in a consistent state.
- Denied, cancelled, malformed, unavailable, and failed operations produce clear messages.
+3
View File
@@ -0,0 +1,3 @@
# Mageia Linux Control Center
A Mageia-focused control center with GUI and TUI frontends.
+11
View File
@@ -0,0 +1,11 @@
# Contributing
## Development environment
Create and activate a virtual environment from the repository root:
```bash
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install -e ".[dev]"
+37
View File
@@ -0,0 +1,37 @@
# Architecture
## Components
The application consists of four components:
1. **Core:** Shared data models, plugin metadata validation, navigation
contracts, and frontend-independent application logic.
2. **GUI:** QML presentation with PySide6 integration.
3. **TUI:** Textual presentation, including a user-selectable ASCII-safe mode.
4. **Privileged service:** A system D-Bus service that exposes specific
operations and checks PolicyKit authorization.
The GUI and TUI run as the logged-in user. They do not run as root.
## Plugin discovery
Plugins are installed and removed by Mageia packages. Each package installs
a declarative manifest into a package-managed registry location. The
application reads registered manifests; it does not recursively scan a
plugin directory.
The initial implementation should validate manifests and list plugins
before loading plugin code or performing system operations.
## Privileged operations
Only the D-Bus service performs operations that require elevation. It
validates every request and applies the relevant PolicyKit authorization
check. Frontend checks are for usability and do not replace service-side
authorization.
## Frontends
The GUI and TUI have independent presentation code and share core models
and service interfaces. A plugin may provide separate GUI and TUI views,
but both use the same declared metadata and operation contracts.
+9
View File
@@ -0,0 +1,9 @@
# This Python file uses the following encoding: utf-8
import sys
from PySide6.QtWidgets import QApplication
if __name__ == "__main__":
app = QApplication(sys.argv)
# ...
sys.exit(app.exec())
+11
View File
@@ -0,0 +1,11 @@
{
"schema_version": 1,
"id": "org.mageia.mcc.example-readonly",
"api_version": "1",
"name": "Example",
"description": "An example read-only control-center plugin.",
"category": "system",
"subcategory": "information",
"frontends": ["gui", "tui"],
"capabilities": ["read-only"]
}
+27
View File
@@ -0,0 +1,27 @@
[project]
name = "mageia-control-center"
version = "0.1.0"
description = "GUI and TUI control center for Mageia Linux"
readme = "README.md"
requires-python = ">=3.13"
dependencies = []
[build-system]
requires = ["uv_build>=0.13.8,<0.14"]
build-backend = "uv_build"
[tool.pyside6-project]
files = ["Doxyfile", "README.md", "docs/CONTRIBUTING.md", "docs/architecture.md", "main.py", "plugins/example-readonly/plugin.json", "src/mcc/__init__.py", "src/mcc/core/__init__.py", "src/mcc/core/plugin_manifest.py", "src/mcc/core/plugin_registry.py", "tests/test_plugin_registry.py"]
[tool.uv.build-backend]
module-name = "mcc"
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-ra"
[dependency-groups]
dev = [
"pytest>=8",
]
+1
View File
@@ -0,0 +1 @@
PySide6
+4
View File
@@ -0,0 +1,4 @@
# This Python file uses the following encoding: utf-8
# if __name__ == "__main__":
# pass
+4
View File
@@ -0,0 +1,4 @@
# This Python file uses the following encoding: utf-8
# if __name__ == "__main__":
# pass
+104
View File
@@ -0,0 +1,104 @@
"""Plugin manifest data model and validation."""
from __future__ import annotations
from dataclasses import dataclass
import json
from pathlib import Path
from typing import Any
@dataclass(frozen=True)
class PluginManifest:
"""Metadata declared by an installed control-center plugin.
Attributes:
schema_version: Version of the manifest's data format.
plugin_id: Stable, reverse-domain-style plugin identifier.
api_version: Version of the plugin API supported by the plugin.
name: User-visible plugin name.
description: Short user-visible description.
category: Stable category identifier.
subcategory: Stable subcategory identifier.
frontends: Frontends for which the plugin provides a view.
capabilities: Declared capabilities, such as ``read-only``.
"""
schema_version: int
plugin_id: str
api_version: str
name: str
description: str
category: str
subcategory: str
frontends: tuple[str, ...]
capabilities: tuple[str, ...]
@classmethod
def from_file(cls, path: Path) -> PluginManifest:
"""Load and validate a manifest from a package-owned JSON file.
Args:
path: Path to the manifest registered by the package manager.
Returns:
A validated plugin manifest.
Raises:
ValueError: If the file is invalid or required fields are missing.
OSError: If the manifest cannot be read.
"""
try:
data: Any = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise ValueError(f"Invalid JSON in plugin manifest: {path}") from exc
if not isinstance(data, dict):
raise ValueError("Plugin manifest must contain a JSON object.")
required = {
"schema_version",
"id",
"api_version",
"name",
"description",
"category",
"subcategory",
"frontends",
"capabilities",
}
missing = required - data.keys()
if missing:
raise ValueError(f"Plugin manifest is missing fields: {sorted(missing)}")
if data["schema_version"] != 1:
raise ValueError("Unsupported plugin manifest schema version.")
for field in ("frontends", "capabilities"):
if not isinstance(data[field], list) or not all(
isinstance(item, str) for item in data[field]
):
raise ValueError(f"'{field}' must be a list of strings.")
string_fields = (
"id",
"api_version",
"name",
"description",
"category",
"subcategory",
)
if any(not isinstance(data[field], str) or not data[field] for field in string_fields):
raise ValueError("Plugin string fields must be non-empty strings.")
return cls(
schema_version=data["schema_version"],
plugin_id=data["id"],
api_version=data["api_version"],
name=data["name"],
description=data["description"],
category=data["category"],
subcategory=data["subcategory"],
frontends=tuple(data["frontends"]),
capabilities=tuple(data["capabilities"]),
)
+128
View File
@@ -0,0 +1,128 @@
"""Plugin registry interfaces and manifest lookup.
The registry provider supplies explicitly registered plugin entries. This
module validates those entries and does not scan plugin directories.
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol
from mcc.core.plugin_manifest import PluginManifest
@dataclass(frozen=True)
class RegistryEntry:
"""A plugin manifest supplied by the configured registry.
Attributes:
plugin_id: Stable identifier expected in the manifest.
manifest_path: Path to the package-owned manifest.
"""
plugin_id: str
manifest_path: str
class RegistryProvider(Protocol):
"""Supplies registered plugin entries without directory discovery.
Implementations may read a package-maintained index or query a dedicated
system registry service. They must not recursively scan plugin folders.
"""
def entries(self) -> list[RegistryEntry]:
"""Return the registry's explicitly registered plugin entries."""
@dataclass(frozen=True)
class PluginLoadError:
"""Describes a plugin entry that could not be loaded.
Attributes:
plugin_id: Identifier from the registry, if available.
message: Explanation of why the entry could not be loaded.
"""
plugin_id: str
message: str
@dataclass(frozen=True)
class RegistryResult:
"""Result of loading registered plugins.
Attributes:
plugins: Successfully validated plugin manifests.
errors: Entries that were invalid or could not be read.
"""
plugins: tuple[PluginManifest, ...]
errors: tuple[PluginLoadError, ...]
class PluginRegistry:
"""Loads and validates plugin manifests from an explicit provider."""
def __init__(self, provider: RegistryProvider) -> None:
"""Initialize the registry.
Args:
provider: Source of explicitly registered plugin entries.
"""
self._provider = provider
def load(self) -> RegistryResult:
"""Load valid manifests and collect errors without aborting.
The provider determines how entries are registered. This method
never searches a directory. A malformed plugin does not prevent
other registered plugins from appearing.
Returns:
Successfully loaded plugins and per-entry errors.
"""
plugins: list[PluginManifest] = []
errors: list[PluginLoadError] = []
seen_ids: set[str] = set()
for entry in self._provider.entries():
if entry.plugin_id in seen_ids:
errors.append(
PluginLoadError(
plugin_id=entry.plugin_id,
message="Duplicate plugin identifier in registry.",
)
)
continue
seen_ids.add(entry.plugin_id)
try:
manifest = PluginManifest.from_file(Path(entry.manifest_path))
except (OSError, ValueError) as exc:
errors.append(
PluginLoadError(
plugin_id=entry.plugin_id,
message=str(exc),
)
)
continue
if manifest.plugin_id != entry.plugin_id:
errors.append(
PluginLoadError(
plugin_id=entry.plugin_id,
message="Registry ID does not match manifest ID.",
)
)
continue
plugins.append(manifest)
return RegistryResult(
plugins=tuple(plugins),
errors=tuple(errors),
)
+104
View File
@@ -0,0 +1,104 @@
"""Tests for explicit plugin registry loading."""
import json
from pathlib import Path
from mcc.core.plugin_registry import (
PluginRegistry,
RegistryEntry,
)
class FakeProvider:
"""Test provider that returns a fixed list of registered entries."""
def __init__(self, registered_entries: list[RegistryEntry]) -> None:
"""Store entries for later retrieval.
Args:
registered_entries: Entries the fake registry should return.
"""
self._registered_entries = registered_entries
def entries(self) -> list[RegistryEntry]:
"""Return the configured entries."""
return self._registered_entries
def write_manifest(path: Path, plugin_id: str) -> None:
"""Write a minimal valid test manifest.
Args:
path: Destination file.
plugin_id: Stable identifier to write into the manifest.
"""
path.write_text(
json.dumps(
{
"schema_version": 1,
"id": plugin_id,
"api_version": "1",
"name": "Example",
"description": "Test plugin.",
"category": "system",
"subcategory": "information",
"frontends": ["gui", "tui"],
"capabilities": ["read-only"],
}
),
encoding="utf-8",
)
def test_registry_loads_registered_plugin(tmp_path: Path) -> None:
"""A valid explicitly registered plugin should be returned."""
plugin_id = "org.mageia.mcc.example"
manifest_path = tmp_path / "plugin.json"
write_manifest(manifest_path, plugin_id)
provider = FakeProvider(
[RegistryEntry(plugin_id=plugin_id, manifest_path=str(manifest_path))]
)
result = PluginRegistry(provider).load()
assert len(result.plugins) == 1
assert result.plugins[0].plugin_id == plugin_id
assert result.errors == ()
def test_registry_reports_missing_manifest(tmp_path: Path) -> None:
"""A missing manifest should produce an error without crashing."""
provider = FakeProvider(
[
RegistryEntry(
plugin_id="org.mageia.mcc.missing",
manifest_path=str(tmp_path / "missing.json"),
)
]
)
result = PluginRegistry(provider).load()
assert result.plugins == ()
assert len(result.errors) == 1
def test_registry_rejects_id_mismatch(tmp_path: Path) -> None:
"""A manifest cannot claim an ID different from its registry entry."""
manifest_path = tmp_path / "plugin.json"
write_manifest(manifest_path, "org.mageia.mcc.actual")
provider = FakeProvider(
[
RegistryEntry(
plugin_id="org.mageia.mcc.expected",
manifest_path=str(manifest_path),
)
]
)
result = PluginRegistry(provider).load()
assert result.plugins == ()
assert "does not match" in result.errors[0].message