Skip to content

基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。

feat: customer keyboard shourtcut (#1508)

遥遥紫荆27592116b65e
diff --git a/lib/pages/my/my_page.dart b/lib/pages/my/my_page.dart
index ab384596..4bbec549 100644
--- a/lib/pages/my/my_page.dart
+++ b/lib/pages/my/my_page.dart
@@ -88,6 +88,14 @@ class _MyPageState extends State<MyPage> {
title: Text('弹幕设置', style: TextStyle(fontFamily: fontFamily)),
description: Text('设置弹幕相关参数', style: TextStyle(fontFamily: fontFamily)),
),
+ SettingsTile.navigation(
+ onPressed: (_) {
+ Modular.to.pushNamed('/settings/keyboard');
+ },
+ leading: const Icon(Icons.keyboard_rounded),
+ title: const Text('操作设置'),
+ description: const Text('设置播放器按键映射'),
+ ),
],
),
SettingsSection(
diff --git a/lib/pages/player/player_item.dart b/lib/pages/player/player_item.dart
index 0ef2c4a2..a05a1529 100644
--- a/lib/pages/player/player_item.dart
+++ b/lib/pages/player/player_item.dart
@@ -30,6 +30,10 @@ import 'package:kazumi/modules/danmaku/danmaku_episode_response.dart';
import 'package:kazumi/pages/player/player_item_surface.dart';
import 'package:mobx/mobx.dart' as mobx;
import 'package:kazumi/pages/my/my_controller.dart';
+import 'package:saver_gallery/saver_gallery.dart';
+
+
+
class PlayerItem extends StatefulWidget {
const PlayerItem({
@@ -68,6 +72,9 @@ class _PlayerItemState extends State<PlayerItem>
final HistoryController historyController = Modular.get<HistoryController>();
final CollectController collectController = Modular.get<CollectController>();
final MyController myController = Modular.get<MyController>();
+ late Map<String, List<String>> keyboardShortcuts;
+ late Map<String, void Function()> keyboardActions;
+
// 1. 在看
// 2. 想看
@@ -104,6 +111,8 @@ class _PlayerItemState extends State<PlayerItem>
Timer? mouseScrollerTimer;
Timer? hideVolumeUITimer;
+ double lastVolume = 0;
+
// 过渡动画控制器
AnimationController? animationController;
@@ -123,6 +132,122 @@ class _PlayerItemState extends State<PlayerItem>
} catch (_) {}
}
+ void _loadShortcuts() {
+ keyboardShortcuts = {};
+ defaultShortcuts.forEach((key, defaultValue) {
+ keyboardShortcuts[key] = setting
+ .get('shortcut_$key', defaultValue: defaultValue)
+ .cast<String>();
+ });
+ }
+
+ void _initKeyboardActions(){
+ keyboardActions = {
+ 'playorpause': () => playerController.playOrPause(),
+ 'forward': () async => handleShortcutSeek('forward'),
+ 'rewind': () async => handleShortcutSeek('rewind'),
+ 'next': () async => handlePreNextEpisode('next'),
+ 'prev': () async => handlePreNextEpisode('prev'),
+ 'volumeup': () async => handleShortcutVolumeChange('up'),
+ 'volumedown': () async => handleShortcutVolumeChange('down'),
+ 'togglemute': () async => handleShortcutVolumeChange('mute'),
+ 'fullscreen': () => handleShortcutFullscreen(),
+ 'screenshot': () async => handleScreenshot(),
+ 'skip': () async => skipOP(),
+ 'exitfullscreen': () => handleShortcutExitFullscreen(),
+ 'toggledanmaku': () => handleDanmaku(),
+ 'speed1': () async => setPlaybackSpeed(1.0),
+ 'speed2': () async => setPlaybackSpeed(2.0),
+ 'speed3': () async => setPlaybackSpeed(3.0),
+ };
+ }
+ bool handleShortcutInput(String keyLabel) {
+ for (final entry in keyboardShortcuts.entries) {
+ final func = entry.key;
+ final keys = entry.value;
+ if (keys.contains(keyLabel)) {
+ final action = keyboardActions[func];
+ if (action != null) {
+ action();
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ //上一集下一集动作
+ Future<void> handlePreNextEpisode(String direction) async{
+ if (videoPageController.loading) return;
+ final currentRoad = videoPageController.currentRoad;
+ final episodes = videoPageController.roadList[currentRoad].data;
+ int targetEpisode;
+ if (direction == 'next'){targetEpisode = videoPageController.currentEpisode + 1;}
+ else if (direction == 'prev') {targetEpisode = videoPageController.currentEpisode - 1;}
+ else {return;}
+
+ if (targetEpisode > episodes.length) {
+ KazumiDialog.showToast(message: '已经是最新一集');
+ return;
+ }
+ if (targetEpisode <= 0) {
+ KazumiDialog.showToast(message: '已经是第一集');
+ return;
+ }
+
+ final identifier = videoPageController.roadList[currentRoad].identifier[targetEpisode - 1];
+ KazumiDialog.showToast(message: '正在加载$identifier');
+ widget.changeEpisode(targetEpisode, currentRoad: currentRoad);
+ }
+
+ //快进快退快捷键动作
+ Future<void> handleShortcutSeek(String direction) async {
+ int skipTime = playerController.arrowKeySkipTime;
+ int current = playerController.currentPosition.inSeconds;
+ int total = playerController.playerDuration.inSeconds;
+ int targetPosition;
+
+ if (direction == 'forward') {
+ targetPosition = current + skipTime;
+ if (targetPosition > total) targetPosition = total;
+ } else if (direction == 'rewind') {
+ targetPosition = current - skipTime;
+ if (targetPosition < 0) targetPosition = 0;
+ } else {
+ return;
+ }
+
+ try {
+ playerTimer?.cancel();
+ await playerController.seek(Duration(seconds: targetPosition));
+ playerTimer = getPlayerTimer();
+ } catch (e) {
+ KazumiLogger().log(Level.error, e.toString());
+ }
+ }
+
+ //全屏快捷键动作
+ void handleShortcutFullscreen(){
+ if (!videoPageController.isPip) handleFullscreen();
+ }
+
+ //退出全屏快捷键动作
+ void handleShortcutExitFullscreen(){
+ if (videoPageController.isFullscreen &&
+ !Utils.isTablet()) {
+ try {
+ playerController.danmakuController
+ .clear();
+ } catch (_) {}
+ Utils.exitFullScreen();
+ videoPageController.isFullscreen =
+ !videoPageController.isFullscreen;
+ } else if (!Platform.isMacOS) {
+ playerController.pause();
+ windowManager.hide();
+ }
+ }
+
void _handleTap() {
if (Utils.isDesktop()) {
playerController.playOrPause();
@@ -161,16 +286,10 @@ class _PlayerItemState extends State<PlayerItem>
mouseScrollerTimer = null;
});
}
-
- void _handleKeyChangingVolume() {
- playerController.showVolume = true;
- hideVolumeUITimer?.cancel();
- hideVolumeUITimer = Timer(const Duration(seconds: 2), () {
- if (mounted) {
- playerController.showVolume = false;
- }
- hideVolumeUITimer = null;
- });
+
+ //跳过指定秒数
+ Future<void> skipOP() async {
+ await playerController.seek(playerController.currentPosition + Duration(seconds: playerController.buttonSkipTime));
}
void handleDanmaku() {
@@ -224,6 +343,37 @@ class _PlayerItemState extends State<PlayerItem>
playerTimer?.cancel();
playerTimer = getPlayerTimer();
}
+
+ //截图
+ Future<void> handleScreenshot() async {
+ KazumiDialog.showToast(message: '截图中...');
+ try {
+ Uint8List? screenshot =
+ await playerController.screenshot(format: 'image/png');
+
+ if (screenshot == null) {
+ KazumiDialog.showToast(message: '截图失败:未获取到图像');
+ return;
+ }
+
+ if (Utils.isDesktop()) {
+ KazumiDialog.showToast(message: '桌面端暂未支持保存截图');
+ return;
+ }
+ final result = await SaverGallery.saveImage(
+ screenshot,
+ fileName: DateTime.timestamp().millisecondsSinceEpoch.toString(),
+ skipIfExists: false,
+ );
+ if (result.isSuccess) {
+ KazumiDialog.showToast(message: '截图保存到相簿成功');
+ } else {
+ KazumiDialog.showToast(message: '截图保存失败:${result.errorMessage}');
+ }
+ } catch (e) {
+ KazumiDialog.showToast(message: '截图失败:$e');
+ }
+ }
// 启用超分辨率(质量档)时弹出提示
Future<void> handleSuperResolutionChange(int shaderIndex) async {
@@ -326,12 +476,37 @@ class _PlayerItemState extends State<PlayerItem>
await playerController.setPlaybackSpeed(speed);
}
- Future<void> increaseVolume() async {
- await playerController.setVolume(playerController.volume + 10);
- }
-
- Future<void> decreaseVolume() async {
- await playerController.setVolume(playerController.volume - 10);
+ Future<void> handleShortcutVolumeChange(String type) async {
+ try {
+ switch (type) {
+ case 'up':
+ await playerController.setVolume(playerController.volume + 10);
+ break;
+ case 'down':
+ await playerController.setVolume(playerController.volume - 10);
+ break;
+ case 'mute':
+ if (playerController.volume > 0) {
+ lastVolume = playerController.volume;
+ await playerController.setVolume(0);
+ } else {
+ await playerController.setVolume(lastVolume);
+ }
+ break;
+ default:
+ return;
+ }
+ playerController.showVolume = true;
+ hideVolumeUITimer?.cancel();
+ hideVolumeUITimer = Timer(const Duration(seconds: 2), () {
+ if (mounted) {
+ playerController.showVolume = false;
+ }
+ hideVolumeUITimer = null;
+ });
+ } catch (e) {
+ KazumiLogger().log(Level.error, '音量操作失败: ${e.toString()}');
+ }
}
Future<void> setBrightness(double value) async {
@@ -983,6 +1158,8 @@ class _PlayerItemState extends State<PlayerItem>
@override
void initState() {
super.initState();
+ _loadShortcuts();
+ _initKeyboardActions();
_fullscreenListener = mobx.reaction<bool>(
(_) => videoPageController.isFullscreen,
(_) {
@@ -1111,120 +1288,18 @@ class _PlayerItemState extends State<PlayerItem>
child: Focus(
// workaround for #461
// I don't know why, but the focus node will break popscope.
- focusNode:
- Utils.isDesktop() ? widget.keyboardFocus : null,
- autofocus: Utils.isDesktop(),
+ focusNode: widget.keyboardFocus,
+ autofocus: true,
onKeyEvent: (focusNode, KeyEvent event) {
if (event is KeyDownEvent) {
- // 当空格键被按下时
- if (event.logicalKey ==
- LogicalKeyboardKey.space) {
- try {
- playerController.playOrPause();
- } catch (e) {
- KazumiLogger().log(
- Level.error, '播放器内部错误 ${e.toString()}');
- }
- }
- // 右方向键被按下
- if (event.logicalKey ==
- LogicalKeyboardKey.arrowRight) {
- lastPlayerSpeed =
- playerController.playerSpeed;
- }
- // 左方向键被按下
- if (event.logicalKey ==
- LogicalKeyboardKey.arrowLeft) {
- int targetPosition = playerController
- .currentPosition.inSeconds -
- playerController.arrowKeySkipTime;
- if (targetPosition < 0) {
- targetPosition = 0;
- }
- try {
- playerTimer?.cancel();
- playerController.seek(
- Duration(seconds: targetPosition));
- playerTimer = getPlayerTimer();
- } catch (e) {
- KazumiLogger()
- .log(Level.error, e.toString());
- }
- }
- // 上方向键被按下
- if (event.logicalKey ==
- LogicalKeyboardKey.arrowUp) {
- increaseVolume();
- _handleKeyChangingVolume();
- }
- // 下方向键被按下
- if (event.logicalKey ==
- LogicalKeyboardKey.arrowDown) {
- decreaseVolume();
- _handleKeyChangingVolume();
- }
- // Esc键被按下
- if (event.logicalKey ==
- LogicalKeyboardKey.escape) {
- if (videoPageController.isFullscreen &&
- !Utils.isTablet()) {
- try {
- playerController.danmakuController
- .clear();
- } catch (_) {}
- Utils.exitFullScreen();
- videoPageController.isFullscreen =
- !videoPageController.isFullscreen;
- } else if (!Platform.isMacOS) {
- playerController.pause();
- windowManager.hide();
- }
- }
- // F键被按下
- if (event.logicalKey ==
- LogicalKeyboardKey.keyF) {
- if (!videoPageController.isPip) {
- handleFullscreen();
- }
- }
- // D键盘被按下
- if (event.logicalKey ==
- LogicalKeyboardKey.keyD) {
- handleDanmaku();
- }
- } else if (event is KeyRepeatEvent) {
- // 右方向键长按
- if (event.logicalKey ==
- LogicalKeyboardKey.arrowRight) {
- if (playerController.playerSpeed < 2.0) {
- playerController.showPlaySpeed = true;
- setPlaybackSpeed(2.0);
- }
- }
- } else if (event is KeyUpEvent) {
- // 右方向键抬起
- if (event.logicalKey ==
- LogicalKeyboardKey.arrowRight) {
- if (playerController.showPlaySpeed) {
- playerController.showPlaySpeed = false;
- setPlaybackSpeed(lastPlayerSpeed);
- } else {
- try {
- playerTimer?.cancel();
- playerController.seek(Duration(
- seconds: playerController
- .currentPosition.inSeconds +
- playerController
- .arrowKeySkipTime));
- playerTimer = getPlayerTimer();
- } catch (e) {
- KazumiLogger().log(Level.error,
- '播放器内部错误 ${e.toString()}');
+ final keyLabel = event.logicalKey.keyLabel.isNotEmpty
+ ? event.logicalKey.keyLabel
+ : event.logicalKey.debugName ?? '';
+ if (handleShortcutInput(keyLabel)) {
+ return KeyEventResult.handled;
}
- }
- }
- }
- return KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
},
child: const PlayerItemSurface())),
(playerController.isBuffering ||
@@ -1316,6 +1391,7 @@ class _PlayerItemState extends State<PlayerItem>
handleProgressBarDragEnd: handleProgressBarDragEnd,
handleSuperResolutionChange:
handleSuperResolutionChange,
+ handlePreNextEpisode: handlePreNextEpisode,
animationController: animationController!,
keyboardFocus: widget.keyboardFocus,
sendDanmaku: widget.sendDanmaku,
@@ -1328,6 +1404,8 @@ class _PlayerItemState extends State<PlayerItem>
showSyncPlayEndPointSwitchDialog:
showSyncPlayEndPointSwitchDialog,
disableAnimations: widget.disableAnimations,
+ handleScreenShot: handleScreenshot,
+ skipOP: skipOP,
)
: SmallestPlayerItemPanel(
onBackPressed: widget.onBackPressed,
@@ -1351,6 +1429,7 @@ class _PlayerItemState extends State<PlayerItem>
showSyncPlayEndPointSwitchDialog:
showSyncPlayEndPointSwitchDialog,
disableAnimations: widget.disableAnimations,
+ skipOP: skipOP,
),
// 播放器手势控制
Positioned.fill(
diff --git a/lib/pages/player/player_item_panel.dart b/lib/pages/player/player_item_panel.dart
index c77e8eab..f68499eb 100644
--- a/lib/pages/player/player_item_panel.dart
+++ b/lib/pages/player/player_item_panel.dart
@@ -7,7 +7,6 @@ import 'package:kazumi/utils/utils.dart';
import 'package:kazumi/pages/video/video_controller.dart';
import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:kazumi/pages/player/player_controller.dart';
-import 'package:saver_gallery/saver_gallery.dart';
import 'package:flutter/services.dart';
import 'package:kazumi/utils/remote.dart';
import 'package:kazumi/bean/appbar/drag_to_move_bar.dart' as dtb;
@@ -26,6 +25,8 @@ class PlayerItemPanel extends StatefulWidget {
required this.showDanmakuSwitch,
required this.changeEpisode,
required this.handleFullscreen,
+ required this.handleScreenShot,
+ required this.handlePreNextEpisode,
required this.handleProgressBarDragStart,
required this.handleProgressBarDragEnd,
required this.handleSuperResolutionChange,
@@ -36,6 +37,7 @@ class PlayerItemPanel extends StatefulWidget {
required this.startHideTimer,
required this.cancelHideTimer,
required this.handleDanmaku,
+ required this.skipOP,
required this.showVideoInfo,
required this.showSyncPlayRoomCreateDialog,
required this.showSyncPlayEndPointSwitchDialog,
@@ -48,6 +50,7 @@ class PlayerItemPanel extends StatefulWidget {
final Future<void> Function(int, {int currentRoad, int offset}) changeEpisode;
final void Function() openMenu;
final void Function() handleFullscreen;
+ final void Function() handleScreenShot;
final void Function(ThumbDragDetails details) handleProgressBarDragStart;
final void Function() handleProgressBarDragEnd;
final Future<void> Function(int shaderIndex) handleSuperResolutionChange;
@@ -56,6 +59,8 @@ class PlayerItemPanel extends StatefulWidget {
final void Function() startHideTimer;
final void Function() cancelHideTimer;
final void Function() handleDanmaku;
+ final void Function(String direction) handlePreNextEpisode;
+ final void Function() skipOP;
final void Function(String) sendDanmaku;
final void Function() showVideoInfo;
final void Function() showSyncPlayRoomCreateDialog;
@@ -76,8 +81,7 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
Modular.get<VideoPageController>();
final PlayerController playerController = Modular.get<PlayerController>();
final TextEditingController textController = TextEditingController();
- final FocusNode textFieldFocus = FocusNode();
-
+ final FocusNode textFieldFocus = FocusNode();
// SVG Caches
String? cachedSvgString;
Widget? cachedDanmakuOnIcon;
@@ -87,26 +91,6 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
static const double _danmakuIconSize = 24.0;
static const double _loadingIndicatorStrokeWidth = 2.0;
- Future<void> _handleScreenshot() async {
- KazumiDialog.showToast(message: '截图中...');
- try {
- Uint8List? screenshot =
- await playerController.screenshot(format: 'image/png');
- final result = await SaverGallery.saveImage(
- screenshot!,
- fileName: DateTime.timestamp().millisecondsSinceEpoch.toString(),
- skipIfExists: false,
- );
- if (result.isSuccess) {
- KazumiDialog.showToast(message: '截图保存到相簿成功');
- } else {
- KazumiDialog.showToast(message: '截图保存失败:${result.errorMessage}');
- }
- } catch (e) {
- KazumiDialog.showToast(message: '截图失败:$e');
- }
- }
-
Widget get danmakuTextField {
return Container(
constraints: Utils.isDesktop()
@@ -343,7 +327,7 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
return cachedDanmakuOnIcon!;
}
- Widget _buildDanmakuToggleButton(BuildContext context, {bool showKeyboardShortcut = true}) {
+ Widget _buildDanmakuToggleButton(BuildContext context) {
return IconButton(
color: Colors.white,
icon: playerController.danmakuLoading
@@ -365,8 +349,8 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
tooltip: playerController.danmakuLoading
? '弹幕加载中...'
: (playerController.danmakuOn
- ? '关闭弹幕${showKeyboardShortcut ? "(d)" : ""}'
- : '打开弹幕${showKeyboardShortcut ? "(d)" : ""}'),
+ ? '关闭弹幕'
+ : '打开弹幕'),
);
}
@@ -382,8 +366,7 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
height: 24,
),
onPressed: () {
- playerController.seek(playerController.currentPosition +
- Duration(seconds: playerController.buttonSkipTime));
+ widget.skipOP();
},
),
),
@@ -738,27 +721,7 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
IconButton(
color: Colors.white,
icon: const Icon(Icons.skip_next_rounded),
- onPressed: () {
- if (videoPageController.loading) {
- return;
- }
- if (videoPageController.currentEpisode ==
- videoPageController
- .roadList[videoPageController.currentRoad]
- .data
- .length) {
- KazumiDialog.showToast(
- message: '已经是最新一集',
- );
- return;
- }
- KazumiDialog.showToast(
- message:
- '正在加载${videoPageController.roadList[videoPageController.currentRoad].identifier[videoPageController.currentEpisode]}');
- widget.changeEpisode(
- videoPageController.currentEpisode + 1,
- currentRoad: videoPageController.currentRoad);
- },
+ onPressed: () => widget.handlePreNextEpisode('next'),
),
if (Utils.isDesktop())
Container(
@@ -837,7 +800,7 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
widget.handleDanmaku();
},
tooltip:
- playerController.danmakuOn ? '关闭弹幕(d)' : '打开弹幕(d)',
+ playerController.danmakuOn ? '关闭弹幕' : '打开弹幕',
),
if (playerController.danmakuOn) ...[
IconButton(
@@ -1344,7 +1307,7 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
color: Colors.white,
),
onPressed: () {
- _handleScreenshot();
+ widget.handleScreenShot();
},
),
IconButton(
diff --git a/lib/pages/player/smallest_player_item_panel.dart b/lib/pages/player/smallest_player_item_panel.dart
index d3328154..903ded7d 100644
--- a/lib/pages/player/smallest_player_item_panel.dart
+++ b/lib/pages/player/smallest_player_item_panel.dart
@@ -33,6 +33,7 @@ class SmallestPlayerItemPanel extends StatefulWidget {
required this.startHideTimer,
required this.cancelHideTimer,
required this.handleDanmaku,
+ required this.skipOP,
required this.showVideoInfo,
required this.showSyncPlayRoomCreateDialog,
required this.showSyncPlayEndPointSwitchDialog,
@@ -43,6 +44,7 @@ class SmallestPlayerItemPanel extends StatefulWidget {
final Future<void> Function(double) setPlaybackSpeed;
final void Function() showDanmakuSwitch;
final void Function() handleDanmaku;
+ final void Function() skipOP;
final void Function() handleFullscreen;
final void Function(ThumbDragDetails details) handleProgressBarDragStart;
final void Function() handleProgressBarDragEnd;
@@ -185,7 +187,7 @@ class _SmallestPlayerItemPanelState extends State<SmallestPlayerItemPanel> {
return cachedDanmakuOnIcon!;
}
- Widget _buildDanmakuToggleButton(BuildContext context, {bool showKeyboardShortcut = false}) {
+ Widget _buildDanmakuToggleButton(BuildContext context) {
return IconButton(
color: Colors.white,
icon: playerController.danmakuLoading
@@ -207,8 +209,8 @@ class _SmallestPlayerItemPanelState extends State<SmallestPlayerItemPanel> {
tooltip: playerController.danmakuLoading
? '弹幕加载中...'
: (playerController.danmakuOn
- ? '关闭弹幕${showKeyboardShortcut ? "(d)" : ""}'
- : '打开弹幕${showKeyboardShortcut ? "(d)" : ""}'),
+ ? '关闭弹幕'
+ : '打开弹幕'),
);
}
@@ -224,8 +226,7 @@ class _SmallestPlayerItemPanelState extends State<SmallestPlayerItemPanel> {
height: 24,
),
onPressed: () {
- playerController.seek(playerController.currentPosition +
- Duration(seconds: playerController.buttonSkipTime));
+ widget.skipOP();
},
),
),
diff --git a/lib/pages/settings/keyboard_settings.dart b/lib/pages/settings/keyboard_settings.dart
new file mode 100644
index 00000000..6aed17ec
--- /dev/null
+++ b/lib/pages/settings/keyboard_settings.dart
@@ -0,0 +1,179 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:hive/hive.dart';
+import 'package:kazumi/utils/storage.dart';
+import 'package:kazumi/utils/constants.dart';
+import 'package:kazumi/bean/appbar/sys_app_bar.dart';
+import 'package:kazumi/bean/dialog/dialog_helper.dart';
+
+class KeyboardSettingsPage extends StatefulWidget {
+ const KeyboardSettingsPage({super.key});
+
+ @override
+ State<KeyboardSettingsPage> createState() => _KeyboardSettingsPageState();
+}
+
+class _KeyboardSettingsPageState extends State<KeyboardSettingsPage> {
+ Box setting = GStorage.setting;
+
+ String? listeningFunction;
+ int? listeningIndex;
+ late Map<String, List<String>> shortcuts;
+
+ final FocusNode focusNode = FocusNode();
+
+ @override
+ void initState() {
+ super.initState();
+ // 根据默认快捷键生成可用快捷键列表,并读取已设置值
+ shortcuts = {
+ for (var key in defaultShortcuts.keys)
+ key: (setting.get('shortcut_$key',
+ defaultValue: defaultShortcuts[key]?.toList() ?? <String>[])
+ ?.cast<String>() ?? [])
+ };
+ }
+
+ @override
+ void dispose() {
+ focusNode.dispose();
+ super.dispose();
+ }
+ bool handleShortcutInput(String rawKey) {
+ if (listeningFunction == null || listeningIndex == null) return false;
+
+ final func = listeningFunction!;
+ final index = listeningIndex!;
+
+ // 冲突规避
+ for (final entry in shortcuts.entries) {
+ final otherFunc = entry.key;
+ final otherKeys = entry.value;
+
+ for (int i = 0; i < otherKeys.length; i++) {
+ if (otherFunc == func && i == index) continue;
+ if (otherKeys[i] == rawKey) {
+ final name = shortcutsChineseName[otherFunc] ?? otherFunc;
+ KazumiDialog.showToast(message: "按键已被【$name】占用,请重新输入");
+ return true;
+ }
+ }
+ }
+ setState(() {
+ shortcuts[func]![index] = rawKey;
+ listeningFunction = null;
+ listeningIndex = null;
+ });
+ setting.put('shortcut_$func', shortcuts[func]);
+
+ return true;
+ }
+
+ void startListening(String func, int index) {
+ setState(() {
+ listeningFunction = func;
+ listeningIndex = index;
+ shortcuts[func]![index] = '...';
+ });
+
+ Future.delayed(const Duration(milliseconds: 50), () {
+ focusNode.requestFocus();
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return Scaffold(
+ appBar: SysAppBar(
+ title: Text('快捷键'),
+ actions: [
+ IconButton(
+ icon: const Icon(Icons.refresh),
+ tooltip: '恢复默认',
+ onPressed: () {
+ setState(() {
+ for (final func in shortcuts.keys) {
+ shortcuts[func] = defaultShortcuts[func]?.toList() ?? [];
+ setting.put('shortcut_$func', shortcuts[func]);
+ }
+ });
+ },
+ ),
+ ],
+ ),
+ body: FocusScope(
+ autofocus: true,
+ child: Focus(
+ focusNode: focusNode,
+ autofocus: true,
+ onKeyEvent: (node, event) {
+ if (event is! KeyDownEvent) return KeyEventResult.ignored;
+ if (listeningFunction == null) return KeyEventResult.ignored;
+
+ final rawKey = event.logicalKey.keyLabel.isNotEmpty
+ ? event.logicalKey.keyLabel
+ : event.logicalKey.debugName ?? '';
+
+ final handled = handleShortcutInput(rawKey);
+ return handled ? KeyEventResult.handled : KeyEventResult.ignored;
+ },
+ child: ListView(
+ padding: const EdgeInsets.all(16),
+ children: shortcuts.entries.map((entry) {
+ final func = entry.key;
+ final keys = entry.value;
+ return Card(
+ margin: const EdgeInsets.symmetric(vertical: 8),
+ child: Padding(
+ padding: const EdgeInsets.all(12),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ shortcutsChineseName[func] ?? func,
+ style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
+ ),
+ const SizedBox(height: 8),
+ Wrap(
+ spacing: 8,
+ runSpacing: 8,
+ children: [
+ for (int i = 0; i < keys.length; i++)
+ GestureDetector(
+ onLongPress: () {
+ setState(() => keys.removeAt(i));
+ setting.put('shortcut_$func', keys);
+ },
+ child: ActionChip(
+ label: Text(
+ keyAliases[keys[i]] ??
+ (keys[i].isEmpty ? '未设置' : keys[i]),
+ ),
+ onPressed: () => startListening(func, i),
+ avatar: const Icon(Icons.edit),
+ materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ focusNode: FocusNode(canRequestFocus: false),
+ ),
+ ),
+ // 添加快捷键
+ ActionChip(
+ label: const Text("+"),
+ onPressed: () {
+ setState(() => keys.add(''));
+ setting.put('shortcut_$func', keys);
+ },
+ focusNode: FocusNode(canRequestFocus: false),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ );
+ }).toList(),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/pages/settings/settings_module.dart b/lib/pages/settings/settings_module.dart
index 80f60fec..ec6dff69 100644
--- a/lib/pages/settings/settings_module.dart
+++ b/lib/pages/settings/settings_module.dart
@@ -9,6 +9,7 @@ import 'package:kazumi/pages/settings/displaymode_settings.dart';
import 'package:kazumi/pages/settings/decoder_settings.dart';
import 'package:kazumi/pages/settings/super_resolution_settings.dart';
import 'package:kazumi/pages/webdav_editor/webdav_module.dart';
+import 'package:kazumi/pages/settings/keyboard_settings.dart';
class SettingsModule extends Module {
@override
@@ -18,6 +19,7 @@ class SettingsModule extends Module {
"/theme/display",
child: (_) => const SetDisplayMode(),
);
+ r.child("/keyboard", child: (_) => const KeyboardSettingsPage());
r.child("/player", child: (_) => const PlayerSettingsPage());
r.child("/player/decoder", child: (_) => const DecoderSettings());
// r.child("/other", child: (_) => const OtherSettingsPage());
diff --git a/lib/utils/constants.dart b/lib/utils/constants.dart
index 97912cf8..e92368ac 100644
--- a/lib/utils/constants.dart
+++ b/lib/utils/constants.dart
@@ -204,3 +204,56 @@ final List<String> defaultAnimeTags = const [
'治愈',
'异世界',
];
+
+// 播放器默认快捷键
+ final Map<String, List<String>> defaultShortcuts = const {
+ 'playorpause': [' '],
+ 'forward': ['Arrow Right'],
+ 'rewind': ['Arrow Left'],
+ 'next': ['N'],
+ 'prev': ['P'],
+ 'volumeup': ['Arrow Up'],
+ 'volumedown': ['Arrow Down'],
+ 'togglemute': ['M'],
+ 'fullscreen': ['F'],
+ 'exitfullscreen': ['Escape'],
+ 'toggledanmaku': ['D'],
+ 'screenshot': ['S'],
+ 'skip': ['K'],
+ 'speed1': ['1'],
+ 'speed2': ['2'],
+ 'speed3': ['3'],
+ };
+
+// 键位别名
+ final Map<String, String> keyAliases = {
+ ' ': '空格',
+ 'Arrow Up': '↑',
+ 'Arrow Down': '↓',
+ 'Arrow Left': '←',
+ 'Arrow Right': '→',
+ 'Enter': '回车',
+ 'Tab': 'Tab',
+ 'Escape': 'Esc',
+ 'Backspace': '退格',
+ };
+
+//功能中文名对应
+ final Map<String, String> shortcutsChineseName = {
+ 'playorpause': '播放 / 暂停',
+ 'forward': '快进',
+ 'rewind': '快退',
+ 'next': '下一集',
+ 'prev': '上一集',
+ 'volumeup': '音量加',
+ 'volumedown': '音量减',
+ 'togglemute': '静音',
+ 'fullscreen': '全屏',
+ 'exitfullscreen': '退出全屏',
+ 'toggledanmaku': '弹幕开关',
+ 'screenshot': '截图',
+ 'skip': '跳过',
+ 'speed1': '倍速:1x',
+ 'speed2': '倍速:2x',
+ 'speed3': '倍速:3x',
+ };
\ No newline at end of file