add BottomNavigationBar/change dirs structure

This commit is contained in:
csf
2022-02-28 18:29:25 +08:00
parent 034d825b74
commit e6b1ff40be
8 changed files with 169 additions and 140 deletions

441
lib/pages/home_page.dart Normal file
View File

@@ -0,0 +1,441 @@
import 'package:flutter/material.dart';
import 'package:flutter_hbb/pages/server_page.dart';
import 'package:provider/provider.dart';
import 'package:tuple/tuple.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:async';
import '../common.dart';
import '../models/model.dart';
import 'remote_page.dart';
abstract class PageShape extends Widget {
final String title = "";
final Icon icon = Icon(null);
final List<Widget> appBarActions = [];
}
class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
var _selectedIndex = 0;
final List<PageShape> _pages = [ConnectionPage(), ServerPage()];
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: MyTheme.grayBg,
appBar: AppBar(
centerTitle: true,
title: Text("RustDesk"),
actions: _pages.elementAt(_selectedIndex).appBarActions,
),
bottomNavigationBar: BottomNavigationBar(
items: _pages
.map((page) =>
BottomNavigationBarItem(icon: page.icon, label: page.title))
.toList(),
currentIndex: _selectedIndex,
type: BottomNavigationBarType.fixed,
selectedItemColor: MyTheme.accent,
unselectedItemColor: MyTheme.darkGray,
onTap: (index) => setState(() {
_selectedIndex = index;
}),
),
body: _pages.elementAt(_selectedIndex),
);
}
}
class ConnectionPage extends StatefulWidget implements PageShape {
ConnectionPage({Key? key}) : super(key: key);
@override
final icon = Icon(Icons.connected_tv);
@override
final title = translate("Connection");
@override
final appBarActions = [
PopupMenuButton<String>(
itemBuilder: (context) => [
PopupMenuItem<String>(
child: Text(translate('ID Server')), value: 'id_server'),
PopupMenuItem<String>(
child: Text(translate('About') + ' RustDesk'), value: 'about')
],
onSelected: (value) {
if (value == 'id_server') {
showServer();
} else if (value == 'about') {
showAbout();
}
})
];
@override
_ConnectionPageState createState() => _ConnectionPageState();
}
class _ConnectionPageState extends State<ConnectionPage> {
final _idController = TextEditingController();
var _updateUrl = '';
var _menuPos;
@override
void initState() {
super.initState();
if (isAndroid) {
Timer(Duration(seconds: 5), () {
_updateUrl = FFI.getByName('software_update_url');
if (_updateUrl.isNotEmpty) setState(() {});
});
}
}
@override
Widget build(BuildContext context) {
Provider.of<FfiModel>(context);
if (_idController.text.isEmpty) _idController.text = FFI.getId();
return SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
getUpdateUI(),
getSearchBarUI(),
Container(height: 12),
getPeers(),
]),
);
}
void onConnect() {
var id = _idController.text.trim();
connect(id);
}
void connect(String id) {
if (id == '') return;
id = id.replaceAll(' ', '');
() async {
await Navigator.push<dynamic>(
context,
MaterialPageRoute<dynamic>(
builder: (BuildContext context) => RemotePage(id: id),
),
);
setState(() {});
}();
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
}
Widget getUpdateUI() {
return _updateUrl.isEmpty
? SizedBox(height: 0)
: InkWell(
onTap: () async {
final url = _updateUrl + '.apk';
if (await canLaunch(url)) {
await launch(url);
}
},
child: Container(
alignment: AlignmentDirectional.center,
width: double.infinity,
color: Colors.pinkAccent,
padding: EdgeInsets.symmetric(vertical: 12),
child: Text(translate('Download new version'),
style: TextStyle(
color: Colors.white, fontWeight: FontWeight.bold))));
}
Widget getSearchBarUI() {
if (!FFI.ffiModel.initialized) {
return Container();
}
var w = Padding(
padding: const EdgeInsets.fromLTRB(16.0, 8.0, 16.0, 0.0),
child: Container(
height: 84,
child: Padding(
padding: const EdgeInsets.only(top: 8, bottom: 8),
child: Ink(
decoration: BoxDecoration(
color: MyTheme.white,
borderRadius: const BorderRadius.only(
bottomRight: Radius.circular(13.0),
bottomLeft: Radius.circular(13.0),
topLeft: Radius.circular(13.0),
topRight: Radius.circular(13.0),
),
),
child: Row(
children: <Widget>[
Expanded(
child: Container(
padding: const EdgeInsets.only(left: 16, right: 16),
child: TextField(
autocorrect: false,
enableSuggestions: false,
keyboardType: TextInputType.visiblePassword,
// keyboardType: TextInputType.number,
style: TextStyle(
fontFamily: 'WorkSans',
fontWeight: FontWeight.bold,
fontSize: 30,
color: MyTheme.idColor,
),
decoration: InputDecoration(
labelText: translate('Remote ID'),
// hintText: 'Enter your remote ID',
border: InputBorder.none,
helperStyle: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
color: MyTheme.darkGray,
),
labelStyle: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 16,
letterSpacing: 0.2,
color: MyTheme.darkGray,
),
),
autofocus: _idController.text.isEmpty,
controller: _idController,
),
),
),
SizedBox(
width: 60,
height: 60,
child: IconButton(
icon: Icon(Icons.arrow_forward,
color: MyTheme.darkGray, size: 45),
onPressed: onConnect,
autofocus: _idController.text.isNotEmpty,
),
)
],
),
),
),
),
);
return Center(
child: Container(constraints: BoxConstraints(maxWidth: 600), child: w));
}
@override
void dispose() {
_idController.dispose();
super.dispose();
}
Widget getPlatformImage(String platform) {
platform = platform.toLowerCase();
if (platform == 'mac os')
platform = 'mac';
else if (platform != 'linux') platform = 'win';
return Image.asset('assets/$platform.png', width: 24, height: 24);
}
Widget getPeers() {
if (!FFI.ffiModel.initialized) {
return Container();
}
final size = MediaQuery.of(context).size;
final space = 8.0;
var width = size.width - 2 * space;
final minWidth = 320.0;
if (size.width > minWidth + 2 * space) {
final n = (size.width / (minWidth + 2 * space)).floor();
width = size.width / n - 2 * space;
}
final cards = <Widget>[];
var peers = FFI.peers();
peers.forEach((p) {
cards.add(Container(
width: width,
child: Card(
child: GestureDetector(
onTap: () => {
if (!isDesktop) {connect('${p.id}')}
},
onDoubleTap: () => {
if (isDesktop) {connect('${p.id}')}
},
onLongPressStart: (details) {
var x = details.globalPosition.dx;
var y = details.globalPosition.dy;
this._menuPos = RelativeRect.fromLTRB(x, y, x, y);
this.showPeerMenu(context, p.id);
},
child: ListTile(
contentPadding: const EdgeInsets.only(left: 12),
subtitle: Text('${p.username}@${p.hostname}'),
title: Text('${p.id}'),
leading: Container(
padding: const EdgeInsets.all(6),
child: getPlatformImage('${p.platform}'),
color: str2color('${p.id}${p.platform}', 0x7f)),
trailing: InkWell(
child: Padding(
padding: const EdgeInsets.all(12),
child: Icon(Icons.more_vert)),
onTapDown: (e) {
var x = e.globalPosition.dx;
var y = e.globalPosition.dy;
this._menuPos = RelativeRect.fromLTRB(x, y, x, y);
},
onDoubleTap: () {},
onTap: () {
showPeerMenu(context, p.id);
}),
)))));
});
return Wrap(children: cards, spacing: space, runSpacing: space);
}
void showPeerMenu(BuildContext context, String id) async {
var value = await showMenu(
context: context,
position: this._menuPos,
items: [
PopupMenuItem<String>(
child: Text(translate('Remove')), value: 'remove'),
],
elevation: 8,
);
if (value == 'remove') {
setState(() => FFI.setByName('remove', '$id'));
() async {
removePreference(id);
}();
}
}
}
void showServer() {
final formKey = GlobalKey<FormState>();
final id0 = FFI.getByName('option', 'custom-rendezvous-server');
final relay0 = FFI.getByName('option', 'relay-server');
final key0 = FFI.getByName('option', 'key');
var id = '';
var relay = '';
var key = '';
showAlertDialog((setState) => Tuple3(
Text(translate('ID Server')),
Form(
key: formKey,
child: Column(mainAxisSize: MainAxisSize.min, children: <Widget>[
TextFormField(
initialValue: id0,
decoration: InputDecoration(
labelText: translate('ID Server'),
),
validator: validate,
onSaved: (String? value) {
if (value != null) id = value.trim();
},
),
/*
TextFormField(
initialValue: relay0,
decoration: InputDecoration(
labelText: translate('Relay Server'),
),
validator: validate,
onSaved: (String value) {
relay = value.trim();
},
),
*/
TextFormField(
initialValue: key0,
decoration: InputDecoration(
labelText: 'Key',
),
validator: null,
onSaved: (String? value) {
if (value != null) key = value.trim();
},
),
])),
[
TextButton(
style: flatButtonStyle,
onPressed: () {
DialogManager.reset();
},
child: Text(translate('Cancel')),
),
TextButton(
style: flatButtonStyle,
onPressed: () {
if (formKey.currentState != null &&
formKey.currentState!.validate()) {
formKey.currentState!.save();
if (id != id0)
FFI.setByName('option',
'{"name": "custom-rendezvous-server", "value": "$id"}');
if (relay != relay0)
FFI.setByName(
'option', '{"name": "relay-server", "value": "$relay"}');
if (key != key0)
FFI.setByName('option', '{"name": "key", "value": "$key"}');
DialogManager.reset();
}
},
child: Text(translate('OK')),
),
],
));
}
Future<Null> showAbout() async {
var version = await FFI.getVersion();
showAlertDialog(
(setState) => Tuple3(
SizedBox.shrink(), // TODO test old:null
Wrap(direction: Axis.vertical, spacing: 12, children: [
Text('Version: $version'),
InkWell(
onTap: () async {
const url = 'https://rustdesk.com/';
if (await canLaunch(url)) {
await launch(url);
}
},
child: Padding(
padding: EdgeInsets.symmetric(vertical: 8),
child: Text('Support',
style: TextStyle(
decoration: TextDecoration.underline,
)),
)),
]),
[]),
() async => true,
true);
}
String? validate(value) {
value = value.trim();
if (value.isEmpty) {
return null;
}
final res = FFI.getByName('test_if_valid_server', value);
return res.isEmpty ? null : res;
}

1037
lib/pages/remote_page.dart Normal file

File diff suppressed because it is too large Load Diff

449
lib/pages/server_page.dart Normal file
View File

@@ -0,0 +1,449 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_hbb/main.dart';
import 'package:flutter_hbb/models/model.dart';
import 'package:provider/provider.dart';
import '../common.dart';
import 'home_page.dart';
import '../models/model.dart';
class ServerPage extends StatelessWidget implements PageShape {
@override
final title = "Share Screen";
@override
final icon = Icon(Icons.mobile_screen_share);
@override
final appBarActions = [
PopupMenuButton<String>(
itemBuilder: (context) {
return [
PopupMenuItem(
child: Text(translate("Change ID")),
value: "changeID",
enabled: false,
),
PopupMenuItem(
child: Text("Set your own password"),
value: "changePW",
enabled: false,
)
];
},
onSelected: (value) => debugPrint("PopupMenuItem onSelected:$value"))
];
@override
Widget build(BuildContext context) {
checkService();
return ChangeNotifierProvider.value(
value: FFI.serverModel,
child: SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
ServerInfo(),
PermissionChecker(),
ConnectionManager(),
SizedBox.fromSize(size: Size(0, 15.0)), // Bottom padding
],
),
),
),
);
}
}
void checkService() {
// 检测当前服务状态,若已存在服务则异步更新数据回来
FFI.invokeMethod("check_service"); // jvm
FFI.serverModel.updateClientState();
}
class ServerInfo extends StatefulWidget {
@override
_ServerInfoState createState() => _ServerInfoState();
}
class _ServerInfoState extends State<ServerInfo> {
var _passwdShow = false;
// TODO set ID / PASSWORD
var _serverId = TextEditingController(text: "");
var _serverPasswd = TextEditingController(text: "");
var _emptyIdShow = translate("connecting_status");
@override
void initState() {
super.initState();
var id = FFI.getByName("server_id");
_serverId.text = id == "" ? _emptyIdShow : id;
_serverPasswd.text = FFI.getByName("server_password");
if (_serverId.text == _emptyIdShow || _serverPasswd.text == "") {
fetchConfigAgain();
}
}
@override
Widget build(BuildContext context) {
return myCard(Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
readOnly: true,
style: TextStyle(
fontSize: 25.0,
fontWeight: FontWeight.bold,
color: MyTheme.accent),
controller: _serverId,
decoration: InputDecoration(
icon: const Icon(Icons.perm_identity),
labelText: translate("ID"),
labelStyle:
TextStyle(fontWeight: FontWeight.bold, color: MyTheme.accent50),
),
onSaved: (String? value) {},
),
TextFormField(
readOnly: true,
obscureText: !_passwdShow,
style: TextStyle(
fontSize: 25.0,
fontWeight: FontWeight.bold,
color: MyTheme.accent),
controller: _serverPasswd,
decoration: InputDecoration(
icon: const Icon(Icons.lock),
labelText: translate("Password"),
labelStyle: TextStyle(
fontWeight: FontWeight.bold, color: MyTheme.accent50),
suffix: IconButton(
icon: Icon(Icons.visibility),
onPressed: () {
setState(() {
_passwdShow = !_passwdShow;
});
})),
onSaved: (String? value) {},
),
],
));
}
fetchConfigAgain() async {
FFI.setByName("start_service");
var count = 0;
const maxCount = 10;
while (count < maxCount) {
if (_serverId.text != _emptyIdShow && _serverPasswd.text != "") {
break;
}
await Future.delayed(Duration(seconds: 2));
var id = FFI.getByName("server_id");
_serverId.text = id == "" ? _emptyIdShow : id;
_serverPasswd.text = FFI.getByName("server_password");
debugPrint(
"fetch id & passwd again at $count:id:${_serverId.text},passwd:${_serverPasswd.text}");
count++;
}
FFI.setByName("stop_service");
}
}
class PermissionChecker extends StatefulWidget {
@override
_PermissionCheckerState createState() => _PermissionCheckerState();
}
class _PermissionCheckerState extends State<PermissionChecker> {
@override
Widget build(BuildContext context) {
final serverModel = Provider.of<ServerModel>(context);
return myCard(Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
cardTitle(translate("Configuration Permissions")),
PermissionRow(
translate("Media"), serverModel.mediaOk, _toAndroidInitService),
const Divider(height: 0),
PermissionRow(
translate("Input"), serverModel.inputOk, showInputWarnAlert),
const Divider(),
serverModel.mediaOk
? ElevatedButton.icon(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.red)),
icon: Icon(Icons.stop),
onPressed: _toAndroidStopService,
label: Text(translate("Stop service")))
: ElevatedButton.icon(
icon: Icon(Icons.play_arrow),
onPressed: _toAndroidInitService,
label: Text(translate("Start Service"))),
],
));
}
}
Widget getConnInfo(String name, String peerID) {
return Row(
children: [
CircleAvatar(child: Text(name[0]), backgroundColor: MyTheme.border),
SizedBox(width: 12),
Text(name, style: TextStyle(color: MyTheme.idColor)),
SizedBox(width: 8),
Text(peerID, style: TextStyle(color: MyTheme.idColor))
],
);
}
void showLoginReqAlert(String peerID, String name) async {
if (globalKey.currentContext == null) return;
await showDialog(
barrierDismissible: false,
context: globalKey.currentContext!,
builder: (alertContext) {
DialogManager.reset();
DialogManager.register(alertContext);
return AlertDialog(
title: Text("Control Request"),
content: Container(
height: 100,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(translate("Do you accept?")),
SizedBox(height: 20),
getConnInfo(name, peerID),
],
)),
actions: [
TextButton(
child: Text(translate("Dismiss")),
onPressed: () {
FFI.setByName("login_res", "false");
DialogManager.reset();
}),
ElevatedButton(
child: Text(translate("Accept")),
onPressed: () {
FFI.setByName("login_res", "true");
if (!FFI.serverModel.isFileTransfer) {
_toAndroidStartCapture();
}
FFI.serverModel.setPeer(true);
DialogManager.reset();
}),
],
);
});
DialogManager.reset();
}
class PermissionRow extends StatelessWidget {
PermissionRow(this.name, this.isOk, this.onPressed);
final String name;
final bool isOk;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
SizedBox(
width: 60,
child: Text(name + ":",
style: TextStyle(fontSize: 16.0, color: MyTheme.accent50))),
SizedBox(
width: 50,
child: Text(isOk ? translate("ON") : translate("OFF"),
style: TextStyle(
fontSize: 16.0,
color: isOk ? Colors.green : Colors.grey)),
)
],
),
TextButton(
onPressed: isOk ? null : onPressed,
child: Text(
translate("OPEN"),
style: TextStyle(fontWeight: FontWeight.bold),
)),
],
);
}
}
class ConnectionManager extends StatelessWidget {
@override
Widget build(BuildContext context) {
final serverModel = Provider.of<ServerModel>(context);
return serverModel.isPeerStart
? myCard(Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
cardTitle(translate("Connection")), // TODO t
Padding(
padding: EdgeInsets.symmetric(vertical: 5.0),
child: getConnInfo(serverModel.peerName, serverModel.peerID),
),
ElevatedButton.icon(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.red)),
icon: Icon(Icons.close),
onPressed: () {
FFI.setByName("close_conn");
// _toAndroidStopCapture();
serverModel.setPeer(false);
},
label: Text(translate("Close")))
],
))
: SizedBox.shrink();
}
}
Widget cardTitle(String text) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 5.0),
child: Text(
text,
style: TextStyle(
fontFamily: 'WorkSans',
fontWeight: FontWeight.bold,
fontSize: 22,
color: MyTheme.accent80,
),
));
}
Widget myCard(Widget child) {
return Container(
width: double.maxFinite,
child: Card(
margin: EdgeInsets.fromLTRB(15.0, 15.0, 15.0, 0),
child: Padding(
padding: EdgeInsets.symmetric(vertical: 15.0, horizontal: 30.0),
child: child,
),
));
}
Future<Null> _toAndroidInitService() async {
bool res = await FFI.invokeMethod("init_service");
FFI.setByName("start_service");
debugPrint("_toAndroidInitService:$res");
}
Future<Null> _toAndroidStartCapture() async {
bool res = await FFI.invokeMethod("start_capture");
debugPrint("_toAndroidStartCapture:$res");
}
// Future<Null> _toAndroidStopCapture() async {
// bool res = await FFI.invokeMethod("stop_capture");
// debugPrint("_toAndroidStopCapture:$res");
// }
Future<Null> _toAndroidStopService() async {
FFI.setByName("close_conn");
FFI.serverModel.setPeer(false);
bool res = await FFI.invokeMethod("stop_service");
FFI.setByName("stop_service");
debugPrint("_toAndroidStopSer:$res");
}
Future<Null> _toAndroidInitInput() async {
bool res = await FFI.invokeMethod("init_input");
debugPrint("_toAndroidInitInput:$res");
}
showInputWarnAlert() async {
if (globalKey.currentContext == null) return;
DialogManager.reset();
await showDialog<bool>(
context: globalKey.currentContext!,
builder: (alertContext) {
// TODO t
DialogManager.register(alertContext);
return AlertDialog(
title: Text("获取输入权限引导"),
// content: Text("请在接下来的系统设置页面 \n进入 [服务] 配置页面\n将[RustDesk Input]服务开启"),
content: Text.rich(TextSpan(style: TextStyle(), children: [
TextSpan(text: "请在接下来的系统设置页\n进入"),
TextSpan(text: " [服务] ", style: TextStyle(color: MyTheme.accent)),
TextSpan(text: "配置页面\n"),
TextSpan(
text: " [RustDesk Input] ",
style: TextStyle(color: MyTheme.accent)),
TextSpan(text: "服务开启")
])),
actions: [
TextButton(
child: Text(translate("Do nothing")),
onPressed: () {
DialogManager.reset();
}),
ElevatedButton(
child: Text(translate("Go System Setting")),
onPressed: () {
_toAndroidInitInput();
DialogManager.reset();
}),
],
);
});
DialogManager.reset();
}
void toAndroidChannelInit() {
FFI.setMethodCallHandler((method, arguments) {
debugPrint("flutter got android msg,$method,$arguments");
try {
switch (method) {
case "try_start_without_auth":
{
FFI.serverModel.updateClientState();
debugPrint(
"pre show loginAlert:${FFI.serverModel.isFileTransfer.toString()}");
showLoginReqAlert(FFI.serverModel.peerID, FFI.serverModel.peerName);
debugPrint("from jvm:try_start_without_auth done");
break;
}
case "start_capture":
{
DialogManager.reset();
FFI.serverModel.updateClientState();
break;
}
case "stop_capture":
{
DialogManager.reset();
FFI.serverModel.setPeer(false);
break;
}
case "on_permission_changed":
{
var name = arguments["name"] as String;
var value = arguments["value"] as String == "true";
debugPrint("from jvm:on_permission_changed,$name:$value");
FFI.serverModel.changeStatue(name, value);
break;
}
}
} catch (e) {
debugPrint("MethodCallHandler err:$e");
}
return "";
});
}