fix: automate graduate timetable read and refine blue glass Dock

This commit is contained in:
Codex
2026-10-13 17:50:04 +08:00
parent 8f20a341c4
commit 476ef097ee
23 changed files with 1072 additions and 176 deletions
+3 -3
View File
@@ -2,9 +2,9 @@ import 'package:flutter/material.dart';
import '../domain/app_settings.dart';
const river = Color(0xFF348F91);
const ink = Color(0xFF183F43);
const canvas = Color(0xFFF3F7F6);
const river = Color(0xFF007AFF);
const ink = Color(0xFF183451);
const canvas = Color(0xFFF3F7FF);
const coursePalette = [
Color(0xFFDDEEEF),
Color(0xFFE3E7F6),
+6 -10
View File
@@ -231,7 +231,7 @@ class _ShellState extends State<_Shell> with WidgetsBindingObserver {
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Color(0xFFF0F7F5), Color(0xFFF7F8F5), Color(0xFFEFF5F3)],
colors: [Color(0xFFF0F6FF), Color(0xFFF7FAFF), Color(0xFFEDF4FF)],
),
),
child: SafeArea(
@@ -313,15 +313,11 @@ class _ShellState extends State<_Shell> with WidgetsBindingObserver {
: Offset.zero,
duration: MediaQuery.disableAnimationsOf(context)
? Duration.zero
: const Duration(milliseconds: 240),
curve: Curves.easeOutCubic,
child: AnimatedOpacity(
opacity: _dockHidden ? 0 : 1,
duration: const Duration(milliseconds: 180),
child: GlassDock(
selectedIndex: _tab,
onSelected: _selectTab,
),
: const Duration(milliseconds: 360),
curve: Curves.easeInOutCubic,
child: GlassDock(
selectedIndex: _tab,
onSelected: _selectTab,
),
),
),
@@ -22,7 +22,11 @@ class _SchoolAuthPageState extends State<SchoolAuthPage> {
void initState() {
super.initState();
widget.session.addListener(_changed);
WidgetsBinding.instance.addPostFrameCallback((_) => _changed());
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
widget.session.setReadingActive(true);
_changed();
});
}
void _changed() {
@@ -80,6 +84,7 @@ class _SchoolAuthPageState extends State<SchoolAuthPage> {
@override
void dispose() {
widget.session.removeListener(_changed);
widget.session.setReadingActive(false);
super.dispose();
}
@@ -96,10 +101,8 @@ class _SchoolAuthPageState extends State<SchoolAuthPage> {
icon: const Icon(Icons.refresh_rounded),
),
IconButton(
tooltip: '重试读取',
onPressed: _saving
? null
: (s.requestingExams ? s.openExams : s.openTimetable),
tooltip: '读取当前页面',
onPressed: _saving ? null : s.readCurrentPage,
icon: const Icon(Icons.sync_rounded),
),
],
@@ -4,14 +4,17 @@ import 'school_navigation_policy.dart';
class SchoolLoginFlow {
Uri? _target;
bool _requested = false;
int _attempts = 0;
void begin(Uri target) {
_target = target;
_requested = false;
_attempts = 0;
}
void reset() {
_target = null;
_requested = false;
_attempts = 0;
}
Uri? onLoaded(Uri uri, {required bool authenticated}) {
@@ -24,11 +27,13 @@ class SchoolLoginFlow {
}
if (uri.path == _target!.path ||
_requested ||
_attempts >= 2 ||
!authenticated ||
!uri.path.startsWith('/pyxx/')) {
!SchoolNavigationPolicy.isGraduatePage(uri)) {
return null;
}
_requested = true;
_attempts++;
return _target;
}
}
@@ -18,7 +18,8 @@ class SchoolNavigationPolicy {
static bool canNavigate(Uri uri, {required bool isMainFrame}) => isMainFrame
? isSchoolPage(uri)
: (uri.scheme == 'https' && uri.userInfo.isEmpty) ||
: isGraduatePage(uri) ||
(uri.scheme == 'https' && uri.userInfo.isEmpty) ||
(uri.scheme == 'about' && uri.path == 'blank');
static bool _https(Uri uri) =>
uri.scheme == 'https' && uri.port == 443 && uri.userInfo.isEmpty;
@@ -43,7 +44,11 @@ class SchoolNavigationPolicy {
uri.port == 80 &&
uri.userInfo.isEmpty &&
uri.host == 'yjsjy.uestc.edu.cn' &&
uri.path.startsWith('/pyxx/'));
(uri.path == '/pyxx' || uri.path.startsWith('/pyxx/')));
static bool isGraduatePage(Uri uri) =>
isSchoolPage(uri) &&
uri.host == 'yjsjy.uestc.edu.cn' &&
(uri.path == '/pyxx' || uri.path.startsWith('/pyxx/'));
static bool isExam(Uri uri) =>
_https(uri) &&
uri.host == 'yjsjy.uestc.edu.cn' &&
@@ -0,0 +1,97 @@
import 'dart:convert';
import 'school_navigation_policy.dart';
/// Only serialize recognized table fragments, never a login document.
const schoolPageProbeScript = r'''(() => {
const trusted = value => {
try {
const u = new URL(value);
return u.hostname === 'yjsjy.uestc.edu.cn' && !u.username && !u.password &&
((u.protocol === 'https:' && (!u.port || u.port === '443')) ||
(u.protocol === 'http:' && (!u.port || u.port === '80'))) &&
/^\/pyxx(?:\/|$)/.test(u.pathname);
} catch (_) { return false; }
};
const topUrl = location.href;
const result = {topUrl, authenticated: false, pages: []};
if (!trusted(topUrl) || document.querySelector('input[type="password"]')) {
return JSON.stringify(result);
}
const topOrigin = new URL(topUrl).origin;
const home = /^\/pyxx\/home\/(?:index)?\/?$/.test(location.pathname);
const chrome = document.querySelector('#navbar') && document.querySelector('#main-container');
result.authenticated = typeof window.logout === 'function' && Boolean(chrome || home);
const seen = new Set();
const visit = (doc, depth) => {
if (!doc || depth > 4 || seen.size >= 16 || seen.has(doc)) return;
seen.add(doc);
let url;
try { url = doc.location.href; } catch (_) { return; }
if (!trusted(url) || new URL(url).origin !== topOrigin ||
doc.querySelector('input[type="password"]')) return;
for (const [kind, tableId, termId] of [
['timetable', '#tbl', '#drpxq'], ['exams', '#sample-table-1', '#xqbh']
]) {
const table = doc.querySelector(tableId), term = doc.querySelector(termId);
if (!table || !term || !term.options || term.selectedIndex < 0) continue;
const selected = term.cloneNode(true);
Array.from(selected.options).forEach((option, index) => {
if (index === term.selectedIndex) option.setAttribute('selected', 'selected');
else option.removeAttribute('selected');
});
const html = selected.outerHTML + table.outerHTML;
if (html.length <= 2 * 1024 * 1024) result.pages.push({kind, url, html});
}
for (const frame of doc.querySelectorAll('iframe,frame')) {
try { visit(frame.contentDocument, depth + 1); } catch (_) {}
}
};
visit(document, 0);
return JSON.stringify(result);
})()''';
class SchoolTableFragment {
const SchoolTableFragment(this.kind, this.url, this.html);
final String kind;
final Uri url;
final String html;
}
class SchoolPageEvidence {
const SchoolPageEvidence(this.authenticated, this.pages);
final bool authenticated;
final List<SchoolTableFragment> pages;
static SchoolPageEvidence decode(Object raw, Uri current) {
dynamic value = raw;
for (var i = 0; i < 2 && value is String; i++) {
value = jsonDecode(value);
}
if (value is! Map ||
value['topUrl'] != current.toString() ||
!SchoolNavigationPolicy.isGraduatePage(current)) {
throw const FormatException('Untrusted school page evidence');
}
final pages = <SchoolTableFragment>[];
final candidates = value['pages'];
if (candidates is List && candidates.length <= 32) {
for (final page in candidates) {
if (page is! Map || page['url'] is! String || page['html'] is! String) {
continue;
}
final uri = Uri.tryParse(page['url'] as String);
final content = page['html'] as String;
if (uri == null ||
!SchoolNavigationPolicy.isGraduatePage(uri) ||
uri.origin != current.origin ||
utf8.encode(content).length > 2 * 1024 * 1024 ||
!const ['timetable', 'exams'].contains(page['kind'])) {
continue;
}
pages.add(SchoolTableFragment(page['kind'] as String, uri, content));
}
}
return SchoolPageEvidence(value['authenticated'] == true, pages);
}
}
+159 -59
View File
@@ -1,5 +1,4 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:webview_flutter/webview_flutter.dart';
@@ -10,6 +9,7 @@ import 'school_navigation_policy.dart';
import 'school_page_adapter.dart';
import 'school_exam_adapter.dart';
import 'school_login_flow.dart';
import 'school_page_probe.dart';
enum SchoolConnectionState {
signedOut,
@@ -31,10 +31,13 @@ class SchoolSession extends ChangeNotifier {
? null
: SchoolNavigationPolicy.secureIdentityRedirect(uri);
if (upgrade != null) {
final generation = _pageGeneration;
try {
await web.loadRequest(upgrade);
} catch (_) {
_failure('学校身份认证暂时无法打开,请重试。');
if (generation == _pageGeneration) {
_failure('学校身份认证暂时无法打开,请重试。');
}
}
return NavigationDecision.prevent;
}
@@ -54,11 +57,13 @@ class SchoolSession extends ChangeNotifier {
return NavigationDecision.navigate;
},
onPageStarted: (_) {
_poll?.cancel();
_manualRead = false;
_pageGeneration++;
_reader.invalidate();
pendingDraft = null;
pendingExams = null;
if (!hasOpened) return;
if (!hasOpened || _routeClosed) return;
_loading = true;
notifyListeners();
},
@@ -90,6 +95,11 @@ class SchoolSession extends ChangeNotifier {
final _reader = SchoolReader(SchoolPageAdapter());
final _flow = SchoolLoginFlow();
Timer? _timeout;
Timer? _poll;
bool _readingActive = false, _manualRead = false;
bool _routeClosed = false;
int _pollsLeft = 0;
int? _probeGeneration;
SchoolConnectionState connectionState = SchoolConnectionState.signedOut;
bool _loading = false,
hasOpened = false,
@@ -137,8 +147,11 @@ class SchoolSession extends ChangeNotifier {
if (closing != null) await closing;
if (serial != _openSerial) return;
_timeout?.cancel();
_poll?.cancel();
_manualRead = false;
_pageGeneration++;
_reader.invalidate();
final generation = _pageGeneration;
pendingDraft = null;
pendingExams = null;
requestingExams = exams;
@@ -155,7 +168,9 @@ class SchoolSession extends ChangeNotifier {
try {
await web.loadRequest(connected ? _target : authUrl);
} catch (_) {
if (serial == _openSerial) _failure('学校入口无法打开,请检查校园网络后重试。');
if (serial == _openSerial && generation == _pageGeneration) {
_failure('学校入口无法打开,请检查校园网络后重试。');
}
}
}
@@ -169,32 +184,67 @@ class SchoolSession extends ChangeNotifier {
}
void _failure(String text) {
if (!hasOpened) return;
if (!hasOpened || _routeClosed) return;
_pageGeneration++;
_reader.invalidate();
_timeout?.cancel();
_poll?.cancel();
pendingDraft = null;
pendingExams = null;
finding = false;
_loading = false;
message = text;
notifyListeners();
}
Future<String> _html() async {
final raw = await web.runJavaScriptReturningResult(
'JSON.stringify(document.documentElement.outerHTML)',
);
final value = raw is String ? raw : raw.toString();
try {
final decoded = jsonDecode(value);
return decoded is String ? decoded : value;
} catch (_) {
return value;
/// Poll only while the authentication screen is open. Navigation callbacks
/// still read immediately; polling handles scripts and frames ready later.
void setReadingActive(bool active) {
if (_readingActive == active && _routeClosed == !active) return;
_readingActive = active;
_routeClosed = !active;
_poll?.cancel();
if (active && hasOpened) {
web.currentUrl().then((url) {
if (_readingActive && url != null) _loaded(url);
});
} else if (!active) {
_pageGeneration++;
_reader.invalidate();
_timeout?.cancel();
pendingDraft = null;
pendingExams = null;
finding = false;
_loading = false;
}
}
bool _truth(Object value) => value == true || value.toString() == 'true';
Future<void> _loaded(String url) async {
if (!hasOpened) return;
void _scheduleProbe(String url, int generation) {
if (!_readingActive ||
!hasOpened ||
generation != _pageGeneration ||
pendingDraft != null ||
pendingExams != null) {
return;
}
_poll?.cancel();
if (_pollsLeft-- <= 0) {
if (finding) _failure('查找超时,请检查学校页面后重试。已有数据保持不变。');
return;
}
_poll = Timer(const Duration(milliseconds: 750), () {
_loaded(url, resetPolling: false);
});
}
Future<SchoolPageEvidence> _evidence(Uri uri) async =>
SchoolPageEvidence.decode(
await web.runJavaScriptReturningResult(schoolPageProbeScript),
uri,
);
Future<void> _loaded(String url, {bool resetPolling = true}) async {
if (!hasOpened || _routeClosed) return;
final generation = _pageGeneration;
final uri = Uri.tryParse(url);
final current = await web.currentUrl();
@@ -206,6 +256,7 @@ class SchoolSession extends ChangeNotifier {
return;
}
_loading = false;
if (pendingDraft != null || pendingExams != null) return;
if (uri.host == 'idas.uestc.edu.cn') {
_timeout?.cancel();
finding = false;
@@ -215,51 +266,61 @@ class SchoolSession extends ChangeNotifier {
notifyListeners();
return;
}
if (!SchoolNavigationPolicy.isGraduatePage(uri) ||
_probeGeneration == generation) {
return;
}
if (resetPolling) _pollsLeft = 60;
_probeGeneration = generation;
final targetPage = requestingExams
? SchoolNavigationPolicy.isExam(uri)
: SchoolNavigationPolicy.isTimetable(uri);
if (targetPage) {
if (targetPage || _manualRead) {
finding = true;
message = _findingMessage;
notifyListeners();
try {
if (requestingExams) {
final text = await _html();
if (!hasOpened || generation != _pageGeneration) return;
final draft = SchoolExamAdapter.extract(text);
pendingExams = draft;
} else {
final draft = await readTimetable();
if (!hasOpened || generation != _pageGeneration) return;
pendingDraft = draft;
}
_timeout?.cancel();
connectionState = SchoolConnectionState.connected;
message = '读取成功,正在保存…';
} catch (_) {
if (!hasOpened || generation != _pageGeneration) return;
_failure(
'没有读取到完整${requestingExams ? '考试信息' : '课表'},请检查学校页面后重试。已有数据保持不变。',
);
if (_timeout?.isActive != true) _armTimeout();
}
try {
final evidence = await _evidence(uri);
if (!hasOpened ||
generation != _pageGeneration ||
await web.currentUrl() != url) {
return;
}
} else {
// A logout link is evidence of a graduate-system session, unlike simply
// returning to a callback URL or the identity administration dashboard.
bool authenticated = false;
try {
authenticated = _truth(
await web.runJavaScriptReturningResult("""(() => {
return Array.from(document.querySelectorAll('a[href]')).some(a => {
try { const u = new URL(a.href, location.href); return u.hostname === 'yjsjy.uestc.edu.cn' && u.pathname === '/pyxx/home/exit'; } catch (_) { return false; }
});
})()"""),
);
} catch (_) {
/* Keep the school page available for manual recovery. */
for (final page in evidence.pages) {
if (page.kind != (requestingExams ? 'exams' : 'timetable')) continue;
try {
if (requestingExams) {
final draft = SchoolExamAdapter.extract(page.html);
if (generation != _pageGeneration) return;
pendingExams = draft;
} else {
// The probe validates the live document's origin. The strict parser
// gets only its recognized fragment with the canonical table path.
final draft = await _reader.read(
timetableUrl,
() async => page.html,
);
if (!hasOpened || generation != _pageGeneration) return;
pendingDraft = draft;
}
_timeout?.cancel();
_poll?.cancel();
connectionState = SchoolConnectionState.connected;
finding = true;
message = '读取成功,正在保存…';
notifyListeners();
return;
} catch (_) {
if (generation != _pageGeneration) return;
// A recognized table can still be incomplete during asynchronous load.
}
}
if (!hasOpened || generation != _pageGeneration) return;
final next = _flow.onLoaded(uri, authenticated: authenticated);
final next = _manualRead
? null
: _flow.onLoaded(uri, authenticated: evidence.authenticated);
if (next != null) {
finding = true;
_loading = true;
@@ -269,20 +330,54 @@ class SchoolSession extends ChangeNotifier {
try {
await web.loadRequest(next);
} catch (_) {
_failure('课表查询页面暂时无法打开,请重试。');
if (generation == _pageGeneration) {
_failure('课表查询页面暂时无法打开,请重试。');
}
}
return;
}
finding = false;
message = '请在学校网页完成认证;进入研究生系统后会自动读取。';
if (!finding) message = '请在学校网页完成认证;进入研究生系统后会自动读取。';
} catch (_) {
// JavaScript and frame access can fail briefly while the page is changing.
} finally {
if (_probeGeneration == generation) _probeGeneration = null;
_scheduleProbe(url, generation);
}
notifyListeners();
if (hasOpened && generation == _pageGeneration) notifyListeners();
}
Future<ImportDraft> readTimetable() async {
final generation = _pageGeneration;
final uri = Uri.tryParse(await web.currentUrl() ?? '');
if (uri == null) throw UnsupportedSchoolLayout();
return _reader.read(uri, _html);
if (uri == null || !SchoolNavigationPolicy.isGraduatePage(uri)) {
throw UnsupportedSchoolLayout();
}
final evidence = await _evidence(uri);
if (generation != _pageGeneration ||
await web.currentUrl() != uri.toString()) {
throw UnsupportedSchoolLayout();
}
for (final page in evidence.pages) {
if (page.kind != 'timetable') continue;
try {
return await _reader.read(timetableUrl, () async => page.html);
} on UnsupportedSchoolLayout {
if (generation != _pageGeneration) rethrow;
}
}
throw UnsupportedSchoolLayout();
}
Future<void> readCurrentPage() async {
_poll?.cancel();
_timeout?.cancel();
_pageGeneration++;
_reader.invalidate();
pendingDraft = null;
pendingExams = null;
_manualRead = true;
final url = await web.currentUrl();
if (url != null) await _loaded(url);
}
bool saved({
@@ -319,6 +414,7 @@ class SchoolSession extends ChangeNotifier {
_reader.invalidate();
_flow.reset();
_timeout?.cancel();
_poll?.cancel();
hasOpened = false;
pendingDraft = null;
pendingExams = null;
@@ -343,7 +439,11 @@ class SchoolSession extends ChangeNotifier {
@override
void dispose() {
hasOpened = false;
_pageGeneration++;
_reader.invalidate();
_timeout?.cancel();
_poll?.cancel();
super.dispose();
}
}
@@ -40,12 +40,11 @@ class _TimetablePageState extends State<TimetablePage> {
140 + MediaQuery.paddingOf(context).bottom,
),
children: [
const Text(
'RSchedule',
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.w700,
letterSpacing: -0.5,
const Padding(
padding: EdgeInsets.symmetric(horizontal: 14),
child: Text(
'RSchedule',
style: TextStyle(fontSize: 22, fontWeight: FontWeight.w700),
),
),
const SizedBox(height: 10),
@@ -107,21 +106,21 @@ class _TimetablePageState extends State<TimetablePage> {
vertical: 7,
),
decoration: BoxDecoration(
color: const Color(0xFFF3E9D6),
color: const Color(0xFFE2EEFF),
borderRadius: BorderRadius.circular(10),
),
child: const Text(
'示例课表',
style: TextStyle(
fontSize: 11,
color: Color(0xFF94733D),
color: Color(0xFF356AA8),
fontWeight: FontWeight.w600,
),
),
),
const Text(
'不会生成提醒或日历事件',
style: TextStyle(fontSize: 10, color: Color(0xFF85928E)),
style: TextStyle(fontSize: 10, color: Color(0xFF8193AB)),
),
TextButton(onPressed: c.leaveDemo, child: const Text('退出示例')),
],
@@ -148,7 +147,7 @@ class _TimetablePageState extends State<TimetablePage> {
const Icon(
Icons.calendar_month_outlined,
size: 66,
color: Color(0xFFB9D6D3),
color: Color(0xFFB7CDF0),
),
const SizedBox(height: 22),
const Text(
+110 -76
View File
@@ -4,6 +4,8 @@ import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/physics.dart';
import 'glass_refraction.dart';
class GlassDock extends StatefulWidget {
const GlassDock({
super.key,
@@ -17,21 +19,45 @@ class GlassDock extends StatefulWidget {
}
class _GlassDockState extends State<GlassDock> with TickerProviderStateMixin {
static const _width = 280.0, _travel = 88.0;
static const _width = 264.0, _height = 68.0, _inset = 3.0, _travel = 86.0;
static const _blue = Color(0xFF007AFF);
static const _selectedInk = Color(0xFF62666C);
late final AnimationController _motion = AnimationController.unbounded(
vsync: this,
value: widget.selectedIndex.toDouble(),
);
late final AnimationController _press = AnimationController(
late final AnimationController _press = AnimationController.unbounded(
vsync: this,
duration: const Duration(milliseconds: 140),
value: 0,
);
bool _reduceMotion = false;
double get _pressure => _press.value.clamp(0.0, 1.18);
void _pressTo(double target) {
if (_reduceMotion) {
_press.value = target;
return;
}
_press.animateWith(
SpringSimulation(
const SpringDescription(mass: 1, stiffness: 440, damping: 20),
_press.value,
target,
_press.velocity,
),
);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_reduceMotion = MediaQuery.disableAnimationsOf(context);
}
double? _drag;
double _dragSpeed = 0;
double get _position => _drag ?? _motion.value.clamp(-0.12, 2.12);
void _spring(int index, [double velocity = 0]) {
if (MediaQuery.disableAnimationsOf(context)) {
if (_reduceMotion) {
_motion.value = index.toDouble();
return;
}
@@ -50,7 +76,7 @@ class _GlassDockState extends State<GlassDock> with TickerProviderStateMixin {
setState(() => _drag = null);
_motion.value = position;
_spring(index, velocity);
_press.reverse();
_pressTo(0);
widget.onSelected(index);
}
@@ -69,53 +95,59 @@ class _GlassDockState extends State<GlassDock> with TickerProviderStateMixin {
super.dispose();
}
Widget _glass({required Widget child, bool lens = false}) => ClipRRect(
borderRadius: BorderRadius.circular(lens ? 36 : 40),
child: BackdropFilter(
// Keep the underlying timetable visible. Optical rims provide the glass
// thickness instead of a frosted, heavily tinted fill.
filter: ui.ImageFilter.blur(
sigmaX: lens ? 0.6 : 1.5,
sigmaY: lens ? 0.6 : 1.5,
),
child: CustomPaint(
foregroundPainter: _GlassRimPainter(lens: lens),
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: lens
? [
Colors.white.withValues(alpha: 0.045),
_blue.withValues(alpha: 0.018),
Colors.white.withValues(alpha: 0.012),
]
: [
Colors.white.withValues(alpha: 0.028),
_blue.withValues(alpha: 0.005),
Colors.white.withValues(alpha: 0.012),
],
),
Widget _glass({required Widget child, bool lens = false}) {
final pressure = _pressure.clamp(0.0, 1.0);
final content = CustomPaint(
foregroundPainter: _GlassRimPainter(lens: lens),
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: lens
? [
const Color(0xFFD8DBE0)
.withValues(alpha: 0.72 * (1 - pressure * 0.91)),
const Color(0xFFC3C7CE)
.withValues(alpha: 0.60 * (1 - pressure * 0.93)),
const Color(0xFFE5E7EB)
.withValues(alpha: 0.72 * (1 - pressure * 0.90)),
]
: [
Colors.white.withValues(alpha: 0.028),
_blue.withValues(alpha: 0.005),
Colors.white.withValues(alpha: 0.012),
],
),
child: child,
),
child: child,
),
),
);
);
return ClipRRect(
borderRadius: BorderRadius.circular(40),
child: lens
? GlassRefraction(strength: 0.25 + pressure * 0.95, child: content)
: BackdropFilter(
filter: ui.ImageFilter.blur(sigmaX: 1.0, sigmaY: 1.0),
child: content,
),
);
}
@override
Widget build(BuildContext context) => AnimatedBuilder(
animation: Listenable.merge([_motion, _press]),
builder: (context, _) {
final press = Curves.easeOut.transform(_press.value);
final press = _pressure;
final speed = (_drag != null ? _dragSpeed : _motion.velocity).abs();
final stretch = (speed / 16).clamp(0.0, 0.14) + press * 0.04;
final lensWidth = 88 * (1 + stretch);
final lensHeight = 56 + press * 5 - stretch * 9;
final stretch = (speed / 16).clamp(0.0, 0.12) + press * 0.18;
final lensWidth = _travel * (1 + stretch);
final lensHeight =
(_height - _inset * 2) *
(1 + press * 0.19 - (speed / 16).clamp(0.0, 0.07));
return SizedBox(
width: _width,
height: 70,
height: _height,
child: DecoratedBox(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(40),
@@ -127,34 +159,34 @@ class _GlassDockState extends State<GlassDock> with TickerProviderStateMixin {
),
],
),
child: _glass(
child: Stack(
clipBehavior: Clip.none,
children: [
Positioned(
left: 8 + _position * _travel - (lensWidth - 88) / 2,
top: (70 - lensHeight) / 2,
width: lensWidth,
height: lensHeight,
child: IgnorePointer(
child: _glass(lens: true, child: const SizedBox.expand()),
),
child: Stack(
clipBehavior: Clip.none,
children: [
Positioned.fill(child: _glass(child: const SizedBox.expand())),
Positioned(
left: (_inset + _position * _travel - (lensWidth - _travel) / 2)
.clamp(1.0, _width - lensWidth - 1),
top: (_height - lensHeight) / 2,
width: lensWidth,
height: lensHeight,
child: IgnorePointer(
child: _glass(lens: true, child: const SizedBox.expand()),
),
Positioned(
left: 8,
right: 8,
top: 7,
bottom: 7,
child: Row(
children: [
_item(0, Icons.calendar_month_rounded, '课表'),
_item(1, Icons.assignment_outlined, '考试'),
_item(2, Icons.person_rounded, '个人设置'),
],
),
),
Positioned(
left: _inset,
right: _inset,
top: _inset,
bottom: _inset,
child: Row(
children: [
_item(0, Icons.calendar_month_rounded, '课表'),
_item(1, Icons.assignment_outlined, '考试'),
_item(2, Icons.person_rounded, '个人设置'),
],
),
],
),
),
],
),
),
);
@@ -170,16 +202,16 @@ class _GlassDockState extends State<GlassDock> with TickerProviderStateMixin {
child: GestureDetector(
key: index == widget.selectedIndex ? const Key('dock-cursor') : null,
behavior: HitTestBehavior.opaque,
onTapDown: (_) => _press.forward(),
onTapDown: (_) => _pressTo(1),
onTapCancel: () {
if (_drag == null) _press.reverse();
if (_drag == null) _pressTo(0);
},
onTap: () => _select(index),
onHorizontalDragStart: index == widget.selectedIndex
? (_) {
final start = _position.clamp(0.0, 2.0);
_motion.stop();
_press.forward();
_pressTo(1);
setState(() {
_drag = start;
_dragSpeed = 0;
@@ -203,24 +235,25 @@ class _GlassDockState extends State<GlassDock> with TickerProviderStateMixin {
: null,
onHorizontalDragCancel: index == widget.selectedIndex
? () {
if (!mounted) return;
final position = _position;
setState(() => _drag = null);
_motion.value = position;
_spring(widget.selectedIndex);
_press.reverse();
_pressTo(0);
}
: null,
child: Center(
child: AnimatedScale(
scale: index == _position.round().clamp(0, 2)
? 1 + _press.value * 0.08
? 1 + _pressure * 0.08
: 1,
duration: const Duration(milliseconds: 130),
child: Icon(
icon,
size: 27,
color: index == _position.round().clamp(0, 2)
? _blue
? _selectedInk
: _blue.withValues(alpha: 0.48),
),
),
@@ -238,6 +271,7 @@ class _GlassRimPainter extends CustomPainter {
static const _blue = Color(0xFF007AFF);
@override
void paint(Canvas canvas, Size size) {
final edge = lens ? const Color(0xFF7B838F) : _blue;
final bounds = Offset.zero & size;
final outer = RRect.fromRectAndRadius(
bounds.deflate(0.7),
@@ -256,10 +290,10 @@ class _GlassRimPainter extends CustomPainter {
bounds.center,
[
Colors.white.withValues(alpha: 0.90),
_blue.withValues(alpha: lens ? 0.30 : 0.15),
edge.withValues(alpha: lens ? 0.30 : 0.15),
Colors.white.withValues(alpha: 0.10),
Colors.white.withValues(alpha: 0.86),
_blue.withValues(alpha: 0.12),
edge.withValues(alpha: 0.12),
Colors.white.withValues(alpha: 0.90),
],
[0.0, 0.18, 0.38, 0.60, 0.80, 1.0],
@@ -278,7 +312,7 @@ class _GlassRimPainter extends CustomPainter {
bounds.bottomRight,
[
Colors.white.withValues(alpha: 0.30),
_blue.withValues(alpha: lens ? 0.13 : 0.07),
edge.withValues(alpha: lens ? 0.13 : 0.07),
Colors.white.withValues(alpha: 0.40),
],
[0.0, 0.5, 1.0],
+115
View File
@@ -0,0 +1,115 @@
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
/// Filters live pixels beneath the glass; symbols above it remain undistorted.
class GlassRefraction extends StatefulWidget {
const GlassRefraction({
super.key,
required this.strength,
required this.child,
});
final double strength;
final Widget child;
@override
State<GlassRefraction> createState() => _GlassRefractionState();
}
class _GlassRefractionState extends State<GlassRefraction> {
static Future<ui.FragmentProgram>? _program;
ui.FragmentShader? _shader;
@override
void initState() {
super.initState();
if (ui.ImageFilter.isShaderFilterSupported) _load();
}
Future<void> _load() async {
try {
final program = await (_program ??= ui.FragmentProgram.fromAsset(
'shaders/liquid_glass.frag',
));
if (mounted) setState(() => _shader = program.fragmentShader());
} catch (error) {
_program = null;
debugPrint('Glass refraction unavailable: $error');
}
}
@override
void dispose() {
_shader?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => _shader == null
? BackdropFilter(
filter: ui.ImageFilter.blur(sigmaX: 0.6, sigmaY: 0.6),
child: widget.child,
)
: _LiveGlassFilter(
shader: _shader!,
strength: widget.strength,
pixelRatio: MediaQuery.devicePixelRatioOf(context),
child: widget.child,
);
}
class _LiveGlassFilter extends SingleChildRenderObjectWidget {
const _LiveGlassFilter({
required this.shader,
required this.strength,
required this.pixelRatio,
required super.child,
});
final ui.FragmentShader shader;
final double strength, pixelRatio;
@override
_RenderLiveGlass createRenderObject(BuildContext context) =>
_RenderLiveGlass(shader, strength, pixelRatio);
@override
void updateRenderObject(
BuildContext context,
_RenderLiveGlass renderObject,
) => renderObject.update(shader, strength, pixelRatio);
}
class _RenderLiveGlass extends RenderProxyBox {
_RenderLiveGlass(this._shader, this._strength, this._pixelRatio);
ui.FragmentShader _shader;
double _strength, _pixelRatio;
final _layer = LayerHandle<BackdropFilterLayer>();
void update(ui.FragmentShader shader, double strength, double pixelRatio) {
_shader = shader;
_strength = strength;
_pixelRatio = pixelRatio;
markNeedsPaint();
}
@override
bool get alwaysNeedsCompositing => child != null;
@override
void paint(PaintingContext context, Offset offset) {
if (child == null) return;
// Sample coordinates are physical pixels. Resolve the actual transform
// during paint so the glass also follows the Dock's hide/show animation.
final origin = localToGlobal(Offset.zero) * _pixelRatio;
_shader
..setFloat(2, origin.dx)
..setFloat(3, origin.dy)
..setFloat(4, size.width * _pixelRatio)
..setFloat(5, size.height * _pixelRatio)
..setFloat(6, _strength);
_layer.layer ??= BackdropFilterLayer();
_layer.layer!.filter = ui.ImageFilter.shader(_shader);
context.pushLayer(_layer.layer!, super.paint, offset);
}
@override
void dispose() {
_layer.layer = null;
super.dispose();
}
}