tool_kit.dart 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. import 'package:flutter/material.dart';
  2. import 'package:flutter/services.dart';
  3. import 'package:flutter_math_fork/flutter_math.dart';
  4. import 'package:provider/provider.dart';
  5. import '../symja.dart';
  6. /// 工具页的公共外壳。
  7. ///
  8. /// 十五个工具原先各写各的:各自的 Scaffold、各自拼字符串、各自显示一个
  9. /// `Text`。这套外壳把**输入 → 计算 → 输出**固定下来,好处有三个:
  10. /// 1. 计算全部走 [Symja],Dart 只负责排版和取输入(绘图除外,见 [ToolChart]);
  11. /// 2. 每条输出**单独成块、点一下就复制**,不再是一大坨拼在一起的文本;
  12. /// 3. 重置按钮和错误提示不用每个工具再写一遍。
  13. ///
  14. /// 刻意不用「抽象基类 + 子类」那套写法:工具之间的差异只有"有哪些输入框"和
  15. /// "算什么表达式"两件事,交给两个参数就够了,继承反而要每个工具建一个类。
  16. class ToolScaffold extends StatefulWidget {
  17. const ToolScaffold({
  18. super.key,
  19. required this.title,
  20. required this.fields,
  21. required this.compute,
  22. this.intro,
  23. this.beforeField = const {},
  24. this.autoRun = false,
  25. });
  26. final String title;
  27. /// 打开就自动算一次。绘图和二分法这类**输入框里已经有默认值**的工具用得上:
  28. /// 一进来就该看到图/解,而不是先按一下按钮。
  29. final bool autoRun;
  30. /// 输入框。顺序即显示顺序。
  31. ///
  32. /// 由**页面**持有(建在 State 里,别建在 build 里,否则主题一变控制器就被换掉、
  33. /// 用户打的字会丢)。外壳不 dispose 它们:对称变换那种一个页面里换几组输入框的
  34. /// 工具,控制器要跨模式活着。
  35. final List<ToolField> fields;
  36. /// 工具自己的说明(公式长什么样、参数什么含义),显示在输入框上方。
  37. final Widget? intro;
  38. /// 在第 n 个输入框**前面**插一块自定义 widget(下标按 [fields] 算)。
  39. ///
  40. /// 卷积那种"一组输入框配一组增删按钮"用它 —— 按钮得贴着**自己那一组**,
  41. /// 全塞进 intro 就会两组的按钮一起跑到最上面去。
  42. final Map<int, Widget> beforeField;
  43. /// 计算。自己从 [fields] 里取文本、拼 Symja 表达式、调 [SymjaSession.compute]。
  44. ///
  45. /// 返回若干条输出:文字的可点复制,图表的不复制(图没什么可复制的)。
  46. final Future<List<ToolOutput>> Function(SymjaSession) compute;
  47. @override
  48. State<ToolScaffold> createState() => _ToolScaffoldState();
  49. }
  50. class _ToolScaffoldState extends State<ToolScaffold> {
  51. final List<ToolOutput> _outputs = [];
  52. String? _error;
  53. bool _busy = false;
  54. /// 换了一组输入框(对称变换那种切模式的情况)就把上一次的结果清掉 ——
  55. /// 留着上一模式的答案是误导。
  56. @override
  57. void didUpdateWidget(ToolScaffold old) {
  58. super.didUpdateWidget(old);
  59. if (!identical(old.fields, widget.fields)) {
  60. _outputs.clear();
  61. _error = null;
  62. }
  63. }
  64. @override
  65. void initState() {
  66. super.initState();
  67. if (widget.autoRun) {
  68. WidgetsBinding.instance.addPostFrameCallback((_) {
  69. if (mounted) _run();
  70. });
  71. }
  72. }
  73. Future<void> _run() async {
  74. final session = context.read<SymjaSession>();
  75. setState(() {
  76. _busy = true;
  77. _error = null;
  78. _outputs.clear();
  79. });
  80. try {
  81. final out = await widget.compute(session);
  82. if (!mounted) return;
  83. setState(() => _outputs.addAll(out));
  84. } on SymjaException catch (e) {
  85. if (mounted) setState(() => _error = '$e');
  86. } catch (e) {
  87. // 输入格式不对(少填了、写了非数字)在这里兜住,别把异常弹到 framework
  88. if (mounted) setState(() => _error = '$e');
  89. } finally {
  90. if (mounted) setState(() => _busy = false);
  91. }
  92. }
  93. void _reset() {
  94. for (final f in widget.fields) {
  95. f.controller.clear();
  96. }
  97. setState(() {
  98. _outputs.clear();
  99. _error = null;
  100. });
  101. }
  102. /// 把输入框排成一列,遇到标了 [ToolField.rowWithPrevious] 的就跟前一个并排。
  103. List<Widget> _fieldRows(BuildContext context) {
  104. final rows = <Widget>[];
  105. var group = <ToolField>[];
  106. void flush() {
  107. if (group.isEmpty) return;
  108. if (group.length == 1) {
  109. rows.add(group.first.build(context));
  110. } else {
  111. rows.add(
  112. Row(
  113. crossAxisAlignment: CrossAxisAlignment.start,
  114. children: [
  115. for (var i = 0; i < group.length; i++) ...[
  116. if (i > 0) const SizedBox(width: 10),
  117. Expanded(child: group[i].build(context)),
  118. ],
  119. ],
  120. ),
  121. );
  122. }
  123. group = <ToolField>[];
  124. }
  125. for (var i = 0; i < widget.fields.length; i++) {
  126. final f = widget.fields[i];
  127. final before = widget.beforeField[i];
  128. if (before != null) {
  129. flush();
  130. rows.add(before);
  131. rows.add(const SizedBox(height: 8));
  132. }
  133. if (!f.rowWithPrevious) flush();
  134. group.add(f);
  135. }
  136. flush();
  137. return rows;
  138. }
  139. /// 计算中:给个可见的反馈,复杂表达式可能要算好几秒。
  140. Widget _busyStrip(ColorScheme scheme) => Padding(
  141. padding: const EdgeInsets.symmetric(vertical: 10),
  142. child: Row(
  143. children: [
  144. const SizedBox(
  145. width: 14,
  146. height: 14,
  147. child: CircularProgressIndicator(strokeWidth: 2),
  148. ),
  149. const SizedBox(width: 10),
  150. Text('计算中…', style: TextStyle(color: scheme.outline)),
  151. ],
  152. ),
  153. );
  154. @override
  155. Widget build(BuildContext context) {
  156. final scheme = Theme.of(context).colorScheme;
  157. return Scaffold(
  158. appBar: AppBar(title: Text(widget.title)),
  159. body: ListView(
  160. padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
  161. children: [
  162. if (widget.intro != null) ...[
  163. widget.intro!,
  164. const SizedBox(height: 12),
  165. ],
  166. ..._fieldRows(context),
  167. const SizedBox(height: 12),
  168. Row(
  169. children: [
  170. Expanded(
  171. child: FilledButton.icon(
  172. onPressed: _busy ? null : _run,
  173. icon: const Icon(Icons.calculate_outlined),
  174. label: const Text('计算'),
  175. ),
  176. ),
  177. const SizedBox(width: 12),
  178. OutlinedButton.icon(
  179. onPressed: _busy ? null : _reset,
  180. icon: const Icon(Icons.refresh),
  181. label: const Text('重置'),
  182. ),
  183. ],
  184. ),
  185. if (_busy) _busyStrip(scheme),
  186. if (_error != null)
  187. Padding(
  188. padding: const EdgeInsets.only(top: 16),
  189. child: Card(
  190. color: scheme.errorContainer,
  191. child: Padding(
  192. padding: const EdgeInsets.all(14),
  193. child: Row(
  194. crossAxisAlignment: CrossAxisAlignment.start,
  195. children: [
  196. Icon(
  197. Icons.error_outline,
  198. size: 20,
  199. color: scheme.onErrorContainer,
  200. ),
  201. const SizedBox(width: 10),
  202. Expanded(
  203. child: Text(
  204. _error!,
  205. style: TextStyle(color: scheme.onErrorContainer),
  206. ),
  207. ),
  208. ],
  209. ),
  210. ),
  211. ),
  212. ),
  213. for (final o in _outputs)
  214. Padding(
  215. padding: const EdgeInsets.only(top: 12),
  216. child: _OutputCard(output: o),
  217. ),
  218. ],
  219. ),
  220. );
  221. }
  222. }
  223. /// 一个输入框。label 同时是发送给 Symja 时的变量含义提示。
  224. class ToolField {
  225. ToolField(
  226. this.label, {
  227. String? hint,
  228. this.keyboard = const TextInputType.numberWithOptions(
  229. signed: true,
  230. decimal: true,
  231. ),
  232. this.rowWithPrevious = false,
  233. }) : hint = hint ?? '输入分数如 1/2,或多个值用空格分隔',
  234. controller = TextEditingController();
  235. final String label;
  236. final String hint;
  237. final TextInputType keyboard;
  238. final TextEditingController controller;
  239. /// 和**上一个**输入框并排放在同一行(宽度平分)。
  240. ///
  241. /// 成对出现的东西不该各占一行 —— 卷积的「取值 i / 概率 i」、
  242. /// 卡方检验的 2×2 列联表都是这样。
  243. final bool rowWithPrevious;
  244. String get text => controller.text.trim();
  245. /// 这一栏里填了几个值。用来做"三组数据个数要一样"这类检查 ——
  246. /// 数个数是记账,不是计算,留在 Dart 侧。
  247. int get count => _tokens.length;
  248. List<String> get _tokens =>
  249. text.split(RegExp(r'[\s,,]+')).where((s) => s.isNotEmpty).toList();
  250. /// 空格/逗号分隔的多个值 → Symja 的列表 `{1, 2, 3}`。
  251. ///
  252. /// 工具页允许用户直接写 `1/2` 这样的分数和 `Pi` 这样的常量 —— 它们交给 Symja
  253. /// 解析,Dart 侧不做数字转换(转换反而会把 `1/2` 变成 0.5 这种近似值)。
  254. String get list => '{${_tokens.join(', ')}}';
  255. Widget build(BuildContext context) => Padding(
  256. padding: const EdgeInsets.symmetric(vertical: 6),
  257. child: TextField(
  258. controller: controller,
  259. keyboardType: keyboard,
  260. decoration: InputDecoration(
  261. labelText: label,
  262. hintText: hint,
  263. border: const OutlineInputBorder(),
  264. isDense: true,
  265. ),
  266. ),
  267. );
  268. }
  269. /// 一条输出。[ToolText] 可点复制,[ToolChart] 不行 —— 图没有可复制的文本形态。
  270. sealed class ToolOutput {
  271. const ToolOutput(this.label);
  272. final String label;
  273. }
  274. /// 一条文字输出。[tex] 不为空时渲染成数学排版,点复制复制的仍是纯文本。
  275. class ToolText extends ToolOutput {
  276. const ToolText(super.label, this.text, {this.tex});
  277. final String text;
  278. final String? tex;
  279. }
  280. /// 一条图表输出。**图表不参与复制**(任务里明确要求的)。
  281. class ToolChart extends ToolOutput {
  282. const ToolChart(super.label, this.chart);
  283. final Widget chart;
  284. }
  285. class _OutputCard extends StatelessWidget {
  286. const _OutputCard({required this.output});
  287. final ToolOutput output;
  288. Future<void> _copy(BuildContext context, String text) async {
  289. await Clipboard.setData(ClipboardData(text: text));
  290. if (!context.mounted) return;
  291. ScaffoldMessenger.of(context)
  292. ..clearSnackBars()
  293. ..showSnackBar(
  294. SnackBar(
  295. content: Text(
  296. '已复制:${text.length > 30 ? '${text.substring(0, 30)}…' : text}',
  297. ),
  298. duration: const Duration(milliseconds: 1200),
  299. ),
  300. );
  301. }
  302. @override
  303. Widget build(BuildContext context) {
  304. final scheme = Theme.of(context).colorScheme;
  305. final o = output;
  306. if (o is ToolChart) {
  307. return Card(
  308. child: Padding(
  309. padding: const EdgeInsets.all(12),
  310. child: Column(
  311. crossAxisAlignment: CrossAxisAlignment.start,
  312. children: [
  313. Text(o.label, style: Theme.of(context).textTheme.labelLarge),
  314. const SizedBox(height: 8),
  315. o.chart,
  316. ],
  317. ),
  318. ),
  319. );
  320. }
  321. final t = o as ToolText;
  322. return Card(
  323. clipBehavior: Clip.antiAlias,
  324. child: InkWell(
  325. onTap: () => _copy(context, t.text),
  326. child: Padding(
  327. padding: const EdgeInsets.all(14),
  328. child: Row(
  329. crossAxisAlignment: CrossAxisAlignment.center,
  330. children: [
  331. Expanded(
  332. child: Column(
  333. crossAxisAlignment: CrossAxisAlignment.start,
  334. children: [
  335. Text(
  336. t.label,
  337. style: TextStyle(fontSize: 12, color: scheme.outline),
  338. ),
  339. const SizedBox(height: 6),
  340. // 有 TeX 就用数学排版显示;太长或没生成就退回纯文本
  341. if (t.tex != null)
  342. Math.tex(
  343. t.tex!,
  344. mathStyle: MathStyle.text,
  345. textStyle: TextStyle(
  346. fontSize: 20,
  347. color: scheme.onSurface,
  348. ),
  349. onErrorFallback: (_) => _plain(t.text),
  350. )
  351. else
  352. _plain(t.text),
  353. ],
  354. ),
  355. ),
  356. const SizedBox(width: 8),
  357. Icon(Icons.copy_outlined, size: 18, color: scheme.outline),
  358. ],
  359. ),
  360. ),
  361. ),
  362. );
  363. }
  364. /// 纯文本渲染。刻意用 `Text` 而不是 `SelectableText` —— 后者会把点击吃掉拿去
  365. /// 做选区,整张卡片的"点一下复制"就时灵时不灵了。
  366. Widget _plain(String text) =>
  367. Text(text, style: const TextStyle(fontFamily: 'monospace', fontSize: 16));
  368. }
  369. /// 近似值的 Symja 写法:保留 k 位**小数**。
  370. ///
  371. /// 为什么不是 `N[expr, k]`:**Symja 的 N 忽略第二个参数**(实测 4 位和 15 位打印
  372. /// 一模一样)。`NumberForm` / `SetPrecision` 也没实现(会原样返回 numberform(...))。
  373. /// `Round[值, 1/10^k]` 是真把值截到 k 位小数,文本和 LaTeX 都跟着变干净。
  374. String approxExpr(String expr, int digits) => 'N[Round[$expr, 1/10^$digits]]';
  375. /// 精确值 + 近似值两行输出。
  376. ///
  377. /// 工具页原先在 Dart 里既给分数又给小数(`1/3 (≈0.3333)`)。精确值走
  378. /// `Rationalize` —— 输入写成小数(`0.2`)时 Symja 会一路按小数算下去,
  379. /// 均值显示成 `3.6` 就不再是"精确值"了;`Rationalize` 把它还原成分数 `18/5`。
  380. /// 近似值再问一次 `N[...]`。
  381. ///
  382. /// **两者相等时只留一行**,而且要比**数值**而不是字符串:`N[5]` 打印成 `5.0`,
  383. /// 拿字符串比就变成每个整数结果都多一条没用的 "5.0"。
  384. Future<List<ToolOutput>> exactAndApprox(
  385. SymjaSession session,
  386. String label,
  387. String expr,
  388. ) async {
  389. final exact = await session.compute('Rationalize[$expr]', applyMode: false);
  390. // 近似值也从**有理化之后**的数转小数:输入写成 0.2/0.3 时机器浮点会带出
  391. // `3.5999999999999996` 这种尾巴,先还原成分数再取小数就干净了(3.6)。
  392. // 位数听设置里那个滑动条(计算器的"近似"也是同一个值)。
  393. final approx = await session.compute(
  394. approxExpr('Rationalize[$expr]', session.approximateDigits),
  395. applyMode: false,
  396. );
  397. final same = _sameValue(exact.text, approx.text);
  398. return [
  399. ToolText(label, exact.text, tex: exact.tex),
  400. if (!same) ToolText('$label(近似)', approx.text, tex: approx.tex),
  401. ];
  402. }
  403. /// 两个显示串是不是同一个数(都解析得出来的话)。
  404. bool _sameValue(String a, String b) {
  405. if (a == b) return true;
  406. final x = asNumber(a), y = asNumber(b);
  407. if (x == null || y == null) return false;
  408. return (x - y).abs() <= 1e-9 * (1 + x.abs());
  409. }
  410. /// 把近似值缀在精确值后面:`16/81 ≈ 0.1975`。同一个数就只留精确值。
  411. ///
  412. /// 给"一条条分开"的分布表用 —— 每项单独成卡时不拆成两张,
  413. /// 否则 n=10 的二项分布会列出二十多张卡。
  414. String withApprox(String exact, String approx) {
  415. final a = approx.trim();
  416. if (a.isEmpty) return exact;
  417. return _sameValue(exact.trim(), a) ? exact : '$exact ≈ $a';
  418. }
  419. /// 纯数值输出:只给近似值(用户要的本来就是个数,不是分数)。
  420. Future<ToolOutput> numeric(
  421. SymjaSession session,
  422. String label,
  423. String expr,
  424. ) async {
  425. final r = await session.compute(
  426. approxExpr('Rationalize[$expr]', session.approximateDigits),
  427. applyMode: false,
  428. );
  429. return ToolText(label, r.text, tex: null);
  430. }
  431. /// 把 Symja 输出的列表文本拆成嵌套的字符串列表。
  432. ///
  433. /// 工具要拿到"一条条"结果(比如每个 k 的概率、每对卷积取值)才能分开显示,
  434. /// 而通道里回来的是 `{{0, 1/6}, {1, 1/3}}` 这样一个字符串。刻意**不**做数字解析:
  435. /// 拆出来的还是 Symja 的原文(`1/6` 就是 `1/6`),要算数再交回给 Symja。
  436. List<Object> parseSymjaList(String s) {
  437. final t = s.trim();
  438. if (!t.startsWith('{') || !t.endsWith('}')) return [t];
  439. final out = <Object>[];
  440. final buf = StringBuffer();
  441. var depth = 0;
  442. for (var i = 1; i < t.length - 1; i++) {
  443. final c = t[i];
  444. if (c == '{' || c == '[' || c == '(') depth++;
  445. if (c == '}' || c == ']' || c == ')') depth--;
  446. if (c == ',' && depth == 0) {
  447. out.add(_item(buf.toString()));
  448. buf.clear();
  449. continue;
  450. }
  451. buf.write(c);
  452. }
  453. if (buf.isNotEmpty) out.add(_item(buf.toString()));
  454. return out;
  455. }
  456. Object _item(String raw) {
  457. final t = raw.trim();
  458. return t.startsWith('{') ? parseSymjaList(t) : t;
  459. }
  460. /// 取出列表里的数字(Symja 的近似值带一个 `` ` `` 精度标记,要去掉)。
  461. ///
  462. /// 只给**画图**用 —— 图表要的是 double,而"精确值"那条路始终走 Symja 原文。
  463. double? asNumber(Object? item) {
  464. if (item is! String) return null;
  465. return double.tryParse(item.replaceAll('`', '').trim());
  466. }