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: add support to deeplink and file association on macOS #422

Merged
merged 21 commits into from
Jul 12, 2023
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
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: 5 additions & 0 deletions .changes/support-open-file.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"tao": minor
---

Add `Event::OpenURLs` on macOS.
6 changes: 4 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@ targets = [
members = [ "tao-macros" ]

[features]
default = [ ]
dox = [ "gtk/dox" ]
default = [ "macos-open-files" ]
dox = [ "gtk/dox"]
tray = [ "libappindicator", "dirs-next" ]
macos-open-urls = []
macos-open-files = []

[build-dependencies]
cc = "1"
Expand Down
49 changes: 49 additions & 0 deletions src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,46 @@ pub enum Event<'a, T: 'static> {
position: PhysicalPosition<f64>,
},

/// Emitted when the app is requested to open a URL.
///
/// ## Platform-specific
///
/// This event is only relevant on macOS.
///
/// ## Note
///
/// Needs `macos-open-urls` feature flag.
OpenURLs(Vec<String>),

/// Emitted when the app is requested to open a file.
///
/// After this event is processed, the app will respond to the OS
/// using the value pointed at by `success`.
///
/// ## Platform-specific
///
/// This event is only relevant on macOS.
///
/// ## Note
///
/// Needs `macos-open-files` feature flag.
OpenFile {
filename: String,
/// An indicator to the OS of the success or faile of opening the file.
success: &'a mut bool,
},

/// Emitted when the app is requested to open files.
///
/// ## Platform-specific
///
/// This event is only relevant on macOS.
///
/// ## Note
///
/// Needs `macos-open-files` feature flag.
OpenFiles(Vec<String>),

/// Emitted when a global shortcut is triggered.
///
/// ## Platform-specific
Expand Down Expand Up @@ -207,6 +247,9 @@ impl<T: Clone> Clone for Event<'static, T> {
position: *position,
},
GlobalShortcutEvent(accelerator_id) => GlobalShortcutEvent(*accelerator_id),
OpenURLs(urls) => OpenURLs(urls.clone()),
OpenFile { .. } => unreachable!("Static event can't be about open file"),
OpenFiles(filenames) => OpenFiles(filenames.clone()),
}
}
}
Expand Down Expand Up @@ -246,6 +289,9 @@ impl<'a, T> Event<'a, T> {
position,
}),
GlobalShortcutEvent(accelerator_id) => Ok(GlobalShortcutEvent(accelerator_id)),
OpenURLs(urls) => Ok(OpenURLs(urls)),
OpenFile { filename, success } => Ok(OpenFile { filename, success }),
OpenFiles(filenames) => Ok(OpenFiles(filenames)),
}
}

Expand Down Expand Up @@ -287,6 +333,9 @@ impl<'a, T> Event<'a, T> {
position,
}),
GlobalShortcutEvent(accelerator_id) => Some(GlobalShortcutEvent(accelerator_id)),
OpenURLs(urls) => Some(OpenURLs(urls)),
OpenFile { .. } => None,
OpenFiles(filenames) => Some(OpenFiles(filenames)),
}
}
}
Expand Down
80 changes: 79 additions & 1 deletion src/platform_impl/macos/app_delegate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use crate::{platform::macos::ActivationPolicy, platform_impl::platform::app_state::AppState};

