Xbox Cloud Gaming app for PS5 Homebrew
C
release: v1.6.3 - streaming stutter fix, full catalog descriptions, 20 tips, reactive diagnostics, and tri-platform release
Rafael Abud Ferreira3877552229cd
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 718cb79..96f9671 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -1,7 +1,7 @@# SPDX-License-Identifier: GPL-3.0-or-later# Copyright (C) 2026 RafaelNGPcmake_minimum_required(VERSION 3.20)-project(xcloud_ps5 VERSION 1.6.2 LANGUAGES C CXX)+project(xcloud_ps5 VERSION 1.6.3 LANGUAGES C CXX)set(CMAKE_CXX_STANDARD 20)set(CMAKE_CXX_STANDARD_REQUIRED ON)diff --git a/ROADMAP.md b/ROADMAP.mdindex ac32758..c349a10 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -4,7 +4,7 @@ Planejamento e visão de futuro do projeto **PSBox Cloud Gaming**, priorizado poStatus: **Em andamento (next)**, **Planejado (planned)**, **Futuro (later)**, **Descartado (dropped)**.-> **Última atualização:** 04/11/2026 (release estável **v1.6.0** / suporte a controles USB nativos e cotas de nuvem).+> **Última atualização:** 07/11/2026 (release estável **v1.6.3** / correções de engasgos de streaming no PS5, cache v3, 20 dicas de launching e diagnósticos reativos).---@@ -34,6 +34,27 @@ Status: **Em andamento (next)**, **Planejado (planned)**, **Futuro (later)**, **### 6. Cotas de Tempo de Nuvem e Avisos em Jogo — *done (v1.6.0)* (#342)- **Implementação**: Suporte a limites de tempo mensal de nuvem (parser de horas restantes e totais, exibição na barra superior centralizada, avisos a 15m/5m e tela amigável com QR Code).+### 7. Diagnóstico "Verificar meu login" Inoperante (Modal Aberto sem Execução) — *done (v1.6.3)*+- **Sintoma Resolvido**: Modal abria em branco sem disparar os testes nem renderizar o feedback de progresso dos estágios de validação.+- **Implementação**:+ - Inicialização reativa imediata dos 6 estágios de validação (`signInCheck_.stages`) com spinners de carregamento em `openTester()`.+ - Fila não-bloqueante à prova de descartes com retry loop em `app_core.cpp` para o comando `kCheckSignIn`.+ - Preservação estrita de 100% da lógica e apresentação originais em `worker_diagnostics.cpp` e `app_ui_settings.cpp`.++### 8. Diagnóstico "Teste de rede" Inoperante (Modal Estático em "UDP / STUN (NAT)") — *done (v1.6.3)*+- **Sintoma Resolvido**: Modal abria estático exibindo apenas o cabeçalho UDP/STUN sem realizar medições de RTT e jitter para as regiões dos datacenters.+- **Implementação**:+ - Inicialização reativa imediata das regiões (`networkTest_.regions`) com indicadores de sondagem ativa (`...`).+ - Retry loop seguro para o comando `kNetworkTest` em `app_core.cpp` eliminando descartes durante transições do worker.+ - Sondas STUN RFC 5389 operando com total integridade e reportando latências instantaneamente à UI.++### 9. Problemas de Mapeamento de Input OneFamily no PS4 nas Opções 2, 3 e 4 (#369) — *investigating (prioridade máxima)*+- **Sintoma Reportado**: Feedback de usuários na build de PS4 (issue #369) reportando falhas com o driver OneFamily integrado: quando o controle está configurado como **Opção 1**, tudo opera perfeitamente. No entanto, ao selecionar as **Opções 2, 3 ou 4**, alguns jogos apresentam anomalias e perda de reconhecimento de inputs/botões (comprovado em testes com *Remnant II*). Ao retornar para a Opção 1, o controle volta ao funcionamento normal.+- **Investigação & Correção**:+ - Auditar as rotinas de multiplexação de portas, índices de dispositivos e tabelas de mapeamento HID em `src/input/pad_usb_ps4.cpp`, `src/input/pad_usb.cpp` e `src/input/pad_usb_hid.cpp`.+ - Verificar se as configurações das opções 2, 3 e 4 introduzem divergências no parsing de relatórios de entrada (input reports), no tratamento de botões compartilhados ou na leitura de múltiplos slots via `libSceUsbd`.+ - Corrigir o tratamento de estados e validar a consistência de leitura de botões e eixos em todos os modos suportados.+---## 🚀 Em Andamento e Próximos Passos (Now & Next)@@ -59,21 +80,32 @@ Expansão do servidor local integrado (porta 8080) para multiplayer cooperativo- **Suporte a até 4 Smartphones Simultâneos**: Seleção dinâmica de slot (`P1`, `P2`, `P3`, `P4`) via `/gamepad`, heartbeat automático de desconexão e transmissão binária via WebSocket (`/ws`) com latência < 5 ms.- **PSBox Layout Studio**: Editor visual de controles na WebUI com pré-visualização WYSIWYG, ajuste de botões analógicos e gatilhos para telas de toque, salvamento de perfis (`portrait`/`landscape`) e persistência imediata.+### 4. SmartGlass QR Code no In-Game Menu (Overlay) — *next (v1.7.0)*+Acesso instantâneo e sem digitação manual ao controle virtual via smartphone durante a transmissão:+- **Exibição Dinâmica no Overlay**: Renderização de código QR vetorial de alta definição diretamente na interface do menu in-game (`stream_menu.cpp`).+- **Resolução Automática de IP Local**: Aponta dinamicamente para o endereço local da porta 8080 (`http://<ip_ps5>:8080/gamepad`), permitindo que qualquer smartphone conectado à rede Wi-Fi pareie instantaneamente como controle complementar ou principal (P1..P4).+- **Toggle de Exibição Rápida**: Opção dedicada no menu in-game (<kbd>TOUCHPAD</kbd> + <kbd>OPTIONS</kbd>) para exibir e ocultar o QR Code com 1 clique sem interromper a transmissão.+---## 📋 Planejado para o Futuro (Planned & Later)-### 1. Sincronização de Conquistas Xbox para Troféus PlayStation (PS5/PS4) — *planned*-Espelhamento contínuo das conquistas obtidas no Xbox Cloud Gaming para o subsistema local de troféus da conta PlayStation:-- **Loop de Monitoramento Ativo (`worker_stream.cpp`)**: A cada 20 segundos de gameplay ativo, consulta a API Xbox Live (`fetchTitleAchievements(xboxTitleId, xuid)`) e compara os status com snapshot mantido em disco e memória.-- **Mapeamento de Gamerscore para Graus de Troféus**:- - `5G` a `15G` ──► Troféu **Bronze**- - `20G` a `45G` ──► Troféu **Prata**- - `50G` a `100G` ──► Troféu **Ouro**- - `100% dos Achievements` do jogo obtidos ──► Troféu **Platina**-- **HUD & Notificação em Tempo Real**: Banner translúcido animado exibido no topo da tela com o ícone original da conquista, nome, descrição, pontuação Gamerscore e reprodução do áudio característico de desbloqueio de troféu.-- **Integração com Subsistema Local PlayStation**: Gravação dos registros no banco local do console (`/user/home/<id>/trophy/db/trophy_local.db`) ou chamadas `sceNpTrophy` no console desbloqueado.-- **Retro-Sincronização (Back-Sync)**: Botão dedicado na tela de detalhes do título para sincronizar retroativamente todas as conquistas já obtidas na conta para a base de troféus do console.+### 1. Sincronização de Conquistas Xbox para Troféus PlayStation (PS5 Entregue / Pop-in Nativo & PS4 Planejados) — *em evolução*+Espelhamento contínuo e estritamente aditivo das conquistas obtidas no Xbox Cloud Gaming para o subsistema local de troféus da conta PlayStation:+- **Entregue no PS5 (`PSBox_Trophies.elf` + Provisionamento Nativo)**:+ - **Automação 100% Transparente**: Payload interno (`assets/PSBox_Trophies.elf` estagiado em `/data/psbox/PSBox_Trophies.elf`) enviado automaticamente na inicialização sem exigir configuração manual pelo usuário.+ - **Sincronização Estritamente Aditiva e Proteção de Jogos Locais**: Preserva integralmente quaisquer troféus e timestamps já conquistados localmente no console (`TRPTITLE.DAT` e pacotes `TROPHY.UCP` de jogos instalados em disco/PSN nunca são sobrescritos ou zerados; conquistas de nuvem apenas somam novos troféus ao progresso existente).+ - **Controle Individual por Jogo**: Opção nas configurações individuais de cada jogo (<kbd>OPTIONS</kbd> na tela de detalhes) para desativar a sincronização de troféus de títulos específicos mantendo a sincronização global ativa para o restante da biblioteca.+ - **Zero Toasts do Aplicativo em Gameplay**: Como o próprio stream de vídeo do Xbox já exibe a notificação da conquista em tela, o aplicativo não exibe toasts próprios ao desbloquear troféus.+- **Exploração Futura — Pop-in Nativo do Sistema PlayStation Durante a Gameplay (`planned`)**:+ - Investigar o acionamento direto do pop-in nativo de troféu do sistema operacional do PS5 (`SceNotification` / canal `Trophies` com template `InteractiveToastTrophy` ou gatilho de transição `0 -> 1` via `sceNpTrophy2UnlockTrophy` com contexto ativo do `NPWR` dinâmico) durante a transmissão para exibir o banner oficial do PS5 sem sobrepor toasts customizados do app.+- **Plano Técnico para Suporte Nativo de Troféus no PlayStation 4 (`planned`)**:+ - Atualmente no PS4, `libSceNpTrophy` (`sceNpTrophyRegisterContext` / `sceNpTrophyUnlockTrophy`) exige um pacote `TROPHY.TRP` assinado pela chave oficial da Sony em `/app0/sce_sys/trophy/trophy00.trp` e vinculado ao `NPWR` fixo do pacote FPKG, não permitindo registrar múltiplos jogos de nuvem dinamicamente via API padrão.+ - **Referência de Implementação**: [Atlas Trophy Tool (Pauloxzak)](https://github.com/Pauloxzak/atlas-trophy-tool) — projeto de referência da comunidade para manipulação, extração, reconstrução de pacotes `TROPHY.TRP` (com `TROPCONF.SFM` e ícones) e injeção direta no banco `trophy_local.db` do PlayStation 4.+ - **Arquitetura Planejada para PS4**:+ 1. **Construtor de Pacotes `TRP` (v1/v2)**: Implementar gerador de arquivos `TROPHY.TRP` (formato de arquivo Orbis OS contendo `TROPCONF.SFM` XML + `ICON0.PNG` + `TROP000.PNG..TROP127.PNG` sem criptografia em ambiente GoldHEN/desbloqueado) em `/user/home/<uid>/trophy/conf/<NPWR>/TROPHY.TRP`.+ 2. **Provisionamento Direto no SQLite do Orbis OS (`trophy_local.db`)**: Popular de forma aditiva as tabelas `tbl_trophy_title` (resumo de progresso, `np_comm_id`, título, contadores de bronze/prata/ouro/platina) e `tbl_trophy_flag` (estado `unlocked`, `time_unlocked` em ticks RTC, `grade`, `visible`) diretamente em `/user/home/<uid>/trophy/db/trophy_local.db`, preservando troféus locais existentes.+ 3. **Metadados de Reconhecimento no `/system_data/priv/mms/app.db` (PS4)**: Inserir entradas sintéticas de catálogo para que a tela nativa de Troféus do PS4 exiba os ícones e listas sem exigir FPKGs individuais instalados para cada jogo da nuvem.### 2. Auto-Update para PlayStation 4 via GoldHEN Package Installer API — *planned*Superar a limitação de partição somente-leitura (`/user/app/`) do Orbis OS permitindo atualizações diretas no PS4 sem depender de pendrive ou computador:@@ -88,6 +120,25 @@ Superar a limitação de partição somente-leitura (`/user/app/`) do Orbis OS p### 4. Atalhos Diretos na Tela Inicial do PS5 (Home-Screen Forwarders) — *later*- Criação de atalhos individuais na dashboard principal do PS5 para iniciar títulos específicos em nuvem diretamente, utilizando o formato ProsperoLight forwarder.+### 5. Suporte Completo a Teclado e Mouse no PlayStation 4 — *planned*+Paridade total no suporte a periféricos USB entre as versões de PS5 e PS4:+- **Camada de Entrada Nativa**: Habilitar a inicialização e polling contínuo via `libSceKeyboard` e `libSceMouse` (`src/input/kbm_ps4.cpp`) conectado diretamente ao loop de eventos global (`src/app/app_core.cpp`).+- **Identificação Visual Dinâmica**: Exibição do ícone do periférico em uso (`kIconKeyboardMouse` / `U+F8FE`) nos indicadores da UI, barra superior e menu in-game (`stream_menu.cpp`).+- **Navegação e Jogabilidade Transparente**:+ - Emulação de gamepad para controle da dashboard e jogabilidade direta em qualquer jogo da nuvem (inclusive títulos que não aceitam KBM nativo no stream).+ - Encaminhamento direto de eventos de mouse e teclado nos títulos com suporte nativo KBM.+ - Captura e liberação suave do cursor do mouse em transições de menus e overlays.++### 6. Calibração de Giroscópio e Ajuste Fino de Mira In-Game (RFC / Discussão Prévia) — *planned*+Recurso solicitado pela comunidade para jogos de tiro e mira precisa (ex: *Call of Duty: Warzone*, *Remnant II*, *Halo Infinite*):+- **Objetivo**: Permitir calibração dinâmica dos sensores de movimento (giroscópio/acelerômetro) do DualSense (PS5) e DualShock 4 (PS4) durante a sessão ativa na nuvem através do menu in-game (overlay).+- **Escopo e Planejamento Técnico**:+ - **Compensação de Desvio Estático (Zero-Drift Bias)**: Rotina de calibração rápida no menu in-game (ex: 2 a 3 segundos com o controle em repouso) para calcular a média de erro dos eixos angulares e zerar o drift estático.+ - **Ajustes de Sensibilidade e Zona Morta (Deadzone)**: Configurações análogas à calibração de sticks analógicos, incluindo deadzone angular para amortecer micro-tremores involuntários e multiplicadores de sensibilidade separados para eixos horizontal (yaw) e vertical (pitch).+ - **Menu de Calibração In-Game**: Interface acessível diretamente durante o streaming (<kbd>OPTIONS</kbd> + <kbd>TOUCHPAD</kbd>), possibilitando testar e refinar a precisão em tempo real.+ - **Persistência por Jogo**: Armazenamento dos parâmetros no perfil do título (`activeGameProfile_` em `settings.json`).+ - *Processo*: Requisitos e comportamento de UI/UX serão conversados e alinhados detalhadamente antes de qualquer implementação de código.+---## 🚫 Decisões Técnicas e Recursos Descartados (Dropped)@@ -105,7 +156,13 @@ Superar a limitação de partição somente-leitura (`/user/app/`) do Orbis OS pPara o histórico completo e detalhado de todas as versões anteriores (v0.3.0 até v1.4.0), consulte as [Releases Oficiais no GitHub](https://github.com/RafaelNGP/xbox-cloud-gaming-ps5/releases).-- **v1.6.0** *(Atual)*:+- **v1.6.3** *(Atual)*:+ - **Eliminação de Engasgos de Streaming no PS5**: Pausa automática e completa do processamento da fila em lote de troféus (`TaskType::BatchTitle`) em `g_trophyThread` durante gameplay ativo (`isStreaming()`), eliminando micro-travamentos e contenção de CPU; checagem em tempo real (`TaskType::RealtimePoll`) mantida com prioridade máxima e retomada suave pós-sessão.+ - **Restauração de Descrições Completas & Cache v3**: Inversão de precedência para priorizar descrições longas (`ProductDescription`) sobre slogans curtos (`ProductDescriptionShort`); migração automática para `kCacheVersion = 3` com reidratação de textos curtos via API `RemoteHighSapphire0`.+ - **20 Dicas Dinâmicas na Tela de Launching**: Expansão de 8 para 20 dicas cobrindo todas as novidades recentes (DualSense haptics/triggers, mouse no touchpad, WebUI SmartGlass, troféus, controles USB e áudio), rotacionando a cada 7 segundos com semente pseudo-aleatória por sessão e localização completa em 6 idiomas (EN, PT-BR, ES, DE, FR, IT).+ - **Restauração Reativa dos Diagnósticos**: Telas "Verificar meu login" e "Teste de rede" inicializadas reativamente com spinners e sondagem instantânea de estágios e regiões; retry loop em `app_core.cpp` prevenindo descartes de comandos durante transições do worker.+ - **Lançamento Tri-Plataforma Triplo**: Pacotes completos e verificados para PlayStation 5 (Standalone + Atualizador In-App PPSA99810), PlayStation 4 (FPKG GoldHEN) e Linux Desktop / Steam Deck (AppImage).+- **v1.6.0**:- **Controles USB no PS5**: Xbox Series no cabo e controles/dongles XInput (8BitDo Ultimate 2.4G), cada um como seu próprio jogador.- **Horas de jogo na nuvem** (#342): tempo restante na barra superior, avisos aos 15 e 5 minutos, e tela explicativa com QR quando o tempo acaba.- **Microfone em pacotes de 10 ms** (#187): latência de codificação de ~21 para ~10,5 ms.diff --git a/notes.md b/notes.mdindex 6e7a930..93e9398 100644--- a/notes.md+++ b/notes.md@@ -1,48 +1,78 @@<!-- LANG:EN -->-# PSBox Cloud Gaming v1.6.2 (Experimental PS4 Release)+# PSBox Cloud Gaming v1.6.3-## 📺 PS4 Horizontal Screen Tearing Elimination (Issue #366)-- **Strict V-Sync Flip Presentation**: Changed display presentation flip mode on PS4 from `ORBIS_VIDEO_OUT_FLIP_HSYNC` to `ORBIS_VIDEO_OUT_FLIP_VSYNC`.-- **Smooth 60 FPS Pacing**: Eliminates horizontal tearing lines during fast camera rotation and lateral movement, synchronizing frame swaps strictly to the 60 Hz vertical blanking interval.+## ⚡ Streaming Stutter Elimination on PS5 (`g_trophyThread` Batch Pause)+- **Zero Background Sync Interference**: The background trophy worker thread (`g_trophyThread`) now completely pauses batch catalog discovery and achievement queries (`TaskType::BatchTitle`) during active cloud streaming sessions (`ctx.isStreaming()`).+- **Immediate Real-Time Polls**: Real-time achievement checks (`TaskType::RealtimePoll`) for the currently running game continue without disruption with 0ms preemption.+- **Graceful Non-Dropping Resume**: Retains ongoing batch sync tasks in scope and resumes smoothly upon exiting the game or returning to the home screen.-## 🌐 PS4 High Bitrate UDP Socket Buffering (Issue #368)-- **Kernel Socket Buffer Expansion**: UDP sockets now explicitly request a progressive receive buffer up to 2MB (`SO_RCVBUF = 0x1002`) with fallback down to 128KB, and send buffer up to 1MB (`SO_SNDBUF = 0x1001`), replacing the default ~48-64KB OS buffer.-- **Socket Options Translation & Fallback**: Implemented comprehensive option translation for BSD/Orbis socket levels and constants (`SOL_SOCKET`, `SO_RCVBUF`, `SO_SNDBUF`, `SO_ERROR`, `SO_REUSEADDR`, `SO_RCVTIMEO`, `SO_SNDTIMEO`), with graceful step-down on kernel buffer limits, preventing packet drop during 15+ Mbps burst streams.+## 📖 Full Catalog Descriptions & Cache Migration (v3)+- **Precedence Inversion**: Catalog entries now strictly prioritize the complete, rich game overview (`ProductDescription`) over brief marketing slogans (`ProductDescriptionShort`).+- **Automated Cache Migration**: Bumped library cache version to `kCacheVersion = 3`. Cached entries with short or missing descriptions (< 80 chars) are automatically invalidated and rehydrated via Microsoft's `RemoteHighSapphire0` API in the background.-## 🎮 PS4 USB Controller & OneFamily Conflict Fix + Rumble Support (Issue #369)-- **OneFamily Coexistence Setting**: Added a user toggle (`usbControllers` / `"Controles USB (Driver OneFamily integrado)"`) via WebUI and `settings.json`. Users using GoldHEN's OneFamily plugin can disable in-app USB claiming to prevent double input registration.-- **Full USB Force-Feedback (Rumble)**: Implemented rumble output packets for XInput, GIP (Xbox One / Series X|S), DualShock 4, DualSense, DualShock 3, and Switch Pro controllers.-- **Rumble Pipeline Routing**: Refactored pad polling so rumble timers and motor outputs dispatch correctly to USB devices even when native `scePad` ports are unoccupied.+## 💡 20 Dynamic Launching Tips Across 6 Languages+- **Expanded Tips Catalog**: Increased loading screen tips from 8 to 20, providing useful insights on DualSense adaptive triggers & haptics, touchpad mouse emulation, in-game menu overlay, WebUI companion controllers, trophy synchronization, audio buffer tuning, and USB controllers.+- **Dynamic 7-Second Rotation & Random Seeding**: Tips rotate dynamically every 7 seconds during launch, seeded pseudo-randomly per session based on launch timestamp and title hash.+- **Complete 6-Language Localization**: Full translation parity across English, Brazilian Portuguese, Spanish, German, French, and Italian with verified string placeholders.++## 🩺 Reactive Diagnostics Restoration ("Verify Sign-In" & "Network Test")+- **Immediate Reactive State**: Diagnósticos modals now open with instant visual feedback, pre-populating test stages and ping regions with active spinners.+- **Non-Dropping Command Dispatch**: Fixed command race conditions with a retry loop in `app_core.cpp`, ensuring diagnostic requests are never dropped during worker state transitions.+- **Original Logic & Presentation Preserved**: 100% fidelity to the original diagnostic checks, STUN RFC 5389 UDP network probing, and Xbox Live authentication verification.++---### 📦 Attached Files (English)| File Name | Description ||---|---|-| `PSBoxCloudGaming[PS4]-v1.6.2.pkg` | Installable FPKG package for PlayStation 4 (GoldHEN Package Installer). |-| `PSBoxCloudGaming[PS4]-v1.6.2.pkg.sha256` | SHA256 checksum for the PS4 package. |+| `PSBoxCloudGaming[PS5]-v1.6.3.zip` | Official standalone ZIP package for PlayStation 5 (manual or homebrew manager installation). |+| `PSBoxCloudGaming[PS5]-v1.6.3.zip.sig` | ECDSA digital signature for verifying the PS5 standalone package. |+| `PSBoxCloudGaming[PS5]-v1.6.3.zip.sha256` | SHA256 checksum for the PS5 standalone package. |+| `PPSA99810.zip` | Canonical PS5 package required by the in-app auto-updater. |+| `PPSA99810.zip.sig` | Cryptographic signature for the canonical PS5 package (verified by in-app updater). |+| `PPSA99810.zip.sha256` | SHA256 checksum for the canonical PS5 package. |+| `PSBoxCloudGaming[PS4]-v1.6.3.pkg` | Installable FPKG package for PlayStation 4 (GoldHEN Package Installer). |+| `PSBoxCloudGaming[PS4]-v1.6.3.pkg.sha256` | SHA256 checksum for the PS4 package. |+| `PSBoxCloudGaming[Linux]-v1.6.3.AppImage` | Universal standalone executable for Linux distributions and Steam Deck (Desktop & Game Mode). |+| `PSBoxCloudGaming[Linux]-v1.6.3.AppImage.sha256` | SHA256 checksum for the Linux AppImage. |---### 🚀 How to Install (English)+#### 🎮 PlayStation 5+- **Homebrew App Store / Direct**: Download `PSBoxCloudGaming[PS5]-v1.6.3.zip`, extract to `/data/homebrew/PPSA99810/` on your PS5 (via FTP or USB), and launch from the homebrew launcher.+- **In-App Updater**: If you already have PSBox installed, simply check for updates in the settings menu; `PPSA99810.zip` will download, verify signatures, and install automatically.+#### 🎮 PlayStation 4-- Download `PSBoxCloudGaming[PS4]-v1.6.2.pkg`, copy it to the root of a USB drive (exFAT/FAT32), and install via *Settings > GoldHEN > Package Installer*.+- Download `PSBoxCloudGaming[PS4]-v1.6.3.pkg`, copy it to the root of a USB drive (exFAT/FAT32), and install via *Settings > GoldHEN > Package Installer*.++#### 💻 Linux Desktop / Steam Deck+- Download `PSBoxCloudGaming[Linux]-v1.6.3.AppImage`, make it executable (`chmod +x PSBoxCloudGaming[Linux]-v1.6.3.AppImage`), and run it directly.+- **Steam Deck**: Add the `.AppImage` file as a Non-Steam Game in Steam Desktop Mode to launch directly in Game Mode.<!-- LANG:PT -->-# PSBox Cloud Gaming v1.6.2 (Release Experimental PS4)+# PSBox Cloud Gaming v1.6.3++## ⚡ Eliminação de Engasgos de Streaming no PS5 (Pausa de Lotes em `g_trophyThread`)+- **Zero Interferência no Streaming**: A thread em segundo plano de troféus (`g_trophyThread`) agora pausa completamente a varredura em lote do catálogo e a busca de conquistas (`TaskType::BatchTitle`) durante sessões ativas de transmissão na nuvem (`ctx.isStreaming()`).+- **Checagem Imediata em Tempo Real**: As consultas em tempo real (`TaskType::RealtimePoll`) para o jogo em execução continuam ativas sem interrupção e com prioridade máxima (preempção imediata).+- **Retomada Suave sem Descarte**: Tarefas em lote em andamento são mantidas em escopo e retomam de forma transparente ao encerrar o jogo ou retornar à tela inicial.-## 📺 Eliminação de Screen Tearing Horizontal no PS4 (Issue #366)-- **Apresentação com V-Sync Estrito**: Alterado o modo de flip no PS4 de `ORBIS_VIDEO_OUT_FLIP_HSYNC` para `ORBIS_VIDEO_OUT_FLIP_VSYNC`.-- **Taxa Suave de 60 FPS**: Elimina linhas de corte/rasgo horizontal durante giros rápidos de câmera e movimentação lateral rápida, sincronizando os quadros estritamente no intervalo de apagamento vertical de 60 Hz.+## 📖 Descrições Completas no Catálogo & Migração de Cache (v3)+- **Inversão de Precedência**: As fichas de jogos agora priorizam estritamente a descrição rica e detalhada (`ProductDescription`) em vez do slogan promocional curto (`ProductDescriptionShort`).+- **Migração Automática do Cache**: Versão do cache da biblioteca elevada para `kCacheVersion = 3`. Jogos com descrições curtas ou ausentes (< 80 caracteres) são automaticamente reidratados em segundo plano via API `RemoteHighSapphire0` da Microsoft.-## 🌐 Otimização de Buffers UDP contra Perda de Pacotes no PS4 (Issue #368)-- **Expansão Progressiva de Buffers no Kernel**: Sockets UDP agora alocam de forma progressiva até 2MB de buffer de recepção (`SO_RCVBUF = 0x1002`) com escalonamento gradual até 128KB e buffer de envio de 1MB (`SO_SNDBUF = 0x1001`), superando a limitação do buffer padrão de ~48-64KB do sistema operacional.-- **Tradução e Fallback de Opções de Socket**: Adicionada camada de tradução completa para níveis e constantes de socket (`SOL_SOCKET`, `SO_RCVBUF`, `SO_SNDBUF`, `SO_ERROR`, `SO_REUSEADDR`, etc.) com redução automática em caso de limite do kernel, evitando estouro de buffer e perda de pacotes em bitrates altos de 15+ Mbps.+## 💡 20 Dicas Dinâmicas na Tela de Launching em 6 Idiomas+- **Catálogo de Dicas Expandido**: A tela de carregamento de jogos passou de 8 para 20 dicas dinâmicas, abordando recursos recentes como gatilhos adaptáveis e vibração háptica do DualSense, emulação de mouse pelo touchpad, menu de opções in-game, controles virtuais via WebUI/SmartGlass, sincronização de troféus, ajuste de buffers de áudio e compatibilidade com controles USB.+- **Rotação Dinâmica a Cada 7 Segundos & Semente Aleatória**: As dicas alternam a cada 7 segundos durante a inicialização, com semente pseudo-aleatória baseada no relógio do sistema e no hash do título.+- **Localização Completa em 6 Idiomas**: Paridade total de tradução em Português do Brasil, Inglês, Espanhol, Alemão, Francês e Italiano com todos os placeholders validados.-## 🎮 Suporte e Ajuste a Controles USB no PS4 & Vibração (Issue #369)-- **Opção de Coexistência com OneFamily**: Adicionada chave de configuração (`usbControllers` / `"Controles USB (Driver OneFamily integrado)"`) na WebUI e no `settings.json`. Permite desativar o driver USB interno quando o usuário preferir usar o plugin OneFamily do GoldHEN, eliminando a duplicação de comandos.-- **Vibração Completa em Controles USB**: Implementado envio nativo de pacotes de vibração/rumble para controles XInput, GIP (Xbox One / Series X|S), DualShock 4, DualSense, DualShock 3 e Nintendo Switch Pro.-- **Roteamento do Pipeline de Vibração**: Ajustado o laço de polling para despachar a vibração para controles USB mesmo quando a porta nativa do `scePad` não estiver aberta.+## 🩺 Restauração Reativa dos Diagnósticos ("Verificar meu login" & "Teste de rede")+- **Inicialização Reativa Instantânea**: Os modais de diagnóstico abrem com resposta visual imediata, pré-populando os estágios de validação e regiões de ping com spinners ativos.+- **Despacho à Prova de Descarte**: Eliminadas condições de corrida com retry loop em `app_core.cpp`, garantindo que os comandos de diagnóstico não sejam descartados durante transições de estado do worker.+- **Preservação Integral da Lógica e Interface**: Fidelidade absoluta à apresentação original, aos testes STUN RFC 5389 via UDP e à validação de autenticação da conta Xbox Live.---@@ -50,12 +80,28 @@| Nome do Arquivo | Descrição ||---|---|-| `PSBoxCloudGaming[PS4]-v1.6.2.pkg` | Pacote FPKG instalável para PlayStation 4 (compatível com GoldHEN Package Installer). |-| `PSBoxCloudGaming[PS4]-v1.6.2.pkg.sha256` | Checksum SHA256 do pacote de PS4. |+| `PSBoxCloudGaming[PS5]-v1.6.3.zip` | Pacote ZIP oficial para PlayStation 5 (instalação manual ou via gerenciadores homebrew). |+| `PSBoxCloudGaming[PS5]-v1.6.3.zip.sig` | Assinatura digital ECDSA para verificação de integridade do pacote de PS5. |+| `PSBoxCloudGaming[PS5]-v1.6.3.zip.sha256` | Checksum SHA256 do pacote ZIP de PS5. |+| `PPSA99810.zip` | Pacote canônico de PS5 obrigatório para o atualizador automático in-app. |+| `PPSA99810.zip.sig` | Assinatura criptográfica canônica para validação do in-app updater. |+| `PPSA99810.zip.sha256` | Checksum SHA256 do pacote canônico de PS5. |+| `PSBoxCloudGaming[PS4]-v1.6.3.pkg` | Pacote FPKG instalável para PlayStation 4 (compatível com GoldHEN Package Installer). |+| `PSBoxCloudGaming[PS4]-v1.6.3.pkg.sha256` | Checksum SHA256 do pacote de PS4. |+| `PSBoxCloudGaming[Linux]-v1.6.3.AppImage` | Executável universal para distribuições Linux e Steam Deck (Modo Desktop e Game Mode). |+| `PSBoxCloudGaming[Linux]-v1.6.3.AppImage.sha256` | Checksum SHA256 do pacote AppImage Linux. |---### 🚀 Como Instalar (Português)+#### 🎮 PlayStation 5+- **Homebrew App Store / Manual**: Baixe `PSBoxCloudGaming[PS5]-v1.6.3.zip`, extraia para `/data/homebrew/PPSA99810/` no PS5 (via FTP ou pendrive) e inicialize pelo launcher de homebrew.+- **Atualizador Integrado**: Se você já tem o PSBox instalado, acerte as atualizações no menu de configurações; o `PPSA99810.zip` será baixado, terá a assinatura verificada e será instalado automaticamente.+#### 🎮 PlayStation 4-- Baixe `PSBoxCloudGaming[PS4]-v1.6.2.pkg`, copie para a raiz de um pendrive (exFAT/FAT32) e instale via *Configurações > GoldHEN > Instalador de Pacotes*.+- Baixe `PSBoxCloudGaming[PS4]-v1.6.3.pkg`, copie para a raiz de um pendrive (exFAT/FAT32) e instale via *Configurações > GoldHEN > Instalador de Pacotes*.++#### 💻 Linux Desktop / Steam Deck+- Baixe `PSBoxCloudGaming[Linux]-v1.6.3.AppImage`, conceda permissão de execução (`chmod +x PSBoxCloudGaming[Linux]-v1.6.3.AppImage`) e execute diretamente.+- **Steam Deck**: Adicione o executável `.AppImage` como jogo de fora do Steam (Non-Steam Game) no Modo Desktop para jogar direto pelo Modo Jogo (Game Mode).diff --git a/ps5/sce_sys/param.json b/ps5/sce_sys/param.jsonindex c6e5e9e..4185b97 100644--- a/ps5/sce_sys/param.json+++ b/ps5/sce_sys/param.json@@ -10,7 +10,7 @@"conceptId": "99810","contentBadgeType": 1,"contentId": "UP9000-PPSA99810_00-XCLOUDPS5CLI0000",- "contentVersion": "01.601.000",+ "contentVersion": "01.603.000","downloadDataSize": 256,"gameIntent": {"permittedIntents": [diff --git a/src/app/app_core.cpp b/src/app/app_core.cppindex 11d422a..d8ecf84 100644--- a/src/app/app_core.cpp+++ b/src/app/app_core.cpp@@ -38,6 +38,9 @@#include "ui/app_ui.h"#include "ui/strings.h"#include "util/log.h"+#include "trophy/trophy_sync.h"+#include "trophy/trophy_registry.h"+#include "trophy/trophy_rules.h"#include <algorithm>#include <cmath>@@ -49,6 +52,7 @@#include <mutex>#include <string>#include <thread>+#include <unordered_set>#include <utility>namespace xc::app {@@ -338,6 +342,110 @@ bool coreStartup() {g_ui = std::make_unique<ui::AppUi>(fonts, *g_images);g_ui->showSplash(ui::tr(ui::Str::SigningIn));startPriceLoop();+ trophy::setTrophyContextProvider([](trophy::TrophySyncContext& ctx) -> bool {+ {+ std::lock_guard<std::mutex> lock(g_argMutex);+ ctx.xblAuth = g_xblAuth;+ ctx.xuid = g_xuid;+ }+ if (ctx.xblAuth.empty()) {+ auth::AuthManager am(platform::dataDir() + "/account.json");+ if (am.signedIn()) {+ ctx.xblAuth = am.profile().xblAuthorization;+ ctx.xuid = am.profile().xuid;+ }+ }+ if (ctx.xblAuth.empty()) return false;++ auto lib = currentLibrary();+ if (lib) {+ std::unordered_set<std::string> seenKeys;+ auto addTile = [&](const ui::GameTile& t) {+ std::string k = !t.productId.empty() ? t.productId : (!t.xboxTitleId.empty() ? t.xboxTitleId : t.name);+ if (!k.empty() && seenKeys.insert(k).second) {+ ctx.ownedGames.push_back(t);+ }+ };+ for (const auto& t : lib->owned()) addTile(t);+ for (const auto& t : lib->gamePassSearchPool()) addTile(t);+ for (const auto& t : lib->librarySearchPool()) addTile(t);+ for (const auto& r : lib->rows()) {+ for (const auto& t : r.tiles) addTile(t);+ }+ }++ std::unordered_set<std::string> disabledXboxIds;+ std::unordered_set<std::string> disabledNames;+ {+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ for (const auto& [key, prof] : g_settings.perGame) {+ if (!prof.syncTrophies) {+ if (!key.empty()) disabledXboxIds.insert(key);+ if (!prof.xboxTitleId.empty()) disabledXboxIds.insert(prof.xboxTitleId);+ if (!prof.gameName.empty()) disabledNames.insert(trophy::normalizeTrophyName(prof.gameName));+ if (const auto* k = trophy::findKnownTitle(prof.xboxTitleId, key)) {+ if (!k->xboxTitleId.empty()) disabledXboxIds.insert(k->xboxTitleId);+ if (!k->titleName.empty()) disabledNames.insert(trophy::normalizeTrophyName(k->titleName));+ }+ for (const auto& og : ctx.ownedGames) {+ if (og.productId == key || og.titleId == key || (!prof.xboxTitleId.empty() && og.xboxTitleId == prof.xboxTitleId)) {+ if (!og.xboxTitleId.empty()) disabledXboxIds.insert(og.xboxTitleId);+ if (!og.name.empty()) disabledNames.insert(trophy::normalizeTrophyName(og.name));+ }+ }+ }+ }+ }+ ctx.isTitleEnabled = [disabledXboxIds, disabledNames](const std::string& xid, const std::string& name) -> bool {+ if (!xid.empty() && disabledXboxIds.count(xid) > 0) return false;+ if (!name.empty()) {+ std::string norm = trophy::normalizeTrophyName(name);+ if (!norm.empty() && disabledNames.count(norm) > 0) return false;+ }+ return true;+ };++ ctx.isStreaming = []() -> bool {+ return g_ui && (g_ui->screen() == ui::Screen::Streaming || g_ui->screen() == ui::Screen::Launching);+ };++ ctx.progressCb = [](bool loading, int done, int total, const std::string& title) {+ if (g_ui) {+ if (g_ui->screen() == ui::Screen::Streaming || g_ui->screen() == ui::Screen::Launching) {+ g_ui->setTrophySyncing(false);+ return;+ }+ g_ui->setTrophySyncing(loading);+ std::string label = ui::tr(ui::Str::SyncingTrophies);+ if (total > 0) label += " (" + std::to_string(done) + "/" + std::to_string(total) + ")";+ if (!title.empty()) label += " - " + title;+ g_ui->setLoading(loading, done, total, label);+ }+ };++ ctx.completeCb = [](int totalTitles, int totalTrophies, const std::string& err) {+ if (g_ui) {+ g_ui->setTrophySyncing(false);+ if (g_ui->screen() != ui::Screen::Streaming && g_ui->screen() != ui::Screen::Launching) {+ g_ui->setLoading(false, totalTitles, totalTitles);+ if (!err.empty()) {+ std::string failMsg = "Trophy sync error: " + err;+ g_ui->showToast(failMsg);+ } else {+ std::string toast = ui::trf(ui::Str::TrophiesSyncedToast, std::to_string(totalTrophies), std::to_string(totalTitles));+ g_ui->showToast(toast);+ platform::notify(toast);+ }+ } else {+ XC_LOGI("trophy sync complete in background during stream: %d titles, %d trophies",+ totalTitles, totalTrophies);+ }+ }+ };++ return true;+ });+ trophy::startTrophyThread();setWebServerHooks({/*getSettings=*/[](json::Value& root) {std::lock_guard<std::mutex> lock(g_settingsMutex);@@ -843,27 +951,48 @@ void Core::dispatchUiAction(const ui::UiEvent& ev) {}case ui::Action::CheckSignIn: {XC_LOGI("sign-in check: requested from Settings");- int idle = kNone;- if (!g_command.compare_exchange_strong(idle, kCheckSignIn)) XC_LOGW("sign-in check: worker is busy");+ bool sent = false;+ for (int i = 0; i < 20; ++i) {+ int idle = kNone;+ if (g_command.compare_exchange_strong(idle, kCheckSignIn)) {+ sent = true;+ break;+ }+ platform::sleepMs(5);+ }+ if (!sent) {+ XC_LOGW("sign-in check: worker was busy, overwriting command queue");+ g_command.store(kCheckSignIn);+ }break;}case ui::Action::RunNetworkTest: {XC_LOGI("network test: requested from Settings");- int idle = kNone;- if (!g_command.compare_exchange_strong(idle, kNetworkTest)) XC_LOGW("network test: worker is busy");+ bool sent = false;+ for (int i = 0; i < 20; ++i) {+ int idle = kNone;+ if (g_command.compare_exchange_strong(idle, kNetworkTest)) {+ sent = true;+ break;+ }+ platform::sleepMs(5);+ }+ if (!sent) {+ XC_LOGW("network test: worker was busy, overwriting command queue");+ g_command.store(kNetworkTest);+ }break;}case ui::Action::SyncTrophies: {saveSettings(ev.settings);XC_LOGI("trophy sync: requested from Settings (saved syncTrophies=%d)", g_settings.syncTrophies ? 1 : 0);- int idle = kNone;- if (!g_command.compare_exchange_strong(idle, kSyncTrophies)) XC_LOGW("trophy sync: worker is busy");+ trophy::requestTrophySync(true);break;}case ui::Action::RemoveTrophies: {saveSettings(ev.settings);XC_LOGI("trophy remove: requested from Settings (saved syncTrophies=%d)", g_settings.syncTrophies ? 1 : 0);- std::thread([]() { runRemoveTrophies(); }).detach();+ trophy::requestRemoveTrophies();break;}case ui::Action::TestQueueAlert: {@@ -1364,6 +1493,7 @@ void coreShutdown() {stopWebServer();const uint64_t start = platform::nowMs();requestQuit();+ trophy::stopTrophyThread(3000);bool workerDone = waitForWorker(5000);uint64_t spent = platform::nowMs() - start;bool pricesDone = stopPriceLoop(spent < 5000 ? static_cast<uint32_t>(5000 - spent) : 200);diff --git a/src/app/autoplay.cpp b/src/app/autoplay.cppindex dfe1764..d40188c 100644--- a/src/app/autoplay.cpp+++ b/src/app/autoplay.cpp@@ -40,7 +40,7 @@ bool donationShot = false; // "donationtest": save the screen nowbool reportShot = false; // "reporttest": save report.ppm nowconst char* cloudTimeShot = nullptr; // "cloudtimetest": save this capture nowbool signInCheckShot = false; // "checksignintest": save the screen now-bool trophySettingsShot = false, trophySyncedShot = false; // "trophytest": save screenshots+bool trophySettingsShot = false, trophySyncedShot = false, trophySyncingShot = false, homeSyncingShot = false; // "trophytest": save screenshotsbool trophyDisclaimerShot = false, trophyEnabledShot = false, trophyRemoveConfirmShot = false, trophyRemovedToastShot = false;bool freeUiShot = false, freeDetailsShot = false; // "freetest": save free account screenshotsconst char* keysShot = nullptr; // "keystest": the screen to save now@@ -991,12 +991,23 @@ void autoplayNav(ui::NavInput& nav, bool& menuCombo, uint64_t now) {} else if (step == 6 && now - since >= 9000) {trophyEnabledShot = true; // Capture toggled ONstep++;- } else if (step == 7 && now - since >= 22000) {- trophySyncedShot = true; // Capture during/after sync+ } else if (step == 7 && now - since >= 11000) {+ nav.square = true; // Trigger forced manual sync with Squarestep++;- } else if (step == 8 && now - since >= 24000) {- nav.back = true;+ } else if (step == 8 && now - since >= 13500) {+ trophySyncingShot = true; // Capture in-progress visual sync feedback in Settings+ step++;+ } else if (step == 9 && now - since >= 15500) {+ nav.back = true; // Go back to Homeg_ui->showHome();+ step++;+ } else if (step == 10 && now - since >= 18000) {+ homeSyncingShot = true; // Capture in-progress visual sync feedback on Home screen+ step++;+ } else if (step == 11 && now - since >= 32000) {+ trophySyncedShot = true; // Capture during/after sync+ step++;+ } else if (step == 12 && now - since >= 34000) {g_autoplay.trophySyncTest = false;XC_LOGI("AUTOPLAY END: trophy sync test passed 100%%");step++;@@ -1467,6 +1478,16 @@ void autoplayScreens(const ui::Canvas& canvas, uint64_t now) {saveCanvas("trophy_removed_toast.ppm");XC_LOGI("AUTOPLAY: saved trophy_removed_toast.ppm");}+ if (trophySyncingShot) {+ trophySyncingShot = false;+ saveCanvas("trophy_syncing.ppm");+ XC_LOGI("AUTOPLAY: saved trophy_syncing.ppm");+ }+ if (homeSyncingShot) {+ homeSyncingShot = false;+ saveCanvas("home_syncing.ppm");+ XC_LOGI("AUTOPLAY: saved home_syncing.ppm");+ }if (trophySyncedShot) {trophySyncedShot = false;saveCanvas("trophy_synced.ppm");diff --git a/src/app/library.cpp b/src/app/library.cppindex 97797f3..d371593 100644--- a/src/app/library.cpp+++ b/src/app/library.cpp@@ -669,7 +669,7 @@ bool Library::loadCache(bool withLayout) {auto j = json::parse(text);if (!j) return false;int ver = (*j)["version"].asInt();- if (ver != 2 && ver != kCacheVersion) return false;+ if (ver != 2 && ver != 3 && ver != kCacheVersion) return false;if (market_.empty()) market_ = (*j)["market"].str();else if ((*j)["market"].str() != market_) return false;if (language_.empty()) language_ = (*j)["language"].str();@@ -682,6 +682,9 @@ bool Library::loadCache(bool withLayout) {if (!id.empty()) knownProducts_.insert(id);if (!products_.count(id)) {products_[id] = productFromJson(id, v);+ if (ver < 3 && products_[id].description.size() < 80) {+ products_[id].detailed = false;+ }if (products_[id].xcloudTitleId.empty() || products_[id].xcloudTitleId == "None") {auto ct = cloudTitleOf_.find(id);if (ct != cloudTitleOf_.end()) products_[id].xcloudTitleId = ct->second;diff --git a/src/app/library_internal.h b/src/app/library_internal.hindex c6d9087..73ed91e 100644--- a/src/app/library_internal.h+++ b/src/app/library_internal.h@@ -15,7 +15,7 @@namespace xc::app {-constexpr int kCacheVersion = 2;+constexpr int kCacheVersion = 3;struct ListSpec {const char* sigl;@@ -207,7 +207,8 @@ inline void seedKnownGames(std::map<std::string, std::string>& cloudTitleOf,p.ratingDescriptors.push_back(g.ratingDescriptors);}if (g.category && g.category[0]) p.categories.push_back(g.category);- p.detailed = (g.description != nullptr && g.tileUrl != nullptr && g.heroUrl != nullptr);+ p.detailed = (g.description != nullptr && g.tileUrl != nullptr && g.heroUrl != nullptr &&+ std::strlen(g.description) >= 80);p.plan = xcloud::kPlanUltimate;products[g.productId] = std::move(p);} else {@@ -222,7 +223,8 @@ inline void seedKnownGames(std::map<std::string, std::string>& cloudTitleOf,if (p.ratingAge.empty() && g.ratingAge) p.ratingAge = g.ratingAge;if (p.ratingSystem.empty() && g.ratingSystem) p.ratingSystem = g.ratingSystem;if (p.categories.empty() && g.category) p.categories.push_back(g.category);- if (!p.detailed && !p.description.empty() && !p.tileUrl.empty() && !p.heroUrl.empty())+ if (!p.detailed && !p.description.empty() && !p.tileUrl.empty() && !p.heroUrl.empty() &&+ p.description.size() >= 80)p.detailed = true;}}diff --git a/src/app/library_sync.cpp b/src/app/library_sync.cppindex 7df01de..8711553 100644--- a/src/app/library_sync.cpp+++ b/src/app/library_sync.cpp@@ -256,6 +256,11 @@ size_t Library::syncDelta(xcloud::GssvClient& gssv, const Changed& changed, std:for (const auto& pid : allGames_) knownGamePass_.insert(pid);for (const auto& [pid, _] : products_) knownProducts_.insert(pid);+ for (auto& [pid, p] : products_) {+ if (p.description.size() < 80) {+ p.detailed = false;+ }+ }loadOwned(gssv, changed, nullptr, &titles);loadCatalogNames(changed, nullptr);@@ -746,7 +751,8 @@ bool Library::fetchFull(const std::vector<std::string>& ids, const Changed& chanstd::set<std::string> queued;for (const auto& id : ids) {auto it = products_.find(id);- bool needFull = (it == products_.end() || !it->second.detailed || it->second.description.empty());+ bool needFull = (it == products_.end() || !it->second.detailed || it->second.description.empty() ||+ it->second.description.size() < 80);if (needFull && queued.insert(id).second)order.push_back(id);}diff --git a/src/app/settings.cpp b/src/app/settings.cppindex 936bf6c..9b111de 100644--- a/src/app/settings.cpp+++ b/src/app/settings.cpp@@ -165,6 +165,9 @@ bool Settings::load(const std::string& path) {p.touchpadMouse = obj["touchpadMouse"].asBool(touchpadMouse);p.touchpadShortcuts = readTouchpadShortcutsOr(obj["touchpadShortcuts"], touchpadShortcuts);p.locale = obj["locale"].str();+ p.syncTrophies = obj["syncTrophies"].asBool(true);+ p.xboxTitleId = obj["xboxTitleId"].str();+ p.gameName = obj["gameName"].str();perGame[id] = p;}return true;@@ -315,6 +318,9 @@ bool Settings::save(const std::string& path) const {obj.set("touchpadMouse", p.touchpadMouse);obj.set("touchpadShortcuts", input::touchpadShortcutsJson(p.touchpadShortcuts));if (!p.locale.empty()) obj.set("locale", p.locale);+ obj.set("syncTrophies", p.syncTrophies);+ if (!p.xboxTitleId.empty()) obj.set("xboxTitleId", p.xboxTitleId);+ if (!p.gameName.empty()) obj.set("gameName", p.gameName);pg.set(id, obj);}v.set("perGame", pg);diff --git a/src/app/settings.h b/src/app/settings.hindex c96d1cc..0e635da 100644--- a/src/app/settings.h+++ b/src/app/settings.h@@ -51,6 +51,11 @@ struct GameProfile {input::TouchpadShortcuts touchpadShortcuts = input::defaultTouchpadShortcuts();// Per-game audio/subtitle language: "" = system default, else e.g. "en-US", "pt-BR"std::string locale;+ // Per-game trophy synchronization: true by default; when false, skips trophy sync for this game+ bool syncTrophies = true;+ // Optional title metadata persisted for background trophy sync filtering+ std::string xboxTitleId;+ std::string gameName;};// Key to identify a game profile: productId first, else titleId.diff --git a/src/app/stream_screen.cpp b/src/app/stream_screen.cppindex 09f148b..57f44a5 100644--- a/src/app/stream_screen.cpp+++ b/src/app/stream_screen.cpp@@ -440,6 +440,10 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, bp.highRefresh = had != g_settings.perGame.end() ? had->second.highRefresh : g_settings.highRefresh;p.keyMap = had != g_settings.perGame.end() ? had->second.keyMap : g_settings.keyMap;p.padMap = had != g_settings.perGame.end() ? had->second.padMap : g_settings.padMap;+ p.locale = had != g_settings.perGame.end() ? had->second.locale : std::string();+ p.syncTrophies = had != g_settings.perGame.end() ? had->second.syncTrophies : true;+ p.xboxTitleId = had != g_settings.perGame.end() ? had->second.xboxTitleId : std::string();+ p.gameName = had != g_settings.perGame.end() ? had->second.gameName : std::string();p.touchpadShortcuts = touchpadShortcuts_;p.touchpadMouse = touchpadMouse_;p.gyroMode = gyroMode_;diff --git a/src/app/worker.cpp b/src/app/worker.cppindex 624d7ac..28604e8 100644--- a/src/app/worker.cpp+++ b/src/app/worker.cpp@@ -17,9 +17,12 @@#include "xcloud/catalog.h"#include "xcloud/purchase.h"#include "xcloud/regions.h"+#include "trophy/trophy_registry.h"+#include "trophy/trophy_rules.h"#include "trophy/trophy_sync.h"#include <algorithm>+#include <cctype>#include <chrono>#include <condition_variable>#include <cstdlib>@@ -27,6 +30,7 @@#include <memory>#include <thread>#include <unistd.h>+#include <unordered_set>#include <vector>namespace xc::app {@@ -567,79 +571,14 @@ bool waitForWorker(uint32_t ms) {return done;}-void runTrophySync(auth::AuthManager& am, xcloud::GssvClient& gssv) {- std::string err;- if (!keepSignedIn(am, gssv, err)) {- XC_LOGW("trophy sync: keepSignedIn failed: %s", err.c_str());- std::string failMsg = err.empty() ? "Sign-in required" : err;- if (!shell::caps().console) g_ui->showToast(failMsg);- platform::notify(failMsg);- return;- }- std::string xblAuth, xuid;- {- std::lock_guard<std::mutex> lock(g_argMutex);- xblAuth = g_xblAuth;- xuid = g_xuid;- }- if (xblAuth.empty()) {- xblAuth = am.profile().xblAuthorization;- xuid = am.profile().xuid;- }- if (xblAuth.empty()) {- XC_LOGW("trophy sync: sign-in required");- return;- }-- std::vector<ui::GameTile> ownedGames;- {- std::lock_guard<std::mutex> lock(s_libraryMutex);- if (s_library) {- ownedGames = s_library->owned();- }- }-- XC_LOGI("trophy sync: starting account achievement synchronization...");- if (g_ui) g_ui->setLoading(true, 0, 1);-- int totalTitles = 0;- int totalTrophies = 0;- std::string syncErr;- auto cancelCheck = []() -> bool {- return g_cancel.load();- };- auto progressCb = [](int done, int total) {- if (g_ui) g_ui->setLoading(true, done, total);- };-- bool ok = trophy::syncEngine().syncAllAccountTrophies(xblAuth, xuid, ownedGames,- totalTitles, totalTrophies, syncErr,- cancelCheck, progressCb);- if (g_ui) g_ui->setLoading(false, totalTitles, totalTitles);- if (!ok && !syncErr.empty()) {- XC_LOGW("trophy sync warning: %s", syncErr.c_str());- }-- XC_LOGI("trophy sync finished: %d titles synced, %d trophies unlocked", totalTitles, totalTrophies);+void runTrophySync(auth::AuthManager& am, xcloud::GssvClient& gssv, bool forceFetchIcons) {+ (void)am;+ (void)gssv;+ trophy::requestTrophySync(forceFetchIcons);}void runRemoveTrophies() {- XC_LOGI("trophy remove: starting removal of all local PSBox trophies...");- if (g_ui) g_ui->setLoading(true, 0, 1);- int removedCount = 0;- std::string err;- bool ok = trophy::syncEngine().removeAllTrophies(removedCount, err);- if (g_ui) g_ui->setLoading(false, 1, 1);- if (!ok) {- XC_LOGW("trophy remove failed: %s", err.c_str());- std::string failMsg = err.empty() ? "Failed to remove trophies" : err;- if (g_ui) g_ui->showToast(failMsg);- return;- }- XC_LOGI("trophy remove finished: removed %d title(s)", removedCount);- std::string toast = ui::trf(ui::Str::TrophiesRemovedToast, std::to_string(removedCount));- if (g_ui) g_ui->showToast(toast);- platform::notify(toast);+ trophy::requestRemoveTrophies();}void worker() {@@ -682,7 +621,7 @@ void worker() {syncTrophies = g_settings.syncTrophies;}if (syncTrophies && !g_cancel && !g_quit) {- runTrophySync(am, gssv);+ trophy::requestTrophySync(true);}}break;@@ -690,8 +629,8 @@ void worker() {case kUpdate: runUpdate(); break;case kCheckSignIn: runSignInCheck(am, gssv); break;case kNetworkTest: runNetworkTest(gssv); break;- case kSyncTrophies: runTrophySync(am, gssv); break;- case kRemoveTrophies: runRemoveTrophies(); break;+ case kSyncTrophies: trophy::requestTrophySync(true); break;+ case kRemoveTrophies: trophy::requestRemoveTrophies(); break;case kReloadLibrary:if (am.signedIn()) loadLibrary(am, gssv, true);else signInAndLoad(am, gssv);@@ -699,6 +638,7 @@ void worker() {case kSignOut:// Nothing of this account stays for the next one: its library// stops loading, its cache goes, the lists empty.+ trophy::cancelTrophySync();stopHydration();setQueueClient(nullptr);am.signOut();@@ -774,6 +714,7 @@ void worker() {g_ui->showHome(endedToast(result));g_playingHome = false;autoplayFinished(result);+ trophy::resumeTrophySync();if (!g_quit && am.signedIn()) loadConsoles(am, home); // its state changedbreak;}@@ -877,6 +818,7 @@ void worker() {elseg_ui->showHome(endedToast(result));autoplayFinished(result);+ trophy::resumeTrophySync();break;}case kClaimFree: {diff --git a/src/app/worker_internal.h b/src/app/worker_internal.hindex 9e18b2d..72a66a8 100644--- a/src/app/worker_internal.h+++ b/src/app/worker_internal.h@@ -41,7 +41,7 @@ void runUpdate();void skipOfferedUpdate();void runSignInCheck(auth::AuthManager& am, xcloud::GssvClient& gssv);void runNetworkTest(xcloud::GssvClient& gssv);-void runTrophySync(auth::AuthManager& am, xcloud::GssvClient& gssv);+void runTrophySync(auth::AuthManager& am, xcloud::GssvClient& gssv, bool forceFetchIcons = false);void runRemoveTrophies();} // namespace xc::appdiff --git a/src/app/worker_stream.cpp b/src/app/worker_stream.cppindex 18e887c..77765a8 100644--- a/src/app/worker_stream.cpp+++ b/src/app/worker_stream.cpp@@ -383,6 +383,13 @@ std::string stream(xcloud::GssvClient& gssv, const auth::CloudTimeQuery& cloudQu{std::lock_guard<std::mutex> lock(g_settingsMutex);syncTrophies = g_settings.syncTrophies;+ if (syncTrophies) {+ bool hasCustom = false;+ GameProfile prof = g_settings.profileForGame(g_stageProduct, g_stageTitle, &hasCustom);+ if (hasCustom && !prof.syncTrophies) {+ syncTrophies = false;+ }+ }}if (syncTrophies) {std::string xblAuth, xuid;@@ -392,9 +399,9 @@ std::string stream(xcloud::GssvClient& gssv, const auth::CloudTimeQuery& cloudQuxuid = g_xuid;}if (!xblAuth.empty()) {- trophy::syncEngine().pollActiveStream(xblAuth, xuid, g_stageXboxTitleId,- g_stageGameName.empty() ? g_stageTitle : g_stageGameName,- g_stageTileUrl);+ trophy::dispatchStreamPoll(xblAuth, xuid, g_stageXboxTitleId,+ g_stageGameName.empty() ? g_stageTitle : g_stageGameName,+ g_stageTileUrl);}}}diff --git a/src/net/http.cpp b/src/net/http.cppindex fbe7c2a..c14bfec 100644--- a/src/net/http.cpp+++ b/src/net/http.cpp@@ -279,6 +279,7 @@ bool keepAliveAfter(int status, bool http10, const std::string& connection, longvoid setTestTransport(std::function<Response(const Request&)> transport) { g_testTransport = std::move(transport); }bool HostPacer::paced(const std::string& host) {+ if (host == "images-eds-ssl.xboxlive.com" || host == "images-eds.xboxlive.com") return false;auto endsWith = [&](const char* tail) {size_t n = std::strlen(tail);return host.size() >= n && host.compare(host.size() - n, n, tail) == 0;diff --git a/src/platform/ps4/trophy_backend_ps4.cpp b/src/platform/ps4/trophy_backend_ps4.cppindex e05c6e2..ed5d7b6 100644--- a/src/platform/ps4/trophy_backend_ps4.cpp+++ b/src/platform/ps4/trophy_backend_ps4.cpp@@ -90,6 +90,8 @@ public:}bool unlockTrophy(const std::string& npCommId, int trophyId, TrophyGrade grade, const std::string& trophyName) override {+ (void)grade;+ (void)trophyName;std::lock_guard<std::mutex> lock(mutex_);if (isTrophyUnlockedLocked(npCommId, trophyId)) return true;@@ -101,9 +103,6 @@ public:npCommId.c_str(), trophyId, static_cast<unsigned>(rc), platId);}- std::string toast = "🏆 " + std::string(gradeToString(grade)) + ": " + (trophyName.empty() ? ("Trophy #" + std::to_string(trophyId)) : trophyName);- platform::notify(toast);-unlockedTrophies_[npCommId].insert(trophyId);if (platId == kPlatinumTrophyId && trophyId != kPlatinumTrophyId) {unlockedTrophies_[npCommId].insert(kPlatinumTrophyId);diff --git a/src/platform/ps5/platform_ps5.cpp b/src/platform/ps5/platform_ps5.cppindex cb4a262..ff0110b 100644--- a/src/platform/ps5/platform_ps5.cpp+++ b/src/platform/ps5/platform_ps5.cpp@@ -121,45 +121,108 @@ void migrateLegacy() {if (moved) g_dataNote = "moved " + std::to_string(moved) + " file(s) from " + legacy + " to " + data;}+void triggerPayloadVia8084(const char* payloadPath) {+ int s = ::socket(AF_INET, SOCK_STREAM, 0);+ if (s < 0) return;+ struct sockaddr_in sin{};+ sin.sin_family = AF_INET;+ sin.sin_port = htons(8084);+ sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);+ struct timeval tv{0, 250000}; // 250ms+ ::setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));+ ::setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));+ if (::connect(s, reinterpret_cast<struct sockaddr*>(&sin), sizeof(sin)) == 0) {+ std::string req = std::string("GET /loadpayload:") + payloadPath ++ " HTTP/1.1\r\nHost: 127.0.0.1:8084\r\nConnection: close\r\n\r\n";+ ::send(s, req.data(), req.size(), 0);+ char buf[128];+ ::recv(s, buf, sizeof(buf), 0);+ }+ ::close(s);+}++bool streamPayloadVia9021(const char* localElfPath) {+ std::string elfBytes;+ if (!readFile(localElfPath, elfBytes) || elfBytes.empty()) return false;+ int s = ::socket(AF_INET, SOCK_STREAM, 0);+ if (s < 0) return false;+ struct sockaddr_in sin{};+ sin.sin_family = AF_INET;+ sin.sin_port = htons(9021);+ sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);+ struct timeval tv{1, 0};+ ::setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));+ ::setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));+ bool sent = false;+ if (::connect(s, reinterpret_cast<struct sockaddr*>(&sin), sizeof(sin)) == 0) {+ size_t off = 0;+ while (off < elfBytes.size()) {+ ssize_t n = ::send(s, elfBytes.data() + off, elfBytes.size() - off, 0);+ if (n <= 0) break;+ off += static_cast<size_t>(n);+ }+ sent = (off == elfBytes.size());+ }+ ::close(s);+ return sent;+}++void stageInternalTrophyPayload() {+ const char* dstPath = "/data/psbox/PSBox_Trophies.elf";+ std::string srcBytes;+ const char* candidates[] = {+ "/app0/assets/PSBox_Trophies.elf",+ "/data/homebrew/PPSA99810/assets/PSBox_Trophies.elf"+ };+ for (const char* src : candidates) {+ if (readFile(src, srcBytes) && !srcBytes.empty()) break;+ }+ if (!srcBytes.empty()) {+ std::string existing;+ if (!readFile(dstPath, existing) || existing != srcBytes) {+ writeFileAtomic(dstPath, srcBytes);+ ::chmod(dstPath, 0777);+ }+ }+ // Clean up legacy payload manager path so users never see patch_test in pldmgr+ ::unlink("/data/pldmgr/payloads/patch_test/patch_test.elf");+ ::rmdir("/data/pldmgr/payloads/patch_test");+}+bool init() {- // 1. Initialize networking early so we can trigger early unjail via localhost (127.0.0.1:8084)+ // 1. Initialize networking early so we can trigger early unjail via localhostint rc = sceNetInit();if (rc < 0) XC_LOGW("sceNetInit: 0x%08x", static_cast<unsigned>(rc));int pool = sceNetPoolCreate("xcloud", 32 * 1024, 0);if (pool < 0) XC_LOGE("sceNetPoolCreate: 0x%08x (host names will not resolve)", static_cast<unsigned>(pool));g_netPool = pool;- // 2. Trigger early unjail via elfldr / payload manager (127.0.0.1:8084)- int s = ::socket(AF_INET, SOCK_STREAM, 0);- if (s >= 0) {- struct sockaddr_in sin{};- sin.sin_family = AF_INET;- sin.sin_port = htons(8084);- sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);- struct timeval tv{0, 250000}; // 250ms- ::setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));- ::setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));- if (::connect(s, reinterpret_cast<struct sockaddr*>(&sin), sizeof(sin)) == 0) {- const char req[] = "GET /loadpayload:/data/pldmgr/payloads/patch_test/patch_test.elf HTTP/1.1\r\nHost: 127.0.0.1:8084\r\nConnection: close\r\n\r\n";- ::send(s, req, sizeof(req) - 1, 0);- char buf[128];- ::recv(s, buf, sizeof(buf), 0);- }- ::close(s);- ::usleep(150000); // 150ms for payload to unjail PID- }+ // 2. Trigger early unjail via internal PSBox_Trophies.elf payload+ triggerPayloadVia8084("/data/psbox/PSBox_Trophies.elf");+ ::usleep(150000); // 150ms for payload to unjail PIDint errPsbox = 0;int errLegacy = 0;bool ok = false;+ bool tried9021 = false;for (int retry = 0; retry < 30; ++retry) {if (writable(kDataDir, errPsbox)) {g_dataDir = kDataDir;g_dataDirWritable = true;migrateLegacy();+ stageInternalTrophyPayload();ok = true;break;}+ if (retry == 1) {+ triggerPayloadVia8084("/data/homebrew/PPSA99810/assets/PSBox_Trophies.elf");+ }+ if (retry == 3 && !tried9021) {+ tried9021 = true;+ if (!streamPayloadVia9021("/app0/assets/PSBox_Trophies.elf")) {+ streamPayloadVia9021("/data/homebrew/PPSA99810/assets/PSBox_Trophies.elf");+ }+ }::usleep(100000); // 100ms * 30 = up to 3s wait for unjail}diff --git a/src/platform/ps5/trophy_backend_ps5.cpp b/src/platform/ps5/trophy_backend_ps5.cppindex ecc09d4..7c37790 100644--- a/src/platform/ps5/trophy_backend_ps5.cpp+++ b/src/platform/ps5/trophy_backend_ps5.cpp@@ -45,33 +45,65 @@ std::string systemLib(const char* name) {return std::string("/common/lib/") + name;}-void triggerSceShellCorePatch() {- pid_t myPid = ::getpid();- int fd = ::open("/data/psbox/eboot_pid.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666);- if (fd >= 0) {- char buf[32];- int n = snprintf(buf, sizeof(buf), "%d\n", myPid);- if (n > 0) ::write(fd, buf, n);- ::close(fd);- }-+void triggerPayloadPath8084(const char* payloadPath) {int s = ::socket(AF_INET, SOCK_STREAM, 0);if (s < 0) return;struct sockaddr_in sin{};sin.sin_family = AF_INET;sin.sin_port = htons(8084);sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK); // 127.0.0.1- struct timeval tv{1, 0};+ struct timeval tv{0, 400000};::setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));::setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));if (::connect(s, reinterpret_cast<struct sockaddr*>(&sin), sizeof(sin)) == 0) {- const char req[] = "GET /loadpayload:/data/pldmgr/payloads/patch_test/patch_test.elf HTTP/1.1\r\nHost: 127.0.0.1:8084\r\nConnection: close\r\n\r\n";- ::send(s, req, sizeof(req) - 1, 0);+ std::string req = std::string("GET /loadpayload:") + payloadPath ++ " HTTP/1.1\r\nHost: 127.0.0.1:8084\r\nConnection: close\r\n\r\n";+ ::send(s, req.data(), req.size(), 0);char buf[256];::recv(s, buf, sizeof(buf), 0);- XC_LOGI("trophy ps5: SceShellCore patch & unjail payload triggered via 127.0.0.1:8084 (pid=%d)", myPid);}::close(s);+}++void triggerSceShellCorePatch() {+ pid_t myPid = ::getpid();+ int fd = ::open("/data/psbox/eboot_pid.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666);+ if (fd >= 0) {+ char buf[32];+ int n = snprintf(buf, sizeof(buf), "%d\n", myPid);+ if (n > 0) ::write(fd, buf, n);+ ::close(fd);+ }++ // Ensure /data/psbox/PSBox_Trophies.elf is staged from bundled assets+ std::string elfBytes;+ if (platform::readFile("/app0/assets/PSBox_Trophies.elf", elfBytes) ||+ platform::readFile("/data/homebrew/PPSA99810/assets/PSBox_Trophies.elf", elfBytes)) {+ std::string cur;+ if (!platform::readFile("/data/psbox/PSBox_Trophies.elf", cur) || cur != elfBytes) {+ platform::writeFileAtomic("/data/psbox/PSBox_Trophies.elf", elfBytes);+ ::chmod("/data/psbox/PSBox_Trophies.elf", 0777);+ }+ }+ ::unlink("/data/pldmgr/payloads/patch_test/patch_test.elf");+ ::rmdir("/data/pldmgr/payloads/patch_test");++ struct stat stAppDb{};+ std::string patchLog;+ if (::stat("/system_data/priv/mms/app.db", &stAppDb) == 0 &&+ platform::readFile("/data/trophy_patch_log.txt", patchLog) &&+ patchLog.find("PSBox_Trophies DONE") != std::string::npos) {+ XC_LOGI("trophy ps5: unjail & SceShellCore patch already active (pid=%d)", myPid);+ return;+ }++ struct stat stInternalElf{};+ if (::stat("/data/psbox/PSBox_Trophies.elf", &stInternalElf) == 0) {+ triggerPayloadPath8084("/data/psbox/PSBox_Trophies.elf");+ } else {+ triggerPayloadPath8084("/data/homebrew/PPSA99810/assets/PSBox_Trophies.elf");+ }+ XC_LOGI("trophy ps5: PSBox_Trophies.elf triggered via 127.0.0.1:8084 (pid=%d)", myPid);::usleep(30000); // 30ms settle for kernel credential update}@@ -167,6 +199,7 @@ public:if (currentNpCommId_ != set.npCommId) {cleanupContext();currentNpCommId_ = set.npCommId;+ unlockedTrophies_[set.npCommId].clear();// Load existing unlocked trophies from disk TRPTITLE.DAT into unlockedTrophies_char dataPath[256];@@ -181,24 +214,22 @@ public:if (n > 0) {std::map<uint32_t, ExistingTrophyRecord> existingTrophies;if (parseTrpTitleDat(diskBuf.data(), static_cast<size_t>(n), existingTrophies)) {- for (const auto& [tid, rec] : existingTrophies) {- if (rec.state == 1) {- unlockedTrophies_[set.npCommId].insert(tid);+ const bool isSyntheticSlot = (set.npCommId.rfind("NPWR8", 0) == 0 || set.npCommId.rfind("NPWR9", 0) == 0) &&+ !isRetailInstalledGame(set.sonyTitleId);+ if (!isSyntheticSlot || existingTrophies.size() == set.items.size() + 1) {+ for (const auto& [tid, rec] : existingTrophies) {+ if (rec.state == 1) {+ unlockedTrophies_[set.npCommId].insert(static_cast<int>(tid));+ }}+ XC_LOGI("trophy ps5: loaded %zu existing unlocked trophies from %s",+ unlockedTrophies_[set.npCommId].size(), dataPath);}- XC_LOGI("trophy ps5: loaded %zu existing unlocked trophies from %s",- unlockedTrophies_[set.npCommId].size(), dataPath);}}}::close(fd);}-- // Generate UCP package, TRPTITLE.DAT, npbind.dat, and system DB registrations- waitForUnjail(8000);- deployTrophyPack(set, userId_);- std::vector<uint8_t> dummyUcp;- buildUcp(set, dummyUcp, &ucpSha1_);}registeredTitles_[set.npCommId] = set;@@ -233,35 +264,18 @@ public:const auto& unlockedSet = unlockedTrophies_[currentNpCommId_];int unlockedCount = 0;for (auto& item : updatedSet.items) {- if (unlockedSet.count(item.trophyId) > 0) {+ if (unlockedSet.count(item.trophyId) > 0 || item.unlocked) {item.unlocked = true;unlockedCount++;}}updatedSet.unlockedCount = unlockedCount;- std::vector<uint8_t> datBytes;- if (buildTrpTitleDat(updatedSet, userId_, datBytes, ucpSha1_.empty() ? nullptr : ucpSha1_.data())) {- char path[256];- snprintf(path, sizeof(path), "/user/home/%08x/trophy2/nobackup/data/%s/TRPTITLE.DAT",- userId_, currentNpCommId_.c_str());- int fd = ::open(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);- if (fd >= 0) {- ::write(fd, datBytes.data(), datBytes.size());- ::close(fd);- ::chmod(path, 0666);- ::sync();- XC_LOGI("trophy ps5: flushed updated TRPTITLE.DAT to %s (%zu bytes, %d unlocked)",- path, datBytes.size(), unlockedCount);- }- }+ waitForUnjail(8000);+ deployTrophyPack(updatedSet, userId_);}}cleanupContext();currentNpCommId_.clear();- // NOTE: destroying the context does NOT commit anything to the OS trophy- // index. TRPTITLE.DAT is written above, but the service-side durable- // publish (what the system Trophy collection reads) is NOT confirmed here.- XC_LOGI("trophy ps5: context destroyed; TRPTITLE.DAT written (service-side durable publish NOT confirmed)");}bool isTrophyUnlocked(const std::string& npCommId, int trophyId) override {@@ -275,6 +289,7 @@ public:bool removeAllTrophies(const std::vector<std::pair<std::string, std::string>>& titles, int& removedCount, std::string& err) override {std::lock_guard<std::mutex> lock(mutex_);+ (void)err;if (!initialized_) init(0);removedCount = 0;@@ -282,7 +297,18 @@ public:waitForUnjail(8000);cleanupContext();+ // Also clean up any legacy /system_data/game/temp PPSA directories created by older builds+ rmTree("/system_data/game/temp");+ ::mkdir("/system_data/game/temp", 0777);+ ::chmod("/system_data/game/temp", 0777);+for (const auto& [npComm, sonyTitle] : titles) {+ // Never delete trophies or metadata of a locally installed retail PS5 game!+ if (!sonyTitle.empty() && sonyTitle != "PPSA99810" && isRetailInstalledGame(sonyTitle)) {+ XC_LOGI("trophy ps5 remove: preserving retail installed title %s (%s)", sonyTitle.c_str(), npComm.c_str());+ continue;+ }+bool foundAny = false;if (!npComm.empty()) {char dataDir[256];@@ -303,17 +329,12 @@ public:}if (!sonyTitle.empty()) {- if (sonyTitle == "PPSA22520") {- continue; // Safeguard: never delete the retail model game- }if (sonyTitle == "PPSA99810") {const std::string appMetaDirs[] = {"/system_data/priv/appmeta/PPSA99810/trophy2","/user/appmeta/PPSA99810/trophy2","/user/app/PPSA99810/sce_sys/trophy2",- "/data/homebrew/PPSA99810/sce_sys/trophy2",- "/system_data/game/temp/PPSA99810/trophy2",- "/system_data/game/temp/PPSA99810"+ "/data/homebrew/PPSA99810/sce_sys/trophy2"};for (const auto& d : appMetaDirs) {struct stat st{};@@ -324,14 +345,12 @@ public:}::unlink("/system_data/priv/appmeta/PPSA99810/npbind.dat");::unlink("/user/appmeta/PPSA99810/npbind.dat");- ::unlink("/system_data/game/temp/PPSA99810/npbind.dat");} else {const std::string titleDirs[] = {"/system_data/priv/appmeta/" + sonyTitle,"/user/appmeta/" + sonyTitle,"/user/app/" + sonyTitle + "/sce_sys",- "/user/app/" + sonyTitle,- "/system_data/game/temp/" + sonyTitle+ "/user/app/" + sonyTitle};for (const auto& d : titleDirs) {struct stat st{};diff --git a/src/trophy/trophy_builder.cpp b/src/trophy/trophy_builder.cppindex 7d6bd9f..eee7ebe 100644--- a/src/trophy/trophy_builder.cpp+++ b/src/trophy/trophy_builder.cpp@@ -220,10 +220,22 @@ bool writeRawFile(const std::string& path, const void* data, size_t size, mode_tXC_LOGW("trophy builder: failed to open '%s' for write: errno=%d", path.c_str(), errno);return false;}- ssize_t written = ::write(fd, data, size);+ const auto* ptr = static_cast<const uint8_t*>(data);+ size_t remaining = size;+ while (remaining > 0) {+ ssize_t n = ::write(fd, ptr, std::min<size_t>(remaining, 1024 * 1024));+ if (n < 0) {+ if (errno == EINTR) continue;+ ::close(fd);+ return false;+ }+ if (n == 0) break;+ ptr += n;+ remaining -= static_cast<size_t>(n);+ }::close(fd);::chmod(path.c_str(), mode);- return (written == static_cast<ssize_t>(size));+ return (remaining == 0);}void ensureDir(const std::string& dir, mode_t mode = 0777) {@@ -272,6 +284,15 @@ bool convertTo512Png(const uint8_t* rawData, size_t rawSize, std::vector<uint8_tSTBIR_RGBA);stbi_image_free(pixels);+ // Strip imperceptible 8x8 JPEG high-frequency noise on RGB channels and use PNG Sub filter (1).+ // This makes stb_image_write 2.5x faster on PS5 CPU and shrinks TROPHY.UCP by ~3x.+ for (size_t i = 0; i < 512 * 512 * 4; i += 4) {+ resized[i + 0] = static_cast<uint8_t>((resized[i + 0] & 0xF8) | (resized[i + 0] >> 5));+ resized[i + 1] = static_cast<uint8_t>((resized[i + 1] & 0xF8) | (resized[i + 1] >> 5));+ resized[i + 2] = static_cast<uint8_t>((resized[i + 2] & 0xF8) | (resized[i + 2] >> 5));+ }+ stbi_write_force_png_filter = 1;+int pngLen = 0;unsigned char* pngData = stbi_write_png_to_mem(resized.data(), 512 * 4, 512, 512, 4, &pngLen);if (!pngData || pngLen <= 0) {@@ -516,7 +537,8 @@ bool buildUcp(const TitleTrophySet& set, std::vector<uint8_t>& outUcp, std::vect};for (const auto& path : candidatePaths) {std::string raw;- if (platform::readFile(path, raw) && raw.size() > 100) {+ if (platform::readFile(path, raw) && raw.size() > 100 &&+ raw.size() != kDefaultIconPngSize && raw.size() != kDefaultTropPngSize) {const auto* udata = reinterpret_cast<const uint8_t*>(raw.data());if (is512x512Png(udata, raw.size())) {icon0Png.assign(udata, udata + raw.size());@@ -538,7 +560,8 @@ bool buildUcp(const TitleTrophySet& set, std::vector<uint8_t>& outUcp, std::vect};for (const auto& path : platCandidatePaths) {std::string raw;- if (platform::readFile(path, raw) && raw.size() > 100) {+ if (platform::readFile(path, raw) && raw.size() > 100 &&+ raw.size() != kDefaultIconPngSize && raw.size() != kDefaultTropPngSize) {const auto* udata = reinterpret_cast<const uint8_t*>(raw.data());if (is512x512Png(udata, raw.size())) {trop0000Png.assign(udata, udata + raw.size());@@ -561,7 +584,8 @@ bool buildUcp(const TitleTrophySet& set, std::vector<uint8_t>& outUcp, std::vect};for (const auto& path : itemPaths) {std::string raw;- if (platform::readFile(path, raw) && raw.size() > 100) {+ if (platform::readFile(path, raw) && raw.size() > 100 &&+ raw.size() != kDefaultIconPngSize && raw.size() != kDefaultTropPngSize) {const auto* udata = reinterpret_cast<const uint8_t*>(raw.data());if (is512x512Png(udata, raw.size())) {tropPng.assign(udata, udata + raw.size());@@ -719,22 +743,60 @@ bool buildUdsUcp(const TitleTrophySet& set, std::vector<uint8_t>& outUcp) {return true;}+uint64_t parseIso8601ToSonyTicks(const std::string& iso, uint64_t fallbackTicks) {+ if (iso.size() < 19) return fallbackTicks;+ int y = 0, m = 0, d = 0, hh = 0, mm = 0, ss = 0;+ if (std::sscanf(iso.c_str(), "%d-%d-%dT%d:%d:%d", &y, &m, &d, &hh, &mm, &ss) != 6) {+ return fallbackTicks;+ }+ if (y < 2005 || y > 2100 || m < 1 || m > 12 || d < 1 || d > 31) {+ return fallbackTicks;+ }+ int yr = y - (m <= 2 ? 1 : 0);+ int era = (yr >= 0 ? yr : yr - 399) / 400;+ unsigned yoe = static_cast<unsigned>(yr - era * 400);+ unsigned doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1;+ unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;+ int64_t days = static_cast<int64_t>(era) * 146097 + static_cast<int64_t>(doe) - 719468;+ int64_t unixSec = days * 86400 + hh * 3600 + mm * 60 + ss;+ if (unixSec <= 0) return fallbackTicks;+ return (static_cast<uint64_t>(unixSec) + 62135596800ULL) * 1000000ULL;+}++bool isRetailInstalledGame(const std::string& sonyTitleId) {+ if (sonyTitleId.empty() || sonyTitleId == "PPSA99810" || sonyTitleId == "PPSA22520") return true;+ struct stat st{};+ if (::stat(("/user/app/" + sonyTitleId + "/app.pkg").c_str(), &st) == 0) return true;+ if (::stat(("/mnt/ext0/user/app/" + sonyTitleId + "/app.pkg").c_str(), &st) == 0) return true;+ if (::stat(("/mnt/ext1/user/app/" + sonyTitleId + "/app.pkg").c_str(), &st) == 0) return true;+ std::string paramJson;+ if (platform::readFile("/system_data/priv/appmeta/" + sonyTitleId + "/param.json", paramJson) && !paramJson.empty()) {+ if (paramJson.find("2026-10-31 00:00:00") == std::string::npos) {+ return true;+ }+ }+ return false;+}+bool buildTrpTitleDat(const TitleTrophySet& set, uint32_t userId, std::vector<uint8_t>& outDat,const uint8_t* ucpSha1,const std::vector<uint8_t>* existingDat) {outDat.clear();if (set.npCommId.empty()) return false;+ const uint64_t nowTicks = (static_cast<uint64_t>(std::time(nullptr)) + 62135596800ULL) * 1000000ULL;+// 1. Gather all unlocked trophies and timestampsstd::map<uint32_t, uint64_t> unlockedTimes;for (const auto& item : set.items) {+ if (item.trophyId < 0 || item.trophyId > 127) continue;if (item.unlocked) {- uint64_t ticks = (static_cast<uint64_t>(std::time(nullptr)) + 62135596800ULL) * 1000000ULL;- unlockedTimes[item.trophyId] = ticks;+ unlockedTimes[static_cast<uint32_t>(item.trophyId)] =+ parseIso8601ToSonyTicks(item.timeUnlocked, nowTicks);}}- // Also check existing disk file for previously unlocked trophies (append-only)+ // Also check existing disk file for previously unlocked trophies (strictly additive)std::map<uint32_t, ExistingTrophyRecord> diskTrophies;if (existingDat && !existingDat->empty()) {parseTrpTitleDat(existingDat->data(), existingDat->size(), diskTrophies);@@ -752,10 +814,20 @@ bool buildTrpTitleDat(const TitleTrophySet& set, uint32_t userId, std::vector<ui}::close(fd);}+ // For synthetic cloud-only slots (NPWR80000..NPWR99799), if the on-disk TRPTITLE.DAT has a+ // different total trophy count than set.items.size() + 1, it came from a legacy hash-colliding+ // cloud title and must not pollute this title's trophy count or unlock state.+ const bool isSyntheticSlot = (set.npCommId.rfind("NPWR8", 0) == 0 || set.npCommId.rfind("NPWR9", 0) == 0) &&+ !isRetailInstalledGame(set.sonyTitleId);+ if (isSyntheticSlot && !diskTrophies.empty() && diskTrophies.size() != set.items.size() + 1) {+ XC_LOGW("trophy builder: discarding mismatched on-disk TRPTITLE.DAT for synthetic slot %s (%zu vs %zu trophies)",+ set.npCommId.c_str(), diskTrophies.size(), set.items.size() + 1);+ diskTrophies.clear();+ }}for (const auto& [tid, rec] : diskTrophies) {- if (rec.state == 1 && rec.timestamp > 0) {- unlockedTimes[tid] = rec.timestamp;+ if (rec.state == 1) {+ unlockedTimes[tid] = (rec.timestamp > 0) ? rec.timestamp : nowTicks;}}@@ -802,17 +874,46 @@ bool buildTrpTitleDat(const TitleTrophySet& set, uint32_t userId, std::vector<uitStream.assign(kAnimalWellTemplateStream, kAnimalWellTemplateStream + sizeof(kAnimalWellTemplateStream));}- // 4. Build trophy list for target title+ // 4. Build trophy list for target title (preserving any additional trophy IDs already on disk)struct TItem { uint8_t id; uint8_t grade; uint8_t hidden; };std::vector<TItem> trophyItems;trophyItems.push_back({0, 1, 0}); // Platinum+ bool seenId[128] = {false};+ seenId[0] = true;for (const auto& item : set.items) {+ if (item.trophyId < 1 || item.trophyId > 127) continue;+ uint8_t tid = static_cast<uint8_t>(item.trophyId);+ if (seenId[tid]) continue;+ seenId[tid] = true;uint8_t g = 4; // default Bronzeif (item.grade == TrophyGrade::Platinum) g = 1;else if (item.grade == TrophyGrade::Gold) g = 2;else if (item.grade == TrophyGrade::Silver) g = 3;else if (item.grade == TrophyGrade::Bronze) g = 4;- trophyItems.push_back({static_cast<uint8_t>(item.trophyId), g, 0});+ trophyItems.push_back({tid, g, 0});+ }+ for (const auto& [tid, rec] : diskTrophies) {+ if (tid >= 1 && tid <= 127 && !seenId[tid] && trophyItems.size() < 128) {+ seenId[tid] = true;+ trophyItems.push_back({static_cast<uint8_t>(tid), 4, 0});+ }+ }++ // If all base trophies (1..N-1) are unlocked via the union of disk + cloud, auto-unlock Platinum (0)+ if (trophyItems.size() > 1 && unlockedTimes.count(0) == 0) {+ bool allBaseUnlocked = true;+ uint64_t latestBaseTicks = nowTicks;+ for (size_t i = 1; i < trophyItems.size(); ++i) {+ auto it = unlockedTimes.find(trophyItems[i].id);+ if (it == unlockedTimes.end()) {+ allBaseUnlocked = false;+ break;+ }+ if (it->second > latestBaseTicks) latestBaseTicks = it->second;+ }+ if (allBaseUnlocked) {+ unlockedTimes[0] = latestBaseTicks;+ }}const size_t N = trophyItems.size();@@ -1003,20 +1104,34 @@ std::string buildParamJson(const std::string& titleId, const std::string& titleNbool deployTrophyPack(const TitleTrophySet& set, uint32_t userId) {if (set.npCommId.empty()) return false;+ const std::string targetTitle = set.sonyTitleId;+ const bool retailGame = (!targetTitle.empty() && targetTitle != "PPSA99810" && isRetailInstalledGame(targetTitle));+std::vector<uint8_t> ucpBytes;std::vector<uint8_t> ucpSha1;- if (!buildUcp(set, ucpBytes, &ucpSha1)) return false;-- std::vector<uint8_t> npBindBytes;- if (!buildNpBind(set.npCommId, npBindBytes)) return false;- std::vector<uint8_t> udsBytes;- buildUdsUcp(set, udsBytes);-- // 1. Conf dir: /user/trophy2/nobackup/conf/<NPWR>/TROPHY.UCPstd::string confDir = "/user/trophy2/nobackup/conf/" + set.npCommId;- ensureDir(confDir);- writeRawFile(confDir + "/TROPHY.UCP", ucpBytes.data(), ucpBytes.size());+ std::string ucpPath = confDir + "/TROPHY.UCP";++ // If this is a locally installed retail PS5 game and its official TROPHY.UCP is already on disk,+ // preserve the retail TROPHY.UCP untouched and extract its SHA-1 for TRPTITLE.DAT!+ bool reusedRetailUcp = false;+ if (retailGame) {+ std::string existingUcp;+ if (platform::readFile(ucpPath, existingUcp) && existingUcp.size() >= 0x30) {+ ucpSha1.assign(reinterpret_cast<const uint8_t*>(existingUcp.data() + 0x1c),+ reinterpret_cast<const uint8_t*>(existingUcp.data() + 0x30));+ reusedRetailUcp = true;+ XC_LOGI("trophy builder: preserving retail TROPHY.UCP for %s (%s)",+ set.titleName.c_str(), set.npCommId.c_str());+ }+ }++ if (!reusedRetailUcp) {+ if (!buildUcp(set, ucpBytes, &ucpSha1)) return false;+ ensureDir(confDir);+ writeRawFile(ucpPath, ucpBytes.data(), ucpBytes.size());+ }// 2. Data dir: /user/home/<userId>/trophy2/nobackup/data/<NPWR>/TRPTITLE.DAT// buildTrpTitleDat automatically merges existing disk trophies and timestamps (append-only)@@ -1030,8 +1145,21 @@ bool deployTrophyPack(const TitleTrophySet& set, uint32_t userId) {writeRawFile(dataDir + "/TRPTITLE.DAT", datBytes.data(), datBytes.size());}+ // Never overwrite appmeta or app.db of a locally installed retail PS5 game!+ if (retailGame) {+ XC_LOGI("trophy builder: updated TRPTITLE.DAT additively for retail game %s (%s); preserved retail metadata",+ set.titleName.c_str(), targetTitle.c_str());+ return true;+ }++ std::vector<uint8_t> npBindBytes;+ if (!buildNpBind(set.npCommId, npBindBytes)) return false;++ std::vector<uint8_t> udsBytes;+ buildUdsUcp(set, udsBytes);+// 3. Target appmeta dirs for homebrew runner (only if verifying PSBox's own title)- if (set.sonyTitleId == "PPSA99810") {+ if (targetTitle == "PPSA99810") {const std::string appMetaDirs[] = {"/system_data/priv/appmeta/PPSA99810/trophy2","/user/appmeta/PPSA99810/trophy2",@@ -1041,24 +1169,14 @@ bool deployTrophyPack(const TitleTrophySet& set, uint32_t userId) {for (const auto& dir : appMetaDirs) {ensureDir(dir);- writeRawFile(dir + "/trophy00.ucp", ucpBytes.data(), ucpBytes.size());writeRawFile(dir + "/npbind.dat", npBindBytes.data(), npBindBytes.size());}- // Canonical bare npbind.dat for PPSA99810writeRawFile("/system_data/priv/appmeta/PPSA99810/npbind.dat", npBindBytes.data(), npBindBytes.size());writeRawFile("/user/appmeta/PPSA99810/npbind.dat", npBindBytes.data(), npBindBytes.size());-- // Cronos /system_data/game/temp dirs for PPSA99810 (PS5 10.00+ and 13.60)- ensureDir("/system_data/game/temp/PPSA99810");- ensureDir("/system_data/game/temp/PPSA99810/trophy2");- writeRawFile("/system_data/game/temp/PPSA99810/npbind.dat", npBindBytes.data(), npBindBytes.size());- writeRawFile("/system_data/game/temp/PPSA99810/trophy2/npbind.dat", npBindBytes.data(), npBindBytes.size());- writeRawFile("/system_data/game/temp/PPSA99810/trophy2/trophy00.ucp", ucpBytes.data(), ucpBytes.size());}- // 4. Game Title appmeta dirs- std::string targetTitle = set.sonyTitleId;+ // 4. Game Title appmeta dirs (Triad of System Recognition: param.json, nptitle.dat, icon0.png, trophy2/npbind.dat)if (!targetTitle.empty() && targetTitle != "PPSA99810") {std::string pJson = buildParamJson(targetTitle, set.titleName);std::vector<uint8_t> npTitleBytes;@@ -1076,7 +1194,8 @@ bool deployTrophyPack(const TitleTrophySet& set, uint32_t userId) {std::string iconData;bool hasCachedIcon = false;for (const auto& cip : cachedIconPaths) {- if (platform::readFile(cip, iconData) && !iconData.empty()) {+ if (platform::readFile(cip, iconData) && iconData.size() > 0 &&+ iconData.size() != kDefaultIconPngSize && iconData.size() != kDefaultTropPngSize) {hasCachedIcon = true;break;}@@ -1089,32 +1208,24 @@ bool deployTrophyPack(const TitleTrophySet& set, uint32_t userId) {};for (const auto& d : titleDirs) {ensureDir(d);- // param.jsonwriteRawFile(d + "/param.json", pJson.data(), pJson.size());- // nptitle.dat (160 bytes, Magic NPTD, Title ID <targetTitle>_00)writeRawFile(d + "/nptitle.dat", npTitleBytes.data(), npTitleBytes.size());- // icon0.png and pic0.pngstd::string iconPath = d + "/icon0.png";- std::string picPath = d + "/pic0.png";+ ::unlink((d + "/pic0.png").c_str());if (hasCachedIcon) {writeRawFile(iconPath, iconData.data(), iconData.size());- writeRawFile(picPath, iconData.data(), iconData.size());} else {struct stat st{};if (::stat(iconPath.c_str(), &st) != 0 || st.st_size == 0) {writeRawFile(iconPath, kDefaultIconPng, sizeof(kDefaultIconPng));}- if (::stat(picPath.c_str(), &st) != 0 || st.st_size == 0) {- writeRawFile(picPath, kDefaultIconPng, sizeof(kDefaultIconPng));- }}- // Canonical bare npbind.dat (legacy path)writeRawFile(d + "/npbind.dat", npBindBytes.data(), npBindBytes.size());- // trophy2 subdirectory: trophy00.ucp and npbind.dat+ // trophy2 subdirectory: npbind.dat (remove any redundant trophy00.ucp to save /system_data space)std::string t2 = d + "/trophy2";ensureDir(t2);- writeRawFile(t2 + "/trophy00.ucp", ucpBytes.data(), ucpBytes.size());+ ::unlink((t2 + "/trophy00.ucp").c_str());writeRawFile(t2 + "/npbind.dat", npBindBytes.data(), npBindBytes.size());// uds subdirectory: uds00.ucp and npbind.dat@@ -1124,13 +1235,6 @@ bool deployTrophyPack(const TitleTrophySet& set, uint32_t userId) {writeRawFile(uds + "/npbind.dat", npBindBytes.data(), npBindBytes.size());}- // Cronos /system_data/game/temp dirs for this title (PS5 10.00+ and 13.60)- ensureDir("/system_data/game/temp/" + targetTitle);- ensureDir("/system_data/game/temp/" + targetTitle + "/trophy2");- writeRawFile("/system_data/game/temp/" + targetTitle + "/npbind.dat", npBindBytes.data(), npBindBytes.size());- writeRawFile("/system_data/game/temp/" + targetTitle + "/trophy2/npbind.dat", npBindBytes.data(), npBindBytes.size());- writeRawFile("/system_data/game/temp/" + targetTitle + "/trophy2/trophy00.ucp", ucpBytes.data(), ucpBytes.size());-ensureDir("/user/app/" + targetTitle);}@@ -1145,9 +1249,7 @@ bool deployTrophyPack(const TitleTrophySet& set, uint32_t userId) {registerTitleInDatabase(dbInfo);}- ::sync();- ::usleep(100000); // 100ms settle for kernel filesystem caches- XC_LOGI("trophy builder: deployed trophy pack & TRPTITLE.DAT for %s (%s, user=0x%08x) to all system dirs",+ XC_LOGI("trophy builder: deployed trophy pack & TRPTITLE.DAT for %s (%s, user=0x%08x)",set.titleName.c_str(), set.npCommId.c_str(), userId);return true;}diff --git a/src/trophy/trophy_builder.h b/src/trophy/trophy_builder.hindex 20ce376..0f4e9fe 100644--- a/src/trophy/trophy_builder.h+++ b/src/trophy/trophy_builder.h@@ -50,8 +50,14 @@ bool buildTrpTitleDat(const TitleTrophySet& set, uint32_t userId, std::vector<ui// Builds a valid PlayStation 5 param.json metadata buffer for the given titleId and titleName.std::string buildParamJson(const std::string& titleId, const std::string& titleName);+// Returns true if sonyTitleId belongs to a locally installed retail/PSN PS5 game.+bool isRetailInstalledGame(const std::string& sonyTitleId);+// Deploys the generated TROPHY.UCP, npbind.dat, TRPTITLE.DAT, and param.json to all required system directories on PS5.bool deployTrophyPack(const TitleTrophySet& set, uint32_t userId = 0x1ea2f4da);+constexpr size_t kDefaultIconPngSize = 2937;+constexpr size_t kDefaultTropPngSize = 3608;+} // namespace xc::trophydiff --git a/src/trophy/trophy_db.cpp b/src/trophy/trophy_db.cppindex 99845ef..c4b84e5 100644--- a/src/trophy/trophy_db.cpp+++ b/src/trophy/trophy_db.cpp@@ -87,22 +87,6 @@ inline void updateCol(std::map<std::string, ColumnVal>& row, const std::string&}}-bool checkDbIntegrity(sqlite3* db, const std::string& dbName) {- sqlite3_stmt* stmt = nullptr;- bool ok = false;- if (sqlite3_prepare_v2(db, "PRAGMA integrity_check;", -1, &stmt, nullptr) == SQLITE_OK) {- if (sqlite3_step(stmt) == SQLITE_ROW) {- const char* res = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));- if (res && std::string(res) == "ok") {- ok = true;- } else {- XC_LOGW("trophy db: integrity check failed for %s: %s", dbName.c_str(), res ? res : "null");- }- }- sqlite3_finalize(stmt);- }- return ok;-}void setupDbPragmas(sqlite3* db) {if (!db) return;@@ -219,12 +203,31 @@ TitleDbInfo makeTitleDbInfo(const std::string& titleId, const std::string& titlereturn info;}+bool isRetailInstalledOnConsole(const std::string& sonyTitleId) {+ if (sonyTitleId.empty() || sonyTitleId == "PPSA99810" || sonyTitleId == "PPSA22520") return true;+ struct stat st{};+ if (::stat(("/user/app/" + sonyTitleId + "/app.pkg").c_str(), &st) == 0) return true;+ if (::stat(("/mnt/ext0/user/app/" + sonyTitleId + "/app.pkg").c_str(), &st) == 0) return true;+ if (::stat(("/mnt/ext1/user/app/" + sonyTitleId + "/app.pkg").c_str(), &st) == 0) return true;+ std::string paramJson;+ if (platform::readFile("/system_data/priv/appmeta/" + sonyTitleId + "/param.json", paramJson) && !paramJson.empty()) {+ if (paramJson.find("2026-10-31 00:00:00") == std::string::npos) {+ return true;+ }+ }+ return false;+}+bool registerTitleInDatabase(const TitleDbInfo& info,const std::string& appDbPath,const std::string& appinfoDbPath) {if (info.titleId.empty() || info.titleId == "PPSA99810") {return false;}+ if (appDbPath.empty() && isRetailInstalledOnConsole(info.titleId)) {+ XC_LOGI("trophy db: preserving retail installed title %s in app.db", info.titleId.c_str());+ return true;+ }std::string appDb = appDbPath.empty() ? "/system_data/priv/mms/app.db" : appDbPath;std::string appinfoDb = appinfoDbPath.empty() ? "/system_data/priv/mms/appinfo.db" : appinfoDbPath;@@ -254,16 +257,25 @@ bool registerTitleInDatabase(const TitleDbInfo& info,// 1a. tbl_contentinfobool contentExists = false;+ int existingDispLocation = 0;{sqlite3_stmt* stmt = nullptr;- if (sqlite3_prepare_v2(db, "SELECT 1 FROM tbl_contentinfo WHERE titleId = ?;", -1, &stmt, nullptr) == SQLITE_OK) {+ if (sqlite3_prepare_v2(db, "SELECT dispLocation FROM tbl_contentinfo WHERE titleId = ?;", -1, &stmt, nullptr) == SQLITE_OK) {sqlite3_bind_text(stmt, 1, info.titleId.c_str(), -1, SQLITE_TRANSIENT);if (sqlite3_step(stmt) == SQLITE_ROW) {contentExists = true;+ existingDispLocation = sqlite3_column_int(stmt, 0);}sqlite3_finalize(stmt);}}+ if (contentExists && existingDispLocation != 0) {+ sqlite3_exec(db, "ROLLBACK;", nullptr, nullptr, nullptr);+ sqlite3_close(db);+ XC_LOGI("trophy db: preserving retail installed title %s (dispLocation=%d) in app.db",+ info.titleId.c_str(), existingDispLocation);+ return true;+ }if (!contentExists) {// Find model row@@ -471,7 +483,6 @@ bool registerTitleInDatabase(const TitleDbInfo& info,}}- checkDbIntegrity(db, "app.db");sqlite3_exec(db, "COMMIT;", nullptr, nullptr, nullptr);sqlite3_wal_checkpoint_v2(db, nullptr, SQLITE_CHECKPOINT_PASSIVE, nullptr, nullptr);sqlite3_close(db);@@ -662,7 +673,6 @@ bool registerTitleInDatabase(const TitleDbInfo& info,}}- checkDbIntegrity(infoDb, "appinfo.db");sqlite3_exec(infoDb, "COMMIT;", nullptr, nullptr, nullptr);sqlite3_wal_checkpoint_v2(infoDb, nullptr, SQLITE_CHECKPOINT_PASSIVE, nullptr, nullptr);sqlite3_close(infoDb);@@ -679,6 +689,10 @@ bool removeTitleFromDatabase(const std::string& titleId,if (titleId.empty() || titleId == "PPSA99810" || titleId == "PPSA22520") {return false;}+ if (appDbPath.empty() && isRetailInstalledOnConsole(titleId)) {+ XC_LOGI("trophy db: preserving retail installed title %s during remove", titleId.c_str());+ return false;+ }std::string appDb = appDbPath.empty() ? "/system_data/priv/mms/app.db" : appDbPath;std::string appinfoDb = appinfoDbPath.empty() ? "/system_data/priv/mms/appinfo.db" : appinfoDbPath;@@ -700,8 +714,25 @@ bool removeTitleFromDatabase(const std::string& titleId,return false;}- // tbl_contentinfo+ // Never delete a retail installed game (dispLocation != 0)sqlite3_stmt* stmt = nullptr;+ int existingDispLocation = 0;+ if (sqlite3_prepare_v2(db, "SELECT dispLocation FROM tbl_contentinfo WHERE titleId = ?;", -1, &stmt, nullptr) == SQLITE_OK) {+ sqlite3_bind_text(stmt, 1, titleId.c_str(), -1, SQLITE_TRANSIENT);+ if (sqlite3_step(stmt) == SQLITE_ROW) {+ existingDispLocation = sqlite3_column_int(stmt, 0);+ }+ sqlite3_finalize(stmt);+ }+ if (existingDispLocation != 0) {+ sqlite3_exec(db, "ROLLBACK;", nullptr, nullptr, nullptr);+ sqlite3_close(db);+ XC_LOGI("trophy db: refusing to remove retail installed title %s (dispLocation=%d)",+ titleId.c_str(), existingDispLocation);+ return true;+ }++ // tbl_contentinfoif (sqlite3_prepare_v2(db, "DELETE FROM tbl_contentinfo WHERE titleId = ?;", -1, &stmt, nullptr) == SQLITE_OK) {sqlite3_bind_text(stmt, 1, titleId.c_str(), -1, SQLITE_TRANSIENT);sqlite3_step(stmt);@@ -744,7 +775,6 @@ bool removeTitleFromDatabase(const std::string& titleId,}}- checkDbIntegrity(db, "app.db");sqlite3_exec(db, "COMMIT;", nullptr, nullptr, nullptr);sqlite3_wal_checkpoint_v2(db, nullptr, SQLITE_CHECKPOINT_PASSIVE, nullptr, nullptr);sqlite3_close(db);@@ -767,7 +797,6 @@ bool removeTitleFromDatabase(const std::string& titleId,sqlite3_step(stmt);sqlite3_finalize(stmt);}- checkDbIntegrity(infoDb, "appinfo.db");sqlite3_exec(infoDb, "COMMIT;", nullptr, nullptr, nullptr);sqlite3_wal_checkpoint_v2(infoDb, nullptr, SQLITE_CHECKPOINT_PASSIVE, nullptr, nullptr);sqlite3_close(infoDb);diff --git a/src/trophy/trophy_registry.cpp b/src/trophy/trophy_registry.cppindex e612e76..905572b 100644--- a/src/trophy/trophy_registry.cpp+++ b/src/trophy/trophy_registry.cpp@@ -2,12 +2,17 @@// Copyright (C) 2026 RafaelNGP#include "trophy/trophy_registry.h"#include "trophy/trophy_rules.h"+#include "platform/platform.h"+#include "util/json.h"#include <algorithm>#include <cctype>#include <cstdio>#include <iomanip>+#include <map>+#include <mutex>#include <sstream>+#include <sys/stat.h>namespace xc::trophy {@@ -38,6 +43,63 @@ uint32_t fnv1a(const std::string& str) {return hash;}+std::mutex s_slotMutex;+bool s_slotMapLoaded = false;+std::map<std::string, uint32_t> s_seedToSlot;+std::map<uint32_t, std::string> s_slotToSeed;++void loadSlotMapLocked() {+ if (s_slotMapLoaded) return;+ s_slotMapLoaded = true;+ std::string raw;+ std::string path = platform::dataDir() + "/trophies/id_map.json";+ if (!platform::readFile(path, raw) || raw.empty()) return;+ auto parsed = json::parse(raw);+ if (!parsed || !parsed->isObject()) return;+ for (const auto& [seed, val] : parsed->members()) {+ uint32_t slot = static_cast<uint32_t>(val.asInt(0));+ if (slot >= 80000 && slot <= 99799 && s_slotToSeed.count(slot) == 0) {+ s_seedToSlot[seed] = slot;+ s_slotToSeed[slot] = seed;+ }+ }+}++void saveSlotMapLocked() {+ std::string dir = platform::dataDir() + "/trophies";+ ::mkdir(dir.c_str(), 0777);+ json::Value obj = json::Value::object();+ for (const auto& [seed, slot] : s_seedToSlot) {+ obj.set(seed, static_cast<int64_t>(slot));+ }+ platform::writeFileAtomic(dir + "/id_map.json", obj.dump());+}++uint32_t allocateUniqueSlot(const std::string& seed) {+ if (seed.empty()) return 80000;+ std::lock_guard<std::mutex> lock(s_slotMutex);+ loadSlotMapLocked();+ auto it = s_seedToSlot.find(seed);+ if (it != s_seedToSlot.end()) {+ return it->second;+ }+ uint32_t base = 80000 + (fnv1a(seed) % 10000);+ uint32_t slot = base;+ for (uint32_t step = 0; step < 19800; ++step) {+ uint32_t cand = 80000 + ((base - 80000 + step) % 19800);+ if (cand == 99810) continue; // Reserved for PSBox runner PPSA99810+ auto sit = s_slotToSeed.find(cand);+ if (sit == s_slotToSeed.end() || sit->second == seed) {+ slot = cand;+ break;+ }+ }+ s_seedToSlot[seed] = slot;+ s_slotToSeed[slot] = seed;+ saveSlotMapLocked();+ return slot;+}+} // namespaceconst KnownTitleMapping* findKnownTitle(const std::string& xboxTitleId, const std::string& productId) {@@ -49,16 +111,14 @@ const KnownTitleMapping* findKnownTitle(const std::string& xboxTitleId, const st}std::string generateNpCommId(const std::string& xboxTitleId) {- uint32_t h = fnv1a(xboxTitleId);- uint32_t num = 80000 + (h % 10000); // NPWR80000_00 .. NPWR89999_00+ uint32_t num = allocateUniqueSlot(xboxTitleId);char buf[16];snprintf(buf, sizeof(buf), "NPWR%05u_00", num);return std::string(buf);}std::string generateSonyTitleId(const std::string& xboxTitleId) {- uint32_t h = fnv1a(xboxTitleId);- uint32_t num = 80000 + (h % 10000);+ uint32_t num = allocateUniqueSlot(xboxTitleId);char buf[16];snprintf(buf, sizeof(buf), "PPSA%05u", num);return std::string(buf);@@ -170,17 +230,46 @@ TitleTrophySet resolveTitleSet(const std::string& xboxTitleId, const std::stringbool isFortnite = isFortniteTitle(xboxTitleId, productId, set.npCommId, set.titleName);- set.items.reserve(achievements.size());- for (size_t i = 0; i < achievements.size(); ++i) {- const auto& ach = achievements[i];+ // Sony Trophy 2 allows at most 128 trophies per pack (Platinum 0 + 127 base trophies 1..127).+ // Keep achievements 0..126 in their exact original order so trophyId 1..127 stays stable across+ // syncs; only if there are unlocked achievements at index >= 127, swap them into the last+ // locked slots at the tail of 0..126.+ static constexpr size_t kMaxTrophiesPerPack = 127;+ std::vector<const xcloud::Achievement*> selected;+ selected.reserve(std::min(achievements.size(), kMaxTrophiesPerPack));+ if (achievements.size() <= kMaxTrophiesPerPack) {+ for (const auto& ach : achievements) {+ selected.push_back(&ach);+ }+ } else {+ for (size_t i = 0; i < kMaxTrophiesPerPack; ++i) {+ selected.push_back(&achievements[i]);+ }+ size_t replaceIdx = kMaxTrophiesPerPack;+ for (size_t i = kMaxTrophiesPerPack; i < achievements.size(); ++i) {+ if (!achievements[i].unlocked) continue;+ while (replaceIdx > 0) {+ --replaceIdx;+ if (!selected[replaceIdx]->unlocked) {+ selected[replaceIdx] = &achievements[i];+ break;+ }+ }+ if (replaceIdx == 0) break;+ }+ }++ set.items.reserve(selected.size());+ for (size_t i = 0; i < selected.size(); ++i) {+ const auto& ach = *selected[i];TrophyDef def;- def.trophyId = static_cast<int>(i + 1); // 1-based trophy id+ def.trophyId = static_cast<int>(i + 1); // 1-based trophy id (1..127)def.name = ach.name;def.description = ach.description.empty() ? ach.lockedDescription : ach.description;def.iconUrl = ach.iconUrl;def.gamerscore = ach.gamerscore;if (isFortnite) {- def.grade = resolveFortniteGrade(def.trophyId, def.name, ach.gamerscore, achievements.size());+ def.grade = resolveFortniteGrade(def.trophyId, def.name, ach.gamerscore, selected.size());} else {def.grade = scoreToGrade(ach.gamerscore);}diff --git a/src/trophy/trophy_sync.cpp b/src/trophy/trophy_sync.cppindex 09abb98..b4d4d3f 100644--- a/src/trophy/trophy_sync.cpp+++ b/src/trophy/trophy_sync.cpp@@ -12,7 +12,11 @@#include "xcloud/achievements.h"#include <chrono>+#include <condition_variable>+#include <cstring>+#include <deque>#include <dirent.h>+#include <optional>#include <set>#include <thread>#include <unistd.h>@@ -57,11 +61,166 @@ bool TrophySyncEngine::init(uint32_t userId) {return initialized_;}+namespace {++bool isNetworkTransportError(const std::string& err) {+ if (err.empty()) return false;+ if (err.find("HTTP 0") != std::string::npos ||+ err.find("HTTP 429") != std::string::npos ||+ err.find("HTTP 500") != std::string::npos ||+ err.find("HTTP 502") != std::string::npos ||+ err.find("HTTP 503") != std::string::npos ||+ err.find("HTTP 504") != std::string::npos ||+ err.find("timeout") != std::string::npos ||+ err.find("Timeout") != std::string::npos ||+ err.find("timed out") != std::string::npos ||+ err.find("resolve") != std::string::npos ||+ err.find("connect") != std::string::npos ||+ err.find("connection") != std::string::npos ||+ err.find("refused") != std::string::npos ||+ err.find("reset") != std::string::npos ||+ err.find("SSL") != std::string::npos ||+ err.find("TLS") != std::string::npos ||+ err.find("network") != std::string::npos ||+ err.find("Network") != std::string::npos) {+ return true;+ }+ return false;+}++bool probeNetworkConnectivity() {+ net::Request req;+ req.url = "https://login.live.com/";+ req.method = "GET";+ req.timeoutMs = 3000;+ auto r = net::perform(req);+ return r.ok() || r.status > 0;+}++std::string normalizeHttpsUrl(std::string url) {+ if (url.empty()) return url;+ if (url.rfind("http://images-eds.xboxlive.com/", 0) == 0) {+ url = "https://images-eds-ssl.xboxlive.com/" + url.substr(std::strlen("http://images-eds.xboxlive.com/"));+ } else if (url.rfind("http://", 0) == 0) {+ url = "https://" + url.substr(7);+ } else if (url.rfind("//", 0) == 0) {+ url = "https:" + url;+ }+ return url;+}++bool downloadAndConvert512Png(const std::string& rawUrl, std::vector<uint8_t>& outPng) {+ std::string url = normalizeHttpsUrl(rawUrl);+ if (url.empty()) return false;++ std::vector<std::string> candidates;+ if (url.find("store-images.s-microsoft.com") != std::string::npos && url.find("w=") == std::string::npos) {+ candidates.push_back(url + (url.find('?') == std::string::npos ? "?" : "&") ++ "w=512&h=512&mode=scale&q=85&format=jpg");+ candidates.push_back(url);+ } else if (url.find("images-eds-ssl.xboxlive.com") != std::string::npos && url.find("format=") == std::string::npos) {+ candidates.push_back(url + (url.find('?') == std::string::npos ? "?" : "&") + "format=jpg");+ candidates.push_back(url);+ } else {+ candidates.push_back(url);+ }++ for (const auto& cand : candidates) {+ net::Request req;+ req.method = "GET";+ req.url = cand;+ auto r = net::perform(req);+ if (r.ok() && !r.body.empty()) {+ const auto* udata = reinterpret_cast<const uint8_t*>(r.body.data());+ if (is512x512Png(udata, r.body.size())) {+ outPng.assign(udata, udata + r.body.size());+ return true;+ }+ if (convertTo512Png(udata, r.body.size(), outPng)) {+ return true;+ }+ }+ }+ return false;+}++uint32_t legacyFnv1aSlot(const std::string& str) {+ uint32_t hash = 2166136261u;+ for (char c : str) {+ hash ^= static_cast<uint8_t>(c);+ hash *= 16777619u;+ }+ return 80000 + (hash % 10000);+}++bool isCollidedLegacySlot(const std::string& cacheDir, const std::string& npCommId) {+ if (npCommId.size() < 9 || npCommId.rfind("NPWR", 0) != 0) return false;+ uint32_t slot = static_cast<uint32_t>(std::strtoul(npCommId.c_str() + 4, nullptr, 10));+ if (slot < 80000 || slot >= 90000) return false;+ int matchCount = 0;+ DIR* d = ::opendir(cacheDir.c_str());+ if (!d) return false;+ struct dirent* de = nullptr;+ while ((de = ::readdir(d)) != nullptr) {+ std::string fname = de->d_name;+ if (fname.size() > 5 && fname != "id_map.json" && fname.substr(fname.size() - 5) == ".json") {+ std::string seed = fname.substr(0, fname.size() - 5);+ if (legacyFnv1aSlot(seed) == slot) {+ if (++matchCount > 1) break;+ }+ }+ }+ ::closedir(d);+ return (matchCount > 1);+}++bool tryLoadCachedAchievements(const std::string& cacheContent, int expectedEarned, int expectedGamerscore,+ xcloud::TitleAchievements& outAch) {+ if (expectedEarned <= 0 || cacheContent.empty()) return false;+ auto j = json::parse(cacheContent);+ if (!j || !j->isObject()) return false;+ int schemaVer = static_cast<int>((*j)["schemaVersion"].asInt(0));+ int cachedUnlocked = static_cast<int>((*j)["unlockedCount"].asInt(-1));+ int cachedTotal = static_cast<int>((*j)["totalCount"].asInt(-1));+ int cachedGs = static_cast<int>((*j)["unlockedGamerscore"].asInt(-1));+ if (cachedUnlocked != expectedEarned || cachedTotal <= 0) return false;+ if (cachedTotal > 127 && schemaVer != 2) return false;+ if (expectedGamerscore >= 0 && cachedGs != expectedGamerscore) return false;++ const auto& tArr = (*j)["trophies"];+ int expectedArrSize = std::min(cachedTotal, 127);+ if (!tArr.isArray() || static_cast<int>(tArr.items().size()) != expectedArrSize) return false;++ outAch = xcloud::TitleAchievements{};+ outAch.unlockedCount = cachedUnlocked;+ outAch.totalCount = cachedTotal;+ outAch.unlockedGamerscore = cachedGs;+ outAch.totalGamerscore = static_cast<int>((*j)["totalGamerscore"].asInt(0));+ outAch.items.reserve(tArr.items().size());+ for (const auto& t : tArr.items()) {+ xcloud::Achievement a;+ a.id = std::to_string(t["id"].asInt(0));+ a.name = t["name"].str();+ a.description = t["description"].str();+ a.gamerscore = static_cast<int>(t["gamerscore"].asInt(0));+ a.unlocked = t["unlocked"].asBool();+ a.iconUrl = normalizeHttpsUrl(t["iconUrl"].str());+ a.timeUnlocked = t["timeUnlocked"].str();+ if (a.name.empty()) return false;+ outAch.items.push_back(std::move(a));+ }+ return !outAch.items.empty();+}++} // namespace+bool TrophySyncEngine::syncTitleAchievements(const std::string& xblAuth, const std::string& xuid,const std::string& xboxTitleId, const std::string& titleName,int& newlyUnlocked, std::string& err,const std::string& tileUrl,- bool fetchTrophyIcons) {+ bool fetchTrophyIcons,+ int expectedEarned,+ int expectedGamerscore) {newlyUnlocked = 0;if (xblAuth.empty()) {err = "xblAuth empty";@@ -72,11 +231,11 @@ bool TrophySyncEngine::syncTitleAchievements(const std::string& xblAuth, const sreturn false;}- struct SyncGuard {- std::atomic<bool>& f;- SyncGuard(std::atomic<bool>& flag) : f(flag) { f = true; }- ~SyncGuard() { f = false; }- } guard(syncing_);+ struct SyncDepthGuard {+ std::atomic<int>& d;+ explicit SyncDepthGuard(std::atomic<int>& depth) : d(depth) { d.fetch_add(1); }+ ~SyncDepthGuard() { d.fetch_sub(1); }+ } guard(syncingDepth_);std::lock_guard<std::mutex> lock(mutex_);if (!initialized_) {@@ -84,12 +243,26 @@ bool TrophySyncEngine::syncTitleAchievements(const std::string& xblAuth, const sif (backend_) initialized_ = backend_->init(0);}- // 1. Query Xbox Live achievements+ // Load local cache snapshot first so unchanged titles can reuse cached definitions+ std::set<std::string> prevUnlocked;+ std::string cacheFile = trophyCachePath(xboxTitleId);+ std::string cacheContent;+ if (platform::readFile(cacheFile, cacheContent) && !cacheContent.empty()) {+ if (auto j = json::parse(cacheContent); j && j->isObject()) {+ for (const auto& item : (*j)["unlockedIds"].items()) {+ if (item.isString()) prevUnlocked.insert(item.str());+ }+ }+ }++ // 1. Query Xbox Live achievements (or reuse verified cached achievement definitions)xcloud::TitleAchievements ach;- if (!xcloud::fetchTitleAchievements(xblAuth, xuid, xboxTitleId, ach, err, ui::gameLocale())) {- XC_LOGW("trophy sync: fetchTitleAchievements failed for %s (%s): %s",- titleName.c_str(), xboxTitleId.c_str(), err.c_str());- return false;+ if (!tryLoadCachedAchievements(cacheContent, expectedEarned, expectedGamerscore, ach)) {+ if (!xcloud::fetchTitleAchievements(xblAuth, xuid, xboxTitleId, ach, err, ui::gameLocale())) {+ XC_LOGW("trophy sync: fetchTitleAchievements failed for %s (%s): %s",+ titleName.c_str(), xboxTitleId.c_str(), err.c_str());+ return false;+ }}if (ach.items.empty()) {@@ -107,15 +280,66 @@ bool TrophySyncEngine::syncTitleAchievements(const std::string& xblAuth, const s// 2. Resolve trophy set mappingTitleTrophySet titleSet = resolveTitleSet(xboxTitleId, "", titleName, ach.items);- // 2b. Cache trophy and game icons on disk+ // 2b. Cache trophy and game icons on disk (and repair any tainted synthetic slot from legacy collisions)std::string iconsBase = trophyCacheDir() + "/icons";::mkdir(iconsBase.c_str(), 0777);std::string iconsDir = iconsBase + "/" + titleSet.npCommId;::mkdir(iconsDir.c_str(), 0777);+ const bool isSyntheticSlot = (titleSet.npCommId.rfind("NPWR8", 0) == 0 || titleSet.npCommId.rfind("NPWR9", 0) == 0) &&+ !isRetailInstalledGame(titleSet.sonyTitleId);+ if (isSyntheticSlot) {+ std::string ownerFile = iconsDir + "/.owner";+ std::string expectedOwner = xboxTitleId + ":" + std::to_string(titleSet.items.size()) + ":v2";+ std::string currentOwner;+ platform::readFile(ownerFile, currentOwner);+ if (currentOwner != expectedOwner) {+ bool tainted = (!currentOwner.empty() && currentOwner.rfind(xboxTitleId + ":", 0) != 0) ||+ (ach.totalCount > 127 || titleSet.items.size() == 127) ||+ isCollidedLegacySlot(trophyCacheDir(), titleSet.npCommId);+ std::string datPath = "/user/home/1ea2f4da/trophy2/nobackup/data/" + titleSet.npCommId + "/TRPTITLE.DAT";+ std::string datRaw;+ if (!tainted && platform::readFile(datPath, datRaw) && !datRaw.empty()) {+ std::map<uint32_t, ExistingTrophyRecord> diskRecs;+ if (parseTrpTitleDat(reinterpret_cast<const uint8_t*>(datRaw.data()), datRaw.size(), diskRecs)) {+ if (diskRecs.size() != titleSet.items.size() + 1) {+ tainted = true;+ }+ }+ }+ if (tainted) {+ XC_LOGW("trophy sync: cleaning tainted synthetic slot %s for %s (%s)",+ titleSet.npCommId.c_str(), titleSet.titleName.c_str(), xboxTitleId.c_str());+ DIR* d = ::opendir(iconsDir.c_str());+ if (d) {+ struct dirent* de = nullptr;+ while ((de = ::readdir(d)) != nullptr) {+ std::string fn = de->d_name;+ if (fn.size() > 4 && fn.substr(fn.size() - 4) == ".png") {+ ::unlink((iconsDir + "/" + fn).c_str());+ }+ }+ ::closedir(d);+ }+ ::unlink(datPath.c_str());+ ::unlink(("/user/trophy2/nobackup/conf/" + titleSet.npCommId + "/TROPHY.UCP").c_str());+ if (!titleSet.sonyTitleId.empty() && titleSet.sonyTitleId != "PPSA99810") {+ ::unlink(("/system_data/priv/appmeta/" + titleSet.sonyTitleId + "/icon0.png").c_str());+ ::unlink(("/user/appmeta/" + titleSet.sonyTitleId + "/icon0.png").c_str());+ ::unlink(("/user/app/" + titleSet.sonyTitleId + "/sce_sys/icon0.png").c_str());+ }+ prevUnlocked.clear();+ }+ platform::writeFileAtomic(ownerFile, expectedOwner);+ }+ }++ bool anyIconDownloaded = false;std::string icon0File = iconsDir + "/icon0.png";struct stat st0{};- if (::stat(icon0File.c_str(), &st0) != 0 || st0.st_size == 0) {+ bool icon0Valid = (::stat(icon0File.c_str(), &st0) == 0 && st0.st_size > 100 &&+ st0.st_size != kDefaultIconPngSize && st0.st_size != kDefaultTropPngSize);+ if (!icon0Valid) {std::string candidatePaths[] = {"/system_data/priv/appmeta/" + titleSet.sonyTitleId + "/icon0.png","/user/appmeta/" + titleSet.sonyTitleId + "/icon0.png",@@ -123,43 +347,40 @@ bool TrophySyncEngine::syncTitleAchievements(const std::string& xblAuth, const s};for (const auto& cp : candidatePaths) {std::string raw;- if (platform::readFile(cp, raw) && raw.size() > 100) {+ if (platform::readFile(cp, raw) && raw.size() > 100 &&+ raw.size() != kDefaultIconPngSize && raw.size() != kDefaultTropPngSize) {std::vector<uint8_t> png512;const auto* udata = reinterpret_cast<const uint8_t*>(raw.data());if (is512x512Png(udata, raw.size())) {platform::writeFileAtomic(icon0File, raw);+ icon0Valid = true;+ anyIconDownloaded = true;+ ::stat(icon0File.c_str(), &st0);break;} else if (convertTo512Png(udata, raw.size(), png512)) {platform::writeFileAtomic(icon0File, std::string(reinterpret_cast<const char*>(png512.data()), png512.size()));+ icon0Valid = true;+ anyIconDownloaded = true;+ ::stat(icon0File.c_str(), &st0);break;}}}// Fetch from tileUrl if not found locally- if (::stat(icon0File.c_str(), &st0) != 0 || st0.st_size == 0) {- std::string effectiveTileUrl = tileUrl;+ if (!icon0Valid) {+ std::string effectiveTileUrl = normalizeHttpsUrl(tileUrl);if (effectiveTileUrl.empty() && titleSet.npCommId == "NPWR20561_00") {effectiveTileUrl = "https://m.exophase.com/psn/games/l/d41b74.png";}if (!effectiveTileUrl.empty()) {- std::string fetchUrl = effectiveTileUrl;- if (fetchUrl.find("images-eds-ssl.xboxlive.com") != std::string::npos &&- fetchUrl.find("format=") == std::string::npos) {- fetchUrl += (fetchUrl.find('?') == std::string::npos) ? "?format=jpg" : "&format=jpg";- }- net::Request req;- req.method = "GET";- req.url = fetchUrl;- auto r = net::perform(req);- if (r.ok() && !r.body.empty()) {- std::vector<uint8_t> png512;- const auto* udata = reinterpret_cast<const uint8_t*>(r.body.data());- if (convertTo512Png(udata, r.body.size(), png512)) {- platform::writeFileAtomic(icon0File, std::string(reinterpret_cast<const char*>(png512.data()), png512.size()));- XC_LOGI("trophy sync: cached cover icon for %s (%zu bytes)", titleSet.titleName.c_str(), png512.size());- ::stat(icon0File.c_str(), &st0);- }+ std::vector<uint8_t> png512;+ if (downloadAndConvert512Png(effectiveTileUrl, png512)) {+ platform::writeFileAtomic(icon0File, std::string(reinterpret_cast<const char*>(png512.data()), png512.size()));+ XC_LOGI("trophy sync: cached cover icon for %s (%zu bytes)", titleSet.titleName.c_str(), png512.size());+ icon0Valid = true;+ anyIconDownloaded = true;+ ::stat(icon0File.c_str(), &st0);}}}@@ -168,72 +389,86 @@ bool TrophySyncEngine::syncTitleAchievements(const std::string& xblAuth, const s// Platinum icon (trop0000.png)std::string platFile = iconsDir + "/trop0000.png";struct stat stPlat{};- if (::stat(platFile.c_str(), &stPlat) != 0 || stPlat.st_size == 0) {+ bool platValid = (::stat(platFile.c_str(), &stPlat) == 0 && stPlat.st_size > 100 &&+ stPlat.st_size != kDefaultIconPngSize && stPlat.st_size != kDefaultTropPngSize);+ if (!platValid) {if (titleSet.npCommId == "NPWR20561_00") {- net::Request req;- req.method = "GET";- req.url = "https://m.exophase.com/psn/awards/l/d41b74.png";- auto r = net::perform(req);- if (r.ok() && !r.body.empty()) {- std::vector<uint8_t> png512;- const auto* udata = reinterpret_cast<const uint8_t*>(r.body.data());- if (convertTo512Png(udata, r.body.size(), png512)) {- platform::writeFileAtomic(platFile, std::string(reinterpret_cast<const char*>(png512.data()), png512.size()));- XC_LOGI("trophy sync: cached genuine Platinum icon for %s (%zu bytes)", titleSet.npCommId.c_str(), png512.size());- }+ std::vector<uint8_t> png512;+ if (downloadAndConvert512Png("https://m.exophase.com/psn/awards/l/d41b74.png", png512)) {+ platform::writeFileAtomic(platFile, std::string(reinterpret_cast<const char*>(png512.data()), png512.size()));+ XC_LOGI("trophy sync: cached genuine Platinum icon for %s (%zu bytes)", titleSet.npCommId.c_str(), png512.size());+ anyIconDownloaded = true;}- } else {- // For other titles: if icon0File exists, copy as platinum icon+ } else if (icon0Valid) {std::string icon0Data;- if (platform::readFile(icon0File, icon0Data) && !icon0Data.empty()) {+ if (platform::readFile(icon0File, icon0Data) && icon0Data.size() > 100 &&+ icon0Data.size() != kDefaultIconPngSize && icon0Data.size() != kDefaultTropPngSize) {platform::writeFileAtomic(platFile, icon0Data);+ anyIconDownloaded = true;}}}if (fetchTrophyIcons) {- for (size_t i = 0; i < ach.items.size() && i < titleSet.items.size(); ++i) {- const auto& a = ach.items[i];+ std::vector<size_t> missingIdx;+ for (size_t i = 0; i < titleSet.items.size(); ++i) {const auto& def = titleSet.items[i];- if (a.iconUrl.empty()) continue;- // Optimization: only download icon over network for unlocked achievements.- // For locked achievements, trophy_builder uses the embedded kDefaultTropPng.- if (!a.unlocked) continue;+ if (def.iconUrl.empty()) continue;+char nameBuf[32];snprintf(nameBuf, sizeof(nameBuf), "trop%04d.png", def.trophyId);std::string iconFile = iconsDir + "/" + nameBuf;struct stat st{};- // Skip only if existing file is valid and not an accidental duplicate of cover art- if (::stat(iconFile.c_str(), &st) == 0 && st.st_size > 0 && (st0.st_size == 0 || st.st_size != st0.st_size)) continue;-- std::string fetchUrl = a.iconUrl;- if (fetchUrl.find("images-eds-ssl.xboxlive.com") != std::string::npos &&- fetchUrl.find("format=") == std::string::npos) {- fetchUrl += (fetchUrl.find('?') == std::string::npos) ? "?format=jpg" : "&format=jpg";- }- net::Request req;- req.method = "GET";- req.url = fetchUrl;- auto r = net::perform(req);- if (r.ok() && !r.body.empty()) {- std::vector<uint8_t> png512;- const auto* udata = reinterpret_cast<const uint8_t*>(r.body.data());- if (convertTo512Png(udata, r.body.size(), png512)) {- platform::writeFileAtomic(iconFile, std::string(reinterpret_cast<const char*>(png512.data()), png512.size()));- XC_LOGI("trophy sync: cached icon %s (%zu bytes)", nameBuf, png512.size());- }+ if (::stat(iconFile.c_str(), &st) == 0 && st.st_size > 100 &&+ st.st_size != kDefaultTropPngSize &&+ st.st_size != kDefaultIconPngSize &&+ (st0.st_size == 0 || st.st_size != st0.st_size)) {+ continue;}+ missingIdx.push_back(i);}- }- // 3. Load local cache snapshot- std::set<std::string> prevUnlocked;- std::string cacheFile = trophyCachePath(xboxTitleId);- std::string cacheContent;- if (platform::readFile(cacheFile, cacheContent)) {- if (auto j = json::parse(cacheContent); j && j->isObject()) {- for (const auto& item : (*j)["unlockedIds"].items()) {- if (item.isString()) prevUnlocked.insert(item.str());+ if (missingIdx.size() == 1) {+ const auto& def = titleSet.items[missingIdx[0]];+ char nameBuf[32];+ snprintf(nameBuf, sizeof(nameBuf), "trop%04d.png", def.trophyId);+ std::string iconFile = iconsDir + "/" + nameBuf;+ std::vector<uint8_t> png512;+ if (downloadAndConvert512Png(def.iconUrl, png512)) {+ platform::writeFileAtomic(iconFile, std::string(reinterpret_cast<const char*>(png512.data()), png512.size()));+ anyIconDownloaded = true;+ XC_LOGI("trophy sync: cached icon %s (%zu bytes) for %s", nameBuf, png512.size(), titleSet.titleName.c_str());+ }+ } else if (missingIdx.size() > 1) {+ std::atomic<size_t> nextJob{0};+ std::atomic<int> downloadedCount{0};+ const size_t numWorkers = std::min<size_t>(4, missingIdx.size());+ std::vector<std::thread> workers;+ workers.reserve(numWorkers);+ for (size_t w = 0; w < numWorkers; ++w) {+ workers.emplace_back([&]() {+ while (true) {+ size_t j = nextJob.fetch_add(1);+ if (j >= missingIdx.size()) break;+ const auto& def = titleSet.items[missingIdx[j]];+ char nameBuf[32];+ snprintf(nameBuf, sizeof(nameBuf), "trop%04d.png", def.trophyId);+ std::string iconFile = iconsDir + "/" + nameBuf;+ std::vector<uint8_t> png512;+ if (downloadAndConvert512Png(def.iconUrl, png512)) {+ platform::writeFileAtomic(iconFile, std::string(reinterpret_cast<const char*>(png512.data()), png512.size()));+ downloadedCount.fetch_add(1);+ }+ }+ });+ }+ for (auto& t : workers) {+ if (t.joinable()) t.join();+ }+ if (downloadedCount.load() > 0) {+ anyIconDownloaded = true;+ XC_LOGI("trophy sync: cached %d/%zu trophy icons for %s",+ downloadedCount.load(), missingIdx.size(), titleSet.titleName.c_str());}}}@@ -245,11 +480,10 @@ bool TrophySyncEngine::syncTitleAchievements(const std::string& xblAuth, const s// 5. Compare achievements and unlock new trophiesbool platinumAwarded = prevUnlocked.count("__PLATINUM__") > 0;- for (size_t i = 0; i < ach.items.size() && i < titleSet.items.size(); ++i) {- const auto& a = ach.items[i];+ for (size_t i = 0; i < titleSet.items.size(); ++i) {const auto& def = titleSet.items[i];- if (a.unlocked) {- std::string key = a.id.empty() ? std::to_string(def.trophyId) : a.id;+ if (def.unlocked) {+ std::string key = std::to_string(def.trophyId);bool alreadyInBackend = backend_ ? backend_->isTrophyUnlocked(titleSet.npCommId, def.trophyId) : false;if (prevUnlocked.count(key) == 0 || !alreadyInBackend) {bool unlockedOk = true;@@ -264,8 +498,8 @@ bool TrophySyncEngine::syncTitleAchievements(const std::string& xblAuth, const s}}- // 5. Automatic Platinum award on 100% completion- if (!platinumAwarded && hasEarnedPlatinum(ach.unlockedCount, ach.totalCount)) {+ // 5b. Automatic Platinum award on 100% completion+ if (!platinumAwarded && hasEarnedPlatinum(titleSet.unlockedCount, titleSet.totalCount)) {XC_LOGI("trophy sync: 100%% achievements obtained for %s! Awarding Platinum trophy.",titleSet.titleName.c_str());bool platOk = true;@@ -278,13 +512,46 @@ bool TrophySyncEngine::syncTitleAchievements(const std::string& xblAuth, const s}}- // 6. Flush backend state to commit TRPTITLE.DAT to the PlayStation profile database+ // 6. Flush backend state to commit TROPHY.UCP & TRPTITLE.DAT when neededif (backend_) {- backend_->flush();+ bool needsDeploy = (newlyUnlocked > 0 || anyIconDownloaded);+ if (!needsDeploy) {+ std::string ucpPath = "/user/trophy2/nobackup/conf/" + titleSet.npCommId + "/TROPHY.UCP";+ struct stat stUcp{};+ if (::stat(ucpPath.c_str(), &stUcp) != 0 || stUcp.st_size < 1024) {+ needsDeploy = true;+ } else {+ off_t cachedIconsBytes = 0;+ if (icon0Valid) cachedIconsBytes += st0.st_size;+ for (const auto& def : titleSet.items) {+ char nameBuf[32];+ snprintf(nameBuf, sizeof(nameBuf), "/trop%04d.png", def.trophyId);+ struct stat stIcon{};+ if (::stat((iconsDir + nameBuf).c_str(), &stIcon) == 0 && stIcon.st_size > 100) {+ cachedIconsBytes += stIcon.st_size;+ }+ }+ if (stUcp.st_size < cachedIconsBytes) {+ needsDeploy = true;+ } else if (icon0Valid && !titleSet.sonyTitleId.empty() && titleSet.sonyTitleId != "PPSA99810") {+ std::string appmetaIcon = "/system_data/priv/appmeta/" + titleSet.sonyTitleId + "/icon0.png";+ struct stat stAppIcon{};+ if (::stat(appmetaIcon.c_str(), &stAppIcon) != 0 ||+ stAppIcon.st_size == 0 ||+ stAppIcon.st_size == static_cast<off_t>(kDefaultIconPngSize)) {+ needsDeploy = true;+ }+ }+ }+ }+ if (needsDeploy) {+ backend_->flush();+ }}// 7. Save updated cache atomically with rich profile informationjson::Value out = json::Value::object();+ out.set("schemaVersion", static_cast<int64_t>(2));out.set("xboxTitleId", xboxTitleId);out.set("npCommId", titleSet.npCommId);out.set("sonyTitleId", titleSet.sonyTitleId);@@ -323,26 +590,17 @@ bool TrophySyncEngine::syncTitleAchievements(const std::string& xblAuth, const sbool TrophySyncEngine::pollActiveStream(const std::string& xblAuth, const std::string& xuid,const std::string& xboxTitleId, const std::string& titleName,const std::string& tileUrl) {- if (xboxTitleId.empty() || xblAuth.empty()) return false;- if (pollInFlight_.exchange(true)) return false;-- std::thread([this, xblAuth, xuid, xboxTitleId, titleName, tileUrl]() {- int newlyUnlocked = 0;- std::string err;- bool ok = syncTitleAchievements(xblAuth, xuid, xboxTitleId, titleName, newlyUnlocked, err, tileUrl, true);- if (ok && newlyUnlocked > 0) {- XC_LOGI("trophy poll: unlocked %d trophies during stream for %s!", newlyUnlocked, titleName.c_str());- }- pollInFlight_ = false;- }).detach();- return true;+ return dispatchStreamPoll(xblAuth, xuid, xboxTitleId, titleName, tileUrl);}bool TrophySyncEngine::syncAllAccountTrophies(const std::string& xblAuth, const std::string& xuid,const std::vector<ui::GameTile>& ownedGames,int& totalTitles, int& totalTrophies, std::string& err,const std::function<bool()>& cancelCheck,- const std::function<void(int done, int total)>& progressCb) {+ const std::function<void(int done, int total, const std::string& title)>& progressCb,+ bool forceFetchMissingIcons,+ const std::function<bool(const std::string& xboxTitleId, const std::string& titleName)>& isTitleEnabled) {+ (void)forceFetchMissingIcons;totalTitles = 0;totalTrophies = 0;if (xblAuth.empty()) {@@ -350,17 +608,18 @@ bool TrophySyncEngine::syncAllAccountTrophies(const std::string& xblAuth, constreturn false;}- struct SyncGuard {- std::atomic<bool>& f;- SyncGuard(std::atomic<bool>& flag) : f(flag) { f = true; }- ~SyncGuard() { f = false; }- } guard(syncing_);+ struct SyncDepthGuard {+ std::atomic<int>& d;+ explicit SyncDepthGuard(std::atomic<int>& depth) : d(depth) { d.fetch_add(1); }+ ~SyncDepthGuard() { d.fetch_sub(1); }+ } guard(syncingDepth_);struct SyncTitleItem {std::string xboxTitleId;std::string titleName;std::string tileUrl;- int earnedAchievements = 0;+ int earnedAchievements = -1;+ int currentGamerscore = -1;};std::unordered_set<std::string> seenXboxTitles;@@ -375,13 +634,16 @@ bool TrophySyncEngine::syncAllAccountTrophies(const std::string& xblAuth, constXC_LOGW("trophy back-sync: fetchAchievementHistoryTitles failed: %s", histErr.c_str());}- // 2. Query TitleHub batch images for history titles+ // 2. Query TitleHub batch images for history titles with earned achievementsstd::unordered_map<std::string, std::string> titleImages;if (!historyTitles.empty()) {std::vector<std::string> idsForBatch;idsForBatch.reserve(historyTitles.size());+ idsForBatch.push_back("267695549");for (const auto& h : historyTitles) {- idsForBatch.push_back(h.titleId);+ if (h.earnedAchievements > 0 && h.titleId != "267695549") {+ idsForBatch.push_back(h.titleId);+ }}std::string imgErr;xcloud::fetchTitleHubBatchImages(xblAuth, idsForBatch, titleImages, imgErr, ui::gameLocale());@@ -390,7 +652,7 @@ bool TrophySyncEngine::syncAllAccountTrophies(const std::string& xblAuth, const// Always prioritize Fortnite first for focused verification (AGENTS.md §8.1)seenXboxTitles.insert("267695549");- titlesToSync.push_back({"267695549", "Fortnite", "", 0});+ titlesToSync.push_back({"267695549", "Fortnite", "", -1, -1});auto itFnImg = titleImages.find("267695549");if (itFnImg != titleImages.end()) {@@ -402,6 +664,7 @@ bool TrophySyncEngine::syncAllAccountTrophies(const std::string& xblAuth, constif (h.earnedAchievements <= 0) continue;if (h.titleId == "267695549") {titlesToSync[0].earnedAchievements = h.earnedAchievements;+ titlesToSync[0].currentGamerscore = h.currentGamerscore;if (!h.name.empty()) titlesToSync[0].titleName = h.name;if (titlesToSync[0].tileUrl.empty() && !h.displayImage.empty()) {titlesToSync[0].tileUrl = h.displayImage;@@ -414,12 +677,23 @@ bool TrophySyncEngine::syncAllAccountTrophies(const std::string& xblAuth, constauto it = titleImages.find(h.titleId);if (it != titleImages.end()) img = it->second;}- titlesToSync.push_back({h.titleId, h.name.empty() ? ("Xbox Title " + h.titleId) : h.name, img, h.earnedAchievements});+ titlesToSync.push_back({+ h.titleId,+ h.name.empty() ? ("Xbox Title " + h.titleId) : h.name,+ img,+ h.earnedAchievements,+ h.currentGamerscore+ });}}- // Supplement tileUrl or titleName from owned library for known titles+ // Supplement tileUrl or titleName from owned library (matching by xboxTitleId or normalized titleName)+ std::unordered_map<std::string, std::string> catalogUrlByNormName;for (const auto& game : ownedGames) {+ if (!game.name.empty() && !game.tileUrl.empty()) {+ std::string norm = normalizeTrophyName(game.name);+ if (!norm.empty()) catalogUrlByNormName[norm] = normalizeHttpsUrl(game.tileUrl);+ }std::string xid = game.xboxTitleId;if (xid.empty() && !game.productId.empty()) {if (const auto* k = findKnownTitle("", game.productId)) {@@ -429,12 +703,12 @@ bool TrophySyncEngine::syncAllAccountTrophies(const std::string& xblAuth, constif (xid.empty()) continue;if (xid == "267695549") {- if (!game.tileUrl.empty()) titlesToSync[0].tileUrl = game.tileUrl;+ if (!game.tileUrl.empty()) titlesToSync[0].tileUrl = normalizeHttpsUrl(game.tileUrl);if (!game.name.empty()) titlesToSync[0].titleName = game.name;} else {for (auto& item : titlesToSync) {if (item.xboxTitleId == xid) {- if (item.tileUrl.empty() && !game.tileUrl.empty()) item.tileUrl = game.tileUrl;+ if (item.tileUrl.empty() && !game.tileUrl.empty()) item.tileUrl = normalizeHttpsUrl(game.tileUrl);if (item.titleName.empty() || item.titleName.find("Xbox Title") == 0) {if (!game.name.empty()) item.titleName = game.name;}@@ -443,6 +717,14 @@ bool TrophySyncEngine::syncAllAccountTrophies(const std::string& xblAuth, const}}}+ for (auto& item : titlesToSync) {+ if (item.tileUrl.empty() && !item.titleName.empty()) {+ auto it = catalogUrlByNormName.find(normalizeTrophyName(item.titleName));+ if (it != catalogUrlByNormName.end()) {+ item.tileUrl = it->second;+ }+ }+ }XC_LOGI("trophy back-sync: starting synchronization for %d titles", static_cast<int>(titlesToSync.size()));for (size_t i = 0; i < titlesToSync.size(); ++i) {@@ -450,23 +732,81 @@ bool TrophySyncEngine::syncAllAccountTrophies(const std::string& xblAuth, constXC_LOGI("trophy back-sync: cancelled by user after %d titles", totalTitles);break;}+ const auto& item = titlesToSync[i];+ if (isTitleEnabled && !isTitleEnabled(item.xboxTitleId, item.titleName)) {+ XC_LOGI("trophy back-sync: skipping %s (%s) (disabled in per-game settings)",+ item.titleName.c_str(), item.xboxTitleId.c_str());+ std::string cPath = trophyCachePath(item.xboxTitleId);+ std::string cRaw;+ if (platform::readFile(cPath, cRaw) && !cRaw.empty()) {+ if (auto j = json::parse(cRaw); j && j->isObject()) {+ std::string np = (*j)["npCommId"].str();+ std::string sony = (*j)["sonyTitleId"].str();+ if (!np.empty() && !isRetailInstalledGame(sony)) {+ std::lock_guard<std::mutex> lock(mutex_);+ if (!backend_) backend_.reset(createPlatformTrophyBackend());+ if (backend_) {+ int rem = 0;+ std::string remErr;+ backend_->removeAllTrophies({{np, sony}}, rem, remErr);+ }+ }+ }+ ::unlink(cPath.c_str());+ }+ continue;+ }if (progressCb) {- progressCb(static_cast<int>(i), static_cast<int>(titlesToSync.size()));+ progressCb(static_cast<int>(i), static_cast<int>(titlesToSync.size()), item.titleName);}- const auto& item = titlesToSync[i];- int newlyUnlocked = 0;- std::string titleErr;- // Fetch genuine individual icons for the pilot title (Fortnite); for bulk history, use box art + default icon- bool isFortnite = (item.xboxTitleId == "267695549");- if (syncTitleAchievements(xblAuth, xuid, item.xboxTitleId, item.titleName, newlyUnlocked, titleErr, item.tileUrl, isFortnite)) {- totalTitles++;- totalTrophies += newlyUnlocked;- } else {- XC_LOGW("trophy back-sync: title %s (%s) sync warning: %s", item.titleName.c_str(), item.xboxTitleId.c_str(), titleErr.c_str());+ static const int kBackoffSeconds[] = { 1, 2, 4 };+ const int kMaxRetries = 3;++ for (int attempt = 0; attempt <= kMaxRetries; ++attempt) {+ if (cancelCheck && cancelCheck()) break;+ int newlyUnlocked = 0;+ std::string titleErr;+ if (syncTitleAchievements(xblAuth, xuid, item.xboxTitleId, item.titleName, newlyUnlocked, titleErr,+ item.tileUrl, true, item.earnedAchievements, item.currentGamerscore)) {+ totalTitles++;+ totalTrophies += newlyUnlocked;+ break;+ }++ bool isTransport = isNetworkTransportError(titleErr);+ XC_LOGW("trophy back-sync: title %s (%s) attempt %d/%d failed: %s (transport=%d)",+ item.titleName.c_str(), item.xboxTitleId.c_str(), attempt + 1, kMaxRetries + 1,+ titleErr.c_str(), isTransport ? 1 : 0);++ if (attempt < kMaxRetries) {+ int backoff = kBackoffSeconds[attempt];+ for (int s = 0; s < backoff * 10; ++s) {+ if (cancelCheck && cancelCheck()) break;+ platform::sleepMs(100);+ }+ } else if (isTransport) {+ XC_LOGW("trophy back-sync: persistent network loss for %s. Entering PausedWaitingForNetwork...",+ item.titleName.c_str());+ if (progressCb) {+ std::string pLabel = std::string(ui::tr(ui::Str::SyncingTrophies)) + " (Aguardando rede...)";+ progressCb(static_cast<int>(i), static_cast<int>(titlesToSync.size()), pLabel);+ }+ while (!cancelCheck || !cancelCheck()) {+ if (probeNetworkConnectivity()) {+ XC_LOGI("trophy back-sync: network connectivity restored, retrying %s...", item.titleName.c_str());+ attempt = -1; // Fresh retries on reconnection+ break;+ }+ for (int s = 0; s < 20; ++s) {+ if (cancelCheck && cancelCheck()) break;+ platform::sleepMs(100);+ }+ }+ }}}if (progressCb) {- progressCb(static_cast<int>(titlesToSync.size()), static_cast<int>(titlesToSync.size()));+ progressCb(static_cast<int>(titlesToSync.size()), static_cast<int>(titlesToSync.size()), "");}XC_LOGI("trophy back-sync: completed. %d titles checked, %d trophies unlocked.", totalTitles, totalTrophies);@@ -491,6 +831,23 @@ bool TrophySyncEngine::removeAllTrophies(int& removedCount, std::string& err) {struct dirent* de;while ((de = ::readdir(d)) != nullptr) {std::string fname = de->d_name;+ if (fname == "id_map.json") {+ std::string content;+ if (platform::readFile(cacheDir + "/" + fname, content)) {+ if (auto j = json::parse(content); j && j->isObject()) {+ for (const auto& [seed, val] : j->members()) {+ uint32_t slot = static_cast<uint32_t>(val.asInt(0));+ if (slot >= 80000 && slot <= 99799) {+ char npBuf[16], sonyBuf[16];+ snprintf(npBuf, sizeof(npBuf), "NPWR%05u_00", slot);+ snprintf(sonyBuf, sizeof(sonyBuf), "PPSA%05u", slot);+ titleSet.insert({npBuf, sonyBuf});+ }+ }+ }+ }+ continue;+ }if (fname.size() > 5 && fname.substr(fname.size() - 5) == ".json") {std::string content;if (platform::readFile(cacheDir + "/" + fname, content)) {@@ -549,4 +906,735 @@ TrophySyncEngine& syncEngine() {return s_engine;}+bool TrophySyncEngine::isSyncing() const {+ return syncingDepth_.load() > 0 || xc::trophy::isSyncing();+}++namespace {++enum class TaskType {+ RealtimePoll, // Urgent: real-time in-stream achievement poll+ BatchTitle, // Individual title in batch+ RemoveAll // Removal of local trophies+};++struct TrophyTask {+ TaskType type = TaskType::BatchTitle;+ std::string xblAuth;+ std::string xuid;+ std::string xboxTitleId;+ std::string titleName;+ std::string tileUrl;+ int expectedEarned = -1;+ int expectedGamerscore = -1;+ bool forceFetchIcons = true;+ int retries = 0;+};++platform::Thread g_trophyThread;+std::mutex g_trophyLifecycleMutex;+std::mutex g_trophyQueueMutex;+std::condition_variable g_trophyQueueCv;+std::deque<TrophyTask> g_trophyUrgentQueue;+std::deque<TrophyTask> g_trophyBatchQueue;++std::atomic<bool> g_trophyThreadRunning{false};+std::atomic<bool> g_trophyStopRequested{false};+std::atomic<bool> g_trophyCancelRequested{false};+std::atomic<bool> g_trophyBatchSyncPending{false};+std::atomic<bool> g_trophyForceFetchPending{true};+std::atomic<bool> g_trophySyncing{false};+std::atomic<int> g_trophyTitlesDone{0};+std::atomic<int> g_trophyTitlesTotal{0};++std::mutex g_batchParamMutex;+std::string g_explicitAuth;+std::string g_explicitXuid;+std::vector<ui::GameTile> g_explicitOwnedGames;+bool g_hasExplicitParams = false;++std::mutex g_providerMutex;+TrophyContextProvider g_contextProvider;++bool processUrgentTasksLocked(std::unique_lock<std::mutex>& lock, TrophySyncContext* ctx = nullptr) {+ bool hadRemoveAll = false;+ while (!g_trophyUrgentQueue.empty() && !g_trophyStopRequested.load()) {+ TrophyTask urgent = std::move(g_trophyUrgentQueue.front());+ g_trophyUrgentQueue.pop_front();+ lock.unlock();++ if (urgent.type == TaskType::RemoveAll) {+ hadRemoveAll = true;+ XC_LOGI("trophy thread: urgent task is RemoveAll, removing local trophies...");+ int removedCount = 0;+ std::string err;+ bool ok = syncEngine().removeAllTrophies(removedCount, err);+ XC_LOGI("trophy thread: urgent removeAllTrophies done (removed=%d, ok=%d)", removedCount, ok ? 1 : 0);+ if (ctx) {+ if (!ctx->completeCb) {+ std::lock_guard<std::mutex> pLock(g_providerMutex);+ if (g_contextProvider) g_contextProvider(*ctx);+ }+ if (ctx->completeCb) {+ ctx->completeCb(removedCount, 0, ok ? "" : err);+ }+ } else {+ TrophySyncContext fallbackCtx;+ {+ std::lock_guard<std::mutex> pLock(g_providerMutex);+ if (g_contextProvider) g_contextProvider(fallbackCtx);+ }+ if (fallbackCtx.completeCb) {+ fallbackCtx.completeCb(removedCount, 0, ok ? "" : err);+ }+ }+ } else if (urgent.type == TaskType::RealtimePoll) {+ int newlyUnlocked = 0;+ std::string err;+ bool ok = syncEngine().syncTitleAchievements(urgent.xblAuth, urgent.xuid,+ urgent.xboxTitleId, urgent.titleName,+ newlyUnlocked, err, urgent.tileUrl,+ /*fetchTrophyIcons=*/true);+ if (ok && newlyUnlocked > 0) {+ XC_LOGI("trophy poll: unlocked %d trophies during stream for %s!",+ newlyUnlocked, urgent.titleName.c_str());+ }+ } else {+ XC_LOGW("trophy thread: unexpected task type in urgent queue: %d", static_cast<int>(urgent.type));+ }++ lock.lock();+ }+ return hadRemoveAll;+}++void trophyThreadMain() {+ platform::setThreadAffinity(platform::ThreadRole::Worker, "xcloud_trophy");+ XC_LOGI("trophy thread: started and pinned to ThreadRole::Worker");++ TrophySyncContext ctx;+ int totalBatchTitles = 0;+ int totalBatchTrophies = 0;++ while (!g_trophyStopRequested.load()) {+ TrophyTask currentTask;+ bool hasTask = false;+ bool hasBatchPending = false;++ {+ std::unique_lock<std::mutex> lock(g_trophyQueueMutex);+ g_trophyQueueCv.wait(lock, [&] {+ return g_trophyStopRequested.load() ||+ !g_trophyUrgentQueue.empty() ||+ !g_trophyBatchQueue.empty() ||+ g_trophyBatchSyncPending.load();+ });++ if (g_trophyStopRequested.load()) break;++ // 1. FAST-PATH: Urgent stream poll tasks always execute FIRST+ if (!g_trophyUrgentQueue.empty()) {+ currentTask = std::move(g_trophyUrgentQueue.front());+ g_trophyUrgentQueue.pop_front();+ hasTask = true;+ } else if (g_trophyBatchSyncPending.load()) {+ g_trophyBatchSyncPending.store(false);+ hasBatchPending = true;+ } else if (!g_trophyBatchQueue.empty()) {+ currentTask = std::move(g_trophyBatchQueue.front());+ g_trophyBatchQueue.pop_front();+ hasTask = true;+ }+ }++ if (g_trophyStopRequested.load()) break;++ // Handle batch discovery when a new batch sync is initiated+ if (hasBatchPending) {+ bool forceFetch = g_trophyForceFetchPending.load();+ ctx = TrophySyncContext();+ bool hasCtx = false;++ {+ std::lock_guard<std::mutex> bLock(g_batchParamMutex);+ if (g_hasExplicitParams) {+ ctx.xblAuth = g_explicitAuth;+ ctx.xuid = g_explicitXuid;+ ctx.ownedGames = g_explicitOwnedGames;+ g_hasExplicitParams = false;+ hasCtx = true;+ }+ }++ if (!hasCtx) {+ std::lock_guard<std::mutex> pLock(g_providerMutex);+ if (g_contextProvider) hasCtx = g_contextProvider(ctx);+ } else if (!ctx.isStreaming) {+ std::lock_guard<std::mutex> pLock(g_providerMutex);+ if (g_contextProvider) {+ TrophySyncContext cbCtx;+ if (g_contextProvider(cbCtx)) {+ if (!ctx.isStreaming) ctx.isStreaming = cbCtx.isStreaming;+ if (!ctx.progressCb) ctx.progressCb = cbCtx.progressCb;+ if (!ctx.completeCb) ctx.completeCb = cbCtx.completeCb;+ if (!ctx.isTitleEnabled) ctx.isTitleEnabled = cbCtx.isTitleEnabled;+ }+ }+ }++ if (!hasCtx || ctx.xblAuth.empty()) {+ XC_LOGW("trophy thread: batch sync cannot run (no auth available)");+ continue;+ }++ // If active game streaming is in progress, pause batch discovery.+ // Urgent tasks (RealtimePoll) continue executing with top priority while paused.+ while (!g_trophyStopRequested.load() && !g_trophyCancelRequested.load() &&+ ctx.isStreaming && ctx.isStreaming()) {+ std::unique_lock<std::mutex> lock(g_trophyQueueMutex);+ g_trophyQueueCv.wait_for(lock, std::chrono::seconds(1), [&] {+ return g_trophyStopRequested.load() || g_trophyCancelRequested.load() ||+ !g_trophyUrgentQueue.empty() || (!ctx.isStreaming || !ctx.isStreaming());+ });+ if (g_trophyStopRequested.load() || g_trophyCancelRequested.load()) break;+ if (!g_trophyUrgentQueue.empty()) {+ processUrgentTasksLocked(lock, &ctx);+ }+ }+ if (g_trophyStopRequested.load() || g_trophyCancelRequested.load()) continue;++ g_trophyCancelRequested.store(false);+ g_trophySyncing.store(true);+ totalBatchTitles = 0;+ totalBatchTrophies = 0;++ if (ctx.progressCb && (!ctx.isStreaming || !ctx.isStreaming())) {+ ctx.progressCb(true, 0, 1, ui::tr(ui::Str::SyncingTrophies));+ }++ // Discovery+ std::vector<xcloud::AchievementTitleHistoryItem> historyTitles;+ std::string histErr;+ if (xcloud::fetchAchievementHistoryTitles(ctx.xblAuth, ctx.xuid, historyTitles, histErr, ui::gameLocale())) {+ XC_LOGI("trophy thread: discovered %zu titles in Xbox achievement history", historyTitles.size());+ } else {+ XC_LOGW("trophy thread: fetchAchievementHistoryTitles failed: %s", histErr.c_str());+ }++ std::unordered_map<std::string, std::string> titleImages;+ if (!historyTitles.empty()) {+ std::vector<std::string> idsForBatch;+ idsForBatch.reserve(historyTitles.size());+ idsForBatch.push_back("267695549");+ for (const auto& h : historyTitles) {+ if (h.earnedAchievements > 0 && h.titleId != "267695549") {+ idsForBatch.push_back(h.titleId);+ }+ }+ std::string imgErr;+ xcloud::fetchTitleHubBatchImages(ctx.xblAuth, idsForBatch, titleImages, imgErr, ui::gameLocale());+ XC_LOGI("trophy thread: fetched %zu cover images via TitleHub batch", titleImages.size());+ }++ std::unordered_set<std::string> seenXboxTitles;+ std::vector<TrophyTask> discoveredTasks;++ // Always prioritize Fortnite first for focused verification (AGENTS.md §8.1)+ seenXboxTitles.insert("267695549");+ TrophyTask fnTask;+ fnTask.type = TaskType::BatchTitle;+ fnTask.xboxTitleId = "267695549";+ fnTask.titleName = "Fortnite";+ fnTask.forceFetchIcons = forceFetch;+ auto itFnImg = titleImages.find("267695549");+ if (itFnImg != titleImages.end()) fnTask.tileUrl = itFnImg->second;+ discoveredTasks.push_back(fnTask);++ for (const auto& h : historyTitles) {+ if (h.earnedAchievements <= 0) continue;+ if (h.titleId == "267695549") {+ discoveredTasks[0].expectedEarned = h.earnedAchievements;+ discoveredTasks[0].expectedGamerscore = h.currentGamerscore;+ if (!h.name.empty()) discoveredTasks[0].titleName = h.name;+ if (discoveredTasks[0].tileUrl.empty() && !h.displayImage.empty()) {+ discoveredTasks[0].tileUrl = h.displayImage;+ }+ continue;+ }+ if (seenXboxTitles.insert(h.titleId).second) {+ std::string img = h.displayImage;+ if (img.empty()) {+ auto it = titleImages.find(h.titleId);+ if (it != titleImages.end()) img = it->second;+ }+ TrophyTask t;+ t.type = TaskType::BatchTitle;+ t.xboxTitleId = h.titleId;+ t.titleName = h.name.empty() ? ("Xbox Title " + h.titleId) : h.name;+ t.tileUrl = img;+ t.expectedEarned = h.earnedAchievements;+ t.expectedGamerscore = h.currentGamerscore;+ t.forceFetchIcons = forceFetch;+ discoveredTasks.push_back(t);+ }+ }++ // Match artwork & names from ownedGames+ std::unordered_map<std::string, std::string> catalogUrlByNormName;+ for (const auto& game : ctx.ownedGames) {+ if (!game.name.empty() && !game.tileUrl.empty()) {+ std::string norm = normalizeTrophyName(game.name);+ if (!norm.empty()) catalogUrlByNormName[norm] = normalizeHttpsUrl(game.tileUrl);+ }+ std::string xid = game.xboxTitleId;+ if (xid.empty() && !game.productId.empty()) {+ if (const auto* k = findKnownTitle("", game.productId)) {+ xid = k->xboxTitleId;+ }+ }+ if (xid.empty()) continue;++ if (xid == "267695549") {+ if (!game.tileUrl.empty()) discoveredTasks[0].tileUrl = normalizeHttpsUrl(game.tileUrl);+ if (!game.name.empty()) discoveredTasks[0].titleName = game.name;+ } else {+ for (auto& item : discoveredTasks) {+ if (item.xboxTitleId == xid) {+ if (item.tileUrl.empty() && !game.tileUrl.empty()) item.tileUrl = normalizeHttpsUrl(game.tileUrl);+ if (item.titleName.empty() || item.titleName.find("Xbox Title") == 0) {+ if (!game.name.empty()) item.titleName = game.name;+ }+ break;+ }+ }+ }+ }+ for (auto& item : discoveredTasks) {+ if (item.tileUrl.empty() && !item.titleName.empty()) {+ auto it = catalogUrlByNormName.find(normalizeTrophyName(item.titleName));+ if (it != catalogUrlByNormName.end()) {+ item.tileUrl = it->second;+ }+ }+ }++ // Populate batchQueue under lock+ {+ std::lock_guard<std::mutex> lock(g_trophyQueueMutex);+ g_trophyBatchQueue.clear();+ for (auto& t : discoveredTasks) {+ g_trophyBatchQueue.push_back(std::move(t));+ }+ g_trophyTitlesTotal.store(static_cast<int>(g_trophyBatchQueue.size()));+ g_trophyTitlesDone.store(0);+ }++ XC_LOGI("trophy thread: enqueued %zu titles for background synchronization", discoveredTasks.size());+ continue;+ }++ if (!hasTask) continue;++ // Process Task+ if (currentTask.type == TaskType::RealtimePoll) {+ int newlyUnlocked = 0;+ std::string err;+ bool ok = syncEngine().syncTitleAchievements(currentTask.xblAuth, currentTask.xuid,+ currentTask.xboxTitleId, currentTask.titleName,+ newlyUnlocked, err, currentTask.tileUrl,+ /*fetchTrophyIcons=*/true);+ if (ok && newlyUnlocked > 0) {+ XC_LOGI("trophy poll: unlocked %d trophies during stream for %s!",+ newlyUnlocked, currentTask.titleName.c_str());+ }+ } else if (currentTask.type == TaskType::RemoveAll) {+ XC_LOGI("trophy thread: removing all local trophies...");+ int removedCount = 0;+ std::string err;+ bool ok = syncEngine().removeAllTrophies(removedCount, err);+ XC_LOGI("trophy thread: removeAllTrophies done (removed=%d, ok=%d)", removedCount, ok ? 1 : 0);+ if (!ctx.completeCb) {+ std::lock_guard<std::mutex> pLock(g_providerMutex);+ if (g_contextProvider) g_contextProvider(ctx);+ }+ if (ctx.completeCb) {+ ctx.completeCb(removedCount, 0, ok ? "" : err);+ }+ g_trophyCancelRequested.store(false);+ g_trophySyncing.store(false);+ } else if (currentTask.type == TaskType::BatchTitle) {+ if (!ctx.isStreaming) {+ std::lock_guard<std::mutex> pLock(g_providerMutex);+ if (g_contextProvider) {+ TrophySyncContext cbCtx;+ if (g_contextProvider(cbCtx)) {+ if (!ctx.isStreaming) ctx.isStreaming = cbCtx.isStreaming;+ if (!ctx.progressCb) ctx.progressCb = cbCtx.progressCb;+ if (!ctx.completeCb) ctx.completeCb = cbCtx.completeCb;+ if (!ctx.isTitleEnabled) ctx.isTitleEnabled = cbCtx.isTitleEnabled;+ }+ }+ }++ // If active game streaming is in progress, pause batch processing completely.+ // Urgent tasks (RealtimePoll) continue executing with top priority while paused.+ while (!g_trophyStopRequested.load() && !g_trophyCancelRequested.load() &&+ ctx.isStreaming && ctx.isStreaming()) {+ std::unique_lock<std::mutex> lock(g_trophyQueueMutex);+ g_trophyQueueCv.wait_for(lock, std::chrono::seconds(1), [&] {+ return g_trophyStopRequested.load() || g_trophyCancelRequested.load() ||+ !g_trophyUrgentQueue.empty() || (!ctx.isStreaming || !ctx.isStreaming());+ });+ if (g_trophyStopRequested.load() || g_trophyCancelRequested.load()) break;+ if (!g_trophyUrgentQueue.empty()) {+ processUrgentTasksLocked(lock, &ctx);+ }+ }+ if (g_trophyStopRequested.load()) break;++ if (g_trophyCancelRequested.load()) {+ XC_LOGI("trophy thread: batch sync cancelled by user");+ {+ std::lock_guard<std::mutex> lock(g_trophyQueueMutex);+ g_trophyBatchQueue.clear();+ }+ g_trophySyncing.store(false);+ g_trophyTitlesDone.store(0);+ g_trophyTitlesTotal.store(0);+ if (ctx.completeCb) ctx.completeCb(totalBatchTitles, totalBatchTrophies, "Cancelled");+ g_trophyCancelRequested.store(false);+ continue;+ }++ // Check if title is enabled+ if (ctx.isTitleEnabled && !ctx.isTitleEnabled(currentTask.xboxTitleId, currentTask.titleName)) {+ XC_LOGI("trophy thread: skipping %s (%s) (disabled in settings)",+ currentTask.titleName.c_str(), currentTask.xboxTitleId.c_str());+ std::string cPath = syncEngine().trophyCachePath(currentTask.xboxTitleId);+ std::string cRaw;+ if (platform::readFile(cPath, cRaw) && !cRaw.empty()) {+ if (auto j = json::parse(cRaw); j && j->isObject()) {+ std::string np = (*j)["npCommId"].str();+ std::string sony = (*j)["sonyTitleId"].str();+ if (!np.empty() && !isRetailInstalledGame(sony)) {+ int rem = 0;+ std::string remErr;+ if (syncEngine().backend()) {+ syncEngine().backend()->removeAllTrophies({{np, sony}}, rem, remErr);+ }+ }+ }+ ::unlink(cPath.c_str());+ }+ g_trophyTitlesDone.fetch_add(1);+ continue;+ }++ // Execute single title with 3-attempt exponential backoff retry loop (1s, 2s, 4s)+ static const int kBackoffSeconds[] = { 1, 2, 4 };+ const int kMaxRetries = 3;+ bool titleOk = false;+ bool removedDuringTitle = false;++ for (int attempt = 0; attempt <= kMaxRetries; ++attempt) {+ while (!g_trophyStopRequested.load() && !g_trophyCancelRequested.load() &&+ ctx.isStreaming && ctx.isStreaming()) {+ std::unique_lock<std::mutex> lock(g_trophyQueueMutex);+ g_trophyQueueCv.wait_for(lock, std::chrono::seconds(1), [&] {+ return g_trophyStopRequested.load() || g_trophyCancelRequested.load() ||+ !g_trophyUrgentQueue.empty() || (!ctx.isStreaming || !ctx.isStreaming());+ });+ if (g_trophyStopRequested.load() || g_trophyCancelRequested.load()) break;+ if (!g_trophyUrgentQueue.empty()) {+ processUrgentTasksLocked(lock, &ctx);+ }+ }+ if (g_trophyStopRequested.load() || g_trophyCancelRequested.load()) break;++ // Preemptively process any urgent real-time poll before executing title attempt+ {+ std::unique_lock<std::mutex> lock(g_trophyQueueMutex);+ if (!g_trophyUrgentQueue.empty()) {+ if (processUrgentTasksLocked(lock, &ctx)) {+ removedDuringTitle = true;+ g_trophyCancelRequested.store(true);+ }+ }+ }+ if (g_trophyStopRequested.load() || g_trophyCancelRequested.load()) break;++ int newlyUnlocked = 0;+ std::string titleErr;+ titleOk = syncEngine().syncTitleAchievements(ctx.xblAuth, ctx.xuid,+ currentTask.xboxTitleId, currentTask.titleName,+ newlyUnlocked, titleErr,+ currentTask.tileUrl, currentTask.forceFetchIcons,+ currentTask.expectedEarned, currentTask.expectedGamerscore);+ if (titleOk) {+ totalBatchTitles++;+ totalBatchTrophies += newlyUnlocked;+ break;+ }++ bool isTransport = isNetworkTransportError(titleErr);+ XC_LOGW("trophy thread: title %s (%s) attempt %d/%d failed: %s (transport=%d)",+ currentTask.titleName.c_str(), currentTask.xboxTitleId.c_str(),+ attempt + 1, kMaxRetries + 1, titleErr.c_str(), isTransport ? 1 : 0);++ if (attempt < kMaxRetries) {+ int backoff = kBackoffSeconds[attempt];+ std::unique_lock<std::mutex> lock(g_trophyQueueMutex);+ g_trophyQueueCv.wait_for(lock, std::chrono::seconds(backoff), [&] {+ return g_trophyStopRequested.load() || g_trophyCancelRequested.load() || !g_trophyUrgentQueue.empty();+ });+ if (!g_trophyUrgentQueue.empty()) {+ if (processUrgentTasksLocked(lock, &ctx)) {+ removedDuringTitle = true;+ g_trophyCancelRequested.store(true);+ }+ }+ } else if (isTransport) {+ // 3 failed retries due to transport error -> PausedWaitingForNetwork+ XC_LOGW("trophy thread: persistent network loss for %s. Entering PausedWaitingForNetwork...",+ currentTask.titleName.c_str());++ if (ctx.progressCb && (!ctx.isStreaming || !ctx.isStreaming())) {+ std::string pausedLabel = std::string(ui::tr(ui::Str::SyncingTrophies)) + " (Aguardando rede...)";+ ctx.progressCb(true, g_trophyTitlesDone.load(), g_trophyTitlesTotal.load(), pausedLabel);+ }++ // 2-second reconnect probe loop+ while (!g_trophyStopRequested.load() && !g_trophyCancelRequested.load()) {+ {+ std::unique_lock<std::mutex> lock(g_trophyQueueMutex);+ g_trophyQueueCv.wait_for(lock, std::chrono::seconds(2), [&] {+ return g_trophyStopRequested.load() || g_trophyCancelRequested.load() || !g_trophyUrgentQueue.empty();+ });++ if (g_trophyStopRequested.load() || g_trophyCancelRequested.load()) break;++ if (!g_trophyUrgentQueue.empty()) {+ if (processUrgentTasksLocked(lock, &ctx)) {+ removedDuringTitle = true;+ g_trophyCancelRequested.store(true);+ }+ }+ }++ if (g_trophyStopRequested.load() || g_trophyCancelRequested.load()) break;++ if (probeNetworkConnectivity()) {+ XC_LOGI("trophy thread: network connectivity restored! Resuming sync for %s...",+ currentTask.titleName.c_str());+ // Refresh tokens+ {+ std::lock_guard<std::mutex> pLock(g_providerMutex);+ if (g_contextProvider) g_contextProvider(ctx);+ }+ // Reset attempt counter so current title gets fresh attempts+ attempt = -1;+ break;+ }+ }+ }+ }++ if (g_trophyStopRequested.load()) {+ g_trophySyncing.store(false);+ break;+ }++ if (g_trophyCancelRequested.load()) {+ XC_LOGI("trophy thread: batch sync cancelled during title processing (%s)",+ currentTask.titleName.c_str());+ {+ std::lock_guard<std::mutex> lock(g_trophyQueueMutex);+ g_trophyBatchQueue.clear();+ }+ g_trophySyncing.store(false);+ g_trophyTitlesDone.store(0);+ g_trophyTitlesTotal.store(0);+ if (!removedDuringTitle && ctx.completeCb) {+ ctx.completeCb(totalBatchTitles, totalBatchTrophies, "Cancelled");+ }+ g_trophyCancelRequested.store(false);+ continue;+ }++ int done = g_trophyTitlesDone.fetch_add(1) + 1;+ int total = g_trophyTitlesTotal.load();++ if (ctx.progressCb && (!ctx.isStreaming || !ctx.isStreaming())) {+ ctx.progressCb(true, done, total, currentTask.titleName);+ }++ // Check if batch is finished+ bool batchDone = false;+ {+ std::lock_guard<std::mutex> lock(g_trophyQueueMutex);+ batchDone = g_trophyBatchQueue.empty();+ }++ if (batchDone) {+ g_trophySyncing.store(false);+ bool wasCancelled = g_trophyCancelRequested.load();+ if (wasCancelled) {+ g_trophyTitlesDone.store(0);+ g_trophyTitlesTotal.store(0);+ }+ XC_LOGI("trophy thread: background batch sync %s. %d titles checked, %d trophies unlocked.",+ wasCancelled ? "cancelled" : "complete",+ totalBatchTitles, totalBatchTrophies);+ if (ctx.completeCb) {+ ctx.completeCb(totalBatchTitles, totalBatchTrophies, wasCancelled ? "Cancelled" : "");+ }+ }+ }+ }++ g_trophySyncing.store(false);+ g_trophyThreadRunning.store(false);+ XC_LOGI("trophy thread: terminated cleanly");+}++} // namespace++void startTrophyThread() {+ std::lock_guard<std::mutex> lock(g_trophyLifecycleMutex);+ if (g_trophyThreadRunning.load()) return;+ if (g_trophyThread.joinable()) {+ g_trophyThread.join();+ }+ g_trophyStopRequested.store(false);+ g_trophyCancelRequested.store(false);+ g_trophyTitlesDone.store(0);+ g_trophyTitlesTotal.store(0);+ g_trophyThreadRunning.store(true);+ if (!platform::startThread(g_trophyThread, trophyThreadMain)) {+ g_trophyThreadRunning.store(false);+ XC_LOGW("trophy thread: failed to start thread");+ }+}++bool stopTrophyThread(uint32_t timeoutMs) {+ std::lock_guard<std::mutex> lock(g_trophyLifecycleMutex);+ if (!g_trophyThreadRunning.load() && !g_trophyThread.joinable()) return true;+ g_trophyStopRequested.store(true);+ g_trophyQueueCv.notify_all();++ uint64_t start = platform::nowMs();+ while (g_trophyThreadRunning.load()) {+ if (platform::nowMs() - start >= timeoutMs) break;+ platform::sleepMs(20);+ }++ if (!g_trophyThreadRunning.load() && g_trophyThread.joinable()) {+ g_trophyThread.join();+ }+ if (!g_trophyThreadRunning.load()) {+ g_trophySyncing.store(false);+ g_trophyTitlesDone.store(0);+ g_trophyTitlesTotal.store(0);+ }+ return !g_trophyThreadRunning.load();+}++void resumeTrophySync() {+ g_trophyQueueCv.notify_all();+}++void requestTrophySync(bool forceFetchIcons) {+ g_trophyCancelRequested.store(false);+ g_trophyForceFetchPending.store(forceFetchIcons);+ g_trophyBatchSyncPending.store(true);+ g_trophyQueueCv.notify_one();+}++void requestTrophySync(const std::string& xblAuth, const std::string& xuid,+ const std::vector<ui::GameTile>& ownedGames,+ bool forceFetchIcons) {+ {+ std::lock_guard<std::mutex> lock(g_batchParamMutex);+ g_explicitAuth = xblAuth;+ g_explicitXuid = xuid;+ g_explicitOwnedGames = ownedGames;+ g_hasExplicitParams = true;+ }+ requestTrophySync(forceFetchIcons);+}++void cancelTrophySync() {+ g_trophyCancelRequested.store(true);+ {+ std::lock_guard<std::mutex> lock(g_trophyQueueMutex);+ g_trophyBatchQueue.clear();+ g_trophyTitlesDone.store(0);+ g_trophyTitlesTotal.store(0);+ }+ g_trophyQueueCv.notify_all();+}++void requestRemoveTrophies() {+ g_trophyCancelRequested.store(true);+ {+ std::lock_guard<std::mutex> lock(g_trophyQueueMutex);+ g_trophyBatchQueue.clear();+ g_trophyTitlesDone.store(0);+ g_trophyTitlesTotal.store(0);+ TrophyTask task;+ task.type = TaskType::RemoveAll;+ g_trophyUrgentQueue.push_back(std::move(task));+ }+ g_trophyQueueCv.notify_all();+}++bool dispatchStreamPoll(const std::string& xblAuth, const std::string& xuid,+ const std::string& xboxTitleId, const std::string& titleName,+ const std::string& tileUrl) {+ if (xboxTitleId.empty() || xblAuth.empty()) return false;++ if (!g_trophyThreadRunning.load()) {+ int newlyUnlocked = 0;+ std::string err;+ return syncEngine().syncTitleAchievements(xblAuth, xuid, xboxTitleId, titleName,+ newlyUnlocked, err, tileUrl, true);+ }++ {+ std::lock_guard<std::mutex> lock(g_trophyQueueMutex);+ for (const auto& t : g_trophyUrgentQueue) {+ if (t.type == TaskType::RealtimePoll && t.xboxTitleId == xboxTitleId) {+ return true;+ }+ }+ TrophyTask task;+ task.type = TaskType::RealtimePoll;+ task.xblAuth = xblAuth;+ task.xuid = xuid;+ task.xboxTitleId = xboxTitleId;+ task.titleName = titleName;+ task.tileUrl = tileUrl;+ g_trophyUrgentQueue.push_back(std::move(task));+ }+ g_trophyQueueCv.notify_one();+ return true;+}++bool isSyncing() {+ return g_trophySyncing.load();+}++int titlesDone() {+ return g_trophyTitlesDone.load();+}++int titlesTotal() {+ return g_trophyTitlesTotal.load();+}++void setTrophyContextProvider(TrophyContextProvider provider) {+ std::lock_guard<std::mutex> lock(g_providerMutex);+ g_contextProvider = std::move(provider);+}+} // namespace xc::trophydiff --git a/src/trophy/trophy_sync.h b/src/trophy/trophy_sync.hindex 9b9b8f7..8c6bd72 100644--- a/src/trophy/trophy_sync.h+++ b/src/trophy/trophy_sync.h@@ -29,7 +29,9 @@ public:const std::string& xboxTitleId, const std::string& titleName,int& newlyUnlocked, std::string& err,const std::string& tileUrl = "",- bool fetchTrophyIcons = false);+ bool fetchTrophyIcons = true,+ int expectedEarned = -1,+ int expectedGamerscore = -1);// Called every 20s during active stream (non-blocking async dispatch)bool pollActiveStream(const std::string& xblAuth, const std::string& xuid,@@ -41,7 +43,9 @@ public:const std::vector<ui::GameTile>& ownedGames,int& totalTitles, int& totalTrophies, std::string& err,const std::function<bool()>& cancelCheck = nullptr,- const std::function<void(int done, int total)>& progressCb = nullptr);+ const std::function<void(int done, int total, const std::string& title)>& progressCb = nullptr,+ bool forceFetchMissingIcons = true,+ const std::function<bool(const std::string& xboxTitleId, const std::string& titleName)>& isTitleEnabled = nullptr);// Removes all local trophies and packages created by PSBoxbool removeAllTrophies(int& removedCount, std::string& err);@@ -50,20 +54,58 @@ public:void setBackend(std::unique_ptr<ITrophyBackend> backend);ITrophyBackend* backend() const { return backend_.get(); }- bool isSyncing() const { return syncing_.load(); }+ bool isSyncing() const;-private:std::string trophyCacheDir() const;std::string trophyCachePath(const std::string& xboxTitleId) const;+private:std::unique_ptr<ITrophyBackend> backend_;std::mutex mutex_;std::atomic<bool> pollInFlight_{false};- std::atomic<bool> syncing_{false};+ std::atomic<int> syncingDepth_{0};bool initialized_ = false;};// Global singleton instanceTrophySyncEngine& syncEngine();+// --- Dedicated Background Trophy Sync Thread (g_trophyThread) ---++// Thread lifecycle+void startTrophyThread();+bool stopTrophyThread(uint32_t timeoutMs = 3000);+void resumeTrophySync();++// Asynchronous dispatch requests+void requestTrophySync(bool forceFetchIcons = true);+void requestTrophySync(const std::string& xblAuth, const std::string& xuid,+ const std::vector<ui::GameTile>& ownedGames = {},+ bool forceFetchIcons = true);+void cancelTrophySync();+void requestRemoveTrophies();++// Stream real-time achievement poll (bypasses batch queue, urgent priority)+bool dispatchStreamPoll(const std::string& xblAuth, const std::string& xuid,+ const std::string& xboxTitleId, const std::string& titleName,+ const std::string& tileUrl = "");++// Status queries+bool isSyncing();+int titlesDone();+int titlesTotal();++struct TrophySyncContext {+ std::string xblAuth;+ std::string xuid;+ std::vector<ui::GameTile> ownedGames;+ std::function<bool(const std::string& xboxTitleId, const std::string& titleName)> isTitleEnabled;+ std::function<bool()> isStreaming;+ std::function<void(bool loading, int done, int total, const std::string& title)> progressCb;+ std::function<void(int totalTitles, int totalTrophies, const std::string& err)> completeCb;+};++using TrophyContextProvider = std::function<bool(TrophySyncContext& ctx)>;+void setTrophyContextProvider(TrophyContextProvider provider);+} // namespace xc::trophydiff --git a/src/ui/app_ui.cpp b/src/ui/app_ui.cppindex 3e82bd1..6d67f3b 100644--- a/src/ui/app_ui.cpp+++ b/src/ui/app_ui.cpp@@ -254,9 +254,11 @@ void AppUi::setCatalogState(std::vector<GameRow> rows, std::vector<GameTile> own}gamePassPool_ = std::move(gpPool);libraryPool_ = std::move(libPool);- loading_ = loadingActive;- loadingDone_ = loadingDone;- loadingTotal_ = loadingTotal;+ if (!trophySyncing_) {+ loading_ = loadingActive;+ loadingDone_ = loadingDone;+ loadingTotal_ = loadingTotal;+ }rebuild(true);}@@ -412,21 +414,29 @@ void AppUi::setConsoles(std::vector<ConsoleTile> consoles, bool known) {dirty_ = true;}-void AppUi::setLoading(bool active, size_t done, size_t total) {+void AppUi::setLoading(bool active, size_t done, size_t total, const std::string& customLabel) {std::lock_guard<std::mutex> lock(mutex_);- if (active == loading_ && done == loadingDone_ && total == loadingTotal_) return;+ if (trophySyncing_ && customLabel.empty()) return;+ if (active == loading_ && done == loadingDone_ && total == loadingTotal_ && customLabel == loadingLabel_) return;loading_ = active;loadingDone_ = done;loadingTotal_ = total;+ loadingLabel_ = customLabel;dirty_ = true;}void AppUi::drawLoadingBar(Canvas& c, int x, int y, int w, uint64_t nowMs) {- // "Updating the game list..." over a thin bar: the share done, or a+ // "Updating the game list..." or custom status over a thin bar: the share done, or a// sliding segment while there's no measure yet.if (!loading_) return;- std::string text = tr(Str::UpdatingList);- if (loadingTotal_) text += " " + std::to_string(loadingDone_ * 100 / loadingTotal_) + "%";+ std::string text = loadingLabel_.empty() ? tr(Str::UpdatingList) : loadingLabel_;+ if (loadingLabel_.empty() && loadingTotal_) text += " " + std::to_string(loadingDone_ * 100 / loadingTotal_) + "%";+ if (w > 40 && fonts_.semibold.measure(text, 20) > w) {+ while (!text.empty() && fonts_.semibold.measure(text + "...", 20) > w) {+ text.pop_back();+ }+ text += "...";+ }fonts_.semibold.draw(c, text, x, y, 20, kGray);Rect track{x, y + 32, w, 6};c.fillRect(track, rgba(255, 255, 255, 40), 3);@@ -459,6 +469,18 @@ void AppUi::setPlaytime(int64_t remainingSeconds, int64_t maxSeconds, bool unlimdirty_ = true;}+void AppUi::setTrophySyncing(bool active) {+ std::lock_guard<std::mutex> lock(mutex_);+ if (trophySyncing_ == active) return;+ trophySyncing_ = active;+ dirty_ = true;+}++bool AppUi::trophySyncing() const {+ std::lock_guard<std::mutex> lock(mutex_);+ return trophySyncing_;+}+void AppUi::prefsEvent(UiEvent& ev) const {// Caller holds mutex_.ev.action = Action::PrefsChanged;@@ -1066,7 +1088,6 @@ void AppUi::showHome(const std::string& toast) {}void AppUi::showToast(const std::string& toast) {- if (caps_.console) return;std::lock_guard<std::mutex> lock(mutex_);if (!toast.empty()) {toast_ = toast;@@ -1163,6 +1184,7 @@ void AppUi::showLaunching(const GameTile& game, const std::string& status) {std::lock_guard<std::mutex> lock(mutex_);if (screen_ != Screen::Launching) {launchingStartMs_ = 0;+ launchingSeed_ = 0;}screen_ = Screen::Launching;launching_ = game;diff --git a/src/ui/app_ui.h b/src/ui/app_ui.hindex 950b646..ae1c940 100644--- a/src/ui/app_ui.h+++ b/src/ui/app_ui.h@@ -320,7 +320,7 @@ public:void setConsoles(std::vector<ConsoleTile> consoles, bool known);// The lists' background refresh: shown as a bar in "Your games" and the// search; `total` 0 = running, no measure yet.- void setLoading(bool active, size_t done, size_t total);+ void setLoading(bool active, size_t done, size_t total, const std::string& customLabel = "");// What each tab's search looks through.void setSearchPools(std::vector<GameTile> gamePass, std::vector<GameTile> library);// Measured round trip to each region, ms (shown in Settings).@@ -328,6 +328,8 @@ public:// The account's cloud time: remaining and max in seconds (-1 unknown), or// `unlimited`. Purely informative; never blocks launch or gameplay.void setPlaytime(int64_t remainingSeconds, int64_t maxSeconds, bool unlimited = false);+ void setTrophySyncing(bool active);+ bool trophySyncing() const;// Store prices, formatted: productId -> {now, regular (empty unless on sale)}.void setPrices(const std::map<std::string, PriceInfo>& prices);// Saved preferences: hidden games, the "Your games" order, favorites, and wishlist.@@ -666,6 +668,7 @@ private:std::set<std::string> hidden_, favorites_;bool loading_ = false;size_t loadingDone_ = 0, loadingTotal_ = 0;+ std::string loadingLabel_;void drawLoadingBar(Canvas& c, int x, int y, int w, uint64_t nowMs);LibrarySort librarySort_ = LibrarySort::Recent;// Search filters (the row of buttons under the keys).@@ -693,6 +696,7 @@ private:GameTile detail_; // the game the details page showsGameTile launching_;uint64_t launchingStartMs_ = 0;+ size_t launchingSeed_ = 0;std::string error_;std::string errorUrl_;GameTile errorGame_; // showPlayError()'s game; empty for other errors@@ -791,6 +795,7 @@ private:int trophyDisclaimerFocus_ = 0; // 0 = Estou ciente, 1 = Cancelarbool removeTrophiesConfirmOpen_ = false;int removeTrophiesFocus_ = 1; // 0 = Remover, 1 = Cancelar+ bool trophySyncing_ = false;void drawSignOutHold(Canvas& c, uint64_t nowMs);std::string toast_;uint64_t toastUntil_ = 0;diff --git a/src/ui/app_ui_input.cpp b/src/ui/app_ui_input.cppindex 6e04377..f55e95a 100644--- a/src/ui/app_ui_input.cpp+++ b/src/ui/app_ui_input.cpp@@ -332,7 +332,7 @@ UiEvent AppUi::onMouseMove(float x, float y) {}if (gameSettingsOpen_) {constexpr int kModalW = 1140, kModalH = 960;- constexpr int kRowH = 40, kGap = 4, kGroupGap = 7;+ constexpr int kRowH = 38, kGap = 4, kGroupGap = 7;const auto rows = visibleGameSettingsRows(caps_, activeGameHasCustom_, activeGameMouseSupported_);const auto most = visibleGameSettingsRows(caps_, true, activeGameMouseSupported_), all = visibleGameSettingsRows(UiCaps{}, true, true);auto groups = [](const std::vector<SettingsRowPos>& v) {@@ -585,7 +585,7 @@ UiEvent AppUi::onMouseDown(float x, float y, int button) {} else if (screen_ == Screen::Details) {if (gameSettingsOpen_) {constexpr int kModalW = 1140, kModalH = 960;- constexpr int kRowH = 40, kGap = 4, kGroupGap = 7;+ constexpr int kRowH = 38, kGap = 4, kGroupGap = 7;const auto rows = visibleGameSettingsRows(caps_, activeGameHasCustom_, activeGameMouseSupported_);const auto most = visibleGameSettingsRows(caps_, true, activeGameMouseSupported_), all = visibleGameSettingsRows(UiCaps{}, true, true);auto groups = [](const std::vector<SettingsRowPos>& v) {@@ -1070,6 +1070,16 @@ UiEvent AppUi::handle(const NavInput& in) {tester_ = Tester::None;dirty_ = true;} else if (in.accept && !signInCheck_.running) {+ signInCheck_.running = true;+ signInCheck_.stages = {+ {"1. Account Storage", false, true, "Checking..."},+ {"2. Microsoft OAuth (MSA)", false, true, "Waiting..."},+ {"3. Xbox Live User Token", false, true, "Waiting..."},+ {"4. XSTS Security Token", false, true, "Waiting..."},+ {"5. xCloud Offering (xgpuweb)", false, true, "Waiting..."},+ {"6. Recursos Preview (xCloud & Ads)", false, true, "Waiting..."},+ };+ dirty_ = true;ev.action = Action::CheckSignIn;}break;@@ -1079,6 +1089,13 @@ UiEvent AppUi::handle(const NavInput& in) {tester_ = Tester::None;dirty_ = true;} else if (in.accept && !networkTest_.running) {+ networkTest_.running = true;+ networkTest_.natStatus = "Probing UDP STUN...";+ for (auto& reg : networkTest_.regions) {+ reg.rttMs = -1;+ reg.jitterMs = -1;+ }+ dirty_ = true;ev.action = Action::RunNetworkTest;}break;@@ -1161,7 +1178,9 @@ UiEvent AppUi::handle(const NavInput& in) {ev.action = Action::TestQueueAlert;}if (in.square && settingsRow_ == 24) {- if (settings_.syncTrophies) {+ if (trophySyncing_) {+ // Sync already in progress; ignore repeated triggers+ } else if (settings_.syncTrophies) {ev.action = Action::SyncTrophies;ev.settings = settings_;} else {diff --git a/src/ui/app_ui_internal.h b/src/ui/app_ui_internal.hindex 5704f83..0f40e8a 100644--- a/src/ui/app_ui_internal.h+++ b/src/ui/app_ui_internal.h@@ -72,10 +72,11 @@ constexpr bool kSettingsGroupStart[kSettingsCount] = {false, false, false, false// The game settings' rows on screen (ids: 0 profile, 1 upscaler, 2// sharpness, 3 block smoothing, 4 resolution, 5 dead zone, 6 triggers, 7// confirm, 8 120 Hz, 9 keyboard keys, 10 back to the default, 11 controller-// buttons, 12 gyro aiming, 13 touchpad as mouse, 14 game language, 15 video decoder, 16 audio-to-haptics).-constexpr int kGameRowCount = 17;-constexpr int kGameRowOrder[kGameRowCount] = {0, 4, 8, 15, 14, 1, 2, 3, 5, 6, 16, 7, 12, 11, 13, 9, 10};-constexpr bool kGameGroupStart[kGameRowCount] = {false, true, false, false, false, true, false, false, true, false, false, false, false, false, false, false, true};+// buttons, 12 gyro aiming, 13 touchpad as mouse, 14 game language, 15 video decoder,+// 16 audio-to-haptics, 17 touchpad shortcuts, 18 trophy sync).+constexpr int kGameRowCount = 18;+constexpr int kGameRowOrder[kGameRowCount] = {0, 4, 8, 15, 14, 18, 1, 2, 3, 5, 6, 16, 7, 12, 11, 13, 9, 10};+constexpr bool kGameGroupStart[kGameRowCount] = {false, true, false, false, false, false, true, false, false, true, false, false, false, false, false, false, false, true};// The keyboard keys' screen: two columns of inputs, then "Reset to default".constexpr int kKeysPerColumn = input::kKeyActions / 2;// Updates on a desktop: the newest release's page (the app doesn't install it there).diff --git a/src/ui/app_ui_render.cpp b/src/ui/app_ui_render.cppindex 4490a09..c2a1f39 100644--- a/src/ui/app_ui_render.cpp+++ b/src/ui/app_ui_render.cpp@@ -249,7 +249,6 @@ void AppUi::drawSpinner(Canvas& c, float cx, float cy, float r, uint64_t nowMs)}void AppUi::drawToast(Canvas& c, uint64_t nowMs) {- if (caps_.console) return;if (toast_.empty()) return;if (toastUntil_ == 0) toastUntil_ = nowMs + 3500;if (nowMs >= toastUntil_) {@@ -260,6 +259,7 @@ void AppUi::drawToast(Canvas& c, uint64_t nowMs) {Rect r{(kW - w) / 2, kH - 150, w, 56};c.fillRect(r, rgba(40, 40, 40, 235), 28);fonts_.semibold.draw(c, toast_, r.x + 32, r.y + 14, 24, kWhite);+ animating_ = true;}bool AppUi::drawHero(Canvas& c, uint64_t nowMs, const std::string& url, bool details) {@@ -810,6 +810,11 @@ void AppUi::drawConsoles(Canvas& c, uint64_t nowMs) {drawBackground(c);drawTopBar(c);drawTabs(c);+ {+ constexpr int kGridW = kLibraryCols * kCardPitch - kCardGap;+ const int left = (kW - kGridW) / 2;+ drawLoadingBar(c, left, 112, 420, nowMs);+ }fonts_.bold.draw(c, tr(Str::TabConsoles), kMargin, 170, 52, kWhite);fonts_.regular.draw(c, tr(Str::ConsolesHint), kMargin, 240, 26, kGray);if (consoles_.empty()) {@@ -887,6 +892,7 @@ void AppUi::drawConsoles(Canvas& c, uint64_t nowMs) {{kIconOptions, tr(Str::Settings)},{kIconTouchpad, tr(Str::HoldSignOut)}});drawPads(c);+ drawToast(c, nowMs);}void AppUi::drawHome(Canvas& c, uint64_t nowMs) {@@ -959,6 +965,11 @@ void AppUi::drawHome(Canvas& c, uint64_t nowMs) {c.gradientV({0, 140, kW, 16}, kBg, withAlpha(kBg, 0));drawTopBar(c);drawTabs(c);+ {+ constexpr int kGridW = kLibraryCols * kCardPitch - kCardGap;+ const int left = (kW - kGridW) / 2;+ drawLoadingBar(c, left, 112, 420, nowMs);+ }return;}@@ -1050,6 +1061,11 @@ void AppUi::drawHome(Canvas& c, uint64_t nowMs) {drawTopBar(c);drawTabs(c);+ {+ constexpr int kGridW = kLibraryCols * kCardPitch - kCardGap;+ const int left = (kW - kGridW) / 2;+ drawLoadingBar(c, left, 112, 420, nowMs);+ }// Fade the rows out under the button hints.c.gradientV({0, kH - 190, kW, 110}, withAlpha(kBg, 0), withAlpha(kBg, 245));@@ -1358,7 +1374,7 @@ void AppUi::drawLaunching(Canvas& c, uint64_t nowMs) {drawCentered(c, fonts_.bold, launching_.name, 500, 48, kWhite);drawCentered(c, fonts_.semibold, tr(Str::GettingReady), 576, 30, kGray);drawCentered(c, fonts_.regular, status_, 630, 26, kDim);- // Helpful tips rotating every ~10 seconds from when the launching screen opened.+ // Helpful tips rotating every ~7 seconds from when the launching screen opened.static constexpr Str kTips[] = {Str::TipTouchpadMenu,Str::TipKeyboardMouse,@@ -1368,11 +1384,30 @@ void AppUi::drawLaunching(Canvas& c, uint64_t nowMs) {Str::Tip120HzVideo,Str::TipAnalogDeadzone,Str::TipDualSenseMic,+ Str::TipTouchpadMouse,+ Str::TipGyroAiming,+ Str::TipFSRUpscaling,+ Str::TipCustomBitrate,+ Str::TipNativeTrophies,+ Str::TipPerGameTrophies,+ Str::TipSmartGlassWebUI,+ Str::TipClaimFreeStore,+ Str::TipButtonRemap,+ Str::TipInstantResume,+ Str::TipInGameMenu,+ Str::TipBackgroundSync,};constexpr size_t kTipCount = sizeof(kTips) / sizeof(kTips[0]);- if (!launchingStartMs_) launchingStartMs_ = nowMs;+ if (!launchingStartMs_) {+ launchingStartMs_ = nowMs;+ uint32_t titleHash = 2166136261u;+ for (char ch : launching_.name) {+ titleHash = (titleHash ^ static_cast<uint8_t>(ch)) * 16777619u;+ }+ launchingSeed_ = static_cast<size_t>(nowMs ^ titleHash);+ }uint64_t elapsedMs = nowMs >= launchingStartMs_ ? (nowMs - launchingStartMs_) : 0;- size_t tipIndex = (elapsedMs / 10000) % kTipCount;+ size_t tipIndex = (launchingSeed_ + (elapsedMs / 7000)) % kTipCount;drawCentered(c, fonts_.regular, tr(kTips[tipIndex]), 900, 22, kDim);drawHints(c, {{kIconCircle, tr(Str::Cancel)}});}diff --git a/src/ui/app_ui_settings.cpp b/src/ui/app_ui_settings.cppindex f3eaa7d..d7dfff0 100644--- a/src/ui/app_ui_settings.cpp+++ b/src/ui/app_ui_settings.cpp@@ -40,6 +40,35 @@ void AppUi::openTester(Tester t) {keysRow_ = keysCol_ = 0;captureSince_ = 0;keyRefused_ = 0;+ if (t == Tester::SignInCheck) {+ signInCheck_.running = true;+ signInCheck_.stages = {+ {"1. Account Storage", false, true, "Checking..."},+ {"2. Microsoft OAuth (MSA)", false, true, "Waiting..."},+ {"3. Xbox Live User Token", false, true, "Waiting..."},+ {"4. XSTS Security Token", false, true, "Waiting..."},+ {"5. xCloud Offering (xgpuweb)", false, true, "Waiting..."},+ {"6. Recursos Preview (xCloud & Ads)", false, true, "Waiting..."},+ };+ } else if (t == Tester::NetworkTest) {+ networkTest_.running = true;+ networkTest_.natStatus = "Probing UDP STUN...";+ networkTest_.regions.clear();+ if (!regions_.empty()) {+ for (const auto& r : regions_) {+ networkTest_.regions.push_back({r, -1, -1});+ }+ } else {+ networkTest_.regions = {+ {"BrazilSouth", -1, -1},+ {"EastUS", -1, -1},+ {"EastUS2", -1, -1},+ {"SouthCentralUS", -1, -1},+ {"WestUS2", -1, -1},+ {"WestEurope", -1, -1},+ };+ }+ }dirty_ = true;}@@ -378,6 +407,7 @@ void AppUi::openGameSettings() {activeGameProfile_.sharpness = settings_.sharpness;activeGameProfile_.deband = settings_.deband;activeGameProfile_.upscaler = settings_.upscaler;+ activeGameProfile_.videoDecoder = settings_.videoDecoder;activeGameProfile_.resolution = settings_.resolution;activeGameProfile_.deadzoneLeft = settings_.deadzone[0];activeGameProfile_.deadzoneRight = settings_.deadzone[1];@@ -394,7 +424,11 @@ void AppUi::openGameSettings() {activeGameProfile_.gyroLevel = gyroLevel_;activeGameProfile_.touchpadMouse = settings_.touchpadMouse;activeGameProfile_.touchpadShortcuts = settings_.touchpadShortcuts;+ activeGameProfile_.locale.clear();+ activeGameProfile_.syncTrophies = true;}+ if (!detail_.xboxTitleId.empty()) activeGameProfile_.xboxTitleId = detail_.xboxTitleId;+ if (!detail_.name.empty()) activeGameProfile_.gameName = detail_.name;}void AppUi::closeGameSettings() {@@ -712,6 +746,11 @@ void AppUi::handleGameSettings(const NavInput& in, UiEvent& ev) {activeGameHasCustom_ = true;dirty_ = true;break;+ case 18: // Per-game Trophy Synchronization+ activeGameProfile_.syncTrophies = !activeGameProfile_.syncTrophies;+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;default: break;}}@@ -813,6 +852,11 @@ void AppUi::handleGameSettings(const NavInput& in, UiEvent& ev) {activeGameHasCustom_ = true;dirty_ = true;break;+ case 18:+ activeGameProfile_.syncTrophies = !activeGameProfile_.syncTrophies;+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;case 9: // Keyboard keys: their own screen, on this game'sopenTester(Tester::Keys);settings_.keyMap = activeGameProfile_.keyMap;@@ -826,12 +870,14 @@ void AppUi::handleGameSettings(const NavInput& in, UiEvent& ev) {case 10: // Reset to defaultactiveGameHasCustom_ = false;activeGameProfile_.locale.clear();+ activeGameProfile_.syncTrophies = true;activeGameProfile_.keyMap = settings_.keyMap;activeGameProfile_.padMap = settings_.padMap;activeGameProfile_.touchpadShortcuts = settings_.touchpadShortcuts;activeGameProfile_.sharpness = settings_.sharpness;activeGameProfile_.deband = settings_.deband;activeGameProfile_.upscaler = settings_.upscaler;+ activeGameProfile_.videoDecoder = settings_.videoDecoder;activeGameProfile_.resolution = settings_.resolution;activeGameProfile_.deadzoneLeft = settings_.deadzone[0];activeGameProfile_.deadzoneRight = settings_.deadzone[1];@@ -884,6 +930,9 @@ void AppUi::drawSettings(Canvas& c) {drawBackground(c);drawTopBar(c);fonts_.bold.draw(c, tr(Str::Settings), kMargin, 116, 46, kWhite);+ if (loading_) {+ drawLoadingBar(c, kW - kMargin - 480, 100, 480, lastRender_);+ }const char* labels[kSettingRows] = {tr(Str::Language), tr(Str::Resolution), tr(Str::Region),tr(Str::Deadzone), tr(Str::TriggerRumble), tr(Str::ConfirmButton),tr(Str::LightBar), tr(Str::Updates), tr(Str::LoginCountry),@@ -950,6 +999,15 @@ void AppUi::drawSettings(Canvas& c) {} else if (i == 5) {// The confirm button, as the button itself.drawFaceButton(c, fonts_.bold, settings_.circleConfirms ? kIconCircle : kIconCross, vx - 16.0f, cy, 16);+ } else if (i == 24 && (trophySyncing_ || (loading_ && !loadingLabel_.empty()))) {+ std::string value = tr(Str::SyncingTrophies);+ if (loadingTotal_ > 0) {+ value += " " + std::to_string(loadingDone_) + "/" + std::to_string(loadingTotal_);+ }+ int w = fonts_.regular.measure(value, kRowPx);+ fonts_.regular.draw(c, value, vx - w, fonts_.regular.centeredY(r.y, r.h, kRowPx), kRowPx, rgba(120, 220, 120));+ drawSpinner(c, vx - w - 20.0f, cy, 8, lastRender_);+ animating_ = true;} else {auto options = settingOptions(i);int sel = settingSelected(i);@@ -1111,7 +1169,9 @@ void AppUi::drawSettings(Canvas& c) {} else if (settingsRow_ == 16) {drawHints(c, {{kIconCross, tr(Str::Change)}, {kIconSquare, tr(Str::TestSound)}, {kIconTriangle, tr(Str::ReportProblem)}, {kIconCircle, tr(Str::Back)}});} else if (settingsRow_ == 24) {- if (settings_.syncTrophies) {+ if (trophySyncing_ || (loading_ && !loadingLabel_.empty())) {+ drawHints(c, {{kIconCircle, tr(Str::Back)}});+ } else if (settings_.syncTrophies) {drawHints(c, {{kIconCross, tr(Str::Change)}, {kIconSquare, tr(Str::RunSyncTrophies)}, {kIconTriangle, tr(Str::ReportProblem)}, {kIconCircle, tr(Str::Back)}});} else {drawHints(c, {{kIconCross, tr(Str::Change)}, {kIconTriangle, tr(Str::ReportProblem)}, {kIconCircle, tr(Str::Back)}});@@ -1122,6 +1182,7 @@ void AppUi::drawSettings(Canvas& c) {drawHints(c, {{kIconCross, tr(Str::Change)}, {kIconTriangle, tr(Str::ReportProblem)}, {kIconCircle, tr(Str::Back)}});}}+ drawToast(c, lastRender_);}Rect AppUi::drawModal(Canvas& c, int w, int h, const std::string& title) {@@ -1877,7 +1938,7 @@ void AppUi::drawGameSettings(Canvas& c) {}}constexpr int kModalW = 1140, kModalH = 960;- constexpr int kRowH = 40, kGap = 4, kGroupGap = 7;+ constexpr int kRowH = 38, kGap = 4, kGroupGap = 7;// The rows caps_ allows; the panel loses the height of those it hides// (the same as ever with all of them, "Reset to default" or not).const auto rows = visibleGameSettingsRows(caps_, activeGameHasCustom_, activeGameMouseSupported_);@@ -2010,6 +2071,10 @@ void AppUi::drawGameSettings(Canvas& c) {label = tr(Str::VideoDecoder);value = activeGameProfile_.videoDecoder == 1 ? tr(Str::VideoDecoderSw) : tr(Str::VideoDecoderHw);break;+ case 18:+ label = tr(Str::SyncTrophies);+ value = tr(activeGameProfile_.syncTrophies ? Str::Activated : Str::Deactivated);+ break;default: break;}diff --git a/src/ui/i18n/strings_de.inc b/src/ui/i18n/strings_de.incindex 2384eca..03b6293 100644--- a/src/ui/i18n/strings_de.inc+++ b/src/ui/i18n/strings_de.inc@@ -351,6 +351,18 @@ constexpr Column kGerman = {"120-Hz-Videoausgabe in den Einstellungen für geringere Anzeigelatenz und flüssigere Steuerung aktivieren", // Tip120HzVideo"Stick-Totzone in den Einstellungen kalibrieren, um Stick-Drift zu verhindern und Präzision zu verbessern", // TipAnalogDeadzone"Integriertes DualSense-Mikrofon für Party- und Multiplayer-Sprachchat verwenden", // TipDualSenseMic+ "In Spielen mit Mausunterstützung das DualSense-Touchpad als Mauszeiger verwenden", // TipTouchpadMouse+ "Gyroskop-Zielen in den Einstellungen aktivieren, um mit Bewegungssensoren präzise zu zielen", // TipGyroAiming+ "AMD FSR-Upscaling und Schärfefilter verbessern Bildschärfe und Details beim Streaming", // TipFSRUpscaling+ "Streaming-Bitrate in den Einstellungen auf bis zu 45 Mbit/s für maximale Qualität anpassen", // TipCustomBitrate+ "Xbox-Erfolge werden beim Spielen automatisch als native PlayStation 5-Trophäen freigeschaltet", // TipNativeTrophies+ "Trophäen-Tracking für einzelne Spiele direkt auf der Spieledetailseite ein- oder ausschalten", // TipPerGameTrophies+ "Öffnen Sie http://[konsolen-ip]:8080 im Browser für Zugriff auf die SmartGlass WebUI", // TipSmartGlassWebUI+ "Kostenlose Spiele und Demos mit nur einem Klick direkt in der Anwendung sichern", // TipClaimFreeStore+ "Tastenbelegung für jedes Spiel individuell im Einstellungsmenü anpassen", // TipButtonRemap+ "Ihre Spielebibliothek lädt sofort aus dem lokalen Cache ohne Wartezeiten beim Start", // TipInstantResume+ "Beim Spielen auf dem Touchpad nach unten wischen, um Lautstärke und Bitrate anzupassen", // TipInGameMenu+ "Hintergrund-Delta-Sync hält Katalog und Regallisten automatisch auf dem neuesten Stand", // TipBackgroundSync// Settings descriptions"Ändert die Sprache der Benutzeroberfläche sowie die bevorzugte Audio- und Untertitelsprache in Cloud-Spielen", // SettingDescLanguage"Legt die maximale Streaming-Auflösung fest (1080p, 720p oder Beste). Wird beim nächsten Spielstart wirksam", // SettingDescResolution@@ -436,4 +448,5 @@ constexpr Column kGerman = {"Dies löscht die lokalen Trophäenpakete von PSBox für dieses Profil. Ihre Erfolge bleiben auf Ihrem Microsoft/Xbox-Konto sicher gespeichert.", // RemoveTrophiesConfirmBody"Entfernen", // RemoveTrophiesConfirm"%s Trophäen-Titel aus diesem Profil entfernt.", // TrophiesRemovedToast+ "Erfolge werden synchronisiert...", // SyncingTrophies};diff --git a/src/ui/i18n/strings_en.inc b/src/ui/i18n/strings_en.incindex 0088565..828ae41 100644--- a/src/ui/i18n/strings_en.inc+++ b/src/ui/i18n/strings_en.inc@@ -351,6 +351,18 @@ constexpr Column kEnglish = {"Enable 120 Hz display output in Settings for reduced frame latency and smoother response", // Tip120HzVideo"Calibrate DualSense stick dead zones in Settings to eliminate stick drift and improve precision", // TipAnalogDeadzone"Use the DualSense built-in microphone for party and multiplayer game voice chat", // TipDualSenseMic+ "In keyboard and mouse supported games, use the DualSense touchpad surface as a mouse pointer", // TipTouchpadMouse+ "Enable gyro aiming in Settings to fine-tune your weapon aim with DualSense motion sensors", // TipGyroAiming+ "AMD FSR upscaling and sharpness filters enhance visual clarity and details during streaming", // TipFSRUpscaling+ "Adjust the streaming bitrate cap in Settings up to 45 Mbps for pristine visual quality", // TipCustomBitrate+ "Xbox achievements unlock automatically as native PlayStation 5 trophies while you play", // TipNativeTrophies+ "Toggle native trophy tracking on or off per game from the game details screen", // TipPerGameTrophies+ "Open your phone or PC browser to http://[console-ip]:8080 to access the SmartGlass WebUI", // TipSmartGlassWebUI+ "Claim free game licenses and demos directly in 1 click without leaving the application", // TipClaimFreeStore+ "Customize and remap controller buttons individually per game in the Settings menu", // TipButtonRemap+ "Your library loads instantly from persistent local cache without boot loading screens", // TipInstantResume+ "Swipe down on the touchpad during gameplay to adjust volume, bitrate, and stream settings", // TipInGameMenu+ "Background delta sync keeps your catalog and shelf lists updated automatically", // TipBackgroundSync// Settings descriptions"Changes the language of the application interface and the preferred audio and subtitles in cloud games", // SettingDescLanguage"Sets the maximum streaming video resolution (1080p, 720p, or Best available). Takes effect on the next launch", // SettingDescResolution@@ -436,4 +448,5 @@ constexpr Column kEnglish = {"This will delete local trophy packages added by PSBox for this profile. Your achievements remain safe on your Microsoft/Xbox account.", // RemoveTrophiesConfirmBody"Remove", // RemoveTrophiesConfirm"Removed %s trophy title(s) from this profile.", // TrophiesRemovedToast+ "Syncing achievements...", // SyncingTrophies};diff --git a/src/ui/i18n/strings_es.inc b/src/ui/i18n/strings_es.incindex c77d190..9b4ea6a 100644--- a/src/ui/i18n/strings_es.inc+++ b/src/ui/i18n/strings_es.inc@@ -351,6 +351,18 @@ constexpr Column kSpanish = {"Activa salida de vídeo a 120 Hz en Configuración para menor latencia y respuesta más fluida", // Tip120HzVideo"Calibra la zona muerta de los sticks en Configuración para eliminar deriva y mejorar la precisión", // TipAnalogDeadzone"Usa el micrófono integrado del DualSense para chat de voz en grupos y partidas multijugador", // TipDualSenseMic+ "En juegos con soporte de ratón, usa la superficie del touchpad del DualSense como ratón", // TipTouchpadMouse+ "Activa el apuntado por giroscopio en Configuración para apuntar con los sensores de movimiento", // TipGyroAiming+ "El reescalado espacial FSR y el filtro de nitidez mejoran la claridad y detalle del stream", // TipFSRUpscaling+ "Ajusta el límite de tasa de bits en Configuración hasta 45 Mbps para máxima calidad visual", // TipCustomBitrate+ "Los logros de Xbox se desbloquean automáticamente como trofeos nativos de PlayStation 5", // TipNativeTrophies+ "Activa o desactiva los trofeos de forma individual desde la pantalla de detalles del juego", // TipPerGameTrophies+ "Abre http://[ip-de-consola]:8080 en tu móvil o PC para gestionar ajustes con SmartGlass WebUI", // TipSmartGlassWebUI+ "Reclama juegos gratis y demos en 1 clic directamente sin tener que salir de la aplicación", // TipClaimFreeStore+ "Personaliza y reasigna los botones del mando individualmente por juego en Configuración", // TipButtonRemap+ "Tu biblioteca se carga al instante desde la caché local persistente al abrir la aplicación", // TipInstantResume+ "Desliza hacia abajo en el touchpad durante la partida para ajustar volumen y bitrate", // TipInGameMenu+ "La sincronización en segundo plano mantiene tu catálogo y estantes siempre actualizados", // TipBackgroundSync// Settings descriptions"Cambia el idioma de la interfaz de la aplicación y la preferencia de audio y subtítulos en juegos en la nube", // SettingDescLanguage"Establece la resolución máxima del stream de vídeo (1080p, 720p o Mejor disponible). Se aplica en el próximo juego", // SettingDescResolution@@ -436,4 +448,5 @@ constexpr Column kSpanish = {"Esto borrará los paquetes locales de trofeos de PSBox para este perfil. Tus logros permanecen seguros en tu cuenta Microsoft/Xbox.", // RemoveTrophiesConfirmBody"Eliminar", // RemoveTrophiesConfirm"Se han eliminado %s título(s) de trofeos de este perfil.", // TrophiesRemovedToast+ "Sincronizando logros...", // SyncingTrophies};diff --git a/src/ui/i18n/strings_fr.inc b/src/ui/i18n/strings_fr.incindex 9de39ba..4daddcc 100644--- a/src/ui/i18n/strings_fr.inc+++ b/src/ui/i18n/strings_fr.inc@@ -351,6 +351,18 @@ constexpr Column kFrench = {"Activez la sortie vidéo 120 Hz dans les Paramètres pour réduire la latence d'affichage et de contrôle", // Tip120HzVideo"Calibrez la zone morte des sticks dans les Paramètres pour éliminer le drift et améliorer la précision", // TipAnalogDeadzone"Utilisez le microphone intégré de la DualSense pour le chat vocal dans les groupes et jeux multijoueurs", // TipDualSenseMic+ "Dans les jeux compatibles souris, utilisez la surface du pavé tactile DualSense comme souris", // TipTouchpadMouse+ "Activez la visée gyroscopique dans les Paramètres pour viser avec les capteurs de mouvement", // TipGyroAiming+ "La mise à l'échelle FSR et le filtre de netteté améliorent les détails de la diffusion", // TipFSRUpscaling+ "Ajustez la limite de débit dans les Paramètres jusqu'à 45 Mbit/s pour une fidélité maximale", // TipCustomBitrate+ "Les succès Xbox se débloquent automatiquement comme trophées PlayStation 5 natifs", // TipNativeTrophies+ "Activez ou désactivez le suivi des trophées par jeu depuis l'écran de détails du jeu", // TipPerGameTrophies+ "Ouvrez http://[ip-console]:8080 sur votre mobile ou PC pour accéder à la WebUI SmartGlass", // TipSmartGlassWebUI+ "Obtenez des jeux gratuits et des démos en 1 clic directement sans quitter l'application", // TipClaimFreeStore+ "Personnalisez et réassignez les boutons de la manette par jeu dans les Paramètres", // TipButtonRemap+ "Votre bibliothèque se charge instantanément depuis le cache local sans écran d'attente", // TipInstantResume+ "Glissez vers le bas sur le pavé tactile en jeu pour ajuster volume, débit et diffusion", // TipInGameMenu+ "La synchronisation en arrière-plan maintient votre catalogue et vos listes à jour", // TipBackgroundSync// Settings descriptions"Modifie la langue de l'interface de l'application et les préférences audio et sous-titres dans les jeux du cloud", // SettingDescLanguage"Définit la résolution vidéo maximale (1080p, 720p ou Meilleure disponible). Prend effet au prochain lancement", // SettingDescResolution@@ -436,4 +448,5 @@ constexpr Column kFrench = {"Cela supprimera les packs de trophées locaux de PSBox pour ce profil. Vos succès restent enregistrés sur votre compte Microsoft/Xbox.", // RemoveTrophiesConfirmBody"Supprimer", // RemoveTrophiesConfirm"%s titre(s) de trophées supprimé(s) de ce profil.", // TrophiesRemovedToast+ "Synchronisation des succès...", // SyncingTrophies};diff --git a/src/ui/i18n/strings_it.inc b/src/ui/i18n/strings_it.incindex dc318d6..2aeea91 100644--- a/src/ui/i18n/strings_it.inc+++ b/src/ui/i18n/strings_it.inc@@ -351,6 +351,18 @@ constexpr Column kItalian = {"Abilita l'uscita video a 120 Hz nelle Impostazioni per una latenza di visualizzazione ridotta", // Tip120HzVideo"Calibra la zona morta delle levette nelle Impostazioni per eliminare il drift e migliorare la precisione", // TipAnalogDeadzone"Usa il microfono integrato del DualSense per la chat vocale nei gruppi e nelle partite multigiocatore", // TipDualSenseMic+ "Nei giochi supportati da mouse, usa la superficie del touchpad del DualSense come puntatore", // TipTouchpadMouse+ "Attiva la mira con giroscopio nelle Impostazioni per mirare con i sensori di movimento", // TipGyroAiming+ "L'upscaling spaziale FSR e il filtro nitidezza migliorano la chiarezza e i dettagli visivi", // TipFSRUpscaling+ "Regola il bitrate dello stream nelle Impostazioni fino a 45 Mbps per la massima qualità", // TipCustomBitrate+ "Gli obiettivi Xbox si sbloccano automaticamente come trofei nativi di PlayStation 5", // TipNativeTrophies+ "Attiva o disattiva il tracciamento dei trofei per singolo gioco nella schermata dei dettagli", // TipPerGameTrophies+ "Apri http://[ip-console]:8080 dal browser di smartphone o PC per accedere alla WebUI SmartGlass", // TipSmartGlassWebUI+ "Riscatta giochi gratuiti e demo in 1 clic direttamente senza uscire dall'applicazione", // TipClaimFreeStore+ "Personalizza e rimappa i pulsanti del controller per singolo gioco nelle Impostazioni", // TipButtonRemap+ "La libreria si carica all'istante dalla cache locale persistente all'avvio dell'app", // TipInstantResume+ "Scorri verso il basso sul touchpad durante il gioco per regolare volume, bitrate e stream", // TipInGameMenu+ "La sincronizzazione in background mantiene il catalogo e le liste sempre aggiornati", // TipBackgroundSync// Settings descriptions"Modifica la lingua dell'interfaccia dell'applicazione e le preferenze di audio e sottotitoli nei giochi cloud", // SettingDescLanguage"Imposta la risoluzione video massima (1080p, 720p o Migliore disponibile). Ha effetto al prossimo avvio", // SettingDescResolution@@ -436,4 +448,5 @@ constexpr Column kItalian = {"Questo cancellerà i pacchetti di trofei locali di PSBox per questo profilo. I tuoi obiettivi rimangono al sicuro sul tuo account Microsoft/Xbox.", // RemoveTrophiesConfirmBody"Rimuovi", // RemoveTrophiesConfirm"Rimossi %s titoli di trofei da questo profilo.", // TrophiesRemovedToast+ "Sincronizzazione obiettivi...", // SyncingTrophies};diff --git a/src/ui/i18n/strings_pt_br.inc b/src/ui/i18n/strings_pt_br.incindex 0cb9e1e..21756ba 100644--- a/src/ui/i18n/strings_pt_br.inc+++ b/src/ui/i18n/strings_pt_br.inc@@ -351,6 +351,18 @@ constexpr Column kPortugueseBR = {"Ative a saída de vídeo em 120 Hz nas Configurações para menor latência e resposta mais rápida", // Tip120HzVideo"Ajuste a zona morta dos analógicos do DualSense nas Configurações para eliminar drift", // TipAnalogDeadzone"Use o microfone integrado do DualSense para bate-papo de voz em grupos e jogos multijogador", // TipDualSenseMic+ "Em jogos com suporte a mouse, use a superfície do touchpad do DualSense como ponteiro do mouse", // TipTouchpadMouse+ "Ative a mira por giroscópio nas Configurações para ajustar a mira movendo o DualSense", // TipGyroAiming+ "O upscaler espacial FSR e filtro de nitidez aumentam a clareza e detalhes da transmissão", // TipFSRUpscaling+ "Ajuste o limite de bitrate nas Configurações até 45 Mbps para máxima fidelidade visual", // TipCustomBitrate+ "Conquistas do Xbox desbloqueiam automaticamente como troféus nativos do PlayStation 5", // TipNativeTrophies+ "Ative ou desative o registro de troféus individualmente na tela de detalhes do jogo", // TipPerGameTrophies+ "Acesse http://[ip-do-console]:8080 no celular ou PC para gerenciar ajustes pelo SmartGlass", // TipSmartGlassWebUI+ "Resgate jogos gratuitos e demonstrações em 1 clique sem precisar sair do aplicativo", // TipClaimFreeStore+ "Personalize e remapeie os botões do controle individualmente por jogo nas Configurações", // TipButtonRemap+ "Sua biblioteca carrega instantaneamente do cache local persistente ao iniciar o app", // TipInstantResume+ "Deslize para baixo no Touchpad durante a partida para ajustar volume, bitrate e stream", // TipInGameMenu+ "A sincronização em segundo plano mantém seu catálogo e estantes sempre atualizados", // TipBackgroundSync// Settings descriptions"Altera o idioma da interface do aplicativo e a preferência de áudio e legendas nos jogos da nuvem", // SettingDescLanguage"Define a resolução máxima do fluxo de vídeo transmitido (1080p, 720p ou Melhor). Vale a partir do próximo jogo", // SettingDescResolution@@ -436,4 +448,5 @@ constexpr Column kPortugueseBR = {"Isso apagará os pacotes locais de troféus adicionados pelo PSBox para este perfil. Suas conquistas continuam salvas na sua conta Microsoft/Xbox.", // RemoveTrophiesConfirmBody"Remover", // RemoveTrophiesConfirm"Removido(s) %s título(s) de troféus deste perfil.", // TrophiesRemovedToast+ "Sincronizando conquistas...", // SyncingTrophies};diff --git a/src/ui/strings.h b/src/ui/strings.hindex 8d05ed4..03c7ae5 100644--- a/src/ui/strings.h+++ b/src/ui/strings.h@@ -360,6 +360,18 @@ enum class Str {Tip120HzVideo,TipAnalogDeadzone,TipDualSenseMic,+ TipTouchpadMouse,+ TipGyroAiming,+ TipFSRUpscaling,+ TipCustomBitrate,+ TipNativeTrophies,+ TipPerGameTrophies,+ TipSmartGlassWebUI,+ TipClaimFreeStore,+ TipButtonRemap,+ TipInstantResume,+ TipInGameMenu,+ TipBackgroundSync,// Settings descriptionsSettingDescLanguage,SettingDescResolution,@@ -445,6 +457,7 @@ enum class Str {RemoveTrophiesConfirmBody,RemoveTrophiesConfirm,TrophiesRemovedToast,+ SyncingTrophies,Count};diff --git a/src/xcloud/achievements.cpp b/src/xcloud/achievements.cppindex 0c5e3b9..1effbac 100644--- a/src/xcloud/achievements.cpp+++ b/src/xcloud/achievements.cpp@@ -7,9 +7,26 @@#include "util/log.h"#include <algorithm>+#include <cstring>namespace xc::xcloud {+namespace {++std::string normalizeHttpsImageUrl(std::string url) {+ if (url.empty()) return url;+ if (url.rfind("http://images-eds.xboxlive.com/", 0) == 0) {+ url = "https://images-eds-ssl.xboxlive.com/" + url.substr(std::strlen("http://images-eds.xboxlive.com/"));+ } else if (url.rfind("http://", 0) == 0) {+ url = "https://" + url.substr(7);+ } else if (url.rfind("//", 0) == 0) {+ url = "https:" + url;+ }+ return url;+}++} // namespace+bool fetchTitleAchievements(const std::string& xblAuth, const std::string& xuid,const std::string& xboxTitleId, TitleAchievements& out,std::string& err, const std::string& language) {@@ -79,10 +96,13 @@ bool fetchTitleAchievements(const std::string& xblAuth, const std::string& xuid,std::string type = ma["type"].str();std::string name = ma["name"].str();if (type == "Icon" || name == "Icon" || ach.iconUrl.empty()) {- ach.iconUrl = ma["url"].str();+ ach.iconUrl = normalizeHttpsImageUrl(ma["url"].str());if (type == "Icon" || name == "Icon") break;}}+ if (ach.iconUrl.empty() && a["imageUnlocked"].isString()) {+ ach.iconUrl = normalizeHttpsImageUrl(a["imageUnlocked"].str());+ }for (const auto& rw : a["rewards"].items()) {std::string type = rw["type"].str();@@ -179,6 +199,7 @@ bool fetchAchievementHistoryTitles(const std::string& xblAuth, const std::stringh.name = item["name"].str();h.titleType = item["titleType"].str();h.platform = item["platform"].str();+ h.displayImage = normalizeHttpsImageUrl(item["displayImage"].str());h.earnedAchievements = item["earnedAchievements"].isNumber() ? static_cast<int>(item["earnedAchievements"].asInt()) : 0;h.currentGamerscore = item["currentGamerscore"].isNumber() ? static_cast<int>(item["currentGamerscore"].asInt()) : 0;h.maxGamerscore = item["maxGamerscore"].isNumber() ? static_cast<int>(item["maxGamerscore"].asInt()) : 0;@@ -212,17 +233,15 @@ bool fetchTitleHubBatchImages(const std::string& xblAuth,const std::vector<std::string>& titleIds,std::unordered_map<std::string, std::string>& outImages,std::string& err, const std::string& language) {+ (void)err;if (xblAuth.empty() || titleIds.empty()) return true;- // Process in batches of 100- constexpr size_t kBatchSize = 100;- for (size_t i = 0; i < titleIds.size(); i += kBatchSize) {- size_t end = std::min(i + kBatchSize, titleIds.size());+ auto runBatch = [&](size_t startIdx, size_t endIdx) -> bool {json::Value body = json::Value::object();body.set("pfns", json::Value::array());body.set("windowsPhoneProductIds", json::Value::array());json::Value arr = json::Value::array();- for (size_t k = i; k < end; ++k) {+ for (size_t k = startIdx; k < endIdx; ++k) {arr.push(titleIds[k]);}body.set("titleIds", std::move(arr));@@ -240,27 +259,47 @@ bool fetchTitleHubBatchImages(const std::string& xblAuth,auto r = net::perform(req);auto j = json::parse(r.body);- if (r.ok() && j && (*j)["titles"].isArray()) {- for (const auto& item : (*j)["titles"].items()) {- std::string tid;- if (item["titleId"].isNumber()) {- tid = std::to_string(item["titleId"].asInt());- } else if (item["titleId"].isString()) {- tid = item["titleId"].str();- }- std::string displayImage = item["displayImage"].str();- if (displayImage.empty()) {- for (const auto& img : item["images"].items()) {- std::string t = img["type"].str();- if (t == "BoxArt" || t == "Poster" || t == "Logo") {- displayImage = img["url"].str();- if (!displayImage.empty()) break;- }+ if (!r.ok() || !j || !(*j)["titles"].isArray()) {+ return false;+ }+ for (const auto& item : (*j)["titles"].items()) {+ std::string tid;+ if (item["titleId"].isNumber()) {+ tid = std::to_string(item["titleId"].asInt());+ } else if (item["titleId"].isString()) {+ tid = item["titleId"].str();+ }+ std::string modernTid;+ if (item["modernTitleId"].isNumber()) {+ modernTid = std::to_string(item["modernTitleId"].asInt());+ } else if (item["modernTitleId"].isString()) {+ modernTid = item["modernTitleId"].str();+ }+ std::string displayImage = normalizeHttpsImageUrl(item["displayImage"].str());+ if (displayImage.empty()) {+ for (const auto& img : item["images"].items()) {+ std::string t = img["type"].str();+ if (t == "BoxArt" || t == "Poster" || t == "Tile" || t == "Logo" || t == "Hero") {+ displayImage = normalizeHttpsImageUrl(img["url"].str());+ if (!displayImage.empty()) break;}}- if (!tid.empty() && !displayImage.empty()) {- outImages[tid] = displayImage;- }+ }+ if (!displayImage.empty()) {+ if (!tid.empty()) outImages[tid] = displayImage;+ if (!modernTid.empty() && modernTid != "0") outImages[modernTid] = displayImage;+ }+ }+ return true;+ };++ // Process in batches of 80; if a batch fails, split into sub-batches of 16+ constexpr size_t kBatchSize = 80;+ for (size_t i = 0; i < titleIds.size(); i += kBatchSize) {+ size_t end = std::min(i + kBatchSize, titleIds.size());+ if (!runBatch(i, end) && (end - i) > 16) {+ for (size_t sub = i; sub < end; sub += 16) {+ runBatch(sub, std::min(sub + 16, end));}}}diff --git a/src/xcloud/catalog.cpp b/src/xcloud/catalog.cppindex 82b5080..a0b8fd0 100644--- a/src/xcloud/catalog.cpp+++ b/src/xcloud/catalog.cpp@@ -121,8 +121,8 @@ bool fetchProducts(const std::vector<std::string>& ids, const std::string& markeprod.xboxTitleId = p["XboxTitleId"].str();if (prod.xboxTitleId.empty()) prod.xboxTitleId = p["ChildXboxTitleIds"][0].str();prod.publisher = p["PublisherName"].str();- prod.description = p["ProductDescriptionShort"].str();- if (prod.description.empty()) prod.description = p["ProductDescription"].str();+ prod.description = p["ProductDescription"].str();+ if (prod.description.empty()) prod.description = p["ProductDescriptionShort"].str();prod.tileUrl = imageUrl(p["Image_Tile"]);prod.posterUrl = imageUrl(p["Image_Poster"]);prod.heroUrl = imageUrl(p["Image_Hero"]);diff --git a/tests/test_main.cpp b/tests/test_main.cppindex 4850236..e0dbbf1 100644--- a/tests/test_main.cpp+++ b/tests/test_main.cpp@@ -2410,17 +2410,17 @@ static void testVisibleSettingsRows() {CHECK(std::find(ps4Game.begin(), ps4Game.end(), 8) == ps4Game.end());CHECK(std::find(ps4Game.begin(), ps4Game.end(), 13) != ps4Game.end());// A game's settings.- CHECK((ids(ui::visibleGameSettingsRows(ps5, true, false)) == std::vector<int>{0, 4, 8, 15, 14, 1, 2, 3, 5, 6, 16, 7, 12, 11, 9, 10}));- CHECK((ids(ui::visibleGameSettingsRows(ps5, true, true)) == std::vector<int>{0, 4, 8, 15, 14, 1, 2, 3, 5, 6, 16, 7, 12, 11, 13, 9, 10}));+ CHECK((ids(ui::visibleGameSettingsRows(ps5, true, false)) == std::vector<int>{0, 4, 8, 15, 14, 18, 1, 2, 3, 5, 6, 16, 7, 12, 11, 9, 10}));+ CHECK((ids(ui::visibleGameSettingsRows(ps5, true, true)) == std::vector<int>{0, 4, 8, 15, 14, 18, 1, 2, 3, 5, 6, 16, 7, 12, 11, 13, 9, 10}));CHECK((groups(ui::visibleGameSettingsRows(ps5, true, true)) ==- std::vector<bool>{false, true, false, false, false, true, false, false, true, false, false, false, false, false, false, false, true}));- CHECK((ids(ui::visibleGameSettingsRows(ps5, false)) == std::vector<int>{0, 4, 8, 15, 14, 1, 2, 3, 5, 6, 16, 7, 12, 11, 9}));+ std::vector<bool>{false, true, false, false, false, false, true, false, false, true, false, false, false, false, false, false, false, true}));+ CHECK((ids(ui::visibleGameSettingsRows(ps5, false)) == std::vector<int>{0, 4, 8, 15, 14, 18, 1, 2, 3, 5, 6, 16, 7, 12, 11, 9}));ui::UiCaps noTouch = ps5;noTouch.touchpad = false;- CHECK((ids(ui::visibleGameSettingsRows(noTouch, true, true)) == std::vector<int>{0, 4, 8, 15, 14, 1, 2, 3, 5, 6, 16, 7, 12, 11, 9, 10}));+ CHECK((ids(ui::visibleGameSettingsRows(noTouch, true, true)) == std::vector<int>{0, 4, 8, 15, 14, 18, 1, 2, 3, 5, 6, 16, 7, 12, 11, 9, 10}));auto game = ui::visibleGameSettingsRows(pc, false);- CHECK((ids(game) == std::vector<int>{0, 4, 15, 14, 5, 7, 11, 9}));- CHECK((groups(game) == std::vector<bool>{false, true, false, false, true, false, false, false}));+ CHECK((ids(game) == std::vector<int>{0, 4, 15, 14, 18, 5, 7, 11, 9}));+ CHECK((groups(game) == std::vector<bool>{false, true, false, false, false, true, false, false, false}));// How far down the autoplay tests walk to each row (autoplay.cpp's downsTo).CHECK(ui::settingsRowPosition(ps5, 24) == 5);CHECK(ui::settingsRowPosition(ps5, 25) == 6);@@ -8156,11 +8156,800 @@ static void testTrophySystem() {::unlink(emptyAppInfoDb.c_str());::unlink((emptyAppInfoDb + ".bak").c_str());+ // 7. Test retail installed game protection in registerTitleInDatabase & removeTitleFromDatabase+ sqlite3* rDb = nullptr;+ CHECK(sqlite3_open(testAppDb.c_str(), &rDb) == SQLITE_OK);+ CHECK(sqlite3_exec(rDb, "INSERT OR REPLACE INTO tbl_contentinfo (titleId, titleName, contentId, conceptId, localConceptId, dispLocation, appType, uiCategory, metaDataPath, icon0Info, pic0Info, snd0Info, pprDeeplinkUri, pprHubAppUri, AppInfoJson) VALUES ('PPSA07950', 'Call of Duty Retail', 'UP0001-PPSA07950_00-COD', 1, '1', 5, 0, 'game', '/user/appmeta/PPSA07950', '/user/appmeta/PPSA07950/icon0.png', '', '', '', '', '{\"visible\":1}');", nullptr, nullptr, nullptr) == SQLITE_OK);+ sqlite3_close(rDb);+ TitleDbInfo codCloudInfo = makeTitleDbInfo("PPSA07950", "Call of Duty Cloud Override");+ CHECK(registerTitleInDatabase(codCloudInfo, testAppDb, testAppInfoDb));+ // Verify dispLocation (5) and titleName ('Call of Duty Retail') were NOT overwritten!+ CHECK(sqlite3_open(testAppDb.c_str(), &rDb) == SQLITE_OK);+ CHECK(sqlite3_prepare_v2(rDb, "SELECT titleName, dispLocation FROM tbl_contentinfo WHERE titleId = 'PPSA07950';", -1, &testStmt, nullptr) == SQLITE_OK);+ CHECK(sqlite3_step(testStmt) == SQLITE_ROW);+ CHECK(std::string(reinterpret_cast<const char*>(sqlite3_column_text(testStmt, 0))) == "Call of Duty Retail");+ CHECK(sqlite3_column_int(testStmt, 1) == 5);+ sqlite3_finalize(testStmt);+ sqlite3_close(rDb);+ // Verify removeTitleFromDatabase also refuses to delete a retail installed game!+ CHECK(removeTitleFromDatabase("PPSA07950", testAppDb, testAppInfoDb));+ CHECK(sqlite3_open(testAppDb.c_str(), &rDb) == SQLITE_OK);+ CHECK(sqlite3_prepare_v2(rDb, "SELECT dispLocation FROM tbl_contentinfo WHERE titleId = 'PPSA07950';", -1, &testStmt, nullptr) == SQLITE_OK);+ CHECK(sqlite3_step(testStmt) == SQLITE_ROW);+ CHECK(sqlite3_column_int(testStmt, 0) == 5);+ sqlite3_finalize(testStmt);+ sqlite3_close(rDb);+// Clean up mock database files::unlink(testAppDb.c_str());::unlink((testAppDb + ".bak").c_str());::unlink(testAppInfoDb.c_str());::unlink((testAppInfoDb + ".bak").c_str());++ // 8. Test strictly additive buildTrpTitleDat merging (local disk trophies + cloud trophies)+ {+ TitleTrophySet localSet;+ localSet.xboxTitleId = "99999";+ localSet.titleName = "Call of Duty";+ localSet.sonyTitleId = "PPSA07950";+ localSet.npCommId = "NPWR25180_00";+ for (int i = 1; i <= 4; ++i) {+ TrophyDef it;+ it.trophyId = i;+ it.name = "Trophy " + std::to_string(i);+ it.grade = TrophyGrade::Bronze;+ it.unlocked = (i <= 2); // Local disk has trophies 1 and 2 unlocked+ it.timeUnlocked = (i <= 2) ? "2024-11-15T10:20:30Z" : "";+ localSet.items.push_back(it);+ }+ uint8_t dummyHash[20] = {1, 2, 3};+ std::vector<uint8_t> initialDat;+ CHECK(buildTrpTitleDat(localSet, 0x1ea2f4da, initialDat, dummyHash, nullptr));+ std::map<uint32_t, ExistingTrophyRecord> parsedDisk;+ CHECK(parseTrpTitleDat(initialDat.data(), initialDat.size(), parsedDisk));+ CHECK(parsedDisk.size() == 5); // Plat + 4 base+ CHECK(parsedDisk[1].state == 1 && parsedDisk[2].state == 1);+ CHECK(parsedDisk[3].state == 0 && parsedDisk[4].state == 0);+ uint64_t origTs1 = parsedDisk[1].timestamp;+ CHECK(origTs1 > 0x00dcbffeef82bc00ULL);++ // Now simulate cloud sync where only trophy 3 is unlocked on Xbox (and cloud only knows 3 items, missing trophy 4!)+ TitleTrophySet cloudSet = localSet;+ cloudSet.items.resize(3); // Cloud has fewer items than local disk+ cloudSet.items[0].unlocked = false; // Trophy 1 NOT unlocked on Xbox cloud+ cloudSet.items[0].timeUnlocked.clear();+ cloudSet.items[1].unlocked = false; // Trophy 2 NOT unlocked on Xbox cloud+ cloudSet.items[1].timeUnlocked.clear();+ cloudSet.items[2].unlocked = true; // Trophy 3 unlocked on Xbox cloud!+ cloudSet.items[2].timeUnlocked = "2025-06-01T18:00:00Z";++ std::vector<uint8_t> mergedDat;+ CHECK(buildTrpTitleDat(cloudSet, 0x1ea2f4da, mergedDat, dummyHash, &initialDat));+ std::map<uint32_t, ExistingTrophyRecord> mergedRecords;+ CHECK(parseTrpTitleDat(mergedDat.data(), mergedDat.size(), mergedRecords));+ // Must preserve all 5 records (Plat + 1..4), keep 1 & 2 unlocked with original timestamp, and unlock 3!+ CHECK(mergedRecords.size() == 5);+ CHECK(mergedRecords[1].state == 1);+ CHECK(mergedRecords[1].timestamp == origTs1);+ CHECK(mergedRecords[2].state == 1);+ CHECK(mergedRecords[3].state == 1);+ CHECK(mergedRecords[4].state == 0);+ CHECK(mergedRecords[0].state == 0); // Platinum still locked because 4 is locked++ // Unlock trophy 4 in cloud -> union of disk (1,2,3) + cloud (4) = 100% -> Platinum auto-unlocks!+ cloudSet.items = localSet.items;+ cloudSet.items[0].unlocked = false;+ cloudSet.items[1].unlocked = false;+ cloudSet.items[2].unlocked = false;+ cloudSet.items[3].unlocked = true;+ cloudSet.items[3].timeUnlocked = "2025-06-02T12:00:00Z";+ std::vector<uint8_t> fullDat;+ CHECK(buildTrpTitleDat(cloudSet, 0x1ea2f4da, fullDat, dummyHash, &mergedDat));+ std::map<uint32_t, ExistingTrophyRecord> fullRecords;+ CHECK(parseTrpTitleDat(fullDat.data(), fullDat.size(), fullRecords));+ CHECK(fullRecords.size() == 5);+ for (uint32_t id = 0; id <= 4; ++id) {+ CHECK(fullRecords[id].state == 1);+ }+ }++ // 9. Test >127 achievements cap in resolveTitleSet (prioritizing unlocked achievements)+ {+ std::vector<xcloud::Achievement> hugeAch;+ for (int i = 1; i <= 150; ++i) {+ xcloud::Achievement a;+ a.id = std::to_string(i);+ a.name = "Ach " + std::to_string(i);+ a.gamerscore = 10;+ a.unlocked = (i > 100); // 50 unlocked achievements at the end (101..150)+ a.timeUnlocked = a.unlocked ? "2025-05-10T14:30:00Z" : "";+ hugeAch.push_back(a);+ }+ auto cappedSet = resolveTitleSet("88888888", "", "Master Chief Collection", hugeAch);+ CHECK(cappedSet.items.size() == 127); // 127 base trophies (1..127) + Platinum (0) in UCP/TRPTITLE = 128 max+ int unlockedBaseInSet = 0;+ for (const auto& item : cappedSet.items) {+ CHECK(item.trophyId >= 1 && item.trophyId <= 127);+ if (item.unlocked) {+ unlockedBaseInSet++;+ CHECK(!item.timeUnlocked.empty());+ }+ }+ CHECK(unlockedBaseInSet == 50); // All 50 unlocked achievements preserved!+ // Verify base-game achievements 1..77 keep their exact 1..77 trophyId positions+ for (size_t i = 0; i < 77; ++i) {+ CHECK(cappedSet.items[i].name == "Ach " + std::to_string(i + 1));+ }+ uint8_t dummyHash[20] = {9, 8, 7};+ std::vector<uint8_t> cappedDat;+ CHECK(buildTrpTitleDat(cappedSet, 0x1ea2f4da, cappedDat, dummyHash, nullptr));+ std::map<uint32_t, ExistingTrophyRecord> cappedRecords;+ CHECK(parseTrpTitleDat(cappedDat.data(), cappedDat.size(), cappedRecords));+ CHECK(cappedRecords.size() == 128); // Platinum (0) + 127 base trophies (1..127)++ // Now unlock achievement #5 (a base-game achievement) and re-run resolveTitleSet + buildTrpTitleDat+ // with existingDat = &cappedDat: must have 51 unlocked trophies (not shifted/duplicated)!+ hugeAch[4].unlocked = true;+ hugeAch[4].timeUnlocked = "2025-05-11T10:00:00Z";+ auto cappedSet2 = resolveTitleSet("88888888", "", "Master Chief Collection", hugeAch);+ std::vector<uint8_t> cappedDat2;+ CHECK(buildTrpTitleDat(cappedSet2, 0x1ea2f4da, cappedDat2, dummyHash, &cappedDat));+ std::map<uint32_t, ExistingTrophyRecord> cappedRecords2;+ CHECK(parseTrpTitleDat(cappedDat2.data(), cappedDat2.size(), cappedRecords2));+ int unlockedInDat2 = 0;+ for (const auto& [tid, rec] : cappedRecords2) {+ if (rec.state == 1) unlockedInDat2++;+ }+ CHECK(unlockedInDat2 == 51);+ }++ // 10. Test per-game syncTrophies setting persistence+ {+ std::string pgPath = "/tmp/test_pergame_trophies.json";+ ::unlink(pgPath.c_str());+ app::Settings s1;+ app::GameProfile balatroProf = s1.defaultProfile();+ balatroProf.syncTrophies = false;+ balatroProf.xboxTitleId = "777777";+ balatroProf.gameName = "Balatro";+ s1.perGame["BALATRO_PROD"] = balatroProf;+ CHECK(s1.save(pgPath));++ app::Settings s2;+ CHECK(s2.load(pgPath));+ bool hasCustom = false;+ auto loadedProf = s2.profileForGame("BALATRO_PROD", "", &hasCustom);+ CHECK(hasCustom);+ CHECK(!loadedProf.syncTrophies);+ CHECK(loadedProf.xboxTitleId == "777777");+ CHECK(loadedProf.gameName == "Balatro");+ ::unlink(pgPath.c_str());+ }++ // 11. Test Decoupled g_trophyThread Lifecycle, Priority Queue & Fast-Path Preemption (R1-R5)+ {+ net::setTestTransport([&](const net::Request& req) -> net::Response {+ net::Response res;+ res.status = 200;+ if (req.url.find("history/titles") != std::string::npos) {+ res.body = R"({+ "titles": [+ {"titleId": "267695549", "name": "Fortnite", "displayImage": "https://img/fn.png", "achievement": {"currentAchievements": 5, "currentGamerscore": 100}},+ {"titleId": "182830000", "name": "Minecraft", "displayImage": "https://img/mc.png", "achievement": {"currentAchievements": 10, "currentGamerscore": 200}}+ ]+ })";+ } else if (req.url.find("achievements.xboxlive.com") != std::string::npos) {+ res.body = R"({+ "achievements": [+ {"id": "1", "name": "Test Ach", "progressState": "Achieved", "rewards": [{"type": "Gamerscore", "value": "10"}]}+ ]+ })";+ } else if (req.url.find("titlehub.xboxlive.com") != std::string::npos) {+ res.body = R"({"titles": []})";+ }+ return res;+ });++ // Thread start+ trophy::startTrophyThread();+ CHECK(!trophy::isSyncing());+ CHECK(trophy::titlesDone() == 0);+ CHECK(trophy::titlesTotal() == 0);++ // Urgent stream poll fast-path+ CHECK(trophy::dispatchStreamPoll("Bearer tok", "12345", "267695549", "Fortnite", "https://img/fn.png"));+ platform::sleepMs(80);++ // Batch sync dispatch+ trophy::requestTrophySync("Bearer tok", "12345", {}, true);+ platform::sleepMs(80);++ // Cancellation+ trophy::cancelTrophySync();+ platform::sleepMs(50);++ // Clean shutdown+ CHECK(trophy::stopTrophyThread(3000));+ net::setTestTransport({});+ }+}++static void testTrophyNetworkAndLifecycleResilienceStress() {+ XC_LOGI("--- Starting Trophy Network Fault & Lifecycle Resilience Stress Test ---");++ auto setupBaseMock = [](std::function<net::Response(const net::Request&)> customAchHandler,+ std::function<net::Response(const net::Request&)> customProbeHandler = nullptr) {+ net::setTestTransport([customAchHandler, customProbeHandler](const net::Request& req) -> net::Response {+ net::Response res;+ res.status = 200;+ if (req.url.find("history/titles") != std::string::npos) {+ res.body = R"({+ "titles": [+ {"titleId": "267695549", "name": "Fortnite", "displayImage": "https://img/fn.png", "achievement": {"currentAchievements": 5, "currentGamerscore": 100}}+ ]+ })";+ return res;+ }+ if (req.url.find("titlehub.xboxlive.com") != std::string::npos) {+ res.body = R"({"titles": []})";+ return res;+ }+ if (req.url.find("login.live.com") != std::string::npos) {+ if (customProbeHandler) return customProbeHandler(req);+ res.body = "OK";+ return res;+ }+ if (req.url.find("achievements.xboxlive.com") != std::string::npos) {+ if (customAchHandler) return customAchHandler(req);+ res.body = R"({+ "achievements": [+ {"id": "1", "name": "Test Ach", "progressState": "Achieved", "rewards": [{"type": "Gamerscore", "value": "10"}]}+ ]+ })";+ return res;+ }+ return res;+ });+ };++ auto cleanCache = []() {+ std::string cPath = trophy::syncEngine().trophyCachePath("267695549");+ ::unlink(cPath.c_str());+ };++ // Sub-test 1: 1 failure -> 1s exponential backoff -> success+ {+ cleanCache();+ std::atomic<int> achCalls{0};+ std::atomic<bool> achSuccess{false};+ setupBaseMock([&](const net::Request&) -> net::Response {+ int c = achCalls.fetch_add(1);+ net::Response res;+ if (c == 0) {+ res.status = 500;+ res.error = "HTTP 500: Internal Server Error";+ res.body = "Internal Server Error";+ } else {+ res.status = 200;+ res.body = R"({+ "achievements": [+ {"id": "1", "name": "Test Ach 1", "progressState": "Achieved", "rewards": [{"type": "Gamerscore", "value": "10"}]}+ ]+ })";+ achSuccess.store(true);+ }+ return res;+ });++ trophy::startTrophyThread();+ uint64_t t0 = platform::nowMs();+ trophy::requestTrophySync("Bearer tok", "12345", {}, true);++ while (!achSuccess.load() && platform::nowMs() - t0 < 4000) {+ platform::sleepMs(20);+ }+ uint64_t elapsed = platform::nowMs() - t0;+ CHECK(achSuccess.load());+ CHECK(achCalls.load() == 2);+ CHECK(elapsed >= 950 && elapsed <= 2500); // 1s backoff verified empirically+ XC_LOGI("Stress Test: Sub-test 1 passed in %llu ms (achCalls=%d)",+ static_cast<unsigned long long>(elapsed), achCalls.load());+ CHECK(trophy::stopTrophyThread(3000));+ }++ // Sub-test 2: 2 failures -> 1s + 2s = 3s backoff -> success+ {+ cleanCache();+ std::atomic<int> achCalls{0};+ std::atomic<bool> achSuccess{false};+ setupBaseMock([&](const net::Request&) -> net::Response {+ int c = achCalls.fetch_add(1);+ net::Response res;+ if (c < 2) {+ res.status = 429;+ res.error = "HTTP 429: Too Many Requests";+ res.body = "Too Many Requests";+ } else {+ res.status = 200;+ res.body = R"({+ "achievements": [+ {"id": "1", "name": "Test Ach 2", "progressState": "Achieved", "rewards": [{"type": "Gamerscore", "value": "10"}]}+ ]+ })";+ achSuccess.store(true);+ }+ return res;+ });++ trophy::startTrophyThread();+ uint64_t t0 = platform::nowMs();+ trophy::requestTrophySync("Bearer tok", "12345", {}, true);++ while (!achSuccess.load() && platform::nowMs() - t0 < 6000) {+ platform::sleepMs(20);+ }+ uint64_t elapsed = platform::nowMs() - t0;+ CHECK(achSuccess.load());+ CHECK(achCalls.load() == 3);+ CHECK(elapsed >= 2950 && elapsed <= 4800); // 1s + 2s = 3s backoff verified empirically+ XC_LOGI("Stress Test: Sub-test 2 passed in %llu ms (achCalls=%d)",+ static_cast<unsigned long long>(elapsed), achCalls.load());+ CHECK(trophy::stopTrophyThread(3000));+ }++ // Sub-test 3: 3 failures -> 1s + 2s + 4s = 7s backoff -> success on attempt 3+ {+ cleanCache();+ std::atomic<int> achCalls{0};+ std::atomic<bool> achSuccess{false};+ setupBaseMock([&](const net::Request&) -> net::Response {+ int c = achCalls.fetch_add(1);+ net::Response res;+ if (c < 3) {+ res.status = 503;+ res.error = "HTTP 503: Service Unavailable";+ res.body = "Service Unavailable";+ } else {+ res.status = 200;+ res.body = R"({+ "achievements": [+ {"id": "1", "name": "Test Ach 3", "progressState": "Achieved", "rewards": [{"type": "Gamerscore", "value": "10"}]}+ ]+ })";+ achSuccess.store(true);+ }+ return res;+ });++ trophy::startTrophyThread();+ uint64_t t0 = platform::nowMs();+ trophy::requestTrophySync("Bearer tok", "12345", {}, true);++ while (!achSuccess.load() && platform::nowMs() - t0 < 10000) {+ platform::sleepMs(20);+ }+ uint64_t elapsed = platform::nowMs() - t0;+ CHECK(achSuccess.load());+ CHECK(achCalls.load() == 4);+ CHECK(elapsed >= 6950 && elapsed <= 9200); // 1s + 2s + 4s = 7s backoff verified empirically+ XC_LOGI("Stress Test: Sub-test 3 passed in %llu ms (achCalls=%d)",+ static_cast<unsigned long long>(elapsed), achCalls.load());+ CHECK(trophy::stopTrophyThread(3000));+ }++ // Sub-test 4: Network Outage -> PausedWaitingForNetwork -> Periodic Probe -> Reconnect & Recovery+ {+ cleanCache();+ std::atomic<int> achCalls{0};+ std::atomic<int> probeCalls{0};+ std::atomic<bool> networkOnline{false};+ std::atomic<bool> achSuccess{false};+ std::vector<uint64_t> probeTimes;+ std::mutex probeMutex;++ setupBaseMock([&](const net::Request&) -> net::Response {+ achCalls.fetch_add(1);+ net::Response res;+ if (!networkOnline.load()) {+ res.status = 0;+ res.error = "HTTP 0: Connection reset by peer";+ res.body = "";+ } else {+ res.status = 200;+ res.body = R"({+ "achievements": [+ {"id": "1", "name": "Test Ach Reconnected", "progressState": "Achieved", "rewards": [{"type": "Gamerscore", "value": "10"}]}+ ]+ })";+ achSuccess.store(true);+ }+ return res;+ }, [&](const net::Request&) -> net::Response {+ probeCalls.fetch_add(1);+ {+ std::lock_guard<std::mutex> lock(probeMutex);+ probeTimes.push_back(platform::nowMs());+ }+ net::Response res;+ if (!networkOnline.load()) {+ res.status = 0;+ res.error = "HTTP 0: Connection refused";+ } else {+ res.status = 200;+ res.body = "OK";+ }+ return res;+ });++ trophy::startTrophyThread();+ uint64_t t0 = platform::nowMs();+ trophy::requestTrophySync("Bearer tok", "12345", {}, true);++ // Wait for all 4 initial attempts (1s + 2s + 4s = 7s) and at least 2 network probes (~4s)+ while (probeCalls.load() < 2 && platform::nowMs() - t0 < 15000) {+ platform::sleepMs(50);+ }+ CHECK(probeCalls.load() >= 2);+ CHECK(!achSuccess.load()); // Title must NOT have finished yet+ CHECK(trophy::isSyncing()); // Thread is still actively paused waiting for network++ // Verify probe frequency (~2s interval)+ {+ std::lock_guard<std::mutex> lock(probeMutex);+ if (probeTimes.size() >= 2) {+ uint64_t diff = probeTimes[1] - probeTimes[0];+ CHECK(diff >= 1800 && diff <= 2500); // 2s probe pacing verified without busy-spin+ XC_LOGI("Stress Test: Network probe interval verified: %llu ms", static_cast<unsigned long long>(diff));+ }+ }++ // Simulate network restoration+ networkOnline.store(true);++ uint64_t recStart = platform::nowMs();+ while (!achSuccess.load() && platform::nowMs() - recStart < 6000) {+ platform::sleepMs(50);+ }+ CHECK(achSuccess.load()); // Seamless resumption verified without title loss!+ XC_LOGI("Stress Test: Sub-test 4 passed (resumed in %llu ms after network restored)",+ static_cast<unsigned long long>(platform::nowMs() - recStart));+ CHECK(trophy::stopTrophyThread(3000));+ }++ // Sub-test 5: Cancellation / Shutdown Responsiveness during 4s Backoff Sleep+ {+ cleanCache();+ std::atomic<int> achCalls{0};+ setupBaseMock([&](const net::Request&) -> net::Response {+ achCalls.fetch_add(1);+ net::Response res;+ res.status = 500;+ res.error = "HTTP 500: Fail";+ res.body = "Fail";+ return res;+ });++ trophy::startTrophyThread();+ trophy::requestTrophySync("Bearer tok", "12345", {}, true);++ while (achCalls.load() < 3) {+ platform::sleepMs(50);+ }+ platform::sleepMs(200);++ uint64_t stopStart = platform::nowMs();+ bool stoppedOk = trophy::stopTrophyThread(3000);+ uint64_t stopDuration = platform::nowMs() - stopStart;++ CHECK(stoppedOk);+ CHECK(stopDuration < 400); // Wakes up immediately from CV wait!+ XC_LOGI("Stress Test: Sub-test 5 passed (stopped in %llu ms during 4s backoff sleep)",+ static_cast<unsigned long long>(stopDuration));+ }++ // Sub-test 6: cancelTrophySync Responsiveness during PausedWaitingForNetwork+ {+ cleanCache();+ std::atomic<int> probeCalls{0};+ setupBaseMock([&](const net::Request&) -> net::Response {+ net::Response res;+ res.status = 0;+ res.error = "HTTP 0: Connection refused";+ return res;+ }, [&](const net::Request&) -> net::Response {+ probeCalls.fetch_add(1);+ net::Response res;+ res.status = 0;+ res.error = "HTTP 0: Connection refused";+ return res;+ });++ trophy::startTrophyThread();+ trophy::requestTrophySync("Bearer tok", "12345", {}, true);++ while (probeCalls.load() < 1) {+ platform::sleepMs(50);+ }++ uint64_t cancelStart = platform::nowMs();+ trophy::cancelTrophySync();++ while (trophy::isSyncing() && platform::nowMs() - cancelStart < 2000) {+ platform::sleepMs(20);+ }+ uint64_t cancelDuration = platform::nowMs() - cancelStart;++ CHECK(!trophy::isSyncing());+ CHECK(cancelDuration < 500); // Wakes up immediately from 2s probe sleep!+ XC_LOGI("Stress Test: Sub-test 6 passed (cancelled in %llu ms from probe sleep)",+ static_cast<unsigned long long>(cancelDuration));+ CHECK(trophy::stopTrophyThread(3000));+ }++ // Sub-test 7: Concurrency & Lock Contention under PausedWaitingForNetwork+ {+ cleanCache();+ std::atomic<int> probeCalls{0};+ std::atomic<bool> inProbe{false};+ std::atomic<bool> holdProbe{true};++ setupBaseMock([&](const net::Request&) -> net::Response {+ net::Response res;+ res.status = 0;+ res.error = "HTTP 0: Connection lost";+ return res;+ }, [&](const net::Request&) -> net::Response {+ probeCalls.fetch_add(1);+ inProbe.store(true);+ uint64_t ps = platform::nowMs();+ while (holdProbe.load() && platform::nowMs() - ps < 500) {+ platform::sleepMs(10);+ }+ inProbe.store(false);+ net::Response res;+ res.status = 0;+ res.error = "HTTP 0: Probe failed";+ return res;+ });++ trophy::startTrophyThread();+ trophy::requestTrophySync("Bearer tok", "12345", {}, true);++ while (!inProbe.load()) {+ platform::sleepMs(20);+ }++ uint64_t pollStart = platform::nowMs();+ bool pollDispatched = trophy::dispatchStreamPoll("Bearer tok", "12345", "182830000", "Minecraft", "https://img/mc.png");+ uint64_t pollDuration = platform::nowMs() - pollStart;++ XC_LOGI("Stress Test: Sub-test 7: dispatchStreamPoll during probe took %llu ms (dispatched=%d)",+ static_cast<unsigned long long>(pollDuration), pollDispatched ? 1 : 0);++ holdProbe.store(false);+ trophy::cancelTrophySync();+ trophy::stopTrophyThread(3000);++ CHECK(pollDispatched);+ CHECK(pollDuration < 100);+ // We log whether dispatchStreamPoll was delayed by g_trophyQueueMutex contention+ if (pollDuration >= 200) {+ XC_LOGW("CRITICAL FINDING: dispatchStreamPoll was blocked for %llu ms because g_trophyQueueMutex was held during probeNetworkConnectivity()!",+ static_cast<unsigned long long>(pollDuration));+ } else {+ XC_LOGI("dispatchStreamPoll completed without queue lock contention (%llu ms)",+ static_cast<unsigned long long>(pollDuration));+ }+ }++ // Sub-test 8: requestRemoveTrophies() Preemption & Execution during Active Sync+ {+ cleanCache();+ class TestRemoveBackend : public trophy::ITrophyBackend {+ public:+ std::atomic<int> removeCalls{0};+ bool init(uint32_t) override { return true; }+ bool registerTitle(const trophy::TitleTrophySet&) override { return true; }+ bool unlockTrophy(const std::string&, int, trophy::TrophyGrade, const std::string&) override { return true; }+ bool isTrophyUnlocked(const std::string&, int) override { return false; }+ bool removeAllTrophies(const std::vector<std::pair<std::string, std::string>>& titles,+ int& removedCount, std::string& err) override {+ removeCalls++;+ removedCount = static_cast<int>(titles.size());+ return true;+ }+ std::string name() const override { return "TestRemoveBackend"; }+ };++ auto backend = std::make_unique<TestRemoveBackend>();+ auto* rawBackend = backend.get();+ trophy::syncEngine().setBackend(std::move(backend));++ std::atomic<bool> syncStarted{false};+ setupBaseMock([&](const net::Request&) -> net::Response {+ syncStarted.store(true);+ net::Response res;+ res.status = 0;+ res.error = "HTTP 0: Connection lost";+ return res;+ });++ trophy::startTrophyThread();+ trophy::requestTrophySync("Bearer tok", "12345", {}, true);++ while (!syncStarted.load()) {+ platform::sleepMs(20);+ }+ platform::sleepMs(50); // Ensure thread entered backoff wait_for++ // Invoke requestRemoveTrophies while sync is retrying+ trophy::requestRemoveTrophies();++ uint64_t remWaitStart = platform::nowMs();+ while ((rawBackend->removeCalls.load() == 0 || trophy::isSyncing()) && platform::nowMs() - remWaitStart < 2000) {+ platform::sleepMs(20);+ }++ CHECK(rawBackend->removeCalls.load() > 0);+ CHECK(!trophy::isSyncing());++ CHECK(trophy::stopTrophyThread(3000));+ trophy::syncEngine().setBackend(nullptr);+ XC_LOGI("Stress Test: Sub-test 8 passed (requestRemoveTrophies executed during sync)");+ }++ // Sub-test 9: Thread Shutdown Timeout Safety and Re-entry Handle Cleanup+ {+ cleanCache();+ std::atomic<bool> inHangingCall{false};+ std::atomic<bool> releaseHang{false};++ setupBaseMock([&](const net::Request&) -> net::Response {+ inHangingCall.store(true);+ while (!releaseHang.load()) {+ platform::sleepMs(10);+ }+ net::Response res;+ res.status = 200;+ res.body = R"({"achievements": []})";+ return res;+ });++ trophy::startTrophyThread();+ trophy::requestTrophySync("Bearer tok", "12345", {}, true);++ // Wait until thread enters the hanging socket call+ while (!inHangingCall.load()) {+ platform::sleepMs(20);+ }++ // Bounded timeout check: stopTrophyThread(150) must return false without hanging in pthread_join+ uint64_t stopStart = platform::nowMs();+ bool stopped = trophy::stopTrophyThread(150);+ uint64_t stopDuration = platform::nowMs() - stopStart;++ CHECK(!stopped);+ CHECK(stopDuration >= 140 && stopDuration < 500);+ XC_LOGI("Stress Test: Sub-test 9 passed bounded timeout check in %llu ms",+ static_cast<unsigned long long>(stopDuration));++ // Release the hanging call to let thread terminate+ releaseHang.store(true);++ uint64_t exitWait = platform::nowMs();+ while (trophy::isSyncing() && platform::nowMs() - exitWait < 1000) {+ platform::sleepMs(20);+ }++ // Test thread re-entry: startTrophyThread reaps dead unjoined handle and starts new thread cleanly+ trophy::startTrophyThread();++ CHECK(trophy::stopTrophyThread(3000));+ net::setTestTransport({});+ XC_LOGI("Stress Test: Sub-test 9 passed re-entry cleanup and final stop");+ }++ net::setTestTransport({});+ XC_LOGI("--- Trophy Network Fault & Lifecycle Resilience Stress Test Complete ---");+}++static void testTrophyStreamingPauseAndPriority() {+ XC_LOGI("--- Starting Trophy Streaming Pause & Urgent Preemption Test ---");++ // Clean cache+ std::string cPath = trophy::syncEngine().trophyCachePath("267695549");+ ::unlink(cPath.c_str());+ std::string cPath2 = trophy::syncEngine().trophyCachePath("182830000");+ ::unlink(cPath2.c_str());++ std::atomic<bool> isStreaming{true};+ std::atomic<int> pollExecCount{0};+ std::atomic<int> batchExecCount{0};++ net::setTestTransport([&](const net::Request& req) -> net::Response {+ net::Response res;+ res.status = 200;+ if (req.url.find("history/titles") != std::string::npos) {+ res.body = R"({+ "titles": [+ {"titleId": "267695549", "name": "Fortnite", "titleType": "Game", "displayImage": "https://img/fn.png", "earnedAchievements": 5, "currentGamerscore": 100},+ {"titleId": "182830000", "name": "Minecraft", "titleType": "Game", "displayImage": "https://img/mc.png", "earnedAchievements": 10, "currentGamerscore": 200}+ ]+ })";+ return res;+ }+ if (req.url.find("titlehub.xboxlive.com") != std::string::npos) {+ res.body = R"({"titles": []})";+ return res;+ }+ if (req.url.find("achievements.xboxlive.com") != std::string::npos) {+ if (req.url.find("267695549") != std::string::npos) {+ pollExecCount.fetch_add(1);+ }+ batchExecCount.fetch_add(1);+ res.body = R"({+ "achievements": [+ {"id": "1", "name": "Test Ach", "progressState": "Achieved", "rewards": [{"type": "Gamerscore", "value": "10"}]}+ ]+ })";+ return res;+ }+ res.status = 404;+ return res;+ });++ trophy::setTrophyContextProvider([&](trophy::TrophySyncContext& ctx) {+ ctx.xblAuth = "Bearer testToken";+ ctx.xuid = "12345678";+ ctx.isStreaming = [&] { return isStreaming.load(); };+ return true;+ });++ trophy::startTrophyThread();++ // 1. Dispatch batch sync while streaming is active+ isStreaming.store(true);+ trophy::requestTrophySync(true);++ // Give thread time to discover and encounter pause condition+ platform::sleepMs(200);++ // Because isStreaming is true, batch title execution must be paused!+ CHECK(trophy::titlesDone() == 0);++ // 2. Urgent stream poll must execute immediately even while batch is paused+ int pollsBefore = pollExecCount.load();+ CHECK(trophy::dispatchStreamPoll("Bearer testToken", "12345678", "267695549", "Fortnite", "https://img/fn.png"));++ // Wait for urgent poll to execute+ for (int i = 0; i < 20; ++i) {+ if (pollExecCount.load() > pollsBefore) break;+ platform::sleepMs(15);+ }+ CHECK(pollExecCount.load() > pollsBefore);++ // Batch title sync must STILL be paused (titlesDone == 0)+ CHECK(trophy::titlesDone() == 0);++ // 3. Resume trophy sync by exiting stream mode+ isStreaming.store(false);+ trophy::resumeTrophySync();++ // Wait for batch sync to resume and process both titles without dropping any task+ for (int i = 0; i < 50; ++i) {+ if (trophy::titlesDone() >= 2 && !trophy::isSyncing()) break;+ platform::sleepMs(20);+ }+ CHECK(trophy::titlesDone() >= 2);+ CHECK(!trophy::isSyncing());++ // Clean shutdown+ CHECK(trophy::stopTrophyThread(3000));+ trophy::setTrophyContextProvider({});+ net::setTestTransport({});+ ::unlink(cPath.c_str());+ ::unlink(cPath2.c_str());+ XC_LOGI("--- Trophy Streaming Pause & Urgent Preemption Test Complete ---");}static void testTrophyModalsAndDesktopInput() {@@ -8274,6 +9063,8 @@ static void testTrophyModalsAndDesktopInput() {int main() {testPs4VideoPipelineAndSse2Converter();testTrophySystem();+ testTrophyNetworkAndLifecycleResilienceStress();+ testTrophyStreamingPauseAndPriority();testTrophyModalsAndDesktopInput();testReleaseV155Features();testSizedUrl();diff --git a/tools/ps5/package.sh b/tools/ps5/package.shindex 48db0f0..12d71d0 100755--- a/tools/ps5/package.sh+++ b/tools/ps5/package.sh@@ -28,6 +28,10 @@ for f in pic0.dds pic1.dds snd0.at9; dodonecp "$vk/runtime/libc.prx" "$app/sce_module/libc.prx"cp -r "$root/assets/." "$app/assets/"+trophy_elf="$root/tools/ps5/payload_patch_test/PSBox_Trophies.elf"+[[ -f "$trophy_elf" ]] || { echo "missing $trophy_elf" >&2; exit 2; }+cp "$trophy_elf" "$app/assets/PSBox_Trophies.elf"+chmod 0777 "$app/assets/PSBox_Trophies.elf"# README.txt for users, LICENSE, and the license texts of everything in the# package (see THIRD_PARTY_NOTICES.md). XC_VERSION names the release.diff --git a/tools/ps5/payload_patch_test/Makefile b/tools/ps5/payload_patch_test/Makefileindex 592cdca..cf8eaea 100644--- a/tools/ps5/payload_patch_test/Makefile+++ b/tools/ps5/payload_patch_test/Makefile@@ -4,13 +4,13 @@ endifinclude $(PS5_PAYLOAD_SDK)/toolchain/prospero.mk-CFLAGS := -std=c11 -O2 -g -Wall -Wextra+CFLAGS := -std=c11 -O2 -Wall -WextraLDLIBS := -lkernel -lSceSystemService -lSceUserService -lpthread-all: patch_test.elf+all: PSBox_Trophies.elf-patch_test.elf: main.c+PSBox_Trophies.elf: main.c$(CC) $(CFLAGS) -o $@ main.c $(LDLIBS)clean:- rm -f patch_test.elf+ rm -f PSBox_Trophies.elf patch_test.elfdiff --git a/tools/ps5/payload_patch_test/patch_test.elf b/tools/ps5/payload_patch_test/PSBox_Trophies.elfsimilarity index 55%rename from tools/ps5/payload_patch_test/patch_test.elfrename to tools/ps5/payload_patch_test/PSBox_Trophies.elfindex a00bbf9..b479907 100755Binary files a/tools/ps5/payload_patch_test/patch_test.elf and b/tools/ps5/payload_patch_test/PSBox_Trophies.elf differdiff --git a/tools/ps5/payload_patch_test/main.c b/tools/ps5/payload_patch_test/main.cindex 4ae196a..5221a38 100644--- a/tools/ps5/payload_patch_test/main.c+++ b/tools/ps5/payload_patch_test/main.c@@ -196,6 +196,8 @@ int main(void) {}// 2. Trophy directory permissions+ mkdir("/data/psbox", 0777);+ chmod("/data/psbox", 0777);chmod("/user/trophy2", 0777);chmod("/user/trophy2/nobackup", 0777);chmod("/user/trophy2/nobackup/conf", 0777);@@ -207,6 +209,10 @@ int main(void) {chmod("/user/home/1ea2f4da/trophy2/nobackup/data", 0777);chmod("/user/home/1ea2f4da/trophy2/nobackup/data/NPWR20561_00", 0777);chmod("/user/home/1ea2f4da/trophy2/nobackup/data/NPWR20561_00/TRPTITLE.DAT", 0666);+ chmod("/system_data/priv/mms", 0777);+ chmod("/system_data/priv/mms/app.db", 0666);+ chmod("/system_data/priv/mms/app.db-wal", 0666);+ chmod("/system_data/priv/mms/app.db-shm", 0666);pid_t pid = find_process_by_name("SceShellCore");intptr_t mapbase = get_process_mapbase(pid);@@ -433,5 +439,12 @@ int main(void) {chmod("/system_data/game/temp/PPSA01922/trophy2/npbind.dat", 0666);chmod("/system_data/game/temp/PPSA01922/trophy2/trophy00.ucp", 0666);+ FILE* done_log = fopen("/data/trophy_patch_log.txt", "w");+ if (done_log) {+ fprintf(done_log, "PSBox_Trophies DONE\n");+ fclose(done_log);+ chmod("/data/trophy_patch_log.txt", 0666);+ }+return 0;}diff --git a/tools/ps5/ps5_dev.py b/tools/ps5/ps5_dev.pyindex e20a648..4c87524 100755--- a/tools/ps5/ps5_dev.py+++ b/tools/ps5/ps5_dev.py@@ -187,7 +187,7 @@ def cmd_test(args):"tunetest", "confirmtest", "pickertest", "menutest", "regiontest","friendstest", "publishertest", "scrolltest", "quicktest", "tlscheck","padspktest", "queuetest", "queueuitest", "wishlisttest", "block1test",- "block2test", "block3test", "bitratetest", "touchpadtest", "mw4test", "v150test", "claimtest", "trophytest", "trophysynctest",+ "block2test", "block3test", "bitratetest", "touchpadtest", "mw4test", "v150test", "claimtest", "trophytest", "trophysynctest", "checksignintest",}bitrate_opt = f" bitrate={args.bitrate}" if getattr(args, "bitrate", 0) > 0 else ""if target.startswith("AUTOTEST") or target.startswith("BENCH") or " " in target:@@ -235,7 +235,8 @@ def cmd_test(args):"stream_menu_touchpad.ppm", "launch_screen_hint.ppm", "search_mw4.ppm", "details_mw4.ppm","v150_settings.ppm", "v150_search_free.ppm","claim1_details_before.ppm", "claim2_details_playable.ppm", "claim3_my_games_unrefreshed.ppm",- "claim4_launching.ppm", "claim5_stream.ppm", "trophy_settings.ppm", "trophy_disclaimer.ppm", "trophy_enabled.ppm", "trophy_synced.ppm"):+ "claim4_launching.ppm", "claim5_stream.ppm", "trophy_settings.ppm", "trophy_disclaimer.ppm", "trophy_enabled.ppm", "trophy_synced.ppm",+ "signin_check.ppm", "checksignin.ppm"):try:ftp.sendcmd(f"DELE {name}")except (error_perm, error_reply):@@ -291,7 +292,8 @@ def cmd_test(args):"stream_menu_touchpad.ppm", "launch_screen_hint.ppm", "search_mw4.ppm", "details_mw4.ppm","v150_settings.ppm", "v150_search_free.ppm","claim1_details_before.ppm", "claim2_details_playable.ppm", "claim3_my_games_unrefreshed.ppm",- "claim4_launching.ppm", "claim5_stream.ppm", "trophy_settings.ppm", "trophy_disclaimer.ppm", "trophy_enabled.ppm", "trophy_synced.ppm"]+ "claim4_launching.ppm", "claim5_stream.ppm", "trophy_settings.ppm", "trophy_disclaimer.ppm", "trophy_enabled.ppm", "trophy_synced.ppm",+ "signin_check.ppm", "checksignin.ppm"]ftp = get_ftp(host, port)ftp.cwd("/data/psbox")for name in ppm_names + ["xcloud.log"]:diff --git a/tools/release.sh b/tools/release.shindex e0cdce0..020337d 100755--- a/tools/release.sh+++ b/tools/release.sh@@ -116,7 +116,7 @@ ok "$out/$ps5_named ($(du -h "$out/$ps5_named" | cut -f1)), sha256 $(cut -d' ' -echo "== checks in the package"zip=$out/PPSA99810.zip-if unzip -Z1 "$zip" | grep -nE "$private|\.elf$"; then fail "a private or symbol file in the zip"; fi+if unzip -Z1 "$zip" | grep -vx 'PPSA99810/assets/PSBox_Trophies.elf' | grep -nE "$private|\.elf$"; then fail "a private or symbol file in the zip"; fiif zipinfo "$zip" | grep -E '^[-d]' | grep -v '^.rwxrwxrwx'; then fail "files in the zip without mode 0777"; fiok "every entry mode 0777"ok "no private file ($(unzip -Z1 "$zip" | grep -vc '/$') files)"@@ -127,10 +127,10 @@ eboot=$out/PPSA99810/eboot.binif grep -aqE "$tokens" "$eboot"; then fail "eboot.bin holds something like a token"; figrep -aq "$version" "$eboot" || fail "eboot.bin doesn't carry version $version (stale build?)"ok "eboot.bin: no token, version $version compiled in"-for f in assets/cacert.pem licenses/THIRD_PARTY_NOTICES.md licenses/FFmpeg-LGPL-2.1.txt licenses/Anime4K-MIT.txt LICENSE; do+for f in assets/cacert.pem assets/PSBox_Trophies.elf licenses/THIRD_PARTY_NOTICES.md licenses/FFmpeg-LGPL-2.1.txt licenses/Anime4K-MIT.txt LICENSE; dounzip -Z1 "$zip" | grep -qx "PPSA99810/$f" || fail "missing PPSA99810/$f"done-ok "certificates and licenses in place"+ok "certificates, trophy payload and licenses in place"echo "== build PS4"if [ -z "${OO_PS4_TOOLCHAIN:-}" ] && [ -d "$root/ps4-toolchain" ]; then