#24 #25 #33 new: sftp file edit

This commit is contained in:
lollipopkit
2023-05-28 18:21:03 +08:00
parent dbabe81e3c
commit 06be4503ca
28 changed files with 329 additions and 173 deletions

View File

@@ -1,16 +1,22 @@
import 'dart:io';
import 'package:code_text_field/code_text_field.dart';
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/l10n.dart';
import 'package:flutter_highlight/theme_map.dart';
import 'package:flutter_highlight/themes/monokai.dart';
import 'package:toolbox/core/extension/navigator.dart';
import 'package:toolbox/core/utils/misc.dart';
import 'package:toolbox/data/res/highlight.dart';
import 'package:toolbox/data/store/setting.dart';
import 'package:toolbox/locator.dart';
import '../widget/two_line_text.dart';
class EditorPage extends StatefulWidget {
final String? path;
final String? initCode;
final String? fileName;
const EditorPage({Key? key, this.initCode, this.fileName}) : super(key: key);
const EditorPage({Key? key, this.path, this.initCode}) : super(key: key);
@override
_EditorPageState createState() => _EditorPageState();
@@ -21,16 +27,30 @@ class _EditorPageState extends State<EditorPage> {
late final _focusNode = FocusNode();
final _setting = locator<SettingStore>();
late Map<String, TextStyle> _codeTheme;
late S _s;
late String? _langCode;
@override
void initState() {
super.initState();
_focusNode.requestFocus();
_langCode = widget.path.highlightCode;
_controller = CodeController(
text: widget.initCode,
language: widget.fileName.highlight,
language: suffix2HighlightMap[_langCode ?? 'plaintext'],
);
_codeTheme = themeMap[_setting.editorTheme.fetch()] ?? monokaiTheme;
if (widget.initCode == null && widget.path != null) {
File(widget.path!)
.readAsString()
.then((value) => _controller.text = value);
}
_focusNode.requestFocus();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_s = S.of(context)!;
}
@override
@@ -45,23 +65,41 @@ class _EditorPageState extends State<EditorPage> {
return Scaffold(
backgroundColor: _codeTheme['root']!.backgroundColor,
appBar: AppBar(
title: Text(widget.fileName ?? ''),
title: TwoLineText(up: getFileName(widget.path) ?? '', down: _s.editor),
actions: [
IconButton(
icon: const Icon(Icons.done),
onPressed: () {
context.pop(_controller.text);
PopupMenuButton(
icon: const Icon(Icons.language),
onSelected: (value) {
_controller.language = suffix2HighlightMap[value];
},
),
initialValue: _langCode,
itemBuilder: (BuildContext context) {
return suffix2HighlightMap.keys.map((e) {
return PopupMenuItem(
value: e,
child: Text(e),
);
}).toList();
},
)
],
),
body: CodeTheme(
data: CodeThemeData(styles: _codeTheme),
child: CodeField(
controller: _controller,
textStyle: const TextStyle(fontFamily: 'SourceCode'),
body: SingleChildScrollView(
child: CodeTheme(
data: CodeThemeData(styles: _codeTheme),
child: CodeField(
focusNode: _focusNode,
controller: _controller,
textStyle: const TextStyle(fontFamily: 'SourceCode'),
),
),
),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.done),
onPressed: () {
context.pop(_controller.text);
},
),
);
}
}

View File

@@ -2,8 +2,8 @@ import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/l10n.dart';
import 'package:provider/provider.dart';
import 'package:toolbox/core/extension/order.dart';
import 'package:toolbox/data/model/server/cpu_status.dart';
import 'package:toolbox/data/model/server/disk_info.dart';
import 'package:toolbox/data/model/server/cpu.dart';
import 'package:toolbox/data/model/server/disk.dart';
import 'package:toolbox/data/model/server/dist.dart';
import 'package:toolbox/data/model/server/memory.dart';
import 'package:toolbox/data/model/server/temp.dart';
@@ -118,7 +118,7 @@ class _ServerDetailPageState extends State<ServerDetailPage>
);
}
Widget _buildCPUView(CpuStatus cs) {
Widget _buildCPUView(Cpus cs) {
return RoundRectCard(
Padding(
padding: roundRectCardPadding,
@@ -171,7 +171,7 @@ class _ServerDetailPageState extends State<ServerDetailPage>
);
}
Widget _buildCPUProgress(CpuStatus cs) {
Widget _buildCPUProgress(Cpus cs) {
final children = <Widget>[];
for (var i = 0; i < cs.coresCount; i++) {
if (i == 0) continue;
@@ -288,7 +288,7 @@ class _ServerDetailPageState extends State<ServerDetailPage>
);
}
Widget _buildDiskView(List<DiskInfo> disk) {
Widget _buildDiskView(List<Disk> disk) {
disk.removeWhere((e) {
for (final ingorePath in _setting.diskIgnorePath.fetch()!) {
if (e.path.startsWith(ingorePath)) return true;

View File

@@ -99,7 +99,7 @@ class _SettingPageState extends State<SettingPage> {
_buildTitle('SSH'),
_buildSSH(),
// Editor
_buildTitle('Editor'),
_buildTitle(_s.editor),
_buildEditor(),
const SizedBox(height: 37),
],
@@ -535,17 +535,18 @@ class _SettingPageState extends State<SettingPage> {
),
actions: [
TextButton(
onPressed: () {
context.pop();
final fontSize = double.tryParse(ctrller.text);
if (fontSize == null) {
showRoundDialog(context: context, child: Text(_s.failed));
return;
}
_fontSize = fontSize;
_setting.termFontSize.put(_fontSize);
},
child: Text(_s.ok)),
onPressed: () {
context.pop();
final fontSize = double.tryParse(ctrller.text);
if (fontSize == null) {
showRoundDialog(context: context, child: Text(_s.failed));
return;
}
_fontSize = fontSize;
_setting.termFontSize.put(_fontSize);
},
child: Text(_s.ok),
),
],
);
},
@@ -559,23 +560,25 @@ class _SettingPageState extends State<SettingPage> {
trailing: Text(_s.edit, style: textSize15),
onTap: () {
showRoundDialog(
context: context,
child: Input(
controller: TextEditingController(text: json.encode(paths)),
label: 'JSON',
type: TextInputType.visiblePassword,
maxLines: 3,
onSubmitted: (p0) {
try {
final list = List<String>.from(json.decode(p0));
_setting.diskIgnorePath.put(list);
context.pop();
showSnackBar(context, Text(_s.success));
} catch (e) {
showSnackBar(context, Text(e.toString()));
}
},
));
context: context,
title: Text(_s.diskIgnorePath),
child: Input(
controller: TextEditingController(text: json.encode(paths)),
label: 'JSON',
type: TextInputType.visiblePassword,
maxLines: 3,
onSubmitted: (p0) {
try {
final list = List<String>.from(json.decode(p0));
_setting.diskIgnorePath.put(list);
context.pop();
showSnackBar(context, Text(_s.success));
} catch (e) {
showSnackBar(context, Text(e.toString()));
}
},
),
);
},
);
}
@@ -641,7 +644,6 @@ class _SettingPageState extends State<SettingPage> {
_editorTheme = idx;
});
_setting.editorTheme.put(idx);
_showRestartSnackbar();
},
child: Text(
_editorTheme,

View File

@@ -3,7 +3,9 @@ import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/l10n.dart';
import 'package:toolbox/core/extension/navigator.dart';
import 'package:toolbox/data/res/misc.dart';
import 'package:toolbox/view/page/editor.dart';
import 'package:toolbox/view/widget/input_field.dart';
import '../../../core/extension/numx.dart';
import '../../../core/extension/stringx.dart';
@@ -141,6 +143,55 @@ class _SFTPDownloadedPageState extends State<SFTPDownloadedPage> {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
leading: const Icon(Icons.edit),
title: Text(_s.edit),
onTap: () async {
context.pop();
final stat = await file.stat();
if (stat.size > editorMaxSize) {
showRoundDialog(
context: context,
child: Text(_s.fileTooLarge(fileName, stat.size, '1m')),
);
return;
}
final f = File(file.absolute.path);
final data = await f.readAsString();
final result = await AppRoute(
EditorPage(
initCode: data,
path: fileName,
),
'sftp dled editor',
).go<String>(context);
if (result != null) {
f.writeAsString(result);
showSnackBar(context, Text(_s.saved));
setState(() {});
}
},
),
ListTile(
leading: const Icon(Icons.abc),
title: Text(_s.rename),
onTap: () {
context.pop();
showRoundDialog(
context: context,
title: Text(_s.rename),
child: Input(
controller: TextEditingController(text: fileName),
onSubmitted: (p0) {
context.pop();
final newPath = '${file.parent.path}/$p0';
file.renameSync(newPath);
setState(() {});
},
),
);
},
),
ListTile(
leading: const Icon(Icons.delete),
title: Text(_s.delete),
@@ -173,31 +224,8 @@ class _SFTPDownloadedPageState extends State<SFTPDownloadedPage> {
shareFiles(context, [file.absolute.path]);
},
),
ListTile(
leading: const Icon(Icons.edit),
title: Text(_s.edit),
onTap: () async {
context.pop();
final stat = await file.stat();
if (stat.size > 1024 * 1024) {
showRoundDialog(
context: context,
child: Text(_s.fileTooLarge(fileName, stat.size, '1m')),
);
return;
}
final f = await File(file.absolute.path).readAsString();
AppRoute(EditorPage(initCode: f), 'sftp dled editor').go(context);
},
)
],
),
actions: [
TextButton(
onPressed: (() => context.pop()),
child: Text(_s.close),
)
],
);
}
}

