diff --git a/lib/chat/chat_screen.dart b/lib/chat/chat_screen.dart index ee8cf6676..f065db9e2 100644 --- a/lib/chat/chat_screen.dart +++ b/lib/chat/chat_screen.dart @@ -3,7 +3,6 @@ import 'dart:math' as math; import 'package:flutter/foundation.dart' show kIsWeb; import 'package:bao_editor/textmate/textmate_syntax.dart' show TextMateSyntax; -import 'package:flutter/gestures.dart' show kDoubleTapTimeout; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; @@ -336,10 +335,10 @@ class _ChatScreenState extends State late final ChatSession _session = widget.session ?? ChatSession(); final GlobalKey _composerKey = GlobalKey(); - /// The suggested reply just put in the composer: its bar stays a double - /// click's time more, for a second click to send it. - String? _pickedReply; - Timer? _pickedReplyFor; + /// The suggested replies put in the composer, as put in, each on a line: + /// their bar stays while it holds just them, for more to be put in beside + /// them, or a second click to send one. + List _pickedReplies = const []; final GlobalKey _historyKey = GlobalKey(); bool _contextPanelOpen = false; bool _renaming = false; @@ -527,7 +526,6 @@ class _ChatScreenState extends State @override void dispose() { - _pickedReplyFor?.cancel(); _backMinimapRoom.dispose(); _session.removeListener(_checkStarting); _session.removeListener(_followPlan); @@ -817,35 +815,49 @@ class _ChatScreenState extends State ); } - /// What the agent suggests the user send next, while nothing is typed: - /// one picked is put in the composer, to be edited and sent. + /// What the agent suggests the user send next, while nothing is typed + /// but those picked: each picked is put in the composer, on a line of its + /// own, to be edited and sent with the others. Widget? _buildReplySuggestions() { final suggestions = _session.replySuggestions; if (suggestions.isEmpty) return null; final draft = _session.draft; - final picked = _pickedReply != null && draft.content == _pickedReply; - if (!picked && + final picked = + _pickedReplies.isNotEmpty && + draft.images.isEmpty && + draft.content == _pickedReplies.join('\n') + ? _pickedReplies + : const []; + if (picked.isEmpty && ((draft.content?.trim().isNotEmpty ?? false) || draft.images.isNotEmpty)) { return null; } + // In place of what the composer holds: only those picked, or nothing. + void putIn(List replies) { + _composerKey.currentState?.clear(); + if (replies.isNotEmpty) draft.restore(replies.join('\n'), const []); + setState(() => _pickedReplies = replies); + } + return ReplySuggestionBar( suggestions: suggestions, + picked: picked, playKey: '${identityHashCode(_session)}\u0000${suggestions.join('\u0000')}', - onPick: (said) { - draft.restore(said, const []); - _pickedReplyFor?.cancel(); - setState(() => _pickedReply = said); - _pickedReplyFor = Timer(kDoubleTapTimeout, () { - if (mounted) setState(() => _pickedReply = null); - }); - }, + onPick: (said) => putIn([said]), + onToggle: (said) => putIn( + picked.contains(said) + ? [ + for (final other in picked) + if (other != said) other, + ] + : [...picked, said], + ), onSend: (said) { - _pickedReplyFor?.cancel(); // Put in at the first click: sent now, not left there too. - if (_pickedReply == said) _composerKey.currentState?.clear(); - _pickedReply = null; + if (picked.isNotEmpty) _composerKey.currentState?.clear(); + setState(() => _pickedReplies = const []); _session.send( ComposerMessage(text: said), editor: widget.openEditor, diff --git a/lib/chat/panels/reply_suggestion_bar.dart b/lib/chat/panels/reply_suggestion_bar.dart index c93098d52..f903ccb0d 100644 --- a/lib/chat/panels/reply_suggestion_bar.dart +++ b/lib/chat/panels/reply_suggestion_bar.dart @@ -1,16 +1,21 @@ import 'package:flutter/gestures.dart' show kDoubleTapTimeout; import 'package:flutter/material.dart'; +import '../../ide/ide_commands.dart' show ideUsesMacKeys; import '../../ide/ide_hover.dart'; import '../../l10n/l10n.dart'; +import '../../platform/held_keys.dart'; import '../../theme/app_theme.dart'; +import '../../theme/workbench_theme.dart' show themeColors; import '../widgets/hover_builder.dart'; /// What the agent suggests the user send next (see ReplySuggestions), on /// top of what is over the empty composer: each a pill, put in the -/// composer at a click ([onPick]) to be edited and sent, sent as it is at a -/// second click soon after ([onSend]; the bar is kept that long); each -/// says so on hover. They flow as words do, but +/// composer at a click ([onPick]) to be edited and sent, in place of those +/// put in before; put in beside them, or taken out, at a click with ⌘ or +/// Ctrl held ([onToggle]), as files are picked; sent as it is at a second +/// click soon after ([onSend]). Each says so on hover; those in the +/// composer ([picked]) stand out. They flow as words do, but /// piled on the composer: on to the line above when the row is full; /// one wider than the row, its text on more lines. /// @@ -23,14 +28,20 @@ class ReplySuggestionBar extends StatefulWidget { super.key, required this.suggestions, required this.onPick, + required this.onToggle, required this.onSend, + this.picked = const [], this.playKey, }); final List suggestions; final ValueChanged onPick; + final ValueChanged onToggle; final ValueChanged onSend; + /// Those in the composer, as put in. + final List picked; + /// What they are shown for (a conversation's, and these suggestions): /// played in once for each; null, each time. final String? playKey; @@ -113,7 +124,9 @@ class _ReplySuggestionBarState extends State still: still, child: _Pill( text: said, + picked: widget.picked.contains(said), onTap: () => widget.onPick(said), + onToggle: () => widget.onToggle(said), onDoubleTap: () => widget.onSend(said), ), ), @@ -160,12 +173,16 @@ class _Entering extends AnimatedWidget { class _Pill extends StatefulWidget { const _Pill({ required this.text, + required this.picked, required this.onTap, + required this.onToggle, required this.onDoubleTap, }); final String text; + final bool picked; final VoidCallback onTap; + final VoidCallback onToggle; final VoidCallback onDoubleTap; @override @@ -177,8 +194,18 @@ class _PillState extends State<_Pill> { /// it is sent. A click is taken at once, not once no second one came. Duration? _clickedAt; - void _click() { + Future _click() async { final at = _clock.elapsed; + // ⌘ or Ctrl held, on any platform: put in beside the others, or taken + // out; clicked twice so, back as it was, not sent. Held as the system + // has it, not only the app: the app's may have missed its key going up. + if (await HeldKeys.commandOrControl()) { + if (!mounted) return; + _clickedAt = null; + widget.onToggle(); + return; + } + if (!mounted) return; final before = _clickedAt; if (before != null && at - before <= kDoubleTapTimeout) { _clickedAt = null; @@ -192,8 +219,19 @@ class _PillState extends State<_Pill> { @override Widget build(BuildContext context) { final line = widget.text.replaceAll(RegExp(r'\s+'), ' ').trim(); + // In the composer: as a picked option in the panels, a list's + // selection in it, the focus border around it. Hovered, its selection + // deeper, not greyed by the hover's tint. + final colors = themeColors; + final selection = colors['list.activeSelectionBackground']; + final fill = widget.picked + ? Color.alphaBlend(selection, AppColors.bubbleFill) + : AppColors.bubbleFill; + final hoveredFill = widget.picked + ? Color.alphaBlend(selection, fill) + : Color.alphaBlend(AppColors.bubbleHover, fill); return IdeHover( - message: context.l10n.replySuggestionHint, + message: context.l10n.replySuggestionHint(ideUsesMacKeys ? '⌘' : 'Ctrl'), position: IdeHoverPosition.above, child: HoverBuilder( builder: (context, hovered) => GestureDetector( @@ -209,19 +247,23 @@ class _PillState extends State<_Pill> { // Hovered, the hover's tint over the fill, not in its // place: the tint is faint, and on its way to it the // fill would turn see-through, the page dark through it. - color: hovered - ? Color.alphaBlend( - AppColors.bubbleHover, - AppColors.bubbleFill, - ) - : AppColors.bubbleFill, + color: hovered ? hoveredFill : fill, // A pill on one line; on more, its corners as round. borderRadius: BorderRadius.circular(13), - border: Border.all(color: AppColors.bubbleBorder()), + border: Border.all( + color: widget.picked + ? colors['focusBorder'] + : AppColors.bubbleBorder(), + ), ), child: Text( line, - style: TextStyle(color: AppColors.text, fontSize: 12.5), + style: TextStyle( + color: widget.picked + ? colors['list.activeSelectionForeground'] + : AppColors.text, + fontSize: 12.5, + ), ), ), ), diff --git a/lib/chat/reply_suggestions.dart b/lib/chat/reply_suggestions.dart index 75df4ac8e..dc31e7658 100644 --- a/lib/chat/reply_suggestions.dart +++ b/lib/chat/reply_suggestions.dart @@ -6,7 +6,7 @@ abstract final class ReplySuggestions { static const tag = 'reply_suggestion'; /// The most shown. - static const max = 3; + static const max = 4; /// The longest shown, in characters: a line to send, not a message. static const maxLength = 80; @@ -20,12 +20,12 @@ abstract final class ReplySuggestions { static const on = 'Reply suggestions are on: the user turned them on ' 'in BaoCode. When you finish your turn and hand back to them, end your ' - 'last message with two or three things they might send you next: in ' + 'last message with two to four things they might send you next: in ' 'their voice and their language, short (about 20 Chinese characters, ' - 'or 10 words, at most), each a different way on (go ahead, change ' - 'course, ask). They pick one to edit and send. The app shows them apart ' - 'from your message: do not speak of them. None while you are still ' - 'working.\n' + 'or 10 words, at most), different ways on (go ahead, change course, ' + 'ask); some may go well together. They pick what to send, edit it and ' + 'send it. The app shows them apart from your message: do not speak of ' + 'them. None while you are still working.\n' '\n' 'Write them as plain text in your reply, not as a tool call: each on a ' 'line of its own, between exactly <$tag> and , with nothing ' @@ -47,7 +47,7 @@ abstract final class ReplySuggestions { /// With each message after, a word. static const stillOn = 'Reply suggestions still on: end your turn with two ' - 'or three short ones, as plain text, each on its own line: ' + 'to four short ones, as plain text, each on its own line: ' '<$tag>….'; /// Once, when they turn them off. diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 117c9b7a4..d71d2eb68 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -2200,9 +2200,14 @@ "queuedEdit": "Take back to edit", "queuedSendNow": "Stop the agent and send this now", "queuedRemove": "Remove from the queue", - "replySuggestionHint": "Click to put it in the input, double-click to send it", + "replySuggestionHint": "Click to put it in the input, double-click to send it, {key}-click to pick more than one", "@replySuggestionHint": { - "description": "Hover of a reply the agent suggests, over the composer." + "description": "Hover of a reply the agent suggests, over the composer. {key} is ⌘ on macOS, Ctrl elsewhere.", + "placeholders": { + "key": { + "type": "String" + } + } }, "stopConfirmMessage": "Stop the agent?", "stopConfirmDetail": "{count, plural, =1{The task running in the background will stop too.} other{The {count} tasks running in the background will stop too.}}", @@ -2592,7 +2597,7 @@ "@generalSettingsPromptSuggestions": { "description": "Settings → General switch: whether the agent suggests, at the end of each turn, what the user might send next, shown over the composer." }, - "generalSettingsPromptSuggestionsDescription": "After each turn, two or three things you might send next, over the composer: click one to put it in the input and edit it, double-click to send it as it is; Tab in an empty input takes the first. The agent writes them at the end of its reply, with no extra request. Applies from the next message.", + "generalSettingsPromptSuggestionsDescription": "After each turn, two to four things you might send next, over the composer: click one to put it in the input and edit it, double-click to send it as it is; click with ⌘ or Ctrl held to put in more than one, each on its own line; Tab in an empty input takes the first. The agent writes them at the end of its reply, with no extra request. Applies from the next message.", "generalSettingsCommitAttributionLabel": "Commit Attribution: {name}", "@generalSettingsCommitAttributionLabel": { "description": "The commit attribution dropdown, as read out: its setting and the choice in effect.", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 2c93d6778..86598c120 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -5708,11 +5708,11 @@ abstract class AppLocalizations { /// **'Remove from the queue'** String get queuedRemove; - /// Hover of a reply the agent suggests, over the composer. + /// Hover of a reply the agent suggests, over the composer. {key} is ⌘ on macOS, Ctrl elsewhere. /// /// In en, this message translates to: - /// **'Click to put it in the input, double-click to send it'** - String get replySuggestionHint; + /// **'Click to put it in the input, double-click to send it, {key}-click to pick more than one'** + String replySuggestionHint(String key); /// No description provided for @stopConfirmMessage. /// @@ -6413,7 +6413,7 @@ abstract class AppLocalizations { /// No description provided for @generalSettingsPromptSuggestionsDescription. /// /// In en, this message translates to: - /// **'After each turn, two or three things you might send next, over the composer: click one to put it in the input and edit it, double-click to send it as it is; Tab in an empty input takes the first. The agent writes them at the end of its reply, with no extra request. Applies from the next message.'** + /// **'After each turn, two to four things you might send next, over the composer: click one to put it in the input and edit it, double-click to send it as it is; click with ⌘ or Ctrl held to put in more than one, each on its own line; Tab in an empty input takes the first. The agent writes them at the end of its reply, with no extra request. Applies from the next message.'** String get generalSettingsPromptSuggestionsDescription; /// The commit attribution dropdown, as read out: its setting and the choice in effect. diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index ca3932c5f..7cc0e1ea3 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -3375,8 +3375,9 @@ class AppLocalizationsEn extends AppLocalizations { String get queuedRemove => 'Remove from the queue'; @override - String get replySuggestionHint => - 'Click to put it in the input, double-click to send it'; + String replySuggestionHint(String key) { + return 'Click to put it in the input, double-click to send it, $key-click to pick more than one'; + } @override String get stopConfirmMessage => 'Stop the agent?'; @@ -3825,7 +3826,7 @@ class AppLocalizationsEn extends AppLocalizations { @override String get generalSettingsPromptSuggestionsDescription => - 'After each turn, two or three things you might send next, over the composer: click one to put it in the input and edit it, double-click to send it as it is; Tab in an empty input takes the first. The agent writes them at the end of its reply, with no extra request. Applies from the next message.'; + 'After each turn, two to four things you might send next, over the composer: click one to put it in the input and edit it, double-click to send it as it is; click with ⌘ or Ctrl held to put in more than one, each on its own line; Tab in an empty input takes the first. The agent writes them at the end of its reply, with no extra request. Applies from the next message.'; @override String generalSettingsCommitAttributionLabel(String name) { diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 8cd972f29..fc341139a 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -3247,7 +3247,9 @@ class AppLocalizationsZh extends AppLocalizations { String get queuedRemove => '移出队列'; @override - String get replySuggestionHint => '单击放进输入框,双击直接发送'; + String replySuggestionHint(String key) { + return '单击放进输入框,双击直接发送,按住 $key 单击可多选'; + } @override String get stopConfirmMessage => '要停止 Agent 吗?'; @@ -3673,7 +3675,7 @@ class AppLocalizationsZh extends AppLocalizations { @override String get generalSettingsPromptSuggestionsDescription => - '每轮结束后,在输入框上方给出两三句你可能想发的话:单击放进输入框润色,双击直接发送;输入框空着时按 Tab 采用第一句。由 Agent 在回复末尾顺手写出,不额外请求模型。从下一条消息起生效。'; + '每轮结束后,在输入框上方给出两到四句你可能想发的话:单击放进输入框润色,双击直接发送;按住 ⌘ 或 Ctrl 单击可多选,每句一行;输入框空着时按 Tab 采用第一句。由 Agent 在回复末尾顺手写出,不额外请求模型。从下一条消息起生效。'; @override String generalSettingsCommitAttributionLabel(String name) { diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 88c2fdc62..ccc12d900 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -935,7 +935,7 @@ "queuedEdit": "撤回并编辑", "queuedSendNow": "中断当前任务,立即发送", "queuedRemove": "移出队列", - "replySuggestionHint": "单击放进输入框,双击直接发送", + "replySuggestionHint": "单击放进输入框,双击直接发送,按住 {key} 单击可多选", "stopConfirmMessage": "要停止 Agent 吗?", "stopConfirmDetail": "{count, plural, other{后台运行中的 {count} 个任务也会一并停止。}}", "stopConfirmStop": "停止", @@ -1052,7 +1052,7 @@ "generalSettingsQueuedAfterTurn": "当前任务完成后依次执行", "generalSettingsQueuedDuringTurn": "插入当前任务", "generalSettingsPromptSuggestions": "推荐回复", - "generalSettingsPromptSuggestionsDescription": "每轮结束后,在输入框上方给出两三句你可能想发的话:单击放进输入框润色,双击直接发送;输入框空着时按 Tab 采用第一句。由 Agent 在回复末尾顺手写出,不额外请求模型。从下一条消息起生效。", + "generalSettingsPromptSuggestionsDescription": "每轮结束后,在输入框上方给出两到四句你可能想发的话:单击放进输入框润色,双击直接发送;按住 ⌘ 或 Ctrl 单击可多选,每句一行;输入框空着时按 Tab 采用第一句。由 Agent 在回复末尾顺手写出,不额外请求模型。从下一条消息起生效。", "generalSettingsCommitAttributionLabel": "提交署名: {name}", "generalSettingsAttributionAgent": "跟随 Agent", "generalSettingsAttributionAgentDetail": "Agent 自带的署名(如 Claude Code 的),或你在 ~/.claude/settings.json 中设置的 attribution。", diff --git a/lib/main.dart b/lib/main.dart index fa00ad452..582e87992 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -90,6 +90,7 @@ import 'platform/native_md_clipboard.dart'; import 'platform/app_binding.dart'; import 'platform/app_platform.dart'; import 'platform/data_dir.dart'; +import 'platform/held_keys.dart'; import 'platform/error_log.dart'; import 'platform/event_log.dart'; import 'platform/open_requests.dart'; @@ -389,6 +390,9 @@ Future main(List arguments) async { .layoutAtLaunch(workspace.layout); } WindowControls.trackActiveView(); + // The modifiers held as the system has them, not one the app missed + // going up. + if (WindowControls.isDesktop) HeldKeys.start(); // What an editor copies, its tags and all, on the clipboard itself. if (WindowControls.isDesktop) { MdClipboard.instance = const NativeMdClipboard(); diff --git a/lib/platform/held_keys.dart b/lib/platform/held_keys.dart new file mode 100644 index 000000000..8f158e0d8 --- /dev/null +++ b/lib/platform/held_keys.dart @@ -0,0 +1,130 @@ +import 'dart:async'; + +import 'package:flutter/gestures.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +import '../workspace/window_controls.dart'; +import 'event_log.dart'; + +/// The modifier keys held, as the system has them: to make the app's own +/// ([HardwareKeyboard]) right. +/// +/// The app's can keep one held after it went up, its key up lost (the +/// app out of front then, an input method or a system shortcut taking it). +/// The engine checks the system's modifiers at each mouse event, but +/// against what it has itself, not against the app's (macOS); on Windows +/// only Shift and Ctrl, as the pointer moves. Till the key was pressed +/// again, a click was then taken as ⌘- or Ctrl-clicked, a key typed as a +/// shortcut (1 typing nothing, N2S9TV9F). +/// +/// So the system is asked: as the app comes in front, at a press while the +/// app has one held, and before a click is taken as one with ⌘ or Ctrl +/// ([commandOrControl]). One the app has held and the system has not is +/// let go, and written to the event log (under `keys`). +abstract final class HeldKeys { + /// Each modifier the system tells of, by its name there (see the windows' + /// `heldModifiers`), and its keys, on either side. + static const _modifiers = { + 'shift': [LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.shiftRight], + 'control': [ + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.controlRight, + ], + 'alt': [LogicalKeyboardKey.altLeft, LogicalKeyboardKey.altRight], + 'meta': [LogicalKeyboardKey.metaLeft, LogicalKeyboardKey.metaRight], + }; + + static bool _started = false; + + /// How long the system is waited for: then the app's taken as it is. + static const _patience = Duration(milliseconds: 300); + + /// The system asked, from the app's start: on the desktop. + static void start() { + if (_started) return; + _started = true; + GestureBinding.instance.pointerRouter.addGlobalRoute((event) { + if (event is PointerDownEvent && _anyHeld) unawaited(sync('a press')); + }); + AppLifecycleListener(onResume: () => unawaited(sync('back in front'))); + } + + /// Whether ⌘ or Ctrl is held, either on any platform, for a click now: + /// the app's, made right by the system's first when the app has one held. + /// As the app has it where the system cannot be asked. + static Future commandOrControl() async { + final keyboard = HardwareKeyboard.instance; + if (!keyboard.isMetaPressed && !keyboard.isControlPressed) return false; + await sync('a click with ⌘ or Ctrl'); + return keyboard.isMetaPressed || keyboard.isControlPressed; + } + + /// Lets go of the modifiers the app has held and the system has not; + /// [why], for the log. + static Future sync(String why) async { + if (!_anyHeld) return; + final keyboard = HardwareKeyboard.instance; + final before = keyboard.physicalKeysPressed.toSet(); + final Map system; + try { + system = + await WindowControls.channelFor(0) + .invokeMapMethod('heldModifiers') + .timeout(_patience) ?? + const {}; + } on MissingPluginException { + return; + } on PlatformException { + return; + } on TimeoutException { + return; + } + // A key pressed or let go meanwhile: what was answered may be old. + final after = keyboard.physicalKeysPressed; + if (system.isEmpty || + after.length != before.length || + !before.containsAll(after)) { + return; + } + letGo(system, why); + } + + /// Lets go of the modifiers the app has held that [system] (each by its + /// name, held or not) has not: as their key up would. + @visibleForTesting + static void letGo(Map system, String why) { + final keyboard = HardwareKeyboard.instance; + final stale = {}; + for (final physical in keyboard.physicalKeysPressed) { + final logical = keyboard.lookUpLayout(physical); + if (logical == null) continue; + for (final MapEntry(key: name, value: keys) in _modifiers.entries) { + if (keys.contains(logical) && system[name] == false) { + stale[physical] = logical; + } + } + } + if (stale.isEmpty) return; + for (final MapEntry(key: physical, value: logical) in stale.entries) { + keyboard.handleKeyEvent( + KeyUpEvent( + physicalKey: physical, + logicalKey: logical, + timeStamp: Duration.zero, + synthesized: true, + ), + ); + } + final names = stale.values.map((key) => key.keyLabel).join(', '); + appEvent('keys', 'held for the app, not the system ($why): $names; let go'); + } + + static bool get _anyHeld { + final keyboard = HardwareKeyboard.instance; + return keyboard.isShiftPressed || + keyboard.isControlPressed || + keyboard.isAltPressed || + keyboard.isMetaPressed; + } +} diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc index 933159449..cee191a7d 100644 --- a/linux/runner/my_application.cc +++ b/linux/runner/my_application.cc @@ -253,7 +253,24 @@ static void window_method_call_cb(FlMethodChannel* channel, FlMethodCall* call, FlValue* args = fl_method_call_get_args(call); g_autoptr(FlMethodResponse) response = nullptr; - if (strcmp(name, "pickDirectory") == 0) { + if (strcmp(name, "heldModifiers") == 0) { + // The modifiers held now, as the system has them: the app's own may + // have missed one going up (see held_keys.dart). + GdkKeymap* keymap = gdk_keymap_get_for_display(gdk_display_get_default()); + const guint state = gdk_keymap_get_modifier_state(keymap); + g_autoptr(FlValue) result = fl_value_new_map(); + fl_value_set_string_take(result, "shift", + fl_value_new_bool((state & GDK_SHIFT_MASK) != 0)); + fl_value_set_string_take( + result, "control", fl_value_new_bool((state & GDK_CONTROL_MASK) != 0)); + fl_value_set_string_take(result, "alt", + fl_value_new_bool((state & GDK_MOD1_MASK) != 0)); + fl_value_set_string_take( + result, "meta", + fl_value_new_bool( + (state & (GDK_SUPER_MASK | GDK_MOD4_MASK | GDK_META_MASK)) != 0)); + response = FL_METHOD_RESPONSE(fl_method_success_response_new(result)); + } else if (strcmp(name, "pickDirectory") == 0) { GSList* names = choose_files(self->window, GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, "Open Folder", FALSE, nullptr, nullptr, FALSE); g_autoptr(FlValue) result = nullptr; diff --git a/macos/Runner/MainFlutterWindow.swift b/macos/Runner/MainFlutterWindow.swift index 4b017bbf0..b18084a51 100644 --- a/macos/Runner/MainFlutterWindow.swift +++ b/macos/Runner/MainFlutterWindow.swift @@ -288,6 +288,16 @@ class BaoWindow: NSWindow { /// The window controls Flutter asks this window for. func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { switch call.method { + case "heldModifiers": + // The modifiers held now, as the system has them: the app's own may + // have missed one going up (see held_keys.dart). + let flags = NSEvent.modifierFlags + result([ + "shift": flags.contains(.shift), + "control": flags.contains(.control), + "alt": flags.contains(.option), + "meta": flags.contains(.command), + ]) case "setAlwaysOnTop": // Floating: above other apps' windows, as a pinned window should be. level = (call.arguments as? Bool ?? false) ? .floating : .normal diff --git a/test/chat/reply_suggestion_bar_test.dart b/test/chat/reply_suggestion_bar_test.dart index 12d03605f..4374f7009 100644 --- a/test/chat/reply_suggestion_bar_test.dart +++ b/test/chat/reply_suggestion_bar_test.dart @@ -9,6 +9,7 @@ void main() { suggestions: const ['one', 'two', 'three'], playKey: key, onPick: (_) {}, + onToggle: (_) {}, onSend: (_) {}, ), ), diff --git a/test/chat/reply_suggestions_shot_test.dart b/test/chat/reply_suggestions_shot_test.dart index c21589a76..5e332bdaf 100644 --- a/test/chat/reply_suggestions_shot_test.dart +++ b/test/chat/reply_suggestions_shot_test.dart @@ -14,6 +14,7 @@ import 'package:baocode/kernel/mock/mock_kernels.dart'; import 'package:baocode/l10n/app_localizations.dart'; import 'package:baocode/theme/app_theme.dart'; import 'package:baocode/theme/code_font.dart'; +import 'package:baocode/theme/workbench_theme.dart'; import 'package:flutter/material.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; @@ -233,4 +234,64 @@ void main() { }, ); }, skip: _out == null); + + for (final (name, theme) in [ + ('6-picked', null), + ('7-picked-light', 'Bao Light'), + ('8-picked-dark', 'Bao Dark'), + ]) { + testWidgets('two picked with ⌘, one hovered: in the composer, a line ' + 'each (${theme ?? 'the default theme'})', (tester) async { + if (theme != null) { + final themes = WorkbenchThemeService.instance; + await tester.runAsync(themes.initialize); + await tester.runAsync(() => themes.setColorTheme(theme)); + } + final cli = FakeCli(); + final session = _scripted(cli); + await _shoot( + tester, + name, + const Size(720, 560), + session, + () async { + await tester.pump(); + _reply(cli, _answer, ['最大高度改成 8 行', '发送按钮挪到右下', '先不改了', '拖拽调高度也做']); + }, + then: () async { + // ⌘ held for the system too. + const window = MethodChannel('baocode/window'); + final messenger = tester.binding.defaultBinaryMessenger + ..setMockMethodCallHandler( + window, + (call) async => call.method == 'heldModifiers' + ? { + 'shift': false, + 'control': false, + 'alt': false, + 'meta': true, + } + : null, + ); + addTearDown(() => messenger.setMockMethodCallHandler(window, null)); + for (final said in ['最大高度改成 8 行', '拖拽调高度也做']) { + await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft); + await tester.tap(find.text(said, findRichText: true)); + await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft); + await tester.pump(); + } + final mouse = await tester.createGesture( + kind: PointerDeviceKind.mouse, + ); + addTearDown(mouse.removePointer); + await mouse.addPointer(location: Offset.zero); + await mouse.moveTo( + // The pill's, not the composer's. + tester.getCenter(find.text('拖拽调高度也做', findRichText: true).first), + ); + await tester.pump(const Duration(milliseconds: 300)); + }, + ); + }, skip: _out == null); + } } diff --git a/test/chat/reply_suggestions_test.dart b/test/chat/reply_suggestions_test.dart index 1a4da6e11..a7e3122a3 100644 --- a/test/chat/reply_suggestions_test.dart +++ b/test/chat/reply_suggestions_test.dart @@ -81,7 +81,7 @@ void main() { expect(ReplySuggestions.of(raw), isEmpty); }); - test('at most three, none too long', () { + test('at most four, none too long', () { final raw = [ 'ok', _said('a'), @@ -89,8 +89,9 @@ void main() { _said('b'), _said('c'), _said('d'), + _said('e'), ].join('\n'); - expect(ReplySuggestions.of(raw), ['a', 'b', 'c']); + expect(ReplySuggestions.of(raw), ['a', 'b', 'c', 'd']); }); test('all in one tag, a line each: each its own', () { diff --git a/test/kernel_ui_test.dart b/test/kernel_ui_test.dart index 0c946c8c2..cecb91a17 100644 --- a/test/kernel_ui_test.dart +++ b/test/kernel_ui_test.dart @@ -790,9 +790,8 @@ void main() { }); testWidgets('after a turn, its suggested replies show over the composer: ' - 'Tab takes the first, a click puts one in, a double click sends it', ( - tester, - ) async { + 'Tab takes the first, a click puts one in, ⌘ more, a double click ' + 'sends one', (tester) async { final session = await pumpSession(tester, MockKernels.claudeCode); session.send(const ComposerMessage(text: '把输入框改成随内容增高')); await tester.pump(); @@ -858,13 +857,79 @@ void main() { // At once, not once it is no double click. await tester.pump(); expect(editor.controller.text, MockScript.suggestions[1]); - // The bar kept for a second click till then; gone after. + // The bar kept while the composer holds just it, it picked there. + await tester.pump(kDoubleTapTimeout); + await tester.pump(); expect(bar, findsOneWidget); + expect(tester.widget(bar).picked, [ + MockScript.suggestions[1], + ]); + expect(session.isStreaming, isFalse); + + // ⌘ held, for the system too: another put in beside it, on a line of + // its own, as clicked. + final window = const MethodChannel('baocode/window'); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + window, + (call) async => call.method == 'heldModifiers' + ? {'shift': false, 'control': false, 'alt': false, 'meta': true} + : null, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + window, + null, + ), + ); + Future metaTap(String said) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft); + await tester.tap( + find.descendant( + of: bar, + matching: find.textContaining(said, findRichText: true), + ), + ); + await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft); + await tester.pump(); + } + + await metaTap(MockScript.suggestions[0]); + expect( + editor.controller.text, + '${MockScript.suggestions[1]}\n${MockScript.suggestions[0]}', + ); + // Clicked again so, not sent as a double click: taken out. + await metaTap(MockScript.suggestions[0]); + expect(session.isStreaming, isFalse); + expect(editor.controller.text, MockScript.suggestions[1]); + await tester.pump(kDoubleTapTimeout); + await metaTap(MockScript.suggestions[2]); + expect(tester.widget(bar).picked, [ + MockScript.suggestions[1], + MockScript.suggestions[2], + ]); + // A click without it: that one alone, in place of them. await tester.pump(kDoubleTapTimeout); + await tester.tap( + find.descendant( + of: bar, + matching: find.textContaining( + MockScript.suggestions[0], + findRichText: true, + ), + ), + ); + await tester.pump(); + expect(editor.controller.text, MockScript.suggestions[0]); + // Something typed after: gone, once faded. + editor.controller.replace( + editor.controller.length, + editor.controller.length, + ',然后', + ); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); expect(bar, findsNothing); - expect(session.isStreaming, isFalse); // A double click sends it as it is. editor.controller.replace(0, editor.controller.length, ''); diff --git a/test/platform/held_keys_test.dart b/test/platform/held_keys_test.dart new file mode 100644 index 000000000..7dfee6bfc --- /dev/null +++ b/test/platform/held_keys_test.dart @@ -0,0 +1,103 @@ +import 'dart:async'; + +import 'package:baocode/chat/panels/reply_suggestion_bar.dart'; +import 'package:baocode/platform/held_keys.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + const channel = MethodChannel('baocode/window'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + + /// The system's answer: [held] the modifiers held, the others not. + void system(Set held, {Future? after}) => + messenger.setMockMethodCallHandler(channel, (call) async { + expect(call.method, 'heldModifiers'); + await after; + return { + for (final name in ['shift', 'control', 'alt', 'meta']) + name: held.contains(name), + }; + }); + + tearDown(() => messenger.setMockMethodCallHandler(channel, null)); + + testWidgets('a modifier the app missed going up is let go', (tester) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); + // Up where the app did not hear: still held for it. + system({'shift'}); + expect(await HeldKeys.commandOrControl(), isFalse); + expect(HardwareKeyboard.instance.isMetaPressed, isFalse); + // One the system has held stays. + expect(HardwareKeyboard.instance.isShiftPressed, isTrue); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); + }); + + testWidgets('one held for both stays held', (tester) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + system({'control'}); + expect(await HeldKeys.commandOrControl(), isTrue); + expect(HardwareKeyboard.instance.isControlPressed, isTrue); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + }); + + testWidgets('the system not answering: as the app has it', (tester) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft); + messenger.setMockMethodCallHandler(channel, (_) async => null); + expect(await HeldKeys.commandOrControl(), isTrue); + await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft); + // Nothing held: not asked. + var asked = false; + messenger.setMockMethodCallHandler(channel, (_) async => asked = true); + expect(await HeldKeys.commandOrControl(), isFalse); + expect(asked, isFalse); + }); + + testWidgets('a key meanwhile: the answer left, maybe old', (tester) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft); + final answer = Completer(); + system(const {}, after: answer.future); + final held = HeldKeys.commandOrControl(); + await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); + answer.complete(); + expect(await held, isTrue); + await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); + await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft); + }); + + testWidgets('a suggested reply clicked with ⌘ held only for the app: ' + 'put in, not picked beside the others', (tester) async { + final picked = []; + final toggled = []; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ReplySuggestionBar( + suggestions: const ['one', 'two'], + onPick: picked.add, + onToggle: toggled.add, + onSend: (_) {}, + ), + ), + ), + ); + await tester.pump(const Duration(seconds: 1)); + await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft); + system(const {}); + await tester.tap(find.text('one')); + await tester.pump(); + expect(picked, ['one']); + expect(toggled, isEmpty); + + // Held for both: picked beside them. + await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft); + system({'meta'}); + await tester.tap(find.text('two')); + await tester.pump(); + expect(toggled, ['two']); + await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft); + }); +} diff --git a/windows/runner/window_channel.cpp b/windows/runner/window_channel.cpp index 8db5bb15d..81e947bdf 100644 --- a/windows/runner/window_channel.cpp +++ b/windows/runner/window_channel.cpp @@ -495,6 +495,24 @@ void WindowChannel::HandleMethodCall( const std::string& method = call.method_name(); const flutter::EncodableMap& arguments = Arguments(call.arguments()); + if (method == "heldModifiers") { + // The modifiers held now, as the system has them: the app's own may + // have missed one going up (see held_keys.dart). + const auto held = [](int key) { + return flutter::EncodableValue((::GetAsyncKeyState(key) & 0x8000) != 0); + }; + result->Success(flutter::EncodableValue(flutter::EncodableMap{ + {flutter::EncodableValue("shift"), held(VK_SHIFT)}, + {flutter::EncodableValue("control"), held(VK_CONTROL)}, + {flutter::EncodableValue("alt"), held(VK_MENU)}, + {flutter::EncodableValue("meta"), + flutter::EncodableValue( + ((::GetAsyncKeyState(VK_LWIN) | ::GetAsyncKeyState(VK_RWIN)) & + 0x8000) != 0)}, + })); + return; + } + if (method == "setAlwaysOnTop") { // Pinned: above other apps' windows, as a floating window should be. const bool on_top = Boolean(call.arguments(), false);