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: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('去商店逛逛'), ), ], ), ) : GridView.builder( padding: const EdgeInsets.only(bottom: 40), gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 5, mainAxisSpacing: 18, crossAxisSpacing: 16, childAspectRatio: 0.60, ), itemCount: filtered.length, itemBuilder: (context, i) => _LibraryCard(game: filtered[i], onRemove: _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 StatelessWidget { final Game game; final VoidCallback onRemove; const _LibraryCard({required this.game, required this.onRemove}); Future _installDir() async { final ins = await AppPrefs.getInstallPath(); final base = ins.isEmpty ? 'C:\\99GameBox\\99GameI' : ins; return '$base\\${game.title.replaceAll(RegExp(r'[\\/:*?"<>|]'), '_')}'; } Future _launch(BuildContext context) async { final dir = await _installDir(); // 尝试查找目录中的exe并启动(启动已下载的游戏不需要会员) final d = Directory(dir); if (await d.exists()) { final exes = d .listSync(recursive: false) .whereType() .where((f) => f.path.toLowerCase().endsWith('.exe')) .toList(); if (exes.isNotEmpty) { Process.run(exes.first.path, [], workingDirectory: dir); return; } } // 未找到可执行文件 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: const Row( children: [ Icon(Icons.error_outline, color: Colors.white, size: 18), SizedBox(width: 8), Expanded( child: Text('未找到游戏文件,请先下载游戏', style: 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\\${game.title}.lnk\");' '\$s.TargetPath=\"$dir\"; \$s.Save()'; Process.run('powershell', ['-command', script]); } Future _uninstall(BuildContext context) async { final res = await ApiService.removeFromLibrary(game.id); if (res['code'] == 0) { onRemove(); } } 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: [ _menuItem(context, Icons.play_arrow, '启动游戏', () => _launch(context)), _menuItem(context, Icons.link, '创建快捷方式', _createShortcut), _menuItem(context, Icons.folder_open, '打开游戏目录', _openDir), _menuItem(context, Icons.delete_outline, '卸载游戏', () => _uninstall(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: () => _launch(context), 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 + game.cover, fit: BoxFit.cover, errorBuilder: (_, __, ___) => Container( color: const Color(0xFF2A2E45), child: Center( child: Text( 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(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(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 (game.versionNote.isNotEmpty) Padding( padding: const EdgeInsets.only(bottom: 2), child: Text( game.versionNote, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle( color: AppColors.textDim, fontSize: 11), ), ), Text(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( game.tags.split(',').first, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle( color: AppColors.textDim, fontSize: 11), ), ), // 启动按钮(对标:标签行右侧紧凑按钮) GestureDetector( onTap: () => _launch(context), child: Container( padding: const EdgeInsets.symmetric( horizontal: 14, vertical: 4), decoration: BoxDecoration( color: AppColors.accent, borderRadius: BorderRadius.circular(3), ), child: const Text('启动', style: TextStyle( color: Colors.white, fontSize: 11)), ), ), ], ), ], ), ), ), ], ), ), ), ); } }