From e047787e2963dea6b7d77264105acdf9a77b4dd4 Mon Sep 17 00:00:00 2001 From: Vishesh Handa Date: Tue, 19 May 2020 19:40:30 +0200 Subject: [PATCH] KatexWidget: Cache the generated images The file is stored in the tmp dir with the filename of "katex_$HASH$.png" where $HASH$ is the md5 hash of the input string to be rendered. The cache isn't ever cleared so far, but maybe the underlying OS will do that automatically? Related to #125 --- lib/widgets/katex_widget.dart | 31 ++++++++++++++----------------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/lib/widgets/katex_widget.dart b/lib/widgets/katex_widget.dart index 3c4cf0c9..dc254104 100644 --- a/lib/widgets/katex_widget.dart +++ b/lib/widgets/katex_widget.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:convert'; import 'dart:io'; import 'package:flutter/material.dart'; @@ -6,6 +7,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_webview_plugin/flutter_webview_plugin.dart'; import 'package:path/path.dart' as p; import 'package:mutex/mutex.dart'; +import 'package:crypto/crypto.dart'; class KatexWidget extends StatefulWidget { final String input; @@ -30,6 +32,9 @@ class _KatexWidgetState extends State { void initState() { super.initState(); + var inputHash = md5.convert(utf8.encode(widget.input)).toString(); + imagePath = p.join(Directory.systemTemp.path, "katex_$inputHash.png"); + jsChannel = JavascriptChannel( name: 'Print', onMessageReceived: (JavascriptMessage message) { @@ -37,23 +42,11 @@ class _KatexWidgetState extends State { print(message.message); var uri = UriData.parse(message.message); + File(imagePath).writeAsBytesSync(uri.contentAsBytes()); - String tmpFile; - var num = 0; - while (true) { - tmpFile = p.join(Directory.systemTemp.path, "katex_$num.png"); - if (!File(tmpFile).existsSync()) { - break; - } - num += 1; - } - File(tmpFile).writeAsBytesSync(uri.contentAsBytes()); - + // Underlying image file has been modified if (mounted) { - setState(() { - print("State has been set $tmpFile"); - imagePath = tmpFile; - }); + setState(() {}); } flutterWebViewPlugin.close(); @@ -65,7 +58,11 @@ class _KatexWidgetState extends State { }, ); - _initAsync(); + if (File(imagePath).existsSync()) { + print("Katex ${widget.input} in cache"); + } else { + _initAsync(); + } } void _initAsync() async { @@ -119,7 +116,7 @@ html2canvas(document.body, {backgroundColor: 'rgba(0, 0, 0, 0)', removeContainer @override Widget build(BuildContext context) { - if (imagePath == null) { + if (!File(imagePath).existsSync()) { return Container(); }