use super::control_handle::ControlHandle;
use crate::NwgError;
use crate::win32::{window::build_notice, window_helper as wh};
const NOT_BOUND: &'static str = "Notice is not yet bound to a winapi object";
const UNUSABLE_NOTICE: &'static str = "Notice parent window was freed";
const BAD_HANDLE: &'static str = "INTERNAL ERROR: Notice handle is not Notice!";
#[derive(Default, PartialEq, Eq)]
pub struct Notice {
pub handle: ControlHandle,
}
impl Notice {
pub fn builder() -> NoticeBuilder {
NoticeBuilder { parent: None }
}
pub fn create<C: Into<ControlHandle>>(parent: C) -> Result<Notice, NwgError> {
let mut notice = Self::default();
Self::builder().parent(parent).build(&mut notice)?;
Ok(notice)
}
pub fn valid(&self) -> bool {
if self.handle.blank() {
return false;
}
let (hwnd, _) = self.handle.notice().expect(BAD_HANDLE);
wh::window_valid(hwnd)
}
pub fn window_handle(&self) -> Option<ControlHandle> {
match self.valid() {
true => Some(ControlHandle::Hwnd(self.handle.notice().unwrap().0)),
false => None,
}
}
pub fn set_window_handle<C: Into<ControlHandle>>(&mut self, window: C) {
if self.handle.blank() {
panic!("{}", NOT_BOUND);
}
let hwnd = window
.into()
.hwnd()
.expect("New notice parent is not a window control");
let (_, id) = self.handle.notice().expect(BAD_HANDLE);
self.handle = ControlHandle::Notice(hwnd, id);
}
pub fn sender(&self) -> NoticeSender {
if self.handle.blank() {
panic!("{}", NOT_BOUND);
}
if !self.valid() {
panic!("{}", UNUSABLE_NOTICE);
}
let (hwnd, id) = self.handle.notice().expect(BAD_HANDLE);
NoticeSender {
hwnd: hwnd as usize,
id,
}
}
}
impl Drop for Notice {
fn drop(&mut self) {
self.handle.destroy();
}
}
#[derive(Clone, Copy)]
pub struct NoticeSender {
hwnd: usize,
id: u32,
}
impl NoticeSender {
pub fn notice(&self) {
use winapi::shared::minwindef::{LPARAM, WPARAM};
use winapi::shared::windef::HWND;
use winapi::um::winuser::SendNotifyMessageW;
unsafe {
SendNotifyMessageW(
self.hwnd as HWND,
wh::NOTICE_MESSAGE,
self.id as WPARAM,
self.hwnd as LPARAM,
);
}
}
}
pub struct NoticeBuilder {
parent: Option<ControlHandle>,
}
impl NoticeBuilder {
pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> NoticeBuilder {
self.parent = Some(p.into());
self
}
pub fn build(self, out: &mut Notice) -> Result<(), NwgError> {
let parent = match self.parent {
Some(p) => match p.hwnd() {
Some(handle) => Ok(handle),
None => Err(NwgError::control_create("Wrong parent type")),
},
None => Err(NwgError::no_parent("Notice")),
}?;
out.handle = build_notice(parent);
Ok(())
}
}