Compare commits
61
Commits
a2b03d3014
...
themes-v2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
756638ecf1 | ||
|
|
34e93ee29b | ||
|
|
e1c04c4f5b | ||
|
|
cb117826c7 | ||
|
|
0e295c8425 | ||
|
|
746524d27e | ||
|
|
660fb557a6 | ||
|
|
575da8504a
|
||
|
|
8616253065 | ||
|
|
0105c5975a
|
||
|
|
c2fd265b49 | ||
|
|
687ab26752 | ||
|
|
9d312fb3bb | ||
|
|
ef214d424c | ||
|
|
d4be3f845d | ||
|
|
83b007818d | ||
|
|
cfb6ec8cce | ||
|
|
323a6f18af | ||
|
|
d56ed9d786 | ||
|
|
51f5fa3e46 | ||
|
|
07cbfa39a6 | ||
|
|
11aefee7ed | ||
|
|
5eea428802 | ||
|
|
760bd9a283 | ||
|
|
47c022642f | ||
|
|
5613c3be25 | ||
|
|
4d57184b73 | ||
|
|
d555ac366f | ||
|
|
918f8651dd | ||
|
|
4b039c9b79 | ||
|
|
809fca6f29 | ||
|
|
0025313c4d | ||
|
|
6b1ed5aa1a | ||
|
|
fc128b7178 | ||
|
|
520ad5c4f1 | ||
|
|
93536af6a6 | ||
|
|
3ef59f94ee | ||
|
|
ebc5fbf9c4 | ||
|
|
1f3fa026ce | ||
|
|
9b4158410d | ||
|
|
1bf8034126 | ||
|
|
a423850dc9 | ||
|
|
a051c021d7 | ||
|
|
4a6e8c5cab | ||
|
|
2f0b034c5e | ||
|
|
f198e2376c | ||
|
|
c1664ed5bf | ||
|
|
0b4af5a4d4 | ||
|
|
e31d92ed3c | ||
|
|
8816852fd9 | ||
|
|
d38250a5e4 | ||
|
|
ad3fe7c586 | ||
|
|
a025f9b285 | ||
|
|
ce572de0d2 | ||
|
|
e861cda23d | ||
|
|
7332618e85 | ||
|
|
62b31169cc | ||
|
|
a75e723416 | ||
|
|
45962242aa | ||
|
|
ce9112f9e2 | ||
|
|
e52399911c |
No files matched your search
@@ -1,7 +1,7 @@
|
||||
# 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.
|
||||
It enhances the osu! experience with quality-of-life features and integration specifically designed for the EZPPFarm community.
|
||||
**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, 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
|
||||
|
||||
- [x] Automatically updates osu! before launching
|
||||
- [x] Automatically start/stop the OpenTabletDriver Daemon (Windows)
|
||||
- [x] Automatic ingame login
|
||||
- [x] Patches the osu! client to show misses in Relax and Autopilot (Windows, Linux and macOS via Wine)
|
||||
- [x] Displays your EZPPFarm stats in the launcher
|
||||
- [x] Shows the number of imported beatmapsets
|
||||
- [x] Shows the number of imported skins
|
||||
- [x] Displays ping to the EZPPFarm server
|
||||
- [x] Discord Rich Presence
|
||||
- [x] Performance Display Overlay (currently in experimental patcher release 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
|
||||
- [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
|
||||
### Game & Server Integration
|
||||
|
||||
- [x] **Direct Server Launch**: Launches osu! directly with `-devserver ez-pp.farm`, bypassing osu! updater loops and preserving launch parameters.
|
||||
- [x] **Automatic In-Game Login**: Automatically signs into your EZPPFarm account upon game boot.
|
||||
- [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] **Live Player Stats**: Displays rank, PP, accuracy, playcount, and server latency directly on the launcher dashboard.
|
||||
- [x] **Library Indexing**: Automatically counts imported beatmapsets and skins.
|
||||
- [x] **OpenTabletDriver Integration**: Automatically starts and stops the OpenTabletDriver daemon on launch/exit (Windows only).
|
||||
- [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**: In-game HUD overlay (available in the experimental patcher stream).
|
||||
|
||||
### Visual Theme Engine v2 & In-App Studio
|
||||
|
||||
- [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
|
||||
|
||||
| Platform | Status |
|
||||
| -------- | ------------------------------------------------------ |
|
||||
| Windows | ✅ Supported |
|
||||
| macOS | 🕧 Partially supported (via Wineskin/Whisky/CrossOver) |
|
||||
| Linux | 🕧 Partially supported (via osu-winello) |
|
||||
| Platform | Status | Runtime / Environment |
|
||||
| -------- | ---------------------- | ---------------------------------------------------------- |
|
||||
| Windows | ✅ Supported | Native Win32 |
|
||||
| macOS | ✅ Supported | Wine wrapper (Wineskin, Whisky, CrossOver, or system Wine) |
|
||||
| Linux | 🕧 Partially Supported | Wine / Proton (via osu-winello / wmctrl) |
|
||||
|
||||
> **Windows** remains the fully supported platform. OpenTabletDriver is Windows-only. On macOS,
|
||||
> 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.
|
||||
> **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.
|
||||
|
||||
---
|
||||
|
||||
## 🪵 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 |
|
||||
| -------------- | -------------------------------------------------------------- |
|
||||
| `launcher.log` | Launcher lifecycle, webview console output and uncaught errors |
|
||||
| `osu.log` | osu! and osu! updater output, including stdout/stderr |
|
||||
| `patcher.log` | Patcher output, including stdout/stderr |
|
||||
- **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`).
|
||||
- **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.
|
||||
- **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.
|
||||
- **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
|
||||
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
|
||||
copy a plain-text support report or reopen the setup wizard for a guided repair.
|
||||
### 🐧 Linux (Partially Supported)
|
||||
|
||||
Linux support is functional but partial, relying on external community tools rather than built-in prefix management:
|
||||
|
||||
- **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
|
||||
|
||||
### Requirements
|
||||
### Prerequisites
|
||||
|
||||
- **Rust** (installed via [rustup](https://rustup.rs/) – recommended for Windows)
|
||||
- **Cargo** (comes with rustup)
|
||||
- **[Rust & Cargo](https://rustup.rs/)** (Rust 2024 edition)
|
||||
- **[Bun](https://bun.sh/)** (JavaScript runtime and package manager)
|
||||
- **[CMake](https://cmake.org/download/)**
|
||||
- **[Bun](https://bun.sh/)** (JavaScript runtime)
|
||||
- On macOS: **Xcode Command Line Tools** (`xcode-select --install`)
|
||||
- Platform tooling:
|
||||
- **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
|
||||
# Install all dependencies
|
||||
bun i
|
||||
# 1. Clone the repository
|
||||
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
|
||||
```
|
||||
|
||||
After building, the launcher executable will be located at:
|
||||
The compiled release packages will be generated at:
|
||||
|
||||
```
|
||||
# Windows
|
||||
@@ -116,50 +177,69 @@ src-tauri/target/release/ezpplauncher.exe
|
||||
# macOS
|
||||
src-tauri/target/release/bundle/macos/EZPPLauncher.app
|
||||
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)
|
||||
├── src-tauri/ # Backend (Rust)
|
||||
│ ├── src/macos.rs # Wine/Wineskin support for macOS
|
||||
│ ├── tauri.conf.json # Tauri configuration
|
||||
│ └── tauri.macos.conf.json # macOS bundle targets (app + dmg)
|
||||
├── package.json # Bun project config
|
||||
EZPPLauncher/
|
||||
├── src/ # Frontend application (Svelte 5, Tailwind CSS)
|
||||
│ ├── lib/
|
||||
│ │ ├── components/
|
||||
│ │ │ ├── presence/ # Discord Rich Presence studio & preview
|
||||
│ │ │ ├── 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
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎨 Launcher Themes
|
||||
## 📄 License
|
||||
|
||||
By default, the launcher includes several downloadable themes. Themes can be created
|
||||
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.
|
||||
This project is licensed under the [GNU General Public License v3.0](LICENSE.md).
|
||||
+16
-2
@@ -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
|
||||
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 |
|
||||
| ----------------------- | ------------------------------------------------- | ---------------------------------------------- |
|
||||
@@ -196,12 +198,24 @@ clamped to `0`–`1`.
|
||||
{ "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.
|
||||
- `speed` is clamped to `0.2`–`3`.
|
||||
- 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
|
||||
|
||||
```json
|
||||
|
||||
@@ -44,6 +44,7 @@ export default ts.config(
|
||||
{
|
||||
rules: {
|
||||
'no-empty': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'error',
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'error',
|
||||
{ argsIgnorePattern: '^_', varsIgnorePattern: '^\\$\\$(Props|Events|Slots|Generic)$' },
|
||||
|
||||
+5
-2
@@ -1,11 +1,14 @@
|
||||
{
|
||||
"name": "ezpplauncher",
|
||||
"version": "3.2.7",
|
||||
"version": "3.3.0",
|
||||
"description": "",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"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:build": "vite build && exit 0",
|
||||
"tauri:build": "tauri build",
|
||||
|
||||
@@ -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']);
|
||||
@@ -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 { 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);
|
||||
console.log(
|
||||
`Generated ${THEME_ICON_NAMES.length} semantic icons for ${Object.keys(collectionPaths).length} sets.`
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
Generated
+2
-1
@@ -1266,12 +1266,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ezpplauncher"
|
||||
version = "3.2.7"
|
||||
version = "3.3.0"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"anyhow",
|
||||
"base64 0.22.1",
|
||||
"byteorder",
|
||||
"flate2",
|
||||
"futures-util",
|
||||
"hardware-id",
|
||||
"hex",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ezpplauncher"
|
||||
version = "3.2.7"
|
||||
version = "3.3.0"
|
||||
description = "EZPPLauncher redefined."
|
||||
authors = ["HorizonCode"]
|
||||
edition = "2024"
|
||||
@@ -56,6 +56,7 @@ aes-gcm = "0.10.3"
|
||||
base64 = "0.22.1"
|
||||
sha2 = "0.11.0"
|
||||
thiserror = "2.0.18"
|
||||
flate2 = "1.0"
|
||||
tauri-plugin-log = "2"
|
||||
log = "0.4"
|
||||
time = { version = "0.3", features = ["local-offset"] }
|
||||
|
||||
@@ -32,6 +32,21 @@
|
||||
},
|
||||
{
|
||||
"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": "$TEMP"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/*"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/**/*"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -60,6 +90,21 @@
|
||||
},
|
||||
{
|
||||
"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": "$TEMP"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/*"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/**/*"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -88,6 +148,21 @@
|
||||
},
|
||||
{
|
||||
"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": "$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": "$TEMP"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/*"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/**/*"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -130,6 +255,21 @@
|
||||
},
|
||||
{
|
||||
"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": "$TEMP"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/*"
|
||||
},
|
||||
{
|
||||
"path": "$TEMP/**/*"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+574
-76
@@ -3,7 +3,7 @@ use hardware_id::get_id;
|
||||
use reqwest::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
@@ -86,11 +86,186 @@ pub fn file_size(path: String) -> Option<u64> {
|
||||
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]
|
||||
pub fn get_hwid() -> String {
|
||||
get_id()
|
||||
.unwrap_or("recorderinsandybridge".to_string())
|
||||
.into()
|
||||
get_id().unwrap_or("recorderinsandybridge".to_string())
|
||||
}
|
||||
|
||||
/// 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)
|
||||
.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 {
|
||||
platform: std::env::consts::OS.to_string(),
|
||||
os_version: System::long_os_version(),
|
||||
@@ -374,8 +551,9 @@ pub async fn get_skins_count(folder: String) -> Option<u64> {
|
||||
let mut count = 0;
|
||||
if let Ok(mut entries) = fs::read_dir(skins_folder).await {
|
||||
while let Ok(Some(entry)) = entries.next_entry().await {
|
||||
if let Ok(ft) = entry.file_type().await {
|
||||
if ft.is_dir() {
|
||||
if let Ok(ft) = entry.file_type().await
|
||||
&& ft.is_dir()
|
||||
{
|
||||
let dir_path = entry.path();
|
||||
let has_ini = tokio::fs::try_exists(dir_path.join("skin.ini"))
|
||||
.await
|
||||
@@ -389,7 +567,6 @@ pub async fn get_skins_count(folder: String) -> Option<u64> {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(count)
|
||||
}
|
||||
|
||||
@@ -561,12 +738,17 @@ pub async fn run_osu_updater(folder: String) -> Result<(), String> {
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn run_osu(folder: String, patch: bool) -> Result<(), String> {
|
||||
log::info!(target: "osu", "Launching osu! from {folder} (patch={patch})");
|
||||
pub async fn run_osu(
|
||||
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")]
|
||||
{
|
||||
return crate::macos::run_osu(&folder, patch).await;
|
||||
return crate::macos::run_osu(&folder, patch, optimize).await;
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
@@ -576,6 +758,18 @@ pub async fn run_osu(folder: String, patch: bool) -> Result<(), String> {
|
||||
#[cfg(windows)]
|
||||
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 = {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
@@ -613,6 +807,22 @@ pub async fn run_osu(folder: String, patch: bool) -> Result<(), String> {
|
||||
|
||||
if let Some(pid) = game_process.id() {
|
||||
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);
|
||||
|
||||
@@ -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}"),
|
||||
Err(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() {
|
||||
let data = fs::read(&file_path).await.map_err(|e| e.to_string())?;
|
||||
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());
|
||||
}
|
||||
} 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(())
|
||||
}
|
||||
|
||||
@@ -1090,24 +1329,24 @@ pub struct PresenceButton {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PresenceActivityPayload {
|
||||
pub state: Option<String>,
|
||||
pub details: Option<String>,
|
||||
pub large_image_key: Option<String>,
|
||||
pub large_image_text: Option<String>,
|
||||
pub small_image_key: Option<Option<String>>,
|
||||
pub small_image_text: Option<Option<String>>,
|
||||
pub button1: Option<Option<presence::PresenceButton>>,
|
||||
pub button2: Option<Option<presence::PresenceButton>>,
|
||||
pub show_timestamp: Option<bool>,
|
||||
pub state: String,
|
||||
pub details: String,
|
||||
pub large_image_key: String,
|
||||
pub large_image_text: String,
|
||||
pub small_image_key: Option<String>,
|
||||
pub small_image_text: Option<String>,
|
||||
pub button1: Option<presence::PresenceButton>,
|
||||
pub button2: Option<presence::PresenceButton>,
|
||||
pub show_timestamp: bool,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn presence_update_activity(activity: PresenceActivityPayload) {
|
||||
presence::update_activity(
|
||||
activity.state.as_deref(),
|
||||
activity.details.as_deref(),
|
||||
activity.large_image_key.as_deref(),
|
||||
activity.large_image_text.as_deref(),
|
||||
&activity.state,
|
||||
&activity.details,
|
||||
&activity.large_image_key,
|
||||
&activity.large_image_text,
|
||||
activity.small_image_key,
|
||||
activity.small_image_text,
|
||||
activity.button1,
|
||||
@@ -1448,6 +1687,125 @@ pub async fn download_and_extract_theme(
|
||||
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]
|
||||
pub async fn extract_theme(
|
||||
app: AppHandle,
|
||||
@@ -1584,8 +1942,9 @@ pub(crate) fn theme_root() -> Result<PathBuf, String> {
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||
fn loopback_theme_asset_base() -> String {
|
||||
if crate::theme_server::base_url().is_none() {
|
||||
if let Ok(root) = theme_root() {
|
||||
if crate::theme_server::base_url().is_none()
|
||||
&& let Ok(root) = theme_root()
|
||||
{
|
||||
match crate::theme_server::media_root() {
|
||||
Ok(media) => {
|
||||
if let Err(error) = crate::theme_server::start(root, media) {
|
||||
@@ -1597,7 +1956,6 @@ fn loopback_theme_asset_base() -> String {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::theme_server::base_url().unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -1605,7 +1963,7 @@ fn loopback_theme_asset_base() -> String {
|
||||
pub fn theme_asset_base() -> String {
|
||||
#[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")))]
|
||||
@@ -1619,7 +1977,7 @@ pub fn theme_preview_url(path: String) -> Result<String, String> {
|
||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||
{
|
||||
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")))]
|
||||
@@ -1732,17 +2090,27 @@ pub async fn optimize_theme_media(app: AppHandle, source_url: String) -> Result<
|
||||
}
|
||||
};
|
||||
|
||||
let _ = app.emit(
|
||||
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: 0.0,
|
||||
progress,
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
let original = source_url.clone();
|
||||
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
|
||||
.map_err(|error| format!("Theme media optimizer thread failed: {error}"))?
|
||||
@@ -1903,9 +2271,11 @@ async fn download_ffmpeg(app: &AppHandle) -> Result<PathBuf, String> {
|
||||
.await
|
||||
.map_err(|error| format!("Could not write the FFmpeg archive: {error}"))?;
|
||||
|
||||
if total > 0 {
|
||||
let percent = ((received.min(total) * 100) / total) as u8;
|
||||
if percent != last_percent {
|
||||
if let Some(percent) = (received.min(total) * 100)
|
||||
.checked_div(total)
|
||||
.map(|v| v as u8)
|
||||
&& percent != last_percent
|
||||
{
|
||||
last_percent = percent;
|
||||
let _ = app.emit(
|
||||
"theme-media-progress",
|
||||
@@ -1916,7 +2286,6 @@ async fn download_ffmpeg(app: &AppHandle) -> Result<PathBuf, String> {
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
file.flush()
|
||||
.await
|
||||
@@ -2005,13 +2374,82 @@ fn find_media_binary(name: &str) -> Option<PathBuf> {
|
||||
}
|
||||
|
||||
#[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,
|
||||
source: &Path,
|
||||
source_url: &str,
|
||||
cache_name: &str,
|
||||
destination: &Path,
|
||||
) -> Result<String, String> {
|
||||
on_progress: F,
|
||||
) -> Result<String, String>
|
||||
where
|
||||
F: Fn(f64) + Send + Sync,
|
||||
{
|
||||
use std::process::Command;
|
||||
|
||||
let probe = Command::new(ffmpeg)
|
||||
@@ -2023,7 +2461,7 @@ fn optimize_theme_media_blocking(
|
||||
let codec = probe_text.lines().find_map(|line| {
|
||||
let index = line.find("Video: ")?;
|
||||
line[index + 7..]
|
||||
.split(|character: char| character == ',' || character == ' ')
|
||||
.split([',', ' '])
|
||||
.next()
|
||||
.map(str::to_ascii_lowercase)
|
||||
});
|
||||
@@ -2035,6 +2473,17 @@ fn optimize_theme_media_blocking(
|
||||
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 _ = std::fs::remove_file(&temporary);
|
||||
|
||||
@@ -2044,6 +2493,7 @@ fn optimize_theme_media_blocking(
|
||||
source.display()
|
||||
);
|
||||
let started = std::time::Instant::now();
|
||||
on_progress(0.0);
|
||||
|
||||
let mut command = Command::new(ffmpeg);
|
||||
command.args(["-hide_banner", "-loglevel", "error", "-nostdin", "-y", "-i"]);
|
||||
@@ -2077,18 +2527,14 @@ fn optimize_theme_media_blocking(
|
||||
"mp4",
|
||||
]);
|
||||
command.arg(&temporary);
|
||||
let first = command.output();
|
||||
|
||||
let success = match first {
|
||||
Ok(output) if output.status.success() => true,
|
||||
Ok(output) => {
|
||||
let success = match run_ffmpeg_with_progress(command, duration_us, &on_progress) {
|
||||
Ok((true, _)) => true,
|
||||
Ok((false, stderr)) => {
|
||||
log::warn!(
|
||||
target: "launcher",
|
||||
"Hardware theme video encode failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
.chars()
|
||||
.take(500)
|
||||
.collect::<String>()
|
||||
stderr.chars().take(500).collect::<String>()
|
||||
);
|
||||
false
|
||||
}
|
||||
@@ -2132,16 +2578,14 @@ fn optimize_theme_media_blocking(
|
||||
"mp4",
|
||||
]);
|
||||
fallback.arg(&temporary);
|
||||
match fallback.output() {
|
||||
Ok(output) if output.status.success() => true,
|
||||
Ok(output) => {
|
||||
|
||||
match run_ffmpeg_with_progress(fallback, duration_us, &on_progress) {
|
||||
Ok((true, _)) => true,
|
||||
Ok((false, stderr)) => {
|
||||
log::warn!(
|
||||
target: "launcher",
|
||||
"Software theme video encode failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
.chars()
|
||||
.take(500)
|
||||
.collect::<String>()
|
||||
stderr.chars().take(500).collect::<String>()
|
||||
);
|
||||
false
|
||||
}
|
||||
@@ -2159,6 +2603,7 @@ fn optimize_theme_media_blocking(
|
||||
|
||||
std::fs::rename(&temporary, destination)
|
||||
.map_err(|error| format!("Could not store the optimized theme video: {error}"))?;
|
||||
on_progress(1.0);
|
||||
log::info!(
|
||||
target: "launcher",
|
||||
"Optimized theme video in {:.1}s: {}",
|
||||
@@ -2286,8 +2731,11 @@ pub async fn open_presence_editor(app: AppHandle) -> Result<(), String> {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let window =
|
||||
WebviewWindowBuilder::new(&app, "presence-editor", WebviewUrl::App("index.html".into()))
|
||||
let window = WebviewWindowBuilder::new(
|
||||
&app,
|
||||
"presence-editor",
|
||||
WebviewUrl::App("index.html".into()),
|
||||
)
|
||||
.title("EZPPLauncher — Discord Rich Presence Editor")
|
||||
.inner_size(1200.0, 800.0)
|
||||
.min_inner_size(980.0, 650.0)
|
||||
@@ -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}"))?
|
||||
.filter_map(|entry| entry.ok())
|
||||
.filter(|entry| entry.file_type().map(|kind| kind.is_dir()).unwrap_or(false))
|
||||
.filter_map(|entry| {
|
||||
.map(|entry| {
|
||||
let path = entry.path();
|
||||
let created_at = entry
|
||||
.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())
|
||||
.map(|duration| duration.as_millis() as u64)
|
||||
.unwrap_or(0);
|
||||
Some(ThemeBackupInfo {
|
||||
ThemeBackupInfo {
|
||||
label: entry.file_name().to_string_lossy().into_owned(),
|
||||
path: path.to_string_lossy().into_owned(),
|
||||
created_at,
|
||||
size: directory_size(&path),
|
||||
})
|
||||
}
|
||||
})
|
||||
.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)
|
||||
})
|
||||
.await
|
||||
@@ -2687,13 +3135,12 @@ fn collect_theme_asset_refs(value: &Value, assets: &mut HashSet<String>) {
|
||||
match value {
|
||||
Value::Object(object) => {
|
||||
for (key, value) in object {
|
||||
if key == "src" || key == "preview" {
|
||||
if let Some(src) = value.as_str() {
|
||||
if let Some(path) = theme_asset_reference(src) {
|
||||
if (key == "src" || key == "preview")
|
||||
&& let Some(src) = value.as_str()
|
||||
&& let Some(path) = theme_asset_reference(src)
|
||||
{
|
||||
assets.insert(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
collect_theme_asset_refs(value, assets);
|
||||
}
|
||||
}
|
||||
@@ -2788,6 +3235,9 @@ fn add_theme_folder_to_zip(
|
||||
|
||||
for entry in entries {
|
||||
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
|
||||
.file_type()
|
||||
.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 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() {
|
||||
// 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)?;
|
||||
continue;
|
||||
}
|
||||
@@ -2804,20 +3265,18 @@ fn add_theme_folder_to_zip(
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(filter) = asset_filter {
|
||||
if let Ok(asset_path) = entry_path.strip_prefix(&assets_root) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let relative = entry_path
|
||||
.strip_prefix(root)
|
||||
.map_err(|e| format!("Failed to build archive path: {e}"))?
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
|
||||
zip.start_file(relative, options)
|
||||
.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> {
|
||||
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(())
|
||||
}
|
||||
+26
-8
@@ -19,21 +19,22 @@ pub mod utils;
|
||||
use crate::{
|
||||
commands::{
|
||||
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,
|
||||
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_osu_skin, get_osu_version, get_platform, get_skins_count, has_net8, has_osuwinello,
|
||||
has_wmctrl, install_ezpp_launcher_update, installation_diagnostics,
|
||||
get_osu_skin, get_osu_version, get_platform, get_skins_count, has_net8,
|
||||
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,
|
||||
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,
|
||||
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,
|
||||
resolve_osu_folder, restore_theme_backup, run_open_tablet_driver, run_osu, run_osu_updater,
|
||||
presence_update_button, presence_update_status, presence_update_user, read_file_chunk, read_theme_info, replace_ui_files,
|
||||
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,
|
||||
stop_open_tablet_driver, theme_asset_base, theme_editor_context, theme_preview_url,
|
||||
valid_osu_folder,
|
||||
unlock_media_autoplay, valid_osu_folder,
|
||||
},
|
||||
state::AppState,
|
||||
};
|
||||
@@ -136,6 +137,12 @@ pub fn run() {
|
||||
if let Err(error) = macos::allow_media_autoplay(&window) {
|
||||
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(())
|
||||
@@ -186,8 +193,12 @@ pub fn run() {
|
||||
restore_theme_backup,
|
||||
extract_theme,
|
||||
download_and_extract_theme,
|
||||
download_and_extract_community_theme,
|
||||
save_theme_project,
|
||||
export_theme,
|
||||
hash_file_sha256,
|
||||
hash_theme_content,
|
||||
read_file_chunk,
|
||||
open_theme_folder,
|
||||
open_theme_editor,
|
||||
focus_theme_editor,
|
||||
@@ -212,6 +223,8 @@ pub fn run() {
|
||||
log_frontend,
|
||||
set_logging_enabled,
|
||||
open_logs_folder,
|
||||
reveal_window,
|
||||
unlock_media_autoplay,
|
||||
logging::list_log_bundles,
|
||||
logging::read_log_bundle
|
||||
])
|
||||
@@ -226,14 +239,19 @@ pub fn run() {
|
||||
// The content view can be replaced again while the webview is being
|
||||
// built, so re-apply the corner mask once the app is ready.
|
||||
#[cfg(target_os = "macos")]
|
||||
if let tauri::RunEvent::Ready = &event {
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
if let tauri::RunEvent::Ready = &event
|
||||
&& let Some(window) = app.get_webview_window("main") {
|
||||
if let Err(error) = macos::round_window(&window, 12.0) {
|
||||
log::warn!(target: "launcher", "Could not round the launcher window: {error}");
|
||||
}
|
||||
if let Err(error) = macos::allow_media_autoplay(&window) {
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+131
-24
@@ -393,7 +393,97 @@ pub struct LogBundleEntry {
|
||||
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]
|
||||
pub fn list_log_bundles() -> Result<Vec<LogBundleInfo>, String> {
|
||||
let dir = logs_directory();
|
||||
@@ -401,6 +491,7 @@ pub fn list_log_bundles() -> Result<Vec<LogBundleInfo>, String> {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let current = current_log_bundle(&dir);
|
||||
let mut bundles = fs::read_dir(&dir)
|
||||
.map_err(|error| format!("Could not read the logs folder: {error}"))?
|
||||
.filter_map(|entry| entry.ok())
|
||||
@@ -411,26 +502,23 @@ pub fn list_log_bundles() -> Result<Vec<LogBundleInfo>, String> {
|
||||
return None;
|
||||
}
|
||||
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 {
|
||||
path: path.to_string_lossy().into_owned(),
|
||||
name,
|
||||
size: metadata.len(),
|
||||
modified,
|
||||
modified: modified_millis(&metadata),
|
||||
})
|
||||
})
|
||||
.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)
|
||||
}
|
||||
|
||||
/// 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]
|
||||
pub fn read_log_bundle(path: String) -> Result<Vec<LogBundleEntry>, String> {
|
||||
let dir = logs_directory();
|
||||
@@ -441,6 +529,9 @@ pub fn read_log_bundle(path: String) -> Result<Vec<LogBundleEntry>, String> {
|
||||
if !requested.starts_with(&root) {
|
||||
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)
|
||||
.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;
|
||||
}
|
||||
|
||||
let mut bytes = Vec::new();
|
||||
entry
|
||||
.by_ref()
|
||||
.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,
|
||||
});
|
||||
let name = entry.name().to_string();
|
||||
let size = entry.size();
|
||||
entries.push(read_log_entry(name, &mut entry, size)?);
|
||||
}
|
||||
|
||||
entries.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
@@ -634,4 +714,31 @@ mod tests {
|
||||
drop(current);
|
||||
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();
|
||||
}
|
||||
}
|
||||
+617
-75
@@ -54,6 +54,41 @@ pub fn round_window(window: &tauri::WebviewWindow, radius: f64) -> Result<(), St
|
||||
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
|
||||
/// autoplay for anything with an audio track, which makes a theme's background
|
||||
/// 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::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
|
||||
.with_webview(|webview| unsafe {
|
||||
let webview = webview.inner() as *mut AnyObject;
|
||||
@@ -68,10 +111,23 @@ pub fn allow_media_autoplay(window: &tauri::WebviewWindow) -> Result<(), String>
|
||||
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() {
|
||||
return;
|
||||
} // WKAudiovisualMediaTypesNone. This is a public WKWebView setting.
|
||||
}
|
||||
|
||||
// WKAudiovisualMediaTypesNone. This is a public WKWebView setting.
|
||||
let _: () =
|
||||
msg_send![configuration, setMediaTypesRequiringUserActionForPlayback: 0usize];
|
||||
let current: usize = msg_send![configuration, mediaTypesRequiringUserActionForPlayback];
|
||||
@@ -79,10 +135,132 @@ pub fn allow_media_autoplay(window: &tauri::WebviewWindow) -> Result<(), String>
|
||||
target: "launcher",
|
||||
"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}"))
|
||||
}
|
||||
|
||||
/// 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.
|
||||
///
|
||||
/// AppKit treats application bundles as packages (directories) by default, so a
|
||||
@@ -156,6 +334,7 @@ pub fn pick_osu_installation() -> Result<Option<PathBuf>, String> {
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WineRuntime {
|
||||
prefix: PathBuf,
|
||||
wine_bin: PathBuf,
|
||||
@@ -239,27 +418,48 @@ impl WineRuntime {
|
||||
})
|
||||
}
|
||||
|
||||
/// Spawn a Windows executable through the wrapper's Wine runtime.
|
||||
pub fn spawn(&self, exe: &Path, args: &[&str]) -> Result<Child, 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()
|
||||
));
|
||||
/// 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 mut command = Command::new(&loader);
|
||||
command.arg(exe).args(args);
|
||||
command.current_dir(exe.parent().unwrap_or(&self.prefix));
|
||||
command
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
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");
|
||||
command.env("WINEDLLOVERRIDES", "mscoree,mshtml=");
|
||||
// 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();
|
||||
@@ -333,6 +533,29 @@ impl WineRuntime {
|
||||
if let Ok(path) = std::env::join_paths(paths) {
|
||||
command.env("PATH", path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Spawn a Windows executable through the wrapper's Wine runtime.
|
||||
pub fn spawn(&self, exe: &Path, args: &[&str]) -> Result<Child, 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::piped())
|
||||
.stderr(Stdio::piped());
|
||||
|
||||
self.apply_wine_environment(&mut command);
|
||||
|
||||
let executable_name = exe
|
||||
.file_name()
|
||||
@@ -348,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.
|
||||
pub async fn kill_prefix(&self) {
|
||||
let wineserver = self.wine_bin.join("wineserver");
|
||||
@@ -357,19 +613,11 @@ impl WineRuntime {
|
||||
|
||||
let mut cmd = Command::new(wineserver);
|
||||
cmd.arg("-k")
|
||||
.env("WINEPREFIX", &self.prefix)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
|
||||
if let Some(app) = &self.app_bundle {
|
||||
if let Ok(fallback) = std::env::join_paths([
|
||||
app.join("Contents/Frameworks"),
|
||||
app.join("Frameworks"),
|
||||
]) {
|
||||
cmd.env("DYLD_FALLBACK_LIBRARY_PATH", fallback);
|
||||
}
|
||||
}
|
||||
self.apply_wine_environment(&mut cmd);
|
||||
|
||||
let _ = cmd.status().await;
|
||||
}
|
||||
@@ -390,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(®_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(®_path)
|
||||
&& content.contains("Apple Braille") {
|
||||
let cleaned: String = content
|
||||
.lines()
|
||||
.filter(|line| !line.contains("Apple Braille"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n") + "\n";
|
||||
let _ = fs::write(®_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.
|
||||
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 runtime = WineRuntime::for_osu_folder(folder).map_err(|error| {
|
||||
log::error!(target: "osu", "Could not prepare the Wine runtime: {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
|
||||
.spawn(&folder.join("osu!.exe"), &["-devserver", "ez-pp.farm"])
|
||||
.spawn(&osu_exe, &["-devserver", "ez-pp.farm"])
|
||||
.map_err(|error| {
|
||||
log::error!(target: "osu", "Could not start osu!: {error}");
|
||||
error
|
||||
@@ -410,19 +784,110 @@ pub async fn run_osu(osu_folder: &str, patch: bool) -> Result<(), String> {
|
||||
crate::logging::capture_osu_output(&mut game);
|
||||
|
||||
if patch {
|
||||
if let Err(error) = start_patcher(&runtime, folder).await {
|
||||
let runtime_clone = runtime.clone();
|
||||
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 {
|
||||
Ok(status) => log::info!(target: "osu", "osu! exited with {status}"),
|
||||
// Wine cold startup handling:
|
||||
// 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) => {
|
||||
log::warn!(target: "osu", "Could not 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(())
|
||||
}
|
||||
|
||||
@@ -440,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!(
|
||||
target: "patcher",
|
||||
@@ -464,38 +938,67 @@ async fn start_patcher(runtime: &WineRuntime, osu_folder: &Path) -> Result<(), S
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Wait until the Wine-hosted osu! process exists, then give it time to create
|
||||
/// its game window. Wine does not expose the window title to the launcher here,
|
||||
/// so the process is the best signal available.
|
||||
async fn wait_for_osu_game() {
|
||||
let mut system = sysinfo::System::new_all();
|
||||
let deadline = Instant::now() + StdDuration::from_secs(30);
|
||||
let mut detected = false;
|
||||
/// Wait until osu! creates its game window (matching Windows and Linux launch logic).
|
||||
/// Polls window titles and waits until a non-empty, non-updater window appears.
|
||||
async fn wait_for_osu_game() -> bool {
|
||||
let mut sys = sysinfo::System::new_all();
|
||||
let deadline = Instant::now() + StdDuration::from_secs(60);
|
||||
|
||||
while Instant::now() < deadline {
|
||||
system.refresh_processes(sysinfo::ProcessesToUpdate::All, true);
|
||||
if system
|
||||
.processes()
|
||||
.values()
|
||||
.any(crate::utils::is_osu_game_process)
|
||||
{
|
||||
detected = true;
|
||||
break;
|
||||
loop {
|
||||
if Instant::now() > deadline {
|
||||
log::warn!(
|
||||
target: "patcher",
|
||||
"Timed out waiting for osu! game window for patcher"
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
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.
|
||||
@@ -568,17 +1071,15 @@ pub fn resolve_osu_folder(folder: &Path) -> Option<PathBuf> {
|
||||
|
||||
let mut prefixes = Vec::new();
|
||||
|
||||
if folder.file_name() == Some(OsStr::new("drive_c")) {
|
||||
if let Some(parent) = canonical_prefix(folder) {
|
||||
if folder.file_name() == Some(OsStr::new("drive_c"))
|
||||
&& let Some(parent) = canonical_prefix(folder) {
|
||||
prefixes.push(parent);
|
||||
}
|
||||
}
|
||||
|
||||
if folder.join("drive_c").is_dir() {
|
||||
if let Some(parent) = canonical_prefix(&folder.join("drive_c")) {
|
||||
if folder.join("drive_c").is_dir()
|
||||
&& let Some(parent) = canonical_prefix(&folder.join("drive_c")) {
|
||||
prefixes.push(parent);
|
||||
}
|
||||
}
|
||||
|
||||
if folder.extension() == Some(OsStr::new("app")) || folder.join("Contents").is_dir() {
|
||||
for drive_c in [
|
||||
@@ -586,12 +1087,11 @@ pub fn resolve_osu_folder(folder: &Path) -> Option<PathBuf> {
|
||||
folder.join("Contents/SharedSupport/drive_c"),
|
||||
folder.join("Contents/SharedSupport/prefix/drive_c"),
|
||||
] {
|
||||
if drive_c.is_dir() {
|
||||
if let Some(parent) = canonical_prefix(&drive_c) {
|
||||
if drive_c.is_dir()
|
||||
&& let Some(parent) = canonical_prefix(&drive_c) {
|
||||
prefixes.push(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut drive_dirs = Vec::new();
|
||||
find_drive_c_dirs(folder, 5, &mut drive_dirs);
|
||||
@@ -729,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
|
||||
// the app root. Resolve it to the real prefix so WINEPREFIX points
|
||||
// at Contents/Resources instead of the bundle itself.
|
||||
if path.file_name() == Some(OsStr::new("drive_c")) {
|
||||
if let Ok(canonical) = fs::canonicalize(&path) {
|
||||
if path.file_name() == Some(OsStr::new("drive_c"))
|
||||
&& let Ok(canonical) = fs::canonicalize(&path) {
|
||||
out.push(canonical);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -882,13 +1381,12 @@ fn find_wine_bin(prefix: &Path, app: Option<&Path>) -> Option<(PathBuf, Option<P
|
||||
}
|
||||
|
||||
for binary in ["wine64", "wine32on64", "wine"] {
|
||||
if let Some(path) = find_in_path(binary) {
|
||||
if let Some(bin) = path.parent() {
|
||||
if let Some(path) = find_in_path(binary)
|
||||
&& let Some(bin) = path.parent() {
|
||||
candidates.push((bin.to_path_buf(), None));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
candidates.into_iter().find(|(bin, _)| has_wine_loader(bin))
|
||||
}
|
||||
@@ -965,3 +1463,47 @@ fn pe_machine(exe: &Path) -> Option<u16> {
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
+60
-78
@@ -4,6 +4,7 @@ use std::sync::Mutex as StdMutex;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use tauri::{AppHandle, RunEvent};
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::time::{Duration, interval};
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
@@ -53,23 +54,19 @@ impl Default for PresenceData {
|
||||
enum PresenceCommand {
|
||||
Connect(oneshot::Sender<bool>),
|
||||
Disconnect(oneshot::Sender<()>),
|
||||
UpdateData(PresenceData),
|
||||
UpdateData(Box<PresenceData>),
|
||||
IsConnected(oneshot::Sender<bool>),
|
||||
}
|
||||
|
||||
enum ReconnectResult {
|
||||
Connected(AsyncDiscordIpcClient),
|
||||
Failed,
|
||||
}
|
||||
|
||||
struct PresenceActor {
|
||||
receiver: mpsc::Receiver<PresenceCommand>,
|
||||
reconnect_rx: mpsc::Receiver<ReconnectResult>,
|
||||
reconnect_tx: mpsc::Sender<ReconnectResult>,
|
||||
reconnect_rx: mpsc::Receiver<Box<AsyncDiscordIpcClient>>,
|
||||
reconnect_tx: mpsc::Sender<Box<AsyncDiscordIpcClient>>,
|
||||
reconnect_task: Option<JoinHandle<()>>,
|
||||
client: Option<AsyncDiscordIpcClient>,
|
||||
data: PresenceData,
|
||||
start_timestamp: i64,
|
||||
reconnecting: bool,
|
||||
should_connect: bool,
|
||||
}
|
||||
|
||||
impl PresenceActor {
|
||||
@@ -85,10 +82,11 @@ impl PresenceActor {
|
||||
receiver,
|
||||
reconnect_rx,
|
||||
reconnect_tx,
|
||||
reconnect_task: None,
|
||||
client: None,
|
||||
data: PresenceData::default(),
|
||||
start_timestamp: start,
|
||||
reconnecting: false,
|
||||
should_connect: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,7 +101,7 @@ impl PresenceActor {
|
||||
PresenceCommand::Connect(resp) => self.cmd_connect(resp).await,
|
||||
PresenceCommand::Disconnect(resp) => self.cmd_disconnect(resp).await,
|
||||
PresenceCommand::UpdateData(data) => {
|
||||
self.data = data;
|
||||
self.data = *data;
|
||||
self.push_presence().await;
|
||||
}
|
||||
PresenceCommand::IsConnected(resp) => {
|
||||
@@ -112,18 +110,13 @@ impl PresenceActor {
|
||||
}
|
||||
}
|
||||
|
||||
Some(result) = self.reconnect_rx.recv() => {
|
||||
self.reconnecting = false;
|
||||
match result {
|
||||
ReconnectResult::Connected(client) => {
|
||||
Some(client) = self.reconnect_rx.recv() => {
|
||||
self.reconnect_task = None;
|
||||
if self.should_connect {
|
||||
log::info!(target: "launcher", "Presence: reconnect succeeded");
|
||||
self.client = Some(client);
|
||||
self.client = Some(*client);
|
||||
self.push_presence().await;
|
||||
}
|
||||
ReconnectResult::Failed => {
|
||||
log::warn!(target: "launcher", "Presence: all reconnect attempts exhausted");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_ = heartbeat.tick() => {
|
||||
@@ -134,15 +127,19 @@ impl PresenceActor {
|
||||
}
|
||||
|
||||
async fn cmd_connect(&mut self, resp: oneshot::Sender<bool>) {
|
||||
self.should_connect = true;
|
||||
if self.client.is_some() {
|
||||
let _ = resp.send(true);
|
||||
return;
|
||||
}
|
||||
if self.reconnect_task.is_some() {
|
||||
let _ = resp.send(false);
|
||||
return;
|
||||
}
|
||||
|
||||
match try_connect_once().await {
|
||||
Some(client) => {
|
||||
self.client = Some(client);
|
||||
self.reconnecting = false;
|
||||
self.push_presence().await;
|
||||
let _ = resp.send(true);
|
||||
}
|
||||
@@ -158,6 +155,10 @@ impl PresenceActor {
|
||||
}
|
||||
|
||||
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() {
|
||||
let _ = client.clear_activity().await;
|
||||
log::info!(target: "launcher", "Presence: disconnected");
|
||||
@@ -188,16 +189,14 @@ impl PresenceActor {
|
||||
builder = builder.small_text(text);
|
||||
}
|
||||
|
||||
if let Some(btn) = &self.data.dynamic_button {
|
||||
if !btn.label.trim().is_empty() && !btn.url.trim().is_empty() {
|
||||
if let Some(btn) = &self.data.dynamic_button
|
||||
&& !btn.label.trim().is_empty() && !btn.url.trim().is_empty() {
|
||||
builder = builder.button(&btn.label, &btn.url);
|
||||
}
|
||||
}
|
||||
if let Some(btn2) = &self.data.secondary_button {
|
||||
if !btn2.label.trim().is_empty() && !btn2.url.trim().is_empty() {
|
||||
if let Some(btn2) = &self.data.secondary_button
|
||||
&& !btn2.label.trim().is_empty() && !btn2.url.trim().is_empty() {
|
||||
builder = builder.button(&btn2.label, &btn2.url);
|
||||
}
|
||||
}
|
||||
|
||||
let activity = builder.build();
|
||||
|
||||
@@ -208,37 +207,37 @@ impl PresenceActor {
|
||||
e
|
||||
);
|
||||
self.client = None;
|
||||
self.should_connect = true;
|
||||
self.spawn_reconnect_task();
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_reconnect_task(&mut self) {
|
||||
if self.reconnecting {
|
||||
if self.reconnect_task.is_some() || !self.should_connect {
|
||||
return;
|
||||
}
|
||||
self.reconnecting = true;
|
||||
|
||||
let tx = self.reconnect_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
const MAX_ATTEMPTS: u32 = 5;
|
||||
for attempt in 1..=MAX_ATTEMPTS {
|
||||
let delay = Duration::from_secs(5 * attempt as u64);
|
||||
let task = tokio::spawn(async move {
|
||||
let mut attempt: u32 = 0;
|
||||
loop {
|
||||
attempt = attempt.saturating_add(1);
|
||||
let delay = Duration::from_secs((5 * u64::from(attempt)).min(30));
|
||||
log::info!(
|
||||
target: "launcher",
|
||||
"Presence: reconnect attempt {}/{} in {:?}…",
|
||||
"Presence: reconnect attempt {} in {:?}…",
|
||||
attempt,
|
||||
MAX_ATTEMPTS,
|
||||
delay
|
||||
);
|
||||
tokio::time::sleep(delay).await;
|
||||
|
||||
if let Some(client) = try_connect_once().await {
|
||||
let _ = tx.send(ReconnectResult::Connected(client)).await;
|
||||
let _ = tx.send(Box::new(client)).await;
|
||||
return;
|
||||
}
|
||||
}
|
||||
let _ = tx.send(ReconnectResult::Failed).await;
|
||||
});
|
||||
self.reconnect_task = Some(task);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -302,52 +301,35 @@ pub async fn has_presence() -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn update_activity(
|
||||
state: Option<&str>,
|
||||
details: Option<&str>,
|
||||
large_image_key: Option<&str>,
|
||||
large_image_text: Option<&str>,
|
||||
small_image_key: Option<Option<String>>,
|
||||
small_image_text: Option<Option<String>>,
|
||||
button1: Option<Option<PresenceButton>>,
|
||||
button2: Option<Option<PresenceButton>>,
|
||||
show_timestamp: Option<bool>,
|
||||
state: &str,
|
||||
details: &str,
|
||||
large_image_key: &str,
|
||||
large_image_text: &str,
|
||||
small_image_key: Option<String>,
|
||||
small_image_text: Option<String>,
|
||||
button1: Option<PresenceButton>,
|
||||
button2: Option<PresenceButton>,
|
||||
show_timestamp: bool,
|
||||
) {
|
||||
let data = {
|
||||
let mut guard = PRESENCE_DATA.lock().unwrap();
|
||||
if let Some(s) = state {
|
||||
guard.state = s.to_string();
|
||||
}
|
||||
if let Some(d) = details {
|
||||
guard.details = d.to_string();
|
||||
}
|
||||
if let Some(img) = large_image_key {
|
||||
guard.large_image_key = img.to_string();
|
||||
}
|
||||
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.state = state.to_string();
|
||||
guard.details = details.to_string();
|
||||
guard.large_image_key = large_image_key.to_string();
|
||||
guard.large_image_text = large_image_text.to_string();
|
||||
guard.small_image_key = small_image_key;
|
||||
guard.small_image_text = small_image_text;
|
||||
guard.dynamic_button = button1;
|
||||
guard.secondary_button = button2;
|
||||
guard.show_timestamp = show_timestamp;
|
||||
guard.clone()
|
||||
};
|
||||
|
||||
let tx = PRESENCE_TX.clone();
|
||||
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();
|
||||
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();
|
||||
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();
|
||||
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();
|
||||
tokio::spawn(async move {
|
||||
let _ = tx.send(PresenceCommand::UpdateData(data)).await;
|
||||
let _ = tx.send(PresenceCommand::UpdateData(Box::new(data))).await;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+398
-6
@@ -40,15 +40,14 @@ pub fn is_osu_process(process: &sysinfo::Process) -> bool {
|
||||
return true;
|
||||
}
|
||||
|
||||
if let Some(exe) = process.exe() {
|
||||
if exe
|
||||
if let Some(exe) = process.exe()
|
||||
&& exe
|
||||
.file_name()
|
||||
.map(|file_name| file_name.to_string_lossy().to_ascii_lowercase() == "osu!.exe")
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
process.cmd().iter().any(|arg| {
|
||||
arg.to_string_lossy()
|
||||
@@ -103,7 +102,7 @@ fn find_osu_user_config_path<P: AsRef<Path>>(folder_path: P) -> Option<PathBuf>
|
||||
})
|
||||
.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)
|
||||
}
|
||||
|
||||
@@ -261,7 +260,7 @@ pub fn get_osu_config<P: AsRef<Path>>(
|
||||
}
|
||||
}
|
||||
|
||||
return Some(config_map);
|
||||
Some(config_map)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -353,9 +352,197 @@ pub fn get_window_title_by_pid(target_pid: Pid) -> String {
|
||||
}
|
||||
|
||||
#[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 {
|
||||
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)]
|
||||
pub fn get_window_title_by_pid(pid: Pid) -> String {
|
||||
@@ -513,3 +700,208 @@ pub fn encrypt_password(password: &str, entropy: &str) -> Result<String, 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "EZPPLauncher",
|
||||
"version": "3.2.7",
|
||||
"version": "3.3.0",
|
||||
"identifier": "farm.EZPPFarm.Launcher",
|
||||
"mainBinaryName": "ezpplauncher",
|
||||
"build": {
|
||||
@@ -21,7 +21,8 @@
|
||||
"decorations": false,
|
||||
"resizable": false,
|
||||
"maximizable": false,
|
||||
"shadow": true
|
||||
"shadow": true,
|
||||
"focus": true
|
||||
}
|
||||
],
|
||||
"withGlobalTauri": true,
|
||||
@@ -29,10 +30,13 @@
|
||||
"csp": {
|
||||
"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",
|
||||
"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:*",
|
||||
"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",
|
||||
"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",
|
||||
"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 https://themes.ez-pp.farm",
|
||||
"media-src": "'self' asset: http://asset.localhost https://asset.localhost http://127.0.0.1:* blob:",
|
||||
"font-src": [
|
||||
"'self'",
|
||||
|
||||
+65
-1
@@ -162,7 +162,10 @@
|
||||
-ms-user-select: none;
|
||||
user-select: none;
|
||||
}
|
||||
html {
|
||||
html,
|
||||
body {
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
overscroll-behavior: none;
|
||||
}
|
||||
body {
|
||||
@@ -173,3 +176,64 @@
|
||||
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
@@ -7,7 +7,13 @@
|
||||
%sveltekit.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>
|
||||
</body>
|
||||
</html>
|
||||
@@ -154,9 +154,9 @@
|
||||
<Terminal class="size-4" />
|
||||
</div>
|
||||
<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">
|
||||
Launcher, osu! and patcher output, grouped by session
|
||||
Current session plus archived launcher, osu! and patcher output
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -191,7 +191,7 @@
|
||||
<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"
|
||||
>
|
||||
<span>Bundles</span>
|
||||
<span>Sessions</span>
|
||||
<span>{bundles.length}</span>
|
||||
</div>
|
||||
<div class="min-h-0 flex-1 overflow-y-auto p-1.5">
|
||||
@@ -202,8 +202,8 @@
|
||||
</div>
|
||||
{:else if bundles.length === 0}
|
||||
<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
|
||||
MiB.
|
||||
No logs yet. The current session appears once the launcher writes its first line;
|
||||
archived bundles are created when logs rotate.
|
||||
</div>
|
||||
{:else}
|
||||
{#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"
|
||||
>
|
||||
<LoaderCircle class="size-4 animate-spin" />
|
||||
Reading bundle…
|
||||
Reading logs…
|
||||
</div>
|
||||
{:else if !selectedBundle}
|
||||
<div
|
||||
class="flex h-full flex-col items-center justify-center gap-2 text-center text-muted-foreground"
|
||||
>
|
||||
<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>
|
||||
{:else if filteredLines.length === 0}
|
||||
<div
|
||||
@@ -328,7 +328,7 @@
|
||||
<span>
|
||||
{selectedBundle
|
||||
? `${selectedBundle.name} · ${formatBytes(selectedBundle.size)}`
|
||||
: 'No bundle selected'}
|
||||
: 'No session selected'}
|
||||
</span>
|
||||
</footer>
|
||||
</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}
|
||||
@@ -12,13 +12,11 @@
|
||||
DISCORD_PRESENCE_PRESETS,
|
||||
interpolatePresenceString,
|
||||
loadDiscordPresenceConfig,
|
||||
pushIdlePresenceFromConfig,
|
||||
saveDiscordPresenceConfig,
|
||||
type DiscordPresenceConfig,
|
||||
type PresenceVariableContext,
|
||||
} from '$lib/discordPresenceConfig';
|
||||
import { discordPresence, launcherVersion } from '$lib/global';
|
||||
import * as presence from '$lib/presence';
|
||||
import { currentUser } from '$lib/userAuthentication';
|
||||
import {
|
||||
Check,
|
||||
@@ -206,10 +204,14 @@
|
||||
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?.info) currentUserInfo.set(event.payload.info);
|
||||
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');
|
||||
} catch (err) {
|
||||
@@ -469,18 +471,9 @@
|
||||
try {
|
||||
await saveDiscordPresenceConfig(workingConfig);
|
||||
initialConfigJson = JSON.stringify(workingConfig);
|
||||
if ($discordPresence && (await presence.isConnected())) {
|
||||
await pushIdlePresenceFromConfig(
|
||||
{
|
||||
user: $currentUser,
|
||||
version: $launcherVersion || undefined,
|
||||
rank: simRank,
|
||||
pp: simPp,
|
||||
accuracy: simAccuracy,
|
||||
},
|
||||
workingConfig
|
||||
);
|
||||
}
|
||||
// The main window owns the live player stats and its presence config
|
||||
// store, so let it refresh and push the updated activity immediately.
|
||||
await emit('discord-presence-config-saved');
|
||||
sileo.success({ title: 'Discord Rich Presence Saved', description: 'Activity updated' });
|
||||
await handleClose();
|
||||
} catch (err) {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -6,18 +6,18 @@
|
||||
import Input from '$lib/components/ui/input/input.svelte';
|
||||
import Label from '$lib/components/ui/label/label.svelte';
|
||||
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 {
|
||||
themeBehaviorTargetLabel,
|
||||
themeElementLabel,
|
||||
themeGroupInteractiveCount,
|
||||
themeGroupLabel,
|
||||
} from '$lib/themeLogic';
|
||||
} from '$lib/theme/themeLogic';
|
||||
import {
|
||||
formatThemeScriptError,
|
||||
parseThemeScript,
|
||||
themeScriptProgramCanLeaveLauncher,
|
||||
} from '$lib/themeScriptLang';
|
||||
} from '$lib/theme/themeScriptLang';
|
||||
import type {
|
||||
ThemeV2Behavior,
|
||||
ThemeV2BehaviorAction,
|
||||
@@ -29,7 +29,7 @@
|
||||
ThemeV2Group,
|
||||
ThemeV2ScriptScreen,
|
||||
ThemeV2ScriptValue,
|
||||
} from '$lib/themeV2';
|
||||
} from '$lib/theme/themeV2';
|
||||
import { Link2, Plus, Trash2 } from '@lucide/svelte';
|
||||
import { SvelteSet } from 'svelte/reactivity';
|
||||
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
analyzeThemeSvelteSource,
|
||||
type ThemeSvelteAnalysis,
|
||||
type ThemeSvelteDiagnostic,
|
||||
} from '$lib/themeSvelte';
|
||||
} from '$lib/theme/themeSvelte';
|
||||
import {
|
||||
THEME_SVELTE_COMPONENT_PLACEHOLDER,
|
||||
THEME_SVELTE_COMPONENT_SKELETON,
|
||||
} from '$lib/themeSvelteSnippets';
|
||||
} from '$lib/theme/themeSvelteSnippets';
|
||||
import { Component, CircleAlert, Maximize2, Minimize2, X } from '@lucide/svelte';
|
||||
import type * as Monaco from 'monaco-editor';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import Button from '$lib/components/ui/button/button.svelte';
|
||||
import Input from '$lib/components/ui/input/input.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';
|
||||
|
||||
let {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { compileThemeSvelte } from '$lib/themeSvelte';
|
||||
import { themeAssetUrl, type ThemeV2ScriptValue } from '$lib/themeV2';
|
||||
import { compileThemeSvelte } from '$lib/theme/themeSvelte';
|
||||
import { themeAssetUrl, type ThemeV2ScriptValue } from '$lib/theme/themeV2';
|
||||
import { TriangleAlert } from '@lucide/svelte';
|
||||
import { mount, unmount } from 'svelte';
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import Logo from '$assets/logo.png';
|
||||
import { fetchCommunityThemeDetails, publishThemeToWorkshop } from '$lib/theme/communityThemes';
|
||||
import FontPreview from '$lib/components/theme/FontPreview.svelte';
|
||||
import ThemeBehaviorInspector from '$lib/components/theme/ThemeBehaviorInspector.svelte';
|
||||
import ThemeElementInspector from '$lib/components/theme/ThemeElementInspector.svelte';
|
||||
@@ -43,39 +44,43 @@
|
||||
THEME_CLOCK_VARIABLE_NAMES,
|
||||
isThemeClockVariable,
|
||||
themeClockValues,
|
||||
} from '$lib/themeClock';
|
||||
} from '$lib/theme/themeClock';
|
||||
import {
|
||||
BUNDLED_THEME_FONTS,
|
||||
bundledThemeFontFamily,
|
||||
fontStack,
|
||||
type ThemeFontChoice,
|
||||
} from '$lib/themeFonts';
|
||||
import { THEME_ICON_PREVIEW_NAMES, THEME_ICON_SETS } from '$lib/themeIcons';
|
||||
} from '$lib/theme/themeFonts';
|
||||
import { THEME_ICON_PREVIEW_NAMES, THEME_ICON_SETS } from '$lib/theme/themeIcons';
|
||||
import {
|
||||
themeBehaviorSummary,
|
||||
themeBehaviorTargetLabel,
|
||||
themeElementLabel,
|
||||
themeGroupContainsElement,
|
||||
themeGroupInteractiveCount,
|
||||
} from '$lib/themeLogic';
|
||||
import { renderThemePreview } from '$lib/themePreview';
|
||||
import { themeScriptInitialVariables, themeScriptVariableNames } from '$lib/themeScript';
|
||||
} from '$lib/theme/themeLogic';
|
||||
import { themeParallax } from '$lib/theme/themeParallax';
|
||||
import { renderThemePreview } from '$lib/theme/themePreview';
|
||||
import { themeScriptInitialVariables, themeScriptVariableNames } from '$lib/theme/themeScript';
|
||||
import {
|
||||
formatThemeScriptError,
|
||||
parseThemeScript,
|
||||
themeScriptProgramCanLeaveLauncher,
|
||||
themeScriptProgramReferences,
|
||||
} from '$lib/themeScriptLang';
|
||||
import { analyzeThemeSvelteSource } from '$lib/themeSvelte';
|
||||
} from '$lib/theme/themeScriptLang';
|
||||
import { analyzeThemeSvelteSource } from '$lib/theme/themeSvelte';
|
||||
import {
|
||||
createDefaultThemeV2,
|
||||
createThemeV2Behavior,
|
||||
createThemeV2Element,
|
||||
normalizeChrome,
|
||||
normalizeThemeTags,
|
||||
normalizeThemeV2,
|
||||
normalizeThemeVersion,
|
||||
themeAssetName,
|
||||
themeHasLaunchButton,
|
||||
type ThemeV2Asset,
|
||||
type ThemeV2Audio,
|
||||
type ThemeV2Background,
|
||||
type ThemeV2BehaviorTarget,
|
||||
type ThemeV2ButtonAction,
|
||||
@@ -91,20 +96,24 @@
|
||||
type ThemeV2VideoElement,
|
||||
type ThemeV2WidgetElement,
|
||||
type ThemeV2WidgetKind,
|
||||
} from '$lib/themeV2';
|
||||
} from '$lib/theme/themeV2';
|
||||
import {
|
||||
exportThemeFolder,
|
||||
markThemeSynced,
|
||||
saveThemeProject,
|
||||
themeAssetBase,
|
||||
themesDirectory,
|
||||
toSafeName,
|
||||
} from '$lib/themes';
|
||||
updateInstalledThemeWorkshopId,
|
||||
} from '$lib/theme/themes';
|
||||
import type { EZPPUser, EZPPUserInfo } from '$lib/types';
|
||||
import { currentUser } from '$lib/userAuthentication';
|
||||
import { osuInstallationPath } from '$lib/userSettings';
|
||||
import { formatBytes, openURL } from '$lib/utils';
|
||||
import {
|
||||
AlertTriangle,
|
||||
AlignCenter,
|
||||
AlignHorizontalSpaceAround,
|
||||
Boxes,
|
||||
Check,
|
||||
CheckCircle2,
|
||||
@@ -123,11 +132,14 @@
|
||||
Download,
|
||||
Eye,
|
||||
EyeOff,
|
||||
FileText,
|
||||
Film,
|
||||
Gauge,
|
||||
Globe,
|
||||
GripVertical,
|
||||
Hand,
|
||||
Image as ImageIcon,
|
||||
Info,
|
||||
Keyboard,
|
||||
Layers,
|
||||
LayoutGrid,
|
||||
@@ -168,6 +180,7 @@
|
||||
import { getCurrentWindow } from '@tauri-apps/api/window';
|
||||
import { open, save as saveDialog } from '@tauri-apps/plugin-dialog';
|
||||
import * as fs from '@tauri-apps/plugin-fs';
|
||||
import semver from 'semver';
|
||||
import { sileo } from 'sileo';
|
||||
import { onMount, tick } from 'svelte';
|
||||
import { SvelteMap, SvelteSet } from 'svelte/reactivity';
|
||||
@@ -252,6 +265,7 @@
|
||||
let lastGradientBackground = $state<Extract<ThemeV2Background, { type: 'gradient' }> | undefined>(
|
||||
undefined
|
||||
);
|
||||
let lastAudio = $state<ThemeV2Audio | undefined>(undefined);
|
||||
let assetBase = $state('');
|
||||
let savedFolder = $state<string | undefined>(undefined);
|
||||
let editorFolderPath = $state<string | undefined>(undefined);
|
||||
@@ -281,6 +295,7 @@
|
||||
let panStart = { x: 0, y: 0, panX: 0, panY: 0 };
|
||||
const canvasScale = $derived(canvasFitScale * canvasZoom);
|
||||
let statusMessage = $state('Ready');
|
||||
let lastPublishedVersion = $state<string | undefined>(undefined);
|
||||
let renamingId = $state<string | undefined>(undefined);
|
||||
let draggingLayer = $state<LayerDragItem | undefined>(undefined);
|
||||
let dropTarget = $state<LayerDropTarget | undefined>(undefined);
|
||||
@@ -700,6 +715,7 @@
|
||||
{ value: 'snow', label: 'Snow' },
|
||||
{ value: 'petals', label: 'Petals' },
|
||||
{ value: 'bubbles', label: 'Bubbles' },
|
||||
{ value: 'embers', label: 'Floating Embers' },
|
||||
] as const;
|
||||
|
||||
const notifyError = (description: string) => sileo.error({ title: 'Theme editor', description });
|
||||
@@ -1796,12 +1812,14 @@
|
||||
|
||||
async function loadContext() {
|
||||
loading = true;
|
||||
lastPublishedVersion = undefined;
|
||||
try {
|
||||
const context = await invoke<ThemeEditorContext>('theme_editor_context');
|
||||
const parsed = context.themeJson
|
||||
? normalizeThemeV2(JSON.parse(context.themeJson) as Partial<ThemeV2Definition>)
|
||||
: createDefaultThemeV2();
|
||||
definition = ensureDefaults(parsed);
|
||||
lastAudio = parsed.audio ? { ...parsed.audio } : undefined;
|
||||
savedFolder = context.folderName ?? undefined;
|
||||
editorFolderPath = context.folderPath ?? undefined;
|
||||
const httpBase = await themeAssetBase();
|
||||
@@ -1991,6 +2009,9 @@
|
||||
color: current.type === 'color' ? current.color : (lastColorBackground?.color ?? '#181825'),
|
||||
opacity: lastColorBackground?.opacity ?? opacity,
|
||||
};
|
||||
if (!definition.audio && lastAudio) {
|
||||
definition.audio = { ...lastAudio };
|
||||
}
|
||||
} else if (type === 'gradient') {
|
||||
definition.background = {
|
||||
type: 'gradient',
|
||||
@@ -2003,6 +2024,9 @@
|
||||
: (lastGradientBackground?.angle ?? 135),
|
||||
opacity: lastGradientBackground?.opacity ?? opacity,
|
||||
};
|
||||
if (!definition.audio && lastAudio) {
|
||||
definition.audio = { ...lastAudio };
|
||||
}
|
||||
} else if (type === 'video') {
|
||||
const candidateVideo =
|
||||
current.type === 'video' && current.src
|
||||
@@ -2023,6 +2047,9 @@
|
||||
if (candidateVideo) {
|
||||
lastVideoBackground = { ...definition.background };
|
||||
}
|
||||
if (definition.audio) {
|
||||
lastAudio = { ...definition.audio };
|
||||
}
|
||||
definition.audio = undefined;
|
||||
} else {
|
||||
const candidateImage =
|
||||
@@ -2042,6 +2069,9 @@
|
||||
if (candidateImage) {
|
||||
lastImageBackground = { ...definition.background };
|
||||
}
|
||||
if (!definition.audio && lastAudio) {
|
||||
definition.audio = { ...lastAudio };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2085,6 +2115,7 @@
|
||||
const asset = await chooseAsset('audio');
|
||||
if (!asset) return;
|
||||
definition.audio = { src: asset.name, loop: definition.audio?.loop !== false };
|
||||
lastAudio = { ...definition.audio };
|
||||
}
|
||||
|
||||
function uniqueFamily(label: string) {
|
||||
@@ -2238,7 +2269,7 @@
|
||||
element.width = 340;
|
||||
element.height = 64;
|
||||
} else if (widgetKind === 'launch-button') {
|
||||
element.width = 210;
|
||||
element.width = 256;
|
||||
element.height = 48;
|
||||
}
|
||||
}
|
||||
@@ -2290,9 +2321,9 @@
|
||||
) as ThemeV2WidgetElement;
|
||||
launchBtn.widget = 'launch-button';
|
||||
launchBtn.name = 'Launch Button';
|
||||
launchBtn.x = 740;
|
||||
launchBtn.x = 720;
|
||||
launchBtn.y = 575;
|
||||
launchBtn.width = 210;
|
||||
launchBtn.width = 256;
|
||||
launchBtn.height = 48;
|
||||
newElements.push(launchBtn);
|
||||
existing = launchBtn;
|
||||
@@ -2899,6 +2930,12 @@
|
||||
notifyError('Add an author name so people know who made the theme.');
|
||||
return false;
|
||||
}
|
||||
const version = normalizeThemeVersion(definition.version);
|
||||
if (!version) {
|
||||
notifyError('The version must use semantic versioning, for example 1.2.3 or 1.2.3-beta.1.');
|
||||
return false;
|
||||
}
|
||||
if (definition.version !== version) definition.version = version;
|
||||
const folderName = savedFolder ?? toSafeName(definition.name);
|
||||
if (!folderName.replace(/_/g, '')) {
|
||||
notifyError('The theme name needs at least one letter or number.');
|
||||
@@ -2995,8 +3032,10 @@
|
||||
|
||||
if (!definition.name.trim()) error('The theme needs a name.');
|
||||
if (!definition.author.trim()) error('The theme needs an author.');
|
||||
if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(definition.version.trim())) {
|
||||
warning('The version should use semantic versioning, for example 1.0.0.');
|
||||
if (!normalizeThemeVersion(definition.version)) {
|
||||
error(
|
||||
'The version must use semantic versioning, for example 1.0.0 or 1.0.0-beta.1, with no "v" prefix.'
|
||||
);
|
||||
}
|
||||
if (!themeHasLaunchButton(definition)) {
|
||||
error(
|
||||
@@ -3312,6 +3351,240 @@
|
||||
}
|
||||
}
|
||||
|
||||
let publishModalOpen = $state(false);
|
||||
let publishThemeId = $state('');
|
||||
let publishing = $state(false);
|
||||
let tagInput = $state('');
|
||||
let publishStatusMessage = $state('');
|
||||
let publishProgress = $state(0);
|
||||
|
||||
async function checkPublishVersion(): Promise<
|
||||
{ ok: true; version: string } | { ok: false; error: string }
|
||||
> {
|
||||
const proposed = normalizeThemeVersion(definition.version);
|
||||
if (!proposed) {
|
||||
return {
|
||||
ok: false,
|
||||
error: 'Use a semantic version such as 1.2.3 in the Theme tab before publishing.',
|
||||
};
|
||||
}
|
||||
|
||||
let publishedVersion = lastPublishedVersion;
|
||||
const workshopId = definition.workshopId?.trim();
|
||||
if (workshopId) {
|
||||
let remoteVersion: string;
|
||||
try {
|
||||
remoteVersion = (await fetchCommunityThemeDetails(workshopId)).version?.trim() ?? '';
|
||||
} catch (error) {
|
||||
console.warn('[Workshop] Could not verify the published theme version:', error);
|
||||
return {
|
||||
ok: false,
|
||||
error:
|
||||
'Could not verify the current workshop version. Check your connection and try again.',
|
||||
};
|
||||
}
|
||||
|
||||
const validRemote = normalizeThemeVersion(remoteVersion);
|
||||
if (!validRemote) {
|
||||
return {
|
||||
ok: false,
|
||||
error:
|
||||
'The current workshop version could not be read. Contact a workshop administrator.',
|
||||
};
|
||||
}
|
||||
if (!publishedVersion || semver.gt(validRemote, publishedVersion)) {
|
||||
publishedVersion = validRemote;
|
||||
}
|
||||
}
|
||||
|
||||
if (publishedVersion) {
|
||||
if (semver.eq(proposed, publishedVersion)) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Version ${proposed} has already been published. Increase the version before publishing again.`,
|
||||
};
|
||||
}
|
||||
if (!semver.gt(proposed, publishedVersion)) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Version ${proposed} must be higher than the last published version ${publishedVersion}.`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { ok: true, version: proposed };
|
||||
}
|
||||
|
||||
async function openPublishDialog() {
|
||||
if (exporting || saving || publishing) return;
|
||||
|
||||
const user = $currentUser;
|
||||
if (!user) {
|
||||
sileo.error({
|
||||
title: 'Authentication Required',
|
||||
description:
|
||||
'You must be logged in to your EZPPFarm account to publish themes to the workshop.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const report = await validateTheme();
|
||||
validationReport = report;
|
||||
const errors = report.issues.some((issue) => issue.level === 'error');
|
||||
if (errors) {
|
||||
validationOpen = true;
|
||||
exportAfterValidation = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const versionCheck = await checkPublishVersion();
|
||||
if (!versionCheck.ok) {
|
||||
sileo.error({
|
||||
title: 'Version not publishable',
|
||||
description: versionCheck.error,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const versionChanged = definition.version !== versionCheck.version;
|
||||
if (versionChanged) definition.version = versionCheck.version;
|
||||
|
||||
const authorIdChanged = definition.authorId !== user.id;
|
||||
if (authorIdChanged) definition.authorId = user.id;
|
||||
|
||||
if (dirty || authorIdChanged || versionChanged) {
|
||||
const saved = await saveTheme({ notify: false });
|
||||
if (!saved) return;
|
||||
}
|
||||
|
||||
publishThemeId = definition.workshopId ?? '';
|
||||
publishProgress = 0;
|
||||
publishStatusMessage = '';
|
||||
publishModalOpen = true;
|
||||
}
|
||||
|
||||
function addThemeTag() {
|
||||
const value = tagInput.trim().toLowerCase();
|
||||
if (!value) return;
|
||||
|
||||
const current = definition.tags ?? [];
|
||||
if (current.length >= 10) {
|
||||
notifyError('A theme may have at most 10 tags.');
|
||||
return;
|
||||
}
|
||||
|
||||
const tags = normalizeThemeTags([...current, value]);
|
||||
if (!tags.includes(value)) {
|
||||
notifyError(
|
||||
'Tags may contain lowercase letters, numbers, dashes and underscores (max 24 characters).'
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
definition.tags = tags;
|
||||
tagInput = '';
|
||||
}
|
||||
|
||||
function removeThemeTag(tag: string) {
|
||||
definition.tags = (definition.tags ?? []).filter((candidate) => candidate !== tag);
|
||||
}
|
||||
|
||||
async function handlePublishToWorkshop() {
|
||||
if (publishing) return;
|
||||
|
||||
const firstPublish = !definition.workshopId;
|
||||
publishing = true;
|
||||
publishProgress = 5;
|
||||
publishStatusMessage = 'Checking version...';
|
||||
|
||||
try {
|
||||
const versionCheck = await checkPublishVersion();
|
||||
if (!versionCheck.ok) {
|
||||
sileo.error({
|
||||
title: 'Version not publishable',
|
||||
description: versionCheck.error,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (definition.version !== versionCheck.version) {
|
||||
definition.version = versionCheck.version;
|
||||
const saved = await saveTheme({ notify: false });
|
||||
if (!saved) return;
|
||||
}
|
||||
|
||||
if (!savedFolder) {
|
||||
const saved = await saveTheme({ notify: false });
|
||||
if (!saved || !savedFolder) return;
|
||||
}
|
||||
|
||||
publishStatusMessage = 'Packaging theme archive...';
|
||||
const baseThemesDir = await themesDirectory();
|
||||
const themeFolder = await path.join(baseThemesDir, savedFolder);
|
||||
const themeId = savedFolder || toSafeName(definition.name);
|
||||
|
||||
const result = await publishThemeToWorkshop({
|
||||
themeFolder,
|
||||
themeId,
|
||||
workshopId: definition.workshopId,
|
||||
name: definition.name,
|
||||
description: definition.description || '',
|
||||
version: versionCheck.version,
|
||||
apiVersion: definition.apiVersion || '2.0.0',
|
||||
tags: definition.tags ?? [],
|
||||
allowForking: definition.allowForking !== false,
|
||||
onProgress: (msg, pct) => {
|
||||
publishStatusMessage = msg;
|
||||
publishProgress = pct;
|
||||
},
|
||||
});
|
||||
|
||||
lastPublishedVersion = versionCheck.version;
|
||||
|
||||
if (result.themeId) {
|
||||
// Persist the server-assigned ID so the next publish updates this
|
||||
// workshop record instead of creating another one.
|
||||
definition.workshopId = result.themeId;
|
||||
publishThemeId = result.themeId;
|
||||
try {
|
||||
await updateInstalledThemeWorkshopId(savedFolder, result.themeId);
|
||||
await markThemeSynced(savedFolder, {
|
||||
workshopId: result.themeId,
|
||||
version: versionCheck.version,
|
||||
});
|
||||
lastSavedKey = snapshotKey(captureSnapshot());
|
||||
} catch (err) {
|
||||
console.warn('[Workshop] Could not store the theme sync metadata:', err);
|
||||
}
|
||||
|
||||
// The launcher window owns the installed-theme list. Tell it about the
|
||||
// new workshop ID so reporting is hidden immediately after publishing.
|
||||
await emit('theme-published', {
|
||||
themeId: result.themeId,
|
||||
name: definition.name,
|
||||
}).catch((err) => {
|
||||
console.warn('[Workshop] Could not notify the launcher about the published theme:', err);
|
||||
});
|
||||
}
|
||||
|
||||
sileo.success({
|
||||
title: firstPublish ? 'Submitted for review' : 'Workshop update submitted',
|
||||
description: firstPublish
|
||||
? `"${definition.name}" will be listed once a moderator approves it.`
|
||||
: `"${definition.name}" was updated in the Community Workshop.`,
|
||||
});
|
||||
|
||||
publishModalOpen = false;
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
sileo.error({
|
||||
title: 'Publish Failed',
|
||||
description: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
} finally {
|
||||
publishing = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function closeEditor() {
|
||||
if (saving) return;
|
||||
if (dirty) {
|
||||
@@ -3734,7 +4007,7 @@
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onclick={() => exportCurrentTheme()}
|
||||
disabled={exporting || saving}
|
||||
disabled={exporting || saving || publishing}
|
||||
>
|
||||
{#if exporting}
|
||||
<LoaderCircle class="animate-spin" />
|
||||
@@ -3743,6 +4016,20 @@
|
||||
{/if}
|
||||
Export
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onclick={openPublishDialog}
|
||||
disabled={exporting || saving || publishing}
|
||||
class="border-cyan-500/30 bg-cyan-950/20 text-cyan-300 hover:bg-cyan-950/40 hover:text-cyan-200"
|
||||
>
|
||||
{#if publishing}
|
||||
<LoaderCircle class="animate-spin" />
|
||||
{:else}
|
||||
<Globe class="size-4" />
|
||||
{/if}
|
||||
Publish
|
||||
</Button>
|
||||
<Button size="sm" onclick={() => saveTheme()} disabled={saving || loading}>
|
||||
{#if saving}
|
||||
<LoaderCircle class="animate-spin" />
|
||||
@@ -4798,7 +5085,12 @@
|
||||
</div>
|
||||
{:else}
|
||||
<div class="min-h-0 flex-1 space-y-3 overflow-y-auto p-3">
|
||||
<ThemeSection title="Theme details" bordered={false} contentClass="space-y-3 pt-2">
|
||||
<ThemeSection
|
||||
title="Theme details"
|
||||
icon={Info}
|
||||
bordered={false}
|
||||
contentClass="space-y-3 pt-2"
|
||||
>
|
||||
<div class="space-y-1.5">
|
||||
<Label for="theme-name" class={labelClass}>Name</Label>
|
||||
<Input
|
||||
@@ -4836,6 +5128,63 @@
|
||||
class="min-h-16 resize-y border-theme-800 bg-theme-950 text-xs text-theme-50"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<div class="flex items-center justify-between">
|
||||
<Label for="theme-tags" class={labelClass}>Tags</Label>
|
||||
<span class="text-[9px] tabular-nums text-muted-foreground">
|
||||
{(definition.tags ?? []).length}/10
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<Input
|
||||
id="theme-tags"
|
||||
bind:value={tagInput}
|
||||
class={fieldClass}
|
||||
placeholder="anime, dark, minimal"
|
||||
maxlength={24}
|
||||
onkeydown={(event) => {
|
||||
if (event.key === 'Enter' || event.key === ',') {
|
||||
event.preventDefault();
|
||||
addThemeTag();
|
||||
}
|
||||
}}
|
||||
onblur={addThemeTag}
|
||||
/>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
class="h-9 shrink-0 gap-1 px-2.5"
|
||||
onclick={addThemeTag}
|
||||
disabled={!tagInput.trim()}
|
||||
>
|
||||
<Plus class="size-3.5" />
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
{#if (definition.tags ?? []).length > 0}
|
||||
<div class="flex flex-wrap gap-1.5 pt-1">
|
||||
{#each definition.tags ?? [] as tag (tag)}
|
||||
<span
|
||||
class="inline-flex items-center gap-1 rounded-full border border-theme-700 bg-theme-900 px-2 py-1 text-[10px] text-theme-100"
|
||||
>
|
||||
{tag}
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full text-muted-foreground transition-colors hover:text-white"
|
||||
aria-label={`Remove ${tag} tag`}
|
||||
onclick={() => removeThemeTag(tag)}
|
||||
>
|
||||
<X class="size-3" />
|
||||
</button>
|
||||
</span>
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="text-[10px] text-muted-foreground/70">
|
||||
Add tags to help people discover this theme.
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
<div
|
||||
class="flex items-start justify-between gap-3 rounded-md border border-theme-800 bg-theme-950 px-3 py-2.5"
|
||||
>
|
||||
@@ -4856,6 +5205,27 @@
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
class="flex items-start justify-between gap-3 rounded-md border border-theme-800 bg-theme-950 px-3 py-2.5"
|
||||
>
|
||||
<div class="space-y-0.5">
|
||||
<Label for="theme-allow-forking" class="text-xs font-medium text-theme-100">
|
||||
Allow forking
|
||||
</Label>
|
||||
<p class="text-[10px] leading-relaxed text-muted-foreground">
|
||||
Let other creators fork this theme from the workshop. Takes effect when you
|
||||
publish or update it; existing forks are not affected.
|
||||
</p>
|
||||
</div>
|
||||
<Checkbox
|
||||
id="theme-allow-forking"
|
||||
class="mt-0.5"
|
||||
checked={definition.allowForking !== false}
|
||||
onCheckedChange={(checked) => {
|
||||
definition.allowForking = checked === true;
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label for="theme-accent" class={labelClass}>Accent</Label>
|
||||
<div class="flex items-center gap-2">
|
||||
@@ -4879,7 +5249,11 @@
|
||||
onchange={setVariableDefault}
|
||||
/>
|
||||
|
||||
<ThemeSection title="Launcher Layout & Chrome" contentClass="space-y-3 pt-2.5">
|
||||
<ThemeSection
|
||||
title="Launcher Layout & Chrome"
|
||||
icon={LayoutGrid}
|
||||
contentClass="space-y-3 pt-2.5"
|
||||
>
|
||||
<div class="space-y-1.5">
|
||||
<Label class={labelClass}>Layout Preset</Label>
|
||||
<div class="grid grid-cols-3 gap-1 rounded-md bg-black/30 p-1">
|
||||
@@ -5064,7 +5438,7 @@
|
||||
</div>
|
||||
</ThemeSection>
|
||||
|
||||
<ThemeSection title="Background" contentClass="space-y-3 pt-2.5">
|
||||
<ThemeSection title="Background" icon={ImageIcon} contentClass="space-y-3 pt-2.5">
|
||||
<div class="grid grid-cols-4 gap-1 rounded-md bg-black/30 p-1">
|
||||
{#each backgroundTypes as option (option.value)}
|
||||
<Button
|
||||
@@ -5390,6 +5764,48 @@
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="space-y-2 border-t border-theme-800/60 pt-2.5">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<Label class={labelClass}>Mouse parallax</Label>
|
||||
<p class="text-[10px] text-muted-foreground">
|
||||
3D depth perspective on mouse move
|
||||
</p>
|
||||
</div>
|
||||
<Checkbox
|
||||
checked={definition.parallax?.enabled ?? false}
|
||||
onCheckedChange={(checked) => {
|
||||
if (!definition.parallax) {
|
||||
definition.parallax = { enabled: false, intensity: 0.25 };
|
||||
}
|
||||
definition.parallax.enabled = checked;
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{#if definition.parallax?.enabled}
|
||||
<div class="space-y-1.5 pt-1">
|
||||
<div class="flex items-center justify-between">
|
||||
<Label class={labelClass}>Parallax intensity</Label>
|
||||
<span class="font-mono text-xs text-muted-foreground">
|
||||
{Math.round((definition.parallax.intensity ?? 0.25) * 100)}%
|
||||
</span>
|
||||
</div>
|
||||
<Slider
|
||||
min={0.05}
|
||||
max={1}
|
||||
step={0.05}
|
||||
value={definition.parallax.intensity ?? 0.25}
|
||||
onValueChange={(val) => {
|
||||
if (!definition.parallax) {
|
||||
definition.parallax = { enabled: true, intensity: 0.25 };
|
||||
}
|
||||
definition.parallax.intensity = val;
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</ThemeSection>
|
||||
|
||||
<ThemeSection title="Typography" icon={Type} open={false} contentClass="space-y-3 pt-2.5">
|
||||
@@ -5579,7 +5995,10 @@
|
||||
size="icon"
|
||||
class="size-8 text-muted-foreground"
|
||||
title="Remove music"
|
||||
onclick={() => (definition.audio = undefined)}
|
||||
onclick={() => {
|
||||
definition.audio = undefined;
|
||||
lastAudio = undefined;
|
||||
}}
|
||||
>
|
||||
<X class="size-3.5" />
|
||||
</Button>
|
||||
@@ -5717,6 +6136,13 @@
|
||||
>
|
||||
<div
|
||||
style="width:{CANVAS_WIDTH}px;height:{CANVAS_HEIGHT}px;transform:scale({canvasScale});transform-origin:top left;"
|
||||
>
|
||||
<div
|
||||
class="contents"
|
||||
use:themeParallax={{
|
||||
enabled: definition.parallax?.enabled === true,
|
||||
intensity: definition.parallax?.intensity ?? 0.25,
|
||||
}}
|
||||
>
|
||||
<ThemeStage
|
||||
{definition}
|
||||
@@ -5739,6 +6165,7 @@
|
||||
onbuttonaction={handleTestButtonAction}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</ContextMenu.Trigger>
|
||||
|
||||
<ContextMenu.Content class="w-56 border-theme-700 bg-theme-950">
|
||||
@@ -5830,6 +6257,7 @@
|
||||
<div class="min-h-0 flex-1 space-y-3 overflow-y-auto p-3">
|
||||
<ThemeSection
|
||||
title="Align"
|
||||
icon={AlignCenter}
|
||||
bordered={false}
|
||||
headingClass="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground"
|
||||
contentClass="space-y-2 pt-2"
|
||||
@@ -5875,6 +6303,7 @@
|
||||
</ThemeSection>
|
||||
<ThemeSection
|
||||
title="Distribute"
|
||||
icon={AlignHorizontalSpaceAround}
|
||||
headingClass="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground"
|
||||
contentClass="space-y-2 pt-2.5"
|
||||
>
|
||||
@@ -5898,6 +6327,7 @@
|
||||
</ThemeSection>
|
||||
<ThemeSection
|
||||
title="Layers"
|
||||
icon={Layers}
|
||||
headingClass="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground"
|
||||
contentClass="space-y-2 pt-2.5"
|
||||
>
|
||||
@@ -6221,6 +6651,7 @@
|
||||
|
||||
<ThemeSection
|
||||
title="Theme summary"
|
||||
icon={FileText}
|
||||
class="mt-4"
|
||||
bordered={false}
|
||||
contentClass="space-y-2 pt-2"
|
||||
@@ -6249,6 +6680,7 @@
|
||||
|
||||
<ThemeSection
|
||||
title="Shortcuts"
|
||||
icon={Keyboard}
|
||||
class="mt-4"
|
||||
bordered={false}
|
||||
open={false}
|
||||
@@ -6569,4 +7001,172 @@
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if publishModalOpen}
|
||||
<div
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-black/75 p-6 backdrop-blur-md"
|
||||
role="presentation"
|
||||
>
|
||||
<div
|
||||
class="w-full max-w-lg rounded-2xl border border-theme-800 bg-theme-950 p-6 shadow-2xl"
|
||||
role="dialog"
|
||||
aria-labelledby="publish-dialog-title"
|
||||
>
|
||||
<div class="flex items-center justify-between border-b border-theme-800/60 pb-3">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="rounded-lg bg-cyan-500/10 p-2 text-cyan-400">
|
||||
<Globe class="size-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 id="publish-dialog-title" class="text-base font-semibold text-white">
|
||||
Publish to Community Workshop
|
||||
</h2>
|
||||
<p class="text-[11px] text-muted-foreground">
|
||||
Share your theme with the EZPPFarm community.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{#if !publishing}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="size-7 text-muted-foreground hover:text-white"
|
||||
onclick={() => (publishModalOpen = false)}
|
||||
>
|
||||
<X class="size-4" />
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if $currentUser}
|
||||
<div
|
||||
class="mt-4 flex items-center justify-between rounded-xl border border-theme-800/70 bg-theme-900/40 px-3.5 py-2.5"
|
||||
>
|
||||
<div class="flex items-center gap-2.5">
|
||||
<img
|
||||
src={`https://a.ez-pp.farm/${$currentUser.id}`}
|
||||
alt={$currentUser.name}
|
||||
class="size-8 rounded-full border border-white/20 bg-theme-800 object-cover"
|
||||
onerror={(e) => {
|
||||
(e.currentTarget as HTMLElement).style.display = 'none';
|
||||
}}
|
||||
/>
|
||||
<div>
|
||||
<div class="flex items-center gap-1.5">
|
||||
<span class="text-xs font-semibold text-white">{$currentUser.name}</span>
|
||||
{#if $currentUser.donor}
|
||||
<span
|
||||
class="rounded bg-amber-500/20 px-1 py-0.2 text-[8px] font-bold text-amber-300 border border-amber-500/30"
|
||||
>
|
||||
Supporter
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
<span class="text-[10px] text-muted-foreground">Creator & Publisher</span>
|
||||
</div>
|
||||
</div>
|
||||
<span class="text-[10px] text-emerald-400 font-medium">Verified Account</span>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mt-4 space-y-3 rounded-xl border border-theme-800/70 bg-theme-900/25 p-4">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<p class="truncate text-sm font-semibold text-white">
|
||||
{definition.name || 'Untitled theme'}
|
||||
</p>
|
||||
<p class="mt-0.5 text-[10px] text-muted-foreground">
|
||||
by {definition.author || 'Unknown'} · v{definition.version || '1.0.0'}
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
class="shrink-0 rounded-full border border-cyan-500/30 bg-cyan-500/10 px-2 py-0.5 font-mono text-[10px] text-cyan-300"
|
||||
>
|
||||
API {definition.apiVersion || '2.0.0'}
|
||||
</span>
|
||||
</div>
|
||||
<p class="text-xs leading-relaxed text-muted-foreground">
|
||||
{definition.description?.trim() || 'No description yet.'}
|
||||
</p>
|
||||
<div class="grid grid-cols-2 gap-3 border-t border-theme-800/60 pt-3">
|
||||
<div class="min-w-0">
|
||||
<span class="text-[10px] font-medium uppercase tracking-wide text-muted-foreground">
|
||||
Workshop ID
|
||||
</span>
|
||||
{#if publishThemeId}
|
||||
<p class="mt-1 truncate font-mono text-[11px] text-theme-100">{publishThemeId}</p>
|
||||
{:else}
|
||||
<p class="mt-1 text-[11px] text-muted-foreground">
|
||||
Assigned by EZPPFarm on publish
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-[10px] font-medium uppercase tracking-wide text-muted-foreground">
|
||||
Tags
|
||||
</span>
|
||||
{#if (definition.tags ?? []).length > 0}
|
||||
<div class="mt-1 flex flex-wrap gap-1">
|
||||
{#each definition.tags ?? [] as tag (tag)}
|
||||
<span class="rounded bg-theme-800 px-1.5 py-0.5 text-[10px] text-theme-100">
|
||||
{tag}
|
||||
</span>
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="mt-1 text-[10px] text-muted-foreground">No tags</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
<p class="text-[10px] leading-relaxed text-muted-foreground/70">
|
||||
These details come from the Theme tab. Published versions cannot be reused, so increase
|
||||
the version before every update.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{#if publishing}
|
||||
<div class="mt-4 rounded-xl border border-cyan-500/20 bg-cyan-950/20 p-3">
|
||||
<div class="flex items-center justify-between text-xs">
|
||||
<span class="flex items-center gap-1.5 text-cyan-300 font-medium">
|
||||
<LoaderCircle class="size-3.5 animate-spin" />
|
||||
{publishStatusMessage}
|
||||
</span>
|
||||
<span class="font-mono text-cyan-400 font-bold tabular-nums">{publishProgress}%</span>
|
||||
</div>
|
||||
<div class="mt-2 h-1.5 w-full overflow-hidden rounded-full bg-theme-900">
|
||||
<div
|
||||
class="h-full bg-cyan-400 transition-all duration-300"
|
||||
style="width: {publishProgress}%"
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mt-5 flex justify-end gap-2 border-t border-theme-800/60 pt-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onclick={() => (publishModalOpen = false)}
|
||||
disabled={publishing}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
class="bg-cyan-600 hover:bg-cyan-500 text-white font-medium gap-1.5"
|
||||
onclick={handlePublishToWorkshop}
|
||||
disabled={publishing || definition.name.trim().length === 0}
|
||||
>
|
||||
{#if publishing}
|
||||
<LoaderCircle class="size-3.5 animate-spin" />
|
||||
Publishing...
|
||||
{:else}
|
||||
<Globe class="size-3.5" />
|
||||
Publish to Workshop
|
||||
{/if}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -15,9 +15,9 @@
|
||||
import * as Select from '$lib/components/ui/select';
|
||||
import Slider from '$lib/components/ui/slider/slider.svelte';
|
||||
import Textarea from '$lib/components/ui/textarea/textarea.svelte';
|
||||
import { getThemeDataSampleValue, resolveThemeDataValue, themeGlobalData } from '$lib/themeData';
|
||||
import type { ThemeFontChoice } from '$lib/themeFonts';
|
||||
import { DEFAULT_THEME_ICON_SET, type ThemeIconSet } from '$lib/themeIcons';
|
||||
import { getThemeDataSampleValue, resolveThemeDataValue, themeGlobalData } from '$lib/theme/themeData';
|
||||
import type { ThemeFontChoice } from '$lib/theme/themeFonts';
|
||||
import { DEFAULT_THEME_ICON_SET, type ThemeIconSet } from '$lib/theme/themeIcons';
|
||||
import {
|
||||
THEME_DATA_FIELDS,
|
||||
THEME_PARTICLE_PRESETS,
|
||||
@@ -29,7 +29,7 @@
|
||||
type ThemeV2MaskShape,
|
||||
type ThemeV2WidgetKind,
|
||||
type ThemeV2WidgetVariant,
|
||||
} from '$lib/themeV2';
|
||||
} from '$lib/theme/themeV2';
|
||||
import { openURL } from '$lib/utils';
|
||||
import {
|
||||
CircleUser,
|
||||
@@ -38,12 +38,15 @@
|
||||
Film,
|
||||
Gauge,
|
||||
Image as ImageIcon,
|
||||
Layers,
|
||||
LayoutGrid,
|
||||
Megaphone,
|
||||
MousePointerClick,
|
||||
Move,
|
||||
Play,
|
||||
RefreshCw,
|
||||
Repeat,
|
||||
Scan,
|
||||
Shapes,
|
||||
Sparkles,
|
||||
Spline,
|
||||
@@ -221,7 +224,7 @@
|
||||
</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">
|
||||
<Label for="element-name" class={label}>Layer name</Label>
|
||||
<Input
|
||||
@@ -290,6 +293,7 @@
|
||||
|
||||
<ThemeSection
|
||||
title="Layer state"
|
||||
icon={Layers}
|
||||
contentClass="flex flex-wrap items-center gap-x-4 gap-y-2 pt-2.5"
|
||||
>
|
||||
<div class="flex items-center gap-1.5">
|
||||
@@ -402,7 +406,11 @@
|
||||
/>
|
||||
|
||||
{#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'}
|
||||
<div class="space-y-1.5">
|
||||
<Label for="element-data-field" class={label}>Value</Label>
|
||||
@@ -695,7 +703,7 @@
|
||||
<ThemeTextStyleControls {element} onchange={(patch) => Object.assign(element, patch)} />
|
||||
</ThemeSection>
|
||||
{: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
|
||||
class="rounded-md border border-amber-500/25 bg-amber-500/10 p-2 text-[9px] leading-relaxed text-amber-100"
|
||||
>
|
||||
@@ -721,7 +729,7 @@
|
||||
</div>
|
||||
</ThemeSection>
|
||||
{: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">
|
||||
<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>
|
||||
@@ -829,7 +837,7 @@
|
||||
{/if}
|
||||
</ThemeSection>
|
||||
{: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">
|
||||
<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>
|
||||
@@ -885,7 +893,7 @@
|
||||
</p>
|
||||
</ThemeSection>
|
||||
{: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">
|
||||
<Label for="element-shape" class={label}>Shape</Label>
|
||||
<Select.Root
|
||||
@@ -1153,7 +1161,7 @@
|
||||
</div>
|
||||
</ThemeSection>
|
||||
{: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">
|
||||
<Label for="element-icon" class={label}>Icon</Label>
|
||||
<ThemeIconPicker bind:value={element.icon} {iconSet} />
|
||||
@@ -1185,7 +1193,7 @@
|
||||
</div>
|
||||
</ThemeSection>
|
||||
{: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">
|
||||
<Label for="element-repeater-source" class={label}>Tile</Label>
|
||||
<Select.Root
|
||||
@@ -1307,7 +1315,7 @@
|
||||
</p>
|
||||
</ThemeSection>
|
||||
{: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="space-y-1">
|
||||
<Label for="element-gauge-mode" class={label}>Style</Label>
|
||||
@@ -1423,7 +1431,7 @@
|
||||
</div>
|
||||
</ThemeSection>
|
||||
{: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">
|
||||
<Label for="element-ticker-text" class={label}>Text</Label>
|
||||
<Textarea
|
||||
@@ -1520,7 +1528,7 @@
|
||||
{/if}
|
||||
</ThemeSection>
|
||||
{: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">
|
||||
<Label for="element-button-label" class={label}>Label</Label>
|
||||
<Input id="element-button-label" class={field} bind:value={element.label} />
|
||||
@@ -1704,7 +1712,7 @@
|
||||
</div>
|
||||
</ThemeSection>
|
||||
{: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">
|
||||
<Label for="element-path-data" class={label}>SVG path data</Label>
|
||||
<Textarea
|
||||
@@ -1850,7 +1858,7 @@
|
||||
</div>
|
||||
</ThemeSection>
|
||||
{: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">
|
||||
<Label for="element-particles-preset" class={label}>Preset</Label>
|
||||
<Select.Root
|
||||
@@ -1954,7 +1962,7 @@
|
||||
</p>
|
||||
</ThemeSection>
|
||||
{: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">
|
||||
<Label for="element-clock-mode" class={label}>Style</Label>
|
||||
<Select.Root
|
||||
@@ -2121,7 +2129,7 @@
|
||||
</p>
|
||||
</ThemeSection>
|
||||
{: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">
|
||||
<Label for="element-countdown-target" class={label}>Target date & time</Label>
|
||||
<DatePicker
|
||||
@@ -2220,7 +2228,7 @@
|
||||
</div>
|
||||
</ThemeSection>
|
||||
{:else if element.type === 'widget'}
|
||||
<ThemeSection title="Widget" contentClass="space-y-3 pt-2.5">
|
||||
<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
|
||||
@@ -2231,7 +2239,7 @@
|
||||
element.widget = val as ThemeV2WidgetKind;
|
||||
if (val === 'player-card') {
|
||||
element.width = 380;
|
||||
element.height = 180;
|
||||
element.height = 220;
|
||||
} else if (val === 'avatar') {
|
||||
element.width = 72;
|
||||
element.height = 72;
|
||||
@@ -2296,12 +2304,18 @@
|
||||
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 = 120;
|
||||
element.height = 140;
|
||||
element.showStats = true;
|
||||
} else if (val === 'full') {
|
||||
element.width = 380;
|
||||
element.height = 200;
|
||||
element.height = 220;
|
||||
element.showStats = true;
|
||||
}
|
||||
} else if (element.widget === 'recent-activity') {
|
||||
if (val === 'minimal') {
|
||||
@@ -2322,7 +2336,7 @@
|
||||
element.width = 140;
|
||||
element.height = 42;
|
||||
} else if (val === 'primary') {
|
||||
element.width = 210;
|
||||
element.width = 256;
|
||||
element.height = 48;
|
||||
}
|
||||
} else if (element.widget === 'header') {
|
||||
@@ -2356,6 +2370,14 @@
|
||||
: 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'
|
||||
@@ -2373,6 +2395,11 @@
|
||||
<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" />
|
||||
@@ -2382,6 +2409,33 @@
|
||||
</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>
|
||||
@@ -2512,7 +2566,7 @@
|
||||
</ThemeSection>
|
||||
{/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">
|
||||
<Label for="element-mask-shape" class={label}>Clip shape</Label>
|
||||
<Select.Root
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
import ThemeSection from '$lib/components/theme/ThemeSection.svelte';
|
||||
import Button from '$lib/components/ui/button/button.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 {
|
||||
filters,
|
||||
@@ -67,6 +68,7 @@
|
||||
|
||||
<ThemeSection
|
||||
title="Filters"
|
||||
icon={SlidersHorizontal}
|
||||
open={false}
|
||||
actions={filterActions}
|
||||
contentClass="space-y-2.5 pt-2.5"
|
||||
|
||||
@@ -16,8 +16,8 @@
|
||||
type ThemeV2Element,
|
||||
type ThemeV2Group,
|
||||
type ThemeV2MaskShape,
|
||||
} from '$lib/themeV2';
|
||||
import { Boxes, RefreshCw, Ungroup } from '@lucide/svelte';
|
||||
} from '$lib/theme/themeV2';
|
||||
import { Boxes, Layers, RefreshCw, Scan, Ungroup } from '@lucide/svelte';
|
||||
|
||||
let {
|
||||
group = $bindable(),
|
||||
@@ -58,7 +58,7 @@
|
||||
</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">
|
||||
<Label for="group-name" class={label}>Group name</Label>
|
||||
<Input
|
||||
@@ -96,6 +96,7 @@
|
||||
|
||||
<ThemeSection
|
||||
title="Group state"
|
||||
icon={Layers}
|
||||
contentClass="flex flex-wrap items-center gap-x-4 gap-y-2 pt-2.5"
|
||||
>
|
||||
<div class="flex items-center gap-1.5">
|
||||
@@ -167,7 +168,7 @@
|
||||
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">
|
||||
<Label for="group-mask-shape" class={label}>Clip shape</Label>
|
||||
<Select.Root
|
||||
|
||||
@@ -1,17 +1,23 @@
|
||||
<script lang="ts">
|
||||
import { getThemeIconBody } from '$lib/themeIconCatalog';
|
||||
import { DEFAULT_THEME_ICON_SET, type ThemeIconName, type ThemeIconSet } from '$lib/themeIcons';
|
||||
import { getThemeIconBody } from '$lib/theme/themeIconCatalog';
|
||||
import {
|
||||
DEFAULT_THEME_ICON_SET,
|
||||
type ThemeIconName,
|
||||
type ThemeIconSet,
|
||||
} from '$lib/theme/themeIcons';
|
||||
|
||||
let {
|
||||
name,
|
||||
set = DEFAULT_THEME_ICON_SET,
|
||||
size = '1em',
|
||||
class: className = '',
|
||||
style = '',
|
||||
}: {
|
||||
name: ThemeIconName;
|
||||
set?: ThemeIconSet;
|
||||
size?: number | string;
|
||||
class?: string;
|
||||
style?: string;
|
||||
} = $props();
|
||||
|
||||
const icon = $derived(getThemeIconBody(name, set));
|
||||
@@ -23,6 +29,7 @@
|
||||
width={size}
|
||||
height={size}
|
||||
class={className}
|
||||
{style}
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
>
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
getFullIconCatalog,
|
||||
type IconPackKey,
|
||||
type ThemeIconCatalogItem,
|
||||
} from '$lib/themeIconCatalog';
|
||||
import { DEFAULT_THEME_ICON_SET, type ThemeIconSet } from '$lib/themeIcons';
|
||||
} from '$lib/theme/themeIconCatalog';
|
||||
import { DEFAULT_THEME_ICON_SET, type ThemeIconSet } from '$lib/theme/themeIcons';
|
||||
import ThemeIcon from './ThemeIcon.svelte';
|
||||
import { Check, ChevronsUpDown, LayoutGrid, List, Search, X } from '@lucide/svelte';
|
||||
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
<script lang="ts">
|
||||
import ThemeBehaviorInspector from '$lib/components/theme/ThemeBehaviorInspector.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 {
|
||||
ThemeV2Behavior,
|
||||
ThemeV2BehaviorTarget,
|
||||
ThemeV2Element,
|
||||
ThemeV2Group,
|
||||
} from '$lib/themeV2';
|
||||
} from '$lib/theme/themeV2';
|
||||
import { AlertTriangle, ChevronDown, Plus, Zap } from '@lucide/svelte';
|
||||
|
||||
let {
|
||||
@@ -30,8 +31,13 @@
|
||||
ondelete: (id: string) => void;
|
||||
} = $props();
|
||||
|
||||
let open = $state(false);
|
||||
const sectionKey = 'Logic';
|
||||
let open = $state(themeEditorSectionOpen.get(sectionKey) ?? false);
|
||||
let selectedId = $state<string | undefined>(undefined);
|
||||
|
||||
$effect(() => {
|
||||
themeEditorSectionOpen.set(sectionKey, open);
|
||||
});
|
||||
let section = $state<HTMLElement>();
|
||||
let lastFocusToken = 0;
|
||||
|
||||
|
||||
@@ -17,12 +17,38 @@
|
||||
let container = $state<HTMLDivElement | undefined>(undefined);
|
||||
let animation: AnimationItem | undefined;
|
||||
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(() => {
|
||||
if (!container || !src) return;
|
||||
reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? 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) => {
|
||||
if (cancelled || !container) return;
|
||||
try {
|
||||
@@ -30,7 +56,8 @@
|
||||
container,
|
||||
renderer: 'svg',
|
||||
loop,
|
||||
autoplay: autoplay && !reducedMotion,
|
||||
autoplay:
|
||||
autoplay && !reducedMotion && windowActive && document.visibilityState === 'visible',
|
||||
...(animationData ? { animationData } : { path: src }),
|
||||
rendererSettings: { preserveAspectRatio: 'xMidYMid meet' },
|
||||
});
|
||||
@@ -52,15 +79,14 @@
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.removeEventListener('blur', onBlur);
|
||||
window.removeEventListener('focus', onFocus);
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange);
|
||||
};
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (!animation) return;
|
||||
animation.loop = loop;
|
||||
animation.setSpeed(speed);
|
||||
if (autoplay && !reducedMotion) animation.play();
|
||||
else animation.pause();
|
||||
syncPlayback();
|
||||
});
|
||||
|
||||
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">
|
||||
import { isThemeClockVariable, THEME_CLOCK_VARIABLE_NAMES } from '$lib/themeClock';
|
||||
import { parseThemeScript } from '$lib/themeScriptLang';
|
||||
import type { ThemeV2Element, ThemeV2Group, ThemeV2ScriptScreen } from '$lib/themeV2';
|
||||
import { isThemeClockVariable, THEME_CLOCK_VARIABLE_NAMES } from '$lib/theme/themeClock';
|
||||
import { parseThemeScript } from '$lib/theme/themeScriptLang';
|
||||
import type { ThemeV2Element, ThemeV2Group, ThemeV2ScriptScreen } from '$lib/theme/themeV2';
|
||||
import { Braces, CircleAlert, Maximize2, Minimize2, X } from '@lucide/svelte';
|
||||
import type * as Monaco from 'monaco-editor';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
<script lang="ts">
|
||||
import { themeEditorSectionOpen } from '$lib/theme/themeEditorUiState';
|
||||
import { ChevronDown } from '@lucide/svelte';
|
||||
import { untrack } from 'svelte';
|
||||
import type { Component, Snippet } from 'svelte';
|
||||
|
||||
let {
|
||||
title,
|
||||
open = $bindable(true),
|
||||
open: initialOpen = true,
|
||||
icon: Icon,
|
||||
badge,
|
||||
description,
|
||||
@@ -27,6 +29,12 @@
|
||||
headingClass?: string;
|
||||
bordered?: boolean;
|
||||
} = $props();
|
||||
|
||||
let isOpen = $state(untrack(() => themeEditorSectionOpen.get(title) ?? initialOpen));
|
||||
|
||||
$effect(() => {
|
||||
themeEditorSectionOpen.set(title, isOpen);
|
||||
});
|
||||
</script>
|
||||
|
||||
<section class="{bordered ? 'border-t border-theme-800 pt-3 ' : ''}{className}">
|
||||
@@ -34,8 +42,8 @@
|
||||
<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"
|
||||
aria-expanded={open}
|
||||
onclick={() => (open = !open)}
|
||||
aria-expanded={isOpen}
|
||||
onclick={() => (isOpen = !isOpen)}
|
||||
>
|
||||
{#if Icon}
|
||||
<Icon class="size-3.5 shrink-0 text-primary" />
|
||||
@@ -49,7 +57,7 @@
|
||||
</span>
|
||||
{/if}
|
||||
<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'
|
||||
: ''}"
|
||||
/>
|
||||
@@ -61,7 +69,7 @@
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if open}
|
||||
{#if isOpen}
|
||||
<div class={contentClass}>
|
||||
{#if description}
|
||||
<p class="text-[10px] leading-relaxed text-muted-foreground">{description}</p>
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
import ThemeV2Elements from '$lib/components/theme/ThemeV2Elements.svelte';
|
||||
import * as Avatar from '$lib/components/ui/avatar';
|
||||
import { currentUserInfo } from '$lib/data';
|
||||
import { scopeThemeCss } from '$lib/themeCssScope';
|
||||
import { fontStack, monoFontStack } from '$lib/themeFonts';
|
||||
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 {
|
||||
normalizeChrome,
|
||||
readableTextColor,
|
||||
@@ -18,7 +18,7 @@
|
||||
type ThemeV2Group,
|
||||
type ThemeV2ScriptValue,
|
||||
type ThemeV2WidgetKind,
|
||||
} from '$lib/themeV2';
|
||||
} from '$lib/theme/themeV2';
|
||||
import { currentUser } from '$lib/userAuthentication';
|
||||
import { countryCodeToEmoji } from '$lib/utils';
|
||||
import { Clock, Trophy } from '@lucide/svelte';
|
||||
|
||||
@@ -4,8 +4,12 @@
|
||||
import Input from '$lib/components/ui/input/input.svelte';
|
||||
import Label from '$lib/components/ui/label/label.svelte';
|
||||
import * as Select from '$lib/components/ui/select';
|
||||
import type { ThemeV2TextDecoration, ThemeV2TextStyle, ThemeV2TextTransform } from '$lib/themeV2';
|
||||
import { Bold, Italic, RotateCcw, Strikethrough, Underline } from '@lucide/svelte';
|
||||
import type {
|
||||
ThemeV2TextDecoration,
|
||||
ThemeV2TextStyle,
|
||||
ThemeV2TextTransform,
|
||||
} from '$lib/theme/themeV2';
|
||||
import { Bold, Italic, RotateCcw, Strikethrough, Type, Underline } from '@lucide/svelte';
|
||||
|
||||
let {
|
||||
element,
|
||||
@@ -89,6 +93,7 @@
|
||||
|
||||
<ThemeSection
|
||||
title="Text style"
|
||||
icon={Type}
|
||||
open={false}
|
||||
actions={textStyleActions}
|
||||
contentClass="space-y-2 pt-2.5"
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
import Button from '$lib/components/ui/button/button.svelte';
|
||||
import Input from '$lib/components/ui/input/input.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';
|
||||
|
||||
type TransformTarget = ThemeV2Transform & { offsetX?: number; offsetY?: number };
|
||||
@@ -34,6 +35,7 @@
|
||||
(transform.skewY ?? 0) === 0 &&
|
||||
!transform.flipX &&
|
||||
!transform.flipY &&
|
||||
(transform.parallax ?? 0) === 0 &&
|
||||
(!includeTranslate || ((transform.offsetX ?? 0) === 0 && (transform.offsetY ?? 0) === 0))
|
||||
);
|
||||
|
||||
@@ -87,6 +89,7 @@
|
||||
skewY: 0,
|
||||
flipX: false,
|
||||
flipY: false,
|
||||
parallax: 0,
|
||||
...(includeTranslate ? { offsetX: 0, offsetY: 0 } : {}),
|
||||
});
|
||||
}
|
||||
@@ -110,6 +113,7 @@
|
||||
|
||||
<ThemeSection
|
||||
title="Transform"
|
||||
icon={RotateCw}
|
||||
open={false}
|
||||
actions={transformActions}
|
||||
contentClass="space-y-2 pt-2.5"
|
||||
@@ -257,4 +261,24 @@
|
||||
</Button>
|
||||
</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>
|
||||
@@ -1,10 +1,12 @@
|
||||
<script lang="ts">
|
||||
import { custom_theme_volume } from '$lib/global';
|
||||
import { themeMediaSource, themeVideoLifecycle } from '$lib/themeMedia';
|
||||
import type { ThemeV2Definition } from '$lib/themeV2';
|
||||
import { themeAssetUrl } from '$lib/themeV2';
|
||||
import { playThemeMedia, themeMediaSource, themeVideoLifecycle } from '$lib/theme/themeMedia';
|
||||
import { themeParallax } from '$lib/theme/themeParallax';
|
||||
import type { ThemeV2Definition } from '$lib/theme/themeV2';
|
||||
import { themeAssetUrl } from '$lib/theme/themeV2';
|
||||
import { reduceAnimations } from '$lib/userSettings';
|
||||
import { trackMediaContainer } from '$lib/utils';
|
||||
import { onDestroy } from 'svelte';
|
||||
|
||||
let {
|
||||
definition,
|
||||
@@ -20,6 +22,17 @@
|
||||
|
||||
let audioElement = $state<HTMLAudioElement | undefined>(undefined);
|
||||
|
||||
onDestroy(() => {
|
||||
if (audioElement) {
|
||||
try {
|
||||
audioElement.pause();
|
||||
audioElement.src = '';
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const assetUrl = (path: string | undefined) => {
|
||||
if (!path) return '';
|
||||
return assetOverrides[path] ?? themeAssetUrl(assets, path);
|
||||
@@ -43,17 +56,19 @@
|
||||
return Array.from({ length: count }, (_, index) => {
|
||||
const value = (offset: number) => random(index + 1 + offset);
|
||||
const isStar = effects.type === 'stars';
|
||||
const size = isStar ? 1 + value(1) * 2.5 : 4 + value(1) * 7;
|
||||
const duration = (isStar ? 2 + value(2) * 3 : 9 + value(2) * 11) / speed;
|
||||
const isEmber = effects.type === 'embers';
|
||||
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 {
|
||||
id: index,
|
||||
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,
|
||||
duration,
|
||||
delay: value(5) * duration,
|
||||
drift: -90 + value(6) * 180,
|
||||
opacity: 0.25 + value(7) * 0.65,
|
||||
drift: isEmber ? -50 + value(6) * 100 : -90 + value(6) * 180,
|
||||
opacity: isEmber ? 0.35 + value(7) * 0.65 : 0.25 + value(7) * 0.65,
|
||||
rotate: value(8) * 360,
|
||||
};
|
||||
});
|
||||
@@ -78,15 +93,21 @@
|
||||
$effect(() => {
|
||||
if (!audioElement || !definition.audio) return;
|
||||
audioElement.volume = $custom_theme_volume;
|
||||
if (!preview) {
|
||||
audioElement.play().catch(() => {
|
||||
// Autoplay can be rejected until the window has been interacted with.
|
||||
});
|
||||
if (!preview && audioElement.paused) {
|
||||
playThemeMedia(audioElement);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="theme-v2 absolute inset-0 overflow-hidden" use:trackMedia>
|
||||
<div
|
||||
class="absolute inset-0"
|
||||
use:themeParallax={{
|
||||
enabled: definition.parallax?.enabled === true,
|
||||
intensity: definition.parallax?.intensity ?? 0.25,
|
||||
}}
|
||||
style="transform:translate3d(calc(var(--mouse-px, 0) * -18px), calc(var(--mouse-py, 0) * -18px), 0);"
|
||||
>
|
||||
{#if background.type === 'color'}
|
||||
<div
|
||||
class="absolute inset-0"
|
||||
@@ -96,7 +117,8 @@
|
||||
<div
|
||||
class="absolute inset-0"
|
||||
style="background-image:linear-gradient({background.angle ??
|
||||
135}deg, {background.from}, {background.to});opacity:{background.opacity ?? 1}"
|
||||
135}deg, {background.from}, {background.to});opacity:{background.opacity ??
|
||||
1};transform:{definition.parallax?.enabled ? 'scale(1.06)' : 'none'}"
|
||||
></div>
|
||||
{:else if background.type === 'image'}
|
||||
{#if background.src}
|
||||
@@ -108,7 +130,11 @@
|
||||
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'};"
|
||||
: 'none'};transform:{background.blur
|
||||
? 'scale(1.08)'
|
||||
: definition.parallax?.enabled
|
||||
? 'scale(1.06)'
|
||||
: 'none'};"
|
||||
/>
|
||||
{/if}
|
||||
{:else if background.type === 'video'}
|
||||
@@ -126,10 +152,15 @@
|
||||
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'};"
|
||||
: 'none'};transform:{background.blur
|
||||
? 'scale(1.08)'
|
||||
: definition.parallax?.enabled
|
||||
? 'scale(1.06)'
|
||||
: 'none'};"
|
||||
></video>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if overlay && (overlay.opacity ?? 0) > 0}
|
||||
<div
|
||||
@@ -163,6 +194,8 @@
|
||||
use:themeMediaSource={assetUrl(definition.audio.src)}
|
||||
loop={definition.audio.loop !== false}
|
||||
autoplay
|
||||
preload="auto"
|
||||
playsinline
|
||||
></audio>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -204,6 +237,33 @@
|
||||
animation-name: v2-stars;
|
||||
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 {
|
||||
|
||||
@@ -3,11 +3,12 @@
|
||||
import ThemeIcon from '$lib/components/theme/ThemeIcon.svelte';
|
||||
import ThemeLottieLayer from '$lib/components/theme/ThemeLottieLayer.svelte';
|
||||
import * as Avatar from '$lib/components/ui/avatar';
|
||||
import DownloadButton from '$lib/components/ui/download-button/DownloadButton.svelte';
|
||||
import { currentUserInfo } from '$lib/data';
|
||||
import { launching as launchingStore } from '$lib/global';
|
||||
import { getThemeDataSampleValue, resolveThemeDataValue, themeGlobalData } from '$lib/themeData';
|
||||
import { fontStack } from '$lib/themeFonts';
|
||||
import { DEFAULT_THEME_ICON_SET, type ThemeIconSet } from '$lib/themeIcons';
|
||||
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 {
|
||||
themeArcGeometry,
|
||||
themeClockDate,
|
||||
@@ -15,9 +16,9 @@
|
||||
themeCountdownText,
|
||||
themeParticleSeeds,
|
||||
themeSvgGradientVector,
|
||||
} from '$lib/themeLayers';
|
||||
import { themeMediaSource, themeVideoLifecycle } from '$lib/themeMedia';
|
||||
import { interpolateThemeText } from '$lib/themeTextVariables';
|
||||
} from '$lib/theme/themeLayers';
|
||||
import { themeMediaSource, themeVideoLifecycle } from '$lib/theme/themeMedia';
|
||||
import { interpolateThemeText } from '$lib/theme/themeTextVariables';
|
||||
import {
|
||||
themeAssetUrl,
|
||||
themeClassNames,
|
||||
@@ -41,7 +42,7 @@
|
||||
type ThemeV2Group,
|
||||
type ThemeV2Point,
|
||||
type ThemeV2ScriptValue,
|
||||
} from '$lib/themeV2';
|
||||
} from '$lib/theme/themeV2';
|
||||
import { currentUser } from '$lib/userAuthentication';
|
||||
import { countryCodeToEmoji, formatRelativeTime, openURL } from '$lib/utils';
|
||||
import { Boxes, ChevronRight, Clock, Move, RotateCw, Trophy } from '@lucide/svelte';
|
||||
@@ -70,6 +71,7 @@
|
||||
launching = undefined,
|
||||
launchProgress = -1,
|
||||
launchText = 'Launch',
|
||||
launchSubtext = undefined,
|
||||
launchDisabled = false,
|
||||
oninteraction,
|
||||
onselect,
|
||||
@@ -103,6 +105,7 @@
|
||||
launching?: boolean;
|
||||
launchProgress?: number;
|
||||
launchText?: string;
|
||||
launchSubtext?: string;
|
||||
launchDisabled?: boolean;
|
||||
oninteraction?: (id: string, type: 'click' | 'hover' | 'leave') => void;
|
||||
onselect?: (id: string | undefined, additive?: boolean) => void;
|
||||
@@ -138,6 +141,15 @@
|
||||
);
|
||||
const elementFilter = (element: ThemeV2Element) =>
|
||||
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) =>
|
||||
themeClassNames(
|
||||
[...ancestorsOf(element).map((group) => group.cssClasses), element.cssClasses]
|
||||
@@ -1224,7 +1236,7 @@
|
||||
element,
|
||||
elements,
|
||||
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`
|
||||
: 'none'};outline-offset:2px;"
|
||||
role={interactive || element.interactive ? 'button' : undefined}
|
||||
@@ -1613,14 +1625,25 @@
|
||||
}}
|
||||
>
|
||||
{#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" />
|
||||
{/if}
|
||||
{#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}
|
||||
{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
|
||||
text={String(interpolateThemeText(element.label, variables) ?? '')}
|
||||
@@ -1852,7 +1875,7 @@
|
||||
)}
|
||||
{@const btnCircumference = 2 * Math.PI * btnRadius}
|
||||
{@const strokeOffset =
|
||||
launchProgress === -1
|
||||
launchProgress < 0
|
||||
? btnCircumference * 0.7
|
||||
: btnCircumference -
|
||||
(Math.max(0, Math.min(100, launchProgress)) / 100) * btnCircumference}
|
||||
@@ -1870,12 +1893,16 @@
|
||||
onbuttonaction?.({ type: 'launch' });
|
||||
}
|
||||
}}
|
||||
title={isLaunching ? launchText : 'Launch osu!'}
|
||||
title={isLaunching
|
||||
? launchSubtext
|
||||
? `${launchText} - ${launchSubtext}`
|
||||
: launchText
|
||||
: 'Launch osu!'}
|
||||
>
|
||||
{#if isLaunching}
|
||||
<!-- Rotating progress ring SVG -->
|
||||
<svg
|
||||
class="absolute inset-0 h-full w-full {launchProgress === -1
|
||||
class="absolute inset-0 h-full w-full {launchProgress < 0
|
||||
? 'animate-spin'
|
||||
: '-rotate-90'}"
|
||||
viewBox="0 0 {element.width} {element.height}"
|
||||
@@ -1902,7 +1929,7 @@
|
||||
/>
|
||||
</svg>
|
||||
|
||||
{#if launchProgress > 0}
|
||||
{#if launchProgress >= 0}
|
||||
<span
|
||||
class="relative z-10 text-[11px] font-black tracking-tight text-primary-foreground"
|
||||
>
|
||||
@@ -1910,9 +1937,9 @@
|
||||
</span>
|
||||
{:else}
|
||||
<ThemeIcon
|
||||
name="loader"
|
||||
name="ellipsis"
|
||||
set={iconSet}
|
||||
class="relative z-10 size-6 animate-spin text-primary-foreground"
|
||||
class="relative z-10 size-4 animate-pulse text-primary-foreground"
|
||||
/>
|
||||
{/if}
|
||||
{:else}
|
||||
@@ -1934,61 +1961,53 @@
|
||||
onbuttonaction?.({ type: 'launch' });
|
||||
}
|
||||
}}
|
||||
title={isLaunching ? launchText : 'Launch osu!'}
|
||||
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"
|
||||
/>
|
||||
<span>{launchProgress > 0 ? `${Math.round(launchProgress)}%` : launchText}</span
|
||||
{/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}
|
||||
<button
|
||||
type="button"
|
||||
class="relative flex h-full w-full items-center justify-center gap-2.5 rounded-full bg-primary px-5 font-bold text-primary-foreground shadow-lg shadow-primary/30 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();
|
||||
<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' });
|
||||
}
|
||||
}}
|
||||
title={isLaunching ? launchText : 'Launch osu!'}
|
||||
>
|
||||
<div class="flex size-7 items-center justify-center rounded-full bg-black/20">
|
||||
{#if isLaunching}
|
||||
<ThemeIcon
|
||||
name="loader"
|
||||
set={iconSet}
|
||||
class="size-3.5 animate-spin text-primary-foreground"
|
||||
/>
|
||||
{:else}
|
||||
<ThemeIcon
|
||||
name="launch"
|
||||
set={iconSet}
|
||||
class="ml-0.5 size-3.5 fill-current text-primary-foreground"
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
<span class="text-sm font-bold tracking-wide">
|
||||
{isLaunching
|
||||
? launchProgress > 0
|
||||
? `${launchText} (${Math.round(launchProgress)}%)`
|
||||
: launchText
|
||||
: 'Launch'}
|
||||
</span>
|
||||
</button>
|
||||
{/if}
|
||||
{:else if element.widget === 'player-card'}
|
||||
{@const playerStats =
|
||||
@@ -2015,7 +2034,7 @@
|
||||
|
||||
{#if element.variant === 'minimal'}
|
||||
<div
|
||||
class="flex h-full w-full items-center gap-2.5 rounded-2xl border border-white/10 bg-black/55 px-3 py-2 text-theme-50 shadow-xl backdrop-blur-md"
|
||||
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
|
||||
@@ -2055,7 +2074,7 @@
|
||||
</div>
|
||||
{:else if element.variant === 'compact'}
|
||||
<div
|
||||
class="flex h-full w-full flex-col justify-between rounded-2xl border border-white/10 bg-black/55 p-3 text-theme-50 shadow-xl backdrop-blur-md"
|
||||
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">
|
||||
@@ -2113,9 +2132,56 @@
|
||||
</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 rounded-2xl border border-white/10 bg-black/55 p-3.5 text-theme-50 shadow-xl backdrop-blur-md"
|
||||
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">
|
||||
@@ -2502,7 +2568,21 @@
|
||||
<span
|
||||
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>
|
||||
{/if}
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
import ThemeSection from '$lib/components/theme/ThemeSection.svelte';
|
||||
import Button from '$lib/components/ui/button/button.svelte';
|
||||
import Input from '$lib/components/ui/input/input.svelte';
|
||||
import type { ThemeV2ScriptValue } from '$lib/themeV2';
|
||||
import { RotateCcw } from '@lucide/svelte';
|
||||
import type { ThemeV2ScriptValue } from '$lib/theme/themeV2';
|
||||
import { Braces, RotateCcw } from '@lucide/svelte';
|
||||
|
||||
let {
|
||||
variables,
|
||||
@@ -38,7 +38,12 @@
|
||||
};
|
||||
</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">
|
||||
Starting values for
|
||||
<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};
|
||||
animation-duration:{s.duration}s;
|
||||
animation-delay:-{s.delay}s;
|
||||
animation-play-state:{$reduceAnimations ? 'paused' : 'running'};
|
||||
"
|
||||
></div>
|
||||
{/each}
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
contentClass = '',
|
||||
open = $bindable(false),
|
||||
id = undefined,
|
||||
ariaLabel = undefined,
|
||||
onValueChange = undefined,
|
||||
}: {
|
||||
value?: string;
|
||||
withTime?: boolean;
|
||||
@@ -29,6 +31,8 @@
|
||||
contentClass?: string;
|
||||
open?: boolean;
|
||||
id?: string;
|
||||
ariaLabel?: string;
|
||||
onValueChange?: (value: string) => void;
|
||||
} = $props();
|
||||
|
||||
let calendarValue = $state<DateValue | undefined>(undefined);
|
||||
@@ -70,6 +74,7 @@
|
||||
if (!calendarValue) {
|
||||
lastEmittedValue = '';
|
||||
value = '';
|
||||
onValueChange?.('');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -91,6 +96,7 @@
|
||||
|
||||
lastEmittedValue = next;
|
||||
value = next;
|
||||
onValueChange?.(next);
|
||||
}
|
||||
|
||||
function handleDateChange(newDate: DateValue | undefined) {
|
||||
@@ -147,6 +153,7 @@
|
||||
<Popover.Trigger
|
||||
{id}
|
||||
{disabled}
|
||||
aria-label={ariaLabel}
|
||||
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',
|
||||
!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} />
|
||||
@@ -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">
|
||||
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: {
|
||||
downloading: boolean;
|
||||
@@ -9,23 +9,60 @@
|
||||
subtext?: string;
|
||||
disabled?: boolean;
|
||||
iconSet?: ThemeIconSet;
|
||||
class?: string;
|
||||
onClick?: () => void;
|
||||
} = $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 strokeDashoffset = $derived(circumference - (prop.progress / 100) * circumference);
|
||||
const strokeDashoffset = $derived(
|
||||
circumference - (Math.max(0, Math.min(100, prop.progress)) / 100) * circumference
|
||||
);
|
||||
</script>
|
||||
|
||||
<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}
|
||||
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.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-pink-950"
|
||||
@@ -40,7 +77,10 @@
|
||||
/>
|
||||
</svg>
|
||||
{: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
|
||||
cx="24"
|
||||
cy="24"
|
||||
@@ -64,35 +104,56 @@
|
||||
</svg>
|
||||
{/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.progress === -1}
|
||||
<ThemeIcon
|
||||
name="ellipsis"
|
||||
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}
|
||||
<span class="text-[10px] font-bold text-primary-foreground">
|
||||
{prop.progress.toFixed()}
|
||||
<span
|
||||
class="font-bold text-primary-foreground leading-none"
|
||||
style="font-size: {percentFontSize}px;"
|
||||
>
|
||||
{prop.progress.toFixed()}%
|
||||
</span>
|
||||
{/if}
|
||||
{:else}
|
||||
<ThemeIcon
|
||||
name="launch"
|
||||
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}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="pr-6 pl-1 text-center w-52">
|
||||
<p class="text-sm font-bold text-primary-foreground leading-tight">
|
||||
<div
|
||||
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}
|
||||
</p>
|
||||
{#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}
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
@@ -11,48 +11,78 @@
|
||||
const SPEED_THRESHOLD = 9;
|
||||
const REQUIRED_CONSECUTIVE = 3;
|
||||
|
||||
let mouseX = $state(0);
|
||||
let mouseY = $state(0);
|
||||
let currentX = 0;
|
||||
let currentY = 0;
|
||||
let targetX = 0;
|
||||
let targetY = 0;
|
||||
let prevAppliedX = -1;
|
||||
let prevAppliedY = -1;
|
||||
let hasMoved = false;
|
||||
|
||||
let lastMouseX = 0;
|
||||
let lastMouseY = 0;
|
||||
let isMouseDown = $state(false);
|
||||
let isHoveringInteractive = $state(false);
|
||||
let isMouseDown = false;
|
||||
let isHoveringInteractive = false;
|
||||
let dragStartX = 0;
|
||||
let dragStartY = 0;
|
||||
let degrees = $state(0);
|
||||
let applyRotation = $state(false);
|
||||
let targetDegrees = 0;
|
||||
let currentDegrees = 0;
|
||||
let applyRotation = false;
|
||||
|
||||
let lastVelocityTime = 0;
|
||||
let consecutiveHighSpeed = 0;
|
||||
let velocityAccumX = 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 {
|
||||
while (el) {
|
||||
const tag = el.tagName.toLowerCase();
|
||||
const role = el.getAttribute('role');
|
||||
const computed = getComputedStyle(el);
|
||||
if (!el) return false;
|
||||
if (
|
||||
['button', 'a', 'input', 'select', 'textarea', 'label', 'option'].includes(tag) ||
|
||||
(role && ['button', 'link', 'checkbox', 'combobox', 'menuitem', 'option'].includes(role)) ||
|
||||
computed.cursor === 'pointer'
|
||||
el.closest(
|
||||
'button, a, input, select, textarea, label, option, [role="button"], [role="link"], [role="checkbox"], [role="combobox"], [role="menuitem"], [role="option"]'
|
||||
)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
el = el.parentElement;
|
||||
return getComputedStyle(el).cursor === 'pointer';
|
||||
}
|
||||
return false;
|
||||
|
||||
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) => {
|
||||
mouseX = e.clientX;
|
||||
mouseY = e.clientY;
|
||||
targetX = e.clientX;
|
||||
targetY = e.clientY;
|
||||
|
||||
const deltaX = e.pageX - window.pageXOffset - dragStartX;
|
||||
const deltaY = e.pageY - window.pageYOffset - dragStartY;
|
||||
if (!hasMoved) {
|
||||
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;
|
||||
velocityAccumY += mouseY - lastMouseY;
|
||||
if (cursor) {
|
||||
cursor.style.opacity = '1';
|
||||
}
|
||||
|
||||
velocityAccumX += targetX - lastMouseX;
|
||||
velocityAccumY += targetY - lastMouseY;
|
||||
|
||||
const now = performance.now();
|
||||
const dt = now - lastVelocityTime;
|
||||
@@ -74,21 +104,22 @@
|
||||
lastVelocityTime = now;
|
||||
}
|
||||
|
||||
let newDegrees = (Math.atan2(-deltaX, deltaY) * 180) / Math.PI + 24.3;
|
||||
if (isMouseDown && applyRotation) {
|
||||
const deltaX = targetX - dragStartX;
|
||||
const deltaY = targetY - dragStartY;
|
||||
const newDegrees = (Math.atan2(-deltaX, deltaY) * 180) / Math.PI + 24.3;
|
||||
|
||||
let diff = (newDegrees - degrees) % 360;
|
||||
let diff = (newDegrees - targetDegrees) % 360;
|
||||
if (diff < -180) diff += 360;
|
||||
if (diff > 180) diff -= 360;
|
||||
|
||||
if (isMouseDown && applyRotation) {
|
||||
degrees += diff;
|
||||
} else {
|
||||
degrees = 0;
|
||||
targetDegrees += diff;
|
||||
}
|
||||
|
||||
const el = document.elementFromPoint(mouseX, mouseY);
|
||||
isHoveringInteractive = isInteractive(el);
|
||||
|
||||
const el = document.elementFromPoint(targetX, targetY);
|
||||
const hovering = isInteractive(el);
|
||||
if (hovering !== isHoveringInteractive) {
|
||||
isHoveringInteractive = hovering;
|
||||
if (!isMouseDown) {
|
||||
animate(cursorAdditive, {
|
||||
opacity: isHoveringInteractive ? 1 : 0,
|
||||
@@ -96,26 +127,11 @@
|
||||
ease: (t: number) => (t - 1) ** 5 + 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
animate(cursor, {
|
||||
duration: smoothCursor ? $cursorSmoothness : 0,
|
||||
translateX: mouseX,
|
||||
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;
|
||||
scheduleCursorFrame();
|
||||
lastMouseX = targetX;
|
||||
lastMouseY = targetY;
|
||||
};
|
||||
|
||||
const handleMouseDown = (event: MouseEvent) => {
|
||||
@@ -128,6 +144,13 @@
|
||||
lastVelocityTime = performance.now();
|
||||
|
||||
isMouseDown = true;
|
||||
scheduleCursorFrame();
|
||||
|
||||
if (rotateSpringAnim) {
|
||||
rotateSpringAnim.pause();
|
||||
rotateSpringAnim = null;
|
||||
}
|
||||
|
||||
animate(cursorInner, {
|
||||
scale: 0.9,
|
||||
duration: 800,
|
||||
@@ -143,6 +166,7 @@
|
||||
|
||||
const handleMouseUp = () => {
|
||||
isMouseDown = false;
|
||||
const hadRotation = applyRotation || Math.abs(currentDegrees) > 0.1;
|
||||
applyRotation = false;
|
||||
consecutiveHighSpeed = 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,
|
||||
});
|
||||
animate(cursorAdditive, {
|
||||
opacity: 0,
|
||||
opacity: isHoveringInteractive ? 1 : 0,
|
||||
duration: 500,
|
||||
scale: 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;
|
||||
let cursorInner: HTMLDivElement;
|
||||
let cursorAdditive: HTMLImageElement;
|
||||
const handleMouseLeave = () => {
|
||||
if (cursor) cursor.style.opacity = '0';
|
||||
};
|
||||
|
||||
const handleMouseEnter = () => {
|
||||
if (cursor && hasMoved) cursor.style.opacity = '1';
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
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 () => {
|
||||
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>
|
||||
@@ -179,8 +318,8 @@
|
||||
onmouseup={handleMouseUp}
|
||||
/>
|
||||
|
||||
<div class="h-7 w-7 fixed pointer-events-none z-[9999]" bind:this={cursor}>
|
||||
<div class="relative">
|
||||
<div class="h-7 w-7 fixed top-0 left-0 pointer-events-none z-[9999] opacity-0" bind:this={cursor}>
|
||||
<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 opacity-0"
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
custom_theme_volume,
|
||||
platform,
|
||||
} 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 Minimize from '@lucide/svelte/icons/minus';
|
||||
import Close from '@lucide/svelte/icons/x';
|
||||
@@ -16,6 +16,34 @@
|
||||
|
||||
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(() => {
|
||||
const appWindow = getCurrentWindow();
|
||||
|
||||
@@ -26,10 +54,18 @@
|
||||
});
|
||||
</script>
|
||||
|
||||
<svelte:window onpointerup={endVolumeDrag} onpointercancel={endVolumeDrag} />
|
||||
|
||||
<div data-tauri-drag-region class="titlebar z-[100]" class:macos-window={$platform === 'macos'}>
|
||||
{#if $custom_theme_audio_playing}
|
||||
{#if $custom_theme_audio_playing}
|
||||
<div class="relative flex items-center justify-center group">
|
||||
{#if $custom_theme_audio_playing || ($active_custom_theme && $active_custom_theme.name !== 'Default')}
|
||||
<div
|
||||
class="relative flex items-center justify-center group"
|
||||
role="group"
|
||||
aria-label="Theme volume"
|
||||
bind:this={volumeControl}
|
||||
onpointerenter={openVolume}
|
||||
onpointerleave={closeVolume}
|
||||
>
|
||||
<div class="relative flex items-center justify-center p-1 cursor-pointer">
|
||||
<div
|
||||
class="absolute inset-0 bg-background rounded
|
||||
@@ -52,8 +88,9 @@
|
||||
|
||||
<div
|
||||
class="absolute top-full right-0 translate-x-[7px]
|
||||
opacity-0 invisible pointer-events-none -translate-y-2
|
||||
group-hover:opacity-100 group-hover:visible group-hover:pointer-events-auto group-hover:translate-y-0
|
||||
{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"
|
||||
>
|
||||
@@ -69,6 +106,7 @@
|
||||
max="1"
|
||||
step="0.01"
|
||||
bind:value={$custom_theme_volume}
|
||||
onpointerdown={startVolumeDrag}
|
||||
oninput={() => {
|
||||
config.value<number>('volume').set($custom_theme_volume);
|
||||
}}
|
||||
@@ -78,7 +116,6 @@
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
<div class="relative flex items-center justify-center p-1 group" id="titlebar-minimize">
|
||||
<div
|
||||
class="absolute inset-0 bg-background rounded
|
||||
|
||||
@@ -125,8 +125,8 @@ export const DISCORD_PRESENCE_PRESETS: DiscordPresencePreset[] = [
|
||||
},
|
||||
button2: {
|
||||
enabled: true,
|
||||
label: 'View Profile',
|
||||
url: '{profileUrl}',
|
||||
label: 'Join EZPPFarm',
|
||||
url: 'https://ez-pp.farm/discord',
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -247,6 +247,8 @@ export type IdlePresenceParams = {
|
||||
rank?: number | string;
|
||||
pp?: number | string;
|
||||
accuracy?: number | string;
|
||||
mode?: string;
|
||||
action?: string;
|
||||
};
|
||||
|
||||
export type PlayingPresenceParams = {
|
||||
@@ -282,6 +284,8 @@ export const pushIdlePresenceFromConfig = async (
|
||||
rank: params?.rank,
|
||||
pp: params?.pp,
|
||||
accuracy: params?.accuracy,
|
||||
mode: params?.mode,
|
||||
action: params?.action ?? 'In Launcher',
|
||||
version: params?.version,
|
||||
profileUrl: params?.user?.id ? `https://ez-pp.farm/u/${params.user.id}` : 'https://ez-pp.farm',
|
||||
};
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { browser } from '$app/environment';
|
||||
import { ezppfarm } from './api/ezpp';
|
||||
import type { Theme } from './themes';
|
||||
import type { Theme } from './theme/themes';
|
||||
import type { Release } from './types';
|
||||
import { setGlobalVolume } from './utils';
|
||||
import type { Component } from 'svelte';
|
||||
|
||||
@@ -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
@@ -88,8 +88,8 @@ export const getSkin = async (folder: string) => {
|
||||
};
|
||||
|
||||
export const runUpdater = async (folder: string) => await invoke('run_osu_updater', { folder });
|
||||
export const runOsu = async (folder: string, patch: boolean) =>
|
||||
await invoke('run_osu', { folder, patch });
|
||||
export const runOsu = async (folder: string, patch: boolean, gameOptimization: boolean = false) =>
|
||||
await invoke('run_osu', { folder, patch, gameOptimization });
|
||||
|
||||
export const getEZPPLauncherStreams = async () => {
|
||||
const resp = await betterFetch<{ streams: string[] }>(updateUrl, {
|
||||
|
||||
+9
-9
@@ -6,15 +6,15 @@ export type PresenceButtonPayload = {
|
||||
};
|
||||
|
||||
export type PresenceActivityPayload = {
|
||||
state?: string;
|
||||
details?: string;
|
||||
largeImageKey?: string;
|
||||
largeImageText?: string;
|
||||
smallImageKey?: string | null;
|
||||
smallImageText?: string | null;
|
||||
button1?: PresenceButtonPayload | null;
|
||||
button2?: PresenceButtonPayload | null;
|
||||
showTimestamp?: boolean;
|
||||
state: string;
|
||||
details: string;
|
||||
largeImageKey: string;
|
||||
largeImageText: string;
|
||||
smallImageKey: string | null;
|
||||
smallImageText: string | null;
|
||||
button1: PresenceButtonPayload | null;
|
||||
button2: PresenceButtonPayload | null;
|
||||
showTimestamp: boolean;
|
||||
};
|
||||
|
||||
export const connect = async () => await invoke('presence_connect');
|
||||
|
||||
@@ -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 { launcherVersion, onlineFriends, osuBuild, osuStream, serverPing } from './global';
|
||||
import { currentUserInfo } from '../data';
|
||||
import { launcherVersion, onlineFriends, osuBuild, osuStream, serverPing } from '../global';
|
||||
import { currentUser } from '../userAuthentication';
|
||||
import { themeClockValues } from './themeClock';
|
||||
import type { ThemeV2DataField, ThemeV2DataMode } from './themeV2';
|
||||
import { currentUser } from './userAuthentication';
|
||||
import { derived } from 'svelte/store';
|
||||
|
||||
export type ThemeDataStats = {
|
||||
@@ -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.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -13,9 +13,10 @@
|
||||
* theme videos and videos picked in the editor (served as /preview/ URLs) are
|
||||
* transcoded to a cached H.264 copy by the Rust backend before playback.
|
||||
*/
|
||||
import { custom_theme_volume } from '../global';
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
import { writable } from 'svelte/store';
|
||||
import { get, writable } from 'svelte/store';
|
||||
|
||||
type MediaCleanup = () => void;
|
||||
|
||||
@@ -66,7 +67,11 @@ const ensureStatusListener = async () => {
|
||||
} else if (stage === 'extract') {
|
||||
themeMediaStatus.set('Installing video engine…');
|
||||
} else if (stage === 'optimize') {
|
||||
themeMediaStatus.set('Converting theme video for hardware playback…');
|
||||
if (progress > 0) {
|
||||
themeMediaStatus.set(`Converting theme video… ${Math.round(progress * 100)}%`);
|
||||
} else {
|
||||
themeMediaStatus.set('Converting theme video…');
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
@@ -74,6 +79,14 @@ const ensureStatusListener = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
export const initThemeMediaStatusListener = () => {
|
||||
void ensureStatusListener();
|
||||
};
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
void ensureStatusListener();
|
||||
}
|
||||
|
||||
const blobUrlPromises = new Map<string, Promise<string>>();
|
||||
const optimizedUrlPromises = new Map<string, Promise<string>>();
|
||||
const objectUrls = new Set<string>();
|
||||
@@ -108,7 +121,7 @@ const optimizedThemeMediaUrl = async (source: string, video: boolean): Promise<s
|
||||
}
|
||||
|
||||
setPreparing(1);
|
||||
themeMediaStatus.set('Preparing theme video for smooth playback…');
|
||||
themeMediaStatus.set('Converting theme video…');
|
||||
await ensureStatusListener();
|
||||
try {
|
||||
const optimized = await invoke<string>('optimize_theme_media', {
|
||||
@@ -187,19 +200,43 @@ const armAutoplayRetry = (node: HTMLMediaElement) => {
|
||||
autoplayArmed.add(node);
|
||||
|
||||
const retry = () => {
|
||||
document.removeEventListener('pointerdown', retry, true);
|
||||
document.removeEventListener('keydown', retry, true);
|
||||
window.removeEventListener('pointerdown', retry, true);
|
||||
window.removeEventListener('keydown', retry, true);
|
||||
window.removeEventListener('click', retry, true);
|
||||
window.removeEventListener('focus', retry, true);
|
||||
autoplayArmed.delete(node);
|
||||
if (node.isConnected) void node.play().catch(() => {});
|
||||
if (node.isConnected) {
|
||||
node.muted = false;
|
||||
const targetVolume = get(custom_theme_volume);
|
||||
if (targetVolume >= 0) node.volume = targetVolume;
|
||||
void node.play().catch(() => {});
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('pointerdown', retry, true);
|
||||
document.addEventListener('keydown', retry, true);
|
||||
window.addEventListener('pointerdown', retry, true);
|
||||
window.addEventListener('keydown', retry, true);
|
||||
window.addEventListener('click', retry, true);
|
||||
window.addEventListener('focus', retry, true);
|
||||
};
|
||||
|
||||
const playThemeMedia = (node: HTMLMediaElement) => {
|
||||
void node
|
||||
.play()
|
||||
export const playThemeMedia = (node: HTMLMediaElement) => {
|
||||
if (node instanceof HTMLVideoElement) {
|
||||
node.playsInline = true;
|
||||
node.setAttribute('playsinline', '');
|
||||
node.setAttribute('webkit-playsinline', '');
|
||||
node.controls = false;
|
||||
node.removeAttribute('controls');
|
||||
}
|
||||
|
||||
node.muted = false;
|
||||
const currentVolume = get(custom_theme_volume);
|
||||
if (currentVolume >= 0) {
|
||||
node.volume = currentVolume;
|
||||
}
|
||||
|
||||
const playPromise = node.play();
|
||||
if (playPromise !== undefined) {
|
||||
playPromise
|
||||
.then(() => {
|
||||
console.debug('Theme media playing', {
|
||||
element: node.tagName,
|
||||
@@ -211,7 +248,9 @@ const playThemeMedia = (node: HTMLMediaElement) => {
|
||||
.catch((error) => {
|
||||
console.warn('Theme media autoplay was blocked', error);
|
||||
armAutoplayRetry(node);
|
||||
void invoke('unlock_media_autoplay').catch(() => {});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -225,13 +264,7 @@ const loadMediaSource = (node: HTMLMediaElement, source: string) => {
|
||||
mediaCleanups.delete(node);
|
||||
|
||||
const previousTime = Number.isFinite(node.currentTime) ? node.currentTime : 0;
|
||||
const wasPlaying = !node.paused;
|
||||
const needsPreparation =
|
||||
node instanceof HTMLVideoElement && isMac && loopbackThemePattern.test(source);
|
||||
|
||||
// Keep the last frame visible while the first H.264 encode runs instead of
|
||||
// letting WebKit struggle through the software VP9 track.
|
||||
if (needsPreparation) node.pause();
|
||||
const wasPlaying = !node.paused || node.autoplay;
|
||||
|
||||
void themeMediaUrl(source, node instanceof HTMLVideoElement).then((url) => {
|
||||
if (mediaTokens.get(node) !== token || !node.isConnected) return;
|
||||
@@ -258,7 +291,7 @@ const loadMediaSource = (node: HTMLMediaElement, source: string) => {
|
||||
}
|
||||
}
|
||||
|
||||
if (wasPlaying || node.autoplay) playThemeMedia(node);
|
||||
playThemeMedia(node);
|
||||
};
|
||||
|
||||
const onError = () => {
|
||||
@@ -270,7 +303,7 @@ const loadMediaSource = (node: HTMLMediaElement, source: string) => {
|
||||
if (node.src !== source) {
|
||||
node.src = source;
|
||||
node.load();
|
||||
if (wasPlaying || node.autoplay) playThemeMedia(node);
|
||||
playThemeMedia(node);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -498,13 +531,14 @@ export function themeMediaSuspension(node: HTMLElement) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Pause background videos while the launcher is hidden or unfocused, then
|
||||
* resume only the videos this helper paused itself. This keeps muted theme
|
||||
* videos from decoding in the background and prevents surprise audio when the
|
||||
* window comes back.
|
||||
* Manage background video playback across document visibility changes.
|
||||
* Muted background videos pause when the document is hidden/minimized or the
|
||||
* launcher loses focus, which saves GPU decoding cycles behind a running game
|
||||
* without interrupting unmuted theme music or audio.
|
||||
*/
|
||||
export function themeVideoLifecycle(node: HTMLVideoElement) {
|
||||
let pausedByLifecycle = false;
|
||||
let focused = true;
|
||||
|
||||
const pause = () => {
|
||||
if (node.paused) return;
|
||||
@@ -513,26 +547,43 @@ export function themeVideoLifecycle(node: HTMLVideoElement) {
|
||||
};
|
||||
|
||||
const resume = () => {
|
||||
if (!pausedByLifecycle) return;
|
||||
if (!pausedByLifecycle && !node.autoplay && !node.loop) return;
|
||||
pausedByLifecycle = false;
|
||||
playThemeMedia(node);
|
||||
};
|
||||
|
||||
const onBlur = () => {
|
||||
focused = false;
|
||||
sync();
|
||||
};
|
||||
const onFocus = () => {
|
||||
focused = true;
|
||||
sync();
|
||||
};
|
||||
const sync = () => {
|
||||
if (document.visibilityState === 'visible' && document.hasFocus()) resume();
|
||||
else pause();
|
||||
if (!node.isConnected) {
|
||||
document.removeEventListener('visibilitychange', sync);
|
||||
window.removeEventListener('blur', onBlur);
|
||||
window.removeEventListener('focus', onFocus);
|
||||
return;
|
||||
}
|
||||
if (document.visibilityState === 'visible' && focused) {
|
||||
resume();
|
||||
} else if (node.muted || node.volume === 0) {
|
||||
pause();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('visibilitychange', sync);
|
||||
window.addEventListener('focus', sync);
|
||||
window.addEventListener('blur', sync);
|
||||
window.addEventListener('blur', onBlur);
|
||||
window.addEventListener('focus', onFocus);
|
||||
sync();
|
||||
|
||||
return {
|
||||
destroy() {
|
||||
document.removeEventListener('visibilitychange', sync);
|
||||
window.removeEventListener('focus', sync);
|
||||
window.removeEventListener('blur', sync);
|
||||
window.removeEventListener('blur', onBlur);
|
||||
window.removeEventListener('focus', onFocus);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -564,14 +615,37 @@ export function themeMediaSource(node: HTMLMediaElement, source: string) {
|
||||
*/
|
||||
export function smoothThemeMedia(node: HTMLElement) {
|
||||
const lastSource = new WeakMap<HTMLMediaElement, string>();
|
||||
const videoLifecycles = new WeakMap<HTMLVideoElement, () => void>();
|
||||
|
||||
const prepare = (media: HTMLMediaElement) => {
|
||||
if (media instanceof HTMLVideoElement) {
|
||||
media.playsInline = true;
|
||||
media.setAttribute('playsinline', '');
|
||||
media.setAttribute('webkit-playsinline', '');
|
||||
media.controls = false;
|
||||
media.removeAttribute('controls');
|
||||
|
||||
if (!videoLifecycles.has(media)) {
|
||||
const lifecycle = themeVideoLifecycle(media);
|
||||
videoLifecycles.set(media, () => lifecycle.destroy());
|
||||
}
|
||||
} else {
|
||||
media.controls = false;
|
||||
media.removeAttribute('controls');
|
||||
}
|
||||
|
||||
const source =
|
||||
media.getAttribute('src') ??
|
||||
media.querySelector<HTMLSourceElement>('source[src]')?.getAttribute('src') ??
|
||||
undefined;
|
||||
if (!source) return;
|
||||
if (!isThemeAssetUrl(source) && !loopbackThemePattern.test(source)) return;
|
||||
if (!source) {
|
||||
playThemeMedia(media);
|
||||
return;
|
||||
}
|
||||
if (!isThemeAssetUrl(source) && !loopbackThemePattern.test(source)) {
|
||||
playThemeMedia(media);
|
||||
return;
|
||||
}
|
||||
if (lastSource.get(media) === source) return;
|
||||
|
||||
lastSource.set(media, source);
|
||||
@@ -595,6 +669,18 @@ export function smoothThemeMedia(node: HTMLElement) {
|
||||
for (const added of mutation.addedNodes) {
|
||||
if (added instanceof HTMLElement) scan(added);
|
||||
}
|
||||
|
||||
for (const removed of mutation.removedNodes) {
|
||||
if (removed instanceof HTMLVideoElement) {
|
||||
videoLifecycles.get(removed)?.();
|
||||
videoLifecycles.delete(removed);
|
||||
} else if (removed instanceof HTMLElement) {
|
||||
removed.querySelectorAll?.<HTMLVideoElement>('video').forEach((video) => {
|
||||
videoLifecycles.get(video)?.();
|
||||
videoLifecycles.delete(video);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import { reduceAnimations } from '$lib/userSettings';
|
||||
import { get } from 'svelte/store';
|
||||
|
||||
export type ThemeParallaxOptions = {
|
||||
enabled?: boolean;
|
||||
intensity?: number;
|
||||
};
|
||||
|
||||
const clampIntensity = (intensity: number | undefined) =>
|
||||
Math.min(1, Math.max(0.05, typeof intensity === 'number' ? intensity : 0.25));
|
||||
|
||||
/**
|
||||
* Tracks the pointer for a theme host and exposes the smoothed offset as
|
||||
* `--mouse-px` / `--mouse-py`. The host must contain both the background and
|
||||
* the freeform layers so those variables are inherited by every layer.
|
||||
*/
|
||||
export function themeParallax(node: HTMLElement, options: ThemeParallaxOptions = {}) {
|
||||
let enabled = options.enabled === true;
|
||||
let intensity = clampIntensity(options.intensity);
|
||||
let mousePx = 0;
|
||||
let mousePy = 0;
|
||||
let targetPx = 0;
|
||||
let targetPy = 0;
|
||||
let animFrame: number | undefined;
|
||||
let reduced = get(reduceAnimations);
|
||||
|
||||
function apply() {
|
||||
node.style.setProperty('--mouse-px', mousePx.toFixed(4));
|
||||
node.style.setProperty('--mouse-py', mousePy.toFixed(4));
|
||||
}
|
||||
|
||||
function stop() {
|
||||
if (animFrame !== undefined) {
|
||||
cancelAnimationFrame(animFrame);
|
||||
animFrame = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function reset() {
|
||||
stop();
|
||||
mousePx = 0;
|
||||
mousePy = 0;
|
||||
targetPx = 0;
|
||||
targetPy = 0;
|
||||
apply();
|
||||
}
|
||||
|
||||
function updateParallax() {
|
||||
animFrame = undefined;
|
||||
const dx = targetPx - mousePx;
|
||||
const dy = targetPy - mousePy;
|
||||
|
||||
if (Math.abs(dx) < 0.0005 && Math.abs(dy) < 0.0005) {
|
||||
mousePx = targetPx;
|
||||
mousePy = targetPy;
|
||||
apply();
|
||||
return;
|
||||
}
|
||||
|
||||
mousePx += dx * 0.12;
|
||||
mousePy += dy * 0.12;
|
||||
apply();
|
||||
animFrame = requestAnimationFrame(updateParallax);
|
||||
}
|
||||
|
||||
function onWindowMouseMove(event: MouseEvent) {
|
||||
if (!enabled || reduced) return;
|
||||
|
||||
const width = window.innerWidth || 1000;
|
||||
const height = window.innerHeight || 650;
|
||||
targetPx = (event.clientX / width - 0.5) * 2 * intensity;
|
||||
targetPy = (event.clientY / height - 0.5) * 2 * intensity;
|
||||
|
||||
if (animFrame === undefined) {
|
||||
animFrame = requestAnimationFrame(updateParallax);
|
||||
}
|
||||
}
|
||||
|
||||
const unsubscribe = reduceAnimations.subscribe((value) => {
|
||||
reduced = value;
|
||||
if (reduced) reset();
|
||||
});
|
||||
|
||||
window.addEventListener('mousemove', onWindowMouseMove);
|
||||
apply();
|
||||
|
||||
return {
|
||||
update(next: ThemeParallaxOptions = {}) {
|
||||
enabled = next.enabled === true;
|
||||
intensity = clampIntensity(next.intensity);
|
||||
if (!enabled || reduced) reset();
|
||||
},
|
||||
destroy() {
|
||||
unsubscribe();
|
||||
window.removeEventListener('mousemove', onWindowMouseMove);
|
||||
stop();
|
||||
node.style.removeProperty('--mouse-px');
|
||||
node.style.removeProperty('--mouse-py');
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -699,6 +699,12 @@ const drawParticles = (context: PreviewContext) => {
|
||||
ctx.beginPath();
|
||||
ctx.arc(x, y, size / 2, 0, Math.PI * 2);
|
||||
ctx.stroke();
|
||||
} else if (effects.type === 'embers') {
|
||||
ctx.shadowColor = color;
|
||||
ctx.shadowBlur = 8;
|
||||
ctx.beginPath();
|
||||
ctx.arc(x, y, size / 2.2, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
} else if (effects.type === 'petals') {
|
||||
ctx.translate(x, y);
|
||||
ctx.rotate(value(8) * Math.PI * 2);
|
||||
@@ -1296,8 +1302,9 @@ const drawWidgetElement = async (context: PreviewContext, element: ThemeV2Widget
|
||||
fillRoundedRect(ctx, element.x, element.y, element.width, element.height, radius, accent);
|
||||
ctx.restore();
|
||||
|
||||
const circleR = Math.max(12, element.height * 0.32);
|
||||
const circleX = element.x + circleR + 10;
|
||||
const baseDim = Math.min(element.width, element.height);
|
||||
const circleR = Math.round(baseDim * 0.35);
|
||||
const circleX = element.x + baseDim / 2;
|
||||
ctx.beginPath();
|
||||
ctx.arc(circleX, centerY, circleR, 0, Math.PI * 2);
|
||||
ctx.fillStyle = 'rgba(0, 0, 0, 0.22)';
|
||||
@@ -1307,7 +1314,12 @@ const drawWidgetElement = async (context: PreviewContext, element: ThemeV2Widget
|
||||
|
||||
ctx.save();
|
||||
ctx.fillStyle = accentText;
|
||||
ctx.font = canvasFont(context, bodyFont, Math.min(14, element.height * 0.33), 700);
|
||||
const availableTextW = Math.max(50, element.width - baseDim);
|
||||
const textFontSize = Math.max(
|
||||
10,
|
||||
Math.min(Math.round(baseDim * 0.32), Math.round((availableTextW * 0.85) / 6))
|
||||
);
|
||||
ctx.font = canvasFont(context, bodyFont, textFontSize, 700);
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
const textCenterX = circleX + circleR + (element.x + element.width - (circleX + circleR)) / 2;
|
||||
@@ -1650,7 +1662,7 @@ const drawWidgetElement = async (context: PreviewContext, element: ThemeV2Widget
|
||||
ctx.fillText(plays, cell2X + cellW - 8, bottomY + 14);
|
||||
ctx.restore();
|
||||
} else {
|
||||
// full
|
||||
// full or banner
|
||||
fillRoundedRect(
|
||||
ctx,
|
||||
element.x,
|
||||
@@ -1671,9 +1683,12 @@ const drawWidgetElement = async (context: PreviewContext, element: ThemeV2Widget
|
||||
1
|
||||
);
|
||||
|
||||
const avatarSize = 48;
|
||||
const showStats =
|
||||
element.variant !== 'banner' && element.showStats !== false && element.height >= 140;
|
||||
const isBanner = element.variant === 'banner' || !showStats;
|
||||
const avatarSize = isBanner ? Math.min(48, Math.max(32, element.height - 24)) : 48;
|
||||
const avatarX = element.x + 16;
|
||||
const avatarY = element.y + 16;
|
||||
const avatarY = isBanner ? element.y + (element.height - avatarSize) / 2 : element.y + 16;
|
||||
fillRoundedRect(ctx, avatarX, avatarY, avatarSize, avatarSize, 12, 'rgba(20, 20, 28, 0.9)');
|
||||
strokeRoundedRect(
|
||||
ctx,
|
||||
@@ -1718,6 +1733,7 @@ const drawWidgetElement = async (context: PreviewContext, element: ThemeV2Widget
|
||||
ctx.font = '500 10px monospace';
|
||||
ctx.fillText(`${levelProgress}%`, barX + barW + 8, barY - 2);
|
||||
|
||||
if (showStats) {
|
||||
const divY = avatarY + avatarSize + 16;
|
||||
ctx.strokeStyle = 'rgba(255, 255, 255, 0.06)';
|
||||
ctx.beginPath();
|
||||
@@ -1754,6 +1770,7 @@ const drawWidgetElement = async (context: PreviewContext, element: ThemeV2Widget
|
||||
ctx.font = canvasFont(context, bodyFont, 12, 700);
|
||||
ctx.fillText(st.value, cx + 10, cy + cellH - 18);
|
||||
});
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
} else if (element.widget === 'recent-activity') {
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,4 +1,4 @@
|
||||
import type { Theme } from '$lib/themes';
|
||||
import type { Theme } from '$lib/theme/themes';
|
||||
|
||||
/**
|
||||
* API 1.0 themes are executable bundles: loading one imports its entry script
|
||||
@@ -48,7 +48,13 @@ export type ThemeV2Background =
|
||||
muted?: boolean;
|
||||
};
|
||||
|
||||
export type ThemeV2EffectType = 'none' | 'snow' | 'stars' | 'petals' | 'bubbles';
|
||||
export type ThemeV2EffectType = 'none' | 'snow' | 'stars' | 'petals' | 'bubbles' | 'embers';
|
||||
|
||||
export type ThemeV2Parallax = {
|
||||
enabled?: boolean;
|
||||
/** Intensity multiplier from 0.05 to 1.0, defaults to 0.25 */
|
||||
intensity?: number;
|
||||
};
|
||||
|
||||
export type ThemeV2Effects = {
|
||||
type: ThemeV2EffectType;
|
||||
@@ -121,6 +127,8 @@ export type ThemeV2Transform = {
|
||||
skewY?: number;
|
||||
flipX?: boolean;
|
||||
flipY?: boolean;
|
||||
/** Parallax depth multiplier (-2 to 2); when parallax is enabled, offsets layer based on cursor. */
|
||||
parallax?: number;
|
||||
};
|
||||
|
||||
/** A group in the layer list. Groups may be nested through `parentId`. */
|
||||
@@ -526,7 +534,8 @@ export type ThemeV2WidgetVariant =
|
||||
| 'icon-only'
|
||||
| 'circle'
|
||||
| 'rounded'
|
||||
| 'square';
|
||||
| 'square'
|
||||
| 'banner';
|
||||
|
||||
export type ThemeV2WidgetElement = ThemeV2ElementBase & {
|
||||
type: 'widget';
|
||||
@@ -535,6 +544,7 @@ export type ThemeV2WidgetElement = ThemeV2ElementBase & {
|
||||
showCountry?: boolean;
|
||||
showLevel?: boolean;
|
||||
showOnlineRing?: boolean;
|
||||
showStats?: boolean;
|
||||
};
|
||||
|
||||
export type ThemeV2Element =
|
||||
@@ -636,14 +646,23 @@ export type ThemeV2Definition = {
|
||||
version: string;
|
||||
apiVersion: '2.0';
|
||||
author: string;
|
||||
/** EZPPFarm user ID of the publisher, written when the theme is published. */
|
||||
authorId?: number;
|
||||
description?: string;
|
||||
/** Workshop discovery tags for this theme. */
|
||||
tags?: string[];
|
||||
/** Server-assigned workshop ID, stored so republishing updates the same theme. */
|
||||
workshopId?: string;
|
||||
/** Marks the theme as adult content in the theme manager. */
|
||||
nsfw?: boolean;
|
||||
/** Whether other creators may fork this theme from the workshop. */
|
||||
allowForking?: boolean;
|
||||
/** Optional preview image, relative to the theme's assets folder. */
|
||||
preview?: string;
|
||||
background: ThemeV2Background;
|
||||
overlay: ThemeV2Overlay;
|
||||
effects: ThemeV2Effects;
|
||||
parallax?: ThemeV2Parallax;
|
||||
audio?: ThemeV2Audio;
|
||||
/** Theme-wide fonts and freeform layers rendered over the launcher UI. */
|
||||
typography: ThemeV2Typography;
|
||||
@@ -713,6 +732,46 @@ export const themeClassTokens = (value: unknown): string[] => {
|
||||
/** Sanitized class attribute value for a layer or group. */
|
||||
export const themeClassNames = (value: unknown): string => themeClassTokens(value).join(' ');
|
||||
|
||||
const THEME_TAG_PATTERN = /^[a-z0-9][a-z0-9_-]{0,23}$/;
|
||||
|
||||
/** Keep workshop tags lowercase, unique, and within the service limits. */
|
||||
export const normalizeThemeTags = (raw: unknown): string[] => {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
const tags: string[] = [];
|
||||
for (const candidate of raw) {
|
||||
if (typeof candidate !== 'string') continue;
|
||||
const tag = candidate.trim().toLowerCase();
|
||||
if (!THEME_TAG_PATTERN.test(tag) || tags.includes(tag)) continue;
|
||||
tags.push(tag);
|
||||
if (tags.length === 10) break;
|
||||
}
|
||||
return tags;
|
||||
};
|
||||
|
||||
const THEME_VERSION_PATTERN =
|
||||
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/;
|
||||
|
||||
/** Accept only strict SemVer 2.0.0, preserving prerelease and build metadata. */
|
||||
export const normalizeThemeVersion = (raw: unknown): string | undefined => {
|
||||
if (typeof raw !== 'string') return undefined;
|
||||
const version = raw.trim();
|
||||
return version.length > 0 && THEME_VERSION_PATTERN.test(version) ? version : undefined;
|
||||
};
|
||||
|
||||
const WORKSHOP_ID_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
||||
|
||||
/** Keep a server-assigned workshop ID while preserving legacy slug IDs. */
|
||||
const normalizeWorkshopId = (raw: unknown): string | undefined => {
|
||||
if (typeof raw !== 'string') return undefined;
|
||||
const id = raw.trim().toLowerCase();
|
||||
return WORKSHOP_ID_PATTERN.test(id) ? id : undefined;
|
||||
};
|
||||
|
||||
const normalizeAuthorId = (raw: unknown): number | undefined => {
|
||||
if (typeof raw !== 'number' || !Number.isSafeInteger(raw) || raw <= 0) return undefined;
|
||||
return raw;
|
||||
};
|
||||
|
||||
const clampInteger = (value: unknown, fallback: number, min: number, max: number) =>
|
||||
Math.round(clamp(value, fallback, min, max));
|
||||
|
||||
@@ -789,6 +848,9 @@ const normalizeTransform = (source: Record<string, unknown>): ThemeV2Transform =
|
||||
skewY: clamp(source.skewY, 0, -89, 89),
|
||||
flipX: source.flipX === true,
|
||||
flipY: source.flipY === true,
|
||||
...(typeof source.parallax === 'number' && Number.isFinite(source.parallax)
|
||||
? { parallax: clamp(source.parallax, 0, -2, 2) }
|
||||
: {}),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1250,6 +1312,7 @@ const normalizeElement = (raw: unknown, index: number): ThemeV2Element | undefin
|
||||
'circle',
|
||||
'rounded',
|
||||
'square',
|
||||
'banner',
|
||||
] as const,
|
||||
widget === 'launch-button' ? 'primary' : widget === 'avatar' ? 'circle' : 'full'
|
||||
);
|
||||
@@ -1257,6 +1320,7 @@ const normalizeElement = (raw: unknown, index: number): ThemeV2Element | undefin
|
||||
const showLevel = typeof source.showLevel === 'boolean' ? source.showLevel : false;
|
||||
const showOnlineRing =
|
||||
typeof source.showOnlineRing === 'boolean' ? source.showOnlineRing : true;
|
||||
const showStats = typeof source.showStats === 'boolean' ? source.showStats : true;
|
||||
return {
|
||||
...base,
|
||||
type,
|
||||
@@ -1265,6 +1329,7 @@ const normalizeElement = (raw: unknown, index: number): ThemeV2Element | undefin
|
||||
showCountry,
|
||||
showLevel,
|
||||
showOnlineRing,
|
||||
showStats,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1664,8 +1729,8 @@ export const createThemeV2Element = (type: ThemeV2Element['type'], index = 0): T
|
||||
...base,
|
||||
type,
|
||||
widget: 'launch-button',
|
||||
width: 220,
|
||||
height: 60,
|
||||
width: 256,
|
||||
height: 48,
|
||||
},
|
||||
index
|
||||
)! as ThemeV2WidgetElement;
|
||||
@@ -1737,7 +1802,9 @@ export const createDefaultThemeV2 = (): ThemeV2Definition => ({
|
||||
apiVersion: '2.0',
|
||||
author: '',
|
||||
description: '',
|
||||
tags: [],
|
||||
nsfw: false,
|
||||
allowForking: true,
|
||||
background: {
|
||||
type: 'gradient',
|
||||
from: '#181825',
|
||||
@@ -1756,6 +1823,10 @@ export const createDefaultThemeV2 = (): ThemeV2Definition => ({
|
||||
speed: 1,
|
||||
color: '#ffffff',
|
||||
},
|
||||
parallax: {
|
||||
enabled: false,
|
||||
intensity: 0.25,
|
||||
},
|
||||
typography: {
|
||||
body: 'Sora Variable',
|
||||
heading: 'Sora Variable',
|
||||
@@ -1830,12 +1901,18 @@ export const normalizeThemeV2 = (raw: Partial<ThemeV2Definition>): ThemeV2Defini
|
||||
}
|
||||
|
||||
const sourceEffects = (raw.effects ?? {}) as Record<string, unknown>;
|
||||
const effectType = ['none', 'snow', 'stars', 'petals', 'bubbles'].includes(
|
||||
const effectType = ['none', 'snow', 'stars', 'petals', 'bubbles', 'embers'].includes(
|
||||
String(sourceEffects.type)
|
||||
)
|
||||
? (String(sourceEffects.type) as ThemeV2EffectType)
|
||||
: 'none';
|
||||
|
||||
const sourceParallax = (raw.parallax ?? {}) as Record<string, unknown>;
|
||||
const parallax: ThemeV2Parallax = {
|
||||
enabled: sourceParallax.enabled === true,
|
||||
intensity: clamp(sourceParallax.intensity, 0.25, 0.05, 1),
|
||||
};
|
||||
|
||||
const sourceOverlay = (raw.overlay ?? {}) as Record<string, unknown>;
|
||||
const sourceAudio = raw.audio as Record<string, unknown> | undefined;
|
||||
const sourceTypography = (raw.typography ?? {}) as Record<string, unknown>;
|
||||
@@ -1853,8 +1930,12 @@ export const normalizeThemeV2 = (raw: Partial<ThemeV2Definition>): ThemeV2Defini
|
||||
version: text(raw.version, '1.0.0'),
|
||||
apiVersion: '2.0',
|
||||
author: text(raw.author, 'Unknown'),
|
||||
authorId: normalizeAuthorId(raw.authorId),
|
||||
description: text(raw.description),
|
||||
tags: normalizeThemeTags(raw.tags),
|
||||
workshopId: normalizeWorkshopId(raw.workshopId),
|
||||
nsfw: raw.nsfw === true,
|
||||
allowForking: raw.allowForking !== false,
|
||||
preview: text(raw.preview),
|
||||
background,
|
||||
overlay: {
|
||||
@@ -1868,6 +1949,7 @@ export const normalizeThemeV2 = (raw: Partial<ThemeV2Definition>): ThemeV2Defini
|
||||
speed: clamp(sourceEffects.speed, 1, 0.2, 3),
|
||||
color: color(sourceEffects.color, '#ffffff'),
|
||||
},
|
||||
parallax,
|
||||
// A video background owns the soundtrack; combining it with theme music
|
||||
// would play two sources at once.
|
||||
audio:
|
||||
@@ -1,20 +1,24 @@
|
||||
import { active_custom_theme, custom_theme_audio_playing, custom_themes } from './global';
|
||||
import { clearThemeMediaCache } from './themeMedia';
|
||||
import { active_custom_theme, custom_theme_audio_playing, custom_themes } from '../global';
|
||||
import { disableMediaControls, setGlobalVolume } from '../utils';
|
||||
import { clearThemeMediaCache, playThemeMedia } from './themeMedia';
|
||||
import { isThemeV2, normalizeThemeV2, type ThemeV2Asset, type ThemeV2Definition } from './themeV2';
|
||||
import { disableMediaControls, setGlobalVolume } from './utils';
|
||||
import { betterFetch } from '@better-fetch/fetch';
|
||||
import { convertFileSrc, invoke } from '@tauri-apps/api/core';
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
import * as path from '@tauri-apps/api/path';
|
||||
import * as fs from '@tauri-apps/plugin-fs';
|
||||
import { SemVer } from 'semver';
|
||||
import { tick } from 'svelte';
|
||||
|
||||
export type Theme = {
|
||||
folder_name: string;
|
||||
/** Server-assigned workshop ID, when this theme has been published. */
|
||||
workshopId?: string;
|
||||
name: string;
|
||||
version: string;
|
||||
apiVersion: string;
|
||||
author: string;
|
||||
/** EZPPFarm user ID stored in the manifest when the theme is published. */
|
||||
authorId?: number;
|
||||
description: string;
|
||||
nsfw: boolean;
|
||||
scriptUrl: string;
|
||||
@@ -24,6 +28,18 @@ export type Theme = {
|
||||
status: 'installed' | 'downloading' | 'extracting' | 'deleting' | 'not-installed';
|
||||
progress: number;
|
||||
updateAvailable: boolean;
|
||||
/** The latest Workshop version, when the theme has been published. */
|
||||
workshopVersion?: string;
|
||||
/** Hash of the theme files when this copy was last known to match the Workshop. */
|
||||
syncedContentHash?: string;
|
||||
/** Local version current when the sync baseline was written. */
|
||||
syncedVersion?: string;
|
||||
/** True when the local theme differs from its published Workshop package. */
|
||||
isNotSynced?: boolean;
|
||||
/** Modification time of the generated preview, used to migrate existing installs. */
|
||||
previewModifiedAt?: number;
|
||||
/** Creation time of the theme folder, used to migrate existing installs. */
|
||||
folderCreatedAt?: number;
|
||||
/** The version available in the repository when an update is pending. */
|
||||
availableVersion?: string;
|
||||
definition?: ThemeV2Definition;
|
||||
@@ -41,7 +57,9 @@ export type ThemeInfo = {
|
||||
name: string;
|
||||
version?: string;
|
||||
apiVersion?: string;
|
||||
workshopId?: string;
|
||||
author?: string;
|
||||
authorId?: number;
|
||||
description?: string;
|
||||
nsfw?: boolean;
|
||||
entry?: string;
|
||||
@@ -90,6 +108,75 @@ const encodeThemePath = (value: string) =>
|
||||
export const themesDirectory = async () =>
|
||||
await path.join(await path.homeDir(), '.ezpplauncher', 'themes');
|
||||
|
||||
const THEME_SYNC_FILENAME = '.workshop-sync.json';
|
||||
const CONTENT_HASH_PATTERN = /^[a-f0-9]{64}$/i;
|
||||
|
||||
export type ThemeWorkshopSync = {
|
||||
contentHash: string;
|
||||
version?: string;
|
||||
workshopId?: string;
|
||||
syncedAt?: number;
|
||||
};
|
||||
|
||||
const readThemeWorkshopSyncFile = async (
|
||||
folderPath: string
|
||||
): Promise<ThemeWorkshopSync | undefined> => {
|
||||
const syncPath = await path.join(folderPath, THEME_SYNC_FILENAME);
|
||||
if (!(await fs.exists(syncPath))) return undefined;
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(await fs.readTextFile(syncPath)) as Partial<ThemeWorkshopSync>;
|
||||
if (!parsed || typeof parsed !== 'object') return undefined;
|
||||
const contentHash =
|
||||
typeof parsed.contentHash === 'string' && CONTENT_HASH_PATTERN.test(parsed.contentHash)
|
||||
? parsed.contentHash.toLowerCase()
|
||||
: undefined;
|
||||
if (!contentHash) return undefined;
|
||||
|
||||
return {
|
||||
contentHash,
|
||||
version: typeof parsed.version === 'string' ? parsed.version : undefined,
|
||||
workshopId: typeof parsed.workshopId === 'string' ? parsed.workshopId : undefined,
|
||||
syncedAt: typeof parsed.syncedAt === 'number' ? parsed.syncedAt : undefined,
|
||||
};
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
export const readThemeWorkshopSync = async (folderName: string) =>
|
||||
readThemeWorkshopSyncFile(await path.join(await themesDirectory(), folderName));
|
||||
|
||||
export const writeThemeWorkshopSync = async (
|
||||
folderName: string,
|
||||
sync: ThemeWorkshopSync
|
||||
): Promise<void> => {
|
||||
const folderPath = await path.join(await themesDirectory(), folderName);
|
||||
const syncPath = await path.join(folderPath, THEME_SYNC_FILENAME);
|
||||
await fs.writeFile(syncPath, new TextEncoder().encode(`${JSON.stringify(sync, null, 2)}\n`));
|
||||
};
|
||||
|
||||
export const hashThemeContent = async (folderName: string) => {
|
||||
const themeFolder = await path.join(await themesDirectory(), folderName);
|
||||
return await invoke<string>('hash_theme_content', { themeFolder });
|
||||
};
|
||||
|
||||
/** Record the current local files as the published Workshop baseline. */
|
||||
export const markThemeSynced = async (
|
||||
folderName: string,
|
||||
options: { version?: string; workshopId?: string } = {}
|
||||
): Promise<ThemeWorkshopSync> => {
|
||||
const contentHash = await hashThemeContent(folderName);
|
||||
const sync: ThemeWorkshopSync = {
|
||||
contentHash,
|
||||
version: options.version,
|
||||
workshopId: options.workshopId,
|
||||
syncedAt: Date.now(),
|
||||
};
|
||||
await writeThemeWorkshopSync(folderName, sync);
|
||||
return sync;
|
||||
};
|
||||
|
||||
/**
|
||||
* Replace a theme in the store instead of mutating it. The theme list is
|
||||
* rendered from a filtered derived list, and Svelte treats each item as
|
||||
@@ -102,51 +189,12 @@ const patchTheme = (name: string, patch: (theme: Theme) => Theme) => {
|
||||
);
|
||||
};
|
||||
|
||||
export const getDownloadableThemes = async () => {
|
||||
const themes: Theme[] = [];
|
||||
|
||||
const downloadableThemes = await betterFetch<
|
||||
{
|
||||
name: string;
|
||||
version: string;
|
||||
author: string;
|
||||
apiVersion?: string;
|
||||
description?: string;
|
||||
nsfw?: boolean;
|
||||
}[]
|
||||
>(`${THEME_REPOSITORY}/raw/branch/main/themes.json`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
'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 (downloadableThemes.data) {
|
||||
for (const theme of downloadableThemes.data) {
|
||||
themes.push({
|
||||
folder_name: `${toSafeName(theme.name)}-${generateRandomString(16)}`,
|
||||
name: theme.name,
|
||||
version: theme.version,
|
||||
apiVersion: theme.apiVersion ?? '1.0',
|
||||
author: theme.author,
|
||||
description: theme.description ?? '',
|
||||
nsfw: theme.nsfw === true,
|
||||
scriptUrl: '',
|
||||
assets: '',
|
||||
preview: `${THEME_REPOSITORY}/raw/branch/main/previews/${toSafeName(theme.name)}.png`,
|
||||
status: 'not-installed',
|
||||
progress: 0,
|
||||
updateAvailable: false,
|
||||
cssStyle: '',
|
||||
});
|
||||
}
|
||||
} else {
|
||||
console.error('Failed to fetch downloadable themes');
|
||||
console.error(downloadableThemes.error);
|
||||
}
|
||||
return themes;
|
||||
/**
|
||||
* Legacy API v1 remote repository loading has been moved to the Community Themes Workshop.
|
||||
* @deprecated Browse and download themes through the Community Themes Workshop instead.
|
||||
*/
|
||||
export const getDownloadableThemes = async (): Promise<Theme[]> => {
|
||||
return [];
|
||||
};
|
||||
|
||||
const themeFromFolder = async (
|
||||
@@ -166,6 +214,8 @@ const themeFromFolder = async (
|
||||
const definition = isV2
|
||||
? normalizeThemeV2(parsed as unknown as Partial<ThemeV2Definition>)
|
||||
: undefined;
|
||||
const sync = await readThemeWorkshopSyncFile(folderPath);
|
||||
const folderStat = await fs.stat(folderPath).catch(() => undefined);
|
||||
|
||||
const httpBase = await themeAssetBase();
|
||||
const httpFolder = httpBase ? `${httpBase}/${encodeURIComponent(folderName)}` : '';
|
||||
@@ -192,9 +242,11 @@ const themeFromFolder = async (
|
||||
: convertFileSrc(await path.normalize(await path.join(folderPath, 'assets')));
|
||||
const previewName = parsed.preview || (isV2 ? 'preview.png' : '');
|
||||
let preview = '';
|
||||
let previewModifiedAt: number | undefined;
|
||||
if (previewName) {
|
||||
const previewPath = await path.join(folderPath, 'assets', previewName);
|
||||
if (await fs.exists(previewPath)) {
|
||||
previewModifiedAt = (await fs.stat(previewPath).catch(() => undefined))?.mtime?.getTime();
|
||||
// The editor rewrites preview.png on every save. A cache-busting query
|
||||
// makes the WebView pick up the new file instead of its cached asset.
|
||||
preview = httpFolder
|
||||
@@ -205,10 +257,17 @@ const themeFromFolder = async (
|
||||
|
||||
return {
|
||||
folder_name: folderName,
|
||||
workshopId: typeof parsed.workshopId === 'string' ? parsed.workshopId : undefined,
|
||||
name: parsed.name,
|
||||
version: parsed.version ?? '1.0.0',
|
||||
apiVersion,
|
||||
author: parsed.author ?? 'Unknown',
|
||||
authorId:
|
||||
typeof parsed.authorId === 'number' &&
|
||||
Number.isSafeInteger(parsed.authorId) &&
|
||||
parsed.authorId > 0
|
||||
? parsed.authorId
|
||||
: undefined,
|
||||
description: parsed.description ?? '',
|
||||
nsfw: parsed.nsfw === true,
|
||||
scriptUrl,
|
||||
@@ -217,6 +276,10 @@ const themeFromFolder = async (
|
||||
status: 'installed',
|
||||
progress: 0,
|
||||
updateAvailable: false,
|
||||
syncedContentHash: sync?.contentHash,
|
||||
syncedVersion: sync?.version,
|
||||
previewModifiedAt,
|
||||
folderCreatedAt: folderStat?.birthtime?.getTime(),
|
||||
cssStyle,
|
||||
definition,
|
||||
};
|
||||
@@ -233,7 +296,7 @@ export const getThemes = async (): Promise<Theme[]> => {
|
||||
author: 'EZPPFarm',
|
||||
name: 'Default',
|
||||
version: '1.0.0',
|
||||
apiVersion: '1.0',
|
||||
apiVersion: '',
|
||||
description: 'The default EZPPLauncher look.',
|
||||
nsfw: false,
|
||||
scriptUrl: '',
|
||||
@@ -424,7 +487,18 @@ export const downloadTheme = async (
|
||||
return { success: true };
|
||||
};
|
||||
|
||||
export const loadTheme = async (theme: Theme, themeContainer: HTMLElement, volume = 0.15) => {
|
||||
type LoadThemeOptions = {
|
||||
/** Crossfade the rendered page when switching themes. */
|
||||
animate?: boolean;
|
||||
};
|
||||
|
||||
export const loadTheme = async (
|
||||
theme: Theme,
|
||||
themeContainer: HTMLElement,
|
||||
volume = 0.15,
|
||||
options: LoadThemeOptions = {}
|
||||
) => {
|
||||
const applyTheme = async () => {
|
||||
// Theme media is buffered as blob URLs; the previous theme's URLs are no
|
||||
// longer needed once it is replaced.
|
||||
clearThemeMediaCache();
|
||||
@@ -434,6 +508,7 @@ export const loadTheme = async (theme: Theme, themeContainer: HTMLElement, volum
|
||||
if (theme.definition) {
|
||||
setGlobalVolume(volume);
|
||||
disableMediaControls();
|
||||
void invoke('unlock_media_autoplay').catch(() => {});
|
||||
return;
|
||||
}
|
||||
if (theme.scriptUrl.length > 0) {
|
||||
@@ -442,6 +517,37 @@ export const loadTheme = async (theme: Theme, themeContainer: HTMLElement, volum
|
||||
}
|
||||
setGlobalVolume(volume);
|
||||
disableMediaControls();
|
||||
|
||||
// Ensure all media elements mounted by v1 themes start playback automatically
|
||||
themeContainer.querySelectorAll<HTMLMediaElement>('video, audio').forEach((media) => {
|
||||
media.muted = false;
|
||||
media.volume = volume;
|
||||
playThemeMedia(media);
|
||||
});
|
||||
|
||||
void invoke('unlock_media_autoplay').catch(() => {});
|
||||
};
|
||||
|
||||
const canAnimate =
|
||||
options.animate &&
|
||||
typeof document !== 'undefined' &&
|
||||
typeof document.startViewTransition === 'function';
|
||||
|
||||
if (!canAnimate) {
|
||||
await applyTheme();
|
||||
return;
|
||||
}
|
||||
|
||||
const transition = document.startViewTransition(async () => {
|
||||
await applyTheme();
|
||||
// Let Svelte paint the new theme before the transition takes its snapshot.
|
||||
await tick();
|
||||
});
|
||||
|
||||
// Theme activation must not wait for, or fail because of, the visual
|
||||
// transition. `finished` can reject when a transition is skipped.
|
||||
void transition.finished.catch(() => {});
|
||||
await transition.updateCallbackDone;
|
||||
};
|
||||
|
||||
export const deleteTheme = async (themeToUninstall: Theme) => {
|
||||
@@ -524,42 +630,22 @@ export const importThemeFromFile = async (themeName: string, filePath: string) =
|
||||
};
|
||||
|
||||
export const reloadThemes = async () => {
|
||||
const [downloadableThemes, installedThemes] = await Promise.all([
|
||||
getDownloadableThemes(),
|
||||
getThemes(),
|
||||
]);
|
||||
|
||||
const installedThemes = await getThemes();
|
||||
const installedMap = new Map(installedThemes.map((t) => [t.name, t]));
|
||||
const combinedMap = new Map(installedThemes.map((t) => [t.name, { ...t }]));
|
||||
|
||||
for (const downloadable of downloadableThemes) {
|
||||
const installed = installedMap.get(downloadable.name);
|
||||
|
||||
if (installed) {
|
||||
try {
|
||||
if (new SemVer(downloadable.version).compare(new SemVer(installed.version)) > 0) {
|
||||
const installedTheme = combinedMap.get(downloadable.name)!;
|
||||
installedTheme.updateAvailable = true;
|
||||
installedTheme.availableVersion = downloadable.version;
|
||||
}
|
||||
} catch {
|
||||
// Ignore malformed versions instead of breaking the whole theme list.
|
||||
}
|
||||
} else {
|
||||
combinedMap.set(downloadable.name, downloadable);
|
||||
}
|
||||
}
|
||||
|
||||
const combinedThemes = [...combinedMap.values()];
|
||||
|
||||
custom_themes.update((storeThemes) => {
|
||||
const storeMap = new Map(storeThemes.map((t) => [t.name, t]));
|
||||
const ACTIVE_STATUSES = new Set(['downloading', 'extracting', 'deleting']);
|
||||
|
||||
const updatedThemes = storeThemes.map((storeTheme) => {
|
||||
const updatedThemes = storeThemes
|
||||
.filter(
|
||||
(storeTheme) => installedMap.has(storeTheme.name) || ACTIVE_STATUSES.has(storeTheme.status)
|
||||
)
|
||||
.map((storeTheme) => {
|
||||
if (ACTIVE_STATUSES.has(storeTheme.status)) return storeTheme;
|
||||
const theme = combinedMap.get(storeTheme.name);
|
||||
const theme = installedMap.get(storeTheme.name);
|
||||
if (!theme) return storeTheme;
|
||||
const versionChanged = storeTheme.version !== theme.version;
|
||||
|
||||
// Replace the object rather than mutating it so the theme cards see the
|
||||
// new values when the list is rendered from a filtered derived array.
|
||||
@@ -570,32 +656,37 @@ export const reloadThemes = async () => {
|
||||
preview: theme.preview,
|
||||
version: theme.version,
|
||||
author: theme.author,
|
||||
authorId: theme.authorId,
|
||||
apiVersion: theme.apiVersion,
|
||||
description: theme.description,
|
||||
nsfw: theme.nsfw,
|
||||
workshopId: theme.workshopId,
|
||||
definition: theme.definition,
|
||||
updateAvailable: theme.updateAvailable,
|
||||
availableVersion: theme.availableVersion,
|
||||
syncedContentHash: theme.syncedContentHash,
|
||||
syncedVersion: theme.syncedVersion,
|
||||
previewModifiedAt: theme.previewModifiedAt,
|
||||
folderCreatedAt: theme.folderCreatedAt,
|
||||
isNotSynced: versionChanged ? false : storeTheme.isNotSynced,
|
||||
updateAvailable: versionChanged ? false : storeTheme.updateAvailable,
|
||||
availableVersion: versionChanged ? undefined : storeTheme.availableVersion,
|
||||
cssStyle: theme.cssStyle,
|
||||
backups: theme.backups ?? storeTheme.backups,
|
||||
};
|
||||
});
|
||||
|
||||
const newThemes = combinedThemes.filter((t) => !storeMap.has(t.name));
|
||||
const newThemes = installedThemes.filter((t) => !storeMap.has(t.name));
|
||||
const merged = [...updatedThemes, ...newThemes];
|
||||
|
||||
return merged.sort((a, b) => {
|
||||
if (a.name === 'Default') return -1;
|
||||
if (b.name === 'Default') return 1;
|
||||
if (a.status === 'installed' && b.status !== 'installed') return -1;
|
||||
if (a.status !== 'installed' && b.status === 'installed') return 1;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
});
|
||||
|
||||
active_custom_theme.update((active) => {
|
||||
if (!active) return active;
|
||||
const updated = combinedMap.get(active.name);
|
||||
const updated = installedMap.get(active.name);
|
||||
return updated ? { ...active, ...updated } : active;
|
||||
});
|
||||
};
|
||||
@@ -614,6 +705,35 @@ export const saveThemeProject = async (
|
||||
return themeFolder;
|
||||
};
|
||||
|
||||
const updateInstalledThemeManifest = async (folderName: string, patch: Record<string, unknown>) => {
|
||||
const themeFolder = await path.join(await themesDirectory(), folderName);
|
||||
const configPath = await path.join(themeFolder, 'theme.json');
|
||||
if (!(await fs.exists(configPath))) {
|
||||
throw new Error('The installed theme.json file was not found.');
|
||||
}
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(await fs.readTextFile(configPath));
|
||||
} catch {
|
||||
throw new Error('The installed theme.json file is not valid JSON.');
|
||||
}
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
throw new Error('The installed theme.json file is not a valid theme manifest.');
|
||||
}
|
||||
|
||||
const updated = { ...(parsed as Record<string, unknown>), ...patch };
|
||||
await fs.writeFile(configPath, new TextEncoder().encode(`${JSON.stringify(updated, null, 2)}\n`));
|
||||
};
|
||||
|
||||
/** Write workshop tags into an installed theme's manifest without dropping other fields. */
|
||||
export const updateInstalledThemeTags = async (folderName: string, tags: string[]) =>
|
||||
updateInstalledThemeManifest(folderName, { tags });
|
||||
|
||||
/** Remember the server-assigned workshop ID so later publishes update the same theme. */
|
||||
export const updateInstalledThemeWorkshopId = async (folderName: string, workshopId: string) =>
|
||||
updateInstalledThemeManifest(folderName, { workshopId });
|
||||
|
||||
export const exportThemeFolder = async (folderName: string, destinationPath: string) => {
|
||||
const themeFolder = await path.join(await themesDirectory(), folderName);
|
||||
await invoke('export_theme', { themeFolder, destinationPath });
|
||||
@@ -645,10 +765,3 @@ export const toSafeName = (name: string) => {
|
||||
.replace(/[. ]+$/g, '_')
|
||||
);
|
||||
};
|
||||
|
||||
const generateRandomString = (length: number) => {
|
||||
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
||||
return Array.from({ length }, () =>
|
||||
characters.charAt(Math.floor(Math.random() * characters.length))
|
||||
).join('');
|
||||
};
|
||||
@@ -2,8 +2,9 @@ import { writable } from 'svelte/store';
|
||||
|
||||
export const customCursor = writable<boolean>(false);
|
||||
export const cursorSmoothening = writable<boolean>(false);
|
||||
export const cursorSmoothness = writable<number>(180);
|
||||
export const cursorSmoothness = writable<number>(14);
|
||||
export const reduceAnimations = writable<boolean>(false);
|
||||
export const gameOptimization = writable<boolean>(false);
|
||||
export const patch = writable<boolean>(true);
|
||||
export const loggingEnabled = writable<boolean>(true);
|
||||
|
||||
|
||||
+78
-11
@@ -1,4 +1,5 @@
|
||||
import { custom_theme_audio_playing } from './global';
|
||||
import { playThemeMedia } from './theme/themeMedia';
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { type ClassValue, clsx } from 'clsx';
|
||||
import * as crypto from 'crypto-js';
|
||||
@@ -132,7 +133,7 @@ export const urlIsValidImage = async (url: string) => {
|
||||
const request = await fetch(url);
|
||||
if (!request.ok) return false;
|
||||
const contentType = request.headers.get('content-type');
|
||||
return contentType?.startsWith('image/');
|
||||
return contentType?.startsWith('image/') === true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
@@ -149,63 +150,128 @@ export function setGlobalVolume(volume: number) {
|
||||
});
|
||||
}
|
||||
|
||||
let activeFadeCancel: (() => void) | undefined = undefined;
|
||||
|
||||
export function fadeGlobalVolume(
|
||||
volumeFrom: number,
|
||||
volumeTo: number,
|
||||
duration: number,
|
||||
onDone?: () => void
|
||||
) {
|
||||
): Promise<void> {
|
||||
if (activeFadeCancel) {
|
||||
activeFadeCancel();
|
||||
activeFadeCancel = undefined;
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const mediaElements: NodeListOf<HTMLMediaElement> = document.querySelectorAll('audio, video');
|
||||
if (mediaElements.length === 0 || duration <= 0) {
|
||||
if (mediaElements.length > 0) {
|
||||
mediaElements.forEach((element) => {
|
||||
element.volume = Math.min(1, Math.max(0, volumeTo));
|
||||
});
|
||||
}
|
||||
if (onDone) onDone();
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
let animationFrameId: number;
|
||||
|
||||
activeFadeCancel = () => {
|
||||
cancelled = true;
|
||||
cancelAnimationFrame(animationFrameId);
|
||||
};
|
||||
|
||||
const startTime = performance.now();
|
||||
|
||||
function animate() {
|
||||
if (cancelled) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTime = performance.now();
|
||||
const elapsedTime = currentTime - startTime;
|
||||
const progress = Math.min(elapsedTime / duration, 1);
|
||||
|
||||
const interpolatedVolume = volumeFrom + (volumeTo - volumeFrom) * progress;
|
||||
const interpolatedVolume = Math.min(
|
||||
1,
|
||||
Math.max(0, volumeFrom + (volumeTo - volumeFrom) * progress)
|
||||
);
|
||||
|
||||
mediaElements.forEach((element) => {
|
||||
element.volume = interpolatedVolume;
|
||||
});
|
||||
|
||||
if (progress < 1) {
|
||||
requestAnimationFrame(animate);
|
||||
animationFrameId = requestAnimationFrame(animate);
|
||||
} else {
|
||||
activeFadeCancel = undefined;
|
||||
if (onDone) onDone();
|
||||
resolve();
|
||||
}
|
||||
}
|
||||
|
||||
animate();
|
||||
animationFrameId = requestAnimationFrame(animate);
|
||||
});
|
||||
}
|
||||
|
||||
export const pauseGlobalMedia = () => {
|
||||
if (activeFadeCancel) {
|
||||
activeFadeCancel();
|
||||
activeFadeCancel = undefined;
|
||||
}
|
||||
const mediaElements: NodeListOf<HTMLMediaElement> = document.querySelectorAll('audio, video');
|
||||
mediaElements.forEach((element) => element.pause());
|
||||
mediaElements.forEach((element) => {
|
||||
try {
|
||||
element.pause();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const resumeGlobalMedia = () => {
|
||||
const mediaElements: NodeListOf<HTMLMediaElement> = document.querySelectorAll('audio, video');
|
||||
mediaElements.forEach((element) => element.play());
|
||||
mediaElements.forEach((element) => {
|
||||
try {
|
||||
if (element instanceof HTMLVideoElement && element.error) {
|
||||
element.load();
|
||||
}
|
||||
playThemeMedia(element);
|
||||
} catch (err) {
|
||||
console.warn('Could not resume global media:', err);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const setCurrentTimeGlobalMedia = (time: number) => {
|
||||
const mediaElements: NodeListOf<HTMLMediaElement> = document.querySelectorAll('audio, video');
|
||||
mediaElements.forEach((element) => (element.currentTime = time));
|
||||
mediaElements.forEach((element) => {
|
||||
try {
|
||||
if (Number.isFinite(element.duration) && element.duration > 0) {
|
||||
element.currentTime = Math.min(Math.max(0, time), element.duration);
|
||||
} else {
|
||||
element.currentTime = Math.max(0, time);
|
||||
}
|
||||
} catch {
|
||||
// ignore if media is not seekable
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export function trackMediaContainer(node: HTMLElement) {
|
||||
const media = new Set<HTMLMediaElement>();
|
||||
|
||||
function update() {
|
||||
custom_theme_audio_playing.set(
|
||||
Array.from(media).some((el) => !el.paused && !(el instanceof HTMLVideoElement && el.muted))
|
||||
);
|
||||
custom_theme_audio_playing.set(Array.from(media).some((el) => !el.paused));
|
||||
}
|
||||
|
||||
function register(el: HTMLMediaElement) {
|
||||
media.add(el);
|
||||
update();
|
||||
|
||||
const handler = () => update();
|
||||
el.addEventListener('play', handler);
|
||||
@@ -213,6 +279,7 @@ export function trackMediaContainer(node: HTMLElement) {
|
||||
|
||||
return () => {
|
||||
media.delete(el);
|
||||
update();
|
||||
el.removeEventListener('play', handler);
|
||||
el.removeEventListener('pause', handler);
|
||||
};
|
||||
|
||||
+134
-32
@@ -1,8 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { browser } from '$app/environment';
|
||||
import Logo from '$assets/logo.png';
|
||||
import DiscordPresenceEditor from '$lib/components/presence/DiscordPresenceEditor.svelte';
|
||||
import ThemeEditorWindow from '$lib/components/theme/ThemeEditorWindow.svelte';
|
||||
import ThemeV2Background from '$lib/components/theme/ThemeV2Background.svelte';
|
||||
import * as AlertDialog from '$lib/components/ui/alert-dialog';
|
||||
import AnimatedBg from '$lib/components/ui/animated-bg/AnimatedBg.svelte';
|
||||
@@ -38,19 +36,22 @@
|
||||
import { exit, getLauncherVersion, getPlatform, setLoggingEnabled } from '$lib/osuUtil';
|
||||
import * as presence from '$lib/presence';
|
||||
import {
|
||||
initThemeMediaStatusListener,
|
||||
smoothThemeMedia,
|
||||
themeMediaPreparing,
|
||||
themeMediaStatus,
|
||||
themeMediaSuspended,
|
||||
themeMediaSuspension,
|
||||
} from '$lib/themeMedia';
|
||||
import { isThemeTrusted } from '$lib/themeTrust';
|
||||
import { themeV2Css } from '$lib/themeV2';
|
||||
import { getDownloadableThemes, getThemes, loadTheme } from '$lib/themes';
|
||||
} from '$lib/theme/themeMedia';
|
||||
import { themeParallax } from '$lib/theme/themeParallax';
|
||||
import { isThemeTrusted } from '$lib/theme/themeTrust';
|
||||
import { themeV2Css } from '$lib/theme/themeV2';
|
||||
import { getThemes, loadTheme } from '$lib/theme/themes';
|
||||
import { currentUser } from '$lib/userAuthentication';
|
||||
import {
|
||||
cursorSmoothening,
|
||||
customCursor,
|
||||
gameOptimization,
|
||||
loggingEnabled,
|
||||
patch,
|
||||
reduceAnimations,
|
||||
@@ -63,7 +64,6 @@
|
||||
import { WebviewWindow } from '@tauri-apps/api/webviewWindow';
|
||||
import { getCurrentWindow } from '@tauri-apps/api/window';
|
||||
import { Buffer } from 'buffer';
|
||||
import { SemVer } from 'semver';
|
||||
import { sileo } from 'sileo';
|
||||
import { onDestroy, onMount } from 'svelte';
|
||||
import { get } from 'svelte/store';
|
||||
@@ -71,6 +71,37 @@
|
||||
|
||||
let { children } = $props();
|
||||
|
||||
function appActivity(node: HTMLElement) {
|
||||
let focused = true;
|
||||
|
||||
const sync = () => {
|
||||
node.classList.toggle('app-inactive', document.hidden || !focused);
|
||||
};
|
||||
const onBlur = () => {
|
||||
focused = false;
|
||||
sync();
|
||||
};
|
||||
const onFocus = () => {
|
||||
focused = true;
|
||||
sync();
|
||||
};
|
||||
const onVisibilityChange = () => sync();
|
||||
|
||||
window.addEventListener('blur', onBlur);
|
||||
window.addEventListener('focus', onFocus);
|
||||
document.addEventListener('visibilitychange', onVisibilityChange);
|
||||
sync();
|
||||
|
||||
return {
|
||||
destroy() {
|
||||
window.removeEventListener('blur', onBlur);
|
||||
window.removeEventListener('focus', onFocus);
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange);
|
||||
node.classList.remove('app-inactive');
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
let unlistenEditorState: (() => void) | undefined;
|
||||
let unlistenRequestEditorData: (() => void) | undefined;
|
||||
let unlistenPresenceEditorState: (() => void) | undefined;
|
||||
@@ -80,6 +111,51 @@
|
||||
unlistenPresenceEditorState?.();
|
||||
});
|
||||
|
||||
// macOS WKWebView enables autocorrect, capitalization and spell checking
|
||||
// for editable fields by default. Disable them across the launcher so
|
||||
// usernames, search fields and theme text are not rewritten while typing.
|
||||
const disableTextAssistance = (element: Element) => {
|
||||
if (
|
||||
!(element instanceof HTMLInputElement) &&
|
||||
!(element instanceof HTMLTextAreaElement) &&
|
||||
!(element instanceof HTMLElement && element.isContentEditable)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
element.spellcheck = false;
|
||||
element.setAttribute('autocorrect', 'off');
|
||||
element.setAttribute('autocapitalize', 'none');
|
||||
};
|
||||
|
||||
const disableTextAssistanceIn = (root: ParentNode) => {
|
||||
if (root instanceof Element) disableTextAssistance(root);
|
||||
root.querySelectorAll('input, textarea, [contenteditable]').forEach(disableTextAssistance);
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
disableTextAssistanceIn(document);
|
||||
|
||||
const observer = new MutationObserver((mutations) => {
|
||||
for (const mutation of mutations) {
|
||||
mutation.addedNodes.forEach((node) => {
|
||||
if (node instanceof Element) disableTextAssistanceIn(node);
|
||||
});
|
||||
}
|
||||
});
|
||||
observer.observe(document.body, { childList: true, subtree: true });
|
||||
|
||||
const handleFocus = (event: FocusEvent) => {
|
||||
if (event.target instanceof Element) disableTextAssistance(event.target);
|
||||
};
|
||||
document.addEventListener('focusin', handleFocus, true);
|
||||
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
document.removeEventListener('focusin', handleFocus, true);
|
||||
};
|
||||
});
|
||||
|
||||
if (browser) initLogging();
|
||||
|
||||
const editorWindow = (() => {
|
||||
@@ -147,6 +223,8 @@
|
||||
}
|
||||
|
||||
onMount(async () => {
|
||||
initThemeMediaStatusListener();
|
||||
|
||||
try {
|
||||
const ver = await getLauncherVersion();
|
||||
if (ver) launcherVersion.set(ver);
|
||||
@@ -170,6 +248,7 @@
|
||||
osuStream: get(osuStream),
|
||||
serverPing: get(serverPing),
|
||||
launcherVersion: get(launcherVersion),
|
||||
discordPresence: get(discordPresence),
|
||||
});
|
||||
} catch {}
|
||||
};
|
||||
@@ -260,6 +339,7 @@
|
||||
const config_custom_cursor = config.value<boolean>('custom_cursor');
|
||||
const config_cursor_smoothening = config.value<boolean>('cursor_smoothening');
|
||||
const config_reduce_animations = config.value<boolean>('reduce_animations');
|
||||
const config_game_optimization = config.value<boolean>('game_optimization');
|
||||
const config_logging_enabled = config.value<boolean>('logging_enabled');
|
||||
const config_discord_presence = config.value<boolean>('discord_presence');
|
||||
const config_tracking_enabled = config.value<boolean>('tracking_consent');
|
||||
@@ -272,9 +352,12 @@
|
||||
const last_theme = localThemes.find((t) => t.name === lastThemeName);
|
||||
const canLoadLastTheme = Boolean(last_theme && isThemeTrusted(last_theme));
|
||||
|
||||
const initialVolume = await config_theme_volume.get(0.15);
|
||||
custom_theme_volume.set(initialVolume);
|
||||
|
||||
if (!last_theme || !canLoadLastTheme) {
|
||||
await config.value<string>('theme').set('Default');
|
||||
loadTheme(defaultTheme, $custom_theme_container!, await config_theme_volume.get(0.15));
|
||||
loadTheme(defaultTheme, $custom_theme_container!, initialVolume);
|
||||
if (last_theme && !canLoadLastTheme) {
|
||||
sileo.error({
|
||||
title: 'Theme needs approval',
|
||||
@@ -283,14 +366,15 @@
|
||||
});
|
||||
}
|
||||
} else {
|
||||
loadTheme(last_theme, $custom_theme_container!, await config_theme_volume.get(0.15));
|
||||
loadTheme(last_theme, $custom_theme_container!, initialVolume);
|
||||
}
|
||||
|
||||
custom_theme_volume.set(await config_theme_volume.get(0.15));
|
||||
void invoke('reveal_window').catch(() => {});
|
||||
patch.set(await config_patching.get(true));
|
||||
customCursor.set(await config_custom_cursor.get(true));
|
||||
cursorSmoothening.set(await config_cursor_smoothening.get(true));
|
||||
reduceAnimations.set(await config_reduce_animations.get(false));
|
||||
gameOptimization.set(await config_game_optimization.get(false));
|
||||
loggingEnabled.set(await config_logging_enabled.get(true));
|
||||
discordPresence.set(await config_discord_presence.get(true));
|
||||
openTabletDriverEnabled.set(await config_otd_enabled.get(false));
|
||||
@@ -303,6 +387,7 @@
|
||||
customCursor.subscribe(async (val) => await config_custom_cursor.set(val));
|
||||
cursorSmoothening.subscribe(async (val) => await config_cursor_smoothening.set(val));
|
||||
reduceAnimations.subscribe(async (val) => await config_reduce_animations.set(val));
|
||||
gameOptimization.subscribe(async (val) => await config_game_optimization.set(val));
|
||||
loggingEnabled.subscribe(async (val) => {
|
||||
await config_logging_enabled.set(val);
|
||||
await setLoggingEnabled(val);
|
||||
@@ -338,31 +423,13 @@
|
||||
|
||||
try {
|
||||
currentLoadingInfo.set('Loading themes...');
|
||||
const downloadableThemes = await getDownloadableThemes();
|
||||
const combinedThemes = [...localThemes];
|
||||
for (const theme of downloadableThemes) {
|
||||
if (!combinedThemes.find((t) => t.name === theme.name)) combinedThemes.push(theme);
|
||||
const installedTheme = localThemes.find((t) => t.name === theme.name);
|
||||
if (installedTheme) {
|
||||
const installedThemeVersion = new SemVer(installedTheme.version);
|
||||
const downloadableThemeVersion = new SemVer(theme.version);
|
||||
if (downloadableThemeVersion.compare(installedThemeVersion) > 0) {
|
||||
installedTheme.updateAvailable = true;
|
||||
const index = combinedThemes.findIndex((t) => t.name === theme.name);
|
||||
combinedThemes[index] = installedTheme;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
combinedThemes.sort((a, b) => {
|
||||
localThemes.sort((a, b) => {
|
||||
if (a.name === 'Default') return -1;
|
||||
if (b.name === 'Default') return 1;
|
||||
if (a.status === 'installed' && b.status !== 'installed') return -1;
|
||||
if (a.status !== 'installed' && b.status === 'installed') return 1;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
custom_themes.set(combinedThemes);
|
||||
custom_themes.set(localThemes);
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
sileo.error({
|
||||
@@ -374,6 +441,23 @@
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<style>
|
||||
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;
|
||||
}
|
||||
</style>
|
||||
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
|
||||
{@html `<style>${$active_custom_theme?.cssStyle || ''}</style>`}
|
||||
{#if $active_custom_theme?.definition}
|
||||
@@ -396,9 +480,19 @@
|
||||
/>
|
||||
|
||||
{#if editorWindow}
|
||||
{#await import('$lib/components/theme/ThemeEditorWindow.svelte')}
|
||||
<div class="h-screen w-screen bg-theme-950"></div>
|
||||
{:then editorModule}
|
||||
{@const ThemeEditorWindow = editorModule.default}
|
||||
<ThemeEditorWindow />
|
||||
{/await}
|
||||
{:else if presenceEditorWindow}
|
||||
{#await import('$lib/components/presence/DiscordPresenceEditor.svelte')}
|
||||
<div class="h-screen w-screen bg-theme-950"></div>
|
||||
{:then presenceModule}
|
||||
{@const DiscordPresenceEditor = presenceModule.default}
|
||||
<DiscordPresenceEditor standalone />
|
||||
{/await}
|
||||
{:else}
|
||||
{#if editorOpen}
|
||||
<div
|
||||
@@ -489,7 +583,15 @@
|
||||
</AlertDialog.Content>
|
||||
</AlertDialog.Root>
|
||||
|
||||
<main use:themeMediaSuspension>
|
||||
<main
|
||||
class="relative h-screen w-full overflow-hidden"
|
||||
use:appActivity
|
||||
use:themeMediaSuspension
|
||||
use:themeParallax={{
|
||||
enabled: $active_custom_theme?.definition?.parallax?.enabled === true,
|
||||
intensity: $active_custom_theme?.definition?.parallax?.intensity ?? 0.25,
|
||||
}}
|
||||
>
|
||||
<div class:hidden={!!$active_custom_theme?.definition}>
|
||||
<div class="opacity-30">
|
||||
<div transition:fade={{ duration: $reduceAnimations ? 0 : 500 }}>
|
||||
@@ -524,7 +626,7 @@
|
||||
<div
|
||||
class="pointer-events-none fixed bottom-4 left-1/2 z-50 -translate-x-1/2 rounded-full border border-white/10 bg-black/75 px-4 py-2 text-xs font-medium text-white/80 shadow-xl backdrop-blur animate-pulse"
|
||||
>
|
||||
{$themeMediaStatus || 'Preparing theme video for smooth playback…'}
|
||||
{$themeMediaStatus || 'Converting theme video…'}
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
+1138
-202
File diff suppressed because it is too large.
Load diff
@@ -4,7 +4,6 @@
|
||||
import { git } from '$lib/api/git';
|
||||
import { config } from '$lib/config';
|
||||
import { currentUserInfo } from '$lib/data';
|
||||
import { estimateFrameRate } from '$lib/displayUtils';
|
||||
import {
|
||||
beatmapSets,
|
||||
currentLoadingInfo,
|
||||
@@ -30,12 +29,7 @@
|
||||
} from '$lib/osuUtil';
|
||||
import type { EZPPUser } from '$lib/types';
|
||||
import { currentUser } from '$lib/userAuthentication';
|
||||
import {
|
||||
cursorSmoothness,
|
||||
osuInstallationPath,
|
||||
preferredMode,
|
||||
preferredType,
|
||||
} from '$lib/userSettings';
|
||||
import { osuInstallationPath, preferredMode, preferredType } from '$lib/userSettings';
|
||||
import Launch from './Launch.svelte';
|
||||
import SetupWizard from './SetupWizard.svelte';
|
||||
import { animate, utils } from 'animejs';
|
||||
@@ -65,21 +59,7 @@
|
||||
}, 450);
|
||||
};
|
||||
|
||||
const calculateCursorSmoothness = async () => {
|
||||
const refreshRate = await estimateFrameRate();
|
||||
const hzMin = 60;
|
||||
const hzMax = 500;
|
||||
const durationMin = 350;
|
||||
const durationMax = 600;
|
||||
const clamped = Math.min(Math.max(refreshRate, hzMin), hzMax);
|
||||
const duration =
|
||||
durationMin + ((clamped - hzMin) / (hzMax - hzMin)) * (durationMax - durationMin);
|
||||
cursorSmoothness.set(Math.round(duration));
|
||||
};
|
||||
|
||||
const prepare = async () => {
|
||||
await calculateCursorSmoothness();
|
||||
|
||||
const username = await config.value<string>('username').get('');
|
||||
const password = await config.value<string>('password').get('');
|
||||
|
||||
|
||||
Reference in new issue
Block a user