Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(push): push notifications #1015

Draft
wants to merge 5 commits into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "tao"
version = "0.30.7"
version = "0.30.8"
description = "Cross-platform window manager library."
authors = [
"Tauri Programme within The Commons Conservancy",
Expand Down Expand Up @@ -32,6 +32,7 @@ serde = [ "dep:serde", "dpi/serde" ]
rwh_04 = [ "dep:rwh_04" ]
rwh_05 = [ "dep:rwh_05" ]
rwh_06 = [ "dep:rwh_06" ]
push-notifications = []

[workspace]
members = [ "tao-macros" ]
Expand Down Expand Up @@ -61,11 +62,13 @@ parking_lot = "0.12"
unicode-segmentation = "1.11"
windows-version = "0.1"
windows-core = "0.58"
windows-async = "0.1.1"

[target."cfg(target_os = \"windows\")".dependencies.windows]
version = "0.58"
features = [
"implement",
"Networking_PushNotifications",
"Win32_Devices_HumanInterfaceDevice",
"Win32_Foundation",
"Win32_Globalization",
Expand Down
18 changes: 18 additions & 0 deletions src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
use std::path::PathBuf;
use std::time::Instant;

use crate::push::PushToken;
use crate::{
dpi::{PhysicalPosition, PhysicalSize},
keyboard::{self, ModifiersState},
Expand Down Expand Up @@ -143,6 +144,17 @@ pub enum Event<'a, T: 'static> {
/// - **Other**: Unsupported.
#[non_exhaustive]
Reopen { has_visible_windows: bool },

/// ## Push Tokens
///
/// Emitted when registration completes and an application push token is made available; on Apple
/// platforms, this is the APNS token. On Android, this is the FCM token.
PushRegistration(PushToken),

/// ## Push Token Errors
///
/// Emitted when push token registration fails.
PushRegistrationError(String),
Comment on lines +148 to +157
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

needs guard

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure what you mean by "needs guard"

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@amrbashir these are my own comments to remind myself to add #[cfg(feature = "push-notifications") so that this code isn't included unless developers opt-in.

}

impl<T: Clone> Clone for Event<'static, T> {
Expand Down Expand Up @@ -171,6 +183,8 @@ impl<T: Clone> Clone for Event<'static, T> {
} => Reopen {
has_visible_windows: *has_visible_windows,
},
PushRegistration(token) => PushRegistration(token.clone()),
PushRegistrationError(error) => PushRegistrationError(error.clone()),
}
}
}
Expand All @@ -195,6 +209,8 @@ impl<'a, T> Event<'a, T> {
} => Ok(Reopen {
has_visible_windows,
}),
PushRegistration(token) => Ok(PushRegistration(token)),
PushRegistrationError(error) => Err(PushRegistrationError(error)),
}
}

Expand All @@ -221,6 +237,8 @@ impl<'a, T> Event<'a, T> {
} => Some(Reopen {
has_visible_windows,
}),
PushRegistration(token) => Some(PushRegistration(token)),
PushRegistrationError(error) => Some(PushRegistrationError(error)),
Comment on lines +240 to +241
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these need guards as well

}
}
}
Expand Down
21 changes: 18 additions & 3 deletions src/event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,6 @@
//! [create_proxy]: crate::event_loop::EventLoop::create_proxy
//! [event_loop_proxy]: crate::event_loop::EventLoopProxy
//! [send_event]: crate::event_loop::EventLoopProxy::send_event
use std::time::Instant;
use std::{error, fmt, marker::PhantomData, ops::Deref};

use crate::{
dpi::PhysicalPosition,
error::ExternalError,
Expand All @@ -24,6 +21,12 @@ use crate::{
platform_impl,
window::{ProgressBarState, Theme},
};
use std::time::Instant;
use std::{error, fmt, marker::PhantomData, ops::Deref};

#[cfg(feature = "push-notifications")]
#[cfg(any(windows))]
use windows::Networking::PushNotifications::PushNotificationChannel;

/// Provides a way to retrieve events from the system and from the windows that were registered to
/// the events loop.
Expand Down Expand Up @@ -319,6 +322,18 @@ impl<T> EventLoopWindowTarget<T> {
))]
self.p.set_theme(theme)
}

