Skip to content

Commit

Permalink
refactor(core): remove Params and replace with strings (#2191)
Browse files Browse the repository at this point in the history
* refactor(core): remove `Params` and replace with strings

* add tauri-utils to changelog

* update default runtime macro to accept type and feature

* remove accidental default feature addition

* remove changefile todo items that have no futher action

* fix clippy warning

* update changefile

* finish change file

* fix splashscreen example

* fix markdown typo [skip ci]

* remove final uses of `Params`

* add license header to new runtime module in tauri-macros

* update plugin guide to use runtime instead of params
  • Loading branch information
chippers committed Jul 15, 2021
1 parent 074caa3 commit fd8fab5
Show file tree
Hide file tree
Showing 46 changed files with 855 additions and 1,409 deletions.
50 changes: 50 additions & 0 deletions .changes/weak-typing.md
@@ -0,0 +1,50 @@
---
"tauri": patch
"tauri-runtime": patch
"tauri-runtime-wry": patch
"tauri-macros": patch
"tauri-utils": patch
---

`Params` has been removed, along with all the associated types on it. Functions that previously accepted those
associated types now accept strings instead. Type that used a generic parameter `Params` now use `Runtime` instead. If
you use the `wry` feature, then types with a `Runtime` generic parameter should default to `Wry`, letting you omit the
explicit type and let the compiler infer it instead.

`tauri`:

* See `Params` note
* If you were using `Params` inside a function parameter or definition, all references to it have been replaced with a
simple runtime that defaults to `Wry`. If you are not using a custom runtime, just remove `Params` from the definition
of functions/items that previously took it. If you are using a custom runtime, you _may_ need to pass the runtime type
to these functions.
* If you were using custom types for `Params` (uncommon and if you don't understand you probably were not using it), all
methods that were previously taking the custom type now takes an `Into<String>` or a `&str`. The types were already
required to be string-able, so just make sure to convert it into a string before passing it in if this breaking change
affects you.

`tauri-macros`:

* (internal) Added private `default_runtime` proc macro to allow us to give item definitions a custom runtime only when
the specified feature is enabled.

`tauri-runtime`:

* See `Params` note
* Removed `Params`, `MenuId`, `Tag`, `TagRef`.
* Added `menu::{MenuHash, MenuId, MenuIdRef}` as type aliases for the internal type that menu types now use.
* All previous menu items that had a `MenuId` generic now use the underlying `MenuId` type without a generic.
* `Runtime`, `RuntimeHandle`, and `Dispatch` have no more generic parameter on `create_window(...)` and instead use the
`Runtime` type directly
* `Runtime::system_tray` has no more `MenuId` generic and uses the string based `SystemTray` type directly.
* (internal) `CustomMenuItem::id_value()` is now hashed on creation and exposed as the `id` field with type `MenuHash`.

`tauri-runtime-wry`:

* See `Params` note
* update menu and runtime related types to the ones changed in `tauri-runtime`.

`tauri-utils`:

* `Assets::get` signature has changed to take a `&AssetKey` instead of `impl Into<AssetKey>` to become trait object
safe.
1 change: 0 additions & 1 deletion Cargo.toml
Expand Up @@ -15,7 +15,6 @@ members = [
"examples/helloworld/src-tauri",
"examples/multiwindow/src-tauri",
"examples/navigation/src-tauri",
"examples/params/src-tauri",
"examples/splashscreen/src-tauri",
"examples/state/src-tauri",
"examples/sidecar/src-tauri",
Expand Down
16 changes: 15 additions & 1 deletion core/tauri-macros/src/lib.rs
Expand Up @@ -5,9 +5,10 @@
extern crate proc_macro;
use crate::context::ContextItems;
use proc_macro::TokenStream;
use syn::parse_macro_input;
use syn::{parse_macro_input, DeriveInput};

mod command;
mod runtime;

#[macro_use]
mod context;
Expand Down Expand Up @@ -60,3 +61,16 @@ pub fn generate_context(items: TokenStream) -> TokenStream {
let path = parse_macro_input!(items as ContextItems);
context::generate_context(path).into()
}

/// Adds the default type for the last parameter (assumed to be runtime) for a specific feature.
///
/// e.g. To default the runtime generic to type `crate::Wry` when the `wry` feature is enabled, the
/// syntax would look like `#[default_runtime(crate::Wry, wry)`. This is **always** set for the last
/// generic, so make sure the last generic is the runtime when using this macro.
#[doc(hidden)]
#[proc_macro_attribute]
pub fn default_runtime(attributes: TokenStream, input: TokenStream) -> TokenStream {
let attributes = parse_macro_input!(attributes as runtime::Attributes);
let input = parse_macro_input!(input as DeriveInput);
runtime::default_runtime(attributes, input).into()
}
62 changes: 62 additions & 0 deletions core/tauri-macros/src/runtime.rs
@@ -0,0 +1,62 @@
// Copyright 2019-2021 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

use proc_macro2::TokenStream;
use quote::quote;
use syn::parse::{Parse, ParseStream};
use syn::{parse_quote, DeriveInput, GenericParam, Ident, Token, Type, TypeParam};

/// The default runtime type to enable when the provided feature is enabled.
pub(crate) struct Attributes {
default_type: Type,
feature: Ident,
}

impl Parse for Attributes {
fn parse(input: ParseStream) -> syn::Result<Self> {
let default_type = input.parse()?;
input.parse::<Token![,]>()?;
Ok(Attributes {
default_type,
feature: input.parse()?,
})
}
}

pub(crate) fn default_runtime(attributes: Attributes, input: DeriveInput) -> TokenStream {
// create a new copy to manipulate for the wry feature flag
let mut wry = input.clone();
let wry_runtime = wry
.generics
.params
.last_mut()
.expect("default_runtime requires the item to have at least 1 generic parameter");

// set the default value of the last generic parameter to the provided runtime type
match wry_runtime {
GenericParam::Type(
param @ TypeParam {
eq_token: None,
default: None,
..
},
) => {
param.eq_token = Some(parse_quote!(=));
param.default = Some(attributes.default_type);
}
_ => {
panic!("DefaultRuntime requires the last parameter to not have a default value")
}
};

let feature = attributes.feature.to_string();

quote!(
#[cfg(feature = #feature)]
#wry

#[cfg(not(feature = #feature))]
#input
)
}
45 changes: 21 additions & 24 deletions core/tauri-runtime-wry/src/lib.rs
Expand Up @@ -13,8 +13,8 @@ use tauri_runtime::{
dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Position, Size},
DetachedWindow, PendingWindow, WindowEvent,
},
ClipboardManager, Dispatch, Error, GlobalShortcutManager, Icon, Params, Result, RunEvent,
RunIteration, Runtime, RuntimeHandle, UserAttentionType,
ClipboardManager, Dispatch, Error, GlobalShortcutManager, Icon, Result, RunEvent, RunIteration,
Runtime, RuntimeHandle, UserAttentionType,
};

#[cfg(feature = "menu")]
Expand Down Expand Up @@ -407,7 +407,7 @@ pub struct WindowBuilderWrapper {
inner: WryWindowBuilder,
center: bool,
#[cfg(feature = "menu")]
menu: Menu<u16>,
menu: Menu,
}

// safe since `menu_items` are read only here
Expand Down Expand Up @@ -454,7 +454,7 @@ impl WindowBuilder for WindowBuilderWrapper {
}

#[cfg(feature = "menu")]
fn menu<I: MenuId>(mut self, menu: Menu<I>) -> Self {
fn menu(mut self, menu: Menu) -> Self {
self.menu = convert_menu_id(Menu::new(), menu);
self
}
Expand Down Expand Up @@ -898,10 +898,10 @@ impl Dispatch for WryDispatcher {

// Creates a window by dispatching a message to the event loop.
// Note that this must be called from a separate thread, otherwise the channel will introduce a deadlock.
fn create_window<P: Params<Runtime = Self::Runtime>>(
fn create_window(
&mut self,
pending: PendingWindow<P>,
) -> Result<DetachedWindow<P>> {
pending: PendingWindow<Self::Runtime>,
) -> Result<DetachedWindow<Self::Runtime>> {
let (tx, rx) = channel();
let label = pending.label.clone();
let context = self.context.clone();
Expand Down Expand Up @@ -1203,10 +1203,10 @@ impl RuntimeHandle for WryHandle {

// Creates a window by dispatching a message to the event loop.
// Note that this must be called from a separate thread, otherwise the channel will introduce a deadlock.
fn create_window<P: Params<Runtime = Self::Runtime>>(
fn create_window(
&self,
pending: PendingWindow<P>,
) -> Result<DetachedWindow<P>> {
pending: PendingWindow<Self::Runtime>,
) -> Result<DetachedWindow<Self::Runtime>> {
let (tx, rx) = channel();
let label = pending.label.clone();
let dispatcher_context = self.dispatcher_context.clone();
Expand Down Expand Up @@ -1306,10 +1306,7 @@ impl Runtime for Wry {
self.clipboard_manager_handle.clone()
}

fn create_window<P: Params<Runtime = Self>>(
&self,
pending: PendingWindow<P>,
) -> Result<DetachedWindow<P>> {
fn create_window(&self, pending: PendingWindow<Self>) -> Result<DetachedWindow<Self>> {
let label = pending.label.clone();
let proxy = self.event_loop.create_proxy();
let webview = create_webview(
Expand Down Expand Up @@ -1347,7 +1344,7 @@ impl Runtime for Wry {
}

#[cfg(feature = "system-tray")]
fn system_tray<I: MenuId>(&self, system_tray: SystemTray<I>) -> Result<Self::TrayHandler> {
fn system_tray(&self, system_tray: SystemTray) -> Result<Self::TrayHandler> {
let icon = system_tray
.icon
.expect("tray icon not set")
Expand Down Expand Up @@ -1904,10 +1901,10 @@ fn center_window(window: &Window) -> Result<()> {
}
}

fn create_webview<P: Params<Runtime = Wry>>(
fn create_webview(
event_loop: &EventLoopWindowTarget<Message>,
context: DispatcherContext,
pending: PendingWindow<P>,
pending: PendingWindow<Wry>,
) -> Result<WebviewWrapper> {
#[allow(unused_mut)]
let PendingWindow {
Expand Down Expand Up @@ -1983,7 +1980,7 @@ fn create_webview<P: Params<Runtime = Wry>>(
.map_err(|e| Error::CreateWebview(Box::new(e)))?;

Ok(WebviewWrapper {
label: format!("{}", label),
label,
inner: webview,
#[cfg(feature = "menu")]
menu_items,
Expand All @@ -1993,10 +1990,10 @@ fn create_webview<P: Params<Runtime = Wry>>(
}

/// Create a wry rpc handler from a tauri rpc handler.
fn create_rpc_handler<P: Params<Runtime = Wry>>(
fn create_rpc_handler(
context: DispatcherContext,
label: P::Label,
handler: WebviewRpcHandler<P>,
label: String,
handler: WebviewRpcHandler<Wry>,
) -> Box<dyn Fn(&Window, WryRpcRequest) -> Option<RpcResponse> + 'static> {
Box::new(move |window, request| {
handler(
Expand All @@ -2014,10 +2011,10 @@ fn create_rpc_handler<P: Params<Runtime = Wry>>(
}

/// Create a wry file drop handler from a tauri file drop handler.
fn create_file_drop_handler<P: Params<Runtime = Wry>>(
fn create_file_drop_handler(
context: DispatcherContext,
label: P::Label,
handler: FileDropHandler<P>,
label: String,
handler: FileDropHandler<Wry>,
) -> Box<dyn Fn(&Window, WryFileDropEvent) -> bool + 'static> {
Box::new(move |window, event| {
handler(
Expand Down
28 changes: 15 additions & 13 deletions core/tauri-runtime-wry/src/menu.rs
Expand Up @@ -8,7 +8,7 @@ pub use tauri_runtime::{
SystemTrayMenuEntry, SystemTrayMenuItem, TrayHandle,
},
window::MenuEvent,
Icon, MenuId, SystemTrayEvent,
Icon, SystemTrayEvent,
};
pub use wry::application::{
event::TrayEvent,
Expand All @@ -31,6 +31,9 @@ pub use wry::application::platform::macos::{
#[cfg(feature = "system-tray")]
use crate::{Error, Message, Result, TrayMessage};

#[cfg(feature = "menu")]
use tauri_runtime::menu::MenuHash;

use uuid::Uuid;

use std::{
Expand Down Expand Up @@ -145,12 +148,12 @@ impl From<NativeImage> for NativeImageWrapper {

pub struct MenuItemAttributesWrapper<'a>(pub WryMenuItemAttributes<'a>);

impl<'a, I: MenuId> From<&'a CustomMenuItem<I>> for MenuItemAttributesWrapper<'a> {
fn from(item: &'a CustomMenuItem<I>) -> Self {
impl<'a> From<&'a CustomMenuItem> for MenuItemAttributesWrapper<'a> {
fn from(item: &'a CustomMenuItem) -> Self {
let mut attributes = WryMenuItemAttributes::new(&item.title)
.with_enabled(item.enabled)
.with_selected(item.selected)
.with_id(WryMenuId(item.id_value()));
.with_id(WryMenuId(item.id));
if let Some(accelerator) = item.keyboard_accelerator.as_ref() {
attributes = attributes.with_accelerators(&accelerator.parse().expect("invalid accelerator"));
}
Expand Down Expand Up @@ -195,11 +198,11 @@ impl From<SystemTrayMenuItem> for MenuItemWrapper {
}

#[cfg(feature = "menu")]
pub fn convert_menu_id<I: MenuId>(mut new_menu: Menu<u16>, menu: Menu<I>) -> Menu<u16> {
pub fn convert_menu_id(mut new_menu: Menu, menu: Menu) -> Menu {
for item in menu.items {
match item {
MenuEntry::CustomItem(c) => {
let mut item = CustomMenuItem::new(c.id_value(), c.title);
let mut item = CustomMenuItem::new(c.id_str, c.title);
#[cfg(target_os = "macos")]
if let Some(native_image) = c.native_image {
item = item.native_image(native_image);
Expand Down Expand Up @@ -229,8 +232,8 @@ pub fn convert_menu_id<I: MenuId>(mut new_menu: Menu<u16>, menu: Menu<I>) -> Men

#[cfg(feature = "menu")]
pub fn to_wry_menu(
custom_menu_items: &mut HashMap<u16, WryCustomMenuItem>,
menu: Menu<u16>,
custom_menu_items: &mut HashMap<MenuHash, WryCustomMenuItem>,
menu: Menu,
) -> MenuBar {
let mut wry_menu = MenuBar::new();
for item in menu.items {
Expand Down Expand Up @@ -262,22 +265,21 @@ pub fn to_wry_menu(
}

#[cfg(feature = "system-tray")]
pub fn to_wry_context_menu<I: MenuId>(
custom_menu_items: &mut HashMap<u16, WryCustomMenuItem>,
menu: SystemTrayMenu<I>,
pub fn to_wry_context_menu(
custom_menu_items: &mut HashMap<MenuHash, WryCustomMenuItem>,
menu: SystemTrayMenu,
) -> WryContextMenu {
let mut tray_menu = WryContextMenu::new();
for item in menu.items {
match item {
SystemTrayMenuEntry::CustomItem(c) => {
#[allow(unused_mut)]
let mut item = tray_menu.add_item(MenuItemAttributesWrapper::from(&c).0);
let id = c.id_value();
#[cfg(target_os = "macos")]
if let Some(native_image) = c.native_image {
item.set_native_image(NativeImageWrapper::from(native_image).0);
}
custom_menu_items.insert(id, item);
custom_menu_items.insert(c.id, item);
}
SystemTrayMenuEntry::NativeItem(i) => {
tray_menu.add_native_item(MenuItemWrapper::from(i).0);
Expand Down

0 comments on commit fd8fab5

Please sign in to comment.