1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
// SPDX-License-Identifier: MPL-2.0
//! A safe wrapper over *[libui-ng-sys]*.
//!
//! ## Background
//!
//! *[libui]* is a C library that provides a neutral interface to native GUI technologies (e.g.,
//! windows, widgets) on major OSes. *[libui-ng]* is the "next generation" of *libui*, developed and
//! maintained separately. *libui-ng-sys* provides Rust bindings to *libui-ng*, and *boing* is a
//! safe yet fairly unopinionated layer on top of *libui-ng-sys*.
//!
//! ## Usage
//!
//! To get started with *boing*, see the [`Ui`] struct.
//!
//! ## Examples
//!
//! ```no_run
//! # fn main() -> Result<(), boing::Error> {
//! # use boing::Ui;
//! #
//! let ui = Ui::new()?;
//!
//! // Append a drop-down menu labeled "File" to the menubar of all windows created with
//! // `has_menubar` set to `true`; see [`Ui::create_window`] for more information.
//! let file_menu = ui.create_menu("File")?;
//! // Append a menu item labeled "Quit" (in English) to the previously-created file menu. This
//! // "Quit" item will exit the application when clicked.
//! file_menu.push_quit_item()?;
//!
//! // Create a 200x200 pixel window titled "Hello World!" with a menubar that exits the application
//! // when closed.
//! let window = ui.create_window("Hello World!", 200u16, 200u16, true, true)?;
//! // Create a button labeled "Press Me!" and set it as the main child control of the
//! // previously-created window.
//! window.set_child(ui.create_pushbutton("Press Me!")?);
//! // Present the window to the user. Calling this method is necessary for the window to appear at
//! // all.
//! window.show();
//!
//! // Enter the UI event loop. As [`Ui::run`] borrows immutably, this can be called again.
//! ui.run();
//! #
//! # Ok(())
//! # }
//! ```
//!
//! For more examples, including a control gallery, see the *[boing-examples]* crate.
//!
//! [libui-ng-sys]: https://crates.io/crates/libui-ng-sys
//! [libui]: https://github.com/andlabs/libui
//! [libui-ng]: https://github.com/libui-ng/libui-ng
//! [examples]: https://github.com/norepimorphism/boing/tree/main/boing-examples
// All *libui-ng-sys* exports violate Rust's naming conventions.
#![allow(non_upper_case_globals)]
#[macro_use]
mod prelude {
pub use std::{ops::DerefMut, os::raw::{c_int, c_uint, c_void}};
pub use boing_internals::*;
pub use libui_ng_sys::*;
pub use crate::{Container, Control, NonNegativeInt, Ui, Widget};
pub trait Sealed {}
pub fn bool_from_libui(value: c_int) -> bool {
// Note: this will only trigger on debug builds.
debug_assert!((value == 0) || (value == 1));
// Many C programs test booleans with `if(_)`, which is shorthand for `if(_ != 0)`, so we
// will replicate that functionality here.
value != 0
}
macro_rules! call_fallible_libui_fn {
($fn:ident( $($arg:expr),* $(,)? )) => {
// We probably need an `unsafe` block here, but we will defer that to the caller of this
// macro (who knows why this is safe to do).
$fn( $($arg),* )
.as_mut()
.ok_or($crate::Error::LibuiFn { name: stringify!($fn), cause: None })
};
}
macro_rules! call_libui_new_fn {
(
ui: $ui:expr,
fn: $fn:ident( $($arg:expr),* $(,)? ) -> $out_ty:ident $(,)?
) => {
// We probably need an `unsafe` block here, but we will defer that to the caller of this
// macro (who knows why this is safe to do).
call_fallible_libui_fn!( $fn($($arg),*) ).map(|ptr| $ui.alloc_object({
// SAFETY: `ptr` is ostensibly a valid control returned by *libui-ng*, and it will
// live until either we destroy it or *libui-ng* is de-initialized.
// Note: this does not necessarily invoke [`Control::new`], in particular if this is
// a non-control widget.
$out_ty::from_ptr($ui, ptr)
}))
};
}
}
pub mod reexports {
//! Re-exported items from dependencies.
macro_rules! reexport {
($krate:ident) => {
pub mod $krate {
#,
").",
)]
pub use ::$krate::*;
}
};
}
#[cfg(feature = "image")]
reexport!(image);
reexport!(libui_ng_sys);
#[cfg(feature = "raw-window-handle")]
reexport!(raw_window_handle);
}
pub mod area;
mod axis;
mod checkbox;
pub mod color;
mod combobox;
mod control;
pub mod font;
pub mod form;
mod grid;
mod group;
pub mod image;
mod label;
pub mod menu;
mod multiline_text_entry;
mod path;
mod progress_bar;
mod pushbutton;
mod radio_buttons;
mod separator;
mod slider;
mod spinbox;
mod tab;
// pub mod table;
mod text_entry;
mod ui;
mod window;
use std::fmt;
pub use area::Area;
pub use axis::Axis;
pub use checkbox::Checkbox;
pub use color::{Color, Picker as ColorPicker};
pub use combobox::Combobox;
pub use control::Control;
pub use font::{Font, Picker as FontPicker};
pub use form::Form;
pub use grid::Grid;
pub use group::Group;
pub use crate::image::Image;
pub use label::Label;
pub use menu::{Item as MenuItem, Menu};
pub use multiline_text_entry::MultilineTextEntry;
pub use non_negative_int::NonNegativeInt;
pub use path::Path;
pub use progress_bar::ProgressBar;
pub use pushbutton::Pushbutton;
pub use radio_buttons::RadioButtons;
pub use separator::Separator;
pub use slider::Slider;
pub use spinbox::Spinbox;
pub use tab::Tab;
// pub use table::{Model as TableModel, Table};
pub use text_entry::TextEntry;
pub use ui::Ui;
pub use window::Window;
/// The error type returned by fallible *boing* functions.
#[derive(Debug)]
pub enum Error {
/// *libui-ng* is already initialized.
///
/// This error is returned from [`Ui::new`] when called multiple times. Please ensure that
/// [`Ui::new`] is invoked exactly once in your application.
AlreadyInitedLibui,
/// A C string failed to be converted to a Rust string.
ConvertCString(std::str::Utf8Error),
/// A Rust string failed to be converted to a C string.
ConvertRustString(std::ffi::NulError),
/// A *libui-ng* function failed.
LibuiFn {
/// The name of the function that failed.
name: &'static str,
/// The cause, if any, of the failure.
cause: Option<String>,
},
}
impl std::error::Error for Error {}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::AlreadyInitedLibui => {
f.write_str("libui-ng is already initialized")
}
Self::ConvertCString(e) => {
write!(f, "failed to convert C string to Rust string: {e}")
}
Self::ConvertRustString(e) => {
write!(f, "failed to convert Rust string to C string: {e}")
}
Self::LibuiFn { name, cause } => {
write!(f, "libui-ng function {name}() failed")?;
if let Some(cause) = cause {
write!(f, ": {cause}")?;
}
Ok(())
}
}
}
}
/// A graphical element.
pub trait Widget: prelude::Sealed {
/// The corresponding *libui-ng* type.
type Handle;
/// A handle to the underlying *libui-ng* object.
///
/// # Safety
///
/// The returned pointer is guaranteed to be non-null. Beyond that, it is your
/// responsibility to use the handle appropriately. Consulting the *libui-ng*
/// documentation or source code may be helpful, as well as the *boing* or
/// *[libui-ng-sys]* source code.
///
/// [libui-ng-sys]: https://github.com/norepimorphism/libui-ng-sys
#[must_use]
fn as_ptr(&self) -> *mut Self::Handle;
}
/// A control that contains other controls.
pub trait Container: prelude::Sealed {
#[must_use]
fn is_empty(&self) -> bool {
self.child_count().to_libui() == 0
}
/// The number of child controls this control contains.
///
/// On creation, this is 0.
#[must_use]
fn child_count(&self) -> NonNegativeInt;
/// Determines if a child control at the given index exists.
fn contains_child(&self, index: impl Into<NonNegativeInt>) -> bool {
index.into() < self.child_count()
}
/// Removes the child control that was pushed last.
///
/// If there are no children, this does nothing.
///
/// Unlike [`remove_child`](Self::remove_child), this will not invalidate the indices of any
/// other children.
fn pop_child(&self) {
let child_count = self.child_count().to_libui();
let index = child_count - 1;
if index >= 0 {
// SAFETY: `index` is non-negative.
self.remove_child(unsafe { NonNegativeInt::from_libui(index) });
}
}
/// Removes the child control at the given index.
///
/// # Panics
///
/// Panics if the index is out of bounds.
///
/// # Warning
///
/// This action **will** invalidate the indices of all children after this child. For
/// example, after removing a child with index 3, the child previously represented by index
/// 4 now fills index 3, and removing a child with index 4 will then remove the child
/// previously represented by index 5.
fn remove_child(&self, index: impl Into<NonNegativeInt>);
/// Removes all child controls.
fn clear(&self) {
// Note: this is essentially equivalent to calling [`pop_child`] in a loop but is a little
// more efficient.
for i in (0..self.child_count().to_libui()).into_iter().rev() {
self.remove_child(unsafe { NonNegativeInt::from_libui(i) });
}
}
}
mod non_negative_int {
//! The primary non-negative integer type used by *libui-ng*.
use std::os::raw::c_int;
macro_rules! impl_from_uints {
($( $ty:ty )*) => {
$(
impl From<$ty> for NonNegativeInt {
#[inline]
fn from(value: $ty) -> Self {
Self(value.into())
}
}
)*
};
}
macro_rules! impl_try_from_uints {
($( $ty:ty )*) => {
$(
impl TryFrom<$ty> for NonNegativeInt {
type Error = std::num::TryFromIntError;
#[inline]
fn try_from(value: $ty) -> Result<Self, Self::Error> {
value.try_into().map(Self)
}
}
)*
};
}
impl_from_uints!(u8 u16);
impl_try_from_uints!(u32 u128 usize);
impl NonNegativeInt {
/// Initializes a `NonNegativeInt` with a non-negative integer returned from *libui-ng*.
///
/// # Safety
///
/// `value` must be non-negative (i.e., greater than or equal to zero).
pub(crate) unsafe fn from_libui(value: c_int) -> Self {
Self(value)
}
}
/// The primary non-negative integer type used by *libui-ng*.
///
/// Many *boing* functions that interface with the *libui-ng* API accept or return values of
/// this type where non-negative (i.e., greater than or equal to zero) integers are expected.
///
/// # Representation
///
/// As a portable C library, *libui-ng* chose the signed `int` type to represent all integers,
/// including those that are semantically non-negative (e.g., indices, quantities). For this
/// reason, `NonNegativeInt` is represented by the Rust equivalent, `c_int`. However, to
/// preserve *libui-ng* semantics, a `NonNegativeInt` can only be constructed by unsigned
/// integer types like `u8`, `u16`, and `u32`.
///
/// This is also why `NonNegativeInt` implements [`From`] for `u8` and `u16` but [`TryFrom`] for
/// `u32`. An `c_int` cannot encode the full range of positive values of a `u32`, and in
/// particular, the conversion will fail for `u32` values above [`c_int::MAX`].
///
/// # Usage
///
/// In many cases, you can treat `NonNegativeInt` as an opaque type. For example, indices of the
/// type `NonNegativeInt` returned by allocation functions like
/// [`Tab::push_new_page`](crate::tab::push_new_page) can be used as handles without regard to
/// the integer values they contain. But, if you do need to obtain the value of a
/// `NonNegativeInt`, you can use [`as_u32`](Self::as_u32). Note that although a `u32` is
/// returned, the value will still not exceed [`c_int::MAX`].
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
#[repr(transparent)]
pub struct NonNegativeInt(c_int);
impl NonNegativeInt {
/// The inner `c_int`.
///
/// This function should only be used to extract `c_int`s from `NonNegativeInt`s that are
/// guaranteed to be non-negative, such as those created from unsigned integers with
/// [`From`] or [`TryFrom`].
pub(crate) fn to_libui(self) -> c_int {
self.0
}
/// Obtains the value as a `u32`.
///
/// # Panics
///
/// This function may panic in exceptional circumstances such as when a `NonNegativeInt`
/// contains a negative integer returned by *libui-ng* where a non-negative integer was
/// expected.
pub fn as_u32(self) -> u32 {
match u32::try_from(self.0) {
Ok(it) => it,
Err(_) => {
panic!(
"Found a negative integer ({}) where a non-negative integer was expected. \
\
I would greatly appreciate if you submitted an issue to the *boing* \
repository. Thanks! ~norepi",
self.0,
);
}
}
}
}
}