|
| 1 | +package md.zennotes; |
| 2 | + |
| 3 | +import android.content.res.AssetFileDescriptor; |
| 4 | +import android.os.CancellationSignal; |
| 5 | +import android.os.Handler; |
| 6 | +import android.os.Looper; |
| 7 | +import android.util.Base64; |
| 8 | +import androidx.core.view.inputmethod.InputConnectionCompat; |
| 9 | +import androidx.core.view.inputmethod.InputContentInfoCompat; |
| 10 | +import com.getcapacitor.JSObject; |
| 11 | +import com.getcapacitor.Plugin; |
| 12 | +import com.getcapacitor.PluginCall; |
| 13 | +import com.getcapacitor.PluginMethod; |
| 14 | +import com.getcapacitor.annotation.CapacitorPlugin; |
| 15 | +import java.io.InputStream; |
| 16 | +import java.io.IOException; |
| 17 | +import java.util.HashMap; |
| 18 | +import java.util.Map; |
| 19 | +import java.util.UUID; |
| 20 | +import java.util.concurrent.ExecutorService; |
| 21 | +import java.util.concurrent.Executors; |
| 22 | +import java.util.concurrent.RejectedExecutionException; |
| 23 | + |
| 24 | +@CapacitorPlugin(name = "ImagePaste") |
| 25 | +public class ImagePastePlugin extends Plugin { |
| 26 | + private final Map<String, InputContentInfoCompat> pending = new HashMap<>(); |
| 27 | + private final Handler expiry = new Handler(Looper.getMainLooper()); |
| 28 | + private final ExecutorService reader = Executors.newSingleThreadExecutor(); |
| 29 | + private ClipboardImageRead activeRead; |
| 30 | + private volatile boolean destroyed; |
| 31 | + |
| 32 | + @Override public void load() { |
| 33 | + ((ImagePasteWebView) getBridge().getWebView()).imageReceiver = this::receive; |
| 34 | + } |
| 35 | + |
| 36 | + @PluginMethod public void setEnabled(PluginCall call) { |
| 37 | + boolean enabled = call.getBoolean("enabled", false); |
| 38 | + getActivity().runOnUiThread(() -> { |
| 39 | + if (destroyed) { call.reject("Image pasting is unavailable."); return; } |
| 40 | + ((ImagePasteWebView) getBridge().getWebView()).setImagePasteEnabled(enabled); |
| 41 | + call.resolve(); |
| 42 | + }); |
| 43 | + } |
| 44 | + |
| 45 | + private synchronized boolean receive(InputContentInfoCompat content, int flags) { |
| 46 | + if (destroyed || !hasListeners("image") || activeRead != null || !pending.isEmpty() || !"content".equals(content.getContentUri().getScheme())) return false; |
| 47 | + boolean supported = false; |
| 48 | + for (String type : ImagePasteWebView.IMAGE_TYPES) supported |= content.getDescription().hasMimeType(type); |
| 49 | + if (!supported) return false; |
| 50 | + try { |
| 51 | + if ((flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0) content.requestPermission(); |
| 52 | + } catch (RuntimeException error) { return false; } |
| 53 | + String id = UUID.randomUUID().toString(); |
| 54 | + pending.put(id, content); |
| 55 | + JSObject event = new JSObject(); |
| 56 | + event.put("id", id); |
| 57 | + notifyListeners("image", event); |
| 58 | + expiry.postDelayed(() -> release(id), 30000); |
| 59 | + return true; |
| 60 | + } |
| 61 | + |
| 62 | + private synchronized InputContentInfoCompat take(String id) { return pending.remove(id); } |
| 63 | + private void release(String id) { |
| 64 | + InputContentInfoCompat content = take(id); |
| 65 | + if (content != null) releasePermission(content); |
| 66 | + } |
| 67 | + private static void releasePermission(InputContentInfoCompat content) { |
| 68 | + try { content.releasePermission(); } catch (RuntimeException ignored) { /* provider already revoked it */ } |
| 69 | + } |
| 70 | + |
| 71 | + // Plugin methods run off the UI thread. Never send arbitrary URIs through |
| 72 | + // the JS bridge: read only the short-lived token from a user paste event. |
| 73 | + @PluginMethod public synchronized void read(PluginCall call) { |
| 74 | + if (destroyed) { call.reject("Image pasting is unavailable."); return; } |
| 75 | + InputContentInfoCompat content = take(call.getString("id", "")); |
| 76 | + if (content == null) { call.reject("The pasted image expired. Please paste it again."); return; } |
| 77 | + CancellationSignal cancellation = new CancellationSignal(); |
| 78 | + ClipboardImageRead read = new ClipboardImageRead(() -> { |
| 79 | + releasePermission(content); |
| 80 | + try { cancellation.cancel(); } catch (RuntimeException ignored) { /* provider already gone */ } |
| 81 | + }); |
| 82 | + activeRead = read; |
| 83 | + try { reader.execute(() -> readImage(call, content, read, cancellation)); } |
| 84 | + catch (RejectedExecutionException error) { |
| 85 | + activeRead = null; |
| 86 | + read.close(); |
| 87 | + call.reject("Image pasting is unavailable. Please reopen the note."); |
| 88 | + } |
| 89 | + } |
| 90 | + private void readImage(PluginCall call, InputContentInfoCompat content, ClipboardImageRead read, CancellationSignal cancellation) { |
| 91 | + try { |
| 92 | + if (read.isClosed()) return; |
| 93 | + byte[] bytes; |
| 94 | + try (AssetFileDescriptor descriptor = getContext().getContentResolver() |
| 95 | + .openAssetFileDescriptor(content.getContentUri(), "r", cancellation)) { |
| 96 | + InputStream stream = read.attach(descriptor == null ? null : descriptor.createInputStream()); |
| 97 | + bytes = ClipboardImageData.read(stream, ClipboardImageData.MAX_BYTES); |
| 98 | + } |
| 99 | + JSObject result = new JSObject(); |
| 100 | + result.put("mimeType", ClipboardImageData.mimeType(bytes)); |
| 101 | + result.put("base64", Base64.encodeToString(bytes, Base64.NO_WRAP)); |
| 102 | + read.respondIfOpen(() -> call.resolve(result)); |
| 103 | + } catch (ClipboardImageData.InvalidImage error) { |
| 104 | + read.respondIfOpen(() -> call.reject(error.getMessage())); |
| 105 | + } catch (IOException | RuntimeException error) { |
| 106 | + read.respondIfOpen(() -> call.reject("Could not read the pasted image. Please copy it again.")); |
| 107 | + } finally { |
| 108 | + read.close(); |
| 109 | + synchronized (this) { if (activeRead == read) activeRead = null; } |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + @PluginMethod public void discard(PluginCall call) { |
| 114 | + release(call.getString("id", "")); |
| 115 | + call.resolve(); |
| 116 | + } |
| 117 | + |
| 118 | + @Override protected synchronized void handleOnDestroy() { |
| 119 | + destroyed = true; |
| 120 | + expiry.removeCallbacksAndMessages(null); |
| 121 | + if (activeRead != null) { activeRead.close(); activeRead = null; } |
| 122 | + reader.shutdownNow(); |
| 123 | + for (InputContentInfoCompat content : pending.values()) releasePermission(content); |
| 124 | + pending.clear(); |
| 125 | + } |
| 126 | +} |
0 commit comments