#![allow(deprecated)]
use crate::controls::ControlHandle;
use crate::win32::{window_helper as wh, window::build_timer};
use crate::NwgError;
use std::cell::RefCell;
const NOT_BOUND: &'static str = "Timer is not yet bound to a winapi object";
const UNUSABLE_TIMER: &'static str = "Timer parent window was freed";
const BAD_HANDLE: &'static str = "INTERNAL ERROR: Timer handle is not Timer!";
#[deprecated(
since = "1.0.11",
note = "Use AnimationTimer instead. The winapi timer does not have a constant tick and will call your single threaded from another thread."
)]
#[derive(Default)]
pub struct Timer {
pub handle: ControlHandle,
interval: RefCell<u32>,
}
impl Timer {
pub fn builder() -> TimerBuilder {
TimerBuilder {
parent: None,
interval: 100,
stopped: true
}
}
pub fn valid(&self) -> bool {
if self.handle.blank() { return false; }
let (hwnd, _) = self.handle.timer().expect(BAD_HANDLE);
wh::window_valid(hwnd)
}
pub fn interval(&self) -> u32 {
*self.interval.borrow()
}
pub fn set_interval(&self, i: u32) {
*self.interval.borrow_mut() = i;
}
pub fn stop(&self) {
if self.handle.blank() { panic!("{}", NOT_BOUND); }
if !self.valid() { panic!("{}", UNUSABLE_TIMER); }
let (hwnd, id) = self.handle.timer().expect(BAD_HANDLE);
wh::kill_timer(hwnd, id);
}
pub fn start(&self) {
if self.handle.blank() { panic!("{}", NOT_BOUND); }
if !self.valid() { panic!("{}", UNUSABLE_TIMER); }
let (hwnd, id) = self.handle.timer().expect(BAD_HANDLE);
wh::start_timer(hwnd, id, self.interval());
}
}
impl Drop for Timer {
fn drop(&mut self) {
self.handle.destroy();
}
}
pub struct TimerBuilder {
parent: Option<ControlHandle>,
interval: u32,
stopped: bool
}
impl TimerBuilder {
pub fn interval(mut self, interval: u32) -> TimerBuilder {
self.interval = interval;
self
}
pub fn stopped(mut self, stop: bool) -> TimerBuilder {
self.stopped = stop;
self
}
pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> TimerBuilder {
self.parent = Some(p.into());
self
}
pub fn build(self, out: &mut Timer) -> 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("Timer"))
}?;
*out = Default::default();
out.handle = unsafe { build_timer(parent, self.interval, self.stopped) };
out.set_interval(self.interval);
Ok(())
}
}
impl PartialEq for Timer {
fn eq(&self, other: &Self) -> bool {
self.handle == other.handle
}
}