Skip to content

Commit

Permalink
Replace Lazy with OnceLock
Browse files Browse the repository at this point in the history
Removes once_cell dependency
  • Loading branch information
bilelmoussaoui committed Jan 27, 2024
1 parent de10246 commit eaf82b3
Show file tree
Hide file tree
Showing 11 changed files with 87 additions and 84 deletions.
13 changes: 8 additions & 5 deletions examples/custom_editable/custom_tag/imp.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use std::cell::{Cell, RefCell};
use std::{
cell::{Cell, RefCell},
sync::OnceLock,
};

use glib::{clone, once_cell::sync::Lazy, subclass::Signal};
use glib::{clone, subclass::Signal};
use gtk::{glib, prelude::*, subclass::prelude::*};

#[derive(Debug, glib::Properties)]
Expand Down Expand Up @@ -39,13 +42,13 @@ impl ObjectSubclass for CustomTag {
#[glib::derived_properties]
impl ObjectImpl for CustomTag {
fn signals() -> &'static [Signal] {
static SIGNALS: Lazy<Vec<Signal>> = Lazy::new(|| {
static SIGNALS: OnceLock<Vec<Signal>> = OnceLock::new();
SIGNALS.get_or_init(|| {
vec![
Signal::builder("closed").build(),
Signal::builder("clicked").build(),
]
});
SIGNALS.as_ref()
})
}

fn constructed(&self) {
Expand Down
7 changes: 2 additions & 5 deletions examples/expressions/note/imp.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
use gtk::{
glib::{self, once_cell::unsync::OnceCell},
prelude::*,
subclass::prelude::*,
};
use gtk::{glib, prelude::*, subclass::prelude::*};
use std::cell::OnceCell;

use super::Metadata;

Expand Down
17 changes: 8 additions & 9 deletions gdk4-wayland/src/wayland_display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

#[cfg(feature = "wayland_crate")]
#[cfg_attr(docsrs, doc(cfg(feature = "wayland_crate")))]
use glib::{once_cell::sync::Lazy, prelude::*, translate::*, Quark};
use glib::{prelude::*, translate::*, Quark};
#[cfg(all(feature = "v4_4", feature = "egl"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "v4_4", feature = "egl"))))]
use khronos_egl as egl;
Expand All @@ -16,10 +16,6 @@ use wayland_client::{

use crate::WaylandDisplay;

#[cfg(feature = "wayland_crate")]
static WAYLAND_DISPLAY_CONNECTION_QUARK: Lazy<Quark> =
Lazy::new(|| Quark::from_str("gtk-rs-wayland-display-connection-quark"));

impl WaylandDisplay {
#[cfg(all(feature = "v4_4", feature = "egl"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "v4_4", feature = "egl"))))]
Expand Down Expand Up @@ -75,10 +71,13 @@ impl WaylandDisplay {

#[cfg(feature = "wayland_crate")]
pub(crate) fn connection(&self) -> wayland_client::Connection {
use std::sync::OnceLock;
static QUARK: OnceLock<Quark> = OnceLock::new();
let quark =
*QUARK.get_or_init(|| Quark::from_str("gtk-rs-wayland-display-connection-quark"));

unsafe {
match self
.qdata::<Option<wayland_client::Connection>>(*WAYLAND_DISPLAY_CONNECTION_QUARK)
{
match self.qdata::<Option<wayland_client::Connection>>(quark) {
Some(conn) => conn.as_ref().clone().unwrap(),
None => {
let display_ptr =
Expand All @@ -87,7 +86,7 @@ impl WaylandDisplay {
display_ptr as *mut _,
);
let conn = wayland_client::Connection::from_backend(backend);
self.set_qdata(*WAYLAND_DISPLAY_CONNECTION_QUARK, conn.clone());
self.set_qdata(quark, conn.clone());

conn
}
Expand Down
9 changes: 4 additions & 5 deletions gtk4/src/builder_rust_scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -305,10 +305,10 @@ mod tests {

#[crate::test]
fn test_rust_builder_scope_object_during_dispose() {
use glib::subclass::Signal;
use std::sync::OnceLock;
use std::{cell::Cell, rc::Rc};

use glib::{once_cell::sync::Lazy, subclass::Signal};

#[derive(Debug, Default)]
pub struct MyObjectPrivate {
counter: Rc<Cell<u64>>,
Expand All @@ -320,9 +320,8 @@ mod tests {
}
impl ObjectImpl for MyObjectPrivate {
fn signals() -> &'static [Signal] {
static SIGNALS: Lazy<Vec<Signal>> =
Lazy::new(|| vec![Signal::builder("destroyed").build()]);
SIGNALS.as_ref()
static SIGNALS: OnceLock<Vec<Signal>> = OnceLock::new();
SIGNALS.get_or_init(|| vec![Signal::builder("destroyed").build()])
}
fn dispose(&self) {
self.obj().emit_by_name::<()>("destroyed", &[]);
Expand Down
23 changes: 12 additions & 11 deletions gtk4/src/functions.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// Take a look at the license at the top of the repository in the LICENSE file.

use std::{boxed::Box as Box_, mem, pin::Pin, ptr};
use std::{boxed::Box as Box_, pin::Pin, sync::OnceLock};

use glib::{once_cell::sync::Lazy, translate::*, IntoGStr, Quark, Slice, ToValue};
use glib::{translate::*, IntoGStr, Quark, Slice, ToValue};

pub use crate::auto::functions::*;
use crate::{prelude::*, AboutDialog, StyleProvider, Window};
Expand Down Expand Up @@ -87,8 +87,8 @@ pub fn accelerator_parse(accelerator: impl IntoGStr) -> Option<(gdk::Key, gdk::M
assert_initialized_main_thread!();
unsafe {
accelerator.run_with_gstr(|accelerator| {
let mut accelerator_key = mem::MaybeUninit::uninit();
let mut accelerator_mods = mem::MaybeUninit::uninit();
let mut accelerator_key = std::mem::MaybeUninit::uninit();
let mut accelerator_mods = std::mem::MaybeUninit::uninit();
let ret = from_glib(ffi::gtk_accelerator_parse(
accelerator.as_ptr(),
accelerator_key.as_mut_ptr(),
Expand All @@ -115,7 +115,7 @@ pub fn accelerator_parse_with_keycode(
unsafe {
accelerator.run_with_gstr(|accelerator| {
let mut accelerator_key = std::mem::MaybeUninit::uninit();
let mut accelerator_codes_ptr = ptr::null_mut();
let mut accelerator_codes_ptr = std::ptr::null_mut();
let mut accelerator_mods = std::mem::MaybeUninit::uninit();
let success = from_glib(ffi::gtk_accelerator_parse_with_keycode(
accelerator.as_ptr(),
Expand All @@ -127,7 +127,7 @@ pub fn accelerator_parse_with_keycode(
if success {
let mut len = 0;
if !accelerator_codes_ptr.is_null() {
while ptr::read(accelerator_codes_ptr.add(len)) != 0 {
while std::ptr::read(accelerator_codes_ptr.add(len)) != 0 {
len += 1;
}
}
Expand Down Expand Up @@ -173,7 +173,7 @@ pub fn show_uri_full<P: FnOnce(Result<(), glib::Error>) + 'static>(
res: *mut gio::ffi::GAsyncResult,
user_data: glib::ffi::gpointer,
) {
let mut error = ptr::null_mut();
let mut error = std::ptr::null_mut();
let _ = ffi::gtk_show_uri_full_finish(parent_ptr as *mut ffi::GtkWindow, res, &mut error);
let result = if error.is_null() {
Ok(())
Expand Down Expand Up @@ -221,13 +221,14 @@ pub fn show_uri_full_future(
}))
}

static SHOW_ABOUT_DIALOG_QUARK: Lazy<Quark> = Lazy::new(|| Quark::from_str("gtk-rs-about-dialog"));

#[doc(alias = "gtk_show_about_dialog")]
pub fn show_about_dialog<P: IsA<Window>>(parent: Option<&P>, properties: &[(&str, &dyn ToValue)]) {
assert_initialized_main_thread!();
static QUARK: OnceLock<Quark> = OnceLock::new();
let quark = *QUARK.get_or_init(|| Quark::from_str("gtk-rs-about-dialog"));

unsafe {
if let Some(d) = parent.and_then(|p| p.qdata::<AboutDialog>(*SHOW_ABOUT_DIALOG_QUARK)) {
if let Some(d) = parent.and_then(|p| p.qdata::<AboutDialog>(quark)) {
d.as_ref().show();
} else {
let mut builder = glib::Object::builder::<AboutDialog>();
Expand All @@ -241,7 +242,7 @@ pub fn show_about_dialog<P: IsA<Window>>(parent: Option<&P>, properties: &[(&str

// cache the dialog if a parent is set
if let Some(dialog_parent) = parent {
dialog_parent.set_qdata(*SHOW_ABOUT_DIALOG_QUARK, about_dialog.clone());
dialog_parent.set_qdata(quark, about_dialog.clone());
}
about_dialog.show();
};
Expand Down
30 changes: 14 additions & 16 deletions gtk4/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,31 +62,29 @@ where
R: Send + 'static,
{
skip_assert_initialized!();
static TEST_THREAD_WORKER: std::sync::OnceLock<glib::ThreadPool> = std::sync::OnceLock::new();
let pool = TEST_THREAD_WORKER.get_or_init(|| {
let pool = glib::ThreadPool::exclusive(1).unwrap();
pool.push(move || {
crate::init().expect("Tests failed to initialize gtk");
})
.expect("Failed to schedule a test call");
pool
});

use std::{panic, sync::mpsc};

let (tx, rx) = mpsc::sync_channel(1);
TEST_THREAD_WORKER
.push(move || {
tx.send(panic::catch_unwind(function))
.unwrap_or_else(|_| panic!("Failed to return result from thread pool"));
})
.expect("Failed to schedule a test call");
pool.push(move || {
tx.send(panic::catch_unwind(function))
.unwrap_or_else(|_| panic!("Failed to return result from thread pool"));
})
.expect("Failed to schedule a test call");
rx.recv()
.expect("Failed to receive result from thread pool")
.unwrap_or_else(|e| std::panic::resume_unwind(e))
}

static TEST_THREAD_WORKER: glib::once_cell::sync::Lazy<glib::ThreadPool> =
glib::once_cell::sync::Lazy::new(|| {
let pool = glib::ThreadPool::exclusive(1).unwrap();
pool.push(move || {
crate::init().expect("Tests failed to initialize gtk");
})
.expect("Failed to schedule a test call");
pool
});

#[allow(clippy::derived_hash_with_manual_eq)]
#[allow(clippy::too_many_arguments)]
#[allow(clippy::type_complexity)]
Expand Down
11 changes: 7 additions & 4 deletions gtk4/src/subclass/buildable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
// rustdoc-stripper-ignore-next
//! Traits intended for implementing the [`Buildable`](crate::Buildable)
//! interface.
use std::sync::OnceLock;

use glib::{once_cell::sync::Lazy, translate::*, GString, Object, Quark, Value};
use glib::{translate::*, GString, Object, Quark, Value};

use super::PtrHolder;
use crate::{prelude::*, subclass::prelude::*, Buildable, Builder};
Expand Down Expand Up @@ -286,8 +287,6 @@ unsafe extern "C" fn buildable_parser_finished<T: BuildableImpl>(
imp.parser_finished(&from_glib_borrow(builderptr))
}

static BUILDABLE_GET_INTERNAL_CHILD_QUARK: Lazy<Quark> =
Lazy::new(|| Quark::from_str("gtk4-rs-subclass-buildable-get-internal-child"));
unsafe extern "C" fn buildable_get_internal_child<T: BuildableImpl>(
buildable: *mut ffi::GtkBuildable,
builderptr: *mut ffi::GtkBuilder,
Expand All @@ -299,11 +298,15 @@ unsafe extern "C" fn buildable_get_internal_child<T: BuildableImpl>(

let ret = imp.internal_child(&from_glib_borrow(builderptr), &name);

static QUARK: OnceLock<Quark> = OnceLock::new();
let quark =
*QUARK.get_or_init(|| Quark::from_str("gtk4-rs-subclass-buildable-get-internal-child"));

// transfer none: ensure the internal child stays alive for as long as the
// object building it
let ret = ret.into_glib_ptr();
imp.obj().set_qdata(
*BUILDABLE_GET_INTERNAL_CHILD_QUARK,
quark,
PtrHolder(ret, |ptr| {
glib::gobject_ffi::g_object_unref(ptr as *mut _);
}),
Expand Down
12 changes: 6 additions & 6 deletions gtk4/src/subclass/cell_layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
// rustdoc-stripper-ignore-next
//! Traits intended for implementing the [`CellLayout`](crate::CellLayout)
//! interface.
use std::sync::OnceLock;

use glib::{once_cell::sync::Lazy, translate::*, Quark};
use glib::{translate::*, Quark};

use crate::{
prelude::*, subclass::prelude::*, CellArea, CellLayout, CellRenderer, TreeIter, TreeModel,
Expand Down Expand Up @@ -388,9 +389,6 @@ unsafe extern "C" fn cell_layout_set_cell_data_func<T: CellLayoutImpl>(
imp.set_cell_data_func(&*cell, callback)
}

static CELL_LAYOUT_GET_CELLS_QUARK: Lazy<Quark> =
Lazy::new(|| Quark::from_str("gtk-rs-subclass-cell-layout-get-cells"));

unsafe extern "C" fn cell_layout_get_cells<T: CellLayoutImpl>(
cell_layout: *mut ffi::GtkCellLayout,
) -> *mut glib::ffi::GList {
Expand All @@ -399,9 +397,11 @@ unsafe extern "C" fn cell_layout_get_cells<T: CellLayoutImpl>(

let cells = imp.cells();

static QUARK: OnceLock<Quark> = OnceLock::new();
let quark = *QUARK.get_or_init(|| Quark::from_str("gtk-rs-subclass-cell-layout-get-cells"));

// transfer container: list owned by the caller by not the actual content
// so we need to keep the cells around and return a ptr of the list
imp.obj()
.set_qdata(*CELL_LAYOUT_GET_CELLS_QUARK, cells.clone());
imp.obj().set_qdata(quark, cells.clone());
cells.to_glib_container().0
}
17 changes: 7 additions & 10 deletions gtk4/src/subclass/editable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
// rustdoc-stripper-ignore-next
//! Traits intended for implementing the [`Editable`](crate::Editable)
//! interface.
use std::sync::OnceLock;

use glib::{once_cell::sync::Lazy, translate::*, GString, Quark};
use glib::{translate::*, GString, Quark};
use libc::{c_char, c_int};

use crate::{prelude::*, subclass::prelude::*, Editable};
Expand Down Expand Up @@ -319,9 +320,6 @@ unsafe extern "C" fn editable_get_text<T: EditableImpl>(
imp.text().into_glib_ptr()
}

static EDITABLE_GET_DELEGATE_QUARK: Lazy<Quark> =
Lazy::new(|| Quark::from_str("gtk-rs-subclass-editable-get-delegate"));

unsafe extern "C" fn editable_get_delegate<T: EditableImpl>(
editable: *mut ffi::GtkEditable,
) -> *mut ffi::GtkEditable {
Expand All @@ -330,10 +328,10 @@ unsafe extern "C" fn editable_get_delegate<T: EditableImpl>(

let delegate = imp.delegate();

match imp
.obj()
.qdata::<Option<Editable>>(*EDITABLE_GET_DELEGATE_QUARK)
{
static QUARK: OnceLock<Quark> = OnceLock::new();
let quark = *QUARK.get_or_init(|| Quark::from_str("gtk-rs-subclass-editable-get-delegate"));

match imp.obj().qdata::<Option<Editable>>(quark) {
Some(delegate_data) => {
assert_eq!(
delegate_data.as_ref(),
Expand All @@ -342,8 +340,7 @@ unsafe extern "C" fn editable_get_delegate<T: EditableImpl>(
);
}
None => {
imp.obj()
.set_qdata(*EDITABLE_GET_DELEGATE_QUARK, delegate.clone());
imp.obj().set_qdata(quark, delegate.clone());
}
};
delegate.to_glib_none().0
Expand Down
12 changes: 7 additions & 5 deletions gtk4/src/subclass/entry_buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

// rustdoc-stripper-ignore-next
//! Traits intended for subclassing [`EntryBuffer`](crate::EntryBuffer).
use std::sync::OnceLock;

use glib::{once_cell::sync::Lazy, translate::*, GString};
use glib::{translate::*, GString};

use super::PtrHolder;
use crate::{prelude::*, subclass::prelude::*, EntryBuffer};
Expand Down Expand Up @@ -182,9 +183,6 @@ unsafe extern "C" fn entry_buffer_deleted_text<T: EntryBufferImpl>(
imp.deleted_text(position, n_chars)
}

static GET_TEXT_QUARK: Lazy<glib::Quark> =
Lazy::new(|| glib::Quark::from_str("gtk4-rs-subclass-entry-buffer-text"));

unsafe extern "C" fn entry_buffer_get_text<T: EntryBufferImpl>(
ptr: *mut ffi::GtkEntryBuffer,
n_bytes: *mut usize,
Expand All @@ -198,9 +196,13 @@ unsafe extern "C" fn entry_buffer_get_text<T: EntryBufferImpl>(
}
// Ensures that the returned text stays alive for as long as
// the entry buffer instance

static QUARK: OnceLock<glib::Quark> = OnceLock::new();
let quark = *QUARK.get_or_init(|| glib::Quark::from_str("gtk4-rs-subclass-entry-buffer-text"));

let fullptr = ret.into_glib_ptr();
imp.obj().set_qdata(
*GET_TEXT_QUARK,
quark,
PtrHolder(fullptr, |ptr| {
glib::ffi::g_free(ptr as *mut _);
}),
Expand Down
Loading

0 comments on commit eaf82b3

Please sign in to comment.