Files
flutter-rimworld-modman/lib/main.dart
2025-03-15 23:17:21 +01:00

611 lines
20 KiB
Dart

import 'package:flutter/material.dart';
import 'package:rimworld_modman/modloader.dart';
import 'dart:io';
// Global variable to store loaded mods for access across the app
late ModList modManager;
void main() {
// Initialize the mod manager
modManager = ModList(path: modsRoot);
// Start the app
runApp(const RimWorldModManager());
}
class RimWorldModManager extends StatelessWidget {
const RimWorldModManager({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Rimworld Mod Manager',
theme: ThemeData.dark().copyWith(
primaryColor: const Color(0xFF3D4A59),
colorScheme: ColorScheme.fromSeed(
seedColor: const Color(0xFF3D4A59),
brightness: Brightness.dark,
),
scaffoldBackgroundColor: const Color(0xFF1E262F),
cardColor: const Color(0xFF2A3440),
appBarTheme: const AppBarTheme(
backgroundColor: Color(0xFF2A3440),
foregroundColor: Colors.white,
),
),
home: const ModManagerHomePage(),
);
}
}
class ModManagerHomePage extends StatefulWidget {
const ModManagerHomePage({super.key});
@override
State<ModManagerHomePage> createState() => _ModManagerHomePageState();
}
class _ModManagerHomePageState extends State<ModManagerHomePage> {
int _selectedIndex = 0;
final List<Widget> _pages = [
const ModListPage(),
const LoadOrderPage(),
const TroubleshootingPage(),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Rimworld Mod Manager')),
body: _pages[_selectedIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _selectedIndex,
onTap: (index) {
setState(() {
_selectedIndex = index;
});
},
items: const [
BottomNavigationBarItem(icon: Icon(Icons.extension), label: 'Mods'),
BottomNavigationBarItem(
icon: Icon(Icons.reorder),
label: 'Load Order',
),
BottomNavigationBarItem(
icon: Icon(Icons.build),
label: 'Troubleshoot',
),
],
),
);
}
}
// Page to display all installed mods with enable/disable toggles
class ModListPage extends StatefulWidget {
const ModListPage({super.key});
@override
State<ModListPage> createState() => _ModListPageState();
}
class _ModListPageState extends State<ModListPage> {
final List<Mod> _loadedMods = [];
bool _isLoading = false;
String _loadingStatus = '';
int _totalModsFound = 0;
bool _skipFileCount = false; // Skip file counting by default for faster loading
@override
Widget build(BuildContext context) {
return Scaffold(
body: _loadedMods.isEmpty && !_isLoading
? _buildEmptyState()
: _buildModList(),
);
}
Widget _buildEmptyState() {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.extension, size: 64),
const SizedBox(height: 16),
Text('Mod List', style: Theme.of(context).textTheme.headlineMedium),
const SizedBox(height: 16),
Text(
'Ready to scan for Rimworld mods.',
style: Theme.of(context).textTheme.bodyLarge,
),
const SizedBox(height: 12),
Row(
mainAxisSize: MainAxisSize.min,
children: [
Checkbox(
value: _skipFileCount,
onChanged: (value) {
setState(() {
_skipFileCount = value ?? true;
});
},
),
const Text('Skip file counting (faster loading)'),
],
),
const SizedBox(height: 24),
ElevatedButton(
onPressed: _startLoadingMods,
child: const Text('Scan for Mods'),
),
],
),
);
}
Widget _buildModList() {
return Column(
children: [
if (_isLoading)
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
LinearProgressIndicator(
value:
_totalModsFound > 0
? _loadedMods.length / _totalModsFound
: null,
),
const SizedBox(height: 8),
Text(
_loadingStatus,
style: Theme.of(context).textTheme.bodyMedium,
),
],
),
),
Expanded(
child: ListView.builder(
itemCount: _loadedMods.length,
itemBuilder: (context, index) {
final mod = _loadedMods[index];
return Card(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: ListTile(
title: Text(mod.name),
subtitle: Text(
'ID: ${mod.id}\nSize: ${mod.size} files',
style: Theme.of(context).textTheme.bodySmall,
),
trailing: Icon(
Icons.circle,
color:
mod.hardDependencies.isNotEmpty
? Colors.orange
: Colors.green,
size: 12,
),
onTap: () {
// TODO: Show mod details
},
),
);
},
),
),
if (!_isLoading && _loadedMods.isNotEmpty)
Padding(
padding: const EdgeInsets.all(16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('${_loadedMods.length} mods loaded'),
ElevatedButton(
onPressed: _startLoadingMods,
child: const Text('Reload'),
),
],
),
),
],
);
}
void _startLoadingMods() {
setState(() {
_loadedMods.clear();
_isLoading = true;
_loadingStatus = 'Scanning for mods...';
});
// First get the mod directories to know the total count
final directory = Directory(modsRoot);
if (directory.existsSync()) {
final List<FileSystemEntity> entities = directory.listSync();
final List<String> modDirectories =
entities.whereType<Directory>().map((dir) => dir.path).toList();
setState(() {
_totalModsFound = modDirectories.length;
_loadingStatus = 'Found $_totalModsFound mod directories. Loading...';
});
}
// Use the serial loading with our skipFileCount option
modManager
.load(skipFileCount: _skipFileCount)
.listen(
(mod) {
setState(() {
_loadedMods.add(mod);
_loadingStatus = 'Loaded ${_loadedMods.length}/$_totalModsFound mods...';
});
},
onError: (error) {
setState(() {
_isLoading = false;
_loadingStatus = 'Error loading mods: $error';
});
},
onDone: () {
setState(() {
_isLoading = false;
_loadingStatus = 'Completed! ${_loadedMods.length} mods loaded.';
// Sort mods by name for better display
_loadedMods.sort((a, b) => a.name.compareTo(b.name));
});
},
);
}
}
// Page to manage mod load order with dependency visualization
class LoadOrderPage extends StatefulWidget {
const LoadOrderPage({super.key});
@override
State<LoadOrderPage> createState() => _LoadOrderPageState();
}
class _LoadOrderPageState extends State<LoadOrderPage> {
bool _isLoading = false;
String _statusMessage = '';
List<Mod> _sortedMods = [];
bool _hasCycles = false;
List<String>? _cycleInfo;
List<List<String>> _incompatibleMods = [];
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Mod Load Order',
style: Theme.of(context).textTheme.headlineMedium,
),
const SizedBox(height: 16),
Text(
'Automatically sort mods based on dependencies, prioritizing larger mods.',
style: Theme.of(context).textTheme.bodyLarge,
),
const SizedBox(height: 24),
Row(
children: [
ElevatedButton(
onPressed: _isLoading ? null : _sortMods,
child: const Text('Auto-sort Mods'),
),
const SizedBox(width: 8),
Chip(
backgroundColor: Colors.amber.withOpacity(0.2),
label: const Text(
'Larger mods prioritized',
style: TextStyle(fontSize: 12),
),
),
const SizedBox(width: 16),
ElevatedButton(
onPressed: _isLoading || _sortedMods.isEmpty ? null : _saveModOrder,
child: const Text('Save Load Order'),
),
],
),
const SizedBox(height: 16),
if (_isLoading)
const LinearProgressIndicator(),
if (_statusMessage.isNotEmpty)
Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Text(
_statusMessage,
style: TextStyle(
color: _hasCycles || _incompatibleMods.isNotEmpty
? Colors.orange
: Colors.green,
),
),
),
if (_hasCycles && _cycleInfo != null)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(
'Dependency cycle detected: ${_cycleInfo!.join(" -> ")}',
style: TextStyle(color: Colors.orange),
),
),
if (_incompatibleMods.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Incompatible mods detected:',
style: TextStyle(color: Colors.orange),
),
...List.generate(_incompatibleMods.length > 5 ? 5 : _incompatibleMods.length, (index) {
final pair = _incompatibleMods[index];
return Text(
'- ${modManager.mods[pair[0]]?.name} and ${modManager.mods[pair[1]]?.name}',
style: TextStyle(color: Colors.orange),
);
}),
if (_incompatibleMods.length > 5)
Text('...and ${_incompatibleMods.length - 5} more'),
],
),
),
const SizedBox(height: 16),
if (_sortedMods.isNotEmpty)
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.grey.withOpacity(0.1),
borderRadius: BorderRadius.circular(8),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text('Legend:', style: TextStyle(fontWeight: FontWeight.bold)),
const SizedBox(height: 4),
Row(
children: [
Icon(Icons.link, color: Colors.orange, size: 16),
const SizedBox(width: 4),
Text('Hard dependencies', style: TextStyle(fontSize: 12)),
const SizedBox(width: 12),
Icon(Icons.link_off, color: Colors.blue, size: 16),
const SizedBox(width: 4),
Text('Soft dependencies', style: TextStyle(fontSize: 12)),
],
),
const SizedBox(height: 4),
Row(
children: [
Container(width: 12, height: 12, color: Colors.amber),
const SizedBox(width: 4),
Text('Very large mod (>1000 files)', style: TextStyle(fontSize: 12)),
const SizedBox(width: 12),
Container(width: 12, height: 12, color: Colors.yellow.shade600),
const SizedBox(width: 4),
Text('Large mod (>500 files)', style: TextStyle(fontSize: 12)),
],
),
],
),
),
Expanded(
child: _sortedMods.isEmpty
? Center(
child: Text(
'Click "Auto-sort Mods" to generate a load order based on dependencies.',
textAlign: TextAlign.center,
),
)
: ListView.builder(
itemCount: _sortedMods.length,
itemBuilder: (context, index) {
final mod = _sortedMods[index];
return Card(
margin: const EdgeInsets.symmetric(vertical: 4),
child: ListTile(
leading: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('${index + 1}'),
const SizedBox(height: 2),
if (mod.size > 0) Text('${mod.size}', style: TextStyle(fontSize: 10, color: Colors.grey)),
],
),
title: Text(mod.name),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(mod.id, style: TextStyle(fontSize: 10)),
if (mod.hardDependencies.isNotEmpty)
Text(
'Hard dependencies: ${mod.hardDependencies.length}',
style: TextStyle(fontSize: 10, color: Colors.orange),
),
if (mod.softDependencies.isNotEmpty)
Text(
'Soft dependencies: ${mod.softDependencies.length}',
style: TextStyle(fontSize: 10, color: Colors.blue),
),
],
),
isThreeLine: mod.hardDependencies.isNotEmpty || mod.softDependencies.isNotEmpty,
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (mod.hardDependencies.isNotEmpty)
Icon(Icons.link, color: Colors.orange, size: 16),
const SizedBox(width: 4),
if (mod.softDependencies.isNotEmpty)
Icon(Icons.link_off, color: Colors.blue, size: 16),
const SizedBox(width: 4),
Text(
'${mod.size} files',
style: TextStyle(
fontSize: 12,
fontWeight: mod.size > 1000 ? FontWeight.bold : FontWeight.normal,
color: mod.size > 1000
? Colors.amber
: mod.size > 500
? Colors.yellow.shade600
: Colors.grey,
),
),
],
),
),
);
},
),
),
],
),
),
);
}
void _sortMods() async {
if (modManager.mods.isEmpty) {
setState(() {
_statusMessage = 'No mods have been loaded yet. Please load mods first.';
});
return;
}
setState(() {
_isLoading = true;
_statusMessage = 'Sorting mods based on dependencies...';
_hasCycles = false;
_cycleInfo = null;
_incompatibleMods = [];
});
// This could be slow so run in a separate isolate or compute
await Future.delayed(Duration.zero); // Allow UI to update
try {
// Check for cycles first
final hardGraph = modManager.buildDependencyGraph();
final cycle = modManager.detectCycle(hardGraph);
if (cycle != null) {
setState(() {
_hasCycles = true;
_cycleInfo = cycle;
});
}
// Get incompatibilities
_incompatibleMods = modManager.findIncompatibilities();
// Get the sorted mods
final sortedMods = modManager.getModsInLoadOrder();
setState(() {
_sortedMods = sortedMods;
_isLoading = false;
_statusMessage = 'Sorting complete! ${sortedMods.length} mods sorted.';
if (_hasCycles) {
_statusMessage += ' Warning: Dependency cycles were found and fixed.';
}
if (_incompatibleMods.isNotEmpty) {
_statusMessage += ' Warning: ${_incompatibleMods.length} incompatible mod pairs found.';
}
});
} catch (e) {
setState(() {
_isLoading = false;
_statusMessage = 'Error sorting mods: $e';
});
}
}
void _saveModOrder() async {
if (_sortedMods.isEmpty) return;
setState(() {
_isLoading = true;
_statusMessage = 'Saving mod load order...';
});
try {
// Create a ConfigFile instance
final configFile = ConfigFile(path: configPath);
// Load the current config
configFile.load();
// Replace the mods with our sorted list
// We need to convert our Mods to the format expected by the config file
configFile.mods.clear();
for (final mod in _sortedMods) {
configFile.mods.add(mod);
}
// Save the updated config
configFile.save();
setState(() {
_isLoading = false;
_statusMessage = 'Mod load order saved successfully!';
});
} catch (e) {
setState(() {
_isLoading = false;
_statusMessage = 'Error saving mod load order: $e';
});
}
}
}
// Page for troubleshooting problematic mods
class TroubleshootingPage extends StatelessWidget {
const TroubleshootingPage({super.key});
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.build, size: 64),
const SizedBox(height: 16),
Text(
'Troubleshooting',
style: Theme.of(context).textTheme.headlineMedium,
),
const SizedBox(height: 16),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32.0),
child: Text(
'Find problematic mods with smart batch testing.',
style: Theme.of(context).textTheme.bodyLarge,
textAlign: TextAlign.center,
),
),
const SizedBox(height: 24),
ElevatedButton(
onPressed: () {
// TODO: Implement troubleshooting wizard
},
child: const Text('Start Troubleshooting'),
),
],
),
);
}
}