From 21f4a86a39e0ac01dde2454e28d5cdf88bc4fc41 Mon Sep 17 00:00:00 2001 From: jdz Date: Wed, 28 Oct 2026 22:56:19 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(linux):=20=E6=96=B0=E5=A2=9E=E6=A1=8C?= =?UTF-8?q?=E9=9D=A2=20DDL=20=E7=BB=84=E4=BB=B6=E5=B9=B6=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E7=82=B9=E5=87=BB=E5=B1=82=E7=BA=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/linux-release.yml | 13 +- lib/main.dart | 20 ++ lib/pages/assignments_page.dart | 23 ++- lib/pages/settings_page.dart | 14 ++ lib/services/assignment_service.dart | 106 +++++++++- lib/services/deadline_widget_service.dart | 192 ++++++++++++++++++ lib/services/service_provider.dart | 6 +- lib/services/storage_service.dart | 8 + lib/widgets/app_shell/app_shell.dart | 13 ++ linux/runner/CMakeLists.txt | 4 + linux/runner/deadline_snapshot_store.cc | 92 +++++++++ linux/runner/deadline_snapshot_store.h | 10 + linux/runner/my_application.cc | 69 ++++++- linux/widgets/CMakeLists.txt | 11 + linux/widgets/README.md | 104 ++++++++++ linux/widgets/common/snapshot.mjs | 41 ++++ linux/widgets/gnome/desktopCard.js | 164 +++++++++++++++ linux/widgets/gnome/extension.js | 167 +++++++++++++++ linux/widgets/gnome/metadata.json | 9 + linux/widgets/gnome/reader.mjs | 39 ++++ ...l.extensions.techpie-deadlines.gschema.xml | 18 ++ linux/widgets/gnome/stylesheet.css | 7 + 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 | 101 +++++++++ linux/widgets/kde/metadata.json | 14 ++ linux/widgets/tests/desktop-stacking.test.mjs | 104 ++++++++++ test/widget_test.dart | 2 +- 31 files changed, 1584 insertions(+), 15 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/widgets/CMakeLists.txt create mode 100644 linux/widgets/README.md 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 create mode 100644 linux/widgets/tests/desktop-stacking.test.mjs diff --git a/.github/workflows/linux-release.yml b/.github/workflows/linux-release.yml index 796ee6e8..a838c573 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 linux/widgets/README.md \ + 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 41ffecb8..3753f6b6 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'; @@ -98,6 +99,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, @@ -183,10 +187,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()); @@ -311,6 +317,7 @@ class TechPieApp extends StatefulWidget { final CampusCardService campusCardService; final EcardBindService ecardBindService; final EcardWidgetService? ecardWidgetService; + final DeadlineWidgetService? deadlineWidgetService; const TechPieApp({ super.key, @@ -329,6 +336,7 @@ class TechPieApp extends StatefulWidget { required this.campusCardService, required this.ecardBindService, this.ecardWidgetService, + this.deadlineWidgetService, }); @override @@ -352,11 +360,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); @@ -366,6 +379,7 @@ class _TechPieAppState extends State with WidgetsBindingObserver { void dispose() { WidgetsBinding.instance.removeObserver(this); widget.ecardWidgetService?.clearOpenPayHandler(); + widget.deadlineWidgetService?.dispose(); widget.campusCardService.dispose(); super.dispose(); } @@ -380,6 +394,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 @@ -450,6 +469,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 ccca0982..31cbf53e 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}); @@ -453,6 +454,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, @@ -463,7 +466,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..9539f97c 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -409,6 +409,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), diff --git a/lib/services/assignment_service.dart b/lib/services/assignment_service.dart index 18f4e390..d87fd8fd 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/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..334305e6 100644 --- a/lib/services/storage_service.dart +++ b/lib/services/storage_service.dart @@ -315,6 +315,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/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..b93ed1f9 100644 --- a/linux/runner/CMakeLists.txt +++ b/linux/runner/CMakeLists.txt @@ -9,6 +9,7 @@ project(runner LANGUAGES CXX) add_executable(${BINARY_NAME} "main.cc" "my_application.cc" + "deadline_snapshot_store.cc" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" ) @@ -23,4 +24,7 @@ add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") 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) + 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..acf73b00 100644 --- a/linux/runner/my_application.cc +++ b/linux/runner/my_application.cc @@ -1,4 +1,5 @@ #include "my_application.h" +#include "deadline_snapshot_store.h" #include #ifdef GDK_WINDOWING_X11 @@ -10,10 +11,37 @@ struct _MyApplication { GtkApplication parent_instance; char** dart_entrypoint_arguments; + FlMethodChannel* deadline_channel; + gboolean pending_deadlines; }; 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 +50,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 +107,11 @@ static void my_application_activate(GApplication* application) { gtk_widget_realize(GTK_WIDGET(view)); fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + 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 +131,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 +155,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); @@ -121,11 +186,13 @@ static void my_application_shutdown(GApplication* application) { static void my_application_dispose(GObject* object) { MyApplication* self = MY_APPLICATION(object); 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 +211,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/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/README.md b/linux/widgets/README.md new file mode 100644 index 00000000..4a3357b7 --- /dev/null +++ b/linux/widgets/README.md @@ -0,0 +1,104 @@ +# TechPie Linux deadline widgets (first version) + +KDE Plasma 6: a resizable desktop card and compact panel button. GNOME Shell +45–51: a desktop card and top-bar indicator with an expandable deadline list. +GNOME 51 has been checked in an isolated Shell session; other declared versions +and the Plasma desktop still need native visual acceptance. + +The widgets show upcoming, visible, incomplete assignments and exams, sorted by +deadline. They do not contact campus services or receive credentials. They read +the last snapshot published by TechPie; keep the app running for new data. +Expired entries and countdowns are refreshed locally at most every 30 seconds. +The timestamp is when the snapshot was saved, not a claim of a successful server +sync. A widget click opens the app's Deadlines page. + +## Install a release bundle + +Extract the entire Linux release archive to a stable location first. From its +`bundle` directory, using the absolute path to that bundle's executable: + +```bash +python3 widgets/install.py install --desktop kde --app /absolute/path/bundle/techpie +# Or GNOME, or --desktop both: +python3 widgets/install.py install --desktop gnome --app /absolute/path/bundle/techpie +``` + +In TechPie, open **Settings → General → Deadline widgets** to enable sharing. +The setting is off initially. Sharing exposes task titles, course names and +dates to the current user's desktop. Turning it off or signing out clears the +shared task data. Enabled widgets publish an empty list before the first sync. +Widgets are not enabled for the GNOME lock screen. + +- KDE: use the desktop/panel **Add Widgets** picker and select **TechPie Deadlines**. +- GNOME: after a first installation, log out/in if the extension is not listed; + enable **TechPie Deadlines** in Extensions. The installer does not enable it. +- GNOME: drag the card heading to move it. Its position is saved relative to the + primary monitor's work area. The indicator menu can hide the card or reset its + position. It stays below application windows and hides in overview/fullscreen. +- If the app bundle moves, rerun the installer with the new executable path. +- Dependencies: Python 3 for installation, Qt 6 Core/Gui/Qml for KDE; GJS/GNOME + Shell and GLib's `glib-compile-schemas` for GNOME. The app also requires its normal GTK/WebKit/libsecret runtime + dependencies plus json-glib. For Arch, the corresponding widget build packages + are `base-devel cmake qt6-base qt6-declarative json-glib`; Plasma provides its + own QML modules. No root access is required for user installation. + +## Build from source + +Build the normal Linux app using Flutter **3.41.9**. Then build the KDE adapter: + +```bash +cmake -S linux/widgets -B build/linux-widgets -DCMAKE_BUILD_TYPE=Release +cmake --build build/linux-widgets --parallel +python3 linux/widgets/install.py install --desktop kde \ + --kde-package build/linux-widgets/kde \ + --app /absolute/path/build/linux/x64/release/bundle/techpie +``` + +For GNOME, use the same installer with `--desktop gnome`; no Qt build is needed. +The Linux release workflow includes both packages and the compiled Qt adapter. +The Qt plugin must be rebuilt for another architecture and must not require a +newer Qt minor version than the target desktop provides. + +## Uninstall + +Disable the GNOME extension/remove the Plasma widget first, then run: + +```bash +python3 widgets/install.py uninstall --desktop both +``` + +Only marked TechPie widget directories and the managed launcher are removed. +The app and its data are retained. Turn off sharing in the app to erase the +snapshot. No account credentials are ever stored in the widget directory. + +## Data and lifecycle + +The shared v1 protocol follows the macOS branch. Its display-only snapshot is +`$XDG_DATA_HOME/techpie/widgets/deadline-widget-v1.json`, defaulting to +`~/.local/share/techpie/widgets/deadline-widget-v1.json`. Directory permissions +are `0700`, files `0600`; writes are atomic. Readers accept at most 256 KiB / 512 +entries and validate fields, version, timestamps and duplicate IDs. Both watch +directories so atomic replacement and first-time creation are detected. + +The Flutter service serializes writes, ignores superseded account generations, +and uses the same account-isolation changes as the macOS reference. Linux +registers `techpie://deadlines` and activates an existing application instance. +Its existing application ID is retained so saved preferences keep their location. +The existing payment widget and Huawei Watch code remain separate consumers. + +GNOME's `desktopCard.js` owns the desktop actor and placement; `extension.js` +owns the indicator, reader and lifecycle. GSettings stores card visibility and +position. KDE keeps its reader/model in `backend` and presentation in QML. +This version targets an unpacked native bundle; Flatpak/Snap integration is +outside its scope. + +## Desktop card stacking regression + +The GNOME card ignores minimized or hidden window actors when choosing its +stacking position. It restores that position before painting, after Mutter has +finished updating the window stack, so DING's transparent desktop window cannot +cover its buttons after applications are minimized. + +```bash +node --experimental-vm-modules --test linux/widgets/tests/desktop-stacking.test.mjs +``` diff --git a/linux/widgets/common/snapshot.mjs b/linux/widgets/common/snapshot.mjs new file mode 100644 index 00000000..9ae96e6d --- /dev/null +++ b/linux/widgets/common/snapshot.mjs @@ -0,0 +1,41 @@ +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`; +} diff --git a/linux/widgets/gnome/desktopCard.js b/linux/widgets/gnome/desktopCard.js new file mode 100644 index 00000000..509963a3 --- /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} 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, width: 360}); + 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._queueRestack())], + [this._windowGroup, this._windowGroup.connect('child-added', () => this._queueRestack())], + ]; + 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._queueRestack(); + this._position(); + } + + _queueRestack() { + if (this._restackLater || this._destroyed) return; + // Mutter may still synchronize window actors after display::restacked. + // Move the card only after that work, immediately before painting. + this._restackLater = global.compositor.get_laters().add( + Meta.LaterType.BEFORE_REDRAW, () => { + this._restackLater = 0; + if (!this._destroyed) this._restack(); + return false; + }); + } + + _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?.(); + // Minimized/off-workspace actors can precede the desktop actor. + // They must not anchor the card underneath the desktop window. + return child.visible && child.mapped && 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); + const [, height] = this.actor.get_preferred_height(this.actor.width); + this.actor.width = Math.min(360, Math.max(1, area.width - 48)); + 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._queueRestack(); + 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 items = snapshot ? upcoming(snapshot).slice(0, 4) : []; + for (const item of items) { + const row = column({style_class: 'techpie-deadline-row'}); + row.add_child(new St.Label({text: item.title, x_expand: true})); + row.add_child(new St.Label({text: `${item.course} · ${remaining(item.dueAt)}`, + 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._destroyed = true; + if (this._restackLater) { + global.compositor.get_laters().remove(this._restackLater); + this._restackLater = 0; + } + 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..98e8b577 --- /dev/null +++ b/linux/widgets/gnome/extension.js @@ -0,0 +1,167 @@ +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, 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 items = this._snapshot ? upcoming(this._snapshot) : []; + this._desktop.update(this._snapshot, this._state); + this._label.text = items.length ? remaining(items[0].dueAt) : 'TechPie'; + 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 box = new St.BoxLayout({...direction, style_class: 'techpie-deadline-row'}); + box.add_child(new St.Label({text: `${item.kind === 'exam' ? '◷' : '•'} ${item.title} · ${remaining(item.dueAt)}`})); + 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..2062b5ee --- /dev/null +++ b/linux/widgets/gnome/stylesheet.css @@ -0,0 +1,7 @@ +.techpie-deadline-row { spacing: 4px; max-width: 420px; } +.techpie-deadline-detail { font-size: 0.85em; } +.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..f77181bf --- /dev/null +++ b/linux/widgets/kde/contents/ui/main.qml @@ -0,0 +1,101 @@ +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 + 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" + } + + fullRepresentation: ColumnLayout { + Layout.minimumWidth: Kirigami.Units.gridUnit * 12 + Layout.minimumHeight: Kirigami.Units.gridUnit * 8 + Layout.preferredWidth: Kirigami.Units.gridUnit * 20 + 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.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 + 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.title; font.bold: true + elide: Text.ElideRight; Layout.fillWidth: true + } + PlasmaComponents.Label { + text: root.remaining(modelData.dueAt) + color: modelData.dueAt - deadlines.now < 3600 ? Kirigami.Theme.negativeTextColor : Kirigami.Theme.textColor + } + } + 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 + } + } +} 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"] +} diff --git a/linux/widgets/tests/desktop-stacking.test.mjs b/linux/widgets/tests/desktop-stacking.test.mjs new file mode 100644 index 00000000..64c92374 --- /dev/null +++ b/linux/widgets/tests/desktop-stacking.test.mjs @@ -0,0 +1,104 @@ +// Run: node --experimental-vm-modules --test linux/widgets/tests/desktop-stacking.test.mjs +import {readFileSync} from 'node:fs'; +import vm from 'node:vm'; +import assert from 'node:assert/strict'; +import {test} from 'node:test'; + +const pending = new Map(); +let nextId = 1; +const laters = { + add(_phase, callback) { const id = nextId++; pending.set(id, callback); return id; }, + remove(id) { pending.delete(id); }, +}; +const context = vm.createContext({global: {compositor: {get_laters: () => laters}}}); +const modules = new Map([ + ['gi://Clutter', {default: {}}], + ['gi://St', {default: {}}], + ['gi://Meta', {default: {WindowType: {DESKTOP: 1}, LaterType: {BEFORE_REDRAW: 5}}}], + ['resource:///org/gnome/shell/ui/main.js', {layoutManager: {untrackChrome() {}}}], + ['./snapshot.mjs', {upcoming() {}, remaining() {}, urgency() {}}], +]); +const filename = process.env.TECHPIE_CARD_MODULE ?? + new URL('../gnome/desktopCard.js', import.meta.url); +const module = new vm.SourceTextModule(readFileSync(filename, 'utf8'), {context}); +await module.link(specifier => { + const exports = modules.get(specifier); + assert.ok(exports, `unexpected dependency: ${specifier}`); + return new vm.SyntheticModule(Object.keys(exports), function () { + for (const [key, value] of Object.entries(exports)) this.setExport(key, value); + }, {context}); +}); +await module.evaluate(); +const {DesktopCard} = module.namespace; + +function fixture() { + pending.clear(); + const window = (type, shown = true) => ({visible: shown, mapped: shown, + get_meta_window: () => ({get_window_type: () => type})}); + const hiddenApp = window(0, false); + const desktop = window(1); + const visibleApp = window(0); + const actor = {destroy() { this.destroyed = true; }}; + const children = [hiddenApp, actor, desktop, visibleApp]; + const move = (child, sibling, offset) => { + children.splice(children.indexOf(child), 1); + const index = sibling ? children.indexOf(sibling) + offset : children.length; + children.splice(index, 0, child); + }; + const card = Object.create(DesktopCard.prototype); + Object.assign(card, {actor, _signals: [], _windowGroup: { + get_children: () => children, + set_child_below_sibling: (a, sibling) => move(a, sibling, 0), + set_child_above_sibling: (a, sibling) => move(a, sibling, 1), + }}); + const paint = () => { + const callbacks = [...pending.values()]; pending.clear(); + for (const callback of callbacks) callback(); + }; + return {card, actor, children, hiddenApp, desktop, visibleApp, paint}; +} + +test('a minimized actor before DING never pulls the card underneath DING', () => { + const f = fixture(); + f.card._restack(); + assert.ok(f.children.indexOf(f.actor) > f.children.indexOf(f.desktop)); + assert.ok(f.children.indexOf(f.actor) < f.children.indexOf(f.visibleApp)); +}); + +test('restacking runs after compositor stack changes, before painting', () => { + const f = fixture(); + f.card._queueRestack(); + assert.equal(pending.size, 1); + assert.ok(f.children.indexOf(f.actor) < f.children.indexOf(f.desktop)); + f.children.splice(f.children.indexOf(f.actor), 1); + f.children.unshift(f.actor); // Mutter overwrites the order after restacked. + f.paint(); + assert.ok(f.children.indexOf(f.actor) > f.children.indexOf(f.desktop)); + assert.ok(f.children.indexOf(f.actor) < f.children.indexOf(f.visibleApp)); +}); + +test('coalesces repeated events and allows a later restack', () => { + const f = fixture(); + for (let i = 0; i < 20; i++) f.card._queueRestack(); + assert.equal(pending.size, 1); + f.paint(); + f.card._queueRestack(); + assert.equal(pending.size, 1); +}); + +test('with all apps minimized the card stays above the desktop', () => { + const f = fixture(); + f.visibleApp.visible = f.visibleApp.mapped = false; + f.card._restack(); + assert.ok(f.children.indexOf(f.actor) > f.children.indexOf(f.desktop)); +}); + +test('destroy cancels queued work and never schedules another callback', () => { + const f = fixture(); + f.card._queueRestack(); + f.card.destroy(); + assert.equal(pending.size, 0); + assert.equal(f.actor.destroyed, true); + f.card._queueRestack(); + assert.equal(pending.size, 0); +}); diff --git a/test/widget_test.dart b/test/widget_test.dart index 882e8125..2a93d020 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -170,7 +170,7 @@ void main() { // Tap Deadlines await tester.tap(find.text('Deadlines').first); await tester.pumpAndSettle(); - expect(find.text('No upcoming deadlines'), findsOneWidget); + expect(find.text('连接课程平台以获取Deadlines'), findsOneWidget); expect(find.byType(FloatingActionButton), findsNothing); // Tap Settings From 8aa05afd369635251a1b376be0abc53889403afd Mon Sep 17 00:00:00 2001 From: dzhes Date: Fri, 13 Nov 2026 18:22:38 +0800 Subject: [PATCH 2/2] docs: use concise English developer documentation --- linux/widgets/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/linux/widgets/README.md b/linux/widgets/README.md index 4a3357b7..ffd92565 100644 --- a/linux/widgets/README.md +++ b/linux/widgets/README.md @@ -1,4 +1,4 @@ -# TechPie Linux deadline widgets (first version) +# TechPie Linux deadline widgets KDE Plasma 6: a resizable desktop card and compact panel button. GNOME Shell 45–51: a desktop card and top-bar indicator with an expandable deadline list. @@ -9,8 +9,8 @@ The widgets show upcoming, visible, incomplete assignments and exams, sorted by deadline. They do not contact campus services or receive credentials. They read the last snapshot published by TechPie; keep the app running for new data. Expired entries and countdowns are refreshed locally at most every 30 seconds. -The timestamp is when the snapshot was saved, not a claim of a successful server -sync. A widget click opens the app's Deadlines page. +The timestamp records when the snapshot was saved. Server-sync status is tracked +by the app. A widget click opens the app's Deadlines page. ## Install a release bundle @@ -89,8 +89,8 @@ The existing payment widget and Huawei Watch code remain separate consumers. GNOME's `desktopCard.js` owns the desktop actor and placement; `extension.js` owns the indicator, reader and lifecycle. GSettings stores card visibility and position. KDE keeps its reader/model in `backend` and presentation in QML. -This version targets an unpacked native bundle; Flatpak/Snap integration is -outside its scope. +Install the widgets from an unpacked native bundle. Flatpak/Snap widget integration +remains pending. ## Desktop card stacking regression