From b82a7298fdc0eaf8b41be1def1ff19c4704ed822 Mon Sep 17 00:00:00 2001 From: mmc <1556375442@qq.com> Date: Thu, 5 Mar 2026 15:46:41 +0800 Subject: [PATCH] =?UTF-8?q?=E8=B7=AF=E6=99=AF=E8=A7=82=E8=A7=84=E5=88=92?= =?UTF-8?q?=E8=A7=86=E9=A2=91=20=E5=88=9D=E6=AD=A5ui?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../widgets/map/testmap_pages.dart | 55 ++- .../presentation/widgets/path_list_pages.dart | 79 +---- .../home/presentation/widgets/video.dart | 321 ++++++++++++++++++ 3 files changed, 392 insertions(+), 63 deletions(-) create mode 100644 lib/features/home/presentation/widgets/video.dart diff --git a/lib/features/home/presentation/widgets/map/testmap_pages.dart b/lib/features/home/presentation/widgets/map/testmap_pages.dart index 60140b47..37fe8f34 100644 --- a/lib/features/home/presentation/widgets/map/testmap_pages.dart +++ b/lib/features/home/presentation/widgets/map/testmap_pages.dart @@ -14,6 +14,7 @@ import 'package:latlong2/latlong.dart'; import 'package:maibu_satabot_v2/components/confrim_dialog.dart'; import 'package:maibu_satabot_v2/components/toast.dart'; import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart'; +import 'package:maibu_satabot_v2/core/consts/tcp_consts.dart'; import 'package:maibu_satabot_v2/core/di/injection.dart'; import 'package:maibu_satabot_v2/core/network/net_message_dispatcher.dart'; import 'package:maibu_satabot_v2/core/network/protocol_decoder.dart'; @@ -32,6 +33,7 @@ import 'package:maibu_satabot_v2/features/home/presentation/widgets/map/CenterLo import 'package:maibu_satabot_v2/features/home/presentation/widgets/map/HeadingPointer.dart'; import 'package:maibu_satabot_v2/features/home/presentation/widgets/startpoint_area.dart'; import 'package:image/image.dart' as _image; // 注意命名空间冲突,使用 as img +import 'package:maibu_satabot_v2/features/home/presentation/widgets/video.dart'; import 'dart:ui' as ui; import '../path_list_pages.dart'; @@ -66,6 +68,9 @@ class _MapPageEnterpriseState extends State { final _dispatcher = sl(); late StreamSubscription _sub; bool _isRefreshing = false; // 新增:页面刷新状态标志 + bool _isVideoDialogOpen = false; // 控制视频弹窗显示 + String _videoStreamUrl = ""; + Offset _videoPopupPos = const Offset(0, 100); // 弹窗初始位置 // 🔥 关键修复:添加截图全局Key final GlobalKey _mapRepaintKey = GlobalKey(); @@ -73,6 +78,7 @@ class _MapPageEnterpriseState extends State { // 初始化轨迹管理器(泛型指定为LatLng) late final TracePoint _traceManager; late String workMode = "弓字模式"; // 作业模式:默认值为"弓字模式" + WorkStatus _workStatus = WorkStatus.idle; LatLng? _currentLatLng; @@ -772,6 +778,12 @@ class _MapPageEnterpriseState extends State { super.dispose(); } + void _handleVideo() { + setState(() { + _isVideoDialogOpen = true; // 打开视频弹窗 + }); + } + // 模拟添加完成点 void _addCompletePoint() { final newPoint = LatLng(39.9042 + (DateTime.now().millisecond / 10000), 116.4074 + (DateTime.now().millisecond / 10000)); @@ -784,6 +796,38 @@ class _MapPageEnterpriseState extends State { _traceManager.upsert(newPoint); } + // 构建视频弹窗 + // 构建视频小弹窗(可拖拽) + // 构建视频小弹窗(可拖拽) + Widget _buildVideoPopup() { + return Positioned( + left: _videoPopupPos.dx, + top: _videoPopupPos.dy, + child: GestureDetector( + // 拖拽区域(整个弹窗可拖拽) + onPanUpdate: (details) { + setState(() { + _videoPopupPos = Offset(_videoPopupPos.dx + details.delta.dx, _videoPopupPos.dy + details.delta.dy); + }); + }, + child: WebRTCMapPlayer( + streamUrl: _videoStreamUrl, + width: 320, + height: 180, + showLeftPip: true, + showRightPip: true, + onClose: _closeVideoDialog, // 关闭回调 + ), + ), + ); + } + + void _closeVideoDialog() { + setState(() { + _isVideoDialogOpen = false; + }); + } + // 🔥 改动2:修改 _buildPlotListItem 方法,增加删除时调用Bloc的逻辑 Widget _buildPlotListItem(PlotData plot, Function(PlotData) onDelete) { return GestureDetector( @@ -1539,7 +1583,14 @@ class _MapPageEnterpriseState extends State { final screenHeight = MediaQuery.of(context).size.height; final menuHeight = 16 * 6; // 假设 VerticalFloatMenu 有 6 个选项,每个高度为 56 final maxTop = screenHeight - menuHeight; - + final userState = context.watch().state; + final deviceId = context.watch().state.selectedDevice?.deviceName; + if (deviceId != null && userState.user?.token != null) { + _videoStreamUrl = "webrtc://${TCPConsts.TCP_IP}/live/livestream/$deviceId?token=${userState.user!.token}"; + } else { + _videoStreamUrl = ''; // 无设备/用户信息时置空 + print("设备未选中或用户未登录,无法生成视频流地址"); + } return Scaffold( body: SafeArea( child: Stack( @@ -1902,6 +1953,7 @@ class _MapPageEnterpriseState extends State { debugPrint('外部收到作业模式:$mode'); }, onRefreshTap: _handleRefresh, // 推荐用局部刷新 + onVideoTap: _handleVideo, ), ), ), @@ -2101,6 +2153,7 @@ class _MapPageEnterpriseState extends State { ), if (_isWorkPanelOpen) _buildWorkPanel(), + if (_isVideoDialogOpen) _buildVideoPopup(), ], ), ), diff --git a/lib/features/home/presentation/widgets/path_list_pages.dart b/lib/features/home/presentation/widgets/path_list_pages.dart index 11267517..56309bfb 100644 --- a/lib/features/home/presentation/widgets/path_list_pages.dart +++ b/lib/features/home/presentation/widgets/path_list_pages.dart @@ -7,6 +7,7 @@ class VerticalFloatMenu extends StatefulWidget { final ValueChanged? onListBox; final ValueChanged? onWorkModeSelected; final VoidCallback? onRefreshTap; // 新增刷新回调 + final VoidCallback? onVideoTap; const VerticalFloatMenu({ super.key, @@ -15,6 +16,7 @@ class VerticalFloatMenu extends StatefulWidget { this.onListBox, this.onWorkModeSelected, this.onRefreshTap, // 接收刷新回调 + this.onVideoTap, }); @override @@ -44,17 +46,7 @@ class _VerticalFloatMenuState extends State { color: Colors.white, child: Column( mainAxisSize: MainAxisSize.min, - children: _menuItems - .asMap() - .entries - .map( - (entry) => _buildMenuItem( - entry.value["icon"], - entry.key, - entry.value["name"], - ), - ) - .toList(), + children: _menuItems.asMap().entries.map((entry) => _buildMenuItem(entry.value["icon"], entry.key, entry.value["name"])).toList(), ), ); } @@ -91,6 +83,9 @@ class _VerticalFloatMenuState extends State { // 可以添加刷新中的临时状态(比如图标旋转) }); } + if (index == 5) { + widget.onVideoTap?.call(); + } }, child: Container( width: double.infinity, @@ -100,19 +95,9 @@ class _VerticalFloatMenuState extends State { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - Icon( - icon, - color: isSelected ? Colors.lightBlue : Colors.black, - size: 22, - ), + Icon(icon, color: isSelected ? Colors.lightBlue : Colors.black, size: 22), const SizedBox(height: 2), - Text( - name, - style: TextStyle( - fontSize: 10, - color: isSelected ? Colors.lightBlue : Colors.black, - ), - ), + Text(name, style: TextStyle(fontSize: 10, color: isSelected ? Colors.lightBlue : Colors.black)), ], ), ), @@ -131,21 +116,13 @@ class _VerticalFloatMenuState extends State { return StatefulBuilder( builder: (context, setState) { return Dialog( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(16), - ), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), child: Padding( padding: const EdgeInsets.all(20), child: Column( mainAxisSize: MainAxisSize.min, children: [ - const Text( - "选择作业模式", - style: TextStyle( - fontSize: 18, - fontWeight: FontWeight.bold, - ), - ), + const Text("选择作业模式", style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), const SizedBox(height: 20), _modeItem( title: "弓字模式", @@ -172,14 +149,8 @@ class _VerticalFloatMenuState extends State { Row( mainAxisAlignment: MainAxisAlignment.end, children: [ - TextButton( - onPressed: () => Navigator.pop(context), - child: const Text("取消"), - ), - ElevatedButton( - onPressed: () => Navigator.pop(context, selectedMode), - child: const Text("确定"), - ), + TextButton(onPressed: () => Navigator.pop(context), child: const Text("取消")), + ElevatedButton(onPressed: () => Navigator.pop(context, selectedMode), child: const Text("确定")), ], ), ], @@ -192,41 +163,25 @@ class _VerticalFloatMenuState extends State { ); } - Widget _modeItem({ - required String title, - required String subtitle, - required bool isSelected, - required VoidCallback onTap, - }) { + Widget _modeItem({required String title, required String subtitle, required bool isSelected, required VoidCallback onTap}) { return InkWell( onTap: onTap, child: Container( padding: const EdgeInsets.all(14), decoration: BoxDecoration( - border: Border.all( - color: isSelected ? Colors.lightBlue : Colors.grey.shade300, - ), + border: Border.all(color: isSelected ? Colors.lightBlue : Colors.grey.shade300), borderRadius: BorderRadius.circular(12), color: isSelected ? Colors.lightBlue.shade50 : Colors.white, ), child: Row( children: [ - Icon( - isSelected ? Icons.check_circle : Icons.circle_outlined, - color: isSelected ? Colors.lightBlue : Colors.grey, - ), + Icon(isSelected ? Icons.check_circle : Icons.circle_outlined, color: isSelected ? Colors.lightBlue : Colors.grey), const SizedBox(width: 12), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - title, - style: const TextStyle(fontWeight: FontWeight.bold), - ), - Text( - subtitle, - style: const TextStyle(fontSize: 12, color: Colors.grey), - ), + Text(title, style: const TextStyle(fontWeight: FontWeight.bold)), + Text(subtitle, style: const TextStyle(fontSize: 12, color: Colors.grey)), ], ), ], diff --git a/lib/features/home/presentation/widgets/video.dart b/lib/features/home/presentation/widgets/video.dart new file mode 100644 index 00000000..9c80a5b5 --- /dev/null +++ b/lib/features/home/presentation/widgets/video.dart @@ -0,0 +1,321 @@ +import 'dart:convert'; +import 'dart:ui'; +import 'package:flutter/material.dart'; +import 'package:flutter_webrtc/flutter_webrtc.dart'; +import 'package:http/http.dart' as http; + +// 定义视图枚举(前、右、后、左) +enum VideoViewType { + front, // 前视图(左上) + right, // 右视图(右上) + back, // 后视图(右下) + left, // 左视图(左下) +} + +class WebRTCMapPlayer extends StatefulWidget { + final String streamUrl; + final bool showLeftPip; + final bool showRightPip; + final double width; // 弹窗宽度 + final double height; // 弹窗高度 + final Function() onClose; // 关闭回调 + + const WebRTCMapPlayer({ + super.key, + required this.streamUrl, + required this.onClose, + this.showLeftPip = true, + this.showRightPip = true, + this.width = 320, // 默认宽度 + this.height = 180, // 默认高度(16:9比例) + }); + + @override + State createState() => _WebRTCMapPlayerState(); +} + +class _WebRTCMapPlayerState extends State { + final RTCVideoRenderer _renderer = RTCVideoRenderer(); + RTCPeerConnection? _peerConnection; + + bool _isInitialized = false; + VideoViewType _currentViewType = VideoViewType.front; // 初始为前视图 + + // 悬浮小窗位置(小弹窗内的悬浮窗,按比例缩小) + final ValueNotifier _leftPosNotifier = ValueNotifier(const Offset(10, 40)); + final ValueNotifier _rightPosNotifier = ValueNotifier(const Offset(60, 40)); + bool _isPosInitialized = false; + + @override + void initState() { + super.initState(); + _prepareAndConnect(); + } + + // 初始化并连接 WebRTC + Future _prepareAndConnect() async { + try { + await _renderer.initialize(); + if (!mounted) return; + await _initWebRTCConnection(); + setState(() => _isInitialized = true); + } catch (e) { + debugPrint("视频初始化失败: $e"); + } + } + + // 初始化 WebRTC 连接 + Future _initWebRTCConnection() async { + _peerConnection = await createPeerConnection({ + "sdpSemantics": "unified-plan", + "iceServers": [ + {"urls": "stun:stun.l.google.com:19302"}, + ], + }); + + await _peerConnection!.addTransceiver( + kind: RTCRtpMediaType.RTCRtpMediaTypeVideo, + init: RTCRtpTransceiverInit(direction: TransceiverDirection.RecvOnly), + ); + + _peerConnection!.onTrack = (RTCTrackEvent event) { + if (event.track.kind == 'video' && event.streams.isNotEmpty) { + if (mounted) setState(() => _renderer.srcObject = event.streams[0]); + } + }; + + try { + final offer = await _peerConnection!.createOffer({'offerToReceiveVideo': 1}); + await _peerConnection!.setLocalDescription(offer); + + final uri = Uri.parse(widget.streamUrl.replaceFirst('webrtc://', 'http://')); + final apiUrl = "http://${uri.host}:1985/rtc/v1/play/"; + final response = await http.post( + Uri.parse(apiUrl), + headers: {'Content-Type': 'application/json'}, + body: jsonEncode({"api": apiUrl, "streamurl": widget.streamUrl, "clientip": null, "sdp": offer.sdp}), + ); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + await _peerConnection!.setRemoteDescription(RTCSessionDescription(data['sdp'], 'answer')); + } + } catch (e) { + debugPrint("WebRTC 信令错误: $e"); + } + } + + // 双击切换视图(前→右→后→左→前 循环) + void _switchViewType() { + setState(() { + switch (_currentViewType) { + case VideoViewType.front: + _currentViewType = VideoViewType.right; + break; + case VideoViewType.right: + _currentViewType = VideoViewType.back; + break; + case VideoViewType.back: + _currentViewType = VideoViewType.left; + break; + case VideoViewType.left: + _currentViewType = VideoViewType.front; + break; + } + }); + } + + // 根据视图类型获取对齐方式 + Alignment _getViewAlignment() { + switch (_currentViewType) { + case VideoViewType.front: + return Alignment.topLeft; + case VideoViewType.right: + return Alignment.topRight; + case VideoViewType.back: + return Alignment.bottomRight; + case VideoViewType.left: + return Alignment.bottomLeft; + } + } + + // 获取视图名称 + String _getViewName() { + switch (_currentViewType) { + case VideoViewType.front: + return "前视角"; + case VideoViewType.right: + return "右视角"; + case VideoViewType.back: + return "后视角"; + case VideoViewType.left: + return "左视角"; + } + } + + // 四分屏裁剪视图 + Widget _buildQuadrantView({required Alignment alignment}) { + if (!_isInitialized || _renderer.srcObject == null) { + return Container( + color: Colors.black, + child: const Center( + child: Text("加载中...", style: TextStyle(color: Colors.white)), + ), + ); + } + return RepaintBoundary( + child: ClipRect( + child: FractionallySizedBox( + widthFactor: 2.0, + heightFactor: 2.0, + alignment: alignment, + child: RTCVideoView(_renderer, objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover, mirror: false), + ), + ), + ); + } + + // 主视图羽化效果 + Widget _buildMainViewWithFeathering() { + return ShaderMask( + shaderCallback: (Rect bounds) => const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Colors.transparent, Colors.white, Colors.white, Colors.transparent], + stops: [0.0, 0.15, 0.85, 1.0], + ).createShader(bounds), + blendMode: BlendMode.dstIn, + child: ShaderMask( + shaderCallback: (Rect bounds) => const LinearGradient( + begin: Alignment.centerLeft, + end: Alignment.centerRight, + colors: [Colors.transparent, Colors.white, Colors.white, Colors.transparent], + stops: [0.0, 0.05, 0.95, 1.0], + ).createShader(bounds), + blendMode: BlendMode.dstIn, + child: _buildQuadrantView(alignment: _getViewAlignment()), + ), + ); + } + + // 修正悬浮窗位置 + void _correctPosition(ValueNotifier notifier, double w, double h) { + final maxX = (widget.width - w).clamp(0.0, double.infinity); + final maxY = (widget.height - h).clamp(0.0, double.infinity); + final newX = notifier.value.dx.clamp(0.0, maxX); + final newY = notifier.value.dy.clamp(0.0, maxY); + if (notifier.value.dx != newX || notifier.value.dy != newY) { + notifier.value = Offset(newX, newY); + } + } + + // 小弹窗内的悬浮小窗 + Widget _buildFastPip(ValueNotifier notifier, Alignment align) { + final pipW = widget.width / 4; + final pipH = pipW * 9 / 16; + + return ValueListenableBuilder( + valueListenable: notifier, + builder: (context, pos, child) { + _correctPosition(notifier, pipW, pipH); + return Positioned(left: pos.dx, top: pos.dy, child: child!); + }, + child: GestureDetector( + onPanUpdate: (details) { + notifier.value = Offset(notifier.value.dx + details.delta.dx, notifier.value.dy + details.delta.dy); + }, + child: Container( + width: pipW, + height: pipH, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(6), + boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.5), blurRadius: 8, offset: const Offset(0, 2))], + ), + clipBehavior: Clip.antiAlias, + child: _buildQuadrantView(alignment: align), + ), + ), + ); + } + + @override + void dispose() { + // 彻底销毁 WebRTC 资源 + _peerConnection?.close(); + _peerConnection?.dispose(); + _renderer.srcObject = null; + _renderer.dispose(); + _leftPosNotifier.dispose(); + _rightPosNotifier.dispose(); + debugPrint("视频组件已销毁"); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Container( + width: widget.width, + height: widget.height, + decoration: BoxDecoration( + color: Colors.black, + borderRadius: BorderRadius.circular(12), + boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.3), blurRadius: 15, offset: const Offset(0, 5))], + ), + child: _isInitialized + ? Stack( + children: [ + // 主视频层(双击切换视图) + GestureDetector( + onDoubleTap: _switchViewType, + child: SizedBox.expand(child: _buildMainViewWithFeathering()), + ), + // 视图标识(左上角 - 圆角透明背景) + Positioned( + top: 10, + left: 10, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), + decoration: BoxDecoration( + color: Colors.black.withOpacity(0.5), // 半透明黑色背景 + borderRadius: BorderRadius.circular(8), // 圆角效果 + border: Border.all(color: Colors.white.withOpacity(0.3), width: 0.5), // 可选:加一层浅边框 + ), + child: Text( + _getViewName(), + style: const TextStyle( + color: Colors.white, + fontSize: 12, + fontWeight: FontWeight.bold, + shadows: [Shadow(color: Colors.black, blurRadius: 2)], // 可选:文字加阴影更清晰 + ), + ), + ), + ), + // 关闭按钮(右上角,修正位置) + Positioned( + top: 10, + right: 10, + child: GestureDetector( + onTap: widget.onClose, + child: Container( + width: 24, + height: 24, + decoration: const BoxDecoration( + color: Colors.red, + shape: BoxShape.circle, + boxShadow: [BoxShadow(color: Colors.black, blurRadius: 2)], + ), + child: const Icon(Icons.close, color: Colors.white, size: 16), + ), + ), + ), + // 悬浮小窗(小弹窗内的迷你窗) + if (widget.showLeftPip) _buildFastPip(_leftPosNotifier, Alignment.bottomLeft), + if (widget.showRightPip) _buildFastPip(_rightPosNotifier, Alignment.bottomRight), + ], + ) + : const Center(child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2)), + ); + } +} +