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 af85bf5a..5c8d95e6 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -101,7 +101,11 @@ Future _realMain(SharedPreferences prefs) async { thirdPartyAuthService, scheduleService, ); - final deadlineWidgetService = DeadlineWidgetService(assignmentService); + final deadlineWidgetService = DeadlineWidgetService( + assignmentService, + enabled: kIsWeb || defaultTargetPlatform != TargetPlatform.linux || + storageService.deadlineWidgetsEnabled, + ); final syncService = SyncService( authService, thirdPartyAuthService, @@ -194,7 +198,8 @@ Future _realMain(SharedPreferences prefs) async { bootMark('cached data ready'); if (!kIsWeb && (defaultTargetPlatform == TargetPlatform.iOS || - defaultTargetPlatform == TargetPlatform.macOS)) { + defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.linux)) { deadlineWidgetService.initialize(); } @@ -481,6 +486,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 623c515c..3ae94474 100644 --- a/lib/pages/assignments_page.dart +++ b/lib/pages/assignments_page.dart @@ -20,6 +20,7 @@ import '../widgets/ios/ios_native_navigation_bar.dart'; import '../widgets/page_refresh.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}); @@ -460,6 +461,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, @@ -470,7 +473,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 18a42df3..e58b48d2 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -428,6 +428,21 @@ class _SettingsPageState extends State { // General section _sectionHeader(theme, 'General'), + if (!kIsWeb && defaultTargetPlatform == TargetPlatform.linux && + 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/deadline_widget_service.dart b/lib/services/deadline_widget_service.dart index b0ddbff0..67499658 100644 --- a/lib/services/deadline_widget_service.dart +++ b/lib/services/deadline_widget_service.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'dart:convert'; +import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; @@ -16,12 +17,25 @@ class DeadlineWidgetService with WidgetsBindingObserver { this._assignments, { MethodChannel? channel, DateTime Function()? now, + bool enabled = true, }) : _channel = channel ?? const MethodChannel('techpie/deadline_widgets'), + _enabled = enabled, + _linux = !kIsWeb && defaultTargetPlatform == TargetPlatform.linux, _now = now ?? DateTime.now; final AssignmentService _assignments; final MethodChannel _channel; final DateTime Function() _now; + final bool _linux; + 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; @@ -47,15 +61,13 @@ class DeadlineWidgetService with WidgetsBindingObserver { 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 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)); + }); return [ for (final a in items) { @@ -73,19 +85,50 @@ class DeadlineWidgetService with WidgetsBindingObserver { ]; } + static List> _linuxItems(List> items) { + final result = >[]; + final ids = {}; + var bytes = 1024; // Reserve the envelope and list separators. + for (final item in items) { + final id = item['id']! as String; + final due = item['dueAt']! as num; + if (utf8.encode(id).length > 4096 || !ids.add(id) || due < 0 || due > 253402300799) continue; + final row = { + 'id': id, + 'kind': item['kind']!, + 'title': String.fromCharCodes((item['title']! as String).runes.take(256)), + 'course': String.fromCharCodes((item['subtitle']! as String).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; - final ready = _assignments.hasCachedData; - final items = displayItems( - _assignments.visibleAssignments, - _assignments.isCompleted, - _now(), - ); + final ready = _enabled && (_linux || _assignments.hasCachedData); + final display = _assignments.hasCachedData + ? displayItems( + _assignments.visibleAssignments, + _assignments.isCompleted, + _now(), + ) + : >[]; + final items = _linux ? _linuxItems(display) : display; final content = ready ? jsonEncode(items) : null; _writes = _writes.then((_) async { - if (_disposed || epoch != _assignments.identityEpoch) return; + if (_disposed || + epoch != _assignments.identityEpoch || + ready != (_enabled && (_linux || _assignments.hasCachedData))) { + return; + } if (_lastPublished == content && content != null) return; try { if (!ready) { 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 9037dc6b..9544b374 100644 --- a/lib/services/storage_service.dart +++ b/lib/services/storage_service.dart @@ -326,6 +326,12 @@ class StorageService { 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/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..ffd92565 --- /dev/null +++ b/linux/widgets/README.md @@ -0,0 +1,104 @@ +# 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. +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 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 + +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. +Install the widgets from an unpacked native bundle. Flatpak/Snap widget integration +remains pending. + +## 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/deadline_widget_service_test.dart b/test/deadline_widget_service_test.dart index 78d7e594..63ac55da 100644 --- a/test/deadline_widget_service_test.dart +++ b/test/deadline_widget_service_test.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'dart:convert'; +import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_secure_storage_ohos/flutter_secure_storage_ohos.dart'; @@ -21,8 +22,7 @@ void main() { TestWidgetsFlutterBinding.ensureInitialized(); final now = DateTime.utc(2026, 10, 12); const channel = MethodChannel('test/deadline_widgets'); - final messenger = - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; late AssignmentService assignments; late DeadlineWidgetService service; late List calls; @@ -53,15 +53,13 @@ void main() { due: now.subtract(const Duration(seconds: 1)), ).toJson(), ]); - assignments = AssignmentService(storage, http, auth, thirdParty, schedule) - ..loadCached(); + assignments = AssignmentService(storage, http, auth, thirdParty, schedule)..loadCached(); calls = []; messenger.setMockMethodCallHandler(channel, (call) async { calls.add(call); return false; }); - service = - DeadlineWidgetService(assignments, channel: channel, now: () => now); + service = DeadlineWidgetService(assignments, channel: channel, now: () => now); addTearDown(() { service.dispose(); assignments.dispose(); @@ -73,8 +71,7 @@ void main() { }); }); - test('cached publication excludes private fields and past deadlines', - () async { + test('cached publication excludes private fields and past deadlines', () async { service.initialize(); await service.flush(); final payload = jsonDecode( @@ -94,16 +91,14 @@ void main() { expect(calls.where((c) => c.method == 'publish'), hasLength(1)); }); - test('completion and hidden overrides immediately update the snapshot', - () async { + test('completion and hidden overrides immediately update the snapshot', () async { service.initialize(); await service.flush(); await assignments.setCompleted(assignments.assignments[1], true); await service.flush(); await assignments.hide(assignments.assignments[2]); await service.flush(); - final items = - (jsonDecode(calls.last.arguments as String) as Map)['items'] as List; + final items = (jsonDecode(calls.last.arguments as String) as Map)['items'] as List; expect(items, hasLength(8)); expect(items.map((e) => e['id']), isNot(contains('synthetic:0'))); expect(items.map((e) => e['id']), isNot(contains('synthetic:1'))); @@ -126,8 +121,7 @@ void main() { expect(calls.last.method, 'clear'); }); - testWidgets('cold and warm taps wait for navigation and reuse the handler', - (tester) async { + testWidgets('cold and warm taps wait for navigation and reuse the handler', (tester) async { messenger.setMockMethodCallHandler(channel, (call) async { calls.add(call); return call.method == 'consumePendingRoute'; @@ -142,8 +136,7 @@ void main() { expect(opened, 1); await messenger.handlePlatformMessage( channel.name, - const StandardMethodCodec() - .encodeMethodCall(const MethodCall('openDeadlines')), + const StandardMethodCodec().encodeMethodCall(const MethodCall('openDeadlines')), (_) {}, ); expect(opened, 2); @@ -187,4 +180,55 @@ void main() { final items = DeadlineWidgetService.displayItems([exam], (_) => false, now); expect(items.single['subtitle'], 'Teaching Center 101'); }); + + test('Linux keeps its v1 snapshot fields and sharing switch', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.linux; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + service.dispose(); + service = DeadlineWidgetService( + assignments, + channel: channel, + now: () => now, + enabled: false, + ); + service.initialize(); + await service.flush(); + expect(calls.last.method, 'clear'); + expect(calls.where((call) => call.method == 'publish'), isEmpty); + + await service.setEnabled(true); + final payload = jsonDecode(calls.last.arguments as String) as Map; + final items = payload['items'] as List; + expect(items, hasLength(10)); + expect((items.first as Map).keys.toSet(), {'id', 'kind', 'title', 'course', 'dueAt'}); + expect(items.first['course'], 'Course'); + + await assignments.clearCache(); + await service.flush(); + expect(calls.last.method, 'publish'); + expect((jsonDecode(calls.last.arguments as String) as Map)['items'], isEmpty); + await service.setEnabled(false); + expect(calls.last.method, 'clear'); + }); + + test('Linux revocation discards queued publications', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.linux; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + service.dispose(); + service = DeadlineWidgetService(assignments, channel: channel, now: () => now); + final blocked = Completer(); + messenger.setMockMethodCallHandler(channel, (call) async { + calls.add(call); + if (call.method == 'publish') await blocked.future; + return false; + }); + service.initialize(); + await Future.delayed(Duration.zero); + await assignments.hide(assignments.assignments.first); + final disabling = service.setEnabled(false); + blocked.complete(); + await disabling; + expect(calls.where((call) => call.method == 'publish'), hasLength(1)); + expect(calls.last.method, 'clear'); + }); } diff --git a/test/widget_test.dart b/test/widget_test.dart index 5f775c05..779560dc 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -248,7 +248,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