/// Sets the push channel for the application.
///
/// ## Platform-specific
///
/// - **Windows only.** Other platforms deliver the push channel or token via other means.
#[cfg(any(windows))]
#[cfg(feature = "push-notifications")]
#[inline]
pub fn set_push_channel(&self, channel: Option<PushNotificationChannel>) {
self.p.set_push_channel(channel)
}
}

#[cfg(feature = "rwh_05")]
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ mod icon;
pub mod keyboard;
pub mod monitor;
mod platform_impl;
pub mod push;

pub mod window;

Expand Down
77 changes: 77 additions & 0 deletions src/platform/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ use crate::{
};
use windows::Win32::UI::Input::KeyboardAndMouse::*;

#[cfg(feature = "push-notifications")]
use windows::Networking::PushNotifications::{
PushNotificationChannel, PushNotificationChannelManager,
};

#[cfg(feature = "push-notifications")]
use {windows::Foundation::AsyncStatus, windows::Foundation::IAsyncOperation};

pub type HWND = isize;
pub type HMENU = isize;

Expand Down Expand Up @@ -440,3 +448,72 @@ impl IconExtWindows for Icon {
Ok(Icon { inner: win_icon })
}
}

/// Additional methods on `PushNotifications` that are specific to Windows.
#[cfg(feature = "push-notifications")]
pub trait PushNotificationsExtWindows {
/// Setup Windows Notifications System, the Windows equivalent to APNS.
///
/// This call yields an `IAsyncOperation` which must be awaited to obtain the underlying
/// `PushNotificationChannel`.
///
/// Return error codes are documented below:
/// (None yet).
fn setup_wns() -> Result<(), u8> {
let mgr = PushNotificationChannelManager::GetDefault();
let mgr = match mgr {
Ok(mgr) => mgr,
Err(_) => {
return Err(1);
}
};
let register_op = match mgr.CreatePushNotificationChannelForApplicationAsync() {
Ok(channel) => channel,
Err(_) => {
return Err(2);
}
};
// Attach callback
attach_callback(register_op, |result| match result {
Ok(value) => register_push_channel(value),
Err(e) => println!("Operation failed with error: {:?}", e),
})
.expect("failed to attach callback for windows push notification token");

Ok(())
}
}

#[cfg(feature = "push-notifications")]
fn register_push_channel(_channel: PushNotificationChannel) {
eprintln!("would register channel")
}

#[cfg(feature = "push-notifications")]
fn attach_callback<T, F>(operation: IAsyncOperation<T>, callback: F) -> windows::core::Result<()>
where
T: windows::core::RuntimeType + 'static,
F: FnOnce(windows::core::Result<T>) + Send + Clone + Copy + 'static,
{
unsafe {
operation.SetCompleted(&windows::Foundation::AsyncOperationCompletedHandler::new(
move |op, _| {
let result = match op.unwrap().Status()? {
AsyncStatus::Completed => Ok(op.unwrap().GetResults()),
AsyncStatus::Canceled => Err(windows::core::Error::new::<String>(
windows::core::HRESULT(0x800704C7u32 as i32), // Operation canceled
"Operation was canceled".into(),
)),
AsyncStatus::Error => Err(windows::core::Error::new::<String>(
op.unwrap().ErrorCode().unwrap(), // Operation failed
"Operation failed".into(),
)),
AsyncStatus::Started => unreachable!(),
_ => unreachable!(),
};
callback(result.expect("empty waiter"));
Ok(())
},
))
}
}
88 changes: 88 additions & 0 deletions src/platform_impl/macos/app_delegate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@ use cocoa::{
foundation::NSString,
};
use objc::{
class,
declare::ClassDecl,
msg_send,
runtime::{Class, Object, Sel, BOOL},
sel, sel_impl,
};
use std::{
cell::{RefCell, RefMut},
Expand Down Expand Up @@ -63,6 +66,14 @@ lazy_static! {
sel!(applicationSupportsSecureRestorableState:),
application_supports_secure_restorable_state as extern "C" fn(&Object, Sel, id) -> BOOL,
);
decl.add_method(
sel!(application:didRegisterForRemoteNotificationsWithDeviceToken:),
did_register_for_apns as extern "C" fn(&Object, Sel, id, id),
);
decl.add_method(
sel!(application:didFailToRegisterForRemoteNotificationsWithError:),
did_fail_to_register_for_apns as extern "C" fn(&Object, _: Sel, id, id),
);
Comment on lines +69 to +76
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

guards

decl.add_ivar::<*mut c_void>(AUX_DELEGATE_STATE_NAME);

AppDelegateClass(decl.register())
Expand Down Expand Up @@ -100,8 +111,26 @@ extern "C" fn dealloc(this: &Object, _: Sel) {
}
}

