Saving update, bullet update, UI update

This commit is contained in:
2025-04-07 14:52:23 +02:00
parent b1ef6f5e9c
commit 07bc9d8157
2 changed files with 214 additions and 75 deletions
+2 -1
View File
@@ -21,6 +21,7 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
Color _bulletColor = Colors.blue; // default fallback Color _bulletColor = Colors.blue; // default fallback
Map<String, bool> _folderTypes = {}; // true = tournament, false = training Map<String, bool> _folderTypes = {}; // true = tournament, false = training
String _folderFilter = 'all'; String _folderFilter = 'all';
bool isRenameEnabled = false;
@override @override
void initState() { void initState() {
@@ -264,7 +265,7 @@ List<String> _filteredFolderNames() {
// Rename folder // Rename folder
Future<void> _renameFolder(String oldFolderName) async { Future<void> _renameFolder(String oldFolderName) async {
final newNameController = TextEditingController(); final newNameController = TextEditingController();
bool isRenameEnabled = false;
bool isTournament = _folderTypes[oldFolderName] == true; bool isTournament = _folderTypes[oldFolderName] == true;
final result = await showDialog<Map<String, dynamic>>( final result = await showDialog<Map<String, dynamic>>(
+195 -57
View File
@@ -45,12 +45,13 @@ class _PreviewScreenState extends State<PreviewScreen> {
int? _highlightedBulletIndex; int? _highlightedBulletIndex;
final List<int> _manualBulletScores = []; final List<int> _manualBulletScores = [];
bool _hasMissingBullets = false;
Color _bulletColor = Colors.blue; // default fallback Color _bulletColor = Colors.blue; // default fallback
double get _bulletOpacity => 0.8; double get _bulletOpacity => 0.8;
Color get _bulletColorWithOpacity => _bulletColor.withOpacity(_bulletOpacity); Color get _bulletColorWithOpacity => _bulletColor.withOpacity(_bulletOpacity);
bool _isEditMode = false;
int? _selectedBulletIndexInEdit;
@override @override
@@ -102,17 +103,6 @@ Color _getColorFromName(String colorName) {
} }
} }
Future<void> _handleMissingBullets() async {
final currentDetected = _mappedBullets.length;
final result = await _showMismatchOptionsDialog(currentDetected);
if (result == 'retry') {
Navigator.pop(context); // Go back to camera screen
} else if (result == 'manual') {
_manualScoreEntry();
}
}
Offset _generatePositionForScore(int score, Offset center) { Offset _generatePositionForScore(int score, Offset center) {
const double bulletRadius = 25; const double bulletRadius = 25;
final List<double> rings = [14, 70, 125, 180, 235, 290, 345, 400, 455, 510]; final List<double> rings = [14, 70, 125, 180, 235, 290, 345, 400, 455, 510];
@@ -213,12 +203,25 @@ Color _getColorFromName(String colorName) {
// 10. Update UI // 10. Update UI
final missing = widget.bulletCount - mappedBullets.length; final missing = widget.bulletCount - mappedBullets.length;
setState(() { setState(() {
_mappedBullets = mappedBullets; _mappedBullets = mappedBullets;
_isLoading = false; _isLoading = false;
_hasMissingBullets = missing > 0;
}); });
if (missing > 0) {
final result = await _showMismatchOptionsDialog(mappedBullets.length);
if (result == 'retry') {
Navigator.pop(context); // Go back to camera screen
} else if (result == 'manual') {
_manualScoreEntry(); // Reuse your original manual dialog
}
}
} catch (e, stack) { } catch (e, stack) {
debugPrint("❌ Error during detection mapping: $e"); debugPrint("❌ Error during detection mapping: $e");
debugPrint(stack.toString()); debugPrint(stack.toString());
@@ -439,25 +442,116 @@ void _manualScoreEntry() {
} }
} }
Widget _buildEditController() {
if (!_isEditMode || _selectedBulletIndexInEdit == null) return const SizedBox.shrink();
return Positioned(
bottom: 20,
left: 0,
right: 0,
child: Center(
child: Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.75),
borderRadius: BorderRadius.circular(12),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(Icons.arrow_drop_up, size: 32, color: Colors.white),
onPressed: () => _moveBullet(const Offset(0, -3)),
splashRadius: 20,
),
Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(Icons.arrow_left, size: 32, color: Colors.white),
onPressed: () => _moveBullet(const Offset(-3, 0)),
splashRadius: 20,
),
const SizedBox(width: 4),
IconButton(
icon: const Icon(Icons.check, size: 28, color: Colors.greenAccent),
onPressed: () => setState(() => _selectedBulletIndexInEdit = null),
splashRadius: 20,
),
const SizedBox(width: 4),
IconButton(
icon: const Icon(Icons.arrow_right, size: 32, color: Colors.white),
onPressed: () => _moveBullet(const Offset(3, 0)),
splashRadius: 20,
),
],
),
IconButton(
icon: const Icon(Icons.arrow_drop_down, size: 32, color: Colors.white),
onPressed: () => _moveBullet(const Offset(0, 3)),
splashRadius: 20,
),
],
),
),
),
);
}
void _moveBullet(Offset offsetDelta) {
setState(() {
final index = _selectedBulletIndexInEdit!;
final current = _mappedBullets[index];
final updated = current + offsetDelta;
_mappedBullets[index] = updated;
// If this is a manually added bullet, update its score live
final manualStartIndex = _mappedBullets.length - _manualBulletScores.length;
if (index >= manualStartIndex) {
final updatedScore = _scoreForBullet(
updated,
_targetImageCenterForScoring ?? fixedRingTargetCenter,
);
_manualBulletScores[index - manualStartIndex] = updatedScore;
}
});
}
Future<String?> _showSaveOptionsDialog() async { Future<String?> _showSaveOptionsDialog() async {
TextEditingController _controller = TextEditingController();
bool isNewFolderEnabled = false;
bool isTournament = false; // 👈 new flag
final directory = await getApplicationDocumentsDirectory(); final directory = await getApplicationDocumentsDirectory();
final saveDirectory = Directory('${directory.path}/saved_images'); final saveDirectory = Directory('${directory.path}/saved_images');
final List<String> existingFolders = []; // Ensure directory exists
if (!await saveDirectory.exists()) {
await saveDirectory.create(recursive: true);
}
// Load existing folders and their modified time
final folderStats = <Map<String, dynamic>>[];
final folders = saveDirectory.listSync(); final folders = saveDirectory.listSync();
for (var folder in folders) { for (var folder in folders) {
if (folder is Directory) { if (folder is Directory) {
existingFolders.add(folder.path.split('/').last); final stat = folder.statSync();
folderStats.add({
'name': folder.path.split('/').last,
'changed': stat.changed,
});
} }
} }
String? lastFolderName = existingFolders.isNotEmpty ? existingFolders.last : null; // Sort by modified time, newest first
folderStats.sort((a, b) =>
(b['changed'] as DateTime).compareTo(a['changed'] as DateTime));
String? lastFolderName =
folderStats.isNotEmpty ? folderStats.first['name'] : null;
TextEditingController _controller = TextEditingController();
bool isNewFolderEnabled = folderStats.isEmpty; // pre-enable if none
bool isTournament = false;
return await showDialog<String>( return await showDialog<String>(
context: context, context: context,
@@ -485,7 +579,6 @@ void _manualScoreEntry() {
textAlign: TextAlign.center, textAlign: TextAlign.center,
), ),
), ),
const Text( const Text(
"Select where you'd like to save the data:", "Select where you'd like to save the data:",
style: TextStyle(color: Colors.white70), style: TextStyle(color: Colors.white70),
@@ -493,6 +586,7 @@ void _manualScoreEntry() {
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
// Quick save to newest folder
if (lastFolderName != null) ...[ if (lastFolderName != null) ...[
SizedBox( SizedBox(
width: double.infinity, width: double.infinity,
@@ -503,7 +597,8 @@ void _manualScoreEntry() {
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
backgroundColor: _bulletColor, backgroundColor: _bulletColor,
foregroundColor: Colors.white, foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14), padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 14),
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
), ),
@@ -514,7 +609,7 @@ void _manualScoreEntry() {
const SizedBox(height: 16), const SizedBox(height: 16),
], ],
// New folder name input // Always show folder name input
SizedBox( SizedBox(
width: double.infinity, width: double.infinity,
child: TextField( child: TextField(
@@ -526,7 +621,8 @@ void _manualScoreEntry() {
fillColor: Colors.grey[800], fillColor: Colors.grey[800],
hintText: "Enter a new folder name", hintText: "Enter a new folder name",
hintStyle: const TextStyle(color: Colors.white54), hintStyle: const TextStyle(color: Colors.white54),
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), contentPadding: const EdgeInsets.symmetric(
horizontal: 16, vertical: 14),
enabledBorder: OutlineInputBorder( enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
borderSide: BorderSide.none, borderSide: BorderSide.none,
@@ -547,7 +643,6 @@ void _manualScoreEntry() {
// Tournament toggle // Tournament toggle
if (isNewFolderEnabled) ...[ if (isNewFolderEnabled) ...[
const SizedBox(height: 12),
GestureDetector( GestureDetector(
onTap: () { onTap: () {
setState(() { setState(() {
@@ -557,19 +652,28 @@ void _manualScoreEntry() {
child: Container( child: Container(
width: double.infinity, width: double.infinity,
decoration: BoxDecoration( decoration: BoxDecoration(
color: isTournament ? _bulletColor.withOpacity(0.2) : Colors.grey[850], color: isTournament
? _bulletColor.withOpacity(0.2)
: Colors.grey[850],
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
border: Border.all( border: Border.all(
color: isTournament ? _bulletColor : Colors.grey[700]!, color: isTournament
? _bulletColor
: Colors.grey[700]!,
width: 1.5, width: 1.5,
), ),
), ),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), padding: const EdgeInsets.symmetric(
horizontal: 16, vertical: 14),
child: Center( child: Center(
child: Text( child: Text(
isTournament ? 'Tournament Mode 🏆' : 'Mark as Tournament 🏆', isTournament
? 'Tournament Mode 🏆'
: 'Mark as Tournament 🏆',
style: TextStyle( style: TextStyle(
color: isTournament ? _bulletColor : Colors.white70, color: isTournament
? _bulletColor
: Colors.white70,
fontWeight: FontWeight.w500, fontWeight: FontWeight.w500,
fontSize: 16, fontSize: 16,
), ),
@@ -577,12 +681,10 @@ void _manualScoreEntry() {
), ),
), ),
), ),
const SizedBox(height: 16),
], ],
// Create folder button
const SizedBox(height: 16),
// Create new folder
SizedBox( SizedBox(
width: double.infinity, width: double.infinity,
child: ElevatedButton( child: ElevatedButton(
@@ -596,7 +698,8 @@ void _manualScoreEntry() {
) )
: null, : null,
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14), padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 14),
backgroundColor: backgroundColor:
isNewFolderEnabled ? _bulletColor : Colors.grey[700], isNewFolderEnabled ? _bulletColor : Colors.grey[700],
foregroundColor: Colors.white, foregroundColor: Colors.white,
@@ -618,6 +721,7 @@ void _manualScoreEntry() {
); );
} }
Map<String, dynamic>? _getRingCenterSize(List<DetectionResult> results) { Map<String, dynamic>? _getRingCenterSize(List<DetectionResult> results) {
try { try {
final ring = results.firstWhere((r) => r.classId == 2); final ring = results.firstWhere((r) => r.classId == 2);
@@ -673,7 +777,6 @@ void _manualScoreEntry() {
return autoScore + manualScore; return autoScore + manualScore;
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
@@ -688,7 +791,9 @@ Widget build(BuildContext context) {
actions: [ actions: [
IconButton( IconButton(
icon: Icon( icon: Icon(
_mode == PreviewMode.mappedTarget ? Icons.camera_alt : Icons.center_focus_strong, _mode == PreviewMode.mappedTarget
? Icons.camera_alt
: Icons.center_focus_strong,
), ),
color: Colors.white, color: Colors.white,
onPressed: () { onPressed: () {
@@ -809,7 +914,7 @@ Widget build(BuildContext context) {
final double bulletSize = ((scaleX + scaleY) / 2) * 55; final double bulletSize = ((scaleX + scaleY) / 2) * 55;
final isHighlighted = index == _highlightedBulletIndex; final isHighlighted = index == _highlightedBulletIndex;
final isManual = index >= (_mappedBullets.length - _manualBulletScores.length); final isSelectedForEdit = index == _selectedBulletIndexInEdit;
return Positioned( return Positioned(
left: dx - bulletSize / 2, left: dx - bulletSize / 2,
@@ -818,13 +923,15 @@ Widget build(BuildContext context) {
width: bulletSize, width: bulletSize,
height: bulletSize, height: bulletSize,
decoration: BoxDecoration( decoration: BoxDecoration(
color: isManual color: _bulletColorWithOpacity,
? Colors.red.withOpacity(0.9)
: _bulletColorWithOpacity,
shape: BoxShape.circle, shape: BoxShape.circle,
border: Border.all( border: Border.all(
color: isHighlighted ? Colors.red : Colors.black, color: isSelectedForEdit
width: isHighlighted ? 3 : 1, ? Colors.red
: (!_isEditMode && isHighlighted)
? Colors.red
: Colors.black,
width: (isSelectedForEdit || (!_isEditMode && isHighlighted)) ? 3 : 1,
), ),
), ),
), ),
@@ -851,15 +958,32 @@ Widget build(BuildContext context) {
bullet, bullet,
_targetImageCenterForScoring ?? fixedRingTargetCenter, _targetImageCenterForScoring ?? fixedRingTargetCenter,
); );
final isSelected = _highlightedBulletIndex == index; final isSelected = index == (_isEditMode ? _selectedBulletIndexInEdit : _highlightedBulletIndex);
return Expanded( return Expanded(
child: Padding( child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 6), padding: const EdgeInsets.symmetric(horizontal: 6),
child: GestureDetector( child: GestureDetector(
onTapDown: (_) => setState(() => _highlightedBulletIndex = index), onTap: () {
onTapUp: (_) => setState(() => _highlightedBulletIndex = null), if (_isEditMode) {
onTapCancel: () => setState(() => _highlightedBulletIndex = null), setState(() => _selectedBulletIndexInEdit = index);
}
},
onTapDown: (_) {
if (!_isEditMode) {
setState(() => _highlightedBulletIndex = index);
}
},
onTapUp: (_) {
if (!_isEditMode) {
setState(() => _highlightedBulletIndex = null);
}
},
onTapCancel: () {
if (!_isEditMode) {
setState(() => _highlightedBulletIndex = null);
}
},
child: AnimatedContainer( child: AnimatedContainer(
duration: const Duration(milliseconds: 200), duration: const Duration(milliseconds: 200),
height: 100, height: 100,
@@ -869,7 +993,8 @@ Widget build(BuildContext context) {
BoxShadow( BoxShadow(
color: Colors.black26, color: Colors.black26,
offset: Offset(0, 2), offset: Offset(0, 2),
blurRadius: 6), blurRadius: 6,
),
], ],
), ),
child: Column( child: Column(
@@ -898,9 +1023,7 @@ Widget build(BuildContext context) {
decoration: BoxDecoration( decoration: BoxDecoration(
color: isSelected color: isSelected
? Colors.red[400] ? Colors.red[400]
: (isManual : _bulletColor,
? Colors.red[600]
: _bulletColor),
borderRadius: const BorderRadius.only( borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(16), bottomLeft: Radius.circular(16),
bottomRight: Radius.circular(16), bottomRight: Radius.circular(16),
@@ -930,16 +1053,28 @@ Widget build(BuildContext context) {
const SizedBox(height: 12), const SizedBox(height: 12),
], ],
), ),
if (_hasMissingBullets)
Positioned( Positioned(
top: 12, top: 12,
right: 12, right: 12,
child: ElevatedButton.icon( child: ElevatedButton.icon(
onPressed: _handleMissingBullets, onPressed: () {
icon: const Icon(Icons.warning_amber_rounded, color: Colors.white, size: 20), setState(() {
label: const Text("Fix Bullets", style: TextStyle(color: Colors.white)), _isEditMode = !_isEditMode;
_selectedBulletIndexInEdit = null;
});
},
icon: Icon(
_isEditMode ? Icons.check : Icons.edit,
color: Colors.white,
size: 20,
),
label: Text(
_isEditMode ? "Done" : "Edit Bullets",
style: const TextStyle(color: Colors.white),
),
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
backgroundColor: Colors.red[600], backgroundColor: _bulletColor,
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10), borderRadius: BorderRadius.circular(10),
@@ -947,7 +1082,10 @@ Widget build(BuildContext context) {
elevation: 4, elevation: 4,
), ),
), ),
), ),
_buildEditController(),
], ],
), ),
bottomNavigationBar: BottomAppBar( bottomNavigationBar: BottomAppBar(