calculator_page.dart 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter_math_fork/flutter_math.dart';
  4. import 'package:provider/provider.dart';
  5. import 'curve_plot.dart';
  6. import 'expr_editor.dart';
  7. import 'expr_node.dart';
  8. import 'symja.dart';
  9. import 'symja_functions.dart';
  10. /// 科学计算器(默认主界面)。
  11. ///
  12. /// 输入用**结构化节点树**(见 lib/expr_node.dart),不是字符串:
  13. /// 按键把节点插进当前光标槽,分数竖排、指数上标、多参数函数各有自己的槽。
  14. /// 纯文本输入留给控制台。
  15. class CalculatorPage extends StatefulWidget {
  16. const CalculatorPage({super.key});
  17. @override
  18. State<CalculatorPage> createState() => _CalculatorPageState();
  19. }
  20. class _CalculatorPageState extends State<CalculatorPage> {
  21. final _doc = ExprDoc();
  22. SymjaResult? _preview;
  23. SymjaResult? _committed;
  24. String? _error;
  25. Timer? _debounce;
  26. int _seq = 0;
  27. @override
  28. void dispose() {
  29. _debounce?.cancel();
  30. super.dispose();
  31. }
  32. // ------------------------------------------------------------------ 求值
  33. /// 编辑器每次变化都走这里:清掉上次的提交态,防抖后重算预览。
  34. void _onDocChanged() {
  35. setState(() {
  36. _committed = null;
  37. _error = null;
  38. });
  39. _debounce?.cancel();
  40. _debounce = Timer(const Duration(milliseconds: 500), _runPreview);
  41. }
  42. String get _source => _doc.toSymja();
  43. Future<void> _runPreview() async {
  44. final expr = _source;
  45. if (expr.isEmpty || expr == 'Null') {
  46. if (mounted) setState(() => _preview = null);
  47. return;
  48. }
  49. final session = context.read<SymjaSession>();
  50. final id = ++_seq;
  51. final r = await session.preview(expr);
  52. if (!mounted || id != _seq) return; // 已有更新的预览在路上
  53. setState(() => _preview = r);
  54. }
  55. Future<void> _commit() async {
  56. final expr = _source;
  57. if (expr.isEmpty || expr == 'Null') return;
  58. _debounce?.cancel();
  59. final session = context.read<SymjaSession>();
  60. final id = ++_seq; // 让在途的预览作废
  61. try {
  62. final r = await session.evaluate(expr);
  63. if (!mounted || id != _seq) return;
  64. setState(() {
  65. _committed = r;
  66. _preview = null;
  67. _error = null;
  68. });
  69. } on SymjaException catch (e) {
  70. if (!mounted || id != _seq) return;
  71. setState(() {
  72. _error = '$e';
  73. _committed = null;
  74. _preview = null;
  75. });
  76. }
  77. await session.refreshVariables();
  78. }
  79. Future<void> _plotCurrent() async {
  80. final expr = _source;
  81. if (expr.isEmpty || expr == 'Null') return;
  82. final session = context.read<SymjaSession>();
  83. final messenger = ScaffoldMessenger.of(context);
  84. try {
  85. final s = await session.sample(expr, from: -6.3, to: 6.3, count: 240);
  86. if (!mounted) return;
  87. await showDialog<void>(
  88. context: context,
  89. builder: (_) => AlertDialog(
  90. title: Text('$expr (${s.ys.length} 点,${s.elapsedMs} ms)'),
  91. content: SizedBox(
  92. width: 360,
  93. height: 280,
  94. child: CurvePlot(series: [
  95. CurveSeries(
  96. label: expr,
  97. color: const Color(0xFF3F51B5),
  98. points: [
  99. for (var i = 0; i < s.ys.length; i++)
  100. Offset(s.xAt(i), s.ys[i]),
  101. ],
  102. ),
  103. ]),
  104. ),
  105. actions: [
  106. TextButton(
  107. onPressed: () => Navigator.pop(context),
  108. child: const Text('关闭'),
  109. ),
  110. ],
  111. ),
  112. );
  113. } on SymjaException catch (e) {
  114. messenger.showSnackBar(SnackBar(content: Text('$e')));
  115. }
  116. }
  117. // ------------------------------------------------------------------ 按键
  118. void _press(_Key k) {
  119. switch (k.act) {
  120. case _Act.char:
  121. if (k.mergeDigit) {
  122. // 数字键并入左边那个数字字面量,`42` 才是一个数而不是两个节点
  123. _doc.insertChar(k.payload);
  124. } else {
  125. _doc.insert(LitNode(k.payload));
  126. }
  127. case _Act.fn:
  128. _doc.applyFunction(k.payload);
  129. case _Act.fnPrefixed:
  130. // 像 Integrate 这种:包的时候整槽当第一个参数,其余按 prefill 预置
  131. _doc.applyFunction(k.payload, prefill: k.prefill);
  132. case _Act.sqrt:
  133. _doc.applyFunction('Sqrt');
  134. case _Act.group:
  135. _doc.makeGroup();
  136. case _Act.power:
  137. _doc.makePower();
  138. case _Act.frac:
  139. _doc.makeFraction();
  140. case _Act.postfix:
  141. // 阶乘是后缀:把光标左边那个节点收进来当操作数
  142. final operand = _doc.takeLeft();
  143. _doc.insert(PostfixNode(
  144. operand: SeqNode(operand == null ? null : [operand]),
  145. ));
  146. case _Act.comma:
  147. _doc.nextArgument();
  148. case _Act.back:
  149. _doc.backspace();
  150. case _Act.clear:
  151. _doc.clear();
  152. case _Act.commit:
  153. _commit();
  154. return; // 提交不改文档,不用刷新
  155. }
  156. _onDocChanged();
  157. }
  158. Future<void> _showPalette() async {
  159. final picked = await showModalBottomSheet<({String value, bool isFn})>(
  160. context: context,
  161. isScrollControlled: true,
  162. showDragHandle: true,
  163. builder: (_) => const _FunctionPalette(),
  164. );
  165. if (picked == null) return;
  166. if (picked.isFn) {
  167. _doc.applyFunction(picked.value);
  168. } else {
  169. _doc.insert(LitNode(picked.value));
  170. }
  171. _onDocChanged();
  172. }
  173. // ------------------------------------------------------------------ UI
  174. @override
  175. Widget build(BuildContext context) {
  176. final session = context.watch<SymjaSession>();
  177. return Scaffold(
  178. appBar: AppBar(
  179. title: const Text('计算器'),
  180. actions: [
  181. // 精确 / 近似 切换。默认精确:`1/3` 就是 `1/3`,这是符号计算的意义所在。
  182. TextButton(
  183. onPressed: () {
  184. session.approximate = !session.approximate;
  185. _onDocChanged(); // 立刻按新模式重算预览
  186. },
  187. child: Text(
  188. session.approximate ? '≈ 近似' : '精确',
  189. style: TextStyle(
  190. fontFamily: 'monospace',
  191. fontSize: 13,
  192. color: Theme.of(context).colorScheme.primary,
  193. ),
  194. ),
  195. ),
  196. IconButton(
  197. tooltip: '画图(x ∈ [-6.3, 6.3])',
  198. icon: const Icon(Icons.show_chart),
  199. onPressed: _plotCurrent,
  200. ),
  201. IconButton(
  202. tooltip: '函数面板',
  203. icon: const Icon(Icons.functions),
  204. onPressed: _showPalette,
  205. ),
  206. IconButton(
  207. tooltip: '清空',
  208. icon: const Icon(Icons.refresh),
  209. onPressed: () {
  210. _doc.clear();
  211. _onDocChanged();
  212. },
  213. ),
  214. ],
  215. ),
  216. body: SafeArea(
  217. child: Column(
  218. children: [
  219. _display(context),
  220. const Divider(height: 1),
  221. Expanded(child: _keypad(context)),
  222. ],
  223. ),
  224. ),
  225. );
  226. }
  227. Widget _display(BuildContext context) {
  228. final scheme = Theme.of(context).colorScheme;
  229. final shown = _committed ?? _preview;
  230. return Container(
  231. width: double.infinity,
  232. constraints: const BoxConstraints(minHeight: 132),
  233. padding: const EdgeInsets.fromLTRB(12, 10, 12, 10),
  234. color: scheme.surfaceContainerLow,
  235. child: Column(
  236. crossAxisAlignment: CrossAxisAlignment.end,
  237. children: [
  238. ExprEditor(doc: _doc, onChanged: _onDocChanged),
  239. const SizedBox(height: 6),
  240. // 序列化结果摆在明面上:用户能看到"到底会被求值成什么"
  241. Text(
  242. _source,
  243. textAlign: TextAlign.right,
  244. style: TextStyle(
  245. fontFamily: 'monospace',
  246. fontSize: 11,
  247. color: scheme.outline,
  248. ),
  249. ),
  250. const SizedBox(height: 6),
  251. SizedBox(
  252. height: 52,
  253. width: double.infinity,
  254. // 等比缩到放得下,**不横向滚动** ——
  255. // 滚动的话长结果只能看到尾巴,"显示不全"就是这么来的。
  256. child: FittedBox(
  257. fit: BoxFit.scaleDown,
  258. alignment: Alignment.centerRight,
  259. child: _resultView(context, shown),
  260. ),
  261. ),
  262. ],
  263. ),
  264. );
  265. }
  266. Widget _resultView(BuildContext context, SymjaResult? shown) {
  267. final scheme = Theme.of(context).colorScheme;
  268. if (_error != null) {
  269. return SelectableText(
  270. _error!,
  271. style: TextStyle(
  272. fontFamily: 'monospace',
  273. fontSize: 13,
  274. color: scheme.error,
  275. ),
  276. );
  277. }
  278. if (shown == null) return const SizedBox.shrink();
  279. final plain = SelectableText(
  280. shown.text,
  281. style: const TextStyle(fontFamily: 'monospace', fontSize: 22),
  282. );
  283. final tex = shown.tex;
  284. final body = tex == null
  285. ? plain
  286. : Math.tex(
  287. tex,
  288. mathStyle: MathStyle.display,
  289. textStyle: TextStyle(fontSize: 26, color: scheme.onSurface),
  290. onErrorFallback: (_) => plain,
  291. );
  292. return Row(
  293. mainAxisSize: MainAxisSize.min,
  294. children: [
  295. if (_committed != null) ...[
  296. Icon(Icons.check_circle, size: 16, color: scheme.primary),
  297. const SizedBox(width: 6),
  298. Text('${_committed!.elapsedMs} ms',
  299. style: TextStyle(fontSize: 11, color: scheme.outline)),
  300. const SizedBox(width: 10),
  301. ],
  302. body,
  303. ],
  304. );
  305. }
  306. Widget _keypad(BuildContext context) {
  307. return LayoutBuilder(
  308. builder: (context, box) {
  309. final rows = <List<_Key>>[
  310. [
  311. _Key('∫', _Act.fnPrefixed, payload: 'Integrate', prefill: ['', 'x']),
  312. _Key('Σ', _Act.fnPrefixed,
  313. payload: 'Sum', prefill: ['', '{n, 1, Infinity}']),
  314. _Key('d/dx', _Act.fnPrefixed, payload: 'D', prefill: ['', 'x']),
  315. _Key('lim', _Act.fnPrefixed, payload: 'Limit', prefill: ['', 'x->0']),
  316. _Key('solve', _Act.fnPrefixed, payload: 'Solve', prefill: ['', 'x']),
  317. ],
  318. [
  319. _Key('sin', _Act.fn, payload: 'Sin'),
  320. _Key('cos', _Act.fn, payload: 'Cos'),
  321. _Key('tan', _Act.fn, payload: 'Tan'),
  322. _Key('ln', _Act.fn, payload: 'Log'),
  323. _Key('√', _Act.sqrt),
  324. ],
  325. [
  326. _Key('7', _Act.char, payload: '7', mergeDigit: true),
  327. _Key('8', _Act.char, payload: '8', mergeDigit: true),
  328. _Key('9', _Act.char, payload: '9', mergeDigit: true),
  329. _Key('(', _Act.group),
  330. _Key('/', _Act.frac),
  331. ],
  332. [
  333. _Key('4', _Act.char, payload: '4', mergeDigit: true),
  334. _Key('5', _Act.char, payload: '5', mergeDigit: true),
  335. _Key('6', _Act.char, payload: '6', mergeDigit: true),
  336. _Key('×', _Act.char, payload: '*'),
  337. _Key('!', _Act.postfix),
  338. ],
  339. [
  340. _Key('1', _Act.char, payload: '1', mergeDigit: true),
  341. _Key('2', _Act.char, payload: '2', mergeDigit: true),
  342. _Key('3', _Act.char, payload: '3', mergeDigit: true),
  343. _Key('+', _Act.char, payload: '+'),
  344. _Key('−', _Act.char, payload: '-'),
  345. ],
  346. [
  347. _Key('0', _Act.char, payload: '0', mergeDigit: true),
  348. _Key('.', _Act.char, payload: '.', mergeDigit: true),
  349. _Key('^', _Act.power),
  350. _Key('x', _Act.char, payload: 'x'),
  351. _Key('n', _Act.char, payload: 'n'),
  352. ],
  353. [
  354. _Key('⌫', _Act.back, tint: true),
  355. _Key('CLR', _Act.clear, tint: true),
  356. _Key(',', _Act.comma),
  357. _Key('ANS', _Act.char, payload: '%', tint: true),
  358. _Key('=', _Act.commit, primary: true),
  359. ],
  360. ];
  361. // 7 行 + 6 个间隙,再扣掉 Padding 上下各 6 ——
  362. // box.maxHeight 是 padding **之前**的高度,漏掉会溢出。
  363. final h = (box.maxHeight - 12 - 6 * 6) / 7;
  364. return Padding(
  365. padding: const EdgeInsets.all(6),
  366. child: Column(
  367. children: [
  368. for (var r = 0; r < rows.length; r++) ...[
  369. if (r > 0) const SizedBox(height: 6),
  370. SizedBox(
  371. height: h,
  372. child: Row(
  373. children: [
  374. for (var c = 0; c < rows[r].length; c++) ...[
  375. if (c > 0) const SizedBox(width: 6),
  376. Expanded(child: _keyButton(rows[r][c])),
  377. ],
  378. ],
  379. ),
  380. ),
  381. ],
  382. ],
  383. ),
  384. );
  385. },
  386. );
  387. }
  388. Widget _keyButton(_Key k) {
  389. final scheme = Theme.of(context).colorScheme;
  390. final bg = k.primary
  391. ? scheme.primary
  392. : k.tint
  393. ? scheme.surfaceContainerHighest
  394. : scheme.surfaceContainerLow;
  395. final fg = k.primary ? scheme.onPrimary : scheme.onSurface;
  396. return Material(
  397. // 加 key 是为了让测试能精确定位按键 —— 编辑器里渲染出的字面量(比如 'x')
  398. // 和键盘上同名的按键都符合 find.text,会撞车。
  399. key: ValueKey('key-${k.label}'),
  400. color: bg,
  401. borderRadius: BorderRadius.circular(10),
  402. child: InkWell(
  403. borderRadius: BorderRadius.circular(10),
  404. onTap: () => _press(k),
  405. child: Center(
  406. child: Text(
  407. k.label,
  408. style: TextStyle(
  409. color: fg,
  410. fontSize: k.label.length > 2 ? 13 : 17,
  411. fontFamily: k.label.length > 2 ? null : 'monospace',
  412. ),
  413. ),
  414. ),
  415. ),
  416. );
  417. }
  418. }
  419. enum _Act {
  420. char,
  421. fn,
  422. fnPrefixed,
  423. sqrt,
  424. group,
  425. power,
  426. frac,
  427. postfix,
  428. comma,
  429. back,
  430. clear,
  431. commit,
  432. }
  433. @immutable
  434. class _Key {
  435. final String label;
  436. final _Act act;
  437. final String payload;
  438. /// fnPrefixed 用:第一个参数留空给用户填,其余的预置。
  439. final List<String> prefill;
  440. /// 数字键:并入左边那个数字字面量,而不是各建一个节点。
  441. final bool mergeDigit;
  442. final bool tint;
  443. final bool primary;
  444. const _Key(
  445. this.label,
  446. this.act, {
  447. this.payload = '',
  448. this.prefill = const [],
  449. this.mergeDigit = false,
  450. this.tint = false,
  451. this.primary = false,
  452. });
  453. }
  454. /// 函数面板:检索 Symja 的两百多个函数名,选中后插入一个函数节点。
  455. class _FunctionPalette extends StatefulWidget {
  456. const _FunctionPalette();
  457. @override
  458. State<_FunctionPalette> createState() => _FunctionPaletteState();
  459. }
  460. class _FunctionPaletteState extends State<_FunctionPalette> {
  461. final _search = TextEditingController();
  462. String _q = '';
  463. @override
  464. void dispose() {
  465. _search.dispose();
  466. super.dispose();
  467. }
  468. @override
  469. Widget build(BuildContext context) {
  470. final q = _q.trim().toLowerCase();
  471. final fns = kSymjaFunctions
  472. .where((f) => q.isEmpty || f.toLowerCase().contains(q))
  473. .toList(growable: false);
  474. return DraggableScrollableSheet(
  475. expand: false,
  476. initialChildSize: 0.75,
  477. maxChildSize: 0.95,
  478. builder: (context, scroll) => Column(
  479. children: [
  480. Padding(
  481. padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
  482. child: TextField(
  483. controller: _search,
  484. autofocus: true,
  485. decoration: InputDecoration(
  486. isDense: true,
  487. hintText: '函数名(共 ${kSymjaFunctions.length} 个)',
  488. prefixIcon: const Icon(Icons.search),
  489. border: const OutlineInputBorder(),
  490. ),
  491. onChanged: (v) => setState(() => _q = v),
  492. ),
  493. ),
  494. // 常量做成可点的 —— 它们从键盘上挪走了,得有个地方能按。
  495. Padding(
  496. padding: const EdgeInsets.symmetric(horizontal: 16),
  497. child: Wrap(
  498. spacing: 8,
  499. runSpacing: 4,
  500. crossAxisAlignment: WrapCrossAlignment.center,
  501. children: [
  502. Text('常量', style: Theme.of(context).textTheme.bodySmall),
  503. for (final c in kSymjaConstants)
  504. ActionChip(
  505. label: Text(
  506. c,
  507. style: const TextStyle(
  508. fontFamily: 'monospace', fontSize: 12),
  509. ),
  510. visualDensity: VisualDensity.compact,
  511. materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
  512. onPressed: () =>
  513. Navigator.pop(context, (value: c, isFn: false)),
  514. ),
  515. ],
  516. ),
  517. ),
  518. const Divider(height: 16),
  519. Expanded(
  520. child: fns.isEmpty
  521. ? const Center(child: Text('没有匹配的函数'))
  522. : ListView.builder(
  523. controller: scroll,
  524. itemCount: fns.length,
  525. itemBuilder: (_, i) => ListTile(
  526. dense: true,
  527. title: Text(
  528. fns[i],
  529. style: const TextStyle(fontFamily: 'monospace'),
  530. ),
  531. onTap: () => Navigator.pop(
  532. context, (value: fns[i], isFn: true)),
  533. ),
  534. ),
  535. ),
  536. ],
  537. ),
  538. );
  539. }
  540. }