use std::fmt;
use std::rc::Rc;
use waft_foundation::{App, Handle, Listenable};
use crate::framework::{
BuildContext, InheritedWidget, IntoWidget, KeyRef, StatelessWidget, WidgetRef,
};
use crate::view::{View, ViewCollection};
use crate::widgets::transitions::ListenableBuilder;
use crate::windowing::{ViewRequestState, WindowController};
pub struct Window {
pub key: Option<KeyRef>,
pub controller: Handle<WindowController>,
pub child: WidgetRef,
}
impl Window {
pub fn new<K>(controller: Handle<WindowController>, child: impl IntoWidget<K>) -> Window {
Window {
key: None,
controller,
child: child.into_widget(),
}
}
pub fn key(mut self, key: KeyRef) -> Window {
self.key = Some(key);
self
}
}
impl fmt::Debug for Window {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Window")
.field("controller", &self.controller)
.finish_non_exhaustive()
}
}
impl StatelessWidget for Window {
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
let controller = self.controller;
let listenable: Rc<dyn Listenable> = Rc::new(controller);
ListenableBuilder::new(listenable, move |app, _context, child| {
let child = child
.cloned()
.expect("the window's content is passed as the child");
match controller.request(app).state(app) {
ViewRequestState::Arrived(view) => {
WindowScope::new(controller, View::new(Rc::clone(view), child)).into_widget()
}
_ => ViewCollection::new(Vec::new()).into_widget(),
}
})
.child(self.child.clone())
.into_widget()
}
}
pub struct WindowScope {
pub controller: Handle<WindowController>,
pub child: WidgetRef,
}
impl WindowScope {
pub fn new<K>(controller: Handle<WindowController>, child: impl IntoWidget<K>) -> WindowScope {
WindowScope {
controller,
child: child.into_widget(),
}
}
pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<Handle<WindowController>> {
context
.depend_on_inherited_widget_of_exact_type::<WindowScope>(app)
.map(|scope| scope.controller)
}
pub fn of(app: &mut App, context: BuildContext) -> Handle<WindowController> {
WindowScope::maybe_of(app, context)
.expect("WindowScope.of() was called with a context that is not inside a Window")
}
}
impl fmt::Debug for WindowScope {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WindowScope")
.field("controller", &self.controller)
.finish_non_exhaustive()
}
}
impl InheritedWidget for WindowScope {
fn child(&self) -> &WidgetRef {
&self.child
}
fn update_should_notify(&self, old_widget: &WindowScope) -> bool {
self.controller != old_widget.controller
}
}