Update to v0.1.4-alpha
- Remove internal test plugin. - Add Quilt mod loader support. - Add support for pretty output (To use it, enable the plugin "PrettyLog") - Add launch/progress_log apis. - Update some missing translations. CoreLib update to 0.1.7
This commit is contained in:
1 parent
8316722169
commit
01c488d471
30 files changed
+826
-99
No files matched your search
@@ -0,0 +1,10 @@
|
||||
from TapLauncher import PluginContext
|
||||
from .log4j import Log4jPlugin
|
||||
|
||||
def entry(context: PluginContext) -> None:
|
||||
plugin = Log4jPlugin(context)
|
||||
context.on_cleanup(plugin.cleanup)
|
||||
context.override_api("launcher.game.launch.extra_arguments", plugin.extra_arguments)
|
||||
context.override_api("launcher.process_log.output", plugin.output)
|
||||
context.override_api("launcher.process_log.create_widget", plugin.create_widget)
|
||||
context.logger.info("Log4j hooks initialized")
|
||||
@@ -0,0 +1,209 @@
|
||||
"""Official Log4j configuration and streaming console XML support."""
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
import tempfile
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from weakref import WeakKeyDictionary, WeakSet
|
||||
from xml.etree import ElementTree as ET
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
MAX_CONFIG_BYTES = 1024 * 1024
|
||||
MAX_EVENT_CHARS = 1024 * 1024
|
||||
EVENT_START = re.compile(r"<(?:log4j:)?Event\b")
|
||||
EVENT_END = re.compile(r"</(?:log4j:)?Event\s*>|<!\[CDATA\[|<!--")
|
||||
|
||||
|
||||
def _event_end(text: str) -> int | None:
|
||||
"""Locate the closing tag without treating CDATA/message text as markup."""
|
||||
offset = 0
|
||||
while match := EVENT_END.search(text, offset):
|
||||
if match.group().startswith("</"):
|
||||
return match.end()
|
||||
terminator = "]]>" if match.group() == "<![CDATA[" else "-->"
|
||||
end = text.find(terminator, match.end())
|
||||
if end < 0:
|
||||
return None
|
||||
offset = end + len(terminator)
|
||||
return None
|
||||
|
||||
|
||||
def _local_name(tag: str) -> str:
|
||||
return tag.rsplit("}", 1)[-1]
|
||||
|
||||
|
||||
def _format_event(xml: str) -> list[tuple[str, str]]:
|
||||
# Minecraft's LegacyXMLLayout emits log4j-prefixed fragments without a root.
|
||||
if "<!DOCTYPE" in xml.upper() or "<!ENTITY" in xml.upper():
|
||||
raise ValueError("Unsupported XML declaration in log event")
|
||||
root = ET.fromstring('<root xmlns:log4j="http://jakarta.apache.org/log4j/">' + xml + "</root>")
|
||||
event = root[0]
|
||||
level = event.get("level", "INFO").upper()
|
||||
thread = event.get("thread", "unknown")
|
||||
logger = event.get("logger", event.get("loggerName", ""))
|
||||
timestamp = event.get("timestamp", event.get("timeMillis"))
|
||||
time_text = ""
|
||||
if timestamp is not None:
|
||||
try:
|
||||
time_text = "[" + datetime.fromtimestamp(int(timestamp) / 1000).strftime("%H:%M:%S") + "] "
|
||||
except (ValueError, OverflowError, OSError):
|
||||
pass
|
||||
prefix = f"{time_text}[{thread}/{level}] "
|
||||
if logger:
|
||||
prefix += f"[{logger}] "
|
||||
messages = []
|
||||
throwables = []
|
||||
for child in event:
|
||||
name = _local_name(child.tag).lower()
|
||||
if name == "message":
|
||||
messages.append("".join(child.itertext()))
|
||||
elif name == "throwable":
|
||||
content = "".join(child.itertext()).strip()
|
||||
if content:
|
||||
throwables.append(content)
|
||||
message = "\n".join(messages)
|
||||
if throwables:
|
||||
message += ("\n" if message else "") + "\n".join(throwables)
|
||||
return [(level, prefix + message)]
|
||||
|
||||
|
||||
class LogParser:
|
||||
def __init__(self, source: str):
|
||||
self.raw_type = "error" if source == "stderr" else "normal"
|
||||
self.pending = ""
|
||||
|
||||
def _raw(self, text: str) -> list[tuple[str, str]]:
|
||||
return [(self.raw_type, line) for line in text.splitlines()]
|
||||
|
||||
def feed(self, text: str | None) -> list[tuple[str, str]]:
|
||||
if text is None:
|
||||
pending, self.pending = self.pending, ""
|
||||
return self._raw(pending)
|
||||
if not self.pending and not EVENT_START.search(text):
|
||||
return [(self.raw_type, text)]
|
||||
self.pending += text + "\n"
|
||||
output = []
|
||||
while self.pending:
|
||||
start = EVENT_START.search(self.pending)
|
||||
if start is None:
|
||||
output.extend(self._raw(self.pending))
|
||||
self.pending = ""
|
||||
break
|
||||
prefix, self.pending = self.pending[:start.start()], self.pending[start.start():]
|
||||
if prefix.strip():
|
||||
output.extend(self._raw(prefix))
|
||||
end = _event_end(self.pending)
|
||||
if end is None:
|
||||
if len(self.pending) > MAX_EVENT_CHARS:
|
||||
output.extend(self._raw(self.pending))
|
||||
self.pending = ""
|
||||
break
|
||||
xml, self.pending = self.pending[:end], self.pending[end:]
|
||||
# The newline emitted after an XML fragment is a delimiter.
|
||||
self.pending = self.pending.removeprefix("\r\n").removeprefix("\n")
|
||||
try:
|
||||
output.extend(_format_event(xml))
|
||||
except (ET.ParseError, ValueError):
|
||||
output.extend(self._raw(xml))
|
||||
return output
|
||||
|
||||
|
||||
class Log4jPlugin:
|
||||
def __init__(self, context):
|
||||
self.context = context
|
||||
self.parsers = WeakKeyDictionary()
|
||||
self.windows = WeakSet()
|
||||
self._download_lock = threading.Lock()
|
||||
|
||||
def extra_arguments(self, profile, version_manifest: dict) -> dict[str, list[str]]:
|
||||
logging = version_manifest.get("logging", {}).get("client")
|
||||
if not logging:
|
||||
return {"jvm": [], "game": []}
|
||||
if logging.get("type") != "log4j2-xml":
|
||||
self.context.logger.warning("Unsupported client logging type: %s", logging.get("type"))
|
||||
return {"jvm": [], "game": []}
|
||||
path = self._prepare_config(logging["file"])
|
||||
argument = logging["argument"]
|
||||
if not isinstance(argument, str) or "${path}" not in argument:
|
||||
raise ValueError("Invalid client logging argument")
|
||||
# A Windows drive prefix (C:/...) can be interpreted as a URI scheme.
|
||||
# Use an explicit file URI, including escaping spaces and Unicode.
|
||||
return {"jvm": [argument.replace("${path}", path.as_uri())], "game": []}
|
||||
|
||||
def _prepare_config(self, file: dict) -> Path:
|
||||
sha1 = file["sha1"].lower()
|
||||
if re.fullmatch(r"[0-9a-f]{40}", sha1) is None:
|
||||
raise ValueError("Invalid client logging SHA-1")
|
||||
expected_size = file["size"]
|
||||
if not isinstance(expected_size, int) or not 0 < expected_size <= MAX_CONFIG_BYTES:
|
||||
raise ValueError("Invalid client logging configuration size")
|
||||
# Content-addressed paths also avoid trusting a manifest filename as a path.
|
||||
path = (Path(self.context.data_dir) / "log_configs" / sha1 / "client.xml").resolve()
|
||||
|
||||
def verified(data):
|
||||
return len(data) == expected_size and hashlib.sha1(data).hexdigest() == sha1
|
||||
|
||||
with self._download_lock:
|
||||
if path.is_file() and path.stat().st_size == expected_size and verified(path.read_bytes()):
|
||||
return path
|
||||
data = bytearray()
|
||||
with requests.get(file["url"], stream=True, timeout=(10, 30)) as response:
|
||||
response.raise_for_status()
|
||||
for chunk in response.iter_content(8192):
|
||||
data.extend(chunk)
|
||||
if len(data) > expected_size:
|
||||
raise ValueError("Client logging configuration exceeds expected size")
|
||||
if not verified(data):
|
||||
raise ValueError("Client logging configuration size or SHA-1 mismatch")
|
||||
ET.fromstring(data) # Fail before launching if the configuration is invalid XML.
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as stream:
|
||||
temporary = Path(stream.name)
|
||||
stream.write(data)
|
||||
temporary.replace(path)
|
||||
finally:
|
||||
if temporary is not None:
|
||||
temporary.unlink(missing_ok=True)
|
||||
return path
|
||||
|
||||
def create_widget(self, window):
|
||||
from .log_widget import ColoredLogOutput
|
||||
|
||||
self.windows.add(window)
|
||||
return ColoredLogOutput(window)
|
||||
|
||||
def output(self, window, source: str, text: str | None) -> list[tuple[str, str]]:
|
||||
from .log_widget import ColoredLogOutput
|
||||
|
||||
# Also upgrade windows that were opened before the plugin was enabled.
|
||||
if hasattr(window, "set_output_widget") and not isinstance(window.log_output, ColoredLogOutput):
|
||||
window.set_output_widget(self.create_widget(window))
|
||||
streams = self.parsers.setdefault(window, {})
|
||||
parser = streams.setdefault(source, LogParser(source))
|
||||
events = parser.feed(text)
|
||||
if text is None:
|
||||
streams.pop(source, None)
|
||||
if not streams:
|
||||
self.parsers.pop(window, None)
|
||||
return events
|
||||
|
||||
def cleanup(self):
|
||||
# Overrides are restored before this callback by Wheel's reverse cleanup.
|
||||
for window, streams in list(self.parsers.items()):
|
||||
for parser in streams.values():
|
||||
for line_type, message in parser.feed(None):
|
||||
window._append_output(line_type, message)
|
||||
self.parsers.clear()
|
||||
from .log_widget import ColoredLogOutput
|
||||
from pages.process_log import create_process_log_widget
|
||||
|
||||
for window in list(self.windows):
|
||||
if isinstance(window.log_output, ColoredLogOutput):
|
||||
window.set_output_widget(create_process_log_widget(window))
|
||||
self.windows.clear()
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Plain-text log viewer with severity colors and no HTML interpretation."""
|
||||
|
||||
import re
|
||||
|
||||
from PySide6.QtGui import QColor, QPalette, QTextCharFormat, QTextCursor
|
||||
from PySide6.QtWidgets import QPlainTextEdit
|
||||
|
||||
|
||||
class ColoredLogOutput(QPlainTextEdit):
|
||||
DARK_COLORS = {
|
||||
"TRACE": "#9299a5", "DEBUG": "#93a8c4", "INFO": "#8ed49f",
|
||||
"WARN": "#f2c66d", "WARNING": "#f2c66d", "ERROR": "#ff8585", "FATAL": "#f099d7",
|
||||
}
|
||||
LIGHT_COLORS = {
|
||||
"TRACE": "#616977", "DEBUG": "#405e91", "INFO": "#24713a",
|
||||
"WARN": "#946000", "WARNING": "#946000", "ERROR": "#bc2424", "FATAL": "#952278",
|
||||
}
|
||||
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self._has_entries = False
|
||||
|
||||
def append_log_entry(self, line_type: str, message: str) -> None:
|
||||
level = line_type.upper()
|
||||
if line_type in {"normal", "error"}:
|
||||
match = re.search(r"\[[^\]\n]*/(TRACE|DEBUG|INFO|WARN|ERROR|FATAL)\]", message)
|
||||
warning = re.match(r"^(WARNING|WARN|ERROR|FATAL):", message)
|
||||
if match or warning:
|
||||
level = (match or warning).group(1)
|
||||
colors = (self.LIGHT_COLORS if self.palette().color(QPalette.ColorRole.Base).lightness() > 128
|
||||
else self.DARK_COLORS)
|
||||
fmt = QTextCharFormat()
|
||||
fmt.setForeground(QColor(colors[level]) if level in colors else self.palette().color(QPalette.ColorRole.Text))
|
||||
fmt.setFontWeight(700 if level == "FATAL" else 400)
|
||||
scroll = self.verticalScrollBar()
|
||||
follow = scroll.value() >= scroll.maximum()
|
||||
cursor = QTextCursor(self.document())
|
||||
cursor.movePosition(QTextCursor.MoveOperation.End)
|
||||
cursor.beginEditBlock()
|
||||
if self._has_entries:
|
||||
cursor.insertBlock()
|
||||
cursor.insertText(message, fmt)
|
||||
cursor.endEditBlock()
|
||||
self._has_entries = True
|
||||
if follow:
|
||||
scroll.setValue(scroll.maximum())
|
||||
|
||||
def set_log_entries(self, entries) -> None:
|
||||
self.clear()
|
||||
self._has_entries = False
|
||||
for line_type, message in entries:
|
||||
self.append_log_entry(line_type, message)
|
||||
File renamed without changes.
|
Before Width: | Height: | Size: 1.7 MiB After Width: | Height: | Size: 1.7 MiB |
@@ -0,0 +1,8 @@
|
||||
group = "net.wei"
|
||||
id = "prettylog"
|
||||
name = "PrettyLog"
|
||||
version = "1.0.0"
|
||||
api_version = ">=0.0.2"
|
||||
entrypoint = "__init__.py:entry" # Python file name:endpoint
|
||||
icon = "nugget.gif" # Relative to this plugin directory; GIF, PNG, JPG or BMP
|
||||
description = "Make log output more pretty! Use the version's official Log4j client XML configuration and display parsed game logs."
|
||||
@@ -1,10 +0,0 @@
|
||||
from TapLauncher import Plugin, PluginContext
|
||||
|
||||
class ExperimentalFarm(Plugin):
|
||||
pass
|
||||
|
||||
def entry(context: PluginContext) -> None:
|
||||
context.data_dir.mkdir(parents=True, exist_ok=True)
|
||||
context.logger.info("Experimental Farm initialized")
|
||||
list_apis = context.get_api("launcher.apis.list")
|
||||
context.logger.debug("Available launcher APIs: %s", list_apis())
|
||||
@@ -1,8 +0,0 @@
|
||||
group = "net.wei"
|
||||
id = "experimentalfarm"
|
||||
name = "實驗田"
|
||||
version = "1.0.0"
|
||||
api_version = ">=0.0.1"
|
||||
entrypoint = "__init__.py:entry" # Python file name:endpoint
|
||||
icon = "nugget.gif" # Relative to this plugin directory; GIF, PNG, JPG or BMP
|
||||
description = "A experimental plugin!"
|
||||
@@ -1,11 +0,0 @@
|
||||
from TapLauncher import PluginContext, core
|
||||
|
||||
def entry(context: PluginContext) -> None:
|
||||
# init
|
||||
context.data_dir.mkdir(parents=True, exist_ok=True)
|
||||
logger = context.logger
|
||||
context.logger.info("Forge test initialized")
|
||||
|
||||
# Start
|
||||
versions = core.fetch_forge_versions()
|
||||
logger.info(f"Found {len(versions)} versions")
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 66 KiB |
@@ -1,8 +0,0 @@
|
||||
group = "net.wei"
|
||||
id = "forgetest"
|
||||
name = "ForgeTest"
|
||||
version = "1.0.0"
|
||||
api_version = ">=0.0.1"
|
||||
entrypoint = "__init__.py:entry" # Python file name:endpoint
|
||||
icon = "neoforged.ico" # Relative to this plugin directory; GIF, PNG, JPG or BMP
|
||||
description = "Test forge support!"
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 6.5 KiB |
@@ -1,4 +1,13 @@
|
||||
{
|
||||
"OK": "OK",
|
||||
"Old Alpha": "Old Alpha",
|
||||
"Old Beta": "Old Beta",
|
||||
"Release": "Release",
|
||||
"Snapshot": "Snapshot",
|
||||
"Use profile isolation": "Use profile isolation",
|
||||
"{version} (stable)": "{version} (stable)",
|
||||
"Selected a quilt loader version before creating profile.": "Selected a quilt loader version before creating profile.",
|
||||
"Profile {profile_id} with quilt loader successfully created.": "Profile {profile_id} with quilt loader successfully created.",
|
||||
"Clear selection": "Clear selection",
|
||||
"Select a mod to view its details.": "Select a mod to view its details.",
|
||||
"Install {count} selected mods": "Install {count} selected mods",
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
{
|
||||
"OK": "確定",
|
||||
"Old Alpha": "舊版 Alpha",
|
||||
"Old Beta": "舊版 Beta",
|
||||
"Release": "正式版",
|
||||
"Snapshot": "快照版",
|
||||
"Use profile isolation": "使用獨立的遊戲目錄",
|
||||
"{version} (stable)": "{version}(穩定版)",
|
||||
"Selected a quilt loader version before creating profile.": "請先選擇 Quilt 載入器版本再建立設定檔。",
|
||||
"Profile {profile_id} with quilt loader successfully created.": "已成功建立使用 Quilt 載入器的設定檔 {profile_id}。",
|
||||
"Clear selection": "清除勾選",
|
||||
"Select a mod to view its details.": "選擇模組以查看詳細資訊。",
|
||||
"Install {count} selected mods": "安裝已勾選的 {count} 個模組",
|
||||
|
||||
Reference in new issue
Block a user