mirror of
https://github.com/tauri-apps/plugins-workspace.git
synced 2026-01-31 00:45:24 +01:00
* feat(dialog) - Support fileAccessMode for open dialog (#3030) On iOS, when trying to access a file that exists outside of the app sandbox, one of 2 things need to happen to be able to perform any operations on said file: * A copy of the file needs to be made to the internal app sandbox * The method startAccessingSecurityScopedResource needs to be called. Previously, a copy of the file was always being made when a file was selected through the picker dialog. While this did ensure there were no file access exceptions when reading from the file, it does not scale well for large files. To resolve this, we now support `fileAccessMode`, which allows a file handle to be returned without copying the file to the app sandbox. This MR only supports this change for iOS; MacOS has a different set of needs for security scoped resources. See discussion in #3716 for more discussion of the difference between iOS and MacOS. See MR #3185 to see how these scoped files will be accessible using security scoping. * fmt, clippy * use enum --------- Co-authored-by: Lucas Nogueira <lucas@tauri.app>
This commit is contained in:
6
.changes/support-file-access-mode-ios.md
Normal file
6
.changes/support-file-access-mode-ios.md
Normal file
@@ -0,0 +1,6 @@
|
||||
---
|
||||
"dialog": minor
|
||||
"dialog-js": minor
|
||||
---
|
||||
|
||||
Add `fileAccessMode` option to file picker.
|
||||
@@ -8,7 +8,8 @@
|
||||
let filter = null;
|
||||
let multiple = false;
|
||||
let directory = false;
|
||||
let pickerMode = "";
|
||||
let pickerMode = "document";
|
||||
let fileAccessMode = "scoped";
|
||||
|
||||
function arrayBufferToBase64(buffer, callback) {
|
||||
var blob = new Blob([buffer], {
|
||||
@@ -52,54 +53,60 @@
|
||||
.catch(onMessage);
|
||||
}
|
||||
|
||||
function openDialog() {
|
||||
open({
|
||||
title: "My wonderful open dialog",
|
||||
defaultPath,
|
||||
filters: filter
|
||||
? [
|
||||
{
|
||||
name: "Tauri Example",
|
||||
extensions: filter.split(",").map((f) => f.trim()),
|
||||
},
|
||||
]
|
||||
: [],
|
||||
multiple,
|
||||
directory,
|
||||
pickerMode: pickerMode === "" ? undefined : pickerMode,
|
||||
})
|
||||
.then(function (res) {
|
||||
if (Array.isArray(res)) {
|
||||
onMessage(res);
|
||||
} else {
|
||||
var pathToRead = res;
|
||||
var isFile = pathToRead.match(/\S+\.\S+$/g);
|
||||
readFile(pathToRead)
|
||||
.then(function (response) {
|
||||
if (isFile) {
|
||||
if (
|
||||
pathToRead.includes(".png") ||
|
||||
pathToRead.includes(".jpg") ||
|
||||
pathToRead.includes(".jpeg")
|
||||
) {
|
||||
arrayBufferToBase64(
|
||||
new Uint8Array(response),
|
||||
function (base64) {
|
||||
var src = "data:image/png;base64," + base64;
|
||||
insecureRenderHtml('<img src="' + src + '"></img>');
|
||||
}
|
||||
);
|
||||
} else {
|
||||
onMessage(res);
|
||||
}
|
||||
} else {
|
||||
onMessage(res);
|
||||
}
|
||||
})
|
||||
.catch(onMessage);
|
||||
}
|
||||
async function openDialog() {
|
||||
try {
|
||||
var result = await open({
|
||||
title: "My wonderful open dialog",
|
||||
defaultPath,
|
||||
filters: filter
|
||||
? [
|
||||
{
|
||||
name: "Tauri Example",
|
||||
extensions: filter.split(",").map((f) => f.trim()),
|
||||
},
|
||||
]
|
||||
: [],
|
||||
multiple,
|
||||
directory,
|
||||
pickerMode,
|
||||
fileAccessMode,
|
||||
})
|
||||
.catch(onMessage);
|
||||
|
||||
if (Array.isArray(result)) {
|
||||
onMessage(result);
|
||||
} else {
|
||||
var pathToRead = result;
|
||||
var isFile = pathToRead.match(/\S+\.\S+$/g);
|
||||
|
||||
await readFile(pathToRead)
|
||||
.then(function (res) {
|
||||
if (isFile) {
|
||||
if (
|
||||
pathToRead.includes(".png") ||
|
||||
pathToRead.includes(".jpg") ||
|
||||
pathToRead.includes(".jpeg")
|
||||
) {
|
||||
arrayBufferToBase64(
|
||||
new Uint8Array(res),
|
||||
function (base64) {
|
||||
var src = "data:image/png;base64," + base64;
|
||||
insecureRenderHtml('<img src="' + src + '"></img>');
|
||||
}
|
||||
);
|
||||
} else {
|
||||
// Convert byte array to UTF-8 string
|
||||
const decoder = new TextDecoder('utf-8');
|
||||
const text = decoder.decode(new Uint8Array(res));
|
||||
onMessage(text);
|
||||
}
|
||||
} else {
|
||||
onMessage(res);
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch(exception) {
|
||||
onMessage(exception)
|
||||
}
|
||||
}
|
||||
|
||||
function saveDialog() {
|
||||
@@ -154,6 +161,13 @@
|
||||
<option value="document">Document</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label for="dialog-file-access-mode">File Access Mode:</label>
|
||||
<select id="dialog-file-access-mode" bind:value={fileAccessMode}>
|
||||
<option value="copy">Copy</option>
|
||||
<option value="scoped">Scoped</option>
|
||||
</select>
|
||||
</div>
|
||||
<br />
|
||||
|
||||
<div class="flex flex-wrap flex-col md:flex-row gap-2 children:flex-shrink-0">
|
||||
|
||||
@@ -76,6 +76,31 @@ interface OpenDialogOptions {
|
||||
* On desktop, this option is ignored.
|
||||
*/
|
||||
pickerMode?: PickerMode
|
||||
/**
|
||||
* The file access mode of the dialog.
|
||||
* If not provided, `copy` is used, which matches the behavior of the {@linkcode open} method before the introduction of this option.
|
||||
*
|
||||
* **Usage**
|
||||
* If a file is opened with {@linkcode fileAccessMode: 'copy'}, it will be copied to the app's sandbox.
|
||||
* This means the file can be read, edited, deleted, copied, or any other operation without any issues, since the file
|
||||
* now belongs to the app.
|
||||
* This also means that the caller has responsibility of deleting the file if this file is not meant to be retained
|
||||
* in the app sandbox.
|
||||
*
|
||||
* If a file is opened with {@linkcode fileAccessMode: 'scoped'}, the file will remain in its original location
|
||||
* and security-scoped access will be automatically managed by the system.
|
||||
*
|
||||
* **Note**
|
||||
* This is specifically meant for document pickers on iOS or MacOS, in conjunction with [security scoped resources](https://developer.apple.com/documentation/foundation/nsurl/startaccessingsecurityscopedresource()).
|
||||
*
|
||||
* Why only document pickers, and not image or video pickers?
|
||||
* The image and video pickers on iOS behave differently from the document pickers, and return [NSItemProvider](https://developer.apple.com/documentation/foundation/nsitemprovider) objects instead of file URLs.
|
||||
* These are meant to be ephemeral (only available within the callback of the picker), and are not accessible outside of the callback.
|
||||
* So for image and video pickers, the only way to access the file is to copy it to the app's sandbox, and this is the URL that is returned from this API.
|
||||
* This means there is no provision for using `scoped` mode with image or video pickers.
|
||||
* If an image or video picker is used, `copy` is always used.
|
||||
*/
|
||||
fileAccessMode?: FileAccessMode
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -111,6 +136,16 @@ interface SaveDialogOptions {
|
||||
*/
|
||||
export type PickerMode = 'document' | 'media' | 'image' | 'video'
|
||||
|
||||
/**
|
||||
* The file access mode of the dialog.
|
||||
*
|
||||
* - `copy`: copy/move the picked file to the app sandbox; no scoped access required.
|
||||
* - `scoped`: keep file in place; security-scoped access is automatically managed.
|
||||
*
|
||||
* **Note:** This option is only supported on iOS 14 and above. This parameter is ignored on iOS 13 and below.
|
||||
*/
|
||||
export type FileAccessMode = 'copy' | 'scoped'
|
||||
|
||||
/**
|
||||
* Default buttons for a message dialog.
|
||||
*
|
||||
|
||||
@@ -34,6 +34,7 @@ struct FilePickerOptions: Decodable {
|
||||
var filters: [Filter]?
|
||||
var defaultPath: String?
|
||||
var pickerMode: PickerMode?
|
||||
var fileAccessMode: FileAccessMode?
|
||||
}
|
||||
|
||||
struct SaveFileDialogOptions: Decodable {
|
||||
@@ -41,6 +42,11 @@ struct SaveFileDialogOptions: Decodable {
|
||||
var defaultPath: String?
|
||||
}
|
||||
|
||||
enum FileAccessMode: String, Decodable {
|
||||
case copy
|
||||
case scoped
|
||||
}
|
||||
|
||||
enum PickerMode: String, Decodable {
|
||||
case document
|
||||
case media
|
||||
@@ -56,6 +62,7 @@ class DialogPlugin: Plugin {
|
||||
override init() {
|
||||
super.init()
|
||||
filePickerController = FilePickerController(self)
|
||||
|
||||
}
|
||||
|
||||
@objc public func showFilePicker(_ invoke: Invoke) throws {
|
||||
@@ -70,12 +77,13 @@ class DialogPlugin: Plugin {
|
||||
case .error(let error):
|
||||
invoke.reject(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if #available(iOS 14, *) {
|
||||
let parsedTypes = parseFiltersOption(args.filters ?? [])
|
||||
|
||||
let mimeKinds = Set(parsedTypes.compactMap { $0.preferredMIMEType?.components(separatedBy: "/")[0] })
|
||||
let mimeKinds = Set(
|
||||
parsedTypes.compactMap { $0.preferredMIMEType?.components(separatedBy: "/")[0] })
|
||||
let filtersIncludeImage = mimeKinds.contains("image")
|
||||
let filtersIncludeVideo = mimeKinds.contains("video")
|
||||
let filtersIncludeNonMedia = mimeKinds.contains(where: { $0 != "image" && $0 != "video" })
|
||||
@@ -85,7 +93,8 @@ class DialogPlugin: Plugin {
|
||||
if args.pickerMode == .media
|
||||
|| args.pickerMode == .image
|
||||
|| args.pickerMode == .video
|
||||
|| (!filtersIncludeNonMedia && (filtersIncludeImage || filtersIncludeVideo)) {
|
||||
|| (!filtersIncludeNonMedia && (filtersIncludeImage || filtersIncludeVideo))
|
||||
{
|
||||
DispatchQueue.main.async {
|
||||
var configuration = PHPickerConfiguration(photoLibrary: PHPhotoLibrary.shared())
|
||||
configuration.selectionLimit = (args.multiple ?? false) ? 0 : 1
|
||||
@@ -107,8 +116,10 @@ class DialogPlugin: Plugin {
|
||||
DispatchQueue.main.async {
|
||||
// The UTType.item is the catch-all, allowing for any file type to be selected.
|
||||
let contentTypes = parsedTypes.isEmpty ? [UTType.item] : parsedTypes
|
||||
let picker: UIDocumentPickerViewController = UIDocumentPickerViewController(forOpeningContentTypes: contentTypes, asCopy: true)
|
||||
|
||||
let picker: UIDocumentPickerViewController = UIDocumentPickerViewController(
|
||||
forOpeningContentTypes: contentTypes,
|
||||
asCopy: args.fileAccessMode == .scoped ? false : true)
|
||||
|
||||
if let defaultPath = args.defaultPath {
|
||||
picker.directoryURL = URL(string: defaultPath)
|
||||
}
|
||||
@@ -181,7 +192,7 @@ class DialogPlugin: Plugin {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return parsedTypes
|
||||
}
|
||||
|
||||
@@ -203,14 +214,14 @@ class DialogPlugin: Plugin {
|
||||
if !filtersIncludeNonMedia && (filtersIncludeImage || filtersIncludeVideo) {
|
||||
DispatchQueue.main.async {
|
||||
let picker = UIImagePickerController()
|
||||
picker.delegate = self.filePickerController
|
||||
picker.delegate = self.filePickerController
|
||||
|
||||
if filtersIncludeImage && !filtersIncludeVideo {
|
||||
picker.sourceType = .photoLibrary
|
||||
}
|
||||
if filtersIncludeImage && !filtersIncludeVideo {
|
||||
picker.sourceType = .photoLibrary
|
||||
}
|
||||
|
||||
picker.modalPresentationStyle = .fullScreen
|
||||
self.presentViewController(picker)
|
||||
picker.modalPresentationStyle = .fullScreen
|
||||
self.presentViewController(picker)
|
||||
}
|
||||
} else {
|
||||
let documentTypes = parsedTypes.isEmpty ? ["public.data"] : parsedTypes
|
||||
@@ -234,7 +245,8 @@ class DialogPlugin: Plugin {
|
||||
for filter in filters {
|
||||
for ext in filter.extensions ?? [] {
|
||||
guard
|
||||
let utType: String = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, ext as CFString, nil)?.takeRetainedValue() as String?
|
||||
let utType: String = UTTypeCreatePreferredIdentifierForTag(
|
||||
kUTTagClassMIMEType, ext as CFString, nil)?.takeRetainedValue() as String?
|
||||
else {
|
||||
continue
|
||||
}
|
||||
@@ -292,6 +304,7 @@ class DialogPlugin: Plugin {
|
||||
manager.viewController?.present(alert, animated: true, completion: nil)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@_cdecl("init_plugin_dialog")
|
||||
|
||||
@@ -95,16 +95,33 @@ public class FilePickerController: NSObject {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// ## In which cases do we need to save a copy of a file selected by a user to the app sandbox?
|
||||
/// In short, only when the file is **not** selected using UIDocumentPickerDelegate.
|
||||
/// For the rest of the cases, we need to write a copy of the file to the app sandbox.
|
||||
///
|
||||
/// For PHPicker (used for photos and videos), `NSItemProvider.loadFileRepresentation` returns a temporary file URL that is deleted after the completion handler.
|
||||
/// The recommendation is to [Persist](https://developer.apple.com/documentation/foundation/nsitemprovider/2888338-loadfilerepresentation) the file by moving/copying
|
||||
/// it to your app’s directory within the completion handler.
|
||||
///
|
||||
/// If available, `loadInPlaceFileRepresentation` can open a file in place; Photos assets typically do not support true in-place access,
|
||||
/// so fall back to persisting a local file.
|
||||
/// Ref: https://developer.apple.com/documentation/foundation/nsitemprovider/2888335-loadinplacefilerepresentation
|
||||
///
|
||||
/// For UIDocumentPicker, prefer "open in place" and avoid copying when possible.
|
||||
/// Ref: https://developer.apple.com/documentation/uikit/uidocumentpickerviewcontroller
|
||||
private func saveTemporaryFile(_ sourceUrl: URL) throws -> URL {
|
||||
|
||||
var directory = URL(fileURLWithPath: NSTemporaryDirectory())
|
||||
if let cachesDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first {
|
||||
directory = cachesDirectory
|
||||
}
|
||||
|
||||
let targetUrl = directory.appendingPathComponent(sourceUrl.lastPathComponent)
|
||||
do {
|
||||
try deleteFile(targetUrl)
|
||||
}
|
||||
|
||||
try FileManager.default.copyItem(at: sourceUrl, to: targetUrl)
|
||||
return targetUrl
|
||||
}
|
||||
@@ -119,8 +136,7 @@ public class FilePickerController: NSObject {
|
||||
extension FilePickerController: UIDocumentPickerDelegate {
|
||||
public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
|
||||
do {
|
||||
let temporaryUrls = try urls.map { try saveTemporaryFile($0) }
|
||||
self.plugin.onFilePickerEvent(.selected(temporaryUrls))
|
||||
self.plugin.onFilePickerEvent(.selected(urls))
|
||||
} catch {
|
||||
self.plugin.onFilePickerEvent(.error("Failed to create a temporary copy of the file"))
|
||||
}
|
||||
@@ -191,6 +207,8 @@ extension FilePickerController: PHPickerViewControllerDelegate {
|
||||
return
|
||||
}
|
||||
do {
|
||||
// We have to make a copy of the file to the app sandbox here, as PHPicker returns an NSItemProvider with either an ephemeral file URL or content that is deleted after the completion handler.
|
||||
// This is a different behavior from UIDocumentPicker, where the file can either be copied to the app sandbox or opened in place, and then accessed with `startAccessingSecurityScopedResource`.
|
||||
let temporaryUrl = try self.saveTemporaryFile(url)
|
||||
temporaryUrls.append(temporaryUrl)
|
||||
} catch {
|
||||
@@ -212,6 +230,8 @@ extension FilePickerController: PHPickerViewControllerDelegate {
|
||||
return
|
||||
}
|
||||
do {
|
||||
// We have to make a copy of the file to the app sandbox here, as PHPicker returns an NSItemProvider with either an ephemeral file URL or content that is deleted after the completion handler.
|
||||
// This is a different behavior from UIDocumentPicker, where the file can either be copied to the app sandbox or opened in place, and then accessed with `startAccessingSecurityScopedResource`.
|
||||
let temporaryUrl = try self.saveTemporaryFile(url)
|
||||
temporaryUrls.append(temporaryUrl)
|
||||
} catch {
|
||||
|
||||
@@ -9,8 +9,9 @@ use tauri::{command, Manager, Runtime, State, Window};
|
||||
use tauri_plugin_fs::FsExt;
|
||||
|
||||
use crate::{
|
||||
Dialog, FileDialogBuilder, FilePath, MessageDialogBuilder, MessageDialogButtons,
|
||||
MessageDialogKind, MessageDialogResult, PickerMode, Result, CANCEL, NO, OK, YES,
|
||||
Dialog, FileAccessMode, FileDialogBuilder, FilePath, MessageDialogBuilder,
|
||||
MessageDialogButtons, MessageDialogKind, MessageDialogResult, PickerMode, Result, CANCEL, NO,
|
||||
OK, YES,
|
||||
};
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -63,6 +64,10 @@ pub struct OpenDialogOptions {
|
||||
#[serde(default)]
|
||||
#[cfg_attr(mobile, allow(dead_code))]
|
||||
picker_mode: Option<PickerMode>,
|
||||
/// The file access mode of the dialog.
|
||||
#[serde(default)]
|
||||
#[cfg_attr(mobile, allow(dead_code))]
|
||||
file_access_mode: Option<FileAccessMode>,
|
||||
}
|
||||
|
||||
/// The options for the save dialog API.
|
||||
@@ -141,6 +146,9 @@ pub(crate) async fn open<R: Runtime>(
|
||||
let extensions: Vec<&str> = filter.extensions.iter().map(|s| &**s).collect();
|
||||
dialog_builder = dialog_builder.add_filter(filter.name, &extensions);
|
||||
}
|
||||
if let Some(file_access_mode) = options.file_access_mode {
|
||||
dialog_builder = dialog_builder.set_file_access_mode(file_access_mode);
|
||||
}
|
||||
|
||||
let res = if options.directory {
|
||||
#[cfg(desktop)]
|
||||
|
||||
@@ -53,6 +53,13 @@ pub enum PickerMode {
|
||||
Video,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum FileAccessMode {
|
||||
Copy,
|
||||
Scoped,
|
||||
}
|
||||
|
||||
pub(crate) const OK: &str = "Ok";
|
||||
pub(crate) const CANCEL: &str = "Cancel";
|
||||
pub(crate) const YES: &str = "Yes";
|
||||
@@ -191,7 +198,7 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
|
||||
commands::save,
|
||||
commands::message,
|
||||
commands::ask,
|
||||
commands::confirm
|
||||
commands::confirm,
|
||||
])
|
||||
.setup(|app, api| {
|
||||
#[cfg(mobile)]
|
||||
@@ -379,6 +386,7 @@ pub struct FileDialogBuilder<R: Runtime> {
|
||||
pub(crate) title: Option<String>,
|
||||
pub(crate) can_create_directories: Option<bool>,
|
||||
pub(crate) picker_mode: Option<PickerMode>,
|
||||
pub(crate) file_access_mode: Option<FileAccessMode>,
|
||||
#[cfg(desktop)]
|
||||
pub(crate) parent: Option<crate::desktop::WindowHandle>,
|
||||
}
|
||||
@@ -391,6 +399,7 @@ pub(crate) struct FileDialogPayload<'a> {
|
||||
filters: &'a Vec<Filter>,
|
||||
multiple: bool,
|
||||
picker_mode: &'a Option<PickerMode>,
|
||||
file_access_mode: &'a Option<FileAccessMode>,
|
||||
}
|
||||
|
||||
// raw window handle :(
|
||||
@@ -407,6 +416,7 @@ impl<R: Runtime> FileDialogBuilder<R> {
|
||||
title: None,
|
||||
can_create_directories: None,
|
||||
picker_mode: None,
|
||||
file_access_mode: None,
|
||||
#[cfg(desktop)]
|
||||
parent: None,
|
||||
}
|
||||
@@ -419,6 +429,7 @@ impl<R: Runtime> FileDialogBuilder<R> {
|
||||
filters: &self.filters,
|
||||
multiple,
|
||||
picker_mode: &self.picker_mode,
|
||||
file_access_mode: &self.file_access_mode,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -488,6 +499,14 @@ impl<R: Runtime> FileDialogBuilder<R> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the file access mode of the dialog.
|
||||
/// This is only used on iOS.
|
||||
/// On desktop and Android, this option is ignored.
|
||||
pub fn set_file_access_mode(mut self, mode: FileAccessMode) -> Self {
|
||||
self.file_access_mode.replace(mode);
|
||||
self
|
||||
}
|
||||
|
||||
/// Shows the dialog to select a single file.
|
||||
///
|
||||
/// This is not a blocking operation,
|
||||
|
||||
@@ -1 +1 @@
|
||||
if("__TAURI__"in window){var __TAURI_PLUGIN_NOTIFICATION__=function(i){"use strict";function t(i,t,n,e){if("function"==typeof t?i!==t||!e:!t.has(i))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?e:"a"===n?e.call(i):e?e.value:t.get(i)}function n(i,t,n,e,a){if("function"==typeof t||!t.has(i))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(i,n),n}var e,a,o,r;"function"==typeof SuppressedError&&SuppressedError;const s="__TAURI_TO_IPC_KEY__";class c{constructor(i){e.set(this,void 0),a.set(this,0),o.set(this,[]),r.set(this,void 0),n(this,e,i||(()=>{})),this.id=function(i,t=!1){return window.__TAURI_INTERNALS__.transformCallback(i,t)}((i=>{const s=i.index;if("end"in i)return void(s==t(this,a,"f")?this.cleanupCallback():n(this,r,s));const c=i.message;if(s==t(this,a,"f")){for(t(this,e,"f").call(this,c),n(this,a,t(this,a,"f")+1);t(this,a,"f")in t(this,o,"f");){const i=t(this,o,"f")[t(this,a,"f")];t(this,e,"f").call(this,i),delete t(this,o,"f")[t(this,a,"f")],n(this,a,t(this,a,"f")+1)}t(this,a,"f")===t(this,r,"f")&&this.cleanupCallback()}else t(this,o,"f")[s]=c}))}cleanupCallback(){window.__TAURI_INTERNALS__.unregisterCallback(this.id)}set onmessage(i){n(this,e,i)}get onmessage(){return t(this,e,"f")}[(e=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakMap,s)](){return`__CHANNEL__:${this.id}`}toJSON(){return this[s]()}}class l{constructor(i,t,n){this.plugin=i,this.event=t,this.channelId=n}async unregister(){return f(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}}async function u(i,t,n){const e=new c(n);try{return await f(`plugin:${i}|register_listener`,{event:t,handler:e}),new l(i,t,e.id)}catch{return await f(`plugin:${i}|registerListener`,{event:t,handler:e}),new l(i,t,e.id)}}async function f(i,t={},n){return window.__TAURI_INTERNALS__.invoke(i,t,n)}var h,d,w;i.ScheduleEvery=void 0,(h=i.ScheduleEvery||(i.ScheduleEvery={})).Year="year",h.Month="month",h.TwoWeeks="twoWeeks",h.Week="week",h.Day="day",h.Hour="hour",h.Minute="minute",h.Second="second";return i.Importance=void 0,(d=i.Importance||(i.Importance={}))[d.None=0]="None",d[d.Min=1]="Min",d[d.Low=2]="Low",d[d.Default=3]="Default",d[d.High=4]="High",i.Visibility=void 0,(w=i.Visibility||(i.Visibility={}))[w.Secret=-1]="Secret",w[w.Private=0]="Private",w[w.Public=1]="Public",i.Schedule=class{static at(i,t=!1,n=!1){return{at:{date:i,repeating:t,allowWhileIdle:n},interval:void 0,every:void 0}}static interval(i,t=!1){return{at:void 0,interval:{interval:i,allowWhileIdle:t},every:void 0}}static every(i,t,n=!1){return{at:void 0,interval:void 0,every:{interval:i,count:t,allowWhileIdle:n}}}},i.active=async function(){return await f("plugin:notification|get_active")},i.cancel=async function(i){await f("plugin:notification|cancel",{notifications:i})},i.cancelAll=async function(){await f("plugin:notification|cancel")},i.channels=async function(){return await f("plugin:notification|listChannels")},i.createChannel=async function(i){await f("plugin:notification|create_channel",{...i})},i.isPermissionGranted=async function(){return"default"!==window.Notification.permission?await Promise.resolve("granted"===window.Notification.permission):await f("plugin:notification|is_permission_granted")},i.onAction=async function(i){return await u("notification","actionPerformed",i)},i.onNotificationReceived=async function(i){return await u("notification","notification",i)},i.pending=async function(){return await f("plugin:notification|get_pending")},i.registerActionTypes=async function(i){await f("plugin:notification|register_action_types",{types:i})},i.removeActive=async function(i){await f("plugin:notification|remove_active",{notifications:i})},i.removeAllActive=async function(){await f("plugin:notification|remove_active")},i.removeChannel=async function(i){await f("plugin:notification|delete_channel",{id:i})},i.requestPermission=async function(){return await window.Notification.requestPermission()},i.sendNotification=function(i){"string"==typeof i?new window.Notification(i):new window.Notification(i.title,i)},i}({});Object.defineProperty(window.__TAURI__,"notification",{value:__TAURI_PLUGIN_NOTIFICATION__})}
|
||||
if("__TAURI__"in window){var __TAURI_PLUGIN_NOTIFICATION__=function(i){"use strict";function n(i,n,t,e){if("function"==typeof n?i!==n||!e:!n.has(i))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===t?e:"a"===t?e.call(i):e?e.value:n.get(i)}function t(i,n,t,e,a){if("function"==typeof n||!n.has(i))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n.set(i,t),t}var e,a,o,r;"function"==typeof SuppressedError&&SuppressedError;const s="__TAURI_TO_IPC_KEY__";class c{constructor(i){e.set(this,void 0),a.set(this,0),o.set(this,[]),r.set(this,void 0),t(this,e,i||(()=>{})),this.id=function(i,n=!1){return window.__TAURI_INTERNALS__.transformCallback(i,n)}((i=>{const s=i.index;if("end"in i)return void(s==n(this,a,"f")?this.cleanupCallback():t(this,r,s));const c=i.message;if(s==n(this,a,"f")){for(n(this,e,"f").call(this,c),t(this,a,n(this,a,"f")+1);n(this,a,"f")in n(this,o,"f");){const i=n(this,o,"f")[n(this,a,"f")];n(this,e,"f").call(this,i),delete n(this,o,"f")[n(this,a,"f")],t(this,a,n(this,a,"f")+1)}n(this,a,"f")===n(this,r,"f")&&this.cleanupCallback()}else n(this,o,"f")[s]=c}))}cleanupCallback(){window.__TAURI_INTERNALS__.unregisterCallback(this.id)}set onmessage(i){t(this,e,i)}get onmessage(){return n(this,e,"f")}[(e=new WeakMap,a=new WeakMap,o=new WeakMap,r=new WeakMap,s)](){return`__CHANNEL__:${this.id}`}toJSON(){return this[s]()}}class l{constructor(i,n,t){this.plugin=i,this.event=n,this.channelId=t}async unregister(){return f(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}}async function u(i,n,t){const e=new c(t);try{return f(`plugin:${i}|register_listener`,{event:n,handler:e}).then((()=>new l(i,n,e.id)))}catch{return f(`plugin:${i}|registerListener`,{event:n,handler:e}).then((()=>new l(i,n,e.id)))}}async function f(i,n={},t){return window.__TAURI_INTERNALS__.invoke(i,n,t)}var h,d,w;i.ScheduleEvery=void 0,(h=i.ScheduleEvery||(i.ScheduleEvery={})).Year="year",h.Month="month",h.TwoWeeks="twoWeeks",h.Week="week",h.Day="day",h.Hour="hour",h.Minute="minute",h.Second="second";return i.Importance=void 0,(d=i.Importance||(i.Importance={}))[d.None=0]="None",d[d.Min=1]="Min",d[d.Low=2]="Low",d[d.Default=3]="Default",d[d.High=4]="High",i.Visibility=void 0,(w=i.Visibility||(i.Visibility={}))[w.Secret=-1]="Secret",w[w.Private=0]="Private",w[w.Public=1]="Public",i.Schedule=class{static at(i,n=!1,t=!1){return{at:{date:i,repeating:n,allowWhileIdle:t},interval:void 0,every:void 0}}static interval(i,n=!1){return{at:void 0,interval:{interval:i,allowWhileIdle:n},every:void 0}}static every(i,n,t=!1){return{at:void 0,interval:void 0,every:{interval:i,count:n,allowWhileIdle:t}}}},i.active=async function(){return await f("plugin:notification|get_active")},i.cancel=async function(i){await f("plugin:notification|cancel",{notifications:i})},i.cancelAll=async function(){await f("plugin:notification|cancel")},i.channels=async function(){return await f("plugin:notification|listChannels")},i.createChannel=async function(i){await f("plugin:notification|create_channel",{...i})},i.isPermissionGranted=async function(){return"default"!==window.Notification.permission?await Promise.resolve("granted"===window.Notification.permission):await f("plugin:notification|is_permission_granted")},i.onAction=async function(i){return await u("notification","actionPerformed",i)},i.onNotificationReceived=async function(i){return await u("notification","notification",i)},i.pending=async function(){return await f("plugin:notification|get_pending")},i.registerActionTypes=async function(i){await f("plugin:notification|register_action_types",{types:i})},i.removeActive=async function(i){await f("plugin:notification|remove_active",{notifications:i})},i.removeAllActive=async function(){await f("plugin:notification|remove_active")},i.removeChannel=async function(i){await f("plugin:notification|delete_channel",{id:i})},i.requestPermission=async function(){return await window.Notification.requestPermission()},i.sendNotification=function(i){"string"==typeof i?new window.Notification(i):new window.Notification(i.title,i)},i}({});Object.defineProperty(window.__TAURI__,"notification",{value:__TAURI_PLUGIN_NOTIFICATION__})}
|
||||
|
||||
Reference in New Issue
Block a user