Compare commits

..
63 Commits
Author SHA1 Message Date
HorizonCode 756638ecf1 fix(ui): hide scrollbars on horizontal chip strips
Define the missing no-scrollbar utility so recent-play and icon-pack strips stop rendering native desktop scrollbars.
2026-11-18 20:37:00 +01:00
HorizonCode 34e93ee29b fix(presence): keep rich presence synced with launcher state
Refresh idle activity from live mode, stats, user, and config changes, replace activity snapshots so cleared buttons and images are removed, and keep retrying Discord IPC until presence is disabled.
2026-11-12 12:59:56 +01:00
HorizonCode e1c04c4f5b fix(build): clean up cross-platform warnings
Scope diagnostics mutability to macOS, pass the Rust LLVM library path to spawned tools, and suppress missing MSVC PDB warnings for cargo-xwin links.
2026-11-12 11:32:36 +01:00
HorizonCode cb117826c7 build(release): remove old build script 2026-11-12 11:19:14 +01:00
HorizonCode 0e295c8425 build(release): add cross-platform release builds
Add host and per-platform release commands, with macOS/Linux-to-Windows NSIS cross-compilation via cargo-xwin and up-front toolchain checks.
2026-11-12 11:16:48 +01:00
HorizonCode 746524d27e Merge branch 'themes-v2' of https://git.ez-pp.farm/EZPPFarm/EZPPLauncher into themes-v2 2026-11-04 22:36:53 +01:00
HorizonCode 660fb557a6 fix(logs): include the current session in the viewer
Read the active launcher, osu!, and patcher logs directly so the current session appears before rotation.
2026-11-04 22:36:16 +01:00
HorizonCode 575da8504a Merge branch 'themes-v2' of https://git.ez-pp.farm/EZPPFarm/EZPPLauncher into themes-v2 2026-11-04 21:44:22 +01:00
HorizonCode 8616253065 feat(themes): crossfade theme changes and fix window overflow
Crossfade user-selected themes, keep the theme volume popover open while
dragging its slider, and clip the fixed app shell so oversized theme layers
cannot create page scrollbars on Windows. Remove the redundant in-use badge
from the active theme card.
2026-11-04 21:43:24 +01:00
HorizonCode 0105c5975a fix: unsafe use 2026-11-04 21:29:02 +01:00
HorizonCode c2fd265b49 perf(launcher): reduce background resource usage
Make the custom cursor event-driven, pause CSS, theme video, and Lottie work
while the launcher is hidden or unfocused, and reduce presence polling while
osu is running.
2026-11-04 17:00:16 +01:00
HorizonCode 687ab26752 fix(themes): remove enabled/disabled badge in title when logging tab is active 2026-11-04 16:43:48 +01:00
HorizonCode 9d312fb3bb fix(themes): re-add themesV2Css import 2026-11-04 16:42:30 +01:00
HorizonCode ef214d424c feat(themes): add revert for unsynced themes
Restore the published Workshop version after confirmation, keeping a backup of
local edits. Owner reverts send auth headers so themes-service skips the
download counter.
2026-11-04 14:50:03 +01:00
HorizonCode d4be3f845d feat(themes): confirm uninstalls and restore tab padding
Add a confirmation dialog before removing an installed theme, warning
that local edits are deleted. Apply content padding to the absolute tab
panels so the workshop and library views stay inset from the frame.
2026-11-04 13:50:05 +01:00
HorizonCode 83b007818d chore(themes): move theme libs into /theme 2026-11-04 13:39:45 +01:00
HorizonCode cfb6ec8cce fix(themes): hide version tag badge for default theme 2026-11-04 13:20:57 +01:00
HorizonCode 323a6f18af feat(themes): flag unpublished edits and share parallax motion
Compare theme content hashes with a stored Workshop baseline so creators
can see when their local copy is not synced. Extract pointer tracking into
a shared action for the launcher and editor preview, and use the slider
component for parallax depth.
2026-11-04 12:04:13 +01:00
HorizonCode d56ed9d786 feat(themes): polish theme editor, updates, and card motion
- Lazy-load the theme editor, workshop, diagnostics, logs, and presence editor.
- Check installed themes for newer workshop versions and support updates with backup/restore.
- Preserve accordion state for the current editor session and add section icons.
- Animate installed and workshop cards on insertion, and fix the duplicate presence idle action.
2026-11-04 09:54:58 +01:00
HorizonCode 51f5fa3e46 fix(themes): enforce strict semver versions
Require SemVer 2.0.0 when saving, validating, or publishing a theme, and validate again at the workshop upload boundary. This rejects partial versions, v-prefixed versions, leading-zero components, and arbitrary strings while preserving valid prerelease and build metadata.
2026-11-04 00:00:07 +01:00
HorizonCode 07cbfa39a6 fix(themes): require a newer version for each publish
Compare the proposed version with the version currently published in the workshop before opening the publish dialog and again before upload. Reject invalid semver, duplicate versions, and downgrades, while tracking the just-submitted version in-session so pending updates cannot be published twice.
2026-11-03 23:54:02 +01:00
HorizonCode 11aefee7ed feat(themes): persist publisher id in theme manifests
Publishing now stamps the signed-in EZPPFarm user ID into theme.json and saves it before packaging, so installed theme cards can resolve avatars by stable user ID. Older manifests keep the author-name fallback.
2026-11-03 23:45:00 +01:00
HorizonCode 5eea428802 fix(themes): show author avatars on installed theme cards
Installed theme cards rendered only an initial because their manifests store the author name, not an avatar URL. Use the EZPPFarm avatar endpoint with the author name and keep the initial as the image-load fallback, matching the community workshop presentation.
2026-11-03 23:39:25 +01:00
HorizonCode 760bd9a283 refactor(themes): align installed cards with the workshop layout
Installed theme cards now use the same visual hierarchy as workshop cards: status and API badges at the top, version on the preview, an author strip over the artwork, a compact title and description, and a footer with status plus compact actions. This removes the oversized primary button and duplicate version/author rows.
2026-11-03 23:13:44 +01:00
HorizonCode 47c022642f feat(themes): polish installed cards and add workshop theme details
Installed themes now use a 16:9 preview with stable card spacing and a single overflow menu for edit, restore, update, report and uninstall actions. Community theme previews and titles open a large detail dialog with a full-size preview, metadata, tags, review status and the relevant install action.
2026-11-03 23:08:35 +01:00
HorizonCode 5613c3be25 fix(workshop): make moderation and install flows production ready
Replace the remaining native prompt and confirm calls with an in-app action dialog, including focus handling and inline errors. Guard likes and concurrent moderation loads, surface stale-data errors, paginate the review queue, and keep load-more state local to each list. Allow the packaged app to reach the workshop host for API calls and previews.
2026-11-03 22:55:18 +01:00
HorizonCode 4d57184b73 feat(settings): animate the active settings description
The selected settings description now morphs between values with TextMorph unless reduced motion is enabled.
2026-11-03 19:26:52 +01:00
HorizonCode d555ac366f refactor(workshop): use the shared select component for theme filters
The sort, announcement audience and report category controls were still native select elements. They now use the same shadcn-svelte Select as the moderation filters for consistent styling and keyboard behavior.
2026-11-03 19:18:31 +01:00
HorizonCode 918f8651dd fix(workshop): make the takedown action work inside the desktop webview
The action used window.prompt, which returns null in the Tauri webview, so the handler aborted before calling the API. Takedown and lift now use an in-app dialog with a required reason, inline errors and a loading state.
2026-11-03 19:07:22 +01:00
HorizonCode 4b039c9b79 fix(workshop): keep download progress across tab switches
The workshop is unmounted when the Installed tab is opened, so its local download state was discarded and returning to the Community tab showed no progress even though the install was still running. Active downloads and percentages now live in a shared module that outlives the component, and in-flight downloads keep updating it.
2026-11-03 19:03:58 +01:00
HorizonCode 809fca6f29 feat(workshop): add the pre-publication review queue
New themes are submitted for review instead of appearing live, so the workshop now surfaces pending and rejected badges on the creator's own cards and adds a Review queue to the moderation panel with approve and reject actions. Publishing reports that the theme is awaiting review, and approval/rejection notifications are labelled.
2026-11-03 19:01:29 +01:00
HorizonCode 0025313c4d fix(workshop): allow concurrent downloads and stop auto-applying
Downloads shared a single active-id guard, so a second theme could not start until the first finished, and completing one immediately applied it over the current theme. Each download now tracks its own progress, runs concurrently, and only adds the theme to the library. The batch-selection bar and checkboxes are removed in favour of the independent buttons.
2026-11-03 18:48:52 +01:00
HorizonCode 6b1ed5aa1a feat(workshop): download multiple selected themes in one batch
Only one theme could be installed at a time because a single download id
guarded every card, so users had to repeat the flow per theme. A selection
mode now adds checkboxes and a batch bar that installs the chosen themes in
sequence, with per-theme progress and a summary of failures.
2026-11-03 18:43:53 +01:00
HorizonCode fc128b7178 feat(notifications): show full notification details with actions
Long announcements were clamped in the list and had nowhere to open, so
notifications now open a detail dialog with the full message, type, theme,
sender and timestamp, plus a shortcut into the Community Workshop.
2026-11-03 18:33:19 +01:00
HorizonCode 520ad5c4f1 feat(workshop): confirm trash restore and permanent deletion
Add confirmation dialogs for restoring and permanently deleting trashed themes, and wire the permanent-delete API call.
2026-11-03 18:10:34 +01:00
HorizonCode 93536af6a6 chore(lint): resolve launcher lint issues
Format files and fix unused code, reactive collection usage, redundant mustaches, and missing each-block keys.
2026-11-03 16:21:23 +01:00
HorizonCode 3ef59f94ee feat(themes): improve workshop filtering and fork controls
Add a compact used-tag filter, preserve workshop ownership across theme
reloads, and let authors disable forking for their themes.
2026-11-03 16:06:11 +01:00
HorizonCode ebc5fbf9c4 feat(themes): polish workshop moderation and theme controls
Add the in-app tag editor, installed-theme reporting, readable moderation and report dialogs, and notification layering fixes. Persist server-assigned workshop IDs for stable republishes, hide self-reporting, fix report-button contrast, and disable macOS autocorrect and spell checking across launcher windows.
2026-11-03 14:58:28 +01:00
HorizonCode 1f3fa026ce feat(workshop): add role badges and streamline theme cards
Use the service owner, moderator, or supporter role for author badges, expose downloads for owned legacy themes, and move secondary card actions into a menu. Include theme tags in publish metadata and keep API 2.0 exports limited to theme.json and assets.
2026-11-03 13:15:37 +01:00
HorizonCode 9b4158410d feat(workshop): add moderation, search, tag, and tooltip controls
Surface staff reports, takedowns, announcements, audit tools, ranked
search, creator tag editing, and shared tooltips in the workshop.
2026-11-03 10:03:53 +01:00
HorizonCode 1bf8034126 feat(themes): set default themes service URL to https://themes.ez-pp.farm 2026-11-02 16:33:01 +01:00
HorizonCode a423850dc9 refactor(themes): remove session tokens and authenticate exclusively via username and password 2026-11-02 16:25:38 +01:00
HorizonCode a051c021d7 fix(themes): implement native download_and_extract_community_theme and expand fs capabilities 2026-11-01 16:59:41 +01:00
HorizonCode 4a6e8c5cab fix(themes): remove descriptions from legacy themes 2026-11-01 16:30:03 +01:00
HorizonCode 2f0b034c5e fix(themes): correct Execution Clap artist attribution to Trap Chick 2026-11-01 16:28:01 +01:00
HorizonCode f198e2376c fix(themes): update legacy theme descriptions and author id to 1001 2026-11-01 16:27:01 +01:00
HorizonCode c1664ed5bf feat(themes): migrate legacy themes to Community Workshop and clean up installed library filters 2026-11-01 16:23:21 +01:00
HorizonCode 0b4af5a4d4 fix(workshop): correct DefaultThemePreview asset import path 2026-11-01 16:04:28 +01:00
HorizonCode e31d92ed3c feat(communityThemes): include credential headers in getAuthHeaders for direct auth 2026-11-01 16:00:07 +01:00
HorizonCode 8816852fd9 feat(themes): implement community themes workshop and chunked uploader 2026-11-01 15:43:24 +01:00
HorizonCode d38250a5e4 fix(theme-v2): ensure theme audio autoplays on load and handles unlock gesture 2026-11-01 14:54:04 +01:00
HorizonCode ad3fe7c586 fix(theme-editor): fix player card widget overflow, add banner variant, and improve widget selection badge 2026-11-01 14:32:56 +01:00
HorizonCode a025f9b285 fix(theme): unlock unmuted media autoplay without user interaction on macos 2026-11-01 13:57:47 +01:00
HorizonCode ce572de0d2 fix(theme): keep video unmuted with persistent volume knob on launch 2026-11-01 13:35:54 +01:00
HorizonCode e861cda23d fix(theme): do not display api version badge for the default built-in theme 2026-11-01 13:03:56 +01:00
HorizonCode 7332618e85 fix(theme): stream video conversion progress and auto-play v1 theme media 2026-11-01 13:00:58 +01:00
HorizonCode 62b31169cc feat: add game optimization mode, 3d cursor parallax, and embers particle effect 2026-11-01 12:36:10 +01:00
HorizonCode a75e723416 chore(rust): resolve all clippy warnings across codebase 2026-11-01 12:14:23 +01:00
HorizonCode 45962242aa fix(patcher): gate patcher compatibility patching to macos only 2026-11-01 12:08:43 +01:00
HorizonCode ce9112f9e2 docs: update README with theme v2, discord presence, and platform support details 2026-11-01 11:00:32 +01:00
HorizonCode e52399911c fix(macos): resolve osu updater loop and patcher wine compatibility
- Remove host Apple Braille font entries from Wine prefix registry to prevent cold-start GDI+ AccessViolationException.
- Purge .require_update, help.txt, and _pending prior to osu! launch so the game launches directly with -devserver ez-pp.farm instead of entering the updater.
- Reset _UpdateFailCount in osu!.cfg and ensure execute.bat points to ez-pp.farm.
- Update ensure_patcher_compatibility to patch osu!.patcher.exe and embedded ManagedInjector.Lib for .NET 4.0 compatibility under Wine.
- Include theme editor, cursor, and download button refinements on themes-v2 branch.
2026-11-01 10:52:39 +01:00
HorizonCode a2b03d3014 style: format files with prettier and fix eslint issues 2026-10-31 21:27:28 +01:00
HorizonCode 7648d1fd4c feat(theme-v2): add detachable header widget, fix preview thumbnail rendering, and improve wineskin launch
- Support detaching title header to canvas with full, compact, and minimal variants
- Render detached widgets and respect chrome layout configuration in theme preview generator
- Fix macOS Wineskin launching by adding Frameworks to DYLD_FALLBACK_LIBRARY_PATH
- Fix launch button interactive handling, scaling margins, and icon-only states
- Improve player widget styling and variant display
2026-10-31 21:00:14 +01:00
121 changed files with 17501 additions and 2610 deletions

No files matched your search

+185 -105
View File
@@ -1,7 +1,7 @@
# EZPPLauncher # EZPPLauncher
**EZPPLauncher** is a custom launcher for the private osu! server [EZPPFarm](https://ez-pp.farm), built with **Rust** and **Svelte** using the [Tauri](https://tauri.app) framework. **EZPPLauncher** is a modern, feature-rich custom launcher for the private osu! server [EZPPFarm](https://ez-pp.farm), built with **Rust** and **Svelte 5** using the [Tauri](https://tauri.app) framework.
It enhances the osu! experience with quality-of-life features and integration specifically designed for the EZPPFarm community. It enhances the osu! experience with quality-of-life features, advanced launcher theming, customized Discord Rich Presence, and seamless server integration. Windows and macOS are supported, with partial support for Linux.
--- ---
@@ -13,101 +13,162 @@ It enhances the osu! experience with quality-of-life features and integration sp
## 🚀 Features ## 🚀 Features
- [x] Automatically updates osu! before launching ### Game & Server Integration
- [x] Automatically start/stop the OpenTabletDriver Daemon (Windows)
- [x] Automatic ingame login - [x] **Direct Server Launch**: Launches osu! directly with `-devserver ez-pp.farm`, bypassing osu! updater loops and preserving launch parameters.
- [x] Patches the osu! client to show misses in Relax and Autopilot (Windows, Linux and macOS via Wine) - [x] **Automatic In-Game Login**: Automatically signs into your EZPPFarm account upon game boot.
- [x] Displays your EZPPFarm stats in the launcher - [x] **In-Game Relax & Autopilot Miss Patcher**: Injects a hook into the osu! client to display misses in Relax and Autopilot modes (Windows, macOS via Wine, and partially on Linux via osu-winello).
- [x] Shows the number of imported beatmapsets - [x] **Live Player Stats**: Displays rank, PP, accuracy, playcount, and server latency directly on the launcher dashboard.
- [x] Shows the number of imported skins - [x] **Library Indexing**: Automatically counts imported beatmapsets and skins.
- [x] Displays ping to the EZPPFarm server - [x] **OpenTabletDriver Integration**: Automatically starts and stops the OpenTabletDriver daemon on launch/exit (Windows only).
- [x] Discord Rich Presence - [x] **Competitive Game Optimization Mode**: Optional low-latency engine setting that boosts osu! process priority to High and requests sub-millisecond Windows timer resolution (1ms) during gameplay.
- [x] Performance Display Overlay (currently in experimental patcher release stream) - [x] **Performance Display Overlay**: In-game HUD overlay (available in the experimental patcher stream).
- [x] Launcher Theming (API 1.0 bundles and API 2.0 declarative themes)
- [x] Advanced theme editor in its own window with freeform text/image/video/shape layers, custom Svelte 5 component layers with Monaco editing and inline compiler diagnostics, gradient/outline/shadow text effects, multi-select and snapping, a drag-and-drop layer tree with moves into and out of nested groups, layer/group transforms with independent X/Y scale and skew, hover group breadcrumbs, on-canvas layer/group rotate handles plus group move and scale handles, layer/group-linked WHEN/IF/THEN logic with quick navigation, safe advanced rule scripts with expressions, branches and loops, draft recovery, validation and export ### Visual Theme Engine v2 & In-App Studio
- [x] Theme update backups with one-click rollback, plus a trust prompt before running executable API 1.0 themes or API 2.0 themes with custom Svelte layers
- [x] In-app diagnostics for osu!, Wine, the patcher, and the experimental stream's .NET 8 runtime, plus a log-bundle viewer - [x] **Declarative Theme API 2.0**: Modern JSON schema supporting background videos, audio, Lottie animations, and layered widgets without custom compilation.
- [x] **Dedicated Visual Theme Editor**: Standalone resizable window with a full-featured visual canvas, live preview, and multi-element selection.
- [x] **Custom Svelte 5 Component Layers**: Embed custom reactive Svelte 5 components with an integrated **Monaco code editor** and live compiler diagnostics.
- [x] **Canvas Transform Tooling**: Multi-selection, snapping, freeform rotation, X/Y scale, skew, and group breadcrumb navigation.
- [x] **Logic & Scripting System**: Visual WHEN/IF/THEN rule builder and sandboxed rule scripting (expressions, branches, loops, visibility toggles) without `eval`.
- [x] **Dynamic Placeholders & Clock Expressions**: Real-time variables (`{username}`, `{rank}`, `{pp}`) and second-accurate clock variables (`{time}`, `{hour}`, `{minute}`).
- [x] **Typography & Icon Families**: Gradient fills, outlines, drop shadows, custom `@fontsource` webfonts, and bundled Lucide, Phosphor, and Tabler icon catalogs.
- [x] **Dynamic Particle Emitters & 3D Cursor Parallax**: Configurable background particles (snow, stars, petals, bubbles, and floating embers) plus smooth cursor-driven 3D parallax depth for layers and backgrounds.
- [x] **Backup & Rollback System**: Automatic versioned theme snapshots with one-click restoration, plus security trust prompts for executable components.
### Discord Rich Presence Studio
- [x] **Dedicated Presence Editor Window**: In-app studio to customize your Discord presence.
- [x] **Interactive Discord Embed Preview**: Real-time visual mockup mirroring Discord's user profile popout card.
- [x] **Dynamic Placeholders**: Interpolate live stats (`{username}`, `{rank}`, `{pp}`, `{accuracy}`, `{playcount}`, `{version}`) into details, state, and asset tooltips.
- [x] **Custom Action Buttons & Presets**: Configurable buttons linking to player profiles, leaderboards, or custom URLs, plus quick presets (Default, Grinding, Competitive, Relax, AFK).
### Diagnostics, Logging & System Tools
- [x] **In-App Diagnostics Panel**: Validates osu! folder integrity, write permissions, Wine runtimes, .NET 8 desktop runtime, FFmpeg, and patcher status.
- [x] **Multi-Stream Log Viewer**: Dedicated rotating logs (`launcher.log`, `osu.log`, `patcher.log`) with session bundling, zip archive export, and an in-app viewer.
- [x] **macOS Wine Automation**: Automatic font registry sanitization (eliminating GDI+ `AccessViolationException` crashes), Wine prefix management, and automated in-place patcher bytecode patching for .NET 4.0 runtimes under Wine.
- [x] **Hardware-Accelerated Media Server**: Local HTTP range streaming server on macOS and Linux for smooth, low-memory WebM and MP4 video playback.
--- ---
## 💻 Supported Platforms ## 💻 Supported Platforms
| Platform | Status | | Platform | Status | Runtime / Environment |
| -------- | ------------------------------------------------------ | | -------- | ---------------------- | ---------------------------------------------------------- |
| Windows | ✅ Supported | | Windows | ✅ Supported | Native Win32 |
| macOS | 🕧 Partially supported (via Wineskin/Whisky/CrossOver) | | macOS | ✅ Supported | Wine wrapper (Wineskin, Whisky, CrossOver, or system Wine) |
| Linux | 🕧 Partially supported (via osu-winello) | | Linux | 🕧 Partially Supported | Wine / Proton (via osu-winello / wmctrl) |
> **Windows** remains the fully supported platform. OpenTabletDriver is Windows-only. On macOS, > **Windows** and **macOS** are fully supported. **Linux is partially supported**: osu! must be managed through external community tooling ([`osu-winello`](https://github.com/NelloKudo/osu-winello)), window tracking requires `wmctrl`, OpenTabletDriver automation is unavailable, and the launcher is restricted to the stable patcher stream.
> in-game patching runs the Windows patcher through the same Wine prefix as osu!. The stable
> patcher stream needs no extra runtime; the experimental stream needs the .NET 8 Desktop Runtime
> installed in that prefix.
### macOS
osu! stable is a Windows build, so on macOS it runs inside a Wine wrapper. EZPPLauncher
supports Wineskin wrappers (the usual `osu!.app` wine skin), Whisky bottles and CrossOver
bottles.
The setup wizard automatically looks for Wineskins in `/Applications` and `~/Applications`.
If detection fails, choose **Browse** and pick the `osu!.app` wrapper itself (or a Wine prefix
folder); the launcher resolves the osu! installation inside it, so there is no need to open the
bundle's package contents.
Large VP8/VP9/AV1 theme videos are transcoded once to a cached 720p H.264/AAC file so WebKit
can use the Mac's hardware decoder. The first large video triggers a one-time (~63 MB) download
of a signed static FFmpeg 9.0.2 build from `ffmpeg.martin-riedl.de` into `~/.ezpplauncher/bin`;
the launcher verifies its pinned SHA-256 and makes it executable. The managed build requires
macOS 12 or newer. If the download fails, a system FFmpeg (Homebrew or MacPorts) is used; without
either, themes still load but large WebM videos remain on WebKit's software decoder and may
stutter. Theme authors can also ship an H.264/MP4 version alongside the WebM.
--- ---
## 🪵 Logs ### 🍎 macOS Integration Details
Launcher, osu! and patcher output is written to `.ezpplauncher/logs` in your home folder: osu! stable is a 32-bit Windows application, so on macOS it runs inside a Wine-based wrapper. EZPPLauncher natively supports **Wineskin wrappers** (the standard `osu!.app` bundle), **Whisky bottles**, and **CrossOver bottles**.
| File | Contents | - **Automatic Wrapper Detection**: The setup wizard automatically searches `/Applications` and `~/Applications` for existing Wineskin bundles and Wine prefixes. If choosing **Browse**, selecting the `osu!.app` bundle directly resolves the underlying prefix without needing to navigate inside "Show Package Contents".
| -------------- | -------------------------------------------------------------- | - **Wine Prefix Font Fix**: macOS system font enumeration under Wine GDI+ can crash osu! on cold start with an `AccessViolationException` when reading Apple Braille fonts. EZPPLauncher automatically detects and cleans incompatible font entries from the prefix registry (`user.reg` / `system.reg`).
| `launcher.log` | Launcher lifecycle, webview console output and uncaught errors | - **Updater Loop Prevention**: Abnormal game exits can leave behind `.require_update`, `help.txt`, or `_pending` folders that cause `osu!.exe` to boot into the Bancho updater and lose command-line parameters. The launcher purges these markers before launch to ensure the `-devserver ez-pp.farm` flag is always preserved.
| `osu.log` | osu! and osu! updater output, including stdout/stderr | - **Automated Patcher Bytecode Patching**: The Windows patcher (`osu!.patcher.exe`) targets .NET 4.5+ and embeds `ManagedInjector.Lib`. In Wine prefixes using the .NET Framework 4.0 runtime, generic `Marshal.SizeOf<T>()` and `Marshal.PtrToStructure<T>()` methods do not exist, and redirected standard I/O causes `Console.ReadKey()` crashes. EZPPLauncher automatically inspects and patches the patcher binary and its embedded Costura assemblies in-place, enabling seamless injection into the running game process under Wine.
| `patcher.log` | Patcher output, including stdout/stderr | - **Hardware-Accelerated Theme Media**: Large VP8/VP9/AV1 theme videos are automatically transcoded to hardware-decoded H.264/AAC. The launcher manages a sandboxed static FFmpeg build in `~/.ezpplauncher/bin` (with fallback to system FFmpeg). Theme assets are served over an internal loopback server supporting HTTP range requests to minimize memory consumption.
- **Native macOS Window Rounding**: Native Cocoa window clipping applies rounded corners and transparent borders to the Tauri window.
A file is only created when that stream actually writes a line. On each new session, or when ---
any file reaches 5 MiB, all three active files are bundled into a single
`logs_<date>_<time>.zip`; the five most recent bundles are kept. You can turn file logging off,
open the folder, or browse and filter a bundle in the built-in viewer from **Settings → Logging**.
On Windows the folder is `%USERPROFILE%\.ezpplauncher\logs`.
**Settings → Diagnostics** checks the selected osu! install and write access, the macOS Wine ### 🐧 Linux (Partially Supported)
prefix/runtime/version and (for the experimental patcher stream) its .NET 8 runtime, the FFmpeg
theme-video transcoder, osu-winello/wmctrl on Linux, and whether the patcher is present. It can Linux support is functional but partial, relying on external community tools rather than built-in prefix management:
copy a plain-text support report or reopen the setup wizard for a guided repair.
- **External Tooling Requirements**:
- **[`osu-winello`](https://github.com/NelloKudo/osu-winello)**: osu! must be installed and managed through osu-winello. EZPPLauncher detects the `osu-wine` binary in standard search locations (`/usr/bin`, `/usr/local/bin`, and `~/.local/bin`).
- **`wmctrl`**: Required for game process discovery and active window title detection under X11 and XWayland (`sudo pacman -S wmctrl` on Arch or `sudo apt install wmctrl` on Debian/Ubuntu).
- **Feature Limitations**:
- **OpenTabletDriver**: Automated daemon start/stop is Windows-only. On Linux, run OpenTabletDriver as a user systemd service (`systemctl --user enable --now opentabletdriver.service`).
- **Patcher Stream**: Linux is constrained to the **stable** patcher stream. The experimental stream (.NET 8 runtime) is not supported on Linux.
- **Theme Streaming via Loopback**: Tauri uses WebKit2GTK on Linux, which does not support byte-range streaming over custom application URI schemes. EZPPLauncher automatically spins up an internal loopback HTTP server to stream large video/audio theme assets with low memory overhead.
---
## 🎮 Discord Rich Presence Studio
The launcher features an interactive Discord Rich Presence editor accessible from **Settings → Discord Presence**:
- **Live Profile Mockup**: Visualizes your presence card exactly as it appears inside Discord.
- **Stat Placeholders**: Insert live interpolated values:
- `{username}`: Player display name
- `{rank}`: Current global rank
- `{pp}`: Total performance points
- `{accuracy}`: Overall hit accuracy percentage
- `{playcount}`: Account playcount
- `{version}`: Active launcher version
- **Custom Buttons**: Add interactive links (e.g. your EZPPFarm profile or twitch stream).
- **Presence Presets**: One-click presets for default launcher idle, grinding, competitive matches, and relax sessions.
---
## 🎨 Launcher Theming
The launcher supports two theme generations:
- **Theme API 2.0 (Recommended)**: A declarative format described in `theme.json` with assets, audio, Lottie animations, and layered elements.
- Can be built and edited visually with the **in-app Theme Editor**.
- Supports custom **Svelte 5 component layers** with Monaco editor integration for rich interactive widgets.
- Features visual WHEN/IF/THEN rule building or sandboxed JavaScript scripting.
- Exported as shareable `.ezpplauncher-theme` zip archives.
- **Theme API 1.0**: Standalone bundled Svelte themes compiled via the CLI.
For detailed documentation, schemas, and packaging guides, refer to [THEME_API_V2.md](THEME_API_V2.md).
---
## 🪵 Logs & Diagnostics
Output from the launcher, osu!, and the patcher is organized under `.ezpplauncher/logs` in your user home directory (`%USERPROFILE%\.ezpplauncher\logs` on Windows, `~/.ezpplauncher/logs` on macOS and Linux):
| File | Source |
| -------------- | ------------------------------------------------------------------------- |
| `launcher.log` | Launcher lifecycle, backend commands, webview console and uncaught errors |
| `osu.log` | osu! game client and updater stdout/stderr |
| `patcher.log` | Patcher stdout/stderr and injection diagnostic messages |
- **Session Archiving**: When a new session begins or when any active log file reaches 5 MiB, the active logs are bundled into a compressed `logs_<date>_<time>.zip` archive. The 5 most recent archives are retained.
- **Built-in Log Viewer**: Browse, search, and filter session logs in real time from **Settings → Logging**.
- **System Diagnostics**: Open **Settings → Diagnostics** to run an automated check on your osu! installation, folder permissions, Wine prefix configuration, .NET runtimes, FFmpeg transcoder, and patcher files, with one-click report copying for troubleshooting.
--- ---
## 🛠 Build From Source ## 🛠 Build From Source
### Requirements ### Prerequisites
- **Rust** (installed via [rustup](https://rustup.rs/) – recommended for Windows) - **[Rust & Cargo](https://rustup.rs/)** (Rust 2024 edition)
- **Cargo** (comes with rustup) - **[Bun](https://bun.sh/)** (JavaScript runtime and package manager)
- **[CMake](https://cmake.org/download/)** - **[CMake](https://cmake.org/download/)**
- **[Bun](https://bun.sh/)** (JavaScript runtime) - Platform tooling:
- On macOS: **Xcode Command Line Tools** (`xcode-select --install`) - **Windows**: Visual Studio C++ Build Tools
- **macOS**: Xcode Command Line Tools (`xcode-select --install`)
- **Linux**: WebKit2GTK, libsoup, and standard build-essential packages
### Steps ### Build Steps
```bash ```bash
# Install all dependencies # 1. Clone the repository
bun i git clone https://git.ez-pp.farm/EZPPFarm/EZPPLauncher.git
cd EZPPLauncher
# Build the project # 2. Install dependencies
bun install
# 3. Type check and verify
bun run check
# 4. Build the release binaries
bun run build bun run build
``` ```
After building, the launcher executable will be located at: The compiled release packages will be generated at:
``` ```
# Windows # Windows
@@ -116,50 +177,69 @@ src-tauri/target/release/ezpplauncher.exe
# macOS # macOS
src-tauri/target/release/bundle/macos/EZPPLauncher.app src-tauri/target/release/bundle/macos/EZPPLauncher.app
src-tauri/target/release/bundle/dmg/EZPPLauncher_*.dmg src-tauri/target/release/bundle/dmg/EZPPLauncher_*.dmg
# Linux
src-tauri/target/release/bundle/deb/
src-tauri/target/release/bundle/appimage/
``` ```
### Cross-platform Releases
Use the release scripts to build a specific platform:
```bash
bun run release:macos
bun run release:windows
bun run release:linux
```
Windows installers can be cross-compiled from macOS with NSIS and `cargo-xwin`:
```bash
brew install nsis llvm cmake nasm ninja
rustup target add x86_64-pc-windows-msvc
cargo install --locked cargo-xwin
bun run release:windows
```
The Windows installer is written to
`src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/`. Cross-compiled
Windows builds are unsigned. macOS releases must be built on macOS, and Linux
releases must be built on Linux.
--- ---
## 📁 Project Structure (Simplified) ## 📁 Project Structure (Overview)
``` ```
├── src/ # Frontend (Svelte) EZPPLauncher/
├── src-tauri/ # Backend (Rust) ├── src/ # Frontend application (Svelte 5, Tailwind CSS)
│ ├── src/macos.rs # Wine/Wineskin support for macOS │ ├── lib/
│ ├── tauri.conf.json # Tauri configuration │ │ ├── components/
│ └── tauri.macos.conf.json # macOS bundle targets (app + dmg) │ │ │ ├── presence/ # Discord Rich Presence studio & preview
├── package.json # Bun project config │ │ │ ├── theme/ # In-app Theme Editor & visual inspectors
│ │ │ └── ui/ # Reusable UI controls, cursor & dialogs
│ │ ├── themeV2.ts # Theme API 2.0 runtime & parsing
│ │ └── osuUtil.ts # Game folder detection & system utilities
│ ├── routes/ # SvelteKit routing & main app views
│ └── screens/ # Launcher dashboard, setup wizard & loading
├── src-tauri/ # Backend core (Rust, Tauri v2)
│ ├── src/
│ │ ├── commands.rs # Tauri IPC invoke commands
│ │ ├── logging.rs # Multi-stream rotating logger & zip bundler
│ │ ├── macos.rs # macOS Wine/Wineskin runtime & font fixes
│ │ ├── theme_server.rs # Internal HTTP range server for theme media
│ │ └── utils.rs # Patcher .NET 4.0 bytecode compatibility engine
│ ├── Cargo.toml # Rust dependencies
│ ├── tauri.conf.json # Main Tauri configuration
│ └── tauri.macos.conf.json # macOS bundle configuration
├── THEME_API_V2.md # Theme API 2.0 schema specification
├── package.json # Bun project dependencies & scripts
└── README.md └── README.md
``` ```
--- ---
## 🎨 Launcher Themes ## 📄 License
By default, the launcher includes several downloadable themes. Themes can be created This project is licensed under the [GNU General Public License v3.0](LICENSE.md).
in two ways:
- Use the built-in **advanced editor** on the Themes screen. It opens in its own
resizable window with a full launcher home canvas, freeform text/image/video/shape
layers, custom Svelte 5 components with a Monaco editor, rich text effects
(gradient fills, outlines, shadows, decoration and case), WebM support,
`@fontsource` fonts and custom font imports. Themes can switch the launcher
chrome between the bundled Lucide, Phosphor and Tabler icon families. Hover a
layer and click a crumb in its group path (or double-click it), then use the
on-canvas frame or the inspector to move, rotate, scale or skew the group.
Logic rules can be linked to layers or groups and edited from their inspectors.
Any rule can switch from the visual builder to a sandboxed JavaScript script
with variables, expressions, `if/else`, `for`/`while`, visibility actions and
navigation; scripts open in a Monaco editor with syntax highlighting,
completion, hover docs and inline errors, and can expand to fullscreen. Text
layers can display live variables with `{name}` placeholders and theme-defined
starting values, plus read-only clock values such as `{time}` and `{hour}` that
refresh every second. Scripts are compiled into a safe instruction set and run by
the launcher without `eval`.
It creates API 2.0 themes and can export them as shareable
`.ezpplauncher-theme` files.
- Use the [create-ezpplauncher-theme](https://git.ez-pp.farm/EZPPFarm/create-ezpplauncher-theme)
CLI. It supports both API 1.0 Svelte themes and API 2.0 declarative themes.
See [THEME_API_V2.md](THEME_API_V2.md) for the full API 2.0 schema, limits and packaging
layout. API 1.0 themes continue to load unchanged.
+16 -2
View File
@@ -7,7 +7,9 @@ editor can create and edit these themes without writing code. Themes can opt int
custom **Svelte layer** when they need behavior that data alone cannot express; that custom **Svelte layer** when they need behavior that data alone cannot express; that
layer runs theme-authored JavaScript and therefore needs an explicit trust prompt. layer runs theme-authored JavaScript and therefore needs an explicit trust prompt.
API 1.0 themes continue to work unchanged. Pick the API that fits the theme: API 1.0 themes still work when they are already installed or installed manually from a
`.ezpplauncher-theme` file, but they can no longer be uploaded to the Community Themes
Workshop. Workshop uploads accept API 2.0 only. Pick the API that fits the theme:
| | API 1.0 | API 2.0 | | | API 1.0 | API 2.0 |
| ----------------------- | ------------------------------------------------- | ---------------------------------------------- | | ----------------------- | ------------------------------------------------- | ---------------------------------------------- |
@@ -196,12 +198,24 @@ clamped to `0`–`1`.
{ "type": "stars", "density": 40, "speed": 1, "color": "#ffd6f2" } { "type": "stars", "density": 40, "speed": 1, "color": "#ffd6f2" }
``` ```
Supported types: `none`, `stars`, `snow`, `petals`, `bubbles`. Supported types: `none`, `stars`, `snow`, `petals`, `bubbles`, `embers`.
- `density` is clamped to `0`–`120` particles. - `density` is clamped to `0`–`120` particles.
- `speed` is clamped to `0.2`–`3`. - `speed` is clamped to `0.2`–`3`.
- Effects are disabled when the user turns on **Reduce animations**. - Effects are disabled when the user turns on **Reduce animations**.
### Parallax
Themes can enable subtle 3D cursor parallax on the background and freeform layers:
```json
"parallax": { "enabled": true, "intensity": 0.25 }
```
- `intensity` is clamped to `0.05`–`1.0` (defaults to `0.25`).
- Individual layers and groups can define their own `parallax` depth factor from `-2.0` to `+2.0` in the inspector (where negative shifts with background and positive shifts with foreground).
- Parallax is automatically disabled when the user turns on **Reduce animations**.
### Audio ### Audio
```json ```json
+1
View File
@@ -44,6 +44,7 @@ export default ts.config(
{ {
rules: { rules: {
'no-empty': 'off', 'no-empty': 'off',
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/no-unused-vars': [ '@typescript-eslint/no-unused-vars': [
'error', 'error',
{ argsIgnorePattern: '^_', varsIgnorePattern: '^\\$\\$(Props|Events|Slots|Generic)$' }, { argsIgnorePattern: '^_', varsIgnorePattern: '^\\$\\$(Props|Events|Slots|Generic)$' },
+5 -2
View File
@@ -1,11 +1,14 @@
{ {
"name": "ezpplauncher", "name": "ezpplauncher",
"version": "3.2.7", "version": "3.3.0",
"description": "", "description": "",
"type": "module", "type": "module",
"scripts": { "scripts": {
"debug": "bun run tauri dev", "debug": "bun run tauri dev",
"build": "bun ./scripts/build.ts", "release": "bun ./scripts/release.ts",
"release:macos": "bun ./scripts/release.ts macos",
"release:windows": "bun ./scripts/release.ts windows",
"release:linux": "bun ./scripts/release.ts linux",
"vite:dev": "vite dev", "vite:dev": "vite dev",
"vite:build": "vite build && exit 0", "vite:build": "vite build && exit 0",
"tauri:build": "tauri build", "tauri:build": "tauri build",
-40
View File
@@ -1,40 +0,0 @@
import { spawn } from 'child_process';
function runVite(): Promise<void> {
return new Promise((resolve, reject) => {
const proc = spawn('bunx', ['--bun', 'vite', 'build'], { stdio: ['inherit', 'pipe', 'pipe'] });
proc.stdout?.on('data', (data: Buffer) => {
process.stdout.write(data);
if (data.toString().includes('✔ done')) {
setTimeout(() => {
proc.kill();
resolve();
}, 500);
}
});
proc.stderr?.on('data', (data: Buffer) => process.stderr.write(data));
proc.on('close', (code) => {
if (code === 0 || code === null) resolve();
else reject(new Error(`vite build exited with code ${code}`));
});
});
}
function run(cmd: string, args: string[]): Promise<void> {
return new Promise((resolve, reject) => {
const proc = spawn(cmd, args, { stdio: 'inherit' });
proc.on('close', (code) => {
if (code === 0) resolve();
else reject(new Error(`${cmd} exited with code ${code}`));
});
});
}
await run('bun', ['./scripts/sync-version.ts']);
await runVite();
//set NO_STRIP=1 in env for linux to prevent stripping of debug symbols in tauri builds, which causes issues with source maps
if (process.platform === 'linux') process.env.NO_STRIP = '1';
await run('bunx', ['tauri', 'build']);
+6 -2
View File
@@ -1,4 +1,8 @@
import { THEME_ICON_NAMES, type ThemeIconName, type ThemeIconSet } from '../src/lib/themeIcons'; import {
THEME_ICON_NAMES,
type ThemeIconName,
type ThemeIconSet,
} from '../src/lib/theme/themeIcons';
import { readFileSync, writeFileSync } from 'node:fs'; import { readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
@@ -135,7 +139,7 @@ export const THEME_ICON_BODIES: Record<ThemeIconSet, Record<ThemeIconName, Theme
)}; )};
`; `;
const outputPath = fileURLToPath(new URL('../src/lib/themeIconData.ts', import.meta.url)); const outputPath = fileURLToPath(new URL('../src/lib/theme/themeIconData.ts', import.meta.url));
writeFileSync(outputPath, output); writeFileSync(outputPath, output);
console.log( console.log(
`Generated ${THEME_ICON_NAMES.length} semantic icons for ${Object.keys(collectionPaths).length} sets.` `Generated ${THEME_ICON_NAMES.length} semantic icons for ${Object.keys(collectionPaths).length} sets.`
+301
View File
@@ -0,0 +1,301 @@
import { spawn, execFileSync } from 'node:child_process';
import { accessSync, constants, existsSync } from 'node:fs';
import path from 'node:path';
const WINDOWS_TARGET = 'x86_64-pc-windows-msvc';
const TARGETS = ['macos', 'windows', 'linux'] as const;
type Target = (typeof TARGETS)[number];
function hostTarget(): Target {
if (process.platform === 'darwin') return 'macos';
if (process.platform === 'win32') return 'windows';
if (process.platform === 'linux') return 'linux';
throw new Error(`Unsupported build host: ${process.platform}`);
}
function findCommand(command: string, envPath: string): string | undefined {
const extensions =
process.platform === 'win32'
? ['', ...(process.env.PATHEXT ?? '.EXE;.CMD;.BAT').split(';')]
: [''];
for (const directory of envPath.split(path.delimiter)) {
if (!directory) continue;
for (const extension of extensions) {
const candidate = path.join(directory, `${command}${extension.toLowerCase()}`);
try {
accessSync(candidate, constants.X_OK);
return candidate;
} catch {
// Keep looking through PATH.
}
}
}
}
function prependExistingPath(env: NodeJS.ProcessEnv, directory: string) {
if (existsSync(directory)) env.PATH = `${directory}${path.delimiter}${env.PATH ?? ''}`;
}
function ensureUtf8Locale(env: NodeJS.ProcessEnv) {
const current = env.LC_ALL || env.LC_CTYPE || env.LANG || '';
if (current && current !== 'C' && current !== 'POSIX') return;
// makeNSIS 3.13 crashes with std::bad_alloc on POSIX under the C locale.
const locale = process.platform === 'darwin' ? 'en_US.UTF-8' : 'C.UTF-8';
env.LC_ALL = locale;
env.LANG = locale;
}
function selectRustupToolchain(env: NodeJS.ProcessEnv) {
const rustup =
findCommand('rustup', env.PATH ?? '') ??
['/opt/homebrew/opt/rustup/bin/rustup', '/usr/local/opt/rustup/bin/rustup'].find((candidate) =>
existsSync(candidate)
);
if (!rustup) return;
try {
const cargo = execFileSync(rustup, ['which', 'cargo'], {
encoding: 'utf8',
env,
stdio: ['ignore', 'pipe', 'ignore'],
}).trim();
env.PATH = `${path.dirname(cargo)}${path.delimiter}${env.PATH ?? ''}`;
if (process.platform === 'darwin') {
const libDir = path.join(path.dirname(path.dirname(cargo)), 'lib');
env.DYLD_FALLBACK_LIBRARY_PATH = [libDir, env.DYLD_FALLBACK_LIBRARY_PATH]
.filter(Boolean)
.join(path.delimiter);
}
} catch {
// Fall back to the cargo already on PATH.
}
}
function hasRustTarget(target: string, env: NodeJS.ProcessEnv): boolean {
try {
const libdir = execFileSync('rustc', ['--print', 'target-libdir', '--target', target], {
encoding: 'utf8',
env,
stdio: ['ignore', 'pipe', 'ignore'],
}).trim();
return existsSync(libdir);
} catch {
return false;
}
}
function configureCrossWindowsLinker(env: NodeJS.ProcessEnv) {
// Microsoft's prebuilt CRT libraries reference PDBs that are not shipped
// with cargo-xwin, so lld-link emits LNK4099 for every library. The debug
// info is unavailable either way, so suppress only that specific warning.
const key = 'CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS';
env[key] = [env[key], '-C', 'link-arg=/ignore:4099'].filter(Boolean).join(' ');
}
function windowsPrerequisites(env: NodeJS.ProcessEnv): string[] {
const missing: string[] = [];
if (!findCommand('cargo-xwin', env.PATH ?? '')) {
missing.push('cargo-xwin (install with: cargo install --locked cargo-xwin)');
}
if (!findCommand('cmake', env.PATH ?? '')) {
missing.push(
process.platform === 'darwin'
? 'CMake (install with: brew install cmake)'
: 'CMake (install cmake and add it to PATH)'
);
}
if (!findCommand('nasm', env.PATH ?? '')) {
missing.push(
process.platform === 'darwin'
? 'NASM (install with: brew install nasm)'
: 'NASM (install nasm and add it to PATH)'
);
}
if (!findCommand('ninja', env.PATH ?? '')) {
missing.push(
process.platform === 'darwin'
? 'Ninja (install with: brew install ninja)'
: 'Ninja (install ninja and add it to PATH)'
);
}
if (!hasRustTarget(WINDOWS_TARGET, env)) {
missing.push(
`${WINDOWS_TARGET} Rust target (install with: rustup target add ${WINDOWS_TARGET})`
);
}
if (process.platform !== 'win32') {
if (!findCommand('llvm-rc', env.PATH ?? '')) {
missing.push(
process.platform === 'darwin'
? 'LLVM (install with: brew install llvm, then add its bin directory to PATH)'
: 'LLVM (install llvm and lld, then add llvm-rc to PATH)'
);
}
if (!findCommand('makensis', env.PATH ?? '')) {
missing.push(
process.platform === 'darwin'
? 'NSIS (install with: brew install nsis)'
: 'NSIS (install makensis and add it to PATH)'
);
}
}
return missing;
}
function artifactDirectory(target: Target): string {
if (target === 'windows') {
const suffix =
process.platform === 'win32'
? path.join('target', 'release')
: path.join('target', WINDOWS_TARGET, 'release');
return path.join('src-tauri', suffix, 'bundle', 'nsis');
}
if (target === 'macos') return path.join('src-tauri', 'target', 'release', 'bundle');
return path.join('src-tauri', 'target', 'release', 'bundle');
}
function run(command: string, args: string[], env: NodeJS.ProcessEnv): Promise<void> {
console.log(`\n$ ${[command, ...args].join(' ')}`);
return new Promise((resolve, reject) => {
const child = spawn(command, args, { env, stdio: 'inherit' });
child.on('error', reject);
child.on('close', (code) => {
if (code === 0) resolve();
else reject(new Error(`${command} exited with code ${code ?? 'unknown'}`));
});
});
}
/**
* Vite's static-adapter build can leave the process alive after writing the
* output. Stop it once the adapter confirms the build is complete.
*/
function buildFrontend(command: string, env: NodeJS.ProcessEnv): Promise<void> {
console.log(`\n$ ${command} x --bun vite build`);
return new Promise((resolve, reject) => {
const child = spawn(command, ['x', '--bun', 'vite', 'build'], {
env,
stdio: ['inherit', 'pipe', 'pipe'],
});
let completed = false;
const finish = (error?: Error) => {
if (completed) return;
completed = true;
if (error) reject(error);
else resolve();
};
child.stdout?.on('data', (data: Buffer) => {
process.stdout.write(data);
if (!completed && data.toString().includes('✔ done')) {
setTimeout(() => {
child.kill();
finish();
}, 500);
}
});
child.stderr?.on('data', (data: Buffer) => process.stderr.write(data));
child.on('error', finish);
child.on('close', (code) => {
if (code === 0) finish();
else finish(new Error(`vite build exited with code ${code ?? 'unknown'}`));
});
});
}
function usage() {
console.log(`Build an EZPPLauncher release.
Usage:
bun run release Build for the current platform
bun run release:macos Build the macOS app and DMG
bun run release:windows Build the Windows NSIS installer
bun run release:linux Build the Linux package
On macOS, release:windows cross-compiles using cargo-xwin. On Linux, use
release:linux on a Linux host; Linux bundles cannot be built from macOS.`);
}
const requested = process.argv[2]?.toLowerCase();
if (requested === '--help' || requested === '-h') {
usage();
process.exit(0);
}
let target: Target;
try {
target = requested ? (requested as Target) : hostTarget();
} catch (error) {
console.error(error instanceof Error ? error.message : error);
process.exit(1);
}
if (!TARGETS.includes(target)) {
console.error(`Unknown release target: ${requested}`);
usage();
process.exit(1);
}
const host = hostTarget();
if (target === 'macos' && host !== 'macos') {
console.error('macOS releases must be built on macOS.');
process.exit(1);
}
if (target === 'linux' && host !== 'linux') {
console.error('Linux releases must be built on Linux. Use a Linux host or CI runner.');
process.exit(1);
}
const env = { ...process.env };
if (host === 'macos') {
prependExistingPath(env, '/opt/homebrew/opt/llvm/bin');
prependExistingPath(env, '/usr/local/opt/llvm/bin');
prependExistingPath(env, '/opt/homebrew/opt/nsis/bin');
prependExistingPath(env, '/usr/local/opt/nsis/bin');
}
if (host !== 'windows') ensureUtf8Locale(env);
if (target === 'windows') selectRustupToolchain(env);
if (target === 'windows' && host !== 'windows') {
const missing = windowsPrerequisites(env);
if (missing.length > 0) {
console.error('Windows cross-compilation is missing prerequisites:\n');
for (const requirement of missing) console.error(` - ${requirement}`);
process.exit(1);
}
configureCrossWindowsLinker(env);
}
const tauriArgs = ['x', 'tauri', 'build'];
if (target === 'windows') {
tauriArgs.push('--bundles', 'nsis');
if (host !== 'windows') tauriArgs.push('--runner', 'cargo-xwin', '--target', WINDOWS_TARGET);
}
const bun = findCommand('bun', env.PATH ?? '') ?? 'bun';
console.log(`Building the ${target} release from ${host}...`);
try {
await run(bun, ['./scripts/sync-version.ts'], env);
await buildFrontend(bun, env);
if (target === 'linux') env.NO_STRIP = '1';
await run(bun, tauriArgs, env);
console.log(`\n✅ ${target} release built.`);
console.log(`Artifacts: ${artifactDirectory(target)}`);
} catch (error) {
console.error(`\n❌ Release build failed: ${error instanceof Error ? error.message : error}`);
process.exit(1);
}
+2 -1
View File
@@ -1266,12 +1266,13 @@ dependencies = [
[[package]] [[package]]
name = "ezpplauncher" name = "ezpplauncher"
version = "3.2.7" version = "3.3.0"
dependencies = [ dependencies = [
"aes-gcm", "aes-gcm",
"anyhow", "anyhow",
"base64 0.22.1", "base64 0.22.1",
"byteorder", "byteorder",
"flate2",
"futures-util", "futures-util",
"hardware-id", "hardware-id",
"hex", "hex",
+2 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "ezpplauncher" name = "ezpplauncher"
version = "3.2.7" version = "3.3.0"
description = "EZPPLauncher redefined." description = "EZPPLauncher redefined."
authors = ["HorizonCode"] authors = ["HorizonCode"]
edition = "2024" edition = "2024"
@@ -56,6 +56,7 @@ aes-gcm = "0.10.3"
base64 = "0.22.1" base64 = "0.22.1"
sha2 = "0.11.0" sha2 = "0.11.0"
thiserror = "2.0.18" thiserror = "2.0.18"
flate2 = "1.0"
tauri-plugin-log = "2" tauri-plugin-log = "2"
log = "0.4" log = "0.4"
time = { version = "0.3", features = ["local-offset"] } time = { version = "0.3", features = ["local-offset"] }
+155
View File
@@ -32,6 +32,21 @@
}, },
{ {
"path": "$HOME/.ezpplauncher/**/*" "path": "$HOME/.ezpplauncher/**/*"
},
{
"path": "$HOME/.ezpplauncher/**/.*"
},
{
"path": "$HOME/.ezpplauncher/**/.*/**"
},
{
"path": "$TEMP"
},
{
"path": "$TEMP/*"
},
{
"path": "$TEMP/**/*"
} }
] ]
}, },
@@ -46,6 +61,21 @@
}, },
{ {
"path": "$HOME/.ezpplauncher/**/*" "path": "$HOME/.ezpplauncher/**/*"
},
{
"path": "$HOME/.ezpplauncher/**/.*"
},
{
"path": "$HOME/.ezpplauncher/**/.*/**"
},
{
"path": "$TEMP"
},
{
"path": "$TEMP/*"
},
{
"path": "$TEMP/**/*"
} }
] ]
}, },
@@ -60,6 +90,21 @@
}, },
{ {
"path": "$HOME/.ezpplauncher/**/*" "path": "$HOME/.ezpplauncher/**/*"
},
{
"path": "$HOME/.ezpplauncher/**/.*"
},
{
"path": "$HOME/.ezpplauncher/**/.*/**"
},
{
"path": "$TEMP"
},
{
"path": "$TEMP/*"
},
{
"path": "$TEMP/**/*"
} }
] ]
}, },
@@ -74,6 +119,21 @@
}, },
{ {
"path": "$HOME/.ezpplauncher/**/*" "path": "$HOME/.ezpplauncher/**/*"
},
{
"path": "$HOME/.ezpplauncher/**/.*"
},
{
"path": "$HOME/.ezpplauncher/**/.*/**"
},
{
"path": "$TEMP"
},
{
"path": "$TEMP/*"
},
{
"path": "$TEMP/**/*"
} }
] ]
}, },
@@ -88,6 +148,21 @@
}, },
{ {
"path": "$HOME/.ezpplauncher/**/*" "path": "$HOME/.ezpplauncher/**/*"
},
{
"path": "$HOME/.ezpplauncher/**/.*"
},
{
"path": "$HOME/.ezpplauncher/**/.*/**"
},
{
"path": "$TEMP"
},
{
"path": "$TEMP/*"
},
{
"path": "$TEMP/**/*"
} }
] ]
}, },
@@ -102,6 +177,41 @@
}, },
{ {
"path": "$HOME/.ezpplauncher/**/*" "path": "$HOME/.ezpplauncher/**/*"
},
{
"path": "$HOME/.ezpplauncher/**/.*"
},
{
"path": "$HOME/.ezpplauncher/**/.*/**"
},
{
"path": "$TEMP"
},
{
"path": "$TEMP/*"
},
{
"path": "$TEMP/**/*"
}
]
},
{
"identifier": "fs:allow-stat",
"allow": [
{
"path": "$HOME/.ezpplauncher"
},
{
"path": "$HOME/.ezpplauncher/*"
},
{
"path": "$HOME/.ezpplauncher/**/*"
},
{
"path": "$HOME/.ezpplauncher/**/.*"
},
{
"path": "$HOME/.ezpplauncher/**/.*/**"
} }
] ]
}, },
@@ -116,6 +226,21 @@
}, },
{ {
"path": "$HOME/.ezpplauncher/**/*" "path": "$HOME/.ezpplauncher/**/*"
},
{
"path": "$HOME/.ezpplauncher/**/.*"
},
{
"path": "$HOME/.ezpplauncher/**/.*/**"
},
{
"path": "$TEMP"
},
{
"path": "$TEMP/*"
},
{
"path": "$TEMP/**/*"
} }
] ]
}, },
@@ -130,6 +255,21 @@
}, },
{ {
"path": "$HOME/.ezpplauncher/**/*" "path": "$HOME/.ezpplauncher/**/*"
},
{
"path": "$HOME/.ezpplauncher/**/.*"
},
{
"path": "$HOME/.ezpplauncher/**/.*/**"
},
{
"path": "$TEMP"
},
{
"path": "$TEMP/*"
},
{
"path": "$TEMP/**/*"
} }
] ]
}, },
@@ -144,6 +284,21 @@
}, },
{ {
"path": "$HOME/.ezpplauncher/**/*" "path": "$HOME/.ezpplauncher/**/*"
},
{
"path": "$HOME/.ezpplauncher/**/.*"
},
{
"path": "$HOME/.ezpplauncher/**/.*/**"
},
{
"path": "$TEMP"
},
{
"path": "$TEMP/*"
},
{
"path": "$TEMP/**/*"
} }
] ]
} }
+613 -115
View File
@@ -3,7 +3,7 @@ use hardware_id::get_id;
use reqwest::Client; use reqwest::Client;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
use std::collections::HashSet; use std::collections::{HashMap, HashSet};
use std::io::Read; use std::io::Read;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
#[cfg(not(target_os = "macos"))] #[cfg(not(target_os = "macos"))]
@@ -86,11 +86,186 @@ pub fn file_size(path: String) -> Option<u64> {
metadata.is_file().then_some(metadata.len()) metadata.is_file().then_some(metadata.len())
} }
/// Calculate the SHA-256 checksum of a file on disk.
#[tauri::command]
pub async fn hash_file_sha256(path: String) -> Result<String, String> {
use sha2::{Digest, Sha256};
use std::io::Read;
tokio::task::spawn_blocking(move || {
let mut file = std::fs::File::open(&path)
.map_err(|e| format!("Failed to open file for hashing: {e}"))?;
let mut hasher = Sha256::new();
let mut buffer = [0u8; 65536];
loop {
let bytes_read = file
.read(&mut buffer)
.map_err(|e| format!("Failed to read file for hashing: {e}"))?;
if bytes_read == 0 {
break;
}
hasher.update(&buffer[..bytes_read]);
}
Ok::<_, String>(hex::encode(hasher.finalize()))
})
.await
.map_err(|e| format!("Thread error: {e}"))?
}
/// Hash the files that make up a theme package. This ignores archive metadata
/// and the local workshop-sync sidecar, so it can be compared before and after
/// editing the theme folder.
#[tauri::command]
pub async fn hash_theme_content(theme_folder: String) -> Result<String, String> {
use sha2::{Digest, Sha256};
let folder = checked_theme_folder(&theme_folder)?;
tokio::task::spawn_blocking(move || {
let asset_filter = referenced_theme_assets(&folder.join("theme.json"));
let mut files = Vec::new();
collect_theme_content_files(&folder, &folder, asset_filter.as_ref(), &mut files)?;
files.sort_by_key(|path| path.to_string_lossy().to_lowercase());
let mut hasher = Sha256::new();
hasher.update(b"ezpplauncher-theme-content-v1\0");
for relative in files {
let path = folder.join(&relative);
let metadata = std::fs::metadata(&path)
.map_err(|e| format!("Failed to inspect theme file {}: {e}", path.display()))?;
if !metadata.is_file() {
continue;
}
let name = relative.to_string_lossy().replace('\\', "/");
hasher.update((name.len() as u64).to_le_bytes());
hasher.update(name.as_bytes());
// Workshop metadata is not theme content. Ignore it so syncing
// tags or the server-assigned ID does not look like a local edit.
if name == "theme.json" {
let text = std::fs::read_to_string(&path).map_err(|e| {
format!("Failed to read theme manifest {}: {e}", path.display())
})?;
let mut config: Value = serde_json::from_str(&text)
.map_err(|e| format!("Failed to parse theme manifest: {e}"))?;
if let Some(object) = config.as_object_mut() {
object.remove("workshopId");
object.remove("tags");
}
let bytes = serde_json::to_vec(&config)
.map_err(|e| format!("Failed to serialize theme manifest: {e}"))?;
hasher.update((bytes.len() as u64).to_le_bytes());
hasher.update(&bytes);
continue;
}
hasher.update(metadata.len().to_le_bytes());
let mut file = std::fs::File::open(&path)
.map_err(|e| format!("Failed to open theme file {}: {e}", path.display()))?;
let mut buffer = [0u8; 65536];
loop {
let bytes_read = file
.read(&mut buffer)
.map_err(|e| format!("Failed to read theme file {}: {e}", path.display()))?;
if bytes_read == 0 {
break;
}
hasher.update(&buffer[..bytes_read]);
}
}
Ok::<_, String>(hex::encode(hasher.finalize()))
})
.await
.map_err(|e| format!("Thread error: {e}"))?
}
fn collect_theme_content_files(
root: &Path,
directory: &Path,
asset_filter: Option<&HashSet<String>>,
files: &mut Vec<PathBuf>,
) -> Result<(), String> {
let entries = std::fs::read_dir(directory)
.map_err(|e| format!("Failed to read {}: {e}", directory.display()))?;
let assets_root = root.join("assets");
for entry in entries {
let entry = entry.map_err(|e| format!("Failed to read theme entry: {e}"))?;
let file_name = entry.file_name();
if file_name.to_string_lossy().starts_with('.') {
continue;
}
let file_type = entry
.file_type()
.map_err(|e| format!("Failed to inspect theme entry: {e}"))?;
if file_type.is_symlink() {
continue;
}
let entry_path = entry.path();
let relative = entry_path
.strip_prefix(root)
.map_err(|e| format!("Failed to build theme path: {e}"))?
.to_string_lossy()
.replace('\\', "/");
if file_type.is_dir() {
if asset_filter.is_some() && directory == root && relative != "assets" {
continue;
}
collect_theme_content_files(root, &entry_path, asset_filter, files)?;
continue;
}
if !file_type.is_file() {
continue;
}
if asset_filter.is_some() && directory == root && relative != "theme.json" {
continue;
}
if let Some(filter) = asset_filter
&& let Ok(asset_path) = entry_path.strip_prefix(&assets_root)
{
let key = asset_path.to_string_lossy().replace('\\', "/");
if !filter.contains(&key) {
continue;
}
}
files.push(PathBuf::from(relative));
}
Ok(())
}
/// Read a chunk of a file on disk starting at `offset` for `length` bytes.
#[tauri::command]
pub async fn read_file_chunk(path: String, offset: u64, length: u64) -> Result<Vec<u8>, String> {
use std::io::{Read, Seek, SeekFrom};
tokio::task::spawn_blocking(move || {
let mut file = std::fs::File::open(&path)
.map_err(|e| format!("Failed to open file for chunk read: {e}"))?;
file.seek(SeekFrom::Start(offset))
.map_err(|e| format!("Failed to seek to offset {offset}: {e}"))?;
let mut buffer = vec![0u8; length as usize];
let bytes_read = file
.read(&mut buffer)
.map_err(|e| format!("Failed to read chunk bytes: {e}"))?;
buffer.truncate(bytes_read);
Ok::<_, String>(buffer)
})
.await
.map_err(|e| format!("Thread error: {e}"))?
}
#[tauri::command] #[tauri::command]
pub fn get_hwid() -> String { pub fn get_hwid() -> String {
get_id() get_id().unwrap_or("recorderinsandybridge".to_string())
.unwrap_or("recorderinsandybridge".to_string())
.into()
} }
/// Show the native macOS picker, which can select `osu!.app` bundles as files. /// Show the native macOS picker, which can select `osu!.app` bundles as files.
@@ -222,6 +397,8 @@ pub async fn installation_diagnostics(app: AppHandle, folder: String) -> Install
.map(patcher_file_stats) .map(patcher_file_stats)
.unwrap_or_default(); .unwrap_or_default();
// macOS fills in the Wine and FFmpeg fields below.
#[cfg_attr(not(target_os = "macos"), allow(unused_mut))]
let mut diagnostics = InstallationDiagnostics { let mut diagnostics = InstallationDiagnostics {
platform: std::env::consts::OS.to_string(), platform: std::env::consts::OS.to_string(),
os_version: System::long_os_version(), os_version: System::long_os_version(),
@@ -374,18 +551,18 @@ pub async fn get_skins_count(folder: String) -> Option<u64> {
let mut count = 0; let mut count = 0;
if let Ok(mut entries) = fs::read_dir(skins_folder).await { if let Ok(mut entries) = fs::read_dir(skins_folder).await {
while let Ok(Some(entry)) = entries.next_entry().await { while let Ok(Some(entry)) = entries.next_entry().await {
if let Ok(ft) = entry.file_type().await { if let Ok(ft) = entry.file_type().await
if ft.is_dir() { && ft.is_dir()
let dir_path = entry.path(); {
let has_ini = tokio::fs::try_exists(dir_path.join("skin.ini")) let dir_path = entry.path();
let has_ini = tokio::fs::try_exists(dir_path.join("skin.ini"))
.await
.unwrap_or(false)
|| tokio::fs::try_exists(dir_path.join("Skin.ini"))
.await .await
.unwrap_or(false) .unwrap_or(false);
|| tokio::fs::try_exists(dir_path.join("Skin.ini")) if has_ini {
.await count += 1;
.unwrap_or(false);
if has_ini {
count += 1;
}
} }
} }
} }
@@ -561,12 +738,17 @@ pub async fn run_osu_updater(folder: String) -> Result<(), String> {
} }
#[tauri::command] #[tauri::command]
pub async fn run_osu(folder: String, patch: bool) -> Result<(), String> { pub async fn run_osu(
log::info!(target: "osu", "Launching osu! from {folder} (patch={patch})"); folder: String,
patch: bool,
game_optimization: Option<bool>,
) -> Result<(), String> {
let optimize = game_optimization.unwrap_or(false);
log::info!(target: "osu", "Launching osu! from {folder} (patch={patch}, optimize={optimize})");
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
{ {
return crate::macos::run_osu(&folder, patch).await; return crate::macos::run_osu(&folder, patch, optimize).await;
} }
#[cfg(not(target_os = "macos"))] #[cfg(not(target_os = "macos"))]
@@ -576,6 +758,18 @@ pub async fn run_osu(folder: String, patch: bool) -> Result<(), String> {
#[cfg(windows)] #[cfg(windows)]
const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200; const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
#[cfg(windows)]
if optimize {
#[link(name = "winmm")]
unsafe extern "system" {
fn timeBeginPeriod(uPeriod: u32) -> u32;
}
unsafe {
timeBeginPeriod(1);
}
log::info!(target: "osu", "Game optimization: requested 1ms timer resolution");
}
let mut game_process = { let mut game_process = {
#[cfg(windows)] #[cfg(windows)]
{ {
@@ -613,6 +807,22 @@ pub async fn run_osu(folder: String, patch: bool) -> Result<(), String> {
if let Some(pid) = game_process.id() { if let Some(pid) = game_process.id() {
log::info!(target: "osu", "osu! started (pid {pid})"); log::info!(target: "osu", "osu! started (pid {pid})");
#[cfg(windows)]
if optimize {
unsafe {
use winapi::um::processthreadsapi::{OpenProcess, SetPriorityClass};
use winapi::um::winbase::HIGH_PRIORITY_CLASS;
use winapi::um::winnt::PROCESS_SET_INFORMATION;
let handle = OpenProcess(PROCESS_SET_INFORMATION, 0, pid);
if !handle.is_null() {
if SetPriorityClass(handle, HIGH_PRIORITY_CLASS) != 0 {
log::info!(target: "osu", "Game optimization: boosted osu! process priority to High (pid {pid})");
}
winapi::um::handleapi::CloseHandle(handle);
}
}
}
} }
crate::logging::capture_osu_output(&mut game_process); crate::logging::capture_osu_output(&mut game_process);
@@ -693,7 +903,21 @@ pub async fn run_osu(folder: String, patch: bool) -> Result<(), String> {
} }
} }
match game_process.wait().await { let wait_res = game_process.wait().await;
#[cfg(windows)]
if optimize {
#[link(name = "winmm")]
unsafe extern "system" {
fn timeEndPeriod(uPeriod: u32) -> u32;
}
unsafe {
timeEndPeriod(1);
}
log::info!(target: "osu", "Game optimization: restored timer resolution");
}
match wait_res {
Ok(status) => log::info!(target: "osu", "osu! exited with {status}"), Ok(status) => log::info!(target: "osu", "osu! exited with {status}"),
Err(error) => { Err(error) => {
log::warn!(target: "osu", "Could not wait for osu!: {error}"); log::warn!(target: "osu", "Could not wait for osu!: {error}");
@@ -742,7 +966,11 @@ pub async fn get_ezpp_launcher_update_files(
if file_path.exists() { if file_path.exists() {
let data = fs::read(&file_path).await.map_err(|e| e.to_string())?; let data = fs::read(&file_path).await.map_err(|e| e.to_string())?;
let hash = format!("{:x}", md5::compute(&data)); let hash = format!("{:x}", md5::compute(&data));
if hash.to_lowercase() != file.md5.to_lowercase() { let matches = hash.eq_ignore_ascii_case(&file.md5)
|| (cfg!(target_os = "macos")
&& file.name == "osu!.patcher.exe"
&& crate::utils::is_compatible_patcher(&data));
if !matches {
files_to_download.push(file.clone()); files_to_download.push(file.clone());
} }
} else { } else {
@@ -834,6 +1062,17 @@ pub async fn download_ezpp_launcher_update_files(
} }
} }
#[cfg(target_os = "macos")]
{
let patcher_exe = osu_path
.join("EZPPLauncher")
.join("patcher")
.join("osu!.patcher.exe");
if patcher_exe.is_file() {
let _ = crate::utils::ensure_patcher_compatibility(&patcher_exe);
}
}
Ok(()) Ok(())
} }
@@ -1090,24 +1329,24 @@ pub struct PresenceButton {
#[derive(Deserialize)] #[derive(Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct PresenceActivityPayload { pub struct PresenceActivityPayload {
pub state: Option<String>, pub state: String,
pub details: Option<String>, pub details: String,
pub large_image_key: Option<String>, pub large_image_key: String,
pub large_image_text: Option<String>, pub large_image_text: String,
pub small_image_key: Option<Option<String>>, pub small_image_key: Option<String>,
pub small_image_text: Option<Option<String>>, pub small_image_text: Option<String>,
pub button1: Option<Option<presence::PresenceButton>>, pub button1: Option<presence::PresenceButton>,
pub button2: Option<Option<presence::PresenceButton>>, pub button2: Option<presence::PresenceButton>,
pub show_timestamp: Option<bool>, pub show_timestamp: bool,
} }
#[tauri::command] #[tauri::command]
pub async fn presence_update_activity(activity: PresenceActivityPayload) { pub async fn presence_update_activity(activity: PresenceActivityPayload) {
presence::update_activity( presence::update_activity(
activity.state.as_deref(), &activity.state,
activity.details.as_deref(), &activity.details,
activity.large_image_key.as_deref(), &activity.large_image_key,
activity.large_image_text.as_deref(), &activity.large_image_text,
activity.small_image_key, activity.small_image_key,
activity.small_image_text, activity.small_image_text,
activity.button1, activity.button1,
@@ -1448,6 +1687,125 @@ pub async fn download_and_extract_theme(
Ok(()) Ok(())
} }
#[tauri::command]
pub async fn download_and_extract_community_theme(
app: AppHandle,
download_url: String,
theme_folder: String,
theme_name: String,
request_headers: Option<HashMap<String, String>>,
) -> Result<(), String> {
let client = reqwest::Client::new();
let mut request = client.get(&download_url).header(
"User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
);
if let Some(headers) = request_headers {
for (name, value) in headers {
request = request.header(name.as_str(), value.as_str());
}
}
let response = request
.send()
.await
.map_err(|e| format!("Failed to download theme: {}", e))?;
if !response.status().is_success() {
return Err(format!("Download failed (HTTP {})", response.status()));
}
let total = response.content_length().unwrap_or(0);
let mut received: u64 = 0;
let mut chunks: Vec<u8> = Vec::new();
let mut stream = response.bytes_stream();
while let Some(chunk) = futures_util::StreamExt::next(&mut stream).await {
let chunk = chunk.map_err(|e| format!("Failed to read chunk: {}", e))?;
received += chunk.len() as u64;
chunks.extend_from_slice(&chunk);
let _ = app.emit(
"download_progress",
DownloadProgress {
theme_name: theme_name.clone(),
received,
total,
progress: if total > 0 {
received as f64 / total as f64
} else {
0.0
},
},
);
}
// Parse zip on blocking thread
let entries: Vec<(String, Vec<u8>, bool)> = tokio::task::spawn_blocking(move || {
let cursor = std::io::Cursor::new(chunks);
let mut archive = zip::ZipArchive::new(cursor)
.map_err(|e| format!("Failed to read zip archive: {}", e))?;
let mut entries = Vec::new();
for i in 0..archive.len() {
let mut zip_entry = archive
.by_index(i)
.map_err(|e| format!("Failed to read zip entry: {}", e))?;
let name = match zip_entry.enclosed_name() {
Some(p) => p.to_string_lossy().to_string(),
None => continue,
};
let is_dir = zip_entry.is_dir();
let mut buf = Vec::new();
if !is_dir {
std::io::copy(&mut zip_entry, &mut buf)
.map_err(|e| format!("Failed to read zip entry data: {}", e))?;
}
entries.push((name, buf, is_dir));
}
Ok::<_, String>(entries)
})
.await
.map_err(|e| format!("Thread error: {}", e))??;
let total_files = entries.len();
let mut extracted = 0;
for (name, buf, is_dir) in entries {
let entry_path = std::path::Path::new(&theme_folder).join(&name);
if is_dir {
tokio::fs::create_dir_all(&entry_path)
.await
.map_err(|e| format!("Failed to create directory: {}", e))?;
} else {
if let Some(parent) = entry_path.parent() {
tokio::fs::create_dir_all(parent)
.await
.map_err(|e| format!("Failed to create parent directory: {}", e))?;
}
tokio::fs::write(&entry_path, &buf)
.await
.map_err(|e| format!("Failed to write file: {}", e))?;
}
extracted += 1;
let _ = app.emit(
"extract_progress",
ExtractProgress {
theme_name: theme_name.clone(),
total: total_files,
extracted,
progress: extracted as f64 / total_files as f64,
current_file: name,
},
);
}
Ok(())
}
#[tauri::command] #[tauri::command]
pub async fn extract_theme( pub async fn extract_theme(
app: AppHandle, app: AppHandle,
@@ -1584,18 +1942,18 @@ pub(crate) fn theme_root() -> Result<PathBuf, String> {
#[cfg(any(target_os = "linux", target_os = "macos"))] #[cfg(any(target_os = "linux", target_os = "macos"))]
fn loopback_theme_asset_base() -> String { fn loopback_theme_asset_base() -> String {
if crate::theme_server::base_url().is_none() { if crate::theme_server::base_url().is_none()
if let Ok(root) = theme_root() { && let Ok(root) = theme_root()
match crate::theme_server::media_root() { {
Ok(media) => { match crate::theme_server::media_root() {
if let Err(error) = crate::theme_server::start(root, media) { Ok(media) => {
log::warn!(target: "launcher", "Could not start the theme asset server: {error}"); if let Err(error) = crate::theme_server::start(root, media) {
} log::warn!(target: "launcher", "Could not start the theme asset server: {error}");
}
Err(error) => {
log::warn!(target: "launcher", "Could not prepare the media cache: {error}");
} }
} }
Err(error) => {
log::warn!(target: "launcher", "Could not prepare the media cache: {error}");
}
} }
} }
crate::theme_server::base_url().unwrap_or_default() crate::theme_server::base_url().unwrap_or_default()
@@ -1605,7 +1963,7 @@ fn loopback_theme_asset_base() -> String {
pub fn theme_asset_base() -> String { pub fn theme_asset_base() -> String {
#[cfg(any(target_os = "linux", target_os = "macos"))] #[cfg(any(target_os = "linux", target_os = "macos"))]
{ {
return loopback_theme_asset_base(); loopback_theme_asset_base()
} }
#[cfg(not(any(target_os = "linux", target_os = "macos")))] #[cfg(not(any(target_os = "linux", target_os = "macos")))]
@@ -1619,7 +1977,7 @@ pub fn theme_preview_url(path: String) -> Result<String, String> {
#[cfg(any(target_os = "linux", target_os = "macos"))] #[cfg(any(target_os = "linux", target_os = "macos"))]
{ {
let _ = loopback_theme_asset_base(); let _ = loopback_theme_asset_base();
return crate::theme_server::preview_url(Path::new(&path)); crate::theme_server::preview_url(Path::new(&path))
} }
#[cfg(not(any(target_os = "linux", target_os = "macos")))] #[cfg(not(any(target_os = "linux", target_os = "macos")))]
@@ -1732,17 +2090,27 @@ pub async fn optimize_theme_media(app: AppHandle, source_url: String) -> Result<
} }
}; };
let _ = app.emit(
"theme-media-progress",
ThemeMediaProgress {
stage: "optimize".to_string(),
progress: 0.0,
},
);
let original = source_url.clone(); let original = source_url.clone();
let app_handle = app.clone();
let on_progress = move |progress: f64| {
let _ = app_handle.emit(
"theme-media-progress",
ThemeMediaProgress {
stage: "optimize".to_string(),
progress,
},
);
};
tokio::task::spawn_blocking(move || { tokio::task::spawn_blocking(move || {
optimize_theme_media_blocking(&ffmpeg, &source, &original, &cache_name, &destination) optimize_theme_media_blocking(
&ffmpeg,
&source,
&original,
&cache_name,
&destination,
on_progress,
)
}) })
.await .await
.map_err(|error| format!("Theme media optimizer thread failed: {error}"))? .map_err(|error| format!("Theme media optimizer thread failed: {error}"))?
@@ -1903,18 +2271,19 @@ async fn download_ffmpeg(app: &AppHandle) -> Result<PathBuf, String> {
.await .await
.map_err(|error| format!("Could not write the FFmpeg archive: {error}"))?; .map_err(|error| format!("Could not write the FFmpeg archive: {error}"))?;
if total > 0 { if let Some(percent) = (received.min(total) * 100)
let percent = ((received.min(total) * 100) / total) as u8; .checked_div(total)
if percent != last_percent { .map(|v| v as u8)
last_percent = percent; && percent != last_percent
let _ = app.emit( {
"theme-media-progress", last_percent = percent;
ThemeMediaProgress { let _ = app.emit(
stage: "download".to_string(), "theme-media-progress",
progress: percent as f64 / 100.0, ThemeMediaProgress {
}, stage: "download".to_string(),
); progress: percent as f64 / 100.0,
} },
);
} }
} }
@@ -2005,13 +2374,82 @@ fn find_media_binary(name: &str) -> Option<PathBuf> {
} }
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
fn optimize_theme_media_blocking( fn run_ffmpeg_with_progress<F>(
mut command: std::process::Command,
duration_us: Option<u64>,
on_progress: &F,
) -> Result<(bool, String), String>
where
F: Fn(f64) + Send + Sync,
{
use std::io::{BufRead, BufReader, Read};
command.args(["-progress", "pipe:1"]);
command.stdout(std::process::Stdio::piped());
command.stderr(std::process::Stdio::piped());
let mut child = command
.spawn()
.map_err(|error| format!("Could not spawn ffmpeg: {error}"))?;
let stdout = child.stdout.take();
let stderr = child.stderr.take();
let stderr_thread = std::thread::spawn(move || {
let mut err_str = String::new();
if let Some(mut err) = stderr {
let _ = err.read_to_string(&mut err_str);
}
err_str
});
if let Some(out) = stdout {
let reader = BufReader::new(out);
let mut last_progress = 0.0;
let mut last_emit = std::time::Instant::now();
for line in reader.lines() {
let Ok(line) = line else { break };
if let Some(val_str) = line.strip_prefix("out_time_us=") {
if let Ok(us) = val_str.trim().parse::<u64>()
&& let Some(total_us) = duration_us
&& total_us > 0
{
let progress = (us as f64 / total_us as f64).clamp(0.0, 0.99);
if (progress - last_progress) >= 0.01
|| last_emit.elapsed() >= std::time::Duration::from_millis(250)
{
last_progress = progress;
last_emit = std::time::Instant::now();
on_progress(progress);
}
}
} else if line.starts_with("progress=end") {
on_progress(1.0);
}
}
}
let status = child
.wait()
.map_err(|error| format!("Failed waiting for ffmpeg: {error}"))?;
let stderr_str = stderr_thread.join().unwrap_or_default();
Ok((status.success(), stderr_str))
}
#[cfg(target_os = "macos")]
fn optimize_theme_media_blocking<F>(
ffmpeg: &Path, ffmpeg: &Path,
source: &Path, source: &Path,
source_url: &str, source_url: &str,
cache_name: &str, cache_name: &str,
destination: &Path, destination: &Path,
) -> Result<String, String> { on_progress: F,
) -> Result<String, String>
where
F: Fn(f64) + Send + Sync,
{
use std::process::Command; use std::process::Command;
let probe = Command::new(ffmpeg) let probe = Command::new(ffmpeg)
@@ -2023,7 +2461,7 @@ fn optimize_theme_media_blocking(
let codec = probe_text.lines().find_map(|line| { let codec = probe_text.lines().find_map(|line| {
let index = line.find("Video: ")?; let index = line.find("Video: ")?;
line[index + 7..] line[index + 7..]
.split(|character: char| character == ',' || character == ' ') .split([',', ' '])
.next() .next()
.map(str::to_ascii_lowercase) .map(str::to_ascii_lowercase)
}); });
@@ -2035,6 +2473,17 @@ fn optimize_theme_media_blocking(
return Ok(source_url.to_string()); return Ok(source_url.to_string());
} }
let duration_us = probe_text.lines().find_map(|line| {
let index = line.find("Duration: ")?;
let time_str = line[index + 10..].split(',').next()?.trim();
let mut parts = time_str.split(':');
let hours: f64 = parts.next()?.parse().ok()?;
let minutes: f64 = parts.next()?.parse().ok()?;
let seconds: f64 = parts.next()?.parse().ok()?;
let total_secs = hours * 3600.0 + minutes * 60.0 + seconds;
Some((total_secs * 1_000_000.0) as u64)
});
let temporary = destination.with_extension("mp4.tmp"); let temporary = destination.with_extension("mp4.tmp");
let _ = std::fs::remove_file(&temporary); let _ = std::fs::remove_file(&temporary);
@@ -2044,6 +2493,7 @@ fn optimize_theme_media_blocking(
source.display() source.display()
); );
let started = std::time::Instant::now(); let started = std::time::Instant::now();
on_progress(0.0);
let mut command = Command::new(ffmpeg); let mut command = Command::new(ffmpeg);
command.args(["-hide_banner", "-loglevel", "error", "-nostdin", "-y", "-i"]); command.args(["-hide_banner", "-loglevel", "error", "-nostdin", "-y", "-i"]);
@@ -2077,18 +2527,14 @@ fn optimize_theme_media_blocking(
"mp4", "mp4",
]); ]);
command.arg(&temporary); command.arg(&temporary);
let first = command.output();
let success = match first { let success = match run_ffmpeg_with_progress(command, duration_us, &on_progress) {
Ok(output) if output.status.success() => true, Ok((true, _)) => true,
Ok(output) => { Ok((false, stderr)) => {
log::warn!( log::warn!(
target: "launcher", target: "launcher",
"Hardware theme video encode failed: {}", "Hardware theme video encode failed: {}",
String::from_utf8_lossy(&output.stderr) stderr.chars().take(500).collect::<String>()
.chars()
.take(500)
.collect::<String>()
); );
false false
} }
@@ -2132,16 +2578,14 @@ fn optimize_theme_media_blocking(
"mp4", "mp4",
]); ]);
fallback.arg(&temporary); fallback.arg(&temporary);
match fallback.output() {
Ok(output) if output.status.success() => true, match run_ffmpeg_with_progress(fallback, duration_us, &on_progress) {
Ok(output) => { Ok((true, _)) => true,
Ok((false, stderr)) => {
log::warn!( log::warn!(
target: "launcher", target: "launcher",
"Software theme video encode failed: {}", "Software theme video encode failed: {}",
String::from_utf8_lossy(&output.stderr) stderr.chars().take(500).collect::<String>()
.chars()
.take(500)
.collect::<String>()
); );
false false
} }
@@ -2159,6 +2603,7 @@ fn optimize_theme_media_blocking(
std::fs::rename(&temporary, destination) std::fs::rename(&temporary, destination)
.map_err(|error| format!("Could not store the optimized theme video: {error}"))?; .map_err(|error| format!("Could not store the optimized theme video: {error}"))?;
on_progress(1.0);
log::info!( log::info!(
target: "launcher", target: "launcher",
"Optimized theme video in {:.1}s: {}", "Optimized theme video in {:.1}s: {}",
@@ -2286,15 +2731,18 @@ pub async fn open_presence_editor(app: AppHandle) -> Result<(), String> {
return Ok(()); return Ok(());
} }
let window = let window = WebviewWindowBuilder::new(
WebviewWindowBuilder::new(&app, "presence-editor", WebviewUrl::App("index.html".into())) &app,
.title("EZPPLauncher — Discord Rich Presence Editor") "presence-editor",
.inner_size(1200.0, 800.0) WebviewUrl::App("index.html".into()),
.min_inner_size(980.0, 650.0) )
.resizable(true) .title("EZPPLauncher — Discord Rich Presence Editor")
.center() .inner_size(1200.0, 800.0)
.build() .min_inner_size(980.0, 650.0)
.map_err(|error| format!("Could not open the presence editor: {error}"))?; .resizable(true)
.center()
.build()
.map_err(|error| format!("Could not open the presence editor: {error}"))?;
let main_window = app.clone(); let main_window = app.clone();
window.on_window_event(move |event| { window.on_window_event(move |event| {
@@ -2506,7 +2954,7 @@ pub async fn list_theme_backups(theme_folder: String) -> Result<Vec<ThemeBackupI
.map_err(|error| format!("Failed to read theme backups: {error}"))? .map_err(|error| format!("Failed to read theme backups: {error}"))?
.filter_map(|entry| entry.ok()) .filter_map(|entry| entry.ok())
.filter(|entry| entry.file_type().map(|kind| kind.is_dir()).unwrap_or(false)) .filter(|entry| entry.file_type().map(|kind| kind.is_dir()).unwrap_or(false))
.filter_map(|entry| { .map(|entry| {
let path = entry.path(); let path = entry.path();
let created_at = entry let created_at = entry
.metadata() .metadata()
@@ -2515,16 +2963,16 @@ pub async fn list_theme_backups(theme_folder: String) -> Result<Vec<ThemeBackupI
.and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok()) .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
.map(|duration| duration.as_millis() as u64) .map(|duration| duration.as_millis() as u64)
.unwrap_or(0); .unwrap_or(0);
Some(ThemeBackupInfo { ThemeBackupInfo {
label: entry.file_name().to_string_lossy().into_owned(), label: entry.file_name().to_string_lossy().into_owned(),
path: path.to_string_lossy().into_owned(), path: path.to_string_lossy().into_owned(),
created_at, created_at,
size: directory_size(&path), size: directory_size(&path),
}) }
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
backups.sort_by(|a, b| b.created_at.cmp(&a.created_at)); backups.sort_by_key(|b| std::cmp::Reverse(b.created_at));
Ok(backups) Ok(backups)
}) })
.await .await
@@ -2687,12 +3135,11 @@ fn collect_theme_asset_refs(value: &Value, assets: &mut HashSet<String>) {
match value { match value {
Value::Object(object) => { Value::Object(object) => {
for (key, value) in object { for (key, value) in object {
if key == "src" || key == "preview" { if (key == "src" || key == "preview")
if let Some(src) = value.as_str() { && let Some(src) = value.as_str()
if let Some(path) = theme_asset_reference(src) { && let Some(path) = theme_asset_reference(src)
assets.insert(path); {
} assets.insert(path);
}
} }
collect_theme_asset_refs(value, assets); collect_theme_asset_refs(value, assets);
} }
@@ -2788,6 +3235,9 @@ fn add_theme_folder_to_zip(
for entry in entries { for entry in entries {
let entry = entry.map_err(|e| format!("Failed to read theme entry: {e}"))?; let entry = entry.map_err(|e| format!("Failed to read theme entry: {e}"))?;
if entry.file_name().to_string_lossy().starts_with('.') {
continue;
}
let file_type = entry let file_type = entry
.file_type() .file_type()
.map_err(|e| format!("Failed to inspect theme entry: {e}"))?; .map_err(|e| format!("Failed to inspect theme entry: {e}"))?;
@@ -2796,7 +3246,18 @@ fn add_theme_folder_to_zip(
} }
let entry_path = entry.path(); let entry_path = entry.path();
let relative = entry_path
.strip_prefix(root)
.map_err(|e| format!("Failed to build archive path: {e}"))?
.to_string_lossy()
.replace('\\', "/");
if file_type.is_dir() { if file_type.is_dir() {
// API 2.0 packages are limited to theme.json and assets/. Do not
// copy README files, editor artifacts, or any other root folder.
if asset_filter.is_some() && directory == root && relative != "assets" {
continue;
}
add_theme_folder_to_zip(zip, root, &entry_path, asset_filter, options)?; add_theme_folder_to_zip(zip, root, &entry_path, asset_filter, options)?;
continue; continue;
} }
@@ -2804,20 +3265,18 @@ fn add_theme_folder_to_zip(
continue; continue;
} }
if let Some(filter) = asset_filter { if asset_filter.is_some() && directory == root && relative != "theme.json" {
if let Ok(asset_path) = entry_path.strip_prefix(&assets_root) { continue;
let key = asset_path.to_string_lossy().replace('\\', "/");
if !filter.contains(&key) {
continue;
}
}
} }
let relative = entry_path if let Some(filter) = asset_filter
.strip_prefix(root) && let Ok(asset_path) = entry_path.strip_prefix(&assets_root)
.map_err(|e| format!("Failed to build archive path: {e}"))? {
.to_string_lossy() let key = asset_path.to_string_lossy().replace('\\', "/");
.replace('\\', "/"); if !filter.contains(&key) {
continue;
}
}
zip.start_file(relative, options) zip.start_file(relative, options)
.map_err(|e| format!("Failed to add a file to the theme archive: {e}"))?; .map_err(|e| format!("Failed to add a file to the theme archive: {e}"))?;
@@ -2911,3 +3370,42 @@ pub fn config_clear(state: State<AppState>) -> Result<(), ConfigError> {
pub fn config_all(state: State<AppState>) -> Result<Vec<(String, Value)>, ConfigError> { pub fn config_all(state: State<AppState>) -> Result<Vec<(String, Value)>, ConfigError> {
state.config.lock().unwrap().all() state.config.lock().unwrap().all()
} }
#[tauri::command]
pub async fn reveal_window(window: tauri::WebviewWindow) -> Result<(), String> {
let (tx, rx) = tokio::sync::oneshot::channel();
let win = window.clone();
window
.run_on_main_thread(move || {
let _ = win.show();
let _ = win.unminimize();
let _ = win.set_focus();
#[cfg(target_os = "macos")]
{
let res = crate::macos::activate_and_focus_window(&win);
let _ = crate::macos::unlock_media_autoplay(&win);
let _ = tx.send(res);
}
#[cfg(not(target_os = "macos"))]
let _ = tx.send(Ok(()));
})
.map_err(|e| e.to_string())?;
rx.await
.map_err(|_| "Main thread channel closed".to_string())?
}
#[tauri::command]
pub async fn unlock_media_autoplay(window: tauri::WebviewWindow) -> Result<(), String> {
#[cfg(target_os = "macos")]
{
crate::macos::unlock_media_autoplay(&window)?;
}
#[cfg(not(target_os = "macos"))]
{
let _ = window;
}
Ok(())
}
+27 -9
View File
@@ -19,21 +19,22 @@ pub mod utils;
use crate::{ use crate::{
commands::{ commands::{
backup_theme_folder, check_for_corruption, close_presence_editor, close_theme_editor, config_all, config_clear, config_delete, backup_theme_folder, check_for_corruption, close_presence_editor, close_theme_editor, config_all, config_clear, config_delete,
config_exists, config_get, config_set, download_and_extract_theme, config_exists, config_get, config_set, download_and_extract_community_theme, download_and_extract_theme,
download_ezpp_launcher_update, download_ezpp_launcher_update_files, encrypt_string, exit, download_ezpp_launcher_update, download_ezpp_launcher_update_files, encrypt_string, exit,
export_theme, extract_theme, file_size, find_osu_installation, focus_presence_editor, focus_theme_editor, get_beatmapsets_count, export_theme, extract_theme, file_size, find_osu_installation, focus_presence_editor, focus_theme_editor, get_beatmapsets_count,
get_ezpp_launcher_update_files, get_hwid, get_launcher_version, get_osu_release_stream, get_ezpp_launcher_update_files, get_hwid, get_launcher_version, get_osu_release_stream,
get_osu_skin, get_osu_version, get_platform, get_skins_count, has_net8, has_osuwinello, get_osu_skin, get_osu_version, get_platform, get_skins_count, has_net8,
has_wmctrl, install_ezpp_launcher_update, installation_diagnostics, has_osuwinello, has_wmctrl, hash_file_sha256, hash_theme_content,
install_ezpp_launcher_update, installation_diagnostics,
is_open_tablet_driver_path_valid, is_open_tablet_driver_running, is_osu_running, is_open_tablet_driver_path_valid, is_open_tablet_driver_running, is_osu_running,
list_theme_backups, log_frontend, open_logs_folder, open_presence_editor, open_theme_editor, open_theme_folder, list_theme_backups, log_frontend, open_logs_folder, open_presence_editor, open_theme_editor, open_theme_folder,
open_url_in_browser, opened_urls, optimize_theme_media, pick_osu_installation, open_url_in_browser, opened_urls, optimize_theme_media, pick_osu_installation,
presence_connect, presence_disconnect, presence_is_connected, presence_update_activity, presence_connect, presence_disconnect, presence_is_connected, presence_update_activity,
presence_update_button, presence_update_status, presence_update_user, read_theme_info, replace_ui_files, presence_update_button, presence_update_status, presence_update_user, read_file_chunk, read_theme_info, replace_ui_files,
resolve_osu_folder, restore_theme_backup, run_open_tablet_driver, run_osu, run_osu_updater, resolve_osu_folder, restore_theme_backup, reveal_window, run_open_tablet_driver, run_osu, run_osu_updater,
save_theme_project, set_logging_enabled, set_osu_config_values, set_osu_user_config_values, save_theme_project, set_logging_enabled, set_osu_config_values, set_osu_user_config_values,
stop_open_tablet_driver, theme_asset_base, theme_editor_context, theme_preview_url, stop_open_tablet_driver, theme_asset_base, theme_editor_context, theme_preview_url,
valid_osu_folder, unlock_media_autoplay, valid_osu_folder,
}, },
state::AppState, state::AppState,
}; };
@@ -136,6 +137,12 @@ pub fn run() {
if let Err(error) = macos::allow_media_autoplay(&window) { if let Err(error) = macos::allow_media_autoplay(&window) {
log::warn!(target: "launcher", "{error}"); log::warn!(target: "launcher", "{error}");
} }
if let Err(error) = macos::unlock_media_autoplay(&window) {
log::warn!(target: "launcher", "{error}");
}
if let Err(error) = macos::activate_and_focus_window(&window) {
log::warn!(target: "launcher", "Could not focus launcher window on startup: {error}");
}
} }
Ok(()) Ok(())
@@ -186,8 +193,12 @@ pub fn run() {
restore_theme_backup, restore_theme_backup,
extract_theme, extract_theme,
download_and_extract_theme, download_and_extract_theme,
download_and_extract_community_theme,
save_theme_project, save_theme_project,
export_theme, export_theme,
hash_file_sha256,
hash_theme_content,
read_file_chunk,
open_theme_folder, open_theme_folder,
open_theme_editor, open_theme_editor,
focus_theme_editor, focus_theme_editor,
@@ -212,6 +223,8 @@ pub fn run() {
log_frontend, log_frontend,
set_logging_enabled, set_logging_enabled,
open_logs_folder, open_logs_folder,
reveal_window,
unlock_media_autoplay,
logging::list_log_bundles, logging::list_log_bundles,
logging::read_log_bundle logging::read_log_bundle
]) ])
@@ -226,16 +239,21 @@ pub fn run() {
// The content view can be replaced again while the webview is being // The content view can be replaced again while the webview is being
// built, so re-apply the corner mask once the app is ready. // built, so re-apply the corner mask once the app is ready.
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
if let tauri::RunEvent::Ready = &event { if let tauri::RunEvent::Ready = &event
if let Some(window) = app.get_webview_window("main") { && let Some(window) = app.get_webview_window("main") {
if let Err(error) = macos::round_window(&window, 12.0) { if let Err(error) = macos::round_window(&window, 12.0) {
log::warn!(target: "launcher", "Could not round the launcher window: {error}"); log::warn!(target: "launcher", "Could not round the launcher window: {error}");
} }
if let Err(error) = macos::allow_media_autoplay(&window) { if let Err(error) = macos::allow_media_autoplay(&window) {
log::warn!(target: "launcher", "{error}"); log::warn!(target: "launcher", "{error}");
} }
if let Err(error) = macos::unlock_media_autoplay(&window) {
log::warn!(target: "launcher", "{error}");
}
if let Err(error) = macos::activate_and_focus_window(&window) {
log::warn!(target: "launcher", "Could not focus launcher window on ready: {error}");
}
} }
}
presence::handle_run_event(app, &event); presence::handle_run_event(app, &event);
}); });
+131 -24
View File
@@ -393,7 +393,97 @@ pub struct LogBundleEntry {
pub content: String, pub content: String,
} }
/// List the rotating ZIP bundles, newest first, for the in-app log viewer. const MAX_LOG_VIEW_BYTES: u64 = 2 * 1024 * 1024;
fn modified_millis(metadata: &fs::Metadata) -> u64 {
metadata
.modified()
.ok()
.and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
.map(|duration| duration.as_millis() as u64)
.unwrap_or(0)
}
/// Describe the active session. Unlike archived bundles, these files are still
/// being written and appear in the viewer without waiting for a rotation.
fn current_log_bundle(dir: &Path) -> Option<LogBundleInfo> {
let mut size = 0;
let mut modified = 0;
let mut has_logs = false;
for stream in Stream::ALL {
let Ok(metadata) = fs::metadata(dir.join(stream.file_name())) else {
continue;
};
if metadata.len() == 0 {
continue;
}
has_logs = true;
size += metadata.len();
modified = modified.max(modified_millis(&metadata));
}
has_logs.then(|| LogBundleInfo {
path: dir.to_string_lossy().into_owned(),
name: "Current session".to_string(),
size,
modified,
})
}
fn read_log_entry(
name: String,
reader: &mut impl Read,
size: u64,
) -> Result<LogBundleEntry, String> {
let mut bytes = Vec::new();
reader
.take(MAX_LOG_VIEW_BYTES)
.read_to_end(&mut bytes)
.map_err(|error| format!("Could not read a log entry: {error}"))?;
let mut content = String::from_utf8_lossy(&bytes).into_owned();
if size > bytes.len() as u64 {
content.push_str("\n… log truncated in the viewer …\n");
}
Ok(LogBundleEntry { name, content })
}
fn read_current_logs(root: &Path) -> Result<Vec<LogBundleEntry>, String> {
let mut entries = Vec::new();
for stream in Stream::ALL {
let path = root.join(stream.file_name());
let metadata = match fs::metadata(&path) {
Ok(metadata) => metadata,
Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
Err(error) => {
return Err(format!(
"Could not read the current {}: {error}",
stream.file_name()
));
}
};
if metadata.len() == 0 {
continue;
}
let mut file = File::open(&path).map_err(|error| {
format!("Could not read the current {}: {error}", stream.file_name())
})?;
entries.push(read_log_entry(
stream.file_name().to_string(),
&mut file,
metadata.len(),
)?);
}
entries.sort_by(|a, b| a.name.cmp(&b.name));
Ok(entries)
}
/// List the active session followed by the rotating ZIP bundles, newest first,
/// for the in-app log viewer.
#[tauri::command] #[tauri::command]
pub fn list_log_bundles() -> Result<Vec<LogBundleInfo>, String> { pub fn list_log_bundles() -> Result<Vec<LogBundleInfo>, String> {
let dir = logs_directory(); let dir = logs_directory();
@@ -401,6 +491,7 @@ pub fn list_log_bundles() -> Result<Vec<LogBundleInfo>, String> {
return Ok(Vec::new()); return Ok(Vec::new());
} }
let current = current_log_bundle(&dir);
let mut bundles = fs::read_dir(&dir) let mut bundles = fs::read_dir(&dir)
.map_err(|error| format!("Could not read the logs folder: {error}"))? .map_err(|error| format!("Could not read the logs folder: {error}"))?
.filter_map(|entry| entry.ok()) .filter_map(|entry| entry.ok())
@@ -411,26 +502,23 @@ pub fn list_log_bundles() -> Result<Vec<LogBundleInfo>, String> {
return None; return None;
} }
let metadata = entry.metadata().ok()?; let metadata = entry.metadata().ok()?;
let modified = metadata
.modified()
.ok()
.and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
.map(|duration| duration.as_millis() as u64)
.unwrap_or(0);
Some(LogBundleInfo { Some(LogBundleInfo {
path: path.to_string_lossy().into_owned(), path: path.to_string_lossy().into_owned(),
name, name,
size: metadata.len(), size: metadata.len(),
modified, modified: modified_millis(&metadata),
}) })
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
bundles.sort_by(|a, b| b.modified.cmp(&a.modified)); bundles.sort_by_key(|b| std::cmp::Reverse(b.modified));
if let Some(current) = current {
bundles.insert(0, current);
}
Ok(bundles) Ok(bundles)
} }
/// Read the launcher/osu/patcher logs out of one bundle. /// Read the active logs or the launcher/osu/patcher logs out of an archive.
#[tauri::command] #[tauri::command]
pub fn read_log_bundle(path: String) -> Result<Vec<LogBundleEntry>, String> { pub fn read_log_bundle(path: String) -> Result<Vec<LogBundleEntry>, String> {
let dir = logs_directory(); let dir = logs_directory();
@@ -441,6 +529,9 @@ pub fn read_log_bundle(path: String) -> Result<Vec<LogBundleEntry>, String> {
if !requested.starts_with(&root) { if !requested.starts_with(&root) {
return Err("The log bundle is outside the logs folder".to_string()); return Err("The log bundle is outside the logs folder".to_string());
} }
if requested == root {
return read_current_logs(&root);
}
let file = File::open(&requested) let file = File::open(&requested)
.map_err(|error| format!("Could not read the log bundle: {error}"))?; .map_err(|error| format!("Could not read the log bundle: {error}"))?;
@@ -456,20 +547,9 @@ pub fn read_log_bundle(path: String) -> Result<Vec<LogBundleEntry>, String> {
continue; continue;
} }
let mut bytes = Vec::new(); let name = entry.name().to_string();
entry let size = entry.size();
.by_ref() entries.push(read_log_entry(name, &mut entry, size)?);
.take(2 * 1024 * 1024)
.read_to_end(&mut bytes)
.map_err(|error| format!("Could not read a log entry: {error}"))?;
let mut content = String::from_utf8_lossy(&bytes).into_owned();
if entry.size() > bytes.len() as u64 {
content.push_str("\n… log truncated in the viewer …\n");
}
entries.push(LogBundleEntry {
name: entry.name().to_string(),
content,
});
} }
entries.sort_by(|a, b| a.name.cmp(&b.name)); entries.sort_by(|a, b| a.name.cmp(&b.name));
@@ -634,4 +714,31 @@ mod tests {
drop(current); drop(current);
fs::remove_dir_all(dir).unwrap(); fs::remove_dir_all(dir).unwrap();
} }
#[test]
fn current_session_includes_active_logs() {
let dir = temp_dir("current");
let logs = Arc::new(LogSet::new(dir.clone()));
write_line(&logs, Stream::Launcher, "launcher current\n");
write_line(&logs, Stream::Osu, "osu current\n");
let current = current_log_bundle(&dir).expect("active logs should have a session");
assert_eq!(current.name, "Current session");
assert_eq!(current.path, dir.to_string_lossy());
assert!(current.size > 0);
let entries = read_current_logs(&dir).unwrap();
assert_eq!(
entries
.iter()
.map(|entry| entry.name.as_str())
.collect::<Vec<_>>(),
["launcher.log", "osu.log"]
);
assert_eq!(entries[0].content, "launcher current\n");
assert_eq!(entries[1].content, "osu current\n");
drop(logs);
fs::remove_dir_all(dir).unwrap();
}
} }
+696 -94
View File
@@ -54,6 +54,41 @@ pub fn round_window(window: &tauri::WebviewWindow, radius: f64) -> Result<(), St
Ok(()) Ok(())
} }
/// Activate the application, bring it to the foreground, and focus the given window.
pub fn activate_and_focus_window(window: &tauri::WebviewWindow) -> Result<(), String> {
use objc2::msg_send;
use objc2::runtime::AnyObject;
let _ = window.show();
let _ = window.unminimize();
let _ = window.set_focus();
let ns_window = window.ns_window().map_err(|error| error.to_string())? as *mut AnyObject;
if !ns_window.is_null() {
unsafe {
let ns_app: *mut AnyObject = msg_send![objc2::class!(NSApplication), sharedApplication];
if !ns_app.is_null() {
let _: () = msg_send![ns_app, activateIgnoringOtherApps: true];
}
let _: () = msg_send![ns_window, makeKeyAndOrderFront: ns_window];
}
}
Ok(())
}
/// Make this application active, bringing it to the front over other background apps.
pub fn activate_app() {
use objc2::msg_send;
use objc2::runtime::AnyObject;
unsafe {
let ns_app: *mut AnyObject = msg_send![objc2::class!(NSApplication), sharedApplication];
if !ns_app.is_null() {
let _: () = msg_send![ns_app, activateIgnoringOtherApps: true];
}
}
}
/// Allow theme media to start without a click. WKWebView otherwise blocks /// Allow theme media to start without a click. WKWebView otherwise blocks
/// autoplay for anything with an audio track, which makes a theme's background /// autoplay for anything with an audio track, which makes a theme's background
/// video sit frozen until the user interacts with the launcher. /// video sit frozen until the user interacts with the launcher.
@@ -61,6 +96,14 @@ pub fn allow_media_autoplay(window: &tauri::WebviewWindow) -> Result<(), String>
use objc2::msg_send; use objc2::msg_send;
use objc2::runtime::AnyObject; use objc2::runtime::AnyObject;
unsafe extern "C" {
fn object_getInstanceVariable(
obj: *mut AnyObject,
name: *const std::ffi::c_char,
out_value: *mut *mut std::ffi::c_void,
) -> *const std::ffi::c_void;
}
window window
.with_webview(|webview| unsafe { .with_webview(|webview| unsafe {
let webview = webview.inner() as *mut AnyObject; let webview = webview.inner() as *mut AnyObject;
@@ -68,10 +111,23 @@ pub fn allow_media_autoplay(window: &tauri::WebviewWindow) -> Result<(), String>
return; return;
} }
let configuration: *mut AnyObject = msg_send![webview, configuration]; // -[WKWebView configuration] returns a copy. To affect live playback,
// access the internal `_configuration` ivar directly when available.
let mut raw_config: *mut std::ffi::c_void = std::ptr::null_mut();
let ivar_name = c"_configuration";
let ivar = object_getInstanceVariable(webview, ivar_name.as_ptr(), &mut raw_config);
let configuration: *mut AnyObject = if !ivar.is_null() && !raw_config.is_null() {
log::debug!(target: "launcher", "Accessing live WKWebView._configuration ivar");
raw_config as *mut AnyObject
} else {
msg_send![webview, configuration]
};
if configuration.is_null() { if configuration.is_null() {
return; return;
} // WKAudiovisualMediaTypesNone. This is a public WKWebView setting. }
// WKAudiovisualMediaTypesNone. This is a public WKWebView setting.
let _: () = let _: () =
msg_send![configuration, setMediaTypesRequiringUserActionForPlayback: 0usize]; msg_send![configuration, setMediaTypesRequiringUserActionForPlayback: 0usize];
let current: usize = msg_send![configuration, mediaTypesRequiringUserActionForPlayback]; let current: usize = msg_send![configuration, mediaTypesRequiringUserActionForPlayback];
@@ -79,10 +135,132 @@ pub fn allow_media_autoplay(window: &tauri::WebviewWindow) -> Result<(), String>
target: "launcher", target: "launcher",
"Theme media autoplay policy: {current}" "Theme media autoplay policy: {current}"
); );
// Configure webpage preferences for unconditional media autoplay
let default_preferences: *mut AnyObject = msg_send![configuration, defaultWebpagePreferences];
if !default_preferences.is_null() {
let sel = objc2::sel!(_setAutoplayPolicy:);
let responds: bool = msg_send![default_preferences, respondsToSelector: sel];
if responds {
// 1 = _WKWebsiteAutoplayPolicyAllow (allow autoplay unconditionally)
let _: () = msg_send![default_preferences, _setAutoplayPolicy: 1isize];
log::debug!(target: "launcher", "Set WKWebpagePreferences._setAutoplayPolicy to Allow (1)");
}
}
// Configure WKPreferences
let preferences: *mut AnyObject = msg_send![configuration, preferences];
if !preferences.is_null() {
let sel_audio = objc2::sel!(_setRequiresUserGestureForAudioPlayback:);
let responds: bool = msg_send![preferences, respondsToSelector: sel_audio];
if responds {
let _: () = msg_send![preferences, _setRequiresUserGestureForAudioPlayback: false];
}
let sel_video = objc2::sel!(_setRequiresUserGestureForVideoPlayback:);
let responds: bool = msg_send![preferences, respondsToSelector: sel_video];
if responds {
let _: () = msg_send![preferences, _setRequiresUserGestureForVideoPlayback: false];
}
let sel_inline = objc2::sel!(_setAllowsInlineMediaPlayback:);
let responds: bool = msg_send![preferences, respondsToSelector: sel_inline];
if responds {
let _: () = msg_send![preferences, _setAllowsInlineMediaPlayback: true];
}
let sel_inline_req = objc2::sel!(_setInlineMediaPlaybackRequiresPlaysInlineAttribute:);
let responds: bool = msg_send![preferences, respondsToSelector: sel_inline_req];
if responds {
let _: () = msg_send![preferences, _setInlineMediaPlaybackRequiresPlaysInlineAttribute: false];
}
let sel_invis = objc2::sel!(_setInvisibleMediaAutoplayNotPermitted:);
let responds: bool = msg_send![preferences, respondsToSelector: sel_invis];
if responds {
let _: () = msg_send![preferences, _setInvisibleMediaAutoplayNotPermitted: false];
}
}
let sel_media_load = objc2::sel!(_setMediaDataLoadsAutomatically:);
let responds: bool = msg_send![configuration, respondsToSelector: sel_media_load];
if responds {
let _: () = msg_send![configuration, _setMediaDataLoadsAutomatically: true];
}
let sel_audio_action = objc2::sel!(_setRequiresUserActionForAudioPlayback:);
let responds: bool = msg_send![configuration, respondsToSelector: sel_audio_action];
if responds {
let _: () = msg_send![configuration, _setRequiresUserActionForAudioPlayback: false];
}
}) })
.map_err(|error| format!("Could not enable theme media autoplay: {error}")) .map_err(|error| format!("Could not enable theme media autoplay: {error}"))
} }
/// Programmatically unlock media autoplay with unmuted sound using WebKit's
/// user gesture SPI and media resumption APIs.
pub fn unlock_media_autoplay(window: &tauri::WebviewWindow) -> Result<(), String> {
use objc2::msg_send;
use objc2::runtime::AnyObject;
use std::ffi::CString;
window
.with_webview(|webview| unsafe {
let webview = webview.inner() as *mut AnyObject;
if webview.is_null() {
return;
}
// 1. Resume all media playback
let sel_resume = objc2::sel!(_resumeAllMediaPlayback);
if msg_send![webview, respondsToSelector: sel_resume] {
let _: () = msg_send![webview, _resumeAllMediaPlayback];
} else {
let sel_resume_pub = objc2::sel!(resumeAllMediaPlayback:);
if msg_send![webview, respondsToSelector: sel_resume_pub] {
let _: () = msg_send![
webview,
resumeAllMediaPlayback: std::ptr::null_mut::<AnyObject>()
];
}
}
// 2. Evaluate unmuted media play script with explicit user gesture SPI
let sel_eval = objc2::sel!(
_evaluateJavaScript:withSourceURL:inFrame:inContentWorld:withUserGesture:completionHandler:
);
if msg_send![webview, respondsToSelector: sel_eval] {
let script_str = match CString::new(
"document.querySelectorAll('video, audio').forEach(function(el) { \
el.muted = false; \
var p = el.play(); \
if (p !== undefined) p.catch(function() {}); \
});",
) {
Ok(s) => s,
Err(_) => return,
};
let ns_script: *mut AnyObject =
msg_send![objc2::class!(NSString), stringWithUTF8String: script_str.as_ptr()];
let page_world: *mut AnyObject =
msg_send![objc2::class!(WKContentWorld), pageWorld];
let _: () = msg_send![
webview,
_evaluateJavaScript: ns_script,
withSourceURL: std::ptr::null_mut::<AnyObject>(),
inFrame: std::ptr::null_mut::<AnyObject>(),
inContentWorld: page_world,
withUserGesture: true,
completionHandler: std::ptr::null_mut::<AnyObject>()
];
log::debug!(target: "launcher", "Unlocked theme media autoplay with user gesture SPI");
}
})
.map_err(|error| format!("Could not unlock theme media autoplay: {error}"))
}
/// Show a native open panel that accepts `.app` bundles as well as folders. /// Show a native open panel that accepts `.app` bundles as well as folders.
/// ///
/// AppKit treats application bundles as packages (directories) by default, so a /// AppKit treats application bundles as packages (directories) by default, so a
@@ -156,10 +334,12 @@ pub fn pick_osu_installation() -> Result<Option<PathBuf>, String> {
}) })
} }
#[derive(Clone, Debug)]
pub struct WineRuntime { pub struct WineRuntime {
prefix: PathBuf, prefix: PathBuf,
wine_bin: PathBuf, wine_bin: PathBuf,
wine_root: Option<PathBuf>, wine_root: Option<PathBuf>,
app_bundle: Option<PathBuf>,
} }
#[derive(Clone)] #[derive(Clone)]
@@ -234,9 +414,127 @@ impl WineRuntime {
prefix, prefix,
wine_bin, wine_bin,
wine_root, wine_root,
app_bundle: app,
}) })
} }
/// Convert a host path inside this Wine prefix into a Windows path (e.g. `C:\osu!\osu!.exe`).
pub fn to_windows_path(&self, path: &Path) -> String {
let path_str = path.to_string_lossy();
if path_str.contains('\\')
|| (path_str.len() >= 2 && path_str.chars().nth(1) == Some(':'))
{
return path_str.into_owned();
}
let drive_c = self.prefix.join("drive_c");
let canon_path = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
let canon_drive_c = fs::canonicalize(&drive_c).unwrap_or(drive_c);
if let Ok(rel) = canon_path.strip_prefix(&canon_drive_c) {
return format!("C:\\{}", rel.display()).replace('/', "\\");
}
if let Ok(rel) = path.strip_prefix(self.prefix.join("drive_c")) {
return format!("C:\\{}", rel.display()).replace('/', "\\");
}
if let Some(drive_c_ancestor) = canon_path
.ancestors()
.find(|a| a.file_name() == Some(OsStr::new("drive_c")))
&& let Ok(rel) = canon_path.strip_prefix(drive_c_ancestor) {
return format!("C:\\{}", rel.display()).replace('/', "\\");
}
// If outside drive_c, Wine maps the Unix root filesystem to Z:\
let path_display = canon_path.display().to_string();
if path_display.starts_with('/') {
format!("Z:{}", path_display).replace('/', "\\")
} else {
path_display
}
}
fn apply_wine_environment(&self, command: &mut Command) {
command.env("WINEPREFIX", &self.prefix);
command.env("WINEDEBUG", "-all");
// DO NOT disable mscoree! osu! and its patcher are .NET / CLR assemblies that require mscoree.dll.
// Disabling mscoree causes Wine to fail with status 0xc0000135 (STATUS_DLL_NOT_FOUND, exit code 53).
// Only suppress gecko html engine installer prompts.
command.env("WINEDLLOVERRIDES", "mshtml=");
command.env("FREETYPE_PROPERTIES", "truetype:interpreter-version=35");
let mut library_paths = Vec::new();
if let Some(app) = &self.app_bundle {
for dir in [
app.join("Contents/Frameworks"),
app.join("Contents/Frameworks/wswine.bundle/lib"),
app.join("Contents/Frameworks/wswine.bundle/lib64"),
app.join("Contents/Frameworks/wswine.bundle/lib32on64"),
app.join("Contents/SharedSupport/wine/lib"),
app.join("Contents/SharedSupport/wine/lib64"),
app.join("Contents/SharedSupport/wine/lib32on64"),
app.join("Frameworks"),
] {
if dir.is_dir() {
library_paths.push(dir);
}
}
}
for dir in [
self.prefix.join("Frameworks"),
self.prefix.join("lib"),
self.prefix.join("lib64"),
self.prefix.join("lib32on64"),
] {
if dir.is_dir() {
library_paths.push(dir);
}
}
if let Some(wine_root) = &self.wine_root {
for dir in [
wine_root.join("lib"),
wine_root.join("lib64"),
wine_root.join("lib32on64"),
wine_root.clone(),
] {
if dir.is_dir() {
library_paths.push(dir);
}
}
}
for system_dir in [
PathBuf::from("/opt/local/lib"),
PathBuf::from("/usr/lib"),
PathBuf::from("/usr/libexec"),
PathBuf::from("/usr/lib/system"),
PathBuf::from("/opt/X11/lib"),
] {
if system_dir.is_dir() {
library_paths.push(system_dir);
}
}
if let Some(existing) = std::env::var_os("DYLD_FALLBACK_LIBRARY_PATH") {
library_paths.extend(std::env::split_paths(&existing));
}
if let Ok(library_path) = std::env::join_paths(library_paths) {
command.env("DYLD_FALLBACK_LIBRARY_PATH", &library_path);
command.env("WINESKIN_LIB_PATH_FOR_FALLBACK", &library_path);
}
let mut paths = vec![self.wine_bin.clone()];
if let Some(existing) = std::env::var_os("PATH") {
paths.extend(std::env::split_paths(&existing));
}
if let Ok(path) = std::env::join_paths(paths) {
command.env("PATH", path);
}
}
/// Spawn a Windows executable through the wrapper's Wine runtime. /// Spawn a Windows executable through the wrapper's Wine runtime.
pub fn spawn(&self, exe: &Path, args: &[&str]) -> Result<Child, String> { pub fn spawn(&self, exe: &Path, args: &[&str]) -> Result<Child, String> {
let loader = self.loader_for(exe); let loader = self.loader_for(exe);
@@ -247,47 +545,17 @@ impl WineRuntime {
)); ));
} }
let win_exe = self.to_windows_path(exe);
let mut command = Command::new(&loader); let mut command = Command::new(&loader);
command.arg(exe).args(args); command.arg(&win_exe).args(args);
command.current_dir(exe.parent().unwrap_or(&self.prefix)); command.current_dir(exe.parent().unwrap_or(&self.prefix));
command command
.stdin(Stdio::null()) .stdin(Stdio::null())
.stdout(Stdio::piped()) .stdout(Stdio::piped())
.stderr(Stdio::piped()); .stderr(Stdio::piped());
command.env("WINEPREFIX", &self.prefix); self.apply_wine_environment(&mut command);
command.env("WINEDEBUG", "-all");
command.env("WINEDLLOVERRIDES", "mscoree,mshtml=");
command.env("FREETYPE_PROPERTIES", "truetype:interpreter-version=35");
if let Some(wine_root) = &self.wine_root {
let mut library_paths = vec![
wine_root.join("lib"),
wine_root.join("lib64"),
wine_root.join("lib32on64"),
wine_root.clone(),
PathBuf::from("/opt/local/lib"),
PathBuf::from("/usr/lib"),
PathBuf::from("/usr/libexec"),
PathBuf::from("/usr/lib/system"),
PathBuf::from("/opt/X11/lib"),
];
if let Some(existing) = std::env::var_os("DYLD_FALLBACK_LIBRARY_PATH") {
library_paths.extend(std::env::split_paths(&existing));
}
if let Ok(library_path) = std::env::join_paths(library_paths) {
command.env("DYLD_FALLBACK_LIBRARY_PATH", &library_path);
command.env("WINESKIN_LIB_PATH_FOR_FALLBACK", &library_path);
}
}
let mut paths = vec![self.wine_bin.clone()];
if let Some(existing) = std::env::var_os("PATH") {
paths.extend(std::env::split_paths(&existing));
}
if let Ok(path) = std::env::join_paths(paths) {
command.env("PATH", path);
}
let executable_name = exe let executable_name = exe
.file_name() .file_name()
@@ -303,6 +571,39 @@ impl WineRuntime {
}) })
} }
/// Spawn a Windows executable in the background (detached) through Wine.
pub fn spawn_detached(&self, exe: &Path, args: &[&str]) -> Result<(), String> {
let loader = self.loader_for(exe);
if !loader.is_file() {
return Err(format!(
"Wine loader not found at {}. The wrapper may be incomplete.",
loader.display()
));
}
let win_exe = self.to_windows_path(exe);
let mut command = Command::new(&loader);
command.arg(&win_exe).args(args);
command.current_dir(exe.parent().unwrap_or(&self.prefix));
command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
self.apply_wine_environment(&mut command);
command.spawn().map_err(|error| {
format!(
"Failed to start detached process through Wine ({}): {}",
loader.display(),
error
)
})?;
Ok(())
}
/// Stop every process that belongs to this Wine prefix. /// Stop every process that belongs to this Wine prefix.
pub async fn kill_prefix(&self) { pub async fn kill_prefix(&self) {
let wineserver = self.wine_bin.join("wineserver"); let wineserver = self.wine_bin.join("wineserver");
@@ -310,14 +611,15 @@ impl WineRuntime {
return; return;
} }
let _ = Command::new(wineserver) let mut cmd = Command::new(wineserver);
.arg("-k") cmd.arg("-k")
.env("WINEPREFIX", &self.prefix)
.stdin(Stdio::null()) .stdin(Stdio::null())
.stdout(Stdio::null()) .stdout(Stdio::null())
.stderr(Stdio::null()) .stderr(Stdio::null());
.status()
.await; self.apply_wine_environment(&mut cmd);
let _ = cmd.status().await;
} }
fn loader_for(&self, exe: &Path) -> PathBuf { fn loader_for(&self, exe: &Path) -> PathBuf {
@@ -325,7 +627,7 @@ impl WineRuntime {
let candidates: &[&str] = if is_64_bit { let candidates: &[&str] = if is_64_bit {
&["wine64", "wine"] &["wine64", "wine"]
} else { } else {
&["wine32on64", "wine", "wine64"] &["wine32on64", "wine64", "wine"]
}; };
candidates candidates
@@ -336,15 +638,141 @@ impl WineRuntime {
} }
} }
/// Prepare the osu! and Wine prefix environment before launching the game.
///
/// 1. Removes stale update files left behind by previous crashes (`.require_update`,
/// `help.txt`, `_pending`), which otherwise force `osu!.exe` to start in updater mode
/// and launch the game without command-line arguments.
/// 2. Resets `_UpdateFailCount` in `osu!.cfg` and `UpdatePending` in user configs.
/// 3. Ensures `execute.bat` points to `ez-pp.farm` rather than external servers.
/// 4. Removes any loose `ManagedInjector.Lib.dll` in the patcher folder to avoid overriding
/// the embedded patched assembly.
/// 5. Cleans Apple Braille font entries from `user.reg` and `system.reg` in the Wine prefix,
/// preventing a fatal FreeType/GDI+ AccessViolationException (exit code 5) on macOS.
pub async fn prepare_osu_environment(folder: &Path, runtime: &WineRuntime) {
clean_wine_font_registry(runtime).await;
// 1. Remove stale update trigger files left behind by crashes
let _ = fs::remove_file(folder.join(".require_update"));
let _ = fs::remove_file(folder.join("help.txt"));
let _ = fs::remove_dir_all(folder.join("_pending"));
// 2. Remove loose ManagedInjector.Lib.dll in patcher folder if present
let _ = fs::remove_file(folder.join("EZPPLauncher/patcher/ManagedInjector.Lib.dll"));
// 3. Reset update fail count in osu!.cfg
let cfg_path = folder.join("osu!.cfg");
if cfg_path.is_file()
&& let Ok(content) = fs::read_to_string(&cfg_path)
&& content.contains("_UpdateFailCount") {
let updated = content
.lines()
.map(|line| {
if line.trim_start().starts_with("_UpdateFailCount") {
"_UpdateFailCount = 0"
} else {
line
}
})
.collect::<Vec<_>>()
.join("\n");
let _ = fs::write(&cfg_path, updated);
}
// 4. Update execute.bat if present to use ez-pp.farm
let bat_path = folder.join("execute.bat");
if bat_path.is_file()
&& let Ok(content) = fs::read_to_string(&bat_path)
&& content.contains("lucoa.best") {
let updated = content.replace("lucoa.best", "ez-pp.farm");
let _ = fs::write(&bat_path, updated);
}
}
async fn clean_wine_font_registry(runtime: &WineRuntime) {
let mut needs_clean = false;
for reg_name in &["user.reg", "system.reg"] {
let reg_path = runtime.prefix.join(reg_name);
if reg_path.is_file()
&& let Ok(content) = fs::read_to_string(&reg_path)
&& content.contains("Apple Braille") {
needs_clean = true;
break;
}
}
if needs_clean {
runtime.kill_prefix().await;
for reg_name in &["user.reg", "system.reg"] {
let reg_path = runtime.prefix.join(reg_name);
if reg_path.is_file()
&& let Ok(content) = fs::read_to_string(&reg_path)
&& content.contains("Apple Braille") {
let cleaned: String = content
.lines()
.filter(|line| !line.contains("Apple Braille"))
.collect::<Vec<_>>()
.join("\n") + "\n";
let _ = fs::write(&reg_path, cleaned);
log::info!(
target: "osu",
"Removed Apple Braille font entries from {}",
reg_path.display()
);
}
}
}
}
/// Run osu! (`-devserver ez-pp.farm`) and wait until the game exits. /// Run osu! (`-devserver ez-pp.farm`) and wait until the game exits.
pub async fn run_osu(osu_folder: &str, patch: bool) -> Result<(), String> { pub async fn run_osu(
osu_folder: &str,
patch: bool,
game_optimization: bool,
) -> Result<(), String> {
if game_optimization {
log::info!(target: "osu", "Game optimization active on macOS");
}
let folder = Path::new(osu_folder); let folder = Path::new(osu_folder);
let runtime = WineRuntime::for_osu_folder(folder).map_err(|error| { let runtime = WineRuntime::for_osu_folder(folder).map_err(|error| {
log::error!(target: "osu", "Could not prepare the Wine runtime: {error}"); log::error!(target: "osu", "Could not prepare the Wine runtime: {error}");
error error
})?; })?;
prepare_osu_environment(folder, &runtime).await;
// In Wineskin wrappers, bridge.exe bridges Discord RPC / IPC pipes.
// Start bridge.exe if present and not already running.
let bridge_exe = folder.join("bridge.exe");
if bridge_exe.is_file() {
let is_running = {
let mut system = sysinfo::System::new_all();
system.refresh_processes(sysinfo::ProcessesToUpdate::All, true);
system.processes().values().any(|process| {
process
.name()
.to_string_lossy()
.to_ascii_lowercase()
.contains("bridge.exe")
|| process
.cmd()
.iter()
.any(|arg| arg.to_string_lossy().to_ascii_lowercase().contains("bridge.exe"))
})
};
if !is_running {
if let Err(error) = runtime.spawn_detached(&bridge_exe, &[]) {
log::warn!(target: "osu", "Could not start bridge.exe: {error}");
} else {
// Give bridge.exe and the Wine prefix environment a moment to initialize.
sleep(Duration::from_millis(600)).await;
}
}
}
let osu_exe = folder.join("osu!.exe");
let mut game = runtime let mut game = runtime
.spawn(&folder.join("osu!.exe"), &["-devserver", "ez-pp.farm"]) .spawn(&osu_exe, &["-devserver", "ez-pp.farm"])
.map_err(|error| { .map_err(|error| {
log::error!(target: "osu", "Could not start osu!: {error}"); log::error!(target: "osu", "Could not start osu!: {error}");
error error
@@ -356,19 +784,110 @@ pub async fn run_osu(osu_folder: &str, patch: bool) -> Result<(), String> {
crate::logging::capture_osu_output(&mut game); crate::logging::capture_osu_output(&mut game);
if patch { if patch {
if let Err(error) = start_patcher(&runtime, folder).await { let runtime_clone = runtime.clone();
log::warn!(target: "patcher", "Could not start the patcher: {error}"); let folder_buf = folder.to_path_buf();
} tauri::async_runtime::spawn(async move {
if let Err(error) = start_patcher(&runtime_clone, &folder_buf).await {
log::warn!(target: "patcher", "Could not start the patcher: {error}");
}
});
} }
match game.wait().await { // Wine cold startup handling:
Ok(status) => log::info!(target: "osu", "osu! exited with {status}"), // If Wine starts cold, concurrent background service and font cache initialization
// in Wine can cause osu! to exit quickly with status 5 (STATUS_ACCESS_VIOLATION).
// Once the prefix is initialized, an automatic retry starts the game cleanly.
let start_time = Instant::now();
let mut wait_result = game.wait().await;
if let Ok(status) = &wait_result
&& status.code() == Some(5) && start_time.elapsed() < StdDuration::from_secs(6) {
log::warn!(
target: "osu",
"osu! exited early with status 5 during Wine cold start; retrying now that Wine runtime is initialized..."
);
let _ = fs::remove_file(folder.join(".require_update"));
sleep(Duration::from_millis(500)).await;
let mut retry_game = runtime
.spawn(&osu_exe, &["-devserver", "ez-pp.farm"])
.map_err(|error| {
log::error!(target: "osu", "Could not restart osu!: {error}");
error
})?;
if let Some(pid) = retry_game.id() {
log::info!(target: "osu", "osu! restarted through Wine (pid {pid})");
}
crate::logging::capture_osu_output(&mut retry_game);
wait_result = retry_game.wait().await;
}
match &wait_result {
Ok(status) => log::info!(target: "osu", "osu! loader exited with {status}"),
Err(error) => { Err(error) => {
log::warn!(target: "osu", "Could not wait for osu!: {error}"); log::warn!(target: "osu", "Could not wait for osu!: {error}");
return Err(format!("Failed to wait for osu!: {}", error)); return Err(format!("Failed to wait for osu!: {}", error));
} }
} }
// Process lifecycle handling:
// When osu! starts, it frequently acts as an updater/bootstrap process that closes
// with exit status 0 after spawning the real, detached game process (`osu!.exe`).
// If an osu! game process is running or appears shortly, we keep waiting until the
// entire game session is finished before returning control to the launcher.
let initial_session_duration = start_time.elapsed();
let mut system = sysinfo::System::new_all();
system.refresh_processes(sysinfo::ProcessesToUpdate::All, true);
let mut game_active = system
.processes()
.values()
.any(crate::utils::is_osu_game_process);
// If no osu! game process is immediately detected and the initial process
// exited very quickly (< 15 seconds), it may have been the bootstrap updater
// that hasn't finished spawning the detached game process yet.
if !game_active && initial_session_duration < StdDuration::from_secs(15) {
let grace_deadline = Instant::now() + StdDuration::from_secs(8);
while Instant::now() < grace_deadline {
sleep(Duration::from_millis(400)).await;
system.refresh_processes(sysinfo::ProcessesToUpdate::All, true);
if system
.processes()
.values()
.any(crate::utils::is_osu_game_process)
{
game_active = true;
break;
}
}
}
if game_active {
log::info!(
target: "osu",
"osu! game process active; waiting for game session to finish..."
);
loop {
sleep(Duration::from_millis(1000)).await;
system.refresh_processes(sysinfo::ProcessesToUpdate::All, true);
if !system
.processes()
.values()
.any(crate::utils::is_osu_game_process)
{
log::info!(target: "osu", "osu! game session finished");
break;
}
}
} else {
log::info!(target: "osu", "No active osu! game process found after loader exit");
}
runtime.kill_prefix().await;
Ok(()) Ok(())
} }
@@ -386,7 +905,16 @@ async fn start_patcher(runtime: &WineRuntime, osu_folder: &Path) -> Result<(), S
)); ));
} }
wait_for_osu_game().await; if !wait_for_osu_game().await {
return Err("Could not detect the osu! process for patcher".into());
}
if let Err(error) = crate::utils::ensure_patcher_compatibility(&patcher_exe) {
log::warn!(
target: "patcher",
"Could not ensure patcher compatibility: {error}"
);
}
log::info!( log::info!(
target: "patcher", target: "patcher",
@@ -410,38 +938,67 @@ async fn start_patcher(runtime: &WineRuntime, osu_folder: &Path) -> Result<(), S
Ok(()) Ok(())
} }
/// Wait until the Wine-hosted osu! process exists, then give it time to create /// Wait until osu! creates its game window (matching Windows and Linux launch logic).
/// its game window. Wine does not expose the window title to the launcher here, /// Polls window titles and waits until a non-empty, non-updater window appears.
/// so the process is the best signal available. async fn wait_for_osu_game() -> bool {
async fn wait_for_osu_game() { let mut sys = sysinfo::System::new_all();
let mut system = sysinfo::System::new_all(); let deadline = Instant::now() + StdDuration::from_secs(60);
let deadline = Instant::now() + StdDuration::from_secs(30);
let mut detected = false;
while Instant::now() < deadline { loop {
system.refresh_processes(sysinfo::ProcessesToUpdate::All, true); if Instant::now() > deadline {
if system log::warn!(
.processes() target: "patcher",
.values() "Timed out waiting for osu! game window for patcher"
.any(crate::utils::is_osu_game_process) );
{ return false;
detected = true; }
break;
// On macOS, Wine's window server process (wine64-preloader) owns the native
// macOS windows, which may not match the client wine32on64 PID directly.
// Scanning Wine/osu! windows directly via get_window_title_by_pid(Pid::from(0))
// reliably detects both named and bounds-identified game and updater windows.
let title = crate::utils::get_window_title_by_pid(sysinfo::Pid::from(0));
if !title.is_empty() {
if !title.contains("updater") {
log::info!(
target: "patcher",
"Detected osu! window \"{title}\" via Wine WindowServer scan; ready for patcher"
);
return true;
} else {
log::debug!(
target: "patcher",
"Detected osu! updater window \"{title}\" via Wine WindowServer scan; waiting for game..."
);
}
}
sys.refresh_processes(sysinfo::ProcessesToUpdate::All, true);
for process in sys.processes().values() {
if crate::utils::is_osu_process(process) || process.name() == "osu!.exe" {
let pid = process.pid();
let title = crate::utils::get_window_title_by_pid(pid);
if !title.is_empty() {
if !title.contains("updater") {
log::info!(
target: "patcher",
"Detected osu! window \"{title}\" (pid {pid}); ready for patcher"
);
return true;
} else {
log::debug!(
target: "patcher",
"Detected osu! updater window \"{title}\" (pid {pid}); waiting for game..."
);
}
}
}
} }
sleep(Duration::from_millis(500)).await; sleep(Duration::from_millis(500)).await;
} }
if !detected {
log::warn!(
target: "patcher",
"Could not detect the osu! process; starting the patcher anyway"
);
}
// Wine gives no reliable window-ready signal, so leave the game a moment
// to finish initializing before the patcher attaches to it.
sleep(Duration::from_secs(8)).await;
} }
/// Run `osu!.exe -repair`, wait for the updater and close the game it starts. /// Run `osu!.exe -repair`, wait for the updater and close the game it starts.
@@ -514,17 +1071,15 @@ pub fn resolve_osu_folder(folder: &Path) -> Option<PathBuf> {
let mut prefixes = Vec::new(); let mut prefixes = Vec::new();
if folder.file_name() == Some(OsStr::new("drive_c")) { if folder.file_name() == Some(OsStr::new("drive_c"))
if let Some(parent) = canonical_prefix(folder) { && let Some(parent) = canonical_prefix(folder) {
prefixes.push(parent); prefixes.push(parent);
} }
}
if folder.join("drive_c").is_dir() { if folder.join("drive_c").is_dir()
if let Some(parent) = canonical_prefix(&folder.join("drive_c")) { && let Some(parent) = canonical_prefix(&folder.join("drive_c")) {
prefixes.push(parent); prefixes.push(parent);
} }
}
if folder.extension() == Some(OsStr::new("app")) || folder.join("Contents").is_dir() { if folder.extension() == Some(OsStr::new("app")) || folder.join("Contents").is_dir() {
for drive_c in [ for drive_c in [
@@ -532,11 +1087,10 @@ pub fn resolve_osu_folder(folder: &Path) -> Option<PathBuf> {
folder.join("Contents/SharedSupport/drive_c"), folder.join("Contents/SharedSupport/drive_c"),
folder.join("Contents/SharedSupport/prefix/drive_c"), folder.join("Contents/SharedSupport/prefix/drive_c"),
] { ] {
if drive_c.is_dir() { if drive_c.is_dir()
if let Some(parent) = canonical_prefix(&drive_c) { && let Some(parent) = canonical_prefix(&drive_c) {
prefixes.push(parent); prefixes.push(parent);
} }
}
} }
let mut drive_dirs = Vec::new(); let mut drive_dirs = Vec::new();
@@ -675,11 +1229,10 @@ fn find_drive_c_dirs(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) {
// Wineskin wrappers often add a convenience drive_c symlink at // Wineskin wrappers often add a convenience drive_c symlink at
// the app root. Resolve it to the real prefix so WINEPREFIX points // the app root. Resolve it to the real prefix so WINEPREFIX points
// at Contents/Resources instead of the bundle itself. // at Contents/Resources instead of the bundle itself.
if path.file_name() == Some(OsStr::new("drive_c")) { if path.file_name() == Some(OsStr::new("drive_c"))
if let Ok(canonical) = fs::canonicalize(&path) { && let Ok(canonical) = fs::canonicalize(&path) {
out.push(canonical); out.push(canonical);
} }
}
continue; continue;
} }
@@ -783,9 +1336,15 @@ fn find_wine_bin(prefix: &Path, app: Option<&Path>) -> Option<(PathBuf, Option<P
app.join("Contents/SharedSupport/wine"), app.join("Contents/SharedSupport/wine"),
app.join("Contents/Resources/WineskinEngine.bundle/Wine"), app.join("Contents/Resources/WineskinEngine.bundle/Wine"),
app.join("Contents/Frameworks/wswine.bundle"), app.join("Contents/Frameworks/wswine.bundle"),
app.join("Wineskin.app/Contents/Resources"),
] { ] {
push_wine_root(&mut candidates, root); push_wine_root(&mut candidates, root);
} }
let wineskin_res = app.join("Wineskin.app/Contents/Resources");
if has_wine_loader(&wineskin_res) {
candidates.push((wineskin_res.clone(), Some(wineskin_res)));
}
} }
for root in [ for root in [
@@ -822,12 +1381,11 @@ fn find_wine_bin(prefix: &Path, app: Option<&Path>) -> Option<(PathBuf, Option<P
} }
for binary in ["wine64", "wine32on64", "wine"] { for binary in ["wine64", "wine32on64", "wine"] {
if let Some(path) = find_in_path(binary) { if let Some(path) = find_in_path(binary)
if let Some(bin) = path.parent() { && let Some(bin) = path.parent() {
candidates.push((bin.to_path_buf(), None)); candidates.push((bin.to_path_buf(), None));
break; break;
} }
}
} }
candidates.into_iter().find(|(bin, _)| has_wine_loader(bin)) candidates.into_iter().find(|(bin, _)| has_wine_loader(bin))
@@ -847,7 +1405,7 @@ fn has_wine_loader(bin: &Path) -> bool {
} }
fn wine_version_for(bin: &Path) -> Option<String> { fn wine_version_for(bin: &Path) -> Option<String> {
let loader = ["wine64", "wine", "wine32on64"] let loader = ["wine64", "wine32on64", "wine"]
.iter() .iter()
.map(|name| bin.join(name)) .map(|name| bin.join(name))
.find(|path| path.is_file())?; .find(|path| path.is_file())?;
@@ -905,3 +1463,47 @@ fn pe_machine(exe: &Path) -> Option<u16> {
Some(u16::from_le_bytes([header[4], header[5]])) Some(u16::from_le_bytes([header[4], header[5]]))
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_to_windows_path_inside_drive_c() {
let runtime = WineRuntime {
prefix: PathBuf::from("/Users/test/wine_prefix"),
wine_bin: PathBuf::from("/opt/wine/bin"),
wine_root: None,
app_bundle: None,
};
let exe = PathBuf::from("/Users/test/wine_prefix/drive_c/osu!/osu!.exe");
assert_eq!(runtime.to_windows_path(&exe), "C:\\osu!\\osu!.exe");
}
#[test]
fn test_to_windows_path_already_windows() {
let runtime = WineRuntime {
prefix: PathBuf::from("/Users/test/wine_prefix"),
wine_bin: PathBuf::from("/opt/wine/bin"),
wine_root: None,
app_bundle: None,
};
let exe = Path::new("C:\\osu!\\osu!.exe");
assert_eq!(runtime.to_windows_path(exe), "C:\\osu!\\osu!.exe");
}
#[test]
fn test_to_windows_path_outside_drive_c() {
let runtime = WineRuntime {
prefix: PathBuf::from("/Users/test/wine_prefix"),
wine_bin: PathBuf::from("/opt/wine/bin"),
wine_root: None,
app_bundle: None,
};
let exe = PathBuf::from("/Applications/other.exe");
assert_eq!(runtime.to_windows_path(&exe), "Z:\\Applications\\other.exe");
}
}
+62 -80
View File
@@ -4,6 +4,7 @@ use std::sync::Mutex as StdMutex;
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
use tauri::{AppHandle, RunEvent}; use tauri::{AppHandle, RunEvent};
use tokio::sync::{mpsc, oneshot}; use tokio::sync::{mpsc, oneshot};
use tokio::task::JoinHandle;
use tokio::time::{Duration, interval}; use tokio::time::{Duration, interval};
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
@@ -53,23 +54,19 @@ impl Default for PresenceData {
enum PresenceCommand { enum PresenceCommand {
Connect(oneshot::Sender<bool>), Connect(oneshot::Sender<bool>),
Disconnect(oneshot::Sender<()>), Disconnect(oneshot::Sender<()>),
UpdateData(PresenceData), UpdateData(Box<PresenceData>),
IsConnected(oneshot::Sender<bool>), IsConnected(oneshot::Sender<bool>),
} }
enum ReconnectResult {
Connected(AsyncDiscordIpcClient),
Failed,
}
struct PresenceActor { struct PresenceActor {
receiver: mpsc::Receiver<PresenceCommand>, receiver: mpsc::Receiver<PresenceCommand>,
reconnect_rx: mpsc::Receiver<ReconnectResult>, reconnect_rx: mpsc::Receiver<Box<AsyncDiscordIpcClient>>,
reconnect_tx: mpsc::Sender<ReconnectResult>, reconnect_tx: mpsc::Sender<Box<AsyncDiscordIpcClient>>,
reconnect_task: Option<JoinHandle<()>>,
client: Option<AsyncDiscordIpcClient>, client: Option<AsyncDiscordIpcClient>,
data: PresenceData, data: PresenceData,
start_timestamp: i64, start_timestamp: i64,
reconnecting: bool, should_connect: bool,
} }
impl PresenceActor { impl PresenceActor {
@@ -85,10 +82,11 @@ impl PresenceActor {
receiver, receiver,
reconnect_rx, reconnect_rx,
reconnect_tx, reconnect_tx,
reconnect_task: None,
client: None, client: None,
data: PresenceData::default(), data: PresenceData::default(),
start_timestamp: start, start_timestamp: start,
reconnecting: false, should_connect: false,
} }
} }
@@ -103,7 +101,7 @@ impl PresenceActor {
PresenceCommand::Connect(resp) => self.cmd_connect(resp).await, PresenceCommand::Connect(resp) => self.cmd_connect(resp).await,
PresenceCommand::Disconnect(resp) => self.cmd_disconnect(resp).await, PresenceCommand::Disconnect(resp) => self.cmd_disconnect(resp).await,
PresenceCommand::UpdateData(data) => { PresenceCommand::UpdateData(data) => {
self.data = data; self.data = *data;
self.push_presence().await; self.push_presence().await;
} }
PresenceCommand::IsConnected(resp) => { PresenceCommand::IsConnected(resp) => {
@@ -112,17 +110,12 @@ impl PresenceActor {
} }
} }
Some(result) = self.reconnect_rx.recv() => { Some(client) = self.reconnect_rx.recv() => {
self.reconnecting = false; self.reconnect_task = None;
match result { if self.should_connect {
ReconnectResult::Connected(client) => { log::info!(target: "launcher", "Presence: reconnect succeeded");
log::info!(target: "launcher", "Presence: reconnect succeeded"); self.client = Some(*client);
self.client = Some(client); self.push_presence().await;
self.push_presence().await;
}
ReconnectResult::Failed => {
log::warn!(target: "launcher", "Presence: all reconnect attempts exhausted");
}
} }
} }
@@ -134,15 +127,19 @@ impl PresenceActor {
} }
async fn cmd_connect(&mut self, resp: oneshot::Sender<bool>) { async fn cmd_connect(&mut self, resp: oneshot::Sender<bool>) {
self.should_connect = true;
if self.client.is_some() { if self.client.is_some() {
let _ = resp.send(true); let _ = resp.send(true);
return; return;
} }
if self.reconnect_task.is_some() {
let _ = resp.send(false);
return;
}
match try_connect_once().await { match try_connect_once().await {
Some(client) => { Some(client) => {
self.client = Some(client); self.client = Some(client);
self.reconnecting = false;
self.push_presence().await; self.push_presence().await;
let _ = resp.send(true); let _ = resp.send(true);
} }
@@ -158,6 +155,10 @@ impl PresenceActor {
} }
async fn cmd_disconnect(&mut self, resp: oneshot::Sender<()>) { async fn cmd_disconnect(&mut self, resp: oneshot::Sender<()>) {
self.should_connect = false;
if let Some(task) = self.reconnect_task.take() {
task.abort();
}
if let Some(mut client) = self.client.take() { if let Some(mut client) = self.client.take() {
let _ = client.clear_activity().await; let _ = client.clear_activity().await;
log::info!(target: "launcher", "Presence: disconnected"); log::info!(target: "launcher", "Presence: disconnected");
@@ -188,16 +189,14 @@ impl PresenceActor {
builder = builder.small_text(text); builder = builder.small_text(text);
} }
if let Some(btn) = &self.data.dynamic_button { if let Some(btn) = &self.data.dynamic_button
if !btn.label.trim().is_empty() && !btn.url.trim().is_empty() { && !btn.label.trim().is_empty() && !btn.url.trim().is_empty() {
builder = builder.button(&btn.label, &btn.url); builder = builder.button(&btn.label, &btn.url);
} }
} if let Some(btn2) = &self.data.secondary_button
if let Some(btn2) = &self.data.secondary_button { && !btn2.label.trim().is_empty() && !btn2.url.trim().is_empty() {
if !btn2.label.trim().is_empty() && !btn2.url.trim().is_empty() {
builder = builder.button(&btn2.label, &btn2.url); builder = builder.button(&btn2.label, &btn2.url);
} }
}
let activity = builder.build(); let activity = builder.build();
@@ -208,37 +207,37 @@ impl PresenceActor {
e e
); );
self.client = None; self.client = None;
self.should_connect = true;
self.spawn_reconnect_task(); self.spawn_reconnect_task();
} }
} }
fn spawn_reconnect_task(&mut self) { fn spawn_reconnect_task(&mut self) {
if self.reconnecting { if self.reconnect_task.is_some() || !self.should_connect {
return; return;
} }
self.reconnecting = true;
let tx = self.reconnect_tx.clone(); let tx = self.reconnect_tx.clone();
tokio::spawn(async move { let task = tokio::spawn(async move {
const MAX_ATTEMPTS: u32 = 5; let mut attempt: u32 = 0;
for attempt in 1..=MAX_ATTEMPTS { loop {
let delay = Duration::from_secs(5 * attempt as u64); attempt = attempt.saturating_add(1);
let delay = Duration::from_secs((5 * u64::from(attempt)).min(30));
log::info!( log::info!(
target: "launcher", target: "launcher",
"Presence: reconnect attempt {}/{} in {:?}…", "Presence: reconnect attempt {} in {:?}…",
attempt, attempt,
MAX_ATTEMPTS,
delay delay
); );
tokio::time::sleep(delay).await; tokio::time::sleep(delay).await;
if let Some(client) = try_connect_once().await { if let Some(client) = try_connect_once().await {
let _ = tx.send(ReconnectResult::Connected(client)).await; let _ = tx.send(Box::new(client)).await;
return; return;
} }
} }
let _ = tx.send(ReconnectResult::Failed).await;
}); });
self.reconnect_task = Some(task);
} }
} }
@@ -302,52 +301,35 @@ pub async fn has_presence() -> bool {
false false
} }
#[allow(clippy::too_many_arguments)]
pub fn update_activity( pub fn update_activity(
state: Option<&str>, state: &str,
details: Option<&str>, details: &str,
large_image_key: Option<&str>, large_image_key: &str,
large_image_text: Option<&str>, large_image_text: &str,
small_image_key: Option<Option<String>>, small_image_key: Option<String>,
small_image_text: Option<Option<String>>, small_image_text: Option<String>,
button1: Option<Option<PresenceButton>>, button1: Option<PresenceButton>,
button2: Option<Option<PresenceButton>>, button2: Option<PresenceButton>,
show_timestamp: Option<bool>, show_timestamp: bool,
) { ) {
let data = { let data = {
let mut guard = PRESENCE_DATA.lock().unwrap(); let mut guard = PRESENCE_DATA.lock().unwrap();
if let Some(s) = state { guard.state = state.to_string();
guard.state = s.to_string(); guard.details = details.to_string();
} guard.large_image_key = large_image_key.to_string();
if let Some(d) = details { guard.large_image_text = large_image_text.to_string();
guard.details = d.to_string(); guard.small_image_key = small_image_key;
} guard.small_image_text = small_image_text;
if let Some(img) = large_image_key { guard.dynamic_button = button1;
guard.large_image_key = img.to_string(); guard.secondary_button = button2;
} guard.show_timestamp = show_timestamp;
if let Some(txt) = large_image_text {
guard.large_image_text = txt.to_string();
}
if let Some(key) = small_image_key {
guard.small_image_key = key;
}
if let Some(text) = small_image_text {
guard.small_image_text = text;
}
if let Some(b1) = button1 {
guard.dynamic_button = b1;
}
if let Some(b2) = button2 {
guard.secondary_button = b2;
}
if let Some(ts) = show_timestamp {
guard.show_timestamp = ts;
}
guard.clone() guard.clone()
}; };
let tx = PRESENCE_TX.clone(); let tx = PRESENCE_TX.clone();
tokio::spawn(async move { tokio::spawn(async move {
let _ = tx.send(PresenceCommand::UpdateData(data)).await; let _ = tx.send(PresenceCommand::UpdateData(Box::new(data))).await;
}); });
} }
@@ -368,7 +350,7 @@ pub fn update_status(state: Option<&str>, details: Option<&str>, large_image_key
let tx = PRESENCE_TX.clone(); let tx = PRESENCE_TX.clone();
tokio::spawn(async move { tokio::spawn(async move {
let _ = tx.send(PresenceCommand::UpdateData(data)).await; let _ = tx.send(PresenceCommand::UpdateData(Box::new(data))).await;
}); });
} }
@@ -382,7 +364,7 @@ pub fn update_user(username: Option<&str>, id: Option<&str>) {
let tx = PRESENCE_TX.clone(); let tx = PRESENCE_TX.clone();
tokio::spawn(async move { tokio::spawn(async move {
let _ = tx.send(PresenceCommand::UpdateData(data)).await; let _ = tx.send(PresenceCommand::UpdateData(Box::new(data))).await;
}); });
} }
@@ -398,7 +380,7 @@ pub fn set_button(label: &str, url: &str) {
let tx = PRESENCE_TX.clone(); let tx = PRESENCE_TX.clone();
tokio::spawn(async move { tokio::spawn(async move {
let _ = tx.send(PresenceCommand::UpdateData(data)).await; let _ = tx.send(PresenceCommand::UpdateData(Box::new(data))).await;
}); });
} }
@@ -411,7 +393,7 @@ pub fn clear_button() {
let tx = PRESENCE_TX.clone(); let tx = PRESENCE_TX.clone();
tokio::spawn(async move { tokio::spawn(async move {
let _ = tx.send(PresenceCommand::UpdateData(data)).await; let _ = tx.send(PresenceCommand::UpdateData(Box::new(data))).await;
}); });
} }
+399 -7
View File
@@ -40,15 +40,14 @@ pub fn is_osu_process(process: &sysinfo::Process) -> bool {
return true; return true;
} }
if let Some(exe) = process.exe() { if let Some(exe) = process.exe()
if exe && exe
.file_name() .file_name()
.map(|file_name| file_name.to_string_lossy().to_ascii_lowercase() == "osu!.exe") .map(|file_name| file_name.to_string_lossy().to_ascii_lowercase() == "osu!.exe")
.unwrap_or(false) .unwrap_or(false)
{ {
return true; return true;
} }
}
process.cmd().iter().any(|arg| { process.cmd().iter().any(|arg| {
arg.to_string_lossy() arg.to_string_lossy()
@@ -103,7 +102,7 @@ fn find_osu_user_config_path<P: AsRef<Path>>(folder_path: P) -> Option<PathBuf>
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
candidates.sort_by(|a, b| b.0.cmp(&a.0)); candidates.sort_by_key(|b| std::cmp::Reverse(b.0));
candidates.into_iter().next().map(|(_, path)| path) candidates.into_iter().next().map(|(_, path)| path)
} }
@@ -261,7 +260,7 @@ pub fn get_osu_config<P: AsRef<Path>>(
} }
} }
return Some(config_map); Some(config_map)
} }
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
@@ -353,8 +352,196 @@ pub fn get_window_title_by_pid(target_pid: Pid) -> String {
} }
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
pub fn get_window_title_by_pid(_pid: Pid) -> String { pub fn get_window_title_by_pid(target_pid: Pid) -> String {
String::new() use objc2::msg_send;
use objc2::runtime::AnyObject;
use std::ffi::CStr;
#[repr(C)]
struct CGPoint {
x: f64,
y: f64,
}
#[repr(C)]
struct CGSize {
width: f64,
height: f64,
}
#[repr(C)]
struct CGRect {
origin: CGPoint,
size: CGSize,
}
unsafe extern "C" {
fn CGWindowListCopyWindowInfo(option: u32, relative_to_window: u32) -> *mut AnyObject;
fn CGRectMakeWithDictionaryRepresentation(
dict: *const AnyObject,
rect: *mut CGRect,
) -> bool;
}
unsafe {
// kCGWindowListOptionAll = 0, kCGNullWindowID = 0
let window_list: *mut AnyObject = CGWindowListCopyWindowInfo(0, 0);
if window_list.is_null() {
return String::new();
}
let count: usize = msg_send![window_list, count];
let pid_key: *mut AnyObject = msg_send![
objc2::class!(NSString),
stringWithUTF8String: c"kCGWindowOwnerPID".as_ptr()
];
let name_key: *mut AnyObject = msg_send![
objc2::class!(NSString),
stringWithUTF8String: c"kCGWindowName".as_ptr()
];
let owner_key: *mut AnyObject = msg_send![
objc2::class!(NSString),
stringWithUTF8String: c"kCGWindowOwnerName".as_ptr()
];
let bounds_key: *mut AnyObject = msg_send![
objc2::class!(NSString),
stringWithUTF8String: c"kCGWindowBounds".as_ptr()
];
let layer_key: *mut AnyObject = msg_send![
objc2::class!(NSString),
stringWithUTF8String: c"kCGWindowLayer".as_ptr()
];
let target_u32 = target_pid.as_u32();
// Pass 1: Try exact target_pid match.
// Pass 2: If target_pid produced no onscreen windows, check Wine/osu! owner windows
// (handles Wine 32-on-64 architecture where wine32on64 delegates window creation to wine64-preloader).
for fallback_pass in [false, true] {
let mut found_game_title = String::new();
let mut found_updater_title = String::new();
let mut has_game_window = false;
let mut has_updater_window = false;
for i in 0..count {
let dict: *mut AnyObject = msg_send![window_list, objectAtIndex: i];
if dict.is_null() {
continue;
}
let pid_num: *mut AnyObject = msg_send![dict, objectForKey: pid_key];
if pid_num.is_null() {
continue;
}
let pid_val: u32 = msg_send![pid_num, unsignedIntValue];
let is_match = if !fallback_pass {
target_u32 != 0 && pid_val == target_u32
} else {
let owner_str: *mut AnyObject = msg_send![dict, objectForKey: owner_key];
if !owner_str.is_null() {
let utf8: *const std::ffi::c_char = msg_send![owner_str, UTF8String];
if !utf8.is_null() {
if let Ok(owner) = CStr::from_ptr(utf8).to_str() {
let lower = owner.to_lowercase();
lower.contains("wine") || lower.contains("osu")
} else {
false
}
} else {
false
}
} else {
false
}
};
if !is_match {
continue;
}
// Check layer: valid application window layers are 0..=50
// (e.g. 0 for normal windows, 3 for floating/focused, 27 for Wine fullscreen/borderless shields)
let layer_num: *mut AnyObject = msg_send![dict, objectForKey: layer_key];
let layer: i32 = if !layer_num.is_null() {
msg_send![layer_num, intValue]
} else {
0
};
if !(0..=50).contains(&layer) {
continue;
}
// 1. Check kCGWindowName if available
let name_str: *mut AnyObject = msg_send![dict, objectForKey: name_key];
if !name_str.is_null() {
let utf8: *const std::ffi::c_char = msg_send![name_str, UTF8String];
if !utf8.is_null()
&& let Ok(s) = CStr::from_ptr(utf8).to_str() {
let trimmed = s.trim();
if !trimmed.is_empty() {
if trimmed.to_lowercase().contains("updater") {
found_updater_title = trimmed.to_string();
} else {
found_game_title = trimmed.to_string();
break;
}
}
}
}
// 2. Check window bounds
let bounds_dict: *mut AnyObject = msg_send![dict, objectForKey: bounds_key];
if !bounds_dict.is_null() {
let mut rect = CGRect {
origin: CGPoint { x: 0.0, y: 0.0 },
size: CGSize {
width: 0.0,
height: 0.0,
},
};
if CGRectMakeWithDictionaryRepresentation(bounds_dict, &mut rect) {
// Ignore menu bar overlays (height <= 50) and tiny dummy windows (<= 100x100)
if rect.size.height > 50.0 && rect.size.width > 100.0 {
// Ignore Wine's default 500x500 dummy desktop surface
let is_wine_default_desktop = (rect.size.width - 500.0).abs() < 2.0
&& (rect.size.height - 500.0).abs() < 2.0;
if !is_wine_default_desktop {
if rect.size.width >= 640.0 && rect.size.height >= 480.0 {
has_game_window = true;
break;
} else if rect.size.width >= 200.0 && rect.size.height >= 80.0 {
has_updater_window = true;
}
}
}
}
}
}
let has_result = !found_game_title.is_empty()
|| has_game_window
|| !found_updater_title.is_empty()
|| has_updater_window;
if has_result {
let _: () = msg_send![window_list, release];
if !found_game_title.is_empty() {
return found_game_title;
} else if has_game_window {
return "osu!".to_string();
} else if !found_updater_title.is_empty() {
return found_updater_title;
} else {
return "osu! updater".to_string();
}
}
}
let _: () = msg_send![window_list, release];
String::new()
}
} }
#[cfg(windows)] #[cfg(windows)]
@@ -513,3 +700,208 @@ pub fn encrypt_password(password: &str, entropy: &str) -> Result<String, String>
Ok(base64_string) Ok(base64_string)
} }
/// Check if the patcher binary has already been patched for .NET 4.0 compatibility under Wine.
pub fn is_compatible_patcher(data: &[u8]) -> bool {
let has_pbi_patch = data
.windows(6)
.any(|w| w == [0x1f, 0x18, 0x00, 0x00, 0x00, 0x00]);
let has_devserver_patch = data
.windows(7)
.any(|w| w == [0x26, 0x26, 0x2b, 0x0e, 0x00, 0x00, 0x00]);
has_pbi_patch && has_devserver_patch
}
/// Ensure `osu!.patcher.exe` is compatible with .NET Framework 4.0 runtime (used by Wine).
///
/// In .NET 4.0 (the runtime provided by Wine prefixes for osu! stable), generic `Marshal.SizeOf<T>()`
/// does not exist (added in .NET 4.5.1), causing a `MissingMethodException` when `GetCommandLine()`
/// queries `PROCESS_BASIC_INFORMATION`. Additionally:
/// 1. `Console.ReadKey()` crashes with `InvalidOperationException` when stdio is redirected without a console.
/// 2. `GetOsuPid()` checks for `" -devserver "` via PEB reading, which fails or is unreliable under Wine.
/// 3. Costura embeds `ManagedInjector.Lib` which also calls generic `Marshal.SizeOf<Native.ModuleEntry32>()`
/// and parses remote PE export tables through generic marshal APIs.
///
/// This function patches the binary in-place so it runs reliably under Wine.
pub fn ensure_patcher_compatibility(patcher_exe: &Path) -> Result<bool, String> {
if !patcher_exe.is_file() {
return Ok(false);
}
// Clean up loose ManagedInjector.Lib.dll if present, as CLR loads loose assemblies before Costura resources.
if let Some(parent) = patcher_exe.parent() {
let loose = parent.join("ManagedInjector.Lib.dll");
if loose.is_file() {
let _ = fs::remove_file(&loose);
}
}
let mut data = fs::read(patcher_exe)
.map_err(|e| format!("Failed to read {}: {e}", patcher_exe.display()))?;
let mut modified = false;
// Pattern 1 in GetCommandLine: ldloc.0, ldc.i4.0, ldloca.s 1, ldloc.1, call Marshal.SizeOf<PBI>
// [0x06, 0x16, 0x12, 0x01, 0x07, 0x28, 0x01, 0x00, 0x00, 0x2b]
let sizeof_pattern = [0x06, 0x16, 0x12, 0x01, 0x07, 0x28, 0x01, 0x00, 0x00, 0x2b];
if let Some(pos) = data
.windows(sizeof_pattern.len())
.position(|w| w == sizeof_pattern)
{
// Replace ldloc.1 (0x07) and call Marshal.SizeOf<PBI> (0x28, 0x01, 0x00, 0x00, 0x2b) with ldc.i4.s 24 (0x1f, 0x18) + 4 nops
let target = pos + 4;
data[target..target + 6].copy_from_slice(&[0x1f, 0x18, 0x00, 0x00, 0x00, 0x00]);
modified = true;
}
// Pattern 2 in Main catch handler: call Console.Write, call Console.ReadKey, pop, leave.s
// [0x28, 0x12, 0x00, 0x00, 0x0a, 0x28, 0x13, 0x00, 0x00, 0x0a, 0x26, 0xde]
let readkey_pattern = [
0x28, 0x12, 0x00, 0x00, 0x0a, 0x28, 0x13, 0x00, 0x00, 0x0a, 0x26, 0xde,
];
if let Some(pos) = data
.windows(readkey_pattern.len())
.position(|w| w == readkey_pattern)
{
// Replace call Console.ReadKey() (5 bytes) + pop (1 byte) with 6 nops
let target = pos + 5;
data[target..target + 6].copy_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
modified = true;
}
// Pattern 3 in GetOsuPid: devserver check bypass
// [0x72, 0x95, 0x01, 0x00, 0x70, 0x6f, 0x15, 0x00, 0x00, 0x0a, 0x2d, 0x0b]
let dev_pattern = [
0x72, 0x95, 0x01, 0x00, 0x70, 0x6f, 0x15, 0x00, 0x00, 0x0a, 0x2d, 0x0b,
];
if let Some(pos) = data
.windows(dev_pattern.len())
.position(|w| w == dev_pattern)
{
// Replace callvirt Contains + brtrue.s with pop, pop, br.s + 3 nops
let target = pos + 5;
data[target..target + 7].copy_from_slice(&[0x26, 0x26, 0x2b, 0x0e, 0x00, 0x00, 0x00]);
modified = true;
}
// Pattern 4: Costura embedded ManagedInjector.Lib resource at offset 0x1f00 (length 10020)
if data.len() >= 0x1f00 + 10020 && data.get(0x1efc..0x1f00) == Some(&[0x24, 0x27, 0x00, 0x00]) {
use flate2::read::DeflateDecoder;
use flate2::write::DeflateEncoder;
use flate2::Compression;
use std::io::{Read, Write};
let stream = &data[0x1f00..0x1f00 + 10020];
let mut decoder = DeflateDecoder::new(stream);
let mut decomp = Vec::new();
if decoder.read_to_end(&mut decomp).is_ok() {
let mut inner_modified = false;
// 4a. NativeHelper.GetModules: Marshal.SizeOf<ModuleEntry32>() -> ldc.i4 548
let module_pattern = [0x12, 0x04, 0x28, 0x08, 0x00, 0x00, 0x2b];
if let Some(pos) = decomp.windows(module_pattern.len()).position(|w| w == module_pattern) {
decomp[pos + 2..pos + 7].copy_from_slice(&[0x20, 0x24, 0x02, 0x00, 0x00]);
inner_modified = true;
}
// 4b. InjectableProcess.GetArchitecture: return NetFrameworkV4 (2) immediately
let arch_pattern = [
0x02, 0x7b, 0x0a, 0x00, 0x00, 0x04, 0x2c, 0x07, 0x02, 0x7b, 0x0a, 0x00, 0x00,
0x04, 0x2a,
];
if let Some(pos) = decomp.windows(arch_pattern.len()).position(|w| w == arch_pattern) {
decomp[pos..pos + 2].copy_from_slice(&[0x18, 0x2a]); // ldc.i4.2, ret
decomp[pos + 2..pos + 15].fill(0x00); // 13 nops
inner_modified = true;
}
// 4c. FrameworkInjectorBase.GetCorBindToRuntimeExAddress: return 0x17b55 directly without remote PE parsing
let corbind_pattern = [
0x03, 0x06, 0x7b, 0x65, 0x00, 0x00, 0x0a, 0x72, 0x3d, 0x03, 0x00, 0x70, 0x04,
0x28, 0x08, 0x00, 0x00, 0x06, 0x0b,
];
if let Some(pos) = decomp.windows(corbind_pattern.len()).position(|w| w == corbind_pattern) {
decomp[pos..pos + 6].copy_from_slice(&[0x20, 0x55, 0x7b, 0x01, 0x00, 0x0b]); // ldc.i4 0x17b55, stloc.1
decomp[pos + 6..pos + 19].fill(0x00); // 13 nops
inner_modified = true;
}
if inner_modified {
let mut encoder = DeflateEncoder::new(Vec::new(), Compression::best());
if encoder.write_all(&decomp).is_ok()
&& let Ok(mut compressed) = encoder.finish()
&& compressed.len() <= 10020 - 5 {
let remaining = 10020 - compressed.len();
let length = (remaining - 5) as u16;
let nlen = !length;
compressed.push(0x01); // BFINAL = 1, BTYPE = 00
compressed.push((length & 0xff) as u8);
compressed.push((length >> 8) as u8);
compressed.push((nlen & 0xff) as u8);
compressed.push((nlen >> 8) as u8);
compressed.extend(std::iter::repeat_n(0x00, length as usize));
if compressed.len() == 10020 {
data[0x1f00..0x1f00 + 10020].copy_from_slice(&compressed);
modified = true;
}
}
}
}
}
if modified {
fs::write(patcher_exe, &data)
.map_err(|e| format!("Failed to write {}: {e}", patcher_exe.display()))?;
log::info!(
target: "patcher",
"Applied .NET 4.0 compatibility patch to {}",
patcher_exe.display()
);
}
Ok(modified)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_patcher_compatibility_patch() {
let mut fake_binary = vec![0x90; 0x3000];
let pbi = [0x06, 0x16, 0x12, 0x01, 0x07, 0x28, 0x01, 0x00, 0x00, 0x2b];
fake_binary[10..10 + pbi.len()].copy_from_slice(&pbi);
let readkey = [
0x28, 0x12, 0x00, 0x00, 0x0a, 0x28, 0x13, 0x00, 0x00, 0x0a, 0x26, 0xde,
];
fake_binary[30..30 + readkey.len()].copy_from_slice(&readkey);
let devserver = [
0x72, 0x95, 0x01, 0x00, 0x70, 0x6f, 0x15, 0x00, 0x00, 0x0a, 0x2d, 0x0b,
];
fake_binary[50..50 + devserver.len()].copy_from_slice(&devserver);
let temp_file = std::env::temp_dir().join("test_patcher_compat.exe");
std::fs::write(&temp_file, &fake_binary).unwrap();
let modified = ensure_patcher_compatibility(&temp_file).unwrap();
assert!(modified);
let patched_data = std::fs::read(&temp_file).unwrap();
assert!(is_compatible_patcher(&patched_data));
let _ = std::fs::remove_file(temp_file);
}
#[test]
#[cfg(target_os = "macos")]
fn test_get_window_title_macos() {
let _ = get_window_title_by_pid(Pid::from_u32(0));
}
#[test]
fn test_patcher_compatibility_real_patcher() {
let real_patcher = Path::new("/Applications/osu!(stable).app/Contents/Resources/drive_c/osu!/EZPPLauncher/patcher/osu!.patcher.exe");
if real_patcher.is_file() {
let res = ensure_patcher_compatibility(real_patcher);
assert!(res.is_ok());
let data = std::fs::read(real_patcher).unwrap();
assert!(is_compatible_patcher(&data));
}
}
}
+9 -5
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "EZPPLauncher", "productName": "EZPPLauncher",
"version": "3.2.7", "version": "3.3.0",
"identifier": "farm.EZPPFarm.Launcher", "identifier": "farm.EZPPFarm.Launcher",
"mainBinaryName": "ezpplauncher", "mainBinaryName": "ezpplauncher",
"build": { "build": {
@@ -21,7 +21,8 @@
"decorations": false, "decorations": false,
"resizable": false, "resizable": false,
"maximizable": false, "maximizable": false,
"shadow": true "shadow": true,
"focus": true
} }
], ],
"withGlobalTauri": true, "withGlobalTauri": true,
@@ -29,10 +30,13 @@
"csp": { "csp": {
"default-src": "'self' tauri: customprotocol: asset:", "default-src": "'self' tauri: customprotocol: asset:",
"script-src": "'self' 'unsafe-inline' 'unsafe-eval' asset: http://asset.localhost https://asset.localhost http://127.0.0.1:* https://analytics.ez-pp.farm", "script-src": "'self' 'unsafe-inline' 'unsafe-eval' asset: http://asset.localhost https://asset.localhost http://127.0.0.1:* https://analytics.ez-pp.farm",
"worker-src": ["'self'", "blob:"], "worker-src": [
"'self'",
"blob:"
],
"style-src": "'self' 'unsafe-inline' asset: http://asset.localhost https://asset.localhost http://127.0.0.1:*", "style-src": "'self' 'unsafe-inline' asset: http://asset.localhost https://asset.localhost http://127.0.0.1:*",
"img-src": "'self' asset: http://asset.localhost https://asset.localhost blob: data: http://127.0.0.1:* https://assets.ppy.sh https://a.ez-pp.farm https://git.ez-pp.farm https://osu.direct", "img-src": "'self' asset: http://asset.localhost https://asset.localhost blob: data: http://127.0.0.1:* https://assets.ppy.sh https://a.ez-pp.farm https://git.ez-pp.farm https://osu.direct https://themes.ez-pp.farm",
"connect-src": "'self' ipc: http://ipc.localhost asset: http://asset.localhost https://asset.localhost http://127.0.0.1:* https://ez-pp.farm https://api.ez-pp.farm https://c.ez-pp.farm https://analytics.ez-pp.farm https://git.ez-pp.farm https://osu.direct https://osu.ppy.sh https://api.fontsource.org https://cdn.jsdelivr.net", "connect-src": "'self' ipc: http://ipc.localhost asset: http://asset.localhost https://asset.localhost http://127.0.0.1:* https://ez-pp.farm https://api.ez-pp.farm https://c.ez-pp.farm https://analytics.ez-pp.farm https://git.ez-pp.farm https://osu.direct https://osu.ppy.sh https://api.fontsource.org https://cdn.jsdelivr.net https://themes.ez-pp.farm",
"media-src": "'self' asset: http://asset.localhost https://asset.localhost http://127.0.0.1:* blob:", "media-src": "'self' asset: http://asset.localhost https://asset.localhost http://127.0.0.1:* blob:",
"font-src": [ "font-src": [
"'self'", "'self'",
+65 -1
View File
@@ -162,7 +162,10 @@
-ms-user-select: none; -ms-user-select: none;
user-select: none; user-select: none;
} }
html { html,
body {
height: 100%;
overflow: hidden;
overscroll-behavior: none; overscroll-behavior: none;
} }
body { body {
@@ -173,3 +176,64 @@
cursor: pointer; cursor: pointer;
} }
} }
.no-scrollbar {
-ms-overflow-style: none;
scrollbar-width: none;
}
.no-scrollbar::-webkit-scrollbar {
display: none;
}
/* Pause continuous visual work while the launcher is hidden or in the background. */
main.app-inactive *,
main.app-inactive *::before,
main.app-inactive *::after {
animation-play-state: paused !important;
}
/* Suppress browser and WebKit native media controls and overlay play buttons on theme videos */
video::-webkit-media-controls,
video::-webkit-media-controls-enclosure,
video::-webkit-media-controls-panel,
video::-webkit-media-controls-play-button,
video::-webkit-media-controls-start-playback-button,
video::-webkit-media-controls-overlay-play-button,
video::-webkit-media-controls-overlay-enclosure {
display: none !important;
-webkit-appearance: none !important;
opacity: 0 !important;
visibility: hidden !important;
pointer-events: none !important;
width: 0 !important;
height: 0 !important;
}
/* Crossfade the rendered page when switching themes via the View Transitions API. */
::view-transition-old(root) {
animation: 320ms cubic-bezier(0.4, 0, 0.2, 1) both theme-crossfade-out;
}
::view-transition-new(root) {
animation: 320ms cubic-bezier(0.4, 0, 0.2, 1) both theme-crossfade-in;
}
@keyframes theme-crossfade-out {
to {
opacity: 0;
}
}
@keyframes theme-crossfade-in {
from {
opacity: 0;
}
}
@media (prefers-reduced-motion: reduce) {
::view-transition-old(root),
::view-transition-new(root) {
animation: none !important;
}
}
+7 -1
View File
@@ -7,7 +7,13 @@
%sveltekit.head% %sveltekit.head%
</head> </head>
<body class="bg-theme-950" data-sveltekit-preload-data="hover"> <body
class="bg-theme-950"
data-sveltekit-preload-data="hover"
spellcheck="false"
autocorrect="off"
autocapitalize="none"
>
<div style="display: contents">%sveltekit.body%</div> <div style="display: contents">%sveltekit.body%</div>
</body> </body>
</html> </html>
+8 -8
View File
@@ -154,9 +154,9 @@
<Terminal class="size-4" /> <Terminal class="size-4" />
</div> </div>
<div class="min-w-0"> <div class="min-w-0">
<h2 id="log-viewer-title" class="text-sm font-semibold">Log bundles</h2> <h2 id="log-viewer-title" class="text-sm font-semibold">Logs</h2>
<p class="truncate text-[10px] text-muted-foreground"> <p class="truncate text-[10px] text-muted-foreground">
Launcher, osu! and patcher output, grouped by session Current session plus archived launcher, osu! and patcher output
</p> </p>
</div> </div>
</div> </div>
@@ -191,7 +191,7 @@
<div <div
class="flex shrink-0 items-center justify-between border-b border-theme-800 px-3 py-2 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground" class="flex shrink-0 items-center justify-between border-b border-theme-800 px-3 py-2 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground"
> >
<span>Bundles</span> <span>Sessions</span>
<span>{bundles.length}</span> <span>{bundles.length}</span>
</div> </div>
<div class="min-h-0 flex-1 overflow-y-auto p-1.5"> <div class="min-h-0 flex-1 overflow-y-auto p-1.5">
@@ -202,8 +202,8 @@
</div> </div>
{:else if bundles.length === 0} {:else if bundles.length === 0}
<div class="p-3 text-[11px] leading-relaxed text-muted-foreground"> <div class="p-3 text-[11px] leading-relaxed text-muted-foreground">
No bundles yet. Logs are zipped on the next launcher restart or when a log reaches 5 No logs yet. The current session appears once the launcher writes its first line;
MiB. archived bundles are created when logs rotate.
</div> </div>
{:else} {:else}
{#each bundles as bundle (bundle.path)} {#each bundles as bundle (bundle.path)}
@@ -291,14 +291,14 @@
class="flex h-full items-center justify-center gap-2 text-xs text-muted-foreground" class="flex h-full items-center justify-center gap-2 text-xs text-muted-foreground"
> >
<LoaderCircle class="size-4 animate-spin" /> <LoaderCircle class="size-4 animate-spin" />
Reading bundle… Reading logs…
</div> </div>
{:else if !selectedBundle} {:else if !selectedBundle}
<div <div
class="flex h-full flex-col items-center justify-center gap-2 text-center text-muted-foreground" class="flex h-full flex-col items-center justify-center gap-2 text-center text-muted-foreground"
> >
<Terminal class="size-8 opacity-40" /> <Terminal class="size-8 opacity-40" />
<p class="text-xs">Choose a log bundle to inspect it.</p> <p class="text-xs">Choose a log session to inspect it.</p>
</div> </div>
{:else if filteredLines.length === 0} {:else if filteredLines.length === 0}
<div <div
@@ -328,7 +328,7 @@
<span> <span>
{selectedBundle {selectedBundle
? `${selectedBundle.name} · ${formatBytes(selectedBundle.size)}` ? `${selectedBundle.name} · ${formatBytes(selectedBundle.size)}`
: 'No bundle selected'} : 'No session selected'}
</span> </span>
</footer> </footer>
</main> </main>
@@ -0,0 +1,485 @@
<script lang="ts">
import { Button } from '$lib/components/ui/button';
import {
fetchNotifications,
fetchUnreadNotificationCount,
markAllNotificationsRead,
markNotificationRead,
type UserNotification,
} from '$lib/notifications';
import { currentUser } from '$lib/userAuthentication';
import {
Bell,
CheckCheck,
ChevronRight,
ExternalLink,
LoaderCircle,
Megaphone,
RefreshCw,
ShieldAlert,
X,
} from '@lucide/svelte';
import { Portal } from 'bits-ui';
let { onOpenWorkshop }: { onOpenWorkshop?: () => void } = $props();
let open = $state(false);
let loading = $state(false);
let loadingMore = $state(false);
let markingAll = $state(false);
let notifications = $state<UserNotification[]>([]);
let unreadCount = $state(0);
let hasMore = $state(false);
let error = $state<string | null>(null);
let selectedNotification = $state<UserNotification | null>(null);
const unreadLabel = $derived(unreadCount > 9 ? '9+' : String(unreadCount));
const NOTIFICATION_TYPE_LABELS: Record<string, string> = {
theme_hidden: 'Theme hidden',
theme_restored: 'Theme restored',
theme_approved: 'Theme approved',
theme_rejected: 'Theme needs changes',
theme_taken_down: 'Theme taken down',
report_resolved: 'Report resolved',
report_dismissed: 'Report dismissed',
system: 'Announcement',
};
function notificationTypeLabel(type: string): string {
return NOTIFICATION_TYPE_LABELS[type] ?? 'Notification';
}
$effect(() => {
const userId = $currentUser?.id;
if (!userId) {
open = false;
notifications = [];
unreadCount = 0;
hasMore = false;
error = null;
return;
}
void refreshCount();
const timer = setInterval(() => {
if (document.visibilityState === 'visible' && !open) void refreshCount();
}, 60_000);
return () => clearInterval(timer);
});
async function refreshCount() {
if (!$currentUser) return;
try {
unreadCount = await fetchUnreadNotificationCount();
} catch {
// The badge is best-effort; the panel surfaces actionable errors.
}
}
async function loadNotifications() {
if (!$currentUser) return;
loading = true;
error = null;
try {
const data = await fetchNotifications({ limit: 30 });
notifications = data.notifications;
unreadCount = data.unreadCount;
hasMore = data.hasMore;
} catch (err) {
error = err instanceof Error ? err.message : String(err);
} finally {
loading = false;
}
}
function openHub() {
if (!$currentUser) return;
selectedNotification = null;
open = true;
void loadNotifications();
}
async function loadOlder() {
if (loadingMore || notifications.length === 0) return;
loadingMore = true;
try {
const data = await fetchNotifications({
limit: 30,
beforeId: notifications[notifications.length - 1].id,
});
const known = new Set(notifications.map((item) => item.id));
notifications = [
...notifications,
...data.notifications.filter((item) => !known.has(item.id)),
];
unreadCount = data.unreadCount;
hasMore = data.hasMore;
} catch (err) {
error = err instanceof Error ? err.message : String(err);
} finally {
loadingMore = false;
}
}
async function markRead(notification: UserNotification) {
if (notification.readAt) return;
try {
await markNotificationRead(notification.id);
const readAt = new Date().toISOString();
notifications = notifications.map((item) =>
item.id === notification.id ? { ...item, readAt } : item
);
if (selectedNotification?.id === notification.id) {
selectedNotification = { ...selectedNotification, readAt };
}
unreadCount = Math.max(0, unreadCount - 1);
} catch (err) {
error = err instanceof Error ? err.message : String(err);
}
}
async function markAllRead() {
if (markingAll || unreadCount === 0) return;
markingAll = true;
try {
await markAllNotificationsRead();
const now = new Date().toISOString();
notifications = notifications.map((item) => ({
...item,
readAt: item.readAt ?? now,
}));
if (selectedNotification) {
selectedNotification = {
...selectedNotification,
readAt: selectedNotification.readAt ?? now,
};
}
unreadCount = 0;
} catch (err) {
error = err instanceof Error ? err.message : String(err);
} finally {
markingAll = false;
}
}
function openNotification(notification: UserNotification) {
error = null;
selectedNotification = notification;
void markRead(notification);
}
function openWorkshopFromNotification() {
if (!selectedNotification?.themeId || !onOpenWorkshop) return;
onOpenWorkshop();
selectedNotification = null;
open = false;
}
function formatDate(value: string): string {
const date = new Date(value);
return Number.isNaN(date.getTime()) ? value : date.toLocaleString();
}
</script>
<button
type="button"
class="relative flex size-12 items-center justify-center rounded-[0.85rem] bg-black/20 text-theme-200 ring-1 ring-inset ring-white/15 transition-colors hover:bg-primary/20 hover:text-theme-50 disabled:cursor-not-allowed disabled:opacity-50"
title={$currentUser ? 'Notifications' : 'Log in to view notifications'}
aria-label={$currentUser
? `Notifications${unreadCount > 0 ? `, ${unreadCount} unread` : ''}`
: 'Notifications'}
disabled={!$currentUser}
onclick={openHub}
>
<Bell class="size-5" />
{#if unreadCount > 0}
<span
class="absolute -top-1 -right-1 flex min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[9px] font-bold text-primary-foreground ring-2 ring-theme-950"
>
{unreadLabel}
</span>
{/if}
</button>
{#if open}
<Portal>
<button
type="button"
class="fixed inset-0 z-[80] cursor-default bg-black/30 backdrop-blur-[1px]"
aria-label="Close notifications"
onclick={() => (open = false)}
></button>
<div
class="fixed bottom-4 left-[4.75rem] z-[90] flex max-h-[min(34rem,calc(100vh-2rem))] w-[22rem] flex-col overflow-hidden rounded-xl border border-theme-800 bg-theme-950 shadow-2xl"
role="dialog"
aria-modal="true"
aria-labelledby="notification-hub-title"
>
<div class="flex items-start justify-between gap-3 border-b border-theme-800/70 p-4">
<div>
<h2
id="notification-hub-title"
class="flex items-center gap-2 text-sm font-semibold text-white"
>
<Bell class="size-4 text-primary" />
Notifications
{#if unreadCount > 0}
<span class="rounded-full bg-primary/20 px-1.5 py-0.5 text-[10px] text-primary">
{unreadCount} new
</span>
{/if}
</h2>
<p class="mt-1 text-[11px] text-muted-foreground">
Moderation updates and system messages.
</p>
</div>
<div class="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
class="size-7 text-muted-foreground hover:text-white"
title="Refresh notifications"
onclick={() => void loadNotifications()}
disabled={loading}
>
<RefreshCw class="size-3.5 {loading ? 'animate-spin' : ''}" />
</Button>
<Button
variant="ghost"
size="icon"
class="size-7 text-muted-foreground hover:text-white"
title="Close"
onclick={() => (open = false)}
>
<X class="size-4" />
</Button>
</div>
</div>
<div class="flex items-center justify-between border-b border-theme-800/50 px-4 py-2">
<span class="text-[10px] text-muted-foreground">
{unreadCount > 0 ? `${unreadCount} unread` : 'All caught up'}
</span>
<Button
variant="ghost"
size="sm"
class="h-6 gap-1 px-1.5 text-[10px] text-muted-foreground hover:text-white"
onclick={() => void markAllRead()}
disabled={markingAll || unreadCount === 0}
>
{#if markingAll}
<LoaderCircle class="size-3 animate-spin" />
{:else}
<CheckCheck class="size-3" />
{/if}
Mark all read
</Button>
</div>
<div class="min-h-0 flex-1 overflow-y-auto p-2">
{#if error}
<div
class="m-2 rounded-lg border border-red-900/40 bg-red-950/20 p-3 text-[11px] text-red-300"
>
{error}
</div>
{/if}
{#if loading && notifications.length === 0}
<div class="flex h-40 items-center justify-center gap-2 text-xs text-muted-foreground">
<LoaderCircle class="size-4 animate-spin text-primary" /> Loading notifications...
</div>
{:else if notifications.length === 0}
<div class="flex h-40 flex-col items-center justify-center gap-2 px-6 text-center">
<Bell class="size-7 text-muted-foreground/40" />
<p class="text-xs text-muted-foreground">No notifications yet.</p>
<p class="text-[10px] text-muted-foreground/70">
Moderation decisions about your themes and reports will appear here.
</p>
</div>
{:else}
<div class="space-y-1">
{#each notifications as notification (notification.id)}
<button
type="button"
class="group w-full rounded-lg border p-3 text-left transition-colors {notification.readAt
? 'border-transparent bg-transparent hover:bg-theme-900/50'
: 'border-primary/20 bg-primary/5 hover:bg-primary/10'}"
onclick={() => openNotification(notification)}
>
<div class="flex items-start gap-2.5">
<div
class="mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-full {notification.type ===
'theme_hidden' || notification.type === 'theme_taken_down'
? 'bg-red-500/10 text-red-300'
: notification.type === 'report_resolved'
? 'bg-emerald-500/10 text-emerald-300'
: notification.type === 'system'
? 'bg-cyan-500/10 text-cyan-300'
: 'bg-amber-500/10 text-amber-300'}"
>
{#if notification.type === 'system'}
<Megaphone class="size-3.5" />
{:else}
<ShieldAlert class="size-3.5" />
{/if}
</div>
<div class="min-w-0 flex-1">
<div class="flex items-start justify-between gap-2">
<p class="text-[11px] font-semibold text-white">{notification.title}</p>
{#if !notification.readAt}
<span class="mt-1 size-1.5 shrink-0 rounded-full bg-primary"></span>
{/if}
</div>
<p class="mt-1 line-clamp-2 text-[10px] leading-relaxed text-muted-foreground">
{notification.message}
</p>
<div class="mt-1.5 flex items-center justify-between gap-2">
<p class="text-[9px] text-muted-foreground/70">
{formatDate(notification.createdAt)}
</p>
<span
class="flex items-center gap-1 text-[9px] text-muted-foreground/60 transition-colors group-hover:text-theme-100"
>
Details <ChevronRight class="size-3" />
</span>
</div>
</div>
</div>
</button>
{/each}
</div>
{#if hasMore}
<div class="flex justify-center p-2">
<Button
variant="ghost"
size="sm"
class="h-7 text-[10px] text-muted-foreground"
onclick={() => void loadOlder()}
disabled={loadingMore}
>
{#if loadingMore}
<LoaderCircle class="mr-1 size-3 animate-spin" />
{/if}
Load older
</Button>
</div>
{/if}
{/if}
</div>
</div>
{#if selectedNotification}
<button
type="button"
class="fixed inset-0 z-[95] cursor-default bg-black/60 backdrop-blur-sm"
aria-label="Close notification details"
onclick={() => (selectedNotification = null)}
></button>
<div class="pointer-events-none fixed inset-0 z-[100] flex items-center justify-center p-4">
<div
class="pointer-events-auto flex max-h-[min(42rem,calc(100vh-2rem))] w-full max-w-lg flex-col overflow-hidden rounded-xl border border-theme-800 bg-theme-950 shadow-2xl"
role="dialog"
aria-modal="true"
aria-labelledby="notification-detail-title"
>
<div class="flex items-start justify-between gap-3 border-b border-theme-800/70 p-4">
<div class="flex min-w-0 items-start gap-3">
<div
class="mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-full {selectedNotification.type ===
'theme_hidden' || selectedNotification.type === 'theme_taken_down'
? 'bg-red-500/10 text-red-300'
: selectedNotification.type === 'report_resolved'
? 'bg-emerald-500/10 text-emerald-300'
: selectedNotification.type === 'system'
? 'bg-cyan-500/10 text-cyan-300'
: 'bg-amber-500/10 text-amber-300'}"
>
{#if selectedNotification.type === 'system'}
<Megaphone class="size-4" />
{:else}
<ShieldAlert class="size-4" />
{/if}
</div>
<div class="min-w-0">
<p class="text-[9px] font-semibold tracking-wide text-muted-foreground uppercase">
{notificationTypeLabel(selectedNotification.type)}
</p>
<h2 id="notification-detail-title" class="mt-1 text-sm font-semibold text-white">
{selectedNotification.title}
</h2>
</div>
</div>
<Button
variant="ghost"
size="icon"
class="size-7 shrink-0 text-muted-foreground hover:text-white"
title="Close notification"
onclick={() => (selectedNotification = null)}
>
<X class="size-4" />
</Button>
</div>
<div class="min-h-0 flex-1 overflow-y-auto p-4">
<p
class="whitespace-pre-wrap break-words text-xs leading-relaxed text-theme-100 select-text"
>
{selectedNotification.message}
</p>
{#if error}
<p
class="mt-3 rounded-md border border-red-900/50 bg-red-950/30 p-2 text-[10px] text-red-300"
>
{error}
</p>
{/if}
<dl
class="mt-4 space-y-1.5 border-t border-theme-800/60 pt-3 text-[10px] text-muted-foreground"
>
{#if selectedNotification.themeName}
<div class="flex gap-1.5">
<dt>Theme:</dt>
<dd class="min-w-0 truncate text-theme-100">{selectedNotification.themeName}</dd>
</div>
{/if}
{#if selectedNotification.actorName}
<div class="flex gap-1.5">
<dt>From:</dt>
<dd class="text-theme-100">{selectedNotification.actorName}</dd>
</div>
{:else if selectedNotification.actorId}
<div class="flex gap-1.5">
<dt>From:</dt>
<dd>Staff</dd>
</div>
{/if}
<div class="flex gap-1.5">
<dt>Received:</dt>
<dd>{formatDate(selectedNotification.createdAt)}</dd>
</div>
</dl>
</div>
<div class="flex items-center justify-between gap-2 border-t border-theme-800/70 p-3">
<Button
variant="ghost"
size="sm"
class="h-8 text-xs"
onclick={() => (selectedNotification = null)}
>
Back
</Button>
{#if selectedNotification.themeId && onOpenWorkshop}
<Button size="sm" class="h-8 gap-1.5 text-xs" onclick={openWorkshopFromNotification}>
<ExternalLink class="size-3.5" />
Open Community Workshop
</Button>
{/if}
</div>
</div>
</div>
{/if}
</Portal>
{/if}
@@ -10,29 +10,23 @@
import { import {
DEFAULT_DISCORD_PRESENCE_CONFIG, DEFAULT_DISCORD_PRESENCE_CONFIG,
DISCORD_PRESENCE_PRESETS, DISCORD_PRESENCE_PRESETS,
discordPresenceCustomConfig,
interpolatePresenceString, interpolatePresenceString,
loadDiscordPresenceConfig, loadDiscordPresenceConfig,
pushIdlePresenceFromConfig,
saveDiscordPresenceConfig, saveDiscordPresenceConfig,
type DiscordPresenceConfig, type DiscordPresenceConfig,
type PresenceVariableContext, type PresenceVariableContext,
} from '$lib/discordPresenceConfig'; } from '$lib/discordPresenceConfig';
import { discordPresence, launcherVersion } from '$lib/global'; import { discordPresence, launcherVersion } from '$lib/global';
import * as presence from '$lib/presence';
import { currentUser } from '$lib/userAuthentication'; import { currentUser } from '$lib/userAuthentication';
import { import {
Check, Check,
Clock, Clock,
Code2, Code2,
Copy,
ExternalLink, ExternalLink,
Eye,
Gamepad2, Gamepad2,
Globe, Globe,
Home, Home,
Image as ImageIcon, Image as ImageIcon,
Info,
Link, Link,
LoaderCircle, LoaderCircle,
Maximize2, Maximize2,
@@ -41,10 +35,8 @@
Play, Play,
Plus, Plus,
RotateCcw, RotateCcw,
Save,
Sparkles, Sparkles,
Type, Type,
User,
X, X,
} from '@lucide/svelte'; } from '@lucide/svelte';
import { invoke } from '@tauri-apps/api/core'; import { invoke } from '@tauri-apps/api/core';
@@ -101,8 +93,10 @@
// Preset selector // Preset selector
let selectedPresetName = $state<string>('EZPPFarm Default'); let selectedPresetName = $state<string>('EZPPFarm Default');
const SIM_MODES = ['osu!', 'taiko', 'catch', 'mania'] as const;
// Simulation parameters for preview // Simulation parameters for preview
let simMode = $state<'osu!' | 'taiko' | 'catch' | 'mania'>('osu!'); let simMode = $state<(typeof SIM_MODES)[number]>('osu!');
let simAction = $state<string>('Playing...'); let simAction = $state<string>('Playing...');
let simBeatmapIndex = $state<number>(0); let simBeatmapIndex = $state<number>(0);
let simRank = $state<number>(1337); let simRank = $state<number>(1337);
@@ -206,10 +200,18 @@
if (standalone) { if (standalone) {
try { try {
unlistenSync = await listen<any>('sync-theme-editor-global-data', (event) => { unlistenSync = await listen<{
user?: Parameters<typeof currentUser.set>[0];
info?: Parameters<typeof currentUserInfo.set>[0];
launcherVersion?: string;
discordPresence?: boolean;
}>('sync-theme-editor-global-data', (event) => {
if (event.payload?.user) currentUser.set(event.payload.user); if (event.payload?.user) currentUser.set(event.payload.user);
if (event.payload?.info) currentUserInfo.set(event.payload.info); if (event.payload?.info) currentUserInfo.set(event.payload.info);
if (event.payload?.launcherVersion) launcherVersion.set(event.payload.launcherVersion); if (event.payload?.launcherVersion) launcherVersion.set(event.payload.launcherVersion);
if (typeof event.payload?.discordPresence === 'boolean') {
discordPresence.set(event.payload.discordPresence);
}
}); });
await emit('request-theme-editor-global-data'); await emit('request-theme-editor-global-data');
} catch (err) { } catch (err) {
@@ -469,18 +471,9 @@
try { try {
await saveDiscordPresenceConfig(workingConfig); await saveDiscordPresenceConfig(workingConfig);
initialConfigJson = JSON.stringify(workingConfig); initialConfigJson = JSON.stringify(workingConfig);
if ($discordPresence && (await presence.isConnected())) { // The main window owns the live player stats and its presence config
await pushIdlePresenceFromConfig( // store, so let it refresh and push the updated activity immediately.
{ await emit('discord-presence-config-saved');
user: $currentUser,
version: $launcherVersion || undefined,
rank: simRank,
pp: simPp,
accuracy: simAccuracy,
},
workingConfig
);
}
sileo.success({ title: 'Discord Rich Presence Saved', description: 'Activity updated' }); sileo.success({ title: 'Discord Rich Presence Saved', description: 'Activity updated' });
await handleClose(); await handleClose();
} catch (err) { } catch (err) {
@@ -844,7 +837,7 @@
Details (First Line) Details (First Line)
</Label> </Label>
<span class="text-[10px] text-muted-foreground" <span class="text-[10px] text-muted-foreground"
>[{'{'}mode{'}'}] {'{'}action{'}'}</span >[{'{'}mode}] {'{'}action}</span
> >
</div> </div>
<Input <Input
@@ -852,7 +845,7 @@
bind:value={workingConfig.playingDetails} bind:value={workingConfig.playingDetails}
onfocus={() => handleInputFocus('playingDetails')} onfocus={() => handleInputFocus('playingDetails')}
onblur={handleInputBlur} onblur={handleInputBlur}
placeholder="[{'{'}mode{'}'}] {'{'}action{'}'}" placeholder="[{'{'}mode}] {'{'}action}"
class="h-8 bg-black/40 text-xs border-theme-800 focus:border-primary" class="h-8 bg-black/40 text-xs border-theme-800 focus:border-primary"
/> />
</div> </div>
@@ -862,14 +855,14 @@
<Label class="text-[11px] font-medium text-theme-200" for="playing-state"> <Label class="text-[11px] font-medium text-theme-200" for="playing-state">
State (Second Line) State (Second Line)
</Label> </Label>
<span class="text-[10px] text-muted-foreground">{'{'}beatmap{'}'}</span> <span class="text-[10px] text-muted-foreground">{'{'}beatmap}</span>
</div> </div>
<Input <Input
id="playing-state" id="playing-state"
bind:value={workingConfig.playingState} bind:value={workingConfig.playingState}
onfocus={() => handleInputFocus('playingState')} onfocus={() => handleInputFocus('playingState')}
onblur={handleInputBlur} onblur={handleInputBlur}
placeholder="{'{'}beatmap{'}'}" placeholder="{'{'}beatmap}"
class="h-8 bg-black/40 text-xs border-theme-800 focus:border-primary" class="h-8 bg-black/40 text-xs border-theme-800 focus:border-primary"
/> />
</div> </div>
@@ -907,14 +900,14 @@
> >
Cover Art Hover Tooltip Cover Art Hover Tooltip
</Label> </Label>
<span class="text-[10px] text-muted-foreground">{'{'}beatmap{'}'}</span> <span class="text-[10px] text-muted-foreground">{'{'}beatmap}</span>
</div> </div>
<Input <Input
id="playing-large-text" id="playing-large-text"
bind:value={workingConfig.playingLargeImageText} bind:value={workingConfig.playingLargeImageText}
onfocus={() => handleInputFocus('playingLargeImageText')} onfocus={() => handleInputFocus('playingLargeImageText')}
onblur={handleInputBlur} onblur={handleInputBlur}
placeholder="{'{'}beatmap{'}'}" placeholder="{'{'}beatmap}"
class="h-8 bg-black/40 text-xs border-theme-800 focus:border-primary" class="h-8 bg-black/40 text-xs border-theme-800 focus:border-primary"
/> />
</div> </div>
@@ -945,7 +938,7 @@
Small Badge Hover Tooltip Small Badge Hover Tooltip
</Label> </Label>
<span class="text-[10px] text-muted-foreground" <span class="text-[10px] text-muted-foreground"
>{'{'}username{'}'} (#{'{'}rank{'}'})</span >{'{'}username} (#{'{'}rank})</span
> >
</div> </div>
<Input <Input
@@ -953,7 +946,7 @@
bind:value={workingConfig.playingSmallImageText} bind:value={workingConfig.playingSmallImageText}
onfocus={() => handleInputFocus('playingSmallImageText')} onfocus={() => handleInputFocus('playingSmallImageText')}
onblur={handleInputBlur} onblur={handleInputBlur}
placeholder="{'{'}username{'}'} (#{'{'}rank{'}'})" placeholder="{'{'}username} (#{'{'}rank})"
class="h-8 bg-black/40 text-xs border-theme-800 focus:border-primary" class="h-8 bg-black/40 text-xs border-theme-800 focus:border-primary"
/> />
</div> </div>
@@ -1031,7 +1024,7 @@
<ThemeSection <ThemeSection
title="Button 1 (Playing In-Game)" title="Button 1 (Playing In-Game)"
icon={Link} icon={Link}
description="Primary action button shown while playing osu! (supports {'{'}beatmapUrl{'}'})" description="Primary action button shown while playing osu! (supports {'{'}beatmapUrl})"
> >
<div class="space-y-3"> <div class="space-y-3">
<div <div
@@ -1067,7 +1060,7 @@
bind:value={workingConfig.playingButton1.url} bind:value={workingConfig.playingButton1.url}
onfocus={() => handleInputFocus('playingButton1Url')} onfocus={() => handleInputFocus('playingButton1Url')}
onblur={handleInputBlur} onblur={handleInputBlur}
placeholder="{'{'}beatmapUrl{'}'}" placeholder="{'{'}beatmapUrl}"
class="h-8 bg-black/40 text-xs border-theme-800 focus:border-primary" class="h-8 bg-black/40 text-xs border-theme-800 focus:border-primary"
/> />
</div> </div>
@@ -1128,7 +1121,7 @@
bordered={false} bordered={false}
> >
<div class="space-y-2"> <div class="space-y-2">
{#each DISCORD_PRESENCE_PRESETS as preset} {#each DISCORD_PRESENCE_PRESETS as preset (preset.name)}
<div <div
class="flex flex-col gap-1.5 rounded-xl border border-theme-800/80 bg-theme-900/40 p-3 transition-colors hover:border-theme-700 {selectedPresetName === class="flex flex-col gap-1.5 rounded-xl border border-theme-800/80 bg-theme-900/40 p-3 transition-colors hover:border-theme-700 {selectedPresetName ===
preset.name preset.name
@@ -1170,7 +1163,7 @@
description="Click any variable to copy or evaluate in the active field" description="Click any variable to copy or evaluate in the active field"
> >
<div class="space-y-1.5"> <div class="space-y-1.5">
{#each PLACEHOLDERS as p} {#each PLACEHOLDERS as p (p.token)}
<div <div
class="flex items-center justify-between rounded-lg border border-theme-800/40 bg-black/30 px-2.5 py-1.5 text-[11px]" class="flex items-center justify-between rounded-lg border border-theme-800/40 bg-black/30 px-2.5 py-1.5 text-[11px]"
> >
@@ -1215,7 +1208,7 @@
</span> </span>
</div> </div>
<div class="flex flex-wrap gap-1"> <div class="flex flex-wrap gap-1">
{#each PLACEHOLDERS as p} {#each PLACEHOLDERS as p (p.token)}
<button <button
type="button" type="button"
class="group flex items-center gap-1 rounded border border-theme-800 bg-theme-900/90 px-1.5 py-0.5 text-[10px] text-theme-200 transition-all hover:border-primary/60 hover:bg-primary/20 hover:text-white active:scale-95" class="group flex items-center gap-1 rounded border border-theme-800 bg-theme-900/90 px-1.5 py-0.5 text-[10px] text-theme-200 transition-all hover:border-primary/60 hover:bg-primary/20 hover:text-white active:scale-95"
@@ -1354,14 +1347,14 @@
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
<span class="text-muted-foreground">Mode:</span> <span class="text-muted-foreground">Mode:</span>
<div class="flex gap-0.5"> <div class="flex gap-0.5">
{#each ['osu!', 'taiko', 'catch', 'mania'] as mode} {#each SIM_MODES as mode (mode)}
<button <button
type="button" type="button"
class="rounded px-2 py-0.5 text-[10px] font-semibold transition-colors {simMode === class="rounded px-2 py-0.5 text-[10px] font-semibold transition-colors {simMode ===
mode mode
? 'bg-primary text-primary-foreground' ? 'bg-primary text-primary-foreground'
: 'bg-black/40 text-theme-300 hover:text-white'}" : 'bg-black/40 text-theme-300 hover:text-white'}"
onclick={() => (simMode = mode as any)} onclick={() => (simMode = mode)}
> >
{mode} {mode}
</button> </button>
@@ -1372,7 +1365,7 @@
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
<span class="text-muted-foreground">Action:</span> <span class="text-muted-foreground">Action:</span>
<div class="flex gap-0.5"> <div class="flex gap-0.5">
{#each ['Playing...', 'Editing...', 'AFK...'] as act} {#each ['Playing...', 'Editing...', 'AFK...'] as act (act)}
<button <button
type="button" type="button"
class="rounded px-2 py-0.5 text-[10px] transition-colors {simAction === act class="rounded px-2 py-0.5 text-[10px] transition-colors {simAction === act
@@ -1392,7 +1385,7 @@
bind:value={simBeatmapIndex} bind:value={simBeatmapIndex}
class="rounded border border-theme-800 bg-black/60 px-2 py-0.5 text-[10px] text-theme-200" class="rounded border border-theme-800 bg-black/60 px-2 py-0.5 text-[10px] text-theme-200"
> >
{#each SAMPLE_BEATMAPS as b, idx} {#each SAMPLE_BEATMAPS as b, idx (`${b.artist}-${b.title}-${idx}`)}
<option value={idx}>{b.artist} - {b.title}</option> <option value={idx}>{b.artist} - {b.title}</option>
{/each} {/each}
</select> </select>
File diff suppressed because it is too large. Load diff
@@ -6,18 +6,18 @@
import Input from '$lib/components/ui/input/input.svelte'; import Input from '$lib/components/ui/input/input.svelte';
import Label from '$lib/components/ui/label/label.svelte'; import Label from '$lib/components/ui/label/label.svelte';
import * as Select from '$lib/components/ui/select'; import * as Select from '$lib/components/ui/select';
import { isThemeClockVariable, THEME_CLOCK_VARIABLE_NAMES } from '$lib/themeClock'; import { isThemeClockVariable, THEME_CLOCK_VARIABLE_NAMES } from '$lib/theme/themeClock';
import { import {
themeBehaviorTargetLabel, themeBehaviorTargetLabel,
themeElementLabel, themeElementLabel,
themeGroupInteractiveCount, themeGroupInteractiveCount,
themeGroupLabel, themeGroupLabel,
} from '$lib/themeLogic'; } from '$lib/theme/themeLogic';
import { import {
formatThemeScriptError, formatThemeScriptError,
parseThemeScript, parseThemeScript,
themeScriptProgramCanLeaveLauncher, themeScriptProgramCanLeaveLauncher,
} from '$lib/themeScriptLang'; } from '$lib/theme/themeScriptLang';
import type { import type {
ThemeV2Behavior, ThemeV2Behavior,
ThemeV2BehaviorAction, ThemeV2BehaviorAction,
@@ -29,7 +29,7 @@
ThemeV2Group, ThemeV2Group,
ThemeV2ScriptScreen, ThemeV2ScriptScreen,
ThemeV2ScriptValue, ThemeV2ScriptValue,
} from '$lib/themeV2'; } from '$lib/theme/themeV2';
import { Link2, Plus, Trash2 } from '@lucide/svelte'; import { Link2, Plus, Trash2 } from '@lucide/svelte';
import { SvelteSet } from 'svelte/reactivity'; import { SvelteSet } from 'svelte/reactivity';
@@ -3,11 +3,11 @@
analyzeThemeSvelteSource, analyzeThemeSvelteSource,
type ThemeSvelteAnalysis, type ThemeSvelteAnalysis,
type ThemeSvelteDiagnostic, type ThemeSvelteDiagnostic,
} from '$lib/themeSvelte'; } from '$lib/theme/themeSvelte';
import { import {
THEME_SVELTE_COMPONENT_PLACEHOLDER, THEME_SVELTE_COMPONENT_PLACEHOLDER,
THEME_SVELTE_COMPONENT_SKELETON, THEME_SVELTE_COMPONENT_SKELETON,
} from '$lib/themeSvelteSnippets'; } from '$lib/theme/themeSvelteSnippets';
import { Component, CircleAlert, Maximize2, Minimize2, X } from '@lucide/svelte'; import { Component, CircleAlert, Maximize2, Minimize2, X } from '@lucide/svelte';
import type * as Monaco from 'monaco-editor'; import type * as Monaco from 'monaco-editor';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
@@ -3,7 +3,7 @@
import Button from '$lib/components/ui/button/button.svelte'; import Button from '$lib/components/ui/button/button.svelte';
import Input from '$lib/components/ui/input/input.svelte'; import Input from '$lib/components/ui/input/input.svelte';
import Label from '$lib/components/ui/label/label.svelte'; import Label from '$lib/components/ui/label/label.svelte';
import { themeClassTokens } from '$lib/themeV2'; import { themeClassTokens } from '$lib/theme/themeV2';
import { Code2, RotateCcw } from '@lucide/svelte'; import { Code2, RotateCcw } from '@lucide/svelte';
let { let {
@@ -1,6 +1,6 @@
<script lang="ts"> <script lang="ts">
import { compileThemeSvelte } from '$lib/themeSvelte'; import { compileThemeSvelte } from '$lib/theme/themeSvelte';
import { themeAssetUrl, type ThemeV2ScriptValue } from '$lib/themeV2'; import { themeAssetUrl, type ThemeV2ScriptValue } from '$lib/theme/themeV2';
import { TriangleAlert } from '@lucide/svelte'; import { TriangleAlert } from '@lucide/svelte';
import { mount, unmount } from 'svelte'; import { mount, unmount } from 'svelte';
File diff suppressed because it is too large. Load diff
@@ -15,9 +15,9 @@
import * as Select from '$lib/components/ui/select'; import * as Select from '$lib/components/ui/select';
import Slider from '$lib/components/ui/slider/slider.svelte'; import Slider from '$lib/components/ui/slider/slider.svelte';
import Textarea from '$lib/components/ui/textarea/textarea.svelte'; import Textarea from '$lib/components/ui/textarea/textarea.svelte';
import { getThemeDataSampleValue, resolveThemeDataValue, themeGlobalData } from '$lib/themeData'; import { getThemeDataSampleValue, resolveThemeDataValue, themeGlobalData } from '$lib/theme/themeData';
import type { ThemeFontChoice } from '$lib/themeFonts'; import type { ThemeFontChoice } from '$lib/theme/themeFonts';
import { DEFAULT_THEME_ICON_SET, type ThemeIconSet } from '$lib/themeIcons'; import { DEFAULT_THEME_ICON_SET, type ThemeIconSet } from '$lib/theme/themeIcons';
import { import {
THEME_DATA_FIELDS, THEME_DATA_FIELDS,
THEME_PARTICLE_PRESETS, THEME_PARTICLE_PRESETS,
@@ -27,23 +27,33 @@
type ThemeV2Element, type ThemeV2Element,
type ThemeV2Group, type ThemeV2Group,
type ThemeV2MaskShape, type ThemeV2MaskShape,
} from '$lib/themeV2'; type ThemeV2WidgetKind,
type ThemeV2WidgetVariant,
} from '$lib/theme/themeV2';
import { openURL } from '$lib/utils';
import { import {
CircleUser,
Clock, Clock,
Component, Component,
Film, Film,
Gauge, Gauge,
Image as ImageIcon, Image as ImageIcon,
Layers,
LayoutGrid,
Megaphone, Megaphone,
MousePointerClick, MousePointerClick,
Move,
Play,
RefreshCw, RefreshCw,
Repeat, Repeat,
Scan,
Shapes, Shapes,
Sparkles, Sparkles,
Spline, Spline,
Timer, Timer,
Type, Type,
} from '@lucide/svelte'; } from '@lucide/svelte';
import { sileo } from 'sileo';
let { let {
element = $bindable(), element = $bindable(),
@@ -198,6 +208,12 @@
<Clock class="size-4" /> <Clock class="size-4" />
{:else if element.type === 'countdown'} {:else if element.type === 'countdown'}
<Timer class="size-4" /> <Timer class="size-4" />
{:else if element.type === 'widget'}
{#if element.widget === 'avatar'}
<CircleUser class="size-4" />
{:else}
<LayoutGrid class="size-4" />
{/if}
{:else} {:else}
<ImageIcon class="size-4" /> <ImageIcon class="size-4" />
{/if} {/if}
@@ -208,7 +224,7 @@
</div> </div>
</div> </div>
<ThemeSection title="Position & size" bordered={false} contentClass="space-y-3 pt-2"> <ThemeSection title="Position & size" icon={Move} bordered={false} contentClass="space-y-3 pt-2">
<div class="space-y-1"> <div class="space-y-1">
<Label for="element-name" class={label}>Layer name</Label> <Label for="element-name" class={label}>Layer name</Label>
<Input <Input
@@ -277,6 +293,7 @@
<ThemeSection <ThemeSection
title="Layer state" title="Layer state"
icon={Layers}
contentClass="flex flex-wrap items-center gap-x-4 gap-y-2 pt-2.5" contentClass="flex flex-wrap items-center gap-x-4 gap-y-2 pt-2.5"
> >
<div class="flex items-center gap-1.5"> <div class="flex items-center gap-1.5">
@@ -389,7 +406,11 @@
/> />
{#if element.type === 'text' || element.type === 'data'} {#if element.type === 'text' || element.type === 'data'}
<ThemeSection title={element.type === 'data' ? 'Data' : 'Text'} contentClass="space-y-3 pt-2.5"> <ThemeSection
title={element.type === 'data' ? 'Data' : 'Text'}
icon={Type}
contentClass="space-y-3 pt-2.5"
>
{#if element.type === 'data'} {#if element.type === 'data'}
<div class="space-y-1.5"> <div class="space-y-1.5">
<Label for="element-data-field" class={label}>Value</Label> <Label for="element-data-field" class={label}>Value</Label>
@@ -682,7 +703,7 @@
<ThemeTextStyleControls {element} onchange={(patch) => Object.assign(element, patch)} /> <ThemeTextStyleControls {element} onchange={(patch) => Object.assign(element, patch)} />
</ThemeSection> </ThemeSection>
{:else if element.type === 'svelte'} {:else if element.type === 'svelte'}
<ThemeSection title="Svelte component" contentClass="space-y-3 pt-2.5"> <ThemeSection title="Svelte component" icon={Component} contentClass="space-y-3 pt-2.5">
<div <div
class="rounded-md border border-amber-500/25 bg-amber-500/10 p-2 text-[9px] leading-relaxed text-amber-100" class="rounded-md border border-amber-500/25 bg-amber-500/10 p-2 text-[9px] leading-relaxed text-amber-100"
> >
@@ -708,7 +729,7 @@
</div> </div>
</ThemeSection> </ThemeSection>
{:else if element.type === 'image' || element.type === 'video'} {:else if element.type === 'image' || element.type === 'video'}
<ThemeSection title="Media" contentClass="space-y-3 pt-2.5"> <ThemeSection title="Media" icon={ImageIcon} contentClass="space-y-3 pt-2.5">
<div class="rounded-md border border-theme-800 bg-black/20 p-2"> <div class="rounded-md border border-theme-800 bg-black/20 p-2">
<p class="text-[10px] uppercase tracking-wide text-muted-foreground">Asset</p> <p class="text-[10px] uppercase tracking-wide text-muted-foreground">Asset</p>
<p class="mt-1 truncate font-mono text-[10px] text-theme-100">{element.src}</p> <p class="mt-1 truncate font-mono text-[10px] text-theme-100">{element.src}</p>
@@ -816,7 +837,7 @@
{/if} {/if}
</ThemeSection> </ThemeSection>
{:else if element.type === 'lottie'} {:else if element.type === 'lottie'}
<ThemeSection title="Lottie animation" contentClass="space-y-3 pt-2.5"> <ThemeSection title="Lottie animation" icon={Film} contentClass="space-y-3 pt-2.5">
<div class="rounded-md border border-theme-800 bg-black/20 p-2"> <div class="rounded-md border border-theme-800 bg-black/20 p-2">
<p class="text-[10px] uppercase tracking-wide text-muted-foreground">Animation</p> <p class="text-[10px] uppercase tracking-wide text-muted-foreground">Animation</p>
<p class="mt-1 truncate font-mono text-[10px] text-theme-100">{element.src}</p> <p class="mt-1 truncate font-mono text-[10px] text-theme-100">{element.src}</p>
@@ -872,7 +893,7 @@
</p> </p>
</ThemeSection> </ThemeSection>
{:else if element.type === 'shape'} {:else if element.type === 'shape'}
<ThemeSection title="Shape" contentClass="space-y-3 pt-2.5"> <ThemeSection title="Shape" icon={Shapes} contentClass="space-y-3 pt-2.5">
<div class="space-y-1"> <div class="space-y-1">
<Label for="element-shape" class={label}>Shape</Label> <Label for="element-shape" class={label}>Shape</Label>
<Select.Root <Select.Root
@@ -1140,7 +1161,7 @@
</div> </div>
</ThemeSection> </ThemeSection>
{:else if element.type === 'icon'} {:else if element.type === 'icon'}
<ThemeSection title="Icon" contentClass="space-y-3 pt-2.5"> <ThemeSection title="Icon" icon={Sparkles} contentClass="space-y-3 pt-2.5">
<div class="space-y-1"> <div class="space-y-1">
<Label for="element-icon" class={label}>Icon</Label> <Label for="element-icon" class={label}>Icon</Label>
<ThemeIconPicker bind:value={element.icon} {iconSet} /> <ThemeIconPicker bind:value={element.icon} {iconSet} />
@@ -1172,7 +1193,7 @@
</div> </div>
</ThemeSection> </ThemeSection>
{:else if element.type === 'repeater'} {:else if element.type === 'repeater'}
<ThemeSection title="Repeater" contentClass="space-y-3 pt-2.5"> <ThemeSection title="Repeater" icon={Repeat} contentClass="space-y-3 pt-2.5">
<div class="space-y-1"> <div class="space-y-1">
<Label for="element-repeater-source" class={label}>Tile</Label> <Label for="element-repeater-source" class={label}>Tile</Label>
<Select.Root <Select.Root
@@ -1294,7 +1315,7 @@
</p> </p>
</ThemeSection> </ThemeSection>
{:else if element.type === 'gauge'} {:else if element.type === 'gauge'}
<ThemeSection title="Gauge" contentClass="space-y-3 pt-2.5"> <ThemeSection title="Gauge" icon={Gauge} contentClass="space-y-3 pt-2.5">
<div class="grid grid-cols-2 gap-2"> <div class="grid grid-cols-2 gap-2">
<div class="space-y-1"> <div class="space-y-1">
<Label for="element-gauge-mode" class={label}>Style</Label> <Label for="element-gauge-mode" class={label}>Style</Label>
@@ -1410,7 +1431,7 @@
</div> </div>
</ThemeSection> </ThemeSection>
{:else if element.type === 'ticker'} {:else if element.type === 'ticker'}
<ThemeSection title="Ticker" contentClass="space-y-3 pt-2.5"> <ThemeSection title="Ticker" icon={Type} contentClass="space-y-3 pt-2.5">
<div class="space-y-1"> <div class="space-y-1">
<Label for="element-ticker-text" class={label}>Text</Label> <Label for="element-ticker-text" class={label}>Text</Label>
<Textarea <Textarea
@@ -1507,7 +1528,7 @@
{/if} {/if}
</ThemeSection> </ThemeSection>
{:else if element.type === 'button'} {:else if element.type === 'button'}
<ThemeSection title="Button" contentClass="space-y-3 pt-2.5"> <ThemeSection title="Button" icon={MousePointerClick} contentClass="space-y-3 pt-2.5">
<div class="space-y-1"> <div class="space-y-1">
<Label for="element-button-label" class={label}>Label</Label> <Label for="element-button-label" class={label}>Label</Label>
<Input id="element-button-label" class={field} bind:value={element.label} /> <Input id="element-button-label" class={field} bind:value={element.label} />
@@ -1593,6 +1614,47 @@
</p> </p>
</div> </div>
{/if} {/if}
<div class="space-y-1.5 pt-1">
<Button
variant="outline"
size="sm"
class="w-full gap-2 border-theme-700 bg-theme-900/60 text-xs text-theme-100 hover:bg-theme-800"
onclick={() => {
if (element.action.type === 'navigate') {
sileo.info({
title: 'Button Action Test',
description: `Navigates to screen "${element.action.screen}"`,
});
} else if (element.action.type === 'launch') {
sileo.info({
title: 'Button Action Test',
description: 'Launches osu!',
});
} else if (element.action.type === 'url') {
if (element.action.url) {
sileo.info({
title: 'Button Action Test',
description: `Opens ${element.action.url}`,
});
void openURL(element.action.url);
} else {
sileo.warning({
title: 'Button Action Test',
description: 'No URL specified',
});
}
}
}}
>
<Play class="size-3.5 text-primary" />
Test Button Action
</Button>
<p class="text-[9px] leading-relaxed text-muted-foreground">
In editor mode, canvas clicks select layers for dragging. Test actions using this button,
or Shift+click on canvas.
</p>
</div>
<div class="grid grid-cols-2 gap-2"> <div class="grid grid-cols-2 gap-2">
<div class="space-y-1"> <div class="space-y-1">
<Label for="element-button-icon" class={label}>Icon</Label> <Label for="element-button-icon" class={label}>Icon</Label>
@@ -1650,7 +1712,7 @@
</div> </div>
</ThemeSection> </ThemeSection>
{:else if element.type === 'path'} {:else if element.type === 'path'}
<ThemeSection title="Vector path" contentClass="space-y-3 pt-2.5"> <ThemeSection title="Vector path" icon={Spline} contentClass="space-y-3 pt-2.5">
<div class="space-y-1"> <div class="space-y-1">
<Label for="element-path-data" class={label}>SVG path data</Label> <Label for="element-path-data" class={label}>SVG path data</Label>
<Textarea <Textarea
@@ -1796,7 +1858,7 @@
</div> </div>
</ThemeSection> </ThemeSection>
{:else if element.type === 'particles'} {:else if element.type === 'particles'}
<ThemeSection title="Particles" contentClass="space-y-3 pt-2.5"> <ThemeSection title="Particles" icon={Sparkles} contentClass="space-y-3 pt-2.5">
<div class="space-y-1"> <div class="space-y-1">
<Label for="element-particles-preset" class={label}>Preset</Label> <Label for="element-particles-preset" class={label}>Preset</Label>
<Select.Root <Select.Root
@@ -1900,7 +1962,7 @@
</p> </p>
</ThemeSection> </ThemeSection>
{:else if element.type === 'clock'} {:else if element.type === 'clock'}
<ThemeSection title="Clock" contentClass="space-y-3 pt-2.5"> <ThemeSection title="Clock" icon={Clock} contentClass="space-y-3 pt-2.5">
<div class="space-y-1"> <div class="space-y-1">
<Label for="element-clock-mode" class={label}>Style</Label> <Label for="element-clock-mode" class={label}>Style</Label>
<Select.Root <Select.Root
@@ -2067,7 +2129,7 @@
</p> </p>
</ThemeSection> </ThemeSection>
{:else if element.type === 'countdown'} {:else if element.type === 'countdown'}
<ThemeSection title="Countdown" contentClass="space-y-3 pt-2.5"> <ThemeSection title="Countdown" icon={Timer} contentClass="space-y-3 pt-2.5">
<div class="space-y-1.5"> <div class="space-y-1.5">
<Label for="element-countdown-target" class={label}>Target date & time</Label> <Label for="element-countdown-target" class={label}>Target date & time</Label>
<DatePicker <DatePicker
@@ -2165,9 +2227,346 @@
</div> </div>
</div> </div>
</ThemeSection> </ThemeSection>
{:else if element.type === 'widget'}
<ThemeSection title="Widget" icon={LayoutGrid} contentClass="space-y-3 pt-2.5">
<div class="space-y-1.5">
<Label for="element-widget-type" class={label}>Widget Type</Label>
<Select.Root
type="single"
value={element.widget}
onValueChange={(val) => {
if (val) {
element.widget = val as ThemeV2WidgetKind;
if (val === 'player-card') {
element.width = 380;
element.height = 220;
} else if (val === 'avatar') {
element.width = 72;
element.height = 72;
if (!element.variant) element.variant = 'circle';
} else if (val === 'recent-activity') {
element.width = 320;
element.height = 180;
} else if (val === 'telemetry') {
element.width = 320;
element.height = 42;
} else if (val === 'header') {
element.width = 320;
element.height = 64;
} else if (val === 'launch-button') {
element.width = 200;
element.height = 52;
}
}
}}
>
<Select.Trigger
id="element-widget-type"
class="h-8 border-theme-800 bg-theme-950 text-xs text-theme-50"
>
{element.widget === 'launch-button'
? 'Launch Button'
: element.widget === 'player-card'
? 'Player Card'
: element.widget === 'avatar'
? 'Player Avatar'
: element.widget === 'recent-activity'
? 'Recent Activity'
: element.widget === 'telemetry'
? 'Telemetry Bar'
: 'Header Title'}
</Select.Trigger>
<Select.Content class="border-theme-800 bg-theme-950">
<Select.Item value="launch-button" label="Launch Button" />
<Select.Item value="player-card" label="Player Card" />
<Select.Item value="avatar" label="Player Avatar" />
<Select.Item value="recent-activity" label="Recent Activity" />
<Select.Item value="telemetry" label="Telemetry Bar" />
<Select.Item value="header" label="Header Title" />
</Select.Content>
</Select.Root>
</div>
<div class="space-y-1.5">
<Label for="element-widget-variant" class={label}>Variant</Label>
<Select.Root
type="single"
value={element.variant ??
(element.widget === 'avatar'
? 'circle'
: element.widget === 'launch-button'
? 'primary'
: 'full')}
onValueChange={(val) => {
if (val) {
element.variant = val as ThemeV2WidgetVariant;
if (element.widget === 'player-card') {
if (val === 'minimal') {
element.width = 280;
element.height = 64;
} else if (val === 'banner') {
element.width = 340;
element.height = 76;
element.showStats = false;
} else if (val === 'compact') {
element.width = 340;
element.height = 140;
element.showStats = true;
} else if (val === 'full') {
element.width = 380;
element.height = 220;
element.showStats = true;
}
} else if (element.widget === 'recent-activity') {
if (val === 'minimal') {
element.width = 280;
element.height = 64;
} else if (val === 'compact') {
element.width = 340;
element.height = 120;
} else if (val === 'full') {
element.width = 340;
element.height = 200;
}
} else if (element.widget === 'launch-button') {
if (val === 'icon-only') {
element.width = 48;
element.height = 48;
} else if (val === 'compact') {
element.width = 140;
element.height = 42;
} else if (val === 'primary') {
element.width = 256;
element.height = 48;
}
} else if (element.widget === 'header') {
if (val === 'minimal') {
element.width = 240;
element.height = 42;
} else if (val === 'compact') {
element.width = 380;
element.height = 48;
} else if (val === 'full') {
element.width = 320;
element.height = 64;
}
}
}
}}
>
<Select.Trigger
id="element-widget-variant"
class="h-8 border-theme-800 bg-theme-950 text-xs text-theme-50"
>
{#if element.widget === 'avatar'}
{element.variant === 'rounded'
? 'Rounded Square'
: element.variant === 'square'
? 'Square'
: 'Circle'}
{:else if element.widget === 'launch-button'}
{element.variant === 'compact'
? 'Compact (Pill)'
: element.variant === 'icon-only'
? 'Icon-Only (Circle)'
: 'Primary (Capsule)'}
{:else if element.widget === 'player-card'}
{element.variant === 'compact'
? 'Compact (2 Stats)'
: element.variant === 'minimal'
? 'Minimal (Pill)'
: element.variant === 'banner'
? 'Banner (Profile & Level Only)'
: 'Full (4 Stats)'}
{:else}
{element.variant === 'compact'
? 'Compact'
: element.variant === 'minimal' || element.variant === 'icon-only'
? 'Minimal'
: 'Full'}
{/if}
</Select.Trigger>
<Select.Content class="border-theme-800 bg-theme-950">
{#if element.widget === 'avatar'}
<Select.Item value="circle" label="Circle" />
<Select.Item value="rounded" label="Rounded Square" />
<Select.Item value="square" label="Square" />
{:else if element.widget === 'launch-button'}
<Select.Item value="primary" label="Primary (Capsule)" />
<Select.Item value="compact" label="Compact (Pill)" />
<Select.Item value="icon-only" label="Icon-Only (Circle)" />
{:else if element.widget === 'player-card'}
<Select.Item value="full" label="Full (4 Stats)" />
<Select.Item value="compact" label="Compact (2 Stats)" />
<Select.Item value="banner" label="Banner (Profile & Level Only)" />
<Select.Item value="minimal" label="Minimal (Pill)" />
{:else}
<Select.Item value="full" label="Full" />
<Select.Item value="compact" label="Compact" />
<Select.Item value="minimal" label="Minimal" />
{/if}
</Select.Content>
</Select.Root>
</div>
{#if element.widget === 'player-card' && element.variant !== 'minimal'}
<div class="space-y-2 border-t border-theme-800 pt-2">
<Label class={label}>Player Card Options</Label>
<div class="space-y-2">
<div class="flex items-center gap-2">
<Checkbox
id="element-player-stats"
checked={element.showStats !== false && element.variant !== 'banner'}
onCheckedChange={(checked) => {
element.showStats = checked === true;
if (!checked) {
element.variant = 'banner';
element.height = Math.min(element.height, 80);
} else {
element.variant = 'full';
element.height = Math.max(element.height, 220);
}
}}
/>
<Label for="element-player-stats" class="text-xs text-theme-100 cursor-pointer">
Show stats grid (rank, pp, accuracy, plays)
</Label>
</div>
</div>
</div>
{/if}
{#if element.widget === 'avatar'}
<div class="space-y-2 border-t border-theme-800 pt-2">
<Label class={label}>Avatar Display Options</Label>
<div class="space-y-2">
<div class="flex items-center gap-2">
<Checkbox
id="element-avatar-country"
checked={element.showCountry !== false}
onCheckedChange={(checked) => (element.showCountry = checked === true)}
/>
<Label
for="element-avatar-country"
class="text-[11px] font-normal text-muted-foreground"
>
Show Country Flag Badge
</Label>
</div>
<div class="flex items-center gap-2">
<Checkbox
id="element-avatar-level"
checked={element.showLevel !== false}
onCheckedChange={(checked) => (element.showLevel = checked === true)}
/>
<Label
for="element-avatar-level"
class="text-[11px] font-normal text-muted-foreground"
>
Show Level Badge
</Label>
</div>
<div class="flex items-center gap-2">
<Checkbox
id="element-avatar-ring"
checked={element.showOnlineRing !== false}
onCheckedChange={(checked) => (element.showOnlineRing = checked === true)}
/>
<Label
for="element-avatar-ring"
class="text-[11px] font-normal text-muted-foreground"
>
Online Status Glow Ring
</Label>
</div>
</div>
</div>
{/if}
<!-- Quick Snap Position Presets for Widgets -->
<div class="space-y-1.5 border-t border-theme-800 pt-2">
<Label class={label}>Quick Position Snaps</Label>
<div class="grid grid-cols-2 gap-1">
<Button
variant="outline"
size="sm"
class="h-6 border-theme-800 bg-theme-900/40 text-[10px] hover:bg-theme-800"
onclick={() => {
element.x = 1000 - element.width - 24;
element.y = 650 - element.height - 24;
}}
>
↘ Bottom-Right
</Button>
<Button
variant="outline"
size="sm"
class="h-6 border-theme-800 bg-theme-900/40 text-[10px] hover:bg-theme-800"
onclick={() => {
element.x = Math.round((1000 - element.width) / 2);
element.y = 650 - element.height - 24;
}}
>
↓ Bottom-Center
</Button>
<Button
variant="outline"
size="sm"
class="h-6 border-theme-800 bg-theme-900/40 text-[10px] hover:bg-theme-800"
onclick={() => {
element.x = 24;
element.y = 650 - element.height - 24;
}}
>
↙ Bottom-Left
</Button>
<Button
variant="outline"
size="sm"
class="h-6 border-theme-800 bg-theme-900/40 text-[10px] hover:bg-theme-800"
onclick={() => {
element.x = 1000 - element.width - 24;
element.y = 24;
}}
>
↗ Top-Right
</Button>
<Button
variant="outline"
size="sm"
class="col-span-2 h-6 border-theme-800 bg-theme-900/40 text-[10px] hover:bg-theme-800"
onclick={() => {
element.x = Math.round((1000 - element.width) / 2);
element.y = Math.round((650 - element.height) / 2);
}}
>
⊙ Center on Canvas
</Button>
</div>
</div>
<p class="text-[9px] leading-relaxed text-muted-foreground">
{#if element.widget === 'launch-button'}
Interactive game launch button. Satisfies the required Launch button condition.
{:else if element.widget === 'player-card'}
Live stats card displaying rank, pp, accuracy, level, and playcount.
{:else if element.widget === 'avatar'}
Player avatar with live profile image, shape styles, country badge, and online ring.
{:else if element.widget === 'recent-activity'}
Highlights the player's latest play, beatmap cover art, and grade badge.
{:else if element.widget === 'telemetry'}
Pill bar showing beatmap counts, skin counts, ping, and osu! build.
{:else if element.widget === 'header'}
Launcher title and dynamic greeting. Full shows title and subtitle, Compact shows an
inline pill greeting, and Minimal displays title only.
{:else}
Launcher title and dynamic greeting.
{/if}
</p>
</ThemeSection>
{/if} {/if}
<ThemeSection title="Mask" contentClass="space-y-3 pt-2.5"> <ThemeSection title="Mask" icon={Scan} contentClass="space-y-3 pt-2.5">
<div class="space-y-1"> <div class="space-y-1">
<Label for="element-mask-shape" class={label}>Clip shape</Label> <Label for="element-mask-shape" class={label}>Clip shape</Label>
<Select.Root <Select.Root
@@ -2,7 +2,8 @@
import ThemeSection from '$lib/components/theme/ThemeSection.svelte'; import ThemeSection from '$lib/components/theme/ThemeSection.svelte';
import Button from '$lib/components/ui/button/button.svelte'; import Button from '$lib/components/ui/button/button.svelte';
import Slider from '$lib/components/ui/slider/slider.svelte'; import Slider from '$lib/components/ui/slider/slider.svelte';
import type { ThemeV2Filters } from '$lib/themeV2'; import type { ThemeV2Filters } from '$lib/theme/themeV2';
import { SlidersHorizontal } from '@lucide/svelte';
let { let {
filters, filters,
@@ -67,6 +68,7 @@
<ThemeSection <ThemeSection
title="Filters" title="Filters"
icon={SlidersHorizontal}
open={false} open={false}
actions={filterActions} actions={filterActions}
contentClass="space-y-2.5 pt-2.5" contentClass="space-y-2.5 pt-2.5"
@@ -16,8 +16,8 @@
type ThemeV2Element, type ThemeV2Element,
type ThemeV2Group, type ThemeV2Group,
type ThemeV2MaskShape, type ThemeV2MaskShape,
} from '$lib/themeV2'; } from '$lib/theme/themeV2';
import { Boxes, RefreshCw, Ungroup } from '@lucide/svelte'; import { Boxes, Layers, RefreshCw, Scan, Ungroup } from '@lucide/svelte';
let { let {
group = $bindable(), group = $bindable(),
@@ -58,7 +58,7 @@
</div> </div>
</div> </div>
<ThemeSection title="Group" bordered={false} contentClass="space-y-3 pt-2"> <ThemeSection title="Group" icon={Boxes} bordered={false} contentClass="space-y-3 pt-2">
<div class="space-y-1"> <div class="space-y-1">
<Label for="group-name" class={label}>Group name</Label> <Label for="group-name" class={label}>Group name</Label>
<Input <Input
@@ -96,6 +96,7 @@
<ThemeSection <ThemeSection
title="Group state" title="Group state"
icon={Layers}
contentClass="flex flex-wrap items-center gap-x-4 gap-y-2 pt-2.5" contentClass="flex flex-wrap items-center gap-x-4 gap-y-2 pt-2.5"
> >
<div class="flex items-center gap-1.5"> <div class="flex items-center gap-1.5">
@@ -167,7 +168,7 @@
ondelete={ondeleterule} ondelete={ondeleterule}
/> />
<ThemeSection title="Mask" contentClass="space-y-3 pt-2.5"> <ThemeSection title="Mask" icon={Scan} contentClass="space-y-3 pt-2.5">
<div class="space-y-1"> <div class="space-y-1">
<Label for="group-mask-shape" class={label}>Clip shape</Label> <Label for="group-mask-shape" class={label}>Clip shape</Label>
<Select.Root <Select.Root
+9 -2
View File
@@ -1,17 +1,23 @@
<script lang="ts"> <script lang="ts">
import { getThemeIconBody } from '$lib/themeIconCatalog'; import { getThemeIconBody } from '$lib/theme/themeIconCatalog';
import { DEFAULT_THEME_ICON_SET, type ThemeIconName, type ThemeIconSet } from '$lib/themeIcons'; import {
DEFAULT_THEME_ICON_SET,
type ThemeIconName,
type ThemeIconSet,
} from '$lib/theme/themeIcons';
let { let {
name, name,
set = DEFAULT_THEME_ICON_SET, set = DEFAULT_THEME_ICON_SET,
size = '1em', size = '1em',
class: className = '', class: className = '',
style = '',
}: { }: {
name: ThemeIconName; name: ThemeIconName;
set?: ThemeIconSet; set?: ThemeIconSet;
size?: number | string; size?: number | string;
class?: string; class?: string;
style?: string;
} = $props(); } = $props();
const icon = $derived(getThemeIconBody(name, set)); const icon = $derived(getThemeIconBody(name, set));
@@ -23,6 +29,7 @@
width={size} width={size}
height={size} height={size}
class={className} class={className}
{style}
aria-hidden="true" aria-hidden="true"
focusable="false" focusable="false"
> >
@@ -6,10 +6,10 @@
getFullIconCatalog, getFullIconCatalog,
type IconPackKey, type IconPackKey,
type ThemeIconCatalogItem, type ThemeIconCatalogItem,
} from '$lib/themeIconCatalog'; } from '$lib/theme/themeIconCatalog';
import { DEFAULT_THEME_ICON_SET, type ThemeIconSet } from '$lib/themeIcons'; import { DEFAULT_THEME_ICON_SET, type ThemeIconSet } from '$lib/theme/themeIcons';
import ThemeIcon from './ThemeIcon.svelte'; import ThemeIcon from './ThemeIcon.svelte';
import { Check, ChevronDown, ChevronsUpDown, LayoutGrid, List, Search, X } from '@lucide/svelte'; import { Check, ChevronsUpDown, LayoutGrid, List, Search, X } from '@lucide/svelte';
let { let {
value = $bindable(undefined), value = $bindable(undefined),
@@ -1,13 +1,14 @@
<script lang="ts"> <script lang="ts">
import ThemeBehaviorInspector from '$lib/components/theme/ThemeBehaviorInspector.svelte'; import ThemeBehaviorInspector from '$lib/components/theme/ThemeBehaviorInspector.svelte';
import Button from '$lib/components/ui/button/button.svelte'; import Button from '$lib/components/ui/button/button.svelte';
import { themeBehaviorSummary, themeGroupInteractiveCount } from '$lib/themeLogic'; import { themeEditorSectionOpen } from '$lib/theme/themeEditorUiState';
import { themeBehaviorSummary, themeGroupInteractiveCount } from '$lib/theme/themeLogic';
import type { import type {
ThemeV2Behavior, ThemeV2Behavior,
ThemeV2BehaviorTarget, ThemeV2BehaviorTarget,
ThemeV2Element, ThemeV2Element,
ThemeV2Group, ThemeV2Group,
} from '$lib/themeV2'; } from '$lib/theme/themeV2';
import { AlertTriangle, ChevronDown, Plus, Zap } from '@lucide/svelte'; import { AlertTriangle, ChevronDown, Plus, Zap } from '@lucide/svelte';
let { let {
@@ -30,8 +31,13 @@
ondelete: (id: string) => void; ondelete: (id: string) => void;
} = $props(); } = $props();
let open = $state(false); const sectionKey = 'Logic';
let open = $state(themeEditorSectionOpen.get(sectionKey) ?? false);
let selectedId = $state<string | undefined>(undefined); let selectedId = $state<string | undefined>(undefined);
$effect(() => {
themeEditorSectionOpen.set(sectionKey, open);
});
let section = $state<HTMLElement>(); let section = $state<HTMLElement>();
let lastFocusToken = 0; let lastFocusToken = 0;
@@ -17,12 +17,38 @@
let container = $state<HTMLDivElement | undefined>(undefined); let container = $state<HTMLDivElement | undefined>(undefined);
let animation: AnimationItem | undefined; let animation: AnimationItem | undefined;
let reducedMotion = false; let reducedMotion = false;
let windowActive = true;
function syncPlayback() {
if (!animation) return;
animation.loop = loop;
animation.setSpeed(speed);
if (autoplay && !reducedMotion && windowActive && document.visibilityState === 'visible') {
animation.play();
} else {
animation.pause();
}
}
onMount(() => { onMount(() => {
if (!container || !src) return; if (!container || !src) return;
reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false; reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
let cancelled = false; let cancelled = false;
const onBlur = () => {
windowActive = false;
syncPlayback();
};
const onFocus = () => {
windowActive = true;
syncPlayback();
};
const onVisibilityChange = () => syncPlayback();
window.addEventListener('blur', onBlur);
window.addEventListener('focus', onFocus);
document.addEventListener('visibilitychange', onVisibilityChange);
const start = (animationData?: unknown) => { const start = (animationData?: unknown) => {
if (cancelled || !container) return; if (cancelled || !container) return;
try { try {
@@ -30,7 +56,8 @@
container, container,
renderer: 'svg', renderer: 'svg',
loop, loop,
autoplay: autoplay && !reducedMotion, autoplay:
autoplay && !reducedMotion && windowActive && document.visibilityState === 'visible',
...(animationData ? { animationData } : { path: src }), ...(animationData ? { animationData } : { path: src }),
rendererSettings: { preserveAspectRatio: 'xMidYMid meet' }, rendererSettings: { preserveAspectRatio: 'xMidYMid meet' },
}); });
@@ -52,15 +79,14 @@
return () => { return () => {
cancelled = true; cancelled = true;
window.removeEventListener('blur', onBlur);
window.removeEventListener('focus', onFocus);
document.removeEventListener('visibilitychange', onVisibilityChange);
}; };
}); });
$effect(() => { $effect(() => {
if (!animation) return; syncPlayback();
animation.loop = loop;
animation.setSpeed(speed);
if (autoplay && !reducedMotion) animation.play();
else animation.pause();
}); });
onDestroy(() => { onDestroy(() => {
@@ -0,0 +1,183 @@
<script lang="ts">
import { Button } from '$lib/components/ui/button';
import * as Dialog from '$lib/components/ui/dialog';
import { Label } from '$lib/components/ui/label';
import * as Select from '$lib/components/ui/select';
import Textarea from '$lib/components/ui/textarea/textarea.svelte';
import {
reportCommunityTheme,
type CommunityTheme,
type ThemeReportCategory,
} from '$lib/theme/communityThemes';
import { Flag, LoaderCircle, X } from '@lucide/svelte';
import { sileo } from 'sileo';
let {
open = $bindable(false),
theme,
}: {
open: boolean;
theme: CommunityTheme | null;
} = $props();
const REPORT_CATEGORIES: Array<{ id: ThemeReportCategory; label: string }> = [
{ id: 'spam', label: 'Spam / advertising' },
{ id: 'harassment', label: 'Harassment / hate' },
{ id: 'malware', label: 'Malware / unsafe code' },
{ id: 'copyright', label: 'Copyright / stolen content' },
{ id: 'broken', label: 'Broken / unusable' },
{ id: 'other', label: 'Other' },
];
let category = $state<ThemeReportCategory>('other');
let details = $state('');
let error = $state<string | null>(null);
let submitting = $state(false);
$effect(() => {
if (!open || !theme) return;
category = 'other';
details = '';
error = null;
});
async function submitReport() {
const target = theme;
if (!target || submitting) return;
const reason = details.trim();
if (reason.length < 10) {
error = 'Please describe the problem in at least 10 characters.';
return;
}
submitting = true;
error = null;
try {
await reportCommunityTheme(target.id, reason.slice(0, 500), category);
sileo.success({
title: 'Report submitted',
description: 'Thank you. A moderator will review the theme.',
});
open = false;
} catch (err) {
error = err instanceof Error ? err.message : String(err);
} finally {
submitting = false;
}
}
</script>
<Dialog.Root bind:open>
<Dialog.Content
class="flex w-[calc(100%_-_2rem)] max-w-lg flex-col gap-0 overflow-hidden rounded-xl border-theme-800 bg-theme-950 p-0 text-white shadow-2xl sm:rounded-xl"
>
{#if theme}
<div class="flex items-start justify-between gap-3 border-b border-theme-800/70 p-4">
<div class="min-w-0">
<Dialog.Title class="flex items-center gap-2 text-sm font-semibold text-white">
<Flag class="size-4 text-amber-300" /> Report theme
</Dialog.Title>
<Dialog.Description class="mt-1 text-[11px] text-muted-foreground">
Reporting <span class="text-white/80">{theme.name}</span> by {theme.author.name}.
Reports are visible to moderators only.
</Dialog.Description>
</div>
<Button
variant="ghost"
size="icon"
class="size-7 shrink-0 text-muted-foreground hover:text-white"
onclick={() => (open = false)}
disabled={submitting}
aria-label="Close report form"
>
<X class="size-4" />
</Button>
</div>
<div class="space-y-3 p-4">
<div class="space-y-1.5">
<Label
for="installed-report-category"
class="text-[10px] uppercase tracking-wide text-white/70"
>
Category
</Label>
<Select.Root
type="single"
value={category}
onValueChange={(value) => {
if (value) category = value as ThemeReportCategory;
}}
>
<Select.Trigger
id="installed-report-category"
class="h-8 border-theme-800 bg-theme-900/60 text-[11px] text-white"
>
{REPORT_CATEGORIES.find((item) => item.id === category)?.label ?? 'Other'}
</Select.Trigger>
<Select.Content class="border-theme-800 bg-theme-950">
{#each REPORT_CATEGORIES as item (item.id)}
<Select.Item value={item.id} label={item.label} />
{/each}
</Select.Content>
</Select.Root>
</div>
<div class="space-y-1.5">
<Label
for="installed-report-details"
class="text-[10px] uppercase tracking-wide text-white/70"
>
Details
</Label>
<Textarea
id="installed-report-details"
class="min-h-28 resize-y border-theme-800 bg-theme-900/60 text-[11px] leading-relaxed text-white"
rows={5}
maxlength={500}
placeholder="Describe what is wrong (at least 10 characters)..."
bind:value={details}
oninput={() => (error = null)}
disabled={submitting}
/>
<span class="block text-right text-[9px] text-muted-foreground">
{details.trim().length}/500 · minimum 10
</span>
</div>
{#if error}
<p
class="rounded-lg border border-red-900/40 bg-red-950/20 p-2.5 text-[11px] text-red-300"
>
{error}
</p>
{/if}
</div>
<div class="flex items-center justify-end gap-2 border-t border-theme-800/70 p-3">
<Button
variant="ghost"
size="sm"
class="h-8 text-xs"
onclick={() => (open = false)}
disabled={submitting}
>
Cancel
</Button>
<Button
size="sm"
class="h-8 gap-1 text-xs"
onclick={() => void submitReport()}
disabled={submitting}
>
{#if submitting}
<LoaderCircle class="size-3 animate-spin" /> Sending...
{:else}
<Flag class="size-3" /> Submit report
{/if}
</Button>
</div>
{/if}
</Dialog.Content>
</Dialog.Root>
@@ -1,7 +1,7 @@
<script lang="ts"> <script lang="ts">
import { isThemeClockVariable, THEME_CLOCK_VARIABLE_NAMES } from '$lib/themeClock'; import { isThemeClockVariable, THEME_CLOCK_VARIABLE_NAMES } from '$lib/theme/themeClock';
import { parseThemeScript } from '$lib/themeScriptLang'; import { parseThemeScript } from '$lib/theme/themeScriptLang';
import type { ThemeV2Element, ThemeV2Group, ThemeV2ScriptScreen } from '$lib/themeV2'; import type { ThemeV2Element, ThemeV2Group, ThemeV2ScriptScreen } from '$lib/theme/themeV2';
import { Braces, CircleAlert, Maximize2, Minimize2, X } from '@lucide/svelte'; import { Braces, CircleAlert, Maximize2, Minimize2, X } from '@lucide/svelte';
import type * as Monaco from 'monaco-editor'; import type * as Monaco from 'monaco-editor';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
+13 -5
View File
@@ -1,10 +1,12 @@
<script lang="ts"> <script lang="ts">
import { themeEditorSectionOpen } from '$lib/theme/themeEditorUiState';
import { ChevronDown } from '@lucide/svelte'; import { ChevronDown } from '@lucide/svelte';
import { untrack } from 'svelte';
import type { Component, Snippet } from 'svelte'; import type { Component, Snippet } from 'svelte';
let { let {
title, title,
open = $bindable(true), open: initialOpen = true,
icon: Icon, icon: Icon,
badge, badge,
description, description,
@@ -27,6 +29,12 @@
headingClass?: string; headingClass?: string;
bordered?: boolean; bordered?: boolean;
} = $props(); } = $props();
let isOpen = $state(untrack(() => themeEditorSectionOpen.get(title) ?? initialOpen));
$effect(() => {
themeEditorSectionOpen.set(title, isOpen);
});
</script> </script>
<section class="{bordered ? 'border-t border-theme-800 pt-3 ' : ''}{className}"> <section class="{bordered ? 'border-t border-theme-800 pt-3 ' : ''}{className}">
@@ -34,8 +42,8 @@
<button <button
type="button" type="button"
class="group flex min-w-0 flex-1 items-center gap-1.5 rounded-md py-0.5 text-left transition-colors hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60" class="group flex min-w-0 flex-1 items-center gap-1.5 rounded-md py-0.5 text-left transition-colors hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60"
aria-expanded={open} aria-expanded={isOpen}
onclick={() => (open = !open)} onclick={() => (isOpen = !isOpen)}
> >
{#if Icon} {#if Icon}
<Icon class="size-3.5 shrink-0 text-primary" /> <Icon class="size-3.5 shrink-0 text-primary" />
@@ -49,7 +57,7 @@
</span> </span>
{/if} {/if}
<ChevronDown <ChevronDown
class="ml-auto size-3.5 shrink-0 text-muted-foreground transition-transform duration-200 {open class="ml-auto size-3.5 shrink-0 text-muted-foreground transition-transform duration-200 {isOpen
? 'rotate-180' ? 'rotate-180'
: ''}" : ''}"
/> />
@@ -61,7 +69,7 @@
{/if} {/if}
</div> </div>
{#if open} {#if isOpen}
<div class={contentClass}> <div class={contentClass}>
{#if description} {#if description}
<p class="text-[10px] leading-relaxed text-muted-foreground">{description}</p> <p class="text-[10px] leading-relaxed text-muted-foreground">{description}</p>
+285 -80
View File
@@ -3,16 +3,25 @@
import ThemeIcon from '$lib/components/theme/ThemeIcon.svelte'; import ThemeIcon from '$lib/components/theme/ThemeIcon.svelte';
import ThemeV2Background from '$lib/components/theme/ThemeV2Background.svelte'; import ThemeV2Background from '$lib/components/theme/ThemeV2Background.svelte';
import ThemeV2Elements from '$lib/components/theme/ThemeV2Elements.svelte'; import ThemeV2Elements from '$lib/components/theme/ThemeV2Elements.svelte';
import { scopeThemeCss } from '$lib/themeCssScope'; import * as Avatar from '$lib/components/ui/avatar';
import { fontStack, monoFontStack } from '$lib/themeFonts'; import { currentUserInfo } from '$lib/data';
import { DEFAULT_THEME_ICON_SET } from '$lib/themeIcons'; import { scopeThemeCss } from '$lib/theme/themeCssScope';
import { fontStack, monoFontStack } from '$lib/theme/themeFonts';
import { DEFAULT_THEME_ICON_SET } from '$lib/theme/themeIcons';
import { import {
normalizeChrome,
readableTextColor, readableTextColor,
themeFontFaceCss, themeFontFaceCss,
themeHasLaunchButton,
type ThemeV2ButtonAction,
type ThemeV2Definition, type ThemeV2Definition,
type ThemeV2Group, type ThemeV2Group,
type ThemeV2ScriptValue, type ThemeV2ScriptValue,
} from '$lib/themeV2'; type ThemeV2WidgetKind,
} from '$lib/theme/themeV2';
import { currentUser } from '$lib/userAuthentication';
import { countryCodeToEmoji } from '$lib/utils';
import { Clock, Trophy } from '@lucide/svelte';
let { let {
definition, definition,
@@ -31,6 +40,8 @@
onpatchgroup, onpatchgroup,
oncontext, oncontext,
oncontextgroup, oncontextgroup,
ondetach,
onbuttonaction,
}: { }: {
definition: ThemeV2Definition; definition: ThemeV2Definition;
assets?: string; assets?: string;
@@ -48,6 +59,8 @@
onpatchgroup?: (id: string, patch: Partial<ThemeV2Group>) => void; onpatchgroup?: (id: string, patch: Partial<ThemeV2Group>) => void;
oncontext?: (id: string | undefined, event: MouseEvent) => void; oncontext?: (id: string | undefined, event: MouseEvent) => void;
oncontextgroup?: (id: string, event: MouseEvent) => void; oncontextgroup?: (id: string, event: MouseEvent) => void;
ondetach?: (widgetKind: ThemeV2WidgetKind) => void;
onbuttonaction?: (action: ThemeV2ButtonAction) => void;
} = $props(); } = $props();
const bodyFont = $derived(definition.typography?.body); const bodyFont = $derived(definition.typography?.body);
@@ -56,6 +69,8 @@
const accent = $derived(definition.accentColor?.trim() || '#ff006e'); const accent = $derived(definition.accentColor?.trim() || '#ff006e');
const accentText = $derived(readableTextColor(accent)); const accentText = $derived(readableTextColor(accent));
const iconSet = $derived(definition.iconSet ?? DEFAULT_THEME_ICON_SET); const iconSet = $derived(definition.iconSet ?? DEFAULT_THEME_ICON_SET);
const chrome = $derived(definition.chrome ?? normalizeChrome(undefined, definition.elements));
const hasLaunchBtn = $derived(themeHasLaunchButton(definition));
const stageStyle = $derived( const stageStyle = $derived(
[ [
`font-family:${fontStack(bodyFont)}`, `font-family:${fontStack(bodyFont)}`,
@@ -124,94 +139,283 @@
</div> </div>
</aside> </aside>
<section class="relative flex min-w-0 flex-col"> <section class="relative flex min-w-0 flex-col justify-between">
<div class="flex min-h-0 flex-1 flex-col"> {#if chrome.header !== false}
<div class="mt-12 mb-auto flex flex-col px-6"> <div class="px-8 pt-7 pb-2 shrink-0 z-10 flex items-start justify-between gap-4">
<span <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
class="text-4xl font-bold drop-shadow-lg"
style="font-family:{fontStack(headingFont, bodyFont)}"
>
EZPPLauncher
</span>
<span class="font-semibold text-muted-foreground drop-shadow-lg">Hello Guest!</span>
</div>
<div class="relative h-50 shrink-0">
<div <div
class="absolute left-0 top-0 m-1 flex h-48 w-72 flex-col items-center justify-center gap-3 rounded-md bg-black/40 p-3 ring-1 ring-inset ring-white/5 backdrop-blur-sm" class="group/header relative flex flex-col {interactive
? 'cursor-pointer rounded-xl p-2 -m-2 transition-all hover:bg-white/5 hover:ring-2 hover:ring-primary/40'
: ''}"
role={interactive ? 'button' : undefined}
tabindex={interactive ? 0 : undefined}
onclick={(e) => {
if (interactive) {
e.stopPropagation();
ondetach?.('header');
}
}}
title={interactive ? 'Click to detach into moveable Header Title layer' : undefined}
> >
<div class="flex flex-col items-center gap-1 text-center"> <span
<span class="text-sm font-semibold text-theme-50">See your stats here</span> class="text-3xl font-extrabold tracking-tight drop-shadow-md text-theme-50"
<span class="text-xs text-muted-foreground"> style="font-family:{fontStack(headingFont, bodyFont)}"
Log in with your EZPPFarm account to track your rank, PP, accuracy and playcount. >
</span> EZPPLauncher
</div> </span>
<div class="flex w-full flex-col gap-2"> <span class="text-xs font-medium text-white/70 drop-shadow mt-0.5">
Good evening, Guest!
</span>
{#if interactive}
<div <div
class="flex h-7 w-full items-center justify-center rounded-md bg-primary text-xs font-medium text-primary-foreground" class="pointer-events-none absolute -bottom-6 left-0 whitespace-nowrap rounded border border-white/20 bg-black/90 px-2 py-0.5 text-[10px] text-white opacity-0 shadow transition-opacity group-hover/header:opacity-100"
> >
Log In Click to detach & move freely
</div> </div>
<div {/if}
class="flex h-7 w-full items-center justify-center rounded-md border border-theme-800 text-xs font-medium text-muted-foreground"
>
Register
</div>
</div>
</div> </div>
</div> </div>
{:else}
<div></div>
{/if}
<div class="px-8 py-2 my-auto z-10">
{#if chrome.layoutMode === 'dashboard'}
<div class="flex flex-row items-stretch gap-5 w-full max-w-4xl">
{#if chrome.playerCard !== false}
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
<div
class="flex-1 min-w-[320px] max-w-[440px] bg-black/40 backdrop-blur-md rounded-2xl border border-white/10 p-4 flex flex-col justify-between gap-3 shadow-xl {interactive
? 'cursor-pointer hover:ring-2 hover:ring-primary/40 transition-all'
: ''}"
role={interactive ? 'button' : undefined}
tabindex={interactive ? 0 : undefined}
onclick={(e) => {
if (interactive) {
e.stopPropagation();
ondetach?.('player-card');
}
}}
title={interactive ? 'Click to detach into moveable Player Card layer' : undefined}
>
<div class="flex items-center gap-3">
<div class="relative shrink-0">
<Avatar.Root
class="size-11 rounded-xl border border-white/15 bg-theme-900 shadow"
>
<Avatar.Image
src="https://a.ez-pp.farm/{$currentUser?.id ??
$currentUserInfo?.info?.id ??
0}"
alt={$currentUser?.name ?? 'Player'}
class="h-full w-full object-cover"
/>
<Avatar.Fallback
class="flex h-full w-full items-center justify-center bg-theme-900 text-primary"
>
<ThemeIcon name="user" set={iconSet} size={20} />
</Avatar.Fallback>
</Avatar.Root>
{#if $currentUserInfo?.info?.country}
<span
class="absolute -bottom-1 -right-1 flex items-center justify-center rounded-md border border-white/20 bg-black/90 px-1 py-0.5 text-[9px] leading-none shadow"
>
{countryCodeToEmoji($currentUserInfo.info.country)}
</span>
{/if}
</div>
<div>
<span class="font-bold text-sm text-theme-50 block"
>{$currentUser?.name ?? 'Guest Player'}</span
>
<span class="text-xs text-muted-foreground block">
Lv.{$currentUserInfo?.stats?.['0']?.level ?? 98} · {(
$currentUserInfo?.stats?.['0']?.acc ?? 93
).toFixed(1)}%
</span>
</div>
</div>
<div class="grid grid-cols-2 gap-2 text-xs">
<div class="bg-white/5 rounded-xl p-2.5">
<span class="text-[10px] text-muted-foreground block">Rank</span>
<span class="font-bold text-sm text-theme-50">#102</span>
</div>
<div class="bg-white/5 rounded-xl p-2.5">
<span class="text-[10px] text-muted-foreground block">Performance</span>
<span class="font-bold text-sm text-primary">4,521pp</span>
</div>
</div>
</div>
{/if}
{#if chrome.recentActivity !== false}
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
<div
class="flex-1 min-w-[300px] max-w-[380px] bg-black/40 backdrop-blur-md rounded-2xl border border-white/10 overflow-hidden shadow-xl flex flex-col justify-between {interactive
? 'cursor-pointer hover:ring-2 hover:ring-primary/40 transition-all'
: ''}"
role={interactive ? 'button' : undefined}
tabindex={interactive ? 0 : undefined}
onclick={(e) => {
if (interactive) {
e.stopPropagation();
ondetach?.('recent-activity');
}
}}
title={interactive
? 'Click to detach into moveable Recent Activity layer'
: undefined}
>
<!-- Mini Cover Header -->
<div class="relative h-20 w-full shrink-0 overflow-hidden bg-theme-900/80">
<div
class="absolute inset-0 bg-gradient-to-t from-black via-black/50 to-transparent"
></div>
<div class="absolute top-2 left-2.5 right-2.5 flex items-center justify-between">
<span
class="rounded-full border border-white/10 bg-black/60 px-2 py-0.5 text-[9px] font-bold uppercase tracking-wider text-white/90"
>
Recent Activity
</span>
<span
class="rounded border border-amber-300/40 bg-amber-400/20 px-1.5 py-0.5 text-[10px] font-black text-amber-300"
>
S
</span>
</div>
<div class="absolute bottom-1.5 left-2.5 right-2.5 flex min-w-0 flex-col">
<span class="truncate text-xs font-bold text-white">Space Pirates</span>
<span class="truncate text-[10px] text-white/70">Waterflame</span>
</div>
</div>
<!-- Metrics Body -->
<div class="flex flex-1 flex-col justify-center gap-2 p-2.5">
<div class="flex items-center justify-between gap-1 text-[11px]">
<span class="max-w-[180px] truncate font-semibold text-primary">
[Galactic Thieves]
</span>
<div
class="flex items-center gap-1 rounded-md border border-amber-400/20 bg-amber-400/10 px-2 py-0.5 text-[10px] font-bold text-amber-300"
>
<Trophy class="size-3" />
<span>Rank #1</span>
</div>
</div>
<div
class="flex items-center justify-between border-t border-white/5 pt-1.5 text-[10px] text-muted-foreground"
>
<span class="flex items-center gap-1 font-mono">
<Clock class="size-2.5" />
5d ago
</span>
<span class="text-white/60">ez-pp.farm</span>
</div>
</div>
</div>
{/if}
</div>
{:else if chrome.layoutMode === 'classic'}
{#if chrome.playerCard !== false}
<div class="flex flex-col justify-end">
<div
class="w-72 h-48 bg-black/40 backdrop-blur-sm rounded-md ring-1 ring-inset ring-white/5 flex flex-col items-center justify-center p-3 gap-3"
>
<div class="flex flex-col items-center gap-1 text-center">
<span class="text-sm font-semibold text-theme-50">See your stats here</span>
<span class="text-xs text-muted-foreground"
>Log in with your EZPPFarm account to track your rank.</span
>
</div>
<div class="flex w-full flex-col gap-2">
<div
class="flex h-7 w-full items-center justify-center rounded-md bg-primary text-xs font-medium text-primary-foreground"
>
Log In
</div>
</div>
</div>
</div>
{/if}
{/if}
</div> </div>
<div {#if chrome.dock !== false}
class="relative z-10 flex items-center justify-between border-t border-t-theme-900 bg-black/40 px-8 py-4 backdrop-blur-sm" <div
> class="relative z-10 flex items-center justify-between border-t border-t-theme-900 bg-black/40 px-8 py-3.5 backdrop-blur-sm shrink-0"
<div class="flex items-center gap-4"> >
<div class="flex items-center gap-2"> {#if chrome.dockTelemetry !== false}
<ThemeIcon name="music" set={iconSet} class="size-3.5 text-blue-400" /> <div class="flex items-center gap-3">
<span class="text-[11px] font-medium text-white/70">1.2k</span> <div
</div> class="flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-white/5 border border-white/5 text-[11px] text-white/80"
<div class="flex items-center gap-2"> >
<ThemeIcon name="brush" set={iconSet} class="size-3.5 text-amber-400" /> <ThemeIcon name="music" set={iconSet} class="size-3.5 text-blue-400" />
<span class="text-[11px] font-medium text-white/70">42</span> <span>1.2k</span>
</div> </div>
<div class="flex items-center gap-2"> <div
<ThemeIcon name="wifi" set={iconSet} class="size-3.5 text-emerald-400" /> class="flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-white/5 border border-white/5 text-[11px] text-white/80"
<span class="text-[11px] font-medium text-white/70">19ms</span> >
</div> <ThemeIcon name="brush" set={iconSet} class="size-3.5 text-amber-400" />
<div class="h-4 w-px bg-white/10"></div> <span>42</span>
<span </div>
class="rounded-full border border-white/6 bg-white/10 px-2 py-0.5 text-[10px] text-white/50" <div
> class="flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-white/5 border border-white/5 text-[11px] text-white/80"
stable >
</span> <ThemeIcon name="wifi" set={iconSet} class="size-3.5 text-emerald-400" />
<span <span>19ms</span>
class="rounded-full border border-white/6 bg-white/10 px-2 py-0.5 font-mono text-[10px] text-white/50" </div>
>
20260101.0
</span>
<span
class="rounded-full border border-primary/20 bg-primary/20 px-2 py-0.5 text-[10px] text-primary"
>
Default skin
</span>
</div>
<div class="flex h-12 items-center rounded-full bg-primary shadow-lg shadow-primary/25">
<div class="relative flex size-12 shrink-0 items-center justify-center">
<div
class="relative z-10 flex size-9 items-center justify-center rounded-full bg-black/30"
>
<ThemeIcon
name="launch"
set={iconSet}
class="ml-0.5 size-4 fill-current text-primary-foreground"
/>
</div> </div>
</div> {:else}
<div class="w-52 pl-1 pr-6 text-center"> <div></div>
<p class="text-sm font-bold leading-tight text-primary-foreground">Launch</p> {/if}
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
<div
class="group/launch relative flex h-11 items-center rounded-full bg-primary shadow-lg shadow-primary/25 {interactive
? 'cursor-pointer hover:ring-2 hover:ring-white/40 transition-all'
: ''}"
role={interactive ? 'button' : undefined}
tabindex={interactive ? 0 : undefined}
onclick={(e) => {
if (interactive) {
e.stopPropagation();
ondetach?.('launch-button');
}
}}
title={interactive
? 'Click to detach and position Launch Button freely anywhere'
: undefined}
>
<div class="relative flex size-11 shrink-0 items-center justify-center">
<div
class="relative z-10 flex size-8 items-center justify-center rounded-full bg-black/30"
>
<ThemeIcon
name="launch"
set={iconSet}
class="ml-0.5 size-3.5 fill-current text-primary-foreground"
/>
</div>
</div>
<div class="w-48 pl-1 pr-5 text-center">
<p class="text-xs font-bold leading-tight text-primary-foreground">Launch</p>
</div>
{#if interactive}
<div
class="pointer-events-none absolute -top-8 left-1/2 -translate-x-1/2 whitespace-nowrap rounded border border-white/20 bg-black/90 px-2 py-0.5 text-[10px] text-white opacity-0 shadow transition-opacity group-hover/launch:opacity-100"
>
Click to detach & move freely
</div>
{/if}
</div> </div>
</div> </div>
</div> {:else if !hasLaunchBtn}
<div
class="fixed bottom-6 right-6 z-30 flex items-center gap-2 rounded-full border border-amber-500/50 bg-amber-500/20 px-3 py-1.5 text-xs font-semibold text-amber-300 backdrop-blur"
>
<span>⚠️ Launch Button Missing</span>
</div>
{/if}
</section> </section>
</div> </div>
@@ -238,5 +442,6 @@
{onpatchgroup} {onpatchgroup}
{oncontext} {oncontext}
{oncontextgroup} {oncontextgroup}
{onbuttonaction}
/> />
</div> </div>
@@ -8,8 +8,8 @@
ThemeV2TextDecoration, ThemeV2TextDecoration,
ThemeV2TextStyle, ThemeV2TextStyle,
ThemeV2TextTransform, ThemeV2TextTransform,
} from '$lib/themeV2'; } from '$lib/theme/themeV2';
import { Bold, Italic, RotateCcw, Strikethrough, Underline } from '@lucide/svelte'; import { Bold, Italic, RotateCcw, Strikethrough, Type, Underline } from '@lucide/svelte';
let { let {
element, element,
@@ -93,6 +93,7 @@
<ThemeSection <ThemeSection
title="Text style" title="Text style"
icon={Type}
open={false} open={false}
actions={textStyleActions} actions={textStyleActions}
contentClass="space-y-2 pt-2.5" contentClass="space-y-2 pt-2.5"
@@ -3,7 +3,8 @@
import Button from '$lib/components/ui/button/button.svelte'; import Button from '$lib/components/ui/button/button.svelte';
import Input from '$lib/components/ui/input/input.svelte'; import Input from '$lib/components/ui/input/input.svelte';
import Label from '$lib/components/ui/label/label.svelte'; import Label from '$lib/components/ui/label/label.svelte';
import type { ThemeV2Transform } from '$lib/themeV2'; import Slider from '$lib/components/ui/slider/slider.svelte';
import type { ThemeV2Transform } from '$lib/theme/themeV2';
import { FlipHorizontal2, FlipVertical2, RotateCcw, RotateCw } from '@lucide/svelte'; import { FlipHorizontal2, FlipVertical2, RotateCcw, RotateCw } from '@lucide/svelte';
type TransformTarget = ThemeV2Transform & { offsetX?: number; offsetY?: number }; type TransformTarget = ThemeV2Transform & { offsetX?: number; offsetY?: number };
@@ -34,6 +35,7 @@
(transform.skewY ?? 0) === 0 && (transform.skewY ?? 0) === 0 &&
!transform.flipX && !transform.flipX &&
!transform.flipY && !transform.flipY &&
(transform.parallax ?? 0) === 0 &&
(!includeTranslate || ((transform.offsetX ?? 0) === 0 && (transform.offsetY ?? 0) === 0)) (!includeTranslate || ((transform.offsetX ?? 0) === 0 && (transform.offsetY ?? 0) === 0))
); );
@@ -87,6 +89,7 @@
skewY: 0, skewY: 0,
flipX: false, flipX: false,
flipY: false, flipY: false,
parallax: 0,
...(includeTranslate ? { offsetX: 0, offsetY: 0 } : {}), ...(includeTranslate ? { offsetX: 0, offsetY: 0 } : {}),
}); });
} }
@@ -110,6 +113,7 @@
<ThemeSection <ThemeSection
title="Transform" title="Transform"
icon={RotateCw}
open={false} open={false}
actions={transformActions} actions={transformActions}
contentClass="space-y-2 pt-2.5" contentClass="space-y-2 pt-2.5"
@@ -257,4 +261,24 @@
</Button> </Button>
</div> </div>
</div> </div>
<div class="mt-2.5 flex items-center justify-between border-t border-theme-800/40 pt-2">
<div class="flex flex-col">
<span class={label}>Parallax depth</span>
<span class="text-[9px] text-muted-foreground">3D cursor perspective</span>
</div>
<div class="flex items-center gap-2">
<Slider
min={-1}
max={1}
step={0.05}
value={transform.parallax ?? 0}
onValueChange={(value) => onchange({ parallax: value })}
class="w-24"
/>
<span class="w-8 font-mono text-[10px] text-right text-muted-foreground">
{Math.round((transform.parallax ?? 0) * 100)}%
</span>
</div>
</div>
</ThemeSection> </ThemeSection>
+114 -54
View File
@@ -1,10 +1,12 @@
<script lang="ts"> <script lang="ts">
import { custom_theme_volume } from '$lib/global'; import { custom_theme_volume } from '$lib/global';
import { themeMediaSource, themeVideoLifecycle } from '$lib/themeMedia'; import { playThemeMedia, themeMediaSource, themeVideoLifecycle } from '$lib/theme/themeMedia';
import type { ThemeV2Definition } from '$lib/themeV2'; import { themeParallax } from '$lib/theme/themeParallax';
import { themeAssetUrl } from '$lib/themeV2'; import type { ThemeV2Definition } from '$lib/theme/themeV2';
import { themeAssetUrl } from '$lib/theme/themeV2';
import { reduceAnimations } from '$lib/userSettings'; import { reduceAnimations } from '$lib/userSettings';
import { trackMediaContainer } from '$lib/utils'; import { trackMediaContainer } from '$lib/utils';
import { onDestroy } from 'svelte';
let { let {
definition, definition,
@@ -20,6 +22,17 @@
let audioElement = $state<HTMLAudioElement | undefined>(undefined); let audioElement = $state<HTMLAudioElement | undefined>(undefined);
onDestroy(() => {
if (audioElement) {
try {
audioElement.pause();
audioElement.src = '';
} catch {
// ignore
}
}
});
const assetUrl = (path: string | undefined) => { const assetUrl = (path: string | undefined) => {
if (!path) return ''; if (!path) return '';
return assetOverrides[path] ?? themeAssetUrl(assets, path); return assetOverrides[path] ?? themeAssetUrl(assets, path);
@@ -43,17 +56,19 @@
return Array.from({ length: count }, (_, index) => { return Array.from({ length: count }, (_, index) => {
const value = (offset: number) => random(index + 1 + offset); const value = (offset: number) => random(index + 1 + offset);
const isStar = effects.type === 'stars'; const isStar = effects.type === 'stars';
const size = isStar ? 1 + value(1) * 2.5 : 4 + value(1) * 7; const isEmber = effects.type === 'embers';
const duration = (isStar ? 2 + value(2) * 3 : 9 + value(2) * 11) / speed; const size = isStar ? 1 + value(1) * 2.5 : isEmber ? 2.5 + value(1) * 4.5 : 4 + value(1) * 7;
const duration =
(isStar ? 2 + value(2) * 3 : isEmber ? 5 + value(2) * 6 : 9 + value(2) * 11) / speed;
return { return {
id: index, id: index,
left: value(3) * 100, left: value(3) * 100,
top: isStar ? value(4) * 100 : value(4) * 15, top: isStar ? value(4) * 100 : isEmber ? 88 + value(4) * 16 : value(4) * 15,
size, size,
duration, duration,
delay: value(5) * duration, delay: value(5) * duration,
drift: -90 + value(6) * 180, drift: isEmber ? -50 + value(6) * 100 : -90 + value(6) * 180,
opacity: 0.25 + value(7) * 0.65, opacity: isEmber ? 0.35 + value(7) * 0.65 : 0.25 + value(7) * 0.65,
rotate: value(8) * 360, rotate: value(8) * 360,
}; };
}); });
@@ -78,58 +93,74 @@
$effect(() => { $effect(() => {
if (!audioElement || !definition.audio) return; if (!audioElement || !definition.audio) return;
audioElement.volume = $custom_theme_volume; audioElement.volume = $custom_theme_volume;
if (!preview) { if (!preview && audioElement.paused) {
audioElement.play().catch(() => { playThemeMedia(audioElement);
// Autoplay can be rejected until the window has been interacted with.
});
} }
}); });
</script> </script>
<div class="theme-v2 absolute inset-0 overflow-hidden" use:trackMedia> <div class="theme-v2 absolute inset-0 overflow-hidden" use:trackMedia>
{#if background.type === 'color'} <div
<div class="absolute inset-0"
class="absolute inset-0" use:themeParallax={{
style="background-color:{background.color};opacity:{background.opacity ?? 1}" enabled: definition.parallax?.enabled === true,
></div> intensity: definition.parallax?.intensity ?? 0.25,
{:else if background.type === 'gradient'} }}
<div style="transform:translate3d(calc(var(--mouse-px, 0) * -18px), calc(var(--mouse-py, 0) * -18px), 0);"
class="absolute inset-0" >
style="background-image:linear-gradient({background.angle ?? {#if background.type === 'color'}
135}deg, {background.from}, {background.to});opacity:{background.opacity ?? 1}" <div
></div> class="absolute inset-0"
{:else if background.type === 'image'} style="background-color:{background.color};opacity:{background.opacity ?? 1}"
{#if background.src} ></div>
<img {:else if background.type === 'gradient'}
class="absolute inset-0 h-full w-full" <div
src={assetUrl(background.src)} class="absolute inset-0"
alt="" style="background-image:linear-gradient({background.angle ??
aria-hidden="true" 135}deg, {background.from}, {background.to});opacity:{background.opacity ??
style="object-fit:{background.fit ?? 'cover'};opacity:{background.opacity ?? 1};transform:{definition.parallax?.enabled ? 'scale(1.06)' : 'none'}"
1};filter:{background.blur ></div>
? `blur(${background.blur}px)` {:else if background.type === 'image'}
: 'none'};transform:{background.blur ? 'scale(1.05)' : 'none'};" {#if background.src}
/> <img
class="absolute inset-0 h-full w-full"
src={assetUrl(background.src)}
alt=""
aria-hidden="true"
style="object-fit:{background.fit ?? 'cover'};opacity:{background.opacity ??
1};filter:{background.blur
? `blur(${background.blur}px)`
: 'none'};transform:{background.blur
? 'scale(1.08)'
: definition.parallax?.enabled
? 'scale(1.06)'
: 'none'};"
/>
{/if}
{:else if background.type === 'video'}
{#if background.src}
<video
class="absolute inset-0 h-full w-full object-cover"
use:themeMediaSource={assetUrl(background.src)}
use:themeVideoLifecycle
autoplay
loop
muted={background.muted !== false}
use:applyMuted={background.muted !== false}
playsinline
disablepictureinpicture
style="object-fit:{background.fit ?? 'cover'};opacity:{background.opacity ??
1};filter:{background.blur
? `blur(${background.blur}px)`
: 'none'};transform:{background.blur
? 'scale(1.08)'
: definition.parallax?.enabled
? 'scale(1.06)'
: 'none'};"
></video>
{/if}
{/if} {/if}
{:else if background.type === 'video'} </div>
{#if background.src}
<video
class="absolute inset-0 h-full w-full object-cover"
use:themeMediaSource={assetUrl(background.src)}
use:themeVideoLifecycle
autoplay
loop
muted={background.muted !== false}
use:applyMuted={background.muted !== false}
playsinline
disablepictureinpicture
style="object-fit:{background.fit ?? 'cover'};opacity:{background.opacity ??
1};filter:{background.blur
? `blur(${background.blur}px)`
: 'none'};transform:{background.blur ? 'scale(1.05)' : 'none'};"
></video>
{/if}
{/if}
{#if overlay && (overlay.opacity ?? 0) > 0} {#if overlay && (overlay.opacity ?? 0) > 0}
<div <div
@@ -163,6 +194,8 @@
use:themeMediaSource={assetUrl(definition.audio.src)} use:themeMediaSource={assetUrl(definition.audio.src)}
loop={definition.audio.loop !== false} loop={definition.audio.loop !== false}
autoplay autoplay
preload="auto"
playsinline
></audio> ></audio>
{/if} {/if}
</div> </div>
@@ -204,6 +237,33 @@
animation-name: v2-stars; animation-name: v2-stars;
animation-timing-function: ease-in-out; animation-timing-function: ease-in-out;
} }
&.embers {
border-radius: 9999px;
box-shadow:
0 0 6px var(--particle-color),
0 0 12px var(--particle-color);
animation-name: v2-embers;
animation-timing-function: ease-out;
}
}
@keyframes v2-embers {
0% {
transform: translate3d(0, 0, 0) scale(0.6);
opacity: 0.1;
}
20% {
opacity: 0.95;
}
80% {
opacity: 0.8;
transform: translate3d(calc(var(--particle-drift) * 0.65), -85vh, 0) scale(1.1);
}
100% {
transform: translate3d(var(--particle-drift), -115vh, 0) scale(0.3);
opacity: 0;
}
} }
@keyframes v2-snow { @keyframes v2-snow {
+761 -15
View File
@@ -2,9 +2,13 @@
import ThemeCustomLayer from '$lib/components/theme/ThemeCustomLayer.svelte'; import ThemeCustomLayer from '$lib/components/theme/ThemeCustomLayer.svelte';
import ThemeIcon from '$lib/components/theme/ThemeIcon.svelte'; import ThemeIcon from '$lib/components/theme/ThemeIcon.svelte';
import ThemeLottieLayer from '$lib/components/theme/ThemeLottieLayer.svelte'; import ThemeLottieLayer from '$lib/components/theme/ThemeLottieLayer.svelte';
import { getThemeDataSampleValue, resolveThemeDataValue, themeGlobalData } from '$lib/themeData'; import * as Avatar from '$lib/components/ui/avatar';
import { fontStack } from '$lib/themeFonts'; import DownloadButton from '$lib/components/ui/download-button/DownloadButton.svelte';
import { DEFAULT_THEME_ICON_SET, type ThemeIconSet } from '$lib/themeIcons'; import { currentUserInfo } from '$lib/data';
import { launching as launchingStore } from '$lib/global';
import { getThemeDataSampleValue, resolveThemeDataValue, themeGlobalData } from '$lib/theme/themeData';
import { fontStack } from '$lib/theme/themeFonts';
import { DEFAULT_THEME_ICON_SET, type ThemeIconSet } from '$lib/theme/themeIcons';
import { import {
themeArcGeometry, themeArcGeometry,
themeClockDate, themeClockDate,
@@ -12,9 +16,9 @@
themeCountdownText, themeCountdownText,
themeParticleSeeds, themeParticleSeeds,
themeSvgGradientVector, themeSvgGradientVector,
} from '$lib/themeLayers'; } from '$lib/theme/themeLayers';
import { themeMediaSource, themeVideoLifecycle } from '$lib/themeMedia'; import { themeMediaSource, themeVideoLifecycle } from '$lib/theme/themeMedia';
import { interpolateThemeText } from '$lib/themeTextVariables'; import { interpolateThemeText } from '$lib/theme/themeTextVariables';
import { import {
themeAssetUrl, themeAssetUrl,
themeClassNames, themeClassNames,
@@ -38,8 +42,10 @@
type ThemeV2Group, type ThemeV2Group,
type ThemeV2Point, type ThemeV2Point,
type ThemeV2ScriptValue, type ThemeV2ScriptValue,
} from '$lib/themeV2'; } from '$lib/theme/themeV2';
import { Boxes, ChevronRight, Move, RotateCw } from '@lucide/svelte'; import { currentUser } from '$lib/userAuthentication';
import { countryCodeToEmoji, formatRelativeTime, openURL } from '$lib/utils';
import { Boxes, ChevronRight, Clock, Move, RotateCw, Trophy } from '@lucide/svelte';
import { onDestroy } from 'svelte'; import { onDestroy } from 'svelte';
import { SvelteSet } from 'svelte/reactivity'; import { SvelteSet } from 'svelte/reactivity';
import { TextMorph } from 'torph/svelte'; import { TextMorph } from 'torph/svelte';
@@ -62,6 +68,11 @@
visibility = {}, visibility = {},
groupVisibility = {}, groupVisibility = {},
variables = {}, variables = {},
launching = undefined,
launchProgress = -1,
launchText = 'Launch',
launchSubtext = undefined,
launchDisabled = false,
oninteraction, oninteraction,
onselect, onselect,
onselectmany, onselectmany,
@@ -91,6 +102,11 @@
groupVisibility?: Record<string, boolean>; groupVisibility?: Record<string, boolean>;
/** Rule variables available to `{name}` placeholders in text layers. */ /** Rule variables available to `{name}` placeholders in text layers. */
variables?: Record<string, ThemeV2ScriptValue>; variables?: Record<string, ThemeV2ScriptValue>;
launching?: boolean;
launchProgress?: number;
launchText?: string;
launchSubtext?: string;
launchDisabled?: boolean;
oninteraction?: (id: string, type: 'click' | 'hover' | 'leave') => void; oninteraction?: (id: string, type: 'click' | 'hover' | 'leave') => void;
onselect?: (id: string | undefined, additive?: boolean) => void; onselect?: (id: string | undefined, additive?: boolean) => void;
onselectmany?: (ids: string[], additive?: boolean) => void; onselectmany?: (ids: string[], additive?: boolean) => void;
@@ -103,6 +119,8 @@
onbuttonaction?: (action: ThemeV2ButtonAction) => void; onbuttonaction?: (action: ThemeV2ButtonAction) => void;
} = $props(); } = $props();
const isLaunching = $derived(launching !== undefined ? launching : $launchingStore);
const assetUrl = (path: string) => assetOverrides[path] ?? themeAssetUrl(assets, path); const assetUrl = (path: string) => assetOverrides[path] ?? themeAssetUrl(assets, path);
const ancestorsOf = (element: ThemeV2Element) => themeGroupAncestors(groups, element); const ancestorsOf = (element: ThemeV2Element) => themeGroupAncestors(groups, element);
@@ -123,6 +141,15 @@
); );
const elementFilter = (element: ThemeV2Element) => const elementFilter = (element: ThemeV2Element) =>
themeFilterCss(element.filters, ...ancestorsOf(element).map((group) => group.filters)); themeFilterCss(element.filters, ...ancestorsOf(element).map((group) => group.filters));
/** Layer depth plus every ancestor group's depth; negative follows the background. */
const elementParallaxCss = (element: ThemeV2Element) => {
const depth =
(element.parallax ?? 0) +
ancestorsOf(element).reduce((total, group) => total + (group.parallax ?? 0), 0);
if (depth === 0) return '';
const offset = depth * 30;
return ` translate3d(calc(var(--mouse-px, 0) * ${offset}px), calc(var(--mouse-py, 0) * ${offset}px), 0)`;
};
const elementClassNames = (element: ThemeV2Element) => const elementClassNames = (element: ThemeV2Element) =>
themeClassNames( themeClassNames(
[...ancestorsOf(element).map((group) => group.cssClasses), element.cssClasses] [...ancestorsOf(element).map((group) => group.cssClasses), element.cssClasses]
@@ -138,10 +165,18 @@
(element) => (element) =>
(element.type === 'data' && element.field.startsWith('clock.')) || (element.type === 'data' && element.field.startsWith('clock.')) ||
element.type === 'clock' || element.type === 'clock' ||
element.type === 'countdown' element.type === 'countdown' ||
(element.type === 'widget' && element.widget === 'header')
) )
); );
const timeGreeting = $derived.by(() => {
const hour = clockNow.getHours();
if (hour < 12) return 'Good morning';
if (hour < 18) return 'Good afternoon';
return 'Good evening';
});
$effect(() => { $effect(() => {
if (!usesClock) return; if (!usesClock) return;
const timer = window.setInterval(() => (clockNow = new Date()), 1000); const timer = window.setInterval(() => (clockNow = new Date()), 1000);
@@ -1201,7 +1236,7 @@
element, element,
elements, elements,
groups groups
)};transform-origin:0 0;touch-action:none;outline:{selected )}{elementParallaxCss(element)};transform-origin:0 0;touch-action:none;outline:{selected
? `${selectedIds.length > 1 ? 1 : 2}px solid #ff006e` ? `${selectedIds.length > 1 ? 1 : 2}px solid #ff006e`
: 'none'};outline-offset:2px;" : 'none'};outline-offset:2px;"
role={interactive || element.interactive ? 'button' : undefined} role={interactive || element.interactive ? 'button' : undefined}
@@ -1560,9 +1595,13 @@
/> />
{/key} {/key}
{:else if element.type === 'button'} {:else if element.type === 'button'}
{@const isActionLaunch = element.action?.type === 'launch'}
<button <button
type="button" type="button"
class="theme-button flex h-full w-full items-center justify-center gap-2 px-4" class="theme-button flex h-full w-full items-center justify-center gap-2 px-4 {isActionLaunch &&
isLaunching
? 'cursor-wait brightness-90'
: ''}"
style="--theme-button-hover:{element.hoverBackground ?? style="--theme-button-hover:{element.hoverBackground ??
'#ff4d94'};background:{element.background ?? '#ff006e'};color:{element.color ?? '#ff4d94'};background:{element.background ?? '#ff006e'};color:{element.color ??
'#ffffff'};border:{element.borderWidth '#ffffff'};border:{element.borderWidth
@@ -1570,16 +1609,42 @@
: 'none'};border-radius:{element.radius ?? 10}px;font-family:{fontStack( : 'none'};border-radius:{element.radius ?? 10}px;font-family:{fontStack(
element.fontFamily element.fontFamily
)};font-size:{element.fontSize ?? 16}px;font-weight:{element.fontWeight ?? 600};" )};font-size:{element.fontSize ?? 16}px;font-weight:{element.fontWeight ?? 600};"
disabled={isActionLaunch && (launchDisabled || isLaunching)}
onclick={(event) => { onclick={(event) => {
if (interactive) return; if (interactive) {
if (event.shiftKey || event.ctrlKey || event.metaKey) {
event.stopPropagation();
onbuttonaction?.(element.action);
}
return;
}
if (isActionLaunch && (launchDisabled || isLaunching)) return;
event.stopPropagation(); event.stopPropagation();
triggerInteraction(element, 'click');
onbuttonaction?.(element.action); onbuttonaction?.(element.action);
}} }}
> >
{#if element.icon} {#if isActionLaunch && isLaunching}
{#if launchProgress >= 0}
<span class="text-[11px] font-bold">{Math.round(launchProgress)}%</span>
{:else}
<ThemeIcon name="loader" set={iconSet} size="1.1em" class="animate-spin" />
{/if}
{:else if element.icon}
<ThemeIcon name={element.icon} set={iconSet} size="1.1em" /> <ThemeIcon name={element.icon} set={iconSet} size="1.1em" />
{/if} {/if}
{#if isMorphEnabled(element)} {#if isActionLaunch && isLaunching}
<div class="flex flex-col items-center justify-center min-w-0">
<span class="truncate">
{launchProgress >= 0
? `${launchText} (${Math.round(launchProgress)}%)`
: launchText}
</span>
{#if launchSubtext}
<span class="text-[10px] opacity-75 truncate max-w-[140px]">{launchSubtext}</span>
{/if}
</div>
{:else if isMorphEnabled(element)}
<TextMorph <TextMorph
text={String(interpolateThemeText(element.label, variables) ?? '')} text={String(interpolateThemeText(element.label, variables) ?? '')}
duration={morphDuration(element)} duration={morphDuration(element)}
@@ -1800,6 +1865,673 @@
</span> </span>
{/if} {/if}
</div> </div>
{:else if element.type === 'widget'}
<div class="pointer-events-auto h-full w-full select-none overflow-visible">
{#if element.widget === 'launch-button'}
{#if element.variant === 'icon-only' || element.variant === 'minimal'}
{@const btnRadius = Math.max(
12,
Math.round(Math.min(element.width, element.height) / 2) - 6
)}
{@const btnCircumference = 2 * Math.PI * btnRadius}
{@const strokeOffset =
launchProgress < 0
? btnCircumference * 0.7
: btnCircumference -
(Math.max(0, Math.min(100, launchProgress)) / 100) * btnCircumference}
<button
type="button"
class="relative flex h-full w-full items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg shadow-primary/30 transition-all {isLaunching
? 'cursor-wait brightness-95'
: launchDisabled
? 'cursor-not-allowed opacity-60'
: 'cursor-pointer hover:scale-105 hover:brightness-110 active:scale-95'}"
disabled={launchDisabled || isLaunching}
onclick={(e) => {
e.stopPropagation();
if (!launchDisabled && !isLaunching) {
onbuttonaction?.({ type: 'launch' });
}
}}
title={isLaunching
? launchSubtext
? `${launchText} - ${launchSubtext}`
: launchText
: 'Launch osu!'}
>
{#if isLaunching}
<!-- Rotating progress ring SVG -->
<svg
class="absolute inset-0 h-full w-full {launchProgress < 0
? 'animate-spin'
: '-rotate-90'}"
viewBox="0 0 {element.width} {element.height}"
>
<circle
cx={element.width / 2}
cy={element.height / 2}
r={btnRadius}
fill="none"
stroke="rgba(0,0,0,0.25)"
stroke-width="3"
/>
<circle
cx={element.width / 2}
cy={element.height / 2}
r={btnRadius}
fill="none"
stroke="currentColor"
stroke-width="3"
stroke-linecap="round"
stroke-dasharray={btnCircumference}
stroke-dashoffset={strokeOffset}
class="transition-[stroke-dashoffset] duration-150"
/>
</svg>
{#if launchProgress >= 0}
<span
class="relative z-10 text-[11px] font-black tracking-tight text-primary-foreground"
>
{Math.round(launchProgress)}%
</span>
{:else}
<ThemeIcon
name="ellipsis"
set={iconSet}
class="relative z-10 size-4 animate-pulse text-primary-foreground"
/>
{/if}
{:else}
<ThemeIcon name="launch" set={iconSet} class="size-6 fill-current ml-0.5" />
{/if}
</button>
{:else if element.variant === 'compact'}
<button
type="button"
class="relative flex h-full w-full items-center justify-center gap-2 rounded-full bg-primary px-3 text-xs font-bold text-primary-foreground shadow-md shadow-primary/25 transition-all {isLaunching
? 'cursor-wait brightness-95'
: launchDisabled
? 'cursor-not-allowed opacity-60'
: 'cursor-pointer hover:brightness-110 active:scale-[0.98]'}"
disabled={launchDisabled || isLaunching}
onclick={(e) => {
e.stopPropagation();
if (!launchDisabled && !isLaunching) {
onbuttonaction?.({ type: 'launch' });
}
}}
title={isLaunching
? launchSubtext
? `${launchText} - ${launchSubtext}`
: launchText
: 'Launch osu!'}
>
{#if isLaunching}
{#if launchProgress >= 0}
<span class="text-[11px] font-black">{Math.round(launchProgress)}%</span>
{:else}
<ThemeIcon
name="loader"
set={iconSet}
class="size-3.5 animate-spin fill-current"
/>
{/if}
<div class="flex flex-col items-center justify-center min-w-0">
<span class="truncate">{launchText}</span>
{#if launchSubtext}
<span class="text-[9px] opacity-75 truncate max-w-[140px]"
>{launchSubtext}</span
>
{/if}
</div>
{:else}
<ThemeIcon name="launch" set={iconSet} class="size-3.5 fill-current" />
<span>Launch</span>
{/if}
</button>
{:else}
<div class="flex h-full w-full items-center justify-center">
<DownloadButton
downloading={isLaunching}
progress={launchProgress}
text={isLaunching ? launchText : 'Launch'}
subtext={launchSubtext}
disabled={launchDisabled}
{iconSet}
class="h-full w-full justify-center"
onClick={() => {
if (interactive) return;
if (!launchDisabled && !isLaunching) {
onbuttonaction?.({ type: 'launch' });
}
}}
/>
</div>
{/if}
{:else if element.widget === 'player-card'}
{@const playerStats =
$currentUserInfo?.stats?.['0'] ?? $themeGlobalData?.user?.stats?.osu}
{@const accuracyVal =
playerStats && 'acc' in playerStats
? playerStats.acc
: playerStats && 'accuracy' in playerStats
? playerStats.accuracy
: 98.3}
{@const playerId = $currentUser?.id ?? $currentUserInfo?.info?.id ?? 0}
{@const playerName = $currentUser?.name ?? 'Player'}
{@const country = $currentUserInfo?.info?.country}
{@const levelVal = playerStats && 'level' in playerStats ? playerStats.level : 1}
{@const levelProgress =
playerStats && 'level_progress' in playerStats ? playerStats.level_progress : 75}
{@const rankVal = playerStats?.rank ? playerStats.rank : 102}
{@const countryRankVal =
playerStats && 'country_rank' in playerStats ? playerStats.country_rank : undefined}
{@const ppVal = playerStats?.pp ? playerStats.pp : 4521}
{@const playsVal = playerStats?.plays
? Number(playerStats.plays).toLocaleString()
: '11,813'}
{#if element.variant === 'minimal'}
<div
class="flex h-full w-full items-center gap-2.5 overflow-hidden rounded-2xl border border-white/10 bg-black/55 px-3 py-2 text-theme-50 shadow-xl backdrop-blur-md"
>
<div class="relative shrink-0">
<Avatar.Root
class="size-10 rounded-xl border border-white/15 bg-theme-900 shadow"
>
<Avatar.Image
src="https://a.ez-pp.farm/{playerId}"
alt={playerName}
class="h-full w-full object-cover"
/>
<Avatar.Fallback
class="flex h-full w-full items-center justify-center bg-theme-900 text-primary"
>
<ThemeIcon name="user" set={iconSet} size={18} />
</Avatar.Fallback>
</Avatar.Root>
{#if country}
<span
class="absolute -bottom-1 -right-1 flex items-center justify-center rounded-md border border-white/20 bg-black/90 px-1 py-0.5 text-[9px] leading-none shadow"
title={country.toUpperCase()}
>
{countryCodeToEmoji(country)}
</span>
{/if}
</div>
<div class="min-w-0 flex-1">
<span class="block truncate text-xs font-bold text-white">{playerName}</span>
<span class="block text-[10px] font-medium text-muted-foreground">
#{rankVal} · {ppVal}pp
</span>
</div>
<span
class="shrink-0 rounded-md bg-primary/20 px-1.5 py-0.5 text-[9px] font-bold text-primary"
>
Lv.{levelVal}
</span>
</div>
{:else if element.variant === 'compact'}
<div
class="flex h-full w-full flex-col justify-between overflow-hidden rounded-2xl border border-white/10 bg-black/55 p-3 text-theme-50 shadow-xl backdrop-blur-md"
>
<div class="flex items-center gap-3">
<div class="relative shrink-0">
<Avatar.Root
class="size-11 rounded-xl border border-white/15 bg-theme-900 shadow"
>
<Avatar.Image
src="https://a.ez-pp.farm/{playerId}"
alt={playerName}
class="h-full w-full object-cover"
/>
<Avatar.Fallback
class="flex h-full w-full items-center justify-center bg-theme-900 text-primary"
>
<ThemeIcon name="user" set={iconSet} size={20} />
</Avatar.Fallback>
</Avatar.Root>
{#if country}
<span
class="absolute -bottom-1 -right-1 flex items-center justify-center rounded-md border border-white/20 bg-black/90 px-1 py-0.5 text-[9px] leading-none shadow"
title={country.toUpperCase()}
>
{countryCodeToEmoji(country)}
</span>
{/if}
</div>
<div class="min-w-0 flex-1">
<div class="flex items-center gap-1.5">
<span class="block truncate text-sm font-bold text-white">{playerName}</span
>
<span
class="rounded bg-primary/20 px-1.5 py-0.5 text-[9px] font-bold text-primary"
>
Lv.{levelVal}
</span>
</div>
<span class="block text-[10px] font-medium text-muted-foreground">
#{rankVal} · {ppVal}pp
</span>
</div>
</div>
<div class="grid grid-cols-2 gap-2 border-t border-white/5 pt-2 text-xs">
<div
class="flex items-center justify-between rounded-lg bg-white/5 px-2.5 py-1"
>
<span class="text-[9px] font-medium text-muted-foreground">Accuracy</span>
<span class="text-[11px] font-bold text-white">{accuracyVal.toFixed(1)}%</span
>
</div>
<div
class="flex items-center justify-between rounded-lg bg-white/5 px-2.5 py-1"
>
<span class="text-[9px] font-medium text-muted-foreground">Plays</span>
<span class="text-[11px] font-bold text-white">{playsVal}</span>
</div>
</div>
</div>
{:else if element.variant === 'banner' || element.showStats === false || element.height < 140}
<div
class="flex h-full w-full items-center gap-3 overflow-hidden rounded-2xl border border-white/10 bg-black/55 p-3.5 text-theme-50 shadow-xl backdrop-blur-md"
>
<div class="relative shrink-0">
<Avatar.Root
class="size-12 rounded-xl border border-white/15 bg-theme-900 shadow-md"
>
<Avatar.Image
src="https://a.ez-pp.farm/{playerId}"
alt={playerName}
class="h-full w-full object-cover"
/>
<Avatar.Fallback
class="flex h-full w-full items-center justify-center bg-theme-900 text-primary"
>
<ThemeIcon name="user" set={iconSet} size={22} />
</Avatar.Fallback>
</Avatar.Root>
{#if country}
<span
class="absolute -bottom-1 -right-1 flex items-center justify-center rounded-md border border-white/20 bg-black/90 px-1 py-0.5 text-[10px] leading-none shadow"
title={country.toUpperCase()}
>
{countryCodeToEmoji(country)}
</span>
{/if}
</div>
<div class="min-w-0 flex flex-col justify-center flex-1">
<span class="block truncate text-sm font-bold text-white">{playerName}</span>
<div class="flex items-center gap-2 mt-1">
<span class="text-[11px] font-semibold text-white/80 shrink-0">
Lv.{levelVal}
</span>
<div class="w-20 rounded-full bg-white/10 h-1.5 overflow-hidden">
<div
class="h-full bg-primary rounded-full transition-all"
style="width: {levelProgress}%"
></div>
</div>
<span class="text-[10px] text-muted-foreground font-mono">
{levelProgress}%
</span>
</div>
</div>
</div>
{:else}
<div
class="flex h-full w-full flex-col justify-between overflow-hidden rounded-2xl border border-white/10 bg-black/55 p-3.5 text-theme-50 shadow-xl backdrop-blur-md"
>
<div class="flex items-center justify-between gap-3">
<div class="flex items-center gap-3 min-w-0">
<div class="relative shrink-0">
<Avatar.Root
class="size-12 rounded-xl border border-white/15 bg-theme-900 shadow-md"
>
<Avatar.Image
src="https://a.ez-pp.farm/{playerId}"
alt={playerName}
class="h-full w-full object-cover"
/>
<Avatar.Fallback
class="flex h-full w-full items-center justify-center bg-theme-900 text-primary"
>
<ThemeIcon name="user" set={iconSet} size={22} />
</Avatar.Fallback>
</Avatar.Root>
{#if country}
<span
class="absolute -bottom-1 -right-1 flex items-center justify-center rounded-md border border-white/20 bg-black/90 px-1 py-0.5 text-[10px] leading-none shadow"
title={country.toUpperCase()}
>
{countryCodeToEmoji(country)}
</span>
{/if}
</div>
<div class="min-w-0 flex flex-col">
<span class="block truncate text-sm font-bold text-white">{playerName}</span
>
<div class="flex items-center gap-2 mt-1">
<span class="text-[11px] font-semibold text-white/80 shrink-0">
Lv.{levelVal}
</span>
<div class="w-20 rounded-full bg-white/10 h-1.5 overflow-hidden">
<div
class="h-full bg-primary rounded-full transition-all"
style="width: {levelProgress}%"
></div>
</div>
<span class="text-[10px] text-muted-foreground font-mono">
{levelProgress}%
</span>
</div>
</div>
</div>
</div>
<div class="grid grid-cols-2 gap-2 border-t border-white/5 pt-2 mt-2">
<div class="rounded-xl bg-white/5 p-2 flex flex-col justify-center">
<div class="flex items-center justify-between">
<span class="text-[9px] font-medium text-muted-foreground">Rank</span>
{#if countryRankVal}
<span class="text-[9px] font-bold text-primary">#{countryRankVal}</span>
{/if}
</div>
<span class="text-xs font-bold text-white mt-0.5">#{rankVal}</span>
</div>
<div class="rounded-xl bg-white/5 p-2 flex flex-col justify-center">
<span class="text-[9px] font-medium text-muted-foreground">Performance</span>
<span class="text-xs font-bold text-primary mt-0.5">{ppVal}pp</span>
</div>
<div class="rounded-xl bg-white/5 p-2 flex flex-col justify-center">
<span class="text-[9px] font-medium text-muted-foreground">Accuracy</span>
<span class="text-xs font-bold text-white mt-0.5"
>{accuracyVal.toFixed(1)}%</span
>
</div>
<div class="rounded-xl bg-white/5 p-2 flex flex-col justify-center">
<span class="text-[9px] font-medium text-muted-foreground">Plays</span>
<span class="text-xs font-bold text-white mt-0.5">{playsVal}</span>
</div>
</div>
</div>
{/if}
{:else if element.widget === 'recent-activity'}
{@const event = $currentUserInfo?.events?.[0]}
{#if element.variant === 'minimal'}
<div
class="flex h-full w-full items-center gap-2.5 overflow-hidden rounded-2xl border border-white/10 bg-black/55 px-3 py-2 text-theme-50 shadow-xl backdrop-blur-md"
>
{#if event?.setId}
<img
src="https://assets.ppy.sh/beatmaps/{event.setId}/covers/cover.jpg"
alt={event.title}
class="size-10 shrink-0 rounded-lg object-cover"
/>
{:else}
<div
class="flex size-10 shrink-0 items-center justify-center rounded-lg bg-theme-900 text-primary"
>
<Trophy class="size-4" />
</div>
{/if}
<div class="min-w-0 flex-1">
<span class="block truncate text-xs font-bold text-white"
>{event?.title ?? 'Space Pirates'}</span
>
<span class="block truncate text-[10px] text-muted-foreground">
{event?.artist ?? 'Waterflame'} · {event
? formatRelativeTime(event.time)
: '5d ago'}
</span>
</div>
<span
class="shrink-0 rounded border border-amber-300/40 bg-amber-400/20 px-1.5 py-0.5 text-[10px] font-black text-amber-300"
>
{event?.grade ?? 'S'}
</span>
</div>
{:else if element.variant === 'compact'}
<div
class="relative flex h-full w-full flex-col justify-between overflow-hidden rounded-2xl border border-white/10 bg-black/55 text-theme-50 shadow-xl backdrop-blur-md"
>
<div class="relative h-14 w-full shrink-0 overflow-hidden bg-theme-900/80">
{#if event?.setId}
<img
src="https://assets.ppy.sh/beatmaps/{event.setId}/covers/cover.jpg"
alt={event.title}
class="h-full w-full object-cover"
/>
{/if}
<div
class="absolute inset-0 bg-gradient-to-t from-black via-black/50 to-transparent"
></div>
<div class="absolute top-1.5 left-2 right-2 flex items-center justify-between">
<span class="text-[9px] font-bold uppercase tracking-wider text-white/90"
>Recent Activity</span
>
<span
class="rounded border border-amber-300/40 bg-amber-400/20 px-1 py-0.2 text-[9px] font-black text-amber-300"
>
{event?.grade ?? 'S'}
</span>
</div>
<div
class="absolute bottom-1 left-2 right-2 truncate text-xs font-bold text-white"
>
{event?.title ?? 'Space Pirates'}
</div>
</div>
<div class="flex items-center justify-between px-2.5 py-1.5 text-[10px]">
<span class="max-w-[180px] truncate font-semibold text-primary"
>[{event?.version ?? 'Galactic Thieves'}]</span
>
<span class="font-bold text-amber-300">Rank #{event?.rank ?? 1}</span>
</div>
</div>
{:else}
<div
class="relative flex h-full w-full flex-col justify-between overflow-hidden rounded-2xl border border-white/10 bg-black/55 text-theme-50 shadow-xl backdrop-blur-md"
>
<!-- Cover Banner -->
<div class="relative h-20 w-full shrink-0 overflow-hidden bg-theme-900/80">
{#if event?.setId}
<img
src="https://assets.ppy.sh/beatmaps/{event.setId}/covers/cover.jpg"
alt={event.title}
class="h-full w-full object-cover"
/>
{/if}
<div
class="absolute inset-0 bg-gradient-to-t from-black via-black/50 to-transparent"
></div>
<div
class="absolute top-2 left-2.5 right-2.5 flex items-center justify-between"
>
<span
class="rounded-full border border-white/10 bg-black/60 px-2 py-0.5 text-[9px] font-bold uppercase tracking-wider text-white/90"
>
Recent Activity
</span>
<span
class="rounded border border-amber-300/40 bg-amber-400/20 px-1.5 py-0.5 text-[10px] font-black text-amber-300"
>
{event?.grade ?? 'S'}
</span>
</div>
<div class="absolute bottom-1.5 left-2.5 right-2.5 flex min-w-0 flex-col">
<span class="truncate text-xs font-bold text-white"
>{event?.title ?? 'Space Pirates'}</span
>
<span class="truncate text-[10px] text-white/70"
>{event?.artist ?? 'Waterflame'}</span
>
</div>
</div>
<!-- Metrics Body -->
<div class="flex flex-1 flex-col justify-center gap-2 p-2.5">
<div class="flex items-center justify-between gap-1 text-[11px]">
<span class="max-w-[180px] truncate font-semibold text-primary">
[{event?.version ?? 'Galactic Thieves'}]
</span>
<div
class="flex items-center gap-1 rounded-md border border-amber-400/20 bg-amber-400/10 px-2 py-0.5 text-[10px] font-bold text-amber-300"
>
<Trophy class="size-3" />
<span>Rank #{event?.rank ?? 1}</span>
</div>
</div>
<div
class="flex items-center justify-between border-t border-white/5 pt-1.5 text-[10px] text-muted-foreground"
>
<span class="flex items-center gap-1 font-mono">
<Clock class="size-2.5" />
{event ? formatRelativeTime(event.time) : '5d ago'}
</span>
<span class="text-white/60">ez-pp.farm</span>
</div>
</div>
</div>
{/if}
{:else if element.widget === 'telemetry'}
<div
class="flex h-full w-full items-center gap-2 rounded-full border border-white/10 bg-black/40 px-3 text-xs text-white/80 backdrop-blur-md"
>
<div class="flex items-center gap-1">
<ThemeIcon name="wifi" set={iconSet} class="size-3 text-emerald-400" />
<span class="text-[10px]">{$themeGlobalData?.server?.ping ?? 19}ms</span>
</div>
<span
class="rounded-full border border-white/5 bg-white/10 px-2 py-0.5 text-[9px] text-white/50"
>
{$themeGlobalData?.osu?.stream ?? 'stable'}
</span>
</div>
{:else if element.widget === 'header'}
{#if element.variant === 'minimal'}
<div class="flex h-full items-center">
<span
class="theme-heading text-2xl font-extrabold tracking-tight drop-shadow-md text-theme-50"
>
EZPPLauncher
</span>
</div>
{:else if element.variant === 'compact'}
<div class="flex h-full items-center gap-3">
<span
class="theme-heading text-2xl font-extrabold tracking-tight drop-shadow-md text-theme-50"
>
EZPPLauncher
</span>
<span
class="rounded-full border border-white/10 bg-black/40 px-2.5 py-0.5 text-xs font-medium text-white/80 shadow-sm backdrop-blur-md"
>
{timeGreeting},
<span class="font-semibold text-white">{$currentUser?.name ?? 'Guest'}</span>!
</span>
</div>
{:else}
<div class="flex h-full flex-col justify-center">
<span
class="theme-heading text-3xl font-extrabold tracking-tight drop-shadow-md text-theme-50"
>
EZPPLauncher
</span>
<span class="text-xs font-medium text-white/70 drop-shadow mt-0.5">
{timeGreeting},
<span class="font-semibold text-white">{$currentUser?.name ?? 'Guest'}</span>!
</span>
</div>
{/if}
{:else if element.widget === 'avatar'}
{@const shapeClass =
element.variant === 'rounded'
? 'rounded-2xl'
: element.variant === 'square'
? 'rounded-md'
: 'rounded-full'}
{@const playerId = $currentUser?.id ?? $currentUserInfo?.info?.id ?? 0}
{@const playerName = $currentUser?.name ?? 'Player'}
{@const country = $currentUserInfo?.info?.country}
{@const level = $currentUserInfo?.stats?.['0']?.level}
<div
class="group/avatar relative flex h-full w-full items-center justify-center {interactive
? ''
: 'cursor-pointer'}"
role="button"
tabindex="0"
onclick={(e) => {
if (!interactive && playerId) {
e.stopPropagation();
void openURL(`https://ez-pp.farm/u/${playerId}`);
}
}}
onkeydown={(e) => {
if (!interactive && playerId && (e.key === 'Enter' || e.key === ' ')) {
e.preventDefault();
e.stopPropagation();
void openURL(`https://ez-pp.farm/u/${playerId}`);
}
}}
title={playerName}
>
<!-- Online Glow Ring -->
{#if element.showOnlineRing !== false}
<div
class="absolute inset-0 {shapeClass} ring-2 ring-primary/40 ring-offset-2 ring-offset-black/50 transition-all duration-300 group-hover/avatar:ring-primary/80"
></div>
{/if}
<!-- Avatar Image / Fallback -->
<Avatar.Root
class="h-full w-full {shapeClass} overflow-hidden border border-white/15 bg-theme-900 shadow-lg transition-transform duration-300 group-hover/avatar:scale-105"
>
<Avatar.Image
src="https://a.ez-pp.farm/{playerId}"
alt={playerName}
class="h-full w-full object-cover"
/>
<Avatar.Fallback
class="flex h-full w-full items-center justify-center bg-theme-900 text-primary"
>
<ThemeIcon
name="user"
set={iconSet}
size={Math.max(
16,
Math.round(Math.min(element.width, element.height) * 0.45)
)}
/>
</Avatar.Fallback>
</Avatar.Root>
<!-- Country Flag Emoji Badge -->
{#if element.showCountry !== false && country}
<span
class="absolute -bottom-1 -right-1 flex items-center justify-center rounded-md border border-white/20 bg-black/90 px-1 py-0.5 text-[10px] leading-none shadow-md backdrop-blur-sm"
title={country.toUpperCase()}
>
{countryCodeToEmoji(country)}
</span>
{/if}
<!-- Level Badge -->
{#if element.showLevel && level !== undefined}
<span
class="absolute -top-1 -left-1 flex items-center justify-center rounded-md border border-primary/40 bg-black/90 px-1 py-0.5 text-[9px] font-bold leading-none text-primary shadow-md"
>
Lv.{level}
</span>
{/if}
</div>
{/if}
</div>
{/if} {/if}
</div> </div>
@@ -1836,7 +2568,21 @@
<span <span
class="absolute -top-7 left-0 rounded bg-primary px-1.5 py-0.5 text-[10px] font-semibold text-primary-foreground shadow" class="absolute -top-7 left-0 rounded bg-primary px-1.5 py-0.5 text-[10px] font-semibold text-primary-foreground shadow"
> >
{element.type} {element.type === 'widget'
? element.widget === 'player-card'
? 'Player Card'
: element.widget === 'recent-activity'
? 'Recent Activity'
: element.widget === 'launch-button'
? 'Launch Button'
: element.widget === 'telemetry'
? 'Telemetry Bar'
: element.widget === 'header'
? 'Header Title'
: element.widget === 'avatar'
? 'Player Avatar'
: 'Widget'
: element.type}
</span> </span>
{/if} {/if}
@@ -2,8 +2,8 @@
import ThemeSection from '$lib/components/theme/ThemeSection.svelte'; import ThemeSection from '$lib/components/theme/ThemeSection.svelte';
import Button from '$lib/components/ui/button/button.svelte'; import Button from '$lib/components/ui/button/button.svelte';
import Input from '$lib/components/ui/input/input.svelte'; import Input from '$lib/components/ui/input/input.svelte';
import type { ThemeV2ScriptValue } from '$lib/themeV2'; import type { ThemeV2ScriptValue } from '$lib/theme/themeV2';
import { RotateCcw } from '@lucide/svelte'; import { Braces, RotateCcw } from '@lucide/svelte';
let { let {
variables, variables,
@@ -38,7 +38,12 @@
}; };
</script> </script>
<ThemeSection title="Variables" badge={variables.length} contentClass="space-y-2 pt-2"> <ThemeSection
title="Variables"
icon={Braces}
badge={variables.length}
contentClass="space-y-2 pt-2"
>
<p class="text-[10px] leading-relaxed text-muted-foreground"> <p class="text-[10px] leading-relaxed text-muted-foreground">
Starting values for Starting values for
<code class="rounded bg-theme-900 px-1 py-0.5 text-theme-100">{'{name}'}</code> <code class="rounded bg-theme-900 px-1 py-0.5 text-theme-100">{'{name}'}</code>
@@ -0,0 +1,29 @@
<script lang="ts">
import * as Tooltip from '$lib/components/ui/tooltip';
import type { Snippet } from 'svelte';
let {
content,
trigger,
side = 'top',
}: {
content: string;
trigger: Snippet<[Record<string, unknown>]>;
side?: 'top' | 'right' | 'bottom' | 'left';
} = $props();
</script>
<Tooltip.Root>
<Tooltip.Trigger>
{#snippet child({ props })}
{@render trigger(props)}
{/snippet}
</Tooltip.Trigger>
<Tooltip.Content
{side}
sideOffset={6}
class="max-w-72 border-theme-700 bg-theme-950 px-2.5 py-1.5 text-[10px] leading-relaxed text-white shadow-xl"
>
{content}
</Tooltip.Content>
</Tooltip.Root>
@@ -48,6 +48,7 @@
opacity:{$reduceAnimations ? 0 : s.opacity}; opacity:{$reduceAnimations ? 0 : s.opacity};
animation-duration:{s.duration}s; animation-duration:{s.duration}s;
animation-delay:-{s.delay}s; animation-delay:-{s.delay}s;
animation-play-state:{$reduceAnimations ? 'paused' : 'running'};
" "
></div> ></div>
{/each} {/each}
@@ -1,76 +1,76 @@
<script lang="ts"> <script lang="ts">
import type { ComponentProps } from "svelte"; import CalendarMonthSelect from './calendar-month-select.svelte';
import type Calendar from "./calendar.svelte"; import CalendarYearSelect from './calendar-year-select.svelte';
import CalendarMonthSelect from "./calendar-month-select.svelte"; import type Calendar from './calendar.svelte';
import CalendarYearSelect from "./calendar-year-select.svelte"; import { DateFormatter, getLocalTimeZone, type DateValue } from '@internationalized/date';
import { DateFormatter, getLocalTimeZone, type DateValue } from "@internationalized/date"; import type { ComponentProps } from 'svelte';
let { let {
captionLayout, captionLayout,
months, months,
monthFormat, monthFormat,
years, years,
yearFormat, yearFormat,
month, month,
locale, locale,
placeholder = $bindable(), placeholder = $bindable(),
monthIndex = 0, monthIndex = 0,
}: { }: {
captionLayout: ComponentProps<typeof Calendar>["captionLayout"]; captionLayout: ComponentProps<typeof Calendar>['captionLayout'];
months: ComponentProps<typeof CalendarMonthSelect>["months"]; months: ComponentProps<typeof CalendarMonthSelect>['months'];
monthFormat: ComponentProps<typeof CalendarMonthSelect>["monthFormat"]; monthFormat: ComponentProps<typeof CalendarMonthSelect>['monthFormat'];
years: ComponentProps<typeof CalendarYearSelect>["years"]; years: ComponentProps<typeof CalendarYearSelect>['years'];
yearFormat: ComponentProps<typeof CalendarYearSelect>["yearFormat"]; yearFormat: ComponentProps<typeof CalendarYearSelect>['yearFormat'];
month: DateValue; month: DateValue;
placeholder: DateValue | undefined; placeholder: DateValue | undefined;
locale: string; locale: string;
monthIndex: number; monthIndex: number;
} = $props(); } = $props();
function formatYear(date: DateValue) { function formatYear(date: DateValue) {
const dateObj = date.toDate(getLocalTimeZone()); const dateObj = date.toDate(getLocalTimeZone());
if (typeof yearFormat === "function") return yearFormat(dateObj.getFullYear()); if (typeof yearFormat === 'function') return yearFormat(dateObj.getFullYear());
return new DateFormatter(locale, { year: yearFormat }).format(dateObj); return new DateFormatter(locale, { year: yearFormat }).format(dateObj);
} }
function formatMonth(date: DateValue) { function formatMonth(date: DateValue) {
const dateObj = date.toDate(getLocalTimeZone()); const dateObj = date.toDate(getLocalTimeZone());
if (typeof monthFormat === "function") return monthFormat(dateObj.getMonth() + 1); if (typeof monthFormat === 'function') return monthFormat(dateObj.getMonth() + 1);
return new DateFormatter(locale, { month: monthFormat }).format(dateObj); return new DateFormatter(locale, { month: monthFormat }).format(dateObj);
} }
</script> </script>
{#snippet MonthSelect()} {#snippet MonthSelect()}
<CalendarMonthSelect <CalendarMonthSelect
{months} {months}
{monthFormat} {monthFormat}
value={month.month} value={month.month}
onchange={(e) => { onchange={(e) => {
if (!placeholder) return; if (!placeholder) return;
const v = Number.parseInt(e.currentTarget.value); const v = Number.parseInt(e.currentTarget.value);
const newPlaceholder = placeholder.set({ month: v }); const newPlaceholder = placeholder.set({ month: v });
placeholder = newPlaceholder.subtract({ months: monthIndex }); placeholder = newPlaceholder.subtract({ months: monthIndex });
}} }}
/> />
{/snippet} {/snippet}
{#snippet YearSelect()} {#snippet YearSelect()}
<CalendarYearSelect {years} {yearFormat} value={month.year} /> <CalendarYearSelect {years} {yearFormat} value={month.year} />
{/snippet} {/snippet}
{#if captionLayout === "dropdown"} {#if captionLayout === 'dropdown'}
{@render MonthSelect()} {@render MonthSelect()}
{@render YearSelect()} {@render YearSelect()}
{:else if captionLayout === "dropdown-months"} {:else if captionLayout === 'dropdown-months'}
{@render MonthSelect()} {@render MonthSelect()}
{#if placeholder} {#if placeholder}
{formatYear(placeholder)} {formatYear(placeholder)}
{/if} {/if}
{:else if captionLayout === "dropdown-years"} {:else if captionLayout === 'dropdown-years'}
{#if placeholder} {#if placeholder}
{formatMonth(placeholder)} {formatMonth(placeholder)}
{/if} {/if}
{@render YearSelect()} {@render YearSelect()}
{:else} {:else}
{formatMonth(month)} {formatYear(month)} {formatMonth(month)} {formatYear(month)}
{/if} {/if}
@@ -1,19 +1,19 @@
<script lang="ts"> <script lang="ts">
import { Calendar as CalendarPrimitive } from "bits-ui"; import { cn } from '$lib/utils.js';
import { cn } from "$lib/utils.js"; import { Calendar as CalendarPrimitive } from 'bits-ui';
let { let {
ref = $bindable(null), ref = $bindable(null),
class: className, class: className,
...restProps ...restProps
}: CalendarPrimitive.CellProps = $props(); }: CalendarPrimitive.CellProps = $props();
</script> </script>
<CalendarPrimitive.Cell <CalendarPrimitive.Cell
bind:ref bind:ref
class={cn( class={cn(
"relative size-(--cell-size) p-0 text-center text-sm focus-within:z-20 [&:first-child[data-selected]_[data-bits-day]]:rounded-s-md [&:last-child[data-selected]_[data-bits-day]]:rounded-e-md", 'relative size-(--cell-size) p-0 text-center text-sm focus-within:z-20 [&:first-child[data-selected]_[data-bits-day]]:rounded-s-md [&:last-child[data-selected]_[data-bits-day]]:rounded-e-md',
className className
)} )}
{...restProps} {...restProps}
/> />
@@ -1,35 +1,35 @@
<script lang="ts"> <script lang="ts">
import { buttonVariants } from "$lib/components/ui/button/index.js"; import { buttonVariants } from '$lib/components/ui/button/index.js';
import { cn } from "$lib/utils.js"; import { cn } from '$lib/utils.js';
import { Calendar as CalendarPrimitive } from "bits-ui"; import { Calendar as CalendarPrimitive } from 'bits-ui';
let { let {
ref = $bindable(null), ref = $bindable(null),
class: className, class: className,
...restProps ...restProps
}: CalendarPrimitive.DayProps = $props(); }: CalendarPrimitive.DayProps = $props();
</script> </script>
<CalendarPrimitive.Day <CalendarPrimitive.Day
bind:ref bind:ref
class={cn( class={cn(
buttonVariants({ variant: "ghost" }), buttonVariants({ variant: 'ghost' }),
"flex size-(--cell-size) flex-col items-center justify-center gap-1 p-0 leading-none font-normal whitespace-nowrap select-none", 'flex size-(--cell-size) flex-col items-center justify-center gap-1 p-0 leading-none font-normal whitespace-nowrap select-none',
"[&[data-today]:not([data-selected])]:bg-accent [&[data-today]:not([data-selected])]:text-accent-foreground [&[data-today][data-disabled]]:text-muted-foreground", '[&[data-today]:not([data-selected])]:bg-accent [&[data-today]:not([data-selected])]:text-accent-foreground [&[data-today][data-disabled]]:text-muted-foreground',
"data-[selected]:bg-primary dark:data-[selected]:hover:bg-accent/50 data-[selected]:text-primary-foreground", 'data-[selected]:bg-primary dark:data-[selected]:hover:bg-accent/50 data-[selected]:text-primary-foreground',
// Outside months // Outside months
"[&[data-outside-month]:not([data-selected])]:text-muted-foreground [&[data-outside-month]:not([data-selected])]:hover:text-accent-foreground", '[&[data-outside-month]:not([data-selected])]:text-muted-foreground [&[data-outside-month]:not([data-selected])]:hover:text-accent-foreground',
// Disabled // Disabled
"data-[disabled]:text-muted-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", 'data-[disabled]:text-muted-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
// Unavailable // Unavailable
"data-[unavailable]:text-muted-foreground data-[unavailable]:line-through", 'data-[unavailable]:text-muted-foreground data-[unavailable]:line-through',
// hover // hover
"dark:hover:text-accent-foreground", 'dark:hover:text-accent-foreground',
// focus // focus
"focus:border-ring focus:ring-ring/50 focus:relative", 'focus:border-ring focus:ring-ring/50 focus:relative',
// inner spans // inner spans
"[&>span]:text-xs [&>span]:opacity-70", '[&>span]:text-xs [&>span]:opacity-70',
className className
)} )}
{...restProps} {...restProps}
/> />
@@ -1,12 +1,12 @@
<script lang="ts"> <script lang="ts">
import { Calendar as CalendarPrimitive } from "bits-ui"; import { cn } from '$lib/utils.js';
import { cn } from "$lib/utils.js"; import { Calendar as CalendarPrimitive } from 'bits-ui';
let { let {
ref = $bindable(null), ref = $bindable(null),
class: className, class: className,
...restProps ...restProps
}: CalendarPrimitive.GridBodyProps = $props(); }: CalendarPrimitive.GridBodyProps = $props();
</script> </script>
<CalendarPrimitive.GridBody bind:ref class={cn(className)} {...restProps} /> <CalendarPrimitive.GridBody bind:ref class={cn(className)} {...restProps} />
@@ -1,12 +1,12 @@
<script lang="ts"> <script lang="ts">
import { Calendar as CalendarPrimitive } from "bits-ui"; import { cn } from '$lib/utils.js';
import { cn } from "$lib/utils.js"; import { Calendar as CalendarPrimitive } from 'bits-ui';
let { let {
ref = $bindable(null), ref = $bindable(null),
class: className, class: className,
...restProps ...restProps
}: CalendarPrimitive.GridHeadProps = $props(); }: CalendarPrimitive.GridHeadProps = $props();
</script> </script>
<CalendarPrimitive.GridHead bind:ref class={cn(className)} {...restProps} /> <CalendarPrimitive.GridHead bind:ref class={cn(className)} {...restProps} />
@@ -1,12 +1,12 @@
<script lang="ts"> <script lang="ts">
import { Calendar as CalendarPrimitive } from "bits-ui"; import { cn } from '$lib/utils.js';
import { cn } from "$lib/utils.js"; import { Calendar as CalendarPrimitive } from 'bits-ui';
let { let {
ref = $bindable(null), ref = $bindable(null),
class: className, class: className,
...restProps ...restProps
}: CalendarPrimitive.GridRowProps = $props(); }: CalendarPrimitive.GridRowProps = $props();
</script> </script>
<CalendarPrimitive.GridRow bind:ref class={cn("flex", className)} {...restProps} /> <CalendarPrimitive.GridRow bind:ref class={cn('flex', className)} {...restProps} />
@@ -1,16 +1,16 @@
<script lang="ts"> <script lang="ts">
import { Calendar as CalendarPrimitive } from "bits-ui"; import { cn } from '$lib/utils.js';
import { cn } from "$lib/utils.js"; import { Calendar as CalendarPrimitive } from 'bits-ui';
let { let {
ref = $bindable(null), ref = $bindable(null),
class: className, class: className,
...restProps ...restProps
}: CalendarPrimitive.GridProps = $props(); }: CalendarPrimitive.GridProps = $props();
</script> </script>
<CalendarPrimitive.Grid <CalendarPrimitive.Grid
bind:ref bind:ref
class={cn("mt-4 flex w-full border-collapse flex-col gap-1", className)} class={cn('mt-4 flex w-full border-collapse flex-col gap-1', className)}
{...restProps} {...restProps}
/> />
@@ -1,19 +1,19 @@
<script lang="ts"> <script lang="ts">
import { Calendar as CalendarPrimitive } from "bits-ui"; import { cn } from '$lib/utils.js';
import { cn } from "$lib/utils.js"; import { Calendar as CalendarPrimitive } from 'bits-ui';
let { let {
ref = $bindable(null), ref = $bindable(null),
class: className, class: className,
...restProps ...restProps
}: CalendarPrimitive.HeadCellProps = $props(); }: CalendarPrimitive.HeadCellProps = $props();
</script> </script>
<CalendarPrimitive.HeadCell <CalendarPrimitive.HeadCell
bind:ref bind:ref
class={cn( class={cn(
"text-muted-foreground w-(--cell-size) rounded-md text-[0.8rem] font-normal", 'text-muted-foreground w-(--cell-size) rounded-md text-[0.8rem] font-normal',
className className
)} )}
{...restProps} {...restProps}
/> />
@@ -1,19 +1,19 @@
<script lang="ts"> <script lang="ts">
import { Calendar as CalendarPrimitive } from "bits-ui"; import { cn } from '$lib/utils.js';
import { cn } from "$lib/utils.js"; import { Calendar as CalendarPrimitive } from 'bits-ui';
let { let {
ref = $bindable(null), ref = $bindable(null),
class: className, class: className,
...restProps ...restProps
}: CalendarPrimitive.HeaderProps = $props(); }: CalendarPrimitive.HeaderProps = $props();
</script> </script>
<CalendarPrimitive.Header <CalendarPrimitive.Header
bind:ref bind:ref
class={cn( class={cn(
"flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium", 'flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium',
className className
)} )}
{...restProps} {...restProps}
/> />
@@ -1,16 +1,16 @@
<script lang="ts"> <script lang="ts">
import { Calendar as CalendarPrimitive } from "bits-ui"; import { cn } from '$lib/utils.js';
import { cn } from "$lib/utils.js"; import { Calendar as CalendarPrimitive } from 'bits-ui';
let { let {
ref = $bindable(null), ref = $bindable(null),
class: className, class: className,
...restProps ...restProps
}: CalendarPrimitive.HeadingProps = $props(); }: CalendarPrimitive.HeadingProps = $props();
</script> </script>
<CalendarPrimitive.Heading <CalendarPrimitive.Heading
bind:ref bind:ref
class={cn("px-(--cell-size) text-sm font-medium", className)} class={cn('px-(--cell-size) text-sm font-medium', className)}
{...restProps} {...restProps}
/> />
@@ -1,48 +1,48 @@
<script lang="ts"> <script lang="ts">
import { Calendar as CalendarPrimitive } from "bits-ui"; import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';
import { cn, type WithoutChildrenOrChild } from "$lib/utils.js"; import ChevronDownIcon from '@lucide/svelte/icons/chevron-down';
import ChevronDownIcon from "@lucide/svelte/icons/chevron-down"; import { Calendar as CalendarPrimitive } from 'bits-ui';
let { let {
ref = $bindable(null), ref = $bindable(null),
class: className, class: className,
value, value,
onchange, onchange,
...restProps ...restProps
}: WithoutChildrenOrChild<CalendarPrimitive.MonthSelectProps> = $props(); }: WithoutChildrenOrChild<CalendarPrimitive.MonthSelectProps> = $props();
</script> </script>
<span <span
class={cn( class={cn(
"has-focus:border-ring border-input has-focus:ring-ring/50 relative flex rounded-md border shadow-xs has-focus:ring-[3px]", 'has-focus:border-ring border-input has-focus:ring-ring/50 relative flex rounded-md border shadow-xs has-focus:ring-[3px]',
className className
)} )}
> >
<CalendarPrimitive.MonthSelect <CalendarPrimitive.MonthSelect
bind:ref bind:ref
class="dark:bg-popover dark:text-popover-foreground absolute inset-0 opacity-0" class="dark:bg-popover dark:text-popover-foreground absolute inset-0 opacity-0"
{...restProps} {...restProps}
> >
{#snippet child({ props, monthItems, selectedMonthItem })} {#snippet child({ props, monthItems, selectedMonthItem })}
<select {...props} {value} {onchange}> <select {...props} {value} {onchange}>
{#each monthItems as monthItem (monthItem.value)} {#each monthItems as monthItem (monthItem.value)}
<option <option
value={monthItem.value} value={monthItem.value}
selected={value !== undefined selected={value !== undefined
? monthItem.value === value ? monthItem.value === value
: monthItem.value === selectedMonthItem.value} : monthItem.value === selectedMonthItem.value}
> >
{monthItem.label} {monthItem.label}
</option> </option>
{/each} {/each}
</select> </select>
<span <span
class="[&>svg]:text-muted-foreground flex h-8 items-center gap-1 rounded-md ps-2 pe-1 text-sm font-medium select-none [&>svg]:size-3.5" class="[&>svg]:text-muted-foreground flex h-8 items-center gap-1 rounded-md ps-2 pe-1 text-sm font-medium select-none [&>svg]:size-3.5"
aria-hidden="true" aria-hidden="true"
> >
{monthItems.find((item) => item.value === value)?.label || selectedMonthItem.label} {monthItems.find((item) => item.value === value)?.label || selectedMonthItem.label}
<ChevronDownIcon class="size-4" /> <ChevronDownIcon class="size-4" />
</span> </span>
{/snippet} {/snippet}
</CalendarPrimitive.MonthSelect> </CalendarPrimitive.MonthSelect>
</span> </span>
@@ -1,15 +1,15 @@
<script lang="ts"> <script lang="ts">
import { type WithElementRef, cn } from "$lib/utils.js"; import { type WithElementRef, cn } from '$lib/utils.js';
import type { HTMLAttributes } from "svelte/elements"; import type { HTMLAttributes } from 'svelte/elements';
let { let {
ref = $bindable(null), ref = $bindable(null),
class: className, class: className,
children, children,
...restProps ...restProps
}: WithElementRef<HTMLAttributes<HTMLElement>> = $props(); }: WithElementRef<HTMLAttributes<HTMLElement>> = $props();
</script> </script>
<div {...restProps} bind:this={ref} class={cn("flex flex-col", className)}> <div {...restProps} bind:this={ref} class={cn('flex flex-col', className)}>
{@render children?.()} {@render children?.()}
</div> </div>
@@ -1,19 +1,19 @@
<script lang="ts"> <script lang="ts">
import type { HTMLAttributes } from "svelte/elements"; import { cn, type WithElementRef } from '$lib/utils.js';
import { cn, type WithElementRef } from "$lib/utils.js"; import type { HTMLAttributes } from 'svelte/elements';
let { let {
ref = $bindable(null), ref = $bindable(null),
class: className, class: className,
children, children,
...restProps ...restProps
}: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props(); }: WithElementRef<HTMLAttributes<HTMLDivElement>> = $props();
</script> </script>
<div <div
bind:this={ref} bind:this={ref}
class={cn("relative flex flex-col gap-4 md:flex-row", className)} class={cn('relative flex flex-col gap-4 md:flex-row', className)}
{...restProps} {...restProps}
> >
{@render children?.()} {@render children?.()}
</div> </div>
@@ -1,19 +1,19 @@
<script lang="ts"> <script lang="ts">
import { cn, type WithElementRef } from "$lib/utils.js"; import { cn, type WithElementRef } from '$lib/utils.js';
import type { HTMLAttributes } from "svelte/elements"; import type { HTMLAttributes } from 'svelte/elements';
let { let {
ref = $bindable(null), ref = $bindable(null),
class: className, class: className,
children, children,
...restProps ...restProps
}: WithElementRef<HTMLAttributes<HTMLElement>> = $props(); }: WithElementRef<HTMLAttributes<HTMLElement>> = $props();
</script> </script>
<nav <nav
{...restProps} {...restProps}
bind:this={ref} bind:this={ref}
class={cn("absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1", className)} class={cn('absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1', className)}
> >
{@render children?.()} {@render children?.()}
</nav> </nav>
@@ -1,31 +1,31 @@
<script lang="ts"> <script lang="ts">
import { Calendar as CalendarPrimitive } from "bits-ui"; import { buttonVariants, type ButtonVariant } from '$lib/components/ui/button/index.js';
import ChevronRightIcon from "@lucide/svelte/icons/chevron-right"; import { cn } from '$lib/utils.js';
import { buttonVariants, type ButtonVariant } from "$lib/components/ui/button/index.js"; import ChevronRightIcon from '@lucide/svelte/icons/chevron-right';
import { cn } from "$lib/utils.js"; import { Calendar as CalendarPrimitive } from 'bits-ui';
let { let {
ref = $bindable(null), ref = $bindable(null),
class: className, class: className,
children, children,
variant = "ghost", variant = 'ghost',
...restProps ...restProps
}: CalendarPrimitive.NextButtonProps & { }: CalendarPrimitive.NextButtonProps & {
variant?: ButtonVariant; variant?: ButtonVariant;
} = $props(); } = $props();
</script> </script>
{#snippet Fallback()} {#snippet Fallback()}
<ChevronRightIcon class="size-4" /> <ChevronRightIcon class="size-4" />
{/snippet} {/snippet}
<CalendarPrimitive.NextButton <CalendarPrimitive.NextButton
bind:ref bind:ref
class={cn( class={cn(
buttonVariants({ variant }), buttonVariants({ variant }),
"size-(--cell-size) bg-transparent p-0 select-none disabled:opacity-50 rtl:rotate-180", 'size-(--cell-size) bg-transparent p-0 select-none disabled:opacity-50 rtl:rotate-180',
className className
)} )}
children={children || Fallback} children={children || Fallback}
{...restProps} {...restProps}
/> />
@@ -1,31 +1,31 @@
<script lang="ts"> <script lang="ts">
import { Calendar as CalendarPrimitive } from "bits-ui"; import { buttonVariants, type ButtonVariant } from '$lib/components/ui/button/index.js';
import ChevronLeftIcon from "@lucide/svelte/icons/chevron-left"; import { cn } from '$lib/utils.js';
import { buttonVariants, type ButtonVariant } from "$lib/components/ui/button/index.js"; import ChevronLeftIcon from '@lucide/svelte/icons/chevron-left';
import { cn } from "$lib/utils.js"; import { Calendar as CalendarPrimitive } from 'bits-ui';
let { let {
ref = $bindable(null), ref = $bindable(null),
class: className, class: className,
children, children,
variant = "ghost", variant = 'ghost',
...restProps ...restProps
}: CalendarPrimitive.PrevButtonProps & { }: CalendarPrimitive.PrevButtonProps & {
variant?: ButtonVariant; variant?: ButtonVariant;
} = $props(); } = $props();
</script> </script>
{#snippet Fallback()} {#snippet Fallback()}
<ChevronLeftIcon class="size-4" /> <ChevronLeftIcon class="size-4" />
{/snippet} {/snippet}
<CalendarPrimitive.PrevButton <CalendarPrimitive.PrevButton
bind:ref bind:ref
class={cn( class={cn(
buttonVariants({ variant }), buttonVariants({ variant }),
"size-(--cell-size) bg-transparent p-0 select-none disabled:opacity-50 rtl:rotate-180", 'size-(--cell-size) bg-transparent p-0 select-none disabled:opacity-50 rtl:rotate-180',
className className
)} )}
children={children || Fallback} children={children || Fallback}
{...restProps} {...restProps}
/> />
@@ -1,47 +1,47 @@
<script lang="ts"> <script lang="ts">
import { Calendar as CalendarPrimitive } from "bits-ui"; import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';
import { cn, type WithoutChildrenOrChild } from "$lib/utils.js"; import ChevronDownIcon from '@lucide/svelte/icons/chevron-down';
import ChevronDownIcon from "@lucide/svelte/icons/chevron-down"; import { Calendar as CalendarPrimitive } from 'bits-ui';
let { let {
ref = $bindable(null), ref = $bindable(null),
class: className, class: className,
value, value,
...restProps ...restProps
}: WithoutChildrenOrChild<CalendarPrimitive.YearSelectProps> = $props(); }: WithoutChildrenOrChild<CalendarPrimitive.YearSelectProps> = $props();
</script> </script>
<span <span
class={cn( class={cn(
"has-focus:border-ring border-input has-focus:ring-ring/50 relative flex rounded-md border shadow-xs has-focus:ring-[3px]", 'has-focus:border-ring border-input has-focus:ring-ring/50 relative flex rounded-md border shadow-xs has-focus:ring-[3px]',
className className
)} )}
> >
<CalendarPrimitive.YearSelect <CalendarPrimitive.YearSelect
bind:ref bind:ref
class="dark:bg-popover dark:text-popover-foreground absolute inset-0 opacity-0" class="dark:bg-popover dark:text-popover-foreground absolute inset-0 opacity-0"
{...restProps} {...restProps}
> >
{#snippet child({ props, yearItems, selectedYearItem })} {#snippet child({ props, yearItems, selectedYearItem })}
<select {...props} {value}> <select {...props} {value}>
{#each yearItems as yearItem (yearItem.value)} {#each yearItems as yearItem (yearItem.value)}
<option <option
value={yearItem.value} value={yearItem.value}
selected={value !== undefined selected={value !== undefined
? yearItem.value === value ? yearItem.value === value
: yearItem.value === selectedYearItem.value} : yearItem.value === selectedYearItem.value}
> >
{yearItem.label} {yearItem.label}
</option> </option>
{/each} {/each}
</select> </select>
<span <span
class="[&>svg]:text-muted-foreground flex h-8 items-center gap-1 rounded-md ps-2 pe-1 text-sm font-medium select-none [&>svg]:size-3.5" class="[&>svg]:text-muted-foreground flex h-8 items-center gap-1 rounded-md ps-2 pe-1 text-sm font-medium select-none [&>svg]:size-3.5"
aria-hidden="true" aria-hidden="true"
> >
{yearItems.find((item) => item.value === value)?.label || selectedYearItem.label} {yearItems.find((item) => item.value === value)?.label || selectedYearItem.label}
<ChevronDownIcon class="size-4" /> <ChevronDownIcon class="size-4" />
</span> </span>
{/snippet} {/snippet}
</CalendarPrimitive.YearSelect> </CalendarPrimitive.YearSelect>
</span> </span>
+103 -103
View File
@@ -1,42 +1,42 @@
<script lang="ts"> <script lang="ts">
import { Calendar as CalendarPrimitive } from "bits-ui"; import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';
import * as Calendar from "./index.js"; import type { ButtonVariant } from '../button/button.svelte';
import { cn, type WithoutChildrenOrChild } from "$lib/utils.js"; import * as Calendar from './index.js';
import type { ButtonVariant } from "../button/button.svelte"; import { isEqualMonth, type DateValue } from '@internationalized/date';
import { isEqualMonth, type DateValue } from "@internationalized/date"; import { Calendar as CalendarPrimitive } from 'bits-ui';
import type { Snippet } from "svelte"; import type { Snippet } from 'svelte';
let { let {
ref = $bindable(null), ref = $bindable(null),
value = $bindable(), value = $bindable(),
placeholder = $bindable(), placeholder = $bindable(),
class: className, class: className,
weekdayFormat = "short", weekdayFormat = 'short',
buttonVariant = "ghost", buttonVariant = 'ghost',
captionLayout = "label", captionLayout = 'label',
locale = "en-US", locale = 'en-US',
months: monthsProp, months: monthsProp,
years, years,
monthFormat: monthFormatProp, monthFormat: monthFormatProp,
yearFormat = "numeric", yearFormat = 'numeric',
day, day,
disableDaysOutsideMonth = false, disableDaysOutsideMonth = false,
...restProps ...restProps
}: WithoutChildrenOrChild<CalendarPrimitive.RootProps> & { }: WithoutChildrenOrChild<CalendarPrimitive.RootProps> & {
buttonVariant?: ButtonVariant; buttonVariant?: ButtonVariant;
captionLayout?: "dropdown" | "dropdown-months" | "dropdown-years" | "label"; captionLayout?: 'dropdown' | 'dropdown-months' | 'dropdown-years' | 'label';
months?: CalendarPrimitive.MonthSelectProps["months"]; months?: CalendarPrimitive.MonthSelectProps['months'];
years?: CalendarPrimitive.YearSelectProps["years"]; years?: CalendarPrimitive.YearSelectProps['years'];
monthFormat?: CalendarPrimitive.MonthSelectProps["monthFormat"]; monthFormat?: CalendarPrimitive.MonthSelectProps['monthFormat'];
yearFormat?: CalendarPrimitive.YearSelectProps["yearFormat"]; yearFormat?: CalendarPrimitive.YearSelectProps['yearFormat'];
day?: Snippet<[{ day: DateValue; outsideMonth: boolean }]>; day?: Snippet<[{ day: DateValue; outsideMonth: boolean }]>;
} = $props(); } = $props();
const monthFormat = $derived.by(() => { const monthFormat = $derived.by(() => {
if (monthFormatProp) return monthFormatProp; if (monthFormatProp) return monthFormatProp;
if (captionLayout.startsWith("dropdown")) return "short"; if (captionLayout.startsWith('dropdown')) return 'short';
return "long"; return 'long';
}); });
</script> </script>
<!-- <!--
@@ -44,72 +44,72 @@ Discriminated Unions + Destructing (required for bindable) do not
get along, so we shut typescript up by casting `value` to `never`. get along, so we shut typescript up by casting `value` to `never`.
--> -->
<CalendarPrimitive.Root <CalendarPrimitive.Root
bind:value={value as never} bind:value={value as never}
bind:ref bind:ref
bind:placeholder bind:placeholder
{weekdayFormat} {weekdayFormat}
{disableDaysOutsideMonth} {disableDaysOutsideMonth}
class={cn( class={cn(
"bg-background group/calendar p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent", 'bg-background group/calendar p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent',
className className
)} )}
{locale} {locale}
{monthFormat} {monthFormat}
{yearFormat} {yearFormat}
{...restProps} {...restProps}
> >
{#snippet children({ months, weekdays })} {#snippet children({ months, weekdays })}
<Calendar.Months> <Calendar.Months>
<Calendar.Nav> <Calendar.Nav>
<Calendar.PrevButton variant={buttonVariant} /> <Calendar.PrevButton variant={buttonVariant} />
<Calendar.NextButton variant={buttonVariant} /> <Calendar.NextButton variant={buttonVariant} />
</Calendar.Nav> </Calendar.Nav>
{#each months as month, monthIndex (month)} {#each months as month, monthIndex (month)}
<Calendar.Month> <Calendar.Month>
<Calendar.Header> <Calendar.Header>
<Calendar.Caption <Calendar.Caption
{captionLayout} {captionLayout}
months={monthsProp} months={monthsProp}
{monthFormat} {monthFormat}
{years} {years}
{yearFormat} {yearFormat}
month={month.value} month={month.value}
bind:placeholder bind:placeholder
{locale} {locale}
{monthIndex} {monthIndex}
/> />
</Calendar.Header> </Calendar.Header>
<Calendar.Grid> <Calendar.Grid>
<Calendar.GridHead> <Calendar.GridHead>
<Calendar.GridRow class="select-none"> <Calendar.GridRow class="select-none">
{#each weekdays as weekday (weekday)} {#each weekdays as weekday (weekday)}
<Calendar.HeadCell> <Calendar.HeadCell>
{weekday.slice(0, 2)} {weekday.slice(0, 2)}
</Calendar.HeadCell> </Calendar.HeadCell>
{/each} {/each}
</Calendar.GridRow> </Calendar.GridRow>
</Calendar.GridHead> </Calendar.GridHead>
<Calendar.GridBody> <Calendar.GridBody>
{#each month.weeks as weekDates (weekDates)} {#each month.weeks as weekDates (weekDates)}
<Calendar.GridRow class="mt-2 w-full"> <Calendar.GridRow class="mt-2 w-full">
{#each weekDates as date (date)} {#each weekDates as date (date)}
<Calendar.Cell {date} month={month.value}> <Calendar.Cell {date} month={month.value}>
{#if day} {#if day}
{@render day({ {@render day({
day: date, day: date,
outsideMonth: !isEqualMonth(date, month.value), outsideMonth: !isEqualMonth(date, month.value),
})} })}
{:else} {:else}
<Calendar.Day /> <Calendar.Day />
{/if} {/if}
</Calendar.Cell> </Calendar.Cell>
{/each} {/each}
</Calendar.GridRow> </Calendar.GridRow>
{/each} {/each}
</Calendar.GridBody> </Calendar.GridBody>
</Calendar.Grid> </Calendar.Grid>
</Calendar.Month> </Calendar.Month>
{/each} {/each}
</Calendar.Months> </Calendar.Months>
{/snippet} {/snippet}
</CalendarPrimitive.Root> </CalendarPrimitive.Root>
+37 -37
View File
@@ -1,40 +1,40 @@
import Root from "./calendar.svelte"; import Caption from './calendar-caption.svelte';
import Cell from "./calendar-cell.svelte"; import Cell from './calendar-cell.svelte';
import Day from "./calendar-day.svelte"; import Day from './calendar-day.svelte';
import Grid from "./calendar-grid.svelte"; import GridBody from './calendar-grid-body.svelte';
import Header from "./calendar-header.svelte"; import GridHead from './calendar-grid-head.svelte';
import Months from "./calendar-months.svelte"; import GridRow from './calendar-grid-row.svelte';
import GridRow from "./calendar-grid-row.svelte"; import Grid from './calendar-grid.svelte';
import Heading from "./calendar-heading.svelte"; import HeadCell from './calendar-head-cell.svelte';
import GridBody from "./calendar-grid-body.svelte"; import Header from './calendar-header.svelte';
import GridHead from "./calendar-grid-head.svelte"; import Heading from './calendar-heading.svelte';
import HeadCell from "./calendar-head-cell.svelte"; import MonthSelect from './calendar-month-select.svelte';
import NextButton from "./calendar-next-button.svelte"; import Month from './calendar-month.svelte';
import PrevButton from "./calendar-prev-button.svelte"; import Months from './calendar-months.svelte';
import MonthSelect from "./calendar-month-select.svelte"; import Nav from './calendar-nav.svelte';
import YearSelect from "./calendar-year-select.svelte"; import NextButton from './calendar-next-button.svelte';
import Month from "./calendar-month.svelte"; import PrevButton from './calendar-prev-button.svelte';
import Nav from "./calendar-nav.svelte"; import YearSelect from './calendar-year-select.svelte';
import Caption from "./calendar-caption.svelte"; import Root from './calendar.svelte';
export { export {
Day, Day,
Cell, Cell,
Grid, Grid,
Header, Header,
Months, Months,
GridRow, GridRow,
Heading, Heading,
GridBody, GridBody,
GridHead, GridHead,
HeadCell, HeadCell,
NextButton, NextButton,
PrevButton, PrevButton,
Nav, Nav,
Month, Month,
YearSelect, YearSelect,
MonthSelect, MonthSelect,
Caption, Caption,
// //
Root as Calendar, Root as Calendar,
}; };
@@ -18,6 +18,8 @@
contentClass = '', contentClass = '',
open = $bindable(false), open = $bindable(false),
id = undefined, id = undefined,
ariaLabel = undefined,
onValueChange = undefined,
}: { }: {
value?: string; value?: string;
withTime?: boolean; withTime?: boolean;
@@ -29,6 +31,8 @@
contentClass?: string; contentClass?: string;
open?: boolean; open?: boolean;
id?: string; id?: string;
ariaLabel?: string;
onValueChange?: (value: string) => void;
} = $props(); } = $props();
let calendarValue = $state<DateValue | undefined>(undefined); let calendarValue = $state<DateValue | undefined>(undefined);
@@ -70,10 +74,11 @@
if (!calendarValue) { if (!calendarValue) {
lastEmittedValue = ''; lastEmittedValue = '';
value = ''; value = '';
onValueChange?.('');
return; return;
} }
let next = ''; let next: string;
if (withTime) { if (withTime) {
const d = new Date( const d = new Date(
calendarValue.year, calendarValue.year,
@@ -91,6 +96,7 @@
lastEmittedValue = next; lastEmittedValue = next;
value = next; value = next;
onValueChange?.(next);
} }
function handleDateChange(newDate: DateValue | undefined) { function handleDateChange(newDate: DateValue | undefined) {
@@ -147,6 +153,7 @@
<Popover.Trigger <Popover.Trigger
{id} {id}
{disabled} {disabled}
aria-label={ariaLabel}
class={cn( class={cn(
'flex h-8 w-full items-center justify-start gap-2 rounded-md border border-input bg-background px-3 text-xs font-normal text-foreground transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 ring-offset-background', 'flex h-8 w-full items-center justify-start gap-2 rounded-md border border-input bg-background px-3 text-xs font-normal text-foreground transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 ring-offset-background',
!formattedDisplay && 'text-muted-foreground', !formattedDisplay && 'text-muted-foreground',
@@ -0,0 +1,29 @@
<script lang="ts">
import { cn } from '$lib/utils.js';
import DialogOverlay from './dialog-overlay.svelte';
import { Dialog as DialogPrimitive, type WithoutChild } from 'bits-ui';
let {
ref = $bindable(null),
class: className,
portalProps,
children,
...restProps
}: WithoutChild<DialogPrimitive.ContentProps> & {
portalProps?: DialogPrimitive.PortalProps;
} = $props();
</script>
<DialogPrimitive.Portal {...portalProps}>
<DialogOverlay />
<DialogPrimitive.Content
bind:ref
class={cn(
'bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border p-6 shadow-lg duration-200 sm:rounded-lg',
className
)}
{...restProps}
>
{@render children?.()}
</DialogPrimitive.Content>
</DialogPrimitive.Portal>
@@ -0,0 +1,16 @@
<script lang="ts">
import { cn } from '$lib/utils.js';
import { Dialog as DialogPrimitive } from 'bits-ui';
let {
ref = $bindable(null),
class: className,
...restProps
}: DialogPrimitive.DescriptionProps = $props();
</script>
<DialogPrimitive.Description
bind:ref
class={cn('text-muted-foreground text-sm', className)}
{...restProps}
/>
@@ -0,0 +1,19 @@
<script lang="ts">
import { cn } from '$lib/utils.js';
import { Dialog as DialogPrimitive } from 'bits-ui';
let {
ref = $bindable(null),
class: className,
...restProps
}: DialogPrimitive.OverlayProps = $props();
</script>
<DialogPrimitive.Overlay
bind:ref
class={cn(
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/80 backdrop-blur-sm',
className
)}
{...restProps}
/>
@@ -0,0 +1,18 @@
<script lang="ts">
import { cn } from '$lib/utils.js';
import { Dialog as DialogPrimitive } from 'bits-ui';
let {
ref = $bindable(null),
class: className,
level = 2,
...restProps
}: DialogPrimitive.TitleProps = $props();
</script>
<DialogPrimitive.Title
bind:ref
class={cn('text-lg font-semibold', className)}
{level}
{...restProps}
/>
@@ -0,0 +1,8 @@
<script lang="ts">
import { Dialog as DialogPrimitive, type WithoutChildrenOrChild } from 'bits-ui';
let { open = $bindable(false), ...restProps }: WithoutChildrenOrChild<DialogPrimitive.RootProps> =
$props();
</script>
<DialogPrimitive.Root bind:open {...restProps} />
+24
View File
@@ -0,0 +1,24 @@
import Content from './dialog-content.svelte';
import Description from './dialog-description.svelte';
import Overlay from './dialog-overlay.svelte';
import Title from './dialog-title.svelte';
import { Dialog as DialogPrimitive } from 'bits-ui';
const Root = DialogPrimitive.Root;
const Trigger = DialogPrimitive.Trigger;
export {
Root,
Trigger,
Overlay,
Content,
Title,
Description,
//
Root as Dialog,
Trigger as DialogTrigger,
Overlay as DialogOverlay,
Content as DialogContent,
Title as DialogTitle,
Description as DialogDescription,
};
@@ -1,6 +1,6 @@
<script lang="ts"> <script lang="ts">
import ThemeIcon from '$lib/components/theme/ThemeIcon.svelte'; import ThemeIcon from '$lib/components/theme/ThemeIcon.svelte';
import { DEFAULT_THEME_ICON_SET, type ThemeIconSet } from '$lib/themeIcons'; import { DEFAULT_THEME_ICON_SET, type ThemeIconSet } from '$lib/theme/themeIcons';
const prop: { const prop: {
downloading: boolean; downloading: boolean;
@@ -9,23 +9,60 @@
subtext?: string; subtext?: string;
disabled?: boolean; disabled?: boolean;
iconSet?: ThemeIconSet; iconSet?: ThemeIconSet;
class?: string;
onClick?: () => void; onClick?: () => void;
} = $props(); } = $props();
const radius = 16; let buttonHeight = $state(48);
let buttonWidth = $state(200);
const baseDim = $derived(
Math.min(buttonHeight > 0 ? buttonHeight : 48, buttonWidth > 0 ? buttonWidth : 200)
);
// Circle scales with button dimensions: ~70% of base dimension (no artificial upper clamp)
const circleSize = $derived(Math.max(16, Math.round(baseDim * 0.7)));
// Icon scales with circle size: ~44% of circle size
const iconSize = $derived(Math.max(10, Math.round(circleSize * 0.44)));
// Progress font size scales with circle size
const percentFontSize = $derived(Math.max(8, Math.round(circleSize * 0.32)));
// Optical horizontal nudge for the play triangle
const iconNudge = $derived(Math.max(1, Math.round(circleSize * 0.04)));
// Responsive font scaling for label and subtext
const availableTextWidth = $derived(
Math.max(50, (buttonWidth > 0 ? buttonWidth : 200) - baseDim)
);
const textChars = $derived(Math.max(6, (prop.text || 'Launch').length));
const maxFontFromWidth = $derived((availableTextWidth * 0.85) / textChars);
const maxFontFromHeight = $derived(baseDim * (prop.subtext ? 0.24 : 0.32));
const labelFontSize = $derived(
Math.max(10, Math.round(Math.min(maxFontFromHeight, maxFontFromWidth)))
);
const subtextFontSize = $derived(Math.max(8, Math.round(labelFontSize * 0.72)));
const radius = 16.5;
const circumference = 2 * Math.PI * radius; const circumference = 2 * Math.PI * radius;
const strokeDashoffset = $derived(circumference - (prop.progress / 100) * circumference); const strokeDashoffset = $derived(
circumference - (Math.max(0, Math.min(100, prop.progress)) / 100) * circumference
);
</script> </script>
<button <button
class="group flex items-center h-12 rounded-full bg-primary disabled:bg-primary/70 shadow-lg shadow-primary/25 transition-all not-disabled:hover:shadow-primary/40 not-disabled:hover:brightness-110 not-disabled:active:scale-[0.98] cursor-pointer w-fit" bind:clientHeight={buttonHeight}
bind:clientWidth={buttonWidth}
class="group flex items-center rounded-full bg-primary disabled:bg-primary/70 shadow-lg shadow-primary/25 transition-all not-disabled:hover:shadow-primary/40 not-disabled:hover:brightness-110 not-disabled:active:scale-[0.98] cursor-pointer {prop.class ??
'h-12 w-fit'}"
disabled={prop.disabled} disabled={prop.disabled}
onclick={prop.onClick} onclick={prop.onClick}
> >
<div class="relative size-12 shrink-0 flex items-center justify-center"> <div class="relative h-full aspect-square shrink-0 flex items-center justify-center">
{#if prop.downloading} {#if prop.downloading}
{#if prop.progress === -1} {#if prop.progress === -1}
<svg class="absolute inset-0 animate-spin" viewBox="0 0 48 48"> <svg
class="absolute inset-0 h-full w-full animate-spin pointer-events-none"
viewBox="0 0 48 48"
>
<circle class="stroke-black/10" cx="24" cy="24" r={radius} fill="none" stroke-width="3" /> <circle class="stroke-black/10" cx="24" cy="24" r={radius} fill="none" stroke-width="3" />
<circle <circle
class="stroke-pink-950" class="stroke-pink-950"
@@ -40,7 +77,10 @@
/> />
</svg> </svg>
{:else} {:else}
<svg class="absolute inset-0 -rotate-90" viewBox="0 0 48 48"> <svg
class="absolute inset-0 h-full w-full -rotate-90 pointer-events-none"
viewBox="0 0 48 48"
>
<circle <circle
cx="24" cx="24"
cy="24" cy="24"
@@ -64,35 +104,56 @@
</svg> </svg>
{/if} {/if}
{/if} {/if}
<div class="size-9 rounded-full bg-black/30 flex items-center justify-center relative z-10"> <div
class="aspect-square rounded-full bg-black/30 flex items-center justify-center relative z-10 max-h-[72%] max-w-[72%]"
style="width: {circleSize}px; height: {circleSize}px;"
>
{#if prop.downloading} {#if prop.downloading}
{#if prop.progress === -1} {#if prop.progress === -1}
<ThemeIcon <ThemeIcon
name="ellipsis" name="ellipsis"
set={prop.iconSet ?? DEFAULT_THEME_ICON_SET} set={prop.iconSet ?? DEFAULT_THEME_ICON_SET}
class="size-4 text-primary-foreground fill-current animate-pulse" size={iconSize}
class="text-primary-foreground fill-current animate-pulse max-w-[50%] max-h-[50%]"
/> />
{:else} {:else}
<span class="text-[10px] font-bold text-primary-foreground"> <span
{prop.progress.toFixed()} class="font-bold text-primary-foreground leading-none"
style="font-size: {percentFontSize}px;"
>
{prop.progress.toFixed()}%
</span> </span>
{/if} {/if}
{:else} {:else}
<ThemeIcon <ThemeIcon
name="launch" name="launch"
set={prop.iconSet ?? DEFAULT_THEME_ICON_SET} set={prop.iconSet ?? DEFAULT_THEME_ICON_SET}
class="size-4 text-primary-foreground fill-current ml-0.5" size={iconSize}
class="text-primary-foreground fill-current max-w-[50%] max-h-[50%]"
style="margin-left: {iconNudge}px;"
/> />
{/if} {/if}
</div> </div>
</div> </div>
<div class="pr-6 pl-1 text-center w-52"> <div
<p class="text-sm font-bold text-primary-foreground leading-tight"> class="text-center flex-1 min-w-0 max-w-full {prop.class ? '' : 'w-48'}"
style="padding-right: {Math.max(8, Math.round(baseDim * 0.25))}px; padding-left: {Math.max(
4,
Math.round(baseDim * 0.08)
)}px;"
>
<p
class="font-bold text-primary-foreground leading-tight truncate"
style="font-size: {labelFontSize}px;"
>
{prop.text} {prop.text}
</p> </p>
{#if prop.subtext} {#if prop.subtext}
<p class="text-[10px] text-primary-foreground/70 leading-tight"> <p
class="text-primary-foreground/70 leading-tight truncate"
style="font-size: {subtextFontSize}px;"
>
{prop.subtext} {prop.subtext}
</p> </p>
{/if} {/if}
+207 -68
View File
@@ -11,48 +11,78 @@
const SPEED_THRESHOLD = 9; const SPEED_THRESHOLD = 9;
const REQUIRED_CONSECUTIVE = 3; const REQUIRED_CONSECUTIVE = 3;
let mouseX = $state(0); let currentX = 0;
let mouseY = $state(0); let currentY = 0;
let targetX = 0;
let targetY = 0;
let prevAppliedX = -1;
let prevAppliedY = -1;
let hasMoved = false;
let lastMouseX = 0; let lastMouseX = 0;
let lastMouseY = 0; let lastMouseY = 0;
let isMouseDown = $state(false); let isMouseDown = false;
let isHoveringInteractive = $state(false); let isHoveringInteractive = false;
let dragStartX = 0; let dragStartX = 0;
let dragStartY = 0; let dragStartY = 0;
let degrees = $state(0); let targetDegrees = 0;
let applyRotation = $state(false); let currentDegrees = 0;
let applyRotation = false;
let lastVelocityTime = 0; let lastVelocityTime = 0;
let consecutiveHighSpeed = 0; let consecutiveHighSpeed = 0;
let velocityAccumX = 0; let velocityAccumX = 0;
let velocityAccumY = 0; let velocityAccumY = 0;
let rotateSpringAnim: ReturnType<typeof animate> | null = null;
let scheduleCursorFrame = () => {};
let cursor: HTMLElement;
let cursorRotateWrapper: HTMLDivElement;
let cursorInner: HTMLImageElement;
let cursorAdditive: HTMLImageElement;
function isInteractive(el: Element | null): boolean { function isInteractive(el: Element | null): boolean {
while (el) { if (!el) return false;
const tag = el.tagName.toLowerCase(); if (
const role = el.getAttribute('role'); el.closest(
const computed = getComputedStyle(el); 'button, a, input, select, textarea, label, option, [role="button"], [role="link"], [role="checkbox"], [role="combobox"], [role="menuitem"], [role="option"]'
if ( )
['button', 'a', 'input', 'select', 'textarea', 'label', 'option'].includes(tag) || ) {
(role && ['button', 'link', 'checkbox', 'combobox', 'menuitem', 'option'].includes(role)) || return true;
computed.cursor === 'pointer'
) {
return true;
}
el = el.parentElement;
} }
return false; return getComputedStyle(el).cursor === 'pointer';
}
function dampContinuously(current: number, target: number, halfLife: number, dt: number): number {
if (halfLife <= 0 || dt <= 0) return target;
return target + (current - target) * Math.pow(0.5, dt / halfLife);
} }
const handleMouseMove = (e: MouseEvent) => { const handleMouseMove = (e: MouseEvent) => {
mouseX = e.clientX; targetX = e.clientX;
mouseY = e.clientY; targetY = e.clientY;
const deltaX = e.pageX - window.pageXOffset - dragStartX; if (!hasMoved) {
const deltaY = e.pageY - window.pageYOffset - dragStartY; currentX = targetX;
currentY = targetY;
prevAppliedX = targetX;
prevAppliedY = targetY;
lastMouseX = targetX;
lastMouseY = targetY;
hasMoved = true;
if (cursor) {
cursor.style.opacity = '1';
cursor.style.transform = `translate3d(${targetX}px, ${targetY}px, 0)`;
}
return;
}
velocityAccumX += mouseX - lastMouseX; if (cursor) {
velocityAccumY += mouseY - lastMouseY; cursor.style.opacity = '1';
}
velocityAccumX += targetX - lastMouseX;
velocityAccumY += targetY - lastMouseY;
const now = performance.now(); const now = performance.now();
const dt = now - lastVelocityTime; const dt = now - lastVelocityTime;
@@ -74,48 +104,34 @@
lastVelocityTime = now; lastVelocityTime = now;
} }
let newDegrees = (Math.atan2(-deltaX, deltaY) * 180) / Math.PI + 24.3;
let diff = (newDegrees - degrees) % 360;
if (diff < -180) diff += 360;
if (diff > 180) diff -= 360;
if (isMouseDown && applyRotation) { if (isMouseDown && applyRotation) {
degrees += diff; const deltaX = targetX - dragStartX;
} else { const deltaY = targetY - dragStartY;
degrees = 0; const newDegrees = (Math.atan2(-deltaX, deltaY) * 180) / Math.PI + 24.3;
let diff = (newDegrees - targetDegrees) % 360;
if (diff < -180) diff += 360;
if (diff > 180) diff -= 360;
targetDegrees += diff;
} }
const el = document.elementFromPoint(mouseX, mouseY); const el = document.elementFromPoint(targetX, targetY);
isHoveringInteractive = isInteractive(el); const hovering = isInteractive(el);
if (hovering !== isHoveringInteractive) {
if (!isMouseDown) { isHoveringInteractive = hovering;
animate(cursorAdditive, { if (!isMouseDown) {
opacity: isHoveringInteractive ? 1 : 0, animate(cursorAdditive, {
duration: 800, opacity: isHoveringInteractive ? 1 : 0,
ease: (t: number) => (t - 1) ** 5 + 1, duration: 800,
}); ease: (t: number) => (t - 1) ** 5 + 1,
});
}
} }
animate(cursor, { scheduleCursorFrame();
duration: smoothCursor ? $cursorSmoothness : 0, lastMouseX = targetX;
translateX: mouseX, lastMouseY = targetY;
translateY: mouseY,
ease: (t: number) => (t === 1 ? 1 : 1 - Math.pow(2, -10 * t)),
});
animate(cursor, {
duration: isMouseDown ? 200 : 1500,
rotate: degrees,
transformOrigin: '0px 0px 0',
ease: (t: number) =>
isMouseDown
? (t - 1) ** 7 + 1
: Math.pow(2, -10 * t) * Math.sin((t - 0.075) * 20.94) + 1 - 0.0005 * t,
});
lastMouseX = mouseX;
lastMouseY = mouseY;
}; };
const handleMouseDown = (event: MouseEvent) => { const handleMouseDown = (event: MouseEvent) => {
@@ -128,6 +144,13 @@
lastVelocityTime = performance.now(); lastVelocityTime = performance.now();
isMouseDown = true; isMouseDown = true;
scheduleCursorFrame();
if (rotateSpringAnim) {
rotateSpringAnim.pause();
rotateSpringAnim = null;
}
animate(cursorInner, { animate(cursorInner, {
scale: 0.9, scale: 0.9,
duration: 800, duration: 800,
@@ -143,6 +166,7 @@
const handleMouseUp = () => { const handleMouseUp = () => {
isMouseDown = false; isMouseDown = false;
const hadRotation = applyRotation || Math.abs(currentDegrees) > 0.1;
applyRotation = false; applyRotation = false;
consecutiveHighSpeed = 0; consecutiveHighSpeed = 0;
velocityAccumX = 0; velocityAccumX = 0;
@@ -154,21 +178,136 @@
ease: (t: number) => Math.pow(2, -10 * t) * Math.sin((t - 0.075) * 20.94) + 1 - 0.0005 * t, ease: (t: number) => Math.pow(2, -10 * t) * Math.sin((t - 0.075) * 20.94) + 1 - 0.0005 * t,
}); });
animate(cursorAdditive, { animate(cursorAdditive, {
opacity: 0, opacity: isHoveringInteractive ? 1 : 0,
duration: 500, duration: 500,
scale: 1, scale: 1,
ease: (t: number) => (t - 1) ** 5 + 1, ease: (t: number) => (t - 1) ** 5 + 1,
}); });
if (hadRotation && cursorRotateWrapper) {
rotateSpringAnim = animate(cursorRotateWrapper, {
rotate: 0,
duration: 1200,
ease: (t: number) => Math.pow(2, -10 * t) * Math.sin((t - 0.075) * 20.94) + 1 - 0.0005 * t,
onComplete: () => {
currentDegrees = 0;
targetDegrees = 0;
rotateSpringAnim = null;
},
});
}
}; };
let cursor: HTMLElement; const handleMouseLeave = () => {
let cursorInner: HTMLDivElement; if (cursor) cursor.style.opacity = '0';
let cursorAdditive: HTMLImageElement; };
const handleMouseEnter = () => {
if (cursor && hasMoved) cursor.style.opacity = '1';
};
onMount(() => { onMount(() => {
document.documentElement.classList.add('hiddenCursor'); document.documentElement.classList.add('hiddenCursor');
document.addEventListener('mouseleave', handleMouseLeave);
document.addEventListener('mouseenter', handleMouseEnter);
let animationFrameId: number | undefined;
let lastFrameTime = performance.now();
let paused = false;
const tick = (now: number) => {
animationFrameId = undefined;
if (paused) return;
const dt = Math.min(Math.max(now - lastFrameTime, 0), 64);
lastFrameTime = now;
let needsAnotherFrame = false;
if (hasMoved && cursor) {
if (!smoothCursor) {
currentX = targetX;
currentY = targetY;
} else {
// Continuous exponential damping half-life in ms (mathematically invariant across refresh rates).
const halfLife = $cursorSmoothness > 50 ? 14 : Math.max(1, $cursorSmoothness || 14);
currentX = dampContinuously(currentX, targetX, halfLife, dt);
currentY = dampContinuously(currentY, targetY, halfLife, dt);
needsAnotherFrame =
Math.abs(targetX - currentX) >= 0.05 || Math.abs(targetY - currentY) >= 0.05;
}
if (Math.abs(targetX - currentX) < 0.05) currentX = targetX;
if (Math.abs(targetY - currentY) < 0.05) currentY = targetY;
if (currentX !== prevAppliedX || currentY !== prevAppliedY) {
cursor.style.transform = `translate3d(${currentX}px, ${currentY}px, 0)`;
prevAppliedX = currentX;
prevAppliedY = currentY;
}
if (isMouseDown && applyRotation && cursorRotateWrapper) {
const rotFactor = 1 - Math.pow(0.5, dt / 25);
currentDegrees += (targetDegrees - currentDegrees) * rotFactor;
cursorRotateWrapper.style.transform = `rotate(${currentDegrees}deg)`;
needsAnotherFrame = true;
}
}
if (needsAnotherFrame) {
animationFrameId = requestAnimationFrame(tick);
}
};
scheduleCursorFrame = () => {
if (paused || animationFrameId !== undefined) return;
lastFrameTime = performance.now();
animationFrameId = requestAnimationFrame(tick);
};
const suspendCursor = () => {
paused = true;
if (animationFrameId !== undefined) {
cancelAnimationFrame(animationFrameId);
animationFrameId = undefined;
}
if (cursor) cursor.style.opacity = '0';
};
const resumeCursor = () => {
if (!paused) return;
paused = false;
lastFrameTime = performance.now();
if (!hasMoved) return;
if (cursor) cursor.style.opacity = '1';
scheduleCursorFrame();
};
const onVisibilityChange = () => {
if (document.visibilityState === 'hidden') suspendCursor();
else if (document.hasFocus()) resumeCursor();
};
const onWindowBlur = () => suspendCursor();
const onWindowFocus = () => {
if (document.visibilityState !== 'hidden') resumeCursor();
};
document.addEventListener('visibilitychange', onVisibilityChange);
window.addEventListener('blur', onWindowBlur);
window.addEventListener('focus', onWindowFocus);
onVisibilityChange();
return () => { return () => {
document.documentElement.classList.remove('hiddenCursor'); document.documentElement.classList.remove('hiddenCursor');
document.removeEventListener('mouseleave', handleMouseLeave);
document.removeEventListener('mouseenter', handleMouseEnter);
document.removeEventListener('visibilitychange', onVisibilityChange);
window.removeEventListener('blur', onWindowBlur);
window.removeEventListener('focus', onWindowFocus);
scheduleCursorFrame = () => {};
suspendCursor();
if (rotateSpringAnim) {
rotateSpringAnim.pause();
}
}; };
}); });
</script> </script>
@@ -179,8 +318,8 @@
onmouseup={handleMouseUp} onmouseup={handleMouseUp}
/> />
<div class="h-7 w-7 fixed pointer-events-none z-[9999]" bind:this={cursor}> <div class="h-7 w-7 fixed top-0 left-0 pointer-events-none z-[9999] opacity-0" bind:this={cursor}>
<div class="relative"> <div class="relative origin-top-left" bind:this={cursorRotateWrapper}>
<img class="absolute top-0 left-0" src={cursor_default} bind:this={cursorInner} alt="cursor" /> <img class="absolute top-0 left-0" src={cursor_default} bind:this={cursorInner} alt="cursor" />
<img <img
class="absolute top-0 left-0 opacity-0" class="absolute top-0 left-0 opacity-0"
+16 -16
View File
@@ -1,19 +1,19 @@
import Root from "./popover.svelte"; import Close from './popover-close.svelte';
import Close from "./popover-close.svelte"; import Content from './popover-content.svelte';
import Content from "./popover-content.svelte"; import Portal from './popover-portal.svelte';
import Trigger from "./popover-trigger.svelte"; import Trigger from './popover-trigger.svelte';
import Portal from "./popover-portal.svelte"; import Root from './popover.svelte';
export { export {
Root, Root,
Content, Content,
Trigger, Trigger,
Close, Close,
Portal, Portal,
// //
Root as Popover, Root as Popover,
Content as PopoverContent, Content as PopoverContent,
Trigger as PopoverTrigger, Trigger as PopoverTrigger,
Close as PopoverClose, Close as PopoverClose,
Portal as PopoverPortal, Portal as PopoverPortal,
}; };
@@ -1,7 +1,7 @@
<script lang="ts"> <script lang="ts">
import { Popover as PopoverPrimitive } from "bits-ui"; import { Popover as PopoverPrimitive } from 'bits-ui';
let { ref = $bindable(null), ...restProps }: PopoverPrimitive.CloseProps = $props(); let { ref = $bindable(null), ...restProps }: PopoverPrimitive.CloseProps = $props();
</script> </script>
<PopoverPrimitive.Close bind:ref data-slot="popover-close" {...restProps} /> <PopoverPrimitive.Close bind:ref data-slot="popover-close" {...restProps} />
@@ -1,31 +1,31 @@
<script lang="ts"> <script lang="ts">
import { Popover as PopoverPrimitive } from "bits-ui"; import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';
import PopoverPortal from "./popover-portal.svelte"; import PopoverPortal from './popover-portal.svelte';
import { cn, type WithoutChildrenOrChild } from "$lib/utils.js"; import { Popover as PopoverPrimitive } from 'bits-ui';
import type { ComponentProps } from "svelte"; import type { ComponentProps } from 'svelte';
let { let {
ref = $bindable(null), ref = $bindable(null),
class: className, class: className,
sideOffset = 4, sideOffset = 4,
align = "center", align = 'center',
portalProps, portalProps,
...restProps ...restProps
}: PopoverPrimitive.ContentProps & { }: PopoverPrimitive.ContentProps & {
portalProps?: WithoutChildrenOrChild<ComponentProps<typeof PopoverPortal>>; portalProps?: WithoutChildrenOrChild<ComponentProps<typeof PopoverPortal>>;
} = $props(); } = $props();
</script> </script>
<PopoverPortal {...portalProps}> <PopoverPortal {...portalProps}>
<PopoverPrimitive.Content <PopoverPrimitive.Content
bind:ref bind:ref
data-slot="popover-content" data-slot="popover-content"
{sideOffset} {sideOffset}
{align} {align}
class={cn( class={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-end-2 data-[side=right]:slide-in-from-start-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--bits-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden", 'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-end-2 data-[side=right]:slide-in-from-start-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--bits-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden',
className className
)} )}
{...restProps} {...restProps}
/> />
</PopoverPortal> </PopoverPortal>
@@ -1,7 +1,7 @@
<script lang="ts"> <script lang="ts">
import { Popover as PopoverPrimitive } from "bits-ui"; import { Popover as PopoverPrimitive } from 'bits-ui';
let { ...restProps }: PopoverPrimitive.PortalProps = $props(); let { ...restProps }: PopoverPrimitive.PortalProps = $props();
</script> </script>
<PopoverPrimitive.Portal {...restProps} /> <PopoverPrimitive.Portal {...restProps} />
@@ -1,17 +1,17 @@
<script lang="ts"> <script lang="ts">
import { cn } from "$lib/utils.js"; import { cn } from '$lib/utils.js';
import { Popover as PopoverPrimitive } from "bits-ui"; import { Popover as PopoverPrimitive } from 'bits-ui';
let { let {
ref = $bindable(null), ref = $bindable(null),
class: className, class: className,
...restProps ...restProps
}: PopoverPrimitive.TriggerProps = $props(); }: PopoverPrimitive.TriggerProps = $props();
</script> </script>
<PopoverPrimitive.Trigger <PopoverPrimitive.Trigger
bind:ref bind:ref
data-slot="popover-trigger" data-slot="popover-trigger"
class={cn("", className)} class={cn('', className)}
{...restProps} {...restProps}
/> />
+2 -2
View File
@@ -1,7 +1,7 @@
<script lang="ts"> <script lang="ts">
import { Popover as PopoverPrimitive } from "bits-ui"; import { Popover as PopoverPrimitive } from 'bits-ui';
let { open = $bindable(false), ...restProps }: PopoverPrimitive.RootProps = $props(); let { open = $bindable(false), ...restProps }: PopoverPrimitive.RootProps = $props();
</script> </script>
<PopoverPrimitive.Root bind:open {...restProps} /> <PopoverPrimitive.Root bind:open {...restProps} />
+84 -47
View File
@@ -7,7 +7,7 @@
custom_theme_volume, custom_theme_volume,
platform, platform,
} from '$lib/global'; } from '$lib/global';
import { DEFAULT_THEME_ICON_SET } from '$lib/themeIcons'; import { DEFAULT_THEME_ICON_SET } from '$lib/theme/themeIcons';
import { reduceAnimations } from '$lib/userSettings'; import { reduceAnimations } from '$lib/userSettings';
import Minimize from '@lucide/svelte/icons/minus'; import Minimize from '@lucide/svelte/icons/minus';
import Close from '@lucide/svelte/icons/x'; import Close from '@lucide/svelte/icons/x';
@@ -16,6 +16,34 @@
const iconSet = $derived($active_custom_theme?.definition?.iconSet ?? DEFAULT_THEME_ICON_SET); const iconSet = $derived($active_custom_theme?.definition?.iconSet ?? DEFAULT_THEME_ICON_SET);
let volumeOpen = $state(false);
let volumeDragging = $state(false);
let volumeControl: HTMLDivElement | undefined = $state();
function openVolume() {
volumeOpen = true;
}
function closeVolume() {
if (!volumeDragging) volumeOpen = false;
}
function startVolumeDrag(event: PointerEvent) {
if (event.button !== 0) return;
volumeDragging = true;
volumeOpen = true;
}
function endVolumeDrag(event: PointerEvent) {
if (!volumeDragging) return;
volumeDragging = false;
const element = document.elementFromPoint(event.clientX, event.clientY);
if (!element || !volumeControl?.contains(element)) {
volumeOpen = false;
}
}
onMount(() => { onMount(() => {
const appWindow = getCurrentWindow(); const appWindow = getCurrentWindow();
@@ -26,58 +54,67 @@
}); });
</script> </script>
<div data-tauri-drag-region class="titlebar z-[100]" class:macos-window={$platform === 'macos'}> <svelte:window onpointerup={endVolumeDrag} onpointercancel={endVolumeDrag} />
{#if $custom_theme_audio_playing}
{#if $custom_theme_audio_playing}
<div class="relative flex items-center justify-center group">
<div class="relative flex items-center justify-center p-1 cursor-pointer">
<div
class="absolute inset-0 bg-background rounded
scale-80 opacity-0
group-hover:opacity-100
group-hover:scale-100
{$reduceAnimations ? '' : 'transition-all duration-200 ease-out'}"
></div>
{#if $custom_theme_volume > 0.7} <div data-tauri-drag-region class="titlebar z-[100]" class:macos-window={$platform === 'macos'}>
<ThemeIcon name="volume" set={iconSet} class="z-10 pointer-events-none" size={14} /> {#if $custom_theme_audio_playing || ($active_custom_theme && $active_custom_theme.name !== 'Default')}
{:else if $custom_theme_volume >= 0.15} <div
<ThemeIcon name="volume-low" set={iconSet} class="z-10 pointer-events-none" size={14} /> class="relative flex items-center justify-center group"
{:else if $custom_theme_volume > 0} role="group"
<ThemeIcon name="volume-low" set={iconSet} class="z-10 pointer-events-none" size={14} /> aria-label="Theme volume"
{:else} bind:this={volumeControl}
<ThemeIcon name="volume-off" set={iconSet} class="z-10 pointer-events-none" size={14} /> onpointerenter={openVolume}
{/if} onpointerleave={closeVolume}
</div> >
<div class="relative flex items-center justify-center p-1 cursor-pointer">
<div
class="absolute inset-0 bg-background rounded
scale-80 opacity-0
group-hover:opacity-100
group-hover:scale-100
{$reduceAnimations ? '' : 'transition-all duration-200 ease-out'}"
></div>
{#if $custom_theme_volume > 0.7}
<ThemeIcon name="volume" set={iconSet} class="z-10 pointer-events-none" size={14} />
{:else if $custom_theme_volume >= 0.15}
<ThemeIcon name="volume-low" set={iconSet} class="z-10 pointer-events-none" size={14} />
{:else if $custom_theme_volume > 0}
<ThemeIcon name="volume-low" set={iconSet} class="z-10 pointer-events-none" size={14} />
{:else}
<ThemeIcon name="volume-off" set={iconSet} class="z-10 pointer-events-none" size={14} />
{/if}
</div>
<div
class="absolute top-full right-0 translate-x-[7px]
{volumeOpen
? 'opacity-100 visible pointer-events-auto translate-y-0'
: 'opacity-0 invisible pointer-events-none -translate-y-2'}
{$reduceAnimations ? '' : 'transition-all duration-200 ease-out'}
z-50"
>
<div class="h-2 w-full"></div>
<div <div
class="absolute top-full right-0 translate-x-[7px] class="flex items-center justify-center h-[120px] w-[35px]
opacity-0 invisible pointer-events-none -translate-y-2 bg-black/20 backdrop-blur-sm border border-white/10 rounded-xl"
group-hover:opacity-100 group-hover:visible group-hover:pointer-events-auto group-hover:translate-y-0
{$reduceAnimations ? '' : 'transition-all duration-200 ease-out'}
z-50"
> >
<div class="h-2 w-full"></div> <input
type="range"
<div min="0"
class="flex items-center justify-center h-[120px] w-[35px] max="1"
bg-black/20 backdrop-blur-sm border border-white/10 rounded-xl" step="0.01"
> bind:value={$custom_theme_volume}
<input onpointerdown={startVolumeDrag}
type="range" oninput={() => {
min="0" config.value<number>('volume').set($custom_theme_volume);
max="1" }}
step="0.01" class="volume-slider"
bind:value={$custom_theme_volume} />
oninput={() => {
config.value<number>('volume').set($custom_theme_volume);
}}
class="volume-slider"
/>
</div>
</div> </div>
</div> </div>
{/if} </div>
{/if} {/if}
<div class="relative flex items-center justify-center p-1 group" id="titlebar-minimize"> <div class="relative flex items-center justify-center p-1 group" id="titlebar-minimize">
<div <div
+19 -19
View File
@@ -1,22 +1,22 @@
import Root from "./tooltip.svelte"; import Arrow from './tooltip-arrow.svelte';
import Content from "./tooltip-content.svelte"; import Content from './tooltip-content.svelte';
import Trigger from "./tooltip-trigger.svelte"; import Portal from './tooltip-portal.svelte';
import Provider from "./tooltip-provider.svelte"; import Provider from './tooltip-provider.svelte';
import Portal from "./tooltip-portal.svelte"; import Trigger from './tooltip-trigger.svelte';
import Arrow from "./tooltip-arrow.svelte"; import Root from './tooltip.svelte';
export { export {
Root, Root,
Content, Content,
Trigger, Trigger,
Provider, Provider,
Portal, Portal,
Arrow, Arrow,
// //
Root as Tooltip, Root as Tooltip,
Content as TooltipContent, Content as TooltipContent,
Trigger as TooltipTrigger, Trigger as TooltipTrigger,
Provider as TooltipProvider, Provider as TooltipProvider,
Portal as TooltipPortal, Portal as TooltipPortal,
Arrow as TooltipArrow, Arrow as TooltipArrow,
}; };
@@ -1,29 +1,29 @@
<script lang="ts"> <script lang="ts">
import { Tooltip as TooltipPrimitive } from "bits-ui"; import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';
import TooltipPortal from "./tooltip-portal.svelte"; import TooltipPortal from './tooltip-portal.svelte';
import { cn, type WithoutChildrenOrChild } from "$lib/utils.js"; import { Tooltip as TooltipPrimitive } from 'bits-ui';
import type { ComponentProps } from "svelte"; import type { ComponentProps } from 'svelte';
let { let {
ref = $bindable(null), ref = $bindable(null),
class: className, class: className,
sideOffset = 6, sideOffset = 6,
portalProps, portalProps,
...restProps ...restProps
}: TooltipPrimitive.ContentProps & { }: TooltipPrimitive.ContentProps & {
portalProps?: WithoutChildrenOrChild<ComponentProps<typeof TooltipPortal>>; portalProps?: WithoutChildrenOrChild<ComponentProps<typeof TooltipPortal>>;
} = $props(); } = $props();
</script> </script>
<TooltipPortal {...portalProps}> <TooltipPortal {...portalProps}>
<TooltipPrimitive.Content <TooltipPrimitive.Content
bind:ref bind:ref
data-slot="tooltip-content" data-slot="tooltip-content"
{sideOffset} {sideOffset}
class={cn( class={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-end-2 data-[side=right]:slide-in-from-start-2 data-[side=top]:slide-in-from-bottom-2 z-50 overflow-hidden rounded-md border border-border px-3 py-1.5 text-xs shadow-md", 'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-end-2 data-[side=right]:slide-in-from-start-2 data-[side=top]:slide-in-from-bottom-2 z-50 overflow-hidden rounded-md border border-border px-3 py-1.5 text-xs shadow-md',
className className
)} )}
{...restProps} {...restProps}
/> />
</TooltipPortal> </TooltipPortal>
@@ -1,7 +1,7 @@
<script lang="ts"> <script lang="ts">
import { Tooltip as TooltipPrimitive } from "bits-ui"; import { Tooltip as TooltipPrimitive } from 'bits-ui';
let { ...restProps }: TooltipPrimitive.PortalProps = $props(); let { ...restProps }: TooltipPrimitive.PortalProps = $props();
</script> </script>
<TooltipPrimitive.Portal {...restProps} /> <TooltipPrimitive.Portal {...restProps} />
@@ -1,13 +1,7 @@
<script lang="ts"> <script lang="ts">
import { Tooltip as TooltipPrimitive } from "bits-ui"; import { Tooltip as TooltipPrimitive } from 'bits-ui';
let { let { delayDuration = 100, ...restProps }: TooltipPrimitive.ProviderProps = $props();
delayDuration = 100,
...restProps
}: TooltipPrimitive.ProviderProps = $props();
</script> </script>
<TooltipPrimitive.Provider <TooltipPrimitive.Provider {delayDuration} {...restProps} />
{delayDuration}
{...restProps}
/>
@@ -1,17 +1,17 @@
<script lang="ts"> <script lang="ts">
import { cn } from "$lib/utils.js"; import { cn } from '$lib/utils.js';
import { Tooltip as TooltipPrimitive } from "bits-ui"; import { Tooltip as TooltipPrimitive } from 'bits-ui';
let { let {
ref = $bindable(null), ref = $bindable(null),
class: className, class: className,
...restProps ...restProps
}: TooltipPrimitive.TriggerProps = $props(); }: TooltipPrimitive.TriggerProps = $props();
</script> </script>
<TooltipPrimitive.Trigger <TooltipPrimitive.Trigger
bind:ref bind:ref
data-slot="tooltip-trigger" data-slot="tooltip-trigger"
class={cn("", className)} class={cn('', className)}
{...restProps} {...restProps}
/> />
+2 -2
View File
@@ -1,7 +1,7 @@
<script lang="ts"> <script lang="ts">
import { Tooltip as TooltipPrimitive } from "bits-ui"; import { Tooltip as TooltipPrimitive } from 'bits-ui';
let { open = $bindable(false), ...restProps }: TooltipPrimitive.RootProps = $props(); let { open = $bindable(false), ...restProps }: TooltipPrimitive.RootProps = $props();
</script> </script>
<TooltipPrimitive.Root bind:open {...restProps} /> <TooltipPrimitive.Root bind:open {...restProps} />
+6 -2
View File
@@ -125,8 +125,8 @@ export const DISCORD_PRESENCE_PRESETS: DiscordPresencePreset[] = [
}, },
button2: { button2: {
enabled: true, enabled: true,
label: 'View Profile', label: 'Join EZPPFarm',
url: '{profileUrl}', url: 'https://ez-pp.farm/discord',
}, },
}, },
}, },
@@ -247,6 +247,8 @@ export type IdlePresenceParams = {
rank?: number | string; rank?: number | string;
pp?: number | string; pp?: number | string;
accuracy?: number | string; accuracy?: number | string;
mode?: string;
action?: string;
}; };
export type PlayingPresenceParams = { export type PlayingPresenceParams = {
@@ -282,6 +284,8 @@ export const pushIdlePresenceFromConfig = async (
rank: params?.rank, rank: params?.rank,
pp: params?.pp, pp: params?.pp,
accuracy: params?.accuracy, accuracy: params?.accuracy,
mode: params?.mode,
action: params?.action ?? 'In Launcher',
version: params?.version, version: params?.version,
profileUrl: params?.user?.id ? `https://ez-pp.farm/u/${params.user.id}` : 'https://ez-pp.farm', profileUrl: params?.user?.id ? `https://ez-pp.farm/u/${params.user.id}` : 'https://ez-pp.farm',
}; };
+1 -1
View File
@@ -1,6 +1,6 @@
import { browser } from '$app/environment'; import { browser } from '$app/environment';
import { ezppfarm } from './api/ezpp'; import { ezppfarm } from './api/ezpp';
import type { Theme } from './themes'; import type { Theme } from './theme/themes';
import type { Release } from './types'; import type { Release } from './types';
import { setGlobalVolume } from './utils'; import { setGlobalVolume } from './utils';
import type { Component } from 'svelte'; import type { Component } from 'svelte';
+101
View File
@@ -0,0 +1,101 @@
import { getAuthHeaders, getThemesServiceUrl } from './theme/communityThemes';
export type NotificationType =
| 'theme_hidden'
| 'theme_restored'
| 'theme_taken_down'
| 'report_resolved'
| 'report_dismissed'
| 'system';
export interface UserNotification {
id: number;
type: string;
title: string;
message: string;
themeId: string | null;
themeName: string | null;
actorId: number | null;
actorName?: string | null;
readAt: string | null;
createdAt: string;
}
export interface NotificationsResponse {
notifications: UserNotification[];
unreadCount: number;
hasMore: boolean;
}
async function requireAuthHeaders(): Promise<Record<string, string>> {
const headers = await getAuthHeaders();
if (!headers['X-Username'] || !headers['X-Password']) {
throw new Error('Please log in to view notifications.');
}
return headers;
}
async function parseError(res: Response, fallback: string): Promise<Error> {
const errorJson = (await res.json().catch(() => ({}))) as { error?: string };
return new Error(errorJson.error || `${fallback} (HTTP ${res.status})`);
}
export async function fetchNotifications(options?: {
limit?: number;
beforeId?: number;
}): Promise<NotificationsResponse> {
const baseUrl = await getThemesServiceUrl();
const headers = await requireAuthHeaders();
const url = new URL(`${baseUrl}/v1/notifications`);
if (options?.limit) url.searchParams.set('limit', String(options.limit));
if (options?.beforeId) url.searchParams.set('beforeId', String(options.beforeId));
const res = await fetch(url.toString(), { headers });
if (!res.ok) throw await parseError(res, 'Failed to load notifications');
return (await res.json()) as NotificationsResponse;
}
export async function fetchUnreadNotificationCount(): Promise<number> {
const baseUrl = await getThemesServiceUrl();
const headers = await requireAuthHeaders();
const res = await fetch(`${baseUrl}/v1/notifications/unread-count`, { headers });
if (!res.ok) throw await parseError(res, 'Failed to load notification count');
const data = (await res.json()) as { count?: number };
return Number(data.count ?? 0);
}
export async function markNotificationRead(notificationId: number): Promise<void> {
const baseUrl = await getThemesServiceUrl();
const headers = await requireAuthHeaders();
const res = await fetch(`${baseUrl}/v1/notifications/${notificationId}/read`, {
method: 'PATCH',
headers,
});
if (!res.ok) throw await parseError(res, 'Failed to update notification');
}
export async function markAllNotificationsRead(): Promise<void> {
const baseUrl = await getThemesServiceUrl();
const headers = await requireAuthHeaders();
const res = await fetch(`${baseUrl}/v1/notifications/read-all`, {
method: 'POST',
headers,
});
if (!res.ok) throw await parseError(res, 'Failed to update notifications');
}
export async function sendSystemAnnouncement(options: {
title: string;
message: string;
audience?: 'all' | 'staff';
}): Promise<{ recipients: number }> {
const baseUrl = await getThemesServiceUrl();
const headers = await requireAuthHeaders();
const res = await fetch(`${baseUrl}/v1/notifications/announce`, {
method: 'POST',
headers: { ...headers, 'Content-Type': 'application/json' },
body: JSON.stringify(options),
});
if (!res.ok) throw await parseError(res, 'Failed to send announcement');
return (await res.json()) as { recipients: number };
}
+2 -2
View File
@@ -88,8 +88,8 @@ export const getSkin = async (folder: string) => {
}; };
export const runUpdater = async (folder: string) => await invoke('run_osu_updater', { folder }); export const runUpdater = async (folder: string) => await invoke('run_osu_updater', { folder });
export const runOsu = async (folder: string, patch: boolean) => export const runOsu = async (folder: string, patch: boolean, gameOptimization: boolean = false) =>
await invoke('run_osu', { folder, patch }); await invoke('run_osu', { folder, patch, gameOptimization });
export const getEZPPLauncherStreams = async () => { export const getEZPPLauncherStreams = async () => {
const resp = await betterFetch<{ streams: string[] }>(updateUrl, { const resp = await betterFetch<{ streams: string[] }>(updateUrl, {
+9 -9
View File
@@ -6,15 +6,15 @@ export type PresenceButtonPayload = {
}; };
export type PresenceActivityPayload = { export type PresenceActivityPayload = {
state?: string; state: string;
details?: string; details: string;
largeImageKey?: string; largeImageKey: string;
largeImageText?: string; largeImageText: string;
smallImageKey?: string | null; smallImageKey: string | null;
smallImageText?: string | null; smallImageText: string | null;
button1?: PresenceButtonPayload | null; button1: PresenceButtonPayload | null;
button2?: PresenceButtonPayload | null; button2: PresenceButtonPayload | null;
showTimestamp?: boolean; showTimestamp: boolean;
}; };
export const connect = async () => await invoke('presence_connect'); export const connect = async () => await invoke('presence_connect');
+10
View File
@@ -0,0 +1,10 @@
import { SvelteMap, SvelteSet } from 'svelte/reactivity';
/**
* Install progress lives outside the workshop component because switching to
* the Installed tab unmounts it. Keeping the state here lets the workshop show
* the current progress again when it is remounted, while the in-flight
* download keeps running.
*/
export const activeThemeDownloads = new SvelteSet<string>();
export const themeDownloadProgress = new SvelteMap<string, number>();
File diff suppressed because it is too large. Load diff
File renamed without changes.
File renamed without changes.
@@ -1,8 +1,8 @@
import { currentUserInfo } from './data'; import { currentUserInfo } from '../data';
import { launcherVersion, onlineFriends, osuBuild, osuStream, serverPing } from './global'; import { launcherVersion, onlineFriends, osuBuild, osuStream, serverPing } from '../global';
import { currentUser } from '../userAuthentication';
import { themeClockValues } from './themeClock'; import { themeClockValues } from './themeClock';
import type { ThemeV2DataField, ThemeV2DataMode } from './themeV2'; import type { ThemeV2DataField, ThemeV2DataMode } from './themeV2';
import { currentUser } from './userAuthentication';
import { derived } from 'svelte/store'; import { derived } from 'svelte/store';
export type ThemeDataStats = { export type ThemeDataStats = {
@@ -177,7 +177,7 @@ export const resolveThemeDataValue = (
const { global, theme, screen, mode = 'osu', now = new Date() } = context; const { global, theme, screen, mode = 'osu', now = new Date() } = context;
const stats = global.user.stats[mode]; const stats = global.user.stats[mode];
let value = ''; let value: string;
switch (field) { switch (field) {
case 'user.name': case 'user.name':
value = global.user.name; value = global.user.name;
+8
View File
@@ -0,0 +1,8 @@
import { SvelteMap } from 'svelte/reactivity';
/**
* Open state for accordion sections in the current theme-editor WebView session.
* This module is re-evaluated when the editor window closes, so the state is not
* persisted across app launches.
*/
export const themeEditorSectionOpen = new SvelteMap<string, boolean>();
File renamed without changes.
@@ -1,10 +1,5 @@
import { THEME_ICON_BODIES, type ThemeIconBody } from './themeIconData'; import { THEME_ICON_BODIES, type ThemeIconBody } from './themeIconData';
import { import { DEFAULT_THEME_ICON_SET, THEME_ICON_NAMES, type ThemeIconSet } from './themeIcons';
DEFAULT_THEME_ICON_SET,
THEME_ICON_NAMES,
type ThemeIconName,
type ThemeIconSet,
} from './themeIcons';
import lucideCollection from '@iconify-json/lucide/icons.json'; import lucideCollection from '@iconify-json/lucide/icons.json';
import phCollection from '@iconify-json/ph/icons.json'; import phCollection from '@iconify-json/ph/icons.json';
import tablerCollection from '@iconify-json/tabler/icons.json'; import tablerCollection from '@iconify-json/tabler/icons.json';
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff. Show more