new UI + new targets.

This commit is contained in:
Jan Pleterski
2026-11-27 14:37:44 +01:00
parent 5f9e2a3b86
commit 2fc741a9f6
113 changed files with 6861 additions and 7381 deletions
+265 -245
View File
@@ -7,11 +7,12 @@ import 'package:camera/camera.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'yolo_detector.dart';
import 'preview_screen.dart';
import '../utils/translations.dart';
import '../utils/target_colors.dart';
import '../theme/app_theme.dart';
import '../utils/format.dart';
import '../services/app_settings.dart';
import '../widgets/camera_sheet.dart';
import '../widgets/help_sheet.dart';
import '../widgets/ui.dart';
class CameraScreen extends StatefulWidget {
const CameraScreen({super.key});
@@ -25,12 +26,9 @@ class _CameraScreenState extends State<CameraScreen> {
Future<void>? _initializeControllerFuture;
YOLODetector? _yoloDetector; // null until the model has loaded
bool _processing = false; // a photo is being analysed
Color _bulletColor = Colors.blue; // default fallback
// The variable to hold the number of bullets entered by the user (default set to 5)
int _numberOfBullets = 5;
String _selectedLanguage = 'English';
late Color _backgroundColor;
// Real camera controls (they change the photo itself)
double _exposure = 0, _minExposure = 0, _maxExposure = 0;
@@ -40,13 +38,8 @@ class _CameraScreenState extends State<CameraScreen> {
@override
void initState() {
super.initState();
// Initialize with default target background color
_backgroundColor = TargetColors.getBackgroundColor('assets/target.png');
_loadBulletCount();
_initCamera();
_loadBulletColor(); // 👈
_loadLanguage();
_loadSelectedTargetColor();
YOLODetector.create().then((detector) {
if (mounted) {
_yoloDetector = detector;
@@ -56,70 +49,7 @@ class _CameraScreenState extends State<CameraScreen> {
});
}
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> _loadSelectedTargetColor() async {
final prefs = await SharedPreferences.getInstance();
final selectedTarget =
prefs.getString('selectedTarget') ?? 'assets/target.png';
setState(() {
_backgroundColor = TargetColors.getBackgroundColor(selectedTarget);
});
}
Future<void> _loadBulletColor() async {
final prefs = await SharedPreferences.getInstance();
final selected = prefs.getString('bulletColor') ?? 'Blue';
setState(() {
_bulletColor = _getColorFromName(selected);
});
}
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
}
}
String _t(String key) => AppSettings.instance.t(key);
Future<void> _loadBulletCount() async {
final prefs = await SharedPreferences.getInstance();
@@ -191,6 +121,8 @@ class _CameraScreenState extends State<CameraScreen> {
if (!kReleaseMode) await _compareWithDartDecoder(detector, bytes, detections);
if (!mounted) return;
// The check screen follows the app theme; the camera is dark again after it
AppSettings.instance.releaseDark();
await Navigator.push(
context,
MaterialPageRoute(
@@ -201,6 +133,7 @@ class _CameraScreenState extends State<CameraScreen> {
),
),
);
AppSettings.instance.holdDark();
} catch (e) {
debugPrint('Error taking picture: $e');
} finally {
@@ -237,22 +170,25 @@ class _CameraScreenState extends State<CameraScreen> {
builder: (sheet) => StatefulBuilder(
builder: (context, setSheetState) => Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
CameraSheetHeader(
title: _t('Select the number of bullets'),
subtitle:
'${AppSettings.minBullets} – ${AppSettings.maxBullets}'),
subtitle: _t('{a}–{b} shots per target')
.replaceAll('{a}', '${AppSettings.minBullets}')
.replaceAll('{b}', '${AppSettings.maxBullets}')),
SheetStepper(
value: _numberOfBullets,
min: AppSettings.minBullets,
max: AppSettings.maxBullets,
accent: _bulletColor,
onChanged: (n) {
_selectBulletCount(n);
setSheetState(() {});
},
),
const SizedBox(height: 8),
const SizedBox(height: 14),
Text(_t('Statistics in the Book only compare targets with the same number of shots.'),
style: TextStyle(fontSize: 12, color: Palette.current.muted)),
],
),
),
@@ -260,42 +196,49 @@ class _CameraScreenState extends State<CameraScreen> {
}
void _showHelpDialog() {
showHelpSheet(context, accent: _bulletColor, t: _t, items: const [
(Icons.crop_square, 'Align the target inside the square frame.'),
(
Icons.camera_alt,
'Camera button: take a photo. Bullets are detected and you can check and save the result.'
),
(Icons.filter_5_rounded, 'Number bottom left: shots per target (1–5).'),
(Icons.tune, 'Settings icon: exposure, zoom and flashlight.'),
showHelpSheet(context, t: _t, clearBarrier: true, items: const [
(Icons.center_focus_strong_outlined, 'Align the target inside the square frame.'),
(Icons.photo_camera_outlined, 'Camera button: take a photo. Bullets are detected and you can check and save the result.'),
(Icons.grid_view_rounded, 'Number bottom left: shots per target (1–5).'),
(Icons.tune_rounded, 'Settings icon: exposure, zoom and flashlight.'),
]);
}
Future<void> _applyCamera(VoidCallback change, Future<void> Function() camera) async {
setState(change);
try {
await camera();
} catch (_) {} // control not supported on this phone
}
void _setZoom(double z) =>
_applyCamera(() => _zoom = z.clamp(_minZoom, _maxZoom), () => _controller!.setZoomLevel(_zoom));
void _toggleTorch() => _applyCamera(
() => _torch = !_torch,
() => _controller!.setFlashMode(_torch ? FlashMode.torch : FlashMode.off),
);
void _showCameraControls() {
showCameraSheet(
context,
builder: (sheet) => StatefulBuilder(
builder: (context, setSheetState) {
Future<void> apply(
VoidCallback change, Future<void> Function() camera) async {
setState(change);
Future<void> apply(VoidCallback change, Future<void> Function() camera) async {
await _applyCamera(change, camera);
setSheetState(() {});
try {
await camera();
} catch (_) {} // control not supported on this phone
}
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
CameraSheetHeader(
title: _t('Image Settings'),
trailing: TextButton.icon(
style: TextButton.styleFrom(foregroundColor: Colors.white70),
icon: const Icon(Icons.restart_alt_rounded, size: 18),
label: Text(_t('Reset')),
onPressed: () => apply(() {
title: _t('Camera settings'),
subtitle: _t('Exposure, zoom and flashlight'),
trailing: ResetPill(
label: _t('Reset'),
onTap: () => apply(() {
_exposure = 0;
_zoom = _minZoom;
}, () async {
@@ -306,45 +249,33 @@ class _CameraScreenState extends State<CameraScreen> {
),
if (_maxExposure > _minExposure)
SheetSlider(
icon: Icons.exposure_rounded,
icon: Icons.light_mode_outlined,
label: _t('Exposure'),
valueText:
'${_exposure >= 0 ? '+' : ''}${_exposure.toStringAsFixed(1)}',
valueText: '${_exposure >= 0 ? '+' : '−'}${dec(_exposure.abs(), 1)}',
value: _exposure,
min: _minExposure,
max: _maxExposure,
accent: _bulletColor,
onChanged: (v) => apply(() => _exposure = v,
() => _controller!.setExposureOffset(v)),
onChanged: (v) => apply(() => _exposure = v, () => _controller!.setExposureOffset(v)),
),
if (_maxZoom > _minZoom)
SheetSlider(
icon: Icons.zoom_in_rounded,
label: _t('Zoom'),
valueText: '${_zoom.toStringAsFixed(1)}×',
valueText: '${dec(_zoom, 1)}×',
value: _zoom,
min: _minZoom,
max: _maxZoom,
accent: _bulletColor,
onChanged: (v) => apply(
() => _zoom = v, () => _controller!.setZoomLevel(v)),
onChanged: (v) => apply(() => _zoom = v, () => _controller!.setZoomLevel(v)),
),
const SizedBox(height: 8),
SizedBox(
width: double.infinity,
child: SheetToggle(
icon: _torch
? Icons.flashlight_on_rounded
: Icons.flashlight_off_rounded,
label: _t('Flashlight'),
active: _torch,
accent: _bulletColor,
onTap: () => apply(
() => _torch = !_torch,
() => _controller!
.setFlashMode(_torch ? FlashMode.torch : FlashMode.off),
),
),
SheetToggle(
icon: Icons.flashlight_on_outlined,
label: _t('Flashlight'),
active: _torch,
onTap: () async {
_toggleTorch();
setSheetState(() {});
},
),
],
);
@@ -362,137 +293,226 @@ class _CameraScreenState extends State<CameraScreen> {
@override
Widget build(BuildContext context) {
if (_controller == null || _initializeControllerFuture == null) {
return const Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}
final c = Palette.current;
final ready = _controller != null && _initializeControllerFuture != null;
return Scaffold(
backgroundColor: _backgroundColor,
extendBody: true,
appBar: AppBar(
backgroundColor: Colors.grey[900],
title: Text(
_t("Align the target inside the square"),
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.white,
backgroundColor: Colors.black,
body: Column(
children: [
// Header: back, the instruction in a pill, help
Padding(
padding: EdgeInsets.fromLTRB(12, MediaQuery.paddingOf(context).top + 8, 12, 8),
child: Row(
children: [
CircleButton(icon: Icons.chevron_left_rounded, iconSize: 26, onTap: () => Navigator.pop(context)),
const SizedBox(width: 10),
Expanded(
child: Container(
height: 40,
alignment: Alignment.center,
padding: const EdgeInsets.symmetric(horizontal: 14),
decoration: BoxDecoration(color: c.tile, borderRadius: BorderRadius.circular(20)),
child: Text(
_t('Align the target inside the square'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: c.ink),
),
),
),
const SizedBox(width: 10),
CircleButton(icon: Icons.info_outline_rounded, onTap: _showHelpDialog),
],
),
),
),
leading: IconButton(
icon: const Icon(Icons.arrow_back, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
centerTitle: true,
actions: [
IconButton(
icon: const Icon(Icons.info_outline_rounded, color: Colors.white),
onPressed: _showHelpDialog,
Expanded(
child: !ready
? const Center(child: CircularProgressIndicator())
: FutureBuilder(
future: _initializeControllerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
return LayoutBuilder(builder: (context, box) {
// Same square as before: 90 % of the screen width, centred
final side = MediaQuery.sizeOf(context).width * 0.9;
return Stack(
fit: StackFit.expand,
children: [
ClipRect(
child: FittedBox(
fit: BoxFit.cover,
child: SizedBox(
width: _controller!.value.previewSize!.height,
height: _controller!.value.previewSize!.width,
child: CameraPreview(_controller!),
),
),
),
IgnorePointer(child: CustomPaint(painter: _FramePainter(side: side, color: c.accent))),
Positioned(
left: 0,
right: 0,
bottom: 18,
child: Center(child: _processing ? _searchingPill(c) : _zoomChips(c)),
),
],
);
});
},
),
),
// Bottom bar: shots per target, shutter, flashlight, settings
Container(
color: c.bg,
padding: EdgeInsets.fromLTRB(20, 18, 20, 18 + MediaQuery.paddingOf(context).bottom),
child: Row(
children: [
Material(
color: c.tile,
borderRadius: BorderRadius.circular(14),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: _showBulletDialog,
child: SizedBox(
width: 78,
height: 56,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('$_numberOfBullets',
style: TextStyle(fontSize: 20, height: 1.1, fontWeight: FontWeight.w800, color: c.ink)),
Text(_t('shots'), style: TextStyle(fontSize: 10.5, color: c.muted)),
],
),
),
),
),
const Spacer(),
_shutter(c),
const Spacer(),
SquareButton(
icon: _torch ? Icons.flashlight_on_rounded : Icons.flashlight_off_outlined,
color: _torch ? c.accent : c.ink,
tooltip: _t('Flashlight'),
onTap: ready ? _toggleTorch : null,
),
const SizedBox(width: 10),
SquareButton(icon: Icons.tune_rounded, tooltip: _t('Camera settings'), onTap: ready ? _showCameraControls : null),
],
),
),
const SizedBox(width: 16),
],
),
bottomNavigationBar: BottomAppBar(
color: Colors.grey[900],
shape: const CircularNotchedRectangle(),
notchMargin: 8.0,
child: SizedBox(
height: 60,
child: Row(
children: [
// Left - Bullet count (just number)
Expanded(
child: Align(
alignment: Alignment.centerLeft,
child: Padding(
padding: const EdgeInsets.only(left: 16.0),
child: InkWell(
onTap: _showBulletDialog,
child: Text(
'$_numberOfBullets',
style: const TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
),
),
);
}
// White shutter in a ring; while the photo is analysed the ring turns
Widget _shutter(Palette c) {
return GestureDetector(
onTap: _processing ? null : _takePicture,
child: SizedBox.square(
dimension: 76,
child: Stack(
alignment: Alignment.center,
children: [
if (_processing)
SizedBox.square(
dimension: 72,
child: CircularProgressIndicator(strokeWidth: 4, color: c.ink, backgroundColor: c.tile),
)
else
Container(
decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: c.ink, width: 4)),
),
// Center space for FAB
const SizedBox(width: 80),
// Right section - Brightness
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
IconButton(
icon:
const Icon(Icons.tune, color: Colors.white, size: 24),
onPressed: _showCameraControls,
),
],
),
),
],
),
AnimatedContainer(
duration: const Duration(milliseconds: 150),
width: _processing ? 0 : 58,
height: _processing ? 0 : 58,
decoration: BoxDecoration(color: c.ink, shape: BoxShape.circle),
),
],
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.white,
onPressed: _processing ? null : _takePicture,
child: _processing
? const SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(
strokeWidth: 3, color: Colors.black),
)
: const Icon(Icons.camera_alt, color: Colors.black),
),
body: FutureBuilder(
future: _initializeControllerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
final screenSize = MediaQuery.of(context).size;
return Stack(
children: [
Positioned.fill(
child: Container(
color: Colors.black, // covers any empty space
child: FittedBox(
fit: BoxFit.cover,
child: SizedBox(
width: _controller!.value.previewSize!.height,
height: _controller!.value.previewSize!.width,
child: CameraPreview(_controller!),
),
),
),
);
}
Widget _searchingPill(Palette c) => Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
decoration: BoxDecoration(color: c.tile, borderRadius: BorderRadius.circular(20)),
child: Text(_t('Looking for hits …'), style: TextStyle(fontSize: 13.5, fontWeight: FontWeight.w600, color: c.ink)),
);
// 1× 2× 3× quick zoom, the ones this camera can do
Widget _zoomChips(Palette c) {
final steps = [for (final z in [1.0, 2.0, 3.0]) if (z >= _minZoom && z <= _maxZoom) z];
if (steps.length < 2) return const SizedBox.shrink();
return Container(
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(color: Colors.black.withValues(alpha: 0.45), borderRadius: BorderRadius.circular(20)),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
for (final z in steps)
GestureDetector(
onTap: () => _setZoom(z),
child: Container(
width: 34,
height: 30,
alignment: Alignment.center,
decoration: BoxDecoration(
color: (_zoom - z).abs() < 0.05 ? c.tile : Colors.transparent,
shape: BoxShape.circle,
),
Center(
child: Container(
width: screenSize.width * 0.9,
height: screenSize.width * 0.9,
decoration: BoxDecoration(
border: Border.all(
color: _bulletColor.withValues(alpha: 0.9),
width: 3,
),
),
),
),
],
);
} else {
return const Center(child: CircularProgressIndicator());
}
},
child: Text('${z.round()}×',
style: TextStyle(
fontSize: 11.5,
fontWeight: FontWeight.w700,
color: (_zoom - z).abs() < 0.05 ? c.ink : c.muted)),
),
),
],
),
);
}
}
/// Dims the image outside the centred square and draws accent corners on it.
class _FramePainter extends CustomPainter {
final double side;
final Color color;
const _FramePainter({required this.side, required this.color});
@override
void paint(Canvas canvas, Size size) {
final rect = Rect.fromCenter(center: size.center(Offset.zero), width: side, height: side);
canvas.drawPath(
Path.combine(PathOperation.difference, Path()..addRect(Offset.zero & size), Path()..addRect(rect)),
Paint()..color = Colors.black.withValues(alpha: 0.45),
);
final p = Paint()
..color = color
..style = PaintingStyle.stroke
..strokeWidth = 4
..strokeCap = StrokeCap.round;
const l = 34.0;
for (final (corner, dx, dy) in [
(rect.topLeft, 1.0, 1.0),
(rect.topRight, -1.0, 1.0),
(rect.bottomLeft, 1.0, -1.0),
(rect.bottomRight, -1.0, -1.0),
]) {
canvas.drawPath(
Path()
..moveTo(corner.dx, corner.dy + dy * l)
..lineTo(corner.dx, corner.dy)
..lineTo(corner.dx + dx * l, corner.dy),
p,
);
}
}
@override
bool shouldRepaint(_FramePainter old) => old.side != side || old.color != color;
}