From d560571e9d6f20e2569896ef5ea2f834fde207b1 Mon Sep 17 00:00:00 2001 From: overdyn Date: Wed, 2 Dec 2026 22:50:29 +0100 Subject: [PATCH] =?UTF-8?q?=D0=A1=D0=B2=D0=BE=D0=B8=20=D0=BA=D0=BE=D0=BD?= =?UTF-8?q?=D1=81=D0=BE=D0=BB=D1=8C=D0=BD=D1=8B=D0=B5=20=D0=BA=D0=B0=D1=80?= =?UTF-8?q?=D1=82=D0=BE=D1=87=D0=BA=D0=B8=20=D0=B4=D0=BB=D1=8F=20=D0=BF?= =?UTF-8?q?=D0=BB=D0=B0=D0=B3=D0=B8=D0=BD=D0=BE=D0=B2:=20PluginMessages.ca?= =?UTF-8?q?rd,=20=D1=80=D0=B5=D0=B6=D0=B8=D0=BC=D1=8B=20STANDARD/SOLID/ALE?= =?UTF-8?q?RT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 3 + CHANGELOG.md | 5 + docs/console-cards.md | 51 +++++ modules/api/api/api.api | 53 +++++ .../pnlibrary/api/logging/CardColorMode.java | 13 ++ .../pnlibrary/api/logging/CardTree.java | 83 +++++++ .../api/logging/ConsoleCardBuilder.java | 130 +++++++++++ .../pnlibrary/api/logging/LoggingService.java | 12 ++ .../api/plugin/metadata/PluginMessages.java | 15 ++ .../pnfolder/pnlibrary/console/CardRow.java | 68 ++++++ .../pnlibrary/console/ConsoleCard.java | 79 +++---- .../pnlibrary/console/ConsoleTheme.java | 23 ++ .../pnfolder/pnlibrary/console/TextWrap.java | 28 +++ .../pnlibrary/console/ConsoleCardTest.java | 7 + .../core/logging/ModuleConsoleCard.java | 203 ++++++++++++++++++ .../pnlibrary/core/logging/ModuleLogging.java | 10 + .../pnlibrary/core/plugin/LoadedModule.java | 2 +- .../core/plugin/module/ModuleMessages.java | 22 +- .../pnlibrary/core/text/ConsoleStyle.java | 40 +++- .../core/logging/ModuleConsoleCardTest.java | 144 +++++++++++++ 20 files changed, 939 insertions(+), 52 deletions(-) create mode 100644 docs/console-cards.md create mode 100644 modules/api/src/main/java/org/pnfolder/pnlibrary/api/logging/CardColorMode.java create mode 100644 modules/api/src/main/java/org/pnfolder/pnlibrary/api/logging/CardTree.java create mode 100644 modules/api/src/main/java/org/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder.java create mode 100644 modules/console/src/main/java/org/pnfolder/pnlibrary/console/CardRow.java create mode 100644 modules/console/src/main/java/org/pnfolder/pnlibrary/console/TextWrap.java create mode 100644 modules/core/src/main/java/org/pnfolder/pnlibrary/core/logging/ModuleConsoleCard.java create mode 100644 modules/core/src/test/java/org/pnfolder/pnlibrary/core/logging/ModuleConsoleCardTest.java diff --git a/AGENTS.md b/AGENTS.md index 0a21ede0f..1b4600b5a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -67,6 +67,9 @@ ## Журнал (новое сверху) Обновляй эту секцию в конце каждой сессии: одна запись, что сделано и что осталось. +### 2026-12-02 (консольные карточки для плагинов) +- `PluginMessages.card(...)`, `ConsoleCardBuilder`, `CardTree`, `CardColorMode`; `core/logging/ModuleConsoleCard`; `ConsoleStyle.solid/alert`; рамка по ширине заголовка, перенос строк (`console/TextWrap`). Док: `docs/console-cards.md`. В `main` не закоммичено; на живых серверах цвета не проверены. + ### 2026-12-02 (ждущие слушатели событий) - `EventScope.subscribeAsync`, `listenAsync`, `@EventHandler` с `CompletionStage` (без таймаута и `denyOnFailure`: пользователь велел сделать как на Velocity) (`core/events/Dispatch`, `Waits`); `PlayerLoginCheckEvent` на Bukkit, Bungee, Velocity; `/pn bus waiting`, кнопка «Сейчас ждут», `EventInspector.waiting()`; Kotlin `subscribeSuspend`. `check apiCheck` и `publishToMavenLocal` прошли. На живых серверах не проверено; pnTest (на dev.6) не обновлялся. По просьбе пользователя вместе с правками для pnAuth уходит в `main` PR и выпускается как `0.1.0-dev.11` (только GitHub, без Maven Central). diff --git a/CHANGELOG.md b/CHANGELOG.md index 433c15bfa..718f4ab73 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,11 @@ - `Delivery` переписан в один класс-отчёт: `status` (`DELIVERED`, `PARTIAL`, `UNSUPPORTED`, `FAILED`), `receipts` (ответ каждого получателя: имя, исход, причина сбоя), `delivered`, `failures`, `failure`, `orThrow()`. Фабрики `Delivery.delivered()`, `unsupported()`, `failed(cause)`, `of(accepted)`, `combine(...)`, `to(audience, operation)`. Вместо прежних `Delivered`/`Unsupported`/`Failed`. `Delivery.to(audience, it -> it.sendMessage(...))` работает для любой аудитории Adventure: одного получателя или группы (каждый получает операцию, даже если другой упал; пустая группа это `UNSUPPORTED`; частичный успех теперь `PARTIAL`, а не потерян). - Звук и заголовок больше не возвращают `Delivery`; он остался у эффектов, частиц и команд. `LibraryAudience.dynamic` заменён функцией `dynamicAudience`. - Чат: подпапка `api.chat.style` убрана. `ChatPalette` лежит в `api.chat`, `ChatTone`, `ChatNotice` и `ConfirmChoice` собраны в один файл `ChatMessages.kt`. Меняется только путь импорта: `api.chat.style.ChatPalette` стал `api.chat.ChatPalette`, то же для `ChatTone` и `color`. В `ChatKit` кнопки команд (`button`, `option`) используют один общий код. +### Консольные карточки для плагинов + +- `context.getMessages().card(title)` и `card(tone, title)`: свободный конструктор `ConsoleCardBuilder` (маскот, таблица, списки, дерево `CardTree`, статус, `render`/`send`/`record`), режимы `STANDARD`, `SOLID`, `ALERT`, свой цвет. Описание: `docs/console-cards.md`. +- Все карточки библиотеки: нижняя черта по ширине шапки, жирные заголовок и статус, перенос длинных пунктов, значения в таблице выровнены по самой длинной подписи. + ### Ждущие слушатели событий - Слушатель может вернуть `CompletionStage` (`listenAsync`, `@EventHandler`), событие дождётся его без занятого потока. Настроек нет, как на Velocity. diff --git a/docs/console-cards.md b/docs/console-cards.md new file mode 100644 index 000000000..a407224cd --- /dev/null +++ b/docs/console-cards.md @@ -0,0 +1,51 @@ +# Свои консольные карточки + +`context.getMessages().card(...)` собирает карточку в стиле библиотеки. Ни один блок не обязателен, порядок любой. +`box(title)` остаётся для стартовых сводок. + +```java +context.getMessages().card(ChatTone.FAILURE, "ПРОВЕРКА МАРШРУТИЗАЦИИ") + .solid() + .record(LogLevel.ERROR, "routing misconfigured") + .owner("x.x", "проблемы конфигурации — работа продолжена") + .blank() + .detail("Конфиг", "plugins/pnauth/config.yml") + .detail("Прокси", "velocity.toml") + .blank() + .section("Что проверить", problems) + .blank() + .status("Плагин продолжает работу • /pnauth reload") + .send(); +``` + +## Начало + +| Вызов | Вид | +|---|---| +| `card("ЗАГОЛОВОК")` | нейтральный, значения белые | +| `card(ChatTone.FAILURE, "ЗАГОЛОВОК")` | маскот, значения и статус в цвете тона | + +## Раскраска + +| Режим | Что делает | +|---|---| +| `STANDARD` (по умолчанию) | стиль библиотеки: сиреневая рамка, серые ветки, акценты цветом тона | +| `.solid()` | вся карточка одним цветом, ваши цвета в тексте убираются | +| `.alert()` | рамка, маскот, ветки и заголовок цветом тона, текст деталей белый | + +`.color(TextColor)` заменяет цвет тона; консоль показывает ближайший классический цвет. + +## Блоки + +- `mascot(face, headline[, subtitle])`, `owner(face, subtitle)` (сам берёт `плагин@модуль версия`), `owner(face, plugin, module, version, subtitle)`. +- `detail(label, value)`, `details(map)`: соседние строки образуют таблицу с `┌ ├ └`. +- `section(title)`, `item(text)`, `items(list)`, `section(title, list)`. +- `tree(CardTree.of("корень", CardTree.of("ветка").leaves("а", "б")))`. +- `line(text | Component)`, `divider(title)`, `blank()`, `support()` / `support(url)`, `status(text)`. + +Длинные `item` и узлы дерева переносятся по пробелам с сохранением веток; пути и ссылки не разрываются. + +## Вывод + +- `render()` возвращает строки без печати, `send()` / `show()` печатает в консоль без `[WARN]`/`[ERROR]`. +- `record(level, summary)` сразу пишет краткую запись в чёрный ящик, в консоль ничего не выводит. diff --git a/modules/api/api/api.api b/modules/api/api/api.api index e4973c884..538434e07 100644 --- a/modules/api/api/api.api +++ b/modules/api/api/api.api @@ -1399,6 +1399,56 @@ public final class org/pnfolder/pnlibrary/api/libraries/state/LibraryUsage { public fun toString ()Ljava/lang/String; } +public final class org/pnfolder/pnlibrary/api/logging/CardColorMode : java/lang/Enum { + public static final field ALERT Lorg/pnfolder/pnlibrary/api/logging/CardColorMode; + public static final field SOLID Lorg/pnfolder/pnlibrary/api/logging/CardColorMode; + public static final field STANDARD Lorg/pnfolder/pnlibrary/api/logging/CardColorMode; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/CardColorMode; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/logging/CardColorMode; +} + +public final class org/pnfolder/pnlibrary/api/logging/CardTree { + public fun child (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/CardTree; + public fun child (Lorg/pnfolder/pnlibrary/api/logging/CardTree;)Lorg/pnfolder/pnlibrary/api/logging/CardTree; + public fun equals (Ljava/lang/Object;)Z + public fun getChildren ()Ljava/util/List; + public fun getText ()Ljava/lang/String; + public fun hashCode ()I + public fun leaves ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/CardTree; + public static fun of (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/CardTree; + public static fun of (Ljava/lang/String;[Lorg/pnfolder/pnlibrary/api/logging/CardTree;)Lorg/pnfolder/pnlibrary/api/logging/CardTree; + public fun toString ()Ljava/lang/String; +} + +public abstract interface class org/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder { + public fun alert ()Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public abstract fun blank ()Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public abstract fun color (Lnet/kyori/adventure/text/format/TextColor;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public abstract fun detail (Ljava/lang/String;Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public fun details (Ljava/util/Map;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public abstract fun divider (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public abstract fun item (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public fun items (Ljava/lang/Iterable;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public abstract fun line (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public abstract fun line (Lnet/kyori/adventure/text/Component;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public fun mascot (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public abstract fun mascot (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public abstract fun owner (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public abstract fun owner (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public abstract fun record (Lorg/pnfolder/pnlibrary/api/logging/LogLevel;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public abstract fun render ()Ljava/util/List; + public abstract fun section (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public fun section (Ljava/lang/String;Ljava/lang/Iterable;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public abstract fun send ()V + public fun show ()V + public fun solid ()Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public abstract fun status (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public abstract fun style (Lorg/pnfolder/pnlibrary/api/logging/CardColorMode;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public abstract fun support ()Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public abstract fun support (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public abstract fun tree (Lorg/pnfolder/pnlibrary/api/logging/CardTree;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; +} + public final class org/pnfolder/pnlibrary/api/logging/LogLevel : java/lang/Enum { public static final field CRITICAL Lorg/pnfolder/pnlibrary/api/logging/LogLevel; public static final field DEBUG Lorg/pnfolder/pnlibrary/api/logging/LogLevel; @@ -1413,6 +1463,7 @@ public final class org/pnfolder/pnlibrary/api/logging/LogLevel : java/lang/Enum public abstract interface class org/pnfolder/pnlibrary/api/logging/LoggingService { public abstract fun box (Ljava/lang/Object;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; public fun box (Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; + public fun card (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/plugin/metadata/PluginMetadata;Lorg/pnfolder/pnlibrary/api/chat/style/ChatTone;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; public abstract fun logger (Ljava/lang/Object;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/PnLogger; public abstract fun shutdownBox (Ljava/lang/Object;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; public fun shutdownBox (Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; @@ -2288,6 +2339,8 @@ public abstract interface class org/pnfolder/pnlibrary/api/plugin/lifecycle/Plug public abstract interface class org/pnfolder/pnlibrary/api/plugin/metadata/PluginMessages { public abstract fun box (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; + public fun card (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; + public fun card (Lorg/pnfolder/pnlibrary/api/chat/style/ChatTone;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder; } public final class org/pnfolder/pnlibrary/api/plugin/metadata/PluginMetadata { diff --git a/modules/api/src/main/java/org/pnfolder/pnlibrary/api/logging/CardColorMode.java b/modules/api/src/main/java/org/pnfolder/pnlibrary/api/logging/CardColorMode.java new file mode 100644 index 000000000..19fcedeba --- /dev/null +++ b/modules/api/src/main/java/org/pnfolder/pnlibrary/api/logging/CardColorMode.java @@ -0,0 +1,13 @@ +package org.pnfolder.pnlibrary.api.logging; + +/** How a console card is colored. */ +public enum CardColorMode { + /** The library look: lavender frame, white labels, gray branches; mascot, values and status carry the tone. */ + STANDARD, + + /** The whole card in one color, for messages that must not be missed. */ + SOLID, + + /** Frame, mascot, branches and title in the tone's color, long detail text in white. */ + ALERT +} diff --git a/modules/api/src/main/java/org/pnfolder/pnlibrary/api/logging/CardTree.java b/modules/api/src/main/java/org/pnfolder/pnlibrary/api/logging/CardTree.java new file mode 100644 index 000000000..c476ca79e --- /dev/null +++ b/modules/api/src/main/java/org/pnfolder/pnlibrary/api/logging/CardTree.java @@ -0,0 +1,83 @@ +package org.pnfolder.pnlibrary.api.logging; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +/** Immutable node of a console card tree; nest nodes to any depth. */ +public final class CardTree { + private final String text; + private final List children; + + private CardTree(String text, List children) { + this.text = text; + this.children = children; + } + + /** A node without children. */ + public static @NotNull CardTree of(@NotNull String text) { + if (text.trim().isEmpty()) { + throw new IllegalArgumentException("Tree text must not be blank"); + } + return new CardTree(text.trim(), Collections.emptyList()); + } + + /** A node with the given children, in order. */ + public static @NotNull CardTree of(@NotNull String text, @NotNull CardTree... children) { + CardTree node = of(text); + for (CardTree child : children) { + node = node.child(child); + } + return node; + } + + /** A copy of this node with one more leaf. */ + public @NotNull CardTree child(@NotNull String leaf) { + return child(of(leaf)); + } + + /** A copy of this node with one more subtree. */ + public @NotNull CardTree child(@NotNull CardTree subtree) { + Objects.requireNonNull(subtree, "subtree"); + List next = new ArrayList<>(children); + next.add(subtree); + return new CardTree(text, Collections.unmodifiableList(next)); + } + + /** A copy of this node with one more leaf per text. */ + public @NotNull CardTree leaves(@NotNull String... leaves) { + CardTree node = this; + for (String leaf : leaves) { + node = node.child(leaf); + } + return node; + } + + /** Text of this node. */ + public @NotNull String getText() { + return text; + } + + /** Children in order. */ + public @NotNull List getChildren() { + return children; + } + + @Override + public boolean equals(Object other) { + return other instanceof CardTree && text.equals(((CardTree) other).text) + && children.equals(((CardTree) other).children); + } + + @Override + public int hashCode() { + return Objects.hash(text, children); + } + + @Override + public String toString() { + return children.isEmpty() ? text : text + children; + } +} diff --git a/modules/api/src/main/java/org/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder.java b/modules/api/src/main/java/org/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder.java new file mode 100644 index 000000000..8db1f7872 --- /dev/null +++ b/modules/api/src/main/java/org/pnfolder/pnlibrary/api/logging/ConsoleCardBuilder.java @@ -0,0 +1,130 @@ +package org.pnfolder.pnlibrary.api.logging; + +import java.util.List; +import java.util.Map; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.TextColor; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * A free-form console card: a titled frame filled with any blocks in any order. No block is required. + * Get one with {@code context.getMessages().card(title)}; nothing is printed until {@link #send()}. + * + *

Connectors are chosen from neighbours: consecutive {@code detail} rows form one table, consecutive + * {@code item} rows form one list. A card may be rendered and sent more than once. + * + *

{@code
+ * context.getMessages().card(ChatTone.FAILURE, "ROUTING CHECK")
+ *     .solid()
+ *     .owner("x.x", "configuration problems")
+ *     .blank()
+ *     .detail("Config", "plugins/auth/config.yml")
+ *     .section("How to fix", Arrays.asList("Use real server names", "Or enable limbo"))
+ *     .status("The plugin keeps running")
+ *     .send();
+ * }
+ */ +public interface ConsoleCardBuilder { + /** Chooses how the card is colored; the last call wins and applies to the whole card. */ + @NotNull ConsoleCardBuilder style(@NotNull CardColorMode mode); + + /** Same as {@code style(CardColorMode.SOLID)}. */ + default @NotNull ConsoleCardBuilder solid() { + return style(CardColorMode.SOLID); + } + + /** Same as {@code style(CardColorMode.ALERT)}. */ + default @NotNull ConsoleCardBuilder alert() { + return style(CardColorMode.ALERT); + } + + /** Replaces the tone's color; the console shows the nearest classic chat color. */ + @NotNull ConsoleCardBuilder color(@NotNull TextColor color); + + /** Adds a mascot with a headline; {@code face} may be given with or without parentheses. */ + default @NotNull ConsoleCardBuilder mascot(@NotNull String face, @NotNull String headline) { + return mascot(face, headline, null); + } + + /** Adds a mascot with a headline and a second line. */ + @NotNull ConsoleCardBuilder mascot(@NotNull String face, @NotNull String headline, @Nullable String subtitle); + + /** Adds the mascot headed by this module's own {@code plugin@module version}. */ + @NotNull ConsoleCardBuilder owner(@NotNull String face, @Nullable String subtitle); + + /** Adds the mascot headed by another {@code plugin@module version}; a {@code null} module is shown as main. */ + @NotNull ConsoleCardBuilder owner(@NotNull String face, @NotNull String plugin, @Nullable String module, + @Nullable String version, @Nullable String subtitle); + + /** Adds one label and value row. */ + @NotNull ConsoleCardBuilder detail(@NotNull String label, @Nullable Object value); + + /** Adds one row per entry, in the map's order. */ + default @NotNull ConsoleCardBuilder details(@NotNull Map details) { + for (Map.Entry entry : details.entrySet()) { + detail(entry.getKey(), entry.getValue()); + } + return this; + } + + /** Adds a heading for the items that follow. */ + @NotNull ConsoleCardBuilder section(@NotNull String title); + + /** Adds a heading with its items. */ + default @NotNull ConsoleCardBuilder section(@NotNull String title, @NotNull Iterable items) { + return section(title).items(items); + } + + /** Adds a list item; long text wraps under its branch. */ + @NotNull ConsoleCardBuilder item(@NotNull String text); + + /** Adds several list items. */ + default @NotNull ConsoleCardBuilder items(@NotNull Iterable items) { + for (String text : items) { + item(text); + } + return this; + } + + /** Adds a nested tree. */ + @NotNull ConsoleCardBuilder tree(@NotNull CardTree tree); + + /** Adds a free line of text. */ + @NotNull ConsoleCardBuilder line(@NotNull String text); + + /** Adds a free line that keeps its colors, except on a {@link CardColorMode#SOLID} card. */ + @NotNull ConsoleCardBuilder line(@NotNull Component component); + + /** Adds a titled divider. */ + @NotNull ConsoleCardBuilder divider(@NotNull String title); + + /** Adds an empty line. */ + @NotNull ConsoleCardBuilder blank(); + + /** Adds the support block with the pnFolder support link. */ + @NotNull ConsoleCardBuilder support(); + + /** Adds the support block with your own link. */ + @NotNull ConsoleCardBuilder support(@NotNull String url); + + /** Adds an emphasized status line; usually the last block. */ + @NotNull ConsoleCardBuilder status(@NotNull String text); + + /** The lines exactly as {@link #send()} prints them, color codes included. */ + @NotNull List render(); + + /** Prints the card to the server console, without log level prefixes of warnings or errors. */ + void send(); + + /** Same as {@link #send()}, named like {@link MessageBox#show()}. */ + default void show() { + send(); + } + + /** + * Immediately stores a short summary of the event in the black box without printing anything, so a support + * report shows what the card was about. + */ + @NotNull ConsoleCardBuilder record(@NotNull LogLevel level, @NotNull String summary); +} diff --git a/modules/api/src/main/java/org/pnfolder/pnlibrary/api/logging/LoggingService.java b/modules/api/src/main/java/org/pnfolder/pnlibrary/api/logging/LoggingService.java index af6946228..9102b4768 100644 --- a/modules/api/src/main/java/org/pnfolder/pnlibrary/api/logging/LoggingService.java +++ b/modules/api/src/main/java/org/pnfolder/pnlibrary/api/logging/LoggingService.java @@ -2,6 +2,9 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.pnfolder.pnlibrary.api.chat.style.ChatTone; +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMetadata; /** Creates plugin-bound loggers and console message boxes. */ @ApiStatus.NonExtendable @@ -12,6 +15,15 @@ public interface LoggingService { /** Starts a startup summary block titled {@code title} for {@code owner}; nothing is printed until {@code show()}. */ @NotNull MessageBox box(@NotNull Object owner, @NotNull String title); + /** + * Starts a free-form card for {@code owner}; {@code metadata} names it in the owner block and the black box. + * A {@code null} tone is the neutral look. Plugins use {@code context.getMessages().card(title)}. + */ + default @NotNull ConsoleCardBuilder card(@NotNull Object owner, @NotNull PluginMetadata metadata, + @Nullable ChatTone tone, @NotNull String title) { + throw new UnsupportedOperationException("Console cards are not supported here"); + } + /** Starts a shutdown summary block titled {@code title} for {@code owner}. */ @NotNull MessageBox shutdownBox(@NotNull Object owner, @NotNull String title); diff --git a/modules/api/src/main/java/org/pnfolder/pnlibrary/api/plugin/metadata/PluginMessages.java b/modules/api/src/main/java/org/pnfolder/pnlibrary/api/plugin/metadata/PluginMessages.java index 1ac93e8bd..d80d38877 100644 --- a/modules/api/src/main/java/org/pnfolder/pnlibrary/api/plugin/metadata/PluginMessages.java +++ b/modules/api/src/main/java/org/pnfolder/pnlibrary/api/plugin/metadata/PluginMessages.java @@ -1,6 +1,8 @@ package org.pnfolder.pnlibrary.api.plugin.metadata; import org.jetbrains.annotations.NotNull; +import org.pnfolder.pnlibrary.api.chat.style.ChatTone; +import org.pnfolder.pnlibrary.api.logging.ConsoleCardBuilder; import org.pnfolder.pnlibrary.api.logging.MessageBox; /** Console message boxes bound to one plugin. */ @@ -8,4 +10,17 @@ public interface PluginMessages { /** Starts a console block titled {@code title}; nothing is printed until {@code show()}. */ @NotNull MessageBox box(@NotNull String title); + + /** + * Starts an empty free-form card in the neutral library look; nothing is printed until {@code send()}. + * Unlike {@link #box(String)} it adds no blocks by itself. + */ + default @NotNull ConsoleCardBuilder card(@NotNull String title) { + throw new UnsupportedOperationException("Console cards are not supported here"); + } + + /** Starts an empty free-form card colored by {@code tone}. */ + default @NotNull ConsoleCardBuilder card(@NotNull ChatTone tone, @NotNull String title) { + throw new UnsupportedOperationException("Console cards are not supported here"); + } } diff --git a/modules/console/src/main/java/org/pnfolder/pnlibrary/console/CardRow.java b/modules/console/src/main/java/org/pnfolder/pnlibrary/console/CardRow.java new file mode 100644 index 000000000..5d53d1d35 --- /dev/null +++ b/modules/console/src/main/java/org/pnfolder/pnlibrary/console/CardRow.java @@ -0,0 +1,68 @@ +package org.pnfolder.pnlibrary.console; + +import java.util.List; + +/** A detail or item row whose connector depends on its neighbours, so a group can never be drawn out of order. */ +final class CardRow { + private final boolean detail; + private final String label; + private final String value; + + private CardRow(boolean detail, String label, String value) { + this.detail = detail; + this.label = label; + this.value = value; + } + + static CardRow detail(String label, String value) { + return new CardRow(true, label, value); + } + + static CardRow item(String text) { + return new CardRow(false, text, ""); + } + + void render(ConsoleTheme theme, List lines, int index, List result) { + String connector = connector(lines, index); + if (detail) { + result.add(theme.muted + " " + connector + " " + theme.text + pad(label, labelWidth(lines, index)) + + theme.accent + value + theme.reset); + return; + } + String color = theme.content.equals(theme.muted) ? "" : theme.content; + String branch = connector; + for (String part : TextWrap.wrap(label)) { + result.add(theme.muted + " " + branch + " " + color + part + theme.reset); + branch = "└".equals(connector) ? " " : "│"; + } + } + + /** Top, middle or bottom of the run of rows of the same kind around {@code index}. */ + private String connector(List lines, int index) { + if (!sameKind(lines, index + 1)) return "└"; + if (!detail) return "├"; // the section heading above is the top of an item group + return sameKind(lines, index - 1) ? "├" : "┌"; + } + + /** The label column of the detail group around {@code index}, so its values line up. */ + private int labelWidth(List lines, int index) { + int first = index; + while (sameKind(lines, first - 1)) first--; + int width = 22; + for (int row = first; sameKind(lines, row); row++) { + width = Math.max(width, ((CardRow) lines.get(row)).label.length()); + } + return width; + } + + private boolean sameKind(List lines, int index) { + return index >= 0 && index < lines.size() && lines.get(index) instanceof CardRow + && ((CardRow) lines.get(index)).detail == detail; + } + + private static String pad(String value, int width) { + StringBuilder result = new StringBuilder(value); + while (result.length() < width) result.append(' '); + return result.append(" ").toString(); + } +} diff --git a/modules/console/src/main/java/org/pnfolder/pnlibrary/console/ConsoleCard.java b/modules/console/src/main/java/org/pnfolder/pnlibrary/console/ConsoleCard.java index 900ebac1a..1b162afc7 100644 --- a/modules/console/src/main/java/org/pnfolder/pnlibrary/console/ConsoleCard.java +++ b/modules/console/src/main/java/org/pnfolder/pnlibrary/console/ConsoleCard.java @@ -46,55 +46,25 @@ public static String label(String plugin, String module, String version) { public List render() { List result = new ArrayList<>(); result.add(""); - result.add(theme.border + " ━━━━━━━━━━━ " + title + " ━━━━━━━━━━━" + theme.reset); + result.add(theme.border + " " + rule(11) + " " + theme.emphasis + title + theme.reset + + theme.border + " " + rule(11) + theme.reset); for (int index = 0; index < lines.size(); index++) { Object line = lines.get(index); - if (line instanceof Row) result.add(((Row) line).render(theme, connector(index))); + if (line instanceof CardRow) ((CardRow) line).render(theme, lines, index, result); else result.add((String) line); } - result.add(theme.border + " ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" + theme.reset); + // As wide as the header: two rules of 11, the title and the spaces around it. + result.add(theme.border + " " + rule(24 + title.codePointCount(0, title.length())) + theme.reset); result.add(""); return Collections.unmodifiableList(result); } - private static String pad(String value, int width) { - String checked = value; - StringBuilder result = new StringBuilder(checked); - while (result.length() < width) result.append(' '); - if (result.length() >= width) result.append(" "); + private static String rule(int width) { + StringBuilder result = new StringBuilder(width); + while (result.length() < width) result.append('\u2501'); return result.toString(); } - /** A detail or item row whose connector depends on its neighbours, so a group can never be drawn out of order. */ - private static final class Row { - private final boolean detail; - private final String label; - private final String value; - - private Row(boolean detail, String label, String value) { - this.detail = detail; - this.label = label; - this.value = value; - } - - private String render(ConsoleTheme theme, String connector) { - if (!detail) return theme.muted + " " + connector + " " + label + theme.reset; - return theme.muted + " " + connector + " " + theme.text + pad(label, 22) - + theme.accent + value + theme.reset; - } - } - - /** The connector of the row at {@code index}: top, middle or bottom of its run of rows of the same kind. */ - private String connector(int index) { - Row row = (Row) lines.get(index); - boolean before = index > 0 && lines.get(index - 1) instanceof Row && ((Row) lines.get(index - 1)).detail == row.detail; - boolean after = index + 1 < lines.size() && lines.get(index + 1) instanceof Row - && ((Row) lines.get(index + 1)).detail == row.detail; - if (!after) return "└"; - if (!row.detail) return "├"; // the section heading above is the top of an item group - return before ? "├" : "┌"; - } - /** Sends this card. * @param sink destination that receives every rendered line */ public void send(ConsoleSink sink) { @@ -186,7 +156,7 @@ public Builder blank() { * @return this builder */ public Builder firstDetail(String label, Object value) { - lines.add(new Row(true, text(label), String.valueOf(value))); + lines.add(CardRow.detail(text(label), String.valueOf(value))); return this; } @@ -198,7 +168,7 @@ public Builder firstDetail(String label, Object value) { * @return this builder */ public Builder detail(String label, Object value) { - lines.add(new Row(true, text(label), String.valueOf(value))); + lines.add(CardRow.detail(text(label), String.valueOf(value))); return this; } @@ -210,7 +180,7 @@ public Builder detail(String label, Object value) { * @return this builder */ public Builder lastDetail(String label, Object value) { - lines.add(new Row(true, text(label), String.valueOf(value))); + lines.add(CardRow.detail(text(label), String.valueOf(value))); return this; } @@ -237,6 +207,18 @@ public Builder divider(String title) { return this; } + /** + * Adds a free line of ordinary text. + * + * @param value line text, possibly carrying its own style sequences + * @return this builder + */ + public Builder line(String value) { + if (value == null) throw new IllegalArgumentException("line is required"); + lines.add(theme.text + " " + value + theme.reset); + return this; + } + /** * Adds a middle item to the current section. * @@ -244,7 +226,7 @@ public Builder divider(String title) { * @return this builder */ public Builder item(String value) { - lines.add(new Row(false, text(value), "")); + lines.add(CardRow.item(text(value))); return this; } @@ -255,7 +237,7 @@ public Builder item(String value) { * @return this builder */ public Builder lastItem(String value) { - lines.add(new Row(false, text(value), "")); + lines.add(CardRow.item(text(value))); return this; } @@ -278,7 +260,7 @@ public Builder tree(ConsoleTree tree) { * @return this builder */ public Builder status(String value) { - lines.add(theme.accent + " ■ " + text(value) + theme.reset); + lines.add(theme.accent + theme.emphasis + " ■ " + text(value) + theme.reset); return this; } @@ -288,10 +270,15 @@ public Builder status(String value) { private void appendTree(ConsoleTree node, String prefix, boolean last, boolean root) { String connector = root ? (node.children().isEmpty() ? "└ " : "┌ ") : (last ? "└ " : "├ "); - lines.add(theme.muted + " " + prefix + connector + theme.text + node.text() + theme.reset); + String below = prefix + (root || last ? " " : "│ "); + String branch = prefix + connector; + for (String part : TextWrap.wrap(node.text())) { + lines.add(theme.muted + " " + branch + theme.text + part + theme.reset); + branch = below; + } List children = node.children(); for (int index = 0; index < children.size(); index++) { - appendTree(children.get(index), prefix + (root ? " " : (last ? " " : "│ ")), + appendTree(children.get(index), below, index == children.size() - 1, false); } } diff --git a/modules/console/src/main/java/org/pnfolder/pnlibrary/console/ConsoleTheme.java b/modules/console/src/main/java/org/pnfolder/pnlibrary/console/ConsoleTheme.java index c7fc5ffb0..ac6836e2b 100644 --- a/modules/console/src/main/java/org/pnfolder/pnlibrary/console/ConsoleTheme.java +++ b/modules/console/src/main/java/org/pnfolder/pnlibrary/console/ConsoleTheme.java @@ -13,6 +13,11 @@ public final class ConsoleTheme { /** Sequence that restores the platform's default style. */ public final String reset; + /** Style applied to list item text. */ + public final String content; + /** Style added after the color of the title and status line, such as bold. */ + public final String emphasis; + /** * Creates a theme from platform-specific style sequences. * @@ -23,11 +28,29 @@ public final class ConsoleTheme { * @param reset style reset sequence */ public ConsoleTheme(String border, String accent, String text, String muted, String reset) { + this(border, accent, text, muted, reset, muted, ""); + } + + /** + * Creates a theme that also styles list items and emphasizes the title and status line. + * + * @param border border style + * @param accent emphasized-value style + * @param text ordinary text style + * @param muted secondary text style + * @param reset style reset sequence + * @param content list item text style + * @param emphasis title and status addition + */ + public ConsoleTheme(String border, String accent, String text, String muted, String reset, + String content, String emphasis) { this.border = value(border); this.accent = value(accent); this.text = value(text); this.muted = value(muted); this.reset = value(reset); + this.content = value(content); + this.emphasis = value(emphasis); } /** Creates an unstyled theme. diff --git a/modules/console/src/main/java/org/pnfolder/pnlibrary/console/TextWrap.java b/modules/console/src/main/java/org/pnfolder/pnlibrary/console/TextWrap.java new file mode 100644 index 000000000..88245c366 --- /dev/null +++ b/modules/console/src/main/java/org/pnfolder/pnlibrary/console/TextWrap.java @@ -0,0 +1,28 @@ +package org.pnfolder.pnlibrary.console; + +import java.util.ArrayList; +import java.util.List; + +/** Splits long card text at spaces; a longer word, such as a path or a link, stays whole so it can be copied. */ +final class TextWrap { + private static final int WIDTH = 80; + + private TextWrap() { + } + + static List wrap(String text) { + List result = new ArrayList<>(); + for (String paragraph : text.split("\r?\n")) { + String rest = paragraph; + while (rest.length() > WIDTH) { + int cut = rest.lastIndexOf(' ', WIDTH); + if (cut <= 0) cut = rest.indexOf(' ', WIDTH); + if (cut <= 0) break; + result.add(rest.substring(0, cut)); + rest = rest.substring(cut + 1); + } + result.add(rest); + } + return result; + } +} diff --git a/modules/console/src/test/java/org/pnfolder/pnlibrary/console/ConsoleCardTest.java b/modules/console/src/test/java/org/pnfolder/pnlibrary/console/ConsoleCardTest.java index 36a725bbc..9cd762c8b 100644 --- a/modules/console/src/test/java/org/pnfolder/pnlibrary/console/ConsoleCardTest.java +++ b/modules/console/src/test/java/org/pnfolder/pnlibrary/console/ConsoleCardTest.java @@ -46,6 +46,13 @@ void rendersNestedTreeWithContinuousBranches() { assertTrue(lines.stream().anyMatch(line -> line.contains("└ После замены"))); } + @Test + void theBottomRuleIsAsWideAsTheHeader() { + List lines = ConsoleCard.builder(ConsoleTheme.plain(), "ПРОВЕРКА МАРШРУТИЗАЦИИ").build().render(); + + assertEquals(lines.get(1).length(), lines.get(2).length()); + } + @Test void mascotOwnsFaceParentheses() { List lines = ConsoleCard.builder(ConsoleTheme.plain(), "POLICY") diff --git a/modules/core/src/main/java/org/pnfolder/pnlibrary/core/logging/ModuleConsoleCard.java b/modules/core/src/main/java/org/pnfolder/pnlibrary/core/logging/ModuleConsoleCard.java new file mode 100644 index 000000000..48265b114 --- /dev/null +++ b/modules/core/src/main/java/org/pnfolder/pnlibrary/core/logging/ModuleConsoleCard.java @@ -0,0 +1,203 @@ +package org.pnfolder.pnlibrary.core.logging; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.function.BiConsumer; +import java.util.function.UnaryOperator; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.TextColor; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette; +import org.pnfolder.pnlibrary.api.chat.style.ChatTone; +import org.pnfolder.pnlibrary.api.logging.CardColorMode; +import org.pnfolder.pnlibrary.api.logging.CardTree; +import org.pnfolder.pnlibrary.api.logging.ConsoleCardBuilder; +import org.pnfolder.pnlibrary.api.logging.LogLevel; +import org.pnfolder.pnlibrary.api.logging.PnLogger; +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMetadata; +import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity; +import org.pnfolder.pnlibrary.console.ConsoleCard; +import org.pnfolder.pnlibrary.console.ConsoleTheme; +import org.pnfolder.pnlibrary.console.ConsoleTree; +import org.pnfolder.pnlibrary.core.text.ConsoleStyle; +import org.pnfolder.pnlibrary.spi.platform.logging.PlatformLogging; + +/** Remembers the blocks of a plugin's card and draws them once the color mode is known. */ +final class ModuleConsoleCard implements ConsoleCardBuilder { + private final PlatformLogging logging; + private final Object owner; + private final PluginMetadata metadata; + private final PnLogger logger; + private final ChatTone tone; + private final String title; + /** Each block gets the card and a filter that removes the caller's own colors where the mode requires it. */ + private final List>> blocks = new ArrayList<>(); + private CardColorMode mode = CardColorMode.STANDARD; + private TextColor color; + + ModuleConsoleCard(PlatformLogging logging, Object owner, PluginMetadata metadata, PnLogger logger, + @Nullable ChatTone tone, String title) { + this.logging = logging; + this.owner = owner; + this.metadata = metadata; + this.logger = logger; + this.tone = tone; + this.title = required(title); + } + + @Override + public @NotNull ConsoleCardBuilder style(@NotNull CardColorMode value) { + mode = Objects.requireNonNull(value, "mode"); + return this; + } + + @Override + public @NotNull ConsoleCardBuilder color(@NotNull TextColor value) { + color = Objects.requireNonNull(value, "color"); + return this; + } + + @Override + public @NotNull ConsoleCardBuilder mascot(@NotNull String face, @NotNull String headline, + @Nullable String subtitle) { + required(face); + required(headline); + return add((card, clean) -> card.mascot(clean.apply(face), clean.apply(headline), + subtitle == null ? null : clean.apply(subtitle))); + } + + @Override + public @NotNull ConsoleCardBuilder owner(@NotNull String face, @Nullable String subtitle) { + return owner(face, metadata.getName(), metadata.getId().getValue(), metadata.getVersion(), subtitle); + } + + @Override + public @NotNull ConsoleCardBuilder owner(@NotNull String face, @NotNull String plugin, @Nullable String module, + @Nullable String version, @Nullable String subtitle) { + return mascot(face, ConsoleCard.label(required(plugin), module, version), subtitle); + } + + @Override + public @NotNull ConsoleCardBuilder detail(@NotNull String label, @Nullable Object value) { + required(label); + String shown = String.valueOf(value); + return add((card, clean) -> card.detail(clean.apply(label), clean.apply(shown))); + } + + @Override + public @NotNull ConsoleCardBuilder section(@NotNull String text) { + required(text); + return add((card, clean) -> card.section(clean.apply(text))); + } + + @Override + public @NotNull ConsoleCardBuilder item(@NotNull String text) { + required(text); + return add((card, clean) -> card.item(clean.apply(text))); + } + + @Override + public @NotNull ConsoleCardBuilder tree(@NotNull CardTree tree) { + Objects.requireNonNull(tree, "tree"); + return add((card, clean) -> card.tree(convert(tree, clean))); + } + + @Override + public @NotNull ConsoleCardBuilder line(@NotNull String text) { + Objects.requireNonNull(text, "text"); + return add((card, clean) -> { + for (String part : text.split("\r?\n", -1)) { + card.line(clean.apply(part)); + } + }); + } + + @Override + public @NotNull ConsoleCardBuilder line(@NotNull Component component) { + return line(LegacyComponentSerializer.legacySection().serialize(component)); + } + + @Override + public @NotNull ConsoleCardBuilder divider(@NotNull String text) { + required(text); + return add((card, clean) -> card.divider(clean.apply(text))); + } + + @Override + public @NotNull ConsoleCardBuilder blank() { + return add((card, clean) -> card.blank()); + } + + @Override + public @NotNull ConsoleCardBuilder support() { + return support(PnLibraryIdentity.SUPPORT_URL); + } + + @Override + public @NotNull ConsoleCardBuilder support(@NotNull String url) { + required(url); + return add((card, clean) -> card.support(clean.apply(url))); + } + + @Override + public @NotNull ConsoleCardBuilder status(@NotNull String text) { + required(text); + return add((card, clean) -> card.status(clean.apply(text))); + } + + @Override + public @NotNull List render() { + UnaryOperator clean = mode == CardColorMode.SOLID + ? ConsoleStyle::strip + : UnaryOperator.identity(); + ConsoleCard.Builder card = ConsoleCard.builder(theme(), clean.apply(title)); + blocks.forEach(block -> block.accept(card, clean)); + return card.build().render(); + } + + @Override + public void send() { + render().forEach(line -> logging.console(owner, line)); + } + + @Override + public @NotNull ConsoleCardBuilder record(@NotNull LogLevel level, @NotNull String summary) { + logger.record(level, summary); + return this; + } + + private ConsoleTheme theme() { + // A card without a tone has no state color: white values normally, the library accent when filled. + TextColor chosen = color != null ? color : tone != null ? tone.getColor() : null; + TextColor filled = chosen != null ? chosen : ChatPalette.ACCENT; + switch (mode) { + case SOLID: + return ConsoleStyle.solid(filled); + case ALERT: + return ConsoleStyle.alert(filled); + default: + return chosen == null ? ConsoleStyle.THEME : ConsoleStyle.theme(chosen); + } + } + + private ConsoleCardBuilder add(BiConsumer> block) { + blocks.add(block); + return this; + } + + private static ConsoleTree convert(CardTree node, UnaryOperator clean) { + ConsoleTree.Builder tree = ConsoleTree.builder(clean.apply(node.getText())); + node.getChildren().forEach(child -> tree.child(convert(child, clean))); + return tree.build(); + } + + private static String required(String value) { + if (value == null || value.trim().isEmpty()) { + throw new IllegalArgumentException("Card text must not be blank"); + } + return value.trim(); + } +} diff --git a/modules/core/src/main/java/org/pnfolder/pnlibrary/core/logging/ModuleLogging.java b/modules/core/src/main/java/org/pnfolder/pnlibrary/core/logging/ModuleLogging.java index e0c40332b..131f298cc 100644 --- a/modules/core/src/main/java/org/pnfolder/pnlibrary/core/logging/ModuleLogging.java +++ b/modules/core/src/main/java/org/pnfolder/pnlibrary/core/logging/ModuleLogging.java @@ -3,6 +3,9 @@ import java.util.Objects; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.pnfolder.pnlibrary.api.chat.style.ChatTone; +import org.pnfolder.pnlibrary.api.logging.ConsoleCardBuilder; +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMetadata; import org.pnfolder.pnlibrary.api.logging.LogLevel; import org.pnfolder.pnlibrary.api.logging.LoggingService; import org.pnfolder.pnlibrary.api.logging.MessageBox; @@ -68,6 +71,13 @@ public void record(@NotNull LogLevel level, @NotNull String message, @Nullable T return new StartupBox(environment, owner, title, BoxKind.GENERIC, title, null); } + @Override + public @NotNull ConsoleCardBuilder card(@NotNull Object owner, @NotNull PluginMetadata metadata, + @Nullable ChatTone tone, @NotNull String title) { + return new ModuleConsoleCard(environment.logging, owner, metadata, + logger(owner, metadata.getId().getValue()), tone, title); + } + @Override public @NotNull MessageBox shutdownBox(@NotNull Object owner, @NotNull String title) { return new StartupBox(environment, owner, title, BoxKind.DISABLED, null, null); diff --git a/modules/core/src/main/java/org/pnfolder/pnlibrary/core/plugin/LoadedModule.java b/modules/core/src/main/java/org/pnfolder/pnlibrary/core/plugin/LoadedModule.java index b774a1069..d8094b075 100644 --- a/modules/core/src/main/java/org/pnfolder/pnlibrary/core/plugin/LoadedModule.java +++ b/modules/core/src/main/java/org/pnfolder/pnlibrary/core/plugin/LoadedModule.java @@ -93,7 +93,7 @@ final class LoadedModule implements ModuleContext, MinecraftForcible { this.expansions = new ModuleExpansions(host.shared.getExpansions(), host.shared.getLibraryExpansions()); this.lifecycle = new ModuleLifecycleReporter(owner, id, metadata, resources, host.logging, host.shared.getPlaceholders(), placeholderApiEnabled, this::isClosed); - this.messages = new ModuleMessages(owner, host.logging); + this.messages = new ModuleMessages(owner, metadata, host.logging); this.actions = new ModuleActionService(resources, host.scenarios, ModuleDiagnosticsName.of(key, id)); } diff --git a/modules/core/src/main/java/org/pnfolder/pnlibrary/core/plugin/module/ModuleMessages.java b/modules/core/src/main/java/org/pnfolder/pnlibrary/core/plugin/module/ModuleMessages.java index fe11284f3..7e65737e9 100644 --- a/modules/core/src/main/java/org/pnfolder/pnlibrary/core/plugin/module/ModuleMessages.java +++ b/modules/core/src/main/java/org/pnfolder/pnlibrary/core/plugin/module/ModuleMessages.java @@ -2,6 +2,10 @@ import java.util.Objects; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.pnfolder.pnlibrary.api.chat.style.ChatTone; +import org.pnfolder.pnlibrary.api.logging.ConsoleCardBuilder; +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMetadata; import org.pnfolder.pnlibrary.api.logging.LoggingService; import org.pnfolder.pnlibrary.api.logging.MessageBox; import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMessages; @@ -9,9 +13,11 @@ /** Plugin message helpers bound to one module owner. */ public final class ModuleMessages implements PluginMessages { private final Object owner; + private final PluginMetadata metadata; private final LoggingService logging; - public ModuleMessages(@NotNull Object owner, @NotNull LoggingService logging) { + public ModuleMessages(@NotNull Object owner, @NotNull PluginMetadata metadata, @NotNull LoggingService logging) { + this.metadata = Objects.requireNonNull(metadata, "metadata"); this.owner = Objects.requireNonNull(owner, "owner"); this.logging = Objects.requireNonNull(logging, "logging"); } @@ -23,4 +29,18 @@ public ModuleMessages(@NotNull Object owner, @NotNull LoggingService logging) { } return logging.box(owner, title.trim()); } + + @Override + public @NotNull ConsoleCardBuilder card(@NotNull String title) { + return newCard(null, title); + } + + @Override + public @NotNull ConsoleCardBuilder card(@NotNull ChatTone tone, @NotNull String title) { + return newCard(Objects.requireNonNull(tone, "tone"), title); + } + + private ConsoleCardBuilder newCard(@Nullable ChatTone tone, String title) { + return logging.card(owner, metadata, tone, title); + } } diff --git a/modules/core/src/main/java/org/pnfolder/pnlibrary/core/text/ConsoleStyle.java b/modules/core/src/main/java/org/pnfolder/pnlibrary/core/text/ConsoleStyle.java index 7ccfac62a..b6dac4851 100644 --- a/modules/core/src/main/java/org/pnfolder/pnlibrary/core/text/ConsoleStyle.java +++ b/modules/core/src/main/java/org/pnfolder/pnlibrary/core/text/ConsoleStyle.java @@ -1,5 +1,6 @@ package org.pnfolder.pnlibrary.core.text; +import java.util.regex.Pattern; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.TextColor; import net.kyori.adventure.text.format.TextDecoration; @@ -18,6 +19,7 @@ public final class ConsoleStyle { private static final LegacyComponentSerializer LEGACY = LegacyComponentSerializer.legacySection(); private static final String PROBE = "|"; + private static final Pattern STYLES = Pattern.compile(LegacyComponentSerializer.SECTION_CHAR + "[0-9a-fk-orxA-FK-ORX]"); /** Turns bold on until the next color or {@link #RESET}. */ public static final String BOLD = format(Component.text(PROBE).decorate(TextDecoration.BOLD)); @@ -38,17 +40,47 @@ private ConsoleStyle() { return theme(tone.getColor()); } + /** {@link #theme(ChatTone)} with any accent color. */ + public static @NotNull ConsoleTheme theme(@NotNull TextColor accent) { + return new ConsoleTheme(color(ChatPalette.ACCENT), color(accent), color(ChatPalette.TEXT), + color(ChatPalette.SOFT), RESET, color(ChatPalette.SOFT), BOLD); + } + + /** The whole card in the tone's color. */ + public static @NotNull ConsoleTheme solid(@NotNull ChatTone tone) { + return solid(tone.getColor()); + } + + /** The whole card in {@code color}. */ + public static @NotNull ConsoleTheme solid(@NotNull TextColor color) { + String code = color(color); + return new ConsoleTheme(code, code, code, code, RESET, code, BOLD); + } + + /** Frame, mascot, branches and title in the tone's color, detail text in white. */ + public static @NotNull ConsoleTheme alert(@NotNull ChatTone tone) { + return alert(tone.getColor()); + } + + /** {@link #alert(ChatTone)} with any color. */ + public static @NotNull ConsoleTheme alert(@NotNull TextColor color) { + String code = color(color); + String white = color(ChatPalette.TEXT); + return new ConsoleTheme(code, code, white, code, RESET, white, BOLD); + } + /** The sequence that switches to the nearest legacy color of {@code color}. */ public static @NotNull String color(@NotNull TextColor color) { return format(Component.text(PROBE, color)); } - public static @NotNull String paint(@NotNull String text, @NotNull TextColor color) { - return color(color) + text + RESET; + /** {@code text} without any color or format sequences. */ + public static @NotNull String strip(@NotNull String text) { + return STYLES.matcher(text).replaceAll(""); } - private static ConsoleTheme theme(TextColor accent) { - return new ConsoleTheme(color(ChatPalette.ACCENT), color(accent), color(ChatPalette.TEXT), color(ChatPalette.SOFT), RESET); + public static @NotNull String paint(@NotNull String text, @NotNull TextColor color) { + return color(color) + text + RESET; } /** The style sequence the serializer writes in front of a one-character probe. */ diff --git a/modules/core/src/test/java/org/pnfolder/pnlibrary/core/logging/ModuleConsoleCardTest.java b/modules/core/src/test/java/org/pnfolder/pnlibrary/core/logging/ModuleConsoleCardTest.java new file mode 100644 index 000000000..da006f7d3 --- /dev/null +++ b/modules/core/src/test/java/org/pnfolder/pnlibrary/core/logging/ModuleConsoleCardTest.java @@ -0,0 +1,144 @@ +package org.pnfolder.pnlibrary.core.logging; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import org.junit.jupiter.api.Test; +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette; +import org.pnfolder.pnlibrary.api.chat.style.ChatTone; +import org.pnfolder.pnlibrary.api.logging.CardTree; +import org.pnfolder.pnlibrary.api.logging.ConsoleCardBuilder; +import org.pnfolder.pnlibrary.api.logging.LogLevel; +import org.pnfolder.pnlibrary.api.platform.PlatformType; +import org.pnfolder.pnlibrary.api.plugin.ModuleContext; +import org.pnfolder.pnlibrary.api.plugin.ModuleId; +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMetadata; +import org.pnfolder.pnlibrary.core.plugin.LoadedPlugins; +import org.pnfolder.pnlibrary.core.plugin.PluginRegistryFixture; +import org.pnfolder.pnlibrary.core.plugin.module.ModuleMessages; +import org.pnfolder.pnlibrary.core.text.ConsoleStyle; + +class ModuleConsoleCardTest { + private final TestPlatform platform = new TestPlatform("pnAuth"); + private final ModuleMessages messages = new ModuleMessages(this, + new PluginMetadata(ModuleId.of("pnauth"), "pnAuth", "1.3.3", "pnFolder", + PlatformType.VELOCITY, "Velocity", "21", 21), + new ModuleLogging(platform, platform, platform, platform)); + + @Test + void aMinimalCardHasOnlyTheFrameAndItsOwnBlocks() { + messages.card("МОЙ БЛОК").section("Инфо").item("Привет").show(); + + assertEquals(Arrays.asList("", + " ━━━━━━━━━━━ МОЙ БЛОК ━━━━━━━━━━━", + " ┌ Инфо", + " └ Привет", + " ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━", + ""), plain(platform.lines)); + } + + @Test + void connectorsFollowNeighboursAndTheOwnerComesFromTheModule() { + List lines = plain(messages.card("X") + .owner("x.x", "проблемы") + .detail("Конфиг", "config.yml").detail("Прокси", "velocity.toml") + .detail("Очень длинная подпись строки номер три", 3) + .blank() + .detail("Одна", null) + .tree(CardTree.of("Корень", CardTree.of("Ветка").leaves("а", "б"), CardTree.of("Конец"))) + .support() + .render()); + String text = String.join("\n", lines); + + assertTrue(text.contains("( x.x ) pnAuth@pnauth 1.3.3"), text); + assertTrue(text.contains("┌ Конфиг") && text.contains("├ Прокси") && text.contains("└ Очень"), text); + assertEquals(column(lines, "config.yml"), column(lines, "velocity.toml"), text); + assertTrue(text.contains("└ Одна"), text); + assertTrue(text.contains("│ └ б") && text.contains("└ Конец"), text); + assertTrue(text.contains("Вопросы и ошибки: https://"), text); + } + + @Test + void longTextWrapsUnderItsBranch() { + String longText = String.join(" ", Collections.nCopies(30, "слово")); + List lines = plain(messages.card("X").section("S").item(longText).item("конец") + .tree(CardTree.of("root", CardTree.of(longText), CardTree.of("z"))).render()); + + assertEquals(4, lines.stream().filter(line -> line.startsWith(" │ слово")).count(), lines.toString()); + assertTrue(lines.stream().allMatch(line -> line.length() < 100), lines.toString()); + } + + @Test + void aSolidCardIsOneColorIncludingTheCallersText() { + String red = ConsoleStyle.color(NamedTextColor.RED); + List lines = messages.card(ChatTone.FAILURE, "ОШИБКА") + .owner("x.x", "стоп") + .detail("a", "b").section("s").item("i").tree(CardTree.of("t").child("c")) + .line(Component.text("зелёная", NamedTextColor.GREEN)) + .divider("d").support().status("конец") + .solid() + .render(); + + for (String line : lines) { + if (line.isEmpty()) { + continue; + } + assertTrue(line.startsWith(red), line); + String rest = line.replace(red, "").replace(ConsoleStyle.BOLD, "").replace(ConsoleStyle.RESET, ""); + assertTrue(rest.indexOf('§') < 0, line); + } + assertTrue(lines.get(1).contains(ConsoleStyle.BOLD + "ОШИБКА")); + assertTrue(lines.stream().anyMatch( + line -> line.startsWith(red + ConsoleStyle.BOLD) && line.contains("■ конец"))); + } + + @Test + void standardAndAlertColorFrameAndDetailTextDifferently() { + String red = ConsoleStyle.color(ChatPalette.DANGER); + String white = ConsoleStyle.color(ChatPalette.TEXT); + ConsoleCardBuilder card = messages.card(ChatTone.FAILURE, "T").item("текст"); + + List standard = card.render(); + assertTrue(standard.get(1).startsWith(ConsoleStyle.THEME.border)); + assertTrue(standard.get(2).startsWith(ConsoleStyle.color(ChatPalette.SOFT))); + + List alert = card.alert().render(); + assertTrue(alert.get(1).startsWith(red)); + assertTrue(alert.get(2).startsWith(red) && alert.get(2).contains(white + "текст"), alert.get(2)); + + List recolored = card.color(NamedTextColor.GREEN).render(); + assertTrue(recolored.get(1).startsWith(ConsoleStyle.color(NamedTextColor.GREEN))); + } + + @Test + void aRegisteredModuleBuildsCardsAndRecordsQuietly() { + LoadedPlugins registry = PluginRegistryFixture.builder() + .logging(new ModuleLogging(platform, platform, platform, platform)).build(); + ModuleContext context = registry.register(new Object()).registerModule("auth", plugin -> + plugin.metadata(metadata -> metadata.name("pnAuth").version("1.3.3"))); + platform.lines.clear(); + + context.getMessages().card(ChatTone.WARNING, "T") + .record(LogLevel.WARNING, "routing problem") + .owner("o.o", null) + .send(); + + assertTrue(plain(platform.lines).stream().anyMatch(line -> line.contains("pnAuth@auth 1.3.3"))); + assertTrue(platform.lines.stream().noneMatch(line -> line.contains("routing problem"))); + context.close(); + } + + private static int column(List lines, String value) { + return lines.stream().filter(line -> line.contains(value)).findFirst().get().indexOf(value); + } + + private static List plain(List lines) { + return lines.stream().map(line -> line.replaceAll("§[0-9a-fk-or]", "")).collect(Collectors.toList()); + } +}