Skip to content

Offline gym log for Android. No account, no ads, no internet.

Gym pass from a photo with crop and rotate

InlitXadf12c3826a6
diff --git a/lib/models/gym_pass.dart b/lib/models/gym_pass.dart
index de56983..ef9d4ed 100644
--- a/lib/models/gym_pass.dart
+++ b/lib/models/gym_pass.dart
@@ -1,4 +1,4 @@
-enum PassFormat { qr, code128, ean13, ean8, upca, code39, itf, dataMatrix, pdf417, aztec }
+enum PassFormat { qr, code128, ean13, ean8, upca, code39, itf, dataMatrix, pdf417, aztec, photo }
PassFormat passFormatFrom(Object? raw) =>
PassFormat.values.firstWhere((f) => f.name == raw, orElse: () => PassFormat.qr);
@@ -20,6 +20,8 @@ class GymPass {
final int hue;
final String member;
+ bool get photo => format == PassFormat.photo;
+
bool get square => const {PassFormat.qr, PassFormat.dataMatrix, PassFormat.aztec}.contains(format);
GymPass copyWith({String? name, String? code, PassFormat? format, int? hue, String? member}) => GymPass(
diff --git a/lib/screens/gym_pass_screen.dart b/lib/screens/gym_pass_screen.dart
index ea18eda..59b16e4 100644
--- a/lib/screens/gym_pass_screen.dart
+++ b/lib/screens/gym_pass_screen.dart
@@ -7,6 +7,7 @@ import 'package:phosphoricons_flutter/phosphoricons_flutter.dart';
import '../l10n/l10n.dart';
import '../models/gym_pass.dart';
+import '../services/media_store.dart';
import '../services/pass_scan.dart';
import '../services/screen_awake.dart';
import '../state/fit_state.dart';
@@ -16,6 +17,7 @@ import '../widgets/entrance.dart';
import '../widgets/glass.dart';
import '../widgets/gym_pass_card.dart';
import '../widgets/liquid_notch.dart';
+import '../widgets/photo_crop.dart';
import '../widgets/routine_folder.dart';
import '../widgets/sheet_page.dart';
import '../widgets/ui_kit.dart';
@@ -98,10 +100,7 @@ class GymPassScreen extends StatelessWidget {
backgroundColor: Colors.transparent,
builder: (sheet) => Container(
padding: sheetPad(sheet),
- decoration: BoxDecoration(
- color: gc.bgRaised,
- borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
- ),
+ decoration: sheetDecoration(gc),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -262,7 +261,7 @@ class _PassView extends StatelessWidget {
const SizedBox(height: 22),
Container(
width: side,
- padding: EdgeInsets.all(pass.square ? 22 : 20),
+ padding: EdgeInsets.all(pass.photo ? 14 : pass.square ? 22 : 20),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(28),
@@ -271,7 +270,7 @@ class _PassView extends StatelessWidget {
],
),
child: SizedBox(
- height: pass.square ? side - 44 : side * 0.5,
+ height: pass.photo ? side * 0.66 : pass.square ? side - 44 : side * 0.5,
child: PassCode(code: pass.code, format: pass.format),
),
),
@@ -324,10 +323,7 @@ Future<void> addGymPass(BuildContext context) async {
);
return Container(
padding: sheetPad(sheet),
- decoration: BoxDecoration(
- color: gc.bgRaised,
- borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
- ),
+ decoration: sheetDecoration(gc),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -339,6 +335,7 @@ Future<void> addGymPass(BuildContext context) async {
row(PhosphorIconsRegular.camera, t.gymPassScan, t.gymPassScanHint, 'camera'),
row(PhosphorIconsRegular.image, t.gymPassPhoto, t.gymPassPhotoHint, 'photo'),
row(PhosphorIconsRegular.keyboard, t.gymPassType, t.gymPassTypeHint, 'type'),
+ row(PhosphorIconsRegular.frameCorners, t.gymPassPicture, t.gymPassPictureHint, 'picture'),
],
),
);
@@ -346,12 +343,41 @@ Future<void> addGymPass(BuildContext context) async {
);
if (how == null || !context.mounted) return;
if (how == 'type') return editGymPass(context, typing: true);
- final code = await _readCode(context, how == 'camera' ? ImageSource.camera : ImageSource.gallery);
+ void openWith(String name) {
+ if (context.mounted) editGymPass(context, code: name, format: PassFormat.photo);
+ }
+
+ if (how == 'picture') {
+ final source = await pickPhotoFor(context);
+ if (source == null || !context.mounted) return;
+ final name = await pickPassPicture(context, source);
+ if (name != null) openWith(name);
+ return;
+ }
+ final code = await _readCode(context, how == 'camera' ? ImageSource.camera : ImageSource.gallery,
+ onPicture: openWith);
if (code == null || !context.mounted) return;
await editGymPass(context, code: code);
}
-Future<String?> _readCode(BuildContext context, ImageSource source) async {
+Future<String?> pickPassPicture(BuildContext context, ImageSource source) async {
+ final XFile? shot;
+ try {
+ shot = await ImagePicker().pickImage(source: source, requestFullMetadata: false);
+ } catch (_) {
+ return null;
+ }
+ if (shot == null || !context.mounted) return null;
+ return _cropPassPicture(context, shot.path);
+}
+
+Future<String?> _cropPassPicture(BuildContext context, String path) async {
+ final png = await showPhotoCrop(context, path, title: t.cropTitle, hint: t.cropHint);
+ if (png == null) return null;
+ return MediaStore.saveBytes('pass', 'png', png);
+}
+
+Future<String?> _readCode(BuildContext context, ImageSource source, {void Function(String name)? onPicture}) async {
final XFile? shot;
try {
shot = await ImagePicker().pickImage(source: source, requestFullMetadata: false);
@@ -365,26 +391,39 @@ Future<String?> _readCode(BuildContext context, ImageSource source) async {
if (!context.mounted) return null;
if (code == null) {
HapticFeedback.heavyImpact();
- showNotchToast(context, t.gymPassNotFound, icon: PhosphorIconsFill.warningCircle, accent: gc.warn);
+ final path = shot.path;
+ showNotchToast(context, t.gymPassNotFound,
+ icon: PhosphorIconsFill.warningCircle,
+ accent: gc.warn,
+ duration: onPicture == null ? null : const Duration(seconds: 6),
+ action: onPicture == null ? null : t.gymPassUsePicture,
+ onTap: onPicture == null
+ ? null
+ : () async {
+ final name = await _cropPassPicture(context, path);
+ if (name != null) onPicture(name);
+ });
return null;
}
HapticFeedback.mediumImpact();
return code;
}
-Future<void> editGymPass(BuildContext context, {GymPass? pass, String? code, bool typing = false}) =>
+Future<void> editGymPass(BuildContext context,
+ {GymPass? pass, String? code, PassFormat? format, bool typing = false}) =>
showAppSheet<void>(
context: context,
backgroundColor: Colors.transparent,
isScrollControlled: true,
- builder: (_) => _PassEditor(pass: pass, code: code, typing: typing),
+ builder: (_) => _PassEditor(pass: pass, code: code, format: format, typing: typing),
);
class _PassEditor extends StatefulWidget {
- const _PassEditor({this.pass, this.code, this.typing = false});
+ const _PassEditor({this.pass, this.code, this.format, this.typing = false});
final GymPass? pass;
final String? code;
+ final PassFormat? format;
final bool typing;
@override
@@ -394,7 +433,11 @@ class _PassEditor extends StatefulWidget {
class _PassEditorState extends State<_PassEditor> {
late final _name = TextEditingController(text: widget.pass?.name ?? t.gymPassDefaultName);
late final _code = TextEditingController(text: widget.pass?.code ?? widget.code ?? '');
- late PassFormat _format = widget.pass?.format ?? (widget.typing ? PassFormat.code128 : PassFormat.qr);
+ late PassFormat _format =
+ widget.pass?.format ?? widget.format ?? (widget.typing ? PassFormat.code128 : PassFormat.qr);
+ late final String? _firstPicture = _format == PassFormat.photo ? _code.text : null;
+ final Set<String> _newPictures = {};
+ bool _saved = false;
late int _hue = widget.pass?.hue ?? fit.gymPasses.length % kFolderHues.length;
static const _formats = [
@@ -404,13 +447,28 @@ class _PassEditorState extends State<_PassEditor> {
PassFormat.code39,
];
+ @override
+ void initState() {
+ super.initState();
+ final first = _firstPicture;
+ if (widget.pass == null && first != null) _newPictures.add(first);
+ }
+
@override
void dispose() {
+ final keep = _saved ? _code.text.trim() : (widget.pass?.code ?? '');
+ for (final name in _newPictures) {
+ if (name != keep) MediaStore.delete(name);
+ }
+ final first = _firstPicture;
+ if (_saved && first != null && widget.pass != null && first != keep) MediaStore.delete(first);
_name.dispose();
_code.dispose();
super.dispose();
}
+ bool get _photo => _format == PassFormat.photo;
+
bool get _valid => passCodeValid(_format, _code.text.trim());
GymPass get _draft => GymPass(
@@ -430,14 +488,32 @@ class _PassEditorState extends State<_PassEditor> {
} else {
fit.updateGymPass(d);
}
+ _saved = true;
HapticFeedback.lightImpact();
Navigator.of(context).pop();
}
+ void _usePicture(String name) {
+ if (!mounted) {
+ MediaStore.delete(name);
+ return;
+ }
+ _newPictures.add(name);
+ setState(() {
+ _code.text = name;
+ _format = PassFormat.photo;
+ });
+ }
+
Future<void> _rescan() async {
final source = await pickPhotoFor(context);
if (source == null || !mounted) return;
- final code = await _readCode(context, source);
+ if (_photo) {
+ final name = await pickPassPicture(context, source);
+ if (name != null) _usePicture(name);
+ return;
+ }
+ final code = await _readCode(context, source, onPicture: _usePicture);
if (code == null || !mounted) return;
setState(() {
_code.text = code;
@@ -476,10 +552,7 @@ class _PassEditorState extends State<_PassEditor> {
return Container(
constraints: BoxConstraints(maxHeight: MediaQuery.sizeOf(context).height * 0.92),
padding: EdgeInsets.only(bottom: MediaQuery.viewInsetsOf(context).bottom),
- decoration: BoxDecoration(
- color: gc.bgRaised,
- borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
- ),
+ decoration: sheetDecoration(gc),
child: SingleChildScrollView(
padding: sheetPad(context),
child: Column(
@@ -514,6 +587,7 @@ class _PassEditorState extends State<_PassEditor> {
),
_label(gc, t.gymPassName),
_field(gc, _name, t.gymPassDefaultName),
+ if (!_photo) ...[
_label(gc, t.gymPassFormat),
Wrap(spacing: 8, runSpacing: 8, children: [
for (final f in _formats)
@@ -538,6 +612,7 @@ class _PassEditorState extends State<_PassEditor> {
]),
_label(gc, t.gymPassCode),
_field(gc, _code, '0123456789', numeric: true),
+ ],
_label(gc, t.gymPassColor),
Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
for (var i = 0; i < kFolderHues.length; i++)
@@ -561,8 +636,9 @@ class _PassEditorState extends State<_PassEditor> {
Center(
child: TextButton.icon(
onPressed: _rescan,
- icon: Icon(PhosphorIconsRegular.arrowsClockwise, size: 15, color: gc.textSecondary),
- label: Text(t.gymPassRescan,
+ icon: Icon(_photo ? PhosphorIconsRegular.image : PhosphorIconsRegular.arrowsClockwise,
+ size: 15, color: gc.textSecondary),
+ label: Text(_photo ? t.gymPassChangePicture : t.gymPassRescan,
style: AppTheme.f(13, weight: FontWeight.w700, color: gc.textSecondary)),
),
),
@@ -586,10 +662,7 @@ Future<ImageSource?> pickPhotoFor(BuildContext context) => showAppSheet<ImageSou
final gc = sheet.gc;
return Container(
padding: sheetPad(sheet),
- decoration: BoxDecoration(
- color: gc.bgRaised,
- borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
- ),
+ decoration: sheetDecoration(gc),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
diff --git a/lib/state/gym_pass_state.dart b/lib/state/gym_pass_state.dart
index 43e032e..1c3c914 100644
--- a/lib/state/gym_pass_state.dart
+++ b/lib/state/gym_pass_state.dart
@@ -61,12 +61,15 @@ mixin GymPassState on FitCore {
void backFromGymPasses() => popRoute(fallback: 'settings');
- void _loadGymPasses(Map<String, dynamic> data) {
+ void _loadGymPasses(Map<String, dynamic> data, {Map<String, String>? restored}) {
gymPasses.clear();
final raw = data['passes'];
if (raw is List) {
gymPasses.addAll(raw
.map((e) => GymPass.fromJson((e as Map).cast<String, dynamic>()))
+ .map((p) => p.photo && restored != null && restored[p.code] != null
+ ? p.copyWith(code: restored[p.code])
+ : p)
.where((p) => p.code.isNotEmpty));
}
lastPassId = data['lastPass'] as String? ?? '';
diff --git a/lib/widgets/cutout_editor.dart b/lib/widgets/cutout_editor.dart
index 6ad62f5..1f9633b 100644
--- a/lib/widgets/cutout_editor.dart
+++ b/lib/widgets/cutout_editor.dart
@@ -261,10 +261,7 @@ class _CutoutEditorState extends State<_CutoutEditor> {
return Container(
height: media.size.height * 0.94,
padding: sheetPad(context, bottom: 16),
- decoration: BoxDecoration(
- color: gc.bgRaised,
- borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
- ),
+ decoration: sheetDecoration(gc),
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
const SheetHandle(),
const SizedBox(height: 16),
@@ -366,7 +363,7 @@ class _CutoutEditorState extends State<_CutoutEditor> {
child: Icon(PhosphorIconsBold.sparkle, size: 18, color: gc.textSecondary),
),
const SizedBox(width: 10),
- Expanded(child: PrimaryButton(label: t.done, height: 50, onTap: _done)),
+ Expanded(child: PrimaryButton(label: t.done, height: 52, onTap: _done)),
]),
]),
);
diff --git a/lib/widgets/gym_pass_card.dart b/lib/widgets/gym_pass_card.dart
index bf97da9..1076ad1 100644
--- a/lib/widgets/gym_pass_card.dart
+++ b/lib/widgets/gym_pass_card.dart
@@ -1,8 +1,11 @@
+import 'dart:io';
+
import 'package:barcode/barcode.dart';
import 'package:flutter/material.dart';
import '../l10n/l10n.dart';
import '../models/gym_pass.dart';
+import '../services/media_store.dart';
import '../state/fit_state.dart';
import '../theme/app_theme.dart';
import 'routine_folder.dart';
@@ -20,6 +23,7 @@ Barcode barcodeFor(PassFormat f) => switch (f) {
PassFormat.dataMatrix => Barcode.dataMatrix(),
PassFormat.pdf417 => Barcode.pdf417(),
PassFormat.aztec => Barcode.aztec(),
+ PassFormat.photo => Barcode.code128(),
};
String passFormatLabel(PassFormat f) => switch (f) {
@@ -33,9 +37,11 @@ String passFormatLabel(PassFormat f) => switch (f) {
PassFormat.dataMatrix => 'Data Matrix',
PassFormat.pdf417 => 'PDF417',
PassFormat.aztec => 'Aztec',
+ PassFormat.photo => t.gymPassPictureFormat,
};
-bool passCodeValid(PassFormat f, String code) => code.isNotEmpty && barcodeFor(f).isValid(code);
+bool passCodeValid(PassFormat f, String code) =>
+ code.isNotEmpty && (f == PassFormat.photo || barcodeFor(f).isValid(code));
Color passHue(int hue) => kFolderHues[hue.abs() % kFolderHues.length];
@@ -48,6 +54,7 @@ class PassCode extends StatelessWidget {
@override
Widget build(BuildContext context) {
+ if (format == PassFormat.photo) return PassPhoto(name: code);
final square = const {PassFormat.qr, PassFormat.dataMatrix, PassFormat.aztec}.contains(format);
final bars = CustomPaint(painter: _CodePainter(code, format, MediaQuery.devicePixelRatioOf(context)));
if (square) return AspectRatio(aspectRatio: 1, child: bars);
@@ -71,6 +78,25 @@ class PassCode extends StatelessWidget {
}
}
+class PassPhoto extends StatelessWidget {
+ const PassPhoto({super.key, required this.name});
+
+ final String name;
+
+ @override
+ Widget build(BuildContext context) {
+ final path = MediaStore.pathFor(name);
+ if (path == null) return const SizedBox.shrink();
+ return Image.file(
+ File(path),
+ fit: BoxFit.contain,
+ filterQuality: FilterQuality.high,
+ gaplessPlayback: true,
+ errorBuilder: (_, _, _) => const SizedBox.shrink(),
+ );
+ }
+}
+
class _CodePainter extends CustomPainter {
_CodePainter(this.code, this.format, this.ratio);
diff --git a/lib/widgets/photo_crop.dart b/lib/widgets/photo_crop.dart
new file mode 100644
index 0000000..a3fe658
--- /dev/null
+++ b/lib/widgets/photo_crop.dart
@@ -0,0 +1,315 @@
+import 'dart:io';
+import 'dart:math' as math;
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:phosphoricons_flutter/phosphoricons_flutter.dart';
+
+import '../l10n/l10n.dart';
+import '../theme/app_colors.dart';
+import '../theme/app_theme.dart';
+import 'svg_icon.dart';
+import 'ui_kit.dart';
+
+Future<Uint8List?> showPhotoCrop(BuildContext context, String path, {String? title, String? hint}) async {
+ final image = await loadCropImage(path);
+ if (image == null || !context.mounted) return null;
+ final out = await Navigator.of(context).push<Uint8List>(PageRouteBuilder<Uint8List>(
+ opaque: false,
+ barrierColor: Colors.transparent,
+ transitionDuration: const Duration(milliseconds: 320),
+ reverseTransitionDuration: const Duration(milliseconds: 220),
+ pageBuilder: (_, animation, _) => FadeTransition(
+ opacity: CurvedAnimation(parent: animation, curve: Curves.easeOutCubic),
+ child: _PhotoCrop(image: image, title: title, hint: hint),
+ ),
+ ));
+ return out;
+}
+
+Future<ui.Image?> loadCropImage(String path, {int maxSide = 2400}) async {
+ ui.ImmutableBuffer? buffer;
+ ui.ImageDescriptor? descriptor;
+ try {
+ buffer = await ui.ImmutableBuffer.fromUint8List(await File(path).readAsBytes());
+ descriptor = await ui.ImageDescriptor.encoded(buffer);
+ final long = math.max(descriptor.width, descriptor.height);
+ final scale = long > maxSide ? maxSide / long : 1.0;
+ final codec = await descriptor.instantiateCodec(
+ targetWidth: (descriptor.width * scale).round(),
+ targetHeight: (descriptor.height * scale).round(),
+ );
+ final frame = await codec.getNextFrame();
+ codec.dispose();
+ return frame.image;
+ } catch (_) {
+ return null;
+ } finally {
+ descriptor?.dispose();
+ buffer?.dispose();
+ }
+}
+
+ui.Image rotateQuarter(ui.Image src) {
+ final recorder = ui.PictureRecorder();
+ final canvas = Canvas(recorder)
+ ..translate(src.height.toDouble(), 0)
+ ..rotate(math.pi / 2);
+ canvas.drawImage(src, Offset.zero, Paint()..filterQuality = FilterQuality.high);
+ return recorder.endRecording().toImageSync(src.height, src.width);
+}
+
+Future<Uint8List?> cropToPng(ui.Image src, Rect unit, {int maxSide = 1600}) async {
+ final r = Rect.fromLTRB(
+ (unit.left * src.width).clamp(0, src.width.toDouble()),
+ (unit.top * src.height).clamp(0, src.height.toDouble()),
+ (unit.right * src.width).clamp(0, src.width.toDouble()),
+ (unit.bottom * src.height).clamp(0, src.height.toDouble()),
+ );
+ if (r.width < 4 || r.height < 4) return null;
+ final scale = math.min(1.0, maxSide / math.max(r.width, r.height));
+ final w = math.max(1, (r.width * scale).round()), h = math.max(1, (r.height * scale).round());
+ final recorder = ui.PictureRecorder();
+ Canvas(recorder).drawImageRect(src, r, Rect.fromLTWH(0, 0, w.toDouble(), h.toDouble()),
+ Paint()..filterQuality = FilterQuality.high);
+ final out = await recorder.endRecording().toImage(w, h);
+ final data = await out.toByteData(format: ui.ImageByteFormat.png);
+ out.dispose();
+ return data?.buffer.asUint8List();
+}
+
+enum _Grip { tl, tr, bl, br, body }
+
+class _PhotoCrop extends StatefulWidget {
+ const _PhotoCrop({required this.image, this.title, this.hint});
+
+ final ui.Image image;
+ final String? title;
+ final String? hint;
+
+ @override
+ State<_PhotoCrop> createState() => _PhotoCropState();
+}
+
+class _PhotoCropState extends State<_PhotoCrop> {
+ late ui.Image _image = widget.image;
+ final List<ui.Image> _made = [];
+ Rect _crop = const Rect.fromLTRB(0.08, 0.3, 0.92, 0.7);
+ _Grip? _grip;
+ bool _busy = false;
+
+ static const _min = 0.06;
+
+ @override
+ void dispose() {
+ widget.image.dispose();
+ for (final i in _made) {
+ i.dispose();
+ }
+ super.dispose();
+ }
+
+ void _rotate() {
+ HapticFeedback.selectionClick();
+ final next = rotateQuarter(_image);
+ _made.add(next);
+ setState(() {
+ _image = next;
+ final c = _crop;
+ _crop = Rect.fromLTRB(1 - c.bottom, c.left, 1 - c.top, c.right);
+ });
+ }
+
+ Future<void> _use() async {
+ if (_busy) return;
+ setState(() => _busy = true);
+ final png = await cropToPng(_image, _crop);
+ if (!mounted) return;
+ HapticFeedback.mediumImpact();
+ Navigator.of(context).pop(png);
+ }
+
+ _Grip _gripAt(Offset p, Rect box) {
+ final c = _toBox(_crop, box);
+ const reach = 34.0;
+ final corners = {
+ _Grip.tl: c.topLeft,
+ _Grip.tr: c.topRight,
+ _Grip.bl: c.bottomLeft,
+ _Grip.br: c.bottomRight,
+ };
+ _Grip? best;
+ var bestD = reach;
+ for (final e in corners.entries) {
+ final d = (e.value - p).distance;
+ if (d < bestD) {
+ best = e.key;
+ bestD = d;
+ }
+ }
+ return best ?? _Grip.body;
+ }
+
+ Rect _toBox(Rect unit, Rect box) => Rect.fromLTRB(
+ box.left + unit.left * box.width,
+ box.top + unit.top * box.height,
+ box.left + unit.right * box.width,
+ box.top + unit.bottom * box.height,
+ );
+
+ void _drag(Offset delta, Rect box) {
+ final dx = delta.dx / box.width, dy = delta.dy / box.height;
+ var c = _crop;
+ switch (_grip) {
+ case _Grip.tl:
+ c = Rect.fromLTRB((c.left + dx).clamp(0, c.right - _min), (c.top + dy).clamp(0, c.bottom - _min), c.right, c.bottom);
+ case _Grip.tr:
+ c = Rect.fromLTRB(c.left, (c.top + dy).clamp(0, c.bottom - _min), (c.right + dx).clamp(c.left + _min, 1), c.bottom);
+ case _Grip.bl:
+ c = Rect.fromLTRB((c.left + dx).clamp(0, c.right - _min), c.top, c.right, (c.bottom + dy).clamp(c.top + _min, 1));
+ case _Grip.br:
+ c = Rect.fromLTRB(c.left, c.top, (c.right + dx).clamp(c.left + _min, 1), (c.bottom + dy).clamp(c.top + _min, 1));
+ case _Grip.body:
+ final mx = dx.clamp(-c.left, 1 - c.right), my = dy.clamp(-c.top, 1 - c.bottom);
+ c = c.shift(Offset(mx, my));
+ case null:
+ return;
+ }
+ setState(() => _crop = c);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final gc = context.gc;
+ return Material(
+ color: gc.bg,
+ child: SafeArea(
+ child: Column(children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 12, 20, 0),
+ child: Row(children: [
+ RoundBtn(icon: Ic.close, onTap: () => Navigator.of(context).pop()),
+ const SizedBox(width: 14),
+ Expanded(
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(widget.title ?? t.cropTitle,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppTheme.f(18, weight: FontWeight.w800, color: gc.text, letterSpacing: -0.3)),
+ const SizedBox(height: 2),
+ Text(widget.hint ?? t.cropHint,
+ maxLines: 2,
+ style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.textSecondary, height: 1.3)),
+ ]),
+ ),
+ const SizedBox(width: 10),
+ RoundAction(
+ label: t.rotatePhoto,
+ onTap: _rotate,
+ child: Icon(PhosphorIconsRegular.arrowClockwise, size: 17, color: gc.text),
+ ),
+ ]),
+ ),
+ Expanded(
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(24, 22, 24, 22),
+ child: LayoutBuilder(builder: (context, area) {
+ final iw = _image.width.toDouble(), ih = _image.height.toDouble();
+ final s = math.min(area.maxWidth / iw, area.maxHeight / ih);
+ final size = Size(iw * s, ih * s);
+ final box = Rect.fromLTWH(
+ (area.maxWidth - size.width) / 2, (area.maxHeight - size.height) / 2, size.width, size.height);
+ return GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onPanStart: (d) {
+ _grip = _gripAt(d.localPosition, box);
+ HapticFeedback.selectionClick();
+ },
+ onPanUpdate: (d) => _drag(d.delta, box),
+ onPanEnd: (_) => _grip = null,
+ child: CustomPaint(
+ size: Size(area.maxWidth, area.maxHeight),
+ painter: _CropPainter(
+ image: _image,
+ box: box,
+ crop: _toBox(_crop, box),
+ shade: gc.bg.withValues(alpha: 0.72),
+ line: Colors.white,
+ ),
+ ),
+ );
+ }),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 0, 20, 16),
+ child: AnimatedOpacity(
+ duration: const Duration(milliseconds: 180),
+ opacity: _busy ? 0.5 : 1,
+ child: PrimaryButton(label: t.useValue, onTap: _use),
+ ),
+ ),
+ ]),
+ ),
+ );
+ }
+}
+
+class _CropPainter extends CustomPainter {
+ const _CropPainter({
+ required this.image,
+ required this.box,
+ required this.crop,
+ required this.shade,
+ required this.line,
+ });
+
+ final ui.Image image;
+ final Rect box;
+ final Rect crop;
+ final Color shade;
+ final Color line;
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ final src = Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble());
+ canvas.drawImageRect(image, src, box, Paint()..filterQuality = FilterQuality.medium);
+ final outside = Path()
+ ..fillType = PathFillType.evenOdd
+ ..addRect(box)
+ ..addRRect(RRect.fromRectAndRadius(crop, const Radius.circular(6)));
+ canvas.drawPath(outside, Paint()..color = shade);
+ canvas.drawRRect(
+ RRect.fromRectAndRadius(crop, const Radius.circular(6)),
+ Paint()
+ ..color = line.withValues(alpha: 0.9)
+ ..style = PaintingStyle.stroke
+ ..strokeWidth = 1.4,
+ );
+ final grip = Paint()
+ ..color = line
+ ..style = PaintingStyle.stroke
+ ..strokeWidth = 4
+ ..strokeCap = StrokeCap.round;
+ final l = math.min(22.0, math.min(crop.width, crop.height) / 3);
+ for (final (p, sx, sy) in [
+ (crop.topLeft, 1.0, 1.0),
+ (crop.topRight, -1.0, 1.0),
+ (crop.bottomLeft, 1.0, -1.0),
+ (crop.bottomRight, -1.0, -1.0),
+ ]) {
+ canvas.drawPath(
+ Path()
+ ..moveTo(p.dx, p.dy + sy * l)
+ ..lineTo(p.dx, p.dy)
+ ..lineTo(p.dx + sx * l, p.dy),
+ grip,
+ );
+ }
+ }
+
+ @override
+ bool shouldRepaint(_CropPainter old) =>
+ old.image != image || old.box != box || old.crop != crop || old.shade != shade || old.line != line;
+}
diff --git a/lib/widgets/photo_source_sheet.dart b/lib/widgets/photo_source_sheet.dart
index c033747..e303ac6 100644
--- a/lib/widgets/photo_source_sheet.dart
+++ b/lib/widgets/photo_source_sheet.dart
@@ -21,10 +21,7 @@ class PhotoSourceSheet extends StatelessWidget {
final gc = context.gc;
return Container(
padding: sheetPad(context),
- decoration: BoxDecoration(
- color: gc.bgRaised,
- borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
- ),
+ decoration: sheetDecoration(gc),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
diff --git a/test/gym_pass_test.dart b/test/gym_pass_test.dart
index 649cdf7..a5f5d4c 100644
--- a/test/gym_pass_test.dart
+++ b/test/gym_pass_test.dart
@@ -1,12 +1,20 @@
+import 'dart:io';
import 'dart:typed_data';
+import 'dart:ui' as ui;
+
+import 'package:archive/archive.dart';
import 'package:barcode/barcode.dart';
+import 'package:flutter/painting.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:gymmane/models/gym_pass.dart';
+import 'package:gymmane/services/backup_zip.dart';
import 'package:gymmane/services/local_store.dart';
+import 'package:gymmane/services/media_store.dart';
import 'package:gymmane/services/pass_scan.dart';
import 'package:gymmane/state/fit_state.dart';
import 'package:gymmane/widgets/gym_pass_card.dart';
+import 'package:gymmane/widgets/photo_crop.dart';
import 'package:shared_preferences/shared_preferences.dart';
Uint8List _qrPixels(String data, int side) {
@@ -91,4 +99,42 @@ void main() {
expect(fit.gymPasses.first.hue, 2);
expect(fit.lastPass!.name, 'Basic-Fit');
});
+
+ test('un pase con foto vale sin número y su foto viaja en la copia', () async {
+ final tmp = await Directory.systemTemp.createTemp('gymmane_pass');
+ MediaStore.directory = tmp.path;
+ addTearDown(() async {
+ MediaStore.directory = null;
+ if (tmp.existsSync()) await tmp.delete(recursive: true);
+ });
+ final png = Uint8List.fromList([0x89, 0x50, 0x4E, 0x47, 9, 8, 7]);
+ final name = (await MediaStore.saveBytes('pass', 'png', png))!;
+ expect(passCodeValid(PassFormat.photo, name), isTrue);
+ expect(passCodeValid(PassFormat.photo, ''), isFalse);
+ fit.addGymPass(name: 'Studio', code: name, format: PassFormat.photo);
+ expect(fit.gymPasses.single.photo, isTrue);
+ expect(fit.gymPasses.single.square, isFalse);
+
+ final zip = await buildBackupZip();
+ expect(ZipDecoder().decodeBytes(zip).files.map((f) => f.name), contains('passes/studio.png'));
+ fit.resetAllData();
+ await MediaStore.delete(name);
+ expect(await restoreBackupZip(zip), isTrue);
+ final back = fit.gymPasses.single;
+ expect(back.format, PassFormat.photo);
+ expect(await MediaStore.readBytes(back.code), png);
+ });
+
+ test('el recorte se queda con la zona marcada y girar cambia el lado largo', () async {
+ final recorder = ui.PictureRecorder();
+ Canvas(recorder).drawRect(const Rect.fromLTWH(0, 0, 400, 200), Paint()..color = const Color(0xFFFFFFFF));
+ final image = await recorder.endRecording().toImage(400, 200);
+ final png = (await cropToPng(image, const Rect.fromLTRB(0.25, 0, 0.75, 0.5)))!;
+ final codec = await ui.instantiateImageCodec(png);
+ final out = (await codec.getNextFrame()).image;
+ expect((out.width, out.height), (200, 100));
+ final turned = rotateQuarter(image);
+ expect((turned.width, turned.height), (200, 400));
+ expect(await cropToPng(image, const Rect.fromLTRB(0.5, 0.5, 0.5, 0.5)), isNull);
+ });
}