Skip to content

Commit 3709986

Browse files
committed
use std tauri init and prefer error logs over crashes
1 parent c5b8536 commit 3709986

8 files changed

Lines changed: 52 additions & 38 deletions

File tree

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ These steps assume that you already have a basic tauri application available. Al
4848

4949
- run `npm run tauri add python`
5050
- add `src-tauri/src-python/main.py` and modify it acording to your needs, for example add `def greet_python(intput): return str(input) + " from python"`
51-
- modify `src-tauri/src/lib.rs` and change `.plugin(tauri_plugin_python::init())` to `.plugin(tauri_plugin_python::init(["greet_python"]))`; make sure you list all python functions you
51+
- modify `src-tauri/src/lib.rs` and change `.plugin(tauri_plugin_python::init())` to `.plugin(tauri_plugin_python::init_and_register(["greet_python"]))`; make sure you list all python functions you
5252
want to call
5353
- add `"bundle": {"resources": [ "src-python/**/*"],` to `tauri.conf.json` so that python files are bundled with your application
5454
- add the plugin in your js, so
@@ -71,7 +71,7 @@ def greet_python(rust_var)
7171
print(rust_var)
7272
return str(rust_var) + " from python"
7373
```
74-
- add `.plugin(tauri_plugin_python::init(vec!["greet_python"))` to `tauri::Builder::default()`, usually in `src-tauri/src/lib.rs`. This will initialize the plugin and make the python function "greet_python" available from javascript.
74+
- add `.plugin(tauri_plugin_python::init_and_register(vec!["greet_python"))` to `tauri::Builder::default()`, usually in `src-tauri/src/lib.rs`. This will initialize the plugin and make the python function "greet_python" available from javascript.
7575
- add javascript for python plugin in the index.html file directly or in your somewhere in your javascript application. For vanilla javascript / iife, the modules can be found in `window.__TAURI__.python`. For modern javascript:
7676
```javascript
7777
import { callFunction } from 'tauri-plugin-python-api'

examples/plain-javascript/src-tauri/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ fn greet_rust(name: &str) -> String {
88
pub fn run() {
99
tauri::Builder::default()
1010
.invoke_handler(tauri::generate_handler![greet_rust])
11-
.plugin(tauri_plugin_python::init(vec!["greet_python"]))
11+
.plugin(tauri_plugin_python::init_and_register(vec!["greet_python"]))
1212
.run(tauri::generate_context!())
1313
.expect("error while running tauri application");
1414
}

permissions/default.toml

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
[default]
22
description = "Default permissions for the plugin"
3-
permissions = ["allow-call-function", "allow-read-variable"]
3+
permissions = [
4+
"allow-call-function",
5+
"allow-read-variable"
6+
]
47
# "allow-register-function" is disabled due to the "secure by default" concept. It can be enabled if the UI isn't exposed via network and secured against XSS sufficiently.
58
# "allow-run-python" is also disabled as it allows to run random python code. It must not be enabled if the UI is exposed via network.

src/desktop.rs

Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,27 +6,12 @@
66
use serde::de::DeserializeOwned;
77
use tauri::{plugin::PluginApi, AppHandle, Runtime};
88

9-
#[cfg(feature = "pyo3")]
10-
use crate::py_lib_pyo3 as py_lib;
11-
#[cfg(not(feature = "pyo3"))]
12-
use crate::py_lib;
13-
149
/// Access to the python plugin APIs.
1510
pub struct Python<R: Runtime>(AppHandle<R>);
1611

17-
fn read_main_py<'a>() -> String {
18-
let py_file_path = std::env::current_dir()
19-
.unwrap()
20-
.join("src-python")
21-
.join("main.py");
22-
std::fs::read_to_string(py_file_path).unwrap_or_default()
23-
// include_str!(concat!(env!("PWD"), "/src-tauri/src-python/main.py"))
24-
}
25-
2612
pub fn init<R: Runtime, C: DeserializeOwned>(
2713
app: &AppHandle<R>,
2814
_api: PluginApi<R, C>,
2915
) -> crate::Result<Python<R>> {
30-
py_lib::init_python(read_main_py()).unwrap();
3116
Ok(Python(app.clone()))
3217
}

src/lib.rs

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@
44
// git clone https://github.com/marcomq/tauri-plugin-python
55

66
use tauri::{
7+
path::BaseDirectory,
78
plugin::{Builder, TauriPlugin},
8-
Manager, Runtime,
9+
AppHandle, Manager, Runtime,
910
};
1011

1112
#[cfg(desktop)]
@@ -23,7 +24,6 @@ mod py_lib_pyo3;
2324
#[cfg(feature = "pyo3")]
2425
use py_lib_pyo3 as py_lib;
2526

26-
2727
pub use error::{Error, Result};
2828
use models::*;
2929

@@ -63,8 +63,30 @@ impl<R: Runtime, T: Manager<R>> crate::PythonExt<R> for T {
6363
}
6464
}
6565

66+
fn read_main_py_from_resources<R: Runtime>(app: &AppHandle<R>) -> String {
67+
let py_file_path = app
68+
.path()
69+
.resolve("src-python/main.py", BaseDirectory::Resource)
70+
.unwrap_or_default();
71+
std::fs::read_to_string(&py_file_path).unwrap_or_default()
72+
}
73+
74+
fn read_main_py_from_current_dir() -> String {
75+
let py_file_path = std::env::current_dir()
76+
.unwrap()
77+
.join("src-python")
78+
.join("main.py");
79+
std::fs::read_to_string(py_file_path).unwrap_or_default()
80+
// include_str!(concat!(env!("PWD"), "/src-tauri/src-python/main.py"))
81+
}
82+
83+
/// Initializes the plugin with functions
84+
pub fn init<R: Runtime>() -> TauriPlugin<R> {
85+
init_and_register(vec![])
86+
}
87+
6688
/// Initializes the plugin.
67-
pub fn init<R: Runtime>(python_functions: Vec<&'static str>) -> TauriPlugin<R> {
89+
pub fn init_and_register<R: Runtime>(python_functions: Vec<&'static str>) -> TauriPlugin<R> {
6890
Builder::new("python")
6991
.invoke_handler(tauri::generate_handler![
7092
commands::run_python,
@@ -78,6 +100,18 @@ pub fn init<R: Runtime>(python_functions: Vec<&'static str>) -> TauriPlugin<R> {
78100
#[cfg(desktop)]
79101
let python = desktop::init(app, api)?;
80102
app.manage(python);
103+
104+
let mut code = read_main_py_from_resources(app);
105+
if code.is_empty() {
106+
println!(
107+
"Warning: 'src-tauri/main.py' seems not to be registered in 'tauri.conf.json'"
108+
);
109+
code = read_main_py_from_current_dir();
110+
}
111+
if code.is_empty() {
112+
println!("ERROR: Error reading 'src-tauri/main.py'");
113+
}
114+
py_lib::init_python(code).unwrap();
81115
for function_name in python_functions {
82116
py_lib::register_function_str(function_name.into(), None).unwrap();
83117
}

src/mobile.rs

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,31 +5,22 @@
55

66
use serde::de::DeserializeOwned;
77
use tauri::{
8-
path::BaseDirectory,
98
plugin::{PluginApi, PluginHandle},
10-
AppHandle, Manager, Runtime,
9+
AppHandle, Runtime,
1110
};
1211

13-
use crate::models::*;
14-
use crate::py_lib;
15-
1612
#[cfg(target_os = "ios")]
1713
tauri::ios_plugin_binding!(init_plugin_python);
1814

1915
// initializes the Kotlin or Swift plugin classes
2016
pub fn init<R: Runtime, C: DeserializeOwned>(
21-
app: &AppHandle<R>,
17+
_app: &AppHandle<R>,
2218
api: PluginApi<R, C>,
2319
) -> crate::Result<Python<R>> {
2420
#[cfg(target_os = "android")]
25-
let handle = api.register_android_plugin("com.plugin.python.application", "ExamplePlugin")?;
21+
let handle = api.register_android_plugin("com.plugin.python", "ExamplePlugin")?;
2622
#[cfg(target_os = "ios")]
2723
let handle = api.register_ios_plugin(init_plugin_python)?;
28-
let py_file_path = app
29-
.path()
30-
.resolve("src-python/main.py", BaseDirectory::Resource)?;
31-
let code = std::fs::read_to_string(py_file_path).expect("Error reading main.py");
32-
py_lib::init_python(code)?;
3324
Ok(Python(handle))
3425
}
3526

src/py_lib.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,10 @@ pub fn register_function_str(fn_name: String, number_of_args: Option<u8>) -> cra
5959
return Err("Cannot register after function called".into());
6060
}
6161
rustpython_vm::Interpreter::without_stdlib(Default::default()).enter(|vm| {
62-
GLOBALS.globals.get_item(&fn_name, vm).unwrap();
62+
GLOBALS
63+
.globals
64+
.get_item(&fn_name, vm)
65+
.expect(&format!("Function {fn_name} not found"));
6366
FUNCTION_MAP.lock().unwrap().insert(fn_name);
6467
Ok(())
6568
})

src/py_lib_pyo3.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,7 @@ lazy_static! {
2222
}
2323

2424
fn get_py_path() -> std::path::PathBuf {
25-
std::env::current_dir()
26-
.unwrap()
27-
.join("src-python")
25+
std::env::current_dir().unwrap().join("src-python")
2826
}
2927

3028
pub fn init_python(code: String) -> crate::Result<()> {

0 commit comments

Comments
 (0)