use std::cell::{Cell, RefCell};
use std::path::{Path, PathBuf};
use std::ptr::NonNull;
use std::rc::{Rc, Weak};
use block2::RcBlock;
use objc2::rc::Retained;
use objc2::runtime::{AnyObject, NSObject, NSObjectProtocol, ProtocolObject};
use objc2::{AnyThread, DefinedClass, MainThreadOnly, define_class, msg_send};
use objc2_app_kit::{NSView, NSWorkspace};
use objc2_av_foundation::{AVPlayer, AVPlayerItem, AVPlayerItemDidPlayToEndTimeNotification};
use objc2_av_kit::{AVPlayerView, AVPlayerViewControlsStyle};
use objc2_core_media::CMTime;
use objc2_foundation::{NSData, NSError, NSObjectNSKeyValueObserverRegistration, NSNotification, NSNotificationCenter, NSOperationQueue, NSRect, NSString, NSStringCompareOptions, NSURL, NSURLRequest};
use objc2_pdf_kit::{PDFDisplayMode, PDFDocument, PDFSelection, PDFView, PDFViewPageChangedNotification};
use objc2_web_kit::{WKNavigation, WKNavigationAction, WKNavigationActionPolicy, WKNavigationDelegate, WKNavigationType, WKWebView, WKWebViewConfiguration};
use crate::signal::{Effect, Signal, batch, untrack};
use crate::view::{Cx, Node, Size, View};
fn as_view<T: objc2::ClassType>(v: &Retained<T>) -> Retained<NSView> {
unsafe { Retained::cast_unchecked(v.clone()) }
}
fn file_url(path: &Path) -> Retained<NSURL> {
NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
}
pub(crate) struct Observer(Retained<ProtocolObject<dyn NSObjectProtocol>>);
impl Observer {
pub(crate) fn new(name: &objc2_foundation::NSNotificationName, object: Option<&AnyObject>, f: impl Fn() + 'static) -> Observer {
let block = RcBlock::new(move |_: NonNull<NSNotification>| crate::failure::entry("a notification", (), &f));
let token = unsafe { NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock(Some(name), object, Some(&NSOperationQueue::mainQueue()), &block) };
Observer(token)
}
}
impl Drop for Observer {
fn drop(&mut self) {
unsafe { NSNotificationCenter::defaultCenter().removeObserver(self.0.as_ref()) };
}
}
enum Load {
Url(String),
Html(String, Option<String>),
File(PathBuf),
}
struct PageState {
view: RefCell<Option<objc2::rc::Weak<WKWebView>>>,
pending: RefCell<Option<Load>>,
title: Signal<String>,
url: Signal<String>,
loading: Signal<bool>,
back: Signal<bool>,
forward: Signal<bool>,
}
#[derive(Clone)]
pub struct WebPage(Rc<PageState>);
impl Default for WebPage {
fn default() -> Self {
Self::new()
}
}
impl WebPage {
pub fn new() -> Self {
WebPage(Rc::new(PageState {
view: RefCell::new(None),
pending: RefCell::new(None),
title: Signal::new(String::new()),
url: Signal::new(String::new()),
loading: Signal::new(false),
back: Signal::new(false),
forward: Signal::new(false),
}))
}
fn view(&self) -> Option<Retained<WKWebView>> {
self.0.view.borrow().as_ref().and_then(|w| w.load())
}
fn start(&self, load: Load) {
match self.view() {
Some(v) => run_load(&v, load),
None => *self.0.pending.borrow_mut() = Some(load),
}
}
pub fn load(&self, url: &str) {
self.start(Load::Url(url.into()));
}
pub fn load_html(&self, html: &str, base_url: Option<&str>) {
self.start(Load::Html(html.into(), base_url.map(Into::into)));
}
pub fn load_file(&self, path: impl AsRef<Path>) {
self.start(Load::File(path.as_ref().to_path_buf()));
}
pub fn title(&self) -> String {
self.0.title.get()
}
pub fn url(&self) -> String {
self.0.url.get()
}
pub fn is_loading(&self) -> bool {
self.0.loading.get()
}
pub fn can_go_back(&self) -> bool {
self.0.back.get()
}
pub fn can_go_forward(&self) -> bool {
self.0.forward.get()
}
pub fn back(&self) {
self.view().map(|v| unsafe { v.goBack() });
}
pub fn forward(&self) {
self.view().map(|v| unsafe { v.goForward() });
}
pub fn reload(&self) {
self.view().map(|v| unsafe { v.reload() });
}
pub fn evaluate(&self, script: &str, then: impl FnOnce(Result<String, String>) + 'static) {
let Some(v) = self.view() else {
then(Err("the web view isn't showing".into()));
return;
};
let then = Cell::new(Some(then));
let block = RcBlock::new(move |result: *mut AnyObject, error: *mut NSError| {
let Some(then) = then.take() else { return };
let out = unsafe {
match (result.as_ref(), error.as_ref()) {
(_, Some(e)) => Err(e.localizedDescription().to_string()),
(Some(r), None) => Ok(match r.downcast_ref::<NSString>() {
Some(s) => s.to_string(),
None => {
let d: Retained<NSString> = msg_send![r, description];
d.to_string()
}
}),
(None, None) => Ok(String::new()),
}
};
crate::failure::entry("a web page's script result", (), || then(out));
});
unsafe { v.evaluateJavaScript_completionHandler(&NSString::from_str(script), Some(&block)) };
}
fn sync(&self, v: &WKWebView) {
let (title, url, loading, back, forward) = unsafe { (v.title(), v.URL(), v.isLoading(), v.canGoBack(), v.canGoForward()) };
let s = &self.0;
batch(|| {
s.title.set_if_changed(title.map(|t| t.to_string()).unwrap_or_default());
s.url.set_if_changed(url.and_then(|u| u.absoluteString()).map(|u| u.to_string()).unwrap_or_default());
s.loading.set_if_changed(loading);
s.back.set_if_changed(back);
s.forward.set_if_changed(forward);
});
}
}
fn run_load(v: &WKWebView, load: Load) {
unsafe {
match load {
Load::Url(url) => {
let Some(u) = NSURL::URLWithString(&NSString::from_str(&url)) else { return };
if u.isFileURL() {
let dir = u.URLByDeletingLastPathComponent().unwrap_or_else(|| u.clone());
v.loadFileURL_allowingReadAccessToURL(&u, &dir);
} else {
v.loadRequest(&NSURLRequest::requestWithURL(&u));
}
}
Load::Html(html, base) => {
let base = base.and_then(|b| NSURL::URLWithString(&NSString::from_str(&b)));
v.loadHTMLString_baseURL(&NSString::from_str(&html), base.as_deref());
}
Load::File(path) => {
let u = file_url(&path);
let dir = file_url(path.parent().unwrap_or(Path::new("/")));
v.loadFileURL_allowingReadAccessToURL(&u, &dir);
}
}
}
}
struct WebState {
page: Weak<PageState>,
links_outside: bool,
}
define_class!(
#[unsafe(super(NSObject))]
#[thread_kind = MainThreadOnly]
#[name = "FerrokitWebDelegate"]
#[ivars = WebState]
struct WebDelegate;
unsafe impl NSObjectProtocol for WebDelegate {}
impl WebDelegate {
#[unsafe(method(observeValueForKeyPath:ofObject:change:context:))]
fn observe(&self, _key: Option<&NSString>, object: Option<&AnyObject>, _change: Option<&AnyObject>, _context: *mut std::ffi::c_void) {
if let Some(view) = object.and_then(|o| o.downcast_ref::<WKWebView>()) {
self.sync(view);
}
}
}
unsafe impl WKNavigationDelegate for WebDelegate {
#[unsafe(method(webView:decidePolicyForNavigationAction:decisionHandler:))]
fn decide(&self, view: &WKWebView, action: &WKNavigationAction, handler: &block2::DynBlock<dyn Fn(WKNavigationActionPolicy)>) {
let (kind, request, frame) = unsafe { (action.navigationType(), action.request(), action.targetFrame()) };
let url = request.URL();
let link = kind == WKNavigationType::LinkActivated || frame.is_none();
if link && let Some(url) = url {
if self.ivars().links_outside && !url.isFileURL() {
NSWorkspace::sharedWorkspace().openURL(&url);
handler.call((WKNavigationActionPolicy::Cancel,));
return;
}
if frame.is_none() {
unsafe { view.loadRequest(&request) };
handler.call((WKNavigationActionPolicy::Cancel,));
return;
}
}
handler.call((WKNavigationActionPolicy::Allow,));
}
#[unsafe(method(webView:didStartProvisionalNavigation:))]
fn started(&self, view: &WKWebView, _n: Option<&WKNavigation>) {
self.sync(view);
}
#[unsafe(method(webView:didCommitNavigation:))]
fn committed(&self, view: &WKWebView, _n: Option<&WKNavigation>) {
self.sync(view);
}
#[unsafe(method(webView:didFinishNavigation:))]
fn finished(&self, view: &WKWebView, _n: Option<&WKNavigation>) {
self.sync(view);
}
#[unsafe(method(webView:didFailNavigation:withError:))]
fn failed(&self, view: &WKWebView, _n: Option<&WKNavigation>, _e: &NSError) {
self.sync(view);
}
#[unsafe(method(webView:didFailProvisionalNavigation:withError:))]
fn failed_early(&self, view: &WKWebView, _n: Option<&WKNavigation>, _e: &NSError) {
self.sync(view);
}
}
);
impl WebDelegate {
fn sync(&self, view: &WKWebView) {
if let Some(page) = self.ivars().page.upgrade() {
WebPage(page).sync(view);
}
}
}
const KEYS: [&str; 5] = ["title", "URL", "loading", "canGoBack", "canGoForward"];
struct Observing {
view: Retained<WKWebView>,
delegate: Retained<WebDelegate>,
}
impl Drop for Observing {
fn drop(&mut self) {
for key in KEYS {
unsafe { self.view.removeObserver_forKeyPath(&self.delegate, &NSString::from_str(key)) };
}
}
}
pub struct WebView {
page: WebPage,
links_outside: bool,
}
impl WebView {
pub fn links_open_in_browser(mut self) -> Self {
self.links_outside = true;
self
}
}
impl View for WebView {
fn build(self, cx: &mut Cx) -> Node {
let mtm = cx.mtm;
let view = unsafe { WKWebView::initWithFrame_configuration(WKWebView::alloc(mtm), NSRect::ZERO, &WKWebViewConfiguration::new(mtm)) };
let delegate = WebDelegate::alloc(mtm).set_ivars(WebState { page: Rc::downgrade(&self.page.0), links_outside: self.links_outside });
let delegate: Retained<WebDelegate> = unsafe { msg_send![super(delegate), init] };
unsafe { view.setNavigationDelegate(Some(ProtocolObject::from_ref(&*delegate))) };
*self.page.0.view.borrow_mut() = Some(objc2::rc::Weak::from_retained(&view));
if let Some(load) = self.page.0.pending.borrow_mut().take() {
run_load(&view, load);
}
for key in KEYS {
unsafe { view.addObserver_forKeyPath_options_context(&delegate, &NSString::from_str(key), objc2_foundation::NSKeyValueObservingOptions::empty(), std::ptr::null_mut()) };
}
let (mut node, _) = Node::leaf(cx, as_view(&view), (true, true), Size { w: 200.0, h: 150.0 });
node.hold(Rc::new(Observing { view, delegate }));
node
}
}
pub fn web_view(page: &WebPage) -> WebView {
WebView { page: page.clone(), links_outside: false }
}
enum PdfSource {
File(Box<dyn Fn() -> Option<PathBuf>>),
Data(Box<dyn Fn() -> Vec<u8>>),
}
pub struct PdfView {
source: PdfSource,
page: Option<Signal<usize>>,
pages: Option<Signal<usize>>,
find: Option<Box<dyn Fn() -> String>>,
mode: PDFDisplayMode,
}
impl PdfView {
pub fn page(mut self, page: &Signal<usize>) -> Self {
self.page = Some(*page);
self
}
pub fn page_count(mut self, count: &Signal<usize>) -> Self {
self.pages = Some(*count);
self
}
pub fn highlight(mut self, query: impl Fn() -> String + 'static) -> Self {
self.find = Some(Box::new(query));
self
}
pub fn single_page(mut self) -> Self {
self.mode = PDFDisplayMode::SinglePage;
self
}
pub fn two_up(mut self) -> Self {
self.mode = PDFDisplayMode::TwoUpContinuous;
self
}
}
impl View for PdfView {
fn build(self, cx: &mut Cx) -> Node {
let view: Retained<PDFView> = unsafe { msg_send![PDFView::alloc(cx.mtm), initWithFrame: NSRect::ZERO] };
unsafe {
view.setAutoScales(true);
view.setDisplayMode(self.mode);
}
let (mut node, _) = Node::leaf(cx, as_view(&view), (true, true), Size { w: 200.0, h: 200.0 });
let (page, pages) = (self.page, self.pages);
let v = view.clone();
let source = self.source;
node.own(Effect::new(move || {
let doc = match &source {
PdfSource::File(f) => f().and_then(|p| unsafe { PDFDocument::initWithURL(PDFDocument::alloc(), &file_url(&p)) }),
PdfSource::Data(f) => unsafe { PDFDocument::initWithData(PDFDocument::alloc(), &NSData::with_bytes(&f())) },
};
untrack(|| {
unsafe { v.setDocument(doc.as_deref()) };
if let Some(c) = pages {
c.set_if_changed(doc.as_ref().map_or(0, |d| unsafe { d.pageCount() }));
}
if let (Some(p), Some(d)) = (page, &doc) {
let want = p.get().min(unsafe { d.pageCount() }.saturating_sub(1));
if let Some(pg) = unsafe { d.pageAtIndex(want) } {
unsafe { v.goToPage(&pg) };
}
p.set_if_changed(want);
}
});
}));
if let Some(p) = page {
let v = view.clone();
let observer = Observer::new(unsafe { PDFViewPageChangedNotification }, Some(&view), move || {
if let (Some(d), Some(cur)) = unsafe { (v.document(), v.currentPage()) } {
p.set_if_changed(unsafe { d.indexForPage(&cur) });
}
});
node.hold(Rc::new(observer));
let v = view.clone();
node.own(Effect::new(move || {
let want = p.get();
unsafe {
let Some(d) = v.document() else { return };
let shown = v.currentPage().map(|c| d.indexForPage(&c));
if shown != Some(want)
&& let Some(pg) = d.pageAtIndex(want.min(d.pageCount().saturating_sub(1)))
{
v.goToPage(&pg);
}
}
}));
}
if let Some(find) = self.find {
let v = view.clone();
node.own(Effect::new(move || {
let q = find();
unsafe {
let Some(d) = v.document() else { return };
if q.is_empty() {
v.setHighlightedSelections(None);
return;
}
let found = d.findString_withOptions(&NSString::from_str(&q), NSStringCompareOptions::CaseInsensitiveSearch);
v.setHighlightedSelections(Some(&found));
if let Some(first) = found.firstObject() {
go_to_match(&v, &first);
}
}
}));
}
node
}
}
fn go_to_match(view: &PDFView, found: &PDFSelection) {
unsafe {
let Some(page) = found.pages().firstObject() else { return };
let placed = |s: &PDFSelection| finite(s.boundsForPage(&page));
if placed(found) {
return view.goToSelection(found);
}
if found.numberOfTextRangesOnPage(&page) > 0 {
let range = found.rangeAtIndex_onPage(0, &page);
if let Some(again) = page.selectionForRange(range)
&& placed(&again)
{
return view.goToSelection(&again);
}
let first = page.characterBoundsAtIndex(range.location as _);
if finite(first) {
return view.goToRect_onPage(first, &page);
}
}
view.goToPage(&page);
}
}
fn finite(r: objc2_foundation::NSRect) -> bool {
[r.origin.x, r.origin.y, r.size.width, r.size.height].iter().all(|v| v.is_finite())
}
pub fn pdf_view(path: impl Fn() -> Option<PathBuf> + 'static) -> PdfView {
PdfView { source: PdfSource::File(Box::new(path)), page: None, pages: None, find: None, mode: PDFDisplayMode::SinglePageContinuous }
}
pub fn pdf_view_data(data: impl Fn() -> Vec<u8> + 'static) -> PdfView {
PdfView { source: PdfSource::Data(Box::new(data)), page: None, pages: None, find: None, mode: PDFDisplayMode::SinglePageContinuous }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum VideoControls {
#[default]
Inline,
Floating,
Minimal,
Hidden,
}
pub struct VideoPlayer {
source: Box<dyn Fn() -> Option<Retained<NSURL>>>,
playing: Option<Signal<bool>>,
time: Option<Signal<f64>>,
duration: Option<Signal<f64>>,
muted: Option<Box<dyn Fn() -> bool>>,
loops: bool,
controls: VideoControls,
}
impl VideoPlayer {
pub fn playing(mut self, playing: &Signal<bool>) -> Self {
self.playing = Some(*playing);
self
}
pub fn time(mut self, seconds: &Signal<f64>) -> Self {
self.time = Some(*seconds);
self
}
pub fn duration(mut self, seconds: &Signal<f64>) -> Self {
self.duration = Some(*seconds);
self
}
pub fn muted(mut self, muted: impl Fn() -> bool + 'static) -> Self {
self.muted = Some(Box::new(muted));
self
}
pub fn loops(mut self) -> Self {
self.loops = true;
self
}
pub fn controls(mut self, controls: VideoControls) -> Self {
self.controls = controls;
self
}
}
struct Watch {
player: Retained<AVPlayer>,
token: Retained<AnyObject>,
_end: RefCell<Option<Observer>>,
}
impl Drop for Watch {
fn drop(&mut self) {
unsafe {
self.player.removeTimeObserver(&self.token);
self.player.pause();
}
}
}
fn seconds(t: CMTime) -> Option<f64> {
let s = unsafe { t.seconds() };
s.is_finite().then_some(s)
}
impl View for VideoPlayer {
fn build(self, cx: &mut Cx) -> Node {
let mtm = cx.mtm;
let view: Retained<AVPlayerView> = unsafe { msg_send![AVPlayerView::alloc(mtm), initWithFrame: NSRect::ZERO] };
let player = unsafe { AVPlayer::new(mtm) };
unsafe {
view.setPlayer(Some(&player));
view.setControlsStyle(match self.controls {
VideoControls::Inline => AVPlayerViewControlsStyle::Inline,
VideoControls::Floating => AVPlayerViewControlsStyle::Floating,
VideoControls::Minimal => AVPlayerViewControlsStyle::Minimal,
VideoControls::Hidden => AVPlayerViewControlsStyle::None,
});
view.setShowsFullScreenToggleButton(true);
}
let (mut node, _) = Node::leaf(cx, as_view(&view), (true, true), Size { w: 160.0, h: 90.0 });
let (playing, time, duration, loops) = (self.playing, self.time, self.duration, self.loops);
let p = player.clone();
let tick = RcBlock::new(move |now: CMTime| {
let (rate, length) = unsafe { (p.rate(), p.currentItem().and_then(|i| seconds(i.duration()))) };
batch(|| {
if let (Some(t), Some(now)) = (time, seconds(now)) {
t.set_if_changed(now);
}
if let (Some(d), Some(length)) = (duration, length) {
d.set_if_changed(length);
}
if let Some(s) = playing {
s.set_if_changed(rate > 0.0);
}
});
});
let token = unsafe { player.addPeriodicTimeObserverForInterval_queue_usingBlock(CMTime::with_seconds(0.25, 600), None, &tick) };
let watch = Rc::new(Watch { player: player.clone(), token, _end: RefCell::new(None) });
let (p, w, source) = (player.clone(), Rc::downgrade(&watch), self.source);
node.own(Effect::new(move || {
let url = source();
untrack(|| {
let item = url.map(|u| unsafe { AVPlayerItem::playerItemWithURL(&u, mtm) });
unsafe { p.replaceCurrentItemWithPlayerItem(item.as_deref()) };
if let Some(d) = duration {
let length = item.as_ref().and_then(|i| unsafe { seconds(i.asset().duration()) });
d.set_if_changed(length.unwrap_or(0.0));
}
if let Some(w) = w.upgrade() {
let p2 = p.clone();
*w._end.borrow_mut() = item.as_ref().map(|i| {
Observer::new(unsafe { AVPlayerItemDidPlayToEndTimeNotification }, Some(i), move || unsafe {
if loops {
p2.seekToTime(CMTime::with_seconds(0.0, 600));
p2.play();
} else if let Some(s) = playing {
s.set_if_changed(false);
}
})
});
}
if playing.is_some_and(|s| s.get()) {
unsafe { p.play() };
}
});
}));
if let Some(s) = playing {
let p = player.clone();
node.own(Effect::new(move || {
let want = s.get();
unsafe {
if want && p.rate() == 0.0 {
p.play();
} else if !want && p.rate() != 0.0 {
p.pause();
}
}
}));
}
if let Some(t) = time {
let p = player.clone();
node.own(Effect::new(move || {
let want = t.get();
let now = unsafe { seconds(p.currentTime()) }.unwrap_or(0.0);
if (now - want).abs() > 0.5 {
unsafe { p.seekToTime(CMTime::with_seconds(want, 600)) };
}
}));
}
if let Some(m) = self.muted {
let p = player.clone();
node.own(Effect::new(move || unsafe { p.setMuted(m()) }));
}
node.hold(watch);
node
}
}
pub fn video_player(path: impl Fn() -> Option<PathBuf> + 'static) -> VideoPlayer {
VideoPlayer {
source: Box::new(move || path().map(|p| file_url(&p))),
playing: None,
time: None,
duration: None,
muted: None,
loops: false,
controls: VideoControls::Inline,
}
}
pub fn video_stream(url: impl Fn() -> Option<String> + 'static) -> VideoPlayer {
let mut player = video_player(|| None);
player.source = Box::new(move || url().and_then(|u| NSURL::URLWithString(&NSString::from_str(&u))));
player
}