From c6bdecc0dd5dfbf0bc155f679e27aa6f3676dd99 Mon Sep 17 00:00:00 2001 From: steven Date: Mon, 16 Nov 2026 13:53:44 +0800 Subject: [PATCH] feat(android): add cover and rear display glance surfaces --- android/app/src/main/AndroidManifest.xml | 3 + .../club/geekpie/techpie/MainActivity.kt | 4 + .../geekpie/techpie/ScreenFormFactorBridge.kt | 91 +++ docs/cover-rear-glance.md | 7 + .../core/config/payment_code_preferences.dart | 10 + .../presentation/widgets/payment_code_qr.dart | 174 +++++ .../application/glance_snapshot_builder.dart | 76 ++ .../glance/domain/glance_snapshot.dart | 77 ++ .../presentation/cover_glance_layout.dart | 732 ++++++++++++++++++ .../presentation/glance_formatters.dart | 41 + .../presentation/glance_payment_card.dart | 215 +++++ .../presentation/glance_payment_view.dart | 296 +++++++ .../glance/presentation/glance_shell.dart | 464 +++++++++++ .../glance/presentation/glance_widgets.dart | 164 ++++ .../presentation/live_glance_shell.dart | 134 ++++ .../presentation/rear_glance_layout.dart | 269 +++++++ lib/main.dart | 23 +- lib/models/screen_form_factor.dart | 115 +++ lib/pages/glance_preview_page.dart | 144 ++++ lib/pages/glance_settings_page.dart | 250 ++++++ lib/pages/settings_page.dart | 14 + lib/services/glance_settings_service.dart | 65 ++ lib/services/schedule_timeline_service.dart | 60 ++ lib/services/screen_form_factor_service.dart | 118 +++ lib/services/service_provider.dart | 8 + lib/services/storage_service.dart | 20 + lib/widgets/app_shell/app_entry_notifier.dart | 11 + lib/widgets/app_shell/app_shell.dart | 8 +- lib/widgets/glance/glance_active_scope.dart | 27 + lib/widgets/glance/glance_gate.dart | 148 ++++ lib/widgets/privacy_consent.dart | 7 +- test/glance/glance_gate_test.dart | 191 +++++ test/glance/glance_payment_view_test.dart | 93 +++ test/glance/glance_shell_test.dart | 359 +++++++++ test/glance/glance_snapshot_builder_test.dart | 148 ++++ test/glance/screen_form_factor_test.dart | 209 +++++ 36 files changed, 4767 insertions(+), 8 deletions(-) create mode 100644 android/app/src/main/kotlin/club/geekpie/techpie/ScreenFormFactorBridge.kt create mode 100644 docs/cover-rear-glance.md create mode 100644 lib/features/campus_card/presentation/widgets/payment_code_qr.dart create mode 100644 lib/features/glance/application/glance_snapshot_builder.dart create mode 100644 lib/features/glance/domain/glance_snapshot.dart create mode 100644 lib/features/glance/presentation/cover_glance_layout.dart create mode 100644 lib/features/glance/presentation/glance_formatters.dart create mode 100644 lib/features/glance/presentation/glance_payment_card.dart create mode 100644 lib/features/glance/presentation/glance_payment_view.dart create mode 100644 lib/features/glance/presentation/glance_shell.dart create mode 100644 lib/features/glance/presentation/glance_widgets.dart create mode 100644 lib/features/glance/presentation/live_glance_shell.dart create mode 100644 lib/features/glance/presentation/rear_glance_layout.dart create mode 100644 lib/models/screen_form_factor.dart create mode 100644 lib/pages/glance_preview_page.dart create mode 100644 lib/pages/glance_settings_page.dart create mode 100644 lib/services/glance_settings_service.dart create mode 100644 lib/services/schedule_timeline_service.dart create mode 100644 lib/services/screen_form_factor_service.dart create mode 100644 lib/widgets/app_shell/app_entry_notifier.dart create mode 100644 lib/widgets/glance/glance_active_scope.dart create mode 100644 lib/widgets/glance/glance_gate.dart create mode 100644 test/glance/glance_gate_test.dart create mode 100644 test/glance/glance_payment_view_test.dart create mode 100644 test/glance/glance_shell_test.dart create mode 100644 test/glance/glance_snapshot_builder_test.dart create mode 100644 test/glance/screen_form_factor_test.dart diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 854b54b6..bf37c06f 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -11,7 +11,10 @@ android:name="${applicationName}" android:icon="@mipmap/ic_launcher" android:allowBackup="false" + android:resizeableActivity="true" android:usesCleartextTraffic="false"> + + result.success(info()) + else -> result.notImplemented() + } + } + + fun dispose() { + channel.setMethodCallHandler(null) + } + + private fun info(): Map { + val display = currentDisplay() + val displayId = display?.displayId ?: Display.DEFAULT_DISPLAY + val metrics = activity.resources.displayMetrics + val bounds = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + activity.windowManager.currentWindowMetrics.bounds + } else { + android.graphics.Rect(0, 0, metrics.widthPixels, metrics.heightPixels) + } + return mapOf( + "isFlipDevice" to miuiFlag("isFlipDevice"), + "isRearDevice" to miuiFlag("isRearDevice"), + "displayId" to displayId, + "windowWidthPx" to bounds.width(), + "windowHeightPx" to bounds.height(), + "density" to metrics.density.toDouble(), + "densityDpi" to metrics.densityDpi, + "isDefaultDisplay" to (displayId == Display.DEFAULT_DISPLAY), + "isInMultiWindowMode" to activity.isInMultiWindowMode, + "model" to Build.MODEL, + "manufacturer" to Build.MANUFACTURER, + "sdkInt" to Build.VERSION.SDK_INT, + ) + } + + private fun currentDisplay(): Display? = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + activity.display + } else { + @Suppress("DEPRECATION") + activity.windowManager.defaultDisplay + } + + /** + * The class is absent on most devices and hidden on some HyperOS builds; + * a failed probe simply means "not this form factor", never a crash. + */ + private fun miuiFlag(method: String): Boolean = try { + val type = Class.forName("miui.util.MiuiMultiDisplayTypeInfo") + type.getMethod(method).invoke(null) as? Boolean ?: false + } catch (_: ReflectiveOperationException) { + false + } catch (_: SecurityException) { + false + } catch (_: LinkageError) { + false + } + + private companion object { + const val CHANNEL = "techpie/screen_form_factor" + } +} diff --git a/docs/cover-rear-glance.md b/docs/cover-rear-glance.md new file mode 100644 index 00000000..4ab2bbef --- /dev/null +++ b/docs/cover-rear-glance.md @@ -0,0 +1,7 @@ +# Cover and rear display glance + +On compatible Android displays the app shows a compact course/deadline/online-payment surface. Settings configure sections and offer previews. Display classification excludes unfolded landscape windows. The main navigator stays mounted across fold/unfold, and shortcuts are consumed by the visible surface. Policy acceptance gates personal data on both surfaces; the glance never changes main-display brightness. + +The implementation retains upstream iOS tab stacks, online Apple Watch support, dependency pins, release version, signing and update channel. It does not add a display permission on other platforms. Offline payment remains in the full campus-card UI; previews and source checks do not verify camera scanning on every physical rear screen. + +Regression coverage includes classification, compact layouts, privacy, foreground/payment lifecycle and shortcut routing. Actual vendor display routing, folding and QR scans still require compatible hardware. diff --git a/lib/features/campus_card/core/config/payment_code_preferences.dart b/lib/features/campus_card/core/config/payment_code_preferences.dart index 38218319..e1ad698c 100644 --- a/lib/features/campus_card/core/config/payment_code_preferences.dart +++ b/lib/features/campus_card/core/config/payment_code_preferences.dart @@ -8,10 +8,20 @@ final maximizePaymentCodeBrightnessProvider = final class MaximizePaymentCodeBrightnessController extends AsyncNotifier { + MaximizePaymentCodeBrightnessController() : _fixed = null; + + /// A controller that ignores the stored preference, for surfaces that must + /// never touch the main display's brightness. + MaximizePaymentCodeBrightnessController.fixed(bool value) : _fixed = value; + static const _key = 'geekpay.maximize_payment_code_brightness'; + final bool? _fixed; + @override Future build() async { + final fixed = _fixed; + if (fixed != null) return fixed; final preferences = await SharedPreferences.getInstance(); return preferences.getBool(_key) ?? false; } diff --git a/lib/features/campus_card/presentation/widgets/payment_code_qr.dart b/lib/features/campus_card/presentation/widgets/payment_code_qr.dart new file mode 100644 index 00000000..0b6327d4 --- /dev/null +++ b/lib/features/campus_card/presentation/widgets/payment_code_qr.dart @@ -0,0 +1,174 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:qr_flutter/qr_flutter.dart'; + +import '../theme/tokens.dart'; + +/// The campus payment QR, shared by the full pass and the glance surface. +/// +/// [qrKey] defaults to the key the full pass has always exposed; the glance +/// passes its own key so a test can tell the two surfaces apart. +final class PaymentCodeQr extends StatefulWidget { + const PaymentCodeQr({ + super.key, + required this.payload, + required this.binaryPayload, + required this.size, + required this.onTap, + this.qrKey = const Key('payment-code-qr'), + }); + + final String payload; + final bool binaryPayload; + final double size; + final VoidCallback onTap; + final Key qrKey; + + @override + State createState() => _PaymentCodeQrState(); +} + +class _PaymentCodeQrState extends State { + late Widget _image; + + @override + void initState() { + super.initState(); + _image = _createImage(); + } + + @override + void didUpdateWidget(PaymentCodeQr oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.payload != widget.payload || + oldWidget.binaryPayload != widget.binaryPayload) { + _image = _createImage(); + } + } + + Widget _createImage() => widget.binaryPayload + ? QrImageView.withQr( + qr: QrCode.fromUint8List( + data: Uint8List.fromList(latin1.encode(widget.payload)), + errorCorrectLevel: QrErrorCorrectLevel.L, + ), + padding: EdgeInsets.zero, + eyeStyle: const QrEyeStyle( + eyeShape: QrEyeShape.square, + color: GpTokens.campusRed, + ), + dataModuleStyle: const QrDataModuleStyle( + dataModuleShape: QrDataModuleShape.square, + color: GpTokens.campusRed, + ), + backgroundColor: GpTokens.cardCanvas, + ) + : QrImageView( + data: widget.payload, + version: QrVersions.auto, + padding: EdgeInsets.zero, + eyeStyle: const QrEyeStyle( + eyeShape: QrEyeShape.square, + color: GpTokens.campusRed, + ), + dataModuleStyle: const QrDataModuleStyle( + dataModuleShape: QrDataModuleShape.square, + color: GpTokens.campusRed, + ), + backgroundColor: GpTokens.cardCanvas, + ); + + @override + Widget build(BuildContext context) { + return Semantics( + button: true, + label: '轻触二维码刷新', + child: GestureDetector( + onTap: widget.onTap, + child: Container( + key: widget.qrKey, + width: widget.size, + height: widget.size, + color: GpTokens.cardCanvas, + padding: EdgeInsets.all(widget.size * 0.035), + child: _image, + ), + ), + ); + } +} + +/// Thirty-second countdown shown under an online code. +final class PaymentCodeCountdown extends StatefulWidget { + const PaymentCodeCountdown({ + super.key, + required this.generation, + required this.active, + required this.style, + this.seconds = 30, + }); + + final int generation; + final bool active; + final TextStyle style; + final int seconds; + + @override + State createState() => _PaymentCodeCountdownState(); +} + +class _PaymentCodeCountdownState extends State { + Timer? _timer; + late int _remaining; + + @override + void initState() { + super.initState(); + _remaining = widget.seconds; + _startTimer(); + } + + @override + void didUpdateWidget(PaymentCodeCountdown oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.generation != widget.generation || + oldWidget.seconds != widget.seconds) { + _remaining = widget.seconds; + _startTimer(); + } else if (oldWidget.active != widget.active) { + _startTimer(); + } + } + + void _startTimer() { + _timer?.cancel(); + if (!widget.active || _remaining <= 1) return; + final initial = _remaining; + _timer = Timer.periodic(const Duration(seconds: 1), (timer) { + final next = (initial - timer.tick).clamp(1, widget.seconds); + setState(() => _remaining = next); + if (_remaining == 1) timer.cancel(); + }); + } + + @override + void dispose() { + _timer?.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => SizedBox( + width: double.infinity, + child: RepaintBoundary( + child: Text( + '$_remaining秒后刷新', + textAlign: TextAlign.center, + style: widget.style, + ), + ), + ); +} diff --git a/lib/features/glance/application/glance_snapshot_builder.dart b/lib/features/glance/application/glance_snapshot_builder.dart new file mode 100644 index 00000000..d9d9eaae --- /dev/null +++ b/lib/features/glance/application/glance_snapshot_builder.dart @@ -0,0 +1,76 @@ +import '../../../models/assignment.dart'; +import '../../../models/course.dart'; +import '../../../models/course_table.dart'; +import '../../../models/custom_course.dart'; +import '../../../services/schedule_timeline_service.dart'; +import '../domain/glance_snapshot.dart'; +import '../presentation/glance_formatters.dart'; + +/// Builds the glance snapshot from raw service data. +/// +/// The course merge and state rules come from [ScheduleTimeline], the same +/// source Home and the band app use. Deadline filtering is done by the caller +/// through [AssignmentService.visibleAssignments]/`isCompleted` so hidden and +/// locally completed items never leak into the small surface. +final class GlanceSnapshotBuilder { + const GlanceSnapshotBuilder._(); + + static GlanceSnapshot build({ + required CourseTable? courseTable, + required List customCourses, + required DateTime? termBegin, + required int? week, + required List rawAssignments, + required List pendingAssignments, + required String? semesterId, + required DateTime now, + required bool loggedIn, + required bool inTerm, + required bool scheduleLoading, + required String? scheduleError, + required bool assignmentsLoading, + required String? assignmentsError, + }) { + final courses = ScheduleTimeline.todayCourses( + table: courseTable, + customCourses: customCourses, + week: week, + termBegin: termBegin, + assignments: rawAssignments, + semesterId: semesterId, + now: now, + ); + final pending = [...pendingAssignments] + ..sort((a, b) => a.due.compareTo(b.due)); + + return GlanceSnapshot( + now: now, + week: week, + inTerm: inTerm, + loggedIn: loggedIn, + courses: [ + for (final course in courses) + GlanceCourse(course: course, state: _stateOf(course, now)), + ], + pendingAssignments: [ + for (final assignment in pending) + GlanceAssignment( + assignment: assignment, + dueLabel: formatGlanceDue(assignment.due, now), + ), + ], + scheduleLoading: scheduleLoading, + scheduleError: scheduleError, + assignmentsLoading: assignmentsLoading, + assignmentsError: assignmentsError, + ); + } + + static GlanceCourseState _stateOf(Course course, DateTime now) => + switch (ScheduleTimeline.courseState(course, now)) { + 'past' => GlanceCourseState.past, + 'ongoing' => GlanceCourseState.ongoing, + 'soon' => GlanceCourseState.soon, + _ => GlanceCourseState.upcoming, + }; +} diff --git a/lib/features/glance/domain/glance_snapshot.dart b/lib/features/glance/domain/glance_snapshot.dart new file mode 100644 index 00000000..e680c82a --- /dev/null +++ b/lib/features/glance/domain/glance_snapshot.dart @@ -0,0 +1,77 @@ +import '../../../models/assignment.dart'; +import '../../../models/course.dart'; + +enum GlanceCourseState { past, ongoing, soon, upcoming } + +final class GlanceCourse { + const GlanceCourse({required this.course, required this.state}); + + final Course course; + final GlanceCourseState state; + + bool get isPast => state == GlanceCourseState.past; + + bool get isOngoing => state == GlanceCourseState.ongoing; +} + +final class GlanceAssignment { + const GlanceAssignment({required this.assignment, required this.dueLabel}); + + final Assignment assignment; + final String dueLabel; +} + +/// A point-in-time view of today's schedule and pending deadlines. +final class GlanceSnapshot { + const GlanceSnapshot({ + required this.now, + required this.week, + required this.inTerm, + required this.loggedIn, + required this.courses, + required this.pendingAssignments, + required this.scheduleLoading, + required this.scheduleError, + required this.assignmentsLoading, + required this.assignmentsError, + }); + + final DateTime now; + final int? week; + final bool inTerm; + final bool loggedIn; + final List courses; + final List pendingAssignments; + final bool scheduleLoading; + final String? scheduleError; + final bool assignmentsLoading; + final String? assignmentsError; + + bool get hasCourses => courses.isNotEmpty; + + bool get hasPending => pendingAssignments.isNotEmpty; + + GlanceCourse? get currentCourse { + for (final course in courses) { + if (course.isOngoing) return course; + } + return null; + } + + GlanceCourse? get nextCourse { + for (final course in courses) { + if (course.state == GlanceCourseState.soon || + course.state == GlanceCourseState.upcoming) { + return course; + } + } + return null; + } + + /// Today's courses that are still ongoing or upcoming, in start order. + List get activeCourses => + [for (final course in courses) if (!course.isPast) course]; + + /// The course to lead with: the one in progress, otherwise the next one. + GlanceCourse? get leadCourse => currentCourse ?? nextCourse; +} diff --git a/lib/features/glance/presentation/cover_glance_layout.dart b/lib/features/glance/presentation/cover_glance_layout.dart new file mode 100644 index 00000000..3b1b84cc --- /dev/null +++ b/lib/features/glance/presentation/cover_glance_layout.dart @@ -0,0 +1,732 @@ +import 'package:flutter/material.dart'; + +import '../../../models/course.dart'; +import '../domain/glance_snapshot.dart'; +import 'glance_formatters.dart'; +import 'glance_widgets.dart'; + +/// Cover pages are designed for the MIX Flip panel: 506 x 439 dp, wider than +/// it is tall. Each page splits into a leading card and a vertical queue so the +/// extra width carries information instead of stretching a single column. +class CoverCoursesPage extends StatelessWidget { + const CoverCoursesPage({ + super.key, + required this.snapshot, + this.onRetry, + }); + + final GlanceSnapshot snapshot; + final VoidCallback? onRetry; + + @override + Widget build(BuildContext context) { + final unavailable = glanceUnavailableState( + snapshot, + courses: true, + compact: false, + onRetry: onRetry, + ); + if (unavailable != null) return unavailable; + + final lead = snapshot.leadCourse; + if (lead == null) { + return GlanceMessage( + icon: Icons.nights_stay_outlined, + title: '今天的课已结束', + subtitle: '今天共 ${snapshot.courses.length} 节课', + ); + } + + final rest = []; + var skippedLead = false; + for (final course in snapshot.activeCourses) { + if (!skippedLead && identical(course, lead)) { + skippedLead = true; + continue; + } + rest.add(course); + } + + return Padding( + padding: const EdgeInsets.fromLTRB(16, 6, 16, 10), + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + flex: 3, + child: _LeadCourseCard( + course: lead, + totalCourses: snapshot.courses.length, + ), + ), + const SizedBox(width: 12), + Expanded( + flex: 2, + child: _CourseQueue(courses: rest), + ), + ], + ), + ); + } +} + +class _LeadCourseCard extends StatelessWidget { + const _LeadCourseCard({ + required this.course, + required this.totalCourses, + }); + + final GlanceCourse course; + final int totalCourses; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final background = course.course.color.containerColor(scheme); + final foreground = course.course.color.onContainerColor(scheme); + final location = + course.course.location.isEmpty ? '地点待定' : course.course.location; + + return Container( + padding: const EdgeInsets.fromLTRB(16, 14, 16, 14), + decoration: BoxDecoration( + color: background, + borderRadius: BorderRadius.circular(20), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + _StatePill(label: _stateLabel(course.state), color: foreground), + const SizedBox(width: 8), + Expanded( + child: Text( + formatGlanceCourseTime(course.course), + maxLines: 1, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.end, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: foreground.withValues(alpha: 0.78), + ), + ), + ), + ], + ), + Expanded( + child: Align( + alignment: Alignment.centerLeft, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + course.course.name, + maxLines: 3, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 25, + height: 1.12, + fontWeight: FontWeight.w700, + color: foreground, + ), + ), + const SizedBox(height: 8), + Row( + children: [ + Icon( + Icons.place_outlined, + size: 14, + color: foreground.withValues(alpha: 0.8), + ), + const SizedBox(width: 4), + Expanded( + child: Text( + location, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12, + color: foreground.withValues(alpha: 0.8), + ), + ), + ), + ], + ), + ], + ), + ), + ), + Divider( + height: 17, + thickness: 1, + color: foreground.withValues(alpha: 0.12), + ), + Text( + '今天共 $totalCourses 节课', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + color: foreground.withValues(alpha: 0.7), + ), + ), + ], + ), + ); + } +} + +class _StatePill extends StatelessWidget { + const _StatePill({required this.label, required this.color}); + + final String label; + final Color color; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: color.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(999), + ), + child: Text( + label, + maxLines: 1, + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w600, + color: color, + ), + ), + ); + } +} + +class _CourseQueue extends StatelessWidget { + const _CourseQueue({required this.courses}); + + final List courses; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final shown = courses.take(4).toList(); + final hidden = courses.length - shown.length; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text( + '之后', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: scheme.onSurfaceVariant, + ), + ), + const Spacer(), + Text( + '${courses.length} 节', + style: TextStyle( + fontSize: 10, + color: scheme.onSurfaceVariant, + ), + ), + ], + ), + const SizedBox(height: 7), + Expanded( + child: shown.isEmpty + ? Center( + child: Text( + '之后没有课了', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 11, + color: scheme.onSurfaceVariant, + ), + ), + ) + : ListView.separated( + padding: EdgeInsets.zero, + itemCount: shown.length, + separatorBuilder: (_, __) => const SizedBox(height: 7), + itemBuilder: (context, index) => + _CourseQueueRow(course: shown[index]), + ), + ), + if (hidden > 0) ...[ + const SizedBox(height: 4), + Text( + '还有 $hidden 节课', + maxLines: 1, + style: TextStyle( + fontSize: 10, + color: scheme.onSurfaceVariant, + ), + ), + ], + ], + ); + } +} + +class _CourseQueueRow extends StatelessWidget { + const _CourseQueueRow({required this.course}); + + final GlanceCourse course; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return Container( + padding: const EdgeInsets.fromLTRB(9, 9, 10, 9), + decoration: BoxDecoration( + color: scheme.surfaceContainerHighest.withValues(alpha: 0.55), + borderRadius: BorderRadius.circular(12), + ), + child: Row( + children: [ + Container( + width: 3, + height: 36, + decoration: BoxDecoration( + color: course.course.color.containerColor(scheme), + borderRadius: BorderRadius.circular(3), + ), + ), + const SizedBox(width: 9), + SizedBox( + width: 42, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + FittedBox( + fit: BoxFit.scaleDown, + alignment: Alignment.centerLeft, + child: Text( + course.course.startTime, + maxLines: 1, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: scheme.onSurface, + ), + ), + ), + FittedBox( + fit: BoxFit.scaleDown, + alignment: Alignment.centerLeft, + child: Text( + course.course.endTime, + maxLines: 1, + style: TextStyle( + fontSize: 10, + color: scheme.onSurfaceVariant, + ), + ), + ), + ], + ), + ), + const SizedBox(width: 6), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + course.course.name, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12.5, + height: 1.18, + fontWeight: FontWeight.w600, + color: scheme.onSurface, + ), + ), + if (course.course.location.isNotEmpty) + Text( + course.course.location, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 10, + color: scheme.onSurfaceVariant, + ), + ), + ], + ), + ), + ], + ), + ); + } +} + +class CoverAssignmentsPage extends StatelessWidget { + const CoverAssignmentsPage({ + super.key, + required this.snapshot, + this.onRetry, + }); + + final GlanceSnapshot snapshot; + final VoidCallback? onRetry; + + @override + Widget build(BuildContext context) { + final unavailable = glanceUnavailableState( + snapshot, + courses: false, + compact: false, + onRetry: onRetry, + ); + if (unavailable != null) return unavailable; + + final items = snapshot.pendingAssignments; + final lead = items.first; + final rest = items.skip(1).toList(); + + return Padding( + padding: const EdgeInsets.fromLTRB(16, 6, 16, 10), + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + flex: 3, + child: _LeadAssignmentCard( + item: lead, + now: snapshot.now, + total: items.length, + ), + ), + const SizedBox(width: 12), + Expanded( + flex: 2, + child: _AssignmentQueue( + items: rest, + now: snapshot.now, + ), + ), + ], + ), + ); + } +} + +class _LeadAssignmentCard extends StatelessWidget { + const _LeadAssignmentCard({ + required this.item, + required this.now, + required this.total, + }); + + final GlanceAssignment item; + final DateTime now; + final int total; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final urgency = _urgencyColor(item.assignment.due, now, scheme); + final course = item.assignment.course; + + return ClipRRect( + borderRadius: BorderRadius.circular(20), + child: ColoredBox( + color: scheme.surfaceContainerHighest.withValues(alpha: 0.55), + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SizedBox(width: 4, child: ColoredBox(color: urgency)), + Expanded( + child: Padding( + padding: const EdgeInsets.fromLTRB(14, 13, 16, 14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 3, + ), + decoration: BoxDecoration( + color: urgency.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(999), + ), + child: Text( + '最紧急', + maxLines: 1, + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w600, + color: urgency, + ), + ), + ), + const Spacer(), + Text( + '共 $total 项', + maxLines: 1, + style: TextStyle( + fontSize: 10, + color: scheme.onSurfaceVariant, + ), + ), + ], + ), + Expanded( + child: Align( + alignment: Alignment.centerLeft, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + item.assignment.title, + maxLines: 3, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 20, + height: 1.2, + fontWeight: FontWeight.w700, + color: scheme.onSurface, + ), + ), + const SizedBox(height: 8), + Text( + course.isEmpty + ? item.assignment.kind.label + : '$course · ${item.assignment.kind.label}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 11, + color: scheme.onSurfaceVariant, + ), + ), + ], + ), + ), + ), + Divider( + height: 17, + thickness: 1, + color: scheme.outlineVariant.withValues(alpha: 0.6), + ), + Row( + children: [ + Text( + '截止', + style: TextStyle( + fontSize: 10, + color: scheme.onSurfaceVariant, + ), + ), + const SizedBox(width: 6), + Expanded( + child: Text( + item.dueLabel, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w700, + color: urgency, + ), + ), + ), + ], + ), + ], + ), + ), + ), + ], + ), + ), + ); + } +} + +class _AssignmentQueue extends StatelessWidget { + const _AssignmentQueue({required this.items, required this.now}); + + final List items; + final DateTime now; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final shown = items.take(3).toList(); + final hidden = items.length - shown.length; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text( + '后续', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: scheme.onSurfaceVariant, + ), + ), + const Spacer(), + Text( + '${items.length} 项', + style: TextStyle( + fontSize: 10, + color: scheme.onSurfaceVariant, + ), + ), + ], + ), + const SizedBox(height: 7), + Expanded( + child: shown.isEmpty + ? Center( + child: Text( + '没有更多待办', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 11, + color: scheme.onSurfaceVariant, + ), + ), + ) + : ListView.separated( + padding: EdgeInsets.zero, + itemCount: shown.length, + separatorBuilder: (_, __) => const SizedBox(height: 7), + itemBuilder: (context, index) => _AssignmentQueueRow( + item: shown[index], + now: now, + ), + ), + ), + if (hidden > 0) ...[ + const SizedBox(height: 4), + Text( + '还有 $hidden 项', + maxLines: 1, + style: TextStyle( + fontSize: 10, + color: scheme.onSurfaceVariant, + ), + ), + ], + ], + ); + } +} + +class _AssignmentQueueRow extends StatelessWidget { + const _AssignmentQueueRow({ + required this.item, + required this.now, + }); + + final GlanceAssignment item; + final DateTime now; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final urgency = _urgencyColor(item.assignment.due, now, scheme); + final course = item.assignment.course; + return Container( + padding: const EdgeInsets.fromLTRB(9, 8, 10, 8), + decoration: BoxDecoration( + color: scheme.surfaceContainerHighest.withValues(alpha: 0.55), + borderRadius: BorderRadius.circular(12), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + width: 3, + height: 34, + margin: const EdgeInsets.only(top: 1), + decoration: BoxDecoration( + color: urgency, + borderRadius: BorderRadius.circular(3), + ), + ), + const SizedBox(width: 9), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + item.assignment.title, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12.5, + height: 1.2, + fontWeight: FontWeight.w600, + color: scheme.onSurface, + ), + ), + const SizedBox(height: 3), + Text( + course.isEmpty + ? item.assignment.kind.label + : '$course · ${item.assignment.kind.label}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 10, + color: scheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 2), + Text( + item.dueLabel, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w600, + color: urgency, + ), + ), + ], + ), + ), + ], + ), + ); + } +} + +String _stateLabel(GlanceCourseState state) => switch (state) { + GlanceCourseState.ongoing => '正在上课', + GlanceCourseState.soon => '即将开始', + GlanceCourseState.upcoming => '下一节', + GlanceCourseState.past => '已结束', + }; + +Color _urgencyColor(DateTime due, DateTime now, ColorScheme scheme) { + final today = DateTime(now.year, now.month, now.day); + final target = DateTime(due.year, due.month, due.day); + final days = target.difference(today).inDays; + if (days <= 0) return scheme.error; + if (days == 1) return scheme.tertiary; + return scheme.onSurfaceVariant; +} diff --git a/lib/features/glance/presentation/glance_formatters.dart b/lib/features/glance/presentation/glance_formatters.dart new file mode 100644 index 00000000..1f2e1758 --- /dev/null +++ b/lib/features/glance/presentation/glance_formatters.dart @@ -0,0 +1,41 @@ +import '../../../models/course.dart'; + +const _weekdays = ['一', '二', '三', '四', '五', '六', '日']; + +String formatGlanceClock(DateTime time) => + '${time.hour.toString().padLeft(2, '0')}:' + '${time.minute.toString().padLeft(2, '0')}'; + +String formatGlanceWeekday(DateTime time) => '周${_weekdays[time.weekday - 1]}'; + +String formatGlanceMonthDay(DateTime time) => + '${time.month.toString().padLeft(2, '0')}/' + '${time.day.toString().padLeft(2, '0')}'; + +/// `周三 · 10/28 · 第9周`; the week suffix disappears outside the term. +String formatGlanceDateLine({ + required DateTime now, + required int? week, + required bool inTerm, +}) { + final parts = [ + formatGlanceWeekday(now), + formatGlanceMonthDay(now), + if (inTerm && week != null) '第$week周', + ]; + return parts.join(' · '); +} + +/// `今天 14:00`, `明天 09:00`, `10/30 23:59`. +String formatGlanceDue(DateTime due, DateTime now) { + final today = DateTime(now.year, now.month, now.day); + final target = DateTime(due.year, due.month, due.day); + final days = target.difference(today).inDays; + final clock = formatGlanceClock(due); + if (days <= 0) return '今天 $clock'; + if (days == 1) return '明天 $clock'; + return '${formatGlanceMonthDay(due)} $clock'; +} + +String formatGlanceCourseTime(Course course) => + '${course.startTime}–${course.endTime}'; diff --git a/lib/features/glance/presentation/glance_payment_card.dart b/lib/features/glance/presentation/glance_payment_card.dart new file mode 100644 index 00000000..8485125b --- /dev/null +++ b/lib/features/glance/presentation/glance_payment_card.dart @@ -0,0 +1,215 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + +import '../../campus_card/presentation/theme/tokens.dart'; +import '../../campus_card/presentation/widgets/payment_code_qr.dart'; + +/// Renders an online payment code on a light card that stays readable on both +/// the cover and the rear screen. The caller supplies the data and the +/// countdown widget, so the preview can reuse the exact layout without polling. +class GlancePaymentCard extends StatelessWidget { + const GlancePaymentCard({ + super.key, + required this.payload, + required this.binaryPayload, + required this.statusLabel, + required this.hint, + required this.onTap, + this.balanceText, + this.countdown, + this.qrKey = const Key('glance-payment-qr'), + }); + + final String payload; + final bool binaryPayload; + final String statusLabel; + final String hint; + final VoidCallback onTap; + final String? balanceText; + final Widget? countdown; + final Key qrKey; + + @override + Widget build(BuildContext context) { + return Container( + decoration: BoxDecoration( + color: GpTokens.cardCanvas, + borderRadius: BorderRadius.circular(16), + ), + padding: const EdgeInsets.all(12), + child: LayoutBuilder( + builder: (context, constraints) { + final landscape = constraints.maxWidth > constraints.maxHeight; + final large = landscape && + constraints.maxWidth >= 380 && + constraints.maxHeight >= 300; + if (landscape) { + final qrSize = math + .min(constraints.maxWidth * 0.55, constraints.maxHeight - 10) + .clamp(90.0, 280.0) + .toDouble(); + return Row( + children: [ + PaymentCodeQr( + payload: payload, + binaryPayload: binaryPayload, + size: qrSize, + onTap: onTap, + qrKey: qrKey, + ), + SizedBox(width: large ? 18 : 10), + Expanded( + child: _PaymentDetails( + statusLabel: statusLabel, + balanceText: balanceText, + hint: hint, + countdown: countdown, + compact: true, + large: large, + ), + ), + ], + ); + } + + final qrSize = math + .min(constraints.maxWidth - 10, constraints.maxHeight * 0.60) + .clamp(120.0, 260.0) + .toDouble(); + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + _PaymentDetails( + statusLabel: statusLabel, + balanceText: balanceText, + hint: null, + countdown: null, + compact: false, + large: false, + ), + const SizedBox(height: 6), + PaymentCodeQr( + payload: payload, + binaryPayload: binaryPayload, + size: qrSize, + onTap: onTap, + qrKey: qrKey, + ), + if (countdown != null) ...[ + const SizedBox(height: 4), + countdown!, + ], + const SizedBox(height: 2), + Text( + hint, + textAlign: TextAlign.center, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 9, + color: GpTokens.campusRed.withValues(alpha: 0.55), + ), + ), + ], + ); + }, + ), + ); + } +} + +class _PaymentDetails extends StatelessWidget { + const _PaymentDetails({ + required this.statusLabel, + required this.balanceText, + required this.hint, + required this.countdown, + required this.compact, + required this.large, + }); + + final String statusLabel; + final String? balanceText; + final String? hint; + final Widget? countdown; + final bool compact; + final bool large; + + @override + Widget build(BuildContext context) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: + compact ? CrossAxisAlignment.start : CrossAxisAlignment.center, + children: [ + Text( + statusLabel, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: compact ? (large ? 12 : 10) : 11, + fontWeight: FontWeight.w600, + color: GpTokens.campusRed, + ), + ), + if (balanceText != null) ...[ + SizedBox(height: compact ? (large ? 4 : 2) : 1), + Text( + balanceText!, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: compact ? (large ? 26 : 18) : 20, + fontWeight: FontWeight.w700, + color: GpTokens.campusRed, + fontFeatures: const [FontFeature.tabularFigures()], + ), + ), + ], + if (countdown != null) ...[ + SizedBox(height: large ? 6 : 3), + countdown!, + ], + if (hint != null) ...[ + SizedBox(height: large ? 6 : 4), + Text( + hint!, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: large ? 10 : 9, + color: GpTokens.campusRed.withValues(alpha: 0.55), + ), + ), + ], + ], + ); + } +} + +/// Static preview used by the settings page: a real QR of a harmless sample +/// payload, no auth, no polling, and no offline quota. +class GlancePaymentPreviewCard extends StatelessWidget { + const GlancePaymentPreviewCard({super.key}); + + @override + Widget build(BuildContext context) { + return GlancePaymentCard( + payload: 'https://techpie.geekpie.club', + binaryPayload: false, + statusLabel: '示例消费码', + balanceText: '¥ 128.00', + hint: '预览,不会生成付款码', + countdown: Text( + '30秒后刷新', + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 10, + color: GpTokens.campusRed.withValues(alpha: 0.62), + ), + ), + onTap: () {}, + ); + } +} diff --git a/lib/features/glance/presentation/glance_payment_view.dart b/lib/features/glance/presentation/glance_payment_view.dart new file mode 100644 index 00000000..efc433ff --- /dev/null +++ b/lib/features/glance/presentation/glance_payment_view.dart @@ -0,0 +1,296 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../campus_card/app/app_providers.dart'; +import '../../campus_card/app/app_runtime.dart'; +import '../../campus_card/core/config/payment_code_preferences.dart'; +import '../../campus_card/domain/models/auth_models.dart'; +import '../../campus_card/domain/models/card_models.dart'; +import '../../campus_card/domain/models/payment_models.dart'; +import '../../campus_card/presentation/theme/theme.dart'; +import '../../campus_card/presentation/theme/tokens.dart'; +import '../../campus_card/presentation/widgets/apple_wallet_components.dart'; +import '../../campus_card/presentation/widgets/payment_code_qr.dart'; +import 'glance_payment_card.dart'; +import 'glance_widgets.dart'; + +/// Online payment code for the cover / rear screen. +/// +/// This view deliberately watches only authentication, the card summary and +/// the online payment controller. Offline codes stay in the full campus-card +/// page so glancing at the small screen can never spend an offline use. +class GlancePaymentView extends StatelessWidget { + const GlancePaymentView({super.key, required this.runtime}); + + final AppRuntime runtime; + + @override + Widget build(BuildContext context) { + return ProviderScope( + overrides: [ + appRuntimeProvider.overrideWithValue(runtime), + maximizePaymentCodeBrightnessProvider.overrideWith( + () => MaximizePaymentCodeBrightnessController.fixed(false), + ), + ], + child: Builder( + builder: (context) { + final host = Theme.of(context); + return Theme( + data: GeekPayTheme.inherit(host), + child: const _GlancePaymentBody(), + ); + }, + ), + ); + } +} + +/// The small surface must never change the main display's brightness. +class _GlancePaymentBody extends ConsumerStatefulWidget { + const _GlancePaymentBody(); + + @override + ConsumerState<_GlancePaymentBody> createState() => + _GlancePaymentBodyState(); +} + +class _GlancePaymentBodyState extends ConsumerState<_GlancePaymentBody> + with WidgetsBindingObserver { + bool _tickerEnabled = true; + bool _foreground = true; + bool _entered = false; + int _revision = 0; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + _foreground = + WidgetsBinding.instance.lifecycleState == null || + WidgetsBinding.instance.lifecycleState == AppLifecycleState.resumed; + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _tickerEnabled = TickerMode.valuesOf(context).enabled; + _scheduleSync(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + _foreground = state == AppLifecycleState.resumed; + _scheduleSync(); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + void _scheduleSync() { + final revision = ++_revision; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) unawaited(_applyActivity(revision)); + }); + } + + Future _applyActivity(int revision) async { + if (!mounted || revision != _revision) return; + final auth = ref.read(authControllerProvider).valueOrNull; + final authenticated = auth?.state == AuthState.authenticated; + final shouldRun = _tickerEnabled && _foreground && authenticated; + if (shouldRun == _entered) return; + final notifier = ref.read(paymentCodeControllerProvider.notifier); + if (shouldRun) { + _entered = true; + try { + await notifier.enter(online: true); + } catch (_) { + _entered = false; + } + } else { + _entered = false; + await notifier.leave(); + } + if (mounted && revision == _revision) setState(() {}); + } + + @override + Widget build(BuildContext context) { + ref.listen(authControllerProvider, (_, __) => _scheduleSync()); + final auth = ref.watch(authControllerProvider); + final card = ref.watch(cardControllerProvider); + final payment = ref.watch(paymentCodeControllerProvider); + + final snapshot = auth.valueOrNull; + if (snapshot == null) { + if (auth.hasError) { + return const GlanceMessage( + icon: Icons.credit_card_off_outlined, + title: '校园卡状态不可用', + subtitle: '请展开手机重试', + ); + } + return const GlanceLoading(label: '正在读取校园卡…'); + } + + switch (snapshot.state) { + case AuthState.signingIn: + return const GlanceLoading(label: '正在登录校园卡…'); + case AuthState.authenticated: + break; + case AuthState.expired: + return const GlanceMessage( + icon: Icons.lock_clock_outlined, + title: '校园卡登录已过期', + subtitle: '请展开手机,在完整 App 中重新登录', + ); + case AuthState.signedOut: + case AuthState.unconfigured: + return const GlanceMessage( + icon: Icons.credit_card_outlined, + title: '校园卡未登录', + subtitle: '请展开手机,在完整 App 中登录', + ); + } + + final cardValue = card.valueOrNull; + final cardBlocked = + cardValue != null && !cardValue.status.permitsPayment; + final balance = cardValue != null && cardValue.detailsAvailable + ? formatMoneyFen(cardValue.balance.value) + : null; + + if (payment.phase == PaymentCodePhase.activationRequired) { + return const GlanceMessage( + icon: Icons.wifi_tethering_error_rounded, + title: '付款码未开通', + subtitle: '请在完整 App 中完成开通', + ); + } + + if (payment.phase == PaymentCodePhase.succeeded && payment.result != null) { + return _PaymentSuccess(result: payment.result!); + } + + final frame = payment.frame; + if (frame == null) { + if (payment.phase == PaymentCodePhase.failed) { + return GlanceMessage( + icon: Icons.qr_code_2_outlined, + title: '付款码加载失败', + subtitle: payment.message, + action: TextButton( + onPressed: () => unawaited(_retry()), + child: const Text('重试'), + ), + ); + } + return const GlanceLoading(label: '正在生成付款码…'); + } + + final disconnected = + payment.connectionState == PaymentConnectionState.disconnected; + final hint = disconnected + ? '网络已断开,轻触重试' + : cardBlocked + ? '校园卡状态异常' + : payment.phase == PaymentCodePhase.refreshing + ? '正在刷新…' + : '轻触二维码刷新'; + + return GlancePaymentCard( + payload: frame.qrPayload, + binaryPayload: frame.rawQrCode.startsWith('5638'), + statusLabel: '在线付款码', + balanceText: balance, + hint: hint, + countdown: PaymentCodeCountdown( + generation: payment.generation, + active: _entered, + style: TextStyle( + fontSize: 10, + color: GpTokens.campusRed.withValues(alpha: 0.62), + ), + ), + onTap: () => unawaited(_refresh()), + ); + } + + Future _retry() async { + if (!_entered) { + await ref + .read(paymentCodeControllerProvider.notifier) + .enter(online: true); + } else { + await ref.read(paymentCodeControllerProvider.notifier).refresh(); + } + } + + Future _refresh() async { + if (!_entered) return; + await ref.read(paymentCodeControllerProvider.notifier).refresh(); + } +} + +class _PaymentSuccess extends StatelessWidget { + const _PaymentSuccess({required this.result}); + + final TransactionResult result; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return Container( + decoration: BoxDecoration( + color: GpTokens.cardCanvas, + borderRadius: BorderRadius.circular(16), + ), + padding: const EdgeInsets.all(16), + child: Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.check_circle, size: 44, color: scheme.tertiary), + const SizedBox(height: 8), + const Text( + '支付成功', + style: TextStyle( + fontSize: 17, + fontWeight: FontWeight.w700, + color: GpTokens.campusRed, + ), + ), + const SizedBox(height: 4), + Text( + formatMoneyFen(result.amount.value, fixedDecimals: true), + style: const TextStyle( + fontSize: 22, + fontWeight: FontWeight.w700, + color: GpTokens.campusRed, + fontFeatures: [FontFeature.tabularFigures()], + ), + ), + if (result.merchantName != null) ...[ + const SizedBox(height: 3), + Text( + result.merchantName!, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 10, + color: GpTokens.campusRed.withValues(alpha: 0.62), + ), + ), + ], + ], + ), + ), + ); + } +} diff --git a/lib/features/glance/presentation/glance_shell.dart b/lib/features/glance/presentation/glance_shell.dart new file mode 100644 index 00000000..7f98815e --- /dev/null +++ b/lib/features/glance/presentation/glance_shell.dart @@ -0,0 +1,464 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../../../models/screen_form_factor.dart'; +import '../../../services/glance_settings_service.dart'; +import '../domain/glance_snapshot.dart'; +import 'cover_glance_layout.dart'; +import 'glance_formatters.dart'; +import 'glance_widgets.dart'; +import 'rear_glance_layout.dart'; + +/// The compact surface shown on the rear screen or the MIX Flip cover. +/// +/// This widget is presentation-only: the live wrapper feeds it a snapshot and +/// the host supplies the payment page, so the same layout can be rendered in +/// tests and in the settings preview without touching services. +class GlanceShell extends StatefulWidget { + const GlanceShell({ + super.key, + required this.surface, + required this.snapshot, + required this.sections, + this.paymentBuilder, + this.initialSection, + this.requestedSection, + this.requestRevision = 0, + this.onPageChanged, + this.onRefresh, + }); + + final GlanceSurface surface; + final GlanceSnapshot snapshot; + final List sections; + final WidgetBuilder? paymentBuilder; + final GlanceSection? initialSection; + final GlanceSection? requestedSection; + final int requestRevision; + final ValueChanged? onPageChanged; + final VoidCallback? onRefresh; + + @override + State createState() => _GlanceShellState(); +} + +class _GlanceShellState extends State { + late PageController _controller; + late int _index; + + List get _sections => [ + for (final section in widget.sections) + if (section != GlanceSection.payment || widget.paymentBuilder != null) + section, + ]; + + @override + void initState() { + super.initState(); + final sections = _sections; + _index = _indexOf(sections, widget.initialSection ?? widget.requestedSection); + _controller = PageController(initialPage: _index); + } + + @override + void didUpdateWidget(GlanceShell oldWidget) { + super.didUpdateWidget(oldWidget); + final sections = _sections; + if (sections.isEmpty) return; + if (_index >= sections.length) { + _index = sections.length - 1; + _jumpTo(_index); + } + if (widget.requestRevision != oldWidget.requestRevision && + widget.requestedSection != null) { + final index = sections.indexOf(widget.requestedSection!); + if (index >= 0) { + _index = index; + _jumpTo(index); + } + } + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + static int _indexOf(List sections, GlanceSection? section) { + if (sections.isEmpty) return 0; + final index = section == null ? -1 : sections.indexOf(section); + return index < 0 ? 0 : index; + } + + void _jumpTo(int index) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted || !_controller.hasClients) return; + if (_controller.page?.round() == index) return; + _controller.jumpToPage(index); + }); + } + + void _select(int index) { + if (index == _index) return; + if (_controller.hasClients) { + unawaited( + _controller.animateToPage( + index, + duration: const Duration(milliseconds: 180), + curve: Curves.easeOutCubic, + ), + ); + } else { + setState(() => _index = index); + } + } + + String _sectionLabel(GlanceSection section) => switch (section) { + GlanceSection.courses => '课程', + GlanceSection.assignments => '作业', + GlanceSection.payment => '消费码', + }; + + Widget _page(BuildContext context, GlanceSection section, bool compact) { + final onRetry = widget.onRefresh; + return switch (section) { + GlanceSection.courses => compact + ? RearCoursesPage(snapshot: widget.snapshot, onRetry: onRetry) + : CoverCoursesPage(snapshot: widget.snapshot, onRetry: onRetry), + GlanceSection.assignments => compact + ? RearAssignmentsPage(snapshot: widget.snapshot, onRetry: onRetry) + : CoverAssignmentsPage(snapshot: widget.snapshot, onRetry: onRetry), + GlanceSection.payment => Padding( + padding: EdgeInsets.fromLTRB( + compact ? 10 : 14, + compact ? 2 : 4, + compact ? 10 : 14, + compact ? 2 : 6, + ), + child: widget.paymentBuilder!(context), + ), + }; + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final background = theme.scaffoldBackgroundColor; + final dark = theme.brightness == Brightness.dark; + final overlay = SystemUiOverlayStyle( + statusBarColor: Colors.transparent, + statusBarIconBrightness: dark ? Brightness.light : Brightness.dark, + statusBarBrightness: dark ? Brightness.dark : Brightness.light, + systemNavigationBarColor: background, + systemNavigationBarDividerColor: Colors.transparent, + systemNavigationBarIconBrightness: + dark ? Brightness.light : Brightness.dark, + systemNavigationBarContrastEnforced: false, + ); + + return AnnotatedRegion( + value: overlay, + child: Scaffold( + backgroundColor: background, + body: SafeArea( + child: LayoutBuilder( + builder: (context, constraints) { + final sections = _sections; + if (sections.isEmpty) { + return const GlanceMessage( + icon: Icons.dashboard_customize_outlined, + title: '未选择显示内容', + subtitle: '请在完整 App 的“背屏与小屏”中开启至少一项', + ); + } + final compact = widget.surface == GlanceSurface.rear && + constraints.maxWidth > constraints.maxHeight; + final wide = widget.surface == GlanceSurface.cover; + final selectedIndex = _index.clamp(0, sections.length - 1); + final section = sections[selectedIndex]; + return Column( + children: [ + _GlanceHeader( + now: widget.snapshot.now, + week: widget.snapshot.week, + inTerm: widget.snapshot.inTerm, + sectionLabel: _sectionLabel(section), + compact: compact, + wide: wide, + onRefresh: widget.onRefresh, + ), + Expanded( + child: PageView.builder( + controller: _controller, + itemCount: sections.length, + onPageChanged: (index) { + setState(() => _index = index); + widget.onPageChanged?.call(sections[index]); + }, + itemBuilder: (context, index) => TickerMode( + enabled: index == selectedIndex, + child: _page(context, sections[index], compact), + ), + ), + ), + _GlanceTabs( + sections: sections, + selectedIndex: selectedIndex, + compact: compact, + labelOf: _sectionLabel, + onSelected: _select, + ), + ], + ); + }, + ), + ), + ), + ); + } +} + +class _GlanceHeader extends StatelessWidget { + const _GlanceHeader({ + required this.now, + required this.week, + required this.inTerm, + required this.sectionLabel, + required this.compact, + required this.wide, + this.onRefresh, + }); + + final DateTime now; + final int? week; + final bool inTerm; + final String sectionLabel; + final bool compact; + final bool wide; + final VoidCallback? onRefresh; + + @override + Widget build(BuildContext context) { + final colors = Theme.of(context).colorScheme; + final date = formatGlanceDateLine( + now: now, + week: week, + inTerm: inTerm, + ); + if (compact) { + return Padding( + padding: const EdgeInsets.fromLTRB(10, 1, 10, 1), + child: Row( + children: [ + Text( + formatGlanceClock(now), + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w700, + color: colors.onSurface, + ), + ), + const SizedBox(width: 6), + Expanded( + child: Text( + date, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 9, + color: colors.onSurfaceVariant, + ), + ), + ), + Text( + sectionLabel, + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + color: colors.onSurfaceVariant, + ), + ), + ], + ), + ); + } + if (wide) { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 8, 2), + child: Row( + children: [ + Text( + formatGlanceClock(now), + style: TextStyle( + fontSize: 24, + height: 1, + fontWeight: FontWeight.w700, + color: colors.onSurface, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Text( + date, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 11, + color: colors.onSurfaceVariant, + ), + ), + ), + const SizedBox(width: 10), + Text( + sectionLabel, + maxLines: 1, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: colors.onSurface, + ), + ), + if (onRefresh != null) + _GlanceRefreshButton(onRefresh: onRefresh!), + ], + ), + ); + } + return Padding( + padding: const EdgeInsets.fromLTRB(14, 8, 8, 3), + child: Row( + children: [ + Text( + formatGlanceClock(now), + style: TextStyle( + fontSize: 22, + height: 1, + fontWeight: FontWeight.w700, + color: colors.onSurface, + ), + ), + const SizedBox(width: 9), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + date, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 10, + color: colors.onSurfaceVariant, + ), + ), + Text( + sectionLabel, + maxLines: 1, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: colors.onSurface, + ), + ), + ], + ), + ), + if (onRefresh != null) + _GlanceRefreshButton(onRefresh: onRefresh!), + ], + ), + ); + } +} + +class _GlanceRefreshButton extends StatelessWidget { + const _GlanceRefreshButton({required this.onRefresh}); + + final VoidCallback onRefresh; + + @override + Widget build(BuildContext context) { + return Semantics( + label: '刷新', + button: true, + child: IconButton( + onPressed: onRefresh, + icon: const Icon(Icons.refresh, size: 18), + padding: EdgeInsets.zero, + constraints: const BoxConstraints.tightFor( + width: 32, + height: 32, + ), + visualDensity: VisualDensity.compact, + ), + ); + } +} + +class _GlanceTabs extends StatelessWidget { + const _GlanceTabs({ + required this.sections, + required this.selectedIndex, + required this.compact, + required this.labelOf, + required this.onSelected, + }); + + final List sections; + final int selectedIndex; + final bool compact; + final String Function(GlanceSection section) labelOf; + final ValueChanged onSelected; + + @override + Widget build(BuildContext context) { + final colors = Theme.of(context).colorScheme; + return Padding( + padding: EdgeInsets.fromLTRB(8, compact ? 1 : 3, 8, compact ? 2 : 5), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + for (var index = 0; index < sections.length; index++) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 3), + child: Semantics( + selected: index == selectedIndex, + button: true, + child: Material( + color: index == selectedIndex + ? colors.primary + : Colors.transparent, + borderRadius: BorderRadius.circular(999), + child: InkWell( + onTap: () => onSelected(index), + borderRadius: BorderRadius.circular(999), + child: Padding( + padding: EdgeInsets.symmetric( + horizontal: compact ? 8 : 11, + vertical: compact ? 3 : 5, + ), + child: Text( + labelOf(sections[index]), + style: TextStyle( + fontSize: compact ? 9 : 11, + fontWeight: index == selectedIndex + ? FontWeight.w600 + : FontWeight.w500, + color: index == selectedIndex + ? colors.onPrimary + : colors.onSurfaceVariant, + ), + ), + ), + ), + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/features/glance/presentation/glance_widgets.dart b/lib/features/glance/presentation/glance_widgets.dart new file mode 100644 index 00000000..1c3290db --- /dev/null +++ b/lib/features/glance/presentation/glance_widgets.dart @@ -0,0 +1,164 @@ +import 'package:flutter/material.dart'; + +import '../domain/glance_snapshot.dart'; + +class GlanceMessage extends StatelessWidget { + const GlanceMessage({ + super.key, + required this.icon, + required this.title, + this.subtitle, + this.compact = false, + this.action, + }); + + final IconData icon; + final String title; + final String? subtitle; + final bool compact; + final Widget? action; + + @override + Widget build(BuildContext context) { + final colors = Theme.of(context).colorScheme; + return Center( + child: Padding( + padding: EdgeInsets.symmetric( + horizontal: compact ? 12 : 24, + vertical: compact ? 6 : 16, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + icon, + size: compact ? 20 : 30, + color: colors.onSurfaceVariant, + ), + SizedBox(height: compact ? 4 : 10), + Text( + title, + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: compact ? 12 : 14, + fontWeight: FontWeight.w600, + color: colors.onSurface, + ), + ), + if (subtitle != null) ...[ + SizedBox(height: compact ? 2 : 6), + Text( + subtitle!, + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: compact ? 10 : 12, + color: colors.onSurfaceVariant, + ), + ), + ], + if (action != null) ...[ + SizedBox(height: compact ? 2 : 8), + action!, + ], + ], + ), + ), + ); + } +} + +class GlanceLoading extends StatelessWidget { + const GlanceLoading({super.key, required this.label, this.compact = false}); + + final String label; + final bool compact; + + @override + Widget build(BuildContext context) { + final colors = Theme.of(context).colorScheme; + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox.square( + dimension: compact ? 18 : 24, + child: CircularProgressIndicator( + strokeWidth: 2, + color: colors.primary, + ), + ), + SizedBox(height: compact ? 6 : 10), + Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: compact ? 10 : 12, + color: colors.onSurfaceVariant, + ), + ), + ], + ), + ); + } +} + +/// Shared empty/loading/error decision for the course and deadline pages. +Widget? glanceUnavailableState( + GlanceSnapshot snapshot, { + required bool courses, + required bool compact, + VoidCallback? onRetry, +}) { + final hasData = courses ? snapshot.hasCourses : snapshot.hasPending; + final loading = courses ? snapshot.scheduleLoading : snapshot.assignmentsLoading; + final error = courses ? snapshot.scheduleError : snapshot.assignmentsError; + if (hasData) return null; + + Widget action() => TextButton( + onPressed: onRetry, + style: TextButton.styleFrom( + minimumSize: Size(compact ? 32 : 44, compact ? 24 : 32), + padding: EdgeInsets.symmetric(horizontal: compact ? 6 : 12), + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + visualDensity: VisualDensity.compact, + ), + child: Text( + '重试', + style: TextStyle(fontSize: compact ? 10 : 12), + ), + ); + + if (!snapshot.loggedIn) { + return GlanceMessage( + icon: Icons.login, + title: '请先在完整 App 登录', + subtitle: '登录后这里会显示${courses ? '今日课程' : '待办作业'}', + compact: compact, + ); + } + if (loading) { + return GlanceLoading( + label: courses ? '正在加载课程…' : '正在加载待办…', + compact: compact, + ); + } + if (error != null) { + return GlanceMessage( + icon: Icons.cloud_off_outlined, + title: courses ? '课程加载失败' : '待办加载失败', + subtitle: error, + compact: compact, + action: onRetry == null ? null : action(), + ); + } + return GlanceMessage( + icon: courses ? Icons.free_breakfast_outlined : Icons.task_alt, + title: courses ? '今天没有课程' : '没有待办事项', + compact: compact, + ); +} diff --git a/lib/features/glance/presentation/live_glance_shell.dart b/lib/features/glance/presentation/live_glance_shell.dart new file mode 100644 index 00000000..a5ca8197 --- /dev/null +++ b/lib/features/glance/presentation/live_glance_shell.dart @@ -0,0 +1,134 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; + +import '../../../models/custom_course.dart'; +import '../../../models/screen_form_factor.dart'; +import '../../../services/assignment_service.dart'; +import '../../../services/auth_service.dart'; +import '../../../services/glance_settings_service.dart'; +import '../../../services/schedule_service.dart'; +import '../../../widgets/app_shell/app_entry_notifier.dart'; +import '../application/glance_snapshot_builder.dart'; +import 'glance_shell.dart'; + +/// Wires the live services into the presentation-only [GlanceShell]. +class LiveGlanceShell extends StatefulWidget { + const LiveGlanceShell({ + super.key, + required this.surface, + required this.settings, + required this.scheduleService, + required this.assignmentService, + required this.authService, + this.paymentBuilder, + this.consumeEntry = true, + }); + + final GlanceSurface surface; + final GlanceSettings settings; + final ScheduleService scheduleService; + final AssignmentService assignmentService; + final AuthService authService; + final WidgetBuilder? paymentBuilder; + final bool consumeEntry; + + @override + State createState() => _LiveGlanceShellState(); +} + +class _LiveGlanceShellState extends State { + Timer? _ticker; + bool _tickerEnabled = true; + GlanceSection? _requested; + int _requestRevision = 0; + + @override + void initState() { + super.initState(); + appShellPendingEcardEntry.addListener(_consumeEntry); + _ticker = Timer.periodic(const Duration(minutes: 1), (_) { + if (mounted) setState(() {}); + }); + WidgetsBinding.instance.addPostFrameCallback((_) => _consumeEntry()); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _tickerEnabled = TickerMode.valuesOf(context).enabled; + } + + @override + void dispose() { + appShellPendingEcardEntry.removeListener(_consumeEntry); + _ticker?.cancel(); + super.dispose(); + } + + void _consumeEntry() { + if (!widget.consumeEntry || !mounted || !_tickerEnabled) return; + final entry = appShellPendingEcardEntry.value; + if (entry == null) return; + appShellPendingEcardEntry.value = null; + if (widget.paymentBuilder == null || + !widget.settings.isEnabled(GlanceSection.payment)) { + return; + } + setState(() { + _requested = GlanceSection.payment; + _requestRevision++; + }); + } + + void _refresh() { + widget.scheduleService.requestFetch(force: true); + unawaited(widget.assignmentService.fetchAssignments()); + } + + @override + Widget build(BuildContext context) { + return ListenableBuilder( + listenable: Listenable.merge([ + widget.scheduleService, + widget.assignmentService, + widget.authService, + ]), + builder: (context, _) { + final schedule = widget.scheduleService; + final assignments = widget.assignmentService; + final now = DateTime.now(); + final week = + teachingWeekOf(now, schedule.termBegin) ?? schedule.currentWeek(); + final pending = assignments.visibleAssignments + .where((item) => !assignments.isCompleted(item) && item.due.isAfter(now)) + .toList(); + final snapshot = GlanceSnapshotBuilder.build( + courseTable: schedule.courseTable, + customCourses: schedule.customCourses, + termBegin: schedule.termBegin, + week: week, + rawAssignments: assignments.assignments, + pendingAssignments: pending, + semesterId: schedule.selectedSemesterId, + now: now, + loggedIn: widget.authService.isLoggedIn, + inTerm: schedule.isTodayInTerm, + scheduleLoading: schedule.loading, + scheduleError: schedule.error, + assignmentsLoading: assignments.loading, + assignmentsError: assignments.error, + ); + return GlanceShell( + surface: widget.surface, + snapshot: snapshot, + sections: widget.settings.sections, + paymentBuilder: widget.paymentBuilder, + requestedSection: _requested, + requestRevision: _requestRevision, + onRefresh: _refresh, + ); + }, + ); + } +} diff --git a/lib/features/glance/presentation/rear_glance_layout.dart b/lib/features/glance/presentation/rear_glance_layout.dart new file mode 100644 index 00000000..62fe3b08 --- /dev/null +++ b/lib/features/glance/presentation/rear_glance_layout.dart @@ -0,0 +1,269 @@ +import 'package:flutter/material.dart'; + +import '../../../models/course.dart'; +import '../domain/glance_snapshot.dart'; +import 'glance_formatters.dart'; +import 'glance_widgets.dart'; + +class RearCoursesPage extends StatelessWidget { + const RearCoursesPage({ + super.key, + required this.snapshot, + this.onRetry, + }); + + final GlanceSnapshot snapshot; + final VoidCallback? onRetry; + + @override + Widget build(BuildContext context) { + final unavailable = glanceUnavailableState( + snapshot, + courses: true, + compact: true, + onRetry: onRetry, + ); + if (unavailable != null) return unavailable; + + final lead = snapshot.leadCourse; + if (lead == null) { + return GlanceMessage( + icon: Icons.nights_stay_outlined, + title: '今天的课已结束', + subtitle: '今天共 ${snapshot.courses.length} 节课', + compact: true, + ); + } + + final scheme = Theme.of(context).colorScheme; + final background = lead.course.color.containerColor(scheme); + final foreground = lead.course.color.onContainerColor(scheme); + final rest = snapshot.activeCourses.length - 1; + + return Padding( + padding: const EdgeInsets.fromLTRB(10, 2, 10, 2), + child: DecoratedBox( + decoration: BoxDecoration( + color: background, + borderRadius: BorderRadius.circular(12), + ), + child: Padding( + padding: const EdgeInsets.fromLTRB(11, 7, 10, 7), + child: Row( + children: [ + Expanded( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text( + _stateLabel(lead.state), + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + color: foreground.withValues(alpha: 0.78), + ), + ), + const SizedBox(width: 6), + Expanded( + child: Text( + formatGlanceCourseTime(lead.course), + textAlign: TextAlign.end, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 10, + color: foreground.withValues(alpha: 0.72), + ), + ), + ), + ], + ), + const SizedBox(height: 3), + Flexible( + child: Text( + lead.course.name, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 18, + height: 1.12, + fontWeight: FontWeight.w700, + color: foreground, + ), + ), + ), + const SizedBox(height: 2), + Text( + lead.course.location.isEmpty + ? '地点待定' + : lead.course.location, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 10, + color: foreground.withValues(alpha: 0.78), + ), + ), + ], + ), + ), + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 5), + decoration: BoxDecoration( + color: foreground.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(8), + ), + child: Text( + rest > 0 ? '之后 $rest 节' : '最后一节', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + color: foreground, + ), + ), + ), + ], + ), + ), + ), + ); + } +} + +class RearAssignmentsPage extends StatelessWidget { + const RearAssignmentsPage({ + super.key, + required this.snapshot, + this.onRetry, + }); + + final GlanceSnapshot snapshot; + final VoidCallback? onRetry; + + @override + Widget build(BuildContext context) { + final unavailable = glanceUnavailableState( + snapshot, + courses: false, + compact: true, + onRetry: onRetry, + ); + if (unavailable != null) return unavailable; + + final item = snapshot.pendingAssignments.first; + final rest = snapshot.pendingAssignments.length - 1; + final scheme = Theme.of(context).colorScheme; + final urgency = _urgencyColor(item.assignment.due, snapshot.now, scheme); + final course = item.assignment.course; + + return Padding( + padding: const EdgeInsets.fromLTRB(10, 2, 10, 2), + child: DecoratedBox( + decoration: BoxDecoration( + color: scheme.surfaceContainerHighest.withValues(alpha: 0.55), + borderRadius: BorderRadius.circular(12), + ), + child: Padding( + padding: const EdgeInsets.fromLTRB(11, 7, 10, 7), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text( + '待办', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + color: urgency, + ), + ), + const Spacer(), + Text( + '${snapshot.pendingAssignments.length} 项', + style: TextStyle( + fontSize: 10, + color: scheme.onSurfaceVariant, + ), + ), + ], + ), + const SizedBox(height: 3), + Flexible( + child: Text( + item.assignment.title, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 17, + height: 1.12, + fontWeight: FontWeight.w700, + color: scheme.onSurface, + ), + ), + ), + const SizedBox(height: 2), + Row( + children: [ + Expanded( + child: Text( + course.isEmpty + ? item.assignment.kind.label + : '$course · ${item.assignment.kind.label}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 10, + color: scheme.onSurfaceVariant, + ), + ), + ), + const SizedBox(width: 6), + Text( + item.dueLabel, + maxLines: 1, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: urgency, + ), + ), + ], + ), + if (rest > 0) + Text( + '还有 $rest 项待办', + maxLines: 1, + style: TextStyle( + fontSize: 10, + color: scheme.onSurfaceVariant, + ), + ), + ], + ), + ), + ), + ); + } +} + +String _stateLabel(GlanceCourseState state) => switch (state) { + GlanceCourseState.ongoing => '正在上课', + GlanceCourseState.soon => '即将开始', + GlanceCourseState.upcoming => '下一节', + GlanceCourseState.past => '已结束', + }; + +Color _urgencyColor(DateTime due, DateTime now, ColorScheme scheme) { + final today = DateTime(now.year, now.month, now.day); + final target = DateTime(due.year, due.month, due.day); + final days = target.difference(today).inDays; + if (days <= 0) return scheme.error; + if (days == 1) return scheme.tertiary; + return scheme.onSurfaceVariant; +} diff --git a/lib/main.dart b/lib/main.dart index f87e697c..f5824dc5 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -19,10 +19,12 @@ import 'services/debug_logger.dart'; import 'services/ecard_bind_service.dart'; import 'services/ecard_widget_service.dart'; import 'services/egate_app_service.dart'; +import 'services/glance_settings_service.dart'; import 'services/http_client.dart'; import 'services/ids/ids_client.dart'; import 'services/oa_gym_service.dart'; import 'services/schedule_service.dart'; +import 'services/screen_form_factor_service.dart'; import 'services/service_provider.dart'; import 'services/storage_service.dart'; import 'services/sync_service.dart'; @@ -32,6 +34,7 @@ import 'services/uni_auth_service.dart'; import 'services/update_service.dart'; import 'widgets/adaptive_feedback.dart'; import 'widgets/app_shell/app_shell.dart'; +import 'widgets/glance/glance_gate.dart'; import 'widgets/privacy_consent.dart'; import 'widgets/update_dialogs.dart'; @@ -66,6 +69,8 @@ void main(List args) async { Future _realMain(SharedPreferences prefs) async { final storageService = StorageService(prefs); + final screenFormFactorService = ScreenFormFactorService(); + final glanceSettings = GlanceSettings(storageService); final debugLogger = DebugLogger()..enabled = storageService.debugMode; final httpClient = LoggingHttpClient(debugLogger); final uniAuthService = UniAuthService(logger: debugLogger); @@ -191,6 +196,8 @@ Future _realMain(SharedPreferences prefs) async { ecardBindService: ecardBindService, ecardWidgetService: ecardWidgetService, deadlineWidgetService: deadlineWidgetService, + screenFormFactorService: screenFormFactorService, + glanceSettings: glanceSettings, ), ); @@ -324,6 +331,8 @@ class TechPieApp extends StatefulWidget { final CampusCardService campusCardService; final EcardBindService ecardBindService; final EcardWidgetService? ecardWidgetService; + final ScreenFormFactorService? screenFormFactorService; + final GlanceSettings? glanceSettings; final DeadlineWidgetService? deadlineWidgetService; const TechPieApp({ @@ -343,6 +352,8 @@ class TechPieApp extends StatefulWidget { required this.campusCardService, required this.ecardBindService, this.ecardWidgetService, + this.screenFormFactorService, + this.glanceSettings, this.deadlineWidgetService, }); @@ -484,19 +495,23 @@ class _TechPieAppState extends State with WidgetsBindingObserver { campusCardService: widget.campusCardService, ecardBindService: widget.ecardBindService, ecardWidgetService: widget.ecardWidgetService, + screenFormFactorService: widget.screenFormFactorService, + glanceSettings: widget.glanceSettings, child: MaterialApp( navigatorKey: _navigatorKey, scaffoldMessengerKey: rootMessengerKey, navigatorObservers: [FeedbackRouteObserver(), _nativeChromeObserver], - builder: (context, child) => AdaptiveFeedbackHost( - key: adaptiveFeedbackHostKey, - child: child ?? const SizedBox.shrink(), + builder: (context, child) => GlanceGate( + child: AdaptiveFeedbackHost( + key: adaptiveFeedbackHostKey, + child: child ?? const SizedBox.shrink(), + ), ), title: 'TechPie', theme: widget.themeService.lightTheme, darkTheme: widget.themeService.darkTheme, themeMode: widget.themeService.themeMode, - home: const PrivacyGate(child: AppShell()), + home: PrivacyGate(onAccepted: () { if (mounted) setState(() {}); }, child: const AppShell()), ), ), ); diff --git a/lib/models/screen_form_factor.dart b/lib/models/screen_form_factor.dart new file mode 100644 index 00000000..3141052a --- /dev/null +++ b/lib/models/screen_form_factor.dart @@ -0,0 +1,115 @@ +import 'package:flutter/foundation.dart'; + +/// The kind of small surface the app is currently rendered on. +enum GlanceSurface { none, cover, rear } + +/// Native description of the screen this activity is attached to. +@immutable +final class ScreenFormFactorInfo { + const ScreenFormFactorInfo({ + required this.isFlipDevice, + required this.isRearDevice, + required this.displayId, + required this.windowWidthPx, + required this.windowHeightPx, + required this.density, + required this.densityDpi, + required this.isDefaultDisplay, + required this.isInMultiWindowMode, + required this.model, + required this.manufacturer, + required this.sdkInt, + }); + + factory ScreenFormFactorInfo.fromMap(Map map) { + bool flag(String key) => map[key] == true; + int integer(String key) { + final value = map[key]; + if (value is num) return value.toInt(); + if (value is String) return int.tryParse(value) ?? 0; + return 0; + } + + double number(String key) { + final value = map[key]; + final parsed = value is num + ? value.toDouble() + : value is String + ? double.tryParse(value) + : null; + return parsed != null && parsed > 0 ? parsed : 1; + } + + String text(String key) => map[key]?.toString() ?? ''; + + return ScreenFormFactorInfo( + isFlipDevice: flag('isFlipDevice'), + isRearDevice: flag('isRearDevice'), + displayId: integer('displayId'), + windowWidthPx: integer('windowWidthPx'), + windowHeightPx: integer('windowHeightPx'), + density: number('density'), + densityDpi: integer('densityDpi'), + isDefaultDisplay: flag('isDefaultDisplay'), + isInMultiWindowMode: flag('isInMultiWindowMode'), + model: text('model'), + manufacturer: text('manufacturer'), + sdkInt: integer('sdkInt'), + ); + } + + final bool isFlipDevice; + final bool isRearDevice; + final int displayId; + final int windowWidthPx; + final int windowHeightPx; + final double density; + final int densityDpi; + final bool isDefaultDisplay; + final bool isInMultiWindowMode; + final String model; + final String manufacturer; + final int sdkInt; + + double get windowWidthDp => windowWidthPx / density; + + double get windowHeightDp => windowHeightPx / density; + + @override + bool operator ==(Object other) => + other is ScreenFormFactorInfo && + other.isFlipDevice == isFlipDevice && + other.isRearDevice == isRearDevice && + other.displayId == displayId && + other.windowWidthPx == windowWidthPx && + other.windowHeightPx == windowHeightPx && + other.density == density && + other.densityDpi == densityDpi && + other.isDefaultDisplay == isDefaultDisplay && + other.isInMultiWindowMode == isInMultiWindowMode && + other.model == model && + other.manufacturer == manufacturer && + other.sdkInt == sdkInt; + + @override + int get hashCode => Object.hash( + isFlipDevice, + isRearDevice, + displayId, + windowWidthPx, + windowHeightPx, + density, + densityDpi, + isDefaultDisplay, + isInMultiWindowMode, + model, + manufacturer, + sdkInt, + ); + + @override + String toString() => + 'ScreenFormFactorInfo(flip: $isFlipDevice, rear: $isRearDevice, ' + 'display: $displayId, ${windowWidthPx}x$windowHeightPx @${density}x, ' + 'multiWindow: $isInMultiWindowMode, $manufacturer $model)'; +} diff --git a/lib/pages/glance_preview_page.dart b/lib/pages/glance_preview_page.dart new file mode 100644 index 00000000..e516c773 --- /dev/null +++ b/lib/pages/glance_preview_page.dart @@ -0,0 +1,144 @@ +import 'package:flutter/material.dart'; + +import '../features/glance/presentation/glance_payment_card.dart'; +import '../features/glance/presentation/live_glance_shell.dart'; +import '../models/screen_form_factor.dart'; +import '../services/service_provider.dart'; +import '../widgets/blurred_app_bar.dart'; + +/// Fixed-size preview so the layouts can be checked on a normal phone. +class GlancePreviewPage extends StatefulWidget { + const GlancePreviewPage({super.key, required this.surface}); + + final GlanceSurface surface; + + @override + State createState() => _GlancePreviewPageState(); +} + +class _GlancePreviewPageState extends State { + late GlanceSurface _surface = widget.surface == GlanceSurface.rear + ? GlanceSurface.rear + : GlanceSurface.cover; + + @override + Widget build(BuildContext context) { + final services = ServiceProvider.of(context); + final settings = services.glanceSettings; + final cover = _surface == GlanceSurface.cover; + final width = cover ? 506.0 : 340.0; + final height = cover ? 439.0 : 210.0; + + return Scaffold( + extendBodyBehindAppBar: true, + appBar: const BlurredAppBar(title: Text('小屏预览')), + body: settings == null + ? const Center(child: Text('当前版本未启用副屏适配')) + : SingleChildScrollView( + padding: EdgeInsets.fromLTRB( + 16, + kToolbarHeight + MediaQuery.viewPaddingOf(context).top + 12, + 16, + 32, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Center( + child: SegmentedButton( + showSelectedIcon: false, + segments: const [ + ButtonSegment( + value: GlanceSurface.cover, + label: Text('外屏'), + icon: Icon(Icons.stay_current_portrait, size: 16), + ), + ButtonSegment( + value: GlanceSurface.rear, + label: Text('背屏'), + icon: Icon(Icons.stay_current_landscape, size: 16), + ), + ], + selected: {_surface}, + onSelectionChanged: (selection) { + if (selection.isEmpty) return; + setState(() => _surface = selection.first); + }, + ), + ), + const SizedBox(height: 10), + Text( + cover + ? 'MIX Flip 外屏 · 1392 × 1208 px(约 506 × 439 dp)' + : '小米 17 Pro 系列背屏 · 340 × 210 dp(904 × 572 / 976 × 596 px)', + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 11, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 12), + Center( + // The cover preview is wider than a phone screen; scale the + // whole 506×439 surface down so the preview keeps the real + // aspect ratio instead of being clamped to the screen width. + child: FittedBox( + fit: BoxFit.scaleDown, + alignment: Alignment.topCenter, + child: Container( + width: width, + height: height, + clipBehavior: Clip.antiAlias, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(cover ? 26 : 14), + border: Border.all( + color: Theme.of( + context, + ).colorScheme.outlineVariant, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.16), + blurRadius: 24, + offset: const Offset(0, 8), + ), + ], + ), + child: MediaQuery( + data: MediaQuery.of(context).copyWith( + size: Size(width, height), + padding: EdgeInsets.zero, + viewPadding: EdgeInsets.zero, + viewInsets: EdgeInsets.zero, + ), + child: LiveGlanceShell( + surface: _surface, + settings: settings, + scheduleService: services.scheduleService, + assignmentService: services.assignmentService, + authService: services.authService, + consumeEntry: false, + paymentBuilder: (_) => + const GlancePaymentPreviewCard(), + ), + ), + ), + ), + ), + const SizedBox(height: 12), + Text( + '预览使用真实课程/作业数据与示例付款码,不会生成真实消费码,' + '也不会消耗离线支付次数。', + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 11, + height: 1.5, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/pages/glance_settings_page.dart b/lib/pages/glance_settings_page.dart new file mode 100644 index 00000000..61aeb293 --- /dev/null +++ b/lib/pages/glance_settings_page.dart @@ -0,0 +1,250 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; + +import '../models/screen_form_factor.dart'; +import '../services/glance_settings_service.dart'; +import '../services/screen_form_factor_service.dart'; +import '../services/service_provider.dart'; +import '../widgets/adaptive_page_navigation.dart'; +import '../widgets/blurred_app_bar.dart'; +import 'glance_preview_page.dart'; + +/// Controls the rear-screen / cover-screen glance and shows what the native +/// probe currently reports, which is the only way to verify the thresholds on +/// a device without one attached to the build machine. +class GlanceSettingsPage extends StatelessWidget { + const GlanceSettingsPage({super.key}); + + @override + Widget build(BuildContext context) { + final services = ServiceProvider.of(context); + final settings = services.glanceSettings; + final formFactor = services.screenFormFactorService; + if (settings == null || formFactor == null) { + return const Scaffold( + appBar: BlurredAppBar(title: Text('背屏与小屏')), + body: Center(child: Text('当前版本未启用副屏适配')), + ); + } + + return Scaffold( + extendBodyBehindAppBar: true, + appBar: const BlurredAppBar(title: Text('背屏与小屏')), + body: ListenableBuilder( + listenable: Listenable.merge([settings, formFactor]), + builder: (context, _) { + final info = formFactor.info; + final surface = classifyGlanceSurface( + logicalSize: MediaQuery.sizeOf(context), + info: info, + enabled: true, + ); + return ListView( + padding: EdgeInsets.fromLTRB( + 0, + kToolbarHeight + MediaQuery.viewPaddingOf(context).top + 12, + 0, + 32, + ), + children: [ + _StatusCard( + surface: surface, + info: info, + onRefresh: () => unawaited(formFactor.refresh()), + ), + const SizedBox(height: 4), + SwitchListTile( + secondary: const Icon(Icons.auto_awesome_outlined), + title: const Text('自动切换到小屏界面'), + subtitle: const Text('在小米背屏或折叠屏外屏上显示精简界面'), + value: settings.enabled, + onChanged: (value) => unawaited(settings.setEnabled(value)), + ), + const Divider(), + _sectionLabel(context, '显示内容'), + for (final section in GlanceSection.values) + SwitchListTile( + secondary: Icon(_sectionIcon(section)), + title: Text(_sectionTitle(section)), + subtitle: Text(_sectionSubtitle(section)), + value: settings.isEnabled(section), + onChanged: settings.isEnabled(section) && + !settings.canDisable(section) + ? null + : (value) => + unawaited(settings.setSection(section, value)), + ), + const Divider(), + _sectionLabel(context, '预览'), + if (info?.isFlipDevice == true) + ListTile( + leading: const Icon(Icons.stay_current_portrait), + title: const Text('外屏预览'), + subtitle: const Text('MIX Flip · 1392 × 1208 px(约 506 × 439 dp)'), + trailing: const Icon(Icons.chevron_right), + onTap: () => unawaited( + pushAdaptivePage( + context, + builder: (_) => const GlancePreviewPage( + surface: GlanceSurface.cover, + ), + ), + ), + ), + if (info?.isRearDevice == true) + ListTile( + leading: const Icon(Icons.stay_current_landscape), + title: const Text('背屏预览'), + subtitle: const Text('小米 17 Pro 系列 · 340 × 210 dp'), + trailing: const Icon(Icons.chevron_right), + onTap: () => unawaited( + pushAdaptivePage( + context, + builder: (_) => const GlancePreviewPage( + surface: GlanceSurface.rear, + ), + ), + ), + ), + const Divider(), + _sectionLabel(context, '说明'), + const Padding( + padding: EdgeInsets.fromLTRB(20, 2, 20, 6), + child: Text( + 'MIX Flip:需在系统「设置 → 外屏 → 应用管理」中添加 TechPie;' + '折叠与展开会保留当前页面。', + style: TextStyle(fontSize: 12, height: 1.5), + ), + ), + const Padding( + padding: EdgeInsets.fromLTRB(20, 0, 20, 6), + child: Text( + '小米背屏:TechPie 是否出现在背屏应用列表由系统控制;' + '本页的预览可在任何设备上检查布局。', + style: TextStyle(fontSize: 12, height: 1.5), + ), + ), + ], + ); + }, + ), + ); + } + + static IconData _sectionIcon(GlanceSection section) => switch (section) { + GlanceSection.courses => Icons.calendar_month_outlined, + GlanceSection.assignments => Icons.assignment_outlined, + GlanceSection.payment => Icons.qr_code_2_outlined, + }; + + static String _sectionTitle(GlanceSection section) => switch (section) { + GlanceSection.courses => '今日课程', + GlanceSection.assignments => '待办作业', + GlanceSection.payment => '消费码', + }; + + static String _sectionSubtitle(GlanceSection section) => switch (section) { + GlanceSection.courses => '显示下一节课与今日剩余课程', + GlanceSection.assignments => '显示最近的待办截止时间', + GlanceSection.payment => '显示在线付款码(不生成离线码)', + }; + + static Widget _sectionLabel(BuildContext context, String label) => Padding( + padding: const EdgeInsets.fromLTRB(20, 14, 20, 4), + child: Text( + label, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ); +} + +class _StatusCard extends StatelessWidget { + const _StatusCard({ + required this.surface, + required this.info, + required this.onRefresh, + }); + + final GlanceSurface surface; + final ScreenFormFactorInfo? info; + final VoidCallback onRefresh; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final (label, icon) = switch (surface) { + GlanceSurface.cover => ('当前:折叠外屏', Icons.stay_current_portrait), + GlanceSurface.rear => ('当前:背屏', Icons.stay_current_landscape), + GlanceSurface.none => ('当前:普通屏幕', Icons.smartphone), + }; + final details = info == null + ? '未读取到屏幕信息' + : '${info!.manufacturer} ${info!.model} · display ${info!.displayId}' + ' · ${info!.windowWidthPx}×${info!.windowHeightPx}px' + ' · ${info!.windowWidthDp.toStringAsFixed(0)}×' + '${info!.windowHeightDp.toStringAsFixed(0)}dp' + ' · ${info!.densityDpi}dpi'; + return Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 4), + child: Container( + padding: const EdgeInsets.fromLTRB(14, 12, 8, 12), + decoration: BoxDecoration( + color: scheme.surfaceContainerHighest.withValues(alpha: 0.55), + borderRadius: BorderRadius.circular(14), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(icon, size: 22, color: scheme.primary), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: scheme.onSurface, + ), + ), + const SizedBox(height: 3), + Text( + details, + style: TextStyle( + fontSize: 11, + height: 1.35, + color: scheme.onSurfaceVariant, + ), + ), + if (surface == GlanceSurface.none && info != null) ...[ + const SizedBox(height: 3), + Text( + '当前设备没有检测到背屏/外屏;可在下方预览。', + style: TextStyle( + fontSize: 11, + color: scheme.onSurfaceVariant, + ), + ), + ], + ], + ), + ), + IconButton( + onPressed: onRefresh, + icon: const Icon(Icons.refresh, size: 18), + tooltip: '重新检测', + visualDensity: VisualDensity.compact, + ), + ], + ), + ), + ); + } +} diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index dabca46e..e08af201 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -37,6 +37,7 @@ import 'debug_log_page.dart'; import 'debug_webview_page.dart'; import 'developer_lab_page.dart'; import 'feedback_page.dart'; +import 'glance_settings_page.dart'; import 'sync_settings_page.dart'; import 'third_party_accounts_page.dart'; import 'third_party_bind_page.dart'; @@ -379,6 +380,19 @@ class _SettingsPageState extends State { ), ), + if (sp.glanceSettings != null && (sp.screenFormFactorService?.supported ?? false)) + ListTile( + leading: const Icon(Icons.flip_outlined), + title: const Text('外屏与背屏'), + subtitle: const Text('课程、截止日期和付款码'), + trailing: const Icon(Icons.chevron_right), + onTap: () => unawaited( + pushAdaptivePage(context, + builder: (_) => const GlanceSettingsPage(), + ), + ), + ), + // Appearance section _sectionHeader(theme, 'Appearance'), if (useIosChrome) diff --git a/lib/services/glance_settings_service.dart b/lib/services/glance_settings_service.dart new file mode 100644 index 00000000..c94ec972 --- /dev/null +++ b/lib/services/glance_settings_service.dart @@ -0,0 +1,65 @@ +import 'package:flutter/foundation.dart'; + +import 'storage_service.dart'; + +enum GlanceSection { courses, assignments, payment } + +/// User preferences for the rear-screen / cover-screen glance. +class GlanceSettings extends ChangeNotifier { + GlanceSettings(this._storage) + : _enabled = _storage.glanceEnabled, + _courses = _storage.glanceShowCourses, + _assignments = _storage.glanceShowAssignments, + _payment = _storage.glanceShowPayment; + + final StorageService _storage; + + bool _enabled; + bool _courses; + bool _assignments; + bool _payment; + + bool get enabled => _enabled; + + bool isEnabled(GlanceSection section) => switch (section) { + GlanceSection.courses => _courses, + GlanceSection.assignments => _assignments, + GlanceSection.payment => _payment, + }; + + List get sections => [ + if (_courses) GlanceSection.courses, + if (_assignments) GlanceSection.assignments, + if (_payment) GlanceSection.payment, + ]; + + bool get hasSections => _courses || _assignments || _payment; + + /// The last enabled section cannot be turned off: the glance would otherwise + /// be an empty surface with no way back. + bool canDisable(GlanceSection section) => + !isEnabled(section) || sections.length > 1; + + Future setEnabled(bool value) async { + if (_enabled == value) return; + _enabled = value; + notifyListeners(); + await _storage.setGlanceEnabled(value); + } + + Future setSection(GlanceSection section, bool value) async { + if (isEnabled(section) == value) return; + if (!value && !canDisable(section)) return; + if (section == GlanceSection.courses) { + _courses = value; + await _storage.setGlanceShowCourses(value); + } else if (section == GlanceSection.assignments) { + _assignments = value; + await _storage.setGlanceShowAssignments(value); + } else { + _payment = value; + await _storage.setGlanceShowPayment(value); + } + notifyListeners(); + } +} diff --git a/lib/services/schedule_timeline_service.dart b/lib/services/schedule_timeline_service.dart new file mode 100644 index 00000000..74ddd600 --- /dev/null +++ b/lib/services/schedule_timeline_service.dart @@ -0,0 +1,60 @@ +import '../models/assignment.dart'; +import '../models/course.dart'; +import '../models/course_table.dart'; +import '../models/custom_course.dart'; +import '../models/exam_course.dart'; + +/// 今日课程合并与状态判定,首页与手环快照共用同一口径。 +class ScheduleTimeline { + /// 合并 EAMS / 自定义 / 考试课程,取 [now] 当天并按开始时间排序。 + static List todayCourses({ + required CourseTable? table, + required List customCourses, + required int? week, + required DateTime? termBegin, + List assignments = const [], + String? semesterId, + required DateTime now, + }) { + final periods = table == null + ? defaultPeriods + : table.periods.map((p) => p.toPeriod()).toList(); + final merged = withExamCourses( + withCustomCourses( + eamsToDisplayCourses( + table?.courses ?? const [], + week, + timetablePeriods: periods, + ), + customCourses, + week, + termBegin, + periods: periods, + ), + examsForSemester(assignments, semesterId), + week, + termBegin, + periods: periods, + ); + return merged + .where((course) => course.dayOfWeek == now.weekday && course.occursOn(now)) + .toList() + ..sort((a, b) => a.gridStart.compareTo(b.gridStart)); + } + + /// past / ongoing / soon(15 分钟内开课)/ upcoming,与首页判定一致。 + /// + /// [end] is exclusive: at the minute a class ends it is over, the same way + /// [buildIslandFrame] reads it. An inclusive bound left the class on screen + /// as "上课中" for one more minute on every surface. + static String courseState(Course course, DateTime now) { + final nowMinutes = now.hour * 60 + now.minute; + final start = parseClockMinutes(course.startTime); + final end = parseClockMinutes(course.endTime); + if (start == null || end == null) return 'upcoming'; + if (nowMinutes >= end) return 'past'; + if (nowMinutes >= start) return 'ongoing'; + final diff = start - nowMinutes; + return diff > 0 && diff <= 15 ? 'soon' : 'upcoming'; + } +} diff --git a/lib/services/screen_form_factor_service.dart b/lib/services/screen_form_factor_service.dart new file mode 100644 index 00000000..780b4801 --- /dev/null +++ b/lib/services/screen_form_factor_service.dart @@ -0,0 +1,118 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +import '../models/screen_form_factor.dart'; +import '../utils/platform.dart'; + +/// Reports the display the activity is on and classifies it as a small surface. +/// +/// The channel is Android-only; every other platform simply reports [none]. +class ScreenFormFactorService extends ChangeNotifier { + ScreenFormFactorService({ + Future Function()? loader, + bool? androidOverride, + }) : _loader = loader ?? _loadFromChannel, + _android = androidOverride ?? isAndroid(); + + static const MethodChannel _channel = MethodChannel( + 'techpie/screen_form_factor', + ); + + final Future Function() _loader; + final bool _android; + + ScreenFormFactorInfo? _info; + bool _inFlight = false; + bool _refreshQueued = false; + bool _disposed = false; + + ScreenFormFactorInfo? get info => _info; + + bool get supported => _android; + + Future initialize() => refresh(); + + Future refresh() async { + if (!_android || _disposed) return; + if (_inFlight) { + _refreshQueued = true; + return; + } + _inFlight = true; + try { + final next = await _loadWithRetry(); + if (_disposed || next == null || next == _info) return; + _info = next; + notifyListeners(); + } finally { + _inFlight = false; + if (_refreshQueued && !_disposed) { + _refreshQueued = false; + unawaited(refresh()); + } + } + } + + Future _loadWithRetry() async { + for (var attempt = 0; attempt < 2; attempt++) { + try { + return await _loader().timeout(const Duration(seconds: 2)); + } on MissingPluginException { + if (attempt == 1) return null; + await Future.delayed(const Duration(milliseconds: 150)); + } on TimeoutException { + return null; + } catch (_) { + return null; + } + } + return null; + } + + static Future _loadFromChannel() async { + final map = await _channel.invokeMapMethod('info'); + if (map == null) return null; + return ScreenFormFactorInfo.fromMap(map); + } + + @override + void dispose() { + _disposed = true; + super.dispose(); + } +} + +/// Pure classification, kept free of platform checks so it can be unit-tested. +/// +/// - The rear screen is a secondary display (`displayId != 0`). The size +/// fallback covers HyperOS builds where the reflection probe is unavailable. +/// - The MIX Flip cover shares display 0 with the inner screen, so the window +/// size is the signal: the 4.01" panel is 1392x1208 px, a wide near-square +/// window of about 506x439 dp. The inner screen is about 1059x445 dp in +/// landscape, so its width is the separator: the cover is wider than tall +/// but no wider than [600] dp, while the unfolded inner screen is much wider. +GlanceSurface classifyGlanceSurface({ + required Size logicalSize, + required ScreenFormFactorInfo? info, + required bool enabled, +}) { + if (!enabled || info == null) return GlanceSurface.none; + final width = logicalSize.width; + final height = logicalSize.height; + if (width <= 0 || height <= 0) return GlanceSurface.none; + + final secondary = info.displayId != 0; + if (info.isRearDevice && secondary) return GlanceSurface.rear; + if (secondary && width > height && height <= 320) return GlanceSurface.rear; + if (info.isFlipDevice && + !secondary && + width >= 400 && + width <= 600 && + height <= 600 && + width > height) { + return GlanceSurface.cover; + } + return GlanceSurface.none; +} diff --git a/lib/services/service_provider.dart b/lib/services/service_provider.dart index a166d008..da134c09 100644 --- a/lib/services/service_provider.dart +++ b/lib/services/service_provider.dart @@ -7,8 +7,10 @@ import 'debug_logger.dart'; import 'ecard_bind_service.dart'; import 'ecard_widget_service.dart'; import 'egate_app_service.dart'; +import 'glance_settings_service.dart'; import 'oa_gym_service.dart'; import 'schedule_service.dart'; +import 'screen_form_factor_service.dart'; import 'storage_service.dart'; import 'sync_service.dart'; import 'theme_service.dart'; @@ -32,6 +34,8 @@ class ServiceProvider extends InheritedWidget { final CampusCardService campusCardService; final EcardBindService ecardBindService; final EcardWidgetService? ecardWidgetService; + final ScreenFormFactorService? screenFormFactorService; + final GlanceSettings? glanceSettings; const ServiceProvider({ super.key, @@ -50,6 +54,8 @@ class ServiceProvider extends InheritedWidget { required this.campusCardService, required this.ecardBindService, this.ecardWidgetService, + this.screenFormFactorService, + this.glanceSettings, required super.child, }); @@ -62,6 +68,8 @@ class ServiceProvider extends InheritedWidget { @override bool updateShouldNotify(ServiceProvider oldWidget) => + screenFormFactorService != oldWidget.screenFormFactorService || + glanceSettings != oldWidget.glanceSettings || authService != oldWidget.authService || debugLogger != oldWidget.debugLogger || storageService != oldWidget.storageService || diff --git a/lib/services/storage_service.dart b/lib/services/storage_service.dart index 7c4e2bab..88285db1 100644 --- a/lib/services/storage_service.dart +++ b/lib/services/storage_service.dart @@ -44,6 +44,26 @@ class StorageService { String? get campusWebOwner => _prefs.getString('campus_web_owner'); Future setCampusWebOwner(String owner) => _prefs.setString('campus_web_owner', owner); + // 背屏 / 折叠外屏的精简界面设置。 + bool get glanceEnabled => _prefs.getBool('glance_enabled') ?? true; + Future setGlanceEnabled(bool value) => + _prefs.setBool('glance_enabled', value); + + bool get glanceShowCourses => + _prefs.getBool('glance_show_courses') ?? true; + Future setGlanceShowCourses(bool value) => + _prefs.setBool('glance_show_courses', value); + + bool get glanceShowAssignments => + _prefs.getBool('glance_show_assignments') ?? true; + Future setGlanceShowAssignments(bool value) => + _prefs.setBool('glance_show_assignments', value); + + bool get glanceShowPayment => + _prefs.getBool('glance_show_payment') ?? true; + Future setGlanceShowPayment(bool value) => + _prefs.setBool('glance_show_payment', value); + // Secure session storage Future saveSession(UserSession session) async { await _secure.write(key: _sessionKey, value: jsonEncode(session.toJson())); diff --git a/lib/widgets/app_shell/app_entry_notifier.dart b/lib/widgets/app_shell/app_entry_notifier.dart new file mode 100644 index 00000000..4ab2217a --- /dev/null +++ b/lib/widgets/app_shell/app_entry_notifier.dart @@ -0,0 +1,11 @@ +import 'package:flutter/foundation.dart'; + +import '../../features/campus_card/app/app_providers.dart'; + +/// A campus-card entry the host asked for — a home-screen widget tap, a +/// shortcut, a `techpie://ecard/pay` link — that has not been shown yet. +/// +/// The shell and the glance surface both observe it; whichever is on screen +/// consumes it exactly once. It lives outside `app_shell.dart` so the glance +/// does not have to import the shell implementation. +final appShellPendingEcardEntry = ValueNotifier(null); diff --git a/lib/widgets/app_shell/app_shell.dart b/lib/widgets/app_shell/app_shell.dart index 7b244bd7..b5a9487f 100644 --- a/lib/widgets/app_shell/app_shell.dart +++ b/lib/widgets/app_shell/app_shell.dart @@ -3,7 +3,6 @@ import 'dart:async'; import 'package:animations/animations.dart'; import 'package:flutter/material.dart'; -import '../../features/campus_card/app/app_providers.dart'; import '../../pages/assignments_page.dart'; import '../../pages/campus_card_page.dart'; import '../../pages/home_page.dart'; @@ -12,10 +11,14 @@ import '../../pages/settings_page.dart'; import '../../utils/adaptive_layout.dart'; import '../../utils/platform.dart'; import '../../widgets/adaptive_page_navigation.dart'; +import '../glance/glance_active_scope.dart'; import 'app_destination.dart'; +import 'app_entry_notifier.dart'; import 'desktop/desktop_shell.dart'; import 'mobile_shell.dart'; +export 'app_entry_notifier.dart'; + /// A campus-card entry the host asked for — a home-screen widget tap, a /// shortcut, a `techpie://ecard/pay` link — that has not been shown yet. /// @@ -24,7 +27,7 @@ import 'mobile_shell.dart'; /// tab the user left the app on — or the selected destination on a wide /// window, and on the root navigator otherwise. A value set before the shell /// mounts waits for it, which is what a cold start needs. -final appShellPendingEcardEntry = ValueNotifier(null); +// Shared with the glance host through app_entry_notifier.dart. final appShellPendingDeadlines = ValueNotifier(false); class AppShell extends StatefulWidget { @@ -140,6 +143,7 @@ class _AppShellState extends State { void _showPendingEcardEntry() { final entry = appShellPendingEcardEntry.value; if (entry == null || !mounted) return; + if (GlanceActiveScope.isActive(context)) return; appShellPendingEcardEntry.value = null; // Login and playback pages can cover the entire tab shell: the code then // opens above that page, and back returns to it. diff --git a/lib/widgets/glance/glance_active_scope.dart b/lib/widgets/glance/glance_active_scope.dart new file mode 100644 index 00000000..3d5e88ef --- /dev/null +++ b/lib/widgets/glance/glance_active_scope.dart @@ -0,0 +1,27 @@ +import 'package:flutter/widgets.dart'; + +/// Marks the full app subtree as hidden behind the glance surface. +/// +/// The shell reads this from an event handler (a pending eCard entry), where +/// registering an inherited dependency is not appropriate, so [isActive] is a +/// non-subscribing lookup. +class GlanceActiveScope extends InheritedWidget { + const GlanceActiveScope({ + super.key, + required this.active, + required super.child, + }); + + final bool active; + + static GlanceActiveScope? maybeOf(BuildContext context) => + context.dependOnInheritedWidgetOfExactType(); + + static bool isActive(BuildContext context) => + context.getInheritedWidgetOfExactType()?.active ?? + false; + + @override + bool updateShouldNotify(GlanceActiveScope oldWidget) => + oldWidget.active != active; +} diff --git a/lib/widgets/glance/glance_gate.dart b/lib/widgets/glance/glance_gate.dart new file mode 100644 index 00000000..ff07418b --- /dev/null +++ b/lib/widgets/glance/glance_gate.dart @@ -0,0 +1,148 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +import '../../features/glance/presentation/glance_payment_view.dart'; +import '../../features/glance/presentation/live_glance_shell.dart'; +import '../../models/screen_form_factor.dart'; +import '../../services/glance_settings_service.dart'; +import '../../services/screen_form_factor_service.dart'; +import '../../services/service_provider.dart'; +import 'glance_active_scope.dart'; + +/// Chooses between the full app and the compact glance, keeping both alive. +/// +/// Mounted from `MaterialApp.builder`, so it hides the whole navigator — +/// including routes, dialogs and snackbars — when the app is on a rear/cover +/// screen. The hidden navigator is not disposed, which is what makes fold and +/// unfold continuous. +class GlanceGate extends StatefulWidget { + const GlanceGate({super.key, required this.child}); + + final Widget child; + + @override + State createState() => _GlanceGateState(); +} + +class _GlanceGateState extends State with WidgetsBindingObserver { + ScreenFormFactorService? _service; + Timer? _refreshDebounce; + bool _glanceMounted = false; + bool _wasActive = false; + GlanceSurface? _lastSurface; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + final services = ServiceProvider.of(context); + _service = services.screenFormFactorService; + final service = _service; + if (service != null && service.info == null) { + unawaited(service.initialize()); + } + } + + @override + void didChangeMetrics() { + _refreshDebounce?.cancel(); + _refreshDebounce = Timer(const Duration(milliseconds: 100), () { + final service = _service; + if (service != null) unawaited(service.refresh()); + }); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + final service = _service; + if (state == AppLifecycleState.resumed && service != null) { + unawaited(service.refresh()); + } + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + _refreshDebounce?.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final services = ServiceProvider.of(context); + final service = services.screenFormFactorService; + final settings = services.glanceSettings; + if (service == null || settings == null) return widget.child; + + return ListenableBuilder( + listenable: Listenable.merge([service, settings]), + builder: (context, _) { + final size = MediaQuery.sizeOf(context); + final surface = classifyGlanceSurface( + logicalSize: size, + info: service.info, + enabled: settings.enabled, + ); + final active = services.storageService.privacyAccepted && + surface != GlanceSurface.none && settings.hasSections; + if (active) _glanceMounted = true; + + if (kDebugMode && surface != _lastSurface) { + _lastSurface = surface; + debugPrint('[glance] surface=$surface info=${service.info}'); + } + if (active != _wasActive) { + _wasActive = active; + if (active) { + WidgetsBinding.instance.addPostFrameCallback((_) { + FocusManager.instance.primaryFocus?.unfocus(); + }); + } + } + + final full = ExcludeFocus( + excluding: active, + child: GlanceActiveScope(active: active, child: widget.child), + ); + return Stack( + fit: StackFit.expand, + children: [ + Offstage( + offstage: active, + child: TickerMode(enabled: !active, child: full), + ), + if (_glanceMounted) + Offstage( + offstage: !active, + child: TickerMode( + enabled: active, + child: LiveGlanceShell( + surface: surface == GlanceSurface.none + ? GlanceSurface.cover + : surface, + settings: settings, + scheduleService: services.scheduleService, + assignmentService: services.assignmentService, + authService: services.authService, + paymentBuilder: + settings.isEnabled(GlanceSection.payment) + ? (context) => GlancePaymentView( + runtime: services.campusCardService.runtime, + ) + : null, + ), + ), + ), + ], + ); + }, + ); + } +} diff --git a/lib/widgets/privacy_consent.dart b/lib/widgets/privacy_consent.dart index 198e4c71..aa02ac0c 100644 --- a/lib/widgets/privacy_consent.dart +++ b/lib/widgets/privacy_consent.dart @@ -22,9 +22,10 @@ Future openPrivacyPolicy() => launchUrl( /// behind it may run before the answer, and «not now» has to leave the user with /// something readable instead of a dead screen. class PrivacyGate extends StatefulWidget { - const PrivacyGate({super.key, required this.child}); + const PrivacyGate({super.key, required this.child, this.onAccepted}); final Widget child; + final VoidCallback? onAccepted; @override State createState() => _PrivacyGateState(); @@ -33,7 +34,9 @@ class PrivacyGate extends StatefulWidget { class _PrivacyGateState extends State { Future _accept() async { await ServiceProvider.of(context).storageService.setPrivacyAccepted(true); - if (mounted) setState(() {}); + if (!mounted) return; + setState(() {}); + widget.onAccepted?.call(); } @override diff --git a/test/glance/glance_gate_test.dart b/test/glance/glance_gate_test.dart new file mode 100644 index 00000000..9b8d5e16 --- /dev/null +++ b/test/glance/glance_gate_test.dart @@ -0,0 +1,191 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:techpie/features/campus_card/app/app_providers.dart'; +import 'package:techpie/features/campus_card/app/app_runtime.dart'; +import 'package:techpie/features/campus_card/app/demo_runtime_factory.dart'; +import 'package:techpie/features/campus_card/data/mock/in_memory_ports.dart'; +import 'package:techpie/features/campus_card/domain/models/auth_models.dart'; +import 'package:techpie/features/glance/presentation/glance_shell.dart'; +import 'package:techpie/main.dart'; +import 'package:techpie/models/screen_form_factor.dart'; +import 'package:techpie/pages/campus_card_page.dart'; +import 'package:techpie/services/assignment_service.dart'; +import 'package:techpie/services/auth_service.dart'; +import 'package:techpie/services/campus_card_service.dart'; +import 'package:techpie/services/debug_logger.dart'; +import 'package:techpie/services/ecard_bind_service.dart'; +import 'package:techpie/services/egate_app_service.dart'; +import 'package:techpie/services/glance_settings_service.dart'; +import 'package:techpie/services/http_client.dart'; +import 'package:techpie/services/oa_gym_service.dart'; +import 'package:techpie/services/schedule_service.dart'; +import 'package:techpie/services/screen_form_factor_service.dart'; +import 'package:techpie/services/storage_service.dart'; +import 'package:techpie/services/sync_service.dart'; +import 'package:techpie/services/theme_service.dart'; +import 'package:techpie/services/third_party_auth_service.dart'; +import 'package:techpie/services/uni_auth_service.dart'; +import 'package:techpie/services/update_service.dart'; +import 'package:techpie/widgets/app_shell/app_shell.dart'; + +const _flipInfo = ScreenFormFactorInfo( + isFlipDevice: true, + isRearDevice: false, + displayId: 0, + windowWidthPx: 809, + windowHeightPx: 1392, + density: 2.75, + densityDpi: 440, + isDefaultDisplay: true, + isInMultiWindowMode: false, + model: 'MIX Flip', + manufacturer: 'Xiaomi', + sdkInt: 36, +); + +Future _pumpApp( + WidgetTester tester, { + required Size size, + AppRuntime? runtime, + bool privacyAccepted = true, +}) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + SharedPreferences.setMockInitialValues({'privacy_accepted_v1': privacyAccepted}); + final prefs = await SharedPreferences.getInstance(); + final storage = StorageService(prefs); + final logger = DebugLogger(); + final http = LoggingHttpClient(logger); + final uniAuth = UniAuthService(); + final auth = AuthService(storage, http, uniAuth); + final theme = ThemeService(storage); + final tpAuth = ThirdPartyAuthService(storage, http); + final schedule = ScheduleService(storage, http, auth, tpAuth); + final assignments = AssignmentService(storage, http, auth, tpAuth, schedule); + final formFactor = ScreenFormFactorService( + loader: () async => _flipInfo, + androidOverride: true, + ); + await formFactor.refresh(); + final glanceSettings = GlanceSettings(storage); + + await tester.pumpWidget( + TechPieApp( + authService: auth, + debugLogger: logger, + storageService: storage, + themeService: theme, + scheduleService: schedule, + assignmentService: assignments, + thirdPartyAuthService: tpAuth, + oaGymService: OaGymService(auth, storage, tpAuth), + egateAppService: EgateAppService(auth, storage, tpAuth), + uniAuthService: uniAuth, + syncService: SyncService(auth, tpAuth, storage), + updateService: UpdateService(), + ecardBindService: EcardBindService(), + campusCardService: runtime == null + ? CampusCardService.withStore(InMemorySecureCredentialStore()) + : CampusCardService.withStore( + InMemorySecureCredentialStore(), + runtimeFactory: () => runtime, + ), + screenFormFactorService: formFactor, + glanceSettings: glanceSettings, + ), + ); + await tester.pumpAndSettle(); +} + +Future _close(WidgetTester tester, [AppRuntime? runtime]) async { + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + await runtime?.dispose(); +} + +void main() { + testWidgets('cover waits for privacy consent before showing campus data', (tester) async { + await _pumpApp(tester, size: const Size(506, 439), privacyAccepted: false); + expect(find.text('隐私政策'), findsOneWidget); + expect(find.byType(GlanceShell), findsNothing); + + await tester.tap(find.text('同意并继续')); + await tester.pumpAndSettle(); + expect(find.text('隐私政策'), findsNothing); + expect(find.byType(GlanceShell), findsOneWidget); + await _close(tester); + }); + + testWidgets('a flip cover shows the glance and hides the full app', ( + tester, + ) async { + await _pumpApp(tester, size: const Size(506, 439)); + + expect(find.byType(GlanceShell), findsOneWidget); + expect(find.byType(AppShell), findsNothing); + expect(find.text('请先在完整 App 登录'), findsOneWidget); + + await _close(tester); + }); + + testWidgets('the inner screen keeps the full app', (tester) async { + await _pumpApp(tester, size: const Size(390, 844)); + + expect(find.byType(AppShell), findsOneWidget); + expect(find.byType(GlanceShell), findsNothing); + + await _close(tester); + }); + + testWidgets('fold and unfold preserve the selected settings tab', ( + tester, + ) async { + await _pumpApp(tester, size: const Size(390, 844)); + await tester.tap(find.text('Settings').first); + await tester.pumpAndSettle(); + expect(find.text('Account'), findsOneWidget); + + tester.view.physicalSize = const Size(506, 439); + await tester.pumpAndSettle(); + expect(find.byType(GlanceShell), findsOneWidget); + expect(find.text('Account'), findsNothing); + + tester.view.physicalSize = const Size(390, 844); + await tester.pumpAndSettle(); + expect(find.byType(AppShell), findsOneWidget); + expect(find.text('Account'), findsOneWidget); + + await _close(tester); + }); + + testWidgets('an eCard tap is consumed by the glance, not the hidden shell', ( + tester, + ) async { + final runtime = await buildDemoRuntime(); + await runtime.auth.signIn(const DemoAuthCredential()); + await _pumpApp( + tester, + size: const Size(506, 439), + runtime: runtime, + ); + + appShellPendingEcardEntry.value = CampusCardEntry.paymentCode; + for (var i = 0; i < 40; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + + expect(appShellPendingEcardEntry.value, isNull); + expect( + find.byType(CampusCardPage, skipOffstage: false), + findsNothing, + ); + expect(find.byKey(const Key('glance-payment-qr')), findsOneWidget); + expect(find.text('在线付款码'), findsOneWidget); + + await _close(tester, runtime); + }); +} diff --git a/test/glance/glance_payment_view_test.dart b/test/glance/glance_payment_view_test.dart new file mode 100644 index 00000000..8f42f42c --- /dev/null +++ b/test/glance/glance_payment_view_test.dart @@ -0,0 +1,93 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:techpie/features/campus_card/app/app_runtime.dart'; +import 'package:techpie/features/campus_card/app/demo_runtime_factory.dart'; +import 'package:techpie/features/campus_card/domain/models/auth_models.dart'; +import 'package:techpie/features/glance/presentation/glance_payment_view.dart'; + +Future _pumpView(WidgetTester tester, AppRuntime runtime) async { + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(useMaterial3: true), + home: Scaffold( + body: Center( + child: SizedBox( + width: 294, + height: 420, + child: GlancePaymentView(runtime: runtime), + ), + ), + ), + ), + ); + for (var i = 0; i < 30; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } +} + +void main() { + late AppRuntime runtime; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + runtime = await buildDemoRuntime(); + }); + + tearDown(() async { + await runtime.dispose(); + }); + + testWidgets('signed-in glance shows an online QR', (tester) async { + await runtime.auth.signIn(const DemoAuthCredential()); + await _pumpView(tester, runtime); + + expect(find.byKey(const Key('glance-payment-qr')), findsOneWidget); + expect(find.text('在线付款码'), findsOneWidget); + + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + }); + + testWidgets('signed-out glance asks the user to open the full app', ( + tester, + ) async { + await _pumpView(tester, runtime); + + expect(find.text('校园卡未登录'), findsOneWidget); + expect(find.byKey(const Key('glance-payment-qr')), findsNothing); + + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + }); + + testWidgets('rear-sized landscape card renders the QR without overflow', ( + tester, + ) async { + await runtime.auth.signIn(const DemoAuthCredential()); + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(useMaterial3: true), + home: Scaffold( + body: Center( + child: SizedBox( + width: 320, + height: 150, + child: GlancePaymentView(runtime: runtime), + ), + ), + ), + ), + ); + for (var i = 0; i < 30; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + + expect(find.byKey(const Key('glance-payment-qr')), findsOneWidget); + expect(find.text('在线付款码'), findsOneWidget); + expect(tester.takeException(), isNull); + + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + }); +} diff --git a/test/glance/glance_shell_test.dart b/test/glance/glance_shell_test.dart new file mode 100644 index 00000000..880f3e05 --- /dev/null +++ b/test/glance/glance_shell_test.dart @@ -0,0 +1,359 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:techpie/features/glance/domain/glance_snapshot.dart'; +import 'package:techpie/features/glance/presentation/glance_payment_card.dart'; +import 'package:techpie/features/glance/presentation/glance_shell.dart'; +import 'package:techpie/models/assignment.dart'; +import 'package:techpie/models/course.dart'; +import 'package:techpie/models/screen_form_factor.dart'; +import 'package:techpie/services/glance_settings_service.dart'; + +final _now = DateTime(2026, 10, 26, 10, 0); + +Course _course( + String name, + String start, + String end, + CourseColor color, { + String location = 'A101', +}) { + return Course( + name: name, + location: location, + dayOfWeek: _now.weekday, + color: color, + placement: CoursePlacement( + startPeriod: 1, + endPeriod: 1, + gridStart: 0, + gridEnd: 1, + usesCustomTime: true, + startTime: start, + endTime: end, + label: '$start\n$end', + ), + ); +} + +GlanceSnapshot _snapshot({ + bool loggedIn = true, + List? courses, + List? assignments, +}) { + return GlanceSnapshot( + now: _now, + week: 9, + inTerm: true, + loggedIn: loggedIn, + courses: courses ?? + [ + GlanceCourse( + course: _course('高等数学', '10:00', '10:45', CourseColor.primary), + state: GlanceCourseState.ongoing, + ), + GlanceCourse( + course: _course('大学物理', '14:00', '14:45', CourseColor.secondary), + state: GlanceCourseState.upcoming, + ), + ], + pendingAssignments: assignments ?? + [ + GlanceAssignment( + assignment: Assignment( + id: 'a1', + platform: 'test', + title: '提交实验报告', + course: '大学物理', + due: _now.add(const Duration(days: 1)), + ), + dueLabel: '明天 23:59', + ), + ], + scheduleLoading: false, + scheduleError: null, + assignmentsLoading: false, + assignmentsError: null, + ); +} + +GlanceSnapshot _denseSnapshot() { + const names = [ + '高等数学(微积分)与线性代数综合', + '大学物理实验', + '线性代数', + '体育', + '马克思主义基本原理', + '大学英语视听说', + '程序设计基础', + ]; + const locations = [ + '理科楼 A101 阶梯教室', + '理科楼 B203', + '教学楼 C302', + '东操场', + '文科楼 D401', + '外语楼 E102', + '机房 F501', + ]; + const colors = [ + CourseColor.primary, + CourseColor.secondary, + CourseColor.tertiary, + CourseColor.green, + CourseColor.orange, + CourseColor.pink, + CourseColor.error, + ]; + final courses = [ + for (var index = 0; index < names.length; index++) + GlanceCourse( + course: _course( + names[index], + '${(8 + index).toString().padLeft(2, '0')}:00', + '${(9 + index).toString().padLeft(2, '0')}:35', + colors[index], + location: locations[index], + ), + state: index == 0 + ? GlanceCourseState.ongoing + : GlanceCourseState.upcoming, + ), + ]; + final assignments = [ + for (var index = 0; index < 5; index++) + GlanceAssignment( + assignment: Assignment( + id: 'dense-$index', + platform: 'test', + title: index == 0 + ? '完成大学物理实验报告并提交完整数据分析与误差讨论' + : '第 ${index + 1} 章课后习题与在线测验', + course: index == 0 ? '大学物理实验' : '高等数学', + due: _now.add(Duration(days: index + 1)), + ), + dueLabel: index == 0 ? '明天 23:59' : '10/${28 + index} 23:59', + ), + ]; + return _snapshot(courses: courses, assignments: assignments); +} + +Future _pumpGlance( + WidgetTester tester, { + required Size size, + required GlanceSurface surface, + required GlanceSnapshot snapshot, + double textScale = 1, +}) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + tester.platformDispatcher.textScaleFactorTestValue = textScale; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(useMaterial3: true), + darkTheme: ThemeData(useMaterial3: true, brightness: Brightness.dark), + home: GlanceShell( + surface: surface, + snapshot: snapshot, + sections: GlanceSection.values, + paymentBuilder: (_) => const GlancePaymentPreviewCard(), + onRefresh: () {}, + ), + ), + ); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets('cover layout renders course, deadlines and payment tabs', ( + tester, + ) async { + await _pumpGlance( + tester, + size: const Size(506, 439), + surface: GlanceSurface.cover, + snapshot: _snapshot(), + ); + + expect(find.text('高等数学'), findsOneWidget); + expect(find.text('正在上课'), findsOneWidget); + expect(find.text('之后'), findsOneWidget); + expect(find.text('大学物理'), findsOneWidget); + expect(find.text('今天共 2 节课'), findsOneWidget); + expect(tester.takeException(), isNull); + + await tester.tap(find.text('作业')); + await tester.pumpAndSettle(); + expect(find.text('提交实验报告'), findsOneWidget); + expect(find.text('明天 23:59'), findsOneWidget); + expect(tester.takeException(), isNull); + + await tester.tap(find.text('消费码')); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('glance-payment-qr')), findsOneWidget); + expect(find.text('示例消费码'), findsOneWidget); + expect(find.text('¥ 128.00'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('cover header and tabs stay inside the 439dp panel', ( + tester, + ) async { + await _pumpGlance( + tester, + size: const Size(506, 439), + surface: GlanceSurface.cover, + snapshot: _snapshot(), + ); + + final refresh = tester.getRect(find.byIcon(Icons.refresh)); + expect(refresh.top, greaterThanOrEqualTo(0)); + expect(refresh.right, lessThanOrEqualTo(506)); + + for (final label in ['课程', '作业', '消费码']) { + final tab = tester.getRect(find.text(label).last); + expect(tab.bottom, lessThanOrEqualTo(439)); + expect(tab.top, greaterThan(0)); + } + expect(tester.takeException(), isNull); + }); + + testWidgets('cover layout survives 1.5x text scaling on every page', ( + tester, + ) async { + await _pumpGlance( + tester, + size: const Size(506, 439), + surface: GlanceSurface.cover, + snapshot: _snapshot(), + textScale: 1.5, + ); + + expect(find.text('高等数学'), findsOneWidget); + expect(tester.takeException(), isNull); + + await tester.tap(find.text('作业')); + await tester.pumpAndSettle(); + expect(find.text('提交实验报告'), findsOneWidget); + expect(tester.takeException(), isNull); + + await tester.tap(find.text('消费码')); + await tester.pumpAndSettle(); + expect(find.text('示例消费码'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('dense cover data fits 506x439 without overflow', (tester) async { + await _pumpGlance( + tester, + size: const Size(506, 439), + surface: GlanceSurface.cover, + snapshot: _denseSnapshot(), + textScale: 1.5, + ); + + expect(find.text('高等数学(微积分)与线性代数综合'), findsOneWidget); + expect(find.text('今天共 7 节课'), findsOneWidget); + expect(tester.takeException(), isNull); + + await tester.tap(find.text('作业')); + await tester.pumpAndSettle(); + expect( + find.text('完成大学物理实验报告并提交完整数据分析与误差讨论'), + findsOneWidget, + ); + expect(find.text('后续'), findsOneWidget); + expect(tester.takeException(), isNull); + + await tester.tap(find.text('消费码')); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('glance-payment-qr')), findsOneWidget); + expect(find.text('示例消费码'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('rear layout is compact and fits its short panel', (tester) async { + await _pumpGlance( + tester, + size: const Size(340, 210), + surface: GlanceSurface.rear, + snapshot: _snapshot(), + ); + + expect(find.text('高等数学'), findsOneWidget); + expect(find.text('之后 1 节'), findsOneWidget); + expect(tester.takeException(), isNull); + + await tester.tap(find.text('作业')); + await tester.pumpAndSettle(); + expect(find.text('提交实验报告'), findsOneWidget); + expect(tester.takeException(), isNull); + + await tester.tap(find.text('消费码')); + await tester.pumpAndSettle(); + expect(find.text('示例消费码'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('rear layout survives 1.5x text scaling', (tester) async { + await _pumpGlance( + tester, + size: const Size(340, 210), + surface: GlanceSurface.rear, + snapshot: _snapshot(), + textScale: 1.5, + ); + + expect(find.text('高等数学'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('empty and logged-out states are explicit', (tester) async { + await _pumpGlance( + tester, + size: const Size(506, 439), + surface: GlanceSurface.cover, + snapshot: _snapshot(courses: const [], assignments: const []), + ); + expect(find.text('今天没有课程'), findsOneWidget); + + await tester.tap(find.text('作业')); + await tester.pumpAndSettle(); + expect(find.text('没有待办事项'), findsOneWidget); + + await tester.pumpWidget(const SizedBox.shrink()); + await _pumpGlance( + tester, + size: const Size(506, 439), + surface: GlanceSurface.cover, + snapshot: _snapshot( + loggedIn: false, + courses: const [], + assignments: const [], + ), + ); + expect(find.text('请先在完整 App 登录'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('a finished day says so instead of showing an empty list', ( + tester, + ) async { + final past = GlanceCourse( + course: _course('早课', '08:00', '08:45', CourseColor.primary), + state: GlanceCourseState.past, + ); + await _pumpGlance( + tester, + size: const Size(506, 439), + surface: GlanceSurface.cover, + snapshot: _snapshot(courses: [past], assignments: const []), + ); + + expect(find.text('今天的课已结束'), findsOneWidget); + expect(tester.takeException(), isNull); + }); +} diff --git a/test/glance/glance_snapshot_builder_test.dart b/test/glance/glance_snapshot_builder_test.dart new file mode 100644 index 00000000..ead4f3cd --- /dev/null +++ b/test/glance/glance_snapshot_builder_test.dart @@ -0,0 +1,148 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:techpie/features/glance/application/glance_snapshot_builder.dart'; +import 'package:techpie/features/glance/domain/glance_snapshot.dart'; +import 'package:techpie/models/assignment.dart'; +import 'package:techpie/models/course_table.dart'; + +CourseTable _table(DateTime now) { + const periods = [ + CoursePeriod(index: 1, timeRange: '08:00-08:45'), + CoursePeriod(index: 2, timeRange: '08:55-09:40'), + CoursePeriod(index: 3, timeRange: '10:00-10:45'), + ]; + final weeks = '0${'1' * 30}'; + return CourseTable( + periods: periods, + courses: [ + EamsCourse( + name: '高等数学', + classroom: 'A101', + teachers: '张老师', + weeks: weeks, + times: { + now.weekday: [1], + }, + ), + EamsCourse( + name: '大学物理', + classroom: 'B202', + teachers: '李老师', + weeks: weeks, + times: { + now.weekday: [3], + }, + ), + ], + ); +} + +Assignment _assignment(String title, DateTime due) => Assignment( + id: title, + platform: 'test', + title: title, + course: '课程', + due: due, + ); + +GlanceSnapshot _build({ + required DateTime now, + List pending = const [], + bool loggedIn = true, + bool scheduleLoading = false, + String? scheduleError, +}) { + return GlanceSnapshotBuilder.build( + courseTable: _table(now), + customCourses: const [], + termBegin: DateTime(now.year, now.month, now.day).subtract( + const Duration(days: 7), + ), + week: 2, + rawAssignments: pending, + pendingAssignments: pending, + semesterId: '2026-1', + now: now, + loggedIn: loggedIn, + inTerm: true, + scheduleLoading: scheduleLoading, + scheduleError: scheduleError, + assignmentsLoading: false, + assignmentsError: null, + ); +} + +void main() { + test('merges the day and identifies the current/next course', () { + final now = DateTime(2026, 10, 26, 8, 10); + final snapshot = _build(now: now); + + expect(snapshot.hasCourses, isTrue); + expect(snapshot.courses.map((item) => item.course.name), [ + '高等数学', + '大学物理', + ]); + expect(snapshot.currentCourse?.course.name, '高等数学'); + expect(snapshot.currentCourse?.state, GlanceCourseState.ongoing); + expect(snapshot.nextCourse?.course.name, '大学物理'); + expect(snapshot.leadCourse?.course.name, '高等数学'); + expect(snapshot.activeCourses.length, 2); + expect(snapshot.week, 2); + expect(snapshot.inTerm, isTrue); + }); + + test('after a course ends the next one leads and past stays in the list', () { + final now = DateTime(2026, 10, 26, 9, 0); + final snapshot = _build(now: now); + + expect(snapshot.currentCourse, isNull); + expect(snapshot.nextCourse?.course.name, '大学物理'); + expect(snapshot.leadCourse?.course.name, '大学物理'); + expect(snapshot.courses.first.state, GlanceCourseState.past); + expect(snapshot.activeCourses.length, 1); + }); + + test('a day with no remaining classes has no lead course', () { + final now = DateTime(2026, 10, 26, 12, 0); + final snapshot = _build(now: now); + + expect(snapshot.hasCourses, isTrue); + expect(snapshot.currentCourse, isNull); + expect(snapshot.nextCourse, isNull); + expect(snapshot.leadCourse, isNull); + expect(snapshot.activeCourses, isEmpty); + }); + + test('sorts pending deadlines and formats their labels', () { + final now = DateTime(2026, 10, 26, 10, 0); + final snapshot = _build( + now: now, + pending: [ + _assignment('后天', DateTime(2026, 10, 28, 23, 59)), + _assignment('今天', DateTime(2026, 10, 26, 18, 0)), + _assignment('明天', DateTime(2026, 10, 27, 9, 0)), + ], + ); + + expect( + snapshot.pendingAssignments.map((item) => item.assignment.title), + ['今天', '明天', '后天'], + ); + expect(snapshot.pendingAssignments.first.dueLabel, '今天 18:00'); + expect(snapshot.pendingAssignments[1].dueLabel, '明天 09:00'); + expect(snapshot.pendingAssignments.last.dueLabel, '10/28 23:59'); + }); + + test('carries login and loading/error flags through unchanged', () { + final snapshot = _build( + now: DateTime(2026, 10, 26, 10, 0), + loggedIn: false, + scheduleLoading: true, + scheduleError: '网络错误', + ); + expect(snapshot.loggedIn, isFalse); + expect(snapshot.scheduleLoading, isTrue); + expect(snapshot.scheduleError, '网络错误'); + expect(snapshot.assignmentsLoading, isFalse); + expect(snapshot.assignmentsError, isNull); + }); +} diff --git a/test/glance/screen_form_factor_test.dart b/test/glance/screen_form_factor_test.dart new file mode 100644 index 00000000..40685756 --- /dev/null +++ b/test/glance/screen_form_factor_test.dart @@ -0,0 +1,209 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:techpie/models/screen_form_factor.dart'; +import 'package:techpie/services/screen_form_factor_service.dart'; + +ScreenFormFactorInfo _info({ + bool flip = false, + bool rear = false, + int displayId = 0, +}) { + return ScreenFormFactorInfo( + isFlipDevice: flip, + isRearDevice: rear, + displayId: displayId, + windowWidthPx: 900, + windowHeightPx: 600, + density: 2.75, + densityDpi: 440, + isDefaultDisplay: displayId == 0, + isInMultiWindowMode: false, + model: 'test', + manufacturer: 'Xiaomi', + sdkInt: 36, + ); +} + +void main() { + group('ScreenFormFactorInfo.fromMap', () { + test('parses native values and keeps bad density usable', () { + final info = ScreenFormFactorInfo.fromMap(const { + 'isFlipDevice': true, + 'isRearDevice': false, + 'displayId': 0, + 'windowWidthPx': 1392, + 'windowHeightPx': 1208, + 'density': 2.75, + 'densityDpi': 440, + 'isDefaultDisplay': true, + 'isInMultiWindowMode': false, + 'model': 'MIX Flip', + 'manufacturer': 'Xiaomi', + 'sdkInt': 36, + }); + expect(info.isFlipDevice, isTrue); + expect(info.windowWidthDp, closeTo(506.18, 0.01)); + expect(info.density, 2.75); + }); + + test('defaults a zero density to 1 instead of dividing by zero', () { + final info = ScreenFormFactorInfo.fromMap(const {'density': 0}); + expect(info.density, 1); + expect(info.windowWidthDp, 0); + }); + }); + + group('classifyGlanceSurface', () { + test('rear-capable phone on its main display stays full', () { + expect( + classifyGlanceSurface( + logicalSize: const Size(400, 800), + info: _info(rear: true), + enabled: true, + ), + GlanceSurface.none, + ); + }); + + test('rear display is detected by display id', () { + expect( + classifyGlanceSurface( + logicalSize: const Size(340, 210), + info: _info(rear: true, displayId: 1), + enabled: true, + ), + GlanceSurface.rear, + ); + }); + + test('secondary small landscape works without the reflection probe', () { + expect( + classifyGlanceSurface( + logicalSize: const Size(340, 210), + info: _info(displayId: 1), + enabled: true, + ), + GlanceSurface.rear, + ); + }); + + test('flip cover is the wide near-square 1392x1208 panel', () { + expect( + classifyGlanceSurface( + logicalSize: const Size(506, 439), + info: _info(flip: true), + enabled: true, + ), + GlanceSurface.cover, + ); + }); + + test('flip inner screen stays full', () { + expect( + classifyGlanceSurface( + logicalSize: const Size(700, 900), + info: _info(flip: true), + enabled: true, + ), + GlanceSurface.none, + ); + // The real inner panel, landscape: 2912x1224 px at 440dpi. It must not + // be mistaken for the wide cover panel. + expect( + classifyGlanceSurface( + logicalSize: const Size(1059, 445), + info: _info(flip: true), + enabled: true, + ), + GlanceSurface.none, + ); + }); + + test('small split-screen on a normal phone stays full', () { + expect( + classifyGlanceSurface( + logicalSize: const Size(300, 700), + info: _info(), + enabled: true, + ), + GlanceSurface.none, + ); + }); + + test('disabled setting and missing info both mean none', () { + expect( + classifyGlanceSurface( + logicalSize: const Size(294, 506), + info: _info(flip: true), + enabled: false, + ), + GlanceSurface.none, + ); + expect( + classifyGlanceSurface( + logicalSize: const Size(294, 506), + info: null, + enabled: true, + ), + GlanceSurface.none, + ); + }); + }); + + group('ScreenFormFactorService', () { + test('loads and notifies only when the answer changes', () async { + var loads = 0; + final first = _info(flip: true); + final service = ScreenFormFactorService( + loader: () async { + loads++; + return first; + }, + androidOverride: true, + ); + var notifications = 0; + service.addListener(() => notifications++); + + await service.refresh(); + expect(service.info, first); + expect(loads, 1); + expect(notifications, 1); + + await service.refresh(); + expect(loads, 2); + expect(notifications, 1); + + service.dispose(); + }); + + test('retries a missing plugin once and then gives up', () async { + var loads = 0; + final service = ScreenFormFactorService( + loader: () async { + loads++; + throw MissingPluginException('not registered'); + }, + androidOverride: true, + ); + await service.refresh(); + expect(loads, 2); + expect(service.info, isNull); + service.dispose(); + }); + + test('does not touch the channel off Android', () async { + var loads = 0; + final service = ScreenFormFactorService( + loader: () async { + loads++; + return _info(); + }, + androidOverride: false, + ); + await service.refresh(); + expect(loads, 0); + expect(service.info, isNull); + service.dispose(); + }); + }); +}