aded preview for sharing targets.

This commit is contained in:
Jan Pleterski
2026-11-13 11:15:01 +01:00
parent 30708c73b1
commit f6974e3e26
5 changed files with 472 additions and 0 deletions
+60
View File
@@ -8,6 +8,8 @@ import 'package:image/image.dart' as img;
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/translations.dart';
import '../utils/target_colors.dart';
import '../widgets/result_share.dart';
import 'session_screen.dart' show targetCount, shotCount;
class TargetViewScreen extends StatefulWidget {
final List<File> jsonFiles;
@@ -30,6 +32,7 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
List<Offset> _bullets = [];
List<Offset> _scaledBullets = []; // Bullets scaled to display target size
int _totalScore = 0;
int _shotCount = 0; // shots fired, misses included (bulletCount)
Map<int, int> _folderChartScores = {};
Offset? _targetCenter;
Uint8List? _targetImageBytes;
@@ -172,11 +175,13 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
final allBullets = <Offset>[];
String latestDate = 'Unknown Date';
var shots = 0;
for (var file in widget.jsonFiles) {
final jsonString = await file.readAsString();
final data = jsonDecode(jsonString);
final bulletsJson = data['bullets'] as List?;
shots += (data['bulletCount'] as int?) ?? bulletsJson?.length ?? 0;
if (bulletsJson != null) {
allBullets.addAll(
bulletsJson.map((b) => Offset(b['x'].toDouble(), b['y'].toDouble())).toList(),
@@ -209,6 +214,7 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
}
_bullets = allBullets;
_shotCount = shots;
} else {
// Single file view - load from current file
final currentFile = widget.jsonFiles[_currentIndex];
@@ -236,6 +242,7 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
}
final bulletsJson = data['bullets'] as List;
_bullets = bulletsJson.map((b) => Offset(b['x'].toDouble(), b['y'].toDouble())).toList();
_shotCount = (data['bulletCount'] as int?) ?? _bullets.length;
}
_targetFilePath = widget.isCombinedView
@@ -308,6 +315,54 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
}
}
// What the screen shows, as one image: target and tiles left, chart right
void _share() {
final center = _targetCenter ?? Offset.zero;
final scores = [for (final b in _bullets) _scoreForBullet(b, center)];
final List<(String, String)> tiles;
final List<MapEntry<int, int>> chart;
if (widget.isCombinedView) {
final groups = <int, int>{};
for (final s in scores) {
groups[s] = (groups[s] ?? 0) + 1;
}
final sorted = groups.entries.toList()..sort((a, b) => b.key.compareTo(a.key));
tiles = [for (final e in sorted) ('${e.value}x', '${e.key}')];
chart = _folderChartScores.entries.toList()..sort((a, b) => a.key.compareTo(b.key));
} else {
final order = List.generate(scores.length, (i) => i)
..sort((a, b) => scores[b].compareTo(scores[a]));
tiles = [for (final i in order) ('${i + 1}', '${scores[i]}')];
chart = [for (int i = 0; i < scores.length; i++) MapEntry(i + 1, scores[i])];
}
final folder = File(_targetFilePath).parent.path.split('/').last;
shareResult(
context,
ResultShareData(
title: folder,
date: _date.replaceAll('/', '.'),
countsLine: widget.isCombinedView
? '${targetCount(widget.jsonFiles.length)} · ${shotCount(_shotCount)}'
: shotCount(_shotCount),
total: _totalScore,
averagePerShot: _shotCount == 0 ? null : _totalScore / _shotCount,
targetImage: _targetImageBytes!,
targetImageSize: Size(_targetImageDecoded!.width.toDouble(),
_targetImageDecoded!.height.toDouble()),
bullets: _scaledBullets,
bulletDiameter: ((_scaleFactorX + _scaleFactorY) / 2) * 53,
bulletColor: _bulletColor,
targetBackground: _backgroundColor,
tiles: tiles,
chart: chart,
chartPerShot: !widget.isCombinedView,
t: _t,
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
@@ -342,6 +397,11 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
centerTitle: true,
iconTheme: const IconThemeData(color: Colors.white),
actions: [
IconButton(
tooltip: _t('Share'),
icon: const Icon(Icons.share_rounded),
onPressed: _targetImageDecoded == null ? null : _share,
),
// The combined view shows a whole session; deleting would remove an
// arbitrary one of its targets. Sessions are deleted from the Book list.
if (!widget.isCombinedView)
+10
View File
@@ -1225,6 +1225,16 @@ class AppTranslations {
'Slovenian': 'Skupek',
'German': 'Summe',
},
'Share': {
'English': 'Share',
'Slovenian': 'Deli',
'German': 'Teilen',
},
'Sharing failed': {
'English': 'Sharing failed',
'Slovenian': 'Deljenje ni uspelo',
'German': 'Teilen fehlgeschlagen',
},
};
static String translate(String key, String language) {
+361
View File
@@ -0,0 +1,361 @@
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
import '../screens/target_view.dart' show BarChartPainter;
/// Everything the share image shows, taken from the target view as it is.
class ResultShareData {
final String title; // session (folder) name
final String date; // already formatted, e.g. 12.11.2026
final String countsLine; // e.g. "7 tarč · 35 strelov"
final int total;
final double? averagePerShot;
final Uint8List targetImage; // the selected target design
final Size targetImageSize;
final List<Offset> bullets; // in targetImage pixels
final double bulletDiameter; // in targetImage pixels
final Color bulletColor;
final Color targetBackground; // matches the target design
final List<(String top, String bottom)> tiles; // e.g. ("6x", "10")
final List<MapEntry<int, int>> chart; // bar label number -> points
final bool chartPerShot; // bars are shots of one target, not targets of a session
final String Function(String) t;
const ResultShareData({
required this.title,
required this.date,
required this.countsLine,
required this.total,
required this.averagePerShot,
required this.targetImage,
required this.targetImageSize,
required this.bullets,
required this.bulletDiameter,
required this.bulletColor,
required this.targetBackground,
required this.tiles,
required this.chart,
required this.chartPerShot,
required this.t,
});
}
bool _sharing = false;
/// Builds the result image off screen and opens the phone's share menu with it.
Future<void> shareResult(BuildContext context, ResultShareData data) async {
if (_sharing) return; // double tap
_sharing = true;
final overlay = Overlay.of(context);
final messenger = ScaffoldMessenger.maybeOf(context);
final key = GlobalKey();
OverlayEntry? entry;
try {
// Decode the target first so it is in the very first frame
await precacheImage(MemoryImage(data.targetImage), context);
// Laid out and painted, but outside the screen
entry = OverlayEntry(
builder: (_) => Positioned(
left: -ResultShareCard.size.width - 100,
top: 0,
child: IgnorePointer(
child: RepaintBoundary(key: key, child: ResultShareCard(data: data)),
),
),
);
overlay.insert(entry);
await WidgetsBinding.instance.endOfFrame;
final render = key.currentContext!.findRenderObject() as RenderRepaintBoundary;
if (render.debugNeedsPaint) await WidgetsBinding.instance.endOfFrame;
// Card is 960x540 logical: pixel ratio 2 gives a 1920x1080 image
final image = await render.toImage(pixelRatio: 2);
final png = await image.toByteData(format: ui.ImageByteFormat.png);
image.dispose();
entry.remove();
entry = null;
final dir = await getTemporaryDirectory();
final file = File(
'${dir.path}/sdk_kovinar_${DateTime.now().millisecondsSinceEpoch}.png');
await file.writeAsBytes(png!.buffer.asUint8List());
await SharePlus.instance.share(ShareParams(
files: [XFile(file.path, mimeType: 'image/png')],
text: '${data.title} · ${data.total}',
));
} catch (e) {
debugPrint('Share failed: $e');
messenger?.showSnackBar(SnackBar(content: Text(data.t('Sharing failed'))));
} finally {
entry?.remove();
_sharing = false;
}
}
/// The 960x540 image: header with the result, target with score tiles on the
/// left, the bar chart with every value on the right.
class ResultShareCard extends StatelessWidget {
static const Size size = Size(960, 540);
final ResultShareData data;
const ResultShareCard({super.key, required this.data});
@override
Widget build(BuildContext context) {
final t = data.t;
final accent = data.bulletColor;
return SizedBox.fromSize(
size: size,
child: Material(
color: const Color(0xFF1B1E21),
child: Padding(
padding: const EdgeInsets.fromLTRB(28, 22, 28, 22),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Header
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('SDK KOVINAR',
style: TextStyle(
color: accent,
fontSize: 12,
fontWeight: FontWeight.w800,
letterSpacing: 2.5)),
const SizedBox(height: 2),
Text(data.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: Colors.white,
fontSize: 28,
fontWeight: FontWeight.w800)),
const SizedBox(height: 2),
Text('${data.date} · ${data.countsLine}',
style: const TextStyle(
color: Colors.white60, fontSize: 14)),
],
),
),
if (data.averagePerShot != null)
_HeaderFigure(
label: t('Average per shot'),
value: data.averagePerShot!.toStringAsFixed(2),
size: 40),
const SizedBox(width: 28),
_HeaderFigure(
label: t('Total score').replaceAll(':', ''),
value: '${data.total}',
size: 40,
color: accent),
],
),
const SizedBox(height: 16),
Expanded(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Target and score tiles
Container(
width: 380,
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: data.targetBackground,
borderRadius: BorderRadius.circular(18),
),
child: Column(
children: [
Expanded(
child: Center(
child: AspectRatio(
aspectRatio: data.targetImageSize.width /
data.targetImageSize.height,
child: _TargetWithHits(data: data),
),
),
),
const SizedBox(height: 10),
SizedBox(
height: 58,
child: Row(
children: [
for (final (top, bottom) in data.tiles)
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 3),
child: _Tile(
top: top,
bottom: bottom,
color: accent),
),
),
],
),
),
],
),
),
const SizedBox(width: 16),
// Chart with every value
Expanded(
child: Container(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 4),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(18),
),
child: CustomPaint(
size: Size.infinite,
painter: BarChartPainter(
data: data.chart,
maxScore: _chartMax(data),
bulletColor: accent,
isShotView: data.chartPerShot,
backgroundColor: Colors.white,
translateFunc: t,
xAxisLabelKey: data.chartPerShot ? 'Points' : null,
),
),
),
),
],
),
),
],
),
),
),
);
}
static double _chartMax(ResultShareData d) {
final max = d.chart.isEmpty
? 0
: d.chart.map((e) => e.value).reduce((a, b) => a > b ? a : b);
return max <= 0 ? 1 : max.toDouble();
}
}
class _HeaderFigure extends StatelessWidget {
final String label;
final String value;
final double size;
final Color color;
const _HeaderFigure(
{required this.label,
required this.value,
required this.size,
this.color = Colors.white});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: [
Text(label.toUpperCase(),
style: const TextStyle(
color: Colors.white54,
fontSize: 11,
fontWeight: FontWeight.w700,
letterSpacing: 1.5)),
Text(value,
style: TextStyle(
color: color,
fontSize: size,
height: 1.05,
fontWeight: FontWeight.w800,
fontFeatures: const [FontFeature.tabularFigures()])),
],
);
}
}
class _TargetWithHits extends StatelessWidget {
final ResultShareData data;
const _TargetWithHits({required this.data});
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, c) {
final scale = c.maxWidth / data.targetImageSize.width;
final d = data.bulletDiameter * scale;
return Stack(
children: [
Positioned.fill(
child: Image.memory(data.targetImage,
fit: BoxFit.fill, gaplessPlayback: true)),
for (final b in data.bullets)
Positioned(
left: b.dx * scale - d / 2,
top: b.dy * scale - d / 2,
width: d,
height: d,
child: DecoratedBox(
decoration: BoxDecoration(
color: data.bulletColor.withValues(alpha: 0.85),
shape: BoxShape.circle,
border: Border.all(color: Colors.black, width: 1),
),
),
),
],
);
});
}
}
class _Tile extends StatelessWidget {
final String top;
final String bottom;
final Color color;
const _Tile({required this.top, required this.bottom, required this.color});
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Column(
children: [
Container(
height: 20,
width: double.infinity,
color: const Color(0xFF2C2F33),
alignment: Alignment.center,
child: FittedBox(
child: Text(top,
style: const TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w700)),
),
),
Expanded(
child: Container(
width: double.infinity,
color: color.withValues(alpha: 0.9),
alignment: Alignment.center,
child: FittedBox(
child: Text(bottom,
style: const TextStyle(
color: Colors.white,
fontSize: 22,
fontWeight: FontWeight.w800)),
),
),
),
],
),
);
}
}
+40
View File
@@ -169,6 +169,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "7.0.1"
fixnum:
dependency: transitive
description:
name: fixnum
sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be
url: "https://pub.dev"
source: hosted
version: "1.1.1"
flutter:
dependency: "direct main"
description: flutter
@@ -352,6 +360,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.19.0"
mime:
dependency: transitive
description:
name: mime
sha256: bd47de35f07e27267e69c8c8b22edf9473bfee170a60d60fcc93730c5144b7f6
url: "https://pub.dev"
source: hosted
version: "2.1.0"
package_info_plus:
dependency: "direct main"
description:
@@ -464,6 +480,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.2.2"
share_plus:
dependency: "direct main"
description:
name: share_plus
sha256: "223873d106614442ea6f20db5a038685cc5b32a2fba81cdecaefbbae0523f7fa"
url: "https://pub.dev"
source: hosted
version: "12.0.2"
share_plus_platform_interface:
dependency: transitive
description:
name: share_plus_platform_interface
sha256: "88023e53a13429bd65d8e85e11a9b484f49d4c190abbd96c7932b74d6927cc9a"
url: "https://pub.dev"
source: hosted
version: "6.1.0"
shared_preferences:
dependency: "direct main"
description:
@@ -669,6 +701,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.1.4"
uuid:
dependency: transitive
description:
name: uuid
sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd"
url: "https://pub.dev"
source: hosted
version: "4.6.0"
vector_math:
dependency: transitive
description:
+1
View File
@@ -26,6 +26,7 @@ dependencies:
package_info_plus: ^8.3.0
cryptography: ^2.9.0
http: ^0.13.6
share_plus: ^12.0.2
dev_dependencies:
flutter_test: