flutter_desktop_online_state: refactor connection page

Signed-off-by: fufesou <shuanglongchen@yeah.net>
This commit is contained in:
fufesou
2022-07-27 22:56:28 +08:00
parent b6d56790fe
commit 0ba8b4079b
15 changed files with 1152 additions and 101 deletions

View File

@@ -0,0 +1,244 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:provider/provider.dart';
import 'package:visibility_detector/visibility_detector.dart';
import 'package:window_manager/window_manager.dart';
import '../../models/peer_model.dart';
import '../../common.dart';
import 'peercard_widget.dart';
typedef OffstageFunc = bool Function(Peer peer);
typedef PeerCardWidgetFunc = Widget Function(Peer peer);
class _PeerWidget extends StatefulWidget {
late final _name;
late final _peers;
late final OffstageFunc _offstageFunc;
late final PeerCardWidgetFunc _peerCardWidgetFunc;
_PeerWidget(String name, List<Peer> peers, OffstageFunc offstageFunc,
PeerCardWidgetFunc peerCardWidgetFunc,
{Key? key})
: super(key: key) {
_name = name;
_peers = peers;
_offstageFunc = offstageFunc;
_peerCardWidgetFunc = peerCardWidgetFunc;
}
@override
_PeerWidgetState createState() => _PeerWidgetState();
}
/// State for the peer widget.
class _PeerWidgetState extends State<_PeerWidget> with WindowListener {
static const int _maxQueryCount = 3;
var _curPeers = Set<String>();
var _lastChangeTime = DateTime.now();
var _lastQueryPeers = Set<String>();
var _lastQueryTime = DateTime.now().subtract(Duration(hours: 1));
var _queryCoun = 0;
var _exit = false;
_PeerWidgetState() {
_startCheckOnlines();
}
@override
void initState() {
windowManager.addListener(this);
super.initState();
}
@override
void dispose() {
windowManager.removeListener(this);
_exit = true;
super.dispose();
}
@override
void onWindowFocus() {
_queryCoun = 0;
}
@override
Widget build(BuildContext context) {
final space = 8.0;
return ChangeNotifierProvider<Peers>(
create: (context) => Peers(super.widget._name, super.widget._peers),
child: SingleChildScrollView(
child: Consumer<Peers>(
builder: (context, peers, child) => Wrap(
children: () {
final cards = <Widget>[];
peers.peers.forEach((peer) {
cards.add(Offstage(
offstage: super.widget._offstageFunc(peer),
child: Container(
width: 225,
height: 150,
child: VisibilityDetector(
key: Key('${peer.id}'),
onVisibilityChanged: (info) {
final peerId = (info.key as ValueKey).value;
if (info.visibleFraction > 0.00001) {
_curPeers.add(peerId);
} else {
_curPeers.remove(peerId);
}
_lastChangeTime = DateTime.now();
},
child: super.widget._peerCardWidgetFunc(peer),
),
)));
});
return cards;
}(),
spacing: space,
runSpacing: space))),
);
}
// ignore: todo
// TODO: variables walk through async tasks?
void _startCheckOnlines() {
() async {
while (!_exit) {
final now = DateTime.now();
if (!setEquals(_curPeers, _lastQueryPeers)) {
if (now.difference(_lastChangeTime) > Duration(seconds: 1)) {
gFFI.ffiModel.platformFFI.ffiBind
.queryOnlines(ids: _curPeers.toList(growable: false));
_lastQueryPeers = {..._curPeers};
_lastQueryTime = DateTime.now();
_queryCoun = 0;
}
} else {
if (_queryCoun < _maxQueryCount) {
if (now.difference(_lastQueryTime) > Duration(seconds: 20)) {
gFFI.ffiModel.platformFFI.ffiBind
.queryOnlines(ids: _curPeers.toList(growable: false));
_lastQueryTime = DateTime.now();
_queryCoun += 1;
}
}
}
await Future.delayed(Duration(milliseconds: 300));
}
}();
}
}
abstract class BasePeerWidget extends StatelessWidget {
late final _name;
late final OffstageFunc _offstageFunc;
late final PeerCardWidgetFunc _peerCardWidgetFunc;
BasePeerWidget({Key? key}) : super(key: key) {}
@override
Widget build(BuildContext context) {
return FutureBuilder<Widget>(future: () async {
return _PeerWidget(
_name, await _loadPeers(), _offstageFunc, _peerCardWidgetFunc);
}(), builder: (context, snapshot) {
if (snapshot.hasData) {
return snapshot.data!;
} else {
return Offstage();
}
});
}
@protected
Future<List<Peer>> _loadPeers();
}
class RecentPeerWidget extends BasePeerWidget {
RecentPeerWidget({Key? key}) : super(key: key) {
super._name = "recent peer";
super._offstageFunc = (Peer _peer) => false;
super._peerCardWidgetFunc = (Peer peer) => RecentPeerCard(peer: peer);
}
Future<List<Peer>> _loadPeers() async {
return gFFI.peers();
}
}
class FavoritePeerWidget extends BasePeerWidget {
FavoritePeerWidget({Key? key}) : super(key: key) {
super._name = "favorite peer";
super._offstageFunc = (Peer _peer) => false;
super._peerCardWidgetFunc = (Peer peer) => FavoritePeerCard(peer: peer);
}
@override
Future<List<Peer>> _loadPeers() async {
return await gFFI.bind.mainGetFav().then((peers) async {
final peersEntities = await Future.wait(peers
.map((id) => gFFI.bind.mainGetPeers(id: id))
.toList(growable: false))
.then((peers_str) {
final len = peers_str.length;
final ps = List<Peer>.empty(growable: true);
for (var i = 0; i < len; i++) {
print("${peers[i]}: ${peers_str[i]}");
ps.add(Peer.fromJson(peers[i], jsonDecode(peers_str[i])['info']));
}
return ps;
});
return peersEntities;
});
}
}
class DiscoveredPeerWidget extends BasePeerWidget {
DiscoveredPeerWidget({Key? key}) : super(key: key) {
super._name = "discovered peer";
super._offstageFunc = (Peer _peer) => false;
super._peerCardWidgetFunc = (Peer peer) => DiscoveredPeerCard(peer: peer);
}
Future<List<Peer>> _loadPeers() async {
return await gFFI.bind.mainGetLanPeers().then((peers_string) {
debugPrint(peers_string);
return [];
});
}
}
class AddressBookPeerWidget extends BasePeerWidget {
AddressBookPeerWidget({Key? key}) : super(key: key) {
super._name = "address book peer";
super._offstageFunc =
(Peer peer) => !_hitTag(gFFI.abModel.selectedTags, peer.tags);
super._peerCardWidgetFunc = (Peer peer) => AddressBookPeerCard(peer: peer);
}
Future<List<Peer>> _loadPeers() async {
return gFFI.abModel.peers.map((e) {
return Peer.fromJson(e['id'], e);
}).toList();
}
bool _hitTag(List<dynamic> selectedTags, List<dynamic> idents) {
if (selectedTags.isEmpty) {
return true;
}
if (idents.isEmpty) {
return false;
}
for (final tag in selectedTags) {
if (!idents.contains(tag)) {
return false;
}
}
return true;
}
}

View File

@@ -0,0 +1,371 @@
import 'package:flutter/material.dart';
import 'package:flutter_hbb/utils/multi_window_manager.dart';
import 'package:get/get.dart';
import 'package:contextmenu/contextmenu.dart';
import '../../common.dart';
import '../../models/model.dart';
import '../../models/peer_model.dart';
class _PeerCard extends StatefulWidget {
final Peer peer;
final List<PopupMenuItem<String>> popupMenuItems;
_PeerCard({required this.peer, required this.popupMenuItems, Key? key})
: super(key: key);
@override
_PeerCardState createState() => _PeerCardState();
}
/// State for the connection page.
class _PeerCardState extends State<_PeerCard> {
var _menuPos;
@override
Widget build(BuildContext context) {
final peer = super.widget.peer;
var deco = Rx<BoxDecoration?>(BoxDecoration(
border: Border.all(color: Colors.transparent, width: 1.0),
borderRadius: BorderRadius.circular(20)));
return Card(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
child: MouseRegion(
onEnter: (evt) {
deco.value = BoxDecoration(
border: Border.all(color: Colors.blue, width: 1.0),
borderRadius: BorderRadius.circular(20));
},
onExit: (evt) {
deco.value = BoxDecoration(
border: Border.all(color: Colors.transparent, width: 1.0),
borderRadius: BorderRadius.circular(20));
},
child: _buildPeerTile(context, peer, deco),
));
}
Widget _buildPeerTile(
BuildContext context, Peer peer, Rx<BoxDecoration?> deco) {
return Obx(
() => Container(
decoration: deco.value,
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: Container(
decoration: BoxDecoration(
color: str2color('${peer.id}${peer.platform}', 0x7f),
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
),
),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
padding: const EdgeInsets.all(6),
child: _getPlatformImage('${peer.platform}'),
),
Row(
children: [
Expanded(
child: Tooltip(
message: '${peer.username}@${peer.hostname}',
child: Text(
'${peer.username}@${peer.hostname}',
style: TextStyle(
color: Colors.white70, fontSize: 12),
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
),
),
),
],
),
],
).paddingAll(4.0),
),
],
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(children: [
Padding(
padding: EdgeInsets.fromLTRB(0, 4, 8, 4),
child: CircleAvatar(
radius: 5,
backgroundColor:
peer.online ? Colors.green : Colors.yellow)),
Text('${peer.id}')
]),
InkWell(
child: Icon(Icons.more_vert),
onTapDown: (e) {
final x = e.globalPosition.dx;
final y = e.globalPosition.dy;
_menuPos = RelativeRect.fromLTRB(x, y, x, y);
},
onTap: () {
_showPeerMenu(context, peer.id);
}),
],
).paddingSymmetric(vertical: 8.0, horizontal: 12.0)
],
),
),
);
}
/// Connect to a peer with [id].
/// If [isFileTransfer], starts a session only for file transfer.
void _connect(String id, {bool isFileTransfer = false}) async {
if (id == '') return;
id = id.replaceAll(' ', '');
if (isFileTransfer) {
await rustDeskWinManager.new_file_transfer(id);
} else {
await rustDeskWinManager.new_remote_desktop(id);
}
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
}
/// Show the peer menu and handle user's choice.
/// User might remove the peer or send a file to the peer.
void _showPeerMenu(BuildContext context, String id) async {
var value = await showMenu(
context: context,
position: this._menuPos,
items: super.widget.popupMenuItems,
elevation: 8,
);
if (value == 'remove') {
setState(() => gFFI.setByName('remove', '$id'));
() async {
removePreference(id);
}();
} else if (value == 'file') {
_connect(id, isFileTransfer: true);
} else if (value == 'add-fav') {
} else if (value == 'connect') {
_connect(id, isFileTransfer: false);
} else if (value == 'ab-delete') {
gFFI.abModel.deletePeer(id);
await gFFI.abModel.updateAb();
setState(() {});
} else if (value == 'ab-edit-tag') {
_abEditTag(id);
}
}
Widget _buildTag(String tagName, RxList<dynamic> rxTags,
{Function()? onTap}) {
return ContextMenuArea(
width: 100,
builder: (context) => [
ListTile(
title: Text(translate("Delete")),
onTap: () {
gFFI.abModel.deleteTag(tagName);
gFFI.abModel.updateAb();
Future.delayed(Duration.zero, () => Get.back());
},
)
],
child: GestureDetector(
onTap: onTap,
child: Obx(
() => Container(
decoration: BoxDecoration(
color: rxTags.contains(tagName) ? Colors.blue : null,
border: Border.all(color: MyTheme.darkGray),
borderRadius: BorderRadius.circular(10)),
margin: EdgeInsets.symmetric(horizontal: 4.0, vertical: 8.0),
padding: EdgeInsets.symmetric(vertical: 2.0, horizontal: 8.0),
child: Text(
tagName,
style: TextStyle(
color: rxTags.contains(tagName) ? MyTheme.white : null),
),
),
),
),
);
}
/// Get the image for the current [platform].
Widget _getPlatformImage(String platform) {
platform = platform.toLowerCase();
if (platform == 'mac os')
platform = 'mac';
else if (platform != 'linux' && platform != 'android') platform = 'win';
return Image.asset('assets/$platform.png', height: 50);
}
void _abEditTag(String id) {
var isInProgress = false;
final tags = List.of(gFFI.abModel.tags);
var selectedTag = gFFI.abModel.getPeerTags(id).obs;
DialogManager.show((setState, close) {
return CustomAlertDialog(
title: Text(translate("Edit Tag")),
content: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: Wrap(
children: tags
.map((e) => _buildTag(e, selectedTag, onTap: () {
if (selectedTag.contains(e)) {
selectedTag.remove(e);
} else {
selectedTag.add(e);
}
}))
.toList(growable: false),
),
),
Offstage(offstage: !isInProgress, child: LinearProgressIndicator())
],
),
actions: [
TextButton(
onPressed: () {
close();
},
child: Text(translate("Cancel"))),
TextButton(
onPressed: () async {
setState(() {
isInProgress = true;
});
gFFI.abModel.changeTagForPeer(id, selectedTag);
await gFFI.abModel.updateAb();
close();
},
child: Text(translate("OK"))),
],
);
});
}
}
abstract class BasePeerCard extends StatelessWidget {
final Peer peer;
BasePeerCard({required this.peer, Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return _PeerCard(peer: peer, popupMenuItems: _getPopupMenuItems());
}
@protected
List<PopupMenuItem<String>> _getPopupMenuItems();
}
class RecentPeerCard extends BasePeerCard {
RecentPeerCard({required Peer peer, Key? key}) : super(peer: peer, key: key);
List<PopupMenuItem<String>> _getPopupMenuItems() {
return [
PopupMenuItem<String>(
child: Text(translate('Connect')), value: 'connect'),
PopupMenuItem<String>(
child: Text(translate('Transfer File')), value: 'file'),
PopupMenuItem<String>(
child: Text(translate('TCP Tunneling')), value: 'tcp-tunnel'),
PopupMenuItem<String>(child: Text(translate('Rename')), value: 'rename'),
PopupMenuItem<String>(child: Text(translate('Remove')), value: 'remove'),
PopupMenuItem<String>(
child: Text(translate('Unremember Password')),
value: 'unremember-password'),
PopupMenuItem<String>(
child: Text(translate('Edit Tag')), value: 'ab-edit-tag'),
];
}
}
class FavoritePeerCard extends BasePeerCard {
FavoritePeerCard({required Peer peer, Key? key})
: super(peer: peer, key: key);
List<PopupMenuItem<String>> _getPopupMenuItems() {
return [
PopupMenuItem<String>(
child: Text(translate('Connect')), value: 'connect'),
PopupMenuItem<String>(
child: Text(translate('Transfer File')), value: 'file'),
PopupMenuItem<String>(
child: Text(translate('TCP Tunneling')), value: 'tcp-tunnel'),
PopupMenuItem<String>(child: Text(translate('Rename')), value: 'rename'),
PopupMenuItem<String>(child: Text(translate('Remove')), value: 'remove'),
PopupMenuItem<String>(
child: Text(translate('Unremember Password')),
value: 'unremember-password'),
PopupMenuItem<String>(
child: Text(translate('Remove from Favorites')), value: 'remove-fav'),
];
}
}
class DiscoveredPeerCard extends BasePeerCard {
DiscoveredPeerCard({required Peer peer, Key? key})
: super(peer: peer, key: key);
List<PopupMenuItem<String>> _getPopupMenuItems() {
return [
PopupMenuItem<String>(
child: Text(translate('Connect')), value: 'connect'),
PopupMenuItem<String>(
child: Text(translate('Transfer File')), value: 'file'),
PopupMenuItem<String>(
child: Text(translate('TCP Tunneling')), value: 'tcp-tunnel'),
PopupMenuItem<String>(child: Text(translate('Rename')), value: 'rename'),
PopupMenuItem<String>(child: Text(translate('Remove')), value: 'remove'),
PopupMenuItem<String>(
child: Text(translate('Unremember Password')),
value: 'unremember-password'),
PopupMenuItem<String>(
child: Text(translate('Edit Tag')), value: 'ab-edit-tag'),
];
}
}
class AddressBookPeerCard extends BasePeerCard {
AddressBookPeerCard({required Peer peer, Key? key})
: super(peer: peer, key: key);
List<PopupMenuItem<String>> _getPopupMenuItems() {
return [
PopupMenuItem<String>(
child: Text(translate('Connect')), value: 'connect'),
PopupMenuItem<String>(
child: Text(translate('Transfer File')), value: 'file'),
PopupMenuItem<String>(
child: Text(translate('TCP Tunneling')), value: 'tcp-tunnel'),
PopupMenuItem<String>(child: Text(translate('Rename')), value: 'rename'),
PopupMenuItem<String>(
child: Text(translate('Remove')), value: 'ab-delete'),
PopupMenuItem<String>(
child: Text(translate('Unremember Password')),
value: 'unremember-password'),
PopupMenuItem<String>(
child: Text(translate('Add to Favorites')), value: 'add-fav'),
];
}
}