View File

@@ -1,13 +1,18 @@
import 'dart:io';
import 'dart:typed_data';
import 'package:dartssh2/dartssh2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/l10n.dart';
import 'package:toolbox/core/extension/navigator.dart';
import 'package:toolbox/core/extension/sftpfile.dart';
import 'package:toolbox/data/res/misc.dart';
import 'package:toolbox/view/page/editor.dart';
import '../../../core/extension/numx.dart';
import '../../../core/extension/stringx.dart';
import '../../../core/route.dart';
import '../../../core/utils/misc.dart';
import '../../../core/utils/ui.dart';
import '../../../data/model/server/server.dart';
import '../../../data/model/server/server_private_info.dart';
@@ -39,7 +44,7 @@ class _SFTPPageState extends State<SFTPPage> {
late S _s;
Server? _si;
ServerState? _state;
SSHClient? _client;
@override
@@ -52,8 +57,8 @@ class _SFTPPageState extends State<SFTPPage> {
void initState() {
super.initState();
final serverProvider = locator<ServerProvider>();
_si = serverProvider.servers[widget.spi.id];
_client = _si?.client;
_client = serverProvider.servers[widget.spi.id]?.client;
_state = serverProvider.servers[widget.spi.id]?.state;
}
@override
@@ -92,7 +97,7 @@ class _SFTPPageState extends State<SFTPPage> {
IconButton(
padding: const EdgeInsets.all(0),
onPressed: () async {
await backward();
await _backward();
},
icon: const Icon(Icons.arrow_back),
),
@@ -116,11 +121,11 @@ class _SFTPPageState extends State<SFTPPage> {
ListTile(
leading: const Icon(Icons.folder),
title: Text(_s.createFolder),
onTap: () => mkdir(context)),
onTap: () => _mkdir(context)),
ListTile(
leading: const Icon(Icons.insert_drive_file),
title: Text(_s.createFile),
onTap: () => newFile(context)),
onTap: () => _newFile(context)),
],
),
actions: [
@@ -163,14 +168,14 @@ class _SFTPPageState extends State<SFTPPage> {
return;
}
_status.path?.update(p!);
listDir(path: p);
_listDir(path: p);
},
icon: const Icon(Icons.gps_fixed),
);
}
Widget _buildFileView() {
if (_client == null || _si?.state != ServerState.connected) {
if (_client == null || _state != ServerState.connected) {
return centerLoading;
}
@@ -180,7 +185,7 @@ class _SFTPPageState extends State<SFTPPage> {
if (_status.files == null) {
_status.path = AbsolutePath('/');
listDir(path: '/', client: _client);
_listDir(path: '/', client: _client);
return centerLoading;
} else {
return RefreshIndicator(
@@ -196,7 +201,7 @@ class _SFTPPageState extends State<SFTPPage> {
leading: Icon(isDir ? Icons.folder : Icons.insert_drive_file),
title: Text(file.filename),
trailing: Text(
'${getTime(file.attr.modifyTime)}\n${getMode(file.attr.mode)}',
'${getTime(file.attr.modifyTime)}\n${file.attr.mode?.str ?? ''}',
style: const TextStyle(color: Colors.grey),
textAlign: TextAlign.right,
),
@@ -205,80 +210,105 @@ class _SFTPPageState extends State<SFTPPage> {
onTap: () {
if (isDir) {
_status.path?.update(file.filename);
listDir(path: _status.path?.path);
_listDir(path: _status.path?.path);
} else {
onItemPress(context, file, true);
_onItemPress(context, file, true);
}
},
onLongPress: () => onItemPress(context, file, false),
onLongPress: () => _onItemPress(context, file, false),
);
},
),
),
onRefresh: () => listDir(path: _status.path?.path),
onRefresh: () => _listDir(path: _status.path?.path),
);
}
}
String getTime(int? unixMill) {
return DateTime.fromMillisecondsSinceEpoch((unixMill ?? 0) * 1000)
.toString()
.replaceFirst('.000', '');
}
String getMode(SftpFileMode? mode) {
if (mode == null) {
return '---';
}
final user = getRoleMode(mode.userRead, mode.userWrite, mode.userExecute);
final group =
getRoleMode(mode.groupRead, mode.groupWrite, mode.groupExecute);
final other =
getRoleMode(mode.otherRead, mode.otherWrite, mode.otherExecute);
return '$user$group$other';
}
String getRoleMode(bool r, bool w, bool x) {
return '${r ? 'r' : '-'}${w ? 'w' : '-'}${x ? 'x' : '-'}';
}
void onItemPress(BuildContext context, SftpName file, bool showDownload) {
void _onItemPress(BuildContext context, SftpName file, bool notDir) {
showRoundDialog(
context: context,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
notDir
? ListTile(
leading: const Icon(Icons.edit),
title: Text(_s.edit),
onTap: () => _edit(context, file),
)
: placeholder,
ListTile(
leading: const Icon(Icons.delete),
title: Text(_s.delete),
onTap: () => delete(context, file),
onTap: () => _delete(context, file),
),
ListTile(
leading: const Icon(Icons.edit),
leading: const Icon(Icons.abc),
title: Text(_s.rename),
onTap: () => rename(context, file),
onTap: () => _rename(context, file),
),
showDownload
notDir
? ListTile(
leading: const Icon(Icons.download),
title: Text(_s.download),
onTap: () => download(context, file),
onTap: () => _download(context, file),
)
: placeholder
: placeholder,
],
),
actions: [
TextButton(
onPressed: () => context.pop(),
child: Text(_s.cancel),
)
],
);
}
void download(BuildContext context, SftpName name) {
Future<void> _edit(BuildContext context, SftpName name) async {
final size = name.attr.size;
if (size == null || size > editorMaxSize) {
showSnackBar(
context,
Text(_s.fileTooLarge(
name.filename,
size ?? 0,
editorMaxSize,
)));
return;
}
final file = await _status.client!.open(
_getRemotePath(name),
mode: SftpFileOpenMode.read | SftpFileOpenMode.write,
);
final localPath = '${(await sftpDir).path}${_getRemotePath(name)}';
await Directory(localPath.substring(0, localPath.lastIndexOf('/')))
.create(recursive: true);
final local = File(localPath);
if (await local.exists()) {
await local.delete();
}
final localFile = local.openWrite(mode: FileMode.append);
const defaultChunkSize = 1024 * 1024;
final chunkSize = size > defaultChunkSize ? defaultChunkSize : size;
for (var i = 0; i < size; i += chunkSize) {
final fileData = file.read(length: chunkSize);
await for (var form in fileData) {
localFile.add(form);
}
}
await localFile.close();
context.pop();
final result = await AppRoute(
EditorPage(path: localPath),
'SFTP edit',
).go<String>(context);
if (result != null) {
await local.writeAsString(result);
await file.writeBytes(result.uint8List);
showSnackBar(context, Text(_s.saved));
}
await file.close();
}
void _download(BuildContext context, SftpName name) {
showRoundDialog(
context: context,
child: Text('${_s.dl2Local(name.filename)}\n${_s.keepForeground}'),
@@ -313,7 +343,7 @@ class _SFTPPageState extends State<SFTPPage> {
);
}
void delete(BuildContext context, SftpName file) {
void _delete(BuildContext context, SftpName file) {
context.pop();
final isDir = file.attr.isDirectory;
final dirText = isDir ? '\n${_s.sureDirEmpty}' : '';
@@ -358,7 +388,7 @@ class _SFTPPageState extends State<SFTPPage> {
);
return;
}
listDir();
_listDir();
},
child: Text(
_s.delete,
@@ -369,7 +399,7 @@ class _SFTPPageState extends State<SFTPPage> {
);
}
void mkdir(BuildContext context) {
void _mkdir(BuildContext context) {
context.pop();
final textController = TextEditingController();
showRoundDialog(
@@ -402,7 +432,7 @@ class _SFTPPageState extends State<SFTPPage> {
_status.client!
.mkdir('${_status.path!.path}/${textController.text}');
context.pop();
listDir();
_listDir();
},
child: Text(
_s.ok,
@@ -413,7 +443,7 @@ class _SFTPPageState extends State<SFTPPage> {
);
}
void newFile(BuildContext context) {
void _newFile(BuildContext context) {
context.pop();
final textController = TextEditingController();
showRoundDialog(
@@ -447,7 +477,7 @@ class _SFTPPageState extends State<SFTPPage> {
.open('${_status.path!.path}/${textController.text}'))
.writeBytes(Uint8List(0));
context.pop();
listDir();
_listDir();
},
child: Text(
_s.ok,
@@ -458,7 +488,7 @@ class _SFTPPageState extends State<SFTPPage> {
);
}
void rename(BuildContext context, SftpName file) {
void _rename(BuildContext context, SftpName file) {
context.pop();
final textController = TextEditingController();
showRoundDialog(
@@ -487,7 +517,7 @@ class _SFTPPageState extends State<SFTPPage> {
}
await _status.client!.rename(file.filename, textController.text);
context.pop();
listDir();
_listDir();
},
child: Text(
_s.rename,
@@ -503,7 +533,7 @@ class _SFTPPageState extends State<SFTPPage> {
return prePath + (prePath.endsWith('/') ? '' : '/') + name.filename;
}
Future<void> listDir({String? path, SSHClient? client}) async {
Future<void> _listDir({String? path, SSHClient? client}) async {
if (_status.isBusy) {
return;
}
@@ -535,13 +565,13 @@ class _SFTPPageState extends State<SFTPPage> {
)
],
);
await backward();
await _backward();
}
}
Future<void> backward() async {
Future<void> _backward() async {
if (_status.path!.undo()) {
await listDir();
await _listDir();
}
}
}

View File

@@ -228,6 +228,9 @@ class _SSHPageState extends State<SSHPage> {
_terminal.keyInput(TerminalKey.enter);
});
break;
case VirtualKeyFunc.file:
// TODO
showRoundDialog(context: context, child: const Text('TODO'));
}
}