Update documentation and add some tests

This commit is contained in:
Joonas Javanainen 2019-07-12 22:57:11 +03:00
parent c791ad214d
commit 3f7cc4d242
No known key found for this signature in database
GPG Key ID: D39CCA5CB19B9179
17 changed files with 126 additions and 32 deletions

View File

@ -7,8 +7,12 @@ use std::ptr;
use crate::string::{ImStr, ImString};
use crate::Ui;
/// Trait for clipboard backends
pub trait ClipboardBackend {
/// Returns the current clipboard contents as an owned imgui-rs string, or None if the
/// clipboard is empty or inaccessible
fn get(&mut self) -> Option<ImString>;
/// Sets the clipboard contents to the given imgui-rs string slice.
fn set(&mut self, value: &ImStr);
}
@ -67,9 +71,10 @@ pub(crate) unsafe extern "C" fn set_clipboard_text(user_data: *mut c_void, text:
});
}
/// # Clipboard
impl<'ui> Ui<'ui> {
/// Returns the current clipboard contents as text or None if clipboard cannot be accessed or
/// it is empty
/// Returns the current clipboard contents as text, or None if the clipboard is empty or cannot
/// be accessed
pub fn clipboard_text(&self) -> Option<ImString> {
let io = self.io();
io.get_clipboard_text_fn.and_then(|get_clipboard_text_fn| {

View File

@ -101,6 +101,7 @@ impl Context {
clear_current_context();
SuspendedContext(self)
}
/// Returns the path to the ini file, or None if not set
pub fn ini_filename(&self) -> Option<&ImStr> {
let io = self.io();
if io.ini_filename.is_null() {
@ -109,6 +110,9 @@ impl Context {
unsafe { Some(ImStr::from_ptr_unchecked(io.ini_filename)) }
}
}
/// Sets the path to the ini file (default is "imgui.ini")
///
/// Pass None to disable automatic .Ini saving.
pub fn set_ini_filename<T: Into<Option<ImString>>>(&mut self, ini_filename: T) {
let ini_filename = ini_filename.into();
self.io_mut().ini_filename = ini_filename
@ -117,6 +121,7 @@ impl Context {
.unwrap_or(ptr::null());
self.ini_filename = ini_filename;
}
/// Returns the path to the log file, or None if not set
pub fn log_filename(&self) -> Option<&ImStr> {
let io = self.io();
if io.log_filename.is_null() {
@ -125,6 +130,7 @@ impl Context {
unsafe { Some(ImStr::from_ptr_unchecked(io.log_filename)) }
}
}
/// Sets the log filename (default is "imgui_log.txt").
pub fn set_log_filename<T: Into<Option<ImString>>>(&mut self, log_filename: T) {
let log_filename = log_filename.into();
self.io_mut().log_filename = log_filename
@ -133,6 +139,7 @@ impl Context {
.unwrap_or(ptr::null());
self.log_filename = log_filename;
}
/// Returns the backend platform name, or None if not set
pub fn platform_name(&self) -> Option<&ImStr> {
let io = self.io();
if io.backend_platform_name.is_null() {
@ -141,6 +148,7 @@ impl Context {
unsafe { Some(ImStr::from_ptr_unchecked(io.backend_platform_name)) }
}
}
/// Sets the backend platform name
pub fn set_platform_name<T: Into<Option<ImString>>>(&mut self, platform_name: T) {
let platform_name = platform_name.into();
self.io_mut().backend_platform_name = platform_name
@ -149,6 +157,7 @@ impl Context {
.unwrap_or(ptr::null());
self.platform_name = platform_name;
}
/// Returns the backend renderer name, or None if not set
pub fn renderer_name(&self) -> Option<&ImStr> {
let io = self.io();
if io.backend_renderer_name.is_null() {
@ -157,6 +166,7 @@ impl Context {
unsafe { Some(ImStr::from_ptr_unchecked(io.backend_renderer_name)) }
}
}
/// Sets the backend renderer name
pub fn set_renderer_name<T: Into<Option<ImString>>>(&mut self, renderer_name: T) {
let renderer_name = renderer_name.into();
self.io_mut().backend_renderer_name = renderer_name
@ -165,13 +175,16 @@ impl Context {
.unwrap_or(ptr::null());
self.renderer_name = renderer_name;
}
/// Loads settings from a string slice containing settings in .Ini file format
pub fn load_ini_settings(&mut self, data: &str) {
unsafe { sys::igLoadIniSettingsFromMemory(data.as_ptr() as *const _, data.len()) }
}
/// Saves settings to a mutable string buffer in .Ini file format
pub fn save_ini_settings(&mut self, buf: &mut String) {
let data = unsafe { CStr::from_ptr(sys::igSaveIniSettingsToMemory(ptr::null_mut())) };
buf.push_str(&data.to_string_lossy());
}
/// Sets the clipboard backend used for clipboard operations
pub fn set_clipboard_backend(&mut self, backend: Box<dyn ClipboardBackend>) {
use std::borrow::BorrowMut;
let mut clipboard_ctx = Box::new(ClipboardContext::new(backend));
@ -392,6 +405,38 @@ Collapsed=0";
assert_eq!(data.trim(), buf.trim());
}
#[test]
fn test_default_ini_filename() {
use crate::im_str;
let _guard = crate::test::TEST_MUTEX.lock();
let ctx = Context::create();
assert_eq!(ctx.ini_filename(), Some(im_str!("imgui.ini")));
}
#[test]
fn test_set_ini_filename() {
use crate::im_str;
let (_guard, mut ctx) = crate::test::test_ctx();
ctx.set_ini_filename(Some(im_str!("test.ini").to_owned()));
assert_eq!(ctx.ini_filename(), Some(im_str!("test.ini")));
}
#[test]
fn test_default_log_filename() {
use crate::im_str;
let _guard = crate::test::TEST_MUTEX.lock();
let ctx = Context::create();
assert_eq!(ctx.log_filename(), Some(im_str!("imgui_log.txt")));
}
#[test]
fn test_set_log_filename() {
use crate::im_str;
let (_guard, mut ctx) = crate::test::test_ctx();
ctx.set_log_filename(Some(im_str!("test.log").to_owned()));
assert_eq!(ctx.log_filename(), Some(im_str!("test.log")));
}
impl Context {
/// Returns an immutable reference to the inputs/outputs object
pub fn io(&self) -> &Io {
@ -436,10 +481,12 @@ impl Context {
},
}
}
/// Starts a new frame and returns an `Ui` instance for constructing a user interface.
///
/// # Panics
///
/// Panics if the context uses a shared font atlas that is already borrowed
pub fn frame<'ui, 'a: 'ui>(&'a mut self) -> Ui<'ui> {
pub fn frame(&mut self) -> Ui {
// Clear default font if it no longer exists. This could be an error in the future
let default_font = self.io().font_default;
if !default_font.is_null() && self.fonts().get_font(FontId(default_font)).is_none() {

View File

@ -21,6 +21,7 @@ bitflags! {
}
}
/// A font identifier
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct FontId(pub(crate) *const Font);
@ -255,11 +256,12 @@ fn test_font_atlas_memory_layout() {
assert_field_offset!(custom_rect_ids, CustomRectIds);
}
/// A source for binary font data
#[derive(Clone, Debug)]
pub enum FontSource<'a> {
DefaultFontData {
config: Option<FontConfig>,
},
/// Default font included with the library (ProggyClean.ttf)
DefaultFontData { config: Option<FontConfig> },
/// Binary TTF/OTF font data
TtfData {
data: &'a [u8],
size_pixels: f32,
@ -267,18 +269,30 @@ pub enum FontSource<'a> {
},
}
/// Configuration settings for a font
#[derive(Clone, Debug)]
pub struct FontConfig {
/// Size in pixels for the rasterizer
pub size_pixels: f32,
/// Horizontal oversampling
pub oversample_h: i32,
/// Vertical oversampling
pub oversample_v: i32,
/// Align every glyph to pixel boundary
pub pixel_snap_h: bool,
/// Extra spacing (in pixels) between glyphs
pub glyph_extra_spacing: [f32; 2],
/// Offset for all glyphs in this font
pub glyph_offset: [f32; 2],
/// Unicode ranges to use from this font
pub glyph_ranges: FontGlyphRanges,
/// Minimum advance_x for glyphs
pub glyph_min_advance_x: f32,
/// Maximum advance_x for glyphs
pub glyph_max_advance_x: f32,
/// Settings for a custom font rasterizer if used
pub rasterizer_flags: u32,
/// Brighten (>1.0) or darken (<1.0) font output
pub rasterizer_multiply: f32,
}
@ -364,8 +378,13 @@ fn test_font_config_default() {
/// Handle to a font atlas texture
#[derive(Clone, Debug)]
pub struct FontAtlasTexture<'a> {
/// Texture width (in pixels)
pub width: u32,
/// Texture height (in pixels)
pub height: u32,
/// Raw texture data (in bytes).
///
/// The format depends on which function was called to obtain this data.
pub data: &'a [u8],
}

View File

@ -5,6 +5,7 @@ use crate::fonts::glyph::FontGlyph;
use crate::internal::{ImVector, RawCast};
use crate::sys;
/// Runtime data for a single font within a font atlas
#[repr(C)]
pub struct Font {
index_advance_x: ImVector<f32>,
@ -28,6 +29,7 @@ pub struct Font {
unsafe impl RawCast<sys::ImFont> for Font {}
impl Font {
/// Returns the identifier of this font
pub fn id(&self) -> FontId {
FontId(self as *const _)
}

View File

@ -1,6 +1,7 @@
use crate::internal::RawCast;
use crate::sys;
/// A single font glyph
#[derive(Copy, Clone, Debug, PartialEq)]
#[repr(C)]
pub struct FontGlyph {

View File

@ -7,6 +7,7 @@ pub mod font;
pub mod glyph;
pub mod glyph_ranges;
/// # Fonts
impl<'ui> Ui<'ui> {
/// Returns the current font
pub fn current_font(&self) -> &Font {
@ -22,7 +23,7 @@ impl<'ui> Ui<'ui> {
pub fn font_tex_uv_white_pixel(&self) -> [f32; 2] {
unsafe { sys::igGetFontTexUvWhitePixel_nonUDT2().into() }
}
/// Set the font scale of the current window
/// Sets the font scale of the current window
pub fn set_window_font_scale(&self, scale: f32) {
unsafe { sys::igSetWindowFontScale(scale) }
}

View File

@ -118,7 +118,7 @@ impl<'ui> Ui<'ui> {
pub fn key_pressed_amount(&self, key_index: u32, repeat_delay: f32, rate: f32) -> u32 {
unsafe { sys::igGetKeyPressedAmount(key_index as i32, repeat_delay, rate) as u32 }
}
/// Focus keyboard on a widget relative to current position
/// Focuses keyboard on a widget relative to current position
pub fn set_keyboard_focus_here(&self, target_widget: FocusedWidget) {
unsafe {
sys::igSetKeyboardFocusHere(target_widget.as_offset());

View File

@ -142,7 +142,7 @@ impl<'ui> Ui<'ui> {
// references to it
unsafe { sys::igResetMouseDragDelta(button as i32) }
}
/// Get the currently desired mouse cursor type.
/// Returns the currently desired mouse cursor type.
///
/// Returns `None` if no cursor should be displayed
pub fn mouse_cursor(&self) -> Option<MouseCursor> {
@ -158,7 +158,7 @@ impl<'ui> Ui<'ui> {
_ => None,
}
}
/// Set the desired mouse cursor type.
/// Sets the desired mouse cursor type.
///
/// Passing `None` hides the mouse cursor.
pub fn set_mouse_cursor(&self, cursor_type: Option<MouseCursor>) {

View File

@ -1,5 +1,8 @@
//! Internal raw utilities (don't use unless you know what you're doing!)
use std::slice;
/// A generic version of the raw imgui-sys ImVector struct types
#[repr(C)]
pub struct ImVector<T> {
size: i32,
@ -49,15 +52,19 @@ pub trait RawWrapper {
/// Casting from/to a raw type that has the same layout and alignment as the target type
pub unsafe trait RawCast<T>: Sized {
/// Casts an immutable reference from the raw type
unsafe fn from_raw(raw: &T) -> &Self {
&*(raw as *const _ as *const Self)
}
/// Casts a mutable reference from the raw type
unsafe fn from_raw_mut(raw: &mut T) -> &mut Self {
&mut *(raw as *mut _ as *mut Self)
}
/// Casts an immutable reference to the raw type
unsafe fn raw(&self) -> &T {
&*(self as *const _ as *const T)
}
/// Casts a mutable reference to the raw type
unsafe fn raw_mut(&mut self) -> &mut T {
&mut *(self as *mut _ as *mut T)
}

View File

@ -42,29 +42,29 @@ impl<'ui> Ui<'ui> {
pub fn spacing(&self) {
unsafe { sys::igSpacing() }
}
/// Fill a space of `size` in pixels with nothing on the current window.
/// Fills a space of `size` in pixels with nothing on the current window.
///
/// Can be used to move the cursor on the window.
pub fn dummy(&self, size: [f32; 2]) {
unsafe { sys::igDummy(size.into()) }
}
/// Move content position to the right by `Style::indent_spacing`
/// Moves content position to the right by `Style::indent_spacing`
pub fn indent(&self) {
unsafe { sys::igIndent(0.0) };
}
/// Move content position to the right by `width`
/// Moves content position to the right by `width`
pub fn indent_by(&self, width: f32) {
unsafe { sys::igIndent(width) };
}
/// Move content position to the left by `Style::indent_spacing`
/// Moves content position to the left by `Style::indent_spacing`
pub fn unindent(&self) {
unsafe { sys::igUnindent(0.0) };
}
/// Move content position to the left by `width`
/// Moves content position to the left by `width`
pub fn unindent_by(&self, width: f32) {
unsafe { sys::igUnindent(width) };
}
/// Group items together as a single item.
/// Groups items together as a single item.
///
/// May be useful to handle the same mouse event on a group of items, for example.
pub fn group(&self) -> GroupToken {
@ -75,7 +75,7 @@ impl<'ui> Ui<'ui> {
pub fn cursor_pos(&self) -> [f32; 2] {
unsafe { sys::igGetCursorPos_nonUDT2().into() }
}
/// Set the cursor position (in window coordinates).
/// Sets the cursor position (in window coordinates).
///
/// This sets the point on which the next widget will be drawn.
pub fn set_cursor_pos(&self, pos: [f32; 2]) {
@ -91,11 +91,11 @@ impl<'ui> Ui<'ui> {
pub fn cursor_screen_pos(&self) -> [f32; 2] {
unsafe { sys::igGetCursorScreenPos_nonUDT2().into() }
}
/// Set the cursor position (in absolute screen coordinates)
/// Sets the cursor position (in absolute screen coordinates)
pub fn set_cursor_screen_pos(&self, pos: [f32; 2]) {
unsafe { sys::igSetCursorScreenPos(pos.into()) }
}
/// Vertically align text baseline so that it will align properly to regularly frame items.
/// Vertically aligns text baseline so that it will align properly to regularly frame items.
///
/// Call this if you have text on a line before a framed item.
pub fn align_text_to_frame_padding(&self) {

View File

@ -99,6 +99,7 @@ impl Context {
}
}
/// A temporary reference for building the user interface for one frame
pub struct Ui<'ui> {
ctx: &'ui Context,
font_atlas: Option<cell::RefMut<'ui, SharedFontAtlas>>,
@ -111,9 +112,11 @@ fn fmt_ptr() -> *const c_char {
}
impl<'ui> Ui<'ui> {
/// Returns an immutable reference to the inputs/outputs object
pub fn io(&self) -> &Io {
unsafe { &*(sys::igGetIO() as *const Io) }
}
/// Returns an immutable reference to the font atlas
pub fn fonts(&self) -> FontAtlasRef {
match self.font_atlas {
Some(ref font_atlas) => FontAtlasRef::Shared(font_atlas),
@ -123,9 +126,14 @@ impl<'ui> Ui<'ui> {
},
}
}
/// Returns a clone of the user interface style
pub fn clone_style(&self) -> Style {
*self.ctx.style()
}
/// Returns a single style color from the user interface style.
///
/// Use this function if you need to access the colors, but don't want to clone the entire
/// style object.
pub fn style_color(&self, style_color: StyleColor) -> [f32; 4] {
self.ctx.style()[style_color]
}
@ -135,6 +143,7 @@ impl<'ui> Ui<'ui> {
pub fn frame_count(&self) -> i32 {
unsafe { sys::igGetFrameCount() }
}
/// Renders the frame and returns a reference to the resulting draw data
pub fn render(self) -> &'ui DrawData {
unsafe {
sys::igRender();

View File

@ -183,6 +183,7 @@ impl<'a> Iterator for DrawCmdIterator<'a> {
}
}
/// A vertex index
pub type DrawIdx = sys::ImDrawIdx;
#[derive(Copy, Clone, Debug, PartialEq)]
@ -193,6 +194,7 @@ pub struct DrawCmdParams {
pub idx_offset: usize,
}
/// A draw command
pub enum DrawCmd {
Elements {
count: usize,

View File

@ -1,5 +1,6 @@
use std::collections::HashMap;
/// An opaque texture identifier
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
#[repr(transparent)]
pub struct TextureId(usize);

View File

@ -603,9 +603,9 @@ impl<'a> ColorButton<'a> {
/// # Widgets: Color Editor/Picker
impl<'ui> Ui<'ui> {
/// Initialize current options (generally on application startup) if you want to select a
/// default format, picker type, etc. Users will be able to change many settings, unless you
/// use .options(false) in your widget builders.
/// Initializes current color editor/picker options (generally on application startup) if you
/// want to select a default format, picker type, etc. Users will be able to change many
/// settings, unless you use .options(false) in your widget builders.
pub fn set_color_edit_options(&self, flags: ColorEditFlags) {
unsafe {
sys::igSetColorEditOptions(flags.bits() as i32);

View File

@ -54,7 +54,7 @@ impl<'a> ProgressBar<'a> {
self.size = size.into();
self
}
/// Builds the progress bar.
/// Builds the progress bar
pub fn build(self, _: &Ui) {
unsafe {
sys::igProgressBar(

View File

@ -3,7 +3,7 @@ use crate::Ui;
/// # Content region
impl<'ui> Ui<'ui> {
/// Returns the current content boundaries in *window coordinates*
/// Returns the current content boundaries (in *window coordinates*)
pub fn content_region_max(&self) -> [f32; 2] {
unsafe { sys::igGetContentRegionMax_nonUDT2().into() }
}
@ -11,13 +11,13 @@ impl<'ui> Ui<'ui> {
pub fn content_region_avail(&self) -> [f32; 2] {
unsafe { sys::igGetContentRegionAvail_nonUDT2().into() }
}
/// Content boundaries min in *window coordinates*.
/// Content boundaries min (in *window coordinates*).
///
/// Roughly equal to [0.0, 0.0] - scroll.
pub fn window_content_region_min(&self) -> [f32; 2] {
unsafe { sys::igGetWindowContentRegionMin_nonUDT2().into() }
}
/// Content boundaries max in *window coordinates*.
/// Content boundaries max (in *window coordinates*).
///
/// Roughly equal to [0.0, 0.0] + size - scroll.
pub fn window_content_region_max(&self) -> [f32; 2] {

View File

@ -27,19 +27,19 @@ impl<'ui> Ui<'ui> {
pub fn scroll_max_y(&self) -> f32 {
unsafe { sys::igGetScrollMaxY() }
}
/// Set the horizontal scrolling position
/// Sets the horizontal scrolling position
pub fn set_scroll_x(&self, scroll_x: f32) {
unsafe { sys::igSetScrollX(scroll_x) };
}
/// Set the vertical scroll position
/// Sets the vertical scroll position
pub fn set_scroll_y(&self, scroll_y: f32) {
unsafe { sys::igSetScrollY(scroll_y) };
}
/// Adjust vertical scroll position to make the current cursor position visible
/// Adjusts the vertical scroll position to make the current cursor position visible
pub fn set_scroll_here_y(&self) {
unsafe { sys::igSetScrollHereY(0.5) };
}
/// Adjust vertical scroll position to make the current cursor position visible.
/// Adjusts the vertical scroll position to make the current cursor position visible.
///
/// center_y_ratio:
///
@ -49,11 +49,11 @@ impl<'ui> Ui<'ui> {
pub fn set_scroll_here_y_with_ratio(&self, center_y_ratio: f32) {
unsafe { sys::igSetScrollHereY(center_y_ratio) };
}
/// Adjust vertical scroll position to make the given position visible
/// Adjusts the vertical scroll position to make the given position visible
pub fn set_scroll_from_pos_y(&self, local_y: f32) {
unsafe { sys::igSetScrollFromPosY(local_y, 0.5) };
}
/// Adjust vertical scroll position to make the given position visible.
/// Adjusts the vertical scroll position to make the given position visible.
///
/// center_y_ratio:
///