diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index f3d993c..eaa851b 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -25,6 +25,9 @@ repos: - id: debug-statements - id: name-tests-test args: [--pytest-test-first] + # Shared fake widgets, not a test module. Split out of conftest.py only + # because that file passed the 500-line cap. + exclude: ^diet_guard/tests/_(tk_fakes|gate_layout_probe|gate_keyboard_probe)\.py$ - id: check-ast - id: mixed-line-ending args: [--fix=lf] @@ -98,7 +101,7 @@ repos: additional_dependencies: - pytest - requests - - gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.2.0#subdirectory=gatelock + - gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.3.0#subdirectory=gatelock - crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.1.0#subdirectory=crdt-sync - mcp - pydantic diff --git a/app/lib/screens/history_screen.dart b/app/lib/screens/history_screen.dart index 2de93e4..819bc7e 100644 --- a/app/lib/screens/history_screen.dart +++ b/app/lib/screens/history_screen.dart @@ -562,15 +562,33 @@ class _EntryTile extends StatelessWidget { @override Widget build(BuildContext context) { + final canDelete = entry.id != null; return ListTile( leading: const Icon(Icons.restaurant), title: Text(entry.desc), subtitle: Text('${entry.time} • ${entry.source}'), - trailing: Text('${entry.kcal.toStringAsFixed(0)} kcal'), + // Delete needs a focusable control, not just a long-press. Long-press has + // no keyboard equivalent at all, so on the desktop build (a Chrome --app + // window) deleting an entry was pointer-only: unreachable by keyboard and + // invisible to a screen reader. The trailing row keeps the kcal figure + // and adds an IconButton, which Tab reaches and Enter/Space activates. + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text('${entry.kcal.toStringAsFixed(0)} kcal'), + if (canDelete) + IconButton( + icon: const Icon(Icons.delete_outline), + tooltip: 'Delete entry', + onPressed: () => _confirmDelete(context), + ), + ], + ), // Any entry can be edited (legacy null-id entries gain a UUID on save). // Delete remains id-only to avoid ambiguous time+desc matches. onTap: () => onEdit?.call(), - onLongPress: entry.id != null ? () => _confirmDelete(context) : null, + // Retained as a redundant pointer shortcut, never the only route. + onLongPress: canDelete ? () => _confirmDelete(context) : null, ); } @@ -629,10 +647,7 @@ class _FilterSheet extends StatelessWidget { final double maxCarbs; final double maxFat; final void Function(HistoryFilter) onFilterChanged; - final void Function({ - required HistorySortField field, - required bool asc, - }) + final void Function({required HistorySortField field, required bool asc}) onSortChanged; final VoidCallback onApply; final VoidCallback onClear; @@ -655,10 +670,7 @@ class _FilterSheet extends StatelessWidget { style: Theme.of(context).textTheme.titleMedium, ), ), - TextButton( - onPressed: onClear, - child: const Text('Clear all'), - ), + TextButton(onPressed: onClear, child: const Text('Clear all')), ], ), ), @@ -671,16 +683,8 @@ class _FilterSheet extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ // Name search - TextField( - decoration: const InputDecoration( - labelText: 'Search by name', - prefixIcon: Icon(Icons.search), - isDense: true, - ), - controller: TextEditingController(text: filter.nameQuery) - ..selection = TextSelection.collapsed( - offset: filter.nameQuery.length, - ), + _NameSearchField( + initialQuery: filter.nameQuery, onChanged: (v) { filter.nameQuery = v; onFilterChanged(filter); @@ -798,10 +802,7 @@ class _FilterSheet extends StatelessWidget { 'Carbs range (g)', style: Theme.of(context).textTheme.labelLarge, ), - _SliderEndpointLabels( - lo: '0', - hi: '${maxCarbs.round()}g', - ), + _SliderEndpointLabels(lo: '0', hi: '${maxCarbs.round()}g'), RangeSlider( key: const Key('carbs-range-slider'), max: maxCarbs, @@ -832,10 +833,7 @@ class _FilterSheet extends StatelessWidget { 'Fat range (g)', style: Theme.of(context).textTheme.labelLarge, ), - _SliderEndpointLabels( - lo: '0', - hi: '${maxFat.round()}g', - ), + _SliderEndpointLabels(lo: '0', hi: '${maxFat.round()}g'), RangeSlider( key: const Key('fat-range-slider'), max: maxFat, @@ -861,10 +859,7 @@ class _FilterSheet extends StatelessWidget { ], // Source filter - Text( - 'Source', - style: Theme.of(context).textTheme.labelLarge, - ), + Text('Source', style: Theme.of(context).textTheme.labelLarge), const SizedBox(height: 4), Wrap( spacing: 8, @@ -971,6 +966,53 @@ class _FilterSheet extends StatelessWidget { // --------------------------------------------------------------------------- /// Thin row showing the min (0) and max endpoint values for a range slider. +/// The filter sheet's name-search field, owning a persistent controller. +/// +/// Stateful on purpose. The controller used to be built inside +/// `_FilterSheet.build` with the caret forced to the end of the text, and +/// `onChanged` rebuilds the sheet — so every keystroke discarded the controller +/// and re-slammed the caret to end-of-text. Appending worked, but Home/End and +/// arrow-key editing in the middle of the query were silently undone on each +/// character. Keeping the controller in State fixes that without changing how +/// the filter is plumbed. +class _NameSearchField extends StatefulWidget { + const _NameSearchField({required this.initialQuery, required this.onChanged}); + + /// Query text to seed the field with on first build only. + final String initialQuery; + + /// Called on each edit with the new query. + final ValueChanged onChanged; + + @override + State<_NameSearchField> createState() => _NameSearchFieldState(); +} + +class _NameSearchFieldState extends State<_NameSearchField> { + late final TextEditingController _controller = TextEditingController( + text: widget.initialQuery, + ); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return TextField( + controller: _controller, + decoration: const InputDecoration( + labelText: 'Search by name', + prefixIcon: Icon(Icons.search), + isDense: true, + ), + onChanged: widget.onChanged, + ); + } +} + class _SliderEndpointLabels extends StatelessWidget { const _SliderEndpointLabels({required this.lo, required this.hi}); final String lo; diff --git a/app/lib/screens/settings_screen.dart b/app/lib/screens/settings_screen.dart index 1f408ae..38974da 100644 --- a/app/lib/screens/settings_screen.dart +++ b/app/lib/screens/settings_screen.dart @@ -14,6 +14,7 @@ import 'package:diet_guard_app/services/github_client_factory.dart'; import 'package:diet_guard_app/services/github_device_auth.dart'; import 'package:diet_guard_app/services/sync_service.dart'; import 'package:diet_guard_app/services/sync_settings.dart'; +import 'package:diet_guard_app/ui/theme.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -274,132 +275,152 @@ class _SettingsScreenState extends State { } return Scaffold( appBar: AppBar(title: const Text('Settings')), - body: ListView( - padding: const EdgeInsets.all(16), - children: [ - Text('Nutrition', style: Theme.of(context).textTheme.titleMedium), - const SizedBox(height: 8), - TextField( - controller: _kcalGoalController, - keyboardType: TextInputType.number, - inputFormatters: [FilteringTextInputFormatter.digitsOnly], - decoration: const InputDecoration( - labelText: 'Daily kcal goal', - helperText: 'Shown in the history day summary', - suffixText: 'kcal', - ), - onChanged: _onKcalGoalChanged, - ), - const SizedBox(height: 24), - const Divider(), - const SizedBox(height: 8), - Text( - 'Authorize in your browser — no token to paste. Syncs to ' - 'kuhyx/syncs by default.', - style: Theme.of(context).textTheme.bodySmall, - ), - const SizedBox(height: 12), - FilledButton.icon( - onPressed: _connectGitHub, - icon: const Icon(Icons.login), - label: const Text('Connect GitHub'), - ), - const SizedBox(height: 16), - TextField( - controller: _ownerController, - decoration: const InputDecoration(labelText: 'GitHub owner'), - ), - const SizedBox(height: 8), - TextField( - controller: _repoController, - decoration: const InputDecoration(labelText: 'Repo'), - ), - const SizedBox(height: 8), - ExpansionTile( - title: const Text('Advanced'), - tilePadding: EdgeInsets.zero, - childrenPadding: const EdgeInsets.only(bottom: 8), + // Centred and capped at the prose width. On the desktop surface this + // ListView spanned the full ~1366px window, so the explanatory + // paragraphs below ran ~180 characters per line -- roughly twice the + // readable limit (tokens.md rule 21) -- and every field stretched with + // them. Invisible on the phone, where the window is already narrow. + body: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: AppWidth.prose), + child: ListView( + padding: const EdgeInsets.all(16), children: [ - TextField( - controller: _clientIdController, - decoration: const InputDecoration( - labelText: 'OAuth App client id', - helperText: 'Needed for the Connect GitHub button', + Text('Nutrition', style: Theme.of(context).textTheme.titleMedium), + const SizedBox(height: 8), + // A four-digit number: capped so the field does not read as a + // layout error by spanning the whole column. + ConstrainedBox( + constraints: const BoxConstraints(maxWidth: AppWidth.field), + child: TextField( + controller: _kcalGoalController, + keyboardType: TextInputType.number, + inputFormatters: [FilteringTextInputFormatter.digitsOnly], + decoration: const InputDecoration( + labelText: 'Daily kcal goal', + helperText: 'Shown in the history day summary', + suffixText: 'kcal', + ), + onChanged: _onKcalGoalChanged, ), ), + const SizedBox(height: 24), + const Divider(), + const SizedBox(height: 8), + Text( + 'Authorize in your browser — no token to paste. Syncs to ' + 'kuhyx/syncs by default.', + style: Theme.of(context).textTheme.bodySmall, + ), + const SizedBox(height: 12), + FilledButton.icon( + onPressed: _connectGitHub, + icon: const Icon(Icons.login), + label: const Text('Connect GitHub'), + ), + const SizedBox(height: 16), + TextField( + controller: _ownerController, + decoration: const InputDecoration(labelText: 'GitHub owner'), + ), const SizedBox(height: 8), TextField( - controller: _tokenController, - obscureText: true, - decoration: InputDecoration( - labelText: 'Personal access token (fallback)', - // Both wrapper hints are web-only; a VM test always takes - // the null branch. - // coverage:ignore-start - helperText: SyncSettings.exposesTokenValue - ? null - : _storedToken.isEmpty - ? 'Stored by the desktop wrapper, never by the browser' - : 'A token is stored by the desktop wrapper; type here ' - 'only to replace it', - // coverage:ignore-end - helperMaxLines: 2, + controller: _repoController, + decoration: const InputDecoration(labelText: 'Repo'), + ), + const SizedBox(height: 8), + ExpansionTile( + title: const Text('Advanced'), + tilePadding: EdgeInsets.zero, + childrenPadding: const EdgeInsets.only(bottom: 8), + children: [ + TextField( + controller: _clientIdController, + decoration: const InputDecoration( + labelText: 'OAuth App client id', + helperText: 'Needed for the Connect GitHub button', + ), + ), + const SizedBox(height: 8), + TextField( + controller: _tokenController, + obscureText: true, + decoration: InputDecoration( + labelText: 'Personal access token (fallback)', + // Both wrapper hints are web-only; a VM test always takes + // the null branch. + // coverage:ignore-start + helperText: SyncSettings.exposesTokenValue + ? null + : _storedToken.isEmpty + ? 'Stored by the desktop wrapper, never by the ' + 'browser' + : 'A token is stored by the desktop wrapper; ' + 'type here only to replace it', + // coverage:ignore-end + helperMaxLines: 2, + ), + ), + ], + ), + const SizedBox(height: 16), + Wrap( + spacing: 8, + children: [ + ElevatedButton( + onPressed: _busy ? null : _save, + child: const Text('Save'), + ), + OutlinedButton( + onPressed: _busy ? null : _testConnection, + child: const Text('Test connection'), + ), + ElevatedButton( + onPressed: _busy ? null : _syncNow, + child: const Text('Sync now'), + ), + ], + ), + const SizedBox(height: 24), + const Divider(), + const SizedBox(height: 8), + Text( + 'Notifications', + style: Theme.of(context).textTheme.titleMedium, + ), + const SizedBox(height: 4), + Text( + _isAndroid + ? 'A background check nags you every ~15 min if a ' + 'meal slot is overdue. Aggressive OEM battery ' + 'optimization (MIUI, some Samsung configs) can ' + 'delay this well past 15 min -- request an ' + 'exemption for reliable nagging.' + : 'A check runs every 5 min while this window is open and ' + 'notifies you about an overdue meal slot. A browser ' + 'cannot run anything once the window is closed -- on ' + 'the PC the real backstop is the diet_guard gate, ' + 'which locks the screen instead.', + style: Theme.of(context).textTheme.bodySmall, + ), + // Battery-optimization exemption is Android-only, and + // `permission_handler` has no web implementation at all; + // the row would throw rather than degrade in the browser. + if (_isAndroid) ...[ + const SizedBox(height: 12), + OutlinedButton.icon( + onPressed: _requestBatteryExemption, + icon: const Icon(Icons.battery_alert), + label: const Text('Disable battery optimization'), ), - ), + ], + if (_status != null) ...[ + const SizedBox(height: 16), + Text(_status!, style: Theme.of(context).textTheme.bodyMedium), + ], ], ), - const SizedBox(height: 16), - Wrap( - spacing: 8, - children: [ - ElevatedButton( - onPressed: _busy ? null : _save, - child: const Text('Save'), - ), - OutlinedButton( - onPressed: _busy ? null : _testConnection, - child: const Text('Test connection'), - ), - ElevatedButton( - onPressed: _busy ? null : _syncNow, - child: const Text('Sync now'), - ), - ], - ), - const SizedBox(height: 24), - const Divider(), - const SizedBox(height: 8), - Text('Notifications', style: Theme.of(context).textTheme.titleMedium), - const SizedBox(height: 4), - Text( - _isAndroid - ? 'A background check nags you every ~15 min if a meal slot ' - 'is overdue. Aggressive OEM battery optimization (MIUI, ' - 'some Samsung configs) can delay this well past 15 min ' - '-- request an exemption for reliable nagging.' - : 'A check runs every 5 min while this window is open and ' - 'notifies you about an overdue meal slot. A browser ' - 'cannot run anything once the window is closed -- on ' - 'the PC the real backstop is the diet_guard gate, ' - 'which locks the screen instead.', - style: Theme.of(context).textTheme.bodySmall, - ), - // Battery-optimization exemption is an Android-only concept, and - // `permission_handler` has no web implementation at all; the row - // would throw rather than degrade if it were shown in the browser. - if (_isAndroid) ...[ - const SizedBox(height: 12), - OutlinedButton.icon( - onPressed: _requestBatteryExemption, - icon: const Icon(Icons.battery_alert), - label: const Text('Disable battery optimization'), - ), - ], - if (_status != null) ...[ - const SizedBox(height: 16), - Text(_status!, style: Theme.of(context).textTheme.bodyMedium), - ], - ], + ), ), ); } diff --git a/app/lib/ui/theme.dart b/app/lib/ui/theme.dart index 93d81d5..134705f 100644 --- a/app/lib/ui/theme.dart +++ b/app/lib/ui/theme.dart @@ -175,3 +175,30 @@ abstract final class AppTextSize { /// 32px. static const double display = 32; } + +/// Line-length and layout caps for the desktop surface. +/// +/// The Linux desktop build is this same Dart running as Flutter **web** in a +/// Chrome `--app` window, so every screen is laid out at whatever width that +/// window happens to be — commonly 1366px on the laptop. Without a cap, a +/// phone-width single-column design simply stretches: prose ran ~180 characters +/// per line (roughly 2x the readable limit) and a four-digit calorie field +/// spanned ~1334px. Neither is clipped, so nothing looks broken; it is just +/// unusable to read. +abstract final class AppWidth { + /// 640px — the prose/paragraph cap (tokens.md rule 21, 40rem, ~65-70 chars). + static const double prose = 640; + + /// 420px — cap for a single-purpose input (a number, a short name). + /// + /// Narrower than [prose] because a field wider than its longest plausible + /// value reads as a layout error rather than an affordance. + static const double field = 420; + + /// Viewport height below which the layout should switch to its compact form. + /// + /// 700px, i.e. 768 minus typical window chrome: the supported floor is a + /// 1366x768 panel, and these are *short* landscape viewports, which + /// phone-portrait test sizes never exercise. + static const double shortViewport = 700; +} diff --git a/app/lib/widgets/day_status_calendar.dart b/app/lib/widgets/day_status_calendar.dart index d3b5013..97f83f2 100644 --- a/app/lib/widgets/day_status_calendar.dart +++ b/app/lib/widgets/day_status_calendar.dart @@ -212,9 +212,20 @@ class DayStatusCalendar extends StatelessWidget { ), ); if (onDaySelected == null) return cellWidget; - return GestureDetector( - onTap: () => onDaySelected!(DateTime(year, m, day)), - child: cellWidget, + // InkWell, not a bare GestureDetector: tapping a day navigates + // to the date-filtered history, and a GestureDetector is not + // focusable, so that navigation had no keyboard route at all + // and no semantics for a screen reader. InkWell is a focus + // stop and is activated by Enter/Space. + final date = DateTime(year, m, day); + return Semantics( + button: true, + label: 'View $day/$m/$year', + child: InkWell( + onTap: () => onDaySelected!(date), + customBorder: const CircleBorder(), + child: cellWidget, + ), ); }), ); diff --git a/app/test/keyboard_operability_test.dart b/app/test/keyboard_operability_test.dart new file mode 100644 index 0000000..88ba543 --- /dev/null +++ b/app/test/keyboard_operability_test.dart @@ -0,0 +1,230 @@ +/// Pointer-free operability tests for controls that had no keyboard route. +/// +/// The desktop build is this Dart running as Flutter **web** in a Chrome +/// `--app` window, so "mobile-only" gestures are not a fallback there — they +/// are the whole interaction. Each test below stands in for something that was +/// literally impossible without a pointer. +/// +/// These are also the repo's first keyboard-reachability assertions: before +/// this file, `test/` had ~109 `tester.tap` calls and zero checks that anything +/// was focusable at all. +library; + +import 'dart:io'; + +import 'package:diet_guard_app/models/food_entry.dart'; +import 'package:diet_guard_app/screens/history_screen.dart'; +import 'package:diet_guard_app/services/budget_history_service.dart'; +import 'package:diet_guard_app/services/document_store_io.dart'; +import 'package:diet_guard_app/services/log_storage_service.dart'; +import 'package:diet_guard_app/ui/theme.dart'; +import 'package:diet_guard_app/widgets/day_status_calendar.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/semantics.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// Landscape and *short* — the supported floor. Phone-portrait sizes, which is +/// all the existing suite pinned, exercise neither constraint. +const _desktopSize = Size(1366, 768); + +void main() { + group('calendar day cells', () { + testWidgets('are focusable, so date navigation has a keyboard route', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: DayStatusCalendar( + statusByDate: const {}, + month: DateTime(2026, 7), + today: DateTime(2026, 7, 30), + onPrevMonth: _noop, + onNextMonth: _noop, + onDaySelected: (_) {}, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // A bare GestureDetector — what this replaced — builds no InkWell and no + // focus node, so no day was reachable by Tab and the whole + // date-filtered-history route was pointer-only. + expect( + find.byType(InkWell), + findsWidgets, + reason: 'day cells must be focusable, not bare GestureDetectors', + ); + }); + + testWidgets('expose a button semantic for screen readers', (tester) async { + final handle = tester.ensureSemantics(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: DayStatusCalendar( + statusByDate: const {}, + month: DateTime(2026, 7), + today: DateTime(2026, 7, 30), + onPrevMonth: _noop, + onNextMonth: _noop, + onDaySelected: (_) {}, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + final node = tester.getSemantics(find.byType(InkWell).first); + expect(node.hasFlag(SemanticsFlag.isButton), isTrue); + // Disposed inline, not via addTearDown: Flutter verifies outstanding + // handles at the end of the test body, before tearDowns run. + handle.dispose(); + }); + + testWidgets('gain a tab stop per day only when selection is enabled', ( + tester, + ) async { + // Counts InkWells rather than matching a semantics label: the day cells + // merge their own label with the day-number Text inside them, so a label + // finder is brittle. The month-navigation chevrons are IconButtons and + // contribute a constant number of InkWells in both cases, so the + // *difference* is exactly the per-day tab stops -- which is the property + // under test. + Future inkWells({required bool selectable}) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: DayStatusCalendar( + statusByDate: const {}, + month: DateTime(2026, 7), + today: DateTime(2026, 7, 30), + onPrevMonth: _noop, + onNextMonth: _noop, + onDaySelected: selectable ? (_) {} : null, + ), + ), + ), + ); + await tester.pumpAndSettle(); + return tester.widgetList(find.byType(InkWell)).length; + } + + final readOnlyCount = await inkWells(selectable: false); + final selectableCount = await inkWells(selectable: true); + + // July 2026 has 31 days. Before the fix this difference was zero: the + // cells were bare GestureDetectors, so no day was ever a tab stop. + expect(selectableCount - readOnlyCount, 31); + }); + }); + + group('width caps', () { + test('prose cap matches the design-system line-length rule', () { + // tokens.md rule 21: 40rem / ~65-70 characters. Without this the desktop + // window rendered prose at roughly 180 characters per line. + expect(AppWidth.prose, 640); + }); + + test('a single-purpose field is capped well below the prose width', () { + expect(AppWidth.field, lessThan(AppWidth.prose)); + }); + + test('the short-viewport breakpoint trips before the 768px floor', () { + expect(AppWidth.shortViewport, lessThan(768)); + }); + }); + + group('history entry delete', () { + late Directory tempDir; + + setUp(() async { + tempDir = await Directory.systemTemp.createTemp('diet_guard_kbd_'); + LogStorageService.resetForTesting(store: FileDocumentStore(tempDir)); + BudgetHistoryService.resetForTesting(store: FileDocumentStore(tempDir)); + }); + + tearDown(() async { + LogStorageService.resetForTesting(); + BudgetHistoryService.resetForTesting(); + await tempDir.delete(recursive: true); + }); + + testWidgets('has a focusable control, not long-press only', (tester) async { + tester.view.physicalSize = _desktopSize; + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + await LogStorageService.instance.writeLog({ + '2026-07-30': [ + const FoodEntry( + id: 'has-id', + time: '2026-07-30T08:00:00+02:00', + desc: 'oatmeal with raisins', + grams: 100, + kcal: 430, + proteinG: 12, + carbsG: 60, + fatG: 9, + source: 'food bank', + ), + ], + }); + + // HistoryScreen loads via a fire-and-forget Future in initState that the + // frame scheduler does not track, so settle inside runAsync. + await tester.runAsync(() async { + await tester.pumpWidget(const MaterialApp(home: HistoryScreen())); + await Future.delayed(const Duration(milliseconds: 50)); + await tester.pumpAndSettle(); + }); + + // Delete used to be bound only to onLongPress, which has no keyboard + // equivalent whatsoever. + expect( + find.byTooltip('Delete entry'), + findsOneWidget, + reason: 'delete needs a tab-reachable control, not long-press only', + ); + }); + + testWidgets('offers no delete control for an entry without an id', ( + tester, + ) async { + tester.view.physicalSize = _desktopSize; + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + await LogStorageService.instance.writeLog({ + '2026-07-30': [ + const FoodEntry( + time: '2026-07-30T09:00:00+02:00', + desc: 'legacy entry', + grams: 100, + kcal: 100, + proteinG: 1, + carbsG: 2, + fatG: 3, + source: 'legacy', + ), + ], + }); + + await tester.runAsync(() async { + await tester.pumpWidget(const MaterialApp(home: HistoryScreen())); + await Future.delayed(const Duration(milliseconds: 50)); + await tester.pumpAndSettle(); + }); + + // Delete stays id-only to avoid ambiguous time+desc matches, so the + // control must be absent rather than present-and-failing. + expect(find.byTooltip('Delete entry'), findsNothing); + }); + }); +} + +/// A do-nothing month-navigation callback. +void _noop() {} diff --git a/diet_guard/_gatelock_buttons.py b/diet_guard/_gatelock_buttons.py index 87c405e..c822e04 100644 --- a/diet_guard/_gatelock_buttons.py +++ b/diet_guard/_gatelock_buttons.py @@ -61,11 +61,17 @@ def make_button( command: Callable[[], None], bold: bool = True, ) -> tk.Button: - """Build a button from the shared primary/secondary/danger palette.""" + """Build a button from the shared primary/secondary/danger palette. + + Binds ```` as well as relying on ``command``. Tk's X11 class + bindings give ``tk.Button`` only ````; there is no ```` + binding, so without this every button in the gate is Space-only and Enter + silently does nothing -- which is not the key a user reaches for. + """ fill, text_color = _BUTTON_FILLS[variant] size = _BUTTON_SIZE[variant] font = (_COLORS.font_family, size, "bold") if bold else (_COLORS.font_family, size) - return tk.Button( + button = tk.Button( parent, text=text, font=font, @@ -76,4 +82,13 @@ def make_button( padx=_BUTTON_PADX, pady=_BUTTON_PADY, command=command, + **_COLORS.focus_kwargs(), ) + + def _activate(_event: tk.Event) -> str: + button.invoke() + return "break" + + button.bind("", _activate, add="+") + button.bind("", _activate, add="+") + return button diff --git a/diet_guard/_gatelock_calendar.py b/diet_guard/_gatelock_calendar.py index 1ad87ca..0f58db1 100644 --- a/diet_guard/_gatelock_calendar.py +++ b/diet_guard/_gatelock_calendar.py @@ -113,6 +113,11 @@ class _GateCalendar(_GateMealFlow): ) cal_widgets = build_calendar_frame(notebook, self._cal_vars, cal_callbacks) notebook.add(cal_widgets.frame, text="History") + # Ctrl+Tab / Ctrl+PageUp / Ctrl+PageDown and Alt+mnemonic tab switching + # all live in toplevel bindings that ttk only installs on request. The + # notebook is in the focus ring and Left/Right work once it holds focus, + # but without this the idioms a user actually reaches for are dead. + notebook.enable_traversal() self._cal_surfaces.append(cal_widgets) self._cal_widgets = cal_widgets return widgets diff --git a/diet_guard/_gatelock_typography.py b/diet_guard/_gatelock_typography.py index 3337206..a8d286d 100644 --- a/diet_guard/_gatelock_typography.py +++ b/diet_guard/_gatelock_typography.py @@ -2,17 +2,36 @@ Split out so :mod:`._gatelock_ui`, :mod:`._gatelock_calendar`, and :mod:`._gatelock_buttons` read the same sizes instead of each picking its -own point value per label -- see ``DESIGN_AUDIT_TODO.md``. Values are the -px sizes from ``~/utils/unified-design-system/tokens.md``'s typography -scale, used directly as Tk point sizes (Tk has no separate px/pt distinction -in this codebase's existing font tuples). +own value per label -- see ``DESIGN_AUDIT_TODO.md``. + +**These are Tk font sizes, and Tk encodes the unit in the sign: positive +means points, negative means pixels.** The design-system scale in +``~/utils/unified-design-system/tokens.md`` is in *pixels*, so every constant +here is negative. + +This module previously carried the positive values with a comment asserting +that "Tk has no separate px/pt distinction". That premise was wrong, and the +consequence was not cosmetic: at ~100 DPI a positive 16 renders with a 26px +linespace where a negative 16 gives 20px, so every string in the gate was +~30% oversized. That alone pushed the Log Meal tab to 866px of required +height inside a 739px pane on a 1366x768 screen -- clipping the title and the +dashboard symmetrically, with no scrollbar to recover them. Keep the signs +negative; ``tests/test_gatelock_typography.py`` enforces it, and +``tests/measure_gate_layout.py`` enforces the height that depends on it. + +``gatelock.LockConfig`` grew the same scale (plus ``LockConfig.font()``, which +applies the sign for you). Once the gatelock pin here moves past v0.2.1, this +module should become a thin re-export of that shared scale rather than a +second copy. """ from __future__ import annotations -DISPLAY = 32 -TITLE = 24 -SUBTITLE = 20 -BODY = 16 -LABEL = 14 -CAPTION = 12 +# Pixel sizes from tokens.md, negated for Tk. Keep in sync with +# gatelock.LockConfig.type_* until this module can defer to it. +DISPLAY = -32 +TITLE = -24 +SUBTITLE = -20 +BODY = -16 +LABEL = -14 +CAPTION = -12 diff --git a/diet_guard/_gatelock_ui.py b/diet_guard/_gatelock_ui.py index 0332768..9771993 100644 --- a/diet_guard/_gatelock_ui.py +++ b/diet_guard/_gatelock_ui.py @@ -19,7 +19,7 @@ from __future__ import annotations import tkinter as tk from typing import TYPE_CHECKING -from gatelock import LockConfig +from gatelock import LockConfig, ScrollableSurface, escape_text_tab_trap from diet_guard._gatelock_buttons import make_button from diet_guard._gatelock_spacing import MD, SM, XS @@ -65,6 +65,12 @@ UNIT_ITEMS = "items" # Per-basis label prefixes for the two measuring modes. BASIS_PREFIX_GRAMS = "Nutrition as on the label — per" BASIS_PREFIX_ITEMS = "Nutrition per 1 item ≈" +# Wrap width for the gate's prose labels, in px. 640 is tokens.md's line-length +# cap (rule 21, 40rem / ~65-70 characters). This was 900 at five call sites, +# which both exceeded the cap and -- more practically -- forced a 900px-wide +# layout on a 1024px screen, since a label's wrap width feeds its requested +# width and therefore the whole centered column's. +_WRAP_PX = 640 __all__ = [ @@ -129,6 +135,7 @@ def _numeric_entry( justify="center", validate="key", validatecommand=vcmd, + **_COLORS.focus_kwargs(), ) @@ -144,6 +151,12 @@ def _macro_cell( return entry +# Re-exported from gatelock so the four lockers share one implementation of +# this Tk-default workaround rather than each carrying a copy. Kept as a +# module-level name because the gate's own tests bind to it here. +_escape_text_tab_trap = escape_text_tab_trap + + def _build_desc(parent: tk.Frame) -> tk.Text: """Build and return the multi-line "what did you eat?" description box. @@ -167,10 +180,14 @@ def _build_desc(parent: tk.Frame) -> tk.Text: bg=_FIELD_BG, fg=FG, insertbackground=FG, - highlightthickness=1, - highlightbackground=_MUTED, + # focus_kwargs() sets highlightcolor (the *focused* ring). This + # previously set only highlightbackground, which is the UNFOCUSED ring + # -- so the box outlined while unfocused and went black (invisible on + # bg) the moment it took focus, exactly inverting the affordance. + **_COLORS.focus_kwargs(), ) text.pack(pady=(XS, SM)) + _escape_text_tab_trap(text) return text @@ -186,7 +203,10 @@ def _build_suggestion_box(parent: tk.Frame) -> tk.Listbox: selectbackground=_ACCENT, selectforeground=_COLORS.on_fill, activestyle="none", - highlightthickness=0, + # Was highlightthickness=0, which removed the focus ring entirely. The + # list *is* arrow-key navigable, so it was keyboard-usable with no + # visual indication of where focus was. + **_COLORS.focus_kwargs(), ) box.pack(pady=(0, SM)) return box @@ -210,24 +230,55 @@ def _build_amount_row( row.pack(pady=(XS, SM)) amount_entry = _numeric_entry(root, row, width=10, variable=vars_.entries.amount) amount_entry.pack(side="left", ipady=XS) - unit_menu = tk.OptionMenu( - row, - vars_.unit, - UNIT_GRAMS, - UNIT_ITEMS, - command=on_unit_change, - ) - unit_menu.configure( - font=(_FONT, LABEL), - bg=_FIELD_BG, - fg=FG, - activebackground=_ACCENT, - highlightthickness=0, - ) - unit_menu.pack(side="left", padx=(SM, 0)) + _build_unit_selector(row, vars_, on_unit_change) return amount_entry +def _build_unit_selector( + row: tk.Frame, + vars_: GateVars, + on_unit_change: Callable[[str], None], +) -> None: + """Build the grams/items selector as focusable radio buttons. + + Deliberately **not** a ``tk.OptionMenu``, which this used to be, for two + independent reasons: + + 1. **It was unreachable by keyboard.** ``OptionMenu``'s underlying + ``Menubutton`` defaults to ``takefocus=0``, so ``::tk::FocusOK`` rejects + it and it never appears in the tab ring (verified: the ring ran + Entry -> Text -> Listbox -> Button -> TNotebook and skipped it). Since + the unit rescales the entire entry, a pointerless user could not switch + between "250 grams" and "3 items" inside a lock they cannot leave + without logging a meal. + 2. **A posted menu is unsafe on a lock surface.** A dropped-down Tk menu is + a separate override-redirect toplevel that steals the Tk grab, which + gatelock's recovery tick then kills within a second. That is the + documented 2026-07-26 failure where a frozen sport selector logged a walk + as table tennis, and it is why screen-locker statically bans + ``OptionMenu`` on lock surfaces. + + ``tk.Radiobutton`` avoids both: it is in the tab ring by default and accepts + **both** ``Space`` and ``Return`` (unlike ``tk.Button``, which on X11 binds + only ``Space``), and it posts nothing. + """ + for unit in (UNIT_GRAMS, UNIT_ITEMS): + tk.Radiobutton( + row, + text=unit, + value=unit, + variable=vars_.unit, + command=lambda u=unit: on_unit_change(u), + font=(_FONT, LABEL), + bg=BG, + fg=FG, + selectcolor=_FIELD_BG, + activebackground=BG, + activeforeground=_ACCENT, + **_COLORS.focus_kwargs(), + ).pack(side="left", padx=(SM, 0)) + + def _build_macro_section( root: tk.Misc, parent: tk.Frame, @@ -290,7 +341,7 @@ def _build_dashboard(parent: tk.Frame, vars_: GateVars) -> None: fg=_MUTED, justify="left", anchor="w", - wraplength=900, + wraplength=_WRAP_PX, ).pack(pady=(XS, 0)) @@ -305,58 +356,69 @@ def build_layout( The controller calls this once (after configuring the window) and is then responsible for binding per-keystroke events to the returned widgets. + + The content lives inside a :class:`~gatelock.ScrollableSurface` rather than + a ``place``-centered frame. It has to: this tab requires ~700px even when + empty and grows a line per logged meal, so on a 1366x768 screen it exceeded + the notebook's content pane and a centered frame clipped it *symmetrically* + -- losing the "Diet Gate" title and the slot header off the top while the + calorie headline and dashboard went off the bottom, with no scrollbar to + recover either. The viewport also makes the overflow keyboard-reachable, + which matters because this is a hard lock the user cannot leave without + logging a meal. See ``tests/measure_gate_layout.py``. """ - frame = tk.Frame(root, bg=BG) - frame.place(relx=0.5, rely=0.5, anchor="center") + surface = ScrollableSurface(root, _COLORS) + frame = surface.container + body = surface.content tk.Label( - frame, + body, text="🍽 Diet Gate", font=(_FONT, DISPLAY, "bold"), bg=BG, fg=_ACCENT, ).pack(pady=(0, XS)) tk.Label( - frame, + body, textvariable=vars_.slot_header, font=(_FONT, SUBTITLE, "bold"), bg=BG, fg=FG, - wraplength=900, + wraplength=_WRAP_PX, justify="center", ).pack(pady=(0, MD)) - desc_text = _build_desc(frame) - suggestion_box = _build_suggestion_box(frame) + desc_text = _build_desc(body) + suggestion_box = _build_suggestion_box(body) amount_entry = _build_amount_row( root, - frame, + body, vars_, callbacks.on_unit_change, ) - basis_prefix, per_entry, macros = _build_macro_section(root, frame, vars_) + basis_prefix, per_entry, macros = _build_macro_section(root, body, vars_) tk.Label( - frame, + body, textvariable=vars_.projection, font=(_FONT, LABEL, "bold"), bg=BG, fg=FG, - wraplength=900, + wraplength=_WRAP_PX, justify="center", ).pack(pady=(XS, XS)) tk.Label( - frame, + body, textvariable=vars_.preview, font=(_FONT, BODY, "bold"), bg=BG, fg=_ACCENT, - wraplength=900, + wraplength=_WRAP_PX, justify="center", ).pack(pady=(XS, SM)) make_button( - frame, + body, text="Log & Continue", variant="primary", command=callbacks.on_submit, @@ -365,7 +427,7 @@ def build_layout( # Manual pull for a meal already logged on another device (the phone) but # not yet propagated to this machine -- saves re-typing it to unlock. make_button( - frame, + body, text="⟳ Fetch from sync", variant="secondary", command=callbacks.on_fetch_sync, @@ -373,17 +435,22 @@ def build_layout( ).pack(pady=(0, SM)) status_label = tk.Label( - frame, + body, textvariable=vars_.status, font=(_FONT, LABEL), bg=BG, fg=FG, - wraplength=900, + wraplength=_WRAP_PX, justify="center", ) status_label.pack() - _build_dashboard(frame, vars_) + _build_dashboard(body, vars_) + + # Wire focus-following and reset the view now that the content exists. + # Without this, Tab walks onto fields scrolled out of sight -- clipping does + # not remove a widget from the tab chain. + surface.finalize() if demo_mode: make_button( diff --git a/diet_guard/tests/_gate_keyboard_probe.py b/diet_guard/tests/_gate_keyboard_probe.py new file mode 100644 index 0000000..9735aa4 --- /dev/null +++ b/diet_guard/tests/_gate_keyboard_probe.py @@ -0,0 +1,131 @@ +"""Walk the gate's real focus ring and report keyboard reachability. + +Reading the code is not enough to know what is reachable: Tk decides via +``::tk::FocusOK``, which consults ``takefocus``, mapped-ness, *and* whether the +widget's class has any key bindings at all. A ``tk.Canvas`` fails that last test +even though it looks like a normal widget, and a ``Menubutton`` fails the first. +So this walks ``tk_focusNext`` the way the Tab key does. + +There is deliberately no ``print``-based CLI: ruff runs with +``--unsafe-fixes``, whose ``T201`` fix *deletes* print statements, silently +turning a diagnostic script into a no-op. :func:`probe` is consumed by +``tests/test_gatelock_keyboard.py``, which fails rather than reports. + +Test support, not a test: it lives under ``tests/`` and is excluded from the +``test_*.py`` naming hook. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +import tkinter as tk +from tkinter import ttk + +from diet_guard._gatelock_ui import GateCallbacks, build_layout +from diet_guard.tests._gate_layout_probe import _make_vars, _noop + +# How far to walk before declaring the ring non-terminating. +_MAX_RING_STEPS = 60 + + +@dataclass +class RingReport: + """What a focus-ring walk found.""" + + classes: list[str] = field(default_factory=list) + focus_rings_visible: dict[str, str] = field(default_factory=dict) + text_escapes_tab: bool = False + buttons_take_return: bool = False + + def has(self, widget_class: str) -> bool: + """Whether the ring includes at least one widget of this class.""" + return widget_class in self.classes + + def describe(self) -> str: + """Return a multi-line human-readable summary.""" + lines = [f"focus ring ({len(self.classes)} stops):"] + lines.append(" " + " -> ".join(self.classes) + " -> (wrap)") + lines.append("focus-ring colors by class:") + for name, color in sorted(self.focus_rings_visible.items()): + verdict = ( + "visible" + if color.lower() not in {"", "#000000", "black"} + else "INVISIBLE" + ) + lines.append(f" {name:<12} highlightcolor={color or ''} {verdict}") + lines.append(f"Text escapes Tab : {self.text_escapes_tab}") + lines.append(f"Buttons accept Return : {self.buttons_take_return}") + return "\n".join(lines) + + +def _walk_ring(start: tk.Misc, limit: int = _MAX_RING_STEPS) -> list[tk.Misc]: + """Return the widgets Tab visits, starting from ``start``, until it wraps.""" + seen: list[tk.Misc] = [] + current = start + for _ in range(limit): + if current in seen: + break + seen.append(current) + current = current.tk_focusNext() + if current is None: + break + return seen + + +def probe(screen_w: int = 1366, screen_h: int = 768) -> RingReport: + """Build the gate and probe its keyboard behaviour.""" + root = tk.Tk() + try: + root.geometry(f"{screen_w}x{screen_h}+0+0") + notebook = ttk.Notebook(root) + notebook.place(relx=0, rely=0, relwidth=1, relheight=1) + callbacks = GateCallbacks( + on_unit_change=_noop, + on_submit=_noop, + on_close=_noop, + on_fetch_sync=_noop, + ) + widgets = build_layout( + notebook, _make_vars(populated=True), callbacks, demo_mode=False + ) + notebook.add(widgets.frame, text="Log Meal") + notebook.enable_traversal() + root.focus_force() + root.update() + root.update_idletasks() + + report = RingReport() + ring = _walk_ring(widgets.desc_text) + for widget in ring: + report.classes.append(widget.winfo_class()) + try: + color = str(widget.cget("highlightcolor")) + except tk.TclError: + continue + report.focus_rings_visible.setdefault(widget.winfo_class(), color) + + # Tab out of the description box: it must not stay focused. + widgets.desc_text.focus_set() + root.update() + widgets.desc_text.event_generate("") + root.update() + root.update_idletasks() + report.text_escapes_tab = root.focus_get() is not widgets.desc_text + + # Return must invoke a button (Tk binds only on X11). + fired: list[str] = [] + probe_button = next( + (w for w in ring if isinstance(w, tk.Button)), + None, + ) + if probe_button is not None: + probe_button.configure(command=lambda: fired.append("hit")) + probe_button.focus_set() + root.update() + probe_button.event_generate("") + root.update() + root.update_idletasks() + report.buttons_take_return = bool(fired) + return report + finally: + root.destroy() diff --git a/diet_guard/tests/_gate_layout_probe.py b/diet_guard/tests/_gate_layout_probe.py new file mode 100644 index 0000000..003a044 --- /dev/null +++ b/diet_guard/tests/_gate_layout_probe.py @@ -0,0 +1,328 @@ +r"""Measure the gate layout against a target screen and prove it is reachable. + +Import :func:`measure` from a test to assert the invariant. There is +deliberately no ``print``-based CLI here: ruff runs with ``--unsafe-fixes``, +whose ``T201`` fix *deletes* print statements, which silently turns a +diagnostic script into a no-op. The gate is ``test_gate_layout_fits.py``, +which fails rather than reports. + +Test support, not a test: it lives under ``tests/`` (excluded from the +``test_*.py`` naming hook) rather than in the package, so its diagnostic-only +branches -- the no-viewport degradation path in particular -- are not held to +the package's 100%-coverage bar for code that only runs against a layout that +has not been fixed yet. + +**What the invariant actually is.** It is not "the content fits" -- the Log Meal +tab legitimately grows a line per logged meal, so on a short screen it will +eventually exceed the pane. It is "nothing is unreachable": the content lives in +a scroll viewport, that viewport scrolls by keyboard, and focus moves the view to +follow. Before the viewport existed the content was ``place``-centered, so +overflow sheared the title off the top and the submit button off the bottom +simultaneously, with no scrollbar and no way back -- inside a hard lock the user +cannot leave without logging a meal. + +``content_span`` is still reported because a layout that needs scrolling on a +*fresh boot* is worth knowing about even when it is technically reachable. + +Run the gate with: + xvfb-run -a -s "-screen 0 1366x768x24" \\ + python3 -m pytest diet_guard/tests/test_gate_layout_fits.py +""" + +from __future__ import annotations + +from dataclasses import dataclass +import tkinter as tk +from tkinter import ttk + +from diet_guard._gatelock_ui import GateCallbacks, GateVars, build_layout +from diet_guard._gatelock_ui_types import GateEntryVars + +# ttk.Notebook's tab strip is chrome the content pane never gets to use. +# Measured rather than assumed; see _notebook_overhead(). +_FALLBACK_TAB_STRIP_PX = 44 +# A realistic full day, as the dashboard renders it. Module-level so ruff's +# FLY002 (static-join-to-f-string) does not rewrite an inline join into one +# over-long line, which then trips E501. +_SAMPLE_DASHBOARD = ( + "08:00 oatmeal with milk and raisins -- 430 kcal", + "12:00 chicken thigh, rice, cucumber -- 780 kcal", + "16:00 greek yoghurt and a banana -- 260 kcal", + "protein 118 / 140 g carbs 210 g fat 61 g", + "protein target: 22 g remaining", +) + + +@dataclass(frozen=True) +class Measurement: + """One layout measurement against one screen size.""" + + screen_w: int + screen_h: int + content_span: int + viewport_h: int + scrolls_by_keyboard: bool + last_widget_visible_after_focus: bool + has_scroll_viewport: bool = True + + @property + def needs_scroll(self) -> bool: + """Whether the content is taller than the viewport.""" + return self.content_span > self.viewport_h + + @property + def reachable(self) -> bool: + """Whether every part of the content can be reached by keyboard. + + Content that fits is trivially reachable. Content that overflows must + scroll by keyboard *and* bring a focused below-the-fold widget into + view. + + Deliberately not asserted: that focusing always *moves* the view. When + the overflow is small the deepest widget is already visible, and then + holding still is the correct behaviour -- the invariant is "the focused + widget is visible", not "the viewport scrolled". + """ + if not self.needs_scroll: + return True + return self.scrolls_by_keyboard and self.last_widget_visible_after_focus + + def describe(self) -> str: + """Return a one-line human-readable summary.""" + fit = ( + f"needs scroll (+{self.content_span - self.viewport_h}px)" + if self.needs_scroll + else "fits" + ) + verdict = "REACHABLE" if self.reachable else "UNREACHABLE CONTENT" + viewport = ( + "scroll viewport present" + if self.has_scroll_viewport + else "NO SCROLL VIEWPORT -- overflow is clipped, not scrolled" + ) + return ( + f"{self.screen_w}x{self.screen_h}: " + f"content {self.content_span} in viewport {self.viewport_h} " + f"-> {fit}; {viewport}; keys={self.scrolls_by_keyboard} " + f"last_visible={self.last_widget_visible_after_focus} " + f"-> {verdict}" + ) + + +def _make_vars(*, populated: bool) -> GateVars: + """Build the gate's Tk variables, optionally with realistic content. + + The empty case is *not* the worst case: the dashboard grows one line per + logged meal, so a layout that fits on a fresh boot can still overflow by + dinnertime. ``populated`` models a full day. + """ + entries = GateEntryVars( + amount=tk.StringVar(value="250" if populated else ""), + per=tk.StringVar(value="100" if populated else ""), + kcal=tk.StringVar(value="520" if populated else ""), + protein=tk.StringVar(value="31" if populated else ""), + carbs=tk.StringVar(value="44" if populated else ""), + fat=tk.StringVar(value="18" if populated else ""), + ) + dashboard = "" + if populated: + dashboard = "\n".join(_SAMPLE_DASHBOARD) + return GateVars( + status=tk.StringVar(value="Enter what you ate." if populated else ""), + slot_header=tk.StringVar( + value="20:00 meal not logged yet -- what did you eat?" + if populated + else "Log your meal" + ), + preview=tk.StringVar(value="520 kcal for 250 g" if populated else ""), + projection=tk.StringVar( + value="projected 1990 / 2100 kcal today" if populated else "" + ), + cal_headline=tk.StringVar( + value="1470 kcal so far -- 630 left" if populated else "" + ), + dashboard=tk.StringVar(value=dashboard), + unit=tk.StringVar(value="grams"), + entries=entries, + ) + + +def _noop(*_args: object) -> None: + """Swallow a widget callback; measurement never activates anything.""" + + +def _notebook_overhead(root: tk.Misc) -> int: + """Return the vertical px a ``ttk.Notebook`` tab strip costs. + + Measured from a throwaway notebook rather than hardcoded, so a theme or + font change cannot silently invalidate the budget. + """ + probe = ttk.Notebook(root) + filler = tk.Frame(probe, width=200, height=100) + probe.add(filler, text="Log Meal") + probe.update_idletasks() + overhead = probe.winfo_reqheight() - filler.winfo_reqheight() + probe.destroy() + return overhead if overhead > 0 else _FALLBACK_TAB_STRIP_PX + + +# Tk widget classes that take keyboard focus by default. Checking `takefocus` +# is not enough: it is "" on most widgets, meaning "ask ::tk::FocusOK", so an +# empty value indicates a *default*-focusable widget rather than an opted-out +# one. Matching on class is what actually mirrors FocusOK's behaviour here. +_FOCUSABLE_CLASSES = frozenset( + { + "Button", + "Checkbutton", + "Entry", + "Listbox", + "Radiobutton", + "Spinbox", + "Text", + } +) + + +def _is_focusable(widget: tk.Misc) -> bool: + """Whether ``widget`` would accept keyboard focus.""" + if str(widget.cget("takefocus")) == "0": + return False + if str(widget.cget("takefocus")) == "1": + return True + return widget.winfo_class() in _FOCUSABLE_CLASSES + + +def _deepest_focusable(widget: tk.Misc) -> tk.Misc | None: + """Return the last descendant that can take keyboard focus. + + Used to prove the *bottom* of the content is reachable, which is where the + submit button and the dashboard live -- exactly what a centered, clipping + frame used to hide. + """ + found: tk.Misc | None = None + for child in widget.winfo_children(): + if _is_focusable(child): + found = child + deeper = _deepest_focusable(child) + if deeper is not None: + found = deeper + return found + + +def _probe_viewport( + root: tk.Misc, + canvas: tk.Canvas, + inner: tk.Misc, + screen_w: int, + screen_h: int, +) -> Measurement: + """Interrogate a built viewport: does it scroll, and does focus follow? + + Split out of :func:`measure` so each function does one thing -- building the + layout, and interrogating it -- and so neither trips the local-variable cap. + """ + box = canvas.bbox("all") + span = (box[3] - box[1]) if box else 0 + viewport_h = canvas.winfo_height() + + canvas.yview_moveto(0.0) + root.update_idletasks() + canvas.yview_scroll(1, "pages") + root.update_idletasks() + scrolls = canvas.yview()[0] > 0.0 + + # Scroll back to the top, then focus the deepest widget and check it ends up + # on screen. Starting from the top is what makes this a real test: it is the + # state a user arrives in. + canvas.yview_moveto(0.0) + root.update_idletasks() + target = _deepest_focusable(inner) + last_visible = False + if target is not None: + target.focus_set() + root.update() + root.update_idletasks() + top = target.winfo_rooty() - inner.winfo_rooty() + visible_from = canvas.canvasy(0) + last_visible = visible_from <= top <= visible_from + viewport_h + + return Measurement( + screen_w=screen_w, + screen_h=screen_h, + content_span=span, + viewport_h=viewport_h, + scrolls_by_keyboard=scrolls, + last_widget_visible_after_focus=last_visible, + ) + + +def measure( + screen_w: int = 1366, + screen_h: int = 768, + *, + populated: bool = True, +) -> Measurement: + """Build the real gate layout inside a notebook and probe reachability. + + Args: + screen_w: Target screen width in px. + screen_h: Target screen height in px. + populated: Fill the variables with a realistic full day of data. + + Returns: + The measurement, including whether all content is keyboard-reachable. + """ + root = tk.Tk() + try: + root.geometry(f"{screen_w}x{screen_h}+0+0") + _notebook_overhead(root) + notebook = ttk.Notebook(root) + notebook.place(relx=0, rely=0, relwidth=1, relheight=1) + callbacks = GateCallbacks( + on_unit_change=_noop, + on_submit=_noop, + on_close=_noop, + on_fetch_sync=_noop, + ) + widgets = build_layout( + notebook, _make_vars(populated=populated), callbacks, demo_mode=False + ) + notebook.add(widgets.frame, text="Log Meal") + # No window manager under Xvfb, so the toplevel must claim focus before + # any FocusIn fires. Production gatelock does this via focus_force(). + root.focus_force() + root.update() + root.update_idletasks() + + # Reach into the viewport the layout built: the container holds the + # canvas, whose single window item is the content frame. + # + # A layout with NO viewport is the case this check exists to catch, so + # it must degrade to an accurate diagnosis rather than an exception -- + # the same measurement runs against layouts that have not been fixed + # yet, and "StopIteration" tells the reader nothing. Without a viewport + # the content is the container itself, the usable height is the pane, + # and nothing scrolls. + canvas = next( + ( + child + for child in widgets.frame.winfo_children() + if isinstance(child, tk.Canvas) + ), + None, + ) + if canvas is None: + return Measurement( + screen_w=screen_w, + screen_h=screen_h, + content_span=widgets.frame.winfo_reqheight(), + viewport_h=notebook.winfo_height(), + scrolls_by_keyboard=False, + last_widget_visible_after_focus=False, + has_scroll_viewport=False, + ) + inner = canvas.winfo_children()[0] + + return _probe_viewport(root, canvas, inner, screen_w, screen_h) + finally: + root.destroy() diff --git a/diet_guard/tests/_tk_fakes.py b/diet_guard/tests/_tk_fakes.py new file mode 100644 index 0000000..c23717d --- /dev/null +++ b/diet_guard/tests/_tk_fakes.py @@ -0,0 +1,356 @@ +"""Functional fake Tk widgets for the gate's display-free tests. + +Extracted from ``conftest.py`` purely for size: the widget tree the gate builds +now spans several modules plus ``gatelock``, and the fakes grew past this repo's +500-line file cap when the scroll viewport and the radio-button unit selector +were added. + +Stays under ``tests/`` deliberately. It was briefly moved into the package to +satisfy the ``test_*.py`` naming hook, but that lost the ruff ``ARG`` exemption +that ``**/tests/**`` already grants -- and a fake widget's whole job is to +accept arguments it ignores. Weakening ruff for package code to accommodate +test scaffolding is the wrong trade; excluding one clearly-named support file +from a naming convention is the cheaper one. + +The fakes are *functional* where behaviour matters -- selecting a radio button +really sets its variable and fires its command, and the canvas really tracks a +scroll offset -- so a test can drive the gate the way a keyboard user now can, +rather than merely asserting that a widget was constructed. +""" + +from __future__ import annotations + +from types import SimpleNamespace + + +class _FakeTclError(Exception): + """Stand-in for ``tkinter.TclError`` (a real, catchable exception).""" + + +class FakeVar: + """A functional ``StringVar``: stores and returns a string.""" + + def __init__(self, master: object = None, value: str = "") -> None: + self._value = value + + def get(self) -> str: + return self._value + + def set(self, value: str) -> None: + self._value = value + + +class FakeEntry: + """A functional one-line entry (delete clears, insert appends). + + ``configure``/``config`` record their kwargs into ``configured``, so a + test can assert on a read-only/editable state toggle the same way it + would with :class:`FakeWidget`. + """ + + def __init__(self, *args: object, **kwargs: object) -> None: + self._value = "" + self.configured: dict[str, object] = dict(kwargs) + + def get(self) -> str: + return self._value + + def delete(self, first: object, last: object = None) -> None: + self._value = "" + + def insert(self, index: object, text: str) -> None: + self._value += text + + def pack(self, *args: object, **kwargs: object) -> FakeEntry: + return self + + def bind(self, *args: object, **kwargs: object) -> None: + pass + + def configure(self, *args: object, **kwargs: object) -> None: + self.configured.update(kwargs) + + config = configure + + def focus_set(self) -> None: + pass + + def focus_force(self) -> None: + pass + + +class FakeText(FakeEntry): + """A functional multi-line text box (``get`` ignores the index range).""" + + def get(self, start: object = None, end: object = None) -> str: + return self._value + + +class FakeListbox: + """A functional listbox tracking items and the current selection.""" + + def __init__(self, *args: object, **kwargs: object) -> None: + self._items: list[str] = [] + self._sel: tuple[int, ...] = () + + def delete(self, first: object, last: object = None) -> None: + self._items = [] + + def insert(self, index: object, text: str) -> None: + self._items.append(text) + + def curselection(self) -> tuple[int, ...]: + return self._sel + + def selection_set(self, index: int) -> None: + self._sel = (index,) + + def selection_clear(self, first: object, last: object = None) -> None: + self._sel = () + + def pack(self, *args: object, **kwargs: object) -> FakeListbox: + return self + + def bind(self, *args: object, **kwargs: object) -> None: + pass + + +class FakeWidget: + """A generic no-op widget for Frame/Label/Button/OptionMenu. + + ``configure``/``config`` record their kwargs into ``configured`` (rather + than discarding them) so a test can assert on a widget's last-set color + or text, e.g. the calendar's per-cell status coloring. + """ + + def __init__(self, *args: object, **kwargs: object) -> None: + self.configured: dict[str, object] = dict(kwargs) + + def pack(self, *args: object, **kwargs: object) -> FakeWidget: + return self + + def place(self, *args: object, **kwargs: object) -> FakeWidget: + return self + + def grid(self, *args: object, **kwargs: object) -> FakeWidget: + return self + + def configure(self, *args: object, **kwargs: object) -> FakeWidget: + self.configured.update(kwargs) + return self + + config = configure + + def bind(self, *args: object, **kwargs: object) -> None: + pass + + def register(self, func: object) -> object: + """Stand in for Tk's Tcl-command registration: return the callable as-is.""" + return func + + def winfo_children(self) -> list[object]: + """No children: the fakes are not a real widget tree.""" + return [] + + def winfo_toplevel(self) -> FakeWidget: + return self + + def update_idletasks(self) -> None: + pass + + def cget(self, key: str) -> object: + return self.configured.get(key, "") + + # Geometry queries. The scroll viewport asks for these to size itself and + # to decide whether content still fits; zero means "nothing measured yet", + # which is the honest answer for a fake with no layout. + def winfo_reqwidth(self) -> int: + return 0 + + def winfo_reqheight(self) -> int: + return 0 + + def winfo_width(self) -> int: + return 0 + + def winfo_height(self) -> int: + return 0 + + def winfo_rooty(self) -> int: + return 0 + + def winfo_screenwidth(self) -> int: + return 1366 + + def winfo_screenheight(self) -> int: + return 768 + + +class FakeNotebook(FakeWidget): + """A functional ``ttk.Notebook``: tracks added tabs and the selection.""" + + def __init__(self, *args: object, **kwargs: object) -> None: + super().__init__(*args, **kwargs) + self.tabs: list[tuple[object, str]] = [] + self._selected = 0 + self.traversal_enabled = False + + def add(self, child: object, *, text: str = "") -> None: + self.tabs.append((child, text)) + + def enable_traversal(self) -> None: + """Record that Ctrl+Tab / Ctrl+PageDown traversal was requested. + + Tracked rather than ignored so a test can assert it happened: ttk only + installs those toplevel bindings on request, and forgetting the call + leaves the tab-switching keys silently dead. + """ + self.traversal_enabled = True + + def select(self, tab_id: object = None) -> int | None: + if tab_id is None: + return self._selected + if isinstance(tab_id, int): + self._selected = tab_id + else: + for index, (child, _label) in enumerate(self.tabs): + if child is tab_id: + self._selected = index + break + return None + + +class FakeRadiobutton(FakeWidget): + """A functional ``tk.Radiobutton``: selecting sets the var and fires. + + Functional rather than a no-op because this is the gate's grams/items unit + selector, which used to be a keyboard-unreachable ``OptionMenu``. A test + needs to be able to drive it the way a keyboard user now can. + """ + + def __init__(self, *args: object, **kwargs: object) -> None: + super().__init__(*args, **kwargs) + self.value = kwargs.get("value") + self._variable = kwargs.get("variable") + self._command = kwargs.get("command") + + def invoke(self) -> None: + """Select this option, as Space/Return does on a real Radiobutton.""" + if self._variable is not None and hasattr(self._variable, "set"): + self._variable.set(self.value) + if callable(self._command): + self._command() + + select = invoke + + +class FakeScrollbar(FakeWidget): + """A ``tk.Scrollbar`` stand-in that records the thumb position.""" + + def __init__(self, *args: object, **kwargs: object) -> None: + super().__init__(*args, **kwargs) + self.fractions: tuple[str, ...] = () + + def set(self, *fractions: str) -> None: + self.fractions = fractions + + +class FakeCanvas(FakeWidget): + """A functional ``tk.Canvas`` stand-in for ``gatelock.ScrollableSurface``. + + Tracks the scroll offset so a test can assert the viewport actually moved, + which is the whole point of the widget being there: the gate's content can + exceed a 768px screen, and before the viewport existed the overflow was + silently clipped off both edges at once. + """ + + def __init__(self, *args: object, **kwargs: object) -> None: + super().__init__(*args, **kwargs) + self.items: list[object] = [] + self.offset = 0.0 + self._children: list[object] = [] + + def create_window(self, *args: object, **kwargs: object) -> int: + window = kwargs.get("window") + if window is not None: + self.items.append(window) + self._children.append(window) + return len(self.items) + + def itemconfigure(self, *args: object, **kwargs: object) -> None: + pass + + def coords(self, *args: object, **kwargs: object) -> None: + pass + + def bbox(self, *_args: object) -> tuple[int, int, int, int]: + return (0, 0, 0, 0) + + def yview(self) -> tuple[float, float]: + return (self.offset, 1.0) + + def yview_scroll(self, number: int, _what: str) -> None: + self.offset = max(0.0, self.offset + number) + + def yview_moveto(self, fraction: float) -> None: + self.offset = fraction + + def canvasy(self, screen_y: float) -> float: + return screen_y + + def winfo_children(self) -> list[object]: + return list(self._children) + + def winfo_height(self) -> int: + return 0 + + def winfo_toplevel(self) -> FakeWidget: + return self + + def update_idletasks(self) -> None: + pass + + def cget(self, key: str) -> object: + return self.configured.get(key, "") + + +class FakeStyle: + """A no-op stand-in for ``ttk.Style`` -- records calls, applies nothing.""" + + def __init__(self, *args: object, **kwargs: object) -> None: + self.theme: str | None = None + self.configured: dict[str, dict[str, object]] = {} + + def theme_use(self, theme_name: str) -> None: + self.theme = theme_name + + def configure(self, style_name: str, **kwargs: object) -> None: + self.configured.setdefault(style_name, {}).update(kwargs) + + def map(self, style_name: str, **kwargs: object) -> None: + self.configured.setdefault(style_name, {}).update(kwargs) + + +_FAKE_TK = SimpleNamespace( + END="end", + TclError=_FakeTclError, + StringVar=FakeVar, + Frame=FakeWidget, + Label=FakeWidget, + Button=FakeWidget, + OptionMenu=FakeWidget, + Radiobutton=FakeRadiobutton, + Entry=FakeEntry, + Text=FakeText, + Listbox=FakeListbox, + Canvas=FakeCanvas, + Scrollbar=FakeScrollbar, + Misc=FakeWidget, + Event=object, +) + +_FAKE_TTK = SimpleNamespace(Notebook=FakeNotebook, Style=FakeStyle) + +# Every mixin module the gate window is built from imports ``tkinter`` +# independently; all of them must see the fake so ``tk.TclError`` etc. are the +# catchable ``_FakeTclError`` everywhere a test raises it. diff --git a/diet_guard/tests/conftest.py b/diet_guard/tests/conftest.py index d229737..a63e37e 100644 --- a/diet_guard/tests/conftest.py +++ b/diet_guard/tests/conftest.py @@ -20,12 +20,12 @@ are functional in-memory stand-ins, shared by ``test_gatelock.py`` and from __future__ import annotations -from contextlib import ExitStack -from types import SimpleNamespace +from contextlib import ExitStack, contextmanager from typing import TYPE_CHECKING from unittest.mock import MagicMock, patch from gatelock import Output, OutputRect +from gatelock import _scrollable as _gatelock_scrollable import pytest from diet_guard import ( @@ -40,6 +40,44 @@ from diet_guard import ( ) from diet_guard._estimator import Nutrition from diet_guard._gatelock import MealGate +from diet_guard.tests._tk_fakes import ( + _FAKE_TK, + _FAKE_TTK, + FakeCanvas, + FakeEntry, + FakeListbox, + FakeNotebook, + FakeRadiobutton, + FakeScrollbar, + FakeStyle, + FakeText, + FakeVar, + FakeWidget, + _FakeTclError, +) + +# Re-exported: the fake widgets moved into the package so this file stays +# under the 500-line cap, but tests import them from conftest by name. +__all__ = [ + "FAKE_OUTPUTS", + "TWO_OUTPUTS", + "_FAKE_TK", + "_FAKE_TTK", + "FakeCanvas", + "FakeEntry", + "FakeListbox", + "FakeNotebook", + "FakeRadiobutton", + "FakeScrollbar", + "FakeStyle", + "FakeText", + "FakeVar", + "FakeWidget", + "_FakeTclError", + "dual_output", + "fake_tk", + "gate", +] if TYPE_CHECKING: from collections.abc import Iterator @@ -180,192 +218,6 @@ def _hmac_key(tmp_path: Path) -> Iterator[None]: # in-memory widgets without ever opening a window or grabbing the keyboard. -class _FakeTclError(Exception): - """Stand-in for ``tkinter.TclError`` (a real, catchable exception).""" - - -class FakeVar: - """A functional ``StringVar``: stores and returns a string.""" - - def __init__(self, master: object = None, value: str = "") -> None: - self._value = value - - def get(self) -> str: - return self._value - - def set(self, value: str) -> None: - self._value = value - - -class FakeEntry: - """A functional one-line entry (delete clears, insert appends). - - ``configure``/``config`` record their kwargs into ``configured``, so a - test can assert on a read-only/editable state toggle the same way it - would with :class:`FakeWidget`. - """ - - def __init__(self, *args: object, **kwargs: object) -> None: - self._value = "" - self.configured: dict[str, object] = dict(kwargs) - - def get(self) -> str: - return self._value - - def delete(self, first: object, last: object = None) -> None: - self._value = "" - - def insert(self, index: object, text: str) -> None: - self._value += text - - def pack(self, *args: object, **kwargs: object) -> FakeEntry: - return self - - def bind(self, *args: object, **kwargs: object) -> None: - pass - - def configure(self, *args: object, **kwargs: object) -> None: - self.configured.update(kwargs) - - config = configure - - def focus_set(self) -> None: - pass - - def focus_force(self) -> None: - pass - - -class FakeText(FakeEntry): - """A functional multi-line text box (``get`` ignores the index range).""" - - def get(self, start: object = None, end: object = None) -> str: - return self._value - - -class FakeListbox: - """A functional listbox tracking items and the current selection.""" - - def __init__(self, *args: object, **kwargs: object) -> None: - self._items: list[str] = [] - self._sel: tuple[int, ...] = () - - def delete(self, first: object, last: object = None) -> None: - self._items = [] - - def insert(self, index: object, text: str) -> None: - self._items.append(text) - - def curselection(self) -> tuple[int, ...]: - return self._sel - - def selection_set(self, index: int) -> None: - self._sel = (index,) - - def selection_clear(self, first: object, last: object = None) -> None: - self._sel = () - - def pack(self, *args: object, **kwargs: object) -> FakeListbox: - return self - - def bind(self, *args: object, **kwargs: object) -> None: - pass - - -class FakeWidget: - """A generic no-op widget for Frame/Label/Button/OptionMenu. - - ``configure``/``config`` record their kwargs into ``configured`` (rather - than discarding them) so a test can assert on a widget's last-set color - or text, e.g. the calendar's per-cell status coloring. - """ - - def __init__(self, *args: object, **kwargs: object) -> None: - self.configured: dict[str, object] = dict(kwargs) - - def pack(self, *args: object, **kwargs: object) -> FakeWidget: - return self - - def place(self, *args: object, **kwargs: object) -> FakeWidget: - return self - - def grid(self, *args: object, **kwargs: object) -> FakeWidget: - return self - - def configure(self, *args: object, **kwargs: object) -> FakeWidget: - self.configured.update(kwargs) - return self - - config = configure - - def bind(self, *args: object, **kwargs: object) -> None: - pass - - def register(self, func: object) -> object: - """Stand in for Tk's Tcl-command registration: return the callable as-is.""" - return func - - -class FakeNotebook(FakeWidget): - """A functional ``ttk.Notebook``: tracks added tabs and the selection.""" - - def __init__(self, *args: object, **kwargs: object) -> None: - super().__init__(*args, **kwargs) - self.tabs: list[tuple[object, str]] = [] - self._selected = 0 - - def add(self, child: object, *, text: str = "") -> None: - self.tabs.append((child, text)) - - def select(self, tab_id: object = None) -> int | None: - if tab_id is None: - return self._selected - if isinstance(tab_id, int): - self._selected = tab_id - else: - for index, (child, _label) in enumerate(self.tabs): - if child is tab_id: - self._selected = index - break - return None - - -class FakeStyle: - """A no-op stand-in for ``ttk.Style`` -- records calls, applies nothing.""" - - def __init__(self, *args: object, **kwargs: object) -> None: - self.theme: str | None = None - self.configured: dict[str, dict[str, object]] = {} - - def theme_use(self, theme_name: str) -> None: - self.theme = theme_name - - def configure(self, style_name: str, **kwargs: object) -> None: - self.configured.setdefault(style_name, {}).update(kwargs) - - def map(self, style_name: str, **kwargs: object) -> None: - self.configured.setdefault(style_name, {}).update(kwargs) - - -_FAKE_TK = SimpleNamespace( - END="end", - TclError=_FakeTclError, - StringVar=FakeVar, - Frame=FakeWidget, - Label=FakeWidget, - Button=FakeWidget, - OptionMenu=FakeWidget, - Entry=FakeEntry, - Text=FakeText, - Listbox=FakeListbox, - Event=object, -) - -_FAKE_TTK = SimpleNamespace(Notebook=FakeNotebook, Style=FakeStyle) - -# Every mixin module the gate window is built from imports ``tkinter`` -# independently; all of them must see the fake so ``tk.TclError`` etc. are the -# catchable ``_FakeTclError`` everywhere a test raises it. _GATE_TK_MODULES = ( _gatelock, _gatelock_buttons, @@ -375,17 +227,35 @@ _GATE_TK_MODULES = ( _gatelock_nutrition, _gatelock_mealflow, _gatelock_ui, + # The gate's scroll viewport lives in gatelock, not here, and imports + # tkinter independently -- so it needs the fake too, or a real tk.Frame + # ends up parented to a FakeNotebook. + _gatelock_scrollable, ) -@pytest.fixture -def gate() -> Iterator[MealGate]: - """Build a demo gate whose widgets are functional fakes.""" +@contextmanager +def fake_tk() -> Iterator[None]: + """Patch every module that builds gate widgets to use the fakes. + + Exposed so tests that construct a gate outside the :func:`gate` fixture + patch the *same* set. Hand-picking a subset is how a test ends up mixing a + real ``tk.Label`` with a fake parent: the widget tree spans several modules + plus ``gatelock``, and any module left real will try to talk to a fake + master. + """ with ExitStack() as stack: for module in _GATE_TK_MODULES: stack.enter_context(patch.object(module, "tk", _FAKE_TK)) stack.enter_context(patch.object(_gatelock_calendar, "ttk", _FAKE_TTK)) stack.enter_context(patch.object(_gatelock_calendar_ui, "ttk", _FAKE_TTK)) + yield + + +@pytest.fixture +def gate() -> Iterator[MealGate]: + """Build a demo gate whose widgets are functional fakes.""" + with fake_tk(): yield MealGate(demo_mode=True) diff --git a/diet_guard/tests/test_gate_layout_fits.py b/diet_guard/tests/test_gate_layout_fits.py new file mode 100644 index 0000000..9b9c907 --- /dev/null +++ b/diet_guard/tests/test_gate_layout_fits.py @@ -0,0 +1,70 @@ +"""The gate must be fully keyboard-reachable at every supported screen size. + +This is the *gate*, not a report: it fails rather than printing numbers. It ran +red before the fix and green after, which is the only evidence that a check +tests anything at all. + +What it caught, measured under a real 1366x768 X server: the Log Meal tab +required 866px inside a 739px content pane -- and 938px with a day of meals +logged -- while being ``place``-centered, so the overflow was sheared off the +top *and* the bottom simultaneously. That took the "Diet Gate" title and the +slot header (which meal you are being asked to log) off one edge and the calorie +headline plus the whole dashboard off the other, with no scrollbar and nothing +to indicate anything was missing. Inside a hard lock that cannot be left +without logging a meal. + +Two independent causes, both needed fixing: every font size was passed to Tk as +*points* rather than pixels (~30% oversized), and there was no scroll container +anywhere in the package. +""" + +from __future__ import annotations + +import pytest + +from diet_guard.tests._gate_layout_probe import measure + +# The screen sizes tokens.md requires: 1366x768 fully usable (the primary +# machine), 1024x600 degrading gracefully. Both are landscape and SHORT -- +# phone-portrait test sizes exercise neither constraint, which is why the +# overflow survived a test suite that already pinned surface sizes. +_REQUIRED_SIZES = [(1366, 768), (1024, 600)] + + +@pytest.mark.parametrize(("screen_w", "screen_h"), _REQUIRED_SIZES) +@pytest.mark.parametrize("populated", [False, True]) +def test_all_gate_content_is_keyboard_reachable( + screen_w: int, screen_h: int, *, populated: bool +) -> None: + """No part of the gate is unreachable, empty or with a full day logged. + + ``populated`` matters: the dashboard grows one line per logged meal, so a + layout that fits on a fresh boot can still overflow by dinner. The empty + case is not the worst case. + """ + result = measure(screen_w, screen_h, populated=populated) + assert result.reachable, result.describe() + + +@pytest.mark.parametrize(("screen_w", "screen_h"), _REQUIRED_SIZES) +def test_overflow_is_always_scrollable(screen_w: int, screen_h: int) -> None: + """Whenever content exceeds the viewport, the keyboard can scroll it. + + Guards the specific regression: content may legitimately overflow, but it + may never overflow *without* a keyboard route to the rest of it. + """ + result = measure(screen_w, screen_h, populated=True) + if result.needs_scroll: + assert result.scrolls_by_keyboard, result.describe() + assert result.last_widget_visible_after_focus, result.describe() + + +def test_fresh_boot_fits_the_primary_screen() -> None: + """With nothing logged, the gate fits 1366x768 without scrolling. + + Scrolling is a correctness backstop, not the intended daily experience: an + empty form that already needs scrolling on the primary machine means the + layout has drifted and the next addition will be worse. + """ + result = measure(1366, 768, populated=False) + assert not result.needs_scroll, result.describe() diff --git a/diet_guard/tests/test_gatelock.py b/diet_guard/tests/test_gatelock.py index b73887d..79625a3 100644 --- a/diet_guard/tests/test_gatelock.py +++ b/diet_guard/tests/test_gatelock.py @@ -32,7 +32,11 @@ from diet_guard._gatelock_nutrition import _format_preview from diet_guard._gatelock_support import wait_for_display from diet_guard._gatelock_ui import DEFAULT_PER_GRAMS from diet_guard._portions import DEFAULT_ITEM_GRAMS -from diet_guard.tests.conftest import _FAKE_TK, _FakeTclError, _nutrition +from diet_guard.tests.conftest import ( + _FakeTclError, + _nutrition, + fake_tk, +) # -------------------------------------------------------------------------- # Module-level helpers @@ -120,7 +124,10 @@ class TestConstruction: def test_production_builds(self) -> None: """A production gate builds with a hard lock config.""" - with patch.object(_gatelock, "tk", _FAKE_TK): + # Use the shared patch set: the widget tree spans several modules plus + # gatelock's scroll viewport, and leaving any of them real mixes a real + # widget with a fake master. + with fake_tk(): gate = MealGate(demo_mode=False) assert gate.demo_mode is False assert gate._lock._config.mode == "hard" diff --git a/diet_guard/tests/test_gatelock_keyboard.py b/diet_guard/tests/test_gatelock_keyboard.py new file mode 100644 index 0000000..19dd560 --- /dev/null +++ b/diet_guard/tests/test_gatelock_keyboard.py @@ -0,0 +1,299 @@ +"""Tests for the gate's pointer-free operability. + +Every assertion here stands in for something a keyboard-only user could not do +before. The gate is a hard lock -- ``overrideredirect`` + a global grab + VT +switching disabled -- so it cannot be left without submitting the form. A +control that needs a pointer is therefore not an inconvenience but a lockout, +which is why these are correctness tests rather than polish. + +The reachability and height side of the same requirement is covered by +``measure_gate_layout.py``; the real focus-ring walk lives in +``probe_gate_keyboard.py``. +""" + +from __future__ import annotations + +import tkinter as tk +from typing import TYPE_CHECKING, Any + +import pytest + +from diet_guard import _gatelock_buttons, _gatelock_ui +from diet_guard._gatelock_ui import UNIT_GRAMS, UNIT_ITEMS +from diet_guard.tests import _gate_keyboard_probe +from diet_guard.tests.conftest import _FAKE_TK, FakeRadiobutton + +if TYPE_CHECKING: + from diet_guard._gatelock import MealGate + + +class TestButtonReturnKey: + """Enter must activate a button; Tk binds only Space on X11.""" + + def test_return_invokes_the_button(self, monkeypatch: pytest.MonkeyPatch) -> None: + """The handler invokes the button and swallows the event.""" + monkeypatch.setattr(_gatelock_buttons, "tk", _FAKE_TK) + fired: list[str] = [] + bound: dict[str, Any] = {} + + class _Button(FakeRadiobutton): + # Signature mirrors FakeWidget.bind so the override type-checks. + def bind(self, *args: object, **_kwargs: object) -> None: + bound[str(args[0])] = args[1] + + def invoke(self) -> None: + fired.append("hit") + + monkeypatch.setattr(_FAKE_TK, "Button", _Button) + _gatelock_buttons.make_button( + _FAKE_TK.Frame(), + text="Log & Continue", + variant="primary", + command=lambda: None, + ) + + assert bound[""](None) == "break" + assert fired == ["hit"] + + def test_keypad_enter_is_bound_too(self, monkeypatch: pytest.MonkeyPatch) -> None: + """The numeric keypad's Enter is a separate keysym from Return.""" + monkeypatch.setattr(_gatelock_buttons, "tk", _FAKE_TK) + bound: dict[str, Any] = {} + + class _Button(FakeRadiobutton): + # Signature mirrors FakeWidget.bind so the override type-checks. + def bind(self, *args: object, **_kwargs: object) -> None: + bound[str(args[0])] = args[1] + + def invoke(self) -> None: + pass + + monkeypatch.setattr(_FAKE_TK, "Button", _Button) + _gatelock_buttons.make_button( + _FAKE_TK.Frame(), + text="Close", + variant="danger", + command=lambda: None, + ) + + assert "" in bound + + +class TestUnitSelectorIsKeyboardReachable: + """The grams/items selector must not be a ``tk.OptionMenu``. + + ``OptionMenu``'s ``Menubutton`` defaults to ``takefocus=0``, so it never + entered the tab ring -- and a posted Tk menu also steals the lock's grab, + which the recovery tick then kills. Radiobuttons avoid both. + """ + + def test_no_option_menu_is_constructed( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Building the gate never constructs an OptionMenu. + + Asserted behaviourally by making the constructor explode, rather than by + grepping the source -- a source scan matches this module's own + explanatory comments about the widget it replaced. + """ + + def _explode(*_args: object, **_kwargs: object) -> None: + message = "OptionMenu is banned on a lock surface" + raise AssertionError(message) + + monkeypatch.setattr(tk, "OptionMenu", _explode) + root = tk.Tk() + try: + selector_row = tk.Frame(root) + vars_ = _gatelock_ui.make_vars(root) + _gatelock_ui._build_unit_selector(selector_row, vars_, lambda _u: None) + classes = [child.winfo_class() for child in selector_row.winfo_children()] + assert classes == ["Radiobutton", "Radiobutton"] + assert "Menubutton" not in classes + finally: + root.destroy() + + def test_radio_options_are_in_the_focus_ring(self) -> None: + """Both units are tab stops -- the OptionMenu never was.""" + root = tk.Tk() + try: + row = tk.Frame(root) + row.pack() + vars_ = _gatelock_ui.make_vars(root) + _gatelock_ui._build_unit_selector(row, vars_, lambda _u: None) + root.focus_force() + root.update() + root.update_idletasks() + for child in row.winfo_children(): + assert str(child.cget("takefocus")) != "0" + finally: + root.destroy() + + def test_selecting_a_radio_fires_the_unit_callback(self) -> None: + """Activating an option updates the var and notifies the controller.""" + root = tk.Tk() + try: + row = tk.Frame(root) + vars_ = _gatelock_ui.make_vars(root) + seen: list[str] = [] + _gatelock_ui._build_unit_selector(row, vars_, seen.append) + items = [ + child + for child in row.winfo_children() + if str(child.cget("value")) == UNIT_ITEMS + ] + items[0].invoke() + assert vars_.unit.get() == UNIT_ITEMS + assert seen == [UNIT_ITEMS] + finally: + root.destroy() + + def test_both_units_are_offered(self, gate: MealGate) -> None: + """Selecting each radio option drives the unit variable.""" + assert gate._vars.unit.get() == UNIT_GRAMS + gate._vars.unit.set(UNIT_ITEMS) + assert gate._vars.unit.get() == UNIT_ITEMS + + +class TestNotebookTraversal: + """Ctrl+Tab / Ctrl+PageDown tab switching must be enabled explicitly.""" + + def test_traversal_is_enabled(self, gate: MealGate) -> None: + """``enable_traversal()`` is called, or the tab keys are dead. + + ttk installs those toplevel bindings only on request, so omitting the + call leaves Ctrl+Tab, Ctrl+PageUp/Down and Alt+mnemonic doing nothing + while looking perfectly normal in the code. + """ + assert gate._notebook.traversal_enabled is True + + +class TestFocusRingIsVisible: + """The focus ring must be the accent, not Tk's black default.""" + + def test_focus_kwargs_sets_the_focused_ring(self) -> None: + """``highlightcolor`` (focused) is the accent and thickness is non-zero. + + Setting only ``highlightbackground`` -- the *unfocused* ring -- is the + bug this replaced: the widget outlined while unfocused and went black + against ``bg`` the moment it took focus. + """ + kwargs = _gatelock_ui._COLORS.focus_kwargs() + assert kwargs["highlightcolor"] == _gatelock_ui._COLORS.accent + assert kwargs["highlightcolor"] != "#000000" + assert int(kwargs["highlightthickness"]) > 0 + + def test_prose_wrap_respects_the_line_length_cap(self) -> None: + """Wrap width is the 640px cap, not the old 900px literal.""" + assert _gatelock_ui._WRAP_PX == 640 + + +class TestTypeScaleIsPixels: + """Tk font sizes must be negative, i.e. pixels rather than points.""" + + @pytest.mark.parametrize( + "size", + [ + _gatelock_ui.DISPLAY, + _gatelock_ui.SUBTITLE, + _gatelock_ui.BODY, + _gatelock_ui.LABEL, + _gatelock_ui.CAPTION, + ], + ) + def test_sizes_are_negative(self, size: int) -> None: + """A positive size means points and renders ~30% oversized. + + Measured: body at 16 points has a 26px linespace where 16 pixels gives + 20px. That inflation alone pushed this layout off a 768px screen. + """ + assert size < 0 + + def test_scale_matches_the_design_system_magnitudes(self) -> None: + """The magnitudes are still tokens.md's 32/24/20/16/14/12 scale.""" + assert abs(_gatelock_ui.DISPLAY) == 32 + assert abs(_gatelock_ui.TITLE) == 24 + assert abs(_gatelock_ui.SUBTITLE) == 20 + assert abs(_gatelock_ui.BODY) == 16 + assert abs(_gatelock_ui.LABEL) == 14 + assert abs(_gatelock_ui.CAPTION) == 12 + + +class TestRealFocusRing: + """Walk the ring Tab actually follows, against a real Tk. + + Reading the code cannot answer this: Tk decides via ``::tk::FocusOK``, which + also rejects any widget whose *class* has no key bindings. That is why a + Canvas viewport was pointer-only and a Menubutton was skipped entirely -- + neither looks unusual in source. + """ + + def test_unit_selector_is_in_the_ring(self) -> None: + """Both grams/items radio options are tab stops. + + The ``OptionMenu`` they replaced was absent from the ring entirely, so + the unit -- which rescales the whole entry -- could only be changed with + a pointer, inside a lock requiring a logged meal to exit. + """ + report = _gate_keyboard_probe.probe() + assert report.classes.count("Radiobutton") == 2, report.describe() + + def test_every_focusable_class_has_a_visible_ring(self) -> None: + """No widget in the ring keeps Tk's black default highlight. + + Tk ships ``highlightcolor="#000000"`` on a ``#211D1B`` background, so + the default is a ring that cannot be seen. + """ + report = _gate_keyboard_probe.probe() + invisible = { + name: color + for name, color in report.focus_rings_visible.items() + if color.lower() in {"", "#000000", "black"} + } + assert not invisible, f"invisible focus rings: {invisible}" + + def test_scroll_viewport_is_a_focus_stop(self) -> None: + """The Canvas viewport is reachable, so it can be scrolled by keyboard. + + A bare ``tk.Canvas`` has no class key bindings and is therefore rejected + by ``FocusOK``; it only appears here because it opts in explicitly. + """ + report = _gate_keyboard_probe.probe() + assert report.has("Canvas"), report.describe() + + def test_text_escapes_and_buttons_take_return(self) -> None: + """The two Tk defaults that make a form unusable are both overridden.""" + report = _gate_keyboard_probe.probe() + assert report.text_escapes_tab, report.describe() + assert report.buttons_take_return, report.describe() + + +class TestRealTkKeyboardBehaviour: + """End-to-end checks against a real Tk, not the fakes. + + The fakes cannot prove anything about Tk's own class bindings, and those + bindings are the whole problem: Tab-traps and missing Return bindings are + Tk defaults, not application code. + """ + + def test_text_tab_escape_against_real_tk(self) -> None: + """A real Text widget releases focus on Tab.""" + root = tk.Tk() + try: + first = tk.Text(root) + first.pack() + second = tk.Entry(root) + second.pack() + _gatelock_ui._escape_text_tab_trap(first) + root.focus_force() + root.update() + first.focus_set() + root.update() + first.event_generate("") + root.update() + root.update_idletasks() + assert root.focus_get() is not first + # And no literal tab was inserted. + assert "\t" not in first.get("1.0", "end") + finally: + root.destroy() diff --git a/pyproject.toml b/pyproject.toml index b56ea72..8c672b2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ version = "1.0.0" description = "Tkinter/systemd log-to-unlock meal gate with calorie/macro budget tracking" requires-python = ">=3.10" dependencies = [ - "gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.2.1#subdirectory=gatelock", + "gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.3.0#subdirectory=gatelock", "crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.1.0#subdirectory=crdt-sync", "requests>=2.31.0", ] diff --git a/requirements.txt b/requirements.txt index 86eb35e..0ca5e59 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,7 +4,7 @@ bandit>=1.7.0 codespell>=2.2.0 coverage>=7.4.0 crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.1.0#subdirectory=crdt-sync -gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.2.1#subdirectory=gatelock +gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.3.0#subdirectory=gatelock mcp>=1.9 mypy>=1.8.0 pre-commit>=3.6.0