fix(android): 保存/导出写入系统公共 Documents(可见),不再落到应用私有 data 目录
- 原生通道 seqstudio/docs:Android 10+ 走 MediaStore 写入 Documents/SequenceDiagram(免权限、商店合规);Android 9- 直接写公共目录(WRITE_EXTERNAL_STORAGE 限 maxSdk=28) - 安卓保存/打开/导出改用「Documents 对话框」:保存输入文件名(自动补全后缀),打开列出 Documents 中的 .seq.json 点选 - 控制器新增 markSaved(外部通道保存后标记干净);重新构建签名 APK
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
/// 安卓公共 Documents(Documents/SequenceDiagram)读写服务。
|
||||
///
|
||||
/// 通过原生通道(MainActivity 中的 `seqstudio/docs`)实现:
|
||||
/// - Android 10+(API 29+)走 MediaStore,无需存储权限(应用商店合规);
|
||||
/// - Android 9 及以下直接写公共目录(配合 maxSdkVersion=28 的权限声明)。
|
||||
///
|
||||
/// 桌面平台不可用([isAvailable] 为 false),此时应使用应用内文件浏览器。
|
||||
library;
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
/// 安卓公共文档读写。
|
||||
class AndroidDocs {
|
||||
AndroidDocs._();
|
||||
|
||||
/// 原生通道。
|
||||
static const MethodChannel _channel = MethodChannel('seqstudio/docs');
|
||||
|
||||
/// 是否可用(仅 Android)。
|
||||
static bool get isAvailable => Platform.isAndroid;
|
||||
|
||||
/// 用于展示的目录描述。
|
||||
static const String displayDir = 'Documents/SequenceDiagram';
|
||||
|
||||
/// 保存文件到公共 Documents/SequenceDiagram,返回展示位置。
|
||||
///
|
||||
/// 参数 [name] 文件名(含后缀);[data] 文件内容;[mime] 可选 MIME 类型。
|
||||
static Future<String> saveFile(String name, Uint8List data, {String? mime}) async {
|
||||
final Object? r = await _channel.invokeMethod<Object?>('saveFile', <String, Object?>{
|
||||
'name': name,
|
||||
'data': data,
|
||||
'mime': mime,
|
||||
});
|
||||
return r as String;
|
||||
}
|
||||
|
||||
/// 列出 Documents/SequenceDiagram 下的文件(`[{name, size}]`,新在前)。
|
||||
static Future<List<Map<String, dynamic>>> listFiles() async {
|
||||
final Object? r = await _channel.invokeMethod<Object?>('listFiles');
|
||||
final List<Object?> list = (r as List<Object?>?) ?? const <Object?>[];
|
||||
return list
|
||||
.map((Object? e) => Map<String, dynamic>.from(e as Map<Object?, Object?>))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// 读取 Documents/SequenceDiagram 下的文件内容;不存在返回 null。
|
||||
static Future<Uint8List?> readFile(String name) async {
|
||||
final Object? r = await _channel.invokeMethod<Object?>('readFile', <String, Object?>{
|
||||
'name': name,
|
||||
});
|
||||
if (r == null) return null;
|
||||
return r as Uint8List;
|
||||
}
|
||||
}
|
||||
@@ -288,6 +288,19 @@ class AppController extends ChangeNotifier {
|
||||
return true;
|
||||
}
|
||||
|
||||
/// 通过外部通道(如安卓公共 Documents)保存成功后标记为已保存。
|
||||
///
|
||||
/// [displayPath] 仅用于展示与状态栏;自动保存快照标记为干净,
|
||||
/// 不写 .bak 备份(外部存储不经过 dart:io)。
|
||||
Future<void> markSaved(String displayPath) async {
|
||||
_filePath = displayPath;
|
||||
_dirty = false;
|
||||
_lastSavedAt = DateTime.now();
|
||||
_status = '已保存 ${_baseName(displayPath)}';
|
||||
await Storage.instance.writeAutosave(_project, projectPath: null, clean: true);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// 从完整路径中提取文件名(兼容 `\` 与 `/` 分隔符)。
|
||||
static String _baseName(String p) => p.split(RegExp(r'[\\/]')).last;
|
||||
|
||||
|
||||
+98
-3
@@ -8,6 +8,7 @@
|
||||
// · 侧栏的“停靠 / 悬浮 / 收起为轨道”状态机;
|
||||
// · 自适应/紧凑工具栏布局(按可用宽度切换);
|
||||
// · 文件打开/保存/另存为与 SVG、PNG 导出流程。
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui' as ui;
|
||||
@@ -19,6 +20,7 @@ import 'package:flutter/services.dart';
|
||||
import '../export/svg_writer.dart';
|
||||
import '../model/models.dart';
|
||||
import '../model/units.dart';
|
||||
import '../persistence/android_docs.dart';
|
||||
import '../state/app_controller.dart';
|
||||
import '../theme/tokens.dart';
|
||||
import 'ai_dialog.dart';
|
||||
@@ -150,6 +152,30 @@ class _AppShellState extends State<AppShell> {
|
||||
|
||||
/// 打开项目:选择 .seq.json 文件并解码加载。
|
||||
Future<void> _open() async {
|
||||
// 安卓版:从公共 Documents/SequenceDiagram 打开。
|
||||
if (AndroidDocs.isAvailable) {
|
||||
final String? name = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (_) => const AndroidFileDialog(
|
||||
saveMode: false,
|
||||
defaultName: '',
|
||||
suffix: '.seq.json',
|
||||
),
|
||||
);
|
||||
if (name == null) return;
|
||||
try {
|
||||
final Uint8List? bytes = await AndroidDocs.readFile(name);
|
||||
if (bytes == null) {
|
||||
if (mounted) await showMessage(context, '打开失败', '未找到文件 $name');
|
||||
return;
|
||||
}
|
||||
c.loadProject(Project.decode(utf8.decode(bytes)), path: null);
|
||||
c.setStatus('已打开 ${AndroidDocs.displayDir}/$name');
|
||||
} catch (e) {
|
||||
if (mounted) await showMessage(context, '打开失败', '$e');
|
||||
}
|
||||
return;
|
||||
}
|
||||
final String? path = await pickFile(context, save: false, initialPath: c.filePath);
|
||||
if (path == null) return;
|
||||
try {
|
||||
@@ -162,15 +188,36 @@ class _AppShellState extends State<AppShell> {
|
||||
|
||||
/// 保存项目:已有路径则直接保存,否则转入“另存为”。
|
||||
Future<void> _save() async {
|
||||
if (c.filePath != null) {
|
||||
await c.save();
|
||||
// 安卓版:始终走“另存为”(Documents 通道),避免把展示路径当真实路径写入。
|
||||
if (AndroidDocs.isAvailable || c.filePath == null) {
|
||||
await _saveAs();
|
||||
return;
|
||||
}
|
||||
await _saveAs();
|
||||
await c.save();
|
||||
}
|
||||
|
||||
/// 另存为:选择目标路径后写入文件(同时生成 .bak 备份)。
|
||||
Future<void> _saveAs() async {
|
||||
// 安卓版:写入公共 Documents/SequenceDiagram(MediaStore 通道)。
|
||||
if (AndroidDocs.isAvailable) {
|
||||
final String? name = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (_) => AndroidFileDialog(
|
||||
saveMode: true,
|
||||
defaultName: '${c.project.name}.seq.json',
|
||||
suffix: '.seq.json',
|
||||
),
|
||||
);
|
||||
if (name == null) return;
|
||||
try {
|
||||
final Uint8List data = Uint8List.fromList(utf8.encode(c.project.encode()));
|
||||
await AndroidDocs.saveFile(name, data, mime: 'application/json');
|
||||
await c.markSaved('${AndroidDocs.displayDir}/$name');
|
||||
} catch (e) {
|
||||
if (mounted) await showMessage(context, '保存失败', '$e');
|
||||
}
|
||||
return;
|
||||
}
|
||||
final String? path = await pickFile(
|
||||
context,
|
||||
save: true,
|
||||
@@ -193,6 +240,30 @@ class _AppShellState extends State<AppShell> {
|
||||
if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 SVG。');
|
||||
return;
|
||||
}
|
||||
// 安卓版:写入公共 Documents/SequenceDiagram。
|
||||
if (AndroidDocs.isAvailable) {
|
||||
final String? name = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (_) => AndroidFileDialog(
|
||||
saveMode: true,
|
||||
defaultName: '${c.project.name}.svg',
|
||||
suffix: '.svg',
|
||||
),
|
||||
);
|
||||
if (name == null) return;
|
||||
try {
|
||||
final String svg = SvgWriter(
|
||||
project: c.project,
|
||||
tokens: Tokens.of(c.brightness),
|
||||
mode: c.project.viewState.mode,
|
||||
).build();
|
||||
await AndroidDocs.saveFile(name, Uint8List.fromList(utf8.encode(svg)), mime: 'image/svg+xml');
|
||||
if (mounted) c.setStatus('已导出 ${AndroidDocs.displayDir}/$name');
|
||||
} catch (e) {
|
||||
if (mounted) await showMessage(context, '导出失败', '$e');
|
||||
}
|
||||
return;
|
||||
}
|
||||
final String? path = await pickFile(
|
||||
context,
|
||||
save: true,
|
||||
@@ -220,6 +291,30 @@ class _AppShellState extends State<AppShell> {
|
||||
if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 PNG。');
|
||||
return;
|
||||
}
|
||||
// 安卓版:写入公共 Documents/SequenceDiagram。
|
||||
if (AndroidDocs.isAvailable) {
|
||||
final String? name = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (_) => AndroidFileDialog(
|
||||
saveMode: true,
|
||||
defaultName: '${c.project.name}.png',
|
||||
suffix: '.png',
|
||||
),
|
||||
);
|
||||
if (name == null) return;
|
||||
try {
|
||||
// 抓取画布舞台的渲染对象并转换为图像。
|
||||
final RenderRepaintBoundary boundary =
|
||||
_stageKey.currentContext!.findRenderObject()! as RenderRepaintBoundary;
|
||||
final ui.Image image = await boundary.toImage(pixelRatio: 2);
|
||||
final ByteData? bd = await image.toByteData(format: ui.ImageByteFormat.png);
|
||||
await AndroidDocs.saveFile(name, bd!.buffer.asUint8List(), mime: 'image/png');
|
||||
if (mounted) c.setStatus('已导出 ${AndroidDocs.displayDir}/$name');
|
||||
} catch (e) {
|
||||
if (mounted) await showMessage(context, '导出失败', '$e');
|
||||
}
|
||||
return;
|
||||
}
|
||||
final String? path = await pickFile(
|
||||
context,
|
||||
save: true,
|
||||
|
||||
@@ -14,6 +14,7 @@ import 'package:flutter/material.dart' hide Action;
|
||||
import '../license/license_service.dart';
|
||||
import '../model/models.dart';
|
||||
import '../model/units.dart';
|
||||
import '../persistence/android_docs.dart';
|
||||
import '../persistence/storage.dart';
|
||||
import '../state/app_controller.dart';
|
||||
import '../theme/tokens.dart';
|
||||
@@ -419,6 +420,180 @@ Future<String?> pickFile(
|
||||
);
|
||||
}
|
||||
|
||||
// ===================== 安卓公共 Documents 文件对话框 =====================
|
||||
|
||||
/// 安卓版文件对话框:保存到 / 打开自公共 `Documents/SequenceDiagram`。
|
||||
///
|
||||
/// - 保存模式:输入文件名(自动补全后缀),确认后由调用方经 [AndroidDocs] 写入;
|
||||
/// - 打开模式:列出 Documents 目录中匹配后缀的文件,点选返回文件名。
|
||||
/// 返回值为文件名;取消返回 null。
|
||||
class AndroidFileDialog extends StatefulWidget {
|
||||
const AndroidFileDialog({
|
||||
super.key,
|
||||
required this.saveMode,
|
||||
required this.defaultName,
|
||||
required this.suffix,
|
||||
});
|
||||
|
||||
/// 保存(true)或打开(false)。
|
||||
final bool saveMode;
|
||||
/// 保存模式的默认文件名。
|
||||
final String defaultName;
|
||||
/// 文件后缀(过滤与自动补全)。
|
||||
final String suffix;
|
||||
|
||||
@override
|
||||
State<AndroidFileDialog> createState() => _AndroidFileDialogState();
|
||||
}
|
||||
|
||||
class _AndroidFileDialogState extends State<AndroidFileDialog> {
|
||||
late TextEditingController _name;
|
||||
List<Map<String, dynamic>> _files = <Map<String, dynamic>>[];
|
||||
bool _loading = false;
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_name = TextEditingController(text: widget.defaultName);
|
||||
if (!widget.saveMode) _load();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_name.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// 列出 Documents 目录中的匹配文件(新在前)。
|
||||
Future<void> _load() async {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
final List<Map<String, dynamic>> all = await AndroidDocs.listFiles();
|
||||
final String sfx = widget.suffix.toLowerCase();
|
||||
final List<Map<String, dynamic>> matched = all
|
||||
.where((Map<String, dynamic> f) => (f['name'] as String? ?? '').toLowerCase().endsWith(sfx))
|
||||
.toList();
|
||||
if (mounted) setState(() => _files = matched);
|
||||
} catch (e) {
|
||||
if (mounted) setState(() => _error = '无法读取 Documents 目录:$e');
|
||||
} finally {
|
||||
if (mounted) setState(() => _loading = false);
|
||||
}
|
||||
}
|
||||
|
||||
/// 替换其它已知后缀并补全目标后缀。
|
||||
String _ensureSuffix(String raw) {
|
||||
String n = raw.trim();
|
||||
if (n.isEmpty) return n;
|
||||
const List<String> known = <String>['.seq.json', '.json', '.svg', '.png'];
|
||||
for (final String k in known) {
|
||||
if (n.toLowerCase().endsWith(k)) {
|
||||
if (k == widget.suffix) return n;
|
||||
n = n.substring(0, n.length - k.length);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return '$n${widget.suffix}';
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final Tokens t = context.tok;
|
||||
return AlertDialog(
|
||||
backgroundColor: t.dialog,
|
||||
title: Text(widget.saveMode ? '保存到 Documents' : '从 Documents 打开'),
|
||||
content: SizedBox(
|
||||
width: 420,
|
||||
child: widget.saveMode
|
||||
? Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Text('文件将保存到平板存储的 ${AndroidDocs.displayDir}/',
|
||||
style: TextStyle(color: t.dim, fontSize: 11)),
|
||||
const SizedBox(height: 10),
|
||||
TextField(
|
||||
controller: _name,
|
||||
autofocus: true,
|
||||
style: TextStyle(color: t.text, fontSize: 12.5),
|
||||
decoration: InputDecoration(
|
||||
isDense: true,
|
||||
labelText: '文件名(${widget.suffix})',
|
||||
filled: true,
|
||||
fillColor: t.panel2,
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
if (_loading)
|
||||
const Padding(
|
||||
padding: EdgeInsets.all(16),
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
)
|
||||
else if (_error != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(10),
|
||||
child: Text(_error!, style: TextStyle(color: t.danger, fontSize: 11.5)),
|
||||
)
|
||||
else if (_files.isEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Text('Documents 目录中暂无 ${widget.suffix} 文件',
|
||||
style: TextStyle(color: t.dim, fontSize: 11.5)),
|
||||
)
|
||||
else
|
||||
Flexible(
|
||||
child: ListView.builder(
|
||||
shrinkWrap: true,
|
||||
itemCount: _files.length,
|
||||
itemBuilder: (BuildContext ctx, int i) {
|
||||
final Map<String, dynamic> f = _files[i];
|
||||
final String name = f['name'] as String? ?? '';
|
||||
return ListTile(
|
||||
dense: true,
|
||||
leading: Icon(Icons.description, size: 20, color: t.sub),
|
||||
title: Text(name, style: TextStyle(color: t.text, fontSize: 12)),
|
||||
onTap: () => Navigator.pop(context, name),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: widget.saveMode
|
||||
? <Widget>[
|
||||
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
|
||||
FilledButton(
|
||||
onPressed: () {
|
||||
final String name = _ensureSuffix(_name.text);
|
||||
if (name.isEmpty) return;
|
||||
Navigator.pop(context, name);
|
||||
},
|
||||
child: const Text('保存'),
|
||||
),
|
||||
]
|
||||
: <Widget>[
|
||||
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
|
||||
if (!_loading && _error == null)
|
||||
TextButton.icon(
|
||||
onPressed: _load,
|
||||
icon: const Icon(Icons.refresh, size: 16),
|
||||
label: const Text('刷新'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ===================== 动作编辑对话框 =====================
|
||||
|
||||
/// 动作编辑对话框:修改选中动作的名称、驱动、工位、相位与颜色。
|
||||
|
||||
Reference in New Issue
Block a user