Просмотр исходного кода

feat(core): update swift-rs (#6355)

* feat(core): update swift-rs

* update tauri-plugin-log

* use env var for min iOS version

* test x86_64-apple-ios

* Revert "test x86_64-apple-ios"

This reverts commit 3ae6b79e5fed9197d1a0a586e23236fe8d8acf00.

* chore: swift min version 5.3 [skip ci]

* fix build [skip ci]

* fix cgrect usage

* test CI

* Revert "test CI"

This reverts commit 76ce0c59928f6cda3fe00b07013e65dd6a7c5fad.

* update swift-rs to 1.0.1

* lint

* lint [skip ci]
Lucas Fernandes Nogueira 2 лет назад
Родитель
Сommit
5d94eaa3bc

+ 1 - 0
.github/workflows/test-core.yml

@@ -18,6 +18,7 @@ on:
 env:
   RUST_BACKTRACE: 1
   CARGO_PROFILE_DEV_DEBUG: 0 # This would add unnecessary bloat to the target folder, decreasing cache efficiency.
+  IOS_DEPLOYMENT_TARGET: '16.0'
 
 concurrency:
   group: ${{ github.workflow }}-${{ github.ref }}

+ 1 - 1
core/tauri-build/Cargo.toml

@@ -33,7 +33,7 @@ filetime = "0.2"
 tauri-winres = "0.1"
 semver = "1"
 [target."cfg(target_os = \"macos\")".dependencies]
-swift-rs = { git = "https://github.com/Brendonovich/swift-rs", rev = "eb6de914ad57501da5019154d476d45660559999", features = ["build"] }
+swift-rs = { version = "1.0.1", features = ["build"] }
 
 [features]
 codegen = [ "tauri-codegen", "quote" ]

+ 9 - 7
core/tauri-build/src/mobile.rs

@@ -78,7 +78,7 @@ impl PluginBuilder {
             .expect("missing `DEP_TAURI_IOS_LIBRARY_PATH` environment variable. Make sure `tauri` is a dependency of the plugin.");
 
           copy_folder(
-            &Path::new(&tauri_library_path),
+            Path::new(&tauri_library_path),
             &path.join("tauri-api"),
             &[".build", "Package.resolved", "Tests"],
           )
@@ -99,12 +99,14 @@ pub fn link_swift_library(name: &str, source: impl AsRef<Path>) {
   let source = source.as_ref();
   println!("cargo:rerun-if-changed={}", source.display());
   let curr_dir = std::env::current_dir().unwrap();
-  std::env::set_current_dir(&source).unwrap();
-  swift_rs::build::SwiftLinker::new("10.13")
-    .with_ios("13.0")
-    .with_package(name, source)
-    .link();
-  std::env::set_current_dir(&curr_dir).unwrap();
+  std::env::set_current_dir(source).unwrap();
+  swift_rs::SwiftLinker::new(
+    &std::env::var("MACOSX_DEPLOYMENT_TARGET").unwrap_or_else(|_| "10.13".into()),
+  )
+  .with_ios(&std::env::var("IOS_DEPLOYMENT_TARGET").unwrap_or_else(|_| "13.0".into()))
+  .with_package(name, source)
+  .link();
+  std::env::set_current_dir(curr_dir).unwrap();
 }
 
 #[doc(hidden)]

+ 1 - 2
core/tauri-utils/src/assets.rs

@@ -174,8 +174,7 @@ impl Assets for EmbeddedAssets {
             .get(html_path.as_ref())
             .copied()
             .into_iter()
-            .flatten()
-            .into_iter(),
+            .flatten(),
         )
         .copied(),
     )

+ 1 - 1
core/tauri/Cargo.toml

@@ -120,7 +120,7 @@ jni = "0.20"
 libc = "0.2"
 objc = "0.2"
 cocoa = "0.24"
-swift-rs = { git = "https://github.com/Brendonovich/swift-rs", rev = "eb6de914ad57501da5019154d476d45660559999" }
+swift-rs = "1.0.1"
 
 [build-dependencies]
 heck = "0.4"

+ 7 - 3
core/tauri/mobile/ios-api/Package.swift

@@ -1,4 +1,4 @@
-// swift-tools-version: 5.7
+// swift-tools-version:5.3
 // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
 // SPDX-License-Identifier: Apache-2.0
 // SPDX-License-Identifier: MIT
@@ -7,6 +7,10 @@ import PackageDescription
 
 let package = Package(
 	name: "Tauri",
+	platforms: [
+		.macOS(.v10_13),
+		.iOS(.v11),
+	],
 	products: [
 		// Products define the executables and libraries a package produces, and make them visible to other packages.
 		.library(
@@ -16,7 +20,7 @@ let package = Package(
 	],
 	dependencies: [
 		// Dependencies declare other packages that this package depends on.
-		.package(url: "https://github.com/Brendonovich/swift-rs", revision: "eb6de914ad57501da5019154d476d45660559999"),
+		.package(name: "SwiftRs", url: "https://github.com/Brendonovich/swift-rs", .revision("cbb9b96b6036108e76879713e910c05bc9e145c7")),
 	],
 	targets: [
 		// Targets are the basic building blocks of a package. A target can define a module or a test suite.
@@ -24,7 +28,7 @@ let package = Package(
 		.target(
 			name: "Tauri",
 			dependencies: [
-					.product(name: "SwiftRs", package: "swift-rs"),
+					.byName(name: "SwiftRs"),
 			],
 			path: "Sources"
 		),

+ 9 - 8
core/tauri/mobile/ios-api/Sources/Tauri/Tauri.swift

@@ -67,7 +67,8 @@ public class PluginManager {
 					}
 					if let error = error {
 						invoke.reject("\(error)")
-						let _ = toRust(error) // TODO app is crashing without this memory leak (when an error is thrown)
+						// TODO: app crashes without this leak
+						let _ = Unmanaged.passRetained(error)
 					}
 				} else {
 					let selector = Selector(("\(invoke.command):"))
@@ -105,8 +106,8 @@ func onWebviewCreated(webview: WKWebView, viewController: UIViewController) {
 }
 
 @_cdecl("post_ipc_message")
-func postIpcMessage(webview: WKWebView, name: UnsafePointer<SRString>, command: UnsafePointer<SRString>, data: NSDictionary, callback: UInt, error: UInt) {
-	let invoke = Invoke(command: command.pointee.to_string(), sendResponse: { (successResult: JsonValue?, errorResult: JsonValue?) -> Void in
+func postIpcMessage(webview: WKWebView, name: SRString, command: SRString, data: NSDictionary, callback: UInt, error: UInt) {
+	let invoke = Invoke(command: command.toString(), sendResponse: { (successResult: JsonValue?, errorResult: JsonValue?) -> Void in
 		let (fn, payload) = errorResult == nil ? (callback, successResult) : (error, errorResult)
 		var payloadJson: String
 		do {
@@ -116,18 +117,18 @@ func postIpcMessage(webview: WKWebView, name: UnsafePointer<SRString>, command:
 		}
 		webview.evaluateJavaScript("window['_\(fn)'](\(payloadJson))")
 	}, data: JSTypes.coerceDictionaryToJSObject(data, formattingDatesAsStrings: true))
-	PluginManager.shared.invoke(name: name.pointee.to_string(), invoke: invoke)
+	PluginManager.shared.invoke(name: name.toString(), invoke: invoke)
 }
 
 @_cdecl("run_plugin_method")
 func runPluginMethod(
 	id: Int,
-	name: UnsafePointer<SRString>,
-	command: UnsafePointer<SRString>,
+	name: SRString,
+	command: SRString,
 	data: NSDictionary,
 	callback: @escaping @convention(c) (Int, Bool, UnsafePointer<CChar>?) -> Void
 ) {
-	let invoke = Invoke(command: command.pointee.to_string(), sendResponse: { (successResult: JsonValue?, errorResult: JsonValue?) -> Void in
+	let invoke = Invoke(command: command.toString(), sendResponse: { (successResult: JsonValue?, errorResult: JsonValue?) -> Void in
 		let (success, payload) = errorResult == nil ? (true, successResult) : (false, errorResult)
 		var payloadJson: String = ""
 		do {
@@ -137,5 +138,5 @@ func runPluginMethod(
 		}
 		callback(id, success, payloadJson.cString(using: String.Encoding.utf8))
 	}, data: JSTypes.coerceDictionaryToJSObject(data, formattingDatesAsStrings: true))
-	PluginManager.shared.invoke(name: name.pointee.to_string(), invoke: invoke)
+	PluginManager.shared.invoke(name: name.toString(), invoke: invoke)
 }

+ 1 - 1
core/tauri/mobile/ios-api/Sources/Tauri/UiUtils.swift

@@ -7,7 +7,7 @@ import UIKit
 public class UIUtils {
     public static func centerPopover(rootViewController: UIViewController?, popoverController: UIViewController) {
         if let viewController = rootViewController {
-            popoverController.popoverPresentationController?.sourceRect = CGRectMake(viewController.view.center.x, viewController.view.center.y, 0, 0)
+            popoverController.popoverPresentationController?.sourceRect = CGRect(x: viewController.view.center.x, y: viewController.view.center.y, width: 0, height: 0)
             popoverController.popoverPresentationController?.sourceView = viewController.view
             popoverController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.up
         }

+ 29 - 21
core/tauri/src/ios.rs

@@ -5,33 +5,41 @@
 use cocoa::base::{id, nil, NO, YES};
 use objc::*;
 use serde_json::Value as JsonValue;
-use swift_rs::SRString;
+use swift_rs::{swift, SRString, SwiftArg};
 
-use std::os::raw::{c_char, c_int};
+use std::{
+  ffi::c_void,
+  os::raw::{c_char, c_int},
+};
 
-type PluginMessageCallback = unsafe extern "C" fn(c_int, c_int, *const c_char);
+type PluginMessageCallbackFn = unsafe extern "C" fn(c_int, c_int, *const c_char);
+pub struct PluginMessageCallback(pub PluginMessageCallbackFn);
 
-extern "C" {
-  pub fn post_ipc_message(
-    webview: id,
-    name: &SRString,
-    method: &SRString,
-    data: id,
-    callback: usize,
-    error: usize,
-  );
+impl<'a> SwiftArg<'a> for PluginMessageCallback {
+  type ArgType = PluginMessageCallbackFn;
 
-  pub fn run_plugin_method(
-    id: i32,
-    name: &SRString,
-    method: &SRString,
-    data: id,
-    callback: PluginMessageCallback,
-  );
-
-  pub fn on_webview_created(webview: id, controller: id);
+  unsafe fn as_arg(&'a self) -> Self::ArgType {
+    self.0
+  }
 }
 
+swift!(pub fn post_ipc_message(
+  webview: *const c_void,
+  name: &SRString,
+  method: &SRString,
+  data: *const c_void,
+  callback: usize,
+  error: usize
+));
+swift!(pub fn run_plugin_method(
+  id: i32,
+  name: &SRString,
+  method: &SRString,
+  data: *const c_void,
+  callback: PluginMessageCallback
+));
+swift!(pub fn on_webview_created(webview: *const c_void, controller: *const c_void));
+
 pub fn json_to_dictionary(json: JsonValue) -> id {
   if let serde_json::Value::Object(map) = json {
     unsafe {

+ 1 - 1
core/tauri/src/lib.rs

@@ -163,7 +163,7 @@
 #![warn(missing_docs, rust_2018_idioms)]
 #![cfg_attr(doc_cfg, feature(doc_cfg))]
 
-#[cfg(any(target_os = "macos", target_os = "ios"))]
+#[cfg(target_os = "ios")]
 #[doc(hidden)]
 pub use cocoa;
 #[cfg(target_os = "macos")]

+ 1 - 1
core/tauri/src/manager.rs

@@ -1408,7 +1408,7 @@ impl<R: Runtime> WindowManager<R> {
     {
       window
         .with_webview(|w| {
-          unsafe { crate::ios::on_webview_created(w.inner(), w.view_controller()) };
+          unsafe { crate::ios::on_webview_created(w.inner() as _, w.view_controller() as _) };
         })
         .expect("failed to run on_webview_created hook");
     }

+ 2 - 2
core/tauri/src/plugin/mobile.rs

@@ -284,8 +284,8 @@ impl<R: Runtime> PluginHandle<R> {
         id,
         &self.name.into(),
         &method.as_ref().into(),
-        crate::ios::json_to_dictionary(serde_json::to_value(payload).unwrap()),
-        plugin_method_response_handler,
+        crate::ios::json_to_dictionary(serde_json::to_value(payload).unwrap()) as _,
+        crate::ios::PluginMessageCallback(plugin_method_response_handler),
       );
     }
     rx.recv()

+ 2 - 2
core/tauri/src/window.rs

@@ -1504,12 +1504,12 @@ impl<R: Runtime> Window<R> {
               self.with_webview(move |webview| {
                 unsafe {
                   crate::ios::post_ipc_message(
-                    webview.inner(),
+                    webview.inner() as _,
                     &plugin.as_str().into(),
                     &heck::ToLowerCamelCase::to_lower_camel_case(message.command.as_str())
                       .as_str()
                       .into(),
-                    crate::ios::json_to_dictionary(message.payload),
+                    crate::ios::json_to_dictionary(message.payload) as _,
                     callback.0,
                     error.0,
                   )

+ 6 - 5
examples/api/src-tauri/Cargo.lock

@@ -2895,10 +2895,11 @@ checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601"
 
 [[package]]
 name = "swift-rs"
-version = "0.3.0"
-source = "git+https://github.com/Brendonovich/swift-rs?rev=eb6de914ad57501da5019154d476d45660559999#eb6de914ad57501da5019154d476d45660559999"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "806ff0904302a8a91644422fcfeee4828c3a9dbcfd1757ba495f1a755c2ac873"
 dependencies = [
- "base64 0.13.1",
+ "base64 0.21.0",
  "serde",
  "serde_json",
 ]
@@ -3125,7 +3126,7 @@ dependencies = [
 [[package]]
 name = "tauri-plugin-log"
 version = "0.1.0"
-source = "git+https://github.com/tauri-apps/plugins-workspace?branch=next#961602bd1b15e9c0d83d4c32c221a075fbabd83b"
+source = "git+https://github.com/tauri-apps/plugins-workspace?branch=feat/update-swift#409ec4074f39749e2da25f3de2ca2599719e619a"
 dependencies = [
  "android_logger",
  "byte-unit",
@@ -4111,7 +4112,7 @@ dependencies = [
 [[package]]
 name = "wry"
 version = "0.27.0"
-source = "git+https://github.com/tauri-apps/wry?branch=dev#7795356a45b1bd015fad0e9973fc5af58c8c339b"
+source = "git+https://github.com/tauri-apps/wry?branch=dev#db6618b560b9fbaed7e333bb6bb2463f5196ca17"
 dependencies = [
  "base64 0.13.1",
  "block",

+ 1 - 1
examples/api/src-tauri/Cargo.toml

@@ -17,7 +17,7 @@ serde_json = "1.0"
 serde = { version = "1.0", features = [ "derive" ] }
 tiny_http = "0.11"
 log = "0.4"
-tauri-plugin-log = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "next" }
+tauri-plugin-log = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "feat/update-swift" }
 tauri-plugin-sample = { path = "./tauri-plugin-sample/" }
 
 [patch.'https://github.com/tauri-apps/tauri']

+ 1 - 1
examples/api/src-tauri/src/lib.rs

@@ -65,7 +65,7 @@ pub fn run() {
       let response = app.sample().ping(PingRequest {
         value: value.clone(),
       });
-      println!("got response: {:?}", response);
+      log::info!("got response: {:?}", response);
       if let Ok(res) = response {
         assert_eq!(res.value, value);
       }

+ 1 - 1
examples/api/src-tauri/tauri-plugin-sample/ios/Package.swift

@@ -1,4 +1,4 @@
-// swift-tools-version: 5.7
+// swift-tools-version:5.3
 // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
 // SPDX-License-Identifier: Apache-2.0
 // SPDX-License-Identifier: MIT

+ 1 - 1
tooling/cli/src/mobile/ios/build.rs

@@ -120,7 +120,7 @@ fn run_build(
     ..Default::default()
   })?;
   let out_dir = bin_path.parent().unwrap();
-  let _lock = flock::open_rw(&out_dir.join("lock").with_extension("ios"), "iOS")?;
+  let _lock = flock::open_rw(out_dir.join("lock").with_extension("ios"), "iOS")?;
 
   let cli_options = CliOptions {
     features: build_options.features.clone(),

+ 1 - 1
tooling/cli/src/mobile/ios/dev.rs

@@ -149,7 +149,7 @@ fn run_dev(
     ..Default::default()
   })?;
   let out_dir = bin_path.parent().unwrap();
-  let _lock = flock::open_rw(&out_dir.join("lock").with_extension("ios"), "iOS")?;
+  let _lock = flock::open_rw(out_dir.join("lock").with_extension("ios"), "iOS")?;
 
   configure_cargo(app, None)?;
 

+ 1 - 4
tooling/cli/src/mobile/mod.rs

@@ -278,10 +278,7 @@ fn get_app(config: &TauriConfig) -> App {
   )
   .expect("failed to load interface");
 
-  let app_name = interface
-    .app_settings()
-    .app_name()
-    .unwrap_or(app_name.clone());
+  let app_name = interface.app_settings().app_name().unwrap_or(app_name);
   let lib_name = interface
     .app_settings()
     .lib_name()

+ 1 - 1
tooling/cli/templates/plugin/ios/Package.swift

@@ -1,4 +1,4 @@
-// swift-tools-version:5.7
+// swift-tools-version:5.3
 // The swift-tools-version declares the minimum version of Swift required to build this package.
 
 import PackageDescription