import 'dart:io'; import 'package:flutter/material.dart'; import 'package:fluttergamebox/api/api_client.dart'; import 'package:fluttergamebox/api/api_service.dart'; import 'package:fluttergamebox/common/theme.dart'; import 'package:fluttergamebox/store/app_state.dart'; import 'package:fluttergamebox/utils/util.dart'; import 'package:fluttergamebox/widgets/download_manager.dart'; import 'package:path/path.dart' as p; class LibraryPage extends StatefulWidget { const LibraryPage({super.key}); @override State createState() => LibraryPageState(); } class LibraryPageState extends State with AutomaticKeepAliveClientMixin { List games = []; List categories = []; int category = 0; bool _loading = true; final GlobalKey _listKey = GlobalKey(); @override bool get wantKeepAlive => true; @override void initState() { super.initState(); _load(); } Future _load() async { final g = await ApiService.library(); final c = await ApiService.categories(); if (!mounted) return; setState(() { games = g; categories = c.where((e) => e.name != '常用工具').toList(); _loading = false; }); } /// 供主Shell刷新(切换到资源库页/关闭详情页时重新拉取) void refresh() => _load(); List get filtered => category == 0 ? games : games.where((g) => g.categoryId == category).toList(); @override Widget build(BuildContext context) { super.build(context); return Container( color: AppColors.bg, padding: const EdgeInsets.fromLTRB(70, 20, 70, 0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // 顶部:类别筛选 Row( children: [ const Text('我的资源库', style: TextStyle( color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500)), const SizedBox(width: 20), _CategoryFilter( categories: categories, value: category, onChanged: (v) => setState(() => category = v ?? 0), ), const Spacer(), // 模拟器管理 ElevatedButton.icon( onPressed: () => _showEmulatorDialog(context), icon: const Icon(Icons.memory, size: 16), label: const Text('模拟器管理', style: TextStyle(fontSize: 13)), style: ElevatedButton.styleFrom( backgroundColor: AppColors.bgLight, foregroundColor: AppColors.textWhite, elevation: 0, padding: const EdgeInsets.symmetric( horizontal: 14, vertical: 8), ), ), ], ), const SizedBox(height: 16), Expanded( child: _loading ? const Center( child: CircularProgressIndicator(color: AppColors.accent)) : filtered.isEmpty ? Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ const Icon(Icons.folder_open, size: 56, color: AppColors.textDim), const SizedBox(height: 12), const Text('资源库空空如也,快去添加游戏吧', style: TextStyle( color: AppColors.textGray, fontSize: 14)), const SizedBox(height: 16), ElevatedButton( onPressed: () => Navigator.pop(context), child: const Text('去商店逛逛'), ), ], ), ) : LayoutBuilder(builder: (context, constraints) { // 卡片高度 = 封面高度 + 信息区实际内容高度,避免出现大段空白 const crossAxisSpacing = 16.0; final cardWidth = (constraints.maxWidth - crossAxisSpacing * 4) / 5; final coverHeight = cardWidth / 1.42; const infoHeight = 96.0; return GridView.builder( padding: const EdgeInsets.only(bottom: 40), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 5, mainAxisSpacing: 18, crossAxisSpacing: crossAxisSpacing, mainAxisExtent: coverHeight + infoHeight, ), itemCount: filtered.length, itemBuilder: (context, i) => _LibraryCard(game: filtered[i], onRemoved: _load), ); }), ), ], ), ); } void _showEmulatorDialog(BuildContext context) { showDialog( context: context, builder: (context) => Dialog( backgroundColor: const Color(0xFF1E2130), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)), child: Container( width: 480, padding: const EdgeInsets.all(24), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ const Icon(Icons.memory, size: 16, color: AppColors.textGray), const SizedBox(width: 8), const Text('模拟器管理', style: TextStyle( color: Colors.white, fontSize: 14, fontWeight: FontWeight.w500)), const Spacer(), GestureDetector( onTap: () => Navigator.pop(context), child: const Icon(Icons.close, size: 16, color: AppColors.textGray), ), ], ), const SizedBox(height: 16), Container( padding: const EdgeInsets.all(12), decoration: BoxDecoration( color: AppColors.bg, borderRadius: BorderRadius.circular(4), ), child: const Row( children: [ Icon(Icons.info_outline, size: 14, color: AppColors.textGray), SizedBox(width: 8), Expanded( child: Text( '下载Switch游戏前,请先下载安装模拟器。启动Switch游戏会自动调用模拟器运行。', style: TextStyle( color: AppColors.textGray, fontSize: 12)), ), ], ), ), const SizedBox(height: 16), _EmulatorItem( name: 'Yuzu模拟器', desc: '最新版本,支持所有Switch游戏', installed: true, ), const SizedBox(height: 10), _EmulatorItem( name: 'Ryujinx模拟器', desc: '兼容性好,部分游戏更流畅', installed: false, ), ], ), ), ), ); } } class _EmulatorItem extends StatelessWidget { final String name; final String desc; final bool installed; const _EmulatorItem({ required this.name, required this.desc, required this.installed, }); @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.all(14), decoration: BoxDecoration( color: AppColors.bg, borderRadius: BorderRadius.circular(6), border: Border.all(color: AppColors.bgLighter), ), child: Row( children: [ Container( width: 44, height: 44, decoration: BoxDecoration( color: AppColors.bgLighter, borderRadius: BorderRadius.circular(6), ), child: const Icon(Icons.videogame_asset, color: AppColors.accent, size: 22), ), const SizedBox(width: 12), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Text(name, style: const TextStyle( color: Colors.white, fontSize: 13, fontWeight: FontWeight.w500)), const SizedBox(width: 8), if (installed) Container( padding: const EdgeInsets.symmetric( horizontal: 6, vertical: 1), decoration: BoxDecoration( color: AppColors.green.withOpacity(0.15), borderRadius: BorderRadius.circular(2), ), child: const Text('已安装', style: TextStyle( color: AppColors.green, fontSize: 10)), ), ], ), const SizedBox(height: 4), Text(desc, style: const TextStyle( color: AppColors.textDim, fontSize: 12)), ], ), ), installed ? OutlinedButton( onPressed: () {}, style: OutlinedButton.styleFrom( foregroundColor: AppColors.textGray, side: const BorderSide(color: AppColors.bgLighter), ), child: const Text('打开', style: TextStyle(fontSize: 12)), ) : ElevatedButton( onPressed: () {}, style: ElevatedButton.styleFrom( backgroundColor: AppColors.accent, foregroundColor: Colors.white, ), child: const Text('安装', style: TextStyle(fontSize: 12)), ), ], ), ); } } class _CategoryFilter extends StatelessWidget { final List categories; final int value; final ValueChanged onChanged; const _CategoryFilter({ required this.categories, required this.value, required this.onChanged, }); @override Widget build(BuildContext context) { return Container( height: 30, padding: const EdgeInsets.symmetric(horizontal: 12), decoration: BoxDecoration( color: AppColors.bgLight, borderRadius: BorderRadius.circular(4), ), child: DropdownButtonHideUnderline( child: DropdownButton( value: value, dropdownColor: const Color(0xFF232739), style: const TextStyle(color: AppColors.textWhite, fontSize: 13), icon: const Icon(Icons.arrow_drop_down, size: 18, color: AppColors.textGray), items: [ const DropdownMenuItem( value: 0, child: Text('全部类别')), ...categories.map((c) => DropdownMenuItem(value: c.id, child: Text(c.name))), ], onChanged: onChanged, ), ), ); } } /// 资源库游戏卡片(右键菜单) class _LibraryCard extends StatefulWidget { final Game game; final VoidCallback? onRemoved; // 从资源库移除后刷新列表 const _LibraryCard({required this.game, this.onRemoved}); @override State<_LibraryCard> createState() => _LibraryCardState(); } class _LibraryCardState extends State<_LibraryCard> { bool _installed = false; // 游戏是否已安装到本机 bool _uninstalling = false; // 正在卸载(删除游戏目录) @override void initState() { super.initState(); _checkInstalled(); } Future _checkInstalled() async { final ok = await isGameInstalled(widget.game.title, widget.game.launchExe); if (mounted) setState(() => _installed = ok); } /// 当前是否已安装(本机已装,或该游戏的下载任务刚完成) bool _effectiveInstalled() { final t = DownloadManager.instance.activeTask; return _installed || (t != null && t.gameId == widget.game.id && t.finished && !t.extractFailed); } Future _installDir() async => gameInstallDir(widget.game.title); /// 启动游戏(启动已下载的游戏不需要会员) Future _launch() async { final ok = await launchInstalledGame(widget.game.title, widget.game.launchExe); if (!ok && mounted) { _showToast('未找到游戏文件,请先下载游戏'); } } /// 安装(未安装时):选择路径后下载并安装 Future _install() async { // 选择下载安装路径 final ok = await showDialog( context: context, builder: (context) => DownloadPathDialog(gameTitle: widget.game.title), ); if (ok != true) return; try { await DownloadManager.instance.startDownload(widget.game); if (mounted) showDownloadDialog(context); } catch (e) { _showToast(e.toString()); } } void _showToast(String msg) { final overlay = Overlay.of(context); final entry = OverlayEntry( builder: (context) => Positioned( top: 60, left: MediaQuery.of(context).size.width / 2 - 140, child: Material( color: Colors.transparent, child: Container( width: 280, padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), decoration: BoxDecoration( color: AppColors.red, borderRadius: BorderRadius.circular(6), ), child: Row( children: [ const Icon(Icons.error_outline, color: Colors.white, size: 18), const SizedBox(width: 8), Expanded( child: Text(msg, style: const TextStyle( color: Colors.white, fontSize: 13)), ), ], ), ), ), ), ); overlay.insert(entry); Future.delayed(const Duration(seconds: 2), () => entry.remove()); } Future _openDir() async { final dir = await _installDir(); final d = Directory(dir); if (!await d.exists()) { await d.create(recursive: true); } Process.run('explorer.exe', [p.normalize(dir)]); } Future _createShortcut() async { // 通过PowerShell创建桌面快捷方式(指向游戏目录) final dir = await _installDir(); final script = '\$s=(New-Object -COM WScript.Shell).CreateShellLink(\"\$env:USERPROFILE\\Desktop\\${widget.game.title}.lnk\");' '\$s.TargetPath=\"$dir\"; \$s.Save()'; Process.run('powershell', ['-command', script]); } /// 卸载:确认后仅删除本机游戏目录(游戏保留在资源库中) Future _uninstall(BuildContext context) async { if (_uninstalling) return; // 已在卸载中 final confirmed = await showDialog( context: context, builder: (context) => Dialog( backgroundColor: const Color(0xFF1E2130), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), child: Container( width: 360, padding: const EdgeInsets.all(24), child: Column( mainAxisSize: MainAxisSize.min, children: [ const Icon(Icons.warning_amber_rounded, color: AppColors.yellow, size: 48), const SizedBox(height: 16), const Text('确认卸载游戏', style: TextStyle( color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold)), const SizedBox(height: 8), Text( '将删除本机的「${widget.game.title}」游戏目录,游戏仍保留在资源库中,卸载后可在详情页重新下载。', textAlign: TextAlign.center, style: const TextStyle(color: AppColors.textGray, fontSize: 13), ), const SizedBox(height: 20), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ OutlinedButton( onPressed: () => Navigator.pop(context, false), style: OutlinedButton.styleFrom( foregroundColor: AppColors.textGray, side: const BorderSide(color: AppColors.bgLighter), padding: const EdgeInsets.symmetric( horizontal: 22, vertical: 10), ), child: const Text('取消'), ), const SizedBox(width: 12), ElevatedButton( onPressed: () => Navigator.pop(context, true), style: ElevatedButton.styleFrom( backgroundColor: AppColors.red, foregroundColor: Colors.white, padding: const EdgeInsets.symmetric( horizontal: 22, vertical: 10), ), child: const Text('卸载'), ), ], ), ], ), ), ), ); if (confirmed != true) return; // 仅删除游戏安装目录,不从资源库移出 setState(() => _uninstalling = true); try { final dir = Directory(await _installDir()); if (await dir.exists()) { await dir.delete(recursive: true); } } catch (_) { debugLog('uninstall delete dir failed: ${widget.game.title}'); } if (mounted) { // 卸载完成后按钮由"卸载中"切换为"安装" setState(() { _uninstalling = false; _installed = false; }); } // 清除残留的已完成下载任务记录,避免仍被判定为已安装 DownloadManager.instance.clearFinishedTask(widget.game.id); } /// 从资源库移除(仅移除记录,不影响本机游戏文件) Future _removeFromLibrary(BuildContext context) async { final confirmed = await showDialog( context: context, builder: (context) => Dialog( backgroundColor: const Color(0xFF1E2130), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), child: Container( width: 360, padding: const EdgeInsets.all(24), child: Column( mainAxisSize: MainAxisSize.min, children: [ const Icon(Icons.list_alt, color: AppColors.yellow, size: 48), const SizedBox(height: 16), const Text('从资源库移除', style: TextStyle( color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold)), const SizedBox(height: 8), Text( '将「${widget.game.title}」从资源库列表中移除,不影响本机已下载的游戏文件。', textAlign: TextAlign.center, style: const TextStyle(color: AppColors.textGray, fontSize: 13), ), const SizedBox(height: 20), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ OutlinedButton( onPressed: () => Navigator.pop(context, false), style: OutlinedButton.styleFrom( foregroundColor: AppColors.textGray, side: const BorderSide(color: AppColors.bgLighter), padding: const EdgeInsets.symmetric( horizontal: 22, vertical: 10), ), child: const Text('取消'), ), const SizedBox(width: 12), ElevatedButton( onPressed: () => Navigator.pop(context, true), style: ElevatedButton.styleFrom( backgroundColor: AppColors.red, foregroundColor: Colors.white, padding: const EdgeInsets.symmetric( horizontal: 22, vertical: 10), ), child: const Text('移除'), ), ], ), ], ), ), ), ); if (confirmed != true) return; try { final res = await ApiClient.delete('/api/library/${widget.game.id}'); if (res['code'] == 0) { AppState.instance.bumpLibrary(); widget.onRemoved?.call(); // 刷新资源库列表 } } catch (_) { debugLog('remove from library failed: ${widget.game.title}'); } } void _showContextMenu(BuildContext context, Offset position) { final overlay = Overlay.of(context); late OverlayEntry entry; entry = OverlayEntry( builder: (context) => Stack( children: [ GestureDetector( behavior: HitTestBehavior.opaque, onTap: () => entry.remove(), onSecondaryTapDown: (_) => entry.remove(), child: Container(color: Colors.black.withOpacity(0.01)), ), Positioned( left: position.dx, top: position.dy, child: Material( color: Colors.transparent, child: Container( width: 150, decoration: BoxDecoration( color: const Color(0xFF232739), borderRadius: BorderRadius.circular(6), border: Border.all(color: AppColors.bgLighter), boxShadow: [ BoxShadow( color: Colors.black.withOpacity(0.5), blurRadius: 12) ], ), child: Column( mainAxisSize: MainAxisSize.min, children: _effectiveInstalled() ? [ // 已安装:启动/快捷方式/打开目录/卸载 _menuItem(context, Icons.play_arrow, '启动游戏', _launch), _menuItem(context, Icons.link, '创建快捷方式', _createShortcut), _menuItem(context, Icons.folder_open, '打开游戏目录', _openDir), _menuItem(context, Icons.delete_outline, '卸载游戏', () => _uninstall(context)), ] : [ // 未安装:安装/从资源库移除 _menuItem(context, Icons.download, '安装游戏', _install), _menuItem(context, Icons.list_alt, '从资源库移除', () => _removeFromLibrary(context)), ], ), ), ), ), ], ), ); overlay.insert(entry); } Widget _menuItem( BuildContext context, IconData icon, String label, VoidCallback onTap) { return InkWell( onTap: onTap, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), child: Row( children: [ Icon(icon, size: 15, color: AppColors.textGray), const SizedBox(width: 10), Text(label, style: const TextStyle( color: AppColors.textWhite, fontSize: 13)), ], ), ), ); } @override Widget build(BuildContext context) { return GestureDetector( onTap: () { if (_uninstalling) return; // 卸载中不响应点击 _effectiveInstalled() ? _launch() : _install(); }, onSecondaryTapDown: (details) => _showContextMenu(context, details.globalPosition), child: MouseRegion( cursor: SystemMouseCursors.click, child: Container( decoration: BoxDecoration( color: AppColors.bgLight, borderRadius: BorderRadius.circular(6), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ AspectRatio( aspectRatio: 1.42, child: Stack( fit: StackFit.expand, children: [ ClipRRect( borderRadius: const BorderRadius.vertical( top: Radius.circular(6)), child: Image.network( ApiClient.baseUrl + widget.game.cover, fit: BoxFit.cover, errorBuilder: (_, __, ___) => Container( color: const Color(0xFF2A2E45), child: Center( child: Text( widget.game.title.characters.first, style: const TextStyle( color: AppColors.textDim, fontSize: 32)), ), ), ), ), // PC资源 标签 Positioned( left: 0, top: 8, child: Container( padding: const EdgeInsets.symmetric( horizontal: 8, vertical: 3), decoration: const BoxDecoration( color: AppColors.accent, borderRadius: BorderRadius.horizontal(right: Radius.circular(3)), ), child: Text(widget.game.platformLabel, style: const TextStyle( color: Colors.white, fontSize: 11)), ), ), // 大小标签 Positioned( right: 6, top: 8, child: Container( padding: const EdgeInsets.symmetric( horizontal: 6, vertical: 2), decoration: BoxDecoration( color: Colors.black.withOpacity(0.6), borderRadius: BorderRadius.circular(3), ), child: Text(widget.game.size, style: const TextStyle( color: Colors.white, fontSize: 11)), ), ), ], ), ), Expanded( child: Padding( padding: const EdgeInsets.all(10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ if (widget.game.versionNote.isNotEmpty) Padding( padding: const EdgeInsets.only(bottom: 2), child: Text( widget.game.versionNote, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle( color: AppColors.textDim, fontSize: 11), ), ), Text(widget.game.title, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle( color: Colors.white, fontSize: 12, height: 1.3)), const Spacer(), Row( children: [ Expanded( child: Text( widget.game.tags.split(',').first, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle( color: AppColors.textDim, fontSize: 11), ), ), // 启动/安装/卸载中按钮(随安装状态切换) ListenableBuilder( listenable: DownloadManager.instance, builder: (context, _) { final installed = _effectiveInstalled(); final label = _uninstalling ? '卸载中' : installed ? '启动' : '安装'; return GestureDetector( // 卸载中禁用点击 onTap: _uninstalling ? null : () => installed ? _launch() : _install(), child: Container( padding: const EdgeInsets.symmetric( horizontal: 14, vertical: 4), decoration: BoxDecoration( color: _uninstalling ? AppColors.bgLighter : installed ? AppColors.accent : AppColors.green, borderRadius: BorderRadius.circular(3), ), child: Text(label, style: const TextStyle( color: Colors.white, fontSize: 11)), ), ); }, ), ], ), ], ), ), ), ], ), ), ), ); } }