From 023006cf2a6a362e34b0548895686b9d44ce52a5 Mon Sep 17 00:00:00 2001 From: jdz Date: Mon, 26 Oct 2026 14:33:37 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=BA=20Linux=20=E5=8A=A0=E4=B8=8A=E6=A1=8C?= =?UTF-8?q?=E9=9D=A2=20Deadline=20=E5=B0=8F=E7=BB=84=E4=BB=B6=E5=92=8C?= =?UTF-8?q?=E5=BA=94=E7=94=A8=E4=BB=A3=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 支持 GNOME 桌面卡片、顶栏入口和 KDE Plasma 小组件, 使用应用生成的本地快照,点击后打开 Deadlines 页面。 补充共享开关、账号切换时的数据清理、临期提示和按内容调整尺寸。 增加可启用或关闭的应用代理,并改用原生 WebKit 登录窗口, 处理 Linux 登录弹窗加载和关闭时的问题。 Linux 发布包同时带上小组件、安装器和项目图标。 Closes #146 Refs #147(Linux 部分) --- .github/workflows/linux-release.yml | 13 +- lib/main.dart | 38 +++- lib/pages/assignments_page.dart | 23 ++- lib/pages/settings_page.dart | 76 +++++++ lib/services/assignment_service.dart | 106 +++++++++- lib/services/deadline_widget_service.dart | 192 ++++++++++++++++++ lib/services/http_client.dart | 18 ++ lib/services/service_provider.dart | 6 +- lib/services/storage_service.dart | 15 ++ lib/services/uni_auth_service.dart | 20 +- lib/widgets/app_shell/app_shell.dart | 13 ++ linux/runner/CMakeLists.txt | 6 + linux/runner/deadline_snapshot_store.cc | 92 +++++++++ linux/runner/deadline_snapshot_store.h | 10 + linux/runner/my_application.cc | 76 ++++++- linux/runner/uni_auth_window.cc | 151 ++++++++++++++ linux/runner/uni_auth_window.h | 24 +++ linux/widgets/CMakeLists.txt | 11 + linux/widgets/common/snapshot.mjs | 48 +++++ linux/widgets/gnome/desktopCard.js | 164 +++++++++++++++ linux/widgets/gnome/extension.js | 177 ++++++++++++++++ linux/widgets/gnome/metadata.json | 9 + linux/widgets/gnome/reader.mjs | 39 ++++ ...l.extensions.techpie-deadlines.gschema.xml | 18 ++ linux/widgets/gnome/stylesheet.css | 22 ++ linux/widgets/install.py | 119 +++++++++++ linux/widgets/kde/backend/deadline_model.cpp | 83 ++++++++ linux/widgets/kde/backend/deadline_model.h | 32 +++ linux/widgets/kde/backend/plugin.cpp | 13 ++ linux/widgets/kde/contents/ui/backend/qmldir | 1 + linux/widgets/kde/contents/ui/main.qml | 128 ++++++++++++ linux/widgets/kde/metadata.json | 14 ++ 32 files changed, 1738 insertions(+), 19 deletions(-) create mode 100644 lib/services/deadline_widget_service.dart create mode 100644 linux/runner/deadline_snapshot_store.cc create mode 100644 linux/runner/deadline_snapshot_store.h create mode 100644 linux/runner/uni_auth_window.cc create mode 100644 linux/runner/uni_auth_window.h create mode 100644 linux/widgets/CMakeLists.txt create mode 100644 linux/widgets/common/snapshot.mjs create mode 100644 linux/widgets/gnome/desktopCard.js create mode 100644 linux/widgets/gnome/extension.js create mode 100644 linux/widgets/gnome/metadata.json create mode 100644 linux/widgets/gnome/reader.mjs create mode 100644 linux/widgets/gnome/schemas/org.gnome.shell.extensions.techpie-deadlines.gschema.xml create mode 100644 linux/widgets/gnome/stylesheet.css create mode 100644 linux/widgets/install.py create mode 100644 linux/widgets/kde/backend/deadline_model.cpp create mode 100644 linux/widgets/kde/backend/deadline_model.h create mode 100644 linux/widgets/kde/backend/plugin.cpp create mode 100644 linux/widgets/kde/contents/ui/backend/qmldir create mode 100644 linux/widgets/kde/contents/ui/main.qml create mode 100644 linux/widgets/kde/metadata.json diff --git a/.github/workflows/linux-release.yml b/.github/workflows/linux-release.yml index 796ee6e8..dcf91963 100644 --- a/.github/workflows/linux-release.yml +++ b/.github/workflows/linux-release.yml @@ -91,7 +91,10 @@ jobs: liblzma-dev \ libwebkit2gtk-4.1-dev \ libsecret-1-dev \ - libjsoncpp-dev + libjsoncpp-dev \ + libjson-glib-dev \ + qt6-base-dev \ + qt6-declarative-dev - name: Set up Flutter uses: subosito/flutter-action@v2 @@ -131,6 +134,14 @@ jobs: # platform's artifact, with the file left in whatever shape the build # produced. The archive holds `bundle/` itself, so it extracts to one # directory — the runner, its libraries and data/ next to each other. + cmake -S linux/widgets -B build/linux-widgets -DCMAKE_BUILD_TYPE=Release + cmake --build build/linux-widgets --parallel 2 + mkdir -p build/linux/x64/release/bundle/widgets + cp assets/icon/icon.png build/linux/x64/release/bundle/techpie.png + cp -R build/linux-widgets/kde linux/widgets/gnome linux/widgets/common \ + build/linux/x64/release/bundle/widgets/ + cp linux/widgets/install.py \ + build/linux/x64/release/bundle/widgets/ mkdir -p dist tar -czf "dist/TechPie-${RELEASE_NAME}-linux-x86-64.tar.gz" \ -C build/linux/x64/release bundle diff --git a/lib/main.dart b/lib/main.dart index a10b6228..234ef7f4 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -13,6 +13,7 @@ import 'models/third_party_account.dart'; import 'services/assignment_service.dart'; import 'services/auth_service.dart'; import 'services/campus_card_service.dart'; +import 'services/deadline_widget_service.dart'; import 'services/debug_logger.dart'; import 'services/ecard_bind_service.dart'; import 'services/ecard_widget_service.dart'; @@ -60,11 +61,19 @@ void main(List args) async { Future _realMain(SharedPreferences prefs) async { final storageService = StorageService(prefs); + configureAppProxy(storageService.appProxyEnabled ? storageService.appProxyUrl : ''); final debugLogger = DebugLogger()..enabled = storageService.debugMode; final httpClient = LoggingHttpClient(debugLogger); - final uniAuthService = UniAuthService(logger: debugLogger); - final authService = - AuthService(storageService, httpClient, uniAuthService, logger: debugLogger); + final uniAuthService = UniAuthService( + logger: debugLogger, + proxyUrl: storageService.appProxyEnabled ? storageService.appProxyUrl : '', + ); + final authService = AuthService( + storageService, + httpClient, + uniAuthService, + logger: debugLogger, + ); final themeService = ThemeService(storageService); final campusCardService = CampusCardService(debugLogger: debugLogger, storage: storageService); final ecardBindService = EcardBindService(); @@ -96,6 +105,9 @@ Future _realMain(SharedPreferences prefs) async { thirdPartyAuthService, scheduleService, ); + final deadlineWidgetService = !kIsWeb && defaultTargetPlatform == TargetPlatform.linux + ? DeadlineWidgetService(assignmentService, enabled: storageService.deadlineWidgetsEnabled) + : null; final syncService = SyncService( authService, thirdPartyAuthService, @@ -181,10 +193,12 @@ Future _realMain(SharedPreferences prefs) async { campusCardService: campusCardService, ecardBindService: ecardBindService, ecardWidgetService: ecardWidgetService, + deadlineWidgetService: deadlineWidgetService, ), ); bootMark('cached data ready'); + deadlineWidgetService?.initialize(); oaGymService.startProfileSync(); unawaited(campusCardService.refreshAccount()); @@ -309,6 +323,7 @@ class TechPieApp extends StatefulWidget { final CampusCardService campusCardService; final EcardBindService ecardBindService; final EcardWidgetService? ecardWidgetService; + final DeadlineWidgetService? deadlineWidgetService; const TechPieApp({ super.key, @@ -327,6 +342,7 @@ class TechPieApp extends StatefulWidget { required this.campusCardService, required this.ecardBindService, this.ecardWidgetService, + this.deadlineWidgetService, }); @override @@ -350,11 +366,16 @@ class _TechPieAppState extends State with WidgetsBindingObserver { WidgetsBinding.instance.addObserver(this); unawaited(_checkForUpdatesQuietly()); widget.ecardWidgetService?.setOpenPayHandler(_openEcardPayCode); + widget.deadlineWidgetService?.setOpenHandler(_openDeadlines); } @override void didUpdateWidget(covariant TechPieApp oldWidget) { super.didUpdateWidget(oldWidget); + if (oldWidget.deadlineWidgetService != widget.deadlineWidgetService) { + oldWidget.deadlineWidgetService?.clearOpenHandler(); + widget.deadlineWidgetService?.setOpenHandler(_openDeadlines); + } if (oldWidget.ecardWidgetService == widget.ecardWidgetService) return; oldWidget.ecardWidgetService?.clearOpenPayHandler(); widget.ecardWidgetService?.setOpenPayHandler(_openEcardPayCode); @@ -364,6 +385,7 @@ class _TechPieAppState extends State with WidgetsBindingObserver { void dispose() { WidgetsBinding.instance.removeObserver(this); widget.ecardWidgetService?.clearOpenPayHandler(); + widget.deadlineWidgetService?.dispose(); widget.campusCardService.dispose(); super.dispose(); } @@ -378,6 +400,11 @@ class _TechPieAppState extends State with WidgetsBindingObserver { } } + Future _openDeadlines() async { + _navigatorKey.currentState?.popUntil((route) => route.isFirst); + appShellPendingDeadlines.value = true; + } + /// The check nobody asked for. /// /// It may raise the update dialog, and says nothing else: a network the user @@ -403,8 +430,10 @@ class _TechPieAppState extends State with WidgetsBindingObserver { } if (release == null || !mounted) return; + final dialogContext = _navigatorKey.currentState?.overlay?.context; + if (dialogContext == null || !dialogContext.mounted) return; _promptedThisLaunch = true; - await showUpdateAvailableDialog(context, release); + await showUpdateAvailableDialog(dialogContext, release); } Future _openEcardPayCode() async { @@ -448,6 +477,7 @@ class _TechPieAppState extends State with WidgetsBindingObserver { campusCardService: widget.campusCardService, ecardBindService: widget.ecardBindService, ecardWidgetService: widget.ecardWidgetService, + deadlineWidgetService: widget.deadlineWidgetService, child: MaterialApp( navigatorKey: _navigatorKey, scaffoldMessengerKey: rootMessengerKey, diff --git a/lib/pages/assignments_page.dart b/lib/pages/assignments_page.dart index 6e4cbd2e..10cd53eb 100644 --- a/lib/pages/assignments_page.dart +++ b/lib/pages/assignments_page.dart @@ -18,6 +18,7 @@ import '../widgets/blurred_app_bar.dart'; import '../widgets/ios/ios_native_navigation_bar.dart'; import '../widgets/swipeable_card.dart'; import 'hidden_assignments_page.dart'; +import 'third_party_accounts_page.dart'; class AssignmentsPage extends StatefulWidget { const AssignmentsPage({super.key}); @@ -415,6 +416,8 @@ class _AssignmentsPageState extends State { Widget _emptyState(BuildContext context, AssignmentService service) { final theme = Theme.of(context); + final hasSources = ServiceProvider.of(context) + .thirdPartyAuthService.boundPlatforms.isNotEmpty; return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -425,7 +428,25 @@ class _AssignmentsPageState extends State { color: theme.colorScheme.onSurfaceVariant, ), const SizedBox(height: 16), - Text('No upcoming deadlines', style: theme.textTheme.titleMedium), + Text( + !hasSources ? '连接课程平台以获取Deadlines' : service.loading + ? '正在同步截止日期…' : !service.hasCachedData + ? '尚未成功同步截止日期' : 'No upcoming deadlines', + style: theme.textTheme.titleMedium, + ), + if (!hasSources) ...[ + const SizedBox(height: 16), + FilledButton.icon( + icon: const Icon(Icons.link), + label: const Text('连接课程平台'), + onPressed: () => unawaited( + pushAdaptivePage( + context, + builder: (_) => const ThirdPartyAccountsPage(), + ), + ), + ), + ], if (service.error != null) ...[ const SizedBox(height: 8), Padding( diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index 6de9c254..c5faddfc 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -7,9 +7,12 @@ import 'package:package_info_plus/package_info_plus.dart'; import 'package:techpie/services/auth_service.dart'; import 'package:url_launcher/url_launcher.dart'; +import '../services/http_client.dart'; import '../services/service_provider.dart'; +import '../services/storage_service.dart'; import '../services/sync_service.dart'; import '../services/theme_service.dart'; +import '../services/uni_auth_service.dart'; import '../services/update_service.dart'; import '../utils/adaptive_layout.dart'; import '../utils/platform.dart'; @@ -409,6 +412,20 @@ class _SettingsPageState extends State { // General section _sectionHeader(theme, 'General'), + if (sp.deadlineWidgetService != null) + _AdaptiveSwitchTile( + usesIosLiquidGlass: useIosChrome, + secondary: const Icon(Icons.widgets_outlined), + title: 'Deadline widgets', + subtitle: 'Share task titles and dates with your desktop. ' + 'Widgets use cached data while TechPie is closed.', + value: storage.deadlineWidgetsEnabled, + onChanged: (value) async { + await storage.setDeadlineWidgetsEnabled(value); + await sp.deadlineWidgetService!.setEnabled(value); + if (mounted) setState(() {}); + }, + ), _AdaptiveSwitchTile( usesIosLiquidGlass: useIosChrome, secondary: const Icon(Icons.visibility_off_outlined), @@ -422,6 +439,28 @@ class _SettingsPageState extends State { }); }, ), + ListTile( + leading: const Icon(Icons.lan_outlined), + title: const Text('Application proxy'), + subtitle: Text( + storage.appProxyEnabled && storage.appProxyUrl.isNotEmpty + ? storage.appProxyUrl + : 'Disabled', + ), + onTap: () => _showProxySettings(storage, sp.uniAuthService), + ), + SwitchListTile( + secondary: const Icon(Icons.power_settings_new), + title: const Text('Enable application proxy'), + value: storage.appProxyEnabled, + onChanged: (value) async { + await storage.setAppProxyEnabled(value); + final proxy = value ? storage.appProxyUrl : ''; + configureAppProxy(proxy); + sp.uniAuthService.setProxyUrl(proxy); + if (mounted) setState(() {}); + }, + ), ListTile( leading: const Icon(Icons.info_outline), title: const Text('About'), @@ -538,6 +577,43 @@ class _SettingsPageState extends State { } } + Future _showProxySettings(StorageService storage, UniAuthService uniAuth) async { + final controller = TextEditingController(text: storage.appProxyUrl); + final value = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Application proxy'), + content: TextField( + controller: controller, + autofocus: true, + decoration: const InputDecoration(hintText: '127.0.0.1:7890'), + keyboardType: TextInputType.url, + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(context), child: const Text('Cancel')), + FilledButton(onPressed: () => Navigator.pop(context, controller.text.trim()), child: const Text('Save')), + ], + ), + ); + controller.dispose(); + if (value == null || !mounted) return; + final proxy = value.trim(); + if (proxy.isNotEmpty && !RegExp(r'^[^\s:]+:\d{1,5}$').hasMatch(proxy)) { + await showAdaptiveAlertDialog( + context: context, + title: 'Invalid proxy', + message: 'Use host:port, for example 127.0.0.1:7890.', + actions: const [AdaptiveAlertAction(label: 'OK')], + ); + return; + } + await storage.setAppProxyUrl(proxy); + await storage.setAppProxyEnabled(proxy.isNotEmpty); + configureAppProxy(proxy); + uniAuth.setProxyUrl(proxy); + setState(() {}); + } + void _showThemePicker(BuildContext context, ThemeService themeService) { if (usesSidebarLayout(context)) { showDesktopPopover( diff --git a/lib/services/assignment_service.dart b/lib/services/assignment_service.dart index dfa74f3b..0b23ba62 100644 --- a/lib/services/assignment_service.dart +++ b/lib/services/assignment_service.dart @@ -26,6 +26,14 @@ class AssignmentService extends ChangeNotifier { List _assignments = []; AssignmentOverrides _overrides = AssignmentOverrides(); bool _loading = false; + int _identityEpoch = 0; + bool _hasCachedData = false; + bool _cacheHydrated = false; + bool _refetchPending = false; + bool _signedOut = false; + bool _disposed = false; + String? _primaryIdentity; + Map _sourceIdentities = {}; String? _error; // Per-platform error messages (keyed by lowercase platform id). final Map _platformErrors = {}; @@ -43,6 +51,8 @@ class AssignmentService extends ChangeNotifier { AssignmentOverrides get overrides => _overrides; bool get loading => _loading; + int get identityEpoch => _identityEpoch; + bool get hasCachedData => _hasCachedData; String? get error => _error; Map get platformErrors => Map.unmodifiable(_platformErrors); @@ -58,6 +68,8 @@ class AssignmentService extends ChangeNotifier { this._tpAuth, this._schedule, ) { + _primaryIdentity = _auth.session?.userId; + _sourceIdentities = _currentSources(); // Refetch when bindings or auth change *after* initial app boot. // The initial fetch is kicked off explicitly from main.dart so we // don't double-fire during service initialization. @@ -81,13 +93,65 @@ class AssignmentService extends ChangeNotifier { _lastRefetchedSemesterId = _schedule.selectedSemesterId; } - /// Auth or binding changed — always refetch (tokens, accounts differ). + /// Queue a refetch during an active sync only when the identity changes. void _onBindingsOrAuthChanged() { + final primary = _auth.session?.userId; + final sources = _currentSources(); + final primaryChanged = primary != _primaryIdentity; + final changed = { + for (final key in {..._sourceIdentities.keys, ...sources.keys}) + if (_sourceIdentities[key] != sources[key]) key, + }; + if (primaryChanged || changed.isNotEmpty) { + if (_cacheHydrated) { + _identityEpoch++; + if (primaryChanged) { + _signedOut = _primaryIdentity != null && primary == null; + } + if (primary != null) _signedOut = false; + _assignments = primaryChanged + ? [] + : _assignments.where((a) { + final source = + (a.platform == 'blackboard' || a.platform == 'exam') ? 'cpdaily' : a.platform; + return !changed.contains(source); + }).toList(); + if (primaryChanged) { + _hasCachedData = false; + unawaited(_storage.clearCachedAssignments()); + } else if (_hasCachedData) { + unawaited( + _storage.saveCachedAssignments( + _assignments.map((a) => a.toJson()).toList(), + ), + ); + } + notifyListeners(); + } + _primaryIdentity = primary; + _sourceIdentities = sources; + } if (!_autoRefetchEnabled) return; + if (_signedOut) return; _lastRefetchedSemesterId = _schedule.selectedSemesterId; + if (_loading) { + // Renewal status notifications must not retry the active sync. + if (primaryChanged || changed.isNotEmpty) _refetchPending = true; + return; + } unawaited(fetchAssignments()); } + Map _currentSources() => { + for (final account in _tpAuth.accounts) + account.platform.id: jsonEncode([ + account.account, + account.sid, + account.hydroOrigin, + account.hydroDomains, + ]), + }; + /// Schedule changed — only refetch if the selected semester actually /// changed, not on every loading/error/course_table flip. This prevents /// a cascade of redundant blackboard+exam fetches during a semester switch. @@ -106,6 +170,7 @@ class AssignmentService extends ChangeNotifier { @override void dispose() { + _disposed = true; _tpAuth.removeListener(_onBindingsOrAuthChanged); _auth.removeListener(_onBindingsOrAuthChanged); _schedule.removeListener(_onScheduleChanged); @@ -115,6 +180,8 @@ class AssignmentService extends ChangeNotifier { /// Clear cached + in-memory deadlines (called on primary logout). Future clearCache() async { + _identityEpoch++; + _hasCachedData = false; _assignments = []; _platformErrors.clear(); _error = null; @@ -125,6 +192,8 @@ class AssignmentService extends ChangeNotifier { /// Hydrate from local cache so the UI doesn't flash empty on app start /// or tab switch. Safe to call before login. Also loads overrides. void loadCached() { + _cacheHydrated = true; + _hasCachedData = _storage.hasCachedAssignments; _overrides = _storage.loadAssignmentOverrides(); final raw = _storage.loadCachedAssignments(); if (raw.isEmpty) { @@ -199,7 +268,8 @@ class AssignmentService extends ChangeNotifier { }; Future fetchAssignments() async { - if (_loading) return; // 避免启动时 listener 链触发的并发重复调用 + if (_loading || _signedOut || _disposed) return; + final epoch = _identityEpoch; _loading = true; _error = null; _platformErrors.clear(); @@ -246,11 +316,14 @@ class AssignmentService extends ChangeNotifier { try { await Future.wait(futures); + if (_disposed || epoch != _identityEpoch) return; final merged = _mergeAssignments( successfulResults: successfulResults, ); _assignments = merged; + _hasCachedData = _hasCachedData || successfulResults.isNotEmpty; + if (!_hasCachedData) return; await _storage.saveCachedAssignments( merged.map((a) => a.toJson()).toList(), ); @@ -258,7 +331,11 @@ class AssignmentService extends ChangeNotifier { _error = '同步失败,请检查网络或稍后重试'; } finally { _loading = false; - notifyListeners(); + if (!_disposed) notifyListeners(); + if (_refetchPending && !_disposed) { + _refetchPending = false; + unawaited(fetchAssignments()); + } } } @@ -278,6 +355,8 @@ class AssignmentService extends ChangeNotifier { } Future fetchPlatform(String platformId) async { + if (_loading || _signedOut || _disposed) return; + final epoch = _identityEpoch; _loading = true; _error = null; _platformErrors.remove(platformId); @@ -311,24 +390,31 @@ class AssignmentService extends ChangeNotifier { } } - if (future != null) { - try { + try { + if (future != null) { await future; + if (_disposed || epoch != _identityEpoch) return; final merged = _mergeAssignments( successfulResults: successfulResults, ); _assignments = merged; + _hasCachedData = _hasCachedData || successfulResults.isNotEmpty; + if (!_hasCachedData) return; await _storage.saveCachedAssignments( merged.map((a) => a.toJson()).toList(), ); - } catch (e) { - _error = e.toString(); + } + } catch (e) { + if (epoch == _identityEpoch) _error = e.toString(); + } finally { + _loading = false; + if (!_disposed) notifyListeners(); + if (_refetchPending && !_disposed) { + _refetchPending = false; + unawaited(fetchAssignments()); } } - - _loading = false; - notifyListeners(); } Future?> _fetchBlackboard() async { diff --git a/lib/services/deadline_widget_service.dart b/lib/services/deadline_widget_service.dart new file mode 100644 index 00000000..6b6b5a8f --- /dev/null +++ b/lib/services/deadline_widget_service.dart @@ -0,0 +1,192 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +import '../models/assignment.dart'; +import '../models/assignment_overrides.dart'; +import 'assignment_service.dart'; + +typedef OpenDeadlinesHandler = Future Function(); + +/// Publishes display-only data; native widgets never receive account credentials. +class DeadlineWidgetService with WidgetsBindingObserver { + DeadlineWidgetService( + this._assignments, { + MethodChannel? channel, + DateTime Function()? now, + bool enabled = true, + }) : _channel = channel ?? const MethodChannel('techpie/deadline_widgets'), + _enabled = enabled, + _now = now ?? DateTime.now; + + final AssignmentService _assignments; + final MethodChannel _channel; + final DateTime Function() _now; + bool _enabled; + bool get enabled => _enabled; + + Future setEnabled(bool enabled) async { + _enabled = enabled; + _lastPublished = null; + await _publish(); + } + + OpenDeadlinesHandler? _handler; + bool _pendingRoute = false; + bool _dispatching = false; + bool _disposed = false; + bool _initialized = false; + String? _lastPublished; + Future _writes = Future.value(); + + void initialize() { + if (_initialized) return; + _initialized = true; + _assignments.addListener(_changed); + WidgetsBinding.instance.addObserver(this); + _channel.setMethodCallHandler((call) async { + if (call.method == 'openDeadlines') await _open(); + }); + unawaited(_consumeRoute()); + _changed(); + } + + static List> displayItems( + Iterable assignments, + bool Function(Assignment) completed, + DateTime now, + ) { + final items = assignments.where((a) => !completed(a) && a.due.isAfter(now)).toList() + ..sort((a, b) { + final order = a.due.compareTo(b.due); + return order != 0 + ? order + : AssignmentOverrides.keyFor(a).compareTo(AssignmentOverrides.keyFor(b)); + }); + final result = >[]; + final ids = {}; + var bytes = 1024; // Reserve the envelope and list separators. + for (final a in items) { + final id = AssignmentOverrides.keyFor(a); + final due = a.due.toUtc().millisecondsSinceEpoch / 1000; + if (utf8.encode(id).length > 4096 || !ids.add(id) || due < 0 || due > 253402300799) continue; + final row = { + 'id': id, + 'kind': a.kind.id, + 'title': String.fromCharCodes(a.title.runes.take(256)), + 'course': String.fromCharCodes(a.course.runes.take(128)), + 'dueAt': due, + }; + final size = utf8.encode(jsonEncode(row)).length + 1; + if (bytes + size > 262144) break; + result.add(row); + bytes += size; + if (result.length == 512) break; + } + return result; + } + + void _changed() => unawaited(_publish()); + + Future _publish() async { + final epoch = _assignments.identityEpoch; + // Publish an empty valid snapshot as soon as sharing is enabled. This + // keeps the desktop card truthful before the first sync. + final ready = _enabled; + final items = _assignments.hasCachedData ? displayItems( + _assignments.visibleAssignments, + _assignments.isCompleted, + _now(), + ) : >[]; + final content = ready ? jsonEncode(items) : null; + _writes = _writes.then((_) async { + if (_disposed || + epoch != _assignments.identityEpoch || + ready != _enabled) { + return; + } + if (_lastPublished == content && content != null) return; + try { + if (!ready) { + await _channel.invokeMethod('clear'); + } else { + await _channel.invokeMethod( + 'publish', + jsonEncode({ + 'schemaVersion': 1, + 'writtenAt': _now().toUtc().millisecondsSinceEpoch / 1000, + 'items': items, + }), + ); + } + _lastPublished = content; + } on MissingPluginException { + // Unsupported platforms keep using the regular deadlines page. + } on PlatformException { + // Retry on the next change/foreground event; never block the app. + } + }); + await _writes; + } + + Future flush() => _writes; + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state != AppLifecycleState.resumed || _disposed) return; + _changed(); + } + + void setOpenHandler(OpenDeadlinesHandler handler) { + _handler = handler; + if (_pendingRoute) unawaited(_open()); + } + + void clearOpenHandler() => _handler = null; + + Future _consumeRoute() async { + try { + if (await _channel.invokeMethod('consumePendingRoute') == true) { + await _open(); + } + } on MissingPluginException { + // A missing native bridge does not delay app navigation. + } on PlatformException { + // Retry when a later native route event arrives. + } + } + + Future _open() async { + if (_disposed) return; + if (_handler == null || _dispatching) { + _pendingRoute = true; + return; + } + _pendingRoute = false; + _dispatching = true; + try { + await _handler!(); + try { + await _channel.invokeMethod('acknowledgePendingRoute'); + } on MissingPluginException { + // Tests may dispatch without a native peer. + } on PlatformException { + // The destination is already visible. + } + } finally { + _dispatching = false; + if (_pendingRoute) unawaited(_open()); + } + } + + void dispose() { + _disposed = true; + _handler = null; + if (!_initialized) return; + _assignments.removeListener(_changed); + WidgetsBinding.instance.removeObserver(this); + _channel.setMethodCallHandler(null); + } +} diff --git a/lib/services/http_client.dart b/lib/services/http_client.dart index 72799b95..137f81db 100644 --- a/lib/services/http_client.dart +++ b/lib/services/http_client.dart @@ -1,9 +1,27 @@ import 'dart:convert'; +import 'dart:io'; import 'package:http/http.dart' as http; import 'debug_logger.dart'; +String _appProxy = ''; + +class TechPieHttpOverrides extends HttpOverrides { + @override + HttpClient createHttpClient(SecurityContext? context) { + final client = super.createHttpClient(context); + // Read the current choice on every request, including existing clients. + client.findProxy = (_) => _appProxy.isEmpty ? 'DIRECT' : 'PROXY $_appProxy'; + return client; + } +} + +void configureAppProxy(String value) { + _appProxy = value.trim(); + HttpOverrides.global = TechPieHttpOverrides(); +} + class LoggingHttpClient { final http.Client _inner; final DebugLogger _logger; diff --git a/lib/services/service_provider.dart b/lib/services/service_provider.dart index a166d008..ec445a1e 100644 --- a/lib/services/service_provider.dart +++ b/lib/services/service_provider.dart @@ -3,6 +3,7 @@ import 'package:flutter/widgets.dart'; import 'assignment_service.dart'; import 'auth_service.dart'; import 'campus_card_service.dart'; +import 'deadline_widget_service.dart'; import 'debug_logger.dart'; import 'ecard_bind_service.dart'; import 'ecard_widget_service.dart'; @@ -32,6 +33,7 @@ class ServiceProvider extends InheritedWidget { final CampusCardService campusCardService; final EcardBindService ecardBindService; final EcardWidgetService? ecardWidgetService; + final DeadlineWidgetService? deadlineWidgetService; const ServiceProvider({ super.key, @@ -50,6 +52,7 @@ class ServiceProvider extends InheritedWidget { required this.campusCardService, required this.ecardBindService, this.ecardWidgetService, + this.deadlineWidgetService, required super.child, }); @@ -76,5 +79,6 @@ class ServiceProvider extends InheritedWidget { updateService != oldWidget.updateService || campusCardService != oldWidget.campusCardService || ecardBindService != oldWidget.ecardBindService || - ecardWidgetService != oldWidget.ecardWidgetService; + ecardWidgetService != oldWidget.ecardWidgetService || + deadlineWidgetService != oldWidget.deadlineWidgetService; } diff --git a/lib/services/storage_service.dart b/lib/services/storage_service.dart index b42ed5c3..47d8f2bc 100644 --- a/lib/services/storage_service.dart +++ b/lib/services/storage_service.dart @@ -33,6 +33,8 @@ class StorageService { static const _syncMasterKeyKey = 'sync_master_key'; // secure storage static const _deviceIdKey = 'device_id'; static const _maskPersonalInfoKey = 'mask_personal_info'; + static const _proxyUrlKey = 'app_proxy_url'; + static const _proxyEnabledKey = 'app_proxy_enabled'; final FlutterSecureStorage _secure; final SharedPreferences _prefs; @@ -203,6 +205,11 @@ class StorageService { Future setMaskPersonalInfo(bool value) => _prefs.setBool(_maskPersonalInfoKey, value); + String get appProxyUrl => _prefs.getString(_proxyUrlKey) ?? ''; + Future setAppProxyUrl(String value) => _prefs.setString(_proxyUrlKey, value); + bool get appProxyEnabled => _prefs.getBool(_proxyEnabledKey) ?? false; + Future setAppProxyEnabled(bool value) => _prefs.setBool(_proxyEnabledKey, value); + bool get useLocalhost => !kReleaseMode && (_prefs.getBool(_useLocalhostKey) ?? false); Future setUseLocalhost(bool value) => @@ -315,6 +322,14 @@ class StorageService { // Assignments cache (non-sensitive — stored as JSON in SharedPreferences) static const _assignmentsKey = 'cached_assignments'; + bool get hasCachedAssignments => _prefs.containsKey(_assignmentsKey); + + bool get deadlineWidgetsEnabled => _prefs.getBool('deadline_widgets_enabled') ?? false; + + Future setDeadlineWidgetsEnabled(bool enabled) async { + await _prefs.setBool('deadline_widgets_enabled', enabled); + } + Future saveCachedAssignments(List> items) => _prefs.setString(_assignmentsKey, jsonEncode(items)); diff --git a/lib/services/uni_auth_service.dart b/lib/services/uni_auth_service.dart index b68ffbd9..ccd81263 100644 --- a/lib/services/uni_auth_service.dart +++ b/lib/services/uni_auth_service.dart @@ -3,6 +3,7 @@ import 'dart:convert'; import 'package:casdoor_flutter_sdk/casdoor_flutter_sdk.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:http/http.dart' as http; import '../pages/macos_casdoor_auth_page.dart'; @@ -69,7 +70,13 @@ class UniAuthService extends ChangeNotifier { bool get loading => _loading; - UniAuthService({DebugLogger? logger}) : _logger = logger; + UniAuthService({DebugLogger? logger, String proxyUrl = ''}) + : _logger = logger, + _proxyUrl = proxyUrl; + + String _proxyUrl; + String get proxyUrl => _proxyUrl; + void setProxyUrl(String value) => _proxyUrl = value.trim(); final DebugLogger? _logger; @@ -142,6 +149,17 @@ class UniAuthService extends ChangeNotifier { callbackUrl = await _showOhosLogin(navigator, casdoor); } else if (defaultTargetPlatform == TargetPlatform.macOS) { callbackUrl = await _showMacosLogin(navigator, casdoor); + } else if (!kIsWeb && defaultTargetPlatform == TargetPlatform.linux) { + try { + callbackUrl = await const MethodChannel('techpie/uni_auth') + .invokeMethod('authenticate', { + 'url': casdoor.getSigninUrl().toString(), + 'proxy': proxyUrl, + }) ?? ''; + } on PlatformException catch (error) { + if (error.code == 'CANCELLED') throw CasdoorAuthCancelledException(); + rethrow; + } } else { callbackUrl = await casdoor.showFullscreen(context); } diff --git a/lib/widgets/app_shell/app_shell.dart b/lib/widgets/app_shell/app_shell.dart index 477618a0..b050a707 100644 --- a/lib/widgets/app_shell/app_shell.dart +++ b/lib/widgets/app_shell/app_shell.dart @@ -24,6 +24,7 @@ import 'mobile_shell.dart'; /// root navigator on a phone. A value set before the shell mounts waits for it, /// which is what a cold start needs. final appShellPendingEcardEntry = ValueNotifier(null); +final appShellPendingDeadlines = ValueNotifier(false); class AppShell extends StatefulWidget { const AppShell({super.key}); @@ -87,6 +88,10 @@ class _AppShellState extends State { void initState() { super.initState(); appShellPendingEcardEntry.addListener(_showPendingEcardEntry); + appShellPendingDeadlines.addListener(_showDeadlines); + if (appShellPendingDeadlines.value) { + WidgetsBinding.instance.addPostFrameCallback((_) => _showDeadlines()); + } if (appShellPendingEcardEntry.value != null) { // Deferred: a push during the first build is a build-time side effect. WidgetsBinding.instance.addPostFrameCallback( @@ -98,9 +103,17 @@ class _AppShellState extends State { @override void dispose() { appShellPendingEcardEntry.removeListener(_showPendingEcardEntry); + appShellPendingDeadlines.removeListener(_showDeadlines); super.dispose(); } + void _showDeadlines() { + if (!mounted || !appShellPendingDeadlines.value) return; + appShellPendingDeadlines.value = false; + _contentNavigatorKeys[2]?.currentState?.popUntil((route) => route.isFirst); + _onDestinationSelected(2); + } + /// Pushes the entry the host asked for into the destination the user is on. void _showPendingEcardEntry() { final entry = appShellPendingEcardEntry.value; diff --git a/linux/runner/CMakeLists.txt b/linux/runner/CMakeLists.txt index e97dabc7..e9392049 100644 --- a/linux/runner/CMakeLists.txt +++ b/linux/runner/CMakeLists.txt @@ -9,6 +9,8 @@ project(runner LANGUAGES CXX) add_executable(${BINARY_NAME} "main.cc" "my_application.cc" + "deadline_snapshot_store.cc" + "uni_auth_window.cc" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" ) @@ -22,5 +24,9 @@ add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") # Add dependency libraries. Add any application-specific dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter) target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) +pkg_check_modules(JSON_GLIB REQUIRED IMPORTED_TARGET json-glib-1.0) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::JSON_GLIB) +pkg_check_modules(WEBKIT REQUIRED IMPORTED_TARGET webkit2gtk-4.1) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::WEBKIT) target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/linux/runner/deadline_snapshot_store.cc b/linux/runner/deadline_snapshot_store.cc new file mode 100644 index 00000000..befd0603 --- /dev/null +++ b/linux/runner/deadline_snapshot_store.cc @@ -0,0 +1,92 @@ +#include "deadline_snapshot_store.h" + +#include +#include +#include +#include + +static gboolean number(JsonObject* object, const char* key) { + if (!json_object_has_member(object, key)) return FALSE; + JsonNode* node = json_object_get_member(object, key); + if (!JSON_NODE_HOLDS_VALUE(node)) return FALSE; + const GType type = json_node_get_value_type(node); + if (type != G_TYPE_INT64 && type != G_TYPE_DOUBLE) return FALSE; + const double value = json_node_get_double(node); + return std::isfinite(value) && value >= 0 && value <= 253402300799.0; +} + +static const gchar* string(JsonObject* object, const char* key, gsize limit) { + if (!json_object_has_member(object, key)) return nullptr; + JsonNode* node = json_object_get_member(object, key); + if (!JSON_NODE_HOLDS_VALUE(node) || json_node_get_value_type(node) != G_TYPE_STRING) + return nullptr; + const gchar* value = json_node_get_string(node); + return value && std::strlen(value) <= limit ? value : nullptr; +} + +gchar* deadline_snapshot_path() { + return g_build_filename(g_get_user_data_dir(), "techpie", "widgets", + "deadline-widget-v1.json", nullptr); +} + +gboolean deadline_snapshot_valid(const gchar* json, gsize length) { + if (!json || length > 262144 || std::strlen(json) != length) return FALSE; + g_autoptr(JsonParser) parser = json_parser_new(); + if (!json_parser_load_from_data(parser, json, length, nullptr)) return FALSE; + JsonNode* root = json_parser_get_root(parser); + if (!root || !JSON_NODE_HOLDS_OBJECT(root)) return FALSE; + JsonObject* object = json_node_get_object(root); + if (json_object_get_size(object) != 3 || !number(object, "schemaVersion") || + json_object_get_double_member(object, "schemaVersion") != 1 || + !number(object, "writtenAt") || !json_object_has_member(object, "items")) + return FALSE; + JsonNode* items_node = json_object_get_member(object, "items"); + if (!JSON_NODE_HOLDS_ARRAY(items_node)) return FALSE; + JsonArray* items = json_node_get_array(items_node); + if (json_array_get_length(items) > 512) return FALSE; + g_autoptr(GHashTable) ids = g_hash_table_new(g_str_hash, g_str_equal); + for (guint i = 0; i < json_array_get_length(items); i++) { + JsonNode* node = json_array_get_element(items, i); + if (!JSON_NODE_HOLDS_OBJECT(node)) return FALSE; + JsonObject* item = json_node_get_object(node); + const gchar* id = string(item, "id", 4096); + const gchar* kind = string(item, "kind", 16); + if (json_object_get_size(item) != 5 || !id || !*id || !kind || + (g_strcmp0(kind, "exam") && g_strcmp0(kind, "assignment")) || + !string(item, "title", 4096) || !string(item, "course", 4096) || + !number(item, "dueAt") || g_hash_table_contains(ids, id)) return FALSE; + g_hash_table_add(ids, const_cast(id)); + } + return TRUE; +} + +gboolean deadline_snapshot_write(const gchar* json, GError** error) { + if (!deadline_snapshot_valid(json, json ? std::strlen(json) : 0)) { + g_set_error_literal(error, G_IO_ERROR, G_IO_ERROR_INVALID_DATA, "Invalid deadline snapshot"); + return FALSE; + } + g_autofree gchar* path = deadline_snapshot_path(); + g_autofree gchar* directory = g_path_get_dirname(path); + if (g_mkdir_with_parents(directory, 0700) != 0 || g_chmod(directory, 0700) != 0) { + g_set_error_literal(error, G_IO_ERROR, G_IO_ERROR_FAILED, "Cannot create widget directory"); + return FALSE; + } + return g_file_set_contents_full(path, json, -1, + static_cast(G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_DURABLE), + 0600, error); +} + +gboolean deadline_snapshot_clear(GError** error) { + g_autofree gchar* path = deadline_snapshot_path(); + g_autoptr(GFile) file = g_file_new_for_path(path); + g_autoptr(GError) local = nullptr; + if (g_file_delete(file, nullptr, &local) || + g_error_matches(local, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) return TRUE; + g_propagate_error(error, g_steal_pointer(&local)); + return FALSE; +} + +gboolean deadline_uri_valid(const gchar* uri) { + return g_strcmp0(uri, "techpie://deadlines") == 0 || + g_strcmp0(uri, "techpie://deadlines/") == 0; +} diff --git a/linux/runner/deadline_snapshot_store.h b/linux/runner/deadline_snapshot_store.h new file mode 100644 index 00000000..216cac38 --- /dev/null +++ b/linux/runner/deadline_snapshot_store.h @@ -0,0 +1,10 @@ +#pragma once + +#include + +// Display-only v1 snapshot. Paths always belong to the current user's XDG data. +gchar* deadline_snapshot_path(); +gboolean deadline_snapshot_valid(const gchar* json, gsize length); +gboolean deadline_snapshot_write(const gchar* json, GError** error); +gboolean deadline_snapshot_clear(GError** error); +gboolean deadline_uri_valid(const gchar* uri); diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc index 60d12536..6f5da637 100644 --- a/linux/runner/my_application.cc +++ b/linux/runner/my_application.cc @@ -1,4 +1,6 @@ #include "my_application.h" +#include "deadline_snapshot_store.h" +#include "uni_auth_window.h" #include #ifdef GDK_WINDOWING_X11 @@ -10,10 +12,38 @@ struct _MyApplication { GtkApplication parent_instance; char** dart_entrypoint_arguments; + FlMethodChannel* deadline_channel; + gboolean pending_deadlines; + UniAuthWindow* uni_auth_window; }; G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) +static void deadline_call(FlMethodChannel* channel, FlMethodCall* call, gpointer data) { + MyApplication* self = MY_APPLICATION(data); + const gchar* method = fl_method_call_get_name(call); + g_autoptr(FlMethodResponse) response = nullptr; + if (g_str_equal(method, "consumePendingRoute")) { + g_autoptr(FlValue) value = fl_value_new_bool(self->pending_deadlines); + response = FL_METHOD_RESPONSE(fl_method_success_response_new(value)); + } else if (g_str_equal(method, "acknowledgePendingRoute")) { + self->pending_deadlines = FALSE; + response = FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); + } else if (g_str_equal(method, "publish") || g_str_equal(method, "clear")) { + g_autoptr(GError) error = nullptr; + FlValue* args = fl_method_call_get_args(call); + gboolean ok; + if (g_str_equal(method, "clear")) ok = deadline_snapshot_clear(&error); + else ok = deadline_snapshot_write( + args && fl_value_get_type(args) == FL_VALUE_TYPE_STRING ? fl_value_get_string(args) : nullptr, + &error); + response = ok ? FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)) + : FL_METHOD_RESPONSE(fl_method_error_response_new("DEADLINE_WIDGET_STORAGE_UNAVAILABLE", + error ? error->message : "Invalid snapshot", nullptr)); + } else response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); + fl_method_call_respond(call, response, nullptr); +} + // Called when first Flutter frame received. static void first_frame_cb(MyApplication* self, FlView* view) { gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); @@ -22,6 +52,11 @@ static void first_frame_cb(MyApplication* self, FlView* view) { // Implements GApplication::activate. static void my_application_activate(GApplication* application) { MyApplication* self = MY_APPLICATION(application); + GtkWindow* existing = gtk_application_get_active_window(GTK_APPLICATION(application)); + if (existing) { + gtk_window_present(existing); + return; + } GtkWindow* window = GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); @@ -74,6 +109,14 @@ static void my_application_activate(GApplication* application) { gtk_widget_realize(GTK_WIDGET(view)); fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + delete self->uni_auth_window; + self->uni_auth_window = new UniAuthWindow( + fl_engine_get_binary_messenger(fl_view_get_engine(view)), window); + g_clear_object(&self->deadline_channel); + g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); + self->deadline_channel = fl_method_channel_new(fl_engine_get_binary_messenger(fl_view_get_engine(view)), + "techpie/deadline_widgets", FL_METHOD_CODEC(codec)); + fl_method_channel_set_method_call_handler(self->deadline_channel, deadline_call, self, nullptr); gtk_widget_grab_focus(GTK_WIDGET(view)); } @@ -93,6 +136,15 @@ static gboolean my_application_local_command_line(GApplication* application, return TRUE; } + for (guint i = 1; (*arguments)[i]; i++) { + if (deadline_uri_valid((*arguments)[i])) { + g_autoptr(GFile) file = g_file_new_for_uri((*arguments)[i]); + GFile* files[] = {file}; + g_application_open(application, files, 1, ""); + *exit_status = 0; + return TRUE; + } + } g_application_activate(application); *exit_status = 0; @@ -108,6 +160,24 @@ static void my_application_startup(GApplication* application) { G_APPLICATION_CLASS(my_application_parent_class)->startup(application); } +static void my_application_open(GApplication* application, GFile** files, gint count, + const gchar*) { + MyApplication* self = MY_APPLICATION(application); + gboolean accepted = FALSE; + for (gint i = 0; i < count; i++) { + g_autofree gchar* uri = g_file_get_uri(files[i]); + if (deadline_uri_valid(uri)) accepted = TRUE; + } + if (!accepted) return; + const gboolean running = self->deadline_channel && + gtk_application_get_active_window(GTK_APPLICATION(application)); + self->pending_deadlines = TRUE; + g_application_activate(application); + if (running) + fl_method_channel_invoke_method(self->deadline_channel, "openDeadlines", nullptr, + nullptr, nullptr, nullptr); +} + // Implements GApplication::shutdown. static void my_application_shutdown(GApplication* application) { // MyApplication* self = MY_APPLICATION(object); @@ -120,12 +190,16 @@ static void my_application_shutdown(GApplication* application) { // Implements GObject::dispose. static void my_application_dispose(GObject* object) { MyApplication* self = MY_APPLICATION(object); + delete self->uni_auth_window; + self->uni_auth_window = nullptr; g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + g_clear_object(&self->deadline_channel); G_OBJECT_CLASS(my_application_parent_class)->dispose(object); } static void my_application_class_init(MyApplicationClass* klass) { G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->open = my_application_open; G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; G_APPLICATION_CLASS(klass)->startup = my_application_startup; @@ -144,5 +218,5 @@ MyApplication* my_application_new() { return MY_APPLICATION(g_object_new(my_application_get_type(), "application-id", APPLICATION_ID, "flags", - G_APPLICATION_NON_UNIQUE, nullptr)); + G_APPLICATION_HANDLES_OPEN, nullptr)); } diff --git a/linux/runner/uni_auth_window.cc b/linux/runner/uni_auth_window.cc new file mode 100644 index 00000000..273771d2 --- /dev/null +++ b/linux/runner/uni_auth_window.cc @@ -0,0 +1,151 @@ +#include "uni_auth_window.h" + +UniAuthWindow::UniAuthWindow(FlBinaryMessenger* messenger, GtkWindow* parent) + : parent_(parent) { + g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); + channel_ = fl_method_channel_new(messenger, "techpie/uni_auth", FL_METHOD_CODEC(codec)); + fl_method_channel_set_method_call_handler(channel_, + [](FlMethodChannel*, FlMethodCall* call, gpointer data) { + auto* self = static_cast(data); + if (g_str_equal(fl_method_call_get_name(call), "authenticate")) { + self->Authenticate(call); + } else { + g_autoptr(FlMethodResponse) response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); + fl_method_call_respond(call, response, nullptr); + } + }, this, nullptr); +} + +UniAuthWindow::~UniAuthWindow() { + if (window_) gtk_widget_destroy(window_); + fl_method_channel_set_method_call_handler(channel_, nullptr, nullptr, nullptr); + g_clear_object(&channel_); +} + +void UniAuthWindow::Complete(const gchar* callback) { + if (!pending_) return; + g_autoptr(FlMethodResponse) response = nullptr; + if (callback) { + g_autoptr(FlValue) value = fl_value_new_string(callback); + response = FL_METHOD_RESPONSE(fl_method_success_response_new(value)); + } else { + response = FL_METHOD_RESPONSE(fl_method_error_response_new("CANCELLED", "Login cancelled", nullptr)); + } + fl_method_call_respond(pending_, response, nullptr); + g_clear_object(&pending_); +} + +void UniAuthWindow::Authenticate(FlMethodCall* call) { + FlValue* args = fl_method_call_get_args(call); + const gchar* url = nullptr; + const gchar* proxy = nullptr; + if (args && fl_value_get_type(args) == FL_VALUE_TYPE_MAP) { + FlValue* url_value = fl_value_lookup_string(args, "url"); + FlValue* proxy_value = fl_value_lookup_string(args, "proxy"); + if (url_value && fl_value_get_type(url_value) == FL_VALUE_TYPE_STRING) url = fl_value_get_string(url_value); + if (proxy_value && fl_value_get_type(proxy_value) == FL_VALUE_TYPE_STRING) proxy = fl_value_get_string(proxy_value); + } + g_autoptr(GUri) uri = url ? g_uri_parse(url, G_URI_FLAGS_NONE, nullptr) : nullptr; + if (!uri || g_strcmp0(g_uri_get_scheme(uri), "https") || + g_strcmp0(g_uri_get_host(uri), "auth.geekpie.club")) { + fl_method_call_respond_error(call, "INVALID_URL", "Invalid authorization URL", nullptr, nullptr); + return; + } + if (pending_) { + gtk_window_present(GTK_WINDOW(window_)); + fl_method_call_respond_error(call, "IN_PROGRESS", "Login already open", nullptr, nullptr); + return; + } + pending_ = FL_METHOD_CALL(g_object_ref(call)); + window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_window_set_title(GTK_WINDOW(window_), "GeekPie UniAuth"); + gtk_window_set_default_size(GTK_WINDOW(window_), 520, 720); + gtk_window_set_transient_for(GTK_WINDOW(window_), parent_); + gtk_window_set_destroy_with_parent(GTK_WINDOW(window_), TRUE); + gtk_window_set_modal(GTK_WINDOW(window_), TRUE); + g_signal_connect(window_, "destroy", G_CALLBACK(+[](GtkWidget*, gpointer data) { + auto* self = static_cast(data); + self->window_ = self->status_ = nullptr; + self->webview_ = nullptr; + self->Complete(nullptr); + }), this); + + GtkWidget* box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 8); + gtk_container_add(GTK_CONTAINER(window_), box); + GtkWidget* header = gtk_header_bar_new(); + gtk_header_bar_set_title(GTK_HEADER_BAR(header), "GeekPie UniAuth"); + gtk_header_bar_set_show_close_button(GTK_HEADER_BAR(header), TRUE); + gtk_window_set_titlebar(GTK_WINDOW(window_), header); + GtkWidget* retry = gtk_button_new_with_label("重新加载"); + gtk_header_bar_pack_start(GTK_HEADER_BAR(header), retry); + g_signal_connect(retry, "clicked", G_CALLBACK(+[](GtkButton*, gpointer data) { + auto* self = static_cast(data); + if (self->webview_) webkit_web_view_reload(self->webview_); + }), this); + status_ = gtk_label_new("正在加载登录页…"); + gtk_label_set_line_wrap(GTK_LABEL(status_), TRUE); + gtk_box_pack_start(GTK_BOX(box), status_, FALSE, FALSE, 4); + g_autoptr(WebKitWebContext) context = webkit_web_context_new_ephemeral(); + if (proxy && *proxy) { + g_autoptr(WebKitNetworkProxySettings) settings = webkit_network_proxy_settings_new(nullptr, nullptr); + webkit_network_proxy_settings_add_proxy_for_scheme(settings, "http", proxy); + webkit_network_proxy_settings_add_proxy_for_scheme(settings, "https", proxy); + webkit_website_data_manager_set_network_proxy_settings( + webkit_web_context_get_website_data_manager(context), WEBKIT_NETWORK_PROXY_MODE_CUSTOM, settings); + } else { + webkit_website_data_manager_set_network_proxy_settings( + webkit_web_context_get_website_data_manager(context), WEBKIT_NETWORK_PROXY_MODE_NO_PROXY, nullptr); + } + webview_ = WEBKIT_WEB_VIEW(webkit_web_view_new_with_context(context)); + // Avoid the WebKit/NVIDIA EGL rendering path in this small login window. + webkit_settings_set_hardware_acceleration_policy(webkit_web_view_get_settings(webview_), + WEBKIT_HARDWARE_ACCELERATION_POLICY_NEVER); + gtk_box_pack_start(GTK_BOX(box), GTK_WIDGET(webview_), TRUE, TRUE, 0); + g_signal_connect(webview_, "load-changed", G_CALLBACK(+[](WebKitWebView*, WebKitLoadEvent event, gpointer data) { + auto* self = static_cast(data); + if (!self->status_) return; + if (event == WEBKIT_LOAD_STARTED) { + gtk_label_set_text(GTK_LABEL(self->status_), "正在加载登录页…"); + gtk_widget_show(self->status_); + } else if (event == WEBKIT_LOAD_COMMITTED) { + gtk_widget_hide(self->status_); + } + }), this); + g_signal_connect(webview_, "load-failed", G_CALLBACK(+[](WebKitWebView*, WebKitLoadEvent, + const gchar*, GError* error, gpointer data) -> gboolean { + auto* self = static_cast(data); + if (!self->status_ || g_error_matches(error, WEBKIT_NETWORK_ERROR, WEBKIT_NETWORK_ERROR_CANCELLED)) return FALSE; + gtk_label_set_text(GTK_LABEL(self->status_), "登录页加载失败,请检查网络后点击“重新加载”。"); + gtk_widget_show(self->status_); + return TRUE; + }), this); + g_signal_connect(webview_, "decide-policy", G_CALLBACK(+[](WebKitWebView* view, + WebKitPolicyDecision* decision, WebKitPolicyDecisionType type, gpointer data) -> gboolean { + if (type != WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION && + type != WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION) return FALSE; + auto* self = static_cast(data); + auto* navigation = WEBKIT_NAVIGATION_POLICY_DECISION(decision); + auto* action = webkit_navigation_policy_decision_get_navigation_action(navigation); + const gchar* url = webkit_uri_request_get_uri(webkit_navigation_action_get_request(action)); + g_autoptr(GUri) uri = g_uri_parse(url, G_URI_FLAGS_NONE, nullptr); + if (uri && g_strcmp0(g_uri_get_scheme(uri), "techpie") == 0) { + webkit_policy_decision_ignore(decision); + if (g_strcmp0(g_uri_get_host(uri), "auth-callback") == 0) { + self->Complete(url); + // GTK queues the close request instead of destroying inside WebKit. + gtk_window_close(GTK_WINDOW(self->window_)); + } + return TRUE; + } + if (type == WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION) { + webkit_policy_decision_ignore(decision); + if (uri && (g_strcmp0(g_uri_get_scheme(uri), "https") == 0 || + g_strcmp0(g_uri_get_scheme(uri), "http") == 0)) + webkit_web_view_load_uri(view, url); + return TRUE; + } + return FALSE; + }), this); + gtk_widget_show_all(window_); + webkit_web_view_load_uri(webview_, url); +} diff --git a/linux/runner/uni_auth_window.h b/linux/runner/uni_auth_window.h new file mode 100644 index 00000000..a86a5e85 --- /dev/null +++ b/linux/runner/uni_auth_window.h @@ -0,0 +1,24 @@ +#ifndef RUNNER_UNI_AUTH_WINDOW_H_ +#define RUNNER_UNI_AUTH_WINDOW_H_ + +#include +#include + +// A GTK authentication window with no secondary Flutter engine. +class UniAuthWindow { + public: + UniAuthWindow(FlBinaryMessenger* messenger, GtkWindow* parent); + ~UniAuthWindow(); + + private: + void Authenticate(FlMethodCall* call); + void Complete(const gchar* callback); + GtkWindow* parent_; + GtkWidget* window_ = nullptr; + GtkWidget* status_ = nullptr; + WebKitWebView* webview_ = nullptr; + FlMethodChannel* channel_; + FlMethodCall* pending_ = nullptr; +}; + +#endif // RUNNER_UNI_AUTH_WINDOW_H_ diff --git a/linux/widgets/CMakeLists.txt b/linux/widgets/CMakeLists.txt new file mode 100644 index 00000000..e7f30a49 --- /dev/null +++ b/linux/widgets/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 3.16) +project(techpie_deadline_widgets LANGUAGES CXX) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_AUTOMOC ON) +find_package(Qt6 6.4 REQUIRED COMPONENTS Core Gui Qml) +set(KDE_PACKAGE "${CMAKE_CURRENT_BINARY_DIR}/kde") +file(COPY kde/metadata.json kde/contents DESTINATION "${KDE_PACKAGE}") +add_library(techpiedeadlines MODULE kde/backend/plugin.cpp kde/backend/deadline_model.cpp) +target_link_libraries(techpiedeadlines PRIVATE Qt6::Core Qt6::Gui Qt6::Qml) +set_target_properties(techpiedeadlines PROPERTIES + LIBRARY_OUTPUT_DIRECTORY "${KDE_PACKAGE}/contents/ui/backend") diff --git a/linux/widgets/common/snapshot.mjs b/linux/widgets/common/snapshot.mjs new file mode 100644 index 00000000..56a0eb19 --- /dev/null +++ b/linux/widgets/common/snapshot.mjs @@ -0,0 +1,48 @@ +export const MAX_BYTES = 262144; +export const MAX_ITEMS = 512; +const timestamp = value => typeof value === 'number' && Number.isFinite(value) && + value >= 0 && value <= 253402300799; +const text = value => typeof value === 'string' && new TextEncoder().encode(value).length <= 4096; + +// Keep this parser independent of Shell/Qt so fixtures run in Node and GJS. +export function decodeSnapshot(json) { + if (typeof json !== 'string' || new TextEncoder().encode(json).length > MAX_BYTES) + throw new Error('Snapshot is too large'); + const snapshot = JSON.parse(json); + if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot) || + Object.keys(snapshot).sort().join(',') !== 'items,schemaVersion,writtenAt' || + snapshot.schemaVersion !== 1 || !timestamp(snapshot.writtenAt) || + !Array.isArray(snapshot.items) || snapshot.items.length > MAX_ITEMS) + throw new Error('Invalid snapshot'); + const ids = new Set(); + for (const item of snapshot.items) { + if (!item || typeof item !== 'object' || Array.isArray(item) || + Object.keys(item).sort().join(',') !== 'course,dueAt,id,kind,title' || + !text(item.id) || !item.id || ids.has(item.id) || + !['assignment', 'exam'].includes(item.kind) || !text(item.title) || + !text(item.course) || !timestamp(item.dueAt)) + throw new Error('Invalid item'); + ids.add(item.id); + } + return snapshot; +} + +export function upcoming(snapshot, now = Date.now() / 1000, limit = 8) { + return snapshot.items.filter(item => item.dueAt > now) + .sort((a, b) => a.dueAt - b.dueAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)) + .slice(0, Math.max(0, limit)); +} + +export function remaining(dueAt, now = Date.now() / 1000) { + const hours = Math.floor((dueAt - now) / 3600); + if (dueAt <= now) return ''; + if (hours === 0) return '<1h'; + return hours < 24 ? `${hours}h` : `${Math.floor(hours / 24)}d ${hours % 24}h`; +} + +export function urgency(dueAt, now = Date.now() / 1000) { + const seconds = dueAt - now; + if (seconds <= 0) return 'normal'; + if (seconds <= 12 * 3600) return 'urgent'; + return seconds <= 36 * 3600 ? 'soon' : 'normal'; +} diff --git a/linux/widgets/gnome/desktopCard.js b/linux/widgets/gnome/desktopCard.js new file mode 100644 index 00000000..c148a532 --- /dev/null +++ b/linux/widgets/gnome/desktopCard.js @@ -0,0 +1,164 @@ +import Clutter from 'gi://Clutter'; +import St from 'gi://St'; +import Meta from 'gi://Meta'; +import * as Main from 'resource:///org/gnome/shell/ui/main.js'; +import {upcoming, remaining, urgency} from './snapshot.mjs'; + +function column(properties = {}) { + const direction = 'orientation' in St.BoxLayout.prototype + ? {orientation: Clutter.Orientation.VERTICAL} : {vertical: true}; + return new St.BoxLayout({...direction, ...properties}); +} + +// Kept below application windows; no reserved screen area or lock-screen actor. +export class DesktopCard { + constructor(settings, open) { + this._settings = settings; + this._open = open; + this.actor = column({style_class: 'popup-menu-content techpie-desktop-card', + reactive: true, x_expand: false, y_expand: false, + x_align: Clutter.ActorAlign.START, y_align: Clutter.ActorAlign.START}); + this._header = new St.Label({text: 'TechPie · Deadlines', reactive: true, + style_class: 'techpie-desktop-header'}); + this.actor.add_child(this._header); + this._rows = column({style_class: 'techpie-desktop-rows'}); + this.actor.add_child(this._rows); + this._footer = new St.Label({style_class: 'techpie-deadline-detail'}); + this.actor.add_child(this._footer); + const button = new St.Button({label: 'Open TechPie', can_focus: true, + style_class: 'button'}); + button.connect('clicked', open); + this.actor.add_child(button); + this._windowGroup = global.window_group; + this._windowGroup.add_child(this.actor); + Main.layoutManager.trackChrome(this.actor, {affectsStruts: false}); + this._signals = [ + [settings, settings.connect('changed', () => this._position())], + [Main.layoutManager, Main.layoutManager.connect('monitors-changed', () => this._position())], + [global.display, global.display.connect('workareas-changed', () => this._position())], + [global.display, global.display.connect('in-fullscreen-changed', () => this._position())], + [global.display, global.display.connect('restacked', () => this._restack())], + [this._windowGroup, this._windowGroup.connect('child-added', () => this._restack())], + ]; + this._header.connect('button-press-event', (_actor, event) => { + if (event.get_button() !== 1) return Clutter.EVENT_PROPAGATE; + const [x, y] = event.get_coords(); + this._drag = [x - this.actor.x, y - this.actor.y]; + this._grab = global.stage.grab(this._header); + return Clutter.EVENT_STOP; + }); + this._header.connect('motion-event', (_actor, event) => { + if (!this._drag) return Clutter.EVENT_PROPAGATE; + const [x, y] = event.get_coords(); + const bounds = this._bounds(); + if (bounds) this.actor.set_position( + Math.max(bounds.x, Math.min(bounds.x + bounds.width, x - this._drag[0])), + Math.max(bounds.y, Math.min(bounds.y + bounds.height, y - this._drag[1]))); + return Clutter.EVENT_STOP; + }); + this._header.connect('button-release-event', () => { + if (!this._drag) return Clutter.EVENT_PROPAGATE; + const bounds = this._bounds(); + const x = bounds?.width ? (this.actor.x - bounds.x) / bounds.width : 1; + const y = bounds?.height ? (this.actor.y - bounds.y) / bounds.height : 0; + this._endDrag(); + settings.set_double('position-x', x); + settings.set_double('position-y', y); + return Clutter.EVENT_STOP; + }); + this._restack(); + this._position(); + } + + _restack() { + // Desktop icon extensions use a transparent desktop window which still + // receives pointer events. Place the card above it, below normal apps. + const sibling = this._windowGroup.get_children().find(child => { + const window = child.get_meta_window?.(); + return window && window.get_window_type() !== Meta.WindowType.DESKTOP; + }); + if (sibling) this._windowGroup.set_child_below_sibling(this.actor, sibling); + else this._windowGroup.set_child_above_sibling(this.actor, null); + } + + _bounds() { + const monitor = Main.layoutManager.primaryMonitor; + if (!monitor) return null; + const area = Main.layoutManager.getWorkAreaForMonitor(monitor.index); + // Clear the previous request before measuring, so removing content + // can shrink the card as well as adding content can grow it. + this.actor.set_size(-1, -1); + const [, naturalWidth] = this.actor.get_preferred_width(-1); + const maxWidth = Math.min(440, Math.max(1, area.width - 48)); + this.actor.width = Math.min(maxWidth, Math.max(300, naturalWidth)); + const [, height] = this.actor.get_preferred_height(this.actor.width); + this.actor.height = height; + return {x: area.x + 24, y: area.y + 24, + width: Math.max(0, area.width - this.actor.width - 48), + height: Math.max(0, area.height - height - 48)}; + } + + _endDrag() { + const grab = this._grab; + this._grab = this._drag = null; + grab?.dismiss(); + } + + _position() { + this._endDrag(); + const bounds = this._bounds(); + this.actor.visible = Boolean(bounds && this._settings.get_boolean('desktop-visible') && + !Main.layoutManager.primaryMonitor.inFullscreen); + if (bounds) this.actor.set_position( + bounds.x + bounds.width * this._settings.get_double('position-x'), + bounds.y + bounds.height * this._settings.get_double('position-y')); + } + + resetPosition() { + this._settings.reset('position-x'); + this._settings.reset('position-y'); + } + + update(snapshot, state) { + this._rows.destroy_all_children(); + const now = Date.now() / 1000; + const items = snapshot ? upcoming(snapshot, now).slice(0, 4) : []; + for (const item of items) { + const level = urgency(item.dueAt, now); + const row = column({style_class: `techpie-deadline-row techpie-deadline-card-${level}`, + x_expand: true, + x_align: Clutter.ActorAlign.FILL}); + const heading = new St.BoxLayout({style_class: 'techpie-deadline-heading', x_expand: true}); + heading.add_child(new St.Label({text: item.kind === 'exam' ? '考试' : '作业', + style_class: 'techpie-deadline-kind'})); + heading.add_child(new St.Label({text: item.title, x_expand: true, + style_class: 'techpie-deadline-title'})); + const time = new St.Label({text: remaining(item.dueAt, now), + style_class: `techpie-deadline-time techpie-deadline-time-${level}`}); + heading.add_child(time); + row.add_child(heading); + const due = new Date(item.dueAt * 1000).toLocaleString(undefined, + {month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit'}); + row.add_child(new St.Label({text: `${item.course} · ${due}`, + x_expand: true, style_class: 'techpie-deadline-detail'})); + const button = new St.Button({child: row, x_expand: true, can_focus: true, + style_class: 'techpie-desktop-item'}); + button.connect('clicked', this._open); + this._rows.add_child(button); + } + if (!items.length) this._rows.add_child(new St.Label({ + text: state === 'unavailable' ? 'Deadline data is unavailable' : snapshot + ? 'No upcoming deadlines' : 'Enable Deadline widgets\nin TechPie Settings', + })); + this._footer.text = snapshot + ? `Cached · ${new Date(snapshot.writtenAt * 1000).toLocaleString()}` : 'Drag the heading to move'; + this._position(); + } + + destroy() { + this._endDrag(); + for (const [object, signal] of this._signals) object.disconnect(signal); + Main.layoutManager.untrackChrome(this.actor); + this.actor.destroy(); + } +} diff --git a/linux/widgets/gnome/extension.js b/linux/widgets/gnome/extension.js new file mode 100644 index 00000000..ee01554d --- /dev/null +++ b/linux/widgets/gnome/extension.js @@ -0,0 +1,177 @@ +import Gio from 'gi://Gio'; +import GLib from 'gi://GLib'; +import St from 'gi://St'; +import Shell from 'gi://Shell'; +import Clutter from 'gi://Clutter'; +import {Extension} from 'resource:///org/gnome/shell/extensions/extension.js'; +import * as Main from 'resource:///org/gnome/shell/ui/main.js'; +import * as PanelMenu from 'resource:///org/gnome/shell/ui/panelMenu.js'; +import * as PopupMenu from 'resource:///org/gnome/shell/ui/popupMenu.js'; +import {decodeSnapshot, upcoming, remaining, urgency, MAX_BYTES} from './snapshot.mjs'; +import {readBounded} from './reader.mjs'; +import {DesktopCard} from './desktopCard.js'; + +export default class TechPieDeadlines extends Extension { + enable() { + this._alive = true; + this._generation = (this._generation ?? 0) + 1; + this._cancellable = new Gio.Cancellable(); + this._settings = this.getSettings(); + this._desktop = new DesktopCard(this._settings, () => this._open()); + this._directory = GLib.build_filenamev([GLib.get_user_data_dir(), 'techpie', 'widgets']); + this._path = GLib.build_filenamev([this._directory, 'deadline-widget-v1.json']); + this._button = new PanelMenu.Button(0.0, 'TechPie Deadlines'); + const box = new St.BoxLayout({style_class: 'panel-status-menu-box'}); + box.add_child(new St.Icon({icon_name: 'view-calendar-symbolic', style_class: 'system-status-icon'})); + this._label = new St.Label({text: 'TechPie', y_align: Clutter.ActorAlign.CENTER}); + box.add_child(this._label); + this._button.add_child(box); + Main.panel.addToStatusArea(this.uuid, this._button); + this._button.menu.connect('open-state-changed', (_menu, open) => { + if (open) this._reload().catch(error => console.error(error)); + }); + this._watch(); + this._reload().catch(error => console.error(error)); + this._timer = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 30, () => { + this._watch(); + this._reload().catch(error => console.error(error)); + return GLib.SOURCE_CONTINUE; + }); + } + + _watch() { + // Watch the closest existing ancestor as the app may not have created + // its directory yet. Reattach after creation or an atomic replacement. + let directory = Gio.File.new_for_path(this._directory); + while (!directory.query_exists(null) && directory.get_parent()) + directory = directory.get_parent(); + const path = directory.get_path(); + if (this._watched === path) return; + this._clearMonitor(); + try { + this._monitor = directory.monitor_directory(Gio.FileMonitorFlags.WATCH_MOVES, this._cancellable); + this._watched = path; + this._monitorSignal = this._monitor.connect('changed', () => { + if (!this._alive) return; + if (this._debounce) GLib.Source.remove(this._debounce); + this._debounce = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 100, () => { + this._debounce = 0; + this._watch(); + this._reload().catch(error => console.error(error)); + return GLib.SOURCE_REMOVE; + }); + }); + } catch (_) { /* Retry on the periodic tick. */ } + } + + _clearMonitor() { + if (this._monitor) { + if (this._monitorSignal) this._monitor.disconnect(this._monitorSignal); + this._monitor.cancel(); + } + this._monitor = null; + this._monitorSignal = 0; + this._watched = null; + } + + async _reload() { + const generation = ++this._generation; + try { + const file = Gio.File.new_for_path(this._path); + const json = await readBounded(file, MAX_BYTES, this._cancellable); + if (!this._alive || generation !== this._generation) return; + this._snapshot = decodeSnapshot(json); + this._state = 'ready'; + } catch (error) { + if (!this._alive || generation !== this._generation) return; + this._snapshot = null; + this._state = error.matches?.(Gio.IOErrorEnum, Gio.IOErrorEnum.NOT_FOUND) + ? 'notSynced' : 'unavailable'; + } + this._render(); + } + + _open() { + const timestamp = global.get_current_time(); + this._button.menu.close(); + // Activate through Shell as well as delivering the URI: on Wayland an + // existing GTK window cannot always raise itself without user input. + const app = Shell.AppSystem.get_default().lookup_app('com.example.techpie.desktop'); + app?.activate(); + Gio.AppInfo.launch_default_for_uri_async('techpie://deadlines', + global.create_app_launch_context(timestamp, -1), this._cancellable, (_source, result) => { + try { Gio.AppInfo.launch_default_for_uri_finish(result); } + catch (_) { + if (this._alive) Main.notify('TechPie', 'Install the TechPie desktop launcher to open deadlines.'); + } + }); + } + + _render() { + if (!this._alive) return; + const menu = this._button.menu; + menu.removeAll(); + const now = Date.now() / 1000; + const items = this._snapshot ? upcoming(this._snapshot, now) : []; + this._desktop.update(this._snapshot, this._state); + this._label.text = items.length ? remaining(items[0].dueAt, now) : 'TechPie'; + this._label.style_class = items.length + ? `techpie-deadline-time-${urgency(items[0].dueAt, now)}` : ''; + if (!this._snapshot || !items.length) { + const message = this._state === 'unavailable' ? 'Deadline data is unavailable' : + this._snapshot ? 'No upcoming deadlines' : 'Enable Deadline widgets in TechPie Settings'; + menu.addMenuItem(new PopupMenu.PopupMenuItem(message, {reactive: false})); + } + for (const item of items) { + const row = new PopupMenu.PopupMenuItem(''); + const direction = 'orientation' in St.BoxLayout.prototype + ? {orientation: Clutter.Orientation.VERTICAL} : {vertical: true}; + const level = urgency(item.dueAt, now); + const box = new St.BoxLayout({...direction, + style_class: `techpie-deadline-row techpie-deadline-card-${level}`}); + const heading = new St.BoxLayout({style_class: 'techpie-deadline-heading'}); + heading.add_child(new St.Label({text: `${item.kind === 'exam' ? '考试' : '作业'} ${item.title}`, + style_class: 'techpie-deadline-title', x_expand: true})); + heading.add_child(new St.Label({text: remaining(item.dueAt, now), + style_class: `techpie-deadline-time techpie-deadline-time-${level}`})); + box.add_child(heading); + box.add_child(new St.Label({text: `${item.course} · ${new Date(item.dueAt * 1000).toLocaleString()}`, + style_class: 'techpie-deadline-detail'})); + row.add_child(box); + row.connect('activate', () => this._open()); + menu.addMenuItem(row); + } + menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); + const visible = new PopupMenu.PopupSwitchMenuItem('Desktop card', + this._settings.get_boolean('desktop-visible')); + visible.connect('toggled', (_item, value) => this._settings.set_boolean('desktop-visible', value)); + menu.addMenuItem(visible); + const reset = new PopupMenu.PopupMenuItem('Reset desktop card position'); + reset.connect('activate', () => this._desktop.resetPosition()); + menu.addMenuItem(reset); + const open = new PopupMenu.PopupMenuItem('Open TechPie Deadlines'); + open.connect('activate', () => this._open()); + menu.addMenuItem(open); + if (this._snapshot) { + menu.addMenuItem(new PopupMenu.PopupMenuItem( + `Cached snapshot · ${new Date(this._snapshot.writtenAt * 1000).toLocaleString()}`, + {reactive: false})); + } + } + + disable() { + this._alive = false; + this._generation++; + this._cancellable?.cancel(); + this._clearMonitor(); + if (this._timer) GLib.Source.remove(this._timer); + if (this._debounce) GLib.Source.remove(this._debounce); + this._timer = this._debounce = 0; + this._monitor = this._cancellable = null; + this._watched = this._snapshot = null; + this._button?.destroy(); + this._desktop?.destroy(); + this._desktop = this._settings = null; + this._button = this._label = null; + } +} diff --git a/linux/widgets/gnome/metadata.json b/linux/widgets/gnome/metadata.json new file mode 100644 index 00000000..0141069e --- /dev/null +++ b/linux/widgets/gnome/metadata.json @@ -0,0 +1,9 @@ +{ + "uuid": "deadlines@techpie.geekpie.club", + "name": "TechPie Deadlines", + "description": "Upcoming TechPie assignments and exams from a local display-only snapshot.", + "shell-version": ["45", "46", "47", "48", "49", "50", "51"], + "version": 1, + "settings-schema": "org.gnome.shell.extensions.techpie-deadlines", + "url": "https://github.com/HeZeBang/TechPie-flutter" +} diff --git a/linux/widgets/gnome/reader.mjs b/linux/widgets/gnome/reader.mjs new file mode 100644 index 00000000..ae883005 --- /dev/null +++ b/linux/widgets/gnome/reader.mjs @@ -0,0 +1,39 @@ +import Gio from 'gi://Gio'; +import GLib from 'gi://GLib'; + +// Bound allocation even if another local process replaces the snapshot with a +// large file. read_bytes_async may return a short read before EOF. +export async function readBounded(file, maximum, cancellable) { + const stream = await new Promise((resolve, reject) => { + file.read_async(GLib.PRIORITY_DEFAULT, cancellable, (source, result) => { + try { resolve(source.read_finish(result)); } + catch (error) { reject(error); } + }); + }); + try { + const parts = []; + let length = 0; + while (length <= maximum) { + const bytes = await new Promise((resolve, reject) => { + stream.read_bytes_async(Math.min(65536, maximum + 1 - length), + GLib.PRIORITY_DEFAULT, cancellable, (input, result) => { + try { resolve(input.read_bytes_finish(result).get_data()); } + catch (error) { reject(error); } + }); + }); + if (!bytes.length) break; + parts.push(bytes); + length += bytes.length; + } + if (length > maximum) throw new Error('Snapshot too large'); + const result = new Uint8Array(length); + let offset = 0; + for (const bytes of parts) { result.set(bytes, offset); offset += bytes.length; } + return new TextDecoder('utf-8', {fatal: true}).decode(result); + } finally { + await new Promise(resolve => stream.close_async(GLib.PRIORITY_DEFAULT, null, (input, result) => { + try { input.close_finish(result); } catch (_) { /* Closing during disable is harmless. */ } + resolve(); + })); + } +} diff --git a/linux/widgets/gnome/schemas/org.gnome.shell.extensions.techpie-deadlines.gschema.xml b/linux/widgets/gnome/schemas/org.gnome.shell.extensions.techpie-deadlines.gschema.xml new file mode 100644 index 00000000..cc467e55 --- /dev/null +++ b/linux/widgets/gnome/schemas/org.gnome.shell.extensions.techpie-deadlines.gschema.xml @@ -0,0 +1,18 @@ + + + + true + Show the desktop deadline card + + + + 1.0 + Horizontal position within the primary work area + + + + 0.0 + Vertical position within the primary work area + + + diff --git a/linux/widgets/gnome/stylesheet.css b/linux/widgets/gnome/stylesheet.css new file mode 100644 index 00000000..631fbfe5 --- /dev/null +++ b/linux/widgets/gnome/stylesheet.css @@ -0,0 +1,22 @@ +.techpie-deadline-row { spacing: 4px; max-width: 420px; } +.techpie-deadline-heading { spacing: 6px; } +.techpie-deadline-title { font-weight: bold; } +.techpie-deadline-kind { font-size: 0.75em; color: rgba(255, 255, 255, 0.68); } +.techpie-deadline-detail { font-size: 0.85em; color: rgba(255, 255, 255, 0.72); } +.techpie-deadline-time { padding: 3px 8px; border-radius: 999px; font-weight: bold; } +.techpie-deadline-time-urgent { color: #ed333b; } +.techpie-deadline-time-soon { color: -st-accent-color; } +.techpie-deadline-card-urgent { background-color: rgba(163, 11, 25, 0.92); } +.techpie-deadline-card-soon { background-color: rgba(163, 11, 25, 0.45); } +.techpie-deadline-card-normal { background-color: rgba(255, 255, 255, 0.08); } +.techpie-deadline-card-urgent, .techpie-deadline-card-soon, .techpie-deadline-card-normal { + padding: 9px 11px; border-radius: 12px; +} +.techpie-deadline-card-urgent .techpie-deadline-time { background-color: rgba(255, 255, 255, 0.18); color: #fff; } +.techpie-deadline-card-soon .techpie-deadline-time { background-color: rgba(163, 11, 25, 0.3); } +.techpie-deadline-card-normal .techpie-deadline-time { background-color: rgba(255, 255, 255, 0.1); } +.techpie-desktop-card { padding: 18px; spacing: 14px; border-radius: 16px; } +.techpie-desktop-header { font-weight: bold; padding: 8px 0; } +.techpie-desktop-rows { spacing: 12px; } +.techpie-desktop-item { text-align: left; border-radius: 8px; padding: 8px; } +.techpie-desktop-item:hover { background-color: rgba(128, 128, 128, 0.2); } diff --git a/linux/widgets/install.py b/linux/widgets/install.py new file mode 100644 index 00000000..8f49637d --- /dev/null +++ b/linux/widgets/install.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Install only TechPie's launcher and selected widgets for the current user.""" +import argparse +import os +from pathlib import Path +import shutil +import subprocess + +ROOT = Path(__file__).resolve().parent +KDE_ID = "club.geekpie.techpie.deadlines" +GNOME_ID = "deadlines@techpie.geekpie.club" +MARKER = ".techpie-widget-install" +# Keep the runner's existing ID: path_provider uses it for app preferences. +DESKTOP_NAME = "com.example.techpie.desktop" + + +def desktop_quote(path): + value = str(path).replace("%", "%%") + for char in ('\\', '"', '`', '$'): + value = value.replace(char, '\\' + char) + # Desktop Entry string escaping is applied before Exec argument escaping. + return ('"' + value + '"').replace('\\', '\\\\') + + +def managed_copy(source, target): + if target.is_symlink() or (target.exists() and not (target / MARKER).is_file()): + raise ValueError(f"Refusing to replace an unmanaged directory: {target}") + # Source validation occurs before any existing installation is replaced. + temporary = target.with_name(target.name + ".techpie-staging") + if temporary.exists(): + raise ValueError(f"Staging directory already exists: {temporary}") + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copytree(source, temporary) + (temporary / MARKER).write_text("TechPie deadline widgets v1\n", encoding="utf-8") + if target.exists(): + shutil.rmtree(target) + temporary.rename(target) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=["install", "uninstall"]) + parser.add_argument("--desktop", choices=["kde", "gnome", "both"], required=True) + parser.add_argument("--app", type=Path, help="Absolute path to the built bundle/techpie") + parser.add_argument("--kde-package", type=Path, default=ROOT / "kde", + help="Built KDE package from cmake, or the bundled package") + parser.add_argument("--data-home", type=Path, + default=Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share"))) + args = parser.parse_args(argv) + if not args.data_home.is_absolute(): + parser.error("--data-home must be absolute") + data = args.data_home.resolve() + targets = [] + if args.desktop in ("kde", "both"): + targets.append((args.kde_package, data / "plasma/plasmoids" / KDE_ID)) + if args.desktop in ("gnome", "both"): + targets.append((ROOT / "gnome", data / "gnome-shell/extensions" / GNOME_ID)) + launcher = data / "applications" / DESKTOP_NAME + if args.action == "install": + if args.desktop in ("gnome", "both") and not shutil.which("glib-compile-schemas"): + parser.error("GNOME installation requires glib-compile-schemas (GLib)") + if not args.app or not args.app.is_absolute() or not args.app.is_file() or not os.access(args.app, os.X_OK): + parser.error("--app must name an absolute executable TechPie bundle path") + app = args.app.resolve() + icon = app.parent / "techpie.png" + if not icon.is_file(): + icon = ROOT.parents[1] / "assets/icon/icon.png" + icon_name = str(icon).replace('\\', '\\\\') if icon.is_file() else "view-calendar-tasks" + if '\n' in str(app) or '\r' in str(app): + parser.error("Application path cannot contain newlines") + for source, target in targets: + if not (source / "metadata.json").is_file(): + parser.error(f"Missing widget package: {source}") + if target.is_symlink() or (target.exists() and not (target / MARKER).is_file()): + parser.error(f"Existing directory is not managed by this installer: {target}") + if source == args.kde_package and args.desktop in ("kde", "both") and not ( + source / "contents/ui/backend/libtechpiedeadlines.so").is_file(): + parser.error("Build the KDE backend first; pass --kde-package BUILD/kde") + if launcher.exists() and "X-TechPie-Managed=true" not in launcher.read_text(encoding="utf-8"): + parser.error(f"Launcher already exists and is not managed: {launcher}") + for source, target in targets: + managed_copy(source, target) + if target.name == GNOME_ID: + shutil.copy2(ROOT / "common/snapshot.mjs", target / "snapshot.mjs") + subprocess.run(["glib-compile-schemas", "--strict", str(target / "schemas")], check=True) + launcher.parent.mkdir(parents=True, exist_ok=True) + launcher.write_text( + "[Desktop Entry]\nType=Application\nName=TechPie\n" + f"Exec={desktop_quote(app)} %u\nIcon={icon_name}\n" + "Terminal=false\nCategories=Education;\nMimeType=x-scheme-handler/techpie;\n" + "StartupWMClass=com.example.techpie\nX-TechPie-Managed=true\n", encoding="utf-8") + print("Installed. Enable Deadline widgets in TechPie Settings.") + if args.desktop in ("gnome", "both"): + print(f"GNOME: log out/in if newly installed, then enable {GNOME_ID} in Extensions.") + if args.desktop in ("kde", "both"): + print("KDE: use Add Widgets and select TechPie Deadlines (restart Plasma session if needed).") + else: + for _, target in targets: + if target.is_symlink(): + parser.error(f"Refusing to remove a symlink: {target}") + if target.exists(): + if not (target / MARKER).is_file(): + parser.error(f"Refusing to remove an unmanaged directory: {target}") + for _, target in targets: + if target.exists(): + shutil.rmtree(target) + # Keep the launcher if the other desktop's widget is still installed. + other_installed = any((path / MARKER).exists() for path in ( + data / "plasma/plasmoids" / KDE_ID, data / "gnome-shell/extensions" / GNOME_ID)) + if not other_installed and launcher.exists() and "X-TechPie-Managed=true" in launcher.read_text(encoding="utf-8"): + launcher.unlink() + print("Removed selected widget packages. Application and snapshots are retained.") + update = shutil.which("update-desktop-database") + if update and launcher.parent.exists(): + subprocess.run([update, str(launcher.parent)], check=True) + + +if __name__ == "__main__": + main() diff --git a/linux/widgets/kde/backend/deadline_model.cpp b/linux/widgets/kde/backend/deadline_model.cpp new file mode 100644 index 00000000..8733a89d --- /dev/null +++ b/linux/widgets/kde/backend/deadline_model.cpp @@ -0,0 +1,83 @@ +#include "deadline_model.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static bool timestamp(const QJsonValue& value) { + return value.isDouble() && std::isfinite(value.toDouble()) && value.toDouble() >= 0 && + value.toDouble() <= 253402300799.0; +} +static bool text(const QJsonValue& value) { + return value.isString() && value.toString().toUtf8().size() <= 4096; +} + +DeadlineModel::DeadlineModel(QObject* parent) : QObject(parent) { + m_path = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + + "/techpie/widgets/deadline-widget-v1.json"; + connect(&m_watcher, &QFileSystemWatcher::directoryChanged, this, &DeadlineModel::refresh); + connect(&m_timer, &QTimer::timeout, this, &DeadlineModel::refresh); + m_timer.start(30000); + refresh(); +} + +void DeadlineModel::refresh() { + m_now = QDateTime::currentMSecsSinceEpoch() / 1000.0; + m_items.clear(); + m_writtenAt = 0; + m_state = "unavailable"; + QString directory = QFileInfo(m_path).absolutePath(); + while (!QDir(directory).exists() && directory != "/") + directory = QFileInfo(directory).absolutePath(); + if (m_watcher.directories() != QStringList{directory}) { + if (!m_watcher.directories().isEmpty()) m_watcher.removePaths(m_watcher.directories()); + m_watcher.addPath(directory); + } + QFile file(m_path); + if (!file.exists()) { m_state = "notSynced"; emit changed(); return; } + if (!file.open(QIODevice::ReadOnly)) { emit changed(); return; } + const QByteArray data = file.read(262145); + if (data.size() > 262144) { emit changed(); return; } + const auto document = QJsonDocument::fromJson(data); + const auto object = document.object(); + const auto array = object.value("items").toArray(); + if (!document.isObject() || object.size() != 3 || object.value("schemaVersion").toDouble() != 1 || + !timestamp(object.value("writtenAt")) || !object.value("items").isArray() || array.size() > 512) { + emit changed(); return; + } + QSet ids; + for (const auto& value : array) { + const auto item = value.toObject(); + const QString id = item.value("id").toString(); + const QString kind = item.value("kind").toString(); + if (!value.isObject() || item.size() != 5 || !text(item.value("id")) || id.isEmpty() || + ids.contains(id) || (kind != "assignment" && kind != "exam") || + !text(item.value("title")) || !text(item.value("course")) || !timestamp(item.value("dueAt"))) { + m_items.clear(); emit changed(); return; + } + ids.insert(id); + if (item.value("dueAt").toDouble() > m_now) m_items.append(item.toVariantMap()); + } + std::sort(m_items.begin(), m_items.end(), [](const QVariant& a, const QVariant& b) { + const auto x = a.toMap(), y = b.toMap(); + const double dx = x.value("dueAt").toDouble(), dy = y.value("dueAt").toDouble(); + return dx == dy ? x.value("id").toString() < y.value("id").toString() : dx < dy; + }); + m_writtenAt = object.value("writtenAt").toDouble(); + m_state = "ready"; + emit changed(); +} + +bool DeadlineModel::openApp() { + return QDesktopServices::openUrl(QUrl(QStringLiteral("techpie://deadlines"))); +} diff --git a/linux/widgets/kde/backend/deadline_model.h b/linux/widgets/kde/backend/deadline_model.h new file mode 100644 index 00000000..eeef1966 --- /dev/null +++ b/linux/widgets/kde/backend/deadline_model.h @@ -0,0 +1,32 @@ +#pragma once + +#include +#include +#include +#include + +class DeadlineModel : public QObject { + Q_OBJECT + Q_PROPERTY(QString state READ state NOTIFY changed) + Q_PROPERTY(QVariantList items READ items NOTIFY changed) + Q_PROPERTY(double writtenAt READ writtenAt NOTIFY changed) + Q_PROPERTY(double now READ now NOTIFY changed) +public: + explicit DeadlineModel(QObject* parent = nullptr); + QString state() const { return m_state; } + QVariantList items() const { return m_items; } + double writtenAt() const { return m_writtenAt; } + double now() const { return m_now; } + Q_INVOKABLE void refresh(); + Q_INVOKABLE bool openApp(); +signals: + void changed(); +private: + QFileSystemWatcher m_watcher; + QTimer m_timer; + QString m_path; + QString m_state = "notSynced"; + QVariantList m_items; + double m_writtenAt = 0; + double m_now = 0; +}; diff --git a/linux/widgets/kde/backend/plugin.cpp b/linux/widgets/kde/backend/plugin.cpp new file mode 100644 index 00000000..377c6993 --- /dev/null +++ b/linux/widgets/kde/backend/plugin.cpp @@ -0,0 +1,13 @@ +#include "deadline_model.h" +#include +#include + +class DeadlinePlugin : public QQmlExtensionPlugin { + Q_OBJECT + Q_PLUGIN_METADATA(IID QQmlExtensionInterface_iid) +public: + void registerTypes(const char* uri) override { + qmlRegisterType(uri, 1, 0, "DeadlineModel"); + } +}; +#include "plugin.moc" diff --git a/linux/widgets/kde/contents/ui/backend/qmldir b/linux/widgets/kde/contents/ui/backend/qmldir new file mode 100644 index 00000000..116972d1 --- /dev/null +++ b/linux/widgets/kde/contents/ui/backend/qmldir @@ -0,0 +1 @@ +plugin techpiedeadlines diff --git a/linux/widgets/kde/contents/ui/main.qml b/linux/widgets/kde/contents/ui/main.qml new file mode 100644 index 00000000..d9823a7f --- /dev/null +++ b/linux/widgets/kde/contents/ui/main.qml @@ -0,0 +1,128 @@ +import QtQuick +import QtQuick.Layouts +import QtQuick.Controls as Controls +import org.kde.plasma.plasmoid +import org.kde.plasma.core as PlasmaCore +import org.kde.plasma.components as PlasmaComponents +import org.kde.kirigami as Kirigami +import "backend" as Backend + +PlasmoidItem { + id: root + Backend.DeadlineModel { id: deadlines } + preferredRepresentation: Plasmoid.formFactor === PlasmaCore.Types.Horizontal || + Plasmoid.formFactor === PlasmaCore.Types.Vertical ? compactRepresentation : fullRepresentation + switchWidth: Kirigami.Units.gridUnit * 12 + switchHeight: Kirigami.Units.gridUnit * 8 + + compactRepresentation: PlasmaComponents.ToolButton { + icon.name: "view-calendar-tasks" + text: deadlines.items.length ? root.remaining(deadlines.items[0].dueAt) : "TechPie" + display: Controls.AbstractButton.TextBesideIcon + Kirigami.Theme.textColor: deadlines.items.length + ? root.remainingColor(deadlines.items[0].dueAt) : root.Kirigami.Theme.textColor + onClicked: root.expanded = !root.expanded + } + + function remaining(dueAt) { + const hours = Math.floor((dueAt - deadlines.now) / 3600) + return hours < 1 ? "<1h" : hours < 24 ? hours + "h" : + Math.floor(hours / 24) + "d " + hours % 24 + "h" + } + + function remainingColor(dueAt) { + const seconds = dueAt - deadlines.now + if (seconds > 0 && seconds <= 12 * 3600) return Kirigami.Theme.negativeTextColor + return seconds > 12 * 3600 && seconds <= 36 * 3600 + ? Kirigami.Theme.highlightColor : Kirigami.Theme.textColor + } + + fullRepresentation: ColumnLayout { + implicitWidth: Math.min(Kirigami.Units.gridUnit * 28, + Math.max(Kirigami.Units.gridUnit * 16, list.contentWidth + Kirigami.Units.gridUnit * 2)) + Layout.minimumWidth: Kirigami.Units.gridUnit * 12 + Layout.minimumHeight: Kirigami.Units.gridUnit * 8 + Layout.preferredWidth: implicitWidth + Layout.preferredHeight: Kirigami.Units.gridUnit * 16 + spacing: Kirigami.Units.smallSpacing + RowLayout { + Layout.fillWidth: true + PlasmaComponents.Label { text: "TechPie Deadlines"; font.bold: true; Layout.fillWidth: true } + PlasmaComponents.Label { + text: deadlines.items.length ? deadlines.items.length + " upcoming" : "" + opacity: 0.7 + } + PlasmaComponents.ToolButton { + icon.name: "document-open" + Accessible.name: "Open TechPie Deadlines" + onClicked: deadlines.openApp() + } + } + PlasmaComponents.Label { + visible: deadlines.state !== "ready" || deadlines.items.length === 0 + Layout.fillWidth: true + Layout.fillHeight: true + wrapMode: Text.Wrap + text: deadlines.state === "unavailable" ? "Deadline data is unavailable" : + deadlines.state === "notSynced" ? "Enable Deadline widgets in TechPie Settings" : + "No upcoming deadlines" + } + ListView { + id: list + visible: deadlines.state === "ready" && deadlines.items.length > 0 + Layout.fillWidth: true + Layout.fillHeight: true + clip: true + spacing: Kirigami.Units.smallSpacing + model: deadlines.items.slice(0, height < Kirigami.Units.gridUnit * 8 ? 2 : + height < Kirigami.Units.gridUnit * 14 ? 4 : 8) + delegate: PlasmaComponents.ItemDelegate { + required property var modelData + width: list.width + background: Rectangle { + radius: Kirigami.Units.largeSpacing + color: root.cardColor(modelData.dueAt) + } + Accessible.name: modelData.title + ", " + modelData.course + ", " + + new Date(modelData.dueAt * 1000).toLocaleString() + onClicked: deadlines.openApp() + contentItem: ColumnLayout { + RowLayout { + Layout.fillWidth: true + Kirigami.Icon { + source: modelData.kind === "exam" ? "view-calendar-tasks" : "document-edit" + Layout.preferredWidth: Kirigami.Units.iconSizes.small + Layout.preferredHeight: Kirigami.Units.iconSizes.small + } + PlasmaComponents.Label { + text: modelData.kind === "exam" ? "考试 " + modelData.title : "作业 " + modelData.title + font.bold: true + elide: Text.ElideRight; Layout.fillWidth: true + } + PlasmaComponents.Label { + text: root.remaining(modelData.dueAt) + color: root.remainingColor(modelData.dueAt) + } + } + PlasmaComponents.Label { + text: modelData.course + " · " + new Date(modelData.dueAt * 1000).toLocaleString() + elide: Text.ElideRight; Layout.fillWidth: true; opacity: 0.7 + } + } + } + } + PlasmaComponents.Label { + visible: deadlines.state === "ready" + text: "Cached snapshot · " + new Date(deadlines.writtenAt * 1000).toLocaleString() + font.pointSize: Kirigami.Theme.smallFont.pointSize + elide: Text.ElideRight; Layout.fillWidth: true; opacity: 0.7 + } + } + + function cardColor(dueAt) { + const seconds = dueAt - deadlines.now + if (seconds > 0 && seconds <= 12 * 3600) return Qt.rgba(0.64, 0.04, 0.10, 0.82) + if (seconds > 12 * 3600 && seconds <= 36 * 3600) return Qt.rgba(0.64, 0.04, 0.10, 0.38) + return Qt.rgba(1, 1, 1, 0.07) + } +} diff --git a/linux/widgets/kde/metadata.json b/linux/widgets/kde/metadata.json new file mode 100644 index 00000000..657641af --- /dev/null +++ b/linux/widgets/kde/metadata.json @@ -0,0 +1,14 @@ +{ + "KPlugin": { + "Id": "club.geekpie.techpie.deadlines", + "Name": "TechPie Deadlines", + "Description": "Upcoming assignments and exams from TechPie", + "Icon": "view-calendar-tasks", + "Version": "1.0", + "Authors": [{"Name": "TechPie contributors"}], + "Category": "Date and Time" + }, + "KPackageStructure": "Plasma/Applet", + "X-Plasma-API-Minimum-Version": "6.0", + "X-Plasma-FormFactors": ["desktop", "horizontal", "vertical"] +}