From 0f0adf750c8cde668cdcf369cbe0ac173a9edf3f Mon Sep 17 00:00:00 2001
From: toasted-nutbread <toasted-nutbread@users.noreply.github.com>
Date: Thu, 15 Aug 2019 19:39:58 -0400
Subject: Add ability to save screenshot to anki cards

---
 ext/mixed/js/display.js | 43 ++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 42 insertions(+), 1 deletion(-)

(limited to 'ext/mixed/js')

diff --git a/ext/mixed/js/display.js b/ext/mixed/js/display.js
index 3bb78fe1..eeb42040 100644
--- a/ext/mixed/js/display.js
+++ b/ext/mixed/js/display.js
@@ -432,7 +432,15 @@ class Display {
         try {
             this.spinner.show();
 
-            const noteId = await apiDefinitionAdd(definition, mode);
+            const context = {};
+            if (this.noteUsesScreenshot()) {
+                const screenshot = await this.getScreenshot();
+                if (screenshot) {
+                    context.screenshot = screenshot;
+                }
+            }
+
+            const noteId = await apiDefinitionAdd(definition, mode, context);
             if (noteId) {
                 const index = this.definitions.indexOf(definition);
                 Display.adderButtonFind(index, mode).addClass('disabled');
@@ -485,10 +493,39 @@ class Display {
         }
     }
 
+    noteUsesScreenshot() {
+        const fields = this.options.anki.terms.fields;
+        for (const name in fields) {
+            if (fields[name].includes('{screenshot}')) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    async getScreenshot() {
+        try {
+            await this.setPopupVisible(false);
+            await Display.delay(1); // Wait for popup to be hidden.
+
+            const format = 'png';
+            const dataUrl = await apiScreenshotGet({format});
+            if (!dataUrl || dataUrl.error) { return; }
+
+            return {dataUrl, format};
+        } finally {
+            await this.setPopupVisible(true);
+        }
+    }
+
     get firstExpressionIndex() {
         return this.options.general.resultOutputMode === 'merge' ? 0 : -1;
     }
 
+    setPopupVisible(visible) {
+        return apiForward('popupSetVisible', {visible});
+    }
+
     static clozeBuild(sentence, source) {
         const result = {
             sentence: sentence.text.trim()
@@ -514,4 +551,8 @@ class Display {
     static viewerButtonFind(index) {
         return $('.entry').eq(index).find('.action-view-note');
     }
+
+    static delay(time) {
+        return new Promise((resolve) => setTimeout(resolve, time));
+    }
 }
-- 
cgit v1.2.3