Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion .github/workflows/linux-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
10 changes: 8 additions & 2 deletions lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,11 @@ Future<void> _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,
Expand Down Expand Up @@ -194,7 +198,8 @@ Future<void> _realMain(SharedPreferences prefs) async {
bootMark('cached data ready');
if (!kIsWeb &&
(defaultTargetPlatform == TargetPlatform.iOS ||
defaultTargetPlatform == TargetPlatform.macOS)) {
defaultTargetPlatform == TargetPlatform.macOS ||
defaultTargetPlatform == TargetPlatform.linux)) {
deadlineWidgetService.initialize();
}

Expand Down Expand Up @@ -481,6 +486,7 @@ class _TechPieAppState extends State<TechPieApp> with WidgetsBindingObserver {
campusCardService: widget.campusCardService,
ecardBindService: widget.ecardBindService,
ecardWidgetService: widget.ecardWidgetService,
deadlineWidgetService: widget.deadlineWidgetService,
child: MaterialApp(
navigatorKey: _navigatorKey,
scaffoldMessengerKey: rootMessengerKey,
Expand Down
23 changes: 22 additions & 1 deletion lib/pages/assignments_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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});
Expand Down Expand Up @@ -460,6 +461,8 @@ class _AssignmentsPageState extends State<AssignmentsPage> {

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,
Expand All @@ -470,7 +473,25 @@ class _AssignmentsPageState extends State<AssignmentsPage> {
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<void>(
context,
builder: (_) => const ThirdPartyAccountsPage(),
),
),
),
],
if (service.error != null) ...[
const SizedBox(height: 8),
Padding(
Expand Down
15 changes: 15 additions & 0 deletions lib/pages/settings_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,21 @@ class _SettingsPageState extends State<SettingsPage> {

// 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),
Expand Down
75 changes: 59 additions & 16 deletions lib/services/deadline_widget_service.dart
Original file line number Diff line number Diff line change
@@ -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';

Expand All @@ -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<void> setEnabled(bool enabled) async {
_enabled = enabled;
_lastPublished = null;
await _publish();
}

OpenDeadlinesHandler? _handler;
bool _pendingRoute = false;
bool _dispatching = false;
Expand All @@ -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)
{
Expand All @@ -73,19 +85,50 @@ class DeadlineWidgetService with WidgetsBindingObserver {
];
}

static List<Map<String, Object>> _linuxItems(List<Map<String, Object>> items) {
final result = <Map<String, Object>>[];
final ids = <String>{};
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 = <String, Object>{
'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<void> _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(),
)
: <Map<String, Object>>[];
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) {
Expand Down
6 changes: 5 additions & 1 deletion lib/services/service_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -32,6 +33,7 @@ class ServiceProvider extends InheritedWidget {
final CampusCardService campusCardService;
final EcardBindService ecardBindService;
final EcardWidgetService? ecardWidgetService;
final DeadlineWidgetService? deadlineWidgetService;

const ServiceProvider({
super.key,
Expand All @@ -50,6 +52,7 @@ class ServiceProvider extends InheritedWidget {
required this.campusCardService,
required this.ecardBindService,
this.ecardWidgetService,
this.deadlineWidgetService,
required super.child,
});

Expand All @@ -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;
}
6 changes: 6 additions & 0 deletions lib/services/storage_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,12 @@ class StorageService {

bool get hasCachedAssignments => _prefs.containsKey(_assignmentsKey);

bool get deadlineWidgetsEnabled => _prefs.getBool('deadline_widgets_enabled') ?? false;

Future<void> setDeadlineWidgetsEnabled(bool enabled) async {
await _prefs.setBool('deadline_widgets_enabled', enabled);
}

Future<void> saveCachedAssignments(List<Map<String, dynamic>> items) =>
_prefs.setString(_assignmentsKey, jsonEncode(items));

Expand Down
4 changes: 4 additions & 0 deletions linux/runner/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand All @@ -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}")
92 changes: 92 additions & 0 deletions linux/runner/deadline_snapshot_store.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
#include "deadline_snapshot_store.h"

#include <json-glib/json-glib.h>
#include <glib/gstdio.h>
#include <cmath>
#include <cstring>

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<gchar*>(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<GFileSetContentsFlags>(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;
}
Loading
Loading