mirror of
https://github.com/kuhyx/wake-alarm.git
synced 2026-11-29 21:33:58 +01:00
Compare commits
3 Commits
ad2e725d52
...
f878d48f11
| Author | SHA1 | Date | |
|---|---|---|---|
| f878d48f11 | |||
| fea60814c2 | |||
| 1e465e0d2c |
@ -96,7 +96,7 @@ repos:
|
|||||||
additional_dependencies:
|
additional_dependencies:
|
||||||
- pytest
|
- pytest
|
||||||
- python-kasa
|
- python-kasa
|
||||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.2.0#subdirectory=gatelock
|
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.4.0#subdirectory=gatelock
|
||||||
# Test suites intentionally use patterns (protected-access, magic-value
|
# Test suites intentionally use patterns (protected-access, magic-value
|
||||||
# comparisons) that don't belong in the source-code 10/10 gate.
|
# comparisons) that don't belong in the source-code 10/10 gate.
|
||||||
exclude: ^(\.venv/)|(^|/)(tests/|conftest\.py)
|
exclude: ^(\.venv/)|(^|/)(tests/|conftest\.py)
|
||||||
@ -139,6 +139,13 @@ repos:
|
|||||||
entry: bash -c 'printf "%s\0" "$@" | xargs -0 -n 40 shellcheck --severity=warning' --
|
entry: bash -c 'printf "%s\0" "$@" | xargs -0 -n 40 shellcheck --severity=warning' --
|
||||||
language: system
|
language: system
|
||||||
types: [shell]
|
types: [shell]
|
||||||
|
- id: screens-fit
|
||||||
|
name: Every lock screen fits 1366x768 (no scrolling required)
|
||||||
|
entry: python3 -m scripts.verify_screen_fits
|
||||||
|
language: system
|
||||||
|
files: '^wake_alarm/.*\.py$'
|
||||||
|
pass_filenames: false
|
||||||
|
require_serial: true
|
||||||
- id: max-file-length
|
- id: max-file-length
|
||||||
name: Max file length (500 lines)
|
name: Max file length (500 lines)
|
||||||
entry: python3 scripts/check_file_length.py
|
entry: python3 scripts/check_file_length.py
|
||||||
|
|||||||
@ -85,19 +85,14 @@ class _HomeScreenState extends State<HomeScreen> {
|
|||||||
'android.intent.extra.alarm.MESSAGE': 'Wake Alarm',
|
'android.intent.extra.alarm.MESSAGE': 'Wake Alarm',
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
await intent.launch().timeout(
|
await intent.launch().timeout(const Duration(seconds: 3), onTimeout: () {});
|
||||||
const Duration(seconds: 3),
|
|
||||||
onTimeout: () {},
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _syncAndSet() async {
|
Future<void> _syncAndSet() async {
|
||||||
final settings = await SyncSettings.load();
|
final settings = await SyncSettings.load();
|
||||||
final service = _service;
|
final service = _service;
|
||||||
if (!settings.isConfigured || service == null) {
|
if (!settings.isConfigured || service == null) {
|
||||||
setState(
|
setState(() => _status = 'Configure GitHub in Settings first.');
|
||||||
() => _status = 'Configure GitHub in Settings first.',
|
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -108,13 +103,9 @@ class _HomeScreenState extends State<HomeScreen> {
|
|||||||
try {
|
try {
|
||||||
await service.setLocal(_hour, _minute);
|
await service.setLocal(_hour, _minute);
|
||||||
await service.push(settings.token);
|
await service.push(settings.token);
|
||||||
setState(
|
setState(() => _status = 'Synced ✓ — opening Clock app…');
|
||||||
() => _status = 'Synced ✓ — opening Clock app…',
|
|
||||||
);
|
|
||||||
await _setPhoneAlarm();
|
await _setPhoneAlarm();
|
||||||
setState(
|
setState(() => _status = 'Done! Confirm the alarm in the Clock app.');
|
||||||
() => _status = 'Done! Confirm the alarm in the Clock app.',
|
|
||||||
);
|
|
||||||
} on Exception catch (e) {
|
} on Exception catch (e) {
|
||||||
setState(() => _status = 'Error: $e');
|
setState(() => _status = 'Error: $e');
|
||||||
} finally {
|
} finally {
|
||||||
@ -140,85 +131,95 @@ class _HomeScreenState extends State<HomeScreen> {
|
|||||||
onPressed: () async {
|
onPressed: () async {
|
||||||
await Navigator.push<void>(
|
await Navigator.push<void>(
|
||||||
context,
|
context,
|
||||||
MaterialPageRoute<void>(
|
MaterialPageRoute<void>(builder: (_) => const SettingsScreen()),
|
||||||
builder: (_) => const SettingsScreen(),
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
await _loadSavedTime();
|
await _loadSavedTime();
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
body: Center(
|
// SafeArea + scroll. This was a bare Center/Padding/Column, which
|
||||||
child: Padding(
|
// cannot scroll, so the content simply overflowed with the black-and-
|
||||||
padding: const EdgeInsets.all(32),
|
// yellow stripe pattern painted over the primary control. Two ways that
|
||||||
child: Column(
|
// happened: phone landscape leaves only ~360px of body height for ~405px
|
||||||
mainAxisSize: MainAxisSize.min,
|
// of content, and the status line renders an unbounded raw
|
||||||
children: [
|
// `'Error: \$e'` with no maxLines, which overflows even in portrait.
|
||||||
const Text('Alarm time', style: TextStyle(fontSize: 16)),
|
body: SafeArea(
|
||||||
const SizedBox(height: 16),
|
child: Center(
|
||||||
GestureDetector(
|
child: SingleChildScrollView(
|
||||||
onTap: _pickTime,
|
padding: const EdgeInsets.all(32),
|
||||||
child: Text(
|
child: Column(
|
||||||
_fmt(_hour, _minute),
|
mainAxisSize: MainAxisSize.min,
|
||||||
style: Theme.of(context)
|
children: [
|
||||||
.textTheme
|
const Text('Alarm time', style: TextStyle(fontSize: 16)),
|
||||||
.displayLarge
|
|
||||||
?.copyWith(fontWeight: FontWeight.bold),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
TextButton(
|
|
||||||
onPressed: _pickTime,
|
|
||||||
child: const Text('Tap to change'),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 32),
|
|
||||||
SizedBox(
|
|
||||||
width: double.infinity,
|
|
||||||
child: ElevatedButton.icon(
|
|
||||||
onPressed: _busy ? null : _syncAndSet,
|
|
||||||
icon: _busy
|
|
||||||
? const SizedBox(
|
|
||||||
width: 18,
|
|
||||||
height: 18,
|
|
||||||
child: CircularProgressIndicator(
|
|
||||||
strokeWidth: 2,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
: const Icon(Icons.alarm_add),
|
|
||||||
label: const Text('Set Alarm & Sync to PC'),
|
|
||||||
style: ElevatedButton.styleFrom(
|
|
||||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
|
||||||
textStyle: const TextStyle(fontSize: 18),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 24),
|
|
||||||
if (_status.isNotEmpty)
|
|
||||||
Text(
|
|
||||||
_status,
|
|
||||||
textAlign: TextAlign.center,
|
|
||||||
style: TextStyle(
|
|
||||||
color: _status.contains('Error')
|
|
||||||
? Theme.of(context).colorScheme.error
|
|
||||||
: Theme.of(
|
|
||||||
context,
|
|
||||||
).extension<AppStatusColors>()!.success,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (!_configured) ...[
|
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Text(
|
GestureDetector(
|
||||||
'Open Settings (gear icon) to connect GitHub.',
|
onTap: _pickTime,
|
||||||
textAlign: TextAlign.center,
|
child: Text(
|
||||||
style: TextStyle(
|
_fmt(_hour, _minute),
|
||||||
color: Theme.of(
|
style: Theme.of(context).textTheme.displayLarge?.copyWith(
|
||||||
context,
|
fontWeight: FontWeight.bold,
|
||||||
).extension<AppStatusColors>()!.warning,
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
TextButton(
|
||||||
|
onPressed: _pickTime,
|
||||||
|
child: const Text('Tap to change'),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 32),
|
||||||
|
SizedBox(
|
||||||
|
width: double.infinity,
|
||||||
|
child: ElevatedButton.icon(
|
||||||
|
onPressed: _busy ? null : _syncAndSet,
|
||||||
|
icon: _busy
|
||||||
|
? const SizedBox(
|
||||||
|
width: 18,
|
||||||
|
height: 18,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
)
|
||||||
|
: const Icon(Icons.alarm_add),
|
||||||
|
label: const Text('Set Alarm & Sync to PC'),
|
||||||
|
style: ElevatedButton.styleFrom(
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||||
|
textStyle: const TextStyle(fontSize: 18),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 24),
|
||||||
|
if (_status.isNotEmpty)
|
||||||
|
Text(
|
||||||
|
_status,
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
// Bounded: _status can be a raw `'Error: $e'`, i.e. an
|
||||||
|
// arbitrarily long exception toString(). Unbounded, that
|
||||||
|
// alone added 100-150px and pushed this column past the
|
||||||
|
// viewport even in portrait. The scroll view above makes
|
||||||
|
// the overflow recoverable; this keeps it from happening.
|
||||||
|
maxLines: 4,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
color: _status.contains('Error')
|
||||||
|
? Theme.of(context).colorScheme.error
|
||||||
|
: Theme.of(
|
||||||
|
context,
|
||||||
|
).extension<AppStatusColors>()!.success,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (!_configured) ...[
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
Text(
|
||||||
|
'Open Settings (gear icon) to connect GitHub.',
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: TextStyle(
|
||||||
|
color: Theme.of(
|
||||||
|
context,
|
||||||
|
).extension<AppStatusColors>()!.warning,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
],
|
],
|
||||||
],
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
@ -37,9 +37,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _connectGitHub() async {
|
Future<void> _connectGitHub() async {
|
||||||
final auth = GitHubDeviceAuth(
|
final auth = GitHubDeviceAuth(clientId: SyncSettings.defaultClientId);
|
||||||
clientId: SyncSettings.defaultClientId,
|
|
||||||
);
|
|
||||||
try {
|
try {
|
||||||
final device = await auth.requestDeviceCode();
|
final device = await auth.requestDeviceCode();
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
@ -90,63 +88,67 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
final isConnected = _settings.isConfigured;
|
final isConnected = _settings.isConfigured;
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(title: const Text('Settings')),
|
appBar: AppBar(title: const Text('Settings')),
|
||||||
body: Padding(
|
// Scrollable: this screen carries a five-line explanatory paragraph and
|
||||||
padding: const EdgeInsets.all(16),
|
// an unbounded `'Error: \$e'`, inside a Column that could not scroll.
|
||||||
child: Column(
|
body: SafeArea(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
child: SingleChildScrollView(
|
||||||
children: [
|
padding: const EdgeInsets.all(16),
|
||||||
_StatusCard(connected: isConnected),
|
child: Column(
|
||||||
const SizedBox(height: 16),
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
if (!isConnected)
|
children: [
|
||||||
ElevatedButton.icon(
|
_StatusCard(connected: isConnected),
|
||||||
onPressed: _busy ? null : _connectGitHub,
|
const SizedBox(height: 16),
|
||||||
icon: _busy
|
if (!isConnected)
|
||||||
? const SizedBox(
|
ElevatedButton.icon(
|
||||||
width: 18,
|
onPressed: _busy ? null : _connectGitHub,
|
||||||
height: 18,
|
icon: _busy
|
||||||
child: CircularProgressIndicator(strokeWidth: 2),
|
? const SizedBox(
|
||||||
)
|
width: 18,
|
||||||
: const Icon(Icons.link),
|
height: 18,
|
||||||
label: const Text('Connect GitHub'),
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
style: ElevatedButton.styleFrom(
|
)
|
||||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
: const Icon(Icons.link),
|
||||||
textStyle: const TextStyle(fontSize: 16),
|
label: const Text('Connect GitHub'),
|
||||||
|
style: ElevatedButton.styleFrom(
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||||
|
textStyle: const TextStyle(fontSize: 16),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
OutlinedButton.icon(
|
||||||
|
onPressed: _busy ? null : _disconnect,
|
||||||
|
icon: const Icon(Icons.link_off),
|
||||||
|
label: const Text('Disconnect'),
|
||||||
),
|
),
|
||||||
)
|
const SizedBox(height: 16),
|
||||||
else
|
if (_status.isNotEmpty)
|
||||||
OutlinedButton.icon(
|
Text(
|
||||||
onPressed: _busy ? null : _disconnect,
|
_status,
|
||||||
icon: const Icon(Icons.link_off),
|
style: TextStyle(
|
||||||
label: const Text('Disconnect'),
|
color: _status.contains('Error')
|
||||||
),
|
? Theme.of(context).colorScheme.error
|
||||||
const SizedBox(height: 16),
|
: Theme.of(
|
||||||
if (_status.isNotEmpty)
|
context,
|
||||||
|
).extension<AppStatusColors>()!.success,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const Divider(height: 32),
|
||||||
Text(
|
Text(
|
||||||
_status,
|
'PC config — create this file:\n'
|
||||||
|
'~/.config/wake_alarm/sync.json\n\n'
|
||||||
|
'{ "token": "<same token>" }\n\n'
|
||||||
|
'The token needs "repo" scope so the PC can read '
|
||||||
|
'kuhyx/syncs at shutdown.',
|
||||||
|
// Was 12px/Colors.grey — below the 16px reading floor (rule
|
||||||
|
// 20) and off-palette (rule 4); this is real setup
|
||||||
|
// instructions, not decorative chrome.
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
color: _status.contains('Error')
|
fontSize: 16,
|
||||||
? Theme.of(context).colorScheme.error
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||||
: Theme.of(
|
|
||||||
context,
|
|
||||||
).extension<AppStatusColors>()!.success,
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const Divider(height: 32),
|
],
|
||||||
Text(
|
),
|
||||||
'PC config — create this file:\n'
|
|
||||||
'~/.config/wake_alarm/sync.json\n\n'
|
|
||||||
'{ "token": "<same token>" }\n\n'
|
|
||||||
'The token needs "repo" scope so the PC can read '
|
|
||||||
'kuhyx/syncs at shutdown.',
|
|
||||||
// Was 12px/Colors.grey — below the 16px reading floor (rule
|
|
||||||
// 20) and off-palette (rule 4); this is real setup
|
|
||||||
// instructions, not decorative chrome.
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 16,
|
|
||||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@ -170,14 +172,13 @@ class _StatusCard extends StatelessWidget {
|
|||||||
Icon(
|
Icon(
|
||||||
connected ? Icons.check_circle : Icons.cancel,
|
connected ? Icons.check_circle : Icons.cancel,
|
||||||
// Dimmed relative to the adjacent label text (rule 28).
|
// Dimmed relative to the adjacent label text (rule 28).
|
||||||
color: (connected ? success : colorScheme.error)
|
color: (connected ? success : colorScheme.error).withValues(
|
||||||
.withValues(alpha: 0.8),
|
alpha: 0.8,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Text(
|
child: Text(connected ? 'Connected to GitHub' : 'Not connected'),
|
||||||
connected ? 'Connected to GitHub' : 'Not connected',
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@ -216,9 +217,7 @@ class _DeviceCodeDialogState extends State<_DeviceCodeDialog> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _openPage() async {
|
Future<void> _openPage() async {
|
||||||
await Clipboard.setData(
|
await Clipboard.setData(ClipboardData(text: widget.device.userCode));
|
||||||
ClipboardData(text: widget.device.userCode),
|
|
||||||
);
|
|
||||||
await launchUrl(
|
await launchUrl(
|
||||||
Uri.parse(widget.device.verificationUri),
|
Uri.parse(widget.device.verificationUri),
|
||||||
mode: LaunchMode.externalApplication,
|
mode: LaunchMode.externalApplication,
|
||||||
@ -249,9 +248,7 @@ class _DeviceCodeDialogState extends State<_DeviceCodeDialog> {
|
|||||||
child: CircularProgressIndicator(strokeWidth: 2),
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
),
|
),
|
||||||
SizedBox(width: 12),
|
SizedBox(width: 12),
|
||||||
Expanded(
|
Expanded(child: Text('Waiting for authorization…')),
|
||||||
child: Text('Waiting for authorization…'),
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
else
|
else
|
||||||
|
|||||||
@ -8,7 +8,7 @@ version = "1.0.0"
|
|||||||
description = "Phone-driven wake alarm with fan ramp and smart-plug control"
|
description = "Phone-driven wake alarm with fan ramp and smart-plug control"
|
||||||
requires-python = ">=3.10"
|
requires-python = ">=3.10"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.2.1#subdirectory=gatelock",
|
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.4.0#subdirectory=gatelock",
|
||||||
"python-kasa>=0.7",
|
"python-kasa>=0.7",
|
||||||
]
|
]
|
||||||
|
|
||||||
@ -95,6 +95,12 @@ color_output = true
|
|||||||
exclude = [".venv/"]
|
exclude = [".venv/"]
|
||||||
|
|
||||||
[tool.pylint.main]
|
[tool.pylint.main]
|
||||||
|
# The repo root on the path, so a file outside the package (scripts/) can be
|
||||||
|
# linted on its own. pylint otherwise infers the path from the files it is
|
||||||
|
# given, so a script resolved its package imports only when a package file
|
||||||
|
# happened to be in the same batch -- passing or failing by what else was
|
||||||
|
# staged.
|
||||||
|
init-hook = "import sys; sys.path.insert(0, '.')"
|
||||||
analyse-fallback-blocks = true
|
analyse-fallback-blocks = true
|
||||||
persistent = true
|
persistent = true
|
||||||
jobs = 0
|
jobs = 0
|
||||||
|
|||||||
@ -5,7 +5,7 @@
|
|||||||
bandit>=1.7.0
|
bandit>=1.7.0
|
||||||
codespell>=2.2.0
|
codespell>=2.2.0
|
||||||
coverage>=7.4.0
|
coverage>=7.4.0
|
||||||
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.2.1#subdirectory=gatelock
|
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.4.0#subdirectory=gatelock
|
||||||
mypy>=1.8.0
|
mypy>=1.8.0
|
||||||
pre-commit>=3.6.0
|
pre-commit>=3.6.0
|
||||||
pylint>=3.0.0
|
pylint>=3.0.0
|
||||||
|
|||||||
177
scripts/verify_screen_fits.py
Executable file
177
scripts/verify_screen_fits.py
Executable file
@ -0,0 +1,177 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Assert the alarm's screens fit a 1366x768 display.
|
||||||
|
|
||||||
|
The alarm ``place``s a centred frame, and a ``place``d frame takes its
|
||||||
|
*requested* size: when it is taller than the screen the parent shears equal
|
||||||
|
amounts off the top **and** the bottom -- which here means losing "WAKE UP!"
|
||||||
|
and the answer entry at once, on a screen whose entire purpose is to be
|
||||||
|
answered before it will stop. There is no scrollbar and nothing to indicate
|
||||||
|
anything is missing, so "it fits" is the only thing keeping it usable.
|
||||||
|
|
||||||
|
Runs the real builders against a real (throwaway) X display, because widget
|
||||||
|
heights come from the font engine and nothing short of rendering can answer
|
||||||
|
this honestly:
|
||||||
|
|
||||||
|
cd ~/wake-alarm && python3 -m scripts.verify_screen_fits
|
||||||
|
|
||||||
|
Run as a *module*, not a path: ``-m`` puts the repo root on
|
||||||
|
``sys.path`` so ``wake_alarm`` resolves from the checkout. Running it as a
|
||||||
|
path only works where the package happens to be pip-installed, which is
|
||||||
|
why it passed locally and died in CI.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tkinter as tk
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from gatelock import LockConfig, measure_fit, report_fit
|
||||||
|
|
||||||
|
from wake_alarm._alarm_view import _build_alarm_view
|
||||||
|
from wake_alarm._challenges import (
|
||||||
|
_make_flash_challenge,
|
||||||
|
_make_math_challenge,
|
||||||
|
_make_reverse_challenge,
|
||||||
|
_make_sequence_challenge,
|
||||||
|
_make_sort_challenge,
|
||||||
|
)
|
||||||
|
from wake_alarm._escape_flow import EscapeCallbacks, EscapeDialog, build_tracker
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Callable
|
||||||
|
|
||||||
|
from gatelock import FitResult, ScrollableSurface
|
||||||
|
|
||||||
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
INNER_ENV = "_SCREEN_FITS_CHECK_INNER"
|
||||||
|
|
||||||
|
# The panel this app has to fit: the machine it runs on.
|
||||||
|
WIDTH = 1366
|
||||||
|
HEIGHT = 768
|
||||||
|
|
||||||
|
|
||||||
|
def reexec_under_xvfb() -> int:
|
||||||
|
"""Re-run this script on a throwaway X display, returning its exit code."""
|
||||||
|
xvfb_run = shutil.which("xvfb-run")
|
||||||
|
if xvfb_run is None:
|
||||||
|
_logger.error(
|
||||||
|
"xvfb-run not found. Install it with: sudo pacman -S --needed "
|
||||||
|
"xorg-server-xvfb"
|
||||||
|
)
|
||||||
|
return 1
|
||||||
|
env = dict(os.environ, **{INNER_ENV: "1"})
|
||||||
|
return subprocess.run(
|
||||||
|
[
|
||||||
|
xvfb_run,
|
||||||
|
"-a",
|
||||||
|
# Bigger than the size under test, so the surface is sized by the
|
||||||
|
# geometry the harness sets rather than clamped by the display.
|
||||||
|
"-s",
|
||||||
|
"-screen 0 1600x1200x24",
|
||||||
|
sys.executable,
|
||||||
|
"-m",
|
||||||
|
"scripts.verify_screen_fits",
|
||||||
|
],
|
||||||
|
check=False,
|
||||||
|
cwd=Path(__file__).resolve().parent.parent,
|
||||||
|
env=env,
|
||||||
|
).returncode
|
||||||
|
|
||||||
|
|
||||||
|
def _placed_child(parent: tk.Misc) -> tk.Misc:
|
||||||
|
"""Return the ``place``d descendant that carries the screen's height.
|
||||||
|
|
||||||
|
``place`` does not propagate a child's size to its parent, so measuring
|
||||||
|
the parent would report an empty screen. Falls back to the parent itself
|
||||||
|
when nothing is placed, which measures correctly for packed layouts.
|
||||||
|
"""
|
||||||
|
for child in parent.winfo_children():
|
||||||
|
if child.winfo_manager() == "place":
|
||||||
|
return child
|
||||||
|
found = _placed_child(child)
|
||||||
|
if found is not child:
|
||||||
|
return found
|
||||||
|
return parent
|
||||||
|
|
||||||
|
|
||||||
|
# Every challenge kind, not a random one: the flash kind renders its code at
|
||||||
|
# 2.25x the display token where the others use 1.5x, and the sequence kind's
|
||||||
|
# display string is the longest. A hook that picked one at random would pass
|
||||||
|
# or fail by dice roll -- which is worse than no hook.
|
||||||
|
_CHALLENGE_KINDS = (
|
||||||
|
("math", _make_math_challenge),
|
||||||
|
("flash", _make_flash_challenge),
|
||||||
|
("sort", _make_sort_challenge),
|
||||||
|
("sequence", _make_sequence_challenge),
|
||||||
|
("reverse", _make_reverse_challenge),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _build_alarm(surface: ScrollableSurface, make: Callable[[], object]) -> tk.Misc:
|
||||||
|
"""Paint one dismiss challenge and return the frame to measure."""
|
||||||
|
_build_alarm_view(
|
||||||
|
surface.content,
|
||||||
|
make(),
|
||||||
|
LockConfig(),
|
||||||
|
on_submit=lambda _event: None,
|
||||||
|
entry_var=tk.StringVar(master=surface.content),
|
||||||
|
)
|
||||||
|
return _placed_child(surface.content)
|
||||||
|
|
||||||
|
|
||||||
|
def _build_escape(surface: ScrollableSurface) -> tk.Misc:
|
||||||
|
"""Paint the escape-hatch form and return the frame to measure."""
|
||||||
|
dialog = EscapeDialog(
|
||||||
|
surface.content,
|
||||||
|
LockConfig(),
|
||||||
|
build_tracker(),
|
||||||
|
EscapeCallbacks(on_granted=lambda: None, on_cancel=lambda: None),
|
||||||
|
)
|
||||||
|
dialog.frame.pack()
|
||||||
|
return dialog.frame
|
||||||
|
|
||||||
|
|
||||||
|
def measure_all() -> list[FitResult]:
|
||||||
|
"""Measure every screen at the supported size."""
|
||||||
|
results = [
|
||||||
|
measure_fit(
|
||||||
|
f"dismiss-challenge:{kind}",
|
||||||
|
lambda surface, make=make: _build_alarm(surface, make),
|
||||||
|
width=WIDTH,
|
||||||
|
height=HEIGHT,
|
||||||
|
)
|
||||||
|
for kind, make in _CHALLENGE_KINDS
|
||||||
|
]
|
||||||
|
results.append(
|
||||||
|
measure_fit("escape-hatch", _build_escape, width=WIDTH, height=HEIGHT)
|
||||||
|
)
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
"""Measure every screen and fail if any of them overflows."""
|
||||||
|
logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stdout)
|
||||||
|
if os.environ.get(INNER_ENV) != "1":
|
||||||
|
return reexec_under_xvfb()
|
||||||
|
|
||||||
|
_logger.info("Measuring every alarm screen against a %dx%d panel:", WIDTH, HEIGHT)
|
||||||
|
if report_fit(measure_all()):
|
||||||
|
_logger.info("\nOK: every screen fits.")
|
||||||
|
return 0
|
||||||
|
_logger.error(
|
||||||
|
"\nAt least one screen is taller than the display. A place-centred "
|
||||||
|
"surface clips at BOTH edges when that happens, so the overflow is "
|
||||||
|
"not merely hidden -- it is unrecoverable."
|
||||||
|
)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@ -290,10 +290,10 @@ class WakeAlarm:
|
|||||||
tk.Label(
|
tk.Label(
|
||||||
container,
|
container,
|
||||||
text=msg,
|
text=msg,
|
||||||
font=("Arial", 36, "bold"),
|
font=cfg.font("display", bold=True),
|
||||||
fg=color,
|
fg=color,
|
||||||
bg=cfg.bg,
|
bg=cfg.bg,
|
||||||
).pack(pady=30)
|
).pack(pady=cfg.space("lg"))
|
||||||
|
|
||||||
self.root.after(3000, self._lock.close)
|
self.root.after(3000, self._lock.close)
|
||||||
|
|
||||||
|
|||||||
@ -7,6 +7,8 @@ from dataclasses import dataclass
|
|||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from gatelock import bind_activate
|
||||||
|
|
||||||
from wake_alarm._constants import DISMISS_ROUNDS_REQUIRED
|
from wake_alarm._constants import DISMISS_ROUNDS_REQUIRED
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
@ -195,71 +197,78 @@ def _build_challenge(
|
|||||||
title_label = tk.Label(
|
title_label = tk.Label(
|
||||||
parent,
|
parent,
|
||||||
text="WAKE UP!",
|
text="WAKE UP!",
|
||||||
font=("Arial", 48, "bold"),
|
font=config.font("display", bold=True, scale=1.5),
|
||||||
fg=config.danger,
|
fg=config.danger,
|
||||||
bg=config.bg,
|
bg=config.bg,
|
||||||
)
|
)
|
||||||
title_label.pack(pady=20)
|
title_label.pack(pady=config.space("md"))
|
||||||
|
|
||||||
round_label = tk.Label(
|
round_label = tk.Label(
|
||||||
parent,
|
parent,
|
||||||
text=f"Round 1 / {DISMISS_ROUNDS_REQUIRED}",
|
text=f"Round 1 / {DISMISS_ROUNDS_REQUIRED}",
|
||||||
font=("Arial", 24, "bold"),
|
font=config.font("title", bold=True),
|
||||||
fg=config.warning,
|
fg=config.warning,
|
||||||
bg=config.bg,
|
bg=config.bg,
|
||||||
)
|
)
|
||||||
round_label.pack(pady=5)
|
round_label.pack(pady=config.space("xs"))
|
||||||
|
|
||||||
info_label = tk.Label(
|
info_label = tk.Label(
|
||||||
parent,
|
parent,
|
||||||
text=challenge.hint,
|
text=challenge.hint,
|
||||||
font=("Arial", 18),
|
font=config.font("body"),
|
||||||
fg=config.fg,
|
fg=config.fg,
|
||||||
bg=config.bg,
|
bg=config.bg,
|
||||||
)
|
)
|
||||||
info_label.pack(pady=10)
|
info_label.pack(pady=config.space("sm"))
|
||||||
|
|
||||||
# Non-flash types use a smaller font because their display text is wider.
|
# Non-flash types use a smaller font because their display text is wider.
|
||||||
code_font_size = (
|
# Multiples of the display token rather than raw sizes, so the challenge
|
||||||
48 if challenge.kind in ("math", "sort", "sequence", "reverse") else 72
|
# scales with the rest of the screen (and is sized in px, not points).
|
||||||
|
code_scale = (
|
||||||
|
1.5 if challenge.kind in ("math", "sort", "sequence", "reverse") else 2.25
|
||||||
)
|
)
|
||||||
code_label = tk.Label(
|
code_label = tk.Label(
|
||||||
parent,
|
parent,
|
||||||
text=challenge.display,
|
text=challenge.display,
|
||||||
font=("Courier", code_font_size, "bold"),
|
font=config.font("display", bold=True, family="Courier", scale=code_scale),
|
||||||
fg=config.success,
|
fg=config.success,
|
||||||
bg=config.bg,
|
bg=config.bg,
|
||||||
)
|
)
|
||||||
code_label.pack(pady=30)
|
code_label.pack(pady=config.space("lg"))
|
||||||
|
|
||||||
entry = tk.Entry(
|
entry = tk.Entry(
|
||||||
parent,
|
parent,
|
||||||
font=("Courier", 36),
|
font=config.font("display", family="Courier"),
|
||||||
justify="center",
|
justify="center",
|
||||||
width=12,
|
width=12,
|
||||||
textvariable=entry_var,
|
textvariable=entry_var,
|
||||||
|
# Tk's default focus ring is 1px BLACK, invisible on bg (#211D1B). This
|
||||||
|
# field is already focused and Return-bound, so the ring is about
|
||||||
|
# confirming *where* keystrokes are going -- on a screen with no other
|
||||||
|
# window and a global grab, that is the only feedback available.
|
||||||
|
**config.focus_kwargs(),
|
||||||
)
|
)
|
||||||
entry.pack(pady=10)
|
entry.pack(pady=config.space("sm"))
|
||||||
entry.focus_set()
|
entry.focus_set()
|
||||||
entry.bind("<Return>", on_submit)
|
entry.bind("<Return>", on_submit)
|
||||||
|
|
||||||
status_label = tk.Label(
|
status_label = tk.Label(
|
||||||
parent,
|
parent,
|
||||||
text="",
|
text="",
|
||||||
font=("Arial", 18),
|
font=config.font("body"),
|
||||||
fg=config.danger,
|
fg=config.danger,
|
||||||
bg=config.bg,
|
bg=config.bg,
|
||||||
)
|
)
|
||||||
status_label.pack(pady=10)
|
status_label.pack(pady=config.space("sm"))
|
||||||
|
|
||||||
timer_label = tk.Label(
|
timer_label = tk.Label(
|
||||||
parent,
|
parent,
|
||||||
text="",
|
text="",
|
||||||
font=("Arial", 14),
|
font=config.font("label"),
|
||||||
fg=config.muted,
|
fg=config.muted,
|
||||||
bg=config.bg,
|
bg=config.bg,
|
||||||
)
|
)
|
||||||
timer_label.pack(pady=5)
|
timer_label.pack(pady=config.space("xs"))
|
||||||
|
|
||||||
return (
|
return (
|
||||||
_AlarmLabels(
|
_AlarmLabels(
|
||||||
@ -300,10 +309,15 @@ def _build_alarm_view(
|
|||||||
escape_button = tk.Button(
|
escape_button = tk.Button(
|
||||||
challenge_frame,
|
challenge_frame,
|
||||||
text="I can't do this right now",
|
text="I can't do this right now",
|
||||||
font=(config.font_family, 14),
|
font=config.font("label"),
|
||||||
bg=config.field_bg,
|
bg=config.field_bg,
|
||||||
fg=config.muted,
|
fg=config.muted,
|
||||||
|
**config.focus_kwargs(),
|
||||||
)
|
)
|
||||||
|
# Tk binds only <space> on Button on X11. The escape hatch is deliberately
|
||||||
|
# hard to reach (hidden until earned, budgeted) but must not additionally be
|
||||||
|
# hard to *press* once shown.
|
||||||
|
bind_activate(escape_button)
|
||||||
|
|
||||||
return _AlarmView(
|
return _AlarmView(
|
||||||
container=container,
|
container=container,
|
||||||
|
|||||||
@ -25,7 +25,14 @@ import logging
|
|||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
from gatelock import EscapeDraft, EscapePolicy, EscapeTracker
|
from gatelock import (
|
||||||
|
EscapeDraft,
|
||||||
|
EscapePolicy,
|
||||||
|
EscapeTracker,
|
||||||
|
bind_activate,
|
||||||
|
bind_cancel,
|
||||||
|
escape_text_tab_trap,
|
||||||
|
)
|
||||||
|
|
||||||
from wake_alarm._constants import ESCAPE_HISTORY_FILE, ESCAPE_OFFER_AFTER_SECONDS
|
from wake_alarm._constants import ESCAPE_HISTORY_FILE, ESCAPE_OFFER_AFTER_SECONDS
|
||||||
|
|
||||||
@ -101,28 +108,28 @@ class EscapeDialog:
|
|||||||
self._status = tk.Label(
|
self._status = tk.Label(
|
||||||
self.frame,
|
self.frame,
|
||||||
text=tracker.budget_summary(),
|
text=tracker.budget_summary(),
|
||||||
font=(config.font_family, 16),
|
font=config.font("body"),
|
||||||
fg=config.muted,
|
fg=config.muted,
|
||||||
bg=config.bg,
|
bg=config.bg,
|
||||||
)
|
)
|
||||||
self._status.pack(pady=6)
|
self._status.pack(pady=config.space("xs"))
|
||||||
|
|
||||||
tk.Label(
|
tk.Label(
|
||||||
self.frame,
|
self.frame,
|
||||||
text="Why can you not do this right now?",
|
text="Why can you not do this right now?",
|
||||||
font=(config.font_family, 22, "bold"),
|
font=config.font("subtitle", bold=True),
|
||||||
fg=config.fg,
|
fg=config.fg,
|
||||||
bg=config.bg,
|
bg=config.bg,
|
||||||
).pack(pady=8)
|
).pack(pady=config.space("sm"))
|
||||||
|
|
||||||
tk.Label(
|
tk.Label(
|
||||||
self.frame,
|
self.frame,
|
||||||
text=tracker.format_recent(),
|
text=tracker.format_recent(),
|
||||||
font=("Courier", 11),
|
font=config.font("caption", family="Courier"),
|
||||||
fg=config.muted,
|
fg=config.muted,
|
||||||
bg=config.bg,
|
bg=config.bg,
|
||||||
justify="left",
|
justify="left",
|
||||||
).pack(pady=6)
|
).pack(pady=config.space("xs"))
|
||||||
|
|
||||||
description = tk.Text(
|
description = tk.Text(
|
||||||
self.frame,
|
self.frame,
|
||||||
@ -132,54 +139,75 @@ class EscapeDialog:
|
|||||||
bg=config.field_bg,
|
bg=config.field_bg,
|
||||||
fg=config.fg,
|
fg=config.fg,
|
||||||
insertbackground=config.fg,
|
insertbackground=config.fg,
|
||||||
|
**config.focus_kwargs(),
|
||||||
)
|
)
|
||||||
|
# Tk traps Tab inside a Text (inserts a literal tab and refocuses the
|
||||||
|
# widget) and binds Shift-Tab to nothing, so the only exits are the
|
||||||
|
# undocumented Ctrl+Tab / Ctrl+Shift+Tab. Unlike diet_guard's equivalent
|
||||||
|
# box, nothing here bound Return either -- so a keyboard-only user who
|
||||||
|
# tabbed into this justification field at 6am could not reach Submit,
|
||||||
|
# inside an alarm whose whole point is that it resists dismissal.
|
||||||
|
escape_text_tab_trap(description)
|
||||||
self._fields = _FormFields(
|
self._fields = _FormFields(
|
||||||
reason=self._field("What is wrong", config),
|
reason=self._field("What is wrong", config),
|
||||||
onset=self._field("When did it start", config),
|
onset=self._field("When did it start", config),
|
||||||
severity=self._field("Severity 1-10", config),
|
severity=self._field("Severity 1-10", config),
|
||||||
description=description,
|
description=description,
|
||||||
)
|
)
|
||||||
description.pack(pady=6)
|
description.pack(pady=config.space("xs"))
|
||||||
|
|
||||||
self._complaint = tk.Label(
|
self._complaint = tk.Label(
|
||||||
self.frame,
|
self.frame,
|
||||||
text="",
|
text="",
|
||||||
font=(config.font_family, 14),
|
font=config.font("label"),
|
||||||
fg=config.danger,
|
fg=config.danger,
|
||||||
bg=config.bg,
|
bg=config.bg,
|
||||||
)
|
)
|
||||||
self._complaint.pack(pady=4)
|
self._complaint.pack(pady=config.space("xs"))
|
||||||
|
|
||||||
self._submit = tk.Button(
|
self._submit = tk.Button(
|
||||||
self.frame,
|
self.frame,
|
||||||
text="Submit",
|
text="Submit",
|
||||||
font=(config.font_family, 16, "bold"),
|
font=config.font("body", bold=True),
|
||||||
bg=config.warning,
|
bg=config.warning,
|
||||||
fg=config.on_fill,
|
fg=config.on_fill,
|
||||||
command=self.submit,
|
command=self.submit,
|
||||||
|
**config.focus_kwargs(),
|
||||||
)
|
)
|
||||||
self._submit.pack(pady=6)
|
self._submit.pack(pady=config.space("xs"))
|
||||||
|
|
||||||
tk.Button(
|
back = tk.Button(
|
||||||
self.frame,
|
self.frame,
|
||||||
text="Back to the alarm",
|
text="Back to the alarm",
|
||||||
font=(config.font_family, 14),
|
font=config.font("label"),
|
||||||
bg=config.field_bg,
|
bg=config.field_bg,
|
||||||
fg=config.fg,
|
fg=config.fg,
|
||||||
command=callbacks.on_cancel,
|
command=callbacks.on_cancel,
|
||||||
).pack(pady=4)
|
**config.focus_kwargs(),
|
||||||
|
)
|
||||||
|
back.pack(pady=config.space("xs"))
|
||||||
|
|
||||||
|
# Tk binds only <space> on Button on X11, never <Return>, so Enter --
|
||||||
|
# the key a user reaches for to submit a form -- did nothing at all.
|
||||||
|
for button in (self._submit, back):
|
||||||
|
bind_activate(button)
|
||||||
|
# Escape returns to the alarm. This cancels the *escape-hatch form*, not
|
||||||
|
# the alarm: the alarm still has to be dismissed by solving a challenge
|
||||||
|
# or by spending the budgeted hatch. Making the sanctioned way back
|
||||||
|
# keyboard-reachable does not weaken that gating.
|
||||||
|
bind_cancel(self.frame, callbacks.on_cancel)
|
||||||
|
|
||||||
def _field(self, label: str, config: LockConfig) -> tk.Entry:
|
def _field(self, label: str, config: LockConfig) -> tk.Entry:
|
||||||
"""Add a labelled single-line field and return its entry."""
|
"""Add a labelled single-line field and return its entry."""
|
||||||
tk.Label(
|
tk.Label(
|
||||||
self.frame,
|
self.frame,
|
||||||
text=label,
|
text=label,
|
||||||
font=(config.font_family, 13),
|
font=config.font("caption"),
|
||||||
fg=config.muted,
|
fg=config.muted,
|
||||||
bg=config.bg,
|
bg=config.bg,
|
||||||
).pack()
|
).pack()
|
||||||
entry = tk.Entry(self.frame, width=40)
|
entry = tk.Entry(self.frame, width=40, **config.focus_kwargs())
|
||||||
entry.pack(pady=2)
|
entry.pack(pady=config.space("xs"))
|
||||||
return entry
|
return entry
|
||||||
|
|
||||||
def _draft(self) -> EscapeDraft:
|
def _draft(self) -> EscapeDraft:
|
||||||
@ -256,7 +284,7 @@ class EscapeHatch:
|
|||||||
return
|
return
|
||||||
for button in self._views.escape_buttons:
|
for button in self._views.escape_buttons:
|
||||||
with contextlib.suppress(tk.TclError):
|
with contextlib.suppress(tk.TclError):
|
||||||
button.pack(pady=8)
|
button.pack(pady=self._views.config.space("sm"))
|
||||||
|
|
||||||
def open(self) -> None:
|
def open(self) -> None:
|
||||||
"""Swap every surface over to the justification form."""
|
"""Swap every surface over to the justification form."""
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user