#[cfg(feature = "push-notifications")]
fn register_push_notifications() {
// register for push notifications. this call is inert on macOS unless the app is entitled to
// access an APS environment. see:
// https://developer.apple.com/documentation/usernotifications/registering-your-app-with-apns
// and:
// https://developer.apple.com/documentation/bundleresources/entitlements/com_apple_developer_aps-environment
let shared_app = get_shared_application();
unsafe {
// registerForRemoteNotifications()
let _: () = msg_send![shared_app, registerForRemoteNotifications];
};
}

extern "C" fn did_finish_launching(this: &Object, _: Sel, _: id) {
trace!("Triggered `applicationDidFinishLaunching`");

#[cfg(feature = "push-notifications")]
register_push_notifications();

AppState::launched(this);
trace!("Completed `applicationDidFinishLaunching`");
}
Expand Down Expand Up @@ -147,3 +176,62 @@ extern "C" fn application_supports_secure_restorable_state(_: &Object, _: Sel, _
trace!("Completed `applicationSupportsSecureRestorableState`");
objc::runtime::YES
}

// application(_:didRegisterForRemoteNotificationsWithDeviceToken:)
extern "C" fn did_register_for_apns(_: &Object, _: Sel, _: id, token_data: id) {
trace!("Triggered `didRegisterForRemoteNotificationsWithDeviceToken`");
let token_bytes = unsafe {
if token_data.is_null() {
trace!("Token data is null; ignoring");
return;
}
let is_nsdata: bool = msg_send![token_data, isKindOfClass:class!(NSData)];
if !is_nsdata {
trace!("Token data is not an NSData object");
return;
}
let bytes: *const u8 = msg_send![token_data, bytes];
let length: usize = msg_send![token_data, length];
std::slice::from_raw_parts(bytes, length).to_vec()
};
AppState::did_register_push_token(token_bytes);
trace!("Completed `didRegisterForRemoteNotificationsWithDeviceToken`");
}

// application(_:didFailToRegisterForRemoteNotificationsWithError:)
extern "C" fn did_fail_to_register_for_apns(_: &Object, _: Sel, _: id, err: *mut Object) {
trace!("Triggered `didFailToRegisterForRemoteNotificationsWithError`");

let error_string = unsafe {
if err.is_null() {
"Unknown error (null error object)".to_string()
} else {
// Verify it's an NSError
let is_error: bool = msg_send![err, isKindOfClass:class!(NSError)];
if !is_error {
trace!("Invalid error object type for push registration failure");
return;
}

// Get the localizedDescription
let description: *mut Object = msg_send![err, localizedDescription];
if description.is_null() {
trace!("Error had no description");
return;
}

// Convert NSString to str
let utf8: *const u8 = msg_send![description, UTF8String];
let len: usize = msg_send![description, lengthOfBytesUsingEncoding:4];
let bytes = std::slice::from_raw_parts(utf8, len);
String::from_utf8_lossy(bytes).to_string()
}
};

AppState::did_fail_to_register_push_token(error_string);
trace!("Completed `didFailToRegisterForRemoteNotificationsWithError`");
}

fn get_shared_application() -> *mut Object {
unsafe { msg_send![class!(NSApplication), sharedApplication] }
}
10 changes: 10 additions & 0 deletions src/platform_impl/macos/app_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,16 @@ impl AppState {
(_, ControlFlow::Poll) => HANDLER.waker().start(),
}
}

pub fn did_register_push_token(token_data: Vec<u8>) {
HANDLER.handle_nonuser_event(EventWrapper::StaticEvent(Event::PushRegistration(
token_data,
)));
}

pub fn did_fail_to_register_push_token(err: String) {
HANDLER.handle_nonuser_event(EventWrapper::StaticEvent(Event::PushRegistrationError(err)));
}
}

/// A hack to make activation of multiple windows work when creating them before
Expand Down
Loading
Loading