use cocoa::base::id;
use cocoa::foundation::NSString;
use objc::{
declare::ClassDecl,
runtime::{Class, Object, Sel},
Expand All @@ -14,6 +15,16 @@ use std::{
os::raw::c_void,
};

#[cfg(any(feature = "macos-open-urls", feature = "macos-open-files"))]
use cocoa::foundation::NSArray;
#[cfg(all(feature = "macos-open-urls", not(feature = "macos-open-files")))]
use cocoa::foundation::NSURL;
#[cfg(any(feature = "macos-open-urls", feature = "macos-open-files"))]
use std::ffi::CStr;

#[cfg(all(feature = "macos-open-files", feature = "macos-open-urls"))]
compile_error!("`macos-open-files` and `macos-open-urls` feature flags can't be used at the same time, please choose only one of them.");

static AUX_DELEGATE_STATE_NAME: &str = "auxState";

pub struct AuxDelegateState {
Expand Down Expand Up @@ -47,6 +58,21 @@ lazy_static! {
sel!(applicationWillTerminate:),
application_will_terminate as extern "C" fn(&Object, Sel, id),
);
#[cfg(all(feature = "macos-open-urls", not(feature = "macos-open-files")))]
decl.add_method(
sel!(application:openURLs:),
application_open_urls as extern "C" fn(&Object, Sel, id, id),
);
#[cfg(all(feature = "macos-open-files", not(feature = "macos-open-urls")))]
decl.add_method(
sel!(application:openFile:),
application_open_file as extern "C" fn(&Object, Sel, id, id) -> cocoa::base::BOOL,
);
#[cfg(all(feature = "macos-open-files", not(feature = "macos-open-urls")))]
decl.add_method(
sel!(application:openFiles:),
application_open_files as extern "C" fn(&Object, Sel, id, id),
);
decl.add_ivar::<*mut c_void>(AUX_DELEGATE_STATE_NAME);

AppDelegateClass(decl.register())
Expand Down Expand Up @@ -81,7 +107,7 @@ extern "C" fn dealloc(this: &Object, _: Sel) {
let state_ptr: *mut c_void = *(this.get_ivar(AUX_DELEGATE_STATE_NAME));
// As soon as the box is constructed it is immediately dropped, releasing the underlying
// memory
Box::from_raw(state_ptr as *mut RefCell<AuxDelegateState>);
drop(Box::from_raw(state_ptr as *mut RefCell<AuxDelegateState>));
}
}

Expand All @@ -96,3 +122,55 @@ extern "C" fn application_will_terminate(_: &Object, _: Sel, _: id) {
AppState::exit();
trace!("Completed `applicationWillTerminate`");
}

#[cfg(all(feature = "macos-open-urls", not(feature = "macos-open-files")))]
extern "C" fn application_open_urls(_: &Object, _: Sel, _: id, urls: id) -> () {
trace!("Trigger `application:openURLs:`");

let url_strings = unsafe {
(0..urls.count())
.map(|i| {
CStr::from_ptr(urls.objectAtIndex(i).absoluteString().UTF8String())
.to_string_lossy()
.to_string()
})
.collect::<Vec<_>>()
};
trace!("Get `application:openURLs:` URLs: {:?}", url_strings);
AppState::open_urls(url_strings);
trace!("Completed `application:openURLs:`");
}

#[cfg(all(feature = "macos-open-files", not(feature = "macos-open-urls")))]
extern "C" fn application_open_file(_: &Object, _: Sel, _: id, file: id) -> cocoa::base::BOOL {
trace!("Trigger `application:openFile:`");

let filename = unsafe { CStr::from_ptr(file.UTF8String()) }
.to_string_lossy()
.to_string();
let mut success = true;

trace!("Get `application:openFile:` URLs: {:?}", filename);
AppState::open_file(filename, &mut success);
trace!("Completed `application:openFile:`");

success as i8

Choose a reason for hiding this comment

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

This line throws error since return should be BOOL

}

#[cfg(all(feature = "macos-open-files", not(feature = "macos-open-urls")))]
extern "C" fn application_open_files(_: &Object, _: Sel, _: id, files: id) -> () {
trace!("Trigger `application:openFiles:`");

let filenames = unsafe {
(0..files.count())
.map(|i| {
CStr::from_ptr(files.objectAtIndex(i).UTF8String())
.to_string_lossy()
.to_string()
})
.collect::<Vec<_>>()
};
trace!("Get `application:openFiles:` URLs: {:?}", filenames);
AppState::open_files(filenames);
trace!("Completed `application:openFiles:`");
}
18 changes: 18 additions & 0 deletions src/platform_impl/macos/app_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,24 @@ impl AppState {
HANDLER.set_in_callback(false);
}

#[cfg(all(feature = "macos-open-urls", not(feature = "macos-open-files")))]
pub fn open_urls(urls: Vec<String>) {
HANDLER.handle_nonuser_event(EventWrapper::StaticEvent(Event::OpenURLs(urls)));
}
#[cfg(all(feature = "macos-open-files", not(feature = "macos-open-urls")))]
pub fn open_file(filename: String, success: &mut bool) {
if let Some(ref mut callback) = *HANDLER.callback.lock().unwrap() {
callback.handle_nonuser_event(
Event::OpenFile { filename, success },
&mut HANDLER.control_flow.lock().unwrap(),
)
}
}
#[cfg(all(feature = "macos-open-files", not(feature = "macos-open-urls")))]
pub fn open_files(files: Vec<String>) {
HANDLER.handle_nonuser_event(EventWrapper::StaticEvent(Event::OpenFiles(files)));
}

pub fn wakeup(panic_info: Weak<PanicInfo>) {
let panic_info = panic_info
.upgrade()
Expand Down
4 changes: 2 additions & 2 deletions src/platform_impl/macos/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ extern "C" fn dealloc(this: &Object, _sel: Sel) {
let state: *mut c_void = *this.get_ivar("taoState");
let marked_text: id = *this.get_ivar("markedText");
let _: () = msg_send![marked_text, release];
Box::from_raw(state as *mut ViewState);
drop(Box::from_raw(state as *mut ViewState));
}
}

Expand Down Expand Up @@ -573,7 +573,7 @@ extern "C" fn insert_text(this: &Object, _sel: Sel, string: id, _replacement_ran
trace!("Completed `insertText`");
}

extern "C" fn do_command_by_selector(this: &Object, _sel: Sel, command: Sel) {
extern "C" fn do_command_by_selector(_this: &Object, _sel: Sel, _command: Sel) {
trace!("Triggered `doCommandBySelector`");
// TODO: (Artur) all these inputs seem to trigger a key event with the correct text
// content so this is not needed anymore, it seems.
Expand Down
2 changes: 1 addition & 1 deletion src/platform_impl/macos/window_delegate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ fn with_state<F: FnOnce(&mut WindowDelegateState) -> T, T>(this: &Object, callba

extern "C" fn dealloc(this: &Object, _sel: Sel) {
with_state(this, |state| unsafe {
Box::from_raw(state as *mut WindowDelegateState);
drop(Box::from_raw(state as *mut WindowDelegateState));
});
}

Expand Down