Skip to content

Commit 9b3936f

Browse files
gdk: Implement Value traits for Key
There is no way to have proper value checking for Key, so we just assumes it is used in a correct use case. Fixes #972
1 parent 9af130d commit 9b3936f

File tree

1 file changed

+52
-1
lines changed

1 file changed

+52
-1
lines changed

gdk4/src/keys.rs

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Take a look at the license at the top of the repository in the LICENSE file.
22

33
use glib::translate::*;
4-
use glib::GString;
4+
use glib::{value::*, GString, Type, Value};
55

66
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
77
// rustdoc-stripper-ignore-next
@@ -4662,3 +4662,54 @@ impl IntoGlib for Key {
46624662
self.0
46634663
}
46644664
}
4665+
4666+
impl ValueType for Key {
4667+
type Type = u32;
4668+
}
4669+
4670+
unsafe impl<'a> FromValue<'a> for Key {
4671+
type Checker = glib::value::GenericValueTypeChecker<Key>;
4672+
4673+
unsafe fn from_value(value: &'a Value) -> Self {
4674+
let res: u32 = glib::gobject_ffi::g_value_get_uint(value.to_glib_none().0);
4675+
// As most of gdk_keyval_ apis don't really do any check for the input value (the key number)
4676+
// other than gdk_keyval_from_name, it is safe to not do any checks and assume people will not mis-use it
4677+
Key::from_glib(res)
4678+
}
4679+
}
4680+
4681+
impl ToValue for Key {
4682+
fn to_value(&self) -> Value {
4683+
let value = Value::for_value_type::<Self>();
4684+
unsafe {
4685+
glib::gobject_ffi::g_value_set_uint(value.to_glib_none().0 as *mut _, self.into_glib());
4686+
}
4687+
value
4688+
}
4689+
4690+
fn value_type(&self) -> Type {
4691+
Type::U32
4692+
}
4693+
}
4694+
4695+
// TODO: Drop once https://github.com/gtk-rs/gtk-rs-core/issues/612
4696+
impl glib::StaticType for Key {
4697+
fn static_type() -> Type {
4698+
Type::U32
4699+
}
4700+
}
4701+
4702+
#[cfg(test)]
4703+
mod test {
4704+
use super::*;
4705+
4706+
#[std::prelude::v1::test]
4707+
fn test_key_value() {
4708+
let key = Key::KP_Enter;
4709+
let value = key.to_value();
4710+
4711+
assert_eq!(value.get::<u32>(), Ok(Key::KP_Enter.into_glib()));
4712+
assert_eq!(unsafe { Key::from_value(&value) }, key);
4713+
assert_eq!(unsafe { Key::from_glib(value.get::<u32>().unwrap()) }, key);
4714+
}
4715+
}

0 commit comments

Comments
 (0)