Merge pull request #3560 from Heap-Hop/refactor_file_manager

Refactor file manager
This commit is contained in:
RustDesk 2023-03-10 12:51:07 +08:00 committed by GitHub
commit 9fe5a75233
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 1991 additions and 2096 deletions

File diff suppressed because it is too large Load Diff

View File

@ -3,7 +3,7 @@ import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_breadcrumb/flutter_breadcrumb.dart';
import 'package:flutter_hbb/models/file_model.dart';
import 'package:provider/provider.dart';
import 'package:get/get.dart';
import 'package:toggle_switch/toggle_switch.dart';
import 'package:wakelock/wakelock.dart';
@ -18,10 +18,51 @@ class FileManagerPage extends StatefulWidget {
State<StatefulWidget> createState() => _FileManagerPageState();
}
enum SelectMode { local, remote, none }
extension SelectModeEq on SelectMode {
bool eq(bool? currentIsLocal) {
if (currentIsLocal == null) {
return false;
}
if (currentIsLocal) {
return this == SelectMode.local;
} else {
return this == SelectMode.remote;
}
}
}
extension SelectModeExt on Rx<SelectMode> {
void toggle(bool currentIsLocal) {
switch (value) {
case SelectMode.local:
value = SelectMode.none;
break;
case SelectMode.remote:
value = SelectMode.none;
break;
case SelectMode.none:
if (currentIsLocal) {
value = SelectMode.local;
} else {
value = SelectMode.remote;
}
break;
}
}
}
class _FileManagerPageState extends State<FileManagerPage> {
final model = gFFI.fileModel;
final _selectedItems = SelectedItems();
final _breadCrumbScroller = ScrollController();
final selectMode = SelectMode.none.obs;
var showLocal = true;
FileController get currentFileController =>
showLocal ? model.localController : model.remoteController;
FileDirectory get currentDir => currentFileController.directory.value;
DirectoryOptions get currentOptions => currentFileController.options.value;
@override
void initState() {
@ -32,13 +73,12 @@ class _FileManagerPageState extends State<FileManagerPage> {
.showLoading(translate('Connecting...'), onCancel: closeConnection);
});
gFFI.ffiModel.updateEventListener(widget.id);
model.onDirChanged = (_) => breadCrumbScrollToEnd();
Wakelock.enable();
}
@override
void dispose() {
model.onClose().whenComplete(() {
model.close().whenComplete(() {
gFFI.close();
gFFI.dialogManager.dismissAll();
Wakelock.disable();
@ -47,15 +87,13 @@ class _FileManagerPageState extends State<FileManagerPage> {
}
@override
Widget build(BuildContext context) => ChangeNotifierProvider.value(
value: model,
child: Consumer<FileModel>(builder: (_context, _model, _child) {
return WillPopScope(
Widget build(BuildContext context) => WillPopScope(
onWillPop: () async {
if (model.selectMode) {
model.toggleSelectMode();
if (selectMode.value != SelectMode.none) {
selectMode.value = SelectMode.none;
setState(() {});
} else {
model.goBack();
currentFileController.goBack();
}
return false;
},
@ -65,19 +103,16 @@ class _FileManagerPageState extends State<FileManagerPage> {
leading: Row(children: [
IconButton(
icon: Icon(Icons.close),
onPressed: () =>
clientClose(widget.id, gFFI.dialogManager)),
onPressed: () => clientClose(widget.id, gFFI.dialogManager)),
]),
centerTitle: true,
title: ToggleSwitch(
initialLabelIndex: model.isLocal ? 0 : 1,
initialLabelIndex: showLocal ? 0 : 1,
activeBgColor: [MyTheme.idColor],
inactiveBgColor:
Theme.of(context).brightness == Brightness.light
inactiveBgColor: Theme.of(context).brightness == Brightness.light
? MyTheme.grayBg
: null,
inactiveFgColor:
Theme.of(context).brightness == Brightness.light
inactiveFgColor: Theme.of(context).brightness == Brightness.light
? Colors.black54
: null,
totalSwitches: 2,
@ -87,9 +122,9 @@ class _FileManagerPageState extends State<FileManagerPage> {
labels: [translate("Local"), translate("Remote")],
icons: [Icons.phone_android_sharp, Icons.screen_share],
onToggle: (index) {
final current = model.isLocal ? 0 : 1;
final current = showLocal ? 0 : 1;
if (index != current) {
model.togglePage();
setState(() => showLocal = !showLocal);
}
},
),
@ -110,7 +145,7 @@ class _FileManagerPageState extends State<FileManagerPage> {
value: "refresh",
),
PopupMenuItem(
enabled: model.currentDir.path != "/",
enabled: currentDir.path != "/",
child: Row(
children: [
Icon(Icons.check,
@ -122,7 +157,7 @@ class _FileManagerPageState extends State<FileManagerPage> {
value: "select",
),
PopupMenuItem(
enabled: model.currentDir.path != "/",
enabled: currentDir.path != "/",
child: Row(
children: [
Icon(Icons.folder_outlined,
@ -134,11 +169,11 @@ class _FileManagerPageState extends State<FileManagerPage> {
value: "folder",
),
PopupMenuItem(
enabled: model.currentDir.path != "/",
enabled: currentDir.path != "/",
child: Row(
children: [
Icon(
model.getCurrentShowHidden()
currentOptions.showHidden
? Icons.check_box_outlined
: Icons.check_box_outline_blank,
color: Theme.of(context).iconTheme.color),
@ -152,10 +187,12 @@ class _FileManagerPageState extends State<FileManagerPage> {
},
onSelected: (v) {
if (v == "refresh") {
model.refresh();
currentFileController.refresh();
} else if (v == "select") {
_selectedItems.clear();
model.toggleSelectMode();
model.localController.selectedItems.clear();
model.remoteController.selectedItems.clear();
selectMode.toggle(showLocal);
setState(() {});
} else if (v == "folder") {
final name = TextEditingController();
gFFI.dialogManager
@ -179,54 +216,222 @@ class _FileManagerPageState extends State<FileManagerPage> {
isOutline: true),
dialogButton("OK", onPressed: () {
if (name.value.text.isNotEmpty) {
model.createDir(PathUtil.join(
model.currentDir.path,
currentFileController.createDir(
PathUtil.join(
currentDir.path,
name.value.text,
model.getCurrentIsWindows()));
currentOptions.isWindows));
close();
}
})
]));
} else if (v == "hidden") {
model.toggleShowHidden();
currentFileController.toggleShowHidden();
}
}),
],
),
body: body(),
body: showLocal
? FileManagerView(
controller: model.localController,
selectMode: selectMode,
)
: FileManagerView(
controller: model.remoteController,
selectMode: selectMode,
),
bottomSheet: bottomSheet(),
));
}));
bool showCheckBox() {
if (!model.selectMode) {
return false;
Widget? bottomSheet() {
return Obx(() {
final selectedItems = getActiveSelectedItems();
final jobTable = model.jobController.jobTable;
final localLabel = selectedItems?.isLocal == null
? ""
: " [${selectedItems!.isLocal ? translate("Local") : translate("Remote")}]";
if (!(selectMode.value == SelectMode.none)) {
final selectedItemsLen =
"${selectedItems?.items.length ?? 0} ${translate("items")}";
if (selectedItems == null ||
selectedItems.items.isEmpty ||
selectMode.value.eq(showLocal)) {
return BottomSheetBody(
leading: Icon(Icons.check),
title: translate("Selected"),
text: selectedItemsLen + localLabel,
onCanceled: () {
selectedItems?.items.clear();
selectMode.value = SelectMode.none;
setState(() {});
},
actions: [
IconButton(
icon: Icon(Icons.compare_arrows),
onPressed: () => setState(() => showLocal = !showLocal),
),
IconButton(
icon: Icon(Icons.delete_forever),
onPressed: selectedItems != null
? () async {
if (selectedItems.items.isNotEmpty) {
await currentFileController
.removeAction(selectedItems);
selectedItems.items.clear();
selectMode.value = SelectMode.none;
}
}
: null,
)
]);
} else {
return BottomSheetBody(
leading: Icon(Icons.input),
title: translate("Paste here?"),
text: selectedItemsLen + localLabel,
onCanceled: () {
selectedItems.items.clear();
selectMode.value = SelectMode.none;
setState(() {});
},
actions: [
IconButton(
icon: Icon(Icons.compare_arrows),
onPressed: () => setState(() => showLocal = !showLocal),
),
IconButton(
icon: Icon(Icons.paste),
onPressed: () {
selectMode.value = SelectMode.none;
final otherSide = showLocal
? model.remoteController
: model.localController;
final thisSideData =
DirectoryData(currentDir, currentOptions);
otherSide.sendFiles(selectedItems, thisSideData);
selectedItems.items.clear();
selectMode.value = SelectMode.none;
},
)
]);
}
return !_selectedItems.isOtherPage(model.isLocal);
}
Widget body() {
final isLocal = model.isLocal;
final fd = model.currentDir;
final entries = fd.entries;
if (jobTable.isEmpty) {
return Offstage();
}
switch (jobTable.last.state) {
case JobState.inProgress:
return BottomSheetBody(
leading: CircularProgressIndicator(),
title: translate("Waiting"),
text:
"${translate("Speed")}: ${readableFileSize(jobTable.last.speed)}/s",
onCanceled: () {
model.jobController.cancelJob(jobTable.last.id);
jobTable.clear();
},
);
case JobState.done:
return BottomSheetBody(
leading: Icon(Icons.check),
title: "${translate("Successful")}!",
text: jobTable.last.display(),
onCanceled: () => jobTable.clear(),
);
case JobState.error:
return BottomSheetBody(
leading: Icon(Icons.error),
title: "${translate("Error")}!",
text: "",
onCanceled: () => jobTable.clear(),
);
case JobState.none:
break;
case JobState.paused:
// TODO: Handle this case.
break;
}
return Offstage();
});
}
SelectedItems? getActiveSelectedItems() {
final localSelectedItems = model.localController.selectedItems;
final remoteSelectedItems = model.remoteController.selectedItems;
if (localSelectedItems.items.isNotEmpty &&
remoteSelectedItems.items.isNotEmpty) {
// assert unreachable
debugPrint("Wrong SelectedItems state, reset");
localSelectedItems.clear();
remoteSelectedItems.clear();
}
if (localSelectedItems.items.isEmpty && remoteSelectedItems.items.isEmpty) {
return null;
}
if (localSelectedItems.items.length > remoteSelectedItems.items.length) {
return localSelectedItems;
} else {
return remoteSelectedItems;
}
}
}
class FileManagerView extends StatefulWidget {
final FileController controller;
final Rx<SelectMode> selectMode;
FileManagerView({required this.controller, required this.selectMode});
@override
State<StatefulWidget> createState() => _FileManagerViewState();
}
class _FileManagerViewState extends State<FileManagerView> {
final _listScrollController = ScrollController();
final _breadCrumbScroller = ScrollController();
bool get isLocal => widget.controller.isLocal;
FileController get controller => widget.controller;
SelectedItems get _selectedItems => widget.controller.selectedItems;
@override
void initState() {
super.initState();
controller.directory.listen((e) => breadCrumbScrollToEnd());
}
@override
Widget build(BuildContext context) {
return Column(children: [
headTools(),
Expanded(
child: ListView.builder(
controller: ScrollController(),
Expanded(child: Obx(() {
final entries = controller.directory.value.entries;
return ListView.builder(
controller: _listScrollController,
itemCount: entries.length + 1,
itemBuilder: (context, index) {
if (index >= entries.length) {
return listTail();
}
var selected = false;
if (model.selectMode) {
selected = _selectedItems.contains(entries[index]);
if (widget.selectMode.value != SelectMode.none) {
selected = _selectedItems.items.contains(entries[index]);
}
final sizeStr = entries[index].isFile
? readableFileSize(entries[index].size.toDouble())
: "";
final showCheckBox = () {
return widget.selectMode.value != SelectMode.none &&
widget.selectMode.value.eq(controller.selectedItems.isLocal);
}();
return Card(
child: ListTile(
leading: entries[index].isDrive
@ -254,13 +459,13 @@ class _FileManagerPageState extends State<FileManagerPage> {
),
trailing: entries[index].isDrive
? null
: showCheckBox()
: showCheckBox
? Checkbox(
value: selected,
onChanged: (v) {
if (v == null) return;
if (v && !selected) {
_selectedItems.add(isLocal, entries[index]);
_selectedItems.add(entries[index]);
} else if (!v && selected) {
_selectedItems.remove(entries[index]);
}
@ -287,26 +492,27 @@ class _FileManagerPageState extends State<FileManagerPage> {
},
onSelected: (v) {
if (v == "delete") {
final items = SelectedItems();
items.add(isLocal, entries[index]);
model.removeAction(items);
final items = SelectedItems(isLocal: isLocal);
items.add(entries[index]);
controller.removeAction(items);
} else if (v == "multi_select") {
_selectedItems.clear();
model.toggleSelectMode();
widget.selectMode.toggle(isLocal);
setState(() {});
}
}),
onTap: () {
if (model.selectMode && !_selectedItems.isOtherPage(isLocal)) {
if (showCheckBox) {
if (selected) {
_selectedItems.remove(entries[index]);
} else {
_selectedItems.add(isLocal, entries[index]);
_selectedItems.add(entries[index]);
}
setState(() {});
return;
}
if (entries[index].isDirectory || entries[index].isDrive) {
model.openDirectory(entries[index].path);
controller.openDirectory(entries[index].path);
} else {
// Perform file-related tasks.
}
@ -315,20 +521,21 @@ class _FileManagerPageState extends State<FileManagerPage> {
? null
: () {
_selectedItems.clear();
model.toggleSelectMode();
if (model.selectMode) {
_selectedItems.add(isLocal, entries[index]);
widget.selectMode.toggle(isLocal);
if (widget.selectMode.value != SelectMode.none) {
_selectedItems.add(entries[index]);
}
setState(() {});
},
),
);
},
))
);
}))
]);
}
breadCrumbScrollToEnd() {
void breadCrumbScrollToEnd() {
Future.delayed(Duration(milliseconds: 200), () {
if (_breadCrumbScroller.hasClients) {
_breadCrumbScroller.animateTo(
@ -342,35 +549,39 @@ class _FileManagerPageState extends State<FileManagerPage> {
Widget headTools() => Container(
child: Row(
children: [
Expanded(
child: BreadCrumb(
items: getPathBreadCrumbItems(() => model.goHome(), (list) {
Expanded(child: Obx(() {
final home = controller.options.value.home;
final isWindows = controller.options.value.isWindows;
return BreadCrumb(
items: getPathBreadCrumbItems(controller.shortPath, isWindows,
() => controller.goToHomeDirectory(), (list) {
var path = "";
if (model.currentHome.startsWith(list[0])) {
if (home.startsWith(list[0])) {
// absolute path
for (var item in list) {
path = PathUtil.join(path, item, model.getCurrentIsWindows());
path = PathUtil.join(path, item, isWindows);
}
} else {
path += model.currentHome;
path += home;
for (var item in list) {
path = PathUtil.join(path, item, model.getCurrentIsWindows());
path = PathUtil.join(path, item, isWindows);
}
}
model.openDirectory(path);
controller.openDirectory(path);
}),
divider: Icon(Icons.chevron_right),
overflow: ScrollableOverflow(controller: _breadCrumbScroller),
)),
);
})),
Row(
children: [
IconButton(
icon: Icon(Icons.arrow_back),
onPressed: model.goBack,
onPressed: controller.goBack,
),
IconButton(
icon: Icon(Icons.arrow_upward),
onPressed: model.goToParentDirectory,
onPressed: controller.goToParentDirectory,
),
PopupMenuButton<SortBy>(
icon: Icon(Icons.sort),
@ -382,123 +593,37 @@ class _FileManagerPageState extends State<FileManagerPage> {
))
.toList();
},
onSelected: model.changeSortStyle),
onSelected: controller.changeSortStyle),
],
)
],
));
Widget listTail() {
return Container(
Widget listTail() => Obx(() => Container(
height: 100,
child: Column(
children: [
Padding(
padding: EdgeInsets.fromLTRB(30, 5, 30, 0),
child: Text(
model.currentDir.path,
controller.directory.value.path,
style: TextStyle(color: MyTheme.darkGray),
),
),
Padding(
padding: EdgeInsets.all(2),
child: Text(
"${translate("Total")}: ${model.currentDir.entries.length} ${translate("items")}",
"${translate("Total")}: ${controller.directory.value.entries.length} ${translate("items")}",
style: TextStyle(color: MyTheme.darkGray),
),
)
],
),
);
}
));
Widget? bottomSheet() {
final state = model.jobState;
final isOtherPage = _selectedItems.isOtherPage(model.isLocal);
final selectedItemsLen = "${_selectedItems.length} ${translate("items")}";
final local = _selectedItems.isLocal == null
? ""
: " [${_selectedItems.isLocal! ? translate("Local") : translate("Remote")}]";
if (model.selectMode) {
if (_selectedItems.length == 0 || !isOtherPage) {
return BottomSheetBody(
leading: Icon(Icons.check),
title: translate("Selected"),
text: selectedItemsLen + local,
onCanceled: () => model.toggleSelectMode(),
actions: [
IconButton(
icon: Icon(Icons.compare_arrows),
onPressed: model.togglePage,
),
IconButton(
icon: Icon(Icons.delete_forever),
onPressed: () {
if (_selectedItems.length > 0) {
model.removeAction(_selectedItems);
}
},
)
]);
} else {
return BottomSheetBody(
leading: Icon(Icons.input),
title: translate("Paste here?"),
text: selectedItemsLen + local,
onCanceled: () => model.toggleSelectMode(),
actions: [
IconButton(
icon: Icon(Icons.compare_arrows),
onPressed: model.togglePage,
),
IconButton(
icon: Icon(Icons.paste),
onPressed: () {
model.toggleSelectMode();
model.sendFiles(_selectedItems);
},
)
]);
}
}
switch (state) {
case JobState.inProgress:
return BottomSheetBody(
leading: CircularProgressIndicator(),
title: translate("Waiting"),
text:
"${translate("Speed")}: ${readableFileSize(model.jobProgress.speed)}/s",
onCanceled: () => model.cancelJob(model.jobProgress.id),
);
case JobState.done:
return BottomSheetBody(
leading: Icon(Icons.check),
title: "${translate("Successful")}!",
text: model.jobProgress.display(),
onCanceled: () => model.jobReset(),
);
case JobState.error:
return BottomSheetBody(
leading: Icon(Icons.error),
title: "${translate("Error")}!",
text: "",
onCanceled: () => model.jobReset(),
);
case JobState.none:
break;
case JobState.paused:
// TODO: Handle this case.
break;
}
return null;
}
List<BreadCrumbItem> getPathBreadCrumbItems(
List<BreadCrumbItem> getPathBreadCrumbItems(String shortPath, bool isWindows,
void Function() onHome, void Function(List<String>) onPressed) {
final path = model.currentShortPath;
final list = PathUtil.split(path, model.getCurrentIsWindows());
final list = PathUtil.split(shortPath, isWindows);
final breadCrumbList = [
BreadCrumbItem(
content: IconButton(

File diff suppressed because it is too large Load Diff

View File

@ -166,17 +166,18 @@ class FfiModel with ChangeNotifier {
} else if (name == 'file_dir') {
parent.target?.fileModel.receiveFileDir(evt);
} else if (name == 'job_progress') {
parent.target?.fileModel.tryUpdateJobProgress(evt);
parent.target?.fileModel.jobController.tryUpdateJobProgress(evt);
} else if (name == 'job_done') {
parent.target?.fileModel.jobDone(evt);
parent.target?.fileModel.jobController.jobDone(evt);
parent.target?.fileModel.refreshAll();
} else if (name == 'job_error') {
parent.target?.fileModel.jobError(evt);
parent.target?.fileModel.jobController.jobError(evt);
} else if (name == 'override_file_confirm') {
parent.target?.fileModel.overrideFileConfirm(evt);
} else if (name == 'load_last_job') {
parent.target?.fileModel.loadLastJob(evt);
parent.target?.fileModel.jobController.loadLastJob(evt);
} else if (name == 'update_folder_files') {
parent.target?.fileModel.updateFolderFiles(evt);
parent.target?.fileModel.jobController.updateFolderFiles(evt);
} else if (name == 'add_connection') {
parent.target?.serverModel.addConnection(evt);
} else if (name == 'on_client_remove') {
@ -1575,9 +1576,6 @@ class FFI {
}();
// every instance will bind a stream
this.id = id;
if (isFileTransfer) {
fileModel.initFileFetcher();
}
}
/// Login with [password], choose if the client should [remember] it.