refactor mobile file manager page

This commit is contained in:
csf 2023-03-09 21:09:17 +09:00
parent f5d0275bf3
commit 00b1439f32

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';
@ -20,8 +20,13 @@ class FileManagerPage extends StatefulWidget {
class _FileManagerPageState extends State<FileManagerPage> {
final model = gFFI.fileModel;
final _selectedItems = SelectedItems();
final _breadCrumbScroller = ScrollController();
var showLocal = true;
var isSelecting = false.obs;
FileController get currentFileController =>
showLocal ? model.localController : model.remoteController;
FileDirectory get currentDir => currentFileController.directory.value;
DirectoryOptions get currentOptions => currentFileController.options.value;
@override
void initState() {
@ -32,7 +37,6 @@ class _FileManagerPageState extends State<FileManagerPage> {
.showLoading(translate('Connecting...'), onCancel: closeConnection);
});
gFFI.ffiModel.updateEventListener(widget.id);
model.onDirChanged = (_) => breadCrumbScrollToEnd();
Wakelock.enable();
}
@ -47,288 +51,447 @@ class _FileManagerPageState extends State<FileManagerPage> {
}
@override
Widget build(BuildContext context) => ChangeNotifierProvider.value(
value: model,
child: Consumer<FileModel>(builder: (_context, _model, _child) {
return WillPopScope(
onWillPop: () async {
if (model.selectMode) {
model.toggleSelectMode();
} else {
model.goBack();
Widget build(BuildContext context) => WillPopScope(
onWillPop: () async {
if (isSelecting.value) {
isSelecting.value = false;
} else {
currentFileController.goBack();
}
return false;
},
child: Scaffold(
// backgroundColor: MyTheme.grayBg,
appBar: AppBar(
leading: Row(children: [
IconButton(
icon: Icon(Icons.close),
onPressed: () => clientClose(widget.id, gFFI.dialogManager)),
]),
centerTitle: true,
title: ToggleSwitch(
initialLabelIndex: showLocal ? 0 : 1,
activeBgColor: [MyTheme.idColor],
inactiveBgColor: Theme.of(context).brightness == Brightness.light
? MyTheme.grayBg
: null,
inactiveFgColor: Theme.of(context).brightness == Brightness.light
? Colors.black54
: null,
totalSwitches: 2,
minWidth: 100,
fontSize: 15,
iconSize: 18,
labels: [translate("Local"), translate("Remote")],
icons: [Icons.phone_android_sharp, Icons.screen_share],
onToggle: (index) {
final current = showLocal ? 0 : 1;
if (index != current) {
setState(() => showLocal = !showLocal);
}
return false;
},
child: Scaffold(
// backgroundColor: MyTheme.grayBg,
appBar: AppBar(
leading: Row(children: [
IconButton(
icon: Icon(Icons.close),
onPressed: () =>
clientClose(widget.id, gFFI.dialogManager)),
]),
centerTitle: true,
title: ToggleSwitch(
initialLabelIndex: model.isLocal ? 0 : 1,
activeBgColor: [MyTheme.idColor],
inactiveBgColor:
Theme.of(context).brightness == Brightness.light
? MyTheme.grayBg
: null,
inactiveFgColor:
Theme.of(context).brightness == Brightness.light
? Colors.black54
: null,
totalSwitches: 2,
minWidth: 100,
fontSize: 15,
iconSize: 18,
labels: [translate("Local"), translate("Remote")],
icons: [Icons.phone_android_sharp, Icons.screen_share],
onToggle: (index) {
final current = model.isLocal ? 0 : 1;
if (index != current) {
model.togglePage();
}
},
),
actions: [
PopupMenuButton<String>(
icon: Icon(Icons.more_vert),
itemBuilder: (context) {
return [
PopupMenuItem(
child: Row(
children: [
Icon(Icons.refresh,
color: Theme.of(context).iconTheme.color),
SizedBox(width: 5),
Text(translate("Refresh File"))
],
),
value: "refresh",
),
PopupMenuItem(
enabled: model.currentDir.path != "/",
child: Row(
children: [
Icon(Icons.check,
color: Theme.of(context).iconTheme.color),
SizedBox(width: 5),
Text(translate("Multi Select"))
],
),
value: "select",
),
PopupMenuItem(
enabled: model.currentDir.path != "/",
child: Row(
children: [
Icon(Icons.folder_outlined,
color: Theme.of(context).iconTheme.color),
SizedBox(width: 5),
Text(translate("Create Folder"))
],
),
value: "folder",
),
PopupMenuItem(
enabled: model.currentDir.path != "/",
child: Row(
children: [
Icon(
model.getCurrentShowHidden()
? Icons.check_box_outlined
: Icons.check_box_outline_blank,
color: Theme.of(context).iconTheme.color),
SizedBox(width: 5),
Text(translate("Show Hidden Files"))
],
),
value: "hidden",
)
];
},
onSelected: (v) {
if (v == "refresh") {
model.refresh();
} else if (v == "select") {
_selectedItems.clear();
model.toggleSelectMode();
} else if (v == "folder") {
final name = TextEditingController();
gFFI.dialogManager
.show((setState, close) => CustomAlertDialog(
title: Text(translate("Create Folder")),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
decoration: InputDecoration(
labelText: translate(
"Please enter the folder name"),
),
controller: name,
),
],
),
actions: [
PopupMenuButton<String>(
icon: Icon(Icons.more_vert),
itemBuilder: (context) {
return [
PopupMenuItem(
child: Row(
children: [
Icon(Icons.refresh,
color: Theme.of(context).iconTheme.color),
SizedBox(width: 5),
Text(translate("Refresh File"))
],
),
value: "refresh",
),
PopupMenuItem(
enabled: currentDir.path != "/",
child: Row(
children: [
Icon(Icons.check,
color: Theme.of(context).iconTheme.color),
SizedBox(width: 5),
Text(translate("Multi Select"))
],
),
value: "select",
),
PopupMenuItem(
enabled: currentDir.path != "/",
child: Row(
children: [
Icon(Icons.folder_outlined,
color: Theme.of(context).iconTheme.color),
SizedBox(width: 5),
Text(translate("Create Folder"))
],
),
value: "folder",
),
PopupMenuItem(
enabled: currentDir.path != "/",
child: Row(
children: [
Icon(
currentOptions.showHidden
? Icons.check_box_outlined
: Icons.check_box_outline_blank,
color: Theme.of(context).iconTheme.color),
SizedBox(width: 5),
Text(translate("Show Hidden Files"))
],
),
value: "hidden",
)
];
},
onSelected: (v) {
if (v == "refresh") {
currentFileController.refresh();
} else if (v == "select") {
model.localController.selectedItems.clear();
model.remoteController.selectedItems.clear();
isSelecting.toggle();
} else if (v == "folder") {
final name = TextEditingController();
gFFI.dialogManager
.show((setState, close) => CustomAlertDialog(
title: Text(translate("Create Folder")),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
decoration: InputDecoration(
labelText: translate(
"Please enter the folder name"),
),
actions: [
dialogButton("Cancel",
onPressed: () => close(false),
isOutline: true),
dialogButton("OK", onPressed: () {
if (name.value.text.isNotEmpty) {
model.createDir(PathUtil.join(
model.currentDir.path,
name.value.text,
model.getCurrentIsWindows()));
close();
}
})
]));
} else if (v == "hidden") {
model.toggleShowHidden();
}
}),
],
),
body: body(),
bottomSheet: bottomSheet(),
));
}));
controller: name,
),
],
),
actions: [
dialogButton("Cancel",
onPressed: () => close(false),
isOutline: true),
dialogButton("OK", onPressed: () {
if (name.value.text.isNotEmpty) {
currentFileController.createDir(
PathUtil.join(
currentDir.path,
name.value.text,
currentOptions.isWindows));
close();
}
})
]));
} else if (v == "hidden") {
currentFileController.toggleShowHidden();
}
}),
],
),
body: showLocal
? FileManagerView(
controller: model.localController,
isSelecting: isSelecting,
showCheckBox: showCheckBox())
: FileManagerView(
controller: model.remoteController,
isSelecting: isSelecting,
showCheckBox: showCheckBox()),
bottomSheet: bottomSheet(),
));
bool showCheckBox() {
if (!model.selectMode) {
return false;
final selectedItems = getActiveSelectedItems();
if (selectedItems != null) {
return selectedItems.isLocal == showLocal;
}
return !_selectedItems.isOtherPage(model.isLocal);
return false;
}
Widget body() {
final isLocal = model.isLocal;
final fd = model.currentDir;
final entries = fd.entries;
Widget? bottomSheet() {
return Obx(() {
final selectedItems = getActiveSelectedItems();
final localLabel = selectedItems?.isLocal == null
? ""
: " [${selectedItems!.isLocal ? translate("Local") : translate("Remote")}]";
if (isSelecting.value) {
final selectedItemsLen =
"${selectedItems?.items.length ?? 0} ${translate("items")}";
if (selectedItems == null ||
selectedItems.items.isEmpty ||
showCheckBox()) {
return BottomSheetBody(
leading: Icon(Icons.check),
title: translate("Selected"),
text: selectedItemsLen + localLabel,
onCanceled: () => isSelecting.toggle(),
actions: [
IconButton(
icon: Icon(Icons.compare_arrows),
onPressed: () => setState(() => showLocal = !showLocal),
),
IconButton(
icon: Icon(Icons.delete_forever),
onPressed: selectedItems != null
? () {
if (selectedItems.items.isNotEmpty) {
currentFileController.removeAction(selectedItems);
}
}
: null,
)
]);
} else {
return BottomSheetBody(
leading: Icon(Icons.input),
title: translate("Paste here?"),
text: selectedItemsLen + localLabel,
onCanceled: () => isSelecting.toggle(),
actions: [
IconButton(
icon: Icon(Icons.compare_arrows),
onPressed: () => setState(() => showLocal = !showLocal),
),
IconButton(
icon: Icon(Icons.paste),
onPressed: () {
isSelecting.toggle();
final otherSide = showLocal
? model.remoteController
: model.localController;
final otherSideData = DirectoryData(
otherSide.directory.value, otherSide.options.value);
currentFileController.sendFiles(
selectedItems, otherSideData);
},
)
]);
}
}
final jobTable = model.jobController.jobTable;
if (jobTable.isEmpty) {
return Offstage();
}
switch (jobTable.last.state) {
case JobState.inProgress:
return Obx(() => BottomSheetBody(
leading: CircularProgressIndicator(),
title: translate("Waiting"),
text:
"${translate("Speed")}: ${readableFileSize(jobTable.last.speed)}/s",
onCanceled: () =>
model.jobController.cancelJob(jobTable.last.id),
));
case JobState.done:
return Obx(() => BottomSheetBody(
leading: Icon(Icons.check),
title: "${translate("Successful")}!",
text: jobTable.last.display(),
onCanceled: () => jobTable.clear(),
));
case JobState.error:
return Obx(() => 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 RxBool isSelecting;
final bool showCheckBox;
FileManagerView(
{required this.controller,
required this.isSelecting,
required this.showCheckBox});
@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(),
itemCount: entries.length + 1,
itemBuilder: (context, index) {
if (index >= entries.length) {
return listTail();
}
var selected = false;
if (model.selectMode) {
selected = _selectedItems.contains(entries[index]);
}
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 (widget.isSelecting.value) {
selected = _selectedItems.items.contains(entries[index]);
}
final sizeStr = entries[index].isFile
? readableFileSize(entries[index].size.toDouble())
: "";
return Card(
child: ListTile(
leading: entries[index].isDrive
? Padding(
padding: EdgeInsets.symmetric(vertical: 8),
child: Image(
image: iconHardDrive,
fit: BoxFit.scaleDown,
color: Theme.of(context)
.iconTheme
.color
?.withOpacity(0.7)))
: Icon(
entries[index].isFile
? Icons.feed_outlined
: Icons.folder,
size: 40),
title: Text(entries[index].name),
selected: selected,
subtitle: entries[index].isDrive
? null
: Text(
"${entries[index].lastModified().toString().replaceAll(".000", "")} $sizeStr",
style: TextStyle(fontSize: 12, color: MyTheme.darkGray),
),
trailing: entries[index].isDrive
? null
: showCheckBox()
? Checkbox(
value: selected,
onChanged: (v) {
if (v == null) return;
if (v && !selected) {
_selectedItems.add(isLocal, entries[index]);
} else if (!v && selected) {
_selectedItems.remove(entries[index]);
}
setState(() {});
})
: PopupMenuButton<String>(
icon: Icon(Icons.more_vert),
itemBuilder: (context) {
return [
PopupMenuItem(
child: Text(translate("Delete")),
value: "delete",
),
PopupMenuItem(
child: Text(translate("Multi Select")),
value: "multi_select",
),
PopupMenuItem(
child: Text(translate("Properties")),
value: "properties",
enabled: false,
)
];
},
onSelected: (v) {
if (v == "delete") {
final items = SelectedItems();
items.add(isLocal, entries[index]);
model.removeAction(items);
} else if (v == "multi_select") {
_selectedItems.clear();
model.toggleSelectMode();
}
}),
onTap: () {
if (model.selectMode && !_selectedItems.isOtherPage(isLocal)) {
if (selected) {
_selectedItems.remove(entries[index]);
} else {
_selectedItems.add(isLocal, entries[index]);
final sizeStr = entries[index].isFile
? readableFileSize(entries[index].size.toDouble())
: "";
return Card(
child: ListTile(
leading: entries[index].isDrive
? Padding(
padding: EdgeInsets.symmetric(vertical: 8),
child: Image(
image: iconHardDrive,
fit: BoxFit.scaleDown,
color: Theme.of(context)
.iconTheme
.color
?.withOpacity(0.7)))
: Icon(
entries[index].isFile
? Icons.feed_outlined
: Icons.folder,
size: 40),
title: Text(entries[index].name),
selected: selected,
subtitle: entries[index].isDrive
? null
: Text(
"${entries[index].lastModified().toString().replaceAll(".000", "")} $sizeStr",
style: TextStyle(fontSize: 12, color: MyTheme.darkGray),
),
trailing: entries[index].isDrive
? null
: widget.isSelecting.value && widget.showCheckBox
? Checkbox(
value: selected,
onChanged: (v) {
if (v == null) return;
if (v && !selected) {
_selectedItems.add(entries[index]);
} else if (!v && selected) {
_selectedItems.remove(entries[index]);
}
setState(() {});
})
: PopupMenuButton<String>(
icon: Icon(Icons.more_vert),
itemBuilder: (context) {
return [
PopupMenuItem(
child: Text(translate("Delete")),
value: "delete",
),
PopupMenuItem(
child: Text(translate("Multi Select")),
value: "multi_select",
),
PopupMenuItem(
child: Text(translate("Properties")),
value: "properties",
enabled: false,
)
];
},
onSelected: (v) {
if (v == "delete") {
final items = SelectedItems(isLocal: isLocal);
items.add(entries[index]);
controller.removeAction(items);
} else if (v == "multi_select") {
_selectedItems.clear();
widget.isSelecting.toggle();
}
}),
onTap: () {
if (widget.isSelecting.value && widget.showCheckBox) {
if (selected) {
_selectedItems.remove(entries[index]);
} else {
_selectedItems.add(entries[index]);
}
return;
}
setState(() {});
return;
}
if (entries[index].isDirectory || entries[index].isDrive) {
model.openDirectory(entries[index].path);
} else {
// Perform file-related tasks.
}
},
onLongPress: entries[index].isDrive
? null
: () {
_selectedItems.clear();
model.toggleSelectMode();
if (model.selectMode) {
_selectedItems.add(isLocal, entries[index]);
}
setState(() {});
},
),
);
},
))
if (entries[index].isDirectory || entries[index].isDrive) {
controller.openDirectory(entries[index].path);
} else {
// Perform file-related tasks.
}
},
onLongPress: entries[index].isDrive
? null
: () {
_selectedItems.clear();
widget.isSelecting.toggle();
if (widget.isSelecting.value) {
_selectedItems.add(entries[index]);
}
setState(() {});
},
),
);
},
);
}))
]);
}
breadCrumbScrollToEnd() {
void breadCrumbScrollToEnd() {
Future.delayed(Duration(milliseconds: 200), () {
if (_breadCrumbScroller.hasClients) {
_breadCrumbScroller.animateTo(
@ -342,35 +505,39 @@ class _FileManagerPageState extends State<FileManagerPage> {
Widget headTools() => Container(
child: Row(
children: [
Expanded(
child: BreadCrumb(
items: getPathBreadCrumbItems(() => model.goHome(), (list) {
var path = "";
if (model.currentHome.startsWith(list[0])) {
// absolute path
for (var item in list) {
path = PathUtil.join(path, item, model.getCurrentIsWindows());
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 (home.startsWith(list[0])) {
// absolute path
for (var item in list) {
path = PathUtil.join(path, item, isWindows);
}
} else {
path += home;
for (var item in list) {
path = PathUtil.join(path, item, isWindows);
}
}
} else {
path += model.currentHome;
for (var item in list) {
path = PathUtil.join(path, item, model.getCurrentIsWindows());
}
}
model.openDirectory(path);
}),
divider: Icon(Icons.chevron_right),
overflow: ScrollableOverflow(controller: _breadCrumbScroller),
)),
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 +549,37 @@ class _FileManagerPageState extends State<FileManagerPage> {
))
.toList();
},
onSelected: model.changeSortStyle),
onSelected: controller.changeSortStyle),
],
)
],
));
Widget listTail() {
return Container(
height: 100,
child: Column(
children: [
Padding(
padding: EdgeInsets.fromLTRB(30, 5, 30, 0),
child: Text(
model.currentDir.path,
style: TextStyle(color: MyTheme.darkGray),
),
),
Padding(
padding: EdgeInsets.all(2),
child: Text(
"${translate("Total")}: ${model.currentDir.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,
Widget listTail() => Obx(() => Container(
height: 100,
child: Column(
children: [
Padding(
padding: EdgeInsets.fromLTRB(30, 5, 30, 0),
child: Text(
controller.directory.value.path,
style: TextStyle(color: MyTheme.darkGray),
),
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,
),
Padding(
padding: EdgeInsets.all(2),
child: Text(
"${translate("Total")}: ${controller.directory.value.entries.length} ${translate("items")}",
style: TextStyle(color: MyTheme.darkGray),
),
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(