diff --git a/CHANGELOG.md b/CHANGELOG.md index 6989437..da5b699 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,100 @@ ## Unreleased +## Version 1.3.0 + +### New Features + +#### Towns + ++ Added a founding credit. Every player without a town is given one once, the next time they join, on top of their + starting balance. Only founding a town with `/t new` can spend it: it comes off the price Towny charges, so a new + player who spends their balance by mistake can still found a town. + + Joining someone else's town gives the credit up. It is never paid out as money. + + `/balance` shows the credit while you hold it. + + Set the amount with `towns.founding-credit` (default `100.0`), or `0` to turn it off. + +#### Main Menu + ++ Added a main menu. Every player carries a glowing menu item in the last slot of their hotbar; right-click it — or + click it in your inventory, or run `/tritown menu` — to open it. + + Your profile sits at the top: balance, founding credit, leaderboard rank, town and nation. + + Below it: your town at a glance (residents, bank, upkeep, time to the new day) with a shortcut into TownyMenu, + the global shop, trading, paying, the leaderboard, the server's vital signs, a sidebar switch, and the admin + panel for those allowed it. + + Anything switched off on the server, or that you are not allowed to use, is left out rather than greyed, and + each row is centred on what remains. + + **Trade** lists the players close enough to trade with, nearest first, with anyone waiting for your answer + first and glowing; click one to ask, or to accept. **Pay** lists everyone online and asks for the amount in + chat. Both run `/trade` and `/pay`, so the same rules and permissions apply. + + **Leaderboard** shows the richest players as heads, gold, silver and bronze at the top, with your own rank on + every page. ++ The menu item cannot be moved, dropped, stored, crafted with, placed or handed to anything — including item + frames, armour stands, allays and the trade table. A copy that turns up anywhere but its slot is deleted within a + second, and it is taken off you when you log out, so it is never saved and never left behind. Whatever was in the + slot before is moved into your inventory, or dropped at your feet if it is full. ++ `main-menu.item.enabled` turns the item off (the menu stays reachable with `/tritown menu`), and + `main-menu.item.material` picks what it is — a nether star by default. + +#### News + ++ Added server news: update notes administrators write in game and every player reads from the main menu or with + `/tritown news`. + + A post has a title, an optional summary and label (such as `v1.3`), and categories of short entries — a line + or two about one change each. Every entry carries a tag: New, Changed, Fixed, Removed or Note. + + Posts are listed pinned first, then newest. Inside a post, its card sits at the top and its categories follow + in order, each one's entries read straight off its card; a long one opens to show them one by one, and + **Read as a book** shows the whole post as pages. ++ Players are told what they have missed. + + Joining with unread posts lists them in chat a moment later, each one a link to the post. + + The **News** button in the main menu glows while anything is unread and stacks up to the number unread, and the + menu item's description counts them too. + + Publishing a post can announce it to everyone online with a title, a sound and a link, or go out quietly. + + A new player only has the newest post waiting for them, not the whole backlog. `/tritown news readall` (or + **Mark all as read**) clears the rest. ++ Posts are written entirely in menus, with `tritown.news.manage`: open **Manage** in the news, or run + `/tritown news manage`. + + A post starts as a draft that only editors can see, can be previewed exactly as players will see it, and is + published when it is ready. It can be taken back to drafts, and deleting it asks first. + + **Write entries** takes one line after another in chat until you type `done`. Starting a line with `+`, `*`, + `!`, `-` or `?` tags it New, Changed, Fixed, Removed or Note; without one it keeps the tag of the line before. + + Categories and entries can be reordered, retagged and removed, a post can be pinned to the top, and a post or + category takes its icon from any item you click in your inventory. + + Every title, summary, category name and entry can be translated into each language the server has, and players + read their own language, falling back to the text as first written. ++ The `news` block of `config.yml` switches the news off, sets the join message's delay and length, what an + announcement shows and plays, and how long an entry may be (`max-entry-length`, default 200). + +### Improvements + +#### Economy + ++ Raised the default starting balance from 100 to 200. Existing servers keep the value already in their + `config.yml`. + +#### Admin Panel + ++ The admin panel now opens at full size, keeps its cards centred when you may not open one of them, and has a + button back to the main menu. + +### Technical Details + +#### Misc + ++ `PagedLayout.CENTERED` frames a paged menu like `FRAMED` and centres a page that is not full, and `GUIFrame` gained + `spacedColumns`, `packedColumns` and `centeredSlots` for laying out rows of buttons and short lists. + `PagedPluginGUI.contentIndex` now takes the click event, since on a centred page the slot an item lands in depends + on how many share it. ++ `GUIManager` no longer delivers clicks and drags that are already cancelled, so a guard at a lower priority can + refuse a click knowing no menu will act on it. ++ `CommandRegistrar.find`, `canRun` and `run` let a menu run one of TriTown's commands directly, with its permission + check, whatever label it ended up registered under. ++ `PagedPluginGUI.topButtons` places items over the top border of a framed menu, where they stay put as the pages turn. ++ `ConfirmGUI` asks before something that cannot be undone: a subject, up to three choices with actions, and Cancel. ++ `Lang.idFor` gives the language a sender reads, for text kept outside the language files. ++ The atomic write the shop file used (temporary file, `.bak`, atomic move) is now `AtomicFile`, shared with the news + file. + ## Version 1.2.0 ### New Features diff --git a/CLAUDE.md b/CLAUDE.md index 8354135..634d92d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -68,23 +68,27 @@ The server console reads commands from the terminal running Gradle. src/main/kotlin/net/trilleo/mc/plugins/tritown/ ├── Main.kt # Plugin entry point (Main.instance, Main.reload()) ├── commands/ # Sub-commands (auto-registered) -│ ├── admin/ economy/ info/ -│ └── moderation/ scoreboard/ shop/ +│ ├── admin/ economy/ info/ menu/ news/ +│ └── moderation/ scoreboard/ shop/ trade/ ├── config/ # PluginConfig (typed config.yml wrapper), EconomySettings ├── data/ # JSON-persisted PlayerData / ServerData and their managers ├── economy/ # The economy: ledger, accounts, currencies, Vault provider, statistics, │ # storage (not scanned) ├── enums/ # AccountType, FlowCategory, StatsWindow, TransactionType, FillMode, … -├── guis/ # GUIs (auto-registered, extend PluginGUI / PagedPluginGUI); admin/ is the panel +├── guis/ # GUIs (auto-registered, extend PluginGUI / PagedPluginGUI); admin/ is the panel, +│ # menu/ the main menu, news/ the news; ConfirmGUI asks before the irreversible ├── items/ # Custom items (auto-registered, extend PluginItem) ├── listeners/ # Event listeners, including Towny events (auto-registered) +├── menu/ # The main menu item and the invariant that keeps it unique (not scanned) +├── news/ # Server news: posts, storage, read state, notifications (not scanned) ├── recipes/ # Recipes (auto-registered, implement PluginRecipe) ├── registration/ # Auto-registration engine (do not modify lightly) ├── shops/ # Admin shops: model, trading, storage, FancyNpcs bridge (not scanned) ├── tasks/ # Scheduled tasks (auto-registered, extend PluginTask) +├── towns/ # Town founding credit (not scanned) ├── trades/ # Player trades: sessions, escrow, the swap (not scanned) └── utils/ # Lang, EconomyUtil, InventoryUtil, itemStack DSL, MessageUtil, LoreUtil, - # ChatPrompt, CountdownUtil, TeamUtil, TagUtil, PDCUtil, GameRuleUtil + # ChatPrompt, CountdownUtil, TeamUtil, TagUtil, PDCUtil, GameRuleUtil, AtomicFile src/main/resources/ ├── config.yml plugin.yml └── lang/ # en_US.yml, zh_CN.yml — every player-facing string @@ -94,8 +98,9 @@ src/main/resources/ The plugin uses `PackageScanner` to discover components at startup — you **never** edit `plugin.yml` or wire things manually. Just extend the right base class and place the file in the correct package. Packages outside the table below -are never scanned, which is why the economy core lives in `economy/`, the shop core in `shops/` and the trade core -in `trades/`: each has to be alive before the registrars build the commands and menus that read it. +are never scanned, which is why the economy core lives in `economy/`, the shop core in `shops/`, the trade core +in `trades/` and the news core in `news/`: each has to be alive before the registrars build the commands and menus that read it. `menu/` is outside +the scan for a simpler reason: `MenuItem` is not a `PluginItem`, because it is named in each holder's language. | Component | Base Class | Package | |:------------|:-------------------------------|:------------------------| @@ -267,6 +272,38 @@ The panel in `guis/admin` is where an owner reads the server; `/tritown admin` o - **Both windows are drawn for their viewer**, never for a side, and anything that changes the table calls `TradeGUI.redraw` so the two can never disagree. +## Working with the Main Menu + +The main menu (`guis/menu`) is how players reach TriTown, opened from the menu item in hotbar slot 8 or with +`/tritown menu`. See [Main Menu](docs/DEVELOPER_GUIDE.md#main-menu). + +- **The menu points the way; it never does the work.** A button runs the command or opens the menu that owns the + action — through `CommandRegistrar.run`, never by repeating its logic — so each rule and message lives in one place. +- **Leave out what the viewer cannot use**, and lay the rest out with `GUIFrame.spacedColumns` so each row stays + centred. Never draw a greyed-out button, and never fix a slot that leaves a hole when a button is missing. +- **The main menu and every menu it opens are six rows.** +- **`MenuItem.reconcile` is the only code that creates a menu item.** The invariant is one copy, in slot 8, only while + the player is online. A new way the item could move gets a guard in `MenuItemListener` (cancel at `LOWEST`, then + `reconcileLater` if the client may be out of step), never a second place that hands out or restores a copy. +- **Never let a menu act on a cancelled click.** `GUIManager` already skips them; a GUI that listens to inventory + events itself must do the same, or a refused click on the menu item reaches it anyway. + +## Working with News + +**Update notes administrators write in game and every player reads.** See +[Server News](docs/DEVELOPER_GUIDE.md#server-news). + +- **Go through `NewsManager`** — it is the only thing that reads or writes a post. After editing a post in place, call + `NewsManager.changed(post)`, which saves at once and dates a published post as edited. +- **A post's words are the administrator's, not translation keys.** Titles, summaries, category names and entries are + `LocalizedText` MiniMessage, embedded as written; read them with `forViewer(player)`, never `tr`. Only the words + around a post live in the language files. +- **Unread comes from `NewsReadState` and nowhere else**, and `unread` must stay one pass over the published posts: + the menu item reads it every second for every player. +- **Keep the model free of Bukkit types** — it is the file's shape. An icon is a material's name, read back through + `NewsRender.material`. +- **Every editor click re-checks `tritown.news.manage`**, not only the command that opened the menu. + ## Versioning & Releases - `plugin_version` in [gradle.properties](gradle.properties) is the single source of truth for the plugin version. It diff --git a/README.md b/README.md index fb02fe4..144ded0 100644 --- a/README.md +++ b/README.md @@ -12,12 +12,27 @@ TriTown is in early development; see the [change log](CHANGELOG.md) for what has shipped. +**A menu in every hotbar.** Every player carries a glowing item in the last slot of their hotbar; right-click it, or +run `/tt menu`, for everything TriTown offers in one place. Your profile sits at the top — balance, founding credit, +leaderboard rank, town and nation — and below it are your town at a glance with a shortcut into +[TownyMenu](https://github.com/Trilleo/TownyMenu), the global shop, a list of the players near enough to trade with +(anyone waiting for your answer first), a list of players to pay, the richest players as heads, the server's vital signs, +the server news, a sidebar switch, and the admin panel for those allowed it. Anything switched off on the server, or that you may not +use, is simply left out, and what remains is centred. The item cannot be moved, dropped, stored, crafted with or handed +to anything, a copy made any other way is deleted within a second, and it is taken off you when you log out, so there +is nothing to duplicate and nothing left behind if TriTown is ever removed. + **A built-in economy.** TriTown supplies the server's Vault economy itself, so Towny gets working player wallets and town and nation banks without a separate economy plugin such as EssentialsX. Balances are stored as whole units of the smallest denomination, so they never drift, and they are written to disk atomically with a backup copy. The currency, starting balance, balance cap and formatting are all configurable. If you would rather keep another economy plugin, `economy.provider.mode` tells TriTown to stand aside and use it instead. +**A first town nobody can lose.** Every player without a town is given a founding credit once, on top of their +starting balance. Only founding a town with `/t new` can spend it: TriTown takes it off the price Towny charges, so a +new player who spends their balance by mistake can still found a town. Joining someone else's town gives it up, and +`/balance` shows it while you hold it. + **A sidebar that follows you.** A scoreboard that changes with where you are standing: a new player without a town is pointed at joining one, your own claims show your town's level, residents, land, bank, upkeep and any warning, another town's claims show whose land it is and what the plot costs, and enemy territory says so. Values sit under headings that @@ -40,6 +55,15 @@ cannot be spent behind their back, and anything changing on the table clears bot swapped out after somebody has agreed to it. Everything comes straight back if either of you closes the menu, walks away or disconnects. +**Server news.** Update notes, written in game and read from the main menu or with `/tt news`. A post is a title and +categories of short entries — a line or two about one change each, tagged New, Changed, Fixed, Removed or Note — read +straight off the menu, or as a book when it runs long. Players hear about what they have missed: a list of unread posts, +each a link, a moment after they join; a **News** button that glows and counts them; and, when a post is published, an +announcement to everyone online (or none, for a small post). Posts are written entirely in menus: start a draft, +type entries into chat one line after another (a leading `+`, `*`, `!`, `-` or `?` picks the tag), preview it as +players will see it, pin it, and publish it when it is ready. Every title and entry can be translated into each of the +server's languages, and players read their own. + **An admin panel.** `/tt admin` opens a menu that reads the server back to you. The economy section shows how much currency exists and who holds it, what created it and what removed it — new players, shops, Towny, administrators or another plugin — with the net drift per day, how unevenly wealth is spread, how fast money circulates, and a chart of @@ -63,11 +87,13 @@ built on. | Towny | 0.103.2.7+ | | Vault | 1.7+ | | FancyNpcs | 2.9+ — optional, for shop NPCs | +| TownyMenu | Optional — for the town shortcut | | Economy plugin | Not required — TriTown provides one | TriTown is an addon: Towny and Vault must both be installed, or TriTown will not load. An economy plugin is optional — install one only if you want it to supply the economy instead of TriTown, and set `economy.provider.mode` accordingly. -FancyNpcs is optional too: without it shops still work, they just cannot be opened by clicking an NPC. +FancyNpcs is optional too: without it shops still work, they just cannot be opened by clicking an NPC. So is +TownyMenu: without it the main menu simply has no town button. ## Building @@ -92,6 +118,7 @@ Prebuilt jars are attached to every [GitHub release](https://github.com/Trilleo/ | Command | Description | |:-------------------------|:--------------------------------------| | `/tt help` | List all available commands | +| `/tt menu` | Open the main menu | | `/tt reload` | Reload the configuration (OP only) | | `/balance [player]` | Check your balance, or someone else's | | `/pay ` | Send money to another player | @@ -101,6 +128,7 @@ Prebuilt jars are attached to every [GitHub release](https://github.com/Trilleo/ | `/trades` | Open the server's global shop | | `/trade ` | Ask another player to trade | | `/tt shop …` | Set up the server's shops (OP only) | +| `/tt news` | Read the server news | | `/tt admin [section]` | Open the admin panel (OP only) | `/eco` takes `give`, `take` and `set` (` [currency]`), `reset ` back to the starting balance, @@ -117,6 +145,10 @@ permission, `tritown.shop.admin.`. Players have no shop command of their have to be within `player-trades.distance` blocks of each other, and have to stay that close for as long as the menu is open. There is no permission node: whether players may trade at all is `player-trades.enabled`. +`/tt news` opens the news; it also takes `open ` for one post (what the links in chat run), `readall` to mark +every post read, and `manage` to write them, which needs `tritown.news.manage` — as does the **Manage** button in the +news. + `/tt admin` opens the panel itself, and `economy` or `shops` opens that section directly. Opening the panel needs `tritown.admin`; the sections need `tritown.admin.economy` and `tritown.admin.shops` on top of it. @@ -131,6 +163,8 @@ version stays available as `/tritown:balance` and so on. |:------------------------------------------|:-------------------|:--------------------------------------------------------------------------------| | `message-prefix` | — | MiniMessage prefix shown before plugin messages | | `language` | `auto` | `auto` follows each player's client, or a language id such as `zh_CN` | +| `main-menu.item.enabled` | `true` | Keep the menu item in the last hotbar slot of every player | +| `main-menu.item.material` | `NETHER_STAR` | What the menu item is; any item works | | `economy.enabled` | `true` | Turn the economy off entirely | | `economy.provider.mode` | `auto` | `internal`, `external` or `auto` — who supplies the Vault economy (restart) | | `economy.provider.defer-to` | common eco plugins | Which installed plugins `auto` stands aside for | @@ -140,7 +174,7 @@ version stays available as `/tritown:balance` and so on. | `economy.currency.fractional-digits` | `2` | Digits kept after the decimal point (see below) | | `economy.currency.format` | `%symbol%%amount%` | Plain pattern other plugins print verbatim — no MiniMessage tags | | `economy.currency.rich-format` | `…` | MiniMessage pattern for TriTown's own messages | -| `economy.starting-balance` | `100.0` | Balance granted on a player's first join | +| `economy.starting-balance` | `200.0` | Balance granted on a player's first join | | `economy.balance-cap` | `1000000000.0` | Largest balance an account may hold; `0` removes the cap | | `economy.minimum-payment` | `0.01` | Smallest amount a payment will accept | | `economy.allow-negative-balances` | `false` | Whether a withdrawal may take an account below zero | @@ -167,6 +201,14 @@ version stays available as `/tritown:balance` and so on. | `player-trades.enabled` | `true` | Turn player-to-player trading off entirely | | `player-trades.distance` | `10.0` | How close two players must be to trade, and stay while the menu is open | | `player-trades.request-expiry` | `60` | Seconds an unanswered trade request stands | +| `towns.founding-credit` | `100.0` | Credit only `/t new` can spend, given once to players without a town; `0` is off | +| `news.enabled` | `true` | Turn the server news off entirely | +| `news.join-message.enabled` | `true` | List a player's unread posts a moment after they join | +| `news.join-message.delay-seconds` | `3` | How long after joining | +| `news.join-message.preview` | `3` | How many unread titles that list names | +| `news.announce.title` / `.chat` | `true` | Title and chat link everyone online gets when a post is announced | +| `news.announce.sound` | a chime | Sound played with the announcement; `""` for none | +| `news.max-entry-length` | `200` | Most characters one entry may have, not counting colour tags | | `scoreboard.enabled` | `true` | Turn the sidebar off entirely | | `scoreboard.refresh-interval` | `2` | Seconds between redraws of a sidebar nothing has changed on | | `scoreboard.default-on` | `true` | Whether a player who has never used `/tt scoreboard` sees one | diff --git a/docs/DEVELOPER_GUIDE.md b/docs/DEVELOPER_GUIDE.md index 405e5b0..4865a27 100644 --- a/docs/DEVELOPER_GUIDE.md +++ b/docs/DEVELOPER_GUIDE.md @@ -2,7 +2,7 @@ This guide explains how to create **commands**, **listeners**, **GUIs**, **tasks**, **custom items**, **recipes**, work with **translations** and the **configuration** system using TriTown's registration system, and how to build on -**Towny**, the **Vault economy**, the **admin panel**, **shops**, **player trades** and the **sidebar**. Commands, listeners, GUIs, tasks, custom items, and recipes all +**Towny**, the **Vault economy**, the **admin panel**, **shops**, **player trades**, the **news** and the **sidebar**. Commands, listeners, GUIs, tasks, custom items, and recipes all follow the same pattern: extend a base class (or implement an interface), place the file in the correct package, and the plugin handles the rest automatically at startup. The configuration system provides typed access to `config.yml` values. @@ -126,6 +126,22 @@ class EconomyAdminCommand : PluginCommand( | `execute` | Yes | Called when a player or console runs the command | | `tabComplete` | No | Called when tab-completion is requested | +### Running a Command from Code + +A menu button that does what a command already does should run that command rather than repeat it, so every check and +message stays in one place. `CommandRegistrar` finds a command by name whether it is a sub-command of `/tritown` or a +command of its own, which matters because a main command whose label another plugin owns is only reachable as +`/tritown:` — dispatching a typed line would reach the wrong plugin: + +```kotlin +CommandRegistrar.canRun(player, "pay") // false when the command is missing or its permission is not held +CommandRegistrar.run(player, "pay", target, amount) // checks the permission, then calls execute +CommandRegistrar.find("pay") // the PluginCommand itself, or null +``` + +`run` returns `false` only when there is no such command; a sender without the permission is told so, as though they +had typed it. + ### Example (Sub-Command) This command is registered as `/tritown ping` (the default behavior): @@ -354,6 +370,11 @@ Never open another inventory from inside a click handler: the click is still bei end up disagreeing about what is on screen. Use `GUIManager.openLater(player, id)`, which opens it on the following tick. +**A click or drag that is already cancelled never reaches a GUI.** `GUIManager` listens with `ignoreCancelled = true`, +so a guard that runs earlier — the [menu item's](#main-menu), at the lowest priority — can refuse a click and know that +no menu will act on it anyway. This is what stops a menu that takes items out of the player's inventory, such as the +trade table or the shop editor, from escrowing or selling something that must not move. + ### Opening a GUI Use `GUIManager.open(player, id)` to open a registered GUI for a player: @@ -382,6 +403,40 @@ if (open?.id == "settings") GUIManager.refresh(player) lets a menu change under somebody — the other side of a trade adding an item, a figure that has moved on. It works on any player, not only the one whose click you are handling, so a menu two people share can keep both windows the same. +### GUIFrame + +`GUIFrame` holds the border every framed menu shares and the slot arithmetic for laying things out inside it. It is +pure arithmetic apart from `pane` and `draw`, and `GUIFrameTest` pins it down. + +| Member | Returns | +|:------------------------------|:---------------------------------------------------------------------------------------| +| `pane()` | One border slot: black glass with no tooltip | +| `contentSlots(rows)` | The slots inside the border, in reading order | +| `draw(inventory, slots)` | Fills every slot not in `slots` with the border | +| `spacedColumns(count)` | Columns for up to 4 buttons spread with a gap between each, centred (`4`; `3, 5`; …) | +| `packedColumns(count)` | Columns for up to 7 items side by side, centred; an even count leaves column 4 empty | +| `centeredSlots(rows, count)` | Slots for `count` items in rows of seven, last row packed, the block centred vertically | + +A menu of buttons whose set depends on the viewer — a permission, a feature switched off — should lay each row out with +`spacedColumns` from the buttons it actually has, rather than fixing slots and leaving a hole where one is missing. +`MainMenuGUI` and `AdminPanelGUI` both do this. + +### ConfirmGUI + +`ConfirmGUI` (in `guis/`) asks before something that cannot be undone. It shows what is at stake at the top and the +answers along a row beneath it — one to three choices of the caller's, then Cancel — and runs whichever is clicked on +the next tick, so an answer may open another menu. Closing it answers nothing. + +```kotlin +ConfirmGUI.show( + player, + title = player.tr("gui.news-manage.delete-title"), + subject = card, + choices = listOf(ConfirmGUI.Choice(deleteButton) { NewsManager.delete(post); NewsManageGUI.show(it) }), + onCancel = { NewsEditorGUI.show(it, post) }, +) +``` + ### Example ```kotlin @@ -473,22 +528,29 @@ For example, a 6-row GUI provides 45 content slots per page (rows 1–5). ### Layouts -| Layout | Content slots (6 rows) | Description | -|:---------------------|:-----------------------|:----------------------------------------------------------------------------| -| `PagedLayout.FULL` | 45 | Every slot above the navigation row is content | -| `PagedLayout.FRAMED` | 28 | Content is inset by one slot on every side, with a black glass border round it | +| Layout | Content slots (6 rows) | Description | +|:-----------------------|:-----------------------|:-------------------------------------------------------------------------------| +| `PagedLayout.FULL` | 45 | Every slot above the navigation row is content | +| `PagedLayout.FRAMED` | 28 | Content is inset by one slot on every side, with a black glass border round it | +| `PagedLayout.CENTERED` | 28 | Framed, and a page that is not full keeps its items centred inside the border | A framed menu carries the border into its navigation row too, so the whole edge is one colour rather than changing where the controls start. +`CENTERED` is for lists that are often short, such as the players online. A full page looks exactly like `FRAMED`; a +page of a few items puts them in the middle of the menu rather than in its top-left corner, with the last row packed +around the centre column (see [`GUIFrame`](#guiframe)). It only changes `LIST` mode — `SET` positions are explicit. + **Do not index `getItems` by the raw slot.** Under a framed layout a slot is not a position in that list, because the -border sits between them. Use `contentIndex(page, rawSlot)`, which returns the position or `null` when the slot holds -no content: +border sits between them, and on a centred page the slot an item lands in depends on how many share the page. Use +`contentIndex(event, page)`, which reads the slots as they were drawn for that viewer and returns the position or +`null` when the slot is not content (an empty slot inside a `FULL` or `FRAMED` area still has a position, one past the +end of the list): ```kotlin override fun onContentClick(event: InventoryClickEvent, page: Int) { event.isCancelled = true - val index = contentIndex(page, event.rawSlot) ?: return + val index = contentIndex(event, page) ?: return val entry = entries.getOrNull(index) ?: return … } @@ -504,7 +566,7 @@ leaving a page steps back rather than showing an empty one: ```kotlin override fun onContentClick(event: InventoryClickEvent, page: Int) { event.isCancelled = true - val index = contentIndex(page, event.rawSlot) ?: return + val index = contentIndex(event, page) ?: return entries.removeAt(index) refresh(event.whoClicked as Player, event.inventory) } @@ -528,6 +590,7 @@ override fun onContentClick(event: InventoryClickEvent, page: Int) { | `onContentClick` | Both | No | Handle clicks on content slots (clicks are cancelled by default) | | `navButtons` | Both | No | Buttons to place in the navigation row, keyed by offset | | `onNavClick` | Both | No | Handle clicks on those buttons | +| `topButtons` | Both | No | Items over the top border of a framed menu, by offset (0 to 8) | A `SET` position is an index into the content area, not an inventory slot, for the same reason `contentIndex` exists. @@ -2085,6 +2148,24 @@ class NewTownListener : Listener { } ``` +### Founding Credit + +`towns/FoundingCredit` (not scanned) holds a credit that only `/t new` can spend. It is sized by `towns.founding-credit` +(`TownSettings`) and wired up by `listeners/town/FoundingCreditListener`: + +- **Granted and forfeited on join.** A player whose `PlayerData` has no `founding-credit` state is given the credit if + Towny says they have no town, and marked `ineligible` otherwise. A player still holding one who has a town by the + time they join (someone added them while they were offline) forfeits it. The join handler runs at `HIGH` so the + player's data has loaded first. +- **Spent through the price, never paid out.** `PreNewTownEvent` fires before Towny checks funds, and the handler at + `HIGHEST` lowers `price` by the credit. Towny then confirms and charges the rest itself, and a price of 0 skips the + withdrawal. No money moves, so there is nothing for the economy statistics to record. Founding just drains less. +- **Settled on `TownAddResidentEvent`.** Towny adds the founder as the first resident part-way through creating a + town, so that one event sees both outcomes. If the town is the one the player was just quoted a reduced price for + and they are its only resident, the credit is `used`. Any other town makes it `forfeited`. A `/t new` that is never + confirmed spends nothing. +- **The amount is read live** from the config, so only the state is stored per player. + ### Bumping Towny Change `towny_version` in `gradle.properties` and the Requirements table in `README.md` together. @@ -2405,6 +2486,69 @@ Amounts are **minor units** throughout, exactly as the ledger holds them; they b --- +## Main Menu + +The main menu is where a player reaches everything TriTown offers. It lives in `guis/menu`, and is opened by +right-clicking the menu item or with `/tritown menu` (`commands/menu/MenuCommand`, no permission). + +| Menu | Id | Shows | +|:------------------|:-------------------|:--------------------------------------------------------------------------| +| `MainMenuGUI` | `main-menu` | The viewer's profile, then rows of buttons for what they may use | +| `PlayerPickerGUI` | `menu-players` | Players to trade with (`Mode.TRADE`, only those in range) or pay (`PAY`) | +| `LeaderboardGUI` | `menu-leaderboard` | The top 112 of `BaltopCache` as heads, with the viewer's rank on each page | + +Every one of them opens at six rows. `MainMenuGUI` puts the profile alone at the top and lays the buttons out in rows of +up to three with `GUIFrame.spacedColumns`. **A button for something switched off or not permitted is left out, not +greyed**, and each row is centred on what remains: the global shop only when shops are on and the viewer passes its +gate, trading only when `player-trades.enabled`, pay and the leaderboard only with the economy running and the +command's permission (`CommandRegistrar.canRun`), the news only while `NewsManager.isAvailable`, the sidebar switch +only while the sidebar runs, the admin panel only with `tritown.admin`, and the TownyMenu shortcut only when TownyMenu is enabled. Empty rows are dropped, so the menu +never has a hole in it. The two list menus use `PagedLayout.CENTERED` and keep *Back* and one extra button either side +of the page number (`MenuRender.BACK_OFFSET`, `EXTRA_OFFSET`). + +**The menu points the way; it does not do the work.** Each button runs the command or opens the menu that already owns +the action — `/trades`, `/trade `, `/pay `, `/tritown news` through `CommandRegistrar.run`, the admin panel, +TownyMenu through its own `/townymenu` — so there is exactly one place each rule and message lives. Paying asks for the +amount with `ChatPrompt` and hands it to `/pay`, which validates it. + +`MenuRender` holds the shared pieces: the back button, player heads, and `later`, which plays the click and runs an +action on the next tick — every button that opens or closes an inventory goes through it. + +### The menu item + +`menu/MenuItem` (not scanned) keeps a menu item in hotbar slot 8 (`MenuItem.SLOT`). It is identified by +`PluginItem.ITEM_ID_KEY` = `main-menu`, never stacks, glows, and is named in the holder's language. + +It rests on one invariant: **while a player is online and the item is enabled, exactly one copy exists, in slot 8 of +their own inventory, and none exists anywhere else.** The design is refuse, then reconcile: + +1. **Refuse.** `listeners/menu/MenuItemListener` runs at `LOWEST` and cancels anything that would move a copy: clicks + on the item or the slot (including number keys and swap-hands), drags onto the slot, dropping it, swapping hands, + placing it, using it on a block or an entity (item frames, armour stands, allays — players are let through, so + shift-right-click trading still works), crafting with it (a nether star is a beacon ingredient), hoppers, pickups + and item spawns. Death drops and kept items lose it. Because `GUIManager` skips cancelled clicks, no menu — the + trade table, the shop editor — ever sees a refused one. +2. **Reconcile.** `MenuItem.reconcile(player)` is the only code that creates a copy. It deletes every copy outside the + slot (the rest of the inventory, the cursor, an open container), then puts a fresh one in the slot if the one there + is missing or stale (another language, another material). The listener calls it after anything that could leave the + inventory out of step — a cancelled drop, a creative-mode click, a respawn, a world or game-mode change, a locale + change — and `tasks/menu/MenuItemTask` runs it for everyone once a second, which catches what no event reports: + `/clear`, another plugin's `setItem`, pick-block. + +So a duplicate can never outlive the second it was made in, and cannot leave the player during it. Whatever was in the +slot before is moved into the inventory, or dropped at the player's feet if it is full — never deleted. + +**The item never outlives the session.** It is stripped on quit — before the server saves the inventory, and after +`TradeListener` hands escrow back, so escrow can never land in the slot — and from everyone in `Main.onDisable`. No copy +is written to a player file, so removing TriTown leaves nothing behind. `MenuItem.purge` also empties a container of +copies whenever anyone opens it, but never another player's inventory, whose slot 8 is legitimate. + +`main-menu.item.enabled` and `main-menu.item.material` live in `MainMenuSettings`. A reload calls +`MenuItem.reconcileAll()`, so a new material or switching the item off applies to everyone at once. While the item is +off, slot 8 is an ordinary slot again: the slot guards only apply while it is enabled. + +--- + ## Admin Panel The panel lives in `guis/admin` and is opened by `/tritown admin` (`commands/admin/AdminCommand`). It is a reading @@ -2431,8 +2575,10 @@ account-type names, and the cards themselves — so the same number reads the sa next to the largest one, green where the supply grew and red where it shrank. It reads as a chart at a glance without a single custom texture, and the exact figures are in the lore. -Permissions: `tritown.admin` opens the panel, `tritown.admin.economy` and `tritown.admin.shops` open the sections. A -card the viewer may not open is not drawn at all. +Permissions: `tritown.admin` (`AdminPanelGUI.PERMISSION`) opens the panel, `tritown.admin.economy` and +`tritown.admin.shops` open the sections. A card the viewer may not open is not drawn at all, and the rest are centred +along the row with `GUIFrame.spacedColumns`, so a missing card leaves no gap. The panel is reached from the +[main menu](#main-menu) as well as by command, so its bottom row leads back there. --- @@ -2868,6 +3014,111 @@ calls the trade off if they leave it hanging. `TradeSettings` is a snapshot swapped in whole on a reload, the way `ShopSettings` is. +## Server News + +Update notes for the server. Administrators write a post in game — a title, an optional summary and label, and +categories of short entries, each tagged New, Changed, Fixed, Removed or Note — and every player reads it from the main +menu or with `/tritown news`. Nothing about a post lives in `config.yml`; the `news` block only sets the rules. + +The core lives under `news/`, which is **not a scanned package**, for the same reason `shops/` is not: `NewsManager` +has to be loaded before the main menu, the command and the menu item read it. The menus are in `guis/news/`, the +command is `commands/news/NewsCommand`, and the join summary is `listeners/news/NewsJoinListener`. + +### The model + +| Type | What it is | +|:----------------|:-------------------------------------------------------------------------------------------| +| `NewsPost` | A post: title, summary, label, icon, categories, draft or published, pinned, dates, author | +| `NewsCategory` | A named group of entries with an icon | +| `NewsEntry` | One change in a sentence or two, with an `EntryTag` | +| `LocalizedText` | Text an administrator wrote, plus an optional translation for each language id | +| `NewsManager` | Every post, drafts included, and the only thing that reads or writes one | +| `NewsReadState` | Which posts each player has read, kept in their `PlayerData` | +| `NewsNotifier` | The join summary and the announcement sent when a post is published | +| `NewsShorthand` | Reads a tag off the front of a line typed in chat (`+`, `*`, `!`, `-`, `?`) | + +The model classes are also the file's shape, so they name no Bukkit types: an icon is a material's name, read back +through `NewsRender.material`. Every field has a default, so Gson fills in whatever an older file lacks, and +`NewsPost.repair` puts back anything a hand edit left `null` — Gson writes a JSON `null`, or an enum name it does not +know, into a non-null Kotlin field without complaint. + +### Text is written, not translated + +Everything a post says is an administrator's MiniMessage, not a translation key, and is embedded as written the way a +shop's name is. `LocalizedText.forViewer(player)` picks the viewer's translation through `Lang.idFor`, falling back to +the text as first written, so a post written in one language still reads for everyone. The words *around* a post — +buttons, tags, dates, the join message — are ordinary `news.*` and `gui.news*` keys. + +### Storage + +`JsonNewsStorage` keeps every post in `/news/posts.json`, written through `AtomicFile` with the previous +copy kept as `.bak`, and read back from the backup when the file will not parse. A file written by a newer build is +refused rather than overwritten, and if the posts cannot be loaded at all `NewsManager.isReady` stays false and the +feature switches itself off rather than start empty. + +Every change is written at once — call `NewsManager.changed(post)` after editing a post in place. It also dates a +published post as edited, without making it unread again: a typo fix should not call everyone back. + +### Unread + +`NewsReadState` stores the ids a player has read (`news-read`) and the moment they first met the news +(`news-since`). A post published before that moment does not count as unread, except the newest post, which always +does until it is read — so a player joining a server with a year of notes has one waiting, not all of them. Publishing +dates a post now, so a post unpublished and published again is news to everyone again. + +`MenuItem.create` counts the unread posts for the menu item's lore, and `MenuItem.reconcile` compares against a fresh +copy every second, so **`NewsReadState.unread` must stay cheap**: one pass over the published posts, nothing more. +The comparison is also what keeps the count current — nothing hands the item out again when a post is read. + +### Notifications + +| When | What the player gets | +|:---------------------------------|:------------------------------------------------------------------------------------------------| +| Joining with unread posts | A chat list of the unread titles, each a link to `/tritown news open ` | +| A post published and announced | A title, a sound and a chat link, per `news.announce.*` | +| Always, while anything is unread | The main menu's **News** button glows and stacks to the count; the menu item's lore counts them | + +The join summary waits `news.join-message.delay-seconds` (at least a second), so the client has sent its locale and the +summary is not lost among the welcome messages. **Publish quietly** skips the announcement entirely; the post is still +unread for everyone. + +### The menus + +| Menu | What it does | +|:------------------------|:-----------------------------------------------------------------------------------| +| `NewsListGUI` | Published posts, pinned first then newest; unread ones glow. Mark all read; Manage | +| `NewsPostGUI` | A post's card atop the frame, its categories listed in order; **Read as a book** | +| `NewsCategoryGUI` | One category, an entry to an item, for a category too long for its card | +| `NewsManageGUI` | Drafts then published posts; new post; delete (through `ConfirmGUI`) | +| `NewsEditorGUI` | A post's categories: add, reorder, remove; settings, preview, publish, delete | +| `NewsSettingsGUI` | Title, summary, label, icon (click an item in your own inventory) and pin | +| `NewsCategoryEditorGUI` | A category's entries: write them in chat, retag, reorder, remove; rename; icon | +| `NewsEntryGUI` | One entry's text and tag | +| `NewsTextGUI` | One piece of text in every installed language; shared by every field | + +`NewsPostGUI` opened with `preview = true` shows a draft as players will see it, does not mark it read, and leads back +to the editor; `/tritown news open ` only ever previews a draft for an editor. Categories and entries are moved the +way shop entries are — a click marks one, the next click says where it goes — and `NewsRender` draws everything the +menus share, including the book. + +Writing, publishing and deleting need `tritown.news.manage` (`NewsCommand.MANAGE_PERMISSION`), which every editor menu +checks on each click as well as the command. + +### Settings + +| Key | What it does | +|:----------------------------------|:-----------------------------------------------------------------| +| `news.enabled` | Turns the news off entirely: no button, no messages, no command | +| `news.join-message.enabled` | Lists unread posts to a player as they join | +| `news.join-message.delay-seconds` | How long after joining | +| `news.join-message.preview` | How many unread titles the list names | +| `news.announce.title` / `.chat` | What everyone online gets when a post is published and announced | +| `news.announce.sound` | A sound key, or `""` for none | +| `news.max-entry-length` | The most visible characters one entry may have | + +`NewsSettings` is a snapshot swapped in whole on a reload. The posts themselves are never re-read on a reload; every +change to them is already on disk. + ## Sidebar The sidebar lives in `net.trilleo.mc.plugins.tritown.scoreboard`, which — like `economy` — is **not** one of the diff --git a/docs/UTILITY_GUIDE.md b/docs/UTILITY_GUIDE.md index a82c647..dcceb4e 100644 --- a/docs/UTILITY_GUIDE.md +++ b/docs/UTILITY_GUIDE.md @@ -19,6 +19,7 @@ reduce boilerplate and provide commonly needed functionality out of the box. | `InventoryUtil` | Gives items to a player, and asks first whether they would fit | | `TownyUtil` | Reads and formats Towny data: names, balances, upkeep, the new day | | `ComponentUtil` | Parses a MiniMessage string into a Component, and escapes input | +| `AtomicFile` | Replaces a file without ever leaving a truncated copy behind | --- @@ -376,6 +377,7 @@ has to follow. | `Lang.load(plugin, language)` | Copies the bundled files to `plugins/TriTown/lang/` if missing and loads every language file. | | `Lang.tr(sender, key, vararg args)` | The translation of `key` for `sender`, with `{name}` placeholders filled; the key itself if missing. | | `Lang.find(sender, key)` | The raw translation, or `null` when no language defines `key` (for runtime-built keys). | +| `Lang.idFor(sender)` | The id of the language `sender` reads, as `tr` picks it, for text kept outside the language files. | | `Lang.ids` | Ids of every loaded language file (`en_US`, `zh_CN`, and any the server owner added). | | `CommandSender.tr(key, vararg args)` | Extension shorthand for `Lang.tr(this, key, *args)`. | @@ -587,6 +589,19 @@ listening. --- +## AtomicFile + +`AtomicFile.write(target, backup, content)` writes `content` to a temporary file beside `target`, moves the old +`target` to `backup`, then moves the new file into place atomically where the file system allows it. A crash part-way +leaves either the old file or the new one, never a truncated one, and a reader that finds `target` unreadable can fall +back to `backup`. The shop file and the news file are both written this way. + +```kotlin +AtomicFile.write(file.toPath(), File(file.path + ".bak").toPath(), gson.toJson(document)) +``` + +--- + ## PDCUtil `PDCUtil` provides a concise API for reading and writing values in diff --git a/gradle.properties b/gradle.properties index aa636b2..bdf6316 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,7 +1,7 @@ kotlin.code.style=official # Plugin Properties -plugin_version=1.2.0 +plugin_version=1.3.0 # Dependency Versions towny_version=0.103.2.7 diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/Main.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/Main.kt index a7e66fc..738fd4c 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/Main.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/Main.kt @@ -11,6 +11,9 @@ import net.trilleo.mc.plugins.tritown.economy.storage.JsonPulseStorage import net.trilleo.mc.plugins.tritown.economy.vault.TriTownVaultEconomy import net.trilleo.mc.plugins.tritown.economy.vault.VaultRegistration import net.trilleo.mc.plugins.tritown.enums.ProviderMode +import net.trilleo.mc.plugins.tritown.menu.MenuItem +import net.trilleo.mc.plugins.tritown.news.NewsManager +import net.trilleo.mc.plugins.tritown.news.storage.JsonNewsStorage import net.trilleo.mc.plugins.tritown.registration.* import net.trilleo.mc.plugins.tritown.scoreboard.ScoreboardService import net.trilleo.mc.plugins.tritown.shops.ShopManager @@ -102,6 +105,12 @@ class Main : JavaPlugin() { } TradeSettings.load(pluginConfig) + TownSettings.load(pluginConfig) + MainMenuSettings.load(pluginConfig, logger) + + // Before the registrars, for the same reason as the shops: the main menu reads the news as it is drawn. + NewsSettings.load(pluginConfig, logger) + NewsManager.start(JsonNewsStorage(dataFolder, logger), logger) ItemRegistrar.registerAll(this) RecipeRegistrar.registerAll(this) @@ -145,6 +154,13 @@ class Main : JavaPlugin() { ShopManager.global() TradeSettings.load(pluginConfig) + TownSettings.load(pluginConfig) + // Only the settings, as with the shops: every change to a post is already on disk. + NewsSettings.load(pluginConfig, logger) + + // The material may have changed, or the item been switched off. + MainMenuSettings.load(pluginConfig, logger) + MenuItem.reconcileAll() } override fun onDisable() { @@ -161,6 +177,9 @@ class Main : JavaPlugin() { // the server is about to save. TradeManager.shutdown() + // So no menu item is saved into an inventory and left behind once TriTown is gone. + MenuItem.stripAll() + ShopManager.shutdown() PlayerDataManager.saveAll() diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/admin/AdminCommand.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/admin/AdminCommand.kt index aec7df7..ed1e125 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/admin/AdminCommand.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/admin/AdminCommand.kt @@ -21,7 +21,7 @@ class AdminCommand : PluginCommand( name = "admin", description = "Open the admin panel", usage = "/tritown admin [economy|shops]", - permission = PERMISSION, + permission = AdminPanelGUI.PERMISSION, ) { override val extraPermissions = listOf(AdminPanelGUI.ECONOMY_PERMISSION, AdminPanelGUI.SHOPS_PERMISSION) @@ -72,8 +72,6 @@ class AdminCommand : PluginCommand( } private companion object { - const val PERMISSION = "tritown.admin" - val SECTIONS = listOf("economy", "shops") } } diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/economy/BalanceCommand.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/economy/BalanceCommand.kt index 393f4b0..fad28be 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/economy/BalanceCommand.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/economy/BalanceCommand.kt @@ -2,6 +2,7 @@ package net.trilleo.mc.plugins.tritown.commands.economy import net.trilleo.mc.plugins.tritown.economy.EconomyService import net.trilleo.mc.plugins.tritown.registration.PluginCommand +import net.trilleo.mc.plugins.tritown.towns.FoundingCredit import net.trilleo.mc.plugins.tritown.utils.sendPrefixed import net.trilleo.mc.plugins.tritown.utils.tr import org.bukkit.command.CommandSender @@ -30,6 +31,9 @@ class BalanceCommand : PluginCommand( } val balance = EconomyService.balance(player.uniqueId, currency) sender.sendPrefixed(sender.tr("command.balance.yours", "balance" to display(balance, currency))) + if (FoundingCredit.holds(player)) { + sender.sendPrefixed(sender.tr("command.balance.founding-credit", "amount" to FoundingCredit.display())) + } return true } diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/menu/MenuCommand.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/menu/MenuCommand.kt new file mode 100644 index 0000000..6799338 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/menu/MenuCommand.kt @@ -0,0 +1,35 @@ +package net.trilleo.mc.plugins.tritown.commands.menu + +import net.trilleo.mc.plugins.tritown.guis.menu.MainMenuGUI +import net.trilleo.mc.plugins.tritown.registration.PluginCommand +import net.trilleo.mc.plugins.tritown.utils.sendPrefixed +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.command.CommandSender +import org.bukkit.entity.Player + +/** + * Opens the main menu, for a player who would rather type than reach for the + * item — or on a server that has switched the item off. + * + * It declares no permission on purpose, the way `/tritown scoreboard` does: + * every player is meant to reach the menu, and the menu itself leaves out what + * a viewer may not use. + */ +class MenuCommand : PluginCommand( + name = "menu", + description = "Open the main menu", + usage = "/tritown menu", +) { + + override fun execute(sender: CommandSender, args: Array): Boolean { + val player = sender as? Player ?: run { + sender.sendPrefixed(sender.tr("command.menu.players-only")) + return true + } + + MainMenuGUI.show(player) + return true + } + + override fun tabComplete(sender: CommandSender, args: Array): List = emptyList() +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/news/NewsCommand.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/news/NewsCommand.kt new file mode 100644 index 0000000..4c47061 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/commands/news/NewsCommand.kt @@ -0,0 +1,92 @@ +package net.trilleo.mc.plugins.tritown.commands.news + +import net.trilleo.mc.plugins.tritown.guis.news.NewsListGUI +import net.trilleo.mc.plugins.tritown.guis.news.NewsManageGUI +import net.trilleo.mc.plugins.tritown.guis.news.NewsPostGUI +import net.trilleo.mc.plugins.tritown.news.NewsManager +import net.trilleo.mc.plugins.tritown.news.NewsReadState +import net.trilleo.mc.plugins.tritown.registration.PluginCommand +import net.trilleo.mc.plugins.tritown.utils.sendPrefixed +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.command.CommandSender +import org.bukkit.entity.Player + +/** + * The server's news: read it, catch up on it, and — for administrators — write it. + * + * It declares no permission on purpose, the way `/tritown menu` does: every + * player is meant to read the news. Writing it is checked against + * [MANAGE_PERMISSION], which the editor menus check as well. + * + * `open ` is what the links in the join summary and the announcement run. + */ +class NewsCommand : PluginCommand( + name = "news", + description = "Read the server's news", + usage = "/tritown news [open |readall|manage]", +) { + + override val extraPermissions = listOf(MANAGE_PERMISSION) + + override fun execute(sender: CommandSender, args: Array): Boolean { + val player = sender as? Player ?: run { + sender.sendPrefixed(sender.tr("command.news.players-only")) + return true + } + + if (!NewsManager.isAvailable) { + player.sendPrefixed(player.tr("command.news.unavailable")) + return true + } + + when (args.firstOrNull()?.lowercase()) { + null -> NewsListGUI.show(player) + "open" -> open(player, args.getOrNull(1)) + "readall" -> { + NewsReadState.markAllRead(player) + player.sendPrefixed(player.tr("command.news.all-read")) + } + + "manage" -> { + if (!player.hasPermission(MANAGE_PERMISSION)) { + player.sendPrefixed(player.tr("command.no-permission")) + } else { + NewsManageGUI.show(player) + } + } + + else -> player.sendPrefixed(player.tr("command.news.usage")) + } + return true + } + + override fun tabComplete(sender: CommandSender, args: Array): List = when (args.size) { + 1 -> actions(sender).filter { it.startsWith(args[0], ignoreCase = true) } + 2 -> if (args[0].equals("open", ignoreCase = true)) { + NewsManager.published().map { it.id }.filter { it.startsWith(args[1], ignoreCase = true) } + } else { + emptyList() + } + + else -> emptyList() + } + + /** A draft opens only for an editor, and then as a preview, so a link to one never shows it to a player. */ + private fun open(player: Player, id: String?) { + val post = id?.let(NewsManager::get) + when { + post == null -> player.sendPrefixed(player.tr("command.news.unknown")) + post.isPublished -> NewsPostGUI.show(player, post, preview = false) + player.hasPermission(MANAGE_PERMISSION) -> NewsPostGUI.show(player, post, preview = true) + else -> player.sendPrefixed(player.tr("command.news.unknown")) + } + } + + private fun actions(sender: CommandSender): List = + if (sender.hasPermission(MANAGE_PERMISSION)) listOf("open", "readall", "manage") else listOf("open", "readall") + + companion object { + /** Needed to write, publish and delete news. */ + const val MANAGE_PERMISSION = "tritown.news.manage" + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/EconomySettings.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/EconomySettings.kt index c63b21a..6a5e7e0 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/EconomySettings.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/EconomySettings.kt @@ -114,7 +114,7 @@ data class EconomySettings( deferTo = deferTo, currencies = listOf(currency), primaryCurrencyId = currency.id, - startingBalance = config.getDouble("economy.starting-balance", 100.0), + startingBalance = config.getDouble("economy.starting-balance", 200.0), balanceCap = config.getDouble("economy.balance-cap", 1_000_000_000.0), minimumPayment = config.getDouble("economy.minimum-payment", 0.01), allowNegativeBalances = config.getBoolean("economy.allow-negative-balances", false), diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/MainMenuSettings.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/MainMenuSettings.kt new file mode 100644 index 0000000..906ef05 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/MainMenuSettings.kt @@ -0,0 +1,49 @@ +package net.trilleo.mc.plugins.tritown.config + +import org.bukkit.Material +import java.util.logging.Logger + +/** + * An immutable snapshot of the `main-menu` block of `config.yml`. + * + * @param itemEnabled whether every player carries the menu item in the last slot of their hotbar + * @param itemMaterial what the menu item is made of + */ +data class MainMenuSettings( + val itemEnabled: Boolean, + val itemMaterial: Material, +) { + + companion object { + + private val DEFAULT_MATERIAL = Material.NETHER_STAR + + @Volatile + private var current: MainMenuSettings? = null + + /** The settings in force. */ + val snapshot: MainMenuSettings + get() = current ?: error("Main menu settings have not been loaded yet") + + /** Whether [load] has run. */ + val isLoaded: Boolean + get() = current != null + + /** Reads the `main-menu` block from [config] and makes it the current snapshot. */ + fun load(config: PluginConfig, logger: Logger): MainMenuSettings = read(config, logger).also { current = it } + + private fun read(config: PluginConfig, logger: Logger): MainMenuSettings = MainMenuSettings( + itemEnabled = config.getBoolean("main-menu.item.enabled", true), + itemMaterial = material(config.getString("main-menu.item.material", DEFAULT_MATERIAL.name), logger), + ) + + /** Air and blocks with no item form cannot sit in a hotbar, so they fall back to the default. */ + private fun material(name: String, logger: Logger): Material { + val material = Material.matchMaterial(name) + if (material != null && material.isItem && !material.isAir) return material + + logger.warning("main-menu.item.material '$name' is not an item; using ${DEFAULT_MATERIAL.name}") + return DEFAULT_MATERIAL + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/NewsSettings.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/NewsSettings.kt new file mode 100644 index 0000000..5ff48d7 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/NewsSettings.kt @@ -0,0 +1,67 @@ +package net.trilleo.mc.plugins.tritown.config + +import net.kyori.adventure.key.Key +import java.util.logging.Logger + +/** + * An immutable snapshot of the `news` block of `config.yml`. + * + * @param enabled whether players can read the news and administrators write it + * @param joinMessage whether a player with unread posts is told so as they join + * @param joinDelayTicks how long after joining that message waits, so it is not lost among the welcome messages + * @param joinPreview how many unread titles the join message lists before pointing at the rest + * @param announceTitle whether publishing a post shows a title on every online player's screen + * @param announceChat whether publishing a post sends every online player a line they can click + * @param announceSound the sound publishing a post plays, or `null` for none + * @param maxEntryLength the most characters one entry may be, so it stays a line rather than an essay + */ +data class NewsSettings( + val enabled: Boolean, + val joinMessage: Boolean, + val joinDelayTicks: Long, + val joinPreview: Int, + val announceTitle: Boolean, + val announceChat: Boolean, + val announceSound: Key?, + val maxEntryLength: Int, +) { + + companion object { + + @Volatile + private var current: NewsSettings? = null + + /** The settings in force. */ + val snapshot: NewsSettings + get() = current ?: error("News settings have not been loaded yet") + + /** Whether [load] has run. */ + val isLoaded: Boolean + get() = current != null + + /** Reads the `news` block from [config] and makes it the current snapshot. */ + fun load(config: PluginConfig, logger: Logger): NewsSettings = read(config, logger).also { current = it } + + private fun read(config: PluginConfig, logger: Logger): NewsSettings = NewsSettings( + enabled = config.getBoolean("news.enabled", true), + joinMessage = config.getBoolean("news.join-message.enabled", true), + joinDelayTicks = config.getLong("news.join-message.delay-seconds", 3L).coerceIn(0L, 60L) * 20L, + joinPreview = config.getInt("news.join-message.preview", 3).coerceIn(0, 10), + announceTitle = config.getBoolean("news.announce.title", true), + announceChat = config.getBoolean("news.announce.chat", true), + announceSound = sound(config.getString("news.announce.sound", DEFAULT_SOUND), logger), + maxEntryLength = config.getInt("news.max-entry-length", 200).coerceIn(20, 1000), + ) + + /** A blank value switches the sound off; anything that is not a key is reported rather than played as silence. */ + private fun sound(name: String, logger: Logger): Key? { + if (name.isBlank()) return null + return runCatching { Key.key(name) }.getOrElse { + logger.warning("news.announce.sound '$name' is not a sound key; playing none") + null + } + } + + private const val DEFAULT_SOUND = "minecraft:block.note_block.chime" + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/TownSettings.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/TownSettings.kt new file mode 100644 index 0000000..c4eb13f --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/config/TownSettings.kt @@ -0,0 +1,28 @@ +package net.trilleo.mc.plugins.tritown.config + +/** + * An immutable snapshot of the `towns` block of `config.yml`. + * + * @param foundingCredit how much of a first town's price TriTown covers; 0 turns the credit off + */ +data class TownSettings( + val foundingCredit: Double, +) { + + companion object { + + @Volatile + private var current: TownSettings? = null + + /** The settings in force. */ + val snapshot: TownSettings + get() = current ?: error("Town settings have not been loaded yet") + + /** Reads the `towns` block from [config] and makes it the current snapshot. */ + fun load(config: PluginConfig): TownSettings = read(config).also { current = it } + + private fun read(config: PluginConfig): TownSettings = TownSettings( + foundingCredit = config.getDouble("towns.founding-credit", 100.0).coerceAtLeast(0.0), + ) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/enums/PagedLayout.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/enums/PagedLayout.kt index e0e1e14..6e717ab 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/enums/PagedLayout.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/enums/PagedLayout.kt @@ -19,4 +19,15 @@ enum class PagedLayout { * grid of loose items. */ FRAMED, + + /** + * Framed, with each page's items centred inside the border rather than + * filled from its top-left corner. + * + * A full page looks exactly like [FRAMED]. A page holding a few — the last + * one, or a list that is short to begin with — keeps its items together in + * the middle of the menu, with the last row packed around the centre column. + * Meant for lists that are often short, such as the players online. + */ + CENTERED, } diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/ConfirmGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/ConfirmGUI.kt new file mode 100644 index 0000000..0a9754b --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/ConfirmGUI.kt @@ -0,0 +1,128 @@ +package net.trilleo.mc.plugins.tritown.guis + +import net.kyori.adventure.text.Component +import net.trilleo.mc.plugins.tritown.enums.FillMode +import net.trilleo.mc.plugins.tritown.guis.menu.MenuRender +import net.trilleo.mc.plugins.tritown.registration.GUIFrame +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PluginGUI +import net.trilleo.mc.plugins.tritown.utils.ComponentUtil +import net.trilleo.mc.plugins.tritown.utils.LoreUtil +import net.trilleo.mc.plugins.tritown.utils.itemStack +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.event.inventory.InventoryCloseEvent +import org.bukkit.inventory.Inventory +import org.bukkit.inventory.ItemStack +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** + * Asks before something that cannot be undone. + * + * What is at stake sits at the top, and the answers along the row beneath it: + * the caller's own choices, then Cancel. Every answer runs on the next tick, + * so it may open another menu. Closing the menu answers nothing. + * + * ```kotlin + * ConfirmGUI.show( + * player, + * title = player.tr("gui.news-manage.delete-title"), + * subject = card, + * choices = listOf(ConfirmGUI.Choice(deleteButton) { NewsManager.delete(post) }), + * onCancel = { NewsManageGUI.show(it) }, + * ) + * ``` + */ +class ConfirmGUI : PluginGUI( + id = ID, + titleKey = "gui.confirm.title", + rows = 6, + fillMode = FillMode.NONE, +) { + + /** An answer: the button that gives it, and what happens when it is clicked. */ + class Choice(val item: ItemStack, val action: (Player) -> Unit) + + private class Question( + val title: String?, + val subject: ItemStack, + val choices: List, + val onCancel: (Player) -> Unit, + ) + + private val questions = ConcurrentHashMap() + + override fun title(player: Player): Component = + questions[player.uniqueId]?.title?.let(ComponentUtil::parse) ?: super.title(player) + + override fun setup(player: Player, inventory: Inventory) { + val question = questions[player.uniqueId] ?: return + val slots = answerSlots(question) + + GUIFrame.draw(inventory, slots.keys + SUBJECT_SLOT) + inventory.setItem(SUBJECT_SLOT, question.subject) + slots.forEach { (slot, choice) -> inventory.setItem(slot, choice?.item ?: cancel(player)) } + } + + override fun onClick(event: InventoryClickEvent) { + event.isCancelled = true + if (event.clickedInventory !== event.view.topInventory) return + + val player = event.whoClicked as? Player ?: return + val question = questions[player.uniqueId] ?: return + val slots = answerSlots(question) + if (event.rawSlot !in slots) return + + // Taken before acting, so a double click cannot answer twice. + questions.remove(player.uniqueId) + val choice = slots[event.rawSlot] + MenuRender.later(player) { if (choice != null) choice.action(player) else question.onCancel(player) } + } + + override fun onClose(event: InventoryCloseEvent) { + questions.remove(event.player.uniqueId) + } + + /** Where each answer goes; `null` is Cancel, which always comes last. */ + private fun answerSlots(question: Question): Map { + val answers: List = question.choices + null + return GUIFrame.spacedColumns(answers.size).zip(answers).associate { (column, choice) -> + ANSWER_ROW * ROW_SIZE + column to choice + } + } + + private fun cancel(player: Player): ItemStack = itemStack(Material.RED_CONCRETE) { + name(player.tr("gui.confirm.cancel")) + meta { lore(LoreUtil.wrapLore(player.tr("gui.confirm.cancel-lore"))) } + } + + companion object { + const val ID = "confirm" + + private const val ROW_SIZE = 9 + private const val SUBJECT_SLOT = 13 + private const val ANSWER_ROW = 3 + + /** + * Asks [player] to pick one of [choices] — at most three, since Cancel + * takes the fourth place in the row — about [subject]. + * + * @param title the menu's title, already translated, or `null` for the generic one + */ + fun show( + player: Player, + title: String?, + subject: ItemStack, + choices: List, + onCancel: (Player) -> Unit, + ): Boolean { + val gui = GUIManager.getGUI(ID) as? ConfirmGUI ?: return false + require(choices.size in 1..3) { "A confirmation offers one to three choices besides Cancel" } + gui.questions[player.uniqueId] = Question(title, subject, choices, onCancel) + return GUIManager.open(player, ID) + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/admin/AdminPanelGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/admin/AdminPanelGUI.kt index e7777b3..7e8fbff 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/admin/AdminPanelGUI.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/admin/AdminPanelGUI.kt @@ -6,6 +6,8 @@ import net.trilleo.mc.plugins.tritown.config.ShopSettings import net.trilleo.mc.plugins.tritown.economy.EconomyPulse import net.trilleo.mc.plugins.tritown.enums.FillMode import net.trilleo.mc.plugins.tritown.enums.StatsWindow +import net.trilleo.mc.plugins.tritown.guis.menu.MainMenuGUI +import net.trilleo.mc.plugins.tritown.guis.menu.MenuRender import net.trilleo.mc.plugins.tritown.guis.shop.ShopRender import net.trilleo.mc.plugins.tritown.registration.GUIFrame import net.trilleo.mc.plugins.tritown.registration.GUIManager @@ -25,39 +27,62 @@ import org.bukkit.inventory.ItemStack * The way in to everything an administrator runs the server from. * * Deliberately thin: it names the sections and shows just enough of each to say - * whether it is worth opening. Everything a section knows lives in that + * whether it is worth opening. It is reached from the main menu as well as by + * command, so it leads back there. Everything a section knows lives in that * section's own menu, so adding one here is adding a card, not rewriting this. */ class AdminPanelGUI : PluginGUI( id = ID, titleKey = "gui.admin.title", - rows = 3, + rows = 6, fillMode = FillMode.NONE, ) { - override fun setup(player: Player, inventory: Inventory) { - GUIFrame.draw(inventory, listOf(ECONOMY_SLOT, SHOPS_SLOT, SERVER_SLOT)) + private enum class Card { ECONOMY, SHOPS, SERVER } - if (player.hasPermission(ECONOMY_PERMISSION)) inventory.setItem(ECONOMY_SLOT, economy(player)) - if (player.hasPermission(SHOPS_PERMISSION)) inventory.setItem(SHOPS_SLOT, shops(player)) - inventory.setItem(SERVER_SLOT, server(player)) + override fun setup(player: Player, inventory: Inventory) { + val cards = cardsFor(player) + GUIFrame.draw(inventory, cards.keys + BACK_SLOT) + + cards.forEach { (slot, card) -> + val item = when (card) { + Card.ECONOMY -> economy(player) + Card.SHOPS -> shops(player) + Card.SERVER -> server(player) + } + inventory.setItem(slot, item) + } + inventory.setItem(BACK_SLOT, MenuRender.back(player)) } override fun onClick(event: InventoryClickEvent) { event.isCancelled = true val player = event.whoClicked as? Player ?: return + if (event.clickedInventory !== event.view.topInventory) return - when (event.rawSlot) { - ECONOMY_SLOT -> if (player.hasPermission(ECONOMY_PERMISSION)) { - GUIManager.openLater(player, EconomyPanelGUI.ID) - } + if (event.rawSlot == BACK_SLOT) { + MenuRender.later(player) { MainMenuGUI.show(player) } + return + } - SHOPS_SLOT -> if (player.hasPermission(SHOPS_PERMISSION)) { - GUIManager.openLater(player, AdminShopsGUI.ID) - } + when (cardsFor(player)[event.rawSlot]) { + Card.ECONOMY -> GUIManager.openLater(player, EconomyPanelGUI.ID) + Card.SHOPS -> GUIManager.openLater(player, AdminShopsGUI.ID) + Card.SERVER, null -> Unit } } + /** The cards [player] may open, centred along the row, so one they lack leaves no gap. */ + private fun cardsFor(player: Player): Map { + val cards = listOfNotNull( + Card.ECONOMY.takeIf { player.hasPermission(ECONOMY_PERMISSION) }, + Card.SHOPS.takeIf { player.hasPermission(SHOPS_PERMISSION) }, + Card.SERVER, + ) + return GUIFrame.spacedColumns(cards.size).zip(cards) + .associate { (column, card) -> CARD_ROW * 9 + column to card } + } + // ── Cards ─────────────────────────────────────────────────────────── private fun economy(player: Player): ItemStack { @@ -136,11 +161,13 @@ class AdminPanelGUI : PluginGUI( companion object { const val ID = "admin-panel" + /** Opening the panel at all; each section asks for its own node on top of it. */ + const val PERMISSION = "tritown.admin" + const val ECONOMY_PERMISSION = "tritown.admin.economy" const val SHOPS_PERMISSION = "tritown.admin.shops" - private const val ECONOMY_SLOT = 11 - private const val SHOPS_SLOT = 13 - private const val SERVER_SLOT = 15 + private const val CARD_ROW = 2 + private const val BACK_SLOT = 49 } } diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/admin/AdminShopsGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/admin/AdminShopsGUI.kt index 242263d..3c3b1d7 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/admin/AdminShopsGUI.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/admin/AdminShopsGUI.kt @@ -81,7 +81,7 @@ class AdminShopsGUI : PagedPluginGUI( if (!ShopManager.isReady) return // The header takes the first position, so the shops start one behind it. - val index = (contentIndex(page, event.rawSlot) ?: return) - 1 + val index = (contentIndex(event, page) ?: return) - 1 val shop = ShopManager.all().getOrNull(index) ?: return if (event.click == ClickType.SHIFT_LEFT) { diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/menu/LeaderboardGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/menu/LeaderboardGUI.kt new file mode 100644 index 0000000..66ebd83 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/menu/LeaderboardGUI.kt @@ -0,0 +1,141 @@ +package net.trilleo.mc.plugins.tritown.guis.menu + +import net.trilleo.mc.plugins.tritown.commands.economy.accountTypeName +import net.trilleo.mc.plugins.tritown.commands.economy.displayName +import net.trilleo.mc.plugins.tritown.economy.BaltopCache +import net.trilleo.mc.plugins.tritown.economy.CurrencyRegistry +import net.trilleo.mc.plugins.tritown.economy.EconomyFormat +import net.trilleo.mc.plugins.tritown.enums.FillMode +import net.trilleo.mc.plugins.tritown.enums.PagedLayout +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PagedPluginGUI +import net.trilleo.mc.plugins.tritown.utils.ComponentUtil +import net.trilleo.mc.plugins.tritown.utils.LoreUtil +import net.trilleo.mc.plugins.tritown.utils.itemStack +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Bukkit +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.event.inventory.InventoryCloseEvent +import org.bukkit.inventory.ItemStack +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** + * The richest accounts, as heads, in the order `/baltop` lists them. + * + * It reads [BaltopCache] rather than the ledger, so opening it never sorts + * anything, and it is built once when opened: paging through it shows the + * leaderboard as it was then, rather than one that reshuffles under the cursor. + */ +class LeaderboardGUI : PagedPluginGUI( + id = ID, + titleKey = "gui.menu-leaderboard.title", + rows = 6, + fillMode = FillMode.NONE, + layout = PagedLayout.CENTERED, +) { + + private val snapshots = ConcurrentHashMap>() + + override fun getItems(player: Player): List = snapshots[player.uniqueId] ?: emptyList() + + override fun onContentClick(event: InventoryClickEvent, page: Int) { + event.isCancelled = true + } + + override fun navButtons(player: Player): Map = + mapOf(MenuRender.BACK_OFFSET to MenuRender.back(player), MenuRender.EXTRA_OFFSET to yours(player)) + + override fun onNavClick(event: InventoryClickEvent, offset: Int) { + val player = event.whoClicked as? Player ?: return + if (offset == MenuRender.BACK_OFFSET) MenuRender.later(player) { MainMenuGUI.show(player) } + } + + override fun onClose(event: InventoryCloseEvent) { + super.onClose(event) + snapshots.remove(event.player.uniqueId) + } + + private fun open(viewer: Player) { + snapshots[viewer.uniqueId] = render(viewer) + GUIManager.open(viewer, ID) + } + + private fun render(viewer: Player): List { + val entries = BaltopCache.current.entries.take(SIZE) + if (entries.isEmpty()) { + return listOf(itemStack(Material.BARRIER) { name(viewer.tr("gui.menu-leaderboard.empty")) }) + } + return entries.mapIndexed { index, entry -> entry(viewer, index + 1, entry) } + } + + private fun entry(viewer: Player, rank: Int, entry: BaltopCache.Entry): ItemStack { + val title = viewer.tr(rankKey(rank), "rank" to rank, "name" to name(entry)) + val lines = buildList { + add(viewer.tr("gui.menu-leaderboard.balance", "balance" to balance(entry))) + if (entry.type.isGovernment) { + add(viewer.tr("gui.menu-leaderboard.account", "type" to accountTypeName(viewer, entry.type))) + } + if (entry.uuid == viewer.uniqueId) { + add("") + add(viewer.tr("gui.menu-leaderboard.you")) + } + } + + if (!entry.type.isGovernment) { + return MenuRender.head( + Bukkit.getOfflinePlayer(entry.uuid), + title, + lines, + glow = entry.uuid == viewer.uniqueId + ) + } + return itemStack(Material.BELL) { + name(title) + meta { lore(LoreUtil.wrapLore(lines.joinToString(""))) } + } + } + + /** Where the viewer stands, kept in the navigation row so it is on every page. */ + private fun yours(viewer: Player): ItemStack { + val entries = BaltopCache.current.entries + val index = entries.indexOfFirst { it.uuid == viewer.uniqueId } + val line = if (index < 0) { + viewer.tr("gui.menu-leaderboard.unranked") + } else { + viewer.tr("gui.menu-leaderboard.ranked", "rank" to index + 1, "balance" to balance(entries[index])) + } + return MenuRender.head(viewer, viewer.tr("gui.menu-leaderboard.your-rank"), listOf(line)) + } + + /** Spelled out rather than built from the rank, so every key is one the translation test can see. */ + private fun rankKey(rank: Int): String = when (rank) { + 1 -> "gui.menu-leaderboard.first" + 2 -> "gui.menu-leaderboard.second" + 3 -> "gui.menu-leaderboard.third" + else -> "gui.menu-leaderboard.entry" + } + + companion object { + const val ID = "menu-leaderboard" + + /** Four full pages; `/baltop` pages further for anyone who wants the long tail. */ + private const val SIZE = 112 + + /** Opens the leaderboard for [player] through the registered instance. */ + fun show(player: Player): Boolean { + val gui = GUIManager.getGUI(ID) as? LeaderboardGUI ?: return false + gui.open(player) + return true + } + + /** [entry]'s name, safe inside MiniMessage. */ + fun name(entry: BaltopCache.Entry): String = displayName(entry.name, entry.type) + + /** [entry]'s balance in the primary currency, safe inside MiniMessage. */ + fun balance(entry: BaltopCache.Entry): String = + ComponentUtil.escape(EconomyFormat.plain(CurrencyRegistry.primary, entry.balance)) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/menu/MainMenuGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/menu/MainMenuGUI.kt new file mode 100644 index 0000000..da313c2 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/menu/MainMenuGUI.kt @@ -0,0 +1,325 @@ +package net.trilleo.mc.plugins.tritown.guis.menu + +import com.palmergames.bukkit.towny.TownyAPI +import net.trilleo.mc.plugins.tritown.config.ShopSettings +import net.trilleo.mc.plugins.tritown.economy.BaltopCache +import net.trilleo.mc.plugins.tritown.economy.CurrencyRegistry +import net.trilleo.mc.plugins.tritown.economy.EconomyService +import net.trilleo.mc.plugins.tritown.enums.FillMode +import net.trilleo.mc.plugins.tritown.guis.admin.AdminPanelGUI +import net.trilleo.mc.plugins.tritown.guis.admin.PanelRender +import net.trilleo.mc.plugins.tritown.news.NewsManager +import net.trilleo.mc.plugins.tritown.news.NewsReadState +import net.trilleo.mc.plugins.tritown.registration.CommandRegistrar +import net.trilleo.mc.plugins.tritown.registration.GUIFrame +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PluginGUI +import net.trilleo.mc.plugins.tritown.scoreboard.ScoreboardService +import net.trilleo.mc.plugins.tritown.shops.ShopAccess +import net.trilleo.mc.plugins.tritown.shops.ShopManager +import net.trilleo.mc.plugins.tritown.towns.FoundingCredit +import net.trilleo.mc.plugins.tritown.trades.TradeManager +import net.trilleo.mc.plugins.tritown.utils.* +import org.bukkit.Bukkit +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.event.inventory.InventoryCloseEvent +import org.bukkit.inventory.Inventory +import org.bukkit.inventory.ItemStack +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** + * The way in to everything TriTown offers a player. + * + * The profile sits on its own at the top, and the buttons below it are laid + * out in rows of up to three. A button for something the server has switched + * off, or the viewer may not use, is left out rather than shown greyed, and + * each row is centred on what is left — so the menu never has a hole in it, + * whichever features a server runs. Where a button leads, the menu it opens + * does the work; this only points the way. + * + * Opened by right-clicking the [net.trilleo.mc.plugins.tritown.menu.MenuItem] + * or with `/tritown menu`. + */ +class MainMenuGUI : PluginGUI( + id = ID, + titleKey = "gui.menu.title", + rows = 6, + fillMode = FillMode.NONE, +) { + + private enum class Button { PROFILE, TOWN, SHOP, TRADE, PAY, LEADERBOARD, SERVER, NEWS, SIDEBAR, ADMIN, CLOSE } + + /** Which button each slot holds, per viewer, since the buttons shown depend on who is looking. */ + private val layouts = ConcurrentHashMap>() + + override fun setup(player: Player, inventory: Inventory) { + val layout = layout(player) + layouts[player.uniqueId] = layout + + GUIFrame.draw(inventory, layout.keys) + layout.forEach { (slot, button) -> inventory.setItem(slot, render(player, button)) } + } + + override fun onClick(event: InventoryClickEvent) { + event.isCancelled = true + if (event.clickedInventory !== event.view.topInventory) return + + val player = event.whoClicked as? Player ?: return + when (layouts[player.uniqueId]?.get(event.rawSlot)) { + Button.TOWN -> MenuRender.later(player) { player.performCommand(TOWNY_MENU_COMMAND) } + Button.SHOP -> MenuRender.later(player) { CommandRegistrar.run(player, "trades") } + Button.TRADE -> MenuRender.later(player) { PlayerPickerGUI.show(player, PlayerPickerGUI.Mode.TRADE) } + Button.PAY -> MenuRender.later(player) { PlayerPickerGUI.show(player, PlayerPickerGUI.Mode.PAY) } + Button.LEADERBOARD -> MenuRender.later(player) { LeaderboardGUI.show(player) } + Button.NEWS -> MenuRender.later(player) { CommandRegistrar.run(player, "news") } + Button.ADMIN -> MenuRender.later(player) { GUIManager.open(player, AdminPanelGUI.ID) } + Button.CLOSE -> MenuRender.later(player) { player.closeInventory() } + Button.SIDEBAR -> { + ScoreboardService.toggle(player) + MenuRender.click(player) + GUIManager.refresh(player) + } + + Button.PROFILE, Button.SERVER, null -> Unit + } + } + + override fun onClose(event: InventoryCloseEvent) { + layouts.remove(event.player.uniqueId) + } + + // ── Layout ────────────────────────────────────────────────────────── + + /** + * The profile in the first row inside the border, then the rows of buttons + * the viewer gets, each centred and with empty rows dropped so the rest + * close up beneath it. + */ + private fun layout(player: Player): Map { + val rows = listOf( + listOf(Button.PROFILE), + listOfNotNull( + Button.TOWN.takeIf { hasTownyMenu() }, + Button.SHOP.takeIf { globalShopFor(player) }, + Button.TRADE.takeIf { TradeManager.isEnabled }, + ), + listOfNotNull( + Button.PAY.takeIf { hasEconomy() && CommandRegistrar.canRun(player, "pay") }, + Button.LEADERBOARD.takeIf { hasEconomy() && CommandRegistrar.canRun(player, "baltop") }, + Button.SERVER, + ), + listOfNotNull( + Button.NEWS.takeIf { NewsManager.isAvailable }, + Button.SIDEBAR.takeIf { ScoreboardService.isRunning }, + Button.ADMIN.takeIf { player.hasPermission(AdminPanelGUI.PERMISSION) }, + ), + ).filter { it.isNotEmpty() } + + val layout = mutableMapOf() + rows.forEachIndexed { index, buttons -> + GUIFrame.spacedColumns(buttons.size).zip(buttons).forEach { (column, button) -> + layout[(FIRST_ROW + index) * ROW_SIZE + column] = button + } + } + layout[CLOSE_SLOT] = Button.CLOSE + return layout + } + + private fun hasTownyMenu(): Boolean = Bukkit.getPluginManager().isPluginEnabled(TOWNY_MENU) + + private fun hasEconomy(): Boolean = EconomyService.isReady && CurrencyRegistry.isLoaded + + private fun globalShopFor(player: Player): Boolean { + if (!ShopSettings.isLoaded || !ShopSettings.snapshot.enabled || !ShopManager.isReady) return false + val shop = ShopManager.global() ?: return false + return ShopAccess.canOpen(player, shop) + } + + // ── Buttons ───────────────────────────────────────────────────────── + + private fun render(player: Player, button: Button): ItemStack = when (button) { + Button.PROFILE -> profile(player) + Button.TOWN -> town(player) + Button.SHOP -> card(player, Material.EMERALD, "gui.menu.shop", "gui.menu.shop-lore") + Button.TRADE -> trade(player) + Button.PAY -> card(player, Material.GOLD_INGOT, "gui.menu.pay", "gui.menu.pay-lore") + Button.LEADERBOARD -> leaderboard(player) + Button.SERVER -> server(player) + Button.NEWS -> news(player) + Button.SIDEBAR -> sidebar(player) + Button.ADMIN -> card(player, Material.COMMAND_BLOCK, "gui.menu.admin", "gui.menu.admin-lore") + Button.CLOSE -> itemStack(Material.BARRIER) { name(player.tr("gui.menu.close")) } + } + + /** A button that only says what it opens. */ + private fun card(player: Player, material: Material, nameKey: String, loreKey: String): ItemStack = + PanelRender.card( + material, + player.tr(nameKey), + listOf(player.tr(loreKey), "", player.tr("gui.admin.click-open")) + ) + + private fun profile(player: Player): ItemStack { + val resident = TownyAPI.getInstance().getResident(player) + val none = player.tr("common.none") + val lines = mutableListOf() + + if (EconomyUtil.isAvailable) { + val balance = ComponentUtil.escape(EconomyUtil.format(EconomyUtil.balance(player))) + lines += player.tr("gui.menu.profile-balance", "balance" to balance) + } + if (FoundingCredit.holds(player)) { + lines += player.tr("gui.menu.profile-credit", "amount" to FoundingCredit.display()) + } + rank(player)?.let { lines += player.tr("gui.menu.profile-rank", "rank" to it) } + + lines += "" + lines += player.tr( + "gui.menu.profile-town", + "town" to (resident?.townOrNull?.let { TownyUtil.name(it.name) } ?: none), + ) + lines += player.tr( + "gui.menu.profile-nation", + "nation" to (resident?.nationOrNull?.let { TownyUtil.name(it.name) } ?: none), + ) + + return MenuRender.head( + player, + player.tr("gui.menu.profile", "name" to ComponentUtil.escape(player.name)), + lines + ) + } + + /** The viewer's town at a glance, or how to get one, on the button that opens TownyMenu. */ + private fun town(player: Player): ItemStack { + val town = TownyAPI.getInstance().getResident(player)?.townOrNull + val lines = mutableListOf() + + if (town == null) { + lines += player.tr("gui.menu.town-none") + if (FoundingCredit.holds(player)) { + lines += player.tr("gui.menu.town-credit", "amount" to FoundingCredit.display()) + } + } else { + lines += player.tr("gui.menu.town-name", "town" to TownyUtil.name(town.name)) + lines += player.tr("gui.menu.town-residents", "amount" to town.numResidents) + lines += player.tr("gui.menu.town-bank", "amount" to TownyUtil.balance(town)) + lines += player.tr("gui.menu.town-upkeep", "amount" to TownyUtil.money(TownyUtil.townUpkeep(town))) + lines += player.tr( + "gui.admin.server-newday", + "time" to TownyUtil.duration(player, TownyUtil.secondsUntilNewDay()), + ) + } + + lines += "" + lines += player.tr("gui.menu.town-open") + return PanelRender.card(Material.BELL, player.tr("gui.menu.town"), lines) + } + + /** Glows while somebody is waiting for an answer, which is the one thing here worth interrupting for. */ + private fun trade(player: Player): ItemStack { + val waiting = TradeManager.requestersFor(player.uniqueId).count { Bukkit.getPlayer(it) != null } + val lines = mutableListOf(player.tr("gui.menu.trade-lore")) + if (waiting > 0) lines += player.tr("gui.menu.trade-waiting", "amount" to waiting) + lines += "" + lines += player.tr("gui.admin.click-open") + + return PanelRender.card(Material.CHEST, player.tr("gui.menu.trade"), lines).also { item -> + if (waiting > 0) item.editMeta { it.setEnchantmentGlintOverride(true) } + } + } + + /** The top three, so the leaderboard is worth a glance without being opened. */ + private fun leaderboard(player: Player): ItemStack { + val lines = mutableListOf(player.tr("gui.menu.leaderboard-lore")) + val top = BaltopCache.current.entries.take(PREVIEW_SIZE) + if (top.isNotEmpty()) { + lines += "" + top.forEachIndexed { index, entry -> + lines += player.tr( + "gui.menu.leaderboard-entry", + "rank" to index + 1, + "name" to LeaderboardGUI.name(entry), + "balance" to LeaderboardGUI.balance(entry), + ) + } + } + lines += "" + lines += player.tr("gui.admin.click-open") + return PanelRender.card(Material.GOLD_BLOCK, player.tr("gui.menu.leaderboard"), lines) + } + + private fun server(player: Player): ItemStack { + val towny = TownyAPI.getInstance() + val lines = listOf( + player.tr("gui.admin.server-online", "amount" to Bukkit.getOnlinePlayers().size), + player.tr("gui.admin.server-towns", "amount" to towny.towns.size), + player.tr("gui.admin.server-nations", "amount" to towny.nations.size), + "", + player.tr("gui.admin.server-newday", "time" to TownyUtil.duration(player, TownyUtil.secondsUntilNewDay())), + ) + return PanelRender.card(Material.CLOCK, player.tr("gui.menu.server"), lines) + } + + /** + * Glows while anything is unread, and stacks up to the number unread — a + * count the viewer can see without opening it — with the newest titles in + * its lore. + */ + private fun news(player: Player): ItemStack { + val unread = NewsReadState.unread(player) + val lines = mutableListOf(player.tr("gui.menu.news-lore")) + if (unread.isNotEmpty()) { + lines += "" + lines += player.tr("gui.menu.news-unread", "amount" to unread.size) + unread.take(PREVIEW_SIZE).forEach { post -> + lines += player.tr("gui.menu.news-entry", "title" to post.title.forViewer(player)) + } + } + lines += "" + lines += player.tr("gui.admin.click-open") + + return PanelRender.card(Material.BOOK, player.tr("gui.menu.news"), lines).also { item -> + if (unread.isNotEmpty()) { + item.amount = unread.size.coerceAtMost(item.maxStackSize) + item.editMeta { it.setEnchantmentGlintOverride(true) } + } + } + } + + private fun sidebar(player: Player): ItemStack { + val shown = ScoreboardService.isEnabledFor(player) + val lines = listOf( + player.tr(if (shown) "gui.menu.sidebar-on" else "gui.menu.sidebar-off"), + "", + player.tr(if (shown) "gui.menu.sidebar-hide" else "gui.menu.sidebar-show"), + ) + val material = if (shown) Material.LIME_DYE else Material.GRAY_DYE + return PanelRender.card(material, player.tr("gui.menu.sidebar"), lines) + } + + /** The viewer's place on the leaderboard, when the economy is TriTown's and they are on it. */ + private fun rank(player: Player): Int? { + if (!hasEconomy()) return null + val index = BaltopCache.current.entries.indexOfFirst { it.uuid == player.uniqueId } + return if (index < 0) null else index + 1 + } + + companion object { + const val ID = "main-menu" + + private const val ROW_SIZE = 9 + private const val FIRST_ROW = 1 + private const val CLOSE_SLOT = 49 + private const val PREVIEW_SIZE = 3 + + private const val TOWNY_MENU = "TownyMenu" + private const val TOWNY_MENU_COMMAND = "townymenu" + + /** Opens the main menu for [player]. */ + fun show(player: Player): Boolean = GUIManager.open(player, ID) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/menu/MenuRender.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/menu/MenuRender.kt new file mode 100644 index 0000000..31ff985 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/menu/MenuRender.kt @@ -0,0 +1,65 @@ +package net.trilleo.mc.plugins.tritown.guis.menu + +import net.kyori.adventure.key.Key +import net.kyori.adventure.sound.Sound +import net.trilleo.mc.plugins.tritown.Main +import net.trilleo.mc.plugins.tritown.utils.LoreUtil +import net.trilleo.mc.plugins.tritown.utils.itemStack +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Bukkit +import org.bukkit.Material +import org.bukkit.OfflinePlayer +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import org.bukkit.inventory.meta.SkullMeta + +/** The pieces the main menu and the menus it opens are drawn with. */ +object MenuRender { + + /** + * The navigation-row offsets of a paged menu's own two buttons: back to the + * main menu on the left of the page number, and one more on its right, so + * the row stays symmetrical. + */ + const val BACK_OFFSET = 3 + const val EXTRA_OFFSET = 5 + + private val click = Sound.sound(Key.key("minecraft:ui.button.click"), Sound.Source.UI, 1f, 1f) + + /** The button that returns to the main menu. */ + fun back(viewer: Player): ItemStack = itemStack(Material.ARROW) { + name(viewer.tr("gui.menu.back")) + meta { lore(LoreUtil.wrapLore(viewer.tr("gui.menu.back-lore"))) } + } + + /** + * [owner]'s head, named [name], with [lines] of wrapped lore. + * + * Blank lines are kept, so the lore can be grouped. A [glow]ing head is one + * the viewer should notice first, such as someone waiting for an answer. + */ + fun head(owner: OfflinePlayer, name: String, lines: List, glow: Boolean = false): ItemStack = + itemStack(Material.PLAYER_HEAD) { + name(name) + meta { + (this as SkullMeta).owningPlayer = owner + lore(LoreUtil.wrapLore(lines.joinToString(""))) + if (glow) setEnchantmentGlintOverride(true) + } + } + + /** + * Runs [action] on the following tick, with a click to go with it. + * + * A click is still being delivered while its handler runs, and opening or + * closing an inventory from inside that delivery leaves the server and the + * client disagreeing about what is on screen. + */ + fun later(player: Player, action: () -> Unit) { + player.playSound(click) + Bukkit.getScheduler().runTask(Main.instance, Runnable { if (player.isOnline) action() }) + } + + /** The click sound on its own, for a button that changes the menu in place. */ + fun click(player: Player) = player.playSound(click) +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/menu/PlayerPickerGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/menu/PlayerPickerGUI.kt new file mode 100644 index 0000000..a867508 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/menu/PlayerPickerGUI.kt @@ -0,0 +1,191 @@ +package net.trilleo.mc.plugins.tritown.guis.menu + +import net.kyori.adventure.text.Component +import net.trilleo.mc.plugins.tritown.config.TradeSettings +import net.trilleo.mc.plugins.tritown.enums.FillMode +import net.trilleo.mc.plugins.tritown.enums.PagedLayout +import net.trilleo.mc.plugins.tritown.registration.CommandRegistrar +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PagedPluginGUI +import net.trilleo.mc.plugins.tritown.trades.TradeManager +import net.trilleo.mc.plugins.tritown.utils.* +import org.bukkit.Bukkit +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.event.inventory.InventoryCloseEvent +import org.bukkit.inventory.ItemStack +import java.util.* +import java.util.concurrent.ConcurrentHashMap +import kotlin.math.roundToInt + +/** + * Picks another player to trade with or to pay. + * + * Choosing someone runs the same command typing it would — `/trade ` or + * `/pay ` — so every rule and message stays with the command, + * and this menu only saves the typing. + * + * For a trade it lists only the players close enough to trade with, with + * anyone waiting for an answer first, since those are the only clicks that can + * do anything. The list is a snapshot, and the refresh button takes a new one + * as people move about. + */ +class PlayerPickerGUI : PagedPluginGUI( + id = ID, + titleKey = "gui.menu-players.title-trade", + rows = 6, + fillMode = FillMode.NONE, + layout = PagedLayout.CENTERED, +) { + + /** What the picker is picking someone for. */ + enum class Mode { TRADE, PAY } + + /** One viewer's list: who each item stands for, `null` for an item that is only a notice. */ + private class View(val mode: Mode, val targets: List, val items: List) + + private val views = ConcurrentHashMap() + + override fun title(player: Player): Component { + val key = if (views[player.uniqueId]?.mode == Mode.PAY) "gui.menu-players.title-pay" else titleKey + return ComponentUtil.parse(player.tr(key)) + } + + override fun getItems(player: Player): List = views[player.uniqueId]?.items ?: emptyList() + + override fun navButtons(player: Player): Map = mapOf( + MenuRender.BACK_OFFSET to MenuRender.back(player), + MenuRender.EXTRA_OFFSET to itemStack(Material.SPYGLASS) { + name(player.tr("gui.menu-players.refresh")) + meta { lore(LoreUtil.wrapLore(player.tr("gui.menu-players.refresh-lore"))) } + }, + ) + + override fun onNavClick(event: InventoryClickEvent, offset: Int) { + val player = event.whoClicked as? Player ?: return + when (offset) { + MenuRender.BACK_OFFSET -> MenuRender.later(player) { MainMenuGUI.show(player) } + MenuRender.EXTRA_OFFSET -> { + val mode = views[player.uniqueId]?.mode ?: return + views[player.uniqueId] = build(player, mode) + MenuRender.click(player) + refresh(player, event.inventory) + } + } + } + + override fun onContentClick(event: InventoryClickEvent, page: Int) { + event.isCancelled = true + val player = event.whoClicked as? Player ?: return + val view = views[player.uniqueId] ?: return + val uuid = contentIndex(event, page)?.let(view.targets::getOrNull) ?: return + + val target = Bukkit.getPlayer(uuid) + if (target == null) { + player.sendPrefixed(player.tr("common.error", "message" to player.tr("gui.menu-players.gone"))) + return + } + + val name = target.name + when (view.mode) { + Mode.TRADE -> MenuRender.later(player) { + player.closeInventory() + CommandRegistrar.run(player, "trade", name) + } + + Mode.PAY -> MenuRender.later(player) { + player.closeInventory() + ChatPrompt.ask(player, payPrompt(player, name)) { amount -> + CommandRegistrar.run( + player, + "pay", + name, + amount + ) + } + } + } + } + + override fun onClose(event: InventoryCloseEvent) { + super.onClose(event) + views.remove(event.player.uniqueId) + } + + private fun open(viewer: Player, mode: Mode) { + views[viewer.uniqueId] = build(viewer, mode) + GUIManager.open(viewer, ID) + } + + private fun build(viewer: Player, mode: Mode): View { + val others = Bukkit.getOnlinePlayers().filter { it.uniqueId != viewer.uniqueId && viewer.canSee(it) } + + val entries: List> = when (mode) { + Mode.TRADE -> { + val waiting = TradeManager.requestersFor(viewer.uniqueId).toSet() + val (asking, rest) = others.partition { it.uniqueId in waiting } + val nearby = rest.filter { TradeManager.inRange(viewer, it) } + .sortedBy { it.location.distanceSquared(viewer.location) } + asking.map { it to request(viewer, it) } + nearby.map { it to nearby(viewer, it) } + } + + Mode.PAY -> others.sortedBy { it.name.lowercase() }.map { it to payee(viewer, it) } + } + + if (entries.isEmpty()) return View(mode, listOf(null), listOf(nobody(viewer, mode))) + return View(mode, entries.map { it.first.uniqueId }, entries.map { it.second }) + } + + // ── Items ─────────────────────────────────────────────────────────── + + private fun request(viewer: Player, other: Player): ItemStack = + MenuRender.head(other, nameOf(viewer, other), listOf(viewer.tr("gui.menu-players.request")), glow = true) + + private fun nearby(viewer: Player, other: Player): ItemStack { + val blocks = other.location.distance(viewer.location).roundToInt() + return MenuRender.head( + other, + nameOf(viewer, other), + listOf(viewer.tr("gui.menu-players.distance", "amount" to blocks), "", viewer.tr("gui.menu-players.ask")), + ) + } + + private fun payee(viewer: Player, other: Player): ItemStack = + MenuRender.head(other, nameOf(viewer, other), listOf(viewer.tr("gui.menu-players.pay"))) + + private fun nobody(viewer: Player, mode: Mode): ItemStack = itemStack(Material.BARRIER) { + when (mode) { + Mode.TRADE -> { + name(viewer.tr("gui.menu-players.nobody-near")) + val distance = TradeSettings.snapshot.distance.roundToInt() + meta { lore(LoreUtil.wrapLore(viewer.tr("gui.menu-players.nobody-near-lore", "amount" to distance))) } + } + + Mode.PAY -> name(viewer.tr("gui.menu-players.nobody-online")) + } + } + + private fun nameOf(viewer: Player, other: Player): String = + viewer.tr("gui.menu-players.name", "name" to ComponentUtil.escape(other.name)) + + private fun payPrompt(player: Player, name: String): String { + val balance = if (EconomyUtil.isAvailable) EconomyUtil.format(EconomyUtil.balance(player)) else "-" + return player.tr( + "gui.menu-players.pay-prompt", + "name" to ComponentUtil.escape(name), + "balance" to ComponentUtil.escape(balance), + ) + } + + companion object { + const val ID = "menu-players" + + /** Opens the picker for [player] through the registered instance. */ + fun show(player: Player, mode: Mode): Boolean { + val gui = GUIManager.getGUI(ID) as? PlayerPickerGUI ?: return false + gui.open(player, mode) + return true + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsCategoryEditorGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsCategoryEditorGUI.kt new file mode 100644 index 0000000..d013283 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsCategoryEditorGUI.kt @@ -0,0 +1,398 @@ +package net.trilleo.mc.plugins.tritown.guis.news + +import net.kyori.adventure.text.Component +import net.trilleo.mc.plugins.tritown.commands.news.NewsCommand +import net.trilleo.mc.plugins.tritown.config.NewsSettings +import net.trilleo.mc.plugins.tritown.enums.FillMode +import net.trilleo.mc.plugins.tritown.enums.PagedLayout +import net.trilleo.mc.plugins.tritown.guis.menu.MenuRender +import net.trilleo.mc.plugins.tritown.news.* +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PagedPluginGUI +import net.trilleo.mc.plugins.tritown.utils.ChatPrompt +import net.trilleo.mc.plugins.tritown.utils.ComponentUtil +import net.trilleo.mc.plugins.tritown.utils.sendPrefixed +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.ClickType +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.event.inventory.InventoryCloseEvent +import org.bukkit.inventory.Inventory +import org.bukkit.inventory.ItemStack +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** + * The entries of one category, where they are written, tagged, reordered and + * removed. + * + * Writing is done in chat, one line after another: each line becomes an entry + * and the next question follows at once, until the administrator types `done`. + * A prefix on the line picks its tag ([NewsShorthand]), so a whole changelog + * goes in without a click between entries. + * + * Entries move the way categories do in [NewsEditorGUI]: shift-right-click + * marks one, and the next click says where it goes. + */ +class NewsCategoryEditorGUI : PagedPluginGUI( + id = ID, + titleKey = "gui.news-category-editor.title", + rows = 6, + fillMode = FillMode.NONE, + layout = PagedLayout.FRAMED, +) { + + private class Editing(val postId: String, val categoryId: String) + + private val editing = ConcurrentHashMap() + + /** The entry each administrator is part-way through moving, by its id. */ + private val moving = ConcurrentHashMap() + + fun open(player: Player, post: NewsPost, category: NewsCategory) { + editing[player.uniqueId] = Editing(post.id, category.id) + moving.remove(player.uniqueId) + GUIManager.open(player, ID) + } + + override fun title(player: Player): Component { + val (_, category) = target(player) ?: return super.title(player) + return ComponentUtil.parse( + player.tr("gui.news-category-editor.title", "name" to NewsRender.text(player, category.name)) + ) + } + + override fun getItems(player: Player): List { + val (_, category) = target(player) ?: return emptyList() + val held = moving[player.uniqueId] + return category.entries.map { icon(player, it, held) } + } + + override fun navButtons(player: Player): Map { + val (_, category) = target(player) ?: return emptyMap() + val back = NewsRender.button( + player, + Material.ARROW, + "gui.news-category-editor.back", + "gui.news-category-editor.back-lore" + ) + + val held = moving[player.uniqueId]?.let(category::entry) + if (held != null) { + return mapOf( + SLOT_HELD to NewsRender.glowing( + NewsRender.card( + NewsRender.tagMaterial(held.tag), + NewsRender.entryLine(player, held), + listOf( + player.tr("gui.news-category-editor.holding"), + player.tr("gui.news-category-editor.click-put-down") + ), + ) + ), + SLOT_MOVE_FIRST to NewsRender.button( + player, + Material.SPECTRAL_ARROW, + "gui.news-category-editor.move-first", + "gui.news-category-editor.move-first-lore" + ), + SLOT_MOVE_LAST to NewsRender.button( + player, + Material.TIPPED_ARROW, + "gui.news-category-editor.move-last", + "gui.news-category-editor.move-last-lore" + ), + SLOT_BACK to back, + ) + } + + return mapOf( + SLOT_ADD to NewsRender.button( + player, + Material.FEATHER, + "gui.news-category-editor.add", + "gui.news-category-editor.add-lore" + ), + SLOT_NAME to NewsRender.card( + Material.NAME_TAG, + player.tr("gui.news-category-editor.name"), + listOf( + player.tr("gui.news-settings.value", "value" to category.name.main), + player.tr("gui.news-settings.translated", "amount" to category.name.translations.size), + "", + player.tr("gui.news-settings.click-edit"), + player.tr("gui.news-settings.right-click-translate"), + ), + ), + SLOT_ICON to NewsRender.card( + NewsRender.categoryIcon(category), + player.tr("gui.news-category-editor.icon"), + listOf( + player.tr("gui.news-category-editor.icon-lore"), + "", + player.tr("gui.news-settings.right-click-reset"), + ), + ), + SLOT_BACK to back, + ) + } + + override fun onNavClick(event: InventoryClickEvent, offset: Int) { + val player = event.whoClicked as? Player ?: return + if (!player.hasPermission(NewsCommand.MANAGE_PERMISSION)) return + val (post, category) = target(player) ?: return + val held = moving[player.uniqueId] + val right = event.click == ClickType.RIGHT || event.click == ClickType.SHIFT_RIGHT + + if (held != null) { + when (offset) { + SLOT_HELD -> release(player, event.inventory) + SLOT_MOVE_FIRST -> place(player, post, category, held, 0, event.inventory) + SLOT_MOVE_LAST -> place(player, post, category, held, category.entries.size, event.inventory) + SLOT_BACK -> MenuRender.later(player) { NewsEditorGUI.show(player, post) } + } + return + } + + when (offset) { + SLOT_ADD -> { + player.closeInventory() + addEntries(player, post, category, EntryTag.NEW, first = true) + } + + SLOT_NAME -> if (right) { + MenuRender.later(player) { + NewsTextGUI.show( + player, + NewsTextGUI.Target(post.id, { it.category(category.id)?.name }, null) { + show( + it, + post, + category + ) + }, + ) + } + } else { + NewsRender.prompt( + player, + player.tr("gui.news-category-editor.prompt-name"), + null, + { show(player, post, category) }) { + category.name.main = it + NewsManager.changed(post) + } + } + + SLOT_ICON -> if (right) { + category.icon = NewsCategory.DEFAULT_ICON + NewsManager.changed(post) + MenuRender.click(player) + refresh(player, event.inventory) + } + + SLOT_BACK -> MenuRender.later(player) { NewsEditorGUI.show(player, post) } + } + } + + /** A click in the administrator's own inventory picks the category's icon; the item stays where it is. */ + override fun onClick(event: InventoryClickEvent) { + val player = event.whoClicked as? Player + if (player != null && event.clickedInventory === player.inventory) { + event.isCancelled = true + if (!player.hasPermission(NewsCommand.MANAGE_PERMISSION) || moving.containsKey(player.uniqueId)) return + val (post, category) = target(player) ?: return + val item = event.currentItem ?: return + if (item.type.isAir) return + + category.icon = item.type.name + NewsManager.changed(post) + MenuRender.click(player) + refresh(player, event.inventory) + return + } + + super.onClick(event) + } + + override fun onContentClick(event: InventoryClickEvent, page: Int) { + val player = event.whoClicked as? Player ?: return + if (!player.hasPermission(NewsCommand.MANAGE_PERMISSION)) return + val (post, category) = target(player) ?: return + val index = contentIndex(event, page) ?: return + + val held = moving[player.uniqueId] + if (held != null) { + place(player, post, category, held, index, event.inventory) + return + } + + val entry = category.entries.getOrNull(index) ?: return + when (event.click) { + ClickType.SHIFT_LEFT -> { + category.entries.remove(entry) + NewsManager.changed(post) + player.sendPrefixed(player.tr("news.editor.entry-removed")) + refresh(player, event.inventory) + } + + ClickType.SHIFT_RIGHT -> { + moving[player.uniqueId] = entry.id + MenuRender.click(player) + refresh(player, event.inventory) + } + + ClickType.RIGHT -> { + entry.tag = EntryTag.entries[(entry.tag.ordinal + 1) % EntryTag.entries.size] + NewsManager.changed(post) + MenuRender.click(player) + refresh(player, event.inventory) + } + + else -> MenuRender.later(player) { NewsEntryGUI.show(player, post, category, entry) } + } + } + + override fun onClose(event: InventoryCloseEvent) { + super.onClose(event) + editing.remove(event.player.uniqueId) + moving.remove(event.player.uniqueId) + } + + /** + * Asks for one entry after another until [DONE_WORD]. + * + * Each line is saved the moment it is typed, so leaving part-way — typing + * `cancel`, or logging out — keeps everything written so far. A line with + * no prefix takes [tag], the tag of the line before it. + */ + private fun addEntries(player: Player, post: NewsPost, category: NewsCategory, tag: EntryTag, first: Boolean) { + val question = if (first) { + player.tr("gui.news-category-editor.prompt-entries", "done" to DONE_WORD) + } else { + player.tr("gui.news-category-editor.prompt-next", "done" to DONE_WORD) + } + + ChatPrompt.ask(player, question) { input -> + // The post may have been deleted by someone else while this was being typed. + if (NewsManager.get(post.id)?.category(category.id) == null) return@ask + if (input.equals(DONE_WORD, ignoreCase = true)) { + show(player, post, category) + return@ask + } + + val (parsedTag, text) = NewsShorthand.parse(input, tag) + val maxLength = NewsSettings.snapshot.maxEntryLength + when { + text.isBlank() -> Unit + NewsRender.visibleLength(text) > maxLength -> + player.sendPrefixed(player.tr("news.editor.too-long", "amount" to maxLength)) + + else -> { + val entry = NewsEntry( + id = NewsIds.next { id -> category.entries.any { it.id == id } }, + tag = parsedTag, + text = LocalizedText(text), + ) + category.entries += entry + NewsManager.changed(post) + player.sendPrefixed( + player.tr( + "news.editor.entry-added", + "entry" to NewsRender.entryLine(player, entry) + ) + ) + } + } + addEntries(player, post, category, parsedTag, first = false) + } + } + + private fun place( + player: Player, + post: NewsPost, + category: NewsCategory, + entryId: String, + index: Int, + inventory: Inventory + ) { + moving.remove(player.uniqueId) + + val from = category.entries.indexOfFirst { it.id == entryId } + if (from >= 0 && from != index) { + val entry = category.entries.removeAt(from) + val target = (if (from < index) index - 1 else index).coerceIn(0, category.entries.size) + category.entries.add(target, entry) + NewsManager.changed(post) + } + + MenuRender.click(player) + refresh(player, inventory) + } + + private fun release(player: Player, inventory: Inventory) { + moving.remove(player.uniqueId) + MenuRender.click(player) + refresh(player, inventory) + } + + private fun icon(player: Player, entry: NewsEntry, heldId: String?): ItemStack { + val lines = buildList { + add(player.tr("gui.news-category.text", "text" to entry.text.main)) + add(player.tr("gui.news-settings.translated", "amount" to entry.text.translations.size)) + add("") + when { + heldId == entry.id -> { + add(player.tr("gui.news-category-editor.being-moved")) + add(player.tr("gui.news-category-editor.click-put-down")) + } + + heldId != null -> add(player.tr("gui.news-category-editor.click-place-before")) + + else -> { + add(player.tr("gui.news-category-editor.click-entry")) + add(player.tr("gui.news-category-editor.right-click-entry")) + add(player.tr("gui.news-category-editor.shift-right-click-entry")) + add(player.tr("gui.news-category-editor.shift-click-entry")) + } + } + } + return NewsRender.card( + NewsRender.tagMaterial(entry.tag), + NewsRender.tag(player, entry.tag), + lines, + glow = heldId == entry.id, + ) + } + + private fun target(player: Player): Pair? { + val state = editing[player.uniqueId] ?: return null + val post = NewsManager.get(state.postId) ?: return null + val category = post.category(state.categoryId) ?: return null + return post to category + } + + companion object { + const val ID = "news-category-editor" + + /** Typed on its own to stop adding entries and go back to the menu. */ + const val DONE_WORD = "done" + + // Offsets in the navigation row; 0, 4 and 8 belong to the page controls. + private const val SLOT_ADD = 1 + private const val SLOT_NAME = 2 + private const val SLOT_ICON = 3 + private const val SLOT_BACK = 5 + + private const val SLOT_HELD = SLOT_ADD + private const val SLOT_MOVE_FIRST = SLOT_NAME + private const val SLOT_MOVE_LAST = SLOT_ICON + + fun show(player: Player, post: NewsPost, category: NewsCategory): Boolean { + val gui = GUIManager.getGUI(ID) as? NewsCategoryEditorGUI ?: return false + gui.open(player, post, category) + return true + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsCategoryGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsCategoryGUI.kt new file mode 100644 index 0000000..646b20f --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsCategoryGUI.kt @@ -0,0 +1,97 @@ +package net.trilleo.mc.plugins.tritown.guis.news + +import net.kyori.adventure.text.Component +import net.trilleo.mc.plugins.tritown.enums.FillMode +import net.trilleo.mc.plugins.tritown.enums.PagedLayout +import net.trilleo.mc.plugins.tritown.guis.menu.MenuRender +import net.trilleo.mc.plugins.tritown.news.NewsCategory +import net.trilleo.mc.plugins.tritown.news.NewsManager +import net.trilleo.mc.plugins.tritown.news.NewsPost +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PagedPluginGUI +import net.trilleo.mc.plugins.tritown.utils.ComponentUtil +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.event.inventory.InventoryCloseEvent +import org.bukkit.inventory.ItemStack +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** One category of a post, an entry to an item, for a category too long to read off its card. */ +class NewsCategoryGUI : PagedPluginGUI( + id = ID, + titleKey = "gui.news-category.title", + rows = 6, + fillMode = FillMode.NONE, + layout = PagedLayout.FRAMED, +) { + + private class Viewing(val postId: String, val categoryId: String, val preview: Boolean) + + private val viewing = ConcurrentHashMap() + + fun open(player: Player, post: NewsPost, category: NewsCategory, preview: Boolean) { + viewing[player.uniqueId] = Viewing(post.id, category.id, preview) + GUIManager.open(player, ID) + } + + override fun title(player: Player): Component { + val category = categoryOf(player) ?: return super.title(player) + return ComponentUtil.parse( + player.tr( + "gui.news-category.title", + "name" to NewsRender.text(player, category.name) + ) + ) + } + + override fun getItems(player: Player): List { + val category = categoryOf(player) ?: return emptyList() + return category.entries.map { entry -> + NewsRender.card( + NewsRender.tagMaterial(entry.tag), + NewsRender.tag(player, entry.tag), + listOf(player.tr("gui.news-category.text", "text" to NewsRender.text(player, entry.text))), + ) + } + } + + override fun navButtons(player: Player): Map = mapOf( + MenuRender.BACK_OFFSET to NewsRender.button( + player, + Material.ARROW, + "gui.news-category.back", + "gui.news-category.back-lore" + ), + ) + + override fun onNavClick(event: InventoryClickEvent, offset: Int) { + if (offset != MenuRender.BACK_OFFSET) return + val player = event.whoClicked as? Player ?: return + val state = viewing[player.uniqueId] ?: return + val post = NewsManager.get(state.postId) ?: return + MenuRender.later(player) { NewsPostGUI.show(player, post, state.preview) } + } + + override fun onClose(event: InventoryCloseEvent) { + super.onClose(event) + viewing.remove(event.player.uniqueId) + } + + private fun categoryOf(player: Player): NewsCategory? { + val state = viewing[player.uniqueId] ?: return null + return NewsManager.get(state.postId)?.category(state.categoryId) + } + + companion object { + const val ID = "news-category" + + fun show(player: Player, post: NewsPost, category: NewsCategory, preview: Boolean): Boolean { + val gui = GUIManager.getGUI(ID) as? NewsCategoryGUI ?: return false + gui.open(player, post, category, preview) + return true + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsEditorGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsEditorGUI.kt new file mode 100644 index 0000000..81efe69 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsEditorGUI.kt @@ -0,0 +1,370 @@ +package net.trilleo.mc.plugins.tritown.guis.news + +import net.kyori.adventure.text.Component +import net.trilleo.mc.plugins.tritown.commands.news.NewsCommand +import net.trilleo.mc.plugins.tritown.enums.FillMode +import net.trilleo.mc.plugins.tritown.enums.PagedLayout +import net.trilleo.mc.plugins.tritown.guis.ConfirmGUI +import net.trilleo.mc.plugins.tritown.guis.menu.MenuRender +import net.trilleo.mc.plugins.tritown.news.* +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PagedPluginGUI +import net.trilleo.mc.plugins.tritown.utils.ChatPrompt +import net.trilleo.mc.plugins.tritown.utils.ComponentUtil +import net.trilleo.mc.plugins.tritown.utils.sendPrefixed +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.ClickType +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.event.inventory.InventoryCloseEvent +import org.bukkit.inventory.Inventory +import org.bukkit.inventory.ItemStack +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** + * One post's categories, in the order readers see them, and everything that + * is done to the post as a whole: its settings, a preview, publishing and + * deleting it. + * + * Categories are moved the way shop entries are: a right click marks the one + * being moved, and the next click says where it goes. While one is held, the + * first buttons of the navigation row turn into the move's own controls. + */ +class NewsEditorGUI : PagedPluginGUI( + id = ID, + titleKey = "gui.news-editor.title", + rows = 6, + fillMode = FillMode.NONE, + layout = PagedLayout.FRAMED, +) { + + private val editing = ConcurrentHashMap() + + /** The category each administrator is part-way through moving, by its id. */ + private val moving = ConcurrentHashMap() + + fun open(player: Player, post: NewsPost) { + editing[player.uniqueId] = post.id + moving.remove(player.uniqueId) + GUIManager.open(player, ID) + } + + override fun title(player: Player): Component { + val post = postOf(player) ?: return super.title(player) + return ComponentUtil.parse(player.tr("gui.news-editor.title", "title" to NewsRender.text(player, post.title))) + } + + override fun getItems(player: Player): List { + val post = postOf(player) ?: return emptyList() + val held = moving[player.uniqueId] + return post.categories.map { icon(player, it, held) } + } + + override fun navButtons(player: Player): Map { + val post = postOf(player) ?: return emptyMap() + val back = NewsRender.button(player, Material.ARROW, "gui.news-editor.back", "gui.news-editor.back-lore") + + val held = moving[player.uniqueId]?.let(post::category) + if (held != null) { + return mapOf( + SLOT_HELD to NewsRender.glowing( + NewsRender.card( + NewsRender.categoryIcon(held), + NewsRender.text(player, held.name), + listOf(player.tr("gui.news-editor.holding"), player.tr("gui.news-editor.click-put-down")), + ) + ), + SLOT_MOVE_FIRST to NewsRender.button( + player, + Material.SPECTRAL_ARROW, + "gui.news-editor.move-first", + "gui.news-editor.move-first-lore" + ), + SLOT_MOVE_LAST to NewsRender.button( + player, + Material.TIPPED_ARROW, + "gui.news-editor.move-last", + "gui.news-editor.move-last-lore" + ), + SLOT_BACK to back, + ) + } + + return mapOf( + SLOT_ADD to NewsRender.button( + player, + Material.BOOKSHELF, + "gui.news-editor.add", + "gui.news-editor.add-lore" + ), + SLOT_SETTINGS to NewsRender.button( + player, + Material.COMPARATOR, + "gui.news-editor.settings", + "gui.news-editor.settings-lore" + ), + SLOT_PREVIEW to NewsRender.button( + player, + Material.SPYGLASS, + "gui.news-editor.preview", + "gui.news-editor.preview-lore" + ), + SLOT_BACK to back, + SLOT_PUBLISH to if (post.isPublished) { + NewsRender.button( + player, + Material.GRAY_DYE, + "gui.news-editor.unpublish", + "gui.news-editor.unpublish-lore" + ) + } else { + NewsRender.button(player, Material.LIME_DYE, "gui.news-editor.publish", "gui.news-editor.publish-lore") + }, + SLOT_DELETE to NewsRender.button( + player, + Material.LAVA_BUCKET, + "gui.news-editor.delete", + "gui.news-editor.delete-lore" + ), + ) + } + + override fun onNavClick(event: InventoryClickEvent, offset: Int) { + val player = event.whoClicked as? Player ?: return + if (!player.hasPermission(NewsCommand.MANAGE_PERMISSION)) return + val post = postOf(player) ?: return + val held = moving[player.uniqueId] + + if (held != null) { + when (offset) { + SLOT_HELD -> release(player, event.inventory) + SLOT_MOVE_FIRST -> place(player, post, held, 0, event.inventory) + SLOT_MOVE_LAST -> place(player, post, held, post.categories.size, event.inventory) + SLOT_BACK -> MenuRender.later(player) { NewsManageGUI.show(player) } + } + return + } + + when (offset) { + SLOT_ADD -> addCategory(player, post) + SLOT_SETTINGS -> MenuRender.later(player) { NewsSettingsGUI.show(player, post) } + SLOT_PREVIEW -> MenuRender.later(player) { NewsPostGUI.show(player, post, preview = true) } + SLOT_BACK -> MenuRender.later(player) { NewsManageGUI.show(player) } + SLOT_PUBLISH -> if (post.isPublished) { + NewsManager.unpublish(post) + player.sendPrefixed(player.tr("news.editor.unpublished")) + MenuRender.click(player) + refresh(player, event.inventory) + } else if (post.entryCount == 0) { + player.sendPrefixed(player.tr("news.editor.publish-empty")) + } else { + MenuRender.later(player) { confirmPublish(player, post) } + } + + SLOT_DELETE -> MenuRender.later(player) { NewsManageGUI.confirmDelete(player, post) { show(it, post) } } + } + } + + override fun onContentClick(event: InventoryClickEvent, page: Int) { + val player = event.whoClicked as? Player ?: return + if (!player.hasPermission(NewsCommand.MANAGE_PERMISSION)) return + val post = postOf(player) ?: return + val index = contentIndex(event, page) ?: return + + val held = moving[player.uniqueId] + if (held != null) { + place(player, post, held, index, event.inventory) + return + } + + val category = post.categories.getOrNull(index) ?: return + when (event.click) { + ClickType.SHIFT_LEFT -> MenuRender.later(player) { confirmRemove(player, post, category) } + ClickType.RIGHT, ClickType.SHIFT_RIGHT -> { + moving[player.uniqueId] = category.id + MenuRender.click(player) + refresh(player, event.inventory) + } + + else -> MenuRender.later(player) { NewsCategoryEditorGUI.show(player, post, category) } + } + } + + override fun onClose(event: InventoryCloseEvent) { + super.onClose(event) + editing.remove(event.player.uniqueId) + moving.remove(event.player.uniqueId) + } + + private fun addCategory(player: Player, post: NewsPost) { + player.closeInventory() + ChatPrompt.ask(player, player.tr("gui.news-editor.prompt-category")) { input -> + if (input.isNotBlank()) { + val category = NewsCategory( + id = NewsIds.next { id -> post.categories.any { it.id == id } }, + name = LocalizedText(input), + ) + post.categories += category + NewsManager.changed(post) + NewsCategoryEditorGUI.show(player, post, category) + } else { + show(player, post) + } + } + } + + /** + * Publishing is the one step players see, so it is asked about first — + * and whether to announce it, since a small post does not need to take + * over everyone's screen. + */ + private fun confirmPublish(player: Player, post: NewsPost) { + val subject = NewsRender.card( + NewsRender.postIcon(post), + NewsRender.title(player, post), + NewsRender.postLines(player, post) + ) + ConfirmGUI.show( + player, + title = player.tr("gui.news-editor.publish-title"), + subject = subject, + choices = listOf( + ConfirmGUI.Choice( + NewsRender.button( + player, + Material.BELL, + "gui.news-editor.publish-announce", + "gui.news-editor.publish-announce-lore" + ) + ) { + publish(it, post, announce = true) + }, + ConfirmGUI.Choice( + NewsRender.button( + player, + Material.LIME_DYE, + "gui.news-editor.publish-quiet", + "gui.news-editor.publish-quiet-lore" + ) + ) { + publish(it, post, announce = false) + }, + ), + onCancel = { show(it, post) }, + ) + } + + private fun publish(player: Player, post: NewsPost, announce: Boolean) { + NewsManager.publish(post, announce, player) + player.sendPrefixed(player.tr("news.editor.published")) + show(player, post) + } + + private fun confirmRemove(player: Player, post: NewsPost, category: NewsCategory) { + ConfirmGUI.show( + player, + title = player.tr("gui.news-editor.remove-title"), + subject = icon(player, category, null, hints = false), + choices = listOf( + ConfirmGUI.Choice( + NewsRender.button( + player, + Material.LAVA_BUCKET, + "gui.news-editor.remove", + "gui.news-editor.remove-lore" + ) + ) { + post.categories.remove(category) + NewsManager.changed(post) + it.sendPrefixed(it.tr("news.editor.category-removed")) + show(it, post) + }, + ), + onCancel = { show(it, post) }, + ) + } + + /** + * Moves the held category to [index], landing in front of whatever was + * clicked — the same rule the shop editor follows, which is why the target + * shifts back a place when moving forwards. + */ + private fun place(player: Player, post: NewsPost, categoryId: String, index: Int, inventory: Inventory) { + moving.remove(player.uniqueId) + + val from = post.categories.indexOfFirst { it.id == categoryId } + if (from >= 0 && from != index) { + val category = post.categories.removeAt(from) + val target = (if (from < index) index - 1 else index).coerceIn(0, post.categories.size) + post.categories.add(target, category) + NewsManager.changed(post) + } + + MenuRender.click(player) + refresh(player, inventory) + } + + private fun release(player: Player, inventory: Inventory) { + moving.remove(player.uniqueId) + MenuRender.click(player) + refresh(player, inventory) + } + + private fun icon(player: Player, category: NewsCategory, heldId: String?, hints: Boolean = true): ItemStack { + val lines = buildList { + add(player.tr("gui.news-editor.entries", "amount" to category.entries.size)) + category.entries.take(NewsRender.LORE_ENTRIES).forEach { add(NewsRender.entryLine(player, it)) } + val rest = category.entries.size - NewsRender.LORE_ENTRIES + if (rest > 0) add(player.tr("gui.news-post.more", "amount" to rest)) + if (!hints) return@buildList + + add("") + when { + heldId == category.id -> { + add(player.tr("gui.news-editor.being-moved")) + add(player.tr("gui.news-editor.click-put-down")) + } + + heldId != null -> add(player.tr("gui.news-editor.click-place-before")) + + else -> { + add(player.tr("gui.news-editor.click-category")) + add(player.tr("gui.news-editor.right-click-category")) + add(player.tr("gui.news-editor.shift-click-category")) + } + } + } + return NewsRender.card( + NewsRender.categoryIcon(category), + NewsRender.text(player, category.name), + lines, + glow = heldId == category.id, + ) + } + + private fun postOf(player: Player): NewsPost? = editing[player.uniqueId]?.let(NewsManager::get) + + companion object { + const val ID = "news-editor" + + // Offsets in the navigation row; 0, 4 and 8 belong to the page controls. + private const val SLOT_ADD = 1 + private const val SLOT_SETTINGS = 2 + private const val SLOT_PREVIEW = 3 + private const val SLOT_BACK = 5 + private const val SLOT_PUBLISH = 6 + private const val SLOT_DELETE = 7 + + private const val SLOT_HELD = SLOT_ADD + private const val SLOT_MOVE_FIRST = SLOT_SETTINGS + private const val SLOT_MOVE_LAST = SLOT_PREVIEW + + fun show(player: Player, post: NewsPost): Boolean { + val gui = GUIManager.getGUI(ID) as? NewsEditorGUI ?: return false + gui.open(player, post) + return true + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsEntryGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsEntryGUI.kt new file mode 100644 index 0000000..3427aff --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsEntryGUI.kt @@ -0,0 +1,165 @@ +package net.trilleo.mc.plugins.tritown.guis.news + +import net.trilleo.mc.plugins.tritown.commands.news.NewsCommand +import net.trilleo.mc.plugins.tritown.config.NewsSettings +import net.trilleo.mc.plugins.tritown.enums.FillMode +import net.trilleo.mc.plugins.tritown.guis.menu.MenuRender +import net.trilleo.mc.plugins.tritown.news.* +import net.trilleo.mc.plugins.tritown.registration.GUIFrame +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PluginGUI +import net.trilleo.mc.plugins.tritown.utils.sendPrefixed +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.ClickType +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.event.inventory.InventoryCloseEvent +import org.bukkit.inventory.Inventory +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** One entry: what it says, in each language, and which tag it carries. */ +class NewsEntryGUI : PluginGUI( + id = ID, + titleKey = "gui.news-entry.title", + rows = 6, + fillMode = FillMode.NONE, +) { + + private class Editing(val postId: String, val categoryId: String, val entryId: String) + + private val editing = ConcurrentHashMap() + + fun open(player: Player, post: NewsPost, category: NewsCategory, entry: NewsEntry) { + editing[player.uniqueId] = Editing(post.id, category.id, entry.id) + GUIManager.open(player, ID) + } + + override fun setup(player: Player, inventory: Inventory) { + val (_, _, entry) = target(player) ?: return + + GUIFrame.draw(inventory, tagSlots().keys + TEXT_SLOT) + inventory.setItem( + TEXT_SLOT, + NewsRender.card( + Material.WRITABLE_BOOK, + NewsRender.entryLine(player, entry), + listOf( + player.tr("gui.news-settings.value", "value" to entry.text.main), + player.tr("gui.news-settings.translated", "amount" to entry.text.translations.size), + "", + player.tr("gui.news-settings.click-edit"), + player.tr("gui.news-settings.right-click-translate"), + ), + ), + ) + tagSlots().forEach { (slot, tag) -> + val lines = listOf( + player.tr(if (tag == entry.tag) "gui.news-entry.tag-current" else "gui.news-entry.tag-click") + ) + inventory.setItem( + slot, + NewsRender.card( + NewsRender.tagMaterial(tag), + NewsRender.tag(player, tag), + lines, + glow = tag == entry.tag + ), + ) + } + inventory.setItem( + BACK_SLOT, + NewsRender.button(player, Material.ARROW, "gui.news-entry.back", "gui.news-entry.back-lore") + ) + inventory.setItem( + DELETE_SLOT, + NewsRender.button(player, Material.LAVA_BUCKET, "gui.news-entry.delete", "gui.news-entry.delete-lore") + ) + } + + override fun onClick(event: InventoryClickEvent) { + event.isCancelled = true + if (event.clickedInventory !== event.view.topInventory) return + + val player = event.whoClicked as? Player ?: return + if (!player.hasPermission(NewsCommand.MANAGE_PERMISSION)) return + val (post, category, entry) = target(player) ?: return + val right = event.click == ClickType.RIGHT || event.click == ClickType.SHIFT_RIGHT + val maxLength = NewsSettings.snapshot.maxEntryLength + + when (event.rawSlot) { + TEXT_SLOT -> if (right) { + MenuRender.later(player) { + NewsTextGUI.show( + player, + NewsTextGUI.Target( + post.id, + { it.category(category.id)?.entry(entry.id)?.text }, + maxLength, + ) { show(it, post, category, entry) }, + ) + } + } else { + NewsRender.prompt( + player, + player.tr("gui.news-entry.prompt-text"), + maxLength, + { show(player, post, category, entry) }) { + entry.text.main = it + NewsManager.changed(post) + } + } + + BACK_SLOT -> MenuRender.later(player) { NewsCategoryEditorGUI.show(player, post, category) } + + DELETE_SLOT -> { + category.entries.remove(entry) + NewsManager.changed(post) + player.sendPrefixed(player.tr("news.editor.entry-removed")) + MenuRender.later(player) { NewsCategoryEditorGUI.show(player, post, category) } + } + + else -> { + val tag = tagSlots()[event.rawSlot] ?: return + entry.tag = tag + NewsManager.changed(post) + MenuRender.click(player) + setup(player, event.inventory) + } + } + } + + override fun onClose(event: InventoryCloseEvent) { + editing.remove(event.player.uniqueId) + } + + private fun tagSlots(): Map = + GUIFrame.packedColumns(EntryTag.entries.size).zip(EntryTag.entries).associate { (column, tag) -> + TAG_ROW * ROW_SIZE + column to tag + } + + private fun target(player: Player): Triple? { + val state = editing[player.uniqueId] ?: return null + val post = NewsManager.get(state.postId) ?: return null + val category = post.category(state.categoryId) ?: return null + val entry = category.entry(state.entryId) ?: return null + return Triple(post, category, entry) + } + + companion object { + const val ID = "news-entry" + + private const val ROW_SIZE = 9 + private const val TEXT_SLOT = 13 + private const val TAG_ROW = 3 + private const val BACK_SLOT = 48 + private const val DELETE_SLOT = 50 + + fun show(player: Player, post: NewsPost, category: NewsCategory, entry: NewsEntry): Boolean { + val gui = GUIManager.getGUI(ID) as? NewsEntryGUI ?: return false + gui.open(player, post, category, entry) + return true + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsListGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsListGUI.kt new file mode 100644 index 0000000..dfaad00 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsListGUI.kt @@ -0,0 +1,111 @@ +package net.trilleo.mc.plugins.tritown.guis.news + +import net.trilleo.mc.plugins.tritown.commands.news.NewsCommand +import net.trilleo.mc.plugins.tritown.enums.FillMode +import net.trilleo.mc.plugins.tritown.enums.PagedLayout +import net.trilleo.mc.plugins.tritown.guis.menu.MainMenuGUI +import net.trilleo.mc.plugins.tritown.guis.menu.MenuRender +import net.trilleo.mc.plugins.tritown.news.NewsManager +import net.trilleo.mc.plugins.tritown.news.NewsPost +import net.trilleo.mc.plugins.tritown.news.NewsReadState +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PagedPluginGUI +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.inventory.ItemStack + +/** + * Every published post, pinned ones first and then the newest, each glowing + * until the viewer has read it. + * + * Opened from the main menu, with `/tritown news`, or from the link in the + * join summary. Administrators also find their way into the editor here. + */ +class NewsListGUI : PagedPluginGUI( + id = ID, + titleKey = "gui.news-list.title", + rows = 6, + fillMode = FillMode.NONE, + layout = PagedLayout.FRAMED, +) { + + override fun getItems(player: Player): List { + val posts = NewsManager.published() + if (posts.isEmpty()) { + return listOf( + NewsRender.card( + Material.BARRIER, + player.tr("gui.news-list.empty"), + listOf(player.tr("gui.news-list.empty-lore")), + ) + ) + } + + val unread = NewsReadState.unread(player).mapTo(mutableSetOf()) { it.id } + return posts.map { card(player, it, it.id in unread) } + } + + override fun navButtons(player: Player): Map = buildMap { + put(MenuRender.BACK_OFFSET, MenuRender.back(player)) + if (NewsReadState.unreadCount(player) > 0) { + put( + MenuRender.EXTRA_OFFSET, + NewsRender.button( + player, + Material.MILK_BUCKET, + "gui.news-list.read-all", + "gui.news-list.read-all-lore" + ), + ) + } + if (player.hasPermission(NewsCommand.MANAGE_PERMISSION)) { + put( + MANAGE_OFFSET, + NewsRender.button(player, Material.WRITABLE_BOOK, "gui.news-list.manage", "gui.news-list.manage-lore"), + ) + } + } + + override fun onNavClick(event: InventoryClickEvent, offset: Int) { + val player = event.whoClicked as? Player ?: return + when (offset) { + MenuRender.BACK_OFFSET -> MenuRender.later(player) { MainMenuGUI.show(player) } + MenuRender.EXTRA_OFFSET -> { + NewsReadState.markAllRead(player) + MenuRender.click(player) + refresh(player, event.inventory) + } + + MANAGE_OFFSET -> if (player.hasPermission(NewsCommand.MANAGE_PERMISSION)) { + MenuRender.later(player) { NewsManageGUI.show(player) } + } + } + } + + override fun onContentClick(event: InventoryClickEvent, page: Int) { + val player = event.whoClicked as? Player ?: return + val index = contentIndex(event, page) ?: return + val post = NewsManager.published().getOrNull(index) ?: return + MenuRender.later(player) { NewsPostGUI.show(player, post, preview = false) } + } + + private fun card(player: Player, post: NewsPost, unread: Boolean): ItemStack { + val lines = buildList { + if (unread) add(player.tr("gui.news-list.unread")) + addAll(NewsRender.postLines(player, post)) + add("") + add(player.tr("gui.news-list.click-read")) + } + return NewsRender.card(NewsRender.postIcon(post), NewsRender.title(player, post), lines, glow = unread) + } + + companion object { + const val ID = "news-list" + + private const val MANAGE_OFFSET = 7 + + fun show(player: Player): Boolean = GUIManager.open(player, ID) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsManageGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsManageGUI.kt new file mode 100644 index 0000000..7a43de5 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsManageGUI.kt @@ -0,0 +1,152 @@ +package net.trilleo.mc.plugins.tritown.guis.news + +import net.trilleo.mc.plugins.tritown.commands.news.NewsCommand +import net.trilleo.mc.plugins.tritown.enums.FillMode +import net.trilleo.mc.plugins.tritown.enums.PagedLayout +import net.trilleo.mc.plugins.tritown.guis.ConfirmGUI +import net.trilleo.mc.plugins.tritown.guis.menu.MenuRender +import net.trilleo.mc.plugins.tritown.news.NewsManager +import net.trilleo.mc.plugins.tritown.news.NewsPost +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PagedPluginGUI +import net.trilleo.mc.plugins.tritown.utils.ChatPrompt +import net.trilleo.mc.plugins.tritown.utils.sendPrefixed +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.ClickType +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.inventory.ItemStack + +/** + * Every post an administrator can work on: drafts first, since those are the + * ones in progress, then everything already published. + */ +class NewsManageGUI : PagedPluginGUI( + id = ID, + titleKey = "gui.news-manage.title", + rows = 6, + fillMode = FillMode.NONE, + layout = PagedLayout.FRAMED, +) { + + override fun getItems(player: Player): List { + val posts = NewsManager.forEditors() + if (posts.isEmpty()) { + return listOf( + NewsRender.card( + Material.BARRIER, + player.tr("gui.news-manage.empty"), + listOf(player.tr("gui.news-manage.empty-lore")), + ) + ) + } + return posts.map { card(player, it) } + } + + override fun navButtons(player: Player): Map = mapOf( + MenuRender.BACK_OFFSET to NewsRender.button( + player, + Material.ARROW, + "gui.news-manage.back", + "gui.news-manage.back-lore" + ), + MenuRender.EXTRA_OFFSET to NewsRender.button( + player, + Material.WRITABLE_BOOK, + "gui.news-manage.new", + "gui.news-manage.new-lore" + ), + ) + + override fun onNavClick(event: InventoryClickEvent, offset: Int) { + val player = event.whoClicked as? Player ?: return + when (offset) { + MenuRender.BACK_OFFSET -> MenuRender.later(player) { NewsListGUI.show(player) } + MenuRender.EXTRA_OFFSET -> create(player) + } + } + + override fun onContentClick(event: InventoryClickEvent, page: Int) { + val player = event.whoClicked as? Player ?: return + if (!player.hasPermission(NewsCommand.MANAGE_PERMISSION)) return + val index = contentIndex(event, page) ?: return + val post = NewsManager.forEditors().getOrNull(index) ?: return + + if (event.click == ClickType.SHIFT_LEFT || event.click == ClickType.SHIFT_RIGHT) { + MenuRender.later(player) { confirmDelete(player, post) { NewsManageGUI.show(it) } } + } else { + MenuRender.later(player) { NewsEditorGUI.show(player, post) } + } + } + + private fun create(player: Player) { + if (!player.hasPermission(NewsCommand.MANAGE_PERMISSION)) return + player.closeInventory() + ChatPrompt.ask(player, player.tr("gui.news-manage.prompt-title")) { input -> + if (input.isBlank()) { + show(player) + return@ask + } + val post = NewsManager.create(player, input) + player.sendPrefixed(player.tr("news.editor.created")) + NewsEditorGUI.show(player, post) + } + } + + private fun card(player: Player, post: NewsPost): ItemStack { + val lines = buildList { + add( + if (post.isPublished) player.tr("gui.news-manage.published") + else player.tr("gui.news-manage.draft") + ) + add(player.tr("gui.news-manage.id", "id" to post.id)) + add(player.tr("gui.news-manage.entries", "categories" to post.categories.size, "amount" to post.entryCount)) + addAll(NewsRender.postLines(player, post)) + add("") + add(player.tr("gui.news-manage.click-edit")) + add(player.tr("gui.news-manage.shift-click-delete")) + } + return NewsRender.card( + NewsRender.postIcon(post), + NewsRender.title(player, post), + lines, + glow = !post.isPublished + ) + } + + companion object { + const val ID = "news-manage" + + fun show(player: Player): Boolean = GUIManager.open(player, ID) + + /** Asks before deleting [post] for good. Deleting it leads here; backing out leads to [onCancel]. */ + fun confirmDelete(player: Player, post: NewsPost, onCancel: (Player) -> Unit) { + val subject = NewsRender.card( + NewsRender.postIcon(post), + NewsRender.title(player, post), + NewsRender.postLines(player, post) + ) + ConfirmGUI.show( + player, + title = player.tr("gui.news-manage.delete-title"), + subject = subject, + choices = listOf( + ConfirmGUI.Choice( + NewsRender.button( + player, + Material.LAVA_BUCKET, + "gui.news-manage.delete", + "gui.news-manage.delete-lore" + ) + ) { + NewsManager.delete(post) + it.sendPrefixed(it.tr("news.editor.deleted")) + show(it) + }, + ), + onCancel = onCancel, + ) + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsPostGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsPostGUI.kt new file mode 100644 index 0000000..d920d33 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsPostGUI.kt @@ -0,0 +1,172 @@ +package net.trilleo.mc.plugins.tritown.guis.news + +import net.kyori.adventure.text.Component +import net.trilleo.mc.plugins.tritown.commands.news.NewsCommand +import net.trilleo.mc.plugins.tritown.enums.FillMode +import net.trilleo.mc.plugins.tritown.enums.PagedLayout +import net.trilleo.mc.plugins.tritown.guis.menu.MenuRender +import net.trilleo.mc.plugins.tritown.news.NewsCategory +import net.trilleo.mc.plugins.tritown.news.NewsManager +import net.trilleo.mc.plugins.tritown.news.NewsPost +import net.trilleo.mc.plugins.tritown.news.NewsReadState +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PagedPluginGUI +import net.trilleo.mc.plugins.tritown.utils.ComponentUtil +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.event.inventory.InventoryCloseEvent +import org.bukkit.inventory.ItemStack +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** + * One post: its card in the middle of the top row, then a card per category, + * in the post's order, listing its entries — which is how most posts are read + * in full without a click. + * + * A category too long for its card is cut short with a count of the rest, and + * clicking it lists the entries one by one. The book button shows the whole + * post as pages, which reads better once a post runs long. + * + * Opened as a preview from the editor, the post shows as a player will see it, + * but is not marked read and leads back to the editor. + */ +class NewsPostGUI : PagedPluginGUI( + id = ID, + titleKey = "gui.news-post.title", + rows = 6, + fillMode = FillMode.NONE, + layout = PagedLayout.FRAMED, +) { + + private class Viewing(val postId: String, val preview: Boolean) + + private val viewing = ConcurrentHashMap() + + fun open(player: Player, post: NewsPost, preview: Boolean) { + viewing[player.uniqueId] = Viewing(post.id, preview) + if (!preview && post.isPublished) NewsReadState.markRead(player, post) + GUIManager.open(player, ID) + } + + override fun title(player: Player): Component { + val post = postOf(player) ?: return super.title(player) + return ComponentUtil.parse(player.tr("gui.news-post.title", "title" to NewsRender.text(player, post.title))) + } + + override fun getItems(player: Player): List { + val post = postOf(player) ?: return emptyList() + return categories(post).map { category(player, it) } + } + + override fun topButtons(player: Player): Map { + val post = postOf(player) ?: return emptyMap() + return mapOf(HEADER_OFFSET to header(player, post)) + } + + override fun navButtons(player: Player): Map { + val state = viewing[player.uniqueId] ?: return emptyMap() + return buildMap { + put( + MenuRender.BACK_OFFSET, + if (state.preview) { + NewsRender.button( + player, + Material.ARROW, + "gui.news-post.back-editor", + "gui.news-post.back-editor-lore" + ) + } else { + NewsRender.button(player, Material.ARROW, "gui.news-post.back", "gui.news-post.back-lore") + }, + ) + put( + MenuRender.EXTRA_OFFSET, + NewsRender.button(player, Material.WRITTEN_BOOK, "gui.news-post.book", "gui.news-post.book-lore") + ) + if (!state.preview && player.hasPermission(NewsCommand.MANAGE_PERMISSION)) { + put( + EDIT_OFFSET, + NewsRender.button(player, Material.WRITABLE_BOOK, "gui.news-post.edit", "gui.news-post.edit-lore") + ) + } + } + } + + override fun onNavClick(event: InventoryClickEvent, offset: Int) { + val player = event.whoClicked as? Player ?: return + val state = viewing[player.uniqueId] ?: return + val post = postOf(player) ?: return + + when (offset) { + MenuRender.BACK_OFFSET -> MenuRender.later(player) { + if (state.preview) NewsEditorGUI.show(player, post) else NewsListGUI.show(player) + } + + MenuRender.EXTRA_OFFSET -> MenuRender.later(player) { + player.closeInventory() + player.openBook(NewsRender.book(player, post)) + } + + EDIT_OFFSET -> if (!state.preview && player.hasPermission(NewsCommand.MANAGE_PERMISSION)) { + MenuRender.later(player) { NewsEditorGUI.show(player, post) } + } + } + } + + override fun onContentClick(event: InventoryClickEvent, page: Int) { + val player = event.whoClicked as? Player ?: return + val state = viewing[player.uniqueId] ?: return + val post = postOf(player) ?: return + + val index = contentIndex(event, page) ?: return + val category = categories(post).getOrNull(index) ?: return + MenuRender.later(player) { NewsCategoryGUI.show(player, post, category, state.preview) } + } + + override fun onClose(event: InventoryCloseEvent) { + super.onClose(event) + viewing.remove(event.player.uniqueId) + } + + private fun header(player: Player, post: NewsPost): ItemStack { + val lines = buildList { + if (viewing[player.uniqueId]?.preview == true) { + add(player.tr(if (post.isPublished) "gui.news-post.preview-published" else "gui.news-post.preview-draft")) + } + addAll(NewsRender.postLines(player, post)) + } + return NewsRender.card(NewsRender.postIcon(post), NewsRender.title(player, post), lines) + } + + private fun category(player: Player, category: NewsCategory): ItemStack { + val lines = buildList { + category.entries.take(NewsRender.LORE_ENTRIES).forEach { add(NewsRender.entryLine(player, it)) } + val rest = category.entries.size - NewsRender.LORE_ENTRIES + if (rest > 0) add(player.tr("gui.news-post.more", "amount" to rest)) + add("") + add(player.tr("gui.news-post.click-category")) + } + return NewsRender.card(NewsRender.categoryIcon(category), NewsRender.text(player, category.name), lines) + } + + /** A category with nothing in it yet has nothing to show a reader. */ + private fun categories(post: NewsPost): List = post.categories.filter { it.entries.isNotEmpty() } + + private fun postOf(player: Player): NewsPost? = viewing[player.uniqueId]?.postId?.let(NewsManager::get) + + companion object { + const val ID = "news-post" + + private const val EDIT_OFFSET = 7 + private const val HEADER_OFFSET = 4 + + fun show(player: Player, post: NewsPost, preview: Boolean): Boolean { + val gui = GUIManager.getGUI(ID) as? NewsPostGUI ?: return false + gui.open(player, post, preview) + return true + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsRender.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsRender.kt new file mode 100644 index 0000000..3149b67 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsRender.kt @@ -0,0 +1,197 @@ +package net.trilleo.mc.plugins.tritown.guis.news + +import net.kyori.adventure.inventory.Book +import net.kyori.adventure.text.Component +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer +import net.trilleo.mc.plugins.tritown.guis.admin.PanelRender +import net.trilleo.mc.plugins.tritown.news.* +import net.trilleo.mc.plugins.tritown.utils.* +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack + +/** + * The pieces the news menus draw with, so a post, a tag or a date reads the + * same in the reader, the editor and the book. + * + * Everything a post says was written by an administrator in MiniMessage and is + * embedded as written, the way a shop's name is. + */ +object NewsRender { + + /** How many entries a category card lists before pointing at the rest. */ + const val LORE_ENTRIES = 8 + + fun text(viewer: Player, text: LocalizedText): String = text.forViewer(viewer) + + /** A stored material name as an item, or [fallback] when it names nothing that can sit in a menu. */ + fun material(name: String, fallback: Material): Material = + Material.matchMaterial(name)?.takeIf { it.isItem && !it.isAir } ?: fallback + + fun postIcon(post: NewsPost): Material = material(post.icon, Material.WRITABLE_BOOK) + + fun categoryIcon(category: NewsCategory): Material = material(category.icon, Material.BOOK) + + fun tag(viewer: Player, tag: EntryTag): String = when (tag) { + EntryTag.NEW -> viewer.tr("news.tag.new") + EntryTag.CHANGED -> viewer.tr("news.tag.changed") + EntryTag.FIXED -> viewer.tr("news.tag.fixed") + EntryTag.REMOVED -> viewer.tr("news.tag.removed") + EntryTag.NOTE -> viewer.tr("news.tag.note") + } + + fun tagMaterial(tag: EntryTag): Material = when (tag) { + EntryTag.NEW -> Material.LIME_DYE + EntryTag.CHANGED -> Material.YELLOW_DYE + EntryTag.FIXED -> Material.LIGHT_BLUE_DYE + EntryTag.REMOVED -> Material.RED_DYE + EntryTag.NOTE -> Material.PAPER + } + + /** One entry as a single line: its tag, then what it says. */ + fun entryLine(viewer: Player, entry: NewsEntry): String = + viewer.tr("news.entry", "tag" to tag(viewer, entry.tag), "text" to text(viewer, entry.text)) + + fun title(viewer: Player, post: NewsPost): String { + val title = text(viewer, post.title) + return if (post.pinned) viewer.tr("gui.news.pinned-title", "title" to title) else viewer.tr( + "gui.news.title", + "title" to title + ) + } + + /** + * What a post is about, for the top of its card: label, dates, author, + * summary and what each category holds. + */ + fun postLines(viewer: Player, post: NewsPost): List = buildList { + post.label?.let { add(viewer.tr("gui.news.label", "label" to it)) } + post.publishedAt?.let { add(viewer.tr("gui.news.published", "date" to PanelRender.time(it))) } + post.editedAt?.let { add(viewer.tr("gui.news.edited", "date" to PanelRender.time(it))) } + post.authorName?.let { add(viewer.tr("gui.news.author", "name" to ComponentUtil.escape(it))) } + post.summary?.let { + add("") + add(viewer.tr("gui.news.summary", "text" to text(viewer, it))) + } + val categories = post.categories.filter { it.entries.isNotEmpty() } + if (categories.isNotEmpty()) { + add("") + categories.forEach { category -> + add( + viewer.tr( + "gui.news.category-count", + "name" to text(viewer, category.name), + "amount" to category.entries.size + ) + ) + } + } + } + + fun card(material: Material, name: String, lines: List, glow: Boolean = false): ItemStack = + PanelRender.card(material, name, lines).also { item -> + if (glow) item.editMeta { it.setEnchantmentGlintOverride(true) } + } + + fun button(viewer: Player, material: Material, nameKey: String, loreKey: String): ItemStack = + itemStack(material) { + name(viewer.tr(nameKey)) + meta { lore(LoreUtil.wrapLore(viewer.tr(loreKey))) } + } + + fun glowing(item: ItemStack): ItemStack = item.clone().also { copy -> + copy.editMeta { it.setEnchantmentGlintOverride(true) } + } + + /** + * Closes the menu and asks [player] for a line of text in chat, then + * [reopen]s whatever they were in. + * + * A blank answer changes nothing, and one longer than [maxLength] visible + * characters is refused with a message rather than cut short, so what was + * typed is never silently changed. + */ + fun prompt(player: Player, question: String, maxLength: Int?, reopen: () -> Unit, onInput: (String) -> Unit) { + player.closeInventory() + ChatPrompt.ask(player, question) { input -> + when { + input.isBlank() -> Unit + maxLength != null && visibleLength(input) > maxLength -> + player.sendPrefixed(player.tr("news.editor.too-long", "amount" to maxLength)) + + else -> onInput(input) + } + reopen() + } + } + + /** How many characters [text] shows once its MiniMessage tags are gone. */ + fun visibleLength(text: String): Int = + PlainTextComponentSerializer.plainText().serialize(ComponentUtil.parse(text)).length + + /** + * [post] as a written book: a title page, then each category and its + * entries, running on to a new page whenever one fills up. + * + * A book shows long notes far better than item lore does, and it is opened + * straight from the post without any item being handed out. + */ + fun book(viewer: Player, post: NewsPost): Book { + val pages = mutableListOf() + + val cover = buildList { + add(viewer.tr("news.book.title", "title" to text(viewer, post.title))) + post.label?.let { add(viewer.tr("news.book.label", "label" to it)) } + post.publishedAt?.let { add(viewer.tr("news.book.date", "date" to PanelRender.time(it))) } + post.summary?.let { add(""); add(viewer.tr("news.book.summary", "text" to text(viewer, it))) } + } + pages += ComponentUtil.parse(cover.joinToString("")) + + var page = mutableListOf() + var used = 0 + fun flush() { + if (page.isNotEmpty()) pages += ComponentUtil.parse(page.joinToString("")) + page = mutableListOf() + used = 0 + } + + fun write(line: String) { + val height = lineHeight(line) + if (used + height > BOOK_LINES) flush() + page += line + used += height + } + + post.categories.filter { it.entries.isNotEmpty() }.forEach { category -> + if (used > 0 && used + 3 > BOOK_LINES) flush() else if (used > 0) write("") + write(viewer.tr("news.book.category", "name" to text(viewer, category.name))) + category.entries.forEach { + write( + viewer.tr( + "news.book.entry", + "tag" to tag(viewer, it.tag), + "text" to text(viewer, it.text) + ) + ) + } + } + flush() + + return Book.book( + ComponentUtil.parse(text(viewer, post.title)), + ComponentUtil.parse(ComponentUtil.escape(post.authorName ?: "")), + pages, + ) + } + + /** Roughly how many of a book page's lines [line] takes once it wraps. A CJK character is about two wide. */ + private fun lineHeight(line: String): Int { + val plain = PlainTextComponentSerializer.plainText().serialize(ComponentUtil.parse(line)) + val width = plain.sumOf { if (it.code >= WIDE_FROM) 2 else 1 } + return width / BOOK_LINE_CHARS + 1 + } + + private const val BOOK_LINES = 13 + private const val BOOK_LINE_CHARS = 19 + private const val WIDE_FROM = 0x2E80 +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsSettingsGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsSettingsGUI.kt new file mode 100644 index 0000000..c3be3ba --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsSettingsGUI.kt @@ -0,0 +1,234 @@ +package net.trilleo.mc.plugins.tritown.guis.news + +import net.trilleo.mc.plugins.tritown.commands.news.NewsCommand +import net.trilleo.mc.plugins.tritown.enums.FillMode +import net.trilleo.mc.plugins.tritown.guis.menu.MenuRender +import net.trilleo.mc.plugins.tritown.news.LocalizedText +import net.trilleo.mc.plugins.tritown.news.NewsManager +import net.trilleo.mc.plugins.tritown.news.NewsPost +import net.trilleo.mc.plugins.tritown.registration.GUIFrame +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PluginGUI +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.ClickType +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.event.inventory.InventoryCloseEvent +import org.bukkit.inventory.Inventory +import org.bukkit.inventory.ItemStack +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** + * A post as a whole: its title, summary, label, icon, and whether it is pinned + * to the top of the news. + * + * The icon is chosen by clicking any item in your own inventory, the way a + * shop entry is added: only its type is read, and the item stays where it is. + */ +class NewsSettingsGUI : PluginGUI( + id = ID, + titleKey = "gui.news-settings.title", + rows = 6, + fillMode = FillMode.NONE, +) { + + private val editing = ConcurrentHashMap() + + fun open(player: Player, post: NewsPost) { + editing[player.uniqueId] = post.id + GUIManager.open(player, ID) + } + + override fun setup(player: Player, inventory: Inventory) { + val post = postOf(player) ?: return + + GUIFrame.draw(inventory, SLOTS) + inventory.setItem(SLOT_TITLE, title(player, post)) + inventory.setItem(SLOT_SUMMARY, summary(player, post)) + inventory.setItem(SLOT_LABEL, label(player, post)) + inventory.setItem(SLOT_ICON, icon(player, post)) + inventory.setItem(SLOT_PIN, pin(player, post)) + inventory.setItem( + SLOT_BACK, + NewsRender.button(player, Material.ARROW, "gui.news-settings.back", "gui.news-settings.back-lore") + ) + } + + override fun onClick(event: InventoryClickEvent) { + event.isCancelled = true + + val player = event.whoClicked as? Player ?: return + if (!player.hasPermission(NewsCommand.MANAGE_PERMISSION)) return + val post = postOf(player) ?: return + + if (event.clickedInventory === player.inventory) { + val item = event.currentItem ?: return + if (item.type.isAir) return + post.icon = item.type.name + NewsManager.changed(post) + MenuRender.click(player) + setup(player, event.inventory) + return + } + if (event.clickedInventory !== event.view.topInventory) return + + val right = event.click == ClickType.RIGHT || event.click == ClickType.SHIFT_RIGHT + val shift = event.click == ClickType.SHIFT_LEFT || event.click == ClickType.SHIFT_RIGHT + val reopen: () -> Unit = { show(player, post) } + + when (event.rawSlot) { + SLOT_TITLE -> if (right) { + translations(player, post) { it.title } + } else { + NewsRender.prompt(player, player.tr("gui.news-settings.prompt-title"), null, reopen) { + post.title.main = it + NewsManager.changed(post) + } + } + + SLOT_SUMMARY -> when { + shift -> { + post.summary = null + NewsManager.changed(post) + MenuRender.click(player) + setup(player, event.inventory) + } + + right && post.summary != null -> translations(player, post) { it.summary } + else -> NewsRender.prompt(player, player.tr("gui.news-settings.prompt-summary"), null, reopen) { + val summary = post.summary ?: LocalizedText().also { created -> post.summary = created } + summary.main = it + NewsManager.changed(post) + } + } + + SLOT_LABEL -> if (right) { + post.label = null + NewsManager.changed(post) + MenuRender.click(player) + setup(player, event.inventory) + } else { + NewsRender.prompt(player, player.tr("gui.news-settings.prompt-label"), MAX_LABEL, reopen) { + post.label = it + NewsManager.changed(post) + } + } + + SLOT_ICON -> if (right) { + post.icon = NewsPost.DEFAULT_ICON + NewsManager.changed(post) + MenuRender.click(player) + setup(player, event.inventory) + } + + SLOT_PIN -> { + post.pinned = !post.pinned + NewsManager.changed(post) + MenuRender.click(player) + setup(player, event.inventory) + } + + SLOT_BACK -> MenuRender.later(player) { NewsEditorGUI.show(player, post) } + } + } + + override fun onClose(event: InventoryCloseEvent) { + editing.remove(event.player.uniqueId) + } + + private fun translations(player: Player, post: NewsPost, field: (NewsPost) -> LocalizedText?) { + MenuRender.later(player) { + NewsTextGUI.show(player, NewsTextGUI.Target(post.id, field, null) { show(it, post) }) + } + } + + private fun title(player: Player, post: NewsPost): ItemStack = NewsRender.card( + Material.NAME_TAG, + player.tr("gui.news-settings.title-name"), + listOf( + player.tr("gui.news-settings.value", "value" to post.title.main), + player.tr("gui.news-settings.translated", "amount" to post.title.translations.size), + "", + player.tr("gui.news-settings.click-edit"), + player.tr("gui.news-settings.right-click-translate"), + ), + ) + + private fun summary(player: Player, post: NewsPost): ItemStack { + val summary = post.summary + val lines = buildList { + add(player.tr("gui.news-settings.summary-lore")) + add( + if (summary == null) player.tr("gui.news-settings.value", "value" to player.tr("common.none")) + else player.tr("gui.news-settings.value", "value" to summary.main) + ) + summary?.let { add(player.tr("gui.news-settings.translated", "amount" to it.translations.size)) } + add("") + add(player.tr("gui.news-settings.click-edit")) + if (summary != null) { + add(player.tr("gui.news-settings.right-click-translate")) + add(player.tr("gui.news-settings.shift-click-clear")) + } + } + return NewsRender.card(Material.BOOK, player.tr("gui.news-settings.summary"), lines) + } + + private fun label(player: Player, post: NewsPost): ItemStack = NewsRender.card( + Material.OAK_SIGN, + player.tr("gui.news-settings.label"), + listOf( + player.tr("gui.news-settings.label-lore"), + player.tr("gui.news-settings.value", "value" to (post.label ?: player.tr("common.none"))), + "", + player.tr("gui.news-settings.click-edit"), + player.tr("gui.news-settings.right-click-clear"), + ), + ) + + private fun icon(player: Player, post: NewsPost): ItemStack = NewsRender.card( + NewsRender.postIcon(post), + player.tr("gui.news-settings.icon"), + listOf( + player.tr("gui.news-settings.icon-lore"), + "", + player.tr("gui.news-settings.right-click-reset"), + ), + ) + + private fun pin(player: Player, post: NewsPost): ItemStack = NewsRender.card( + if (post.pinned) Material.LIME_DYE else Material.GRAY_DYE, + player.tr("gui.news-settings.pin"), + listOf( + player.tr(if (post.pinned) "gui.news-settings.pinned" else "gui.news-settings.not-pinned"), + "", + player.tr("gui.news-settings.click-toggle"), + ), + glow = post.pinned, + ) + + private fun postOf(player: Player): NewsPost? = editing[player.uniqueId]?.let(NewsManager::get) + + companion object { + const val ID = "news-settings" + + private const val SLOT_TITLE = 20 + private const val SLOT_SUMMARY = 22 + private const val SLOT_LABEL = 24 + private const val SLOT_ICON = 30 + private const val SLOT_PIN = 32 + private const val SLOT_BACK = 49 + + private val SLOTS = setOf(SLOT_TITLE, SLOT_SUMMARY, SLOT_LABEL, SLOT_ICON, SLOT_PIN) + + /** A label names a version or a season, so it is kept to a few words. */ + private const val MAX_LABEL = 32 + + fun show(player: Player, post: NewsPost): Boolean { + val gui = GUIManager.getGUI(ID) as? NewsSettingsGUI ?: return false + gui.open(player, post) + return true + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsTextGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsTextGUI.kt new file mode 100644 index 0000000..c0732be --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/news/NewsTextGUI.kt @@ -0,0 +1,177 @@ +package net.trilleo.mc.plugins.tritown.guis.news + +import net.trilleo.mc.plugins.tritown.commands.news.NewsCommand +import net.trilleo.mc.plugins.tritown.enums.FillMode +import net.trilleo.mc.plugins.tritown.guis.menu.MenuRender +import net.trilleo.mc.plugins.tritown.news.LocalizedText +import net.trilleo.mc.plugins.tritown.news.NewsManager +import net.trilleo.mc.plugins.tritown.news.NewsPost +import net.trilleo.mc.plugins.tritown.registration.GUIFrame +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import net.trilleo.mc.plugins.tritown.registration.PluginGUI +import net.trilleo.mc.plugins.tritown.utils.Lang +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.event.inventory.ClickType +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.event.inventory.InventoryCloseEvent +import org.bukkit.inventory.Inventory +import org.bukkit.inventory.ItemStack +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** + * One piece of a post's text in every language the server has. + * + * The default text is what anyone without a translation reads; each language + * file installed gets a button of its own below it. The same menu serves a + * title, a summary, a category name and an entry, which is why it is handed + * the field to edit and the way back rather than knowing either. + */ +class NewsTextGUI : PluginGUI( + id = ID, + titleKey = "gui.news-text.title", + rows = 6, + fillMode = FillMode.NONE, +) { + + /** + * What is being translated. + * + * @param field finds the text in the post as it is now, or `null` once it is gone + * @param maxLength the most visible characters each version may have, if there is a limit + * @param back reopens the menu this was reached from + */ + class Target( + val postId: String, + val field: (NewsPost) -> LocalizedText?, + val maxLength: Int?, + val back: (Player) -> Unit, + ) + + private val targets = ConcurrentHashMap() + + fun open(player: Player, target: Target) { + targets[player.uniqueId] = target + GUIManager.open(player, ID) + } + + override fun setup(player: Player, inventory: Inventory) { + val text = textOf(player) ?: return + val languages = languageSlots() + + GUIFrame.draw(inventory, languages.keys + MAIN_SLOT) + inventory.setItem(MAIN_SLOT, main(player, text)) + languages.forEach { (slot, id) -> inventory.setItem(slot, language(player, text, id)) } + inventory.setItem( + BACK_SLOT, + NewsRender.button(player, Material.ARROW, "gui.news-text.back", "gui.news-text.back-lore") + ) + } + + override fun onClick(event: InventoryClickEvent) { + event.isCancelled = true + if (event.clickedInventory !== event.view.topInventory) return + + val player = event.whoClicked as? Player ?: return + if (!player.hasPermission(NewsCommand.MANAGE_PERMISSION)) return + val target = targets[player.uniqueId] ?: return + val post = NewsManager.get(target.postId) ?: return + val text = target.field(post) ?: return + val reopen: () -> Unit = { show(player, target) } + + if (event.rawSlot == BACK_SLOT) { + MenuRender.later(player) { target.back(player) } + return + } + + if (event.rawSlot == MAIN_SLOT) { + NewsRender.prompt(player, player.tr("gui.news-text.prompt-main"), target.maxLength, reopen) { + text.main = it + NewsManager.changed(post) + } + return + } + + val language = languageSlots()[event.rawSlot] ?: return + if (event.click == ClickType.RIGHT || event.click == ClickType.SHIFT_RIGHT) { + text.clear(language) + NewsManager.changed(post) + MenuRender.click(player) + setup(player, event.inventory) + return + } + + NewsRender.prompt( + player, + player.tr("gui.news-text.prompt-language", "language" to language), + target.maxLength, + reopen + ) { + text.translate(language, it) + NewsManager.changed(post) + } + } + + override fun onClose(event: InventoryCloseEvent) { + targets.remove(event.player.uniqueId) + } + + private fun main(player: Player, text: LocalizedText): ItemStack = NewsRender.card( + Material.WRITABLE_BOOK, + player.tr("gui.news-text.main"), + listOf( + player.tr("gui.news-text.current", "text" to text.main), + "", + player.tr("gui.news-text.main-lore"), + player.tr("gui.news-text.click-edit"), + ), + ) + + private fun language(player: Player, text: LocalizedText, id: String): ItemStack { + val translation = text.translation(id) + val lines = buildList { + add( + if (translation != null) player.tr("gui.news-text.current", "text" to translation) + else player.tr("gui.news-text.untranslated") + ) + add("") + add(player.tr("gui.news-text.click-edit")) + if (translation != null) add(player.tr("gui.news-text.right-click-clear")) + } + return NewsRender.card( + if (translation != null) Material.FILLED_MAP else Material.MAP, + player.tr("gui.news-text.language", "language" to id), + lines, + ) + } + + /** One slot per installed language, packed along the row under the default text. Seven fit. */ + private fun languageSlots(): Map { + val ids = Lang.ids.take(MAX_LANGUAGES) + return GUIFrame.packedColumns(ids.size).zip(ids) + .associate { (column, id) -> LANGUAGE_ROW * ROW_SIZE + column to id } + } + + private fun textOf(player: Player): LocalizedText? { + val target = targets[player.uniqueId] ?: return null + return NewsManager.get(target.postId)?.let(target.field) + } + + companion object { + const val ID = "news-text" + + private const val ROW_SIZE = 9 + private const val MAIN_SLOT = 13 + private const val LANGUAGE_ROW = 3 + private const val MAX_LANGUAGES = 7 + private const val BACK_SLOT = 49 + + fun show(player: Player, target: Target): Boolean { + val gui = GUIManager.getGUI(ID) as? NewsTextGUI ?: return false + gui.open(player, target) + return true + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/shop/ShopEditorGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/shop/ShopEditorGUI.kt index 4741ba2..742ca80 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/shop/ShopEditorGUI.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/shop/ShopEditorGUI.kt @@ -151,7 +151,7 @@ class ShopEditorGUI : PagedPluginGUI( val player = event.whoClicked as? Player ?: return val shop = shopOf(player) ?: return - val index = contentIndex(page, event.rawSlot) ?: return + val index = contentIndex(event, page) ?: return val held = moving[player.uniqueId] if (held != null) { place(player, shop, held, index, event.inventory) diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/shop/ShopGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/shop/ShopGUI.kt index 5c7a86c..de9f595 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/shop/ShopGUI.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/shop/ShopGUI.kt @@ -73,7 +73,7 @@ class ShopGUI : PagedPluginGUI( val view = views[player.uniqueId] ?: return val shop = ShopManager.get(view.shopId) ?: return - val index = contentIndex(page, event.rawSlot) ?: return + val index = contentIndex(event, page) ?: return val entry = view.entryIds.getOrNull(index)?.let(shop::entry) ?: return val result = when (event.click) { diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/shop/ShopListGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/shop/ShopListGUI.kt index 7397550..3275b3f 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/shop/ShopListGUI.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/shop/ShopListGUI.kt @@ -47,7 +47,7 @@ class ShopListGUI : PagedPluginGUI( event.isCancelled = true val player = event.whoClicked as? Player ?: return - val index = contentIndex(page, event.rawSlot) ?: return + val index = contentIndex(event, page) ?: return val shop = ShopManager.all().getOrNull(index) ?: return ShopRender.navigate { diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/shop/ShopStatsGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/shop/ShopStatsGUI.kt index ffb70cd..7c8cd83 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/shop/ShopStatsGUI.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/guis/shop/ShopStatsGUI.kt @@ -54,7 +54,7 @@ class ShopStatsGUI : PagedPluginGUI( val player = event.whoClicked as? Player ?: return val shop = shopOf(player) ?: return - val index = contentIndex(page, event.rawSlot) ?: return + val index = contentIndex(event, page) ?: return if (index != 0 || event.click != ClickType.SHIFT_LEFT) return shop.entries.forEach { it.stats.reset() } diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/menu/MenuItemListener.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/menu/MenuItemListener.kt new file mode 100644 index 0000000..0d51436 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/menu/MenuItemListener.kt @@ -0,0 +1,228 @@ +package net.trilleo.mc.plugins.tritown.listeners.menu + +import com.destroystokyo.paper.event.player.PlayerPostRespawnEvent +import net.trilleo.mc.plugins.tritown.Main +import net.trilleo.mc.plugins.tritown.guis.menu.MainMenuGUI +import net.trilleo.mc.plugins.tritown.menu.MenuItem +import net.trilleo.mc.plugins.tritown.registration.GUIManager +import org.bukkit.Bukkit +import org.bukkit.GameMode +import org.bukkit.entity.Player +import org.bukkit.event.Event +import org.bukkit.event.EventHandler +import org.bukkit.event.EventPriority +import org.bukkit.event.Listener +import org.bukkit.event.block.Action +import org.bukkit.event.block.BlockPlaceEvent +import org.bukkit.event.entity.EntityPickupItemEvent +import org.bukkit.event.entity.ItemSpawnEvent +import org.bukkit.event.entity.PlayerDeathEvent +import org.bukkit.event.inventory.* +import org.bukkit.event.player.* +import org.bukkit.inventory.EquipmentSlot + +/** + * Keeps the [MenuItem] in its slot and opens the menu from it. + * + * Every handler here refuses one way a copy could leave the last hotbar slot. + * They run first, at the lowest priority, so no other plugin ever sees an + * action on the item that is about to be undone — and `GUIManager` skips + * clicks that are already cancelled, so a menu that takes items out of the + * player's inventory, like the trade table, never receives it either. + * + * Refusing is only half of it. After anything that could have left the + * inventory out of step with what the client shows — a cancelled drop, a + * creative-mode click, a respawn — [MenuItem.reconcileLater] puts it right, + * deleting any copy that is not in the slot. + */ +class MenuItemListener : Listener { + + // ── Giving it out and taking it back ──────────────────────────────── + + @EventHandler(priority = EventPriority.MONITOR) + fun onJoin(event: PlayerJoinEvent) = MenuItem.reconcile(event.player) + + /** Taken back before the inventory is saved, so no copy is ever written to disk. */ + @EventHandler(priority = EventPriority.MONITOR) + fun onQuit(event: PlayerQuitEvent) = MenuItem.strip(event.player) + + @EventHandler(priority = EventPriority.MONITOR) + fun onRespawn(event: PlayerPostRespawnEvent) = MenuItem.reconcile(event.player) + + /** A per-world or per-mode inventory plugin swaps the whole inventory, item and all. */ + @EventHandler(priority = EventPriority.MONITOR) + fun onWorldChange(event: PlayerChangedWorldEvent) = MenuItem.reconcileLater(event.player) + + @EventHandler(priority = EventPriority.MONITOR) + fun onGameModeChange(event: PlayerGameModeChangeEvent) = MenuItem.reconcileLater(event.player) + + /** The client reports its language after joining, and the item is named in it. */ + @EventHandler(priority = EventPriority.MONITOR) + fun onLocaleChange(event: PlayerLocaleChangeEvent) = MenuItem.reconcileLater(event.player) + + /** Never dropped on death, and never kept either: [onRespawn] hands out a fresh one. */ + @EventHandler(priority = EventPriority.LOWEST) + fun onDeath(event: PlayerDeathEvent) { + event.drops.removeIf(MenuItem::isMenuItem) + event.itemsToKeep.removeIf(MenuItem::isMenuItem) + } + + // ── Using it ──────────────────────────────────────────────────────── + + /** + * Right-clicking with the item opens the menu, and nothing else the click + * would do happens: it is never placed, eaten, thrown, equipped or put into + * a block such as a lectern, a pot or a jukebox. + * + * Both hands are refused, so the off hand cannot place something while the + * menu is opening. + */ + @EventHandler(priority = EventPriority.LOWEST) + fun onInteract(event: PlayerInteractEvent) { + val player = event.player + if (!MenuItem.isMenuItem(player.inventory.itemInMainHand)) return + if (event.action != Action.RIGHT_CLICK_AIR && event.action != Action.RIGHT_CLICK_BLOCK) return + + event.setUseItemInHand(Event.Result.DENY) + event.setUseInteractedBlock(Event.Result.DENY) + if (event.hand == EquipmentSlot.HAND) open(player) + } + + /** + * Keeps the item out of item frames, armour stands, allays and anything + * else that takes what it is clicked with. + * + * Players are let through, so shift-right-clicking someone to trade still + * works with the item in hand. + */ + @EventHandler(priority = EventPriority.LOWEST) + fun onInteractEntity(event: PlayerInteractEntityEvent) { + if (event.rightClicked is Player) return + if (MenuItem.isMenuItem(event.player.inventory.getItem(event.hand))) event.isCancelled = true + } + + /** Armour stands arrive as this event rather than [PlayerInteractEntityEvent]. */ + @EventHandler(priority = EventPriority.LOWEST) + fun onInteractAtEntity(event: PlayerInteractAtEntityEvent) { + if (event.rightClicked is Player) return + if (MenuItem.isMenuItem(event.player.inventory.getItem(event.hand))) event.isCancelled = true + } + + /** Only reachable with a block chosen as the material, and refused there too. */ + @EventHandler(priority = EventPriority.LOWEST) + fun onPlace(event: BlockPlaceEvent) { + if (MenuItem.isMenuItem(event.itemInHand)) event.isCancelled = true + } + + // ── Keeping it in its slot ────────────────────────────────────────── + + @EventHandler(priority = EventPriority.LOWEST) + fun onDrop(event: PlayerDropItemEvent) { + if (!MenuItem.isMenuItem(event.itemDrop.itemStack)) return + event.isCancelled = true + MenuItem.reconcileLater(event.player) + } + + @EventHandler(priority = EventPriority.LOWEST) + fun onSwapHands(event: PlayerSwapHandItemsEvent) { + if (MenuItem.isMenuItem(event.mainHandItem) || MenuItem.isMenuItem(event.offHandItem)) { + event.isCancelled = true + } + } + + /** + * Refuses any click that would pick the item up, put something on top of + * it, or swap it anywhere. + * + * The slot is checked as well as the item while the item is enabled, because + * a number key or the swap-hands key moves whatever is in a slot without + * either stack being the one clicked. A plain click on the item in the player's own inventory + * opens the menu instead. + * + * A creative client writes its own slots and is only told no afterwards, + * so every creative click on the item is followed by a reconcile. + */ + @EventHandler(priority = EventPriority.LOWEST) + fun onClick(event: InventoryClickEvent) { + val player = event.whoClicked as? Player ?: return + val inventory = player.inventory + + val guarded = MenuItem.isEnabled + val onSlot = guarded && event.clickedInventory === inventory && event.slot == MenuItem.SLOT + val clickedItem = MenuItem.isMenuItem(event.currentItem) + val touches = onSlot || clickedItem || + MenuItem.isMenuItem(event.cursor) || + (guarded && event.click == ClickType.NUMBER_KEY && event.hotbarButton == MenuItem.SLOT) || + (event.click == ClickType.SWAP_OFFHAND && MenuItem.isMenuItem(inventory.itemInOffHand)) + if (!touches) return + + event.isCancelled = true + if (player.gameMode == GameMode.CREATIVE) MenuItem.reconcileLater(player) + + val plainClick = event.click == ClickType.LEFT || event.click == ClickType.RIGHT + val ownInventory = event.view.topInventory.type == InventoryType.CRAFTING + if ((onSlot || clickedItem) && plainClick && ownInventory && event.cursor.isEmpty) { + // A menu opened while the click is still being delivered leaves the client out of step. + Bukkit.getScheduler().runTask(Main.instance, Runnable { open(player) }) + } + } + + @EventHandler(priority = EventPriority.LOWEST) + fun onDrag(event: InventoryDragEvent) { + val player = event.whoClicked as? Player ?: return + val intoSlot = MenuItem.isEnabled && event.rawSlots.any { + event.view.getInventory(it) === player.inventory && event.view.convertSlot(it) == MenuItem.SLOT + } + if (!intoSlot && !MenuItem.isMenuItem(event.oldCursor)) return + + event.isCancelled = true + if (player.gameMode == GameMode.CREATIVE) MenuItem.reconcileLater(player) + } + + // ── Wherever it should never be ───────────────────────────────────── + + /** A beacon costs a nether star, and the item is one unless the owner picked otherwise. */ + @EventHandler(priority = EventPriority.LOWEST) + fun onPrepareCraft(event: PrepareItemCraftEvent) { + if (event.inventory.matrix.any(MenuItem::isMenuItem)) event.inventory.result = null + } + + @EventHandler(priority = EventPriority.LOWEST) + fun onCraft(event: CraftItemEvent) { + if (event.inventory.matrix.any(MenuItem::isMenuItem)) event.isCancelled = true + } + + @EventHandler(priority = EventPriority.LOWEST) + fun onItemSpawn(event: ItemSpawnEvent) { + if (MenuItem.isMenuItem(event.entity.itemStack)) event.isCancelled = true + } + + @EventHandler(priority = EventPriority.LOWEST) + fun onPickup(event: EntityPickupItemEvent) { + if (!MenuItem.isMenuItem(event.item.itemStack)) return + event.isCancelled = true + event.item.remove() + } + + @EventHandler(priority = EventPriority.LOWEST) + fun onHopperPickup(event: InventoryPickupItemEvent) { + if (!MenuItem.isMenuItem(event.item.itemStack)) return + event.isCancelled = true + event.item.remove() + } + + @EventHandler(priority = EventPriority.LOWEST) + fun onHopperMove(event: InventoryMoveItemEvent) { + if (MenuItem.isMenuItem(event.item)) event.isCancelled = true + } + + /** Clears out a container that somehow came to hold a copy, the moment anyone looks inside. */ + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + fun onOpen(event: InventoryOpenEvent) = MenuItem.purge(event.inventory) + + /** A right-click on a block can arrive twice in one tick, and the second must not reopen the menu. */ + private fun open(player: Player) { + if (GUIManager.openGUI(player) is MainMenuGUI) return + MainMenuGUI.show(player) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/news/NewsJoinListener.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/news/NewsJoinListener.kt new file mode 100644 index 0000000..a81b504 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/news/NewsJoinListener.kt @@ -0,0 +1,37 @@ +package net.trilleo.mc.plugins.tritown.listeners.news + +import net.trilleo.mc.plugins.tritown.config.NewsSettings +import net.trilleo.mc.plugins.tritown.news.NewsManager +import net.trilleo.mc.plugins.tritown.news.NewsNotifier +import net.trilleo.mc.plugins.tritown.news.NewsReadState +import org.bukkit.event.EventHandler +import org.bukkit.event.EventPriority +import org.bukkit.event.Listener +import org.bukkit.event.player.PlayerJoinEvent +import org.bukkit.plugin.java.JavaPlugin + +/** Tells a player what they have missed as they join. */ +class NewsJoinListener(private val plugin: JavaPlugin) : Listener { + + /** Above NORMAL, so the player's data has been loaded before it is read. */ + @EventHandler(priority = EventPriority.HIGH) + fun onJoin(event: PlayerJoinEvent) { + if (!NewsManager.isAvailable) return + val player = event.player + NewsReadState.review(player) + + val settings = NewsSettings.snapshot + if (!settings.joinMessage) return + // Later than the join, so the client has sent its language and the + // summary is not lost among the server's welcome messages. + plugin.server.scheduler.runTaskLater( + plugin, + Runnable { NewsNotifier.joinSummary(player) }, + settings.joinDelayTicks.coerceAtLeast(MIN_DELAY_TICKS), + ) + } + + private companion object { + const val MIN_DELAY_TICKS = 20L + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/town/FoundingCreditListener.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/town/FoundingCreditListener.kt new file mode 100644 index 0000000..c48f301 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/listeners/town/FoundingCreditListener.kt @@ -0,0 +1,63 @@ +package net.trilleo.mc.plugins.tritown.listeners.town + +import com.palmergames.bukkit.towny.event.PreNewTownEvent +import com.palmergames.bukkit.towny.event.TownAddResidentEvent +import net.trilleo.mc.plugins.tritown.towns.FoundingCredit +import net.trilleo.mc.plugins.tritown.utils.sendPrefixed +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.entity.Player +import org.bukkit.event.EventHandler +import org.bukkit.event.EventPriority +import org.bukkit.event.Listener +import org.bukkit.event.player.PlayerJoinEvent +import org.bukkit.event.player.PlayerQuitEvent +import org.bukkit.plugin.java.JavaPlugin + +/** Grants, spends and forfeits the [FoundingCredit] as players join the server and towns. */ +class FoundingCreditListener(private val plugin: JavaPlugin) : Listener { + + /** Above NORMAL, so the player's data has been loaded before it is read. */ + @EventHandler(priority = EventPriority.HIGH) + fun onJoin(event: PlayerJoinEvent) { + val player = event.player + val key = when (FoundingCredit.review(player)) { + FoundingCredit.Change.GRANTED -> "founding-credit.granted" + FoundingCredit.Change.FORFEITED -> "founding-credit.forfeited" + else -> return + } + // Later than the join itself, which is otherwise lost among the server's welcome messages. + plugin.server.scheduler.runTaskLater(plugin, Runnable { tell(player, key) }, MESSAGE_DELAY_TICKS) + } + + @EventHandler + fun onQuit(event: PlayerQuitEvent) = FoundingCredit.forget(event.player) + + /** Last, so the credit covers whatever is left after other plugins have changed the price. */ + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + fun onPreNewTown(event: PreNewTownEvent) { + val player = event.player + val covered = FoundingCredit.cover(player, event.townName, event.price) + if (covered <= 0.0) return + + event.price -= covered + player.sendPrefixed(player.tr("founding-credit.applied", "amount" to FoundingCredit.display(covered))) + } + + /** A resident added while offline is caught by [onJoin] instead. */ + @EventHandler(priority = EventPriority.MONITOR) + fun onJoinTown(event: TownAddResidentEvent) { + val player = event.resident.player ?: return + if (FoundingCredit.settle(player, event.town) == FoundingCredit.Change.FORFEITED) { + tell(player, "founding-credit.forfeited") + } + } + + private fun tell(player: Player, key: String) { + if (!player.isOnline) return + player.sendPrefixed(player.tr(key, "amount" to FoundingCredit.display())) + } + + private companion object { + const val MESSAGE_DELAY_TICKS = 40L + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/menu/MenuItem.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/menu/MenuItem.kt new file mode 100644 index 0000000..5e47ce2 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/menu/MenuItem.kt @@ -0,0 +1,163 @@ +package net.trilleo.mc.plugins.tritown.menu + +import net.trilleo.mc.plugins.tritown.Main +import net.trilleo.mc.plugins.tritown.config.MainMenuSettings +import net.trilleo.mc.plugins.tritown.news.NewsReadState +import net.trilleo.mc.plugins.tritown.registration.PluginItem +import net.trilleo.mc.plugins.tritown.utils.LoreUtil +import net.trilleo.mc.plugins.tritown.utils.itemStack +import net.trilleo.mc.plugins.tritown.utils.sendPrefixed +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Bukkit +import org.bukkit.entity.Player +import org.bukkit.inventory.Inventory +import org.bukkit.inventory.ItemFlag +import org.bukkit.inventory.ItemStack +import org.bukkit.inventory.PlayerInventory +import org.bukkit.persistence.PersistentDataType + +/** + * The item in the last hotbar slot that opens the main menu. + * + * Everything about it rests on one invariant: **while a player is online and + * the item is enabled, exactly one copy exists, in slot [SLOT] of their own + * inventory — and none exists anywhere else, ever.** [reconcile] is the only + * code that creates a copy, and it restores the invariant from whatever state + * it finds: strays anywhere in the inventory, on the cursor or in an open + * container are deleted, and the slot is refilled. + * + * [net.trilleo.mc.plugins.tritown.listeners.menu.MenuItemListener] refuses + * every action that would move a copy, but it does not have to be perfect. + * Whatever gets past it — a creative client writing its own slots, a plugin + * calling `setItem`, a drop the server hands back — is undone by the next + * [reconcile], which the listener asks for after anything suspicious and + * [net.trilleo.mc.plugins.tritown.tasks.menu.MenuItemTask] runs every second + * regardless. A duplicate can therefore never outlive the second it was made + * in, and cannot leave the player during it: it is not tradeable, droppable, + * storable or craftable. + * + * The item is taken off a player as they quit and off everyone when TriTown + * stops, so it is never written into a save and never outlives the plugin. + */ +object MenuItem { + + /** The last slot of the hotbar. */ + const val SLOT = 8 + + /** The [PluginItem.ITEM_ID_KEY] value marking a stack as the menu item. */ + private const val ID = "main-menu" + + /** Whether players should be carrying the item. */ + val isEnabled: Boolean + get() = MainMenuSettings.isLoaded && MainMenuSettings.snapshot.itemEnabled + + /** Whether [stack] is a copy of the menu item. Read without cloning its meta, since this runs on every click. */ + fun isMenuItem(stack: ItemStack?): Boolean = + stack != null && !stack.isEmpty && + stack.persistentDataContainer.get(PluginItem.ITEM_ID_KEY, PersistentDataType.STRING) == ID + + /** + * The item as [player] should be carrying it, named in their language. + * + * It never stacks, so two copies can never become one stack of two that + * looks like a single legitimate item. + * + * Its lore counts the news the player has not read. [reconcile] compares + * against a fresh copy every second, so the count follows along without + * anything else having to hand the item out again. + */ + fun create(player: Player): ItemStack = itemStack(MainMenuSettings.snapshot.itemMaterial) { + val unread = NewsReadState.unreadCount(player) + val lore = player.tr("menu-item.lore") + + if (unread > 0) "" + player.tr("menu-item.unread", "amount" to unread) else "" + + name(player.tr("menu-item.name")) + flag(ItemFlag.HIDE_ATTRIBUTES) + pdc(PluginItem.ITEM_ID_KEY, PersistentDataType.STRING, ID) + meta { + lore(LoreUtil.wrapLore(lore)) + setMaxStackSize(1) + setEnchantmentGlintOverride(true) + } + } + + /** + * Restores the invariant for [player]. + * + * Cheap when nothing is wrong: one pass over the inventory and a comparison + * with a freshly built copy, which also catches a stale one — a language + * the player has since switched, or a material changed by a reload. + */ + fun reconcile(player: Player) { + if (!player.isOnline || player.isDead) return + + val wanted = if (isEnabled) create(player) else null + removeCopies(player, keepSlot = wanted != null) + if (wanted == null) return + + val inventory = player.inventory + val held = inventory.getItem(SLOT) + if (held != null && held.amount == 1 && held.isSimilar(wanted)) return + + // Copied before the slot is overwritten: the stack read out of it may be a live view of that slot. + val displaced = held?.takeIf { !it.isEmpty && !isMenuItem(it) }?.clone() + inventory.setItem(SLOT, wanted) + displaced?.let { relocate(player, it) } + } + + /** [reconcile] on the next tick, once whatever the server is in the middle of has finished moving items. */ + fun reconcileLater(player: Player) { + Bukkit.getScheduler().runTask(Main.instance, Runnable { reconcile(player) }) + } + + /** [reconcile] for everyone online, after a reload may have changed what the item should be. */ + fun reconcileAll() { + Bukkit.getOnlinePlayers().forEach(::reconcile) + } + + /** Takes every copy off [player], so none is saved with their inventory. */ + fun strip(player: Player) = removeCopies(player, keepSlot = false) + + /** [strip] for everyone online, as TriTown stops. */ + fun stripAll() { + Bukkit.getOnlinePlayers().forEach(::strip) + } + + /** + * Deletes every copy inside [inventory]. + * + * Another player's inventory is left alone, because the copy in its last + * slot is the one that player is meant to have — an administrator looking + * into it must not take it away. + */ + fun purge(inventory: Inventory) { + if (inventory is PlayerInventory) return + for (slot in 0 until inventory.size) { + if (isMenuItem(inventory.getItem(slot))) inventory.setItem(slot, null) + } + } + + /** Deletes every copy [player] can reach, other than the one in [SLOT] when [keepSlot] is set. */ + private fun removeCopies(player: Player, keepSlot: Boolean) { + val inventory = player.inventory + for (slot in 0 until inventory.size) { + if (slot == SLOT && keepSlot) continue + if (isMenuItem(inventory.getItem(slot))) inventory.setItem(slot, null) + } + if (isMenuItem(player.itemOnCursor)) player.setItemOnCursor(null) + purge(player.openInventory.topInventory) + } + + /** + * Finds room for what was in the slot before the menu item took it. + * + * The menu item goes in first, so the slot it now fills cannot be handed + * straight back; whatever does not fit is dropped at the player's feet + * rather than deleted. + */ + private fun relocate(player: Player, displaced: ItemStack) { + val leftover = player.inventory.addItem(displaced).values + leftover.forEach { player.world.dropItemNaturally(player.location, it) } + player.sendPrefixed(player.tr(if (leftover.isEmpty()) "menu-item.relocated" else "menu-item.dropped")) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/news/NewsManager.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/news/NewsManager.kt new file mode 100644 index 0000000..43508b3 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/news/NewsManager.kt @@ -0,0 +1,112 @@ +package net.trilleo.mc.plugins.tritown.news + +import net.trilleo.mc.plugins.tritown.config.NewsSettings +import net.trilleo.mc.plugins.tritown.news.storage.NewsStorage +import net.trilleo.mc.plugins.tritown.news.storage.NewsStorageException +import org.bukkit.entity.Player +import java.util.concurrent.ConcurrentHashMap +import java.util.logging.Logger + +/** + * Every news post, drafts included, and the only thing that reads or writes one. + * + * Every change is a change to what a post says, which an administrator typed + * and would have to type again, so each one is written straight away rather + * than flushed later. Posts change a few times a week; the write is cheap. + */ +object NewsManager { + + private val posts = ConcurrentHashMap() + + @Volatile + private var store: NewsStorage? = null + private var logger: Logger? = null + + /** Whether the posts loaded. When they did not, the feature stays off rather than risk writing over them. */ + @Volatile + var isReady: Boolean = false + private set + + /** Whether players can read the news right now. */ + val isAvailable: Boolean + get() = isReady && NewsSettings.isLoaded && NewsSettings.snapshot.enabled + + fun start(store: NewsStorage, logger: Logger) { + this.store = store + this.logger = logger + posts.clear() + try { + store.loadAll().forEach { posts[it.id] = it } + isReady = true + } catch (e: NewsStorageException) { + logger.severe("The news could not be loaded, so it is switched off until the file is fixed: ${e.message}") + isReady = false + } + } + + fun get(id: String): NewsPost? = posts[id] + + /** Published posts as players see them: pinned ones first, then the newest. */ + fun published(): List = posts.values + .filter { it.isPublished } + .sortedWith(compareByDescending { it.pinned }.thenByDescending { it.publishedAt ?: 0L }) + + /** Drafts, newest first, then everything published — the order an editor wants them in. */ + fun forEditors(): List = + posts.values.filter { !it.isPublished }.sortedByDescending { it.createdAt } + published() + + fun create(author: Player, title: String): NewsPost { + val post = NewsPost( + id = NewsIds.next(posts::containsKey), + title = LocalizedText(title), + createdAt = System.currentTimeMillis(), + authorUuid = author.uniqueId.toString(), + authorName = author.name, + ) + posts[post.id] = post + save() + return post + } + + fun delete(post: NewsPost) { + posts.remove(post.id) + save() + } + + /** + * Makes [post] visible to everyone, as new: it is dated now, so it is + * unread for every player again even if it had been published before. + */ + fun publish(post: NewsPost, announce: Boolean, publisher: Player) { + post.status = PostStatus.PUBLISHED + post.publishedAt = System.currentTimeMillis() + post.editedAt = null + save() + + // The publisher has just written it, so it is not news to them. + NewsReadState.markRead(publisher, post) + if (announce) NewsNotifier.announce(post) + } + + fun unpublish(post: NewsPost) { + post.status = PostStatus.DRAFT + save() + } + + /** + * Records a change to [post] and writes it. + * + * A published post is dated as edited, so readers can tell it changed + * after they read it, but it is not made unread again: correcting a typo + * should not call everyone back. + */ + fun changed(post: NewsPost) { + if (post.isPublished) post.editedAt = System.currentTimeMillis() + save() + } + + fun save() { + if (!isReady) return + store?.saveAll(posts.values.sortedBy { it.createdAt }) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/news/NewsNotifier.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/news/NewsNotifier.kt new file mode 100644 index 0000000..fa71d0e --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/news/NewsNotifier.kt @@ -0,0 +1,68 @@ +package net.trilleo.mc.plugins.tritown.news + +import net.kyori.adventure.sound.Sound +import net.kyori.adventure.title.Title +import net.trilleo.mc.plugins.tritown.config.NewsSettings +import net.trilleo.mc.plugins.tritown.utils.ComponentUtil +import net.trilleo.mc.plugins.tritown.utils.sendPrefixed +import net.trilleo.mc.plugins.tritown.utils.tr +import org.bukkit.Bukkit +import org.bukkit.entity.Player + +/** + * Tells players there is something to read: a summary as they join, and an + * announcement to everyone online the moment a post is published. + * + * Every line links to the post it names, so reading it is one click away. + */ +object NewsNotifier { + + /** Lists what [player] has not read yet, if anything. */ + fun joinSummary(player: Player) { + if (!player.isOnline || !NewsManager.isAvailable) return + val unread = NewsReadState.unread(player) + if (unread.isEmpty()) return + + val preview = NewsSettings.snapshot.joinPreview + player.sendPrefixed(player.tr("news.join.header", "amount" to unread.size)) + unread.take(preview).forEach { post -> + player.sendMessage( + ComponentUtil.parse( + player.tr( + "news.join.entry", + "id" to post.id, + "title" to title(player, post) + ) + ) + ) + } + if (unread.size > preview) { + player.sendMessage(ComponentUtil.parse(player.tr("news.join.more", "amount" to unread.size - preview))) + } + player.sendMessage(ComponentUtil.parse(player.tr("news.join.open"))) + } + + /** Puts [post] in front of everyone online, in each player's own language. */ + fun announce(post: NewsPost) { + val settings = NewsSettings.snapshot + val sound = settings.announceSound?.let { Sound.sound(it, Sound.Source.MASTER, 1f, 1f) } + + Bukkit.getOnlinePlayers().forEach { player -> + val title = title(player, post) + if (settings.announceTitle) { + player.showTitle( + Title.title( + ComponentUtil.parse(player.tr("news.broadcast.title")), + ComponentUtil.parse(title), + ) + ) + } + if (settings.announceChat) { + player.sendPrefixed(player.tr("news.broadcast.chat", "id" to post.id, "title" to title)) + } + sound?.let(player::playSound) + } + } + + private fun title(player: Player, post: NewsPost): String = post.title.forViewer(player) +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/news/NewsPost.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/news/NewsPost.kt new file mode 100644 index 0000000..f7922de --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/news/NewsPost.kt @@ -0,0 +1,164 @@ +package net.trilleo.mc.plugins.tritown.news + +import net.trilleo.mc.plugins.tritown.utils.Lang +import org.bukkit.command.CommandSender +import java.security.SecureRandom + +/** + * One update note: a titled post made of categories, each holding short entries. + * + * The classes here are what the news file stores, field for field, so none of + * them names a Bukkit type — an icon is a material's name, read back through + * [net.trilleo.mc.plugins.tritown.guis.news.NewsRender.material]. Every field + * has a default, which is what lets Gson fill in whatever an older file lacks. + * + * Everything written here is an administrator's MiniMessage, not a translation + * key; [LocalizedText] carries the other languages. + */ +class NewsPost( + var id: String = "", + var title: LocalizedText = LocalizedText(), + var summary: LocalizedText? = null, + /** A version or season the post belongs to, such as `v1.3`. One language only: it is a name, not a sentence. */ + var label: String? = null, + var icon: String = DEFAULT_ICON, + var categories: MutableList = mutableListOf(), + var status: PostStatus = PostStatus.DRAFT, + var pinned: Boolean = false, + var createdAt: Long = 0L, + var publishedAt: Long? = null, + var editedAt: Long? = null, + var authorUuid: String? = null, + var authorName: String? = null, +) { + + val isPublished: Boolean + get() = status == PostStatus.PUBLISHED + + /** How many entries the post holds across every category. */ + val entryCount: Int + get() = categories.sumOf { it.entries.size } + + fun category(id: String): NewsCategory? = categories.firstOrNull { it.id == id } + + /** + * Puts back what a hand-edited or damaged file left null. + * + * Gson writes a JSON `null`, or an enum name this build does not know, into + * a non-null Kotlin field without complaint, so the file is checked here + * once rather than at every place that reads it. + */ + @Suppress("SENSELESS_COMPARISON", "USELESS_ELVIS") + fun repair() { + title = title ?: LocalizedText() + title.repair() + summary?.repair() + icon = icon ?: DEFAULT_ICON + categories = (categories ?: mutableListOf()).filterNotNull().toMutableList() + status = status ?: PostStatus.DRAFT + categories.forEach { it.repair() } + } + + companion object { + const val DEFAULT_ICON = "WRITABLE_BOOK" + } +} + +class NewsCategory( + var id: String = "", + var name: LocalizedText = LocalizedText(), + var icon: String = DEFAULT_ICON, + var entries: MutableList = mutableListOf(), +) { + + fun entry(id: String): NewsEntry? = entries.firstOrNull { it.id == id } + + @Suppress("SENSELESS_COMPARISON", "USELESS_ELVIS") + internal fun repair() { + name = name ?: LocalizedText() + name.repair() + icon = icon ?: DEFAULT_ICON + entries = (entries ?: mutableListOf()).filterNotNull().toMutableList() + entries.forEach { it.repair() } + } + + companion object { + const val DEFAULT_ICON = "BOOK" + } +} + +/** One change, in a sentence or two. */ +class NewsEntry( + var id: String = "", + var tag: EntryTag = EntryTag.NEW, + var text: LocalizedText = LocalizedText(), +) { + + @Suppress("SENSELESS_COMPARISON", "USELESS_ELVIS") + internal fun repair() { + tag = tag ?: EntryTag.NOTE + text = text ?: LocalizedText() + text.repair() + } +} + +/** What kind of change an entry describes. The label and colour of each live in the language files. */ +enum class EntryTag { NEW, CHANGED, FIXED, REMOVED, NOTE } + +enum class PostStatus { DRAFT, PUBLISHED } + +/** + * Text an administrator wrote, with an optional version for each language. + * + * [main] is what everyone sees unless their language has a translation of its + * own, so a post written in one language still reads for every player. + * Translations are keyed by language id, such as `zh_CN`, and matched without + * regard to case, the way [net.trilleo.mc.plugins.tritown.utils.Lang] matches + * a language file. + */ +class LocalizedText( + var main: String = "", + var translations: MutableMap = mutableMapOf(), +) { + + /** The text for [languageId], falling back to [main]. */ + fun get(languageId: String?): String = languageId?.let(::translation) ?: main + + /** The text in the language [viewer] reads. */ + fun forViewer(viewer: CommandSender?): String = get(Lang.idFor(viewer)) + + /** The translation for [languageId] alone, or `null` when there is none. */ + fun translation(languageId: String): String? = + translations.entries.firstOrNull { it.key.equals(languageId, ignoreCase = true) }?.value + + fun translate(languageId: String, text: String) { + clear(languageId) + translations[languageId] = text + } + + fun clear(languageId: String) { + translations.keys.removeIf { it.equals(languageId, ignoreCase = true) } + } + + @Suppress("SENSELESS_COMPARISON", "USELESS_ELVIS") + internal fun repair() { + main = main ?: "" + translations = (translations ?: mutableMapOf()).filterValues { it != null }.toMutableMap() + } +} + +/** Short ids for posts, categories and entries: easy to type into `/tritown news open`, and never reused by chance. */ +object NewsIds { + + private const val LENGTH = 6 + private const val ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789" + private val random = SecureRandom() + + /** A new id that [taken] does not already hold. */ + fun next(taken: (String) -> Boolean = { false }): String { + while (true) { + val id = String(CharArray(LENGTH) { ALPHABET[random.nextInt(ALPHABET.length)] }) + if (!taken(id)) return id + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/news/NewsReadState.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/news/NewsReadState.kt new file mode 100644 index 0000000..2548dac --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/news/NewsReadState.kt @@ -0,0 +1,82 @@ +package net.trilleo.mc.plugins.tritown.news + +import com.google.gson.JsonArray +import com.google.gson.JsonPrimitive +import net.trilleo.mc.plugins.tritown.data.PlayerDataManager +import org.bukkit.entity.Player + +/** + * Which posts each player has read, kept in their [net.trilleo.mc.plugins.tritown.data.PlayerData]. + * + * A player also carries the moment they first met the news. Posts published + * before it do not count as unread, so someone joining a server with a year of + * update notes is not greeted with all of them — only the newest, which is + * always counted until it is read, so a new player still hears about the + * latest changes. + * + * The menu item reads [unreadCount] every second for every player, so nothing + * here may do more than walk the published posts once. + */ +object NewsReadState { + + private const val READ_KEY = "news-read" + private const val SINCE_KEY = "news-since" + + /** The unread posts for [player], in the order the news lists them. */ + fun unread(player: Player): List { + if (!NewsManager.isAvailable) return emptyList() + val data = PlayerDataManager.get(player) + val since = data.getString(SINCE_KEY).toLongOrNull() ?: 0L + return unreadOf(NewsManager.published(), readIds(player), since) + } + + fun unreadCount(player: Player): Int = unread(player).size + + fun isUnread(player: Player, post: NewsPost): Boolean = unread(player).any { it.id == post.id } + + fun markRead(player: Player, post: NewsPost) { + val ids = readIds(player) + if (post.id in ids) return + store(player, ids + post.id) + } + + fun markAllRead(player: Player) { + store(player, readIds(player) + NewsManager.published().map { it.id }) + } + + /** + * Sets the moment [player] first met the news, and forgets posts that no + * longer exist so the list cannot grow for ever. Called as they join. + */ + fun review(player: Player) { + val data = PlayerDataManager.get(player) + if (!data.has(SINCE_KEY)) data.set(SINCE_KEY, System.currentTimeMillis().toString()) + + val ids = readIds(player) + val kept = ids.filterTo(mutableSetOf()) { NewsManager.get(it) != null } + if (kept.size != ids.size) store(player, kept) + } + + /** + * The posts in [published] that are still unread, given the [read] ids and + * the moment [since] the player first met the news. The newest post counts + * whatever [since] says. Kept apart from [PlayerDataManager] so it can be tested. + */ + internal fun unreadOf(published: List, read: Set, since: Long): List { + val newest = published.maxByOrNull { it.publishedAt ?: 0L } + return published.filter { post -> + post.id !in read && ((post.publishedAt ?: 0L) > since || post === newest) + } + } + + private fun readIds(player: Player): Set = + PlayerDataManager.get(player).getJsonArray(READ_KEY).mapNotNullTo(mutableSetOf()) { + runCatching { it.asString }.getOrNull() + } + + private fun store(player: Player, ids: Set) { + val array = JsonArray() + ids.forEach { array.add(JsonPrimitive(it)) } + PlayerDataManager.get(player).set(READ_KEY, array) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/news/NewsShorthand.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/news/NewsShorthand.kt new file mode 100644 index 0000000..1042e54 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/news/NewsShorthand.kt @@ -0,0 +1,26 @@ +package net.trilleo.mc.plugins.tritown.news + +/** + * Reads the tag off the front of an entry typed in chat, so a whole changelog + * can be written line after line without stopping to pick a tag for each. + * + * `+` is new, `*` changed, `!` fixed, `-` removed and `?` a note. A line + * without one keeps the tag the previous line had. + */ +object NewsShorthand { + + private val prefixes = mapOf( + '+' to EntryTag.NEW, + '*' to EntryTag.CHANGED, + '!' to EntryTag.FIXED, + '-' to EntryTag.REMOVED, + '?' to EntryTag.NOTE, + ) + + /** The tag and text of [line], using [fallback] when it starts with no prefix. */ + fun parse(line: String, fallback: EntryTag): Pair { + val trimmed = line.trim() + val tag = trimmed.firstOrNull()?.let(prefixes::get) ?: return fallback to trimmed + return tag to trimmed.drop(1).trim() + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/news/storage/JsonNewsStorage.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/news/storage/JsonNewsStorage.kt new file mode 100644 index 0000000..5a10de3 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/news/storage/JsonNewsStorage.kt @@ -0,0 +1,95 @@ +package net.trilleo.mc.plugins.tritown.news.storage + +import com.google.gson.GsonBuilder +import com.google.gson.JsonObject +import com.google.gson.JsonParser +import net.trilleo.mc.plugins.tritown.news.NewsPost +import net.trilleo.mc.plugins.tritown.utils.AtomicFile +import java.io.File +import java.util.logging.Logger + +/** + * Keeps every news post in one JSON file, `/news/posts.json`. + * + * Written through [AtomicFile] with the previous copy kept as `.bak`, and read + * back from that backup when the main file will not parse — an empty start + * would be written over the real posts on the next save. A single post that + * will not parse is skipped with a warning. + * + * The file records the layout version it was written in. A newer one is + * refused, because an older build would drop what it did not understand and + * write that loss back. + */ +class JsonNewsStorage(directory: File, private val logger: Logger) : NewsStorage { + + private val root = File(directory, DIRECTORY) + private val newsFile = File(root, NEWS_FILE) + private val backupFile = File(root, "$NEWS_FILE.bak") + private val gson = GsonBuilder().setPrettyPrinting().create() + private val ioLock = Any() + + override fun loadAll(): List = synchronized(ioLock) { + root.mkdirs() + + val document = read(newsFile) ?: run { + if (newsFile.exists()) { + logger.warning("${newsFile.name} could not be read; falling back to the backup") + } + read(backupFile) ?: run { + if (backupFile.exists()) { + throw NewsStorageException("Neither ${newsFile.name} nor its backup could be read") + } + return emptyList() + } + } + + val version = document.get(KEY_VERSION)?.asInt ?: SCHEMA + if (version > SCHEMA) { + throw NewsStorageException( + "${newsFile.name} was written by a newer version of TriTown (schema $version, this build reads " + + "up to $SCHEMA). Update TriTown rather than letting an older build overwrite it." + ) + } + + val array = document.getAsJsonArray(KEY_POSTS) ?: return emptyList() + array.mapNotNull { element -> + runCatching { gson.fromJson(element, NewsPost::class.java).also { it.repair() } } + .getOrNull() + ?.takeIf { it.id.isNotBlank() } + ?: run { + logger.warning("Skipped an unreadable post in ${newsFile.name}") + null + } + } + } + + override fun saveAll(posts: List) = synchronized(ioLock) { + root.mkdirs() + + val document = JsonObject().apply { + addProperty(KEY_VERSION, SCHEMA) + add(KEY_POSTS, gson.toJsonTree(posts)) + } + + try { + AtomicFile.write(newsFile.toPath(), backupFile.toPath(), gson.toJson(document)) + } catch (e: Exception) { + logger.severe("Failed to write ${newsFile.name}: [${e.javaClass.simpleName}] ${e.message}") + } + } + + private fun read(file: File): JsonObject? { + if (!file.exists()) return null + return runCatching { JsonParser.parseString(file.readText()).asJsonObject }.getOrNull() + } + + private companion object { + const val DIRECTORY = "news" + const val NEWS_FILE = "posts.json" + const val KEY_VERSION = "schemaVersion" + const val KEY_POSTS = "posts" + + /** The layout this build writes. */ + const val SCHEMA = 1 + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/news/storage/NewsStorage.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/news/storage/NewsStorage.kt new file mode 100644 index 0000000..833c66a --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/news/storage/NewsStorage.kt @@ -0,0 +1,21 @@ +package net.trilleo.mc.plugins.tritown.news.storage + +import net.trilleo.mc.plugins.tritown.news.NewsPost + +/** Where news posts are kept between restarts. */ +interface NewsStorage { + + /** + * Every stored post, drafts included. + * + * @throws NewsStorageException when the data cannot be read at all, which + * stops the feature rather than letting an empty list overwrite it + */ + fun loadAll(): List + + /** Replaces everything on disk with [posts]. */ + fun saveAll(posts: List) +} + +/** Raised when stored news cannot be read, and must not be silently replaced. */ +class NewsStorageException(message: String) : Exception(message) diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/registration/CommandRegistrar.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/registration/CommandRegistrar.kt index 471decd..0c22aa6 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/registration/CommandRegistrar.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/registration/CommandRegistrar.kt @@ -65,6 +65,40 @@ object CommandRegistrar { .toSortedMap() } + /** + * The registered command called [name], whether it is a sub-command of + * `/tritown` or a command of its own, or `null` when there is none. + */ + fun find(name: String): PluginCommand? = + allCommands.firstOrNull { it.command.name.equals(name, ignoreCase = true) }?.command + + /** Whether [sender] may run the command called [name]; `false` when there is no such command. */ + fun canRun(sender: CommandSender, name: String): Boolean { + val command = find(name) ?: return false + return command.permission?.let(sender::hasPermission) ?: true + } + + /** + * Runs the command called [name] for [sender], as though they had typed it. + * + * For a menu button that does what a command already does. Going through + * the command rather than repeating its logic keeps every check and message + * in one place, and calling it directly rather than dispatching a typed line + * works whatever label it ended up registered under — a main command whose + * name another plugin owns is only reachable as `/tritown:`. + * + * @return `false` when no command has that name + */ + fun run(sender: CommandSender, name: String, vararg args: String): Boolean { + val command = find(name) ?: return false + if (!canRun(sender, name)) { + sender.sendPrefixed(sender.tr("command.no-permission")) + return true + } + command.execute(sender, args) + return true + } + /** * Scans the commands package, instantiates every [PluginCommand] found, * and registers it either as a sub-command of `/tritown` or as a diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/registration/GUIFrame.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/registration/GUIFrame.kt index dad67c1..290a2fd 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/registration/GUIFrame.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/registration/GUIFrame.kt @@ -15,6 +15,9 @@ import org.bukkit.inventory.ItemStack object GUIFrame { private const val ROW_SIZE = 9 + private const val INNER_COLUMNS = 7 + private const val MIDDLE_COLUMN = 4 + private const val MAX_SPACED = 4 /** A single border slot: black glass with no name and no tooltip. */ fun pane(): ItemStack = itemStack(Material.BLACK_STAINED_GLASS_PANE) { @@ -40,6 +43,63 @@ object GUIFrame { } } + /** + * The columns (0 to 8) of [count] buttons spread along a row with a gap + * between each, centred on the middle column. + * + * Four is the most that fit inside the border: one button sits in the + * middle, two either side of it, three at 2, 4 and 6, four at 1, 3, 5 and 7. + */ + fun spacedColumns(count: Int): List { + require(count in 0..MAX_SPACED) { "At most $MAX_SPACED buttons fit spaced along a row, not $count" } + val first = MIDDLE_COLUMN - (count - 1) + return List(count) { first + it * 2 } + } + + /** + * The columns (1 to 7) of [count] items packed side by side inside the + * border, centred on the middle column. + * + * An even count cannot straddle the middle column evenly, so it leaves that + * column empty instead: two items sit at 3 and 5 rather than off to one side + * at 3 and 4, which keeps both halves of the row the same. + */ + fun packedColumns(count: Int): List { + require(count in 0..INNER_COLUMNS) { "At most $INNER_COLUMNS items fit inside a row, not $count" } + val first = MIDDLE_COLUMN - count / 2 + return if (count % 2 == 1) { + List(count) { first + it } + } else { + (first..first + count).filter { it != MIDDLE_COLUMN } + } + } + + /** + * The slots of a [rows]-row framed menu that show [count] items, centred + * both ways. + * + * Rows are filled seven at a time and the last one is [packedColumns], and + * the block of rows they take sits in the middle of the space inside the + * border — so two players in a list read as a pair in the middle of the + * menu rather than as two items lost in its top-left corner. Filling every + * slot gives exactly [contentSlots]. + */ + fun centeredSlots(rows: Int, count: Int): List { + val innerRows = (rows - 2).coerceAtLeast(0) + require(count in 0..innerRows * INNER_COLUMNS) { "$count items do not fit inside a $rows-row menu" } + if (count == 0) return emptyList() + + val used = (count + INNER_COLUMNS - 1) / INNER_COLUMNS + val firstRow = 1 + (innerRows - used) / 2 + + return buildList { + for (index in 0 until used) { + val inRow = if (index == used - 1) count - INNER_COLUMNS * index else INNER_COLUMNS + packedColumns(inRow).forEach { add((firstRow + index) * ROW_SIZE + it) } + } + } + } + /** * Fills every slot of [inventory] that is not in [contentSlots] with the border. * diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/registration/GUIManager.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/registration/GUIManager.kt index 50be7fc..5308e1b 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/registration/GUIManager.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/registration/GUIManager.kt @@ -127,7 +127,15 @@ object GUIManager : Listener { */ fun getRegisteredIds(): Set = guis.keys.toSet() - @EventHandler + /** + * Routes a click to the GUI it landed in. + * + * A click something else has already cancelled is never delivered. Menus + * such as the trade table and the shop editor take whatever was clicked in + * the player's own inventory, so a click that the menu item's guard refused + * must not reach them, or the item would be escrowed or put on sale anyway. + */ + @EventHandler(ignoreCancelled = true) fun onInventoryClick(event: InventoryClickEvent) { val player = event.whoClicked as? Player ?: return val (gui, inventory) = openGUIs[player] ?: return @@ -135,7 +143,7 @@ object GUIManager : Listener { gui.onClick(event) } - @EventHandler + @EventHandler(ignoreCancelled = true) fun onInventoryDrag(event: InventoryDragEvent) { val player = event.whoClicked as? Player ?: return val (gui, inventory) = openGUIs[player] ?: return diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/registration/PagedPluginGUI.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/registration/PagedPluginGUI.kt index 62513ff..59226a4 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/registration/PagedPluginGUI.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/registration/PagedPluginGUI.kt @@ -27,7 +27,8 @@ import java.util.* * [layout] decides what the rest of it does. [PagedLayout.FULL] fills every slot * above that row with content — a 6-row GUI gives 45 content slots per page. * [PagedLayout.FRAMED] insets the content by one slot on every side, giving 28 - * instead and a border around them. + * instead and a border around them. [PagedLayout.CENTERED] frames it the same + * way and centres a page that is not full. * * The class must have either: * - A no-arg constructor, **or** @@ -99,6 +100,15 @@ abstract class PagedPluginGUI( /** Tracks the current page for each player viewing this GUI. */ private val playerPages = mutableMapOf() + /** + * Which position on the page each drawn slot shows, per viewer. + * + * Remembered as drawn rather than worked out again from the layout, because + * a centred page puts its items in different slots depending on how many + * of them there are. + */ + private val shownPositions = mutableMapOf>() + /** * Returns all items that should be distributed across pages for the * given player. The list may be of any size; items are automatically @@ -134,7 +144,7 @@ abstract class PagedPluginGUI( * button or a button in the navigation row). Override to add custom click * handling. * - * Use [contentIndex] to turn the clicked slot into a position in the list + * Use [contentIndex] to turn the click into a position in the list * returned by [getItems]; the raw slot is an inventory slot and does not * match that list once a border is in the way. * @@ -166,17 +176,27 @@ abstract class PagedPluginGUI( */ open fun onNavClick(event: InventoryClickEvent, offset: Int) {} + /** + * Items to place in the top row of a framed menu, keyed by their offset in + * that row (0 to 8), over the border. + * + * Something that belongs to the whole menu rather than to one page — what + * a list is a list *of* — sits here, so it stays put while the pages turn. + * Ignored in [PagedLayout.FULL], where the top row is content. + * + * @param player the player the GUI is being drawn for + */ + open fun topButtons(player: Player): Map = emptyMap() + /** The inventory slots that hold content, in reading order. */ private val contentSlots: List by lazy { when (layout) { PagedLayout.FULL -> (0 until (rows - 1) * ROW_SIZE).toList() - PagedLayout.FRAMED -> GUIFrame.contentSlots(rows) + PagedLayout.FRAMED, PagedLayout.CENTERED -> GUIFrame.contentSlots(rows) } } - private val contentPositions: Map by lazy { - contentSlots.withIndex().associate { (position, slot) -> slot to position } - } + private val contentSlotSet: Set by lazy { contentSlots.toSet() } /** How many items fit on one page. */ protected val pageSize: Int @@ -187,11 +207,18 @@ abstract class PagedPluginGUI( get() = (rows - 1) * ROW_SIZE /** - * The position in [getItems]'s list that [rawSlot] shows on [page], or - * `null` when that slot holds no content. + * The position in [getItems]'s list that the slot [event] clicked shows on + * [page], or `null` when that slot is not part of the content area. + * + * An empty slot inside the content area still has a position, just one past + * the end of the list — except on a [PagedLayout.CENTERED] page, where only + * the slots holding an item are content at all. + * + * In [PagedGUIMode.SET] this is `page * pageSize` plus the position the + * item was given in [getSetItems]. */ - protected fun contentIndex(page: Int, rawSlot: Int): Int? = - contentPositions[rawSlot]?.let { position -> page * pageSize + position } + protected fun contentIndex(event: InventoryClickEvent, page: Int): Int? = + shownPositions[event.whoClicked.uniqueId]?.get(event.rawSlot)?.let { position -> page * pageSize + position } /** * Redraws the page [player] is looking at, into the inventory they have open. @@ -244,13 +271,14 @@ abstract class PagedPluginGUI( navOffset == PAGE_INDICATOR_OFFSET -> return navOffset in 0 until ROW_SIZE -> onNavClick(event, navOffset) - slot in contentPositions -> onContentClick(event, page) + slot in contentSlotSet -> onContentClick(event, page) } } override fun onClose(event: InventoryCloseEvent) { val player = event.player as? Player ?: return playerPages.remove(player.uniqueId) + shownPositions.remove(player.uniqueId) } // ----- Internal helpers --------------------------------------------------- @@ -282,18 +310,23 @@ abstract class PagedPluginGUI( inventory.clear() fillInventory(this, inventory) - if (layout == PagedLayout.FRAMED) GUIFrame.draw(inventory, contentSlots) + if (layout != PagedLayout.FULL) { + GUIFrame.draw(inventory, contentSlots) + for ((offset, button) in topButtons(player)) { + if (offset in 0 until ROW_SIZE) inventory.setItem(offset, button) + } + } val totalPages = totalPages(player) + var slots = contentSlots when (mode) { PagedGUIMode.LIST -> { val items = getItems(player) val start = page * pageSize - val end = minOf(start + pageSize, items.size) - for (index in start until end) { - inventory.setItem(contentSlots[index - start], items[index]) - } + val onPage = items.subList(minOf(start, items.size), minOf(start + pageSize, items.size)) + if (layout == PagedLayout.CENTERED) slots = GUIFrame.centeredSlots(rows, onPage.size) + onPage.forEachIndexed { position, item -> inventory.setItem(slots[position], item) } } PagedGUIMode.SET -> { @@ -303,6 +336,7 @@ abstract class PagedPluginGUI( } } } + shownPositions[player.uniqueId] = slots.withIndex().associate { (position, slot) -> slot to position } renderNavRow(player, inventory, page, totalPages) } @@ -311,7 +345,7 @@ abstract class PagedPluginGUI( private fun renderNavRow(player: Player, inventory: Inventory, page: Int, totalPages: Int) { // A framed menu carries its border all the way round, so the row below the // content matches the rest of it rather than changing colour. - val filler = if (layout == PagedLayout.FRAMED) { + val filler = if (layout != PagedLayout.FULL) { GUIFrame.pane() } else { itemStack(Material.GRAY_STAINED_GLASS_PANE) { diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/shops/storage/JsonShopStorage.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/shops/storage/JsonShopStorage.kt index df94670..51fb008 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/shops/storage/JsonShopStorage.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/shops/storage/JsonShopStorage.kt @@ -3,8 +3,8 @@ package net.trilleo.mc.plugins.tritown.shops.storage import com.google.gson.GsonBuilder import com.google.gson.JsonObject import com.google.gson.JsonParser +import net.trilleo.mc.plugins.tritown.utils.AtomicFile import java.io.File -import java.nio.file.* import java.util.logging.Logger /** @@ -73,7 +73,7 @@ class JsonShopStorage(directory: File, private val logger: Logger) : ShopStorage } try { - writeAtomically(shopsFile.toPath(), gson.toJson(document)) + AtomicFile.write(shopsFile.toPath(), backupFile.toPath(), gson.toJson(document)) } catch (e: Exception) { logger.severe("Failed to write ${shopsFile.name}: [${e.javaClass.simpleName}] ${e.message}") } @@ -84,27 +84,6 @@ class JsonShopStorage(directory: File, private val logger: Logger) : ShopStorage return runCatching { JsonParser.parseString(file.readText()).asJsonObject }.getOrNull() } - private fun writeAtomically(target: Path, content: String) { - val temporary = target.resolveSibling("${target.fileName}.tmp") - Files.writeString( - temporary, - content, - StandardOpenOption.CREATE, - StandardOpenOption.TRUNCATE_EXISTING, - StandardOpenOption.WRITE, - ) - - if (Files.exists(target)) { - Files.move(target, backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING) - } - - try { - Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) - } catch (_: AtomicMoveNotSupportedException) { - Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING) - } - } - private companion object { const val DIRECTORY = "shops" const val SHOPS_FILE = "shops.json" diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/tasks/menu/MenuItemTask.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/tasks/menu/MenuItemTask.kt new file mode 100644 index 0000000..187de0a --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/tasks/menu/MenuItemTask.kt @@ -0,0 +1,21 @@ +package net.trilleo.mc.plugins.tritown.tasks.menu + +import net.trilleo.mc.plugins.tritown.menu.MenuItem +import net.trilleo.mc.plugins.tritown.registration.PluginTask + +/** + * Puts every player's [MenuItem] right once a second. + * + * The listener refuses what it can see, and this catches what it cannot: a + * `/clear`, another plugin rewriting a slot, a creative client, or a pick-block + * that swapped the item into the inventory. Nothing a copy made in between can + * do takes longer than this to undo. + */ +class MenuItemTask : PluginTask(delay = PERIOD, period = PERIOD) { + + override fun run() = MenuItem.reconcileAll() + + private companion object { + const val PERIOD = 20L + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/towns/FoundingCredit.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/towns/FoundingCredit.kt new file mode 100644 index 0000000..8d07269 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/towns/FoundingCredit.kt @@ -0,0 +1,120 @@ +package net.trilleo.mc.plugins.tritown.towns + +import com.palmergames.bukkit.towny.TownyAPI +import com.palmergames.bukkit.towny.`object`.Town +import net.trilleo.mc.plugins.tritown.config.TownSettings +import net.trilleo.mc.plugins.tritown.data.PlayerDataManager +import net.trilleo.mc.plugins.tritown.utils.ComponentUtil +import net.trilleo.mc.plugins.tritown.utils.EconomyUtil +import org.bukkit.entity.Player +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +/** + * Money set aside for a player's first town, which nothing else can spend. + * + * The credit is never paid out. It is taken off the price in Towny's + * `PreNewTownEvent`, so Towny still runs its own checks, confirmation and + * charge, and only charges what the credit does not cover. Because no money + * moves, the economy statistics have nothing to record. Founding just drains + * less. + * + * A player is offered it once. Whether they hold it is kept in their + * [net.trilleo.mc.plugins.tritown.data.PlayerData], and the amount is read from + * the config each time, so an owner who changes it changes it for everyone + * still holding one. + */ +object FoundingCredit { + + /** What a check on a player changed. */ + enum class Change { GRANTED, USED, FORFEITED } + + private const val KEY = "founding-credit" + private const val HELD = "held" + private const val USED = "used" + private const val FORFEITED = "forfeited" + private const val INELIGIBLE = "ineligible" + + /** The town each player was last quoted a reduced price for. */ + private val founding = ConcurrentHashMap() + + /** The credit's value, or 0 when it is switched off. */ + val amount: Double get() = TownSettings.snapshot.foundingCredit + + /** Whether [player] has a credit to spend. */ + fun holds(player: Player): Boolean = amount > 0.0 && state(player) == HELD + + /** + * Grants the credit to a player who has never been offered it and has no + * town, and takes it from one who joined a town while offline. + */ + fun review(player: Player): Change? { + if (amount <= 0.0) return null + val hasTown = TownyAPI.getInstance().getResident(player)?.hasTown() == true + + return when (state(player)) { + null -> if (hasTown) { + setState(player, INELIGIBLE) + null + } else { + setState(player, HELD) + Change.GRANTED + } + + HELD -> if (hasTown) { + setState(player, FORFEITED) + Change.FORFEITED + } else { + null + } + + else -> null + } + } + + /** + * How much of [price] the credit covers when [player] founds [townName]. + * + * Nothing is spent here: Towny has not asked for confirmation yet, and the + * player may never give it. The town is remembered so [settle] can tell + * this founding apart from joining someone else's town. + */ + fun cover(player: Player, townName: String, price: Double): Double { + if (price <= 0.0 || !holds(player)) return 0.0 + founding[player.uniqueId] = townName + return minOf(amount, price) + } + + /** + * Settles the credit once [player] has become a member of [town]. + * + * Towny adds the founder as the first resident part-way through creating + * the town, so this one event sees both outcomes. A town that is new and + * has only them is the one the credit was quoted for. Any other town gives + * the credit up. + */ + fun settle(player: Player, town: Town): Change? { + val quoted = founding.remove(player.uniqueId) + if (!holds(player)) return null + + val founded = quoted.equals(town.name, ignoreCase = true) && town.numResidents == 1 + setState(player, if (founded) USED else FORFEITED) + return if (founded) Change.USED else Change.FORFEITED + } + + /** Drops the quote held for [player], who is leaving. */ + fun forget(player: Player) { + founding.remove(player.uniqueId) + } + + /** [amount] of money as text that is safe inside MiniMessage. */ + fun display(amount: Double = this.amount): String = + if (EconomyUtil.isAvailable) ComponentUtil.escape(EconomyUtil.format(amount)) else amount.toString() + + private fun state(player: Player): String? = + PlayerDataManager.get(player).let { if (it.has(KEY)) it.getString(KEY) else null } + + private fun setState(player: Player, state: String) { + PlayerDataManager.get(player).set(KEY, state) + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/utils/AtomicFile.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/utils/AtomicFile.kt new file mode 100644 index 0000000..148a955 --- /dev/null +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/utils/AtomicFile.kt @@ -0,0 +1,36 @@ +package net.trilleo.mc.plugins.tritown.utils + +import java.nio.file.* + +/** + * Replaces a file without ever leaving a truncated copy behind. + * + * The content goes to a temporary file first, the previous file is kept as + * [backup], and only then is the new one moved into place — so a crash + * mid-write leaves either the old file or the new one, and the backup is there + * for a reader that finds the main file unreadable. + */ +object AtomicFile { + + /** Writes [content] to [target], keeping what was there before as [backup]. */ + fun write(target: Path, backup: Path, content: String) { + val temporary = target.resolveSibling("${target.fileName}.tmp") + Files.writeString( + temporary, + content, + StandardOpenOption.CREATE, + StandardOpenOption.TRUNCATE_EXISTING, + StandardOpenOption.WRITE, + ) + + if (Files.exists(target)) { + Files.move(target, backup, StandardCopyOption.REPLACE_EXISTING) + } + + try { + Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) + } catch (_: AtomicMoveNotSupportedException) { + Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING) + } + } +} diff --git a/src/main/kotlin/net/trilleo/mc/plugins/tritown/utils/Lang.kt b/src/main/kotlin/net/trilleo/mc/plugins/tritown/utils/Lang.kt index 302a15e..bb8ee5a 100644 --- a/src/main/kotlin/net/trilleo/mc/plugins/tritown/utils/Lang.kt +++ b/src/main/kotlin/net/trilleo/mc/plugins/tritown/utils/Lang.kt @@ -75,6 +75,12 @@ object Lang { /** The translation of [key] for [sender], or `null` when no language defines it. */ fun find(sender: CommandSender?, key: String): String? = language(sender).values[key] + /** + * The id of the language [sender] reads, such as `zh_CN` — the same one [tr] + * picks, so text kept outside the language files can follow it. + */ + fun idFor(sender: CommandSender?): String = language(sender).id + private fun language(sender: CommandSender?): Language { val id = if (configured.equals(AUTO, ignoreCase = true)) (sender as? Player)?.locale()?.toString() else configured diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 04c1e75..270775c 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -8,6 +8,22 @@ message-prefix: "[TriTown # Translations live in plugins/TriTown/lang/ and can be edited or extended with new .yml files. language: auto +# ── Main Menu ─────────────────────────────────────────────────────────────── +# The menu players reach everything TriTown offers from: their balance and town, +# the global shop, trading and paying other players, the leaderboard, the +# sidebar switch and a shortcut into TownyMenu. /tritown menu opens it too. +main-menu: + item: + # Keep the menu item in the last slot of every player's hotbar. Right-clicking + # it opens the menu. It cannot be moved, dropped, stored, crafted with or + # handed to anything, and one lost any other way is put straight back. Whatever + # was in that slot is moved into the player's inventory. When false, every + # copy is taken back. + enabled: true + # What the item is. Any item works; since it can never be crafted with, even a + # nether star cannot be spent on a beacon. + material: NETHER_STAR + # ── Economy ───────────────────────────────────────────────────────────────── economy: # Turn the economy off entirely. TriTown then needs another plugin to supply one. @@ -50,7 +66,7 @@ economy: rich-format: "%symbol%%amount%" # Balance granted to a player the first time they join. - starting-balance: 100.0 + starting-balance: 200.0 # Largest balance an account may hold. Set to 0 to remove the cap. # A payment that would break the cap fails rather than being trimmed to fit. balance-cap: 1000000000.0 @@ -164,6 +180,45 @@ player-trades: # Seconds an unanswered request stands before it lapses. request-expiry: 60 +# ── Towns ─────────────────────────────────────────────────────────────────── +towns: + # Money set aside for a player's first town, on top of their starting balance. + # Only /t new can spend it: TriTown takes it off the price Towny charges, so a + # new player who spends their balance by mistake can still found a town. + # Every player without a town is given it once, the next time they join, and + # joining someone else's town gives it up. It is never paid out as money. + # Set to 0 to turn it off. + founding-credit: 100.0 + +# ── News ──────────────────────────────────────────────────────────────────── +# Update notes for the server, read from the main menu or with /tritown news. +# Posts are written in game — /tritown news manage, or the Manage button in the +# news — and nothing about them lives here. Writing them needs +# tritown.news.manage. +news: + # Switch the news off entirely: no menu button, no messages, no command. + enabled: true + join-message: + # Tell a player with unread posts about them a moment after they join, with + # a link to each one. + enabled: true + # How long after joining, so the message is not lost among the welcome ones. + delay-seconds: 3 + # How many unread titles to list before pointing at the rest. + preview: 3 + # What everyone online gets when a post is published with "Publish & announce". + # "Publish quietly" skips all of it. + announce: + # A title across the middle of the screen. + title: true + # A chat line with a link to the post. + chat: true + # A sound key, or "" for none. + sound: "minecraft:block.note_block.chime" + # The most characters one entry may be, not counting colour tags. An entry is + # meant to be a line or two about a single change. + max-entry-length: 200 + # ── Sidebar ───────────────────────────────────────────────────────────────── # The scoreboard shown at the right of the screen. Each board names a condition # and a priority, and a player sees the highest-priority board whose condition diff --git a/src/main/resources/lang/en_US.yml b/src/main/resources/lang/en_US.yml index c137716..f45d731 100644 --- a/src/main/resources/lang/en_US.yml +++ b/src/main/resources/lang/en_US.yml @@ -19,11 +19,25 @@ command: shop: "Shops" trade: "Trading" admin: "Admin" + menu: "Menu" + news: "News" help: header: "TriTown Commands" description: "Show all available commands" + menu: + description: "Open the main menu" + players-only: "The main menu is a menu, so only players can open it." + + news: + description: "Read the server's news" + players-only: "The news is read in a menu, so only players can open it." + unavailable: "The news is not available on this server right now." + unknown: "There is no such post." + all-read: "Marked every post as read." + usage: "Usage: /tritown news [open |readall|manage]" + admin: description: "Open the admin panel" players-only: "The admin panel is a menu, so only players can open it." @@ -39,6 +53,7 @@ command: balance: description: "Check your balance" yours: "Your balance: {balance}" + founding-credit: "Founding credit: {amount} (only for founding a town with /t new)" other: "{name}: {balance}" console-needs-player: "Specify a player: /balance " no-permission-others: "You don't have permission to check another player's balance!" @@ -167,6 +182,56 @@ command: stats: "/tritown shop stats - what a shop has traded" +# The item in the last hotbar slot that opens the main menu. +menu-item: + name: "TriTown Menu" + lore: "Right-click to open the menu.It stays in this slot and cannot be dropped, moved or stored." + relocated: "The TriTown menu lives in your last hotbar slot, so what was there has moved into your inventory." + dropped: "The TriTown menu lives in your last hotbar slot, and your inventory was full, so what was there was dropped at your feet." + unread: "✉ {amount} unread server updates" + +founding-credit: + granted: "You have a {amount} founding credit. It pays towards your first town when you found one with /t new, and nothing else can spend it. Joining someone else's town gives it up." + applied: "Your founding credit covers {amount} of the cost of your town." + forfeited: "You joined a town, so your founding credit has been given up." + +# The server's news: update notes written in game and read from the main menu. +news: + # One entry as a line: its tag, then what it says. + entry: "{tag} {text}" + tag: + new: "✚ New" + changed: "✎ Changed" + fixed: "✔ Fixed" + removed: "✖ Removed" + note: "✦ Note" + join: + header: "✉ You have {amount} unread server updates:" + entry: " • {title} [Read]" + more: " …and {amount} more." + open: " [Open the news]" + broadcast: + title: "Server Update" + chat: "✉ New server update: {title} [Read]" + # The post as a written book. Book pages are light, so dark colours read best. + book: + title: "{title}" + label: "{label}" + date: "{date}" + summary: "{text}" + category: "{name}" + entry: "{tag} {text}" + editor: + created: "Draft created. Add categories, then publish it when it is ready." + deleted: "Post deleted." + published: "Post published." + unpublished: "Post taken back to drafts. Players can no longer see it." + publish-empty: "A post needs at least one entry before it can be published." + category-removed: "Category removed." + entry-added: "Added: {entry}" + entry-removed: "Entry removed." + too-long: "That is too long. Keep it to {amount} characters." + common: unknown: "unknown" invalid-amount: "That is not a valid amount." @@ -252,6 +317,79 @@ gui: next-page: "Next Page" page: "Page {page}/{pages}" + # The main menu, opened from the menu item or with /tritown menu. + menu: + title: "TriTown" + back: "Back" + back-lore: "Return to the main menu." + close: "Close" + profile: "{name}" + profile-balance: "Balance: {balance}" + profile-credit: "Founding credit: {amount}" + profile-rank: "Leaderboard: #{rank}" + profile-town: "Town: {town}" + profile-nation: "Nation: {nation}" + town: "Town" + town-name: "Town: {town}" + town-residents: "Residents: {amount}" + town-bank: "Bank: {amount}" + town-upkeep: "Upkeep: {amount}" + town-none: "You are not in a town yet. Browse the towns to join one, or found your own." + town-credit: "Your {amount} founding credit pays towards the first town you found." + town-open: "Click to open TownyMenu" + shop: "Global Shop" + shop-lore: "Buy from the server and sell back to it, wherever you are standing." + trade: "Trade" + trade-lore: "Swap items and money with a player standing near you. Shift-right-clicking them works too." + trade-waiting: "{amount} waiting for your answer" + pay: "Pay" + pay-lore: "Send money to another player who is online." + leaderboard: "Leaderboard" + leaderboard-lore: "The richest players on the server." + leaderboard-entry: "#{rank} {name} - {balance}" + server: "Server" + sidebar: "Sidebar" + sidebar-on: "The sidebar is shown." + sidebar-off: "The sidebar is hidden." + sidebar-hide: "Click to hide it" + sidebar-show: "Click to show it" + admin: "Admin Panel" + admin-lore: "Read the server's economy and shops." + news: "News" + news-lore: "What has changed on the server lately." + news-unread: "{amount} unread" + news-entry: "• {title}" + + menu-leaderboard: + title: "Leaderboard" + first: "#{rank} {name}" + second: "<#d7dde4>#{rank} {name}" + third: "<#cd7f32>#{rank} {name}" + entry: "#{rank} {name}" + balance: "Balance: {balance}" + account: "A {type} bank" + you: "That's you!" + empty: "Nobody is on the leaderboard yet" + your-rank: "Your Rank" + ranked: "You are #{rank} with {balance}." + unranked: "You are not on the leaderboard yet." + + menu-players: + title-trade: "Trade with…" + title-pay: "Pay…" + name: "{name}" + request: "Wants to trade with you.Click to accept" + distance: "{amount} blocks away" + ask: "Click to ask them to trade" + pay: "Click to choose how much to pay" + pay-prompt: "How much do you want to pay {name}? You have {balance}." + nobody-near: "Nobody is close enough to trade" + nobody-near-lore: "Stand within {amount} blocks of another player to trade with them." + nobody-online: "Nobody else is online" + gone: "That player is no longer online." + refresh: "Refresh" + refresh-lore: "Look again for players, since people move about." + # The admin panel. Amounts, counts and percentages are filled in by TriTown. admin: title: "Admin panel" @@ -688,6 +826,188 @@ gui: status-close: "Closing this menu calls the trade off." status-locked: "The trade just changed. Look it over and confirm again." + # The news: reading it, and the editor administrators write it in. + # Titles, names and entries are what the administrator wrote. + news: + title: "{title}" + pinned-title: "★ {title}" + label: "{label}" + published: "Published {date}" + edited: "Edited {date}" + author: "By {name}" + summary: "{text}" + category-count: "{name}: {amount} changes" + + news-list: + title: "Server News" + empty: "Nothing to read yet" + empty-lore: "Update notes appear here as the server changes." + unread: "NEW - you have not read this yet" + click-read: "Click to read" + read-all: "Mark all as read" + read-all-lore: "Clear the unread markers without opening every post." + manage: "Manage the news" + manage-lore: "Write, edit and publish posts." + + news-post: + title: "{title}" + back: "All news" + back-lore: "Back to the list of posts." + back-editor: "Back to the editor" + back-editor-lore: "Stop previewing." + book: "Read as a book" + book-lore: "The whole post as pages, easier to read when it is long." + edit: "Edit this post" + edit-lore: "Open it in the news editor." + more: "…and {amount} more" + click-category: "Click to see every entry on its own" + preview-draft: "Preview - this draft is not published" + preview-published: "Preview - as players see it" + + news-category: + title: "{name}" + text: "{text}" + back: "Back to the post" + back-lore: "Return to the whole post." + + news-manage: + title: "Manage the news" + empty: "No posts yet" + empty-lore: "Start one with the button below." + draft: "Draft - only editors can see it" + published: "Published" + id: "Id: {id}" + entries: "{categories} categories, {amount} entries" + click-edit: "Click to edit" + shift-click-delete: "Shift-click to delete" + back: "Back" + back-lore: "Return to the news." + new: "New post" + new-lore: "Start a draft. You will be asked for its title in chat." + prompt-title: "Type the new post's title in chat. MiniMessage is allowed." + delete-title: "Delete this post?" + delete: "Delete" + delete-lore: "Remove the post for good. This cannot be undone." + + news-editor: + title: "Editing: {title}" + entries: "Entries: {amount}" + click-category: "Click to edit its entries" + right-click-category: "Right-click to move it somewhere else" + shift-click-category: "Shift-click to remove it" + being-moved: "Being moved" + click-put-down: "Click to leave it where it is" + click-place-before: "Click to drop the held category in front of this one" + holding: "You are moving this category" + move-first: "To the front" + move-first-lore: "Put the category you are moving first." + move-last: "To the back" + move-last-lore: "Put the category you are moving last." + add: "Add a category" + add-lore: "Such as Towns, Economy or Fixes. You will be asked for its name in chat." + prompt-category: "Type the category's name in chat. MiniMessage is allowed." + settings: "Post settings" + settings-lore: "Title, summary, label, icon and pinning." + preview: "Preview" + preview-lore: "See the post exactly as players will." + back: "All posts" + back-lore: "Back to the list of posts." + publish: "Publish" + publish-lore: "Make the post visible to every player." + unpublish: "Unpublish" + unpublish-lore: "Take the post back to drafts, hiding it from players." + delete: "Delete post" + delete-lore: "Remove the post for good." + publish-title: "Publish this post?" + publish-announce: "Publish and announce" + publish-announce-lore: "Show everyone online a title and a link to the post." + publish-quiet: "Publish quietly" + publish-quiet-lore: "Publish without interrupting anyone. Players still see it as unread." + remove-title: "Remove this category?" + remove: "Remove" + remove-lore: "Remove the category and every entry in it." + + news-settings: + title: "Post settings" + title-name: "Title" + summary: "Summary" + summary-lore: "A sentence under the title saying what the update is about." + label: "Label" + label-lore: "A version or season, such as v1.3 or Autumn Update." + icon: "Icon" + icon-lore: "Click any item in your own inventory to use it as the icon. Your item stays where it is." + pin: "Pinned" + pinned: "Pinned to the top of the news" + not-pinned: "Not pinned" + value: "Now: {value}" + translated: "Translations: {amount}" + click-edit: "Click to type new text" + click-toggle: "Click to switch" + right-click-translate: "Right-click to translate it" + right-click-clear: "Right-click to clear it" + right-click-reset: "Right-click to go back to the default" + shift-click-clear: "Shift-click to remove it" + prompt-title: "Type the post's new title in chat. MiniMessage is allowed." + prompt-summary: "Type the summary in chat. MiniMessage is allowed." + prompt-label: "Type the label in chat, such as v1.3." + back: "Back" + back-lore: "Return to the post's categories." + + news-category-editor: + title: "Category: {name}" + click-entry: "Click to edit this entry" + right-click-entry: "Right-click for the next tag" + shift-right-click-entry: "Shift-right-click to move it" + shift-click-entry: "Shift-click to remove it" + being-moved: "Being moved" + click-put-down: "Click to leave it where it is" + click-place-before: "Click to drop the held entry in front of this one" + holding: "You are moving this entry" + move-first: "To the front" + move-first-lore: "Put the entry you are moving first." + move-last: "To the back" + move-last-lore: "Put the entry you are moving last." + add: "Write entries" + add-lore: "Type entries in chat, one line each. Start a line with + new, * changed, ! fixed, - removed or ? note." + name: "Category name" + icon: "Icon" + icon-lore: "Click any item in your own inventory to use it as the icon. Your item stays where it is." + prompt-name: "Type the category's new name in chat. MiniMessage is allowed." + prompt-entries: "Type an entry in chat, one change per line. Start it with + new, * changed, ! fixed, - removed or ? note; without one it keeps the last tag. Type {done} when you are finished." + prompt-next: "Next entry, or {done} to finish." + back: "Back" + back-lore: "Return to the post's categories." + + news-entry: + title: "Entry" + tag-current: "The entry's tag" + tag-click: "Click to use this tag" + prompt-text: "Type the entry's new text in chat. MiniMessage is allowed." + back: "Back" + back-lore: "Return to the category." + delete: "Remove entry" + delete-lore: "Take this entry out of the category." + + news-text: + title: "Translations" + main: "Default text" + main-lore: "Shown to anyone whose language has no translation of its own." + current: "{text}" + untranslated: "Not translated: the default text is shown" + language: "{language}" + click-edit: "Click to type the text" + right-click-clear: "Right-click to remove the translation" + prompt-main: "Type the default text in chat. MiniMessage is allowed." + prompt-language: "Type the {language} text in chat. MiniMessage is allowed." + back: "Back" + back-lore: "Return to where you were." + + # Asked before something that cannot be undone. + confirm: + title: "Are you sure?" + cancel: "Cancel" + cancel-lore: "Go back without changing anything." + # Messages a shop sends to a player, outside the menus themselves. shop: traded: "Traded {amount}x {item} for {price}." diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index 68ca138..fa52029 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -19,11 +19,25 @@ command: shop: "商店" trade: "交易" admin: "管理" + menu: "菜单" + news: "公告" help: header: "TriTown 命令" description: "显示所有可用命令" + menu: + description: "打开主菜单" + players-only: "主菜单是菜单,只有玩家能打开。" + + news: + description: "阅读服务器公告" + players-only: "公告需要在菜单中阅读,只有玩家能打开。" + unavailable: "本服务器的公告暂时不可用。" + unknown: "没有这篇公告。" + all-read: "已将所有公告标记为已读。" + usage: "用法:/tritown news [open |readall|manage]" + admin: description: "打开管理面板" players-only: "管理面板是菜单,只有玩家能打开。" @@ -39,6 +53,7 @@ command: balance: description: "查看你的余额" yours: "你的余额:{balance}" + founding-credit: "建镇资金:{amount} (仅可用于 /t new 创建城镇)" other: "{name}:{balance}" console-needs-player: "请指定一名玩家:/balance " no-permission-others: "你没有权限查看其他玩家的余额!" @@ -167,6 +182,56 @@ command: stats: "/tritown shop stats - 商店的交易统计" +# 快捷栏最后一格中用于打开主菜单的物品。 +menu-item: + name: "TriTown 菜单" + lore: "右键打开菜单。它固定在这一格,无法丢弃、移动或存放。" + relocated: "TriTown 菜单固定在快捷栏最后一格,原本在那里的物品已移入你的背包。" + dropped: "TriTown 菜单固定在快捷栏最后一格,而你的背包已满,原本在那里的物品已掉落在你脚下。" + unread: "✉ {amount} 条未读的服务器公告" + +founding-credit: + granted: "你获得了 {amount} 的建镇资金。使用 /t new 创建你的第一个城镇时会自动抵扣费用,不能用于其他任何用途。加入其他城镇会失去这笔资金。" + applied: "你的建镇资金抵扣了 {amount} 的城镇创建费用。" + forfeited: "你已加入一个城镇,建镇资金已失效。" + +# 服务器公告:在游戏内撰写、从主菜单阅读的更新日志。 +news: + # 单条条目的显示格式:先是标签,然后是内容。 + entry: "{tag} {text}" + tag: + new: "✚ 新增" + changed: "✎ 调整" + fixed: "✔ 修复" + removed: "✖ 移除" + note: "✦ 备注" + join: + header: "✉ 你有 {amount} 条未读的服务器公告:" + entry: " • {title} [阅读]" + more: " ……还有 {amount} 条。" + open: " [打开公告]" + broadcast: + title: "服务器更新" + chat: "✉ 新的服务器公告: {title} [阅读]" + # 以成书形式显示的公告。书页底色较浅,深色文字更易阅读。 + book: + title: "{title}" + label: "{label}" + date: "{date}" + summary: "{text}" + category: "{name}" + entry: "{tag} {text}" + editor: + created: "已创建草稿。添加分类后,准备好即可发布。" + deleted: "公告已删除。" + published: "公告已发布。" + unpublished: "公告已撤回为草稿,玩家将无法再看到它。" + publish-empty: "公告至少需要一条条目才能发布。" + category-removed: "分类已移除。" + entry-added: "已添加:{entry}" + entry-removed: "条目已移除。" + too-long: "内容太长了,请控制在 {amount} 个字符以内。" + common: unknown: "未知" invalid-amount: "这不是有效的金额。" @@ -251,6 +316,79 @@ gui: next-page: "下一页" page: "第 {page}/{pages} 页" + # 主菜单,通过菜单物品或 /tritown menu 打开。 + menu: + title: "TriTown" + back: "返回" + back-lore: "回到主菜单。" + close: "关闭" + profile: "{name}" + profile-balance: "余额:{balance}" + profile-credit: "建镇资金:{amount}" + profile-rank: "财富排行:第 {rank} 名" + profile-town: "城镇:{town}" + profile-nation: "国家:{nation}" + town: "城镇" + town-name: "城镇:{town}" + town-residents: "居民:{amount}" + town-bank: "银行:{amount}" + town-upkeep: "维护费:{amount}" + town-none: "你还没有加入城镇。浏览城镇列表加入一个,或者创建你自己的城镇。" + town-credit: "你的 {amount} 建镇资金可用于支付你创建的第一个城镇。" + town-open: "点击 打开 TownyMenu" + shop: "全局商店" + shop-lore: "无论身在何处,都能向服务器购买物品或把物品卖回给它。" + trade: "交易" + trade-lore: "与身边的玩家交换物品和金钱。也可以潜行右键点击对方发起交易。" + trade-waiting: "{amount} 人正在等待你的回复" + pay: "转账" + pay-lore: "向在线的其他玩家转账。" + leaderboard: "财富排行" + leaderboard-lore: "服务器上最富有的玩家。" + leaderboard-entry: "#{rank} {name} - {balance}" + server: "服务器" + sidebar: "侧边栏" + sidebar-on: "侧边栏当前显示。" + sidebar-off: "侧边栏当前隐藏。" + sidebar-hide: "点击 隐藏" + sidebar-show: "点击 显示" + admin: "管理面板" + admin-lore: "查看服务器的经济与商店数据。" + news: "公告" + news-lore: "服务器最近的变化。" + news-unread: "{amount} 条未读" + news-entry: "• {title}" + + menu-leaderboard: + title: "财富排行" + first: "#{rank} {name}" + second: "<#d7dde4>#{rank} {name}" + third: "<#cd7f32>#{rank} {name}" + entry: "#{rank} {name}" + balance: "余额:{balance}" + account: "{type}银行" + you: "这是你!" + empty: "排行榜上还没有人" + your-rank: "你的排名" + ranked: "你排在 第 {rank} 名,余额 {balance}。" + unranked: "你还没有进入排行榜。" + + menu-players: + title-trade: "与谁交易…" + title-pay: "向谁转账…" + name: "{name}" + request: "想与你交易。点击 接受" + distance: "距离 {amount} 格" + ask: "点击 请求与对方交易" + pay: "点击 选择转账金额" + pay-prompt: "你想向 {name} 转账多少?你有 {balance}。" + nobody-near: "附近没有可以交易的玩家" + nobody-near-lore: "站在其他玩家 {amount} 格以内即可与其交易。" + nobody-online: "没有其他玩家在线" + gone: "该玩家已不在线。" + refresh: "刷新" + refresh-lore: "重新查找玩家,大家总在走动。" + # 管理面板。金额、数量和百分比由 TriTown 填入。 admin: title: "管理面板" @@ -688,6 +826,188 @@ gui: status-close: "关闭此菜单将取消交易。" status-locked: "交易内容刚刚发生变化,请重新确认。" + # 公告:阅读界面,以及管理员撰写公告的编辑器。 + # 标题、名称和条目内容均为管理员所写。 + news: + title: "{title}" + pinned-title: "★ {title}" + label: "{label}" + published: "发布于 {date}" + edited: "编辑于 {date}" + author: "作者:{name}" + summary: "{text}" + category-count: "{name}:{amount} 项变动" + + news-list: + title: "服务器公告" + empty: "暂时没有公告" + empty-lore: "服务器有更新时,更新日志会出现在这里。" + unread: "新 - 你还没有读过这篇" + click-read: "点击 阅读" + read-all: "全部标为已读" + read-all-lore: "无需逐篇打开,直接清除所有未读标记。" + manage: "管理公告" + manage-lore: "撰写、编辑并发布公告。" + + news-post: + title: "{title}" + back: "全部公告" + back-lore: "返回公告列表。" + back-editor: "返回编辑器" + back-editor-lore: "结束预览。" + book: "以书本形式阅读" + book-lore: "把整篇公告排成书页,内容较长时更便于阅读。" + edit: "编辑这篇公告" + edit-lore: "在公告编辑器中打开。" + more: "……还有 {amount} 条" + click-category: "点击 逐条查看" + preview-draft: "预览 - 这篇草稿尚未发布" + preview-published: "预览 - 玩家看到的样子" + + news-category: + title: "{name}" + text: "{text}" + back: "返回公告" + back-lore: "回到整篇公告。" + + news-manage: + title: "管理公告" + empty: "还没有公告" + empty-lore: "点击下方按钮开始撰写。" + draft: "草稿 - 仅编辑者可见" + published: "已发布" + id: "ID:{id}" + entries: "{categories} 个分类,{amount} 条条目" + click-edit: "点击 编辑" + shift-click-delete: "Shift+点击 删除" + back: "返回" + back-lore: "回到公告。" + new: "新建公告" + new-lore: "创建一篇草稿,随后会在聊天栏中询问标题。" + prompt-title: "请在聊天栏中输入新公告的标题,支持 MiniMessage。" + delete-title: "删除这篇公告?" + delete: "删除" + delete-lore: "永久删除这篇公告,此操作无法撤销。" + + news-editor: + title: "编辑:{title}" + entries: "条目:{amount}" + click-category: "点击 编辑其中的条目" + right-click-category: "右键 移动到其他位置" + shift-click-category: "Shift+点击 移除" + being-moved: "正在移动" + click-put-down: "点击 放回原处" + click-place-before: "点击 将移动中的分类放到这一项前面" + holding: "你正在移动这个分类" + move-first: "移到最前" + move-first-lore: "把正在移动的分类放到第一个。" + move-last: "移到最后" + move-last-lore: "把正在移动的分类放到最后一个。" + add: "添加分类" + add-lore: "例如城镇、经济或修复。随后会在聊天栏中询问分类名称。" + prompt-category: "请在聊天栏中输入分类名称,支持 MiniMessage。" + settings: "公告设置" + settings-lore: "标题、摘要、标签、图标与置顶。" + preview: "预览" + preview-lore: "以玩家的视角查看这篇公告。" + back: "全部公告" + back-lore: "返回公告列表。" + publish: "发布" + publish-lore: "让所有玩家都能看到这篇公告。" + unpublish: "撤回发布" + unpublish-lore: "把公告撤回为草稿,玩家将看不到它。" + delete: "删除公告" + delete-lore: "永久删除这篇公告。" + publish-title: "发布这篇公告?" + publish-announce: "发布并通知" + publish-announce-lore: "向所有在线玩家显示标题和公告链接。" + publish-quiet: "静默发布" + publish-quiet-lore: "发布时不打扰任何人,玩家仍会看到它显示为未读。" + remove-title: "移除这个分类?" + remove: "移除" + remove-lore: "移除该分类及其中的所有条目。" + + news-settings: + title: "公告设置" + title-name: "标题" + summary: "摘要" + summary-lore: "标题下方的一句话,说明这次更新的内容。" + label: "标签" + label-lore: "版本号或季节,例如 v1.3 或秋季更新。" + icon: "图标" + icon-lore: "点击你背包中的任意物品即可设为图标,物品本身不会被拿走。" + pin: "置顶" + pinned: "已置顶在公告最上方" + not-pinned: "未置顶" + value: "当前:{value}" + translated: "翻译:{amount}" + click-edit: "点击 输入新内容" + click-toggle: "点击 切换" + right-click-translate: "右键 翻译" + right-click-clear: "右键 清除" + right-click-reset: "右键 恢复默认" + shift-click-clear: "Shift+点击 移除" + prompt-title: "请在聊天栏中输入公告的新标题,支持 MiniMessage。" + prompt-summary: "请在聊天栏中输入摘要,支持 MiniMessage。" + prompt-label: "请在聊天栏中输入标签,例如 v1.3。" + back: "返回" + back-lore: "回到公告的分类列表。" + + news-category-editor: + title: "分类:{name}" + click-entry: "点击 编辑这条条目" + right-click-entry: "右键 切换到下一个标签" + shift-right-click-entry: "Shift+右键 移动" + shift-click-entry: "Shift+点击 移除" + being-moved: "正在移动" + click-put-down: "点击 放回原处" + click-place-before: "点击 将移动中的条目放到这一项前面" + holding: "你正在移动这条条目" + move-first: "移到最前" + move-first-lore: "把正在移动的条目放到第一条。" + move-last: "移到最后" + move-last-lore: "把正在移动的条目放到最后一条。" + add: "撰写条目" + add-lore: "在聊天栏中逐行输入条目。行首可加 + 新增、* 调整、! 修复、- 移除或 ? 备注。" + name: "分类名称" + icon: "图标" + icon-lore: "点击你背包中的任意物品即可设为图标,物品本身不会被拿走。" + prompt-name: "请在聊天栏中输入分类的新名称,支持 MiniMessage。" + prompt-entries: "请在聊天栏中输入条目,每行一项变动。行首可加 + 新增、* 调整、! 修复、- 移除或 ? 备注;不加则沿用上一条的标签。完成后输入 {done}。" + prompt-next: "请输入下一条,或输入 {done} 结束。" + back: "返回" + back-lore: "回到公告的分类列表。" + + news-entry: + title: "条目" + tag-current: "当前标签" + tag-click: "点击 使用这个标签" + prompt-text: "请在聊天栏中输入条目的新内容,支持 MiniMessage。" + back: "返回" + back-lore: "回到分类。" + delete: "移除条目" + delete-lore: "把这条条目从分类中移除。" + + news-text: + title: "翻译" + main: "默认文本" + main-lore: "当玩家的语言没有对应翻译时显示此文本。" + current: "{text}" + untranslated: "未翻译:将显示默认文本" + language: "{language}" + click-edit: "点击 输入文本" + right-click-clear: "右键 删除翻译" + prompt-main: "请在聊天栏中输入默认文本,支持 MiniMessage。" + prompt-language: "请在聊天栏中输入 {language} 的文本,支持 MiniMessage。" + back: "返回" + back-lore: "回到之前的界面。" + + # 执行无法撤销的操作前进行确认。 + confirm: + title: "确定吗?" + cancel: "取消" + cancel-lore: "返回,不做任何修改。" + # 商店在菜单之外发给玩家的消息。 shop: traded: "以 {price} 成交 {amount}个 {item}。" diff --git a/src/test/kotlin/net/trilleo/mc/plugins/tritown/news/NewsModelTest.kt b/src/test/kotlin/net/trilleo/mc/plugins/tritown/news/NewsModelTest.kt new file mode 100644 index 0000000..3f1329c --- /dev/null +++ b/src/test/kotlin/net/trilleo/mc/plugins/tritown/news/NewsModelTest.kt @@ -0,0 +1,90 @@ +package net.trilleo.mc.plugins.tritown.news + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** The pieces of the news that decide what a player reads: which language, which tag, and what is unread. */ +class NewsModelTest { + + // ── LocalizedText ─────────────────────────────────────────────────── + + @Test + fun `a missing translation falls back to the main text`() { + val text = LocalizedText("Hello", mutableMapOf("zh_CN" to "你好")) + + assertEquals("你好", text.get("zh_CN")) + assertEquals("你好", text.get("ZH_cn")) + assertEquals("Hello", text.get("en_US")) + assertEquals("Hello", text.get(null)) + } + + @Test + fun `translating again replaces the old translation whatever its case`() { + val text = LocalizedText("Hello", mutableMapOf("zh_cn" to "旧")) + text.translate("zh_CN", "新") + + assertEquals(mapOf("zh_CN" to "新"), text.translations) + + text.clear("ZH_CN") + assertNull(text.translation("zh_CN")) + } + + // ── NewsShorthand ─────────────────────────────────────────────────── + + @Test + fun `a prefix picks the tag and is dropped from the text`() { + assertEquals( + EntryTag.NEW to "Added harvest festivals", + NewsShorthand.parse("+ Added harvest festivals", EntryTag.NOTE) + ) + assertEquals( + EntryTag.CHANGED to "Shops restock hourly", + NewsShorthand.parse("*Shops restock hourly", EntryTag.NOTE) + ) + assertEquals( + EntryTag.FIXED to "Upkeep charged once", + NewsShorthand.parse("! Upkeep charged once", EntryTag.NOTE) + ) + assertEquals(EntryTag.REMOVED to "Old spawn", NewsShorthand.parse("- Old spawn", EntryTag.NOTE)) + assertEquals(EntryTag.NOTE to "Restart at 6", NewsShorthand.parse("? Restart at 6", EntryTag.NEW)) + } + + @Test + fun `a line without a prefix keeps the previous tag`() { + assertEquals(EntryTag.FIXED to "Another fix", NewsShorthand.parse(" Another fix ", EntryTag.FIXED)) + } + + // ── Unread ────────────────────────────────────────────────────────── + + private fun published(id: String, at: Long) = + NewsPost(id = id, status = PostStatus.PUBLISHED, publishedAt = at) + + @Test + fun `posts from before a player first met the news are not unread, except the newest`() { + val posts = listOf(published("new", 300L), published("mid", 200L), published("old", 100L)) + + val unread = NewsReadState.unreadOf(posts, read = emptySet(), since = 1_000L) + + assertEquals(listOf("new"), unread.map { it.id }) + } + + @Test + fun `posts published since then are unread until read`() { + val posts = listOf(published("c", 300L), published("b", 200L), published("a", 100L)) + + val unread = NewsReadState.unreadOf(posts, read = setOf("c"), since = 150L) + + assertEquals(listOf("b"), unread.map { it.id }) + } + + @Test + fun `the newest post is found by date even when a pinned one is listed first`() { + val pinned = published("pinned", 100L).apply { pinned = true } + val posts = listOf(pinned, published("latest", 500L)) + + val unread = NewsReadState.unreadOf(posts, read = emptySet(), since = 1_000L) + + assertEquals(listOf("latest"), unread.map { it.id }) + } +} diff --git a/src/test/kotlin/net/trilleo/mc/plugins/tritown/news/storage/JsonNewsStorageTest.kt b/src/test/kotlin/net/trilleo/mc/plugins/tritown/news/storage/JsonNewsStorageTest.kt new file mode 100644 index 0000000..fdbf11e --- /dev/null +++ b/src/test/kotlin/net/trilleo/mc/plugins/tritown/news/storage/JsonNewsStorageTest.kt @@ -0,0 +1,123 @@ +package net.trilleo.mc.plugins.tritown.news.storage + +import net.trilleo.mc.plugins.tritown.news.* +import java.io.File +import java.nio.file.Files +import java.util.logging.Level +import java.util.logging.Logger +import kotlin.test.* + +/** The news file holds what administrators wrote by hand, so it must survive a crash, a bad edit and an old build. */ +class JsonNewsStorageTest { + + private val directory: File = Files.createTempDirectory("tritown-news").toFile() + private val logger = Logger.getAnonymousLogger().apply { level = Level.OFF } + private val storage = JsonNewsStorage(directory, logger) + + private val newsFile = File(File(directory, "news"), "posts.json") + private val backupFile = File(File(directory, "news"), "posts.json.bak") + + @AfterTest + fun cleanUp() { + directory.deleteRecursively() + } + + @Test + fun `a server with no news starts empty`() { + assertEquals(emptyList(), storage.loadAll()) + } + + @Test + fun `a post survives a round trip`() { + val post = NewsPost( + id = "abc123", + title = LocalizedText("Autumn update", mutableMapOf("zh_CN" to "秋季更新")), + summary = LocalizedText("Harvest season is here."), + label = "v1.3", + icon = "PUMPKIN", + categories = mutableListOf( + NewsCategory( + id = "cat001", + name = LocalizedText("Towns"), + icon = "BELL", + entries = mutableListOf( + NewsEntry("ent001", EntryTag.NEW, LocalizedText("Towns can now hold a harvest festival.")), + NewsEntry("ent002", EntryTag.FIXED, LocalizedText("Upkeep is no longer charged twice.")), + ), + ) + ), + status = PostStatus.PUBLISHED, + pinned = true, + createdAt = 1_000L, + publishedAt = 2_000L, + authorName = "Trilleo", + ) + + storage.saveAll(listOf(post)) + val loaded = storage.loadAll().single() + + assertEquals("abc123", loaded.id) + assertEquals("秋季更新", loaded.title.get("zh_CN")) + assertEquals("Harvest season is here.", loaded.summary?.main) + assertEquals("v1.3", loaded.label) + assertEquals(PostStatus.PUBLISHED, loaded.status) + assertTrue(loaded.pinned) + assertEquals(2_000L, loaded.publishedAt) + assertEquals(listOf(EntryTag.NEW, EntryTag.FIXED), loaded.categories.single().entries.map { it.tag }) + assertEquals("Upkeep is no longer charged twice.", loaded.categories.single().entry("ent002")?.text?.main) + } + + @Test + fun `fields an older file lacks take their defaults`() { + newsFile.parentFile.mkdirs() + newsFile.writeText("""{"schemaVersion":1,"posts":[{"id":"old001","title":{"main":"Hello"}}]}""") + + val loaded = storage.loadAll().single() + + assertEquals(PostStatus.DRAFT, loaded.status) + assertEquals(NewsPost.DEFAULT_ICON, loaded.icon) + assertTrue(loaded.categories.isEmpty()) + assertTrue(loaded.title.translations.isEmpty()) + } + + @Test + fun `an unknown tag or explicit null is repaired rather than left null`() { + newsFile.parentFile.mkdirs() + newsFile.writeText( + """{"schemaVersion":1,"posts":[{"id":"bad001","title":null,"status":"ARCHIVED","categories":[ + {"id":"c","name":{"main":"X"},"entries":[{"id":"e","tag":"SHINY","text":{"main":"t"}}]}]}]}""" + ) + + val loaded = storage.loadAll().single() + + assertEquals("", loaded.title.main) + assertEquals(PostStatus.DRAFT, loaded.status) + assertEquals(EntryTag.NOTE, loaded.categories.single().entries.single().tag) + } + + @Test + fun `an unreadable file falls back to the backup`() { + storage.saveAll(listOf(NewsPost(id = "first1"))) + storage.saveAll(listOf(NewsPost(id = "second"))) + newsFile.writeText("{ not json") + + assertEquals(listOf("first1"), storage.loadAll().map { it.id }) + } + + @Test + fun `a file and backup that are both unreadable refuse to load`() { + newsFile.parentFile.mkdirs() + newsFile.writeText("{ not json") + backupFile.writeText("{ also not json") + + assertFailsWith { storage.loadAll() } + } + + @Test + fun `a file from a newer build is refused`() { + newsFile.parentFile.mkdirs() + newsFile.writeText("""{"schemaVersion":99,"posts":[]}""") + + assertFailsWith { storage.loadAll() } + } +} diff --git a/src/test/kotlin/net/trilleo/mc/plugins/tritown/registration/GUIFrameTest.kt b/src/test/kotlin/net/trilleo/mc/plugins/tritown/registration/GUIFrameTest.kt index 2ddfee5..af571fa 100644 --- a/src/test/kotlin/net/trilleo/mc/plugins/tritown/registration/GUIFrameTest.kt +++ b/src/test/kotlin/net/trilleo/mc/plugins/tritown/registration/GUIFrameTest.kt @@ -49,4 +49,51 @@ class GUIFrameTest { assertEquals(emptyList(), GUIFrame.contentSlots(2)) assertEquals(emptyList(), GUIFrame.contentSlots(1)) } + + @Test + fun `spaced buttons sit either side of the middle column`() { + assertEquals(emptyList(), GUIFrame.spacedColumns(0)) + assertEquals(listOf(4), GUIFrame.spacedColumns(1)) + assertEquals(listOf(3, 5), GUIFrame.spacedColumns(2)) + assertEquals(listOf(2, 4, 6), GUIFrame.spacedColumns(3)) + assertEquals(listOf(1, 3, 5, 7), GUIFrame.spacedColumns(4)) + } + + @Test + fun `packed items stay inside the border and mirror around the middle`() { + for (count in 0..7) { + val columns = GUIFrame.packedColumns(count) + assertEquals(count, columns.size) + assertTrue(columns.all { it in 1..7 }) + assertEquals(columns.map { 8 - it }.sorted(), columns, "$count items are not symmetrical") + } + } + + @Test + fun `an even count leaves the middle column empty`() { + assertEquals(listOf(3, 5), GUIFrame.packedColumns(2)) + assertEquals(listOf(2, 3, 5, 6), GUIFrame.packedColumns(4)) + assertEquals(listOf(1, 2, 3, 5, 6, 7), GUIFrame.packedColumns(6)) + } + + @Test + fun `a few items sit in the middle of the menu`() { + assertEquals(listOf(22), GUIFrame.centeredSlots(6, 1)) + assertEquals(listOf(21, 23), GUIFrame.centeredSlots(6, 2)) + } + + @Test + fun `a partial page centres its last row under full ones`() { + assertEquals((19..25).toList() + listOf(30, 32), GUIFrame.centeredSlots(6, 9)) + } + + @Test + fun `a full page is exactly the framed content`() { + assertEquals(GUIFrame.contentSlots(6), GUIFrame.centeredSlots(6, 28)) + } + + @Test + fun `nothing to show takes no slots`() { + assertEquals(emptyList(), GUIFrame.centeredSlots(6, 0)) + } }