Giter Club home page Giter Club logo

imgui-rs's Introduction

imgui-rs: Rust bindings for Dear ImGui

Build Status Latest release on crates.io Documentation on docs.rs Wrapped Dear ImGui Version

Hello world

ui.window("Hello world")
    .size([300.0, 100.0], Condition::FirstUseEver)
    .build(|| {
        ui.text("Hello world!");
        ui.text("こんにちは世界!");
        ui.text("This...is...imgui-rs!");
        ui.separator();
        let mouse_pos = ui.io().mouse_pos;
        ui.text(format!(
            "Mouse Position: ({:.1},{:.1})",
            mouse_pos[0], mouse_pos[1]
        ));
    });

Main library crates

The core of imgui-rs consists of:

  • imgui: High-level safe API
  • imgui-sys: Low-level unsafe API (automatically generated)

Next, we provide two example renderers, and two example backend platform implementations:

Each of these contain an examples folder showing their usage. Check their respective Cargo.toml to find compatible versions (e.g imgui-glow-renderer/Cargo.toml the [dependencies] describes the compatible glow version and [dev-dependencies] describes the compatible glutin version)

Finally the imgui-examples folder contains examples of how to use the imgui crate itself - this covers general topics like how to show text, how to create buttons, etc - and should be applicable to usage with any backend/renderer.

Features

  • Bindings for Dear ImGui that can be used with safe Rust. Note: API coverage is not 100%, but will keep improving over time.
  • Builder structs for use cases where the original C++ library uses optional function parameters
  • Easy integration with glow/ glium
  • Easy integration with winit and sdl2 (backend platform)
  • Optional support for the freetype font rasterizer and the docking branch

Minimum Support Rust Version (MSRV)

The MSRV for imgui-rs and all of the backend crates is 1.70. We update our MSRV periodically, and issue a minor bump for it.

Choosing a backend platform and a renderer

Almost every application that uses imgui-rs needs two additional components in addition to the main imgui crate: a backend platform, and a renderer.

imgui-rs is not tied to any particular renderer or platform.

The backend platform is responsible for integrating imgui-rs with the operating system and its window management. Its responsibilities include the following:

  • Handling input events (e.g. keyboard, mouse) and updating imgui-rs state accordingly
  • Passing information about the OS window (e.g. size, DPI factor) to imgui-rs
  • Updating the OS-side mouse cursor when imgui-rs requests it

The renderer is responsible for taking generic, renderer-agnostic draw lists generated by imgui-rs, and rendering them using some graphics API. Its responsibilities include the following:

  • Rendering using vertex/index buffers and command lists
  • Handling of DPI factors and scissor rects
  • Texture management

We provide the following renderers as an official source (ie, they will always be up to date and working): imgui-glow-renderer and imgui-glium-renderer.

Additionally, we provide the following backends as an official source (ie, they will always be up to date and working): imgui-winit-support and imgui-sdl2-support.

The most tested platform/renderer combination is imgui-glium-renderer + glium + imgui-winit-support + winit, but this is not the only possible combination. There's also imgui-glow-renderer, which will increasingly replace glium.

Additionally, there are other libraries which provide other kinds of renderers, which may be out of date with imgui-rs releases, but might work well for your use case:

  1. imgui-wgpu
  2. imgui-d3d12-renderer
  3. imgui-dx11-renderer
  4. imgui-gfx-renderer: Deprecated (no longer maintained beyond imgui-rs v0.8). Renderer implementation that uses the gfx crate (not the new gfx-hal crate)
  5. Many more can be found on crates.io either using search or the "dependents" page (the "depends on" text indicates if the crate has been updated for current versions of imgui-rs)

You can also write your own support code if you have a more advanced use case, because imgui-rs is not tied to any specific graphics / OS API.

Compiling and running the demos

git clone https://github.com/imgui-rs/imgui-rs
cd imgui-rs

Main examples are located in the imgui-examples directory. These can be run like so:

# At the reposity root
cargo test

cargo run --example hello_world
cargo run --example test_window
cargo run --example test_window_impl

Examples for the Glow renderer are under the imgui-glow-renderer/examples/ directory. These can be run the same way as any other examples:

cargo test

cargo run --example glow_01_basic

Note to Windows users: You will need to use the MSVC ABI version of the Rust compiler along with its associated dependencies to build this libary and run the examples.

How to contribute

  1. Change or add something

  2. Make sure you're using the latest stable Rust

  3. Run rustfmt to guarantee code style conformance

    rustup component add rustfmt
    cargo fmt
  4. Open a pull request in Github

License

Licensed under either of

at your option.

Uses Dear ImGui and cimgui.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

imgui-rs's People

Contributors

aclysma avatar agersant avatar aloucks avatar bitshifter avatar bjadamson avatar brendanzab avatar dbr avatar dzil123 avatar embersarc avatar gekkio avatar jasper-bekkers avatar jms55 avatar keyboarddanni avatar lwiklendt avatar malikolivier avatar marijns95 avatar michelson avatar orhanbalci avatar repi avatar rob2309 avatar rodrigorc avatar ruifengx avatar sanbox-irl avatar shockham avatar spacemaniac avatar tangmi avatar tetenpapier avatar thomcc avatar toyboot4e avatar twinklebear avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

imgui-rs's Issues

Compilation errors in a isolated hello_world app

Hi when i compile the examples from this repo works fine, but in a isolated custom app failed with the same code, i think is a version problem:

error[E0277]: the trait bound `glium::Display: glium::backend::Facade` is not satisfied
  --> src/support/mod.rs:25:24
   |
25 |     let mut renderer = Renderer::init(&mut imgui, &display).expect("Failed to initialize renderer");
   |                        ^^^^^^^^^^^^^^ the trait `glium::backend::Facade` is not implemented for `glium::Display`
   |
   = note: required by `imgui_glium_renderer::Renderer::init`

error[E0277]: the trait bound `glium::Frame: glium::Surface` is not satisfied
   --> src/support/mod.rs:127:18
    |
127 |         renderer.render(&mut target, ui).expect("Rendering failed");
    |                  ^^^^^^ the trait `glium::Surface` is not implemented for `glium::Frame`

my Cargo.toml looks like:

[dependencies]
imgui = "*"
glium = "*"
imgui-glium-renderer = "*"

Thanks in advance!!!

ImString as String

Is there a way to retrieve the underlying string of ImString?

https://github.com/Gekkio/imgui-rs/blob/master/src/string.rs#L10
It'd probably look something like this:

impl From<ImString> for String {
    fn from(value: ImString) -> String { 
        let mut s = value.0;
        let _ = s.pop();
        s
    }
}

Except also a Referenced version of ImString would be useful, even if it clones the underlying string.
Reasoning is that I want an ui input field to drive some functionality that takes in Strings.

Examples using original ShowTestWindow()

While not all the example code has been converted to Rust, it would be nice to allow the example application to call the native version of the function at least, to allow the user to see and test the features. (perhaps an extra toggle/button in the example code for that)

Should `&mut self` be used for all state modifying functions?

Hi!

I've been playing around with this wrapper for a couple of hours now and I am very impressed so far :) And imgui seems amazing. Thank you so much for this crate!

This is more of a question than a bug report: There are multiple functions that seems like they mutates state that takes a &self. I did expect &mut self. What is the reasoning behind this?

No Push/PopStyleVar()?

Is there a way to push/pop styles, or are we restricted to style_mut? If there's no push/pop, is this limitation of a closure-based API vs a begin()/end() one?

imgui does not work any more

I cloned the latest imgui-rs and the examples draw only white(later found that the little imgui window was not visible but when maximizing the entire window, it all will just go white - note that I cannot move that little window any more, on the latest master) and windows are not responsive to mouse clicks any more.
I switched v0.0.14 and it was working ok, so I decided to bisect and it seems that the issue appeared in one of these 2 commits:

f33567a1dca83060f4535a9dc5c2e8ed8463edb9
43c40849c344642ba73d32d91eb05705d381f6ea

I could not find exactly which commit introduced the issue because some versions of the code were panicking.

API design: string arguments (static)

One design decision that is often discussed is how string arguments are handled. This issue is for discussing static string arguments (= string literals). Also, the discussion considers safe Rust code. As usual, in unsafe code, all bets are off.

First, let's look at the facts:

  • ImGui expects UTF-8 strings with a null terminator. Interior nul characters are therefore not supported, and will truncate the string
  • Invalid UTF-8 will not crash ImGui, and is comparable to a typo in text. A crash is a bug, and should be fixed upstream
  • Rust &str slices are guaranteed to be UTF-8
  • Rust CString values are guaranteed to have a null terminator and no interior nuls
  • Rust supports both string literals with type &'static str (e.g "hello") and byte string literals &'static [u8] (e.g. b"Hello")
  • Rust string literals are UTF-8 with support for interior nuls
  • Rust byte string literals are ASCII + optional arbitrary bytes with escapes
  • Rust source code files are UTF-8

See the Rust reference for more details about string and byte string literals.

Syntax choices

Let's look at some different syntax choices (not considering possible conversion using Into):

  1. ui.text(im_str!("Hello")); (macro)
  2. ui.text(ImStr::new("Hello")); (ImStr)
  3. ui.text(CString::new("Hello").unwrap()); (CString)
  4. ui.text("Hello"); (string)
  5. ui.text("Hello\0"); (string with explicit null terminator)
  6. ui.text(b"Hello"); (byte string)
  7. ui.text(b"Hello\0"); (byte string with explicit null terminator)

Most people would agree with me that number 4 is the optimal syntax. Number 6 doesn't add any value and in fact makes it impossible to use non-ASCII characters in the literal. Numbers 5 and 7 require the library user to remember the null terminator. Number 1 uses a macro, which is a very custom way of doing things. Numbers 2 are 3 are quite similar from a syntax point of view, but by using a custom ImStr type we can guarantee some extra safety, and can avoid the extra error check by handling interior nuls in a different way.

Dynamic allocation

One important question is whether passing a string requires dynamic allocation and copying. Dynamic allocation is required in these situations:

  • The string requires modifications (e.g. adding null terminator, skipping interior nuls)
  • The used type wants to take ownership of the string instead of borrowing it (e.g. CString always makes a copy)

I'm not yet sure if avoiding dynamic allocation is an unnecessary micro-optimization or an important design goal. I think that it should at least be easy to avoid dynamic allocation.

Another question in dynamic allocation is whether it should be explicit or implicit. For example, should we use the Into trait to do conversions to ImStr, and force the library user to call .into() if a conversion requires allocation? In general Rust tends to be explicit about things, so explicit calls would probably be more Rust-like.

Null termination

ImGui requires null terminated strings, while Rust embraces string slices with known sizes and no null termination. Therefore, there's a couple ways to handle null termination (in decreasing order of attractiveness):

  1. Conditional null termination at compile-time
  2. Unconditional null termination at compile-time
  3. Conditional null termination at runtime
  4. Unconditional null termination at runtime
  5. No null termination

Conditional termination means that we don't add a null terminator if the last byte is already null. I don't know a way of doing this at compile-time, so 1 doesn't seem to be possible at the moment. Having no null termination would be hazardous and is not acceptable for safe Rust code.

Interior nuls

Since ImGui uses the nul character for termination, interior nuls will truncate the string. There's a couple of ways to approach this:

  1. Interior nuls are a compile-time error
  2. Interior nuls are skipped at compile-time
  3. Interior nuls are a runtime error
  4. Interior nuls are skipped at runtime
  5. Interior nuls are left as is and will cause truncation

Since interior nuls will not cause any crashes, IMHO number 5 is reasonable. I find this behaviour to be similar to many other situations which Rust considers to be not unsafe, but possibly undesirable.

UTF-8 validity

ImGui wants UTF-8 strings but won't crash if invalid UTF-8 is passed to it. Having a compile-time or runtime guarantee of UTF-8 is nice, but should only be included if it doesn't complicate the API.

If the API uses Rust string literals in some way, UTF-8 is guaranteed at compile-time. Therefore, byte strings or other approaches need to have some value over strings to be worth using.

Comparison of approaches

1. Macro

Dynamic allocation: None
Null termination: By default 4. Unconditional null termination at runtime
Interior nuls: By default 5. Interior nuls are left as is and will cause truncation
UTF-8 validity: Guaranteed at compile-time

The im_str macro expands to code that concatenates a null terminator at compile time, and uses an unsafe constructor to create an ImStr instance:

im_str!("Hello")

basically compiles to

unsafe { ImStr::from_bytes("Hello\0".as_bytes()) }

Pros:

  • Null terminator concatenation is done at compile time
  • Based on string literals, so UTF-8 validity is guaranteed without extra cost (UTF-8 correctness is checked compile-time)
  • No runtime extra costs

Cons:

  • The macro is a bit unwieldy to use

2. ImStr

This just makes the ImStr wrapping explicit, so everything depends on how the literal argument works. See 4, 5, 6 and 7.

3. CString

Dynamic allocation: On every use
Null termination: 4. Unconditional null termination at runtime
Interior nuls: 3. Interior nuls are a runtime error
UTF-8 validity: By default not guaranteed

Pros:

  • IMHO none

Cons:

  • Dynamic allocation
  • Requires handling of runtime NulError
  • Not guaranteed to be UTF-8
  • IMHO does not add any value over a custom type

4. String

Dynamic allocation: On every use
Null termination: By default 4. Unconditional null termination at runtime
Interior nuls: By default 5. Interior nuls are left as is and will cause truncation
UTF-8 validity: Guaranteed at compile-time

Pros:

  • Easy to use and read
  • Guaranteed to be valid UTF-8 at compile-time

Cons:

  • Dynamic allocation
  • Null termination needs to be handled at runtime

5. String with null terminator

Dynamic allocation: Conditional
Null termination: By default 3. Conditional null termination at runtime
Interior nuls: By default 5. Interior nuls are left as is and will cause truncation
UTF-8 validity: Guaranteed at compile-time

Pros:

  • Quite easy to use and read
  • Guaranteed to be valid UTF-8 at compile-time

Cons:

  • Non-ASCII literals are hard to use
  • Library user needs to remember to add the null terminator
  • Null termination needs to be handled at runtime

6. Byte string

Dynamic allocation: On every use
Null termination: By default 4. Unconditional null termination at runtime
Interior nuls: By default 5. Interior nuls are left as is and will cause truncation
UTF-8 validity: By default not guaranteed

Pros:

  • Easy to use if only ASCII is used

Cons:

  • Dynamic allocation
  • Non-ASCII literals are hard to use
  • Not guaranteed to be UTF-8
  • Null termination needs to be handled at runtime

7. Byte string with null terminator

Dynamic allocation: Conditional
Null termination: By default 3. Conditional null termination at runtime
Interior nuls: By default 5. Interior nuls are left as is and will cause truncation
UTF-8 validity: By default not guaranteed

Pros:

  • Quite easy to use if only ASCII is used

Cons:

  • Non-ASCII literals are hard to use
  • Not guaranteed to be UTF-8
  • Library user needs to remember to add the null terminator
  • Null termination needs to be handled at runtime

example without glium

Hello,

Could you please add an example how to initialize this properly without glium?

I have a glutin window, and I saw in imgui-example/example/support/mod.rs at Support::render() that I should be doing something like this:

    let size_points = window.get_inner_size_points().unwrap();
    let size_pixels = window.get_inner_size_pixels().unwrap();

    let ui = self.imgui.frame(size_points, size_pixels, delta_s);

    run_ui(&ui);

    self.renderer.render(&mut target, ui).unwrap();

When I try the equivalent where window is a glutin::Window, at imgui.frame() I get this error:

third-party/cimgui/imgui/imgui.cpp:2047: void ImGui::NewFrame(): Assertion `g.IO.Fonts->Fonts.Size > 0' failed.

Apparently I should initialize the fonts somehow, a non-glium (glutin only) example would be great help.

gfx-renderer panics on macOS

When I use the gfx renderer I get this panic:

thread 'main' panicked at 'Failed to initialize renderer: Pipeline(Program(Vertex(CompilationFailed("ERROR: 0:1: \'\' :  version \'110\' is not supported\nERROR: 0:2: \'\' :  #version required and missing.\nERROR: 0:5: \'attribute\' : syntax error: syntax error\n"))))', src/libcore/result.rs:860

If I switch the 110 shaders out for the 140 ones, it works fine.

Would you accept a PR to either change to the version 140 shaders, or a way to choose between them programmatically?

Rendering bug after a new Texture2D is loaded

Loading an image within a program's main loop will cause visual artifacts to appear in the elements rendered by ImGui. Here is an example using a 256x256 image:

Here is the isolated test case:

#[macro_use]
extern crate glium;
#[macro_use]
extern crate imgui;
extern crate image;


use glium::glutin;
use glium::{DisplayBuild, Surface};
use imgui::ImGui;
use imgui::glium_renderer::Renderer;

use std::io::Cursor;

fn main() {
    let mut count = 0;

    let display = glutin::WindowBuilder::new()
        .build_glium()
        .unwrap();

    let mut imgui = ImGui::init();

    let mut renderer = Renderer::init(&mut imgui, &display).unwrap();

    let mut open = true;
    loop {
        count += 1;

        // make sure it renders properly for the first few frames
        if count > 200 {
           let img_bkup = {
                let image = image::load(Cursor::new(&include_bytes!("test.png")[..]), image::PNG).unwrap().to_rgba();
                let image_dimensions = image.dimensions(); 
                let image = glium::texture::RawImage2d::from_raw_rgba_reversed(image.into_raw(), image_dimensions);
                glium::texture::Texture2d::new(&display, image).unwrap()
           }; 
        }

        let mut target = display.draw();
        target.clear_color(0.2, 0.2, 0.2, 1.0);

        let (width, height) = target.get_dimensions();
        let ui = imgui.frame(width, height, 0.0);

        {
            ui.show_test_window(&mut open);
        }

        renderer.render(&mut target, ui).unwrap();
        target.finish().unwrap();
    }
}

using versions:

imgui = "0.0.7-pre" // also reproducible with 0.0.6 from crates.io
image = "0.0.7"
glium = "0.13"

This line causes the problem: glium::texture::Texture2d::new(&display, image).unwrap()

I've tested images of 256x256 and 512x512 and it is reproducible with all of them.

I suspect that the texture used by ImGui was accidentally freed, and this image is overwriting it -- but I'm not exactly sure. I don't know of a workaround at this point other than to frontload all textures, or reinitialize ImGui at runtime, both of which are less than ideal.

Any insight would be greatly appreciated!

Using custom textures

I was attempting to load a texture from my application into an imgui window using something similar to the following code:

ui.window(im_str!("PPU"))
    .size((150.0, 130.0), ImGuiSetCond_FirstUseEver)
    .resizable(true)
    .build(|| {
        unsafe {
            imgui_sys::igImage(ppu.get_tex_id(), ImVec2::new(160.0, 144.0), ImVec2::new(0.0, 0.0), ImVec2::new(1.0, 1.0), ImVec4::new(0.0, 0.0, 0.0, 1.0), ImVec4::new(1.0, 0.0, 0.0, 1.0));
        }
    });

But it seems custom textures are disallowed by the imgui-rs glium renderer: https://github.com/Gekkio/imgui-rs/blob/master/imgui-glium-renderer/src/lib.rs#L108

I'm wondering what needs to be done for this to get supported?

Use imgui with PistonWindow

I was trying to make imgui work with a PistonWindow and ran into an issue I understand too poorly to fix.

I create my window like this:

  let window: PistonWindow = WindowSettings::new("piston: image", [w, h])
    .exit_on_esc(true)
    .opengl(opengl)
    .build()
    .unwrap();

and then later in the code I try to initialise a mgui_gfx_renderer::Renderer for imgui with this:

let mut renderer = Renderer::init(&mut imgui, &mut window.factory, shaders, window.output_color).unwrap();

I get this error:

expected type `gfx_core::handle::RenderTargetView<_, (gfx_core::format::R8_G8_B8_A8, gfx_core::format::Unorm)>`
              found type `gfx_core::handle::RenderTargetView<_, (gfx_core::format::R8_G8_B8_A8, gfx_core::format::Srgb)>`

I have tried to figure out why the two libraries use different colour formats but I am simply not knowledgeable enough. Can anyone help?

Is there a better, canonical way of building a imgui UI with Piston?

Make properties of window, frame etc

Hello,
if there is a way to access properties of e.g a window such as its size, I was unable to find how to do that.
This would be useful e.g for making an UI that reacts to the window being resized.

A possible API might be to integrate this into the existing builder pattern:

    let mut size = (0.0,0.0);
    ui.window(im_str!("Hello world"))
        .size((900.0, 500.0), ImGuiCond::FirstUseEver)
        .get_size(&size).
        .build(|| {
            // ...
        });

Or the window might be passed to its inner function (which might be weird with the way the API currently works, but might be made ok by passing an immutable object (see also #90):

    let mut size = (0.0,0.0);
    ui.window(im_str!("Hello world"))
        .size((900.0, 500.0), ImGuiCond::FirstUseEver)
        .build(|it: &Ui::Window| {
            // ...
            let zesize = it.get_size();
        });

`tree_node`'s with the same name seem to be linked?

Probably not something that this library is responsible for but.. maybe you know a way to get around this:
Using ui.tree_node recursively, siblings with the same name all open when I click one of them, and they have the same value.
ss
Is this expected?

SDL2 support.

Is there anyway to use this with SDL2 + raw OpenGL? There are already examples for gfx and glium.

bitflags 0.7.1 broke everything.

So, I was very undecided If I should make this issue or not since I'm so new to rust and everything and I didn't want to use the issues pages as a StackExchange, but after some testing and digging around I think I got a reproducible bug here.
I've gone through so many silly mistakes to get here that feels almost criminal to get to the conclusion, but I'll cut to the chase.
I simply tried to use (as in adding it to Cargo.toml and cargo build) your lib through cargo and crates.io (version 0.0.10) and what I got was this:

error[E0034]: multiple applicable items in scope
   --> /home/dovahkiin/.cargo/registry/src/github.com-1ecc6299db9ec823/imgui-0.0.10/src/input.rs:98:24
    |
98  |             self.flags.set(ImGuiInputTextFlags_AlwaysInsertMode, value);
    |                        ^^^ multiple `set` found
...
321 | impl_input_intn!(InputInt4, 4, igInputInt4);
    | -------------------------------------------- in this macro invocation
    |
    = note: candidate #1 is defined in an impl for the type `imgui_sys::ImGuiInputTextFlags`
    = note: candidate #2 is defined in an impl for the type `imgui_sys::ImGuiInputTextFlags`

error: aborting due to 140 previous errors

And the other 140 were very very similar to that one changing only stuff like mGuiInputTextFlags_NoHorizontalScroll, instead of always insert mode, etc. Basically 140 occurrences of the same bug in different 'methods', 'identifiers'??

And after many silly mistakes, I finally got to this next error when trying to build this whole repo (cloning and cargo build), error which in turn I think is what is causing or at least has some relation with the first one:

error: duplicate definitions with name set, #[deny(overlapping_inherent_impls)] on by default
   --> imgui-sys/src/lib.rs:295:5
    |
295 |       pub fn set(&mut self, mask: ImGuiTreeNodeFlags, value: bool) {
    |  _____^ starting here...
296 | |         if value {
297 | |             *self |= mask;
298 | |         } else {
299 | |             *self -= mask;
300 | |         }
301 | |     }
    | |_____^ ...ending here
    |
    = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
    = note: for more information, see issue #36889 <https://github.com/rust-lang/rust/issues/36889>

error: aborting due to 3 previous errors 

And yes, once again the previous 3 errors are the same in different identifiers. I can post the whole logs for both errors if necessary, but I tried it multiple times and they seem easily reproducible.

Environment:

  • OS: Antergos Linux (arch-linux KISS reskin)
  • rustc: 1.15.1 (021bd294c 2017-02-08)
  • cargo: 0.16.0-nightly (6e0c18c 2017-01-27)

imgui-sys version not match

I try to delete my old imgui-rs folder(it success build and run sample already), and git clone from git hub again to use latest versions.

Issue:

imgui-sys
version required:^0.0.2
version found: 0.0.3-pre

After I change to
[dependencies.imgui-sys]
path = "imgui-sys"
version = "*"

It can build again.

However, the output sample exe cannot run smoothly.
The hello_world.exe will crash when I open it. Thanks.
Can you help on it? Thanks.

Relicense under dual MIT/Apache-2.0

This issue was automatically generated. Feel free to close without ceremony if
you do not agree with re-licensing or if it is not possible for other reasons.
Respond to @cmr with any questions or concerns, or pop over to
#rust-offtopic on IRC to discuss.

You're receiving this because someone (perhaps the project maintainer)
published a crates.io package with the license as "MIT" xor "Apache-2.0" and
the repository field pointing here.

TL;DR the Rust ecosystem is largely Apache-2.0. Being available under that
license is good for interoperation. The MIT license as an add-on can be nice
for GPLv2 projects to use your code.

Why?

The MIT license requires reproducing countless copies of the same copyright
header with different names in the copyright field, for every MIT library in
use. The Apache license does not have this drawback. However, this is not the
primary motivation for me creating these issues. The Apache license also has
protections from patent trolls and an explicit contribution licensing clause.
However, the Apache license is incompatible with GPLv2. This is why Rust is
dual-licensed as MIT/Apache (the "primary" license being Apache, MIT only for
GPLv2 compat), and doing so would be wise for this project. This also makes
this crate suitable for inclusion and unrestricted sharing in the Rust
standard distribution and other projects using dual MIT/Apache, such as my
personal ulterior motive, the Robigalia project.

Some ask, "Does this really apply to binary redistributions? Does MIT really
require reproducing the whole thing?" I'm not a lawyer, and I can't give legal
advice, but some Google Android apps include open source attributions using
this interpretation. Others also agree with
it
.
But, again, the copyright notice redistribution is not the primary motivation
for the dual-licensing. It's stronger protections to licensees and better
interoperation with the wider Rust ecosystem.

How?

To do this, get explicit approval from each contributor of copyrightable work
(as not all contributions qualify for copyright, due to not being a "creative
work", e.g. a typo fix) and then add the following to your README:

## License

Licensed under either of

 * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
 * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)

at your option.

### Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any
additional terms or conditions.

and in your license headers, if you have them, use the following boilerplate
(based on that used in Rust):

// Copyright 2016 imgui-rs developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

It's commonly asked whether license headers are required. I'm not comfortable
making an official recommendation either way, but the Apache license
recommends it in their appendix on how to use the license.

Be sure to add the relevant LICENSE-{MIT,APACHE} files. You can copy these
from the Rust repo for a plain-text
version.

And don't forget to update the license metadata in your Cargo.toml to:

license = "MIT/Apache-2.0"

I'll be going through projects which agree to be relicensed and have approval
by the necessary contributors and doing this changes, so feel free to leave
the heavy lifting to me!

Contributor checkoff

To agree to relicensing, comment with :

I license past and future contributions under the dual MIT/Apache-2.0 license, allowing licensees to chose either at their option.

Or, if you're a contributor, you can check the box in this repo next to your
name. My scripts will pick this exact phrase up and check your checkbox, but
I'll come through and manually review this issue later as well.

API requires unnecessary cloning of owned ImStr values

ImStr values cannot be currently shared without cloning, because all the API methods consume the values instead of borrowing them. If the values represent static strings, cloning has basically no runtime cost, but for owned strings this might matter and it's a significant API wart.

This could probably be fixed by having two types: ImStr and ImString, where ImStr represents a borrowed value and ImString an owned one. This duality is similar to CString/CStr, String/str and PathBuf/Path.

Show style windows - is this possible?

I'm using this for gfx support. In the run_ui closure, I try to show the style editor:

ui.show_style_editor(ui.imgui().style_mut());

It doesn't work when ui isn't &mut. But even if it were, imgui() doesn't take &mut self it seems.

Integrated with toy engine `crayon`.

Hi,

I integrated imgui-rs with my toy game engine crayon this morning, it works as excepted, and save me tons of time. I have to say its the most convenient and intuitive GUI crate i could found right now, thank you so much for sharing it.

If someone has an interest in the implementation details, here is the link, it was written basically based on the examples.

call imgui_sys from ui ?

Hi,

is possible to call ig from imgui_sys from ui interface. something like:

            if ui.collapsing_header(im_str!("Menu")).build() {
                ui.imgui::igNextColumn(); // <-- this
                show_user_guide(ui);
            }

BTW, I've sent a Pull Request that implements columns methods

best

compile without GFX support

Hi,

is there a way to build imgui-rs without SDL? I'm only interestedin using the glium support, is there a config/feature I could set in my Cargo.toml to disable the GFX depdencies?

cheers.

Guidelines for creating widgets and examples

I know it is a wrapper over cpp library but it would be nice to have some kind of guidelines for writing custom widgets.

Also I think currently the most useful, but not implemented feature would be custom file system explorer (for selecting files).

Compiling in this repository? (v0.0.15)

I tried to compile in the root directory.

((HEAD detached at v0.0.15)) $ cargo build
   Compiling bitflags v0.9.1
   Compiling gcc v0.3.53
   Compiling imgui-sys v0.0.15 (file:///home/ploppz/work/rust/CRATES/imgui-rs/imgui-sys)
warning: use of deprecated item: gcc::Config has been renamed to gcc::Build
 --> imgui-sys/build.rs:4:5
  |
4 |     gcc::Config::new()
  |     ^^^^^^^^^^^^^^^^
  |
  = note: #[warn(deprecated)] on by default

error: failed to run custom build command for `imgui-sys v0.0.15 (file:///home/ploppz/work/rust/CRATES/imgui-rs/imgui-sys)`
process didn't exit successfully: `/home/ploppz/work/rust/CRATES/imgui-rs/target/debug/build/imgui-sys-67fb8ce33b91128a/build-script-build` (exit code: 101)
--- stdout
TARGET = Some("x86_64-unknown-linux-gnu")
OPT_LEVEL = Some("0")
TARGET = Some("x86_64-unknown-linux-gnu")
HOST = Some("x86_64-unknown-linux-gnu")
TARGET = Some("x86_64-unknown-linux-gnu")
TARGET = Some("x86_64-unknown-linux-gnu")
HOST = Some("x86_64-unknown-linux-gnu")
CXX_x86_64-unknown-linux-gnu = None
CXX_x86_64_unknown_linux_gnu = None
HOST_CXX = None
CXX = None
HOST = Some("x86_64-unknown-linux-gnu")
TARGET = Some("x86_64-unknown-linux-gnu")
HOST = Some("x86_64-unknown-linux-gnu")
CXXFLAGS_x86_64-unknown-linux-gnu = None
CXXFLAGS_x86_64_unknown_linux_gnu = None
HOST_CXXFLAGS = None
CXXFLAGS = None
DEBUG = Some("true")
running: "c++" "-O0" "-ffunction-sections" "-fdata-sections" "-fPIC" "-g" "-m64" "-Wall" "-Wextra" "-o" "/home/ploppz/work/rust/CRATES/imgui-rs/target/debug/build/imgui-sys-1908936d5c7fe71d/out/third-party/cimgui/cimgui/cimgui.o" "-c" "third-party/cimgui/cimgui/cimgui.cpp"
cargo:warning=c++: error: third-party/cimgui/cimgui/cimgui.cpp: No such file or directory
cargo:warning=c++: fatal error: no input files
cargo:warning=compilation terminated.
exit code: 1

--- stderr
thread 'main' panicked at '

Internal error occurred: Command "c++" "-O0" "-ffunction-sections" "-fdata-sections" "-fPIC" "-g" "-m64" "-Wall" "-Wextra" "-o" "/home/ploppz/work/rust/CRATES/imgui-rs/target/debug/build/imgui-sys-1908936d5c7fe71d/out/third-party/cimgui/cimgui/cimgui.o" "-c" "third-party/cimgui/cimgui/cimgui.cpp" with args "c++" did not execute successfully (status code exit code: 1).

', /home/ploppz/.cargo/registry/src/github.com-1ecc6299db9ec823/gcc-0.3.53/src/lib.rs:1659:4
stack backtrace:
   0: std::sys::imp::backtrace::tracing::imp::unwind_backtrace
             at /checkout/src/libstd/sys/unix/backtrace/tracing/gcc_s.rs:49
   1: std::sys_common::backtrace::_print
             at /checkout/src/libstd/sys_common/backtrace.rs:71
   2: std::panicking::default_hook::{{closure}}
             at /checkout/src/libstd/sys_common/backtrace.rs:60
             at /checkout/src/libstd/panicking.rs:381
   3: std::panicking::default_hook
             at /checkout/src/libstd/panicking.rs:397
   4: std::panicking::rust_panic_with_hook
             at /checkout/src/libstd/panicking.rs:611
   5: std::panicking::begin_panic
             at /checkout/src/libstd/panicking.rs:572
   6: std::panicking::begin_panic_fmt
             at /checkout/src/libstd/panicking.rs:522
   7: gcc::fail
             at /home/ploppz/.cargo/registry/src/github.com-1ecc6299db9ec823/gcc-0.3.53/src/lib.rs:1659
   8: gcc::Build::compile
             at /home/ploppz/.cargo/registry/src/github.com-1ecc6299db9ec823/gcc-0.3.53/src/lib.rs:776
   9: build_script_build::main
             at imgui-sys/build.rs:4
  10: __rust_maybe_catch_panic
             at /checkout/src/libpanic_unwind/lib.rs:99
  11: std::rt::lang_start
             at /checkout/src/libstd/panicking.rs:459
             at /checkout/src/libstd/panic.rs:361
             at /checkout/src/libstd/rt.rs:61
  12: main
  13: __libc_start_main
  14: _start

I wanted to build it just to see the rustdocs of

Implement std::ops::Add for ImVec2 (maybe ImVec4 too?)

Ran into this paper cut, I can't think of a reason not to do this. It's not hiding any allocations, I think it's strictly an improvement if this trait were implemented for ImVec2 and ImVec4.

What do you think Gekkio, if I figured out how to implement this would you support it?

Ui::color_edit not ergonmic when using vector libraries

I ran into this when updating to the latest imgui-rs. There used to be Ui::color_edit3 and Ui::color_edit4 methods which took &mut [f32; 3] and &mut [f32;4] parameters respectively.

This has been changed to use EditableColor with an Into trait which automagics the input into the right format. This seems nice in theory but it doesn't appear to work with custom math types like cgmath's Vector3 and Vector4. For example my code looks like:

ui.color_edit("min start color", min_start_col.as_mut()).build();

where as_mut() returns &mut [f32; 4], which worked fine with the explicit ui.color_edit4 method but now fails to compile with the error:

src/particles/generator.rs|333 col 72 error 283| type annotations required: cannot resolve `cgmath::Vector4<f32>: std::convert::AsMut<_>`
||     |
|| 333 |                         ui.color_edit("min start color", min_start_col.as_mut())
||     |                                                                        ^^^^^^

To fix this error I need to change the code to:

ui.color_edit("min start color", min_start_col.as_mut() as &mut [f32; 4]).build();

Which seems like a regression in the ergonomics of imgui-rs to me, unless there is some simpler fix that I'm not aware of.

Provide way to get keyboard input

Hello,
apparently there is no imgui-rs way to capture keyboard input. In the original imgui, there are functions like IsKeyDown, IsKeyPressed etc.
It would be nice to get something similar.

The easiest way would probably be to just expose an accessor function for io.keys_down in combination with io.key_map, to be used in the same way as we can do ui.imgui().mouse_pos(); already.
(I've tried to use this manually, but the io() method is private.)

Use case: capturing the escape button to close my program while testing.

API question: why provide `delta_time` manually?

This is more of a question then of a feature request. I wonder why does the frame function takes delta_time as an argument? This is quite error-prone (you can easily pass a negative amount of time, or milliseconds instead of seconds) and requires manual management of a bit of state.

Why can't ImGui just store a SteadyTime as a field and update it on every frame call?

Support for repetition

In the original ImGui, there is ImGui::PushID(i);/ImGui::PopID(). This allows adding e.g the same UI code for each item of a collection without name clashes.

Probably, it would be more elegant to have some kind of wrapper for collections (though there might be other cases where PushID/PopID is desirable) instead of directly implementing PushID/PopID. Also note that this is more general than just using tree nodes.

If there is already some way of adding UI for each item of a collection, it would be good to add this to an example.

Android support

I am trying to get this package to work within an Android application but I've got a problem with the way it uses g++ instead of gcc to compile the cpp files.

My .cargo/config file includes the following definitions:

[target.armv7-linux-androideabi]
linker = "/Users/tanis/Documents/android-ndk-arm/bin/arm-linux-androideabi-gcc"

[target.aarch64-linux-android]
linker = "/Users/tanis/Documents/android-ndk-arm64/bin/aarch64-linux-android-gcc"

[target.i686-linux-android]
linker = "/Users/tanis/Documents/android-ndk-x86/bin/i686-linux-android-gcc"

and it works fine for sdl2 and all the other C-based crates but when it comes to imgui I get the following error:

error: failed to run custom build command for `imgui-sys v0.0.15`
process didn't exit successfully: `/Users/tanis/Documents/minigame-rust/target/debug/build/imgui-sys-699678620b97622a/build-script-build` (exit code: 101)
--- stdout
TARGET = Some("armv7-linux-androideabi")
OPT_LEVEL = Some("0")
TARGET = Some("armv7-linux-androideabi")
HOST = Some("x86_64-apple-darwin")
TARGET = Some("armv7-linux-androideabi")
TARGET = Some("armv7-linux-androideabi")
HOST = Some("x86_64-apple-darwin")
CXX_armv7-linux-androideabi = None
CXX_armv7_linux_androideabi = None
TARGET_CXX = None
CXX = None
TARGET = Some("armv7-linux-androideabi")
HOST = Some("x86_64-apple-darwin")
CXXFLAGS_armv7-linux-androideabi = None
CXXFLAGS_armv7_linux_androideabi = None
TARGET_CXXFLAGS = None
CXXFLAGS = None
PROFILE = Some("debug")
running: "arm-linux-androideabi-g++" "-O0" "-ffunction-sections" "-fdata-sections" "-fPIC" "-g" "-march=armv7-a" "-march=armv7-a" "-mfpu=vfpv3-d16" "-mfloat-abi=softfp" "-o" "/Users/tanis/Documents/minigame-rust/target/armv7-linux-androideabi/debug/build/imgui-sys-baa2353af33cf674/out/third-party/cimgui/cimgui/cimgui.o" "-c" "third-party/cimgui/cimgui/cimgui.cpp"


failed to execute command: No such file or directory (os error 2)
Is `arm-linux-androideabi-g++` not installed?



--- stderr
thread 'main' panicked at 'explicit panic', /Users/tanis/.cargo/registry/src/github.com-1ecc6299db9ec823/gcc-0.3.51/src/lib.rs:1239:4
note: Run with `RUST_BACKTRACE=1` for a backtrace.

I suppose this is because I've only defined where to find gcc but there's no indication of where g++ lives. Is there any way to achieve that either with cargo or any other way?

low-level glutin and/or gfx-rs support guidance

Hi, I haven't dug into the codebase too much yet, but I see that sdl2 and glium are supported OOTB. I would be interested in seeing what it'd take to get this library to work with glutin and/or gfx-rs (tbh, I'm not sure what the boundary is for imgui, dependencies-wise, between the window/context stuff and actual opengl,etc interfaces like glium or gfx-rs.

If it's pretty straightforward, maybe I can just do a PR for it. But in any case, an opinion would be appreciated.

Thanks!

Examples don't work on OSX

I'm trying to integrate this into a Glium project and am running into issues on OSX. I thought the issue could be with the way I'm integrating it so I tried running the examples and am having issues.
The hello_world example just gives a blank white screen.
The test_window example renders a clickable menu but the mouse cursor doesnt line up with where Imgui thinks the cursor is (you have to click about half a window above where the item is).
It also looks like the alignment is off and part of the menu gets chopped off.
screen shot 2018-01-12 at 3 31 01 pm

I'm on OSX 10.13.2 with rust nightly.

Right way to handle mouse event

What is the best way to handle mouse events within our interface generation code ?
I wanted to interact on buttons when they are hovered and when the mouse is pressed and I have been unable to find a proper way to do that.

The dirty way consists in modifying the support library provided with the examples in order to provide the mouse state to the application:

diff --git a/rust/src/support/mod.rs b/rust/src/support/mod.rs
index 85a9d6c..74321a7 100644
--- a/rust/src/support/mod.rs
+++ b/rust/src/support/mod.rs
@@ -3,13 +3,13 @@ use imgui_gfx_renderer::{Renderer, Shaders};
 use std::time::Instant;

 #[derive(Copy, Clone, PartialEq, Debug, Default)]
-struct MouseState {
-    pos: (i32, i32),
-    pressed: (bool, bool, bool),
-    wheel: f32,
+pub struct MouseState {
+ pub   pos: (i32, i32),
+ pub   pressed: (bool, bool, bool),
+ pub   wheel: f32,
 }

-pub fn run<F: FnMut(&Ui) -> bool>(title: String, clear_color: [f32; 4], mut run_ui: F) {
+pub fn run<F: FnMut(&Ui, &MouseState) -> bool>(title: String, clear_color: [f32; 4], mut run_ui: F) {
     use gfx::{self, Device};
     use gfx_window_glutin;
     use glutin::{self, GlContext};
@@ -135,7 +135,7 @@ pub fn run<F: FnMut(&Ui) -> bool>(title: String, clear_color: [f32; 4], mut run_
         let size_pixels = window.get_inner_size_pixels().unwrap();

         let ui = imgui.frame(size_points, size_pixels, delta_s);
-        if !run_ui(&ui) {
+        if !run_ui(&ui, &mouse_state) { 
             break;
         }

and in the code of the interface to use stuff in the sys namespace (is_item_hovered does not work when mouse is pressed) :

 if sys::igIsItemHovered(sys::ImGuiHoveredFlags::AllowWhenBlockedByPopup | sys::ImGuiHoveredFlags::AllowWhenBlockedByActiveItem) && mouse.pressed.0 {
 ...
}

But I guess it is not the good way to do that ...

Examples panicking after update to glutin 0.17

This commit caused imgui-rs test_window and test_window_impl to panic (on windows at least, haven't tried on linux).

It adds an unimplemented call to handle a resize event, this is what is causing the application to panic, see:

thread 'main' panicked at 'not yet implemented', examples\support\mod.rs:40:37
stack backtrace:
   0: std::sys_common::backtrace::_print
             at C:\projects\rust\src\libstd\sys_common\backtrace.rs:94
   1: std::panicking::default_hook::{{closure}}
             at C:\projects\rust\src\libstd\panicking.rs:379
   2: std::panicking::default_hook
             at C:\projects\rust\src\libstd\panicking.rs:396
   3: std::panicking::rust_panic_with_hook
             at C:\projects\rust\src\libstd\panicking.rs:610
   4: std::panicking::begin_panic<str*>
             at C:\projects\rust\src\libstd\panicking.rs:571
   5: test_window_impl::support::run::{{closure}}<closure>
             at .\examples\support\mod.rs:40
   6: winit::platform::platform::events_loop::EventsLoop::poll_events<closure>
             at C:\Users\Utilisateur\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.7.5\src\platform\windows\events_loop.rs:154
   7: winit::EventsLoop::poll_events<closure>
             at C:\Users\Utilisateur\.cargo\registry\src\github.com-1ecc6299db9ec823\winit-0.7.5\src\lib.rs:219
   8: test_window_impl::support::run<closure>
             at .\examples\support\mod.rs:33
   9: test_window_impl::main
             at .\examples\test_window_impl.rs:113
  10: panic_unwind::__rust_maybe_catch_panic
             at C:\projects\rust\src\libpanic_unwind\lib.rs:98
  11: std::rt::lang_start
             at C:\projects\rust\src\libstd\rt.rs:54
  12: main
  13: __scrt_common_main_seh
             at f:\dd\vctools\crt\vcstartup\src\startup\exe_common.inl:259
  14: BaseThreadInitThunk
error: process didn't exit successfully: `C:\Danny\imgui-rs\target\debug\examples\test_window_impl.exe` (exit code: 101)

support/mod.rs traits not satisfied in function calls

Using your support/mod.rs brings up problems:

src/support/mod.rs:26:24: 26:38 error: the trait bound `glium::GlutinFacade: glium::backend::Facade` is not satisfied [E0277]
src/support/mod.rs:26         let renderer = Renderer::init(&mut imgui, &display).unwrap();
                                         ^~~~~~~~~~~~~~
src/support/mod.rs:26:24: 26:38 help: run `rustc --explain E0277` to see a detailed explanation
src/support/mod.rs:26:24: 26:38 note: required by `imgui::glium_renderer::Renderer::init`
src/support/mod.rs:87:23: 87:29 error: the trait bound `glium::Frame: glium::Surface` is not satisfied [E0277]
src/support/mod.rs:87         self.renderer.render(&mut target, ui).unwrap();
                                        ^~~~~~
src/support/mod.rs:87:23: 87:29 help: run `rustc --explain E0277` to see a detailed explanation
error: aborting due to 2 previous errors

[dependencies]
imgui = "0.0.9"
time = "0.1"
glium = "0.15.0"

Code from support/mod.rs torn from your latest release. Looking back at the 0.0.9 release, it doesn't seem to have changed.

Custom drawing

Hi there;
As far as I understand it is not possible to do custom drawing with current wrapper. Do you plan to integrate custom drawing capabilities?

does it support Arabic language? RTL

hello and thanks for your work
i want to ask that does it support Arabic language? RTL and how?

because when i write a word like مرحبا it shows like ????????

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.