5f9e2a3b86
BOOK update.
1703 lines
70 KiB
Dart
1703 lines
70 KiB
Dart
import 'dart:io';
|
|
import 'dart:typed_data';
|
|
import 'dart:ui' as ui;
|
|
import 'package:flutter/material.dart';
|
|
import '../utils/target_colors.dart';
|
|
import '../theme/app_theme.dart';
|
|
import 'package:flutter/services.dart' show rootBundle, HapticFeedback;
|
|
import 'package:path_provider/path_provider.dart';
|
|
import 'yolo_detector.dart';
|
|
import 'dart:convert'; // For JSON encoding
|
|
import 'dart:math';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
import '../utils/translations.dart';
|
|
import '../utils/target_scoring.dart';
|
|
|
|
class PreviewScreen extends StatefulWidget {
|
|
final String imagePath;
|
|
final List<DetectionResult> detections;
|
|
final int bulletCount; // Add bulletCount parameter
|
|
|
|
const PreviewScreen(
|
|
{super.key,
|
|
required this.imagePath,
|
|
required this.detections,
|
|
required this.bulletCount});
|
|
|
|
@override
|
|
State<PreviewScreen> createState() => _PreviewScreenState();
|
|
}
|
|
|
|
enum PreviewMode { cameraWithDetections, mappedTarget }
|
|
|
|
class _PreviewScreenState extends State<PreviewScreen> {
|
|
bool _isLoading = true;
|
|
PreviewMode _mode = PreviewMode.mappedTarget;
|
|
|
|
List<Offset> _mappedBullets = [];
|
|
late List<DetectionResult> _realImageDetections;
|
|
|
|
Size? _realImageSize; // the photo; shown from its original bytes
|
|
Size? _targetImageSize; // the selected target skin
|
|
Future<Size?>? _targetImageFuture;
|
|
|
|
Uint8List? _cachedTargetImage;
|
|
Uint8List? _cachedRealImage;
|
|
|
|
late String targetAssetPath;
|
|
|
|
final Offset fixedRingTargetCenter = TargetScoring.center;
|
|
final Size fixedRingTargetSize = const Size(355.94, 359.27);
|
|
|
|
// Scale factors for different target image dimensions
|
|
double _scaleFactorX = 1.0;
|
|
double _scaleFactorY = 1.0;
|
|
Size? _defaultTargetSize; // Default target for reference dimensions
|
|
|
|
int? _highlightedBulletIndex;
|
|
|
|
final List<int> _manualBulletScores = [];
|
|
|
|
Color _bulletColor = Colors.blue; // default fallback
|
|
double get _bulletOpacity => 0.8;
|
|
|
|
bool _isEditMode = false;
|
|
int? _selectedBulletIndexInEdit;
|
|
|
|
// Hold-and-drag on the edit controller: moves the selected bullet with the
|
|
// finger while a magnifier shows the area around it.
|
|
bool _isDragMovingBullet = false;
|
|
Offset _lastDragOffset = Offset.zero;
|
|
double _displayScaleX = 1;
|
|
double _displayScaleY = 1;
|
|
static const double _loupeSize = 130;
|
|
static const double _loupeZoom = 2.5;
|
|
|
|
Color get _editColor => Colors.deepOrangeAccent;
|
|
Color get _activeColor => _isEditMode ? _editColor : _bulletColor;
|
|
Color get _activeColorWithOpacity =>
|
|
_activeColor.withValues(alpha: _bulletOpacity);
|
|
|
|
String _selectedLanguage = 'English';
|
|
Color _backgroundColor = Colors.grey[900]!;
|
|
|
|
String _currentFolderName = '';
|
|
String _currentDate = '';
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
_realImageDetections = widget.detections;
|
|
targetAssetPath = 'assets/target.png'; // Default
|
|
_loadCurrentFolderInfo();
|
|
_initializeScreen();
|
|
}
|
|
|
|
Future<void> _loadCurrentFolderInfo() async {
|
|
try {
|
|
final directory = await getApplicationDocumentsDirectory();
|
|
final saveDirectory = Directory('${directory.path}/saved_images');
|
|
|
|
if (await saveDirectory.exists()) {
|
|
final folders =
|
|
saveDirectory.listSync().whereType<Directory>().toList();
|
|
if (folders.isNotEmpty) {
|
|
// Sort by modification date to get the most recent folder
|
|
folders.sort(
|
|
(a, b) => b.statSync().changed.compareTo(a.statSync().changed));
|
|
final lastFolder = folders.first.path.split('/').last;
|
|
final today = DateTime.now();
|
|
final formattedDate =
|
|
"${today.day.toString().padLeft(2, '0')}-${today.month.toString().padLeft(2, '0')}-${today.year.toString().substring(2)}"; // DD-MM-YY format
|
|
|
|
setState(() {
|
|
_currentFolderName = lastFolder;
|
|
_currentDate = formattedDate;
|
|
});
|
|
}
|
|
}
|
|
} catch (e) {
|
|
debugPrint("Error loading current folder info: $e");
|
|
}
|
|
}
|
|
|
|
Future<void> _initializeScreen() async {
|
|
await Future.wait([
|
|
_loadDefaultTarget(), // Load default target for scale reference
|
|
_loadSelectedTarget(),
|
|
_loadBulletColor(),
|
|
_loadLanguage(),
|
|
]);
|
|
await _runDetectionAndMapping();
|
|
}
|
|
|
|
String _t(String key) {
|
|
return AppTranslations.translate(key, _selectedLanguage);
|
|
}
|
|
|
|
Future<void> _loadLanguage() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
setState(() {
|
|
_selectedLanguage = prefs.getString('language') ?? 'Slovenian';
|
|
});
|
|
}
|
|
|
|
Future<void> _loadDefaultTarget() async {
|
|
try {
|
|
final byteData = await rootBundle.load('assets/target.png');
|
|
_defaultTargetSize = await _imageSize(byteData.buffer.asUint8List());
|
|
} catch (e) {
|
|
debugPrint("❌ Error loading default target: $e");
|
|
}
|
|
}
|
|
|
|
Future<void> _loadSelectedTarget() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
// Always load the selected/skin target for display
|
|
// This is used for background and for calculating scale factors
|
|
final selectedTarget =
|
|
prefs.getString('selectedTarget') ?? 'assets/target.png';
|
|
|
|
// Update the target path and trigger image load
|
|
targetAssetPath = selectedTarget;
|
|
_targetImageFuture = _loadAndDecodeTargetImage();
|
|
_backgroundColor = _getBackgroundColorForTarget(selectedTarget);
|
|
|
|
// Await the image decoding to ensure it's populated before rebuilding
|
|
_targetImageSize = await _targetImageFuture;
|
|
if (_targetImageSize != null) {
|
|
// Calculate scale factors based on target dimensions
|
|
_calculateScaleFactors();
|
|
}
|
|
|
|
setState(() {
|
|
// Trigger rebuild with the new target
|
|
});
|
|
}
|
|
|
|
void _calculateScaleFactors() {
|
|
if (_defaultTargetSize == null || _targetImageSize == null) {
|
|
_scaleFactorX = 1.0;
|
|
_scaleFactorY = 1.0;
|
|
return;
|
|
}
|
|
_scaleFactorX = _targetImageSize!.width / _defaultTargetSize!.width;
|
|
_scaleFactorY = _targetImageSize!.height / _defaultTargetSize!.height;
|
|
|
|
debugPrint(
|
|
"📏 Scale factors calculated: X=$_scaleFactorX, Y=$_scaleFactorY");
|
|
}
|
|
|
|
// One source of truth for target colors (utils/target_colors.dart)
|
|
Color _getBackgroundColorForTarget(String targetPath) =>
|
|
TargetColors.getBackgroundColor(targetPath);
|
|
|
|
Future<void> _loadBulletColor() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final selectedColor = prefs.getString('bulletColor') ?? 'Blue';
|
|
|
|
setState(() {
|
|
_bulletColor = _getColorFromName(selectedColor);
|
|
});
|
|
}
|
|
|
|
Color _getColorFromName(String colorName) {
|
|
switch (colorName.toLowerCase()) {
|
|
case 'blue':
|
|
return Colors.blue;
|
|
case 'green':
|
|
return Colors.green;
|
|
case 'yellow':
|
|
return Colors.yellow;
|
|
case 'purple':
|
|
return Colors.purple;
|
|
case 'cyan':
|
|
return Colors.cyan;
|
|
case 'teal':
|
|
return Colors.teal;
|
|
case 'indigo':
|
|
return Colors.indigo;
|
|
case 'pink':
|
|
return Colors.pink;
|
|
case 'lime':
|
|
return Colors.lime;
|
|
case 'mint':
|
|
return Colors.greenAccent;
|
|
case 'orange':
|
|
return Colors.orange;
|
|
case 'violet':
|
|
return Colors.deepPurpleAccent;
|
|
case 'amber':
|
|
return Colors.amber;
|
|
case 'brown':
|
|
return Colors.brown;
|
|
case 'grey':
|
|
return Colors.grey;
|
|
default:
|
|
return Colors.blue; // fallback
|
|
}
|
|
}
|
|
|
|
// Default-target position for a shot scored by hand. TargetScoring puts it
|
|
// where it scores exactly [score]; the angle spreads the hand-entered shots.
|
|
Offset _generatePositionForScore(int score) {
|
|
// Calculate angle based on which manual bullet this will be (add randomness for distribution)
|
|
final bulletIndex = _manualBulletScores.length;
|
|
final angleIncrement = 360.0 / widget.bulletCount;
|
|
final baseAngle = angleIncrement * bulletIndex;
|
|
// Add random offset within the angle increment to vary positioning
|
|
final randomOffset = (Random().nextDouble() - 0.5) * angleIncrement * 0.5;
|
|
final angle = baseAngle + randomOffset;
|
|
return TargetScoring.positionFor(score, angle * pi / 180);
|
|
}
|
|
|
|
// Shown from the asset's own bytes; only its size is read
|
|
Future<Size?> _loadAndDecodeTargetImage() async {
|
|
final byteData = await rootBundle.load(targetAssetPath);
|
|
final bytes = byteData.buffer.asUint8List();
|
|
_cachedTargetImage = bytes;
|
|
return _imageSize(bytes);
|
|
}
|
|
|
|
// Width and height from the image header, without decoding the pixels
|
|
static Future<Size?> _imageSize(Uint8List bytes) async {
|
|
try {
|
|
final buffer = await ui.ImmutableBuffer.fromUint8List(bytes);
|
|
final descriptor = await ui.ImageDescriptor.encoded(buffer);
|
|
final size =
|
|
Size(descriptor.width.toDouble(), descriptor.height.toDouble());
|
|
descriptor.dispose();
|
|
buffer.dispose();
|
|
return size;
|
|
} catch (_) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
Future<void> _runDetectionAndMapping() async {
|
|
try {
|
|
// 1. Load target background image FIRST to calculate scale factors
|
|
_targetImageSize = await _targetImageFuture;
|
|
if (_targetImageSize != null) {
|
|
// Calculate scale factors based on target image dimensions
|
|
_calculateScaleFactors();
|
|
}
|
|
|
|
// 2. Read the real image file
|
|
final File realImageFile = File(widget.imagePath);
|
|
final realBytes = await realImageFile.readAsBytes();
|
|
|
|
// 3. Read its size (the header is enough; the pixels are shown as they are)
|
|
_realImageSize = await _imageSize(realBytes);
|
|
if (_realImageSize == null) {
|
|
debugPrint("❌ Failed to decode image from path: ${widget.imagePath}");
|
|
setState(() => _isLoading = false);
|
|
return;
|
|
}
|
|
|
|
// 4. Shown from the saved JPEG itself
|
|
_cachedRealImage = realBytes;
|
|
|
|
// 5. Find the detected ring center and size
|
|
final ringCamData = _getRingCenterSize(_realImageDetections);
|
|
if (ringCamData == null) {
|
|
debugPrint("⚠️ Ring (classId 2) not detected in real image.");
|
|
setState(() => _isLoading = false);
|
|
return;
|
|
}
|
|
|
|
final Offset ringCamCenter = ringCamData['center'];
|
|
final Size sizeCam = ringCamData['size'];
|
|
|
|
// 6. Extract all bullet centers (classId 0)
|
|
final List<Offset> bulletsCam = _realImageDetections
|
|
.where((r) => r.classId == 0)
|
|
.map((r) => Offset((r.x1 + r.x2) / 2, (r.y1 + r.y2) / 2))
|
|
.toList();
|
|
|
|
// 7. Step 1: Map bullets to DEFAULT target coordinate system (1200x1200)
|
|
final List<Map<String, dynamic>> scoredBullets = bulletsCam.map((bullet) {
|
|
final mappedToDefaultTarget = _mapToTargetNormalized(
|
|
bullet,
|
|
ringCamCenter,
|
|
fixedRingTargetCenter,
|
|
sizeCam,
|
|
fixedRingTargetSize,
|
|
);
|
|
final score = _scoreForBullet(mappedToDefaultTarget);
|
|
return {'bullet': mappedToDefaultTarget, 'score': score};
|
|
}).toList();
|
|
|
|
// 8. Trim to bullet limit by removing highest scoring ones
|
|
scoredBullets.sort((a, b) => b['score'].compareTo(a['score']));
|
|
while (scoredBullets.length > widget.bulletCount) {
|
|
scoredBullets.removeAt(0);
|
|
}
|
|
|
|
// 9. Step 2: Remap bullets from default target to actual display target
|
|
var mappedBullets = scoredBullets.map((bulletData) {
|
|
final defaultTargetBullet = bulletData['bullet'] as Offset;
|
|
// Scale bullet position based on actual target dimensions
|
|
final displayBullet = Offset(
|
|
defaultTargetBullet.dx * _scaleFactorX,
|
|
defaultTargetBullet.dy * _scaleFactorY,
|
|
);
|
|
return displayBullet;
|
|
}).toList();
|
|
|
|
// 10. Update state with remapped bullets
|
|
setState(() {
|
|
_mappedBullets = mappedBullets;
|
|
_isLoading = false;
|
|
});
|
|
} catch (e, stack) {
|
|
debugPrint("❌ Error during detection mapping: $e");
|
|
debugPrint(stack.toString());
|
|
setState(() {
|
|
_mappedBullets = [];
|
|
_isLoading = false;
|
|
});
|
|
}
|
|
}
|
|
|
|
void _showMissingBulletDialog(int bulletNum) {
|
|
showDialog(
|
|
context: context,
|
|
builder: (context) {
|
|
return Dialog(
|
|
backgroundColor: Colors.grey[900],
|
|
shape:
|
|
RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
|
child: Padding(
|
|
padding: const EdgeInsets.all(24.0),
|
|
child: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
Text(
|
|
'${_t('Bullet')} $bulletNum - ${_t('Bullet Score')}',
|
|
style: const TextStyle(
|
|
color: Colors.white,
|
|
fontSize: 20,
|
|
fontWeight: FontWeight.bold,
|
|
),
|
|
),
|
|
const SizedBox(height: 24),
|
|
// Score buttons 1-9 in 3x3 grid
|
|
GridView.count(
|
|
crossAxisCount: 3,
|
|
shrinkWrap: true,
|
|
mainAxisSpacing: 12,
|
|
crossAxisSpacing: 12,
|
|
childAspectRatio: 1.0,
|
|
children: List.generate(9, (scoreIndex) {
|
|
final score = 9 - scoreIndex;
|
|
return ElevatedButton(
|
|
onPressed: () {
|
|
final bulletPosition = _generatePositionForScore(score);
|
|
// Scale position from default coordinate system to display target size
|
|
final scaledBulletPosition = Offset(
|
|
bulletPosition.dx * _scaleFactorX,
|
|
bulletPosition.dy * _scaleFactorY,
|
|
);
|
|
|
|
setState(() {
|
|
_mappedBullets.add(scaledBulletPosition);
|
|
_manualBulletScores.add(score);
|
|
_isEditMode = true;
|
|
_selectedBulletIndexInEdit =
|
|
_mappedBullets.length - 1;
|
|
});
|
|
|
|
Navigator.pop(context);
|
|
},
|
|
style: ElevatedButton.styleFrom(
|
|
backgroundColor: _bulletColor,
|
|
foregroundColor: Colors.white,
|
|
padding: EdgeInsets.zero,
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius: BorderRadius.circular(12),
|
|
),
|
|
),
|
|
child: Text(
|
|
'$score',
|
|
style: const TextStyle(
|
|
fontSize: 24,
|
|
fontWeight: FontWeight.bold,
|
|
),
|
|
),
|
|
);
|
|
}),
|
|
),
|
|
const SizedBox(height: 12),
|
|
// Bottom row with 0 and 10
|
|
Row(
|
|
children: [
|
|
Expanded(
|
|
child: ElevatedButton(
|
|
onPressed: () {
|
|
final score = 0;
|
|
final bulletPosition =
|
|
_generatePositionForScore(score);
|
|
// Scale position from default coordinate system to display target size
|
|
final scaledBulletPosition = Offset(
|
|
bulletPosition.dx * _scaleFactorX,
|
|
bulletPosition.dy * _scaleFactorY,
|
|
);
|
|
|
|
setState(() {
|
|
_mappedBullets.add(scaledBulletPosition);
|
|
_manualBulletScores.add(score);
|
|
_isEditMode = true;
|
|
_selectedBulletIndexInEdit =
|
|
_mappedBullets.length - 1;
|
|
});
|
|
|
|
Navigator.pop(context);
|
|
},
|
|
style: ElevatedButton.styleFrom(
|
|
backgroundColor: Colors.grey[600],
|
|
foregroundColor: Colors.white,
|
|
padding: const EdgeInsets.symmetric(vertical: 16),
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius: BorderRadius.circular(12),
|
|
),
|
|
),
|
|
child: const Text(
|
|
'0',
|
|
style: TextStyle(
|
|
fontSize: 24,
|
|
fontWeight: FontWeight.bold,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
const SizedBox(width: 12),
|
|
Expanded(
|
|
child: ElevatedButton(
|
|
onPressed: () {
|
|
final score = 10;
|
|
final bulletPosition =
|
|
_generatePositionForScore(score);
|
|
// Scale position from default coordinate system to display target size
|
|
final scaledBulletPosition = Offset(
|
|
bulletPosition.dx * _scaleFactorX,
|
|
bulletPosition.dy * _scaleFactorY,
|
|
);
|
|
|
|
setState(() {
|
|
_mappedBullets.add(scaledBulletPosition);
|
|
_manualBulletScores.add(score);
|
|
_isEditMode = true;
|
|
_selectedBulletIndexInEdit =
|
|
_mappedBullets.length - 1;
|
|
});
|
|
|
|
Navigator.pop(context);
|
|
},
|
|
style: ElevatedButton.styleFrom(
|
|
backgroundColor: Colors.grey[600],
|
|
foregroundColor: Colors.white,
|
|
padding: const EdgeInsets.symmetric(vertical: 16),
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius: BorderRadius.circular(12),
|
|
),
|
|
),
|
|
child: const Text(
|
|
'10',
|
|
style: TextStyle(
|
|
fontSize: 24,
|
|
fontWeight: FontWeight.bold,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
},
|
|
);
|
|
}
|
|
|
|
Future<String?> _getLastFolder() async {
|
|
final directory = await getApplicationDocumentsDirectory();
|
|
final saveDirectory = Directory('${directory.path}/saved_images');
|
|
|
|
if (!await saveDirectory.exists()) {
|
|
return null;
|
|
}
|
|
|
|
final folders = saveDirectory.listSync().whereType<Directory>().toList();
|
|
if (folders.isEmpty) {
|
|
return null;
|
|
}
|
|
|
|
folders
|
|
.sort((a, b) => b.statSync().changed.compareTo(a.statSync().changed));
|
|
return folders.first.path.split('/').last;
|
|
}
|
|
|
|
Future<void> _saveToLastFolder() async {
|
|
try {
|
|
final lastFolder = await _getLastFolder();
|
|
if (lastFolder == null) {
|
|
// No last folder, show options dialog
|
|
_saveTargetDataWithDialog();
|
|
return;
|
|
}
|
|
|
|
await _performSave(lastFolder, false);
|
|
} catch (e) {
|
|
debugPrint("Error saving to last folder: $e");
|
|
}
|
|
}
|
|
|
|
Future<void> _saveTargetDataWithDialog() async {
|
|
try {
|
|
// Show a dialog to let the user select between a new folder or an existing one
|
|
final result = await _showSaveOptionsDialog();
|
|
|
|
if (result == null) return;
|
|
|
|
String? selectedFolder;
|
|
bool isTournament = false;
|
|
|
|
try {
|
|
final decoded = jsonDecode(result);
|
|
selectedFolder = decoded['folder'];
|
|
isTournament = decoded['isTournament'] == true;
|
|
} catch (_) {
|
|
selectedFolder =
|
|
result; // Treat plain string as folder name (existing folder)
|
|
}
|
|
|
|
if (selectedFolder == null) return;
|
|
|
|
await _performSave(selectedFolder, isTournament);
|
|
} catch (e) {
|
|
debugPrint("Error saving target data: $e");
|
|
}
|
|
}
|
|
|
|
Future<void> _performSave(String selectedFolder, bool isTournament) async {
|
|
try {
|
|
final directory = await getApplicationDocumentsDirectory();
|
|
final saveDirectory =
|
|
Directory('${directory.path}/saved_images/$selectedFolder');
|
|
|
|
// Create folder if it doesn't exist
|
|
if (!await saveDirectory.exists()) {
|
|
await saveDirectory.create(recursive: true);
|
|
}
|
|
|
|
// Save tournament metadata if applicable
|
|
if (isTournament) {
|
|
final metadataFile = File('${saveDirectory.path}/metadata.json');
|
|
await metadataFile.writeAsString(jsonEncode({'isTournament': true}));
|
|
}
|
|
|
|
// Use timestamp for a unique file name
|
|
final now = DateTime.now();
|
|
final dateString =
|
|
"${now.day.toString().padLeft(2, '0')}/${now.month.toString().padLeft(2, '0')}/${now.year}";
|
|
final dateStringFile = "${now.year}-${now.month}-${now.day}";
|
|
final timeString = "${now.hour}-${now.minute}-${now.second}";
|
|
final fileName = "target_${dateStringFile}_$timeString.json";
|
|
final filePath = '${saveDirectory.path}/$fileName';
|
|
|
|
// Prepare target data to save
|
|
// Convert bullets from display coordinates back to default target coordinates (1200x1200)
|
|
final bulletsInDefaultCoordinates = _mappedBullets.map((b) {
|
|
return {
|
|
'x': b.dx / _scaleFactorX,
|
|
'y': b.dy / _scaleFactorY,
|
|
};
|
|
}).toList();
|
|
|
|
// Score of every saved bullet, in the same order: hand-entered shots
|
|
// keep the score that was entered. The target view shows these as saved.
|
|
final scores = [for (int i = 0; i < _mappedBullets.length; i++) _scoreAt(i)];
|
|
|
|
final targetData = {
|
|
'date': dateString,
|
|
'totalScore': scores.fold(0, (a, b) => a + b),
|
|
'bulletCount': widget
|
|
.bulletCount, // shots fired; missed ones are absent from 'bullets'
|
|
'bullets': bulletsInDefaultCoordinates,
|
|
'scores': scores,
|
|
};
|
|
|
|
// Write file
|
|
final jsonFile = File(filePath);
|
|
await jsonFile.writeAsString(jsonEncode(targetData));
|
|
|
|
// Close preview and signal refresh
|
|
if (!mounted) return;
|
|
Navigator.pop(context, true);
|
|
} catch (e) {
|
|
debugPrint("Error performing save: $e");
|
|
}
|
|
}
|
|
|
|
/// Score of the bullet at [index], live for manual and detected bullets.
|
|
int _scoreAt(int index) {
|
|
final manualStart = _mappedBullets.length - _manualBulletScores.length;
|
|
if (index >= manualStart) {
|
|
return _manualBulletScores[index - manualStart];
|
|
}
|
|
final b = _mappedBullets[index];
|
|
return _scoreForBullet(Offset(b.dx / _scaleFactorX, b.dy / _scaleFactorY));
|
|
}
|
|
|
|
Widget _buildEditController() {
|
|
final index = _selectedBulletIndexInEdit;
|
|
if (!_isEditMode || index == null || index >= _mappedBullets.length) {
|
|
return const SizedBox.shrink();
|
|
}
|
|
|
|
final s = Surfaces.current;
|
|
final accent = _bulletColor;
|
|
final dragging = _isDragMovingBullet;
|
|
const padSize = 156.0;
|
|
const step = 3.0;
|
|
|
|
Widget arrow(IconData icon, Offset delta, Alignment align) {
|
|
return Align(
|
|
alignment: align,
|
|
child: Material(
|
|
color: Colors.transparent,
|
|
shape: const CircleBorder(),
|
|
clipBehavior: Clip.antiAlias,
|
|
child: InkWell(
|
|
onTap: () => _moveBullet(delta),
|
|
child: SizedBox(
|
|
width: 52,
|
|
height: 52,
|
|
child: Icon(icon, size: 34, color: s.textPrimary),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
return Positioned(
|
|
bottom: 20,
|
|
left: 0,
|
|
right: 0,
|
|
child: Center(
|
|
child: GestureDetector(
|
|
// Hold anywhere on the controller, then drag to move the bullet fast
|
|
onLongPressStart: (_) {
|
|
HapticFeedback.mediumImpact();
|
|
setState(() {
|
|
_isDragMovingBullet = true;
|
|
_lastDragOffset = Offset.zero;
|
|
});
|
|
},
|
|
onLongPressMoveUpdate: (details) {
|
|
final delta = details.offsetFromOrigin - _lastDragOffset;
|
|
_lastDragOffset = details.offsetFromOrigin;
|
|
// Finger movement on screen = bullet movement on screen
|
|
_moveBullet(Offset(
|
|
delta.dx / _displayScaleX,
|
|
delta.dy / _displayScaleY,
|
|
));
|
|
},
|
|
onLongPressEnd: (_) => setState(() => _isDragMovingBullet = false),
|
|
onLongPressCancel: () => setState(() => _isDragMovingBullet = false),
|
|
child: AnimatedContainer(
|
|
duration: const Duration(milliseconds: 150),
|
|
width: 200,
|
|
decoration: BoxDecoration(
|
|
color: s.card,
|
|
borderRadius: BorderRadius.circular(20),
|
|
border: Border.all(
|
|
color: dragging ? accent : Colors.transparent,
|
|
width: 2,
|
|
),
|
|
boxShadow: const [
|
|
BoxShadow(
|
|
color: Colors.black38,
|
|
offset: Offset(0, 4),
|
|
blurRadius: 12,
|
|
),
|
|
],
|
|
),
|
|
child: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
// Header: which bullet, and its live score
|
|
Padding(
|
|
padding: const EdgeInsets.fromLTRB(16, 12, 12, 4),
|
|
child: Row(
|
|
children: [
|
|
Text(
|
|
'${_t('Bullet')} ${index + 1}'.toUpperCase(),
|
|
style: TextStyle(
|
|
fontSize: 12,
|
|
fontWeight: FontWeight.bold,
|
|
letterSpacing: 1.4,
|
|
color: s.textSecondary,
|
|
),
|
|
),
|
|
const Spacer(),
|
|
Container(
|
|
constraints: const BoxConstraints(minWidth: 36),
|
|
padding: const EdgeInsets.symmetric(
|
|
horizontal: 10, vertical: 4),
|
|
decoration: BoxDecoration(
|
|
color: accent,
|
|
borderRadius: BorderRadius.circular(10),
|
|
),
|
|
alignment: Alignment.center,
|
|
child: Text(
|
|
'${_scoreAt(index)}',
|
|
style: const TextStyle(
|
|
color: Colors.white,
|
|
fontSize: 16,
|
|
fontWeight: FontWeight.bold,
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
// Round d-pad with "done" in the middle
|
|
Padding(
|
|
padding: const EdgeInsets.symmetric(vertical: 8),
|
|
child: Container(
|
|
width: padSize,
|
|
height: padSize,
|
|
decoration: BoxDecoration(
|
|
shape: BoxShape.circle,
|
|
color: s.textPrimary.withValues(alpha: 0.06),
|
|
border: Border.all(color: s.divider),
|
|
),
|
|
child: Stack(
|
|
children: [
|
|
arrow(Icons.keyboard_arrow_up_rounded,
|
|
const Offset(0, -step), Alignment.topCenter),
|
|
arrow(Icons.keyboard_arrow_down_rounded,
|
|
const Offset(0, step), Alignment.bottomCenter),
|
|
arrow(Icons.keyboard_arrow_left_rounded,
|
|
const Offset(-step, 0), Alignment.centerLeft),
|
|
arrow(Icons.keyboard_arrow_right_rounded,
|
|
const Offset(step, 0), Alignment.centerRight),
|
|
Center(
|
|
child: Material(
|
|
color: accent,
|
|
shape: const CircleBorder(),
|
|
elevation: 2,
|
|
child: InkWell(
|
|
customBorder: const CircleBorder(),
|
|
onTap: () => setState(
|
|
() => _selectedBulletIndexInEdit = null),
|
|
child: SizedBox(
|
|
width: 52,
|
|
height: 52,
|
|
child: Icon(
|
|
dragging
|
|
? Icons.open_with_rounded
|
|
: Icons.check_rounded,
|
|
color: Colors.white,
|
|
size: 28,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
Padding(
|
|
padding: const EdgeInsets.only(bottom: 12),
|
|
child: Text(
|
|
_t('Hold and drag to move'),
|
|
style: TextStyle(fontSize: 11, color: s.textSecondary),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
/// Magnifier shown above the selected bullet while it is being dragged.
|
|
Widget _buildBulletLoupe(Offset bullet, double scaleX, double scaleY,
|
|
double offsetX, double offsetY) {
|
|
final bx = bullet.dx * scaleX + offsetX;
|
|
final by = bullet.dy * scaleY + offsetY;
|
|
const gap = _loupeSize / 2 + 40;
|
|
// Put the loupe above the bullet, or below it when there is no room.
|
|
final cy = by - gap - _loupeSize / 2 >= 0 ? by - gap : by + gap;
|
|
return Positioned(
|
|
left: bx - _loupeSize / 2,
|
|
top: cy - _loupeSize / 2,
|
|
child: IgnorePointer(
|
|
child: RawMagnifier(
|
|
size: const Size(_loupeSize, _loupeSize),
|
|
magnificationScale: _loupeZoom,
|
|
focalPointOffset: Offset(0, by - cy),
|
|
decoration: const MagnifierDecoration(
|
|
shape: CircleBorder(
|
|
side: BorderSide(color: Colors.white, width: 3),
|
|
),
|
|
shadows: [BoxShadow(color: Colors.black54, blurRadius: 8)],
|
|
),
|
|
child: const Center(
|
|
child: Icon(Icons.add, color: Colors.red, size: 24),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
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) {
|
|
// Scale bullet back to default coordinate system for scoring
|
|
final defaultTargetBullet = Offset(
|
|
updated.dx / _scaleFactorX,
|
|
updated.dy / _scaleFactorY,
|
|
);
|
|
final updatedScore = _scoreForBullet(defaultTargetBullet);
|
|
_manualBulletScores[index - manualStartIndex] = updatedScore;
|
|
}
|
|
});
|
|
}
|
|
|
|
Future<String?> _showSaveOptionsDialog() async {
|
|
final directory = await getApplicationDocumentsDirectory();
|
|
final saveDirectory = Directory('${directory.path}/saved_images');
|
|
|
|
if (!await saveDirectory.exists()) {
|
|
await saveDirectory.create(recursive: true);
|
|
}
|
|
|
|
final folders = saveDirectory.listSync().whereType<Directory>().toList();
|
|
|
|
// Sort to get most recently modified
|
|
folders
|
|
.sort((a, b) => b.statSync().changed.compareTo(a.statSync().changed));
|
|
|
|
// Auto-generate next Training and Tournament folder names
|
|
int trainingCount = 1;
|
|
int tournamentCount = 1;
|
|
|
|
// Get localized folder names
|
|
final trainingWord = _t('Training');
|
|
final tournamentWord = _t('Tournament');
|
|
|
|
for (var folder in folders) {
|
|
final name = folder.path.split('/').last;
|
|
// Numbering continues across languages (English, Slovenian, German names)
|
|
final training = RegExp(r'^(?:Training|Trening) (\d+)$').firstMatch(name);
|
|
if (training != null) {
|
|
final num = int.parse(training.group(1)!);
|
|
if (num >= trainingCount) trainingCount = num + 1;
|
|
}
|
|
final tournament = RegExp(r'^(?:Tournament|Tekmovanje|Wettkampf) (\d+)$')
|
|
.firstMatch(name);
|
|
if (tournament != null) {
|
|
final num = int.parse(tournament.group(1)!);
|
|
if (num >= tournamentCount) tournamentCount = num + 1;
|
|
}
|
|
}
|
|
|
|
final String nextTraining = '$trainingWord $trainingCount';
|
|
final String nextTournament = '$tournamentWord $tournamentCount';
|
|
|
|
if (!mounted) return null;
|
|
return showDialog<String>(
|
|
context: context,
|
|
builder: (context) {
|
|
return Dialog(
|
|
backgroundColor: Colors.grey[900],
|
|
shape:
|
|
RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
|
child: Padding(
|
|
padding: const EdgeInsets.all(24),
|
|
child: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
Text(
|
|
_t('Save Target Data'),
|
|
style: const TextStyle(
|
|
color: Colors.white,
|
|
fontSize: 20,
|
|
fontWeight: FontWeight.bold,
|
|
),
|
|
),
|
|
const SizedBox(height: 24),
|
|
|
|
// 🎯 Training Button (New folder)
|
|
SizedBox(
|
|
width: double.infinity,
|
|
child: ElevatedButton(
|
|
onPressed: () {
|
|
Navigator.pop(
|
|
context,
|
|
jsonEncode(
|
|
{'folder': nextTraining, 'isTournament': false}),
|
|
);
|
|
},
|
|
style: ElevatedButton.styleFrom(
|
|
backgroundColor: _bulletColor,
|
|
foregroundColor: Colors.white,
|
|
padding: const EdgeInsets.symmetric(vertical: 16),
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius: BorderRadius.circular(12),
|
|
),
|
|
),
|
|
child: Column(
|
|
children: [
|
|
Row(
|
|
mainAxisAlignment: MainAxisAlignment.center,
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
const Icon(Icons.track_changes,
|
|
size: 16, color: Colors.white),
|
|
const SizedBox(width: 8),
|
|
Text(
|
|
nextTraining,
|
|
style: const TextStyle(
|
|
fontWeight: FontWeight.bold,
|
|
fontSize: 16,
|
|
color: Colors.white),
|
|
),
|
|
],
|
|
),
|
|
const SizedBox(height: 4),
|
|
Text(
|
|
_t('New folder'),
|
|
style: const TextStyle(
|
|
fontSize: 12, color: Colors.white70),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
const SizedBox(height: 12),
|
|
|
|
// 🏆 Tournament Button (New folder)
|
|
SizedBox(
|
|
width: double.infinity,
|
|
child: ElevatedButton(
|
|
onPressed: () {
|
|
Navigator.pop(
|
|
context,
|
|
jsonEncode(
|
|
{'folder': nextTournament, 'isTournament': true}),
|
|
);
|
|
},
|
|
style: ElevatedButton.styleFrom(
|
|
backgroundColor: _bulletColor,
|
|
foregroundColor: Colors.white,
|
|
padding: const EdgeInsets.symmetric(vertical: 16),
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius: BorderRadius.circular(12),
|
|
),
|
|
),
|
|
child: Column(
|
|
children: [
|
|
Row(
|
|
mainAxisAlignment: MainAxisAlignment.center,
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
const Icon(Icons.emoji_events,
|
|
size: 16, color: Colors.white),
|
|
const SizedBox(width: 8),
|
|
Text(
|
|
nextTournament,
|
|
style: const TextStyle(
|
|
fontWeight: FontWeight.bold,
|
|
fontSize: 16,
|
|
color: Colors.white),
|
|
),
|
|
],
|
|
),
|
|
const SizedBox(height: 4),
|
|
Text(
|
|
_t('New folder'),
|
|
style: const TextStyle(
|
|
fontSize: 12, color: Colors.white70),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
},
|
|
);
|
|
}
|
|
|
|
Map<String, dynamic>? _getRingCenterSize(List<DetectionResult> results) {
|
|
try {
|
|
final ring = results.firstWhere((r) => r.classId == 2);
|
|
final cx = (ring.x1 + ring.x2) / 2;
|
|
final cy = (ring.y1 + ring.y2) / 2;
|
|
final width = ring.x2 - ring.x1;
|
|
final height = ring.y2 - ring.y1;
|
|
return {
|
|
'center': Offset(cx, cy),
|
|
'size': Size(width, height),
|
|
};
|
|
} catch (_) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
Offset _mapToTargetNormalized(Offset bulletCam, Offset ringCam,
|
|
Offset ringTarget, Size sizeCam, Size sizeTarget) {
|
|
// Calculate scale factor between detected ring and target ring
|
|
final scaleX = sizeTarget.width / sizeCam.width;
|
|
final scaleY = sizeTarget.height / sizeCam.height;
|
|
|
|
// Translate bullet position relative to ring center
|
|
final relativeX = bulletCam.dx - ringCam.dx;
|
|
final relativeY = bulletCam.dy - ringCam.dy;
|
|
|
|
// Scale the relative position and map to target
|
|
final mappedX = (relativeX * scaleX) + ringTarget.dx;
|
|
final mappedY = (relativeY * scaleY) + ringTarget.dy;
|
|
|
|
return Offset(mappedX, mappedY);
|
|
}
|
|
|
|
// Bullet in default target coordinates
|
|
int _scoreForBullet(Offset bullet) => TargetScoring.scoreAt(bullet);
|
|
|
|
int get _totalScore {
|
|
// Score is based on the default target coordinate system (1200x1200)
|
|
// since bullets were mapped to that system and then scaled for display
|
|
// Manual bullets are appended after the detected ones and scored below,
|
|
// so take only the detected ones here (at most the remaining shot slots).
|
|
final detected = _mappedBullets.length - _manualBulletScores.length;
|
|
final autoScore = _mappedBullets
|
|
.take(min(detected, widget.bulletCount - _manualBulletScores.length))
|
|
.map((b) {
|
|
// Scale bullet back to default coordinate system for scoring
|
|
final defaultTargetBullet = Offset(
|
|
b.dx / _scaleFactorX,
|
|
b.dy / _scaleFactorY,
|
|
);
|
|
return _scoreForBullet(defaultTargetBullet);
|
|
}).fold(0, (sum, score) => sum + score);
|
|
|
|
final manualScore = _manualBulletScores.fold(0, (a, b) => a + b);
|
|
|
|
return autoScore + manualScore;
|
|
}
|
|
|
|
Color _getBulletButtonColor(int index) {
|
|
final isSelected = _isEditMode
|
|
? index == _selectedBulletIndexInEdit
|
|
: index == _highlightedBulletIndex;
|
|
|
|
if (isSelected) return Colors.red;
|
|
|
|
final manualStart = _mappedBullets.length - _manualBulletScores.length;
|
|
final isManual = index >= manualStart;
|
|
|
|
if (isManual) return Colors.redAccent; // ⬅️ Light red for manual bullets
|
|
|
|
if (_isEditMode) return _editColor;
|
|
|
|
return _bulletColor;
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Scaffold(
|
|
backgroundColor: _backgroundColor,
|
|
appBar: AppBar(
|
|
backgroundColor: Colors.grey[900],
|
|
iconTheme: const IconThemeData(color: Colors.white),
|
|
title: Text(
|
|
_t('Detection Preview'),
|
|
style: const TextStyle(color: Colors.white),
|
|
),
|
|
actions: [
|
|
IconButton(
|
|
icon: Icon(
|
|
_mode == PreviewMode.mappedTarget
|
|
? Icons.camera_alt
|
|
: Icons.center_focus_strong,
|
|
color: Colors.white,
|
|
size: 24,
|
|
),
|
|
onPressed: () async {
|
|
setState(() {
|
|
_mode = _mode == PreviewMode.mappedTarget
|
|
? PreviewMode.cameraWithDetections
|
|
: PreviewMode.mappedTarget;
|
|
});
|
|
await _loadSelectedTarget();
|
|
},
|
|
tooltip: _mode == PreviewMode.mappedTarget
|
|
? _t("Show Camera Detections")
|
|
: _t("Show Mapped Target"),
|
|
),
|
|
const SizedBox(width: 8),
|
|
],
|
|
),
|
|
body: _isLoading
|
|
? const Center(child: CircularProgressIndicator())
|
|
: Stack(
|
|
children: [
|
|
Column(
|
|
children: [
|
|
// Training/Tournament Banner
|
|
Container(
|
|
color: Surfaces.current.card,
|
|
padding: const EdgeInsets.symmetric(
|
|
horizontal: 16, vertical: 10),
|
|
child: Row(
|
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
|
children: [
|
|
Expanded(
|
|
child: Text(
|
|
_currentFolderName.isNotEmpty
|
|
? _currentFolderName
|
|
: _t('No training selected'),
|
|
style: TextStyle(
|
|
color: Surfaces.current.textPrimary,
|
|
fontSize: 13,
|
|
fontWeight: FontWeight.w600,
|
|
),
|
|
overflow: TextOverflow.ellipsis,
|
|
),
|
|
),
|
|
if (_currentDate.isNotEmpty)
|
|
Text(
|
|
_currentDate,
|
|
style: TextStyle(
|
|
color: Surfaces.current.textPrimary,
|
|
fontSize: 11,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
Expanded(
|
|
child: LayoutBuilder(
|
|
builder: (context, constraints) {
|
|
final screenWidth = constraints.maxWidth;
|
|
final screenHeight = constraints.maxHeight;
|
|
|
|
final displayImage = _mode == PreviewMode.mappedTarget
|
|
? _cachedTargetImage
|
|
: _cachedRealImage;
|
|
|
|
final imgData = _mode == PreviewMode.mappedTarget
|
|
? _targetImageSize
|
|
: _realImageSize;
|
|
|
|
if (displayImage == null || imgData == null) {
|
|
return const Center(
|
|
child: Text("Image not available"));
|
|
}
|
|
|
|
final imgWidth = imgData.width.toDouble();
|
|
final imgHeight = imgData.height.toDouble();
|
|
final aspectRatio = imgWidth / imgHeight;
|
|
final screenAspect = screenWidth / screenHeight;
|
|
|
|
double displayWidth, displayHeight, offsetX, offsetY;
|
|
|
|
if (aspectRatio > screenAspect) {
|
|
displayWidth = screenWidth;
|
|
displayHeight = screenWidth / aspectRatio;
|
|
offsetX = 0;
|
|
offsetY = (screenHeight - displayHeight) / 2;
|
|
} else {
|
|
displayHeight = screenHeight;
|
|
displayWidth = screenHeight * aspectRatio;
|
|
offsetY = 0;
|
|
offsetX = (screenWidth - displayWidth) / 2;
|
|
}
|
|
|
|
final scaleX = displayWidth / imgWidth;
|
|
final scaleY = displayHeight / imgHeight;
|
|
_displayScaleX = scaleX;
|
|
_displayScaleY = scaleY;
|
|
|
|
final imageWidget =
|
|
Image.memory(displayImage, fit: BoxFit.fill);
|
|
|
|
return Stack(
|
|
children: [
|
|
Positioned(
|
|
left: offsetX,
|
|
top: offsetY,
|
|
width: displayWidth,
|
|
height: displayHeight,
|
|
child: imageWidget,
|
|
),
|
|
if (_mode == PreviewMode.cameraWithDetections)
|
|
..._realImageDetections.map((d) {
|
|
final left = d.x1 * scaleX + offsetX;
|
|
final top = d.y1 * scaleY + offsetY;
|
|
final width = (d.x2 - d.x1) * scaleX;
|
|
final height = (d.y2 - d.y1) * scaleY;
|
|
return Positioned(
|
|
left: left,
|
|
top: top,
|
|
width: width,
|
|
height: height,
|
|
child: Container(
|
|
decoration: BoxDecoration(
|
|
border: Border.all(
|
|
color: Colors.green, width: 2),
|
|
),
|
|
child: Align(
|
|
alignment: Alignment.topLeft,
|
|
child: Container(
|
|
color: Colors.green
|
|
.withValues(alpha: 0.5),
|
|
padding: const EdgeInsets.symmetric(
|
|
horizontal: 4, vertical: 2),
|
|
child: Text(
|
|
"ID:${d.classId} ${(d.confidence * 100).toStringAsFixed(1)}%",
|
|
style: const TextStyle(
|
|
color: Colors.white,
|
|
fontSize: 12,
|
|
fontWeight: FontWeight.bold,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}),
|
|
if (_mode == PreviewMode.mappedTarget)
|
|
..._mappedBullets
|
|
.asMap()
|
|
.entries
|
|
.take(widget.bulletCount)
|
|
.map((entry) {
|
|
final index = entry.key;
|
|
final b = entry.value;
|
|
final dx = b.dx * scaleX + offsetX;
|
|
final dy = b.dy * scaleY + offsetY;
|
|
// Scale bullet size by target scale factors and display scale factors
|
|
final double bulletSize =
|
|
(((_scaleFactorX + _scaleFactorY) / 2) *
|
|
53) *
|
|
((scaleX + scaleY) / 2);
|
|
|
|
final isHighlighted =
|
|
index == _highlightedBulletIndex;
|
|
final isSelectedForEdit =
|
|
index == _selectedBulletIndexInEdit;
|
|
final manualStart = _mappedBullets.length -
|
|
_manualBulletScores.length;
|
|
final isManual = index >= manualStart;
|
|
|
|
final Color bulletFillColor =
|
|
isSelectedForEdit ||
|
|
(!_isEditMode && isHighlighted)
|
|
? Colors.red.withValues(
|
|
alpha: _bulletOpacity)
|
|
: isManual
|
|
? Colors.red.withValues(
|
|
alpha: _bulletOpacity)
|
|
: _activeColorWithOpacity;
|
|
|
|
return Positioned(
|
|
left: dx - bulletSize / 2,
|
|
top: dy - bulletSize / 2,
|
|
child: Container(
|
|
width: bulletSize,
|
|
height: bulletSize,
|
|
decoration: BoxDecoration(
|
|
color: bulletFillColor,
|
|
shape: BoxShape.circle,
|
|
border: Border.all(
|
|
color: (isSelectedForEdit ||
|
|
(!_isEditMode &&
|
|
isHighlighted))
|
|
? Colors.red
|
|
: Colors.black,
|
|
width: (isSelectedForEdit ||
|
|
(!_isEditMode &&
|
|
isHighlighted))
|
|
? 3
|
|
: 1,
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}),
|
|
if (_mode == PreviewMode.mappedTarget &&
|
|
_isDragMovingBullet &&
|
|
_selectedBulletIndexInEdit != null &&
|
|
_selectedBulletIndexInEdit! <
|
|
_mappedBullets.length)
|
|
_buildBulletLoupe(
|
|
_mappedBullets[_selectedBulletIndexInEdit!],
|
|
scaleX,
|
|
scaleY,
|
|
offsetX,
|
|
offsetY,
|
|
),
|
|
],
|
|
);
|
|
},
|
|
),
|
|
),
|
|
const SizedBox(height: 24),
|
|
// Shown even with no detections, so missed shots can be scored by hand
|
|
if (widget.bulletCount > 0)
|
|
Column(
|
|
children: [
|
|
// Score buttons for detected and missing bullets
|
|
Padding(
|
|
padding: const EdgeInsets.symmetric(
|
|
horizontal: 12, vertical: 6),
|
|
child: AbsorbPointer(
|
|
absorbing: _isEditMode &&
|
|
_selectedBulletIndexInEdit != null,
|
|
child: Row(
|
|
children: [
|
|
// Detected bullets
|
|
...List.generate(
|
|
_mappedBullets.length,
|
|
(index) {
|
|
final bullet = _mappedBullets[index];
|
|
final isManual = index >=
|
|
(_mappedBullets.length -
|
|
_manualBulletScores.length);
|
|
final score = isManual
|
|
? _manualBulletScores[index -
|
|
(_mappedBullets.length -
|
|
_manualBulletScores.length)]
|
|
// Convert bullet back to default coordinate system for scoring
|
|
: _scoreForBullet(Offset(
|
|
bullet.dx / _scaleFactorX,
|
|
bullet.dy / _scaleFactorY,
|
|
));
|
|
|
|
return Expanded(
|
|
child: Padding(
|
|
padding: const EdgeInsets.symmetric(
|
|
horizontal: 6),
|
|
child: GestureDetector(
|
|
onTap: () {
|
|
if (_isEditMode) {
|
|
setState(() =>
|
|
_selectedBulletIndexInEdit =
|
|
index);
|
|
}
|
|
},
|
|
onTapDown: (_) {
|
|
if (!_isEditMode) {
|
|
setState(() =>
|
|
_highlightedBulletIndex =
|
|
index);
|
|
}
|
|
},
|
|
onTapUp: (_) {
|
|
if (!_isEditMode) {
|
|
setState(() =>
|
|
_highlightedBulletIndex =
|
|
null);
|
|
}
|
|
},
|
|
onTapCancel: () {
|
|
if (!_isEditMode) {
|
|
setState(() =>
|
|
_highlightedBulletIndex =
|
|
null);
|
|
}
|
|
},
|
|
child: AnimatedContainer(
|
|
duration: const Duration(
|
|
milliseconds: 200),
|
|
height: 100,
|
|
decoration: BoxDecoration(
|
|
borderRadius:
|
|
BorderRadius.circular(16),
|
|
boxShadow: const [
|
|
BoxShadow(
|
|
color: Colors.black26,
|
|
offset: Offset(0, 2),
|
|
blurRadius: 6,
|
|
),
|
|
],
|
|
),
|
|
child: Column(
|
|
children: [
|
|
Container(
|
|
height: 30,
|
|
decoration: BoxDecoration(
|
|
color:
|
|
Surfaces.current.card,
|
|
borderRadius:
|
|
const BorderRadius
|
|
.only(
|
|
topLeft:
|
|
Radius.circular(16),
|
|
topRight:
|
|
Radius.circular(16),
|
|
),
|
|
),
|
|
alignment: Alignment.center,
|
|
child: Text(
|
|
'${index + 1}',
|
|
style: TextStyle(
|
|
fontWeight:
|
|
FontWeight.bold,
|
|
fontSize: 14,
|
|
color: Surfaces.current
|
|
.textPrimary,
|
|
),
|
|
),
|
|
),
|
|
Expanded(
|
|
child: Container(
|
|
decoration: BoxDecoration(
|
|
color:
|
|
_getBulletButtonColor(
|
|
index),
|
|
borderRadius:
|
|
const BorderRadius
|
|
.only(
|
|
bottomLeft:
|
|
Radius.circular(
|
|
16),
|
|
bottomRight:
|
|
Radius.circular(
|
|
16),
|
|
),
|
|
),
|
|
alignment:
|
|
Alignment.center,
|
|
child: Text(
|
|
'$score',
|
|
style: const TextStyle(
|
|
fontSize: 28,
|
|
fontWeight:
|
|
FontWeight.bold,
|
|
color: Colors.white,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
},
|
|
),
|
|
// Missing bullets
|
|
...List.generate(
|
|
widget.bulletCount - _mappedBullets.length,
|
|
(index) {
|
|
final bulletNum =
|
|
_mappedBullets.length + index + 1;
|
|
return Expanded(
|
|
child: Padding(
|
|
padding: const EdgeInsets.symmetric(
|
|
horizontal: 6),
|
|
child: GestureDetector(
|
|
onTap: () {
|
|
_showMissingBulletDialog(
|
|
bulletNum);
|
|
},
|
|
child: Container(
|
|
height: 100,
|
|
decoration: BoxDecoration(
|
|
borderRadius:
|
|
BorderRadius.circular(16),
|
|
boxShadow: const [
|
|
BoxShadow(
|
|
color: Colors.black26,
|
|
offset: Offset(0, 2),
|
|
blurRadius: 6,
|
|
),
|
|
],
|
|
),
|
|
child: Column(
|
|
children: [
|
|
Container(
|
|
height: 30,
|
|
decoration: BoxDecoration(
|
|
color:
|
|
Surfaces.current.card,
|
|
borderRadius:
|
|
const BorderRadius
|
|
.only(
|
|
topLeft:
|
|
Radius.circular(16),
|
|
topRight:
|
|
Radius.circular(16),
|
|
),
|
|
),
|
|
alignment: Alignment.center,
|
|
child: Text(
|
|
'$bulletNum',
|
|
style: TextStyle(
|
|
fontWeight:
|
|
FontWeight.bold,
|
|
fontSize: 14,
|
|
color: Surfaces.current
|
|
.textPrimary,
|
|
),
|
|
),
|
|
),
|
|
Expanded(
|
|
child: Container(
|
|
decoration: BoxDecoration(
|
|
color: Colors.redAccent,
|
|
borderRadius:
|
|
const BorderRadius
|
|
.only(
|
|
bottomLeft:
|
|
Radius.circular(
|
|
16),
|
|
bottomRight:
|
|
Radius.circular(
|
|
16),
|
|
),
|
|
),
|
|
alignment:
|
|
Alignment.center,
|
|
child: const Text(
|
|
'?',
|
|
style: TextStyle(
|
|
fontSize: 32,
|
|
fontWeight:
|
|
FontWeight.bold,
|
|
color: Colors.white,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
},
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
// Room for the save button, which sticks up out of the bottom bar
|
|
const SizedBox(height: 40),
|
|
],
|
|
),
|
|
_buildEditController(),
|
|
],
|
|
),
|
|
// Same layout as the camera screen: number on the left, round white
|
|
// main action docked in the notch, secondary icons on the right.
|
|
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
|
|
floatingActionButton: FloatingActionButton(
|
|
backgroundColor: Colors.white,
|
|
onPressed: _saveToLastFolder,
|
|
tooltip: _t("Save"),
|
|
child: const Icon(Icons.save, color: Colors.black),
|
|
),
|
|
bottomNavigationBar: BottomAppBar(
|
|
color: Colors.grey[900],
|
|
shape: const CircularNotchedRectangle(),
|
|
notchMargin: 8.0,
|
|
child: SizedBox(
|
|
height: 60,
|
|
child: Row(
|
|
children: [
|
|
// Left - total score
|
|
Expanded(
|
|
child: Padding(
|
|
padding: const EdgeInsets.only(left: 16),
|
|
child: Column(
|
|
mainAxisAlignment: MainAxisAlignment.center,
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text(
|
|
_t('Total').toUpperCase(),
|
|
style: const TextStyle(
|
|
fontSize: 10,
|
|
fontWeight: FontWeight.bold,
|
|
letterSpacing: 1.2,
|
|
color: Colors.white54,
|
|
),
|
|
),
|
|
Text(
|
|
'$_totalScore',
|
|
style: const TextStyle(
|
|
fontSize: 24,
|
|
fontWeight: FontWeight.bold,
|
|
color: Colors.white,
|
|
height: 1.1,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
// Center space for FAB
|
|
const SizedBox(width: 80),
|
|
// Right - save to another folder, edit mode
|
|
Expanded(
|
|
child: Row(
|
|
mainAxisAlignment: MainAxisAlignment.end,
|
|
children: [
|
|
IconButton(
|
|
icon: const Icon(Icons.create_new_folder_outlined,
|
|
color: Colors.white, size: 24),
|
|
onPressed: _saveTargetDataWithDialog,
|
|
tooltip: _t("Save to folder"),
|
|
),
|
|
IconButton(
|
|
icon: Icon(
|
|
_isEditMode ? Icons.check : Icons.edit,
|
|
color: _isEditMode ? Colors.red : Colors.white,
|
|
size: 24,
|
|
),
|
|
onPressed: () {
|
|
setState(() {
|
|
_isEditMode = !_isEditMode;
|
|
_selectedBulletIndexInEdit = null;
|
|
});
|
|
},
|
|
tooltip:
|
|
_isEditMode ? _t("Done Editing") : _t("Edit Mode"),
|
|
),
|
|
const SizedBox(width: 4),
|
|
],
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|