use crate::object::{Cast, ObjectSubclassIs, ObjectType};
use crate::translate::*;
use crate::{Closure, Object, StaticType, Type, Value};
use std::marker;
use std::mem;
use std::ptr;
use std::{any::Any, collections::HashMap};
use super::SignalId;
#[derive(Debug, PartialEq, Eq)]
pub struct InitializingType<T>(pub(crate) Type, pub(crate) marker::PhantomData<*const T>);
impl<T> IntoGlib for InitializingType<T> {
type GlibType = ffi::GType;
fn into_glib(self) -> ffi::GType {
self.0.into_glib()
}
}
struct PrivateStruct<T: ObjectSubclass> {
imp: T,
instance_data: Option<HashMap<Type, Box<dyn Any + Send + Sync>>>,
}
pub unsafe trait InstanceStruct: Sized + 'static {
type Type: ObjectSubclass;
#[doc(alias = "get_impl")]
fn impl_(&self) -> &Self::Type {
unsafe {
let data = Self::Type::type_data();
let private_offset = data.as_ref().impl_offset();
let ptr: *const u8 = self as *const _ as *const u8;
let imp_ptr = ptr.offset(private_offset);
let imp = imp_ptr as *const Self::Type;
&*imp
}
}
#[doc(alias = "get_class")]
fn class(&self) -> &<Self::Type as ObjectSubclass>::Class {
unsafe { &**(self as *const _ as *const *const <Self::Type as ObjectSubclass>::Class) }
}
fn instance_init(&mut self) {
unsafe {
let obj = from_glib_borrow::<_, Object>(self as *mut _ as *mut gobject_ffi::GObject);
let obj = Borrowed::new(obj.into_inner().unsafe_cast());
let mut obj = InitializingObject(obj);
<<Self::Type as ObjectSubclass>::ParentType as IsSubclassable<Self::Type>>::instance_init(
&mut obj,
);
}
}
}
pub unsafe trait ClassStruct: Sized + 'static {
type Type: ObjectSubclass;
fn class_init(&mut self) {
unsafe {
let base = &mut *(self as *mut _
as *mut crate::Class<<Self::Type as ObjectSubclass>::ParentType>);
<<Self::Type as ObjectSubclass>::ParentType as IsSubclassable<Self::Type>>::class_init(
base,
);
}
}
}
pub unsafe trait IsSubclassable<T: ObjectSubclass>: crate::object::IsClass {
fn class_init(class: &mut crate::Class<Self>);
fn instance_init(instance: &mut InitializingObject<T>);
}
pub unsafe trait IsImplementable<T: ObjectSubclass>: crate::object::IsInterface
where
<Self as ObjectType>::GlibClassType: Copy,
{
fn interface_init(iface: &mut crate::Interface<Self>);
fn instance_init(_instance: &mut InitializingObject<T>);
}
unsafe extern "C" fn interface_init<T: ObjectSubclass, A: IsImplementable<T>>(
iface: ffi::gpointer,
_iface_data: ffi::gpointer,
) where
<A as ObjectType>::GlibClassType: Copy,
{
let iface = &mut *(iface as *mut crate::Interface<A>);
let mut data = T::type_data();
if data.as_ref().parent_ifaces.is_none() {
data.as_mut().parent_ifaces = Some(HashMap::new());
}
{
let copy = Box::new(*iface.as_ref());
data.as_mut()
.parent_ifaces
.as_mut()
.unwrap()
.insert(A::static_type(), Box::into_raw(copy) as ffi::gpointer);
}
A::interface_init(iface);
}
pub trait InterfaceList<T: ObjectSubclass> {
fn iface_infos() -> Vec<(ffi::GType, gobject_ffi::GInterfaceInfo)>;
fn instance_init(_instance: &mut InitializingObject<T>);
}
impl<T: ObjectSubclass> InterfaceList<T> for () {
fn iface_infos() -> Vec<(ffi::GType, gobject_ffi::GInterfaceInfo)> {
vec![]
}
fn instance_init(_instance: &mut InitializingObject<T>) {}
}
impl<T: ObjectSubclass, A: IsImplementable<T>> InterfaceList<T> for (A,)
where
<A as ObjectType>::GlibClassType: Copy,
{
fn iface_infos() -> Vec<(ffi::GType, gobject_ffi::GInterfaceInfo)> {
vec![(
A::static_type().into_glib(),
gobject_ffi::GInterfaceInfo {
interface_init: Some(interface_init::<T, A>),
interface_finalize: None,
interface_data: ptr::null_mut(),
},
)]
}
fn instance_init(instance: &mut InitializingObject<T>) {
A::instance_init(instance);
}
}
macro_rules! interface_list_trait(
($name1:ident, $name2: ident, $($name:ident),*) => (
interface_list_trait!(__impl $name1, $name2; $($name),*);
);
(__impl $($name:ident),+; $name1:ident, $($name2:ident),*) => (
interface_list_trait_impl!($($name),+);
interface_list_trait!(__impl $($name),+ , $name1; $($name2),*);
);
(__impl $($name:ident),+; $name1:ident) => (
interface_list_trait_impl!($($name),+);
interface_list_trait_impl!($($name),+, $name1);
);
);
macro_rules! interface_list_trait_impl(
($($name:ident),+) => (
impl<T: ObjectSubclass, $($name: IsImplementable<T>),+> InterfaceList<T> for ( $($name),+ )
where
$(<$name as ObjectType>::GlibClassType: Copy),+
{
fn iface_infos() -> Vec<(ffi::GType, gobject_ffi::GInterfaceInfo)> {
vec![
$(
(
$name::static_type().into_glib(),
gobject_ffi::GInterfaceInfo {
interface_init: Some(interface_init::<T, $name>),
interface_finalize: None,
interface_data: ptr::null_mut(),
},
)
),+
]
}
fn instance_init(instance: &mut InitializingObject<T>) {
$(
$name::instance_init(instance);
)+
}
}
);
);
interface_list_trait!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S);
pub struct TypeData {
#[doc(hidden)]
pub type_: Type,
#[doc(hidden)]
pub parent_class: ffi::gpointer,
#[doc(hidden)]
pub parent_ifaces: Option<HashMap<Type, ffi::gpointer>>,
#[doc(hidden)]
pub class_data: Option<HashMap<Type, Box<dyn Any + Send + Sync>>>,
#[doc(hidden)]
pub private_offset: isize,
#[doc(hidden)]
pub private_imp_offset: isize,
}
unsafe impl Send for TypeData {}
unsafe impl Sync for TypeData {}
impl TypeData {
#[doc(alias = "get_type")]
pub fn type_(&self) -> Type {
self.type_
}
#[doc(alias = "get_parent_class")]
pub fn parent_class(&self) -> ffi::gpointer {
debug_assert!(!self.parent_class.is_null());
self.parent_class
}
#[doc(alias = "get_parent_interface")]
pub fn parent_interface<I: crate::object::IsInterface>(&self) -> ffi::gpointer {
match self.parent_ifaces {
None => unreachable!("No parent interfaces"),
Some(ref parent_ifaces) => *parent_ifaces
.get(&I::static_type())
.expect("Parent interface not found"),
}
}
#[doc(alias = "get_class_data")]
pub fn class_data<T: Any + Send + Sync + 'static>(&self, type_: Type) -> Option<&T> {
match self.class_data {
None => None,
Some(ref data) => data.get(&type_).and_then(|ptr| ptr.downcast_ref()),
}
}
#[doc(alias = "get_class_data_mut")]
pub unsafe fn class_data_mut<T: Any + Send + Sync + 'static>(
&mut self,
type_: Type,
) -> Option<&mut T> {
match self.class_data {
None => None,
Some(ref mut data) => data.get_mut(&type_).and_then(|v| v.downcast_mut()),
}
}
pub unsafe fn set_class_data<T: Any + Send + Sync + 'static>(&mut self, type_: Type, data: T) {
if self.class_data.is_none() {
self.class_data = Some(HashMap::new());
}
if let Some(ref mut class_data) = self.class_data {
if class_data.get(&type_).is_some() {
panic!("The class_data already contains a key for {}", type_);
}
class_data.insert(type_, Box::new(data));
}
}
#[doc(alias = "get_impl_offset")]
pub fn impl_offset(&self) -> isize {
self.private_offset + self.private_imp_offset
}
}
pub unsafe trait ObjectSubclassType {
fn type_data() -> ptr::NonNull<TypeData>;
#[doc(alias = "get_type")]
fn type_() -> Type;
}
pub trait ObjectSubclass: ObjectSubclassType + Sized + 'static {
const NAME: &'static str;
const ABSTRACT: bool = false;
type Type: ObjectType
+ ObjectSubclassIs<Subclass = Self>
+ FromGlibPtrFull<*mut <Self::Type as ObjectType>::GlibType>
+ FromGlibPtrBorrow<*mut <Self::Type as ObjectType>::GlibType>
+ FromGlibPtrNone<*mut <Self::Type as ObjectType>::GlibType>;
type ParentType: IsSubclassable<Self>
+ FromGlibPtrFull<*mut <Self::ParentType as ObjectType>::GlibType>
+ FromGlibPtrBorrow<*mut <Self::ParentType as ObjectType>::GlibType>
+ FromGlibPtrNone<*mut <Self::ParentType as ObjectType>::GlibType>;
type Interfaces: InterfaceList<Self>;
type Instance: InstanceStruct<Type = Self>;
type Class: ClassStruct<Type = Self>;
fn type_init(_type_: &mut InitializingType<Self>) {}
fn class_init(_klass: &mut Self::Class) {}
fn new() -> Self {
unimplemented!();
}
fn with_class(_klass: &Self::Class) -> Self {
Self::new()
}
fn instance_init(_obj: &InitializingObject<Self>) {}
}
pub trait ObjectSubclassExt: ObjectSubclass {
#[doc(alias = "get_instance")]
fn instance(&self) -> Self::Type;
fn from_instance(obj: &Self::Type) -> &Self;
#[doc(alias = "get_instance_data")]
fn instance_data<U: Any + Send + Sync + 'static>(&self, type_: Type) -> Option<&U>;
}
impl<T: ObjectSubclass> ObjectSubclassExt for T {
fn instance(&self) -> Self::Type {
unsafe {
let data = Self::type_data();
let type_ = data.as_ref().type_();
assert!(type_.is_valid());
let offset = -data.as_ref().impl_offset();
let ptr = self as *const Self as *const u8;
let ptr = ptr.offset(offset);
let ptr = ptr as *mut u8 as *mut <Self::Type as ObjectType>::GlibType;
assert_ne!((*(ptr as *mut gobject_ffi::GObject)).ref_count, 0);
gobject_ffi::g_object_ref(ptr as *mut gobject_ffi::GObject);
from_glib_full(ptr)
}
}
fn from_instance(obj: &Self::Type) -> &Self {
unsafe {
let ptr = obj.as_ptr() as *const Self::Instance;
(*ptr).impl_()
}
}
fn instance_data<U: Any + Send + Sync + 'static>(&self, type_: Type) -> Option<&U> {
unsafe {
let type_data = Self::type_data();
let self_type_ = type_data.as_ref().type_();
assert!(self_type_.is_valid());
let offset = -type_data.as_ref().private_imp_offset;
let ptr = self as *const Self as *const u8;
let ptr = ptr.offset(offset);
let ptr = ptr as *const PrivateStruct<Self>;
let priv_ = &*ptr;
match priv_.instance_data {
None => None,
Some(ref data) => data.get(&type_).and_then(|ptr| ptr.downcast_ref()),
}
}
}
}
pub struct InitializingObject<T: ObjectSubclass>(Borrowed<T::Type>);
impl<T: ObjectSubclass> InitializingObject<T> {
pub unsafe fn as_ref(&self) -> &T::Type {
&self.0
}
pub unsafe fn as_ptr(&self) -> *mut T::Type {
self.0.as_ptr() as *const T::Type as *mut T::Type
}
pub fn set_instance_data<U: Any + Send + Sync + 'static>(&mut self, type_: Type, data: U) {
unsafe {
let type_data = T::type_data();
let self_type_ = type_data.as_ref().type_();
assert!(self_type_.is_valid());
let offset = type_data.as_ref().private_offset;
let ptr = self.0.as_ptr() as *mut u8;
let ptr = ptr.offset(offset);
let ptr = ptr as *mut PrivateStruct<T>;
let priv_ = &mut *ptr;
if priv_.instance_data.is_none() {
priv_.instance_data = Some(HashMap::new());
}
if let Some(ref mut instance_data) = priv_.instance_data {
if instance_data.get(&type_).is_some() {
panic!("The class_data already contains a key for {}", type_);
}
instance_data.insert(type_, Box::new(data));
}
}
}
}
unsafe extern "C" fn class_init<T: ObjectSubclass>(
klass: ffi::gpointer,
_klass_data: ffi::gpointer,
) {
let mut data = T::type_data();
let mut private_offset = data.as_ref().private_offset as i32;
gobject_ffi::g_type_class_adjust_private_offset(klass, &mut private_offset);
(*data.as_mut()).private_offset = private_offset as isize;
{
let gobject_klass = &mut *(klass as *mut gobject_ffi::GObjectClass);
gobject_klass.finalize = Some(finalize::<T>);
}
{
let klass = &mut *(klass as *mut T::Class);
let parent_class = gobject_ffi::g_type_class_peek_parent(klass as *mut _ as ffi::gpointer)
as *mut <T::ParentType as ObjectType>::GlibClassType;
assert!(!parent_class.is_null());
(*data.as_mut()).parent_class = parent_class as ffi::gpointer;
klass.class_init();
T::class_init(klass);
}
}
unsafe extern "C" fn instance_init<T: ObjectSubclass>(
obj: *mut gobject_ffi::GTypeInstance,
klass: ffi::gpointer,
) {
let mut data = T::type_data();
let private_offset = (*data.as_mut()).private_offset;
let ptr = obj as *mut u8;
let priv_ptr = ptr.offset(private_offset);
let priv_storage = priv_ptr as *mut PrivateStruct<T>;
let klass = &*(klass as *const T::Class);
let imp = T::with_class(klass);
ptr::write(
priv_storage,
PrivateStruct {
imp,
instance_data: None,
},
);
T::Instance::instance_init(&mut *(obj as *mut _));
let obj = from_glib_borrow::<_, Object>(obj.cast());
let obj = Borrowed::new(obj.into_inner().unsafe_cast());
let mut obj = InitializingObject(obj);
T::Interfaces::instance_init(&mut obj);
T::instance_init(&obj);
}
unsafe extern "C" fn finalize<T: ObjectSubclass>(obj: *mut gobject_ffi::GObject) {
let mut data = T::type_data();
let private_offset = (*data.as_mut()).private_offset;
let ptr = obj as *mut u8;
let priv_ptr = ptr.offset(private_offset);
let priv_storage = &mut *(priv_ptr as *mut PrivateStruct<T>);
ptr::drop_in_place(&mut priv_storage.imp);
if let Some(instance_data) = priv_storage.instance_data.take() {
drop(instance_data);
}
let parent_class = &*(data.as_ref().parent_class() as *const gobject_ffi::GObjectClass);
if let Some(ref func) = parent_class.finalize {
func(obj);
}
}
pub fn register_type<T: ObjectSubclass>() -> Type {
if mem::align_of::<T>() > 2 * mem::size_of::<usize>() {
panic!(
"Alignment {} of type not supported, bigger than {}",
mem::align_of::<T>(),
2 * mem::size_of::<usize>(),
);
}
unsafe {
use std::ffi::CString;
let type_name = CString::new(T::NAME).unwrap();
if gobject_ffi::g_type_from_name(type_name.as_ptr()) != gobject_ffi::G_TYPE_INVALID {
panic!(
"Type {} has already been registered",
type_name.to_str().unwrap()
);
}
let type_ = from_glib(gobject_ffi::g_type_register_static_simple(
<T::ParentType as StaticType>::static_type().into_glib(),
type_name.as_ptr(),
mem::size_of::<T::Class>() as u32,
Some(class_init::<T>),
mem::size_of::<T::Instance>() as u32,
Some(instance_init::<T>),
if T::ABSTRACT {
gobject_ffi::G_TYPE_FLAG_ABSTRACT
} else {
0
},
));
let mut data = T::type_data();
(*data.as_mut()).type_ = type_;
let private_offset = gobject_ffi::g_type_add_instance_private(
type_.into_glib(),
mem::size_of::<PrivateStruct<T>>(),
);
(*data.as_mut()).private_offset = private_offset as isize;
(*data.as_mut()).private_imp_offset = {
let priv_ = std::mem::MaybeUninit::<PrivateStruct<T>>::uninit();
let ptr = priv_.as_ptr();
let imp_ptr = &(*ptr).imp as *const _ as *const u8;
let ptr = ptr as *const u8;
imp_ptr as isize - ptr as isize
};
let iface_types = T::Interfaces::iface_infos();
for (iface_type, iface_info) in iface_types {
gobject_ffi::g_type_add_interface_static(type_.into_glib(), iface_type, &iface_info);
}
T::type_init(&mut InitializingType::<T>(type_, marker::PhantomData));
type_
}
}
pub(crate) unsafe fn signal_override_class_handler<F>(
name: &str,
type_: ffi::GType,
class_handler: F,
) where
F: Fn(&super::SignalClassHandlerToken, &[Value]) -> Option<Value> + Send + Sync + 'static,
{
let class_handler = Closure::new(move |values| {
let instance = gobject_ffi::g_value_get_object(values[0].to_glib_none().0);
class_handler(&super::SignalClassHandlerToken(instance as *mut _), values)
});
if let Some((signal_id, _)) = SignalId::parse_name(name, from_glib(type_), false) {
gobject_ffi::g_signal_override_class_closure(
signal_id.into_glib(),
type_,
class_handler.to_glib_none().0,
);
} else {
panic!("Signal '{}' not found", name);
}
}
pub(crate) unsafe fn signal_chain_from_overridden(
instance: *mut gobject_ffi::GTypeInstance,
token: &super::SignalClassHandlerToken,
values: &[Value],
) -> Option<Value> {
assert_eq!(instance, token.0);
let mut result = Value::uninitialized();
gobject_ffi::g_signal_chain_from_overridden(
values.as_ptr() as *mut Value as *mut gobject_ffi::GValue,
result.to_glib_none_mut().0,
);
Some(result).filter(|r| r.type_().is_valid() && r.type_() != Type::UNIT)
}