diff --git a/assets/logo/mini/banner.png b/assets/logo/mini/banner.png index 607c54d..61ead7d 100644 Binary files a/assets/logo/mini/banner.png and b/assets/logo/mini/banner.png differ diff --git a/assets/logo/mini/logo_font_mini.png b/assets/logo/mini/logo_font_mini.png index 9f7b4c9..34883ee 100644 Binary files a/assets/logo/mini/logo_font_mini.png and b/assets/logo/mini/logo_font_mini.png differ diff --git a/assets/logo/mini/logo_mono_mini.png b/assets/logo/mini/logo_mono_mini.png index 5fd514e..6e9a965 100644 Binary files a/assets/logo/mini/logo_mono_mini.png and b/assets/logo/mini/logo_mono_mini.png differ diff --git a/assets/logo/mini/mascot.png b/assets/logo/mini/mascot.png index 3c8d66a..0c0f5ac 100644 Binary files a/assets/logo/mini/mascot.png and b/assets/logo/mini/mascot.png differ diff --git a/integration_test/ai_directory_device_test.dart b/integration_test/ai_directory_device_test.dart index 960b71f..467b2f7 100644 --- a/integration_test/ai_directory_device_test.dart +++ b/integration_test/ai_directory_device_test.dart @@ -7,10 +7,14 @@ import 'package:integration_test/integration_test.dart'; import '../test/ai_directory_test.dart' as ai_directory; +import '../test/format_cases_test.dart' as format_cases; +import '../test/ic_format_test.dart' as ic_format; import '../test/reply_mode_api_test.dart' as reply_mode_api; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); ai_directory.main(); + ic_format.main(); + format_cases.main(); reply_mode_api.main(); } diff --git a/lib/config/app_config.dart b/lib/config/app_config.dart index 41bac76..8e47ef6 100644 --- a/lib/config/app_config.dart +++ b/lib/config/app_config.dart @@ -43,11 +43,9 @@ abstract class AppConfig { static const Set defaultReactions = {'👍', '❤️', '😂', '😮', '😢'}; - static final Uri newIssueUrl = Uri( - scheme: 'https', - host: 'github.com', - path: '/krille-chan/fluffychat/issues/new', - ); + // IdealChat WEBNEXT_1105: problems go to our own suggestion board, not + // to the FluffyChat issue tracker on GitHub. + static final Uri newIssueUrl = Uri.parse('https://ideal2001.com/board'); static final Uri homeserverList = Uri( scheme: 'https', diff --git a/lib/config/routes.dart b/lib/config/routes.dart index 2693fab..1f2227c 100644 --- a/lib/config/routes.dart +++ b/lib/config/routes.dart @@ -18,6 +18,7 @@ import 'package:fluffychat/pages/chat_permissions_settings/chat_permissions_sett import 'package:fluffychat/pages/chat_search/chat_search_page.dart'; import 'package:fluffychat/pages/device_settings/device_settings.dart'; import 'package:fluffychat/pages/idealchat/ai_status_page.dart'; +import 'package:fluffychat/pages/idealchat/room_skills_page.dart'; import 'package:fluffychat/pages/idealchat/suggestion_board_page.dart'; import 'package:fluffychat/pages/idealchat/task_board_page.dart'; import 'package:fluffychat/pages/intro/intro_page_presenter.dart'; @@ -118,7 +119,10 @@ abstract class AppRoutes { pageBuilder: (context, state) => defaultPageBuilder( context, state, - BootstrapPage(reset: state.uri.queryParameters['reset'] == 'true'), + BootstrapPage( + reset: state.uri.queryParameters['reset'] == 'true', + fromSettings: state.uri.queryParameters['from'] == 'settings', + ), ), ), ShellRoute( @@ -445,6 +449,15 @@ abstract class AppRoutes { ), redirect: loggedOutRedirect, ), + GoRoute( + path: 'room_skills', + pageBuilder: (context, state) => defaultPageBuilder( + context, + state, + RoomSkillsPage(roomId: state.pathParameters['roomid']!), + ), + redirect: loggedOutRedirect, + ), GoRoute( path: 'suggestions', pageBuilder: (context, state) => defaultPageBuilder( diff --git a/lib/config/setting_keys.dart b/lib/config/setting_keys.dart index 7415cd7..2cfd8a8 100644 --- a/lib/config/setting_keys.dart +++ b/lib/config/setting_keys.dart @@ -17,7 +17,10 @@ enum AppSettings { textMessageMaxLength('textMessageMaxLength', 16384), /// Max lines for unselected HTML/text bubbles; 0 = unlimited (no fade). - messagePreviewMaxLines('chat.fluffy.message_preview_max_lines', 50), + // IdealChat SHOWMORE_1105 (owner 11-05 19:35 「全服务都规定一下最多3行吧」). + messagePreviewMaxLines('chat.fluffy.message_preview_max_lines', 3), + // IdealChat ICEMOTE_1105: show the small robot icons (【表情:…】); off = text. + icShowEmotes('idealchat.show_emotes', true), audioRecordingNumChannels('audioRecordingNumChannels', 1), audioRecordingAutoGain('audioRecordingAutoGain', true), audioRecordingEchoCancel('audioRecordingEchoCancel', false), diff --git a/lib/l10n/intl_en.arb b/lib/l10n/intl_en.arb index 9203c55..e4568bd 100644 --- a/lib/l10n/intl_en.arb +++ b/lib/l10n/intl_en.arb @@ -2171,8 +2171,8 @@ "sendReadReceipts": "Send read receipts", "sendTypingNotificationsDescription": "Other participants in a chat can see when you are typing a new message.", "sendReadReceiptsDescription": "Other participants in a chat can see when you have read a message.", - "formattedMessages": "Formatted messages", - "formattedMessagesDescription": "Display rich message content like bold text using markdown.", + "formattedMessages": "Show message formatting", + "formattedMessagesDescription": "Bold, colors, underline and quote boxes are shown as formatted. Turn off to see the plain original text.", "verifyOtherUser": "🔐 Verify other user", "verifyOtherUserDescription": "If you verify another user, you can be sure that you know who you are really writing to. 💪\n\nWhen you start a verification, you and the other user will see a popup in the app. There you will then see a series of emojis or numbers that you have to compare with each other.\n\nThe best way to do this is to meet up or start a video call. 👭", "verifyOtherDevice": "🔐 Verify other device", diff --git a/lib/l10n/intl_zh.arb b/lib/l10n/intl_zh.arb index 2c8a6db..35053c5 100644 --- a/lib/l10n/intl_zh.arb +++ b/lib/l10n/intl_zh.arb @@ -2028,7 +2028,7 @@ } }, "sendTypingNotificationsDescription": "聊天中的其他参与者可以看到你正在输入新消息。", - "formattedMessagesDescription": "使用 Markdown 显示富文本内容,例如加粗文本。", + "formattedMessagesDescription": "加粗、颜色、下划线、引用框按格式显示;关掉只看原文(纯文字)。", "verifyOtherUserDescription": "如果你验证了其他用户,就可以确保你清楚自己正在与谁进行通信。💪\n\n当你开始验证时,你和其他用户将在应用中看到一个弹出窗口。然后你会看到一系列表情符号或数字,你和其他用户需要比较它们是否一致。\n\n最好的方式是线下会面或开始视频通话。👭", "verifyOtherDeviceDescription": "当你验证另一个设备时,这些设备可以交换密钥,从而提高整体安全性。 💪 当你开始验证时,两个设备上的应用都将显示一个弹出窗口。然后你会看到一系列表情符号或数字,你需要比较两个设备上显示的内容。在开始验证之前,最好将两个设备都放在手边。🤳", "canceledKeyVerification": "{sender} 取消了密钥验证", @@ -2041,7 +2041,7 @@ } }, "sendReadReceipts": "发送已读回执", - "formattedMessages": "格式化的消息", + "formattedMessages": "显示消息格式", "verifyOtherDevice": "🔐 验证其它设备", "verifyOtherUser": "🔐 验证其他用户", "sendReadReceiptsDescription": "聊天中的其他参与者可以看到你是否读过消息。", diff --git a/lib/l10n/intl_zh_Hant.arb b/lib/l10n/intl_zh_Hant.arb index d35d9ea..5be3a6a 100644 --- a/lib/l10n/intl_zh_Hant.arb +++ b/lib/l10n/intl_zh_Hant.arb @@ -1735,7 +1735,7 @@ "banUserDescription": "該使用者將被禁止進入聊天室,直到他們被解封之前都無法再次進入聊天室。", "searchChatsRooms": "搜尋 #chats, @users...", "sendReadReceipts": "傳送已讀回條", - "formattedMessagesDescription": "使用 markdown 顯示豐富的訊息內容,如粗體文字。", + "formattedMessagesDescription": "粗體、顏色、底線、引用框按格式顯示;關掉只看原文(純文字)。", "verifyOtherDevice": "🔐 驗證其他裝置", "youInvitedUser": "📩 您邀請了 {user}", "@youInvitedUser": { @@ -2115,7 +2115,7 @@ "searchMore": "搜尋更多......", "gallery": "畫廊", "sendReadReceiptsDescription": "聊天室中的其他參與者可以看到您已讀取一條訊息。", - "formattedMessages": "格式化訊息", + "formattedMessages": "顯示訊息格式", "goToSpace": "前往空間:{space}", "@goToSpace": { "type": "String", diff --git a/lib/main.dart b/lib/main.dart index c3691ce..bc98b1f 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -11,6 +11,9 @@ import 'package:collection/collection.dart'; import 'package:fluffychat/config/app_config.dart'; import 'package:fluffychat/utils/client_manager.dart'; import 'package:fluffychat/utils/error_reporter.dart'; +import 'package:fluffychat/utils/idealchat/ic_error_report.dart'; +import 'package:fluffychat/utils/idealchat/ic_error_widget.dart'; +import 'package:fluffychat/utils/idealchat/ic_next.dart'; import 'package:fluffychat/utils/notification_background_handler.dart'; import 'package:fluffychat/utils/platform_infos.dart'; import 'package:fluffychat/utils/start_push_foreground_service.dart'; @@ -33,85 +36,105 @@ bool _vodozemacInitialized = false; bool isIntegrationTest = false; -void main(List args) => runZonedGuarded(() async { - // Forward Flutter errors to global error reporter - FlutterError.onError = (details) => Zone.current.handleUncaughtError( - details.exception, - details.stack ?? StackTrace.current, - ); - - isIntegrationTest = args.singleOrNull == 'integration_test'; - if (PlatformInfos.isAndroid) { - final port = mainIsolateReceivePort = ReceivePort(); - IsolateNameServer.removePortNameMapping(AppConfig.mainIsolatePortName); - IsolateNameServer.registerPortWithName( - port.sendPort, - AppConfig.mainIsolatePortName, - ); - await waitForPushIsolateDone(); - } - - // Sanitize hash for OIDC: - if (kIsWeb) { - final hash = web.window.location.hash; - if (hash.isNotEmpty && !hash.startsWith('/')) { - web.window.location.hash = hash.replaceFirst('#', '#?'); +void main(List args) => runZonedGuarded( + () async { + // Forward Flutter errors to global error reporter + FlutterError.onError = (details) { + // IdealChat ERRREPORT_1106: report to our server (scrubbed, rate-limited). + IcErrorReport.report('flutter', details.exception, details.stack); + Zone.current.handleUncaughtError( + details.exception, + details.stack ?? StackTrace.current, + ); + }; + PlatformDispatcher.instance.onError = (error, stack) { + IcErrorReport.report('platform', error, stack); + return false; // keep the default handling + }; + + // IdealChat ERRWIDGET_1106: a widget that fails shows one small line in + // its own spot instead of a grey box. + ErrorWidget.builder = icErrorWidget; + + isIntegrationTest = args.singleOrNull == 'integration_test'; + if (PlatformInfos.isAndroid) { + final port = mainIsolateReceivePort = ReceivePort(); + IsolateNameServer.removePortNameMapping(AppConfig.mainIsolatePortName); + IsolateNameServer.registerPortWithName( + port.sendPort, + AppConfig.mainIsolatePortName, + ); + await waitForPushIsolateDone(); } - } - // Our background push shared isolate accesses flutter-internal things very early in the startup proccess - // To make sure that the parts of flutter needed are started up already, we need to ensure that the - // widget bindings are initialized already. - WidgetsFlutterBinding.ensureInitialized(); + // Sanitize hash for OIDC: + if (kIsWeb) { + final hash = web.window.location.hash; + if (hash.isNotEmpty && !hash.startsWith('/')) { + web.window.location.hash = hash.replaceFirst('#', '#?'); + } + } - final store = await AppSettings.init(); - Logs().i('Welcome to ${AppSettings.applicationName.value} <3'); + // Our background push shared isolate accesses flutter-internal things very early in the startup proccess + // To make sure that the parts of flutter needed are started up already, we need to ensure that the + // widget bindings are initialized already. + WidgetsFlutterBinding.ensureInitialized(); - kEnableMatrixSdkBenchmarks = AppSettings.benchmarksInLogs.value; + // WEBNEXT_1105: the side-by-side web build keeps its own preferences. + if (kIsWeb && icNextBuild) SharedPreferences.setPrefix(icNextPrefsPrefix); + final store = await AppSettings.init(); + Logs().i('Welcome to ${AppSettings.applicationName.value} <3'); - if (!_vodozemacInitialized) { - await vod.init( - wasmPath: './assets/assets/vodozemac/${AppConfig.vodozemacVersion}/', - ); - _vodozemacInitialized = true; - } + kEnableMatrixSdkBenchmarks = AppSettings.benchmarksInLogs.value; - Logs().nativeColors = !PlatformInfos.isIOS; + if (!_vodozemacInitialized) { + await vod.init( + wasmPath: './assets/assets/vodozemac/${AppConfig.vodozemacVersion}/', + ); + _vodozemacInitialized = true; + } - // If the app starts in detached mode, we assume that it is in - // background fetch mode for processing push notifications. This is - // currently only supported on Android. - if (PlatformInfos.isAndroid && - AppLifecycleState.detached == WidgetsBinding.instance.lifecycleState) { - await ForegroundServices.startService('background_push'); + Logs().nativeColors = !PlatformInfos.isIOS; + + // If the app starts in detached mode, we assume that it is in + // background fetch mode for processing push notifications. This is + // currently only supported on Android. + if (PlatformInfos.isAndroid && + AppLifecycleState.detached == WidgetsBinding.instance.lifecycleState) { + await ForegroundServices.startService('background_push'); + + final clients = await ClientManager.getClients(store: store); + + // Do not send online presences when app is in background fetch mode. + for (final client in clients) { + client.backgroundSync = false; + client.syncPresence = PresenceType.offline; + } + + // In the background fetch mode we do not want to waste ressources with + // starting the Flutter engine but process incoming push notifications. + BackgroundPush.clientOnly(clients); + // To start the flutter engine afterwards we add an custom observer. + WidgetsBinding.instance.addObserver(AppStarter(clients, store)); + Logs().i( + '${AppSettings.applicationName.value} started in background-fetch mode. No GUI will be created unless the app is no longer detached.', + ); + return; + } final clients = await ClientManager.getClients(store: store); - // Do not send online presences when app is in background fetch mode. - for (final client in clients) { - client.backgroundSync = false; - client.syncPresence = PresenceType.offline; - } - - // In the background fetch mode we do not want to waste ressources with - // starting the Flutter engine but process incoming push notifications. - BackgroundPush.clientOnly(clients); - // To start the flutter engine afterwards we add an custom observer. - WidgetsBinding.instance.addObserver(AppStarter(clients, store)); + // Started in foreground mode. Logs().i( - '${AppSettings.applicationName.value} started in background-fetch mode. No GUI will be created unless the app is no longer detached.', + '${AppSettings.applicationName.value} started in foreground mode. Rendering GUI...', ); - return; - } - - final clients = await ClientManager.getClients(store: store); - - // Started in foreground mode. - Logs().i( - '${AppSettings.applicationName.value} started in foreground mode. Rendering GUI...', - ); - await startGui(clients, store); -}, ErrorReporter.onFlutterError); + await startGui(clients, store); + }, + (error, stack) { + IcErrorReport.report('zone', error, stack); + ErrorReporter.onFlutterError(error, stack); + }, +); /// Fetch the pincode for the applock and start the flutter engine. Future startGui(List clients, SharedPreferences store) async { diff --git a/lib/pages/bootstrap/bootstrap_page.dart b/lib/pages/bootstrap/bootstrap_page.dart index bafa22c..0006917 100644 --- a/lib/pages/bootstrap/bootstrap_page.dart +++ b/lib/pages/bootstrap/bootstrap_page.dart @@ -3,6 +3,8 @@ // // SPDX-License-Identifier: AGPL-3.0-or-later +import 'dart:async'; + import 'package:fluffychat/l10n/l10n.dart'; import 'package:fluffychat/pages/bootstrap/view_model/bootstrap_view_model.dart'; import 'package:fluffychat/pages/bootstrap/widgets/new_passphrase_view.dart'; @@ -14,10 +16,82 @@ import 'package:fluffychat/widgets/matrix.dart'; import 'package:fluffychat/widgets/view_model_builder.dart'; import 'package:go_router/go_router.dart'; import 'package:material_ui/material_ui.dart'; +import 'package:matrix/matrix.dart'; + +/// IdealChat BACKUPPROMPT_1105 (owner 11-05 「总是出现这个」): the chat backup +/// page used to open after every login, so its close button asked "skip chat +/// backup?" every time. After login it now only shows when the account has no +/// backup yet and nobody chose "skip" before; that choice is kept in the +/// account data (all devices and the web app), not only on this phone. +/// Settings → Chat backup still opens it as before. +abstract class IcBackupPrompt { + static const type = 'im.idealchat.backup_prompt'; + + static bool skipped(Client client) => + client.accountData[type]?.content['skipped'] == true; + + static Future markSkipped(Client client) async { + try { + await client.setAccountData(client.userID!, type, { + 'skipped': true, + 'at': DateTime.now().millisecondsSinceEpoch, + }); + } catch (e) { + Logs().w('Unable to remember skipped chat backup', e); + } + } +} -class BootstrapPage extends StatelessWidget { +/// IdealChat NOBACKUP_1107 (owner 11-07 17:59 「很多人碰到这个,能否把这个去掉?」): +/// the chat backup page is never opened by itself any more (login goes to the +/// chat list). Reaching /backup any other way than Settings → Chat backup goes +/// straight to the chat list; from Settings, if it is still loading after 15 s +/// it goes back to the chat list instead of spinning forever. +class BootstrapPage extends StatefulWidget { final bool reset; - const BootstrapPage({required this.reset, super.key}); + + /// Opened from Settings → Chat backup. + final bool fromSettings; + const BootstrapPage({ + required this.reset, + this.fromSettings = false, + super.key, + }); + + @override + State createState() => _BootstrapPageState(); +} + +class _BootstrapPageState extends State { + Timer? _loadingTimeout; + bool _loaded = false; + + bool get reset => widget.reset; + + @override + void initState() { + super.initState(); + if (reset) return; + if (!widget.fromSettings) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) context.go('/rooms'); + }); + return; + } + _loadingTimeout = Timer(const Duration(seconds: 15), () { + if (!mounted || _loaded) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('聊天备份暂时打不开,请稍后再试')), + ); + context.go('/rooms'); + }); + } + + @override + void dispose() { + _loadingTimeout?.cancel(); + super.dispose(); + } @override Widget build(BuildContext context) { @@ -27,6 +101,10 @@ class BootstrapPage extends StatelessWidget { BootstrapViewModel(client: Matrix.of(context).client, reset: reset), builder: (context, viewModel, _) { final cryptoIdentityState = viewModel.value.cryptoIdentityState; + if (cryptoIdentityState != null) { + _loaded = true; + _loadingTimeout?.cancel(); + } if (cryptoIdentityState?.connected == true && !reset) { WidgetsBinding.instance.addPostFrameCallback( (_) => viewModel.goToRoomsPageAfterSuccess(context), @@ -60,6 +138,11 @@ class BootstrapPage extends StatelessWidget { ); if (consent != OkCancelResult.ok) return; if (!context.mounted) return; + // Don't ask again after the next login. + await IcBackupPrompt.markSkipped( + Matrix.of(context).client, + ); + if (!context.mounted) return; } context.go('/rooms'); }, diff --git a/lib/pages/bootstrap/view_model/bootstrap_view_model.dart b/lib/pages/bootstrap/view_model/bootstrap_view_model.dart index b02c844..36118a6 100644 --- a/lib/pages/bootstrap/view_model/bootstrap_view_model.dart +++ b/lib/pages/bootstrap/view_model/bootstrap_view_model.dart @@ -284,7 +284,7 @@ class BootstrapViewModel extends ValueNotifier { ) async { final path = await FilePicker.saveFile( fileName: - 'FluffyChat-Recovery-Key-${DateTime.now().toIso8601String()}.txt', + 'IdealChat-Recovery-Key-${DateTime.now().toIso8601String()}.txt', bytes: Uint8List.fromList(value.recoveryKey!.codeUnits), ); if (path == null) return; diff --git a/lib/pages/chat/chat.dart b/lib/pages/chat/chat.dart index c146fa7..55611e4 100644 --- a/lib/pages/chat/chat.dart +++ b/lib/pages/chat/chat.dart @@ -4,6 +4,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later import 'dart:async'; +import 'dart:convert'; import 'dart:io'; import 'package:collection/collection.dart'; @@ -22,6 +23,10 @@ import 'package:fluffychat/pages/chat_details/chat_details.dart'; import 'package:fluffychat/utils/adaptive_bottom_sheet.dart'; import 'package:fluffychat/utils/error_reporter.dart'; import 'package:fluffychat/utils/file_selector.dart'; +import 'package:fluffychat/utils/idealchat/ai_directory.dart'; +import 'package:fluffychat/utils/idealchat/ic_error_report.dart'; +import 'package:fluffychat/utils/idealchat/ic_format.dart'; +import 'package:fluffychat/utils/idealchat/mention_ranking.dart'; import 'package:fluffychat/utils/matrix_live_kit_calls/matrix_live_kit_call.dart'; import 'package:fluffychat/utils/matrix_sdk_extensions/event_extension.dart'; import 'package:fluffychat/utils/matrix_sdk_extensions/filtered_timeline_extension.dart'; @@ -240,7 +245,159 @@ class ChatController extends State Future requestHistory([_]) async { Logs().v('Requesting history...'); + final before = timeline?.events.length ?? 0; + final visibleBefore = timeline?.events.filterByVisibleInGui().length ?? 0; await timeline?.requestHistory(historyCount: _loadHistoryCount); + await _icFillVisibleHistory(visibleBefore, before); + await _icHealPrevBatch(); + // ROOMRESET_1106: three history loads in a row that add nothing (and the + // room's start isn't loaded) mean the local timeline is stuck. + final tl = timeline; + if (tl == null) return; + if (tl.events.length != before || + tl.events.isEmpty || + tl.events.last.type == EventTypes.RoomCreate) { + _icStuckCount = 0; + return; + } + if (++_icStuckCount >= 3) { + _icStuckCount = 0; + await _icResetRoomTimeline('history_stuck'); + } + } + + // IdealChat ROOMRESET_1106 (主人 11-06「以后如何杜绝此类问题发生」): when a + // room's back-pagination is stuck or the room keeps throwing errors, drop + // its local timeline the same way the SDK does for a gappy sync (limited + // timeline) and load it again from the server. Once per room per 30 + // minutes, at most 3 per hour, reported as kind "heal". + int _icStuckCount = 0; + static final _icResetAt = {}; + static final _icResetTimes = []; + + Future _icResetRoomTimeline(String why) async { + final now = DateTime.now(); + final last = _icResetAt[room.id]; + if (last != null && now.difference(last) < const Duration(minutes: 30)) { + return; + } + _icResetTimes.removeWhere( + (t) => now.difference(t) > const Duration(hours: 1), + ); + if (_icResetTimes.length >= 3) return; + _icResetAt[room.id] = now; + _icResetTimes.add(now); + try { + final client = room.client; + final resp = await client.getRoomEvents( + room.id, + Direction.b, + limit: _loadHistoryCount, + ); + await client.handleSync( + SyncUpdate( + nextBatch: '', + rooms: RoomsUpdate( + join: { + room.id: JoinedRoomUpdate( + state: resp.state, + timeline: TimelineUpdate( + limited: true, + prevBatch: resp.end, + events: resp.chunk.reversed.toList(), + ), + ), + }, + ), + ), + ); + IcErrorReport.report( + 'heal', + Exception('room timeline reset: $why'), + StackTrace.empty, + ); + Logs().i('[IC] room timeline reset ($why) ${room.id}'); + if (!mounted) return; + setState(() { + timeline?.cancelSubscriptions(); + timeline = null; + loadTimelineFuture = _getTimeline().onError( + ErrorReporter(context, 'Unable to reload timeline').onErrorCallback, + ); + }); + } catch (e) { + Logs().w('[IC] room timeline reset failed', e); + } + } + + // IdealChat HISTFILL_1106: the SDK reads older messages from the local + // cache first and only asks the server once the cache is empty. When the + // cached batch is mostly hidden events (reactions, edits, state), hardly + // any visible message is added and the cache never runs out. Keep loading + // (up to 4 more times) until at least 10 more are visible; then fetch one + // page from the server directly (stored in the cache, then read). + Future _icFillVisibleHistory( + int visibleBefore, + int eventsBefore, + ) async { + final tl = timeline; + if (tl == null) return; + // SHORTDB_1106: the cache gave fewer than asked (e.g. 72 of 100), so it + // is exhausted; load once more right away (the cache gives 0 and the SDK + // goes to the server) instead of waiting for a scroll to the very top. + final added = tl.events.length - eventsBefore; + if (added > 0 && added < _loadHistoryCount && tl.canRequestHistory) { + await tl.requestHistory(historyCount: _loadHistoryCount); + } + int gained() => tl.events.filterByVisibleInGui().length - visibleBefore; + for (var i = 0; i < 4 && gained() < 10 && tl.canRequestHistory; i++) { + if (timeline != tl || !mounted) return; + await tl.requestHistory(historyCount: _loadHistoryCount); + } + if (gained() >= 10 || room.prev_batch == null || !tl.canRequestHistory) { + return; + } + try { + await room.requestHistory(historyCount: _loadHistoryCount); + if (timeline == tl && mounted) { + await tl.requestHistory(historyCount: _loadHistoryCount); + } + Logs().i('[IC] history filled from server for ${room.id}'); + } catch (e) { + Logs().w('[IC] history fill from server failed', e); + } + } + + // IdealChat PBHEAL_1106 (主人 11-06「只能看到最近几条」): when the room's + // back-pagination token (prev_batch) is lost from the local cache, the SDK + // silently stops loading older messages. Get a fresh token from the oldest + // loaded event (/context) and save it, then the normal history load works + // again. Once per room per app run, so a room that really reached its start + // can't loop. + static final _icPbHealed = {}; + Future _icHealPrevBatch() async { + final timeline = this.timeline; + if (timeline == null || room.prev_batch != null) return; + if (timeline.canRequestHistory || timeline.events.isEmpty) return; + final oldest = timeline.events.last; + if (oldest.type == EventTypes.RoomCreate) return; + if (!oldest.eventId.startsWith('\$')) return; + if (!_icPbHealed.add(room.id)) return; + try { + final ctx = await room.client.getEventContext( + room.id, + oldest.eventId, + limit: 0, + ); + final start = ctx.start; + if (start == null || room.prev_batch != null) return; + room.prev_batch = start; + await room.client.database.setRoomPrevBatch(start, room.id, room.client); + Logs().i('[IC] prev_batch healed for ${room.id}'); + if (mounted) setState(() {}); + } catch (e) { + Logs().w('[IC] prev_batch heal failed', e); + } } Future requestFuture() async { @@ -398,7 +555,16 @@ class ChatController extends State inputFocus.addListener(_inputFocusListener); _loadDraft(); + IcErrorReport.onRoomErrors = (id) { + if (mounted && id == room.id) _icResetRoomTimeline('errors'); + }; WidgetsBinding.instance.addPostFrameCallback((_) { + // MENTIONS_1105: fetch the full member list and the @ order early + // (after the first frame: `room` needs the sending client first). + IcMentionRanking.loadMembers(room); + IcMentionRanking.of(room); + // AI list for the AI-discussion rule (AIFOLD_1105). + IcAiDirectory.instance.ensureLoaded(room.client); _shareItems(); _checkMatrixRtcCallSupport(); if (widget.action == 'call') { @@ -497,8 +663,13 @@ class ChatController extends State } if (readMarkerEventIndex > 1) { - Logs().v('Scroll up to visible event', readMarkerEventId); - scrollToEventId(readMarkerEventId, highlightEvent: false); + // IdealChat RMJUMP_1106: don't auto-scroll to the read marker on open. + // scrollToIndex in the reversed list could land where no row was + // built while older messages were being inserted — a blank chat + // (主人 11-06 商业变现群). Stay at the newest and offer the + // 「跳到未读」 banner instead. + Logs().v('Read marker above, showing banner', readMarkerEventId); + _showScrollUpMaterialBanner(readMarkerEventId); } else if (readMarkerEventId.isNotEmpty && readMarkerEventIndex == -1) { _showScrollUpMaterialBanner(readMarkerEventId); } @@ -541,6 +712,7 @@ class ChatController extends State } Future? loadTimelineFuture; + StreamSubscription? _icLimitedSub; Future _getTimeline({String? eventContextId}) async { final matrix = Matrix.of(context); @@ -571,10 +743,48 @@ class ChatController extends State } timeline!.requestKeys(onlineKeyBackupOnly: false); if (room.markedUnread) room.markUnread(false); + // IdealChat LIMITEDFIX_1106: when a sync for this room is "limited" (too + // many new events at once), the SDK drops every event of the open + // timeline that is not in that sync without telling the UI — the chat + // went blank or showed only the latest few. Redraw and load one page of + // history (from the server; the cache was just cleared) right after. + _icLimitedSub?.cancel(); + _icLimitedSub = room.client.onSync.stream + .where((s) => s.rooms?.join?[room.id]?.timeline?.limited == true) + .listen((_) { + Future.delayed(const Duration(milliseconds: 50), () { + if (!mounted) return; + setState(() {}); + requestHistory(); + }); + }); + _icPrefetchHistory(); return; } + // IdealChat PREFETCH_1106 (主人 11-06「只显示最近几条」): a room often opens + // with only the ~10-30 messages the cache or sync had; older ones used to + // load only once the list was scrolled to its very top, and with tall + // messages users thought they were already there. Load one page of history + // right away (once per opened timeline) when fewer than 50 are loaded. + void _icPrefetchHistory() { + final tl = timeline; + if (tl == null || activeThreadId != null) return; + if (!tl.canRequestHistory || tl.isRequestingHistory) return; + // OPENFILL_1106: on every opening, read the cache page by page until it + // runs out (a short page then goes to the server, SHORTDB_1106) — up to + // 6 loads — so older messages never wait for a scroll to the very top. + WidgetsBinding.instance.addPostFrameCallback((_) async { + for (var i = 0; i < 6; i++) { + if (!mounted || timeline != tl || !tl.canRequestHistory) return; + final before = tl.events.length; + await requestHistory(); + if (tl.events.length - before < _loadHistoryCount) return; + } + }); + } + String? scrollToEventIdMarker; @override @@ -597,8 +807,12 @@ class ChatController extends State // We only set read marker if we are at the bottom if (_scrolledUp && setOnLatestEvent) return; - // We do not set read marker if we offer user the scroll up banner - if (scrollUpBannerEventId != null) return; + // We do not set read marker if we offer user the scroll up banner — + // except on the newest message while at the bottom (IdealChat + // READMARK_1107, 主人 11-07 「数字为什么不及时消失?」: since RMJUMP_1106 + // the banner shows on every open with unread messages, so the room was + // only marked read after sending). + if (scrollUpBannerEventId != null && !setOnLatestEvent) return; // We do not set read marker if timeline is empty final timeline = this.timeline; @@ -666,6 +880,8 @@ class ChatController extends State @override void dispose() { + _icLimitedSub?.cancel(); + IcErrorReport.onRoomErrors = null; timeline?.cancelSubscriptions(); timeline = null; _storeInputTimeoutTimer?.cancel(); @@ -740,14 +956,37 @@ class ChatController extends State room.setTyping(false); } - // ignore: unawaited_futures - room.sendTextEvent( - sendController.text, - inReplyTo: replyEvent, - editEventId: editEvent?.eventId, - parseCommands: parseCommands, - threadRootEventId: activeThreadId, - ); + // IdealChat LONGTEXT_1107: the server refuses events over 60 000 bytes + // (body + formatted_body, more once encrypted) and the text was lost, so + // a very long message goes out as a .txt file instead. + final textBytes = utf8.encode(sendController.text); + if (editEvent == null && textBytes.length > 20000) { + // ignore: unawaited_futures + room.sendFileEvent( + MatrixFile( + bytes: textBytes, + name: 'message_${DateTime.now().millisecondsSinceEpoch}.txt', + mimeType: 'text/plain', + ), + inReplyTo: replyEvent, + threadRootEventId: activeThreadId, + threadLastEventId: threadLastEventId, + ); + if (mounted) { + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('内容太长,已自动作为文件发送'))); + } + } else { + // ignore: unawaited_futures + room.icSendTextEvent( + sendController.text, + inReplyTo: replyEvent, + editEventId: editEvent?.eventId, + parseCommands: parseCommands, + threadRootEventId: activeThreadId, + ); + } sendController.value = TextEditingValue( text: pendingText, selection: const TextSelection.collapsed(offset: 0), diff --git a/lib/pages/chat/chat_app_bar_title.dart b/lib/pages/chat/chat_app_bar_title.dart index ed89b3d..443f2cf 100644 --- a/lib/pages/chat/chat_app_bar_title.dart +++ b/lib/pages/chat/chat_app_bar_title.dart @@ -8,6 +8,7 @@ import 'package:fluffychat/l10n/l10n.dart'; import 'package:fluffychat/pages/chat/chat.dart'; import 'package:fluffychat/utils/date_time_extension.dart'; import 'package:fluffychat/utils/idealchat/member_counts.dart'; +import 'package:fluffychat/utils/idealchat/room_labels.dart'; import 'package:fluffychat/utils/matrix_sdk_extensions/matrix_locals.dart'; import 'package:fluffychat/utils/sync_status_localization.dart'; import 'package:fluffychat/utils/verified_room_extension.dart'; @@ -47,9 +48,7 @@ class ChatAppBarTitle extends StatelessWidget { tag: 'content_banner', child: Avatar( mxContent: room.avatar, - name: room.getLocalizedDisplayname( - MatrixLocals(L10n.of(context)), - ), + name: room.icDisplayname(MatrixLocals(L10n.of(context))), size: 32, ), ), @@ -70,9 +69,7 @@ class ChatAppBarTitle extends StatelessWidget { ), Expanded( child: Text( - room.getLocalizedDisplayname( - MatrixLocals(L10n.of(context)), - ), + room.icDisplayname(MatrixLocals(L10n.of(context))), maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 16), diff --git a/lib/pages/chat/chat_event_list.dart b/lib/pages/chat/chat_event_list.dart index 7db7802..0c76b52 100644 --- a/lib/pages/chat/chat_event_list.dart +++ b/lib/pages/chat/chat_event_list.dart @@ -137,6 +137,7 @@ class ChatEventList extends StatelessWidget { // The message at this index: final event = events[i]; + final animateIn = (event.transactionId ?? event.eventId) == controller.animateInEventId; diff --git a/lib/pages/chat/chat_input_row.dart b/lib/pages/chat/chat_input_row.dart index 405645c..384d5a9 100644 --- a/lib/pages/chat/chat_input_row.dart +++ b/lib/pages/chat/chat_input_row.dart @@ -395,9 +395,8 @@ class _ChatAccountPicker extends StatelessWidget { const _ChatAccountPicker(this.controller); void _popupMenuButtonSelected(String mxid, BuildContext context) { - final client = Matrix.of( - context, - ).currentBundle!.firstWhere((cl) => cl!.userID == mxid, orElse: () => null); + final client = Matrix.of(context).currentBundle! + .firstWhere((cl) => cl!.userID == mxid, orElse: () => null); if (client == null) { Logs().w('Attempted to switch to a non-existing client $mxid'); return; diff --git a/lib/pages/chat/chat_view.dart b/lib/pages/chat/chat_view.dart index 750e712..b2344f4 100644 --- a/lib/pages/chat/chat_view.dart +++ b/lib/pages/chat/chat_view.dart @@ -478,9 +478,8 @@ class ChatView extends StatelessWidget { onPressed: controller.recreateChat, label: Text( - L10n.of( - context, - ).reopenChat, + L10n.of(context) + .reopenChat, ), ), ], diff --git a/lib/pages/chat/encryption_info.dart b/lib/pages/chat/encryption_info.dart index 9f5cfda..ac75928 100644 --- a/lib/pages/chat/encryption_info.dart +++ b/lib/pages/chat/encryption_info.dart @@ -74,9 +74,8 @@ class EncryptionInfo extends StatelessWidget { ), TextSpan(text: ' '), TextSpan( - text: L10n.of( - context, - ).countUnverifiedDevices(unverifiedDevices), + text: L10n.of(context) + .countUnverifiedDevices(unverifiedDevices), ), TextSpan(text: ' '), TextSpan( diff --git a/lib/pages/chat/events/audio_player.dart b/lib/pages/chat/events/audio_player.dart index b366326..1dc6b17 100644 --- a/lib/pages/chat/events/audio_player.dart +++ b/lib/pages/chat/events/audio_player.dart @@ -108,9 +108,8 @@ class AudioPlayerState extends State { null; WidgetsBinding.instance.addPostFrameCallback((_) { - ScaffoldMessenger.of( - matrix.context, - ).clearMaterialBanners(); + ScaffoldMessenger.of(matrix.context) + .clearMaterialBanners(); }); }, icon: const Icon(Icons.close_outlined), @@ -198,9 +197,8 @@ class AudioPlayerState extends State { } catch (e, s) { Logs().v('Could not download audio file', e, s); if (!mounted) rethrow; - ScaffoldMessenger.of( - context, - ).showSnackBar(SnackBar(content: Text(e.toLocalizedString(context)))); + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text(e.toLocalizedString(context)))); rethrow; } if (!context.mounted) return; @@ -509,9 +507,8 @@ class AudioPlayerState extends State { ), child: Linkify( text: fileDescription, - textScaleFactor: MediaQuery.textScalerOf( - context, - ).scale(1), + textScaleFactor: MediaQuery.textScalerOf(context) + .scale(1), style: TextStyle( color: widget.color, fontSize: widget.fontSize, diff --git a/lib/pages/chat/events/html_message.dart b/lib/pages/chat/events/html_message.dart index 086892e..4bf93fe 100644 --- a/lib/pages/chat/events/html_message.dart +++ b/lib/pages/chat/events/html_message.dart @@ -3,6 +3,8 @@ // // SPDX-License-Identifier: AGPL-3.0-or-later +import 'dart:math'; + import 'package:collection/collection.dart'; import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:fluffychat/config/setting_keys.dart'; @@ -32,6 +34,10 @@ class HtmlMessage extends StatelessWidget { final String? eventId; final Set? checkboxCheckedEvents; + /// AIFOLD_1105 v2: AI discussion messages show only their first lines + /// with 「展开全文」 (null = the user's preview setting). + final int? maxLinesOverride; + const HtmlMessage({ super.key, required this.html, @@ -42,6 +48,7 @@ class HtmlMessage extends StatelessWidget { required this.onOpen, this.eventId, this.checkboxCheckedEvents, + this.maxLinesOverride, }); /// Keep in sync with: https://spec.matrix.org/latest/client-server-api/#mroommessage-msgtypes @@ -157,6 +164,19 @@ class HtmlMessage extends StatelessWidget { } /// Transforms a Node to an InlineSpan. + /// SUMMARYBOX_1106: blockquote of a 【讨论汇总·第N轮】 message. + static bool _isSummaryBox(dom.Element node) { + final parent = node.parent; + if (parent == null) return false; + for (final n in parent.nodes) { + if (identical(n, node)) return false; + final t = (n.text ?? '').trim(); + if (t.isEmpty) continue; + return t.startsWith('【讨论汇总'); + } + return false; + } + InlineSpan _renderHtml(dom.Node node, BuildContext context, {int depth = 1}) { // We must not render elements nested more than 100 elements deep: if (depth >= 100) return const TextSpan(); @@ -323,6 +343,43 @@ class HtmlMessage extends StatelessWidget { // IdealChat P9 (web RED_ALERT_BOX): a quote with data-mx-color is // drawn as a box in that color (e.g. red warnings from the system). final alertColor = node.attributes['data-mx-color']?.hexToColor; + // IdealChat SUMMARYBOX_1106 (owner 11-06 「改」): the discussion + // summary (【讨论汇总·第N轮】
…) is drawn as a soft + // tinted card with rounded corners instead of the black quote bar. + // Tints come from the bubble's text color, so it fits own/other + // bubbles and dark mode. Ordinary quotes keep their style. + if (alertColor == null && _isSummaryBox(node)) { + // Others' bubbles (where AI summaries appear): soft brand tint; + // own bubbles: tint from the bubble's text color. + final cs = Theme.of(context).colorScheme; + final tint = textColor == cs.onSurface ? cs.primary : textColor; + return WidgetSpan( + child: Container( + // SBWIDTH_1106: no infinite width here — inside a message + // bubble it made the list's scroll extent infinite and the + // whole chat blank (release builds don't assert). + margin: const EdgeInsets.symmetric(vertical: 4.0), + padding: const EdgeInsets.fromLTRB(12, 8, 12, 8), + decoration: BoxDecoration( + color: tint.withAlpha(22), + borderRadius: BorderRadius.circular(10), + border: BorderDirectional( + start: BorderSide(color: tint.withAlpha(110), width: 3), + ), + ), + child: Text.rich( + TextSpan( + children: _renderWithLineBreaks( + node.nodes, + context, + depth: depth, + ), + ), + style: TextStyle(fontSize: fontSize, color: textColor), + ), + ), + ); + } return WidgetSpan( child: Container( padding: alertColor != null @@ -392,6 +449,12 @@ class HtmlMessage extends StatelessWidget { ), ); case 'img': + // ICEMOTE_1105: 「显示表情图标」 off → the icon's name as text. + if (node.attributes.containsKey('data-mx-emoticon') && + !AppSettings.icShowEmotes.value) { + final alt = node.attributes['alt'] ?? node.attributes['title']; + return TextSpan(text: alt == null ? '' : '($alt)'); + } final mxcUrl = Uri.tryParse(node.attributes['src'] ?? ''); if (mxcUrl == null || mxcUrl.scheme != 'mxc') { return TextSpan(text: node.attributes['alt']); @@ -564,7 +627,8 @@ class HtmlMessage extends StatelessWidget { style: switch (node.localName) { 'body' => TextStyle(fontSize: fontSize, color: textColor), 'a' => linkStyle, - 'strong' => const TextStyle(fontWeight: FontWeight.bold), + // HTMLSTYLE_1105: is bold too, is colored like . + 'strong' || 'b' => const TextStyle(fontWeight: FontWeight.bold), 'em' || 'i' => const TextStyle(fontStyle: FontStyle.italic), 'del' || 's' || 'strikethrough' => const TextStyle( decoration: TextDecoration.lineThrough, @@ -576,7 +640,7 @@ class HtmlMessage extends StatelessWidget { 'h4' => TextStyle(fontSize: fontSize * 1.3, height: 1.75), 'h5' => TextStyle(fontSize: fontSize * 1.2, height: 1.75), 'h6' => TextStyle(fontSize: fontSize * 1.1, height: 1.5), - 'span' => TextStyle( + 'span' || 'font' => TextStyle( color: node.attributes['color']?.hexToColor ?? node.attributes['data-mx-color']?.hexToColor ?? @@ -597,7 +661,14 @@ class HtmlMessage extends StatelessWidget { @override Widget build(BuildContext context) { final element = parser.parse(html).body ?? dom.Element.html(''); - final configuredMaxLines = AppSettings.messagePreviewMaxLines.value; + // IdealChat REPLYFOLD_1106 (少爷 11-06 14:14「这种一行的回复为什么会存在显示更多」): + // the quoted original inside is not shown, so it must not count + // toward the fold check either (a one-line reply used to fold). + for (final r in element.querySelectorAll('mx-reply')) { + r.remove(); + } + final configuredMaxLines = + maxLinesOverride ?? AppSettings.messagePreviewMaxLines.value; final maxLines = configuredMaxLines <= 0 ? null : configuredMaxLines; final span = _renderHtml(element, context); final style = TextStyle(fontSize: fontSize, color: textColor); @@ -612,7 +683,17 @@ class HtmlMessage extends StatelessWidget { // Heuristic: if plain text has enough newlines or length, it will overflow. final plainText = element.text; - final lineCount = '\n'.allMatches(plainText).length + 1; + // IdealChat LINECOUNT_1105: formatted messages break lines with
and + //

, not "\n", so count those too (a 12-line message used to count as + // one line and never fold). + final brCount = element.querySelectorAll('br').length; + final blockCount = element + .querySelectorAll('p,li,div,blockquote,tr,h1,h2,h3,h4,h5,h6,pre') + .length; + final lineCount = max( + '\n'.allMatches(plainText).length + 1, + blockCount > 0 ? brCount + blockCount : brCount + 1, + ); final likelyOverflows = lineCount > maxLines || plainText.length > maxLines * 50; @@ -631,6 +712,7 @@ class HtmlMessage extends StatelessWidget { textColor: textColor, linkColor: linkStyle.color ?? textColor, fontSize: fontSize, + fullTextLabels: maxLinesOverride != null, ); } } @@ -642,8 +724,10 @@ class _CollapsibleText extends StatefulWidget { final Color textColor; final Color linkColor; final double fontSize; + final bool fullTextLabels; const _CollapsibleText({ + this.fullTextLabels = false, required this.span, required this.style, required this.maxLines, @@ -683,7 +767,17 @@ class _CollapsibleTextState extends State<_CollapsibleText> { onPressed: () => setState(() => _expanded = !_expanded), style: TextButton.styleFrom(foregroundColor: widget.linkColor), icon: Icon(_expanded ? Icons.arrow_drop_up : Icons.arrow_drop_down), - label: Text(_expanded ? l10n.showLess : l10n.showMore), + label: Text( + widget.fullTextLabels + ? (_expanded + ? (l10n.localeName.startsWith('zh') + ? '收起' + : 'Show less') + : (l10n.localeName.startsWith('zh') + ? '展开全文' + : 'Show full text')) + : (_expanded ? l10n.showLess : l10n.showMore), + ), ), ), ], diff --git a/lib/pages/chat/events/ic_choice_buttons.dart b/lib/pages/chat/events/ic_choice_buttons.dart new file mode 100644 index 0000000..f8155fb --- /dev/null +++ b/lib/pages/chat/events/ic_choice_buttons.dart @@ -0,0 +1,78 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat ICCHOICE_1105 (owner 11-05 19:21): a message with 【请您选】 and +// numbered options (one per line, starting with "1." / "2." or "①", maybe +// inside a > box) gets one button per option; tapping it replies with that +// number, the same as typing it. + +import 'package:material_ui/material_ui.dart'; +import 'package:matrix/matrix.dart'; + +const _circled = '①②③④⑤⑥⑦⑧⑨⑩'; +final _optionRe = RegExp( + r'^\s*(?:[>>]\s*)*(?:(\d{1,2})\s*[..、))]|([①-⑩]))\s*(.+?)\s*$', +); + +class IcChoice { + final String number; + final String label; + const IcChoice(this.number, this.label); +} + +List icChoicesOf(Event event) { + if (event.type != EventTypes.Message) return const []; + final body = event.content.tryGet('body') ?? ''; + if (!body.contains('【请您选】')) return const []; + final choices = []; + for (final line in body.split('\n')) { + final m = _optionRe.firstMatch(line); + if (m == null) continue; + final number = m[1] ?? '${_circled.indexOf(m[2]!) + 1}'; + choices.add(IcChoice(number, m[3]!)); + } + return choices.length >= 2 ? choices : const []; +} + +class IcChoiceButtons extends StatelessWidget { + final Event event; + final Color textColor; + + const IcChoiceButtons({ + required this.event, + required this.textColor, + super.key, + }); + + @override + Widget build(BuildContext context) { + if (event.senderId == event.room.client.userID) { + return const SizedBox.shrink(); + } + final choices = icChoicesOf(event); + if (choices.isEmpty) return const SizedBox.shrink(); + return Padding( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 8), + child: Wrap( + spacing: 8, + runSpacing: 6, + children: [ + for (final c in choices) + OutlinedButton( + style: OutlinedButton.styleFrom( + foregroundColor: textColor, + side: BorderSide(color: textColor.withAlpha(120)), + visualDensity: VisualDensity.compact, + ), + onPressed: () => + event.room.sendTextEvent(c.number, inReplyTo: event), + child: Text( + '${c.number}. ${c.label.length > 24 ? '${c.label.substring(0, 23)}…' : c.label}', + ), + ), + ], + ), + ); + } +} diff --git a/lib/pages/chat/events/message.dart b/lib/pages/chat/events/message.dart index 3e4b3fb..ab47051 100644 --- a/lib/pages/chat/events/message.dart +++ b/lib/pages/chat/events/message.dart @@ -986,6 +986,21 @@ class BubblePainter extends CustomPainter { Offset.zero, ancestor: scrollableBox, ); + // IdealChat BUBBLEGRAD_1106: with an empty scrollable (height 0) the + // gradient's start and end coincide and the web renderer has no shader + // ("Null check operator used on a null value" while painting). Use the + // first colour instead. + if (scrollableRect.isEmpty || + !origin.dx.isFinite || + !origin.dy.isFinite || + colors.isEmpty) { + canvas.drawRect( + Offset.zero & size, + Paint() + ..color = colors.isEmpty ? const Color(0x00000000) : colors.first, + ); + return; + } final paint = Paint() ..shader = ui.Gradient.linear( scrollableRect.topCenter, diff --git a/lib/pages/chat/events/message_content.dart b/lib/pages/chat/events/message_content.dart index 4b23070..5a96f2a 100644 --- a/lib/pages/chat/events/message_content.dart +++ b/lib/pages/chat/events/message_content.dart @@ -7,9 +7,11 @@ import 'dart:math'; import 'package:fluffychat/config/setting_keys.dart'; import 'package:fluffychat/l10n/l10n.dart'; +import 'package:fluffychat/pages/chat/events/ic_choice_buttons.dart'; import 'package:fluffychat/pages/chat/events/poll.dart'; import 'package:fluffychat/pages/chat/events/video_player.dart'; import 'package:fluffychat/pages/image_viewer/image_viewer.dart'; +import 'package:fluffychat/utils/idealchat/ic_format.dart'; import 'package:material_ui/material_ui.dart'; import 'package:matrix/matrix.dart'; @@ -168,9 +170,27 @@ class MessageContent extends StatelessWidget { fontSize: fontSize, ); } + // ICFMT_1105: messages without HTML (people, AIs on other + // computers) still show the shared markers as formatting. + // IdealChat REPLYFOLD_1106: a plain-text reply starts with the quoted + // original ("> <@user> ..." lines, then a blank line). The reply box + // above already shows it, so drop it here (it also made one-line + // replies fold behind 「显示更多」). + var icBody = event.body; + if (event.inReplyToEventId() != null && icBody.startsWith('> ')) { + final icParts = icBody.split('\n'); + var icI = 0; + while (icI < icParts.length && icParts[icI].startsWith('>')) { + icI++; + } + if (icI < icParts.length && icParts[icI].trim().isEmpty) icI++; + if (icI < icParts.length) icBody = icParts.sublist(icI).join('\n'); + } var html = AppSettings.renderHtml.value && event.isRichMessage ? event.formattedText - : event.body.replaceAll('<', '<').replaceAll('>', '>'); + : AppSettings.renderHtml.value + ? icPlainToHtml(icBody) + : icBody.replaceAll('<', '<').replaceAll('>', '>'); if (event.messageType == MessageTypes.Emote) { html = '* $html'; } @@ -178,7 +198,7 @@ class MessageContent extends StatelessWidget { final bigEmotes = !event.isRichMessage && bigEmojis.contains(event.body); - return Padding( + final icMessage = Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), child: HtmlMessage( html: html, @@ -193,12 +213,25 @@ class MessageContent extends StatelessWidget { ), onOpen: (url) => UrlLauncher(context, url.url).launchUrl(), eventId: event.eventId, + // REDFULL_1105 (owner 19:57): red highlights need attention — + // show those messages in full. + maxLinesOverride: icHasRedHighlight(event) ? 0 : null, checkboxCheckedEvents: event.aggregatedEvents( timeline, EventCheckboxRoomExtension.relationshipType, ), ), ); + // ICCHOICE_1105: 【请您选】 options as buttons. + if (icChoicesOf(event).isEmpty) return icMessage; + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + icMessage, + IcChoiceButtons(event: event, textColor: textColor), + ], + ); } case PollEventContent.startType: if (event.redacted) { diff --git a/lib/pages/chat/events/poll.dart b/lib/pages/chat/events/poll.dart index 6247b27..1d07d69 100644 --- a/lib/pages/chat/events/poll.dart +++ b/lib/pages/chat/events/poll.dart @@ -133,9 +133,8 @@ class PollWidget extends StatelessWidget { child: Row( children: [ Text( - L10n.of( - context, - ).countVotes(votedUserIds.length), + L10n.of(context) + .countVotes(votedUserIds.length), maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle( diff --git a/lib/pages/chat/input_bar.dart b/lib/pages/chat/input_bar.dart index ddadb9f..3684778 100644 --- a/lib/pages/chat/input_bar.dart +++ b/lib/pages/chat/input_bar.dart @@ -8,6 +8,7 @@ import 'package:fluffychat/config/app_config.dart'; import 'package:fluffychat/config/setting_keys.dart'; import 'package:fluffychat/l10n/l10n.dart'; import 'package:fluffychat/pages/chat/trust_user_key_dialog.dart'; +import 'package:fluffychat/utils/idealchat/mention_ranking.dart'; import 'package:fluffychat/utils/markdown_context_builder.dart'; import 'package:fluffychat/widgets/mxc_image.dart'; import 'package:flutter/services.dart'; @@ -164,13 +165,10 @@ class InputBar extends StatelessWidget { final userMatch = RegExp(r'[@@]([^\s@@]*)$').firstMatch(searchText); if (userMatch != null) { final userSearch = userMatch[1]!.toLowerCase(); - if (!room.participantListComplete) { - try { - await room.requestParticipants(); - } catch (e) { - Logs().w('Unable to load all participants for mentions', e); - } - } + // MENTIONS_1105: full list from the server, no limit, lead AI first, + // then the most active members (see IcMentionRanking). + await IcMentionRanking.loadMembers(room); + final ranking = await IcMentionRanking.of(room); if (userSearch.isEmpty || 'room'.startsWith(userSearch) || '所有人'.startsWith(userSearch) || @@ -183,25 +181,31 @@ class InputBar extends StatelessWidget { 'avatar_url': null, }); } - for (final user in room.getParticipants()) { - if (user.id == room.client.userID) continue; - final displayName = user.displayName?.toLowerCase(); - if (userSearch.isEmpty || - (displayName != null && - (displayName.contains(userSearch) || - slugify(displayName).contains(userSearch))) || - user.id.toLowerCase().contains(userSearch)) { - ret.add({ - 'type': 'user', - 'mxid': user.id, - 'mention': user.mention, - 'displayname': user.displayName, - 'avatar_url': user.avatarUrl?.toString(), - }); - } - if (ret.length > maxResults) { - break; - } + final users = + room.getParticipants([Membership.join]).where((user) { + if (user.id == room.client.userID) return false; + final displayName = user.displayName?.toLowerCase(); + return userSearch.isEmpty || + (displayName != null && + (displayName.contains(userSearch) || + slugify(displayName).contains(userSearch))) || + user.id.toLowerCase().contains(userSearch); + }).toList()..sort( + (a, b) => ranking.compare( + a.id, + b.id, + a.calcDisplayname(), + b.calcDisplayname(), + ), + ); + for (final user in users) { + ret.add({ + 'type': 'user', + 'mxid': user.id, + 'mention': user.mention, + 'displayname': user.displayName, + 'avatar_url': user.avatarUrl?.toString(), + }); } } final roomMatch = RegExp(r'(?:\s|^)#([-\w]+)$').firstMatch(searchText); @@ -350,14 +354,16 @@ class InputBar extends StatelessWidget { } String insertSuggestion(Map suggestion) { - final replaceText = controller!.text.substring( - 0, - controller!.selection.baseOffset, - ); + // IdealChat CURSORFIX_1106: with no cursor (baseOffset -1, field not + // focused) the substring threw RangeError; insert at the end instead. + final text = controller!.text; + final base = controller!.selection.baseOffset; + final cursor = base < 0 || base > text.length ? text.length : base; + final replaceText = text.substring(0, cursor); var startText = ''; - final afterText = replaceText == controller!.text + final afterText = replaceText == text || cursor + 1 > text.length ? '' - : controller!.text.substring(controller!.selection.baseOffset + 1); + : text.substring(cursor + 1); var insertText = ''; if (suggestion['type'] == 'command') { insertText = '${suggestion['name']!} '; diff --git a/lib/pages/chat/recording_view_model.dart b/lib/pages/chat/recording_view_model.dart index 8640c3e..170a19f 100644 --- a/lib/pages/chat/recording_view_model.dart +++ b/lib/pages/chat/recording_view_model.dart @@ -65,8 +65,7 @@ class RecordingViewModelState extends State { try { final codec = - !PlatformInfos - .isIOS && // Blocked by https://github.com/llfbandit/record/issues/560 + !PlatformInfos.isIOS && // Blocked by https://github.com/llfbandit/record/issues/560 await audioRecorder.isEncoderSupported(AudioEncoder.opus) ? AudioEncoder.opus : AudioEncoder.aacLc; diff --git a/lib/pages/chat/send_file_dialog.dart b/lib/pages/chat/send_file_dialog.dart index 1aa1848..c0477a6 100644 --- a/lib/pages/chat/send_file_dialog.dart +++ b/lib/pages/chat/send_file_dialog.dart @@ -14,6 +14,8 @@ import 'package:fluffychat/config/app_config.dart'; import 'package:fluffychat/l10n/l10n.dart'; import 'package:fluffychat/pages/chat/image_edit_geometry.dart'; import 'package:fluffychat/pages/chat/trust_user_key_dialog.dart'; +import 'package:fluffychat/pages/idealchat/member_panel_page.dart'; +import 'package:fluffychat/utils/localized_exception_extension.dart'; import 'package:fluffychat/utils/matrix_sdk_extensions/matrix_file_extension.dart'; import 'package:fluffychat/utils/other_party_can_receive.dart'; import 'package:fluffychat/utils/platform_infos.dart'; @@ -82,6 +84,33 @@ class SendFileDialogState extends State { }); } + /// IdealChat UPLOADCFG_1103: the dialog closes before the file is checked + /// and uploaded, so errors (file too big, network…) used to vanish with no + /// feedback at all. Show them on the chat page instead. + Future _sendWithFeedback(String? uniqueFileType) async { + final outer = widget.outerContext; + final messenger = ScaffoldMessenger.of(outer); + try { + await _send(uniqueFileType); + } catch (e, s) { + Logs().w('Unable to send file', e, s); + if (!outer.mounted) return; + String mb(int n) => + '${(n / 1048576).toStringAsFixed(n >= 10485760 ? 0 : 1)} MB'; + final text = e is FileTooBigMatrixException + ? icT( + outer, + '文件太大,发不出去:${mb(e.actualFileSize)},上限 ${mb(e.maxFileSize)}。', + 'File too large to send: ${mb(e.actualFileSize)}, limit ${mb(e.maxFileSize)}.', + ) + : icT(outer, '文件没发出去:', 'File not sent: ') + + e.toLocalizedString(outer); + messenger.showSnackBar( + SnackBar(content: Text(text), duration: const Duration(seconds: 10)), + ); + } + } + Future _send(String? uniqueFileType) async { final l10n = L10n.of(context); final scaffoldMessenger = ScaffoldMessenger.of(widget.outerContext); @@ -105,7 +134,13 @@ class SendFileDialogState extends State { } if (!mounted) return; Navigator.of(context, rootNavigator: false).pop(); - final clientConfig = await Result.capture(widget.room.client.getConfig()); + // IdealChat UPLOADCFG_1103: the SDK caches the server's upload limit for + // 3 days; re-read it before every send (falls back to the cached value + // when offline) so a raised limit works at once. This also refreshes the + // cache the SDK's own checks in sendFileEvent/uploadContent read. + final clientConfig = await Result.capture( + widget.room.client.getConfig(cacheLifetime: const Duration(seconds: 1)), + ); final maxUploadSize = clientConfig.asValue?.value.mUploadSize ?? 100 * 1000 * 1000; @@ -141,11 +176,19 @@ class SendFileDialogState extends State { } } else { // Else we just create a MatrixFile - file = MatrixFile( + final plain = MatrixFile( bytes: await _files[i].readAsBytes(), name: xfile.name, mimeType: mimeType, - ).detectFileType; + ); + // IdealChat SVGFILE_1107: an SVG is "image/*" but can't be decoded + // as a bitmap (thumbnail/shrink threw ImageCodecException), so it + // goes as a plain file. + file = + mimeType == 'image/svg+xml' || + xfile.name.toLowerCase().endsWith('.svg') + ? plain + : plain.detectFileType; } if (file.bytes.length > maxUploadSize) { @@ -467,7 +510,7 @@ class SendFileDialogState extends State { child: Text(L10n.of(context).cancel), ), AdaptiveDialogAction( - onPressed: () => _send(uniqueFileType), + onPressed: () => _sendWithFeedback(uniqueFileType), child: Text(L10n.of(context).send), ), ], diff --git a/lib/pages/chat/start_poll_bottom_sheet.dart b/lib/pages/chat/start_poll_bottom_sheet.dart index f3afb32..b12b6b1 100644 --- a/lib/pages/chat/start_poll_bottom_sheet.dart +++ b/lib/pages/chat/start_poll_bottom_sheet.dart @@ -57,9 +57,8 @@ class _StartPollBottomSheetState extends State { } catch (e, s) { Logs().w('Unable to create poll', e, s); if (!mounted) return; - ScaffoldMessenger.of( - context, - ).showSnackBar(SnackBar(content: Text(e.toLocalizedString(context)))); + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text(e.toLocalizedString(context)))); } } diff --git a/lib/pages/chat_details/chat_details_view.dart b/lib/pages/chat_details/chat_details_view.dart index b893ec4..b920dcf 100644 --- a/lib/pages/chat_details/chat_details_view.dart +++ b/lib/pages/chat_details/chat_details_view.dart @@ -12,6 +12,7 @@ import 'package:fluffychat/pages/reply_mode/reply_mode_tile.dart'; import 'package:fluffychat/utils/idealchat/ai_directory.dart'; import 'package:fluffychat/utils/idealchat/member_counts.dart'; import 'package:fluffychat/utils/idealchat/reply_mode_api.dart'; +import 'package:fluffychat/utils/idealchat/room_labels.dart'; import 'package:fluffychat/utils/matrix_sdk_extensions/matrix_locals.dart'; import 'package:fluffychat/utils/verified_room_extension.dart'; import 'package:fluffychat/widgets/avatar.dart'; @@ -83,7 +84,7 @@ class ChatDetailsView extends StatelessWidget { (room.summary.mJoinedMemberCount ?? 0); final canRequestMoreMembers = members.length < actualMembersCount; final iconColor = theme.textTheme.bodyLarge!.color; - final displayname = room.getLocalizedDisplayname( + final displayname = room.icDisplayname( MatrixLocals(L10n.of(context)), ); return Scaffold( diff --git a/lib/pages/chat_list/chat_list.dart b/lib/pages/chat_list/chat_list.dart index 1fc4aa4..035eff7 100644 --- a/lib/pages/chat_list/chat_list.dart +++ b/lib/pages/chat_list/chat_list.dart @@ -13,6 +13,7 @@ import 'package:fluffychat/l10n/l10n.dart'; import 'package:fluffychat/pages/chat_list/chat_list_view.dart'; import 'package:fluffychat/utils/call_kit_params.dart'; import 'package:fluffychat/utils/error_reporter.dart'; +import 'package:fluffychat/utils/idealchat/room_labels.dart'; import 'package:fluffychat/utils/idealchat/timezone_reporter.dart'; import 'package:fluffychat/utils/localized_exception_extension.dart'; import 'package:fluffychat/utils/matrix_sdk_extensions/matrix_locals.dart'; @@ -438,6 +439,7 @@ class ChatListController extends State Matrix.of(context).backgroundPush?.setupPush(context); // IdealChat T-0117: after login / on start; resume is in matrix.dart TimezoneReporter.report(Matrix.of(context).widget.clients); + IcRoomLabels.start(Matrix.of(context).widget.clients); // IdealChat T-0111: ask for notification permission after login even // when no push distributor is installed (local notifications). if (PlatformInfos.isAndroid) { diff --git a/lib/pages/chat_list/chat_list_item.dart b/lib/pages/chat_list/chat_list_item.dart index 400da3e..e790d30 100644 --- a/lib/pages/chat_list/chat_list_item.dart +++ b/lib/pages/chat_list/chat_list_item.dart @@ -7,6 +7,7 @@ import 'package:fluffychat/config/app_config.dart'; import 'package:fluffychat/l10n/l10n.dart'; import 'package:fluffychat/pages/chat_list/active_call_indicator.dart'; import 'package:fluffychat/pages/chat_list/unread_bubble.dart'; +import 'package:fluffychat/utils/idealchat/room_labels.dart'; import 'package:fluffychat/utils/matrix_live_kit_calls/matrix_live_kit_call.dart'; import 'package:fluffychat/utils/matrix_sdk_extensions/matrix_locals.dart'; import 'package:fluffychat/utils/room_status_extension.dart'; @@ -55,9 +56,7 @@ class ChatListItem extends StatelessWidget { final backgroundColor = activeChat ? theme.colorScheme.secondaryContainer : null; - final displayname = room.getLocalizedDisplayname( - MatrixLocals(L10n.of(context)), - ); + final displayname = room.icDisplayname(MatrixLocals(L10n.of(context))); final filter = this.filter; if (filter != null && !displayname.toLowerCase().contains(filter)) { return const SizedBox.shrink(); diff --git a/lib/pages/chat_list/client_chooser_button.dart b/lib/pages/chat_list/client_chooser_button.dart index 1b808db..c4beac9 100644 --- a/lib/pages/chat_list/client_chooser_button.dart +++ b/lib/pages/chat_list/client_chooser_button.dart @@ -6,6 +6,7 @@ import 'package:async/async.dart'; import 'package:fluffychat/config/app_config.dart'; import 'package:fluffychat/l10n/l10n.dart'; +import 'package:fluffychat/pages/idealchat/invite_new_page.dart'; import 'package:fluffychat/widgets/avatar.dart'; import 'package:fluffychat/widgets/matrix.dart'; import 'package:go_router/go_router.dart'; @@ -62,6 +63,17 @@ class ClientChooserButton extends StatelessWidget { ], ), ), + // IdealChat INVNEW_1106: registration invite with the remaining quota. + PopupMenuItem( + onTap: () => IcInviteNew.open(context), + child: Row( + children: [ + const Icon(Icons.person_add_alt_outlined), + const SizedBox(width: 18), + Flexible(child: Text(IcInviteNew.label(context))), + ], + ), + ), PopupMenuItem( value: SettingsAction.archive, child: Row( @@ -161,6 +173,8 @@ class ClientChooserButton extends StatelessWidget { Widget build(BuildContext context) { final matrix = Matrix.of(context); final client = Result(() => matrix.client).asValue?.value; + // INVNEW_1106: keep the remaining invite quota fresh for the menu. + if (client != null && client.isLogged()) IcInviteNew.refresh(client); var clientCount = 0; matrix.accountBundles.forEach((key, value) => clientCount += value.length); diff --git a/lib/pages/idealchat/invite_new_page.dart b/lib/pages/idealchat/invite_new_page.dart new file mode 100644 index 0000000..58bb5b2 --- /dev/null +++ b/lib/pages/idealchat/invite_new_page.dart @@ -0,0 +1,147 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat INVNEW_1106 (主人 11-06): under 「邀请联系人」 (a matrix.to link +// for people who already have an account, no quota) the account menu offers +// 「邀请新的人注册(还能再邀请 N 个)」. N is the same number the invite page +// shows: /ai-join/tree → quotas.human.left (not shown when unknown or the +// account has no limit). It opens /invite-ai.html signed in with the user's +// own token (WebView on Android, a new tab on the web). + +import 'dart:convert'; + +import 'package:fluffychat/pages/idealchat/member_panel_page.dart'; +import 'package:fluffychat/utils/idealchat/ic_api.dart'; +import 'package:fluffychat/utils/idealchat/ic_next.dart'; +import 'package:fluffychat/widgets/matrix.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:matrix/matrix.dart'; +import 'package:universal_html/html.dart' as html; +import 'package:webview_flutter/webview_flutter.dart'; + +abstract class IcInviteNew { + /// Same key the invite page reads its token from (invite-ai.html). + static const tokenKey = 'idealchat2001.inviteToken'; + static int? _left; + static DateTime? _at; + + static String label(BuildContext context) { + final left = _left; + return left == null + ? icT(context, '邀请新的人注册', 'Invite someone new to sign up') + : icT( + context, + '邀请新的人注册(还能再邀请 $left 个)', + 'Invite someone new to sign up ($left left)', + ); + } + + static Future refresh(Client client) async { + final at = _at; + if (at != null && DateTime.now().difference(at).inSeconds < 60) return; + _at = DateTime.now(); + try { + final j = await client.icGet('/ai-join/tree'); + final q = j is Map ? j['quotas'] : null; + final h = q is Map ? q['human'] : null; + final left = h is Map ? h['left'] : null; + _left = h is Map && h['exempt'] != true && left is int ? left : null; + } catch (e) { + Logs().v('[IC] invite quota unavailable', e); + } + } + + static void open(BuildContext context) { + final client = Matrix.of(context).client; + _at = null; // fresh number next time the menu opens + if (icUseBrowserTab) { + final token = client.accessToken; + if (token != null) { + try { + html.window.sessionStorage[tokenKey] = token; + } catch (_) {} + } + icOpenInBrowserTab(client.icUri('/invite-ai.html').toString()); + return; + } + Navigator.of( + context, + ).push(MaterialPageRoute(builder: (_) => const InviteNewPage())); + } +} + +class InviteNewPage extends StatefulWidget { + const InviteNewPage({super.key}); + + @override + State createState() => _InviteNewPageState(); +} + +class _InviteNewPageState extends State { + WebViewController? _controller; + int _progress = 0; + + @override + void initState() { + super.initState(); + final client = Matrix.of(context).client; + final base = client.icBase; + final controller = WebViewController(); + controller + ..setJavaScriptMode(JavaScriptMode.unrestricted) + ..setNavigationDelegate( + NavigationDelegate( + onProgress: (p) => mounted ? setState(() => _progress = p) : null, + onPageFinished: (_) async { + final token = client.accessToken; + if (token == null) return; + // Give the page the app's token once, then reload so it signs in + // by itself. Never loops: only while the key is still missing. + await controller.runJavaScript( + 'try{if(!sessionStorage.getItem(${jsonEncode(IcInviteNew.tokenKey)})){' + 'sessionStorage.setItem(${jsonEncode(IcInviteNew.tokenKey)},${jsonEncode(token)});' + 'location.reload();}}catch(_){}', + ); + }, + onNavigationRequest: (request) { + final uri = Uri.tryParse(request.url); + if (uri != null && + uri.host == base.host && + uri.path.startsWith('/invite-ai')) { + return NavigationDecision.navigate; + } + return NavigationDecision.prevent; + }, + ), + ) + ..loadRequest(client.icUri('/invite-ai.html', {'app': 'android'})); + _controller = controller; + } + + @override + Widget build(BuildContext context) { + final controller = _controller; + return Scaffold( + appBar: AppBar( + leading: const Center(child: BackButton()), + title: Text(icT(context, '邀请新的人注册', 'Invite someone new')), + actions: [ + IconButton( + icon: const Icon(Icons.refresh_outlined), + onPressed: () => _controller?.reload(), + ), + ], + bottom: _progress < 100 + ? PreferredSize( + preferredSize: const Size.fromHeight(2), + child: LinearProgressIndicator(value: _progress / 100), + ) + : null, + ), + body: controller == null + ? const Center(child: CircularProgressIndicator.adaptive()) + : WebViewWidget(controller: controller), + ); + } +} diff --git a/lib/pages/idealchat/my_ai_page.dart b/lib/pages/idealchat/my_ai_page.dart new file mode 100644 index 0000000..853999b --- /dev/null +++ b/lib/pages/idealchat/my_ai_page.dart @@ -0,0 +1,113 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat MYAI_1106: Settings → 「我的 AI」. Opens the /board page where each +// user manages their own AIs (model, today's usage, recent errors, own API +// keys, pause). In the app the page gets the user's own token in the URL +// fragment (#token=…): a fragment never reaches the server, and the page +// removes it from the address right away. The token is never logged. +// On the web the page opens in a new tab and signs in with the same-origin +// chat session instead. + +import 'package:fluffychat/pages/idealchat/member_panel_page.dart' show icT; +import 'package:fluffychat/utils/idealchat/ic_api.dart'; +import 'package:fluffychat/utils/idealchat/ic_next.dart'; +import 'package:fluffychat/widgets/matrix.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:webview_flutter/webview_flutter.dart'; + +class MyAiPage extends StatefulWidget { + const MyAiPage({super.key}); + + @override + State createState() => _MyAiPageState(); +} + +class _MyAiPageState extends State { + bool _tabOpened = false; + WebViewController? _controller; + int _progress = 0; + + @override + void initState() { + super.initState(); + _open(); + } + + void _open() { + if (icUseBrowserTab) return; + final client = Matrix.of(context).client; + final base = client.icBase; + final token = client.accessToken; + final uri = client + .icUri('/board/tasks', {'view': 'myai', 'app': 'android'}) + .replace(fragment: token == null ? null : 'token=$token'); + final controller = WebViewController(); + controller + ..setJavaScriptMode(JavaScriptMode.unrestricted) + ..setNavigationDelegate( + NavigationDelegate( + onProgress: (p) => mounted ? setState(() => _progress = p) : null, + onPageStarted: (_) => _applyTheme(controller), + onPageFinished: (_) => _applyTheme(controller), + onNavigationRequest: (request) { + final u = Uri.tryParse(request.url); + if (u != null && + u.host == base.host && + u.path.startsWith('/board')) { + return NavigationDecision.navigate; + } + return NavigationDecision.prevent; + }, + ), + ) + ..loadRequest(uri); + setState(() => _controller = controller); + } + + Future _applyTheme(WebViewController controller) async { + if (!mounted) return; + final dark = Theme.of(context).brightness == Brightness.dark; + await controller.runJavaScript( + "document.documentElement.setAttribute('data-theme','${dark ? 'dark' : 'light'}');", + ); + } + + @override + Widget build(BuildContext context) { + final title = icT(context, '我的 AI', 'My AI'); + if (icUseBrowserTab) { + final url = Matrix.of( + context, + ).client.icUri('/board/tasks', {'view': 'myai'}).toString(); + if (!_tabOpened) { + _tabOpened = true; + icOpenInBrowserTab(url); + } + return IcOpenedInTab(title: title, url: url); + } + final controller = _controller; + return Scaffold( + appBar: AppBar( + leading: const Center(child: BackButton()), + title: Text(title), + actions: [ + IconButton( + icon: const Icon(Icons.refresh_outlined), + onPressed: () => _controller?.reload(), + ), + ], + bottom: _progress < 100 + ? PreferredSize( + preferredSize: const Size.fromHeight(2), + child: LinearProgressIndicator(value: _progress / 100), + ) + : null, + ), + body: controller == null + ? const Center(child: CircularProgressIndicator.adaptive()) + : WebViewWidget(controller: controller), + ); + } +} diff --git a/lib/pages/idealchat/room_files_page.dart b/lib/pages/idealchat/room_files_page.dart new file mode 100644 index 0000000..71b2a91 --- /dev/null +++ b/lib/pages/idealchat/room_files_page.dart @@ -0,0 +1,205 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat ROOMFILES_1106 (主人 11-06 21:39): room ⋮ → 「群文件」 shows every +// file sent in this room (/app/ic-files.html?room=…: filter by kind, search, +// thumbnails, downloads with the user's own login). The page signs in from +// sessionStorage ic_tok / ic_uid; the app hands them over (WebView on Android, +// a new tab on the web). + +import 'dart:convert'; + +import 'package:fluffychat/pages/idealchat/member_panel_page.dart'; +import 'package:fluffychat/utils/idealchat/ic_api.dart'; +import 'package:fluffychat/utils/idealchat/ic_next.dart'; +import 'package:fluffychat/utils/matrix_sdk_extensions/event_extension.dart'; +import 'package:fluffychat/widgets/matrix.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:matrix/matrix.dart'; +import 'package:universal_html/html.dart' as html; +import 'package:webview_flutter/webview_flutter.dart'; + +void icOpenRoomFiles(BuildContext context, String roomId) { + final client = Matrix.of(context).client; + if (icUseBrowserTab) { + try { + final token = client.accessToken, uid = client.userID; + if (token != null && uid != null) { + html.window.sessionStorage['ic_tok'] = token; + html.window.sessionStorage['ic_uid'] = uid; + } + } catch (_) {} + icOpenInBrowserTab( + client.icUri('/app/ic-files.html', {'room': roomId}).toString(), + ); + return; + } + // ROOMFILES_1106b (主人 21:50「不要全屏窗口」): a panel over the chat — + // a side panel on wide screens, a bottom sheet (85% high) on phones. + final title = client.getRoomById(roomId)?.getLocalizedDisplayname(); + if (MediaQuery.sizeOf(context).width >= 900) { + showGeneralDialog( + context: context, + barrierDismissible: true, + barrierLabel: 'close', + barrierColor: Colors.black12, + transitionDuration: const Duration(milliseconds: 220), + pageBuilder: (context, _, _) => Align( + alignment: Alignment.centerRight, + child: Material( + elevation: 8, + child: SizedBox( + width: 420, + height: double.infinity, + child: RoomFilesPage(roomId: roomId, roomName: title), + ), + ), + ), + transitionBuilder: (context, anim, _, child) => SlideTransition( + position: Tween( + begin: const Offset(1, 0), + end: Offset.zero, + ).animate(CurvedAnimation(parent: anim, curve: Curves.easeOut)), + child: child, + ), + ); + return; + } + showModalBottomSheet( + context: context, + isScrollControlled: true, + useSafeArea: true, + showDragHandle: true, + builder: (context) => SizedBox( + height: MediaQuery.sizeOf(context).height * 0.85, + child: RoomFilesPage(roomId: roomId, roomName: title), + ), + ); +} + +class RoomFilesPage extends StatefulWidget { + final String roomId; + final String? roomName; + const RoomFilesPage({required this.roomId, this.roomName, super.key}); + + @override + State createState() => _RoomFilesPageState(); +} + +class _RoomFilesPageState extends State { + WebViewController? _controller; + int _progress = 0; + + @override + void initState() { + super.initState(); + final client = Matrix.of(context).client; + final base = client.icBase; + final controller = WebViewController(); + controller + ..setJavaScriptMode(JavaScriptMode.unrestricted) + // The page's 「下载」 asks the app to save the file: a WebView can't + // save blob downloads, and the app can also decrypt encrypted files. + ..addJavaScriptChannel( + 'IcFiles', + onMessageReceived: (message) => _saveFile(message.message), + ) + ..setNavigationDelegate( + NavigationDelegate( + onProgress: (p) => mounted ? setState(() => _progress = p) : null, + onPageFinished: (_) async { + final token = client.accessToken, uid = client.userID; + if (token == null || uid == null) return; + // Give the page the app's login once, then reload so it signs in + // by itself. Never loops: only while the key is still missing. + await controller.runJavaScript( + 'try{if(!sessionStorage.getItem("ic_tok")){' + 'sessionStorage.setItem("ic_tok",${jsonEncode(token)});' + 'sessionStorage.setItem("ic_uid",${jsonEncode(uid)});' + 'location.reload();}}catch(_){}', + ); + }, + onNavigationRequest: (request) { + final uri = Uri.tryParse(request.url); + if (uri != null && + uri.host == base.host && + uri.path == '/app/ic-files.html') { + return NavigationDecision.navigate; + } + // blob: downloads and links to the chat stay out of the WebView. + return NavigationDecision.prevent; + }, + ), + ) + ..loadRequest( + client.icUri('/app/ic-files.html', { + 'room': widget.roomId, + 'app': 'android', + 'embed': '1', + }), + ); + _controller = controller; + } + + Future _saveFile(String message) async { + try { + final data = jsonDecode(message); + final eventId = data is Map ? data['event'] : null; + if (eventId is! String) return; + final room = Matrix.of(context).client.getRoomById(widget.roomId); + final event = await room?.getEventById(eventId); + if (event == null || !mounted) return; + await event.saveFile(context); + } catch (e) { + Logs().w('[IC] room file save failed', e); + if (!mounted) return; + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text(e.toString()))); + } + } + + @override + Widget build(BuildContext context) { + final controller = _controller; + final name = widget.roomName; + final title = icT(context, '群文件', 'Room files'); + return Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 4, 4, 4), + child: Row( + children: [ + Expanded( + child: Text( + name == null || name.isEmpty ? title : '$title · $name', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.titleMedium, + ), + ), + IconButton( + icon: const Icon(Icons.refresh_outlined), + onPressed: () => _controller?.reload(), + ), + IconButton( + icon: const Icon(Icons.close), + tooltip: MaterialLocalizations.of(context).closeButtonTooltip, + onPressed: () => Navigator.of(context).pop(), + ), + ], + ), + ), + if (_progress < 100) + LinearProgressIndicator(value: _progress / 100, minHeight: 2), + const Divider(height: 1), + Expanded( + child: controller == null + ? const Center(child: CircularProgressIndicator.adaptive()) + : WebViewWidget(controller: controller), + ), + ], + ); + } +} diff --git a/lib/pages/idealchat/room_skills_page.dart b/lib/pages/idealchat/room_skills_page.dart new file mode 100644 index 0000000..96b08ac --- /dev/null +++ b/lib/pages/idealchat/room_skills_page.dart @@ -0,0 +1,240 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat ROOMSKILLS_1105 (owner 11-05 18:31 「可以」): room ⋮ → "Room skills" +// (本群技能), visible to every member. Read-only view of +// GET /board/api/room_skills?room=… (the user's own Bearer token; the server +// checks membership): skills usable here with their trigger words, the +// skills recently used in this room, and the server's note. No switches. + +import 'package:fluffychat/pages/idealchat/member_panel_page.dart'; +import 'package:fluffychat/utils/idealchat/ic_api.dart'; +import 'package:fluffychat/widgets/matrix.dart'; +import 'package:intl/intl.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:matrix/matrix.dart'; + +class RoomSkillsPage extends StatefulWidget { + final String roomId; + + const RoomSkillsPage({required this.roomId, super.key}); + + @override + State createState() => _RoomSkillsPageState(); +} + +class _RoomSkillsPageState extends State { + Map? _data; + Object? _error; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + setState(() { + _data = null; + _error = null; + }); + try { + final json = await Matrix.of( + context, + ).client.icGet('/board/api/room_skills', query: {'room': widget.roomId}); + if (!mounted) return; + if (json is! Map || + (json['room'] != null && json['room'] != widget.roomId)) { + throw const IcApiException(500, null); + } + setState(() => _data = json); + } catch (e) { + if (mounted) setState(() => _error = e); + } + } + + static DateTime? _time(Object? ts) { + if (ts is num) { + final ms = ts < 1e12 ? (ts * 1000).round() : ts.round(); + return DateTime.fromMillisecondsSinceEpoch(ms); + } + if (ts is String) return DateTime.tryParse(ts)?.toLocal(); + return null; + } + + String _who(Room? room, Object? ai) { + final id = ai?.toString() ?? ''; + if (room != null && id.startsWith('@')) { + return room.unsafeGetUserFromMemoryOrFallback(id).calcDisplayname(); + } + return id; + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final room = Matrix.of(context).client.getRoomById(widget.roomId); + final data = _data; + Widget body; + if (_error != null) { + body = Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + _error is IcApiException && + (_error as IcApiException).message != null + ? (_error as IcApiException).message! + : icT(context, '读不到本群技能。', 'Could not load room skills.'), + textAlign: TextAlign.center, + ), + const SizedBox(height: 12), + OutlinedButton( + onPressed: _load, + child: Text(icT(context, '再试一次', 'Try again')), + ), + ], + ), + ), + ); + } else if (data == null) { + body = const Center(child: CircularProgressIndicator.adaptive()); + } else { + final skills = [ + for (final s in (data['skills'] as List? ?? const [])) + if (s is Map) s, + ]; + final recent = [ + for (final r in (data['recent'] as List? ?? const [])) + if (r is Map) r, + ]; + final note = data['note']?.toString() ?? ''; + final timeFormat = DateFormat('MM-dd HH:mm'); + Widget heading(String text) => Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 4), + child: Text( + text, + style: theme.textTheme.titleSmall?.copyWith( + color: theme.colorScheme.primary, + fontWeight: FontWeight.bold, + ), + ), + ); + body = RefreshIndicator( + onRefresh: _load, + child: ListView( + children: [ + heading(icT(context, '本群能用的技能', 'Skills in this group')), + if (skills.isEmpty) + ListTile( + title: Text(icT(context, '本群还没有可用的技能', 'No skills yet')), + ), + for (final s in skills) + ListTile( + title: Row( + children: [ + Flexible( + child: Text( + s['name']?.toString() ?? '', + style: const TextStyle(fontWeight: FontWeight.bold), + ), + ), + if (s['on'] == false) ...[ + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 2, + ), + decoration: BoxDecoration( + color: theme.colorScheme.errorContainer, + borderRadius: BorderRadius.circular(12), + ), + child: Text( + icT(context, '本群已关', 'Off here'), + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.onErrorContainer, + ), + ), + ), + ], + ], + ), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if ((s['desc']?.toString() ?? '').isNotEmpty) + Text(s['desc'].toString()), + if ((s['triggers'] as List? ?? const []).isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + icT( + context, + '说这些话会自动用上:', + 'Used automatically when you say: ', + ) + + (s['triggers'] as List) + .map((t) => t.toString()) + .join('、'), + style: theme.textTheme.bodySmall, + ), + ), + ], + ), + ), + const Divider(), + heading(icT(context, '本群最近用过', 'Recently used here')), + if (recent.isEmpty) + ListTile( + title: Text( + icT(context, '本群还没用过', 'Not used in this group yet'), + ), + ), + for (final r in recent) + ListTile( + dense: true, + leading: Text(() { + final t = _time(r['ts']); + return t == null ? '' : timeFormat.format(t); + }(), style: theme.textTheme.bodySmall), + title: Text(_who(room, r['ai'])), + subtitle: Text( + r['skills'] is List + ? (r['skills'] as List).map((e) => e.toString()).join('、') + : r['skills']?.toString() ?? '', + ), + ), + if (note.isNotEmpty) + Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 24), + child: Text( + note, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ), + ], + ), + ); + } + return Scaffold( + appBar: AppBar( + leading: const Center(child: BackButton()), + title: Text(icT(context, '本群技能', 'Room skills')), + actions: [ + IconButton( + icon: const Icon(Icons.refresh_outlined), + onPressed: _load, + ), + ], + ), + body: body, + ); + } +} diff --git a/lib/pages/idealchat/skill_library_page.dart b/lib/pages/idealchat/skill_library_page.dart new file mode 100644 index 0000000..f2a49b6 --- /dev/null +++ b/lib/pages/idealchat/skill_library_page.dart @@ -0,0 +1,163 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat SKILLLIB_1105: Settings → "Skills" (技能库), only for the owner and +// admins (owner 2026-11-05: 「这个放到idealchat的设置页面里」). Opens the +// read-only skill library of the admin console (/admin/#skills) in-app. Who is +// an admin is decided by the server (/admin/api/sso); the session cookie only +// lives inside this WebView. + +import 'package:fluffychat/pages/idealchat/member_panel_page.dart'; +import 'package:fluffychat/utils/idealchat/ic_api.dart'; +import 'package:fluffychat/utils/idealchat/ic_next.dart'; +import 'package:fluffychat/widgets/matrix.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:matrix/matrix.dart'; +import 'package:webview_flutter/webview_flutter.dart'; + +abstract class IcSkillLibrary { + static const owner = '@zhangmacmini:ideal2001.com'; + static final visible = ValueNotifier(false); + static String? _checkedFor; + + /// Shows the settings entry for the owner at once; for anyone else asks the + /// admin console once per app run (it rate-limits logins). + static void check(Client client) { + final uid = client.userID; + if (uid == null || _checkedFor == uid) return; + _checkedFor = uid; + if (uid == owner) { + visible.value = true; + return; + } + visible.value = false; + client + .icAdminSession() + .then((sid) { + if (client.userID == uid) visible.value = sid != null; + }) + .catchError((e) { + Logs().v('[IC] admin check failed', e); + _checkedFor = null; + }); + } +} + +class SkillLibraryPage extends StatefulWidget { + const SkillLibraryPage({super.key}); + + @override + State createState() => _SkillLibraryPageState(); +} + +class _SkillLibraryPageState extends State { + bool _icTabOpened = false; + WebViewController? _controller; + Object? _error; + bool _notAdmin = false; + int _progress = 0; + + @override + void initState() { + super.initState(); + _open(); + } + + Future _open() async { + if (icUseBrowserTab) return; + setState(() { + _controller = null; + _error = null; + _notAdmin = false; + }); + try { + final client = Matrix.of(context).client; + final sid = await client.icAdminSession(); + if (!mounted) return; + if (sid == null) { + setState(() => _notAdmin = true); + return; + } + final base = client.icBase; + await WebViewCookieManager().setCookie( + WebViewCookie( + name: 'ic_admin_sid', + value: sid, + domain: base.host, + path: '/admin', + ), + ); + final controller = WebViewController() + ..setJavaScriptMode(JavaScriptMode.unrestricted) + ..setNavigationDelegate( + NavigationDelegate( + onProgress: (p) => mounted ? setState(() => _progress = p) : null, + onNavigationRequest: (request) { + final uri = Uri.tryParse(request.url); + return uri != null && + uri.host == base.host && + uri.path.startsWith('/admin') + ? NavigationDecision.navigate + : NavigationDecision.prevent; + }, + ), + ) + ..loadRequest(base.replace(path: '/admin/', fragment: 'skills')); + if (mounted) setState(() => _controller = controller); + } catch (e, s) { + Logs().w('Unable to open skill library', e, s); + if (mounted) setState(() => _error = e); + } + } + + @override + Widget build(BuildContext context) { + // WEBNEXT_1105: no in-app WebView on the web — open the page in a tab. + if (icUseBrowserTab) { + final client = Matrix.of(context).client; + final url = client.icBase + .replace(path: '/admin/', fragment: 'skills') + .toString(); + if (!_icTabOpened) { + _icTabOpened = true; + icOpenInBrowserTab(url); + } + return IcOpenedInTab(title: icT(context, '技能库', 'Skills'), url: url); + } + final controller = _controller; + return Scaffold( + appBar: AppBar( + leading: const Center(child: BackButton()), + title: Text(icT(context, '技能库', 'Skills')), + actions: [ + IconButton( + icon: const Icon(Icons.refresh_outlined), + onPressed: _open, + ), + ], + bottom: controller != null && _progress < 100 + ? PreferredSize( + preferredSize: const Size.fromHeight(2), + child: LinearProgressIndicator(value: _progress / 100), + ) + : null, + ), + body: _notAdmin + ? Center( + child: Text( + icT( + context, + '只有主人和管理员可以看技能库。', + 'Only the owner and admins can view skills.', + ), + ), + ) + : _error != null + ? Center(child: Text(_error.toString())) + : controller == null + ? const Center(child: CircularProgressIndicator.adaptive()) + : WebViewWidget(controller: controller), + ); + } +} diff --git a/lib/pages/idealchat/suggestion_board_page.dart b/lib/pages/idealchat/suggestion_board_page.dart index 73f2b55..1a9ea6c 100644 --- a/lib/pages/idealchat/suggestion_board_page.dart +++ b/lib/pages/idealchat/suggestion_board_page.dart @@ -12,6 +12,7 @@ import 'dart:convert'; import 'package:fluffychat/l10n/l10n.dart'; import 'package:fluffychat/utils/idealchat/ic_api.dart'; +import 'package:fluffychat/utils/idealchat/ic_next.dart'; import 'package:fluffychat/widgets/matrix.dart'; import 'package:material_ui/material_ui.dart'; import 'package:webview_flutter/webview_flutter.dart'; @@ -24,6 +25,8 @@ class SuggestionBoardPage extends StatefulWidget { } class _SuggestionBoardPageState extends State { + bool _icTabOpened = false; + /// Same key the board page reads first (board.html, TK). static const _tokenKey = 'idealchat2001.inviteToken'; @@ -37,6 +40,7 @@ class _SuggestionBoardPageState extends State { } void _open() { + if (icUseBrowserTab) return; final client = Matrix.of(context).client; final base = client.icBase; final controller = WebViewController(); @@ -84,6 +88,16 @@ class _SuggestionBoardPageState extends State { @override Widget build(BuildContext context) { + // WEBNEXT_1105: no in-app WebView on the web — open the page in a tab. + if (icUseBrowserTab) { + final client = Matrix.of(context).client; + final url = client.icUri('/board').toString(); + if (!_icTabOpened) { + _icTabOpened = true; + icOpenInBrowserTab(url); + } + return IcOpenedInTab(title: L10n.of(context).icSuggestionBoard, url: url); + } final controller = _controller; return Scaffold( appBar: AppBar( diff --git a/lib/pages/idealchat/task_board_page.dart b/lib/pages/idealchat/task_board_page.dart index 4c7b036..e38a56b 100644 --- a/lib/pages/idealchat/task_board_page.dart +++ b/lib/pages/idealchat/task_board_page.dart @@ -12,6 +12,7 @@ import 'dart:convert'; import 'package:fluffychat/l10n/l10n.dart'; import 'package:fluffychat/utils/idealchat/ic_api.dart'; +import 'package:fluffychat/utils/idealchat/ic_next.dart'; import 'package:fluffychat/widgets/matrix.dart'; import 'package:go_router/go_router.dart'; import 'package:material_ui/material_ui.dart'; @@ -28,6 +29,7 @@ class TaskBoardPage extends StatefulWidget { } class _TaskBoardPageState extends State { + bool _icTabOpened = false; WebViewController? _controller; Object? _error; int _progress = 0; @@ -46,6 +48,7 @@ class _TaskBoardPageState extends State { } Future _open() async { + if (icUseBrowserTab) return; setState(() { _controller = null; _error = null; @@ -138,6 +141,18 @@ class _TaskBoardPageState extends State { @override Widget build(BuildContext context) { + // WEBNEXT_1105: no in-app WebView on the web — open the page in a tab. + if (icUseBrowserTab) { + final client = Matrix.of(context).client; + final url = client.icUri('/board/tasks', { + 'room': widget.roomId, + }).toString(); + if (!_icTabOpened) { + _icTabOpened = true; + icOpenInBrowserTab(url); + } + return IcOpenedInTab(title: L10n.of(context).icTaskList, url: url); + } final l10n = L10n.of(context); final controller = _controller; return Scaffold( diff --git a/lib/pages/intro/ic_invite_quota_notice.dart b/lib/pages/intro/ic_invite_quota_notice.dart new file mode 100644 index 0000000..e0d705b --- /dev/null +++ b/lib/pages/intro/ic_invite_quota_notice.dart @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat LOGINQUOTA_1106 (主人 11-06 20:24「在登录页面醒目地显示邀请限额」): +// the invite quota rule above the sign-in button. Same wording as the invite +// page (invite-ai.html QUOTABOX_1106). + +import 'package:material_ui/material_ui.dart'; + +class IcInviteQuotaNotice extends StatelessWidget { + const IcInviteQuotaNotice({super.key}); + + static const _amber = Color(0xFFFFC107); + + @override + Widget build(BuildContext context) { + final zh = Localizations.localeOf(context).languageCode == 'zh'; + return Container( + margin: const EdgeInsets.only(bottom: 12), + padding: const EdgeInsets.fromLTRB(12, 10, 12, 10), + decoration: BoxDecoration( + color: _amber.withAlpha(36), + border: const Border(left: BorderSide(color: _amber, width: 4)), + ), + child: Text( + zh + ? '📌 邀请名额:每个账号每一类最多邀请 5 位(家人朋友、我的 AI、独立 AI 分开算)。已注册的和还没用掉的邀请都占名额,没用掉的邀请过期后名额会退回。' + : '📌 Invitations: each account can invite at most 5 per kind (family & friends, my AIs, independent AIs are counted separately). Registered and still-unused invitations both count; an unused invitation gives its place back when it expires.', + style: const TextStyle(fontSize: 16), + ), + ); + } +} diff --git a/lib/pages/intro/intro_page.dart b/lib/pages/intro/intro_page.dart index 29774d1..0806e01 100644 --- a/lib/pages/intro/intro_page.dart +++ b/lib/pages/intro/intro_page.dart @@ -6,6 +6,7 @@ import 'package:fluffychat/config/setting_keys.dart'; import 'package:fluffychat/l10n/l10n.dart'; import 'package:fluffychat/pages/intro/flows/restore_backup_flow.dart'; +import 'package:fluffychat/pages/intro/ic_invite_quota_notice.dart'; import 'package:fluffychat/utils/platform_infos.dart'; import 'package:fluffychat/widgets/layouts/login_scaffold.dart'; import 'package:fluffychat/widgets/matrix.dart'; @@ -159,6 +160,7 @@ class IntroPage extends StatelessWidget { L10n.of(context).createNewAccount, ), ), + const IcInviteQuotaNotice(), SizedBox(height: 16), ElevatedButton( onPressed: login, diff --git a/lib/pages/intro/intro_page_presenter.dart b/lib/pages/intro/intro_page_presenter.dart index 91b0356..bb77898 100644 --- a/lib/pages/intro/intro_page_presenter.dart +++ b/lib/pages/intro/intro_page_presenter.dart @@ -93,7 +93,7 @@ class _IntroPagePresenterState extends State { await client.checkHomeserver(homeserverUrl); await client.oidcLogin(session: session, code: code, state: state); if (!mounted) return; - context.go('/backup'); + context.go('/rooms'); // NOBACKUP_1107: no automatic chat-backup page } catch (e, s) { Logs().w('Unable to login via OIDC', e, s); if (mounted) { diff --git a/lib/pages/invitation_selection/invitation_selection.dart b/lib/pages/invitation_selection/invitation_selection.dart index 58ae39d..f5257b9 100644 --- a/lib/pages/invitation_selection/invitation_selection.dart +++ b/lib/pages/invitation_selection/invitation_selection.dart @@ -34,11 +34,16 @@ class InvitationSelectionController extends State { Future> getContacts(BuildContext context) async { final client = Matrix.of(context).client; - final room = client.getRoomById(roomId!)!; - - final participants = (room.summary.mJoinedMemberCount ?? 0) > 100 - ? room.getParticipants() - : await room.requestParticipants(); + final room = client.getRoomById(roomId!); + if (room == null) return []; + + // IdealChat INVITEEMPTY_1106 (主人 11-06「不输入的时候一直转圈」): this + // used to await the full member list from the server on every rebuild + // (the page rebuilds on each room state update, often in AI groups), so + // the list never appeared. Use the members known locally and load the + // full list once in the background; the list refreshes when it arrives. + final participants = room.getParticipants(); + _icLoadMembersOnce(room); participants.removeWhere( (u) => ![Membership.join, Membership.invite].contains(u.membership), ); @@ -69,6 +74,21 @@ class InvitationSelectionController extends State { return contacts; } + Future>? _contactsFuture; + bool _icMembersRequested = false; + + /// Cached so rebuilds don't restart it (INVITEEMPTY_1106). + Future> contactsFuture(BuildContext context) => + _contactsFuture ??= getContacts(context); + + void _icLoadMembersOnce(Room room) { + if (_icMembersRequested) return; + _icMembersRequested = true; + room.requestParticipants().then((_) { + if (mounted) setState(() => _contactsFuture = null); + }, onError: (e) => Logs().v('[IC] members unavailable', e)); + } + Future inviteAction( BuildContext context, String id, diff --git a/lib/pages/invitation_selection/invitation_selection_view.dart b/lib/pages/invitation_selection/invitation_selection_view.dart index 7da0651..fd50315 100644 --- a/lib/pages/invitation_selection/invitation_selection_view.dart +++ b/lib/pages/invitation_selection/invitation_selection_view.dart @@ -112,8 +112,20 @@ class InvitationSelectionView extends StatelessWidget { ), ) : FutureBuilder>( - future: controller.getContacts(context), + future: controller.contactsFuture(context), builder: (BuildContext context, snapshot) { + // INVITEEMPTY_1106: never spin forever; with no + // contacts (or an error) say how to search. + if (snapshot.hasError || + (snapshot.hasData && snapshot.data!.isEmpty)) { + return Padding( + padding: const EdgeInsets.all(24), + child: Text( + L10n.of(context).searchForUsers, + textAlign: TextAlign.center, + ), + ); + } if (!snapshot.hasData) { return const Center( child: CircularProgressIndicator.adaptive( diff --git a/lib/pages/login/login.dart b/lib/pages/login/login.dart index 88575f3..c9a7b06 100644 --- a/lib/pages/login/login.dart +++ b/lib/pages/login/login.dart @@ -88,7 +88,7 @@ class LoginController extends State { initialDeviceDisplayName: PlatformInfos.appDisplayName, ); if (mounted) { - context.go('/backup'); + context.go('/rooms'); // NOBACKUP_1107: no automatic chat-backup page } } on MatrixException catch (exception) { setState(() => passwordError = exception.errorMessage); diff --git a/lib/pages/settings/settings.dart b/lib/pages/settings/settings.dart index 62af6b9..23375c4 100644 --- a/lib/pages/settings/settings.dart +++ b/lib/pages/settings/settings.dart @@ -206,7 +206,7 @@ class SettingsController extends State { await context.push('/backup?reset=true'); return; } - await context.push('/backup'); + await context.push('/backup?from=settings'); checkBootstrap(); } diff --git a/lib/pages/settings/settings_view.dart b/lib/pages/settings/settings_view.dart index bd62300..7ea0739 100644 --- a/lib/pages/settings/settings_view.dart +++ b/lib/pages/settings/settings_view.dart @@ -8,10 +8,13 @@ import 'package:fluffychat/config/setting_keys.dart'; import 'package:fluffychat/l10n/l10n.dart'; import 'package:fluffychat/pages/idealchat/member_invite.dart'; import 'package:fluffychat/pages/idealchat/member_panel_page.dart'; +import 'package:fluffychat/pages/idealchat/my_ai_page.dart'; +import 'package:fluffychat/pages/idealchat/skill_library_page.dart'; import 'package:fluffychat/utils/fluffy_share.dart'; import 'package:fluffychat/utils/platform_infos.dart'; import 'package:fluffychat/widgets/avatar.dart'; import 'package:fluffychat/widgets/matrix.dart'; +import 'package:fluffychat/widgets/settings_switch_list_tile.dart'; import 'package:go_router/go_router.dart'; import 'package:material_ui/material_ui.dart'; import 'package:matrix/matrix.dart' hide Result; @@ -168,6 +171,12 @@ class SettingsView extends StatelessWidget { ? theme.colorScheme.surfaceContainerHigh : null, ), + // FORMATSW_1105: the formatting switch where people find it. + SettingsSwitchListTile.adaptive( + title: L10n.of(context).formattedMessages, + subtitle: L10n.of(context).formattedMessagesDescription, + setting: AppSettings.renderHtml, + ), ListTile( leading: const Icon(Icons.forum_outlined), title: Text(L10n.of(context).chat), @@ -176,6 +185,34 @@ class SettingsView extends StatelessWidget { ? theme.colorScheme.surfaceContainerHigh : null, ), + // MYAI_1106: 「我的 AI」 — everyone manages their own AIs. + ListTile( + leading: const Icon(Icons.smart_toy_outlined), + title: Text(icT(context, '我的 AI', 'My AI')), + onTap: () => Navigator.of( + context, + ).push(MaterialPageRoute(builder: (_) => const MyAiPage())), + ), + // SKILLLIB_1105: 「技能库」, owner and admins only (server decides). + Builder( + builder: (context) { + IcSkillLibrary.check(Matrix.of(context).client); + return ValueListenableBuilder( + valueListenable: IcSkillLibrary.visible, + builder: (context, show, _) => !show + ? const SizedBox.shrink() + : ListTile( + leading: const Icon(Icons.auto_stories_outlined), + title: Text(icT(context, '技能库', 'Skills')), + onTap: () => Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => const SkillLibraryPage(), + ), + ), + ), + ); + }, + ), // IdealChat (web SETTINGS_REC_1750): 「推荐」 opt-in switches. ListTile( leading: const Icon(Icons.recommend_outlined), diff --git a/lib/pages/settings_chat/settings_chat_view.dart b/lib/pages/settings_chat/settings_chat_view.dart index b3439af..db4a08a 100644 --- a/lib/pages/settings_chat/settings_chat_view.dart +++ b/lib/pages/settings_chat/settings_chat_view.dart @@ -7,6 +7,7 @@ import 'package:emoji_picker_flutter/emoji_picker_flutter.dart'; import 'package:fluffychat/config/setting_keys.dart'; import 'package:fluffychat/config/themes.dart'; import 'package:fluffychat/l10n/l10n.dart'; +import 'package:fluffychat/pages/idealchat/member_panel_page.dart'; import 'package:fluffychat/utils/adaptive_bottom_sheet.dart'; import 'package:fluffychat/utils/platform_infos.dart'; import 'package:fluffychat/widgets/layouts/max_width_body.dart'; @@ -40,6 +41,50 @@ class SettingsChatView extends StatelessWidget { subtitle: L10n.of(context).formattedMessagesDescription, setting: AppSettings.renderHtml, ), + // ICEMOTE_1105: the small robot icons AIs send. + SettingsSwitchListTile.adaptive( + title: icT(context, '显示表情图标', 'Show emoji icons'), + subtitle: icT( + context, + 'AI 消息里的小机器人表情;关掉显示文字,例如(高兴)。', + 'Small robot icons in AI messages; off shows text, e.g. (happy).', + ), + setting: AppSettings.icShowEmotes, + ), + // SHOWMORE_1105: how many lines a message shows before 「显示更多」. + StatefulBuilder( + builder: (context, setState) { + final v = AppSettings.messagePreviewMaxLines.value; + String label(int n) => n <= 0 + ? icT(context, '不限', 'No limit') + : icT(context, '$n 行', '$n lines'); + return ListTile( + title: Text( + icT(context, '每条消息先显示几行', 'Lines shown per message'), + ), + subtitle: Text( + icT( + context, + '超出部分点「显示更多」看全文。现在:${label(v)}', + 'Tap "Show more" for the rest. Now: ${label(v)}', + ), + ), + trailing: DropdownButton( + value: const [3, 5, 10, 0].contains(v) ? v : null, + hint: Text(label(v)), + items: [ + for (final n in const [3, 5, 10, 0]) + DropdownMenuItem(value: n, child: Text(label(n))), + ], + onChanged: (n) async { + if (n == null) return; + await AppSettings.messagePreviewMaxLines.setItem(n); + setState(() {}); + }, + ), + ); + }, + ), SettingsSwitchListTile.adaptive( title: L10n.of(context).hideRedactedMessages, subtitle: L10n.of(context).hideRedactedMessagesBody, diff --git a/lib/pages/sign_in/view_model/sign_in_view_model.dart b/lib/pages/sign_in/view_model/sign_in_view_model.dart index 31c89bb..7bdd4be 100644 --- a/lib/pages/sign_in/view_model/sign_in_view_model.dart +++ b/lib/pages/sign_in/view_model/sign_in_view_model.dart @@ -3,10 +3,8 @@ // // SPDX-License-Identifier: AGPL-3.0-or-later -import 'dart:convert'; import 'package:collection/collection.dart'; -import 'package:fluffychat/config/app_config.dart'; import 'package:fluffychat/config/setting_keys.dart'; import 'package:fluffychat/pages/sign_in/view_model/model/public_homeserver_data.dart'; import 'package:fluffychat/pages/sign_in/view_model/sign_in_state.dart'; @@ -61,13 +59,12 @@ class SignInViewModel extends ValueNotifier { name: AppSettings.defaultHomeserver.value, ); try { - final client = await matrixService.getLoginClient(); - final response = await client.httpClient.get(AppConfig.homeserverList); - final json = jsonDecode(response.body) as Map; - final homeserverJsonList = json['public_servers'] as List; + // IdealChat WEBNEXT_1105: only ideal2001.com; no server list fetched + // from the FluffyChat repository on GitHub. + const homeserverJsonList = >[]; final publicHomeservers = homeserverJsonList - .map((json) => PublicHomeserverData.fromJson(json)) + .map(PublicHomeserverData.fromJson) .toList(); if (signUp) { diff --git a/lib/utils/client_manager.dart b/lib/utils/client_manager.dart index aa7f205..27bf6e8 100644 --- a/lib/utils/client_manager.dart +++ b/lib/utils/client_manager.dart @@ -9,6 +9,8 @@ import 'package:fluffychat/config/setting_keys.dart'; import 'package:fluffychat/l10n/l10n.dart'; import 'package:fluffychat/utils/custom_http_client.dart'; import 'package:fluffychat/utils/custom_image_resizer.dart'; +import 'package:fluffychat/utils/idealchat/ic_next.dart'; +import 'package:fluffychat/utils/idealchat/ic_web_notify.dart'; import 'package:fluffychat/utils/init_with_restore.dart'; import 'package:fluffychat/utils/matrix_live_kit_calls/matrix_live_kit_call_member.dart'; import 'package:fluffychat/utils/notification_background_handler.dart'; @@ -19,7 +21,6 @@ import 'package:flutter_vodozemac/flutter_vodozemac.dart' as vod; import 'package:matrix/encryption/utils/key_verification.dart'; import 'package:matrix/matrix.dart'; import 'package:shared_preferences/shared_preferences.dart'; -import 'package:universal_html/html.dart' as html; import 'matrix_sdk_extensions/flutter_matrix_dart_sdk_database/builder.dart'; @@ -39,7 +40,12 @@ abstract class ClientManager { await store.remove(clientNamespace); } if (clientNames.isEmpty) { - clientNames.add(PlatformInfos.appDisplayName); + // WEBNEXT_1105: own client (and database) name for the test web build. + clientNames.add( + icNextBuild + ? 'next-${PlatformInfos.appDisplayName}' + : PlatformInfos.appDisplayName, + ); await store.setStringList(clientNamespace, clientNames.toList()); } final clients = await Future.wait( @@ -60,6 +66,7 @@ abstract class ClientManager { ); }, ) + .then((_) => _icMigrateSyncFilter(client, store)) .catchError( (e, s) => Logs().e('Unable to initialize client', e, s), ), @@ -125,6 +132,35 @@ abstract class ClientManager { }; } + static final Filter icSyncFilter = Filter( + room: RoomFilter( + state: StateFilter(lazyLoadMembers: true), + timeline: StateFilter(limit: 50), + ), + ); + + /// SYNCLIMIT_1106: the SDK defines its sync filter only once and keeps the + /// id, so sessions from before the limit keep the old filter. Define the + /// new one once per account; it is used from the next app start. + static Future _icMigrateSyncFilter( + Client client, + SharedPreferences store, + ) async { + final userId = client.userID; + if (userId == null || !client.isLogged()) return; + final key = 'ic.syncfilter.tl50.$userId'; + final current = client.syncFilterId; + if (current != null && store.getString(key) == current) return; + try { + final id = await client.defineFilter(userId, icSyncFilter); + await client.database.storeSyncFilterId(id); + await store.setString(key, id); + Logs().i('[IC] sync filter updated (timeline limit 50)'); + } catch (e) { + Logs().w('[IC] sync filter update failed', e); + } + } + static Future createClient( String clientName, SharedPreferences store, @@ -136,6 +172,10 @@ abstract class ClientManager { return Client( clientName, httpClient: CustomHttpClient.createHTTPClient(), + // IdealChat SYNCLIMIT_1106: up to 50 timeline events per room in each + // sync. Without a limit the server sends ~10, so a busy room opened + // with only its last 10 messages ("只显示最近几条"). + syncFilter: icSyncFilter, verificationMethods: { KeyVerificationMethod.numbers, if (kIsWeb || PlatformInfos.isMobile || PlatformInfos.isLinux) @@ -182,7 +222,7 @@ abstract class ClientManager { static Future sendInitNotification(String title, String body) async { if (kIsWeb) { - html.Notification(title, body: body); + icWebNotify(title, body: body); return; } diff --git a/lib/utils/error_reporter.dart b/lib/utils/error_reporter.dart index 630630b..74c7cca 100644 --- a/lib/utils/error_reporter.dart +++ b/lib/utils/error_reporter.dart @@ -3,21 +3,14 @@ // // SPDX-License-Identifier: AGPL-3.0-or-later -import 'dart:convert'; -import 'package:fluffychat/config/app_config.dart'; import 'package:fluffychat/config/setting_keys.dart'; import 'package:fluffychat/l10n/l10n.dart'; -import 'package:fluffychat/utils/platform_infos.dart'; import 'package:fluffychat/widgets/adaptive_dialogs/adaptive_dialog_action.dart'; import 'package:fluffychat/widgets/fluffy_chat_app.dart'; -import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; -import 'package:http/http.dart' as http; import 'package:material_ui/material_ui.dart'; import 'package:matrix/matrix.dart'; -import 'package:universal_html/universal_html.dart' as html; -import 'package:url_launcher/url_launcher.dart'; class ErrorReporter { final BuildContext? context; @@ -92,73 +85,10 @@ class ErrorReporter { onPressed: () => Clipboard.setData(ClipboardData(text: text)), child: Text(L10n.of(context).copy), ), - AdaptiveDialogAction( - onPressed: () async { - final existingIssueUrl = stackTrace == null - ? null - : await _searchIssue( - (error.toString() + stackTrace.toString()).hashCode - .toString(), - ); - if (existingIssueUrl != null) { - launchUrl(existingIssueUrl); - return; - } - launchUrl( - AppConfig.newIssueUrl.resolveUri( - Uri( - queryParameters: { - 'template': 'bug_report.yml', - 'title': - '[Error ${stackTrace.hashCode}] ${message ?? error}', - 'bug-description': error.toString(), - 'stacktrace': stackTrace?.toString(), - 'app-version': await PlatformInfos.getVersion(), - 'platform-info': kIsWeb - ? html.window.navigator.userAgent - : switch (defaultTargetPlatform) { - TargetPlatform.android => 'Android', - TargetPlatform.fuchsia => 'Other', - TargetPlatform.iOS => 'iOS', - TargetPlatform.linux => 'Linux', - TargetPlatform.macOS => 'macOS (Self-compiled)', - TargetPlatform.windows => - 'Windows (Self-compiled)', - }, - }, - ), - ), - mode: LaunchMode.externalApplication, - ); - }, - child: Text(L10n.of(context).report), - ), + // IdealChat WEBNEXT_1105: no "Report" button (it opened the + // FluffyChat GitHub issue tracker). ], ), ); } - - Future _searchIssue(String hash) async { - final result = await http.get( - Uri( - scheme: 'https', - host: 'api.github.com', - path: '/search/issues', - query: 'q=repo:krille-chan/fluffychat+is:issue+$hash', - ), - ); - try { - final jsonResult = - jsonDecode(utf8.decode(result.bodyBytes)) as Map; - final uriString = jsonResult - .tryGetList>('items') - ?.firstOrNull - ?.tryGet('html_url'); - if (uriString == null) return null; - return Uri.tryParse(uriString); - } catch (e, s) { - Logs().w('Unable to search for existing issues on GitHub', e, s); - return null; - } - } } diff --git a/lib/utils/idealchat/ai_directory.dart b/lib/utils/idealchat/ai_directory.dart index 1ad5de0..415430d 100644 --- a/lib/utils/idealchat/ai_directory.dart +++ b/lib/utils/idealchat/ai_directory.dart @@ -10,9 +10,12 @@ // /api/ai_panel/models (Bearer). Missing data falls back to the web's // built-in rules; nothing is written. +import 'dart:convert'; + import 'package:fluffychat/utils/idealchat/ic_api.dart'; import 'package:material_ui/material_ui.dart'; import 'package:matrix/matrix.dart'; +import 'package:shared_preferences/shared_preferences.dart'; enum IcRoomKind { friends, ai, normal } @@ -237,11 +240,24 @@ class IcAiDirectory { return; } _inflight ??= () async { + // IdealChat WEBNEXT_1105 (web ic33 lkg-cache): keep the last copy that + // loaded, and use it when the server can't be reached (cold start + // offline), instead of falling back to the built-in rules. + final prefs = await SharedPreferences.getInstance(); Future load(String name, String path) async { + final key = 'ic_lkg_$name'; try { - applyJson(name, await client.icGet(path)); + final json = await client.icGet(path); + applyJson(name, json); + if (json != null) await prefs.setString(key, jsonEncode(json)); } catch (e) { Logs().v('[IC] $path unavailable', e); + if (_loadedAt != null) return; // keep what this run already has + final saved = prefs.getString(key); + if (saved == null) return; + try { + applyJson(name, jsonDecode(saved)); + } catch (_) {} } } diff --git a/lib/utils/idealchat/ai_discussion.dart b/lib/utils/idealchat/ai_discussion.dart new file mode 100644 index 0000000..c6db7c6 --- /dev/null +++ b/lib/utils/idealchat/ai_discussion.dart @@ -0,0 +1,45 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat AIFOLD_1105: AI discussion messages never pop a notification +// (owner 19:50 dropped the timeline folding — all messages simply show 3 lines +// with 「显示更多」; the no-notification rule stays for now). 【讨论汇总】 messages +// stay normal. The server keeps them as ordinary messages (AIs rely on the +// mentions in them), so this is decided in the client. + +import 'package:fluffychat/utils/idealchat/ai_directory.dart'; +import 'package:matrix/matrix.dart'; + +const icAiDiscussionPrefix = '【AI讨论】'; + +/// The message text without a reply fallback ("> <@user> …" lines). +String _bodyWithoutReplyFallback(String body) { + if (!body.startsWith('>')) return body; + final lines = body.split('\n'); + var i = 0; + while (i < lines.length && lines[i].startsWith('>')) { + i++; + } + return lines.skip(i).join('\n'); +} + +bool icIsAiDiscussion(Event event) { + if (event.type != EventTypes.Message) return false; + final body = event.content.tryGet('body') ?? ''; + // Bridges may put a source tag first (e.g. 「Codex · CLI · 服务器」), so the + // marker counts anywhere in the first 40 characters. 【讨论汇总】 and + // 【请您选】 messages are never folded. + final text = _bodyWithoutReplyFallback(body).trimLeft(); + final head = text.length > 40 ? text.substring(0, 40) : text; + if (head.contains('【讨论汇总') || head.contains('【请您选】')) return false; + if (head.contains(icAiDiscussionPrefix)) return true; + // (b) owner 11-05 19:34: an AI talking only to other AIs — sender is an AI + // and every mentioned user is an AI (no person, no @room). + final dir = IcAiDirectory.instance; + if (!dir.isAi(event.senderId)) return false; + final mentions = event.content.tryGetMap('m.mentions'); + if (mentions == null || mentions['room'] == true) return false; + final ids = mentions.tryGetList('user_ids') ?? const []; + return ids.isNotEmpty && ids.every(dir.isAi); +} diff --git a/lib/utils/idealchat/ic_api.dart b/lib/utils/idealchat/ic_api.dart index 17e2a97..25ac7f7 100644 --- a/lib/utils/idealchat/ic_api.dart +++ b/lib/utils/idealchat/ic_api.dart @@ -93,4 +93,31 @@ extension IcApi on Client { if (match == null) throw const IcApiException(500, 'no session'); return match.group(1)!; } + + /// SKILLLIB_1105: admin console login without password, the same way the + /// /admin page signs in (one-time Matrix OpenID token → /admin/api/sso). + /// Returns the `ic_admin_sid` cookie value, or null when this account is not + /// an admin (403). The server's admin list decides; the app only asks. + Future icAdminSession() async { + final openId = await requestOpenIdToken(userID!, {}); + final response = await httpClient + .post( + icUri('/admin/api/sso'), + headers: { + 'Content-Type': 'application/json', + 'Origin': icBase.origin, + }, + body: jsonEncode({ + 'openid_token': openId.accessToken, + 'stepup': false, + }), + ) + .timeout(const Duration(seconds: 20)); + if (response.statusCode == 403) return null; + if (response.statusCode != 200) { + throw IcApiException(response.statusCode, _message(_decode(response))); + } + final cookie = response.headers['set-cookie'] ?? ''; + return RegExp(r'ic_admin_sid=([^;]+)').firstMatch(cookie)?.group(1); + } } diff --git a/lib/utils/idealchat/ic_error_report.dart b/lib/utils/idealchat/ic_error_report.dart new file mode 100644 index 0000000..673b12b --- /dev/null +++ b/lib/utils/idealchat/ic_error_report.dart @@ -0,0 +1,204 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat ERRREPORT_1106 (主人 11-06「以后如何杜绝此类问题发生」): uncaught +// errors (Flutter framework, PlatformDispatcher, zone) are reported to +// POST /api/metrics/client_error on our own server so a broken screen is noticed +// without anyone having to send a console screenshot. +// +// Sent: error type, a scrubbed message, the top stack frames, the app version, +// a hash of the current room id. Never message text, tokens, user ids or room +// names. Same error (sig) at most once per 10 minutes (counted), at most 30 +// reports per hour, fire-and-forget (a failure never affects the app). + +import 'dart:async'; +import 'dart:convert'; + +import 'package:fluffychat/utils/idealchat/ic_next.dart'; +import 'package:fluffychat/widgets/fluffy_chat_app.dart'; +import 'package:flutter/foundation.dart'; +import 'package:http/http.dart' as http; +import 'package:package_info_plus/package_info_plus.dart'; + +abstract class IcErrorReport { + static final Uri endpoint = Uri.parse( + 'https://ideal2001.com/api/metrics/client_error', + ); + static const _window = Duration(minutes: 10); + static const _maxPerHour = 30; + + static final _pending = >{}; + static final _lastSent = {}; + static final _sentTimes = []; + static String? _release; + static bool _inReport = false; + static final _scheduled = {}; + static Object? _lastError; + + static String get _app => + kIsWeb ? (icNextBuild ? 'webnext' : 'web') : 'android'; + + /// FNV-1a 64-bit, first 12 hex chars. Same function in the web client, so + /// the server can group by it; no crypto package needed. + static String hash(String s) { + var h = BigInt.parse('cbf29ce484222325', radix: 16); + final prime = BigInt.parse('100000001b3', radix: 16); + final mask = (BigInt.one << 64) - BigInt.one; + for (final b in utf8.encode(s)) { + h = ((h ^ BigInt.from(b)) * prime) & mask; + } + return h.toRadixString(16).padLeft(16, '0').substring(0, 12); + } + + static final _scrubbers = [ + RegExp(r'@[^\s:]+:[A-Za-z0-9.\-]+'), // user ids + RegExp(r'![A-Za-z0-9_\-]+(:[A-Za-z0-9.\-]+)?'), // room ids + RegExp(r'\$[A-Za-z0-9_\-]{8,}'), // event ids + RegExp(r'mxc://\S+'), + RegExp(r'https?://\S+'), + RegExp(r'\d{6,}'), + ]; + + static String scrub(String s) { + for (final r in _scrubbers) { + s = s.replaceAll(r, '_'); + } + return s; + } + + /// Stack frames: keep file:line (URLs shortened to the file name), drop ids. + static String scrubFrame(String s) => s + .replaceAllMapped( + RegExp(r'https?://[^\s()]*/([^/\s()?]+)(\?[^\s():]*)?'), + (m) => m.group(1)!, + ) + .replaceAll(_scrubbers[0], '_') + .replaceAll(_scrubbers[1], '_') + .replaceAll(_scrubbers[2], '_'); + + static String? _roomHash() { + try { + final loc = FluffyChatApp.router.routeInformationProvider.value.uri.path; + final m = RegExp(r'/rooms/(![^/]+)').firstMatch(Uri.decodeFull(loc)); + return m == null ? null : hash(m.group(1)!); + } catch (_) { + return null; + } + } + + /// ROOMRESET_1106: the open chat page registers here; 10 errors within 60 + /// seconds while that room is open ask it to reset the room's timeline. + static void Function(String roomId)? onRoomErrors; + static final _roomErrTimes = >{}; + + static String? _roomId() { + try { + final loc = FluffyChatApp.router.routeInformationProvider.value.uri.path; + return RegExp( + r'/rooms/(![^/]+)', + ).firstMatch(Uri.decodeFull(loc))?.group(1); + } catch (_) { + return null; + } + } + + static void _countRoomError(String kind) { + if (kind != 'flutter' && kind != 'zone' && kind != 'platform') return; + final id = _roomId(); + final cb = onRoomErrors; + if (id == null || cb == null) return; + final now = DateTime.now(); + final list = _roomErrTimes.putIfAbsent(id, () => []) + ..removeWhere((t) => now.difference(t) > const Duration(seconds: 60)) + ..add(now); + if (list.length >= 10) { + list.clear(); + Timer.run(() => cb(id)); + } + } + + static void report(String kind, Object error, StackTrace? stack) { + if (_inReport) return; // never report our own failures + // FlutterError.onError forwards to the zone handler: count it once. + if (identical(error, _lastError)) return; + _lastError = error; + _countRoomError(kind); + _inReport = true; + try { + final type = error.runtimeType.toString(); + var msg = scrub(error.toString()); + if (msg.length > 160) msg = msg.substring(0, 160); + final frames = (stack?.toString() ?? '') + .split('\n') + .map((l) => l.trim()) + .where((l) => l.isNotEmpty) + .take(6) + .map(scrubFrame) + .map((l) => l.length > 120 ? l.substring(0, 120) : l) + .toList(); + final sig = hash('$type|${frames.take(3).join('|')}'); + final now = DateTime.now(); + final secs = now.millisecondsSinceEpoch ~/ 1000; + final p = _pending.putIfAbsent( + sig, + () => { + 'v': 1, + 'app': _app, + 'kind': kind, + 'type': type, + 'msg': msg, + 'frames': frames, + 'sig': sig, + 'room': _roomHash(), + 'count': 0, + 'first_ts': secs, + }, + ); + p['count'] = (p['count'] as int) + 1; + p['last_ts'] = secs; + final last = _lastSent[sig]; + if (last != null && now.difference(last) < _window) { + // Flush the counted repeats once the window is over (one timer). + if (_scheduled.add(sig)) { + Timer(_window - now.difference(last), () { + _scheduled.remove(sig); + _send(sig); + }); + } + return; + } + _send(sig); + } catch (_) { + // Reporting must never throw. + } finally { + _inReport = false; + } + } + + static Future _send(String sig) async { + final p = _pending.remove(sig); + if (p == null) return; + final now = DateTime.now(); + _sentTimes.removeWhere((t) => now.difference(t) > const Duration(hours: 1)); + if (_sentTimes.length >= _maxPerHour) return; + _sentTimes.add(now); + _lastSent[sig] = now; + try { + _release ??= await PackageInfo.fromPlatform().then( + (i) => '${i.version}+${i.buildNumber}', + onError: (_) => 'unknown', + ); + p['release'] = _release; + await http + .post( + endpoint, + headers: {'Content-Type': 'application/json'}, + body: jsonEncode(p), + ) + .timeout(const Duration(seconds: 10)); + } catch (_) { + // Fire and forget: no retry, no effect on the app. + } + } +} diff --git a/lib/utils/idealchat/ic_error_widget.dart b/lib/utils/idealchat/ic_error_widget.dart new file mode 100644 index 0000000..c91c92b --- /dev/null +++ b/lib/utils/idealchat/ic_error_widget.dart @@ -0,0 +1,26 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat ERRWIDGET_1106 (主人 11-06「以后如何杜绝此类问题发生」): when one +// widget fails to build (for example one message bubble), Flutter puts an +// ErrorWidget in exactly that spot. Release builds showed a bare grey box; now +// it is one small line, so the rest of the chat stays readable. Debug builds +// keep Flutter's red error screen. + +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +Widget icErrorWidget(FlutterErrorDetails details) { + if (kDebugMode) { + return ErrorWidget(details.exception); + } + return const Padding( + padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4), + child: Text( + '这条消息显示不了', + style: TextStyle(fontSize: 12, color: Color(0xFF888888)), + textDirection: TextDirection.ltr, + ), + ); +} diff --git a/lib/utils/idealchat/ic_format.dart b/lib/utils/idealchat/ic_format.dart new file mode 100644 index 0000000..01d941b --- /dev/null +++ b/lib/utils/idealchat/ic_format.dart @@ -0,0 +1,183 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat ICFMT_1105 (owner 11-05 19:08–19:21 「这个扩展到整个聊天页面」): the +// marker set the AIs use (server ops/format/ic_format.py, 群规二.12) also works +// for what people type, in every room: +// **重点** → bold, ++下划线++ → underline, 🔴「…」 → red+bold+underline, +// line starting with > or > → quote box, `代码` → inline code. +// Markdown (bold, code, >) is still done by the SDK; this adds the rest on top +// of the SDK's HTML. Mentions, replies, edits and threads go through the SDK's +// own sendEvent unchanged. The 「显示消息格式」 switch only affects display. + +import 'package:fluffychat/utils/idealchat/ai_directory.dart'; +import 'package:matrix/matrix.dart'; +// ignore: implementation_imports +import 'package:matrix/src/utils/markdown.dart'; + +const icRed = '#D32F2F'; + +final _redRe = RegExp('\u{1F534}\\s*「([^」\\n<]{1,200})」'); +final _underRe = RegExp(r'\+\+(?=\S)(.+?)(?<=\S)\+\+'); +final _boldRe = RegExp(r'\*\*(?=\S)(.+?)(?<=\S)\*\*'); +final _fullQuoteRe = RegExp(r'^>\s?', multiLine: true); + +/// Full-width > at a line start becomes a normal markdown quote. +String icPrepareForMarkdown(String text) => + text.replaceAllMapped(_fullQuoteRe, (_) => '> '); + +/// Adds red and underline to the SDK's markdown HTML. +String icDecorateHtml(String html) => html + .replaceAllMapped( + _redRe, + (m) => + '\u{1F534}「${m[1]}」', + ) + .replaceAllMapped(_underRe, (m) => '${m[1]}'); + +final _codeRe = RegExp(r'`([^`\n]{1,200})`'); +final _quoteLineRe = RegExp(r'^(?:>|>)\s?'); + +String _esc(String s) => + s.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>'); + +String _inline(String s) => icDecorateHtml( + _esc(s) + .replaceAllMapped(_codeRe, (m) => '${m[1]}') + .replaceAllMapped(_boldRe, (m) => '${m[1]}'), +); + +/// Display a message that has no HTML with the shared markers (same rules as +/// the server's ic_format.py): **bold**, ++underline++, 🔴「…」, `code`, lines +/// starting with > or > as one quote box. ``` blocks are left alone. +String icPlainToHtml(String body) { + if (body.contains('```')) return _esc(body); + final out = []; + final quote = []; + void flush() { + if (quote.isEmpty) return; + out.add('

${quote.join('
')}
'); + quote.clear(); + } + + final lines = body.split('\n'); + for (var i = 0; i < lines.length; i++) { + final m = _quoteLineRe.firstMatch(lines[i]); + if (m != null) { + quote.add(_inline(lines[i].substring(m.end))); + continue; + } + flush(); + out.add(_inline(lines[i]) + (i < lines.length - 1 ? '
' : '')); + } + flush(); + return out.join(); +} + +/// REDFULL_1105: a message with a red highlight (🔴「…」 or #D32F2F in its +/// HTML) is shown in full, not cut to the preview lines. +/// Owner 11-05: anything that needs the reader to answer or decide is not cut +/// either: it mentions the reader (or @room), or an AI asks a question (text +/// ends with ? or ?). +bool icHasRedHighlight(Event event) { + final body = event.content.tryGet('body') ?? ''; + if (_redRe.hasMatch(body)) return true; + final html = event.content.tryGet('formatted_body') ?? ''; + if (html.toUpperCase().contains(icRed)) return true; + // 【请您选】【请您确认】【待您决定】: the reader has to decide. + if (RegExp('【(请您选|请您确认|待您决定)】').hasMatch(body)) return true; + final mentions = event.content.tryGetMap('m.mentions'); + if (mentions != null) { + if (mentions['room'] == true) return true; + final me = event.room.client.userID; + final ids = mentions.tryGetList('user_ids') ?? const []; + if (me != null && ids.contains(me)) return true; + } + final text = body.trimRight(); + return (text.endsWith('?') || text.endsWith('?')) && + IcAiDirectory.instance.isAi(event.senderId); +} + +/// The plain body keeps the words, without ** and ++ markers. +String icPlainBody(String text) => text + .replaceAllMapped(_boldRe, (m) => m[1]!) + .replaceAllMapped(_underRe, (m) => m[1]!); + +extension IcFormattedSend on Room { + /// Like [Room.sendTextEvent] for ordinary messages, with the IdealChat + /// markers. Commands (text starting with /) use the SDK as before. + Future icSendTextEvent( + String message, { + Event? inReplyTo, + String? editEventId, + bool parseCommands = true, + String? threadRootEventId, + }) { + if (parseCommands && message.startsWith('/')) { + return sendTextEvent( + message, + inReplyTo: inReplyTo, + editEventId: editEventId, + threadRootEventId: threadRootEventId, + ); + } + final source = icPrepareForMarkdown(message); + final event = { + 'msgtype': MessageTypes.Text, + 'body': icPlainBody(source), + }; + + // Mentions exactly as the SDK does it. + var potentialMentions = + source + .split('@') + .map( + (text) => text.startsWith('[') + ? '@${text.split(']').first}]' + : '@${text.split(RegExp(r'\s+')).first}', + ) + .toList() + ..removeAt(0); + final hasRoomMention = potentialMentions.remove('@room'); + potentialMentions = + potentialMentions + .map( + (mention) => mention.isValidMatrixIdStrict() + ? mention + : getMention(mention), + ) + .nonNulls + .toSet() + .toList() + ..remove(client.userID); + if (inReplyTo != null) potentialMentions.add(inReplyTo.senderId); + if (hasRoomMention || potentialMentions.isNotEmpty) { + event['m.mentions'] = { + if (hasRoomMention) 'room': true, + if (potentialMentions.isNotEmpty) 'user_ids': potentialMentions, + }; + } + + final html = icDecorateHtml( + markdown( + source, + getEmotePacks: () => getImagePacksFlat(ImagePackUsage.emoticon), + getMention: getMention, + convertLinebreaks: client.convertLinebreaksInFormatting, + enableLatex: client.enableLatexMarkdown, + ), + ); + // Only send HTML when there is real formatting (not just line breaks). + if (RegExp(r'<(?!br\s*/?>)[a-zA-Z]').hasMatch(html)) { + event['format'] = 'org.matrix.custom.html'; + event['formatted_body'] = html; + } + return sendEvent( + event, + inReplyTo: inReplyTo, + editEventId: editEventId, + threadRootEventId: threadRootEventId, + ); + } +} diff --git a/lib/utils/idealchat/ic_next.dart b/lib/utils/idealchat/ic_next.dart new file mode 100644 index 0000000..2ab55f7 --- /dev/null +++ b/lib/utils/idealchat/ic_next.dart @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat WEBNEXT_1105 (系统梳理 合1): the web app built from this same +// source, first on a side-by-side test path (/app/next/). That build is made +// with --dart-define=IC_NEXT=true and keeps its own storage (preferences +// prefix and client/database names), so it can never open or migrate the +// live web app's data in the same browser. + +import 'package:flutter/foundation.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:url_launcher/url_launcher_string.dart'; + +const icNextBuild = bool.fromEnvironment('IC_NEXT'); + +/// Preferences prefix of the side-by-side web build. +const icNextPrefsPrefix = 'icnext.'; + +/// Pages that use an in-app WebView on Android (task board, 留言板, 技能库) +/// open in a new browser tab on the web: same site, same login. +bool get icUseBrowserTab => kIsWeb; + +Future icOpenInBrowserTab(String url) => + launchUrlString(url, webOnlyWindowName: '_blank'); + +/// Shown in place of the WebView on the web: the page was opened in a new tab. +class IcOpenedInTab extends StatelessWidget { + final String title; + final String url; + + const IcOpenedInTab({required this.title, required this.url, super.key}); + + @override + Widget build(BuildContext context) { + final zh = Localizations.localeOf(context).languageCode == 'zh'; + return Scaffold( + appBar: AppBar( + leading: const Center(child: BackButton()), + title: Text(title), + ), + body: Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(zh ? '已在新标签页打开。' : 'Opened in a new tab.'), + const SizedBox(height: 12), + OutlinedButton( + onPressed: () => icOpenInBrowserTab(url), + child: Text(zh ? '再打开一次' : 'Open again'), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/utils/idealchat/ic_web_notify.dart b/lib/utils/idealchat/ic_web_notify.dart new file mode 100644 index 0000000..5306e15 --- /dev/null +++ b/lib/utils/idealchat/ic_web_notify.dart @@ -0,0 +1,50 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat NOTIFFIX_1106: mobile browsers refuse `new Notification()` +// ('Illegal constructor. Use ServiceWorkerRegistration.showNotification'), so +// fall back to an active service worker registration. Autoplay of the +// notification sound may be blocked by the browser: that is not an error. + +import 'package:universal_html/html.dart' as html; + +Future icPlayQuietly(html.AudioElement player) async { + try { + await player.play(); + } catch (_) { + // NotAllowedError (autoplay blocked): stay silent. + } +} + +void icWebNotify(String title, {String? body, String? icon, String? tag}) { + try { + html.Notification(title, body: body, icon: icon, tag: tag); + return; + } catch (_) {} + _viaServiceWorker(title, { + 'body': ?body, + 'icon': ?icon, + 'tag': ?tag, + }); +} + +Future _viaServiceWorker(String title, Map options) async { + try { + final sw = html.window.navigator.serviceWorker; + if (sw == null) return; + final own = await sw.getRegistration(); + var reg = own.active != null ? own : null; + if (reg == null) { + for (final r in await sw.getRegistrations()) { + if (r is html.ServiceWorkerRegistration && r.active != null) { + reg = r; + break; + } + } + } + await reg?.showNotification(title, options); + } catch (_) { + // No way to show it: skip quietly. + } +} diff --git a/lib/utils/idealchat/mention_ranking.dart b/lib/utils/idealchat/mention_ranking.dart new file mode 100644 index 0000000..346e31d --- /dev/null +++ b/lib/utils/idealchat/mention_ranking.dart @@ -0,0 +1,106 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat MENTIONS_1105 (owner 11-05 「名单并不全…不应该写死…主答ai第一位, +// 然后是最活跃的进行排序」): the @ list always comes from the server — the full +// joined member list is fetched once per room per app run, no fixed limit — +// and is ordered: the room's lead AI first (/board/api/reply_mode `lead`), then +// by how many of the room's recent messages each member sent, then by how +// recently they spoke, then by name. + +import 'package:fluffychat/utils/idealchat/ic_api.dart'; +import 'package:matrix/matrix.dart'; + +class IcMentionRanking { + final String? lead; + final Map count; + final Map lastTs; + final DateTime at; + + IcMentionRanking(this.lead, this.count, this.lastTs) : at = DateTime.now(); + + static final _cache = {}; + static final _inflight = >{}; + static final _membersLoaded = {}; + + /// Fresh member list from the server, once per room per app run. + static Future loadMembers(Room room) async { + if (!_membersLoaded.add(room.id)) return; + try { + await room.requestParticipants([Membership.join, Membership.invite]); + } catch (e) { + _membersLoaded.remove(room.id); + Logs().w('[IC] Unable to load all participants for mentions', e); + } + } + + static Future of(Room room) { + final cached = _cache[room.id]; + if (cached != null && + DateTime.now().difference(cached.at) < const Duration(minutes: 2)) { + return Future.value(cached); + } + return _inflight[room.id] ??= _load( + room, + ).whenComplete(() => _inflight.remove(room.id)); + } + + static Future _load(Room room) async { + final client = room.client; + String? lead; + final count = {}; + final lastTs = {}; + await Future.wait([ + () async { + try { + final json = await client.icGet( + '/board/api/reply_mode', + query: {'room': room.id}, + ); + if (json is Map && + json['room'] == room.id && + json['lead'] is String) { + lead = json['lead'] as String; + } + } catch (e) { + Logs().v('[IC] reply_mode lead unavailable', e); + } + }(), + () async { + try { + final res = await client.getRoomEvents( + room.id, + Direction.b, + limit: 200, + ); + for (final e in res.chunk) { + if (e.type != EventTypes.Message && + e.type != EventTypes.Encrypted && + e.type != EventTypes.Sticker) { + continue; + } + final ts = e.originServerTs.millisecondsSinceEpoch; + count[e.senderId] = (count[e.senderId] ?? 0) + 1; + if ((lastTs[e.senderId] ?? 0) < ts) lastTs[e.senderId] = ts; + } + } catch (e) { + Logs().v('[IC] recent messages unavailable for mention order', e); + } + }(), + ]); + return _cache[room.id] = IcMentionRanking(lead, count, lastTs); + } + + /// Sort key: lead AI first, then more recent messages, then more recent, + /// then by name. + int compare(String a, String b, String nameA, String nameB) { + if (a == lead) return -1; + if (b == lead) return 1; + final c = (count[b] ?? 0).compareTo(count[a] ?? 0); + if (c != 0) return c; + final t = (lastTs[b] ?? 0).compareTo(lastTs[a] ?? 0); + if (t != 0) return t; + return nameA.toLowerCase().compareTo(nameB.toLowerCase()); + } +} diff --git a/lib/utils/idealchat/room_labels.dart b/lib/utils/idealchat/room_labels.dart new file mode 100644 index 0000000..31b8709 --- /dev/null +++ b/lib/utils/idealchat/room_labels.dart @@ -0,0 +1,109 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat (web ic47 / SSOT_1545 / ic48 parity, WEBNEXT_1105): +// - The user's upline group (account data ideal.default_groups → upline) is +// shown under its custom label (labels.upline). The label text itself comes +// from the single source /ai-join/room-labels when the server has one. +// Display only: the real room name is never changed. +// - After login, io.idealchat.account and ideal.default_groups are filled in +// from /ai-join/me/account when the account doesn't have them yet (own +// token; never overwrites existing data). + +import 'package:fluffychat/utils/idealchat/ic_api.dart'; +import 'package:matrix/matrix.dart'; + +abstract class IcRoomLabels { + static const _defaultGroups = 'ideal.default_groups'; + static const _account = 'io.idealchat.account'; + + static String? _sotUpline; + static bool _sotLoaded = false; + static final _backfilled = {}; + + /// Custom label for [room], or null to use the normal name. + static String? labelFor(Room room) { + final dg = room.client.accountData[_defaultGroups]?.content; + if (dg == null) return null; + final upline = dg['upline']; + if (upline is! String || upline != room.id) return null; + final labels = dg['labels']; + final label = labels is Map ? labels['upline'] : null; + if (label is! String || label.isEmpty) return null; + return _sotUpline ?? label; + } + + /// Runs once per app run (labels) and once per account (backfill). + static void start(Iterable clients) { + for (final client in clients) { + if (!client.isLogged()) continue; + if (!_sotLoaded) { + _sotLoaded = true; + client + .icGet('/ai-join/room-labels') + .then((j) { + final up = j is Map ? j['upline'] : null; + if (up is String && up.isNotEmpty) _sotUpline = up; + }) + .catchError((e) { + _sotLoaded = false; + Logs().v('[IC] room-labels unavailable', e); + }); + } + _backfill(client); + } + } + + static Future _missing( + Client client, + String userId, + String type, + ) async { + try { + await client.getAccountData(userId, type); + return false; + } on MatrixException catch (e) { + return e.error == MatrixError.M_NOT_FOUND; + } + } + + static Future _backfill(Client client) async { + final userId = client.userID; + if (userId == null || !_backfilled.add(userId)) return; + try { + final missAccount = await _missing(client, userId, _account); + final missGroups = await _missing(client, userId, _defaultGroups); + if (!missAccount && !missGroups) return; + final j = await client.icGet('/ai-join/me/account'); + if (j is! Map || j['user_id'] != userId) return; + final account = j['account']; + final groups = j['default_groups']; + if (missAccount && account is Map) { + await client.setAccountData( + userId, + _account, + Map.from(account), + ); + } + if (missGroups && groups is Map) { + await client.setAccountData( + userId, + _defaultGroups, + Map.from(groups), + ); + } + Logs().i('[IC] account backfill $missAccount $missGroups'); + } catch (e) { + _backfilled.remove(userId); + Logs().v('[IC] account backfill skipped', e); + } + } +} + +extension IcRoomName on Room { + /// Room name as shown to the user (custom upline label if any). + String icDisplayname([ + MatrixLocalizations i18n = const MatrixDefaultLocalizations(), + ]) => IcRoomLabels.labelFor(this) ?? getLocalizedDisplayname(i18n); +} diff --git a/lib/utils/push_helper.dart b/lib/utils/push_helper.dart index a65c7e3..e853635 100644 --- a/lib/utils/push_helper.dart +++ b/lib/utils/push_helper.dart @@ -14,6 +14,7 @@ import 'package:fluffychat/config/setting_keys.dart'; import 'package:fluffychat/l10n/l10n.dart'; import 'package:fluffychat/utils/call_kit_params.dart'; import 'package:fluffychat/utils/client_manager.dart'; +import 'package:fluffychat/utils/idealchat/ai_discussion.dart'; import 'package:fluffychat/utils/matrix_live_kit_calls/matrix_live_kit_call.dart'; import 'package:fluffychat/utils/matrix_sdk_extensions/matrix_locals.dart'; import 'package:fluffychat/utils/notification_avatar_extension.dart'; @@ -181,6 +182,12 @@ Future _tryPushHelper( return; } + // AIFOLD_1105: AI-to-AI discussion never pops a notification. + if (icIsAiDiscussion(event)) { + Logs().i('Push helper: AI discussion, no notification.'); + return; + } + if (event.type == RtcNotificationContent.eventType && event.tryParseRtcNotificationContent()?.notificationType == .ring && PlatformInfos.isMobile) { diff --git a/lib/utils/sign_in_flows/check_homeserver.dart b/lib/utils/sign_in_flows/check_homeserver.dart index bc46e02..75a0943 100644 --- a/lib/utils/sign_in_flows/check_homeserver.dart +++ b/lib/utils/sign_in_flows/check_homeserver.dart @@ -67,7 +67,12 @@ Future connectToHomeserverFlow( final pathSegments = List.of( GoRouter.of(context).routeInformationProvider.value.uri.pathSegments, ); - if (pathSegments.last != 'home') pathSegments.removeLast(); + // IdealChat ADDACCT_1105: only swap sign_in/sign_up for login. On + // /rooms/settings/addaccount the old rule dropped "addaccount" and went to + // the non-existent /rooms/settings/login. + if (const {'sign_in', 'sign_up'}.contains(pathSegments.last)) { + pathSegments.removeLast(); + } pathSegments.add('login'); context.push('/${pathSegments.join('/')}', extra: client); setState(AsyncSnapshot.withData(ConnectionState.done, true)); @@ -78,7 +83,7 @@ Future connectToHomeserverFlow( if (context.mounted) { setState(AsyncSnapshot.withData(ConnectionState.done, true)); - context.go('/backup'); + context.go('/rooms'); // NOBACKUP_1107: no automatic chat-backup page } } catch (e, s) { Logs().w('Unable to login', e, s); diff --git a/lib/utils/start_push_foreground_service.dart b/lib/utils/start_push_foreground_service.dart index 87344b9..78d435e 100644 --- a/lib/utils/start_push_foreground_service.dart +++ b/lib/utils/start_push_foreground_service.dart @@ -68,7 +68,7 @@ abstract class ForegroundServices { } final result = await FlutterForegroundTask.startService( serviceTypes: [ForegroundServiceTypes.shortService], - notificationTitle: 'FluffyChat', + notificationTitle: 'IdealChat', notificationText: l10n.loadingMessages, notificationIcon: NotificationIcon(metaDataName: 'ic_launcher'), ); diff --git a/lib/widgets/chat_settings_popup_menu.dart b/lib/widgets/chat_settings_popup_menu.dart index 4d7a3f1..4a84e26 100644 --- a/lib/widgets/chat_settings_popup_menu.dart +++ b/lib/widgets/chat_settings_popup_menu.dart @@ -6,6 +6,8 @@ import 'dart:async'; import 'package:fluffychat/l10n/l10n.dart'; +import 'package:fluffychat/pages/idealchat/member_panel_page.dart'; +import 'package:fluffychat/pages/idealchat/room_files_page.dart'; import 'package:fluffychat/widgets/adaptive_dialogs/show_ok_cancel_alert_dialog.dart'; import 'package:fluffychat/widgets/future_loading_dialog.dart'; import 'package:go_router/go_router.dart'; @@ -22,6 +24,8 @@ enum ChatPopupMenuActions { // IdealChat: same extra items as the web ⋮ menu tasks, suggestions, + roomSkills, + roomFiles, aiStatus, replyMode, } @@ -101,6 +105,12 @@ class ChatSettingsPopupMenuState extends State { case ChatPopupMenuActions.suggestions: context.push('/rooms/${widget.room.id}/suggestions'); break; + case ChatPopupMenuActions.roomSkills: + context.push('/rooms/${widget.room.id}/room_skills'); + break; + case ChatPopupMenuActions.roomFiles: + icOpenRoomFiles(context, widget.room.id); + break; case ChatPopupMenuActions.aiStatus: context.push('/rooms/${widget.room.id}/ai_status'); break; @@ -143,6 +153,28 @@ class ChatSettingsPopupMenuState extends State { ], ), ), + // ROOMSKILLS_1105: 本群技能 (every member, read-only) + PopupMenuItem( + value: ChatPopupMenuActions.roomSkills, + child: Row( + children: [ + const Icon(Icons.auto_stories_outlined), + const SizedBox(width: 12), + Text(icT(context, '本群技能', 'Room skills')), + ], + ), + ), + // ROOMFILES_1106: 群文件 + PopupMenuItem( + value: ChatPopupMenuActions.roomFiles, + child: Row( + children: [ + const Icon(Icons.folder_outlined), + const SizedBox(width: 12), + Text(icT(context, '群文件', 'Room files')), + ], + ), + ), PopupMenuItem( value: ChatPopupMenuActions.aiStatus, child: Row( diff --git a/lib/widgets/local_notifications_extension.dart b/lib/widgets/local_notifications_extension.dart index 5027e65..6299e9b 100644 --- a/lib/widgets/local_notifications_extension.dart +++ b/lib/widgets/local_notifications_extension.dart @@ -6,6 +6,9 @@ import 'package:fluffychat/config/setting_keys.dart'; import 'package:fluffychat/l10n/l10n.dart'; import 'package:fluffychat/utils/client_download_content_extension.dart'; +import 'package:fluffychat/utils/idealchat/ai_discussion.dart'; +import 'package:fluffychat/utils/idealchat/ic_web_notify.dart'; +import 'package:fluffychat/utils/idealchat/room_labels.dart'; import 'package:fluffychat/utils/matrix_sdk_extensions/matrix_locals.dart'; import 'package:fluffychat/utils/notification_background_handler.dart'; import 'package:fluffychat/utils/push_helper.dart'; @@ -24,6 +27,8 @@ extension LocalNotificationsExtension on MatrixState { ..load(); Future showLocalNotification(Event event) async { + // AIFOLD_1105: AI-to-AI discussion never pops a notification. + if (icIsAiDiscussion(event)) return; if (event.type == RtcNotificationContent.eventType && event.tryParseRtcNotificationContent()?.notificationType == .ring) { final context = @@ -48,9 +53,7 @@ extension LocalNotificationsExtension on MatrixState { } } - final title = event.room.getLocalizedDisplayname( - MatrixLocals(L10n.of(context)), - ); + final title = event.room.icDisplayname(MatrixLocals(L10n.of(context))); final body = await event.calcLocalizedBody( MatrixLocals(L10n.of(context)), withSenderNamePrefix: @@ -90,9 +93,9 @@ extension LocalNotificationsExtension on MatrixState { method: thumbnailMethod, ); - if (AppSettings.webNotificationSound.value) _audioPlayer.play(); + if (AppSettings.webNotificationSound.value) icPlayQuietly(_audioPlayer); - html.Notification( + icWebNotify( title, body: body, icon: thumbnailUri?.toString(), diff --git a/lib/widgets/matrix.dart b/lib/widgets/matrix.dart index 74fe508..8c9621b 100644 --- a/lib/widgets/matrix.dart +++ b/lib/widgets/matrix.dart @@ -9,6 +9,7 @@ import 'dart:convert'; import 'package:collection/collection.dart'; import 'package:fluffychat/l10n/l10n.dart'; import 'package:fluffychat/utils/client_manager.dart'; +import 'package:fluffychat/utils/idealchat/room_labels.dart'; import 'package:fluffychat/utils/idealchat/timezone_reporter.dart'; import 'package:fluffychat/utils/init_with_restore.dart'; import 'package:fluffychat/utils/matrix_sdk_extensions/matrix_file_extension.dart'; @@ -166,7 +167,7 @@ class MatrixState extends State { _registerSubs(_loginClientCandidate!.clientName); setActiveClient(_loginClientCandidate); _loginClientCandidate = null; - FluffyChatApp.router.go('/backup'); + FluffyChatApp.router.go('/rooms'); // NOBACKUP_1107 }); if (widget.clients.isEmpty) widget.clients.add(candidate); return candidate; @@ -299,7 +300,14 @@ class MatrixState extends State { ), ); c.onSync.stream.first.then((s) { - html.Notification.requestPermission(); + // IdealChat NOTIFGUARD_1106: some mobile browsers have no + // Notification at all; asking threw and the listener below was never + // set up. Ask only where supported. + try { + if (html.Notification.supported) { + html.Notification.requestPermission(); + } + } catch (_) {} onNotification[name] ??= c.onNotification.stream.listen( showLocalNotification, ); @@ -357,6 +365,7 @@ class MatrixState extends State { void didChangeAppLifecycleState(AppLifecycleState state) { if (state == AppLifecycleState.resumed) { TimezoneReporter.report(widget.clients); + IcRoomLabels.start(widget.clients); } final foreground = state != AppLifecycleState.inactive && @@ -430,7 +439,7 @@ class MatrixState extends State { final exportBytes = Uint8List.fromList(const Utf8Codec().encode(export)); final exportFileName = - 'fluffychat-export-${DateFormat(DateFormat.YEAR_MONTH_DAY).format(DateTime.now())}.fluffybackup'; + 'idealchat-export-${DateFormat(DateFormat.YEAR_MONTH_DAY).format(DateTime.now())}.fluffybackup'; final file = MatrixFile(bytes: exportBytes, name: exportFileName); if (!context.mounted) return; diff --git a/pubspec.lock b/pubspec.lock index f325b54..d89e406 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -2045,10 +2045,9 @@ packages: swipe_to_action: dependency: "direct main" description: - name: swipe_to_action - sha256: "05289a2bff6a0227deeff382afa1c46643d1f077e678d78f76440e153ea1ef7d" - url: "https://pub.dev" - source: hosted + path: "vendor/swipe_to_action" + relative: true + source: path version: "0.3.0" sync_http: dependency: transitive diff --git a/pubspec.yaml b/pubspec.yaml index 8fe964b..6606b23 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -9,7 +9,7 @@ publish_to: none # On version bump please also increase: # 1. The build number (for F-Droid) # 2. The version in /snap/snapcraft.yaml -version: 2.10.4+3572 +version: 2.10.6+3574 environment: sdk: ">=3.11.1 <4.0.0" @@ -147,3 +147,7 @@ flutter_launcher_icons: # 2. Always link an (upstream?) issue # 3. Explain how and when this can be removed (overrides must be temporarily) dependency_overrides: + # IdealChat SWIPEMOUNT_1106: swipe_to_action 0.3.0 with a mounted check in + # its post-frame setState (blank timeline). Remove when upstream fixes it. + swipe_to_action: + path: vendor/swipe_to_action diff --git a/test/format_cases_test.dart b/test/format_cases_test.dart new file mode 100644 index 0000000..694e7d2 --- /dev/null +++ b/test/format_cases_test.dart @@ -0,0 +1,90 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// FMTCASES_1105: generated from ~/IdealChat/ops/format/format_cases.json by +// `python3 ops/format/test_format_cases.py --write-dart`. Do not edit by hand. +// The server's ic_format.py is the standard; the app must render the same. + +import 'dart:convert'; + +import 'package:fluffychat/utils/idealchat/ic_format.dart'; +import 'package:flutter_test/flutter_test.dart'; + +// BEGIN format_cases.json +const _casesJson = r'''{ + "_note": "FMTCASES_1105(系统梳理 合2):聊天格式记号的共用测试样例。标准实现是 ops/format/ic_format.py 的 to_html()/plain();安卓 ic_format.dart 的 icPlainToHtml()/icPlainBody() 必须给出同样结果。改规则时先改这里,跑 python3 ops/format/test_format_cases.py 和安卓测试。不含 ``` 和【表情:】(这两样在 apply() 里另有处理)。", + "cases": [ + { + "name": "bold", + "input": "**重点**", + "html": "重点", + "body": "重点" + }, + { + "name": "bold_single", + "input": "**a**", + "html": "a", + "body": "a" + }, + { + "name": "underline", + "input": "++下划线++", + "html": "下划线", + "body": "下划线" + }, + { + "name": "red", + "input": "看这里 🔴「要您拿主意」 好", + "html": "看这里 🔴「要您拿主意」 好", + "body": "看这里 🔴「要您拿主意」 好" + }, + { + "name": "code", + "input": "`xx<y", + "body": "`x 汇总一\n> 汇总二", + "html": "
汇总一
汇总二
", + "body": "> 汇总一\n> 汇总二" + }, + { + "name": "quote_fullwidth", + "input": "> 汇总", + "html": "
汇总
", + "body": "> 汇总" + }, + { + "name": "mixed", + "input": "好,已改:\n> **【讨论汇总·第1轮】**\n> 采纳:配色换深蓝\n> 🔴「封面标题要您定」\n普通字 ++下划线++ `x
【讨论汇总·第1轮】
采纳:配色换深蓝
🔴「封面标题要您定」
普通字 下划线 x<y", + "body": "好,已改:\n> 【讨论汇总·第1轮】\n> 采纳:配色换深蓝\n> 🔴「封面标题要您定」\n普通字 下划线 `xc", + "body": "a第二行", + "body": "第一行\n第二行" + } + ] +}'''; +// END format_cases.json + +void main() { + final cases = (jsonDecode(_casesJson) as Map)['cases'] as List; + for (final c in cases.cast()) { + test('shared format case: ${c['name']}', () { + expect(icPlainToHtml(c['input'] as String), c['html']); + expect(icPlainBody(c['input'] as String), c['body']); + }); + } +} diff --git a/test/ic_format_test.dart b/test/ic_format_test.dart new file mode 100644 index 0000000..e19dd16 --- /dev/null +++ b/test/ic_format_test.dart @@ -0,0 +1,47 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +import 'package:fluffychat/utils/idealchat/ic_format.dart'; +import 'package:flutter_test/flutter_test.dart'; +// ignore: implementation_imports +import 'package:matrix/src/utils/markdown.dart'; + +String fmt(String text) => icDecorateHtml(markdown(icPrepareForMarkdown(text))); + +void main() { + test('red marker becomes red + bold + underline', () { + expect( + fmt('看这里 🔴「要您拿主意」 好'), + contains( + '🔴「要您拿主意」', + ), + ); + }); + test('bold, underline, code', () { + final h = fmt('**加粗** 和 ++下划线++ 和 `代码`'); + expect(h, contains('加粗')); + expect(h, contains('下划线')); + expect(h, contains('代码')); + }); + test('> and full-width > make a quote box', () { + expect(fmt('> 汇总'), contains('
')); + expect(fmt('> 汇总'), contains('
')); + }); + test('plain body drops ** and ++ only', () { + expect(icPlainBody('**a** ++b++ 🔴「c」'), 'a b 🔴「c」'); + }); + test('html in text stays escaped', () { + expect(fmt('x'), isNot(contains(''))); + }); + test('plain messages show the markers (display)', () { + final h = icPlainToHtml('**重点** 和 🔴「红字」\n> 汇总一\n> 汇总二\n`x`'); + expect(h, contains('重点')); + expect(h, contains('「红字」')); + expect(h, contains('
汇总一
汇总二
')); + expect(h, contains('x<b>')); + }); + test('``` blocks are left alone', () { + expect(icPlainToHtml('```\n**a**\n```'), isNot(contains(''))); + }); +} diff --git a/tools/ic/apply_toolchain_patches.py b/tools/ic/apply_toolchain_patches.py new file mode 100644 index 0000000..42be83a --- /dev/null +++ b/tools/ic/apply_toolchain_patches.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 +"""IdealChat toolchain patches (SETSTATEGUARD_1106). Idempotent; run before every +Flutter build: python3 tools/ic/apply_toolchain_patches.py +- State.setState after dispose: in release builds it threw "Null check operator + used on a null value" (any package, e.g. swipe_to_action) and the chat timeline + went blank. Now it does nothing in release; debug builds still assert as before. +Exit 1 if the anchor isn't found (new Flutter version: re-check the patch).""" +import os, sys +ROOT = os.path.expanduser("~/IdealChat/client/toolchain/flutter-3.47.7") +F = os.path.join(ROOT, "packages/flutter/lib/src/widgets/framework.dart") +MARK = "IdealChat SETSTATEGUARD_1106" +ANCHOR = " final Object? result = fn() as dynamic;\n" +s = open(F, encoding="utf-8").read() +if MARK in s: + print("setState guard: already applied"); sys.exit(0) +if s.count(ANCHOR) != 1: + print("setState guard: anchor not found, check", F); sys.exit(1) +s = s.replace(ANCHOR, " // " + MARK + ": release builds used to throw on the `_element!` below\n" + " // when setState ran after dispose (timers, frame callbacks, futures).\n" + " if (_element == null) return;\n" + ANCHOR) +open(F, "w", encoding="utf-8").write(s) +print("setState guard: applied") diff --git a/tools/ic/find_unsafe_setstate.py b/tools/ic/find_unsafe_setstate.py new file mode 100644 index 0000000..fe9d1a0 --- /dev/null +++ b/tools/ic/find_unsafe_setstate.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +"""SETSTATEGUARD_1106: list setState calls that run later (frame callback, timer, +future, stream, listener, after await) without a nearby `mounted` check. +Heuristic. Usage: find_unsafe_setstate.py [--packages] +Exit code = number of hits in the project's own lib/ (packages are report-only; +the toolchain setState guard covers them in release).""" +import json, os, re, sys + +LATER = re.compile(r"addPostFrameCallback|scheduleFrameCallback|Timer(\.periodic)?\(|Future\.delayed|" + r"\.then\(|\.listen\(|\.whenComplete\(|\.catchError\(|addListener\(|\bawait\b|onDone|" + r"WidgetsBinding\.instance") +MOUNTED = re.compile(r"\bmounted\b|context\.mounted") + +def scan(path): + hits = [] + try: + lines = open(path, encoding="utf-8").read().split("\n") + except Exception: + return hits + for i, l in enumerate(lines): + if "setState(" not in l or l.strip().startswith("//") or "void setState(" in l: + continue + # walk back to the enclosing function start (crude: a line ending with "{" at + # lower indent that looks like a method), max 40 lines + ind = len(l) - len(l.lstrip()) + window = [] + for j in range(i - 1, max(-1, i - 40), -1): + t = lines[j] + window.append(t) + ti = len(t) - len(t.lstrip()) + if ti <= 2 and t.rstrip().endswith("{"): + break + w = "\n".join(reversed(window)) + m = None + for mm in LATER.finditer(w): + m = mm + if not m: + continue + after = w[m.start():] + if MOUNTED.search(after) or MOUNTED.search(l): + continue + hits.append((path, i + 1, l.strip()[:100])) + return hits + +def dart_files(d): + for r, _, fs in os.walk(d): + for f in fs: + if f.endswith(".dart") and not f.endswith((".g.dart", ".freezed.dart")): + yield os.path.join(r, f) + +def main(): + proj = sys.argv[1] + own = [] + for f in dart_files(os.path.join(proj, "lib")): + own += scan(f) + for p, n, t in own: + print(f"APP {os.path.relpath(p, proj)}:{n}: {t}") + if "--packages" in sys.argv: + cfg = json.load(open(os.path.join(proj, ".dart_tool/package_config.json"))) + for pkg in cfg["packages"]: + uri = pkg["rootUri"] + if not uri.startswith("file://") or "/flutter-3.47.7/" in uri: + continue + root = uri[7:] + n = 0 + for f in dart_files(os.path.join(root, pkg.get("packageUri", "lib/"))): + n += len(scan(f)) + if n: + print(f"PKG {pkg['name']}: {n}") + print(f"TOTAL_APP {len(own)}") + sys.exit(min(len(own), 100)) + +main() diff --git a/vendor/swipe_to_action/CHANGELOG.md b/vendor/swipe_to_action/CHANGELOG.md new file mode 100644 index 0000000..00a73fd --- /dev/null +++ b/vendor/swipe_to_action/CHANGELOG.md @@ -0,0 +1,11 @@ +## 0.3.0 + +* Ignore swipe when it starts in system gesture insets by [EpicKiwi](https://github.com/EpicKiwi) + +## 0.2.0 + +* Null-safety migration by [devcat37](https://github.com/devcat37) + +## 0.1.0 + +* Initial release. diff --git a/vendor/swipe_to_action/LICENSE b/vendor/swipe_to_action/LICENSE new file mode 100644 index 0000000..28dc868 --- /dev/null +++ b/vendor/swipe_to_action/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Inex Code + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/swipe_to_action/README.md b/vendor/swipe_to_action/README.md new file mode 100644 index 0000000..05d555c --- /dev/null +++ b/vendor/swipe_to_action/README.md @@ -0,0 +1,58 @@ +# swipe_to_action + +A widget which can be used to call functions when the wrapped child is dragged or flinged. Only intended to work with horizontal swipes. + +Features: +- Aware of input type (touch, mouse, stylus), allowed types can be passed. +- Allows calling different functions depending on swipe direction. +- Allows different backgrounds depending on swipe direction. +- Allows calling a confirmation function before calling intended function. + +## Getting Started + +Import the package + +```dart +import 'package:swipe_to_action/swipe_to_action.dart'; +``` + +And use Swipeable class, for example: +```dart +Swipeable( + key: ValueKey("Some key, required"), + onSwipe: (direction) { + if (direction == SwipeDirection.startToEnd) { + // do something + } else { + // do something else + } + }, + // Widget to display below. + // If [secondaryBackground] is defined, only works when swiping from start to end. + // Optional. + background: Container(color: Colors.green), + // Widget to display below if swiping from end to start. + // Only works if [background] is defined + // Optional. + secondaryBackground: Container(color: Colors.teal), + // Function to call before calling onSwipe. If it returns false, + // swipe is aborted and onSwipe is not called. + // Optional. + confirmSwipe: (direction) async { + return true; + }, + // By default swiping works only with touch or stylus. You may alter this + // by specifying device kinds to use. This is a list of all device kinds. + allowedPointerKinds = { + PointerDeviceKind.touch, + PointerDeviceKind.stylus, + PointerDeviceKind.invertedStylus, + PointerDeviceKind.mouse, + PointerDeviceKind.unknown, + }, + + child: /* required */, +) +``` + +All arguments are documented: you may refer to IntelliSense, source code or API docs. diff --git a/vendor/swipe_to_action/lib/src/swipeable.dart b/vendor/swipe_to_action/lib/src/swipeable.dart new file mode 100644 index 0000000..2f1be19 --- /dev/null +++ b/vendor/swipe_to_action/lib/src/swipeable.dart @@ -0,0 +1,522 @@ +import 'dart:ui'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; + +const double _kMinFlingVelocity = 700.0; +const double _kMinFlingVelocityDelta = 400.0; +const double _kFlingVelocityScale = 1.0 / 300.0; +const double _kDismissThreshold = 0.4; + +/// Signature used by [Swipeable] to indicate that it has been swiped in +/// the given `direction`. +/// +/// Used by [Swipeable.onSwipe]. +typedef SwipeDirectionCallback = void Function(SwipeDirection direction); + +/// Signature used by [Swipeable] to give the application an opportunity to +/// confirm or veto a swipe gesture. +/// +/// Used by [Swipeable.confirmSwipe]. +typedef ConfirmSwipeCallback = Future Function(SwipeDirection direction); + +/// The direction in which a [Swipeable] can be swiped. +enum SwipeDirection { + /// The [Swipeable] can be swiped by dragging either left or right. + horizontal, + + /// The [Swipeable] can be swiped by dragging in the reverse of the + /// reading direction (e.g., from right to left in left-to-right languages). + endToStart, + + /// The [Swipeable] can be swiped by dragging in the reading direction + /// (e.g., from left to right in left-to-right languages). + startToEnd, + + /// Called instead of null. + none, +} + +class Swipeable extends StatefulWidget { + /// Creates a widget that calls a function when swiped. + /// + /// The [key] argument must not be null because [Swipeable]s are commonly + /// used in lists and removed from the list when dismissed. Without keys, the + /// default behavior is to sync widgets based on their index in the list, + /// which means the item after the dismissed item would be synced with the + /// state of the dismissed item. Using keys causes the widgets to sync + /// according to their keys and avoids this pitfall. + const Swipeable({ + required final Key key, + required this.child, + required this.onSwipe, + this.background, + this.secondaryBackground, + this.confirmSwipe, + this.direction = SwipeDirection.horizontal, + this.dismissThresholds = const {}, + this.maxOffset = 0.4, + this.movementDuration = const Duration(milliseconds: 200), + this.crossAxisEndOffset = 0.0, + this.dragStartBehavior = DragStartBehavior.start, + this.allowedPointerKinds = const { + PointerDeviceKind.invertedStylus, + PointerDeviceKind.stylus, + PointerDeviceKind.touch, + }, + }) : assert(secondaryBackground == null || background != null), + super(key: key); + + /// The widget below this widget in the tree. + /// + /// {@macro flutter.widgets.child} + final Widget child; + + /// A widget that is stacked behind the child. If secondaryBackground is also + /// specified then this widget only appears when the child has been dragged + /// to the right. + final Widget? background; + + /// A widget that is stacked behind the child and is exposed when the child + /// has been dragged to the left. It may only be specified when background + /// has also been specified. + final Widget? secondaryBackground; + + /// Gives the app an opportunity to confirm or veto a pending dismissal. + /// + /// If the returned Future completes true, then this widget will be + /// dismissed, otherwise it will be moved back to its original location. + /// + /// If the returned Future completes to false or null the [onSwipe] + /// callback will not run. + final ConfirmSwipeCallback? confirmSwipe; + + /// Called when the widget has been dismissed, after finishing resizing. + final SwipeDirectionCallback onSwipe; + + /// The direction in which the widget can be dismissed. + final SwipeDirection direction; + + /// The offset threshold the item has to be dragged in order to be considered + /// dismissed. + /// + /// Represented as a fraction, e.g. if it is 0.4 (the default), then the item + /// has to be dragged at least 40% towards one direction to be considered + /// dismissed. Clients can define different thresholds for each dismiss + /// direction. + /// + /// Flinging is treated as being equivalent to dragging almost to 1.0, so + /// flinging can dismiss an item past any threshold less than 1.0. + /// + /// Setting a threshold of 1.0 (or greater) prevents a drag in the given + /// [SwipeDirection] even if it would be allowed by the [direction] + /// property. + /// + /// See also: + /// + /// * [direction], which controls the directions in which the items can + /// be dismissed. + final Map dismissThresholds; + + /// The maximum horizontal offset the item can move to/ + /// + /// Represented as a fraction, e.g. if it is 0.4 (the default), then the + /// item can be moved at maximum 40% of item's width. + final double maxOffset; + + /// Defines the duration for card to dismiss or to come back to original position if not dismissed. + final Duration movementDuration; + + /// Defines the end offset across the main axis after the card is dismissed. + /// + /// If non-zero value is given then widget moves in cross direction depending on whether + /// it is positive or negative. + final double crossAxisEndOffset; + + /// Defines pointer types which are allowed to trigger swipe gesture. + /// + /// Defaults to {PointerDeviceKind.touch, PointerDeviceKind.invertedStylus, PointerDeviceKind.stylus} + final Set allowedPointerKinds; + + /// Determines the way that drag start behavior is handled. + /// + /// If set to [DragStartBehavior.start], the drag gesture used to dismiss a + /// dismissible will begin upon the detection of a drag gesture. If set to + /// [DragStartBehavior.down] it will begin when a down event is first detected. + /// + /// In general, setting this to [DragStartBehavior.start] will make drag + /// animation smoother and setting it to [DragStartBehavior.down] will make + /// drag behavior feel slightly more reactive. + /// + /// By default, the drag start behavior is [DragStartBehavior.start]. + /// + /// See also: + /// + /// * [DragGestureRecognizer.dragStartBehavior], which gives an example for the different behaviors. + final DragStartBehavior dragStartBehavior; + + @override + State createState() => _SwipeableState(); +} + +class _SwipeableClipper extends CustomClipper { + _SwipeableClipper({ + required this.moveAnimation, + }) : super(reclip: moveAnimation); + + final Animation moveAnimation; + + @override + Rect getClip(final Size size) { + final offset = moveAnimation.value.dx * size.width; + if (offset < 0) { + return Rect.fromLTRB(size.width + offset, 0.0, size.width, size.height); + } + return Rect.fromLTRB(0.0, 0.0, offset, size.height); + } + + @override + Rect getApproximateClipRect(final Size size) => getClip(size); + + @override + bool shouldReclip(final _SwipeableClipper oldClipper) => + oldClipper.moveAnimation.value != moveAnimation.value; +} + +enum _FlingGestureKind { none, forward, reverse } + +class _SwipeableState extends State + with TickerProviderStateMixin, AutomaticKeepAliveClientMixin { + @override + void initState() { + _moveController = + AnimationController(duration: widget.movementDuration, vsync: this) + ..addStatusListener(_handleDismissStatusChanged); + _updateMoveAnimation(); + + super.initState(); + } + + late AnimationController _moveController; + late Animation _moveAnimation; + + double _dragExtent = 0.0; + bool _dragUnderway = false; + Size? _sizePriorToCollapse; + + bool _isTouch = true; + + // Minimum global X where swipe is allowed to start + double? _minX; + // Maximum global X where swipe is allowed to start + double? _maxX; + // Screen width reference that helped to compute _minX and _maxX + // used to check if insets should be updated or not + double? _widthReference; + + @override + bool get wantKeepAlive => _moveController.isAnimating == true; + + @override + void dispose() { + _moveController.dispose(); + super.dispose(); + } + + SwipeDirection _extentToDirection(final double extent) { + if (extent == 0.0) { + return SwipeDirection.none; + } + switch (Directionality.of(context)) { + case TextDirection.rtl: + return extent < 0 + ? SwipeDirection.startToEnd + : SwipeDirection.endToStart; + case TextDirection.ltr: + return extent > 0 + ? SwipeDirection.startToEnd + : SwipeDirection.endToStart; + } + } + + SwipeDirection get _swipeDirection => _extentToDirection(_dragExtent); + + bool get _isActive => _dragUnderway || _moveController.isAnimating; + + double get _overallDragAxisExtent { + final size = context.size; + return size?.width ?? 0.0; + } + + void _handlePointerDown(final PointerDownEvent event) { + final xPos = event.position.dx; + + var validTouch = widget.allowedPointerKinds.contains(event.kind); + + // Check if touch was performed after minX and before maxX to avoid system + // gesture insets + if (validTouch && _minX != null) { + validTouch = xPos > _minX!; + } + + if (validTouch && _maxX != null) { + validTouch = xPos < _maxX!; + } + + setState(() { + _isTouch = validTouch; + }); + } + + void _handleDragStart(final DragStartDetails details) { + _dragUnderway = true; + if (_moveController.isAnimating) { + _dragExtent = + _moveController.value * _overallDragAxisExtent * _dragExtent.sign; + _moveController.stop(); + } else { + _dragExtent = 0.0; + _moveController.value = 0.0; + } + setState(() { + _updateMoveAnimation(); + }); + } + + void _handleDragUpdate(final DragUpdateDetails details) { + if (!_isActive || _moveController.isAnimating) { + return; + } + + final delta = details.primaryDelta ?? 0.0; + final oldDragExtent = _dragExtent; + switch (widget.direction) { + case SwipeDirection.none: + return; + + case SwipeDirection.horizontal: + _dragExtent += delta; + break; + + case SwipeDirection.endToStart: + switch (Directionality.of(context)) { + case TextDirection.rtl: + if (_dragExtent + delta > 0) { + _dragExtent += delta; + } + break; + case TextDirection.ltr: + if (_dragExtent + delta < 0) { + _dragExtent += delta; + } + break; + } + break; + + case SwipeDirection.startToEnd: + switch (Directionality.of(context)) { + case TextDirection.rtl: + if (_dragExtent + delta < 0) { + _dragExtent += delta; + } + break; + case TextDirection.ltr: + if (_dragExtent + delta > 0) { + _dragExtent += delta; + } + break; + } + break; + } + if (oldDragExtent.sign != _dragExtent.sign) { + setState(() { + _updateMoveAnimation(); + }); + } + if (!_moveController.isAnimating) { + _moveController.value = _dragExtent.abs() / _overallDragAxisExtent; + } + } + + void _updateMoveAnimation() { + final end = _dragExtent.sign; + _moveAnimation = _moveController.drive( + Tween( + begin: Offset.zero, + end: Offset(widget.maxOffset * end, widget.crossAxisEndOffset), + ), + ); + } + + _FlingGestureKind _describeFlingGesture(final Velocity velocity) { + if (_dragExtent == 0.0) { + // If it was a fling, then it was a fling that was let loose at the exact + // middle of the range (i.e. when there's no displacement). In that case, + // we assume that the user meant to fling it back to the center, as + // opposed to having wanted to drag it out one way, then fling it past the + // center and into and out the other side. + return _FlingGestureKind.none; + } + final vx = velocity.pixelsPerSecond.dx; + final vy = velocity.pixelsPerSecond.dy; + SwipeDirection flingDirection; + // Verify that the fling is in the generally right direction and fast enough. + if (vx.abs() - vy.abs() < _kMinFlingVelocityDelta || + vx.abs() < _kMinFlingVelocity) { + return _FlingGestureKind.none; + } + assert(vx != 0.0); + flingDirection = _extentToDirection(vx); + + if (flingDirection == _swipeDirection) { + return _FlingGestureKind.forward; + } + return _FlingGestureKind.reverse; + } + + Future _handleDragEnd(final DragEndDetails details) async { + if (!_isActive || _moveController.isAnimating) { + return; + } + _dragUnderway = false; + if (_moveController.isCompleted && + await _confirmStartSwipeAnimation() == true) { + _startSwipeAnimation(); + return; + } + final flingVelocity = details.velocity.pixelsPerSecond.dx; + switch (_describeFlingGesture(details.velocity)) { + case _FlingGestureKind.forward: + assert(_dragExtent != 0.0); + assert(!_moveController.isDismissed); + if ((widget.dismissThresholds[_swipeDirection] ?? _kDismissThreshold) >= + 1.0) { + await _moveController.reverse(); + break; + } + _dragExtent = flingVelocity.sign; + await _moveController.fling( + velocity: flingVelocity.abs() * _kFlingVelocityScale, + ); + break; + case _FlingGestureKind.reverse: + assert(_dragExtent != 0.0); + assert(!_moveController.isDismissed); + _dragExtent = flingVelocity.sign; + await _moveController.fling( + velocity: -flingVelocity.abs() * _kFlingVelocityScale, + ); + break; + case _FlingGestureKind.none: + if (!_moveController.isDismissed) { + // we already know it's not completed, we check that above + if (_moveController.value > + (widget.dismissThresholds[_swipeDirection] ?? + _kDismissThreshold)) { + await _moveController.forward(); + } else { + await _moveController.reverse(); + } + } + break; + } + } + + Future _handleDismissStatusChanged(final AnimationStatus status) async { + if (status == AnimationStatus.completed && !_dragUnderway) { + if (await _confirmStartSwipeAnimation() == true) { + _startSwipeAnimation(); + } else { + await _moveController.reverse(); + } + } + updateKeepAlive(); + } + + Future _confirmStartSwipeAnimation() async { + if (widget.confirmSwipe != null) { + final direction = _swipeDirection; + return widget.confirmSwipe!(direction); + } + return true; + } + + void _startSwipeAnimation() { + assert(_moveController.isCompleted); + assert(_sizePriorToCollapse == null); + + final direction = _swipeDirection; + widget.onSwipe(direction); + + _moveController.reverse(); + } + + @override + Widget build(final BuildContext context) { + super.build(context); // See AutomaticKeepAliveClientMixin. + + assert(debugCheckHasDirectionality(context)); + + var background = widget.background; + if (widget.secondaryBackground != null) { + final direction = _swipeDirection; + if (direction == SwipeDirection.endToStart) { + background = widget.secondaryBackground; + } + } + + // Get system screen size and system gesture insets + // to avoid starting a swipe in this areas + final MediaQueryData? mediaQuery = MediaQuery.maybeOf(context); + if (mediaQuery != null) { + if (_widthReference == null || _widthReference != mediaQuery.size.width) { + WidgetsBinding.instance.addPostFrameCallback((final _) { + // IdealChat SWIPEMOUNT_1106: the message may be gone by the next + // frame (fast AI messages); setState on an unmounted State threw + // "Null check operator used on a null value" every frame and the + // timeline stayed blank. + if (!mounted) return; + setState(() { + _widthReference = mediaQuery.size.width; + _minX = mediaQuery.systemGestureInsets.left; + _maxX = + mediaQuery.size.width - mediaQuery.systemGestureInsets.right; + }); + }); + } + } + + Widget content = SlideTransition( + position: _moveAnimation, + child: widget.child, + ); + + if (background != null) { + content = Stack( + children: [ + if (!_moveAnimation.isDismissed) + Positioned.fill( + child: ClipRect( + clipper: _SwipeableClipper( + moveAnimation: _moveAnimation, + ), + child: background, + ), + ), + content, + ], + ); + } + // We are not swiping but we may be being dragging in widget.direction. + return Listener( + onPointerDown: _handlePointerDown, + child: GestureDetector( + onHorizontalDragStart: _isTouch ? _handleDragStart : null, + onHorizontalDragUpdate: _isTouch ? _handleDragUpdate : null, + onHorizontalDragEnd: _isTouch ? _handleDragEnd : null, + behavior: HitTestBehavior.opaque, + dragStartBehavior: widget.dragStartBehavior, + child: content, + ), + ); + } +} diff --git a/vendor/swipe_to_action/lib/swipe_to_action.dart b/vendor/swipe_to_action/lib/swipe_to_action.dart new file mode 100644 index 0000000..22ac3c3 --- /dev/null +++ b/vendor/swipe_to_action/lib/swipe_to_action.dart @@ -0,0 +1,3 @@ +library swipe_to_action; + +export 'src/swipeable.dart'; diff --git a/vendor/swipe_to_action/pubspec.yaml b/vendor/swipe_to_action/pubspec.yaml new file mode 100644 index 0000000..b06fa31 --- /dev/null +++ b/vendor/swipe_to_action/pubspec.yaml @@ -0,0 +1,25 @@ +name: swipe_to_action +description: A widget which can be used to call functions when the wrapped child is dragged or flinged. +version: 0.3.0 +homepage: https://inex.dev/inex/swipe_to_action + +environment: + sdk: ">=2.12.0 <4.0.0" + flutter: ">=2.0.0" + +dependencies: + flutter: + sdk: flutter + flutter_web_plugins: + sdk: flutter + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^5.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter. +flutter: diff --git a/web/config.json b/web/config.json index 1471986..1c59182 100644 --- a/web/config.json +++ b/web/config.json @@ -1,7 +1,9 @@ { - "applicationName": "idealchat2001", + "applicationName": "家里的聊天", "defaultHomeserver": "ideal2001.com", "presetHomeserver": "ideal2001.com", - "welcomeText": "登录 ideal2001.com。只填用户名和密码,不用填服务器。", - "website": "https://ideal2001.com" + "welcomeText": "家人和 AI 助手,一起聊天、一起做事。", + "website": "https://ideal2001.com", + "colorSchemeSeedInt": 4279813822, + "logoUrl": "https://ideal2001.com/app/icons/Icon-192.png" } diff --git a/web/favicon.png b/web/favicon.png index 491bd96..c7ef0e7 100644 Binary files a/web/favicon.png and b/web/favicon.png differ diff --git a/web/icons/Icon-16.png b/web/icons/Icon-16.png index 491bd96..c7ef0e7 100644 Binary files a/web/icons/Icon-16.png and b/web/icons/Icon-16.png differ diff --git a/web/icons/Icon-192.png b/web/icons/Icon-192.png index ab6738c..0772b53 100644 Binary files a/web/icons/Icon-192.png and b/web/icons/Icon-192.png differ diff --git a/web/icons/Icon-32.png b/web/icons/Icon-32.png index 81c9e1c..12df988 100644 Binary files a/web/icons/Icon-32.png and b/web/icons/Icon-32.png differ diff --git a/web/icons/Icon-48.png b/web/icons/Icon-48.png index 835705d..27472ca 100644 Binary files a/web/icons/Icon-48.png and b/web/icons/Icon-48.png differ diff --git a/web/icons/Icon-512.png b/web/icons/Icon-512.png index f20d124..0b32447 100644 Binary files a/web/icons/Icon-512.png and b/web/icons/Icon-512.png differ diff --git a/web/icons/Icon-maskable-192.png b/web/icons/Icon-maskable-192.png index adc053d..702fb3c 100644 Binary files a/web/icons/Icon-maskable-192.png and b/web/icons/Icon-maskable-192.png differ diff --git a/web/icons/Icon-maskable-512.png b/web/icons/Icon-maskable-512.png index 44a9d1f..af68066 100644 Binary files a/web/icons/Icon-maskable-512.png and b/web/icons/Icon-maskable-512.png differ diff --git a/web/icons/apple-touch-icon.png b/web/icons/apple-touch-icon.png index 16f8962..acd947d 100644 Binary files a/web/icons/apple-touch-icon.png and b/web/icons/apple-touch-icon.png differ diff --git a/web/index.html b/web/index.html index cd86eb4..dbda8dd 100644 --- a/web/index.html +++ b/web/index.html @@ -26,7 +26,7 @@ - + @@ -34,15 +34,47 @@ - idealchat2001 + IdealChat + + + + + + + + + +
+ +
加载中…第一次打开要下载约 12MB,请稍等
+ +
+