Convert Figma logo to code with AI

fltk-rs logofltk-rs

Rust bindings for the FLTK GUI library.

1,717
112
1,717
7

Top Related Projects

5,380

Window handling library in pure Rust

24,581

egui: an easy-to-use immediate mode GUI in Rust that runs on both web and native

18,873

Slint is an open-source declarative GUI toolkit to build native user interfaces for Rust, C++, JavaScript, or Python apps.

26,382

A cross-platform GUI library for Rust, inspired by Elm

3,790

The Rust UI-Toolkit.

Quick Overview

FLTK-RS is a Rust binding for the Fast Light Toolkit (FLTK), a cross-platform GUI library. It provides a safe and idiomatic Rust interface to FLTK, allowing developers to create native-looking graphical user interfaces with minimal dependencies.

Pros

  • Cross-platform compatibility (Windows, macOS, Linux)
  • Lightweight and fast, with minimal dependencies
  • Provides both high-level and low-level APIs for flexibility
  • Supports custom widgets and theming

Cons

  • Limited documentation compared to more popular GUI frameworks
  • Smaller community and ecosystem compared to alternatives like GTK or Qt
  • May require some knowledge of the underlying FLTK C++ library for advanced usage
  • Less modern look and feel compared to some newer GUI frameworks

Code Examples

  1. Creating a simple window with a button:
use fltk::{app, button::Button, prelude::*, window::Window};

fn main() {
    let app = app::App::default();
    let mut wind = Window::new(100, 100, 400, 300, "Hello from rust");
    let mut but = Button::new(160, 210, 80, 40, "Click me!");
    wind.end();
    wind.show();
    but.set_callback(|_| println!("Button clicked!"));
    app.run().unwrap();
}
  1. Creating a custom widget:
use fltk::{prelude::*, widget::Widget, draw};

#[derive(Clone)]
struct MyWidget {
    widget: Widget,
}

impl MyWidget {
    pub fn new(x: i32, y: i32, w: i32, h: i32) -> Self {
        let mut w = MyWidget {
            widget: Widget::new(x, y, w, h, None),
        };
        w.widget.draw(move |_| {
            draw::draw_box(draw::BoxType::FlatBox, x, y, w, h, draw::Color::Red);
        });
        w
    }
}

fn main() {
    let app = app::App::default();
    let mut wind = Window::new(100, 100, 400, 300, "Custom Widget");
    let _my_widget = MyWidget::new(160, 210, 80, 40);
    wind.end();
    wind.show();
    app.run().unwrap();
}
  1. Using the image widget:
use fltk::{app, image, prelude::*, window::Window};

fn main() {
    let app = app::App::default();
    let mut wind = Window::new(100, 100, 400, 300, "Image Example");
    let mut image = image::PngImage::load("path/to/image.png").unwrap();
    image.scale(200, 150, true, true);
    wind.set_image(Some(image));
    wind.end();
    wind.show();
    app.run().unwrap();
}

Getting Started

To use FLTK-RS in your Rust project, add the following to your Cargo.toml:

[dependencies]
fltk = "1.4"

Then, in your Rust file:

use fltk::{app, button::Button, prelude::*, window::Window};

fn main() {
    let app = app::App::default();
    let mut wind = Window::new(100, 100, 400, 300, "My First FLTK App");
    let mut but = Button::new(160, 210, 80, 40, "Click me!");
    wind.end();
    wind.show();
    but.set_callback(|_| println!("Hello, World!"));
    app.run().unwrap();
}

Run your project with cargo run to see the GUI application in action.

Competitor Comparisons

5,380

Window handling library in pure Rust

Pros of winit

  • More low-level and lightweight, offering greater flexibility for custom rendering
  • Supports a wider range of platforms, including mobile and web
  • Better integration with other Rust graphics libraries like wgpu and glutin

Cons of winit

  • Requires more boilerplate code to set up basic window functionality
  • Lacks built-in UI widgets and layout management
  • Steeper learning curve for beginners due to its low-level nature

Code comparison

winit:

use winit::{
    event::{Event, WindowEvent},
    event_loop::{ControlFlow, EventLoop},
    window::WindowBuilder,
};

fn main() {
    let event_loop = EventLoop::new();
    let window = WindowBuilder::new().build(&event_loop).unwrap();
    event_loop.run(move |event, _, control_flow| {
        // Event handling logic here
    });
}

fltk-rs:

use fltk::{app, window::Window};

fn main() {
    let app = app::App::default();
    let mut wind = Window::new(100, 100, 400, 300, "Hello from rust-fltk");
    wind.end();
    wind.show();
    app.run().unwrap();
}

The code comparison shows that winit requires more setup for basic window creation and event handling, while fltk-rs provides a more straightforward approach with built-in window management and event loop.

24,581

egui: an easy-to-use immediate mode GUI in Rust that runs on both web and native

Pros of egui

  • Immediate mode GUI, offering more flexibility and easier state management
  • Designed for high performance and low resource usage
  • Cross-platform support with web (WebAssembly) compatibility

Cons of egui

  • Less native look and feel compared to FLTK
  • Smaller ecosystem and fewer built-in widgets
  • Steeper learning curve for developers used to traditional retained-mode GUIs

Code Comparison

egui example:

ui.horizontal(|ui| {
    ui.label("Your name: ");
    ui.text_edit_singleline(&mut name);
});
ui.button("Click me");

FLTK-rs example:

let mut input = Input::new(100, 100, 200, 30, "Your name:");
let mut button = Button::new(100, 150, 80, 30, "Click me");

Summary

egui is an immediate mode GUI library focused on performance and flexibility, while FLTK-rs provides a more traditional retained-mode API with a native look. egui excels in resource efficiency and web compatibility, whereas FLTK-rs offers a more familiar development experience and a larger set of pre-built widgets. The choice between them depends on project requirements, target platforms, and developer preferences.

18,873

Slint is an open-source declarative GUI toolkit to build native user interfaces for Rust, C++, JavaScript, or Python apps.

Pros of Slint

  • Designed for cross-platform development with a focus on embedded systems
  • Uses a declarative UI language, making it easier to create complex layouts
  • Supports hot reloading, enabling faster development iterations

Cons of Slint

  • Newer project with a smaller community and ecosystem
  • Limited widget set compared to more established GUI frameworks
  • Steeper learning curve for developers unfamiliar with declarative UI languages

Code Comparison

Slint example:

export component Button {
    width: 100px;
    height: 30px;
    Text {
        text: "Click me";
    }
}

FLTK-rs example:

use fltk::{prelude::*, *};

let mut btn = button::Button::new(100, 100, 80, 40, "Click me");
btn.set_callback(|_| {
    println!("Button clicked!");
});

Summary

Slint offers a modern approach to UI development with its declarative language and focus on embedded systems, while FLTK-rs provides a more traditional, imperative approach with a larger widget set and established ecosystem. Slint's hot reloading feature can speed up development, but its newer status means less community support compared to FLTK-rs. The choice between the two depends on project requirements, target platforms, and developer preferences.

26,382

A cross-platform GUI library for Rust, inspired by Elm

Pros of iced

  • Pure Rust implementation, offering better safety and easier integration with Rust projects
  • More modern, reactive approach to UI design with a focus on state management
  • Cross-platform support with web (WebAssembly) capabilities

Cons of iced

  • Slower development and less mature compared to FLTK
  • Smaller ecosystem and fewer available widgets out of the box
  • Steeper learning curve for developers new to reactive UI paradigms

Code Comparison

iced example:

use iced::{button, Button, Column, Element, Sandbox, Settings, Text};

struct Counter {
    value: i32,
    increment_button: button::State,
    decrement_button: button::State,
}

impl Sandbox for Counter {
    // ... implementation details
}

fltk-rs example:

use fltk::{app, button::Button, frame::Frame, prelude::*, window::Window};

fn main() {
    let app = app::App::default();
    let mut wind = Window::new(100, 100, 400, 300, "Hello from rust");
    let mut frame = Frame::new(0, 0, 400, 200, "");
    let mut but = Button::new(160, 210, 80, 40, "Click me!");
    // ... event handling and window showing
}

The iced example showcases its reactive approach with a struct representing the application state, while the fltk-rs example demonstrates a more traditional imperative style of UI programming.

3,790

The Rust UI-Toolkit.

Pros of OrbTk

  • Pure Rust implementation, offering better integration with Rust ecosystems
  • Cross-platform support, including web and mobile platforms
  • More modern and flexible widget system

Cons of OrbTk

  • Less mature and stable compared to FLTK-rs
  • Smaller community and fewer resources available
  • Limited native look and feel on different platforms

Code Comparison

OrbTk example:

use orbtk::prelude::*;

fn main() {
    Application::new()
        .window(|ctx| {
            Window::new()
                .title("OrbTk")
                .position((100.0, 100.0))
                .size(420.0, 420.0)
                .child(TextBlock::new().text("Hello World!").build(ctx))
                .build(ctx)
        })
        .run();
}

FLTK-rs example:

use fltk::{app, prelude::*, window::Window};

fn main() {
    let app = app::App::default();
    let mut wind = Window::new(100, 100, 400, 300, "Hello from rust");
    wind.end();
    wind.show();
    app.run().unwrap();
}

Both libraries offer Rust bindings for GUI development, but OrbTk is a pure Rust implementation while FLTK-rs wraps the C++ FLTK library. OrbTk provides a more modern API and widget system, but FLTK-rs benefits from the maturity and stability of the underlying FLTK library. The choice between them depends on specific project requirements and preferences.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

fltk-rs

Documentation Crates.io License Build

Rust bindings for the FLTK 1.4 Graphical User Interface library.

The fltk crate is a cross-platform lightweight gui library which can be statically linked to produce small, self-contained and fast gui applications.

Resources:

Why choose FLTK?

  • Lightweight. Small binary, around 1mb after stripping. Small memory footprint.
  • Speed. Fast to install, fast to build, fast at startup and fast at runtime.
  • Single executable. No DLLs to deploy.
  • Supports old architectures.
  • FLTK's permissive license which allows static linking for closed-source applications.
  • Themeability (5 supported schemes: Base, GTK, Plastic, Gleam and Oxy), and additional theming using fltk-theme.
  • Provides around 80 customizable widgets.
  • Has inbuilt image support.

Here is a list of software using FLTK. For software using fltk-rs, check here.

  • Link to the official FLTK repository.
  • Link to the official documentation.

Usage

Just add the following to your project's Cargo.toml file:

[dependencies]
fltk = "^1.5"

To use the latest changes in the repo:

[dependencies]
fltk = { version = "^1.5", git = "https://github.com/fltk-rs/fltk-rs" }

Or if you have other depenendencies which depend on fltk-rs:

[dependencies]
fltk = "^1.5"

[patch.crates-io]
fltk = { git = "https://github.com/fltk-rs/fltk-rs" }

To use the bundled libs (available for x64 windows (msvc & gnu (msys2-mingw)), x64 & aarch64 linux & macos):

[dependencies]
fltk = { version = "^1.5", features = ["fltk-bundled"] }

The library is automatically built and statically linked to your binary.

An example hello world application:

use fltk::{app, prelude::*, window::Window};

fn main() {
    let app = app::App::default();
    let mut wind = Window::new(100, 100, 400, 300, "Hello from rust");
    wind.end();
    wind.show();
    app.run().unwrap();
}

Another example showing the basic callback functionality:

use fltk::{app, button::Button, frame::Frame, prelude::*, window::Window};

fn main() {
    let app = app::App::default();
    let mut wind = Window::new(100, 100, 400, 300, "Hello from rust");
    let mut frame = Frame::new(0, 0, 400, 200, "");
    let mut but = Button::new(160, 210, 80, 40, "Click me!");
    wind.end();
    wind.show();
    but.set_callback(move |_| frame.set_label("Hello World!")); // the closure capture is mutable borrow to our button
    app.run().unwrap();
}

Please check the examples directory for more examples. You will notice that all widgets are instantiated with a new() method, taking the x and y coordinates, the width and height of the widget, as well as a label which can be left blank if needed. Another way to initialize a widget is using the builder pattern: (The following buttons are equivalent)

use fltk::{button::Button, prelude::*};
let but1 = Button::new(10, 10, 80, 40, "Button 1");

let but2 = Button::default()
    .with_pos(10, 10)
    .with_size(80, 40)
    .with_label("Button 2");

An example of a counter showing use of the builder pattern:

use fltk::{app, button::Button, frame::Frame, prelude::*, window::Window};
fn main() {
    let app = app::App::default();
    let mut wind = Window::default()
        .with_size(160, 200)
        .center_screen()
        .with_label("Counter");
    let mut frame = Frame::default()
        .with_size(100, 40)
        .center_of(&wind)
        .with_label("0");
    let mut but_inc = Button::default()
        .size_of(&frame)
        .above_of(&frame, 0)
        .with_label("+");
    let mut but_dec = Button::default()
        .size_of(&frame)
        .below_of(&frame, 0)
        .with_label("-");
    wind.make_resizable(true);
    wind.end();
    wind.show();
    /* Event handling */
    app.run().unwrap();
}

Alternatively, you can use Flex (for flexbox layouts), Pack or Grid:

use fltk::{app, button::Button, frame::Frame, group::Flex, prelude::*, window::Window};
fn main() {
    let app = app::App::default();
    let mut wind = Window::default().with_size(160, 200).with_label("Counter");
    let mut flex = Flex::default().with_size(120, 140).center_of_parent().column();
    let mut but_inc = Button::default().with_label("+");
    let mut frame = Frame::default().with_label("0");
    let mut but_dec = Button::default().with_label("-");
    flex.end();
    wind.end();
    wind.show();
    app.run().unwrap();
}

Another example:

use fltk::{app, button::Button, frame::Frame, group::Flex, prelude::*, window::Window};

fn main() {
    let app = app::App::default();
    let mut wind = Window::default().with_size(400, 300);
    let mut col = Flex::default_fill().column();
    col.set_margins(120, 80, 120, 80);
    let mut frame = Frame::default();
    let mut but = Button::default().with_label("Click me!");
    col.fixed(&but, 40);
    col.end();
    wind.end();
    wind.show();

    but.set_callback(move |_| frame.set_label("Hello world"));

    app.run().unwrap();
}

Events

Events can be handled using the set_callback method (as above) or the available fltk::app::set_callback() free function, which will handle the default trigger of each widget(like clicks for buttons):

    /* previous hello world code */
    but.set_callback(move |_| frame.set_label("Hello World!"));
    another_but.set_callback(|this_button| this_button.set_label("Works"));
    app.run().unwrap();

Another way is to use message passing:

    /* previous counter code */
    let (s, r) = app::channel::<Message>();

    but_inc.emit(s, Message::Increment);
    but_dec.emit(s, Message::Decrement);
    
    while app.wait() {
        let label: i32 = frame.label().parse().unwrap();
        if let Some(msg) = r.recv() {
            match msg {
                Message::Increment => frame.set_label(&(label + 1).to_string()),
                Message::Decrement => frame.set_label(&(label - 1).to_string()),
            }
        }
    }

For the remainder of the code, check the full example here.

For custom event handling, the handle() method can be used:

    some_widget.handle(move |widget, ev: Event| {
        match ev {
            Event::Push => {
                println!("Pushed!");
                true
            },
            /* other events to be handled */
            _ => false,
        }
    });

Handled or ignored events using the handle method should return true, unhandled events should return false. More examples are available in the fltk/examples directory.

For an alternative event handling mechanism using an immediate-mode approach, check the fltk-evented crate.

Theming

FLTK offers 5 application schemes:

  • Base
  • Gtk
  • Gleam
  • Plastic
  • Oxy

(Additional theming can be found in the fltk-theme crate)

These can be set using the App::with_scheme() method.

let app = app::App::default().with_scheme(app::Scheme::Gleam);

Themes of individual widgets can be optionally modified using the provided methods in the WidgetExt trait, such as set_color(), set_label_font(), set_frame() etc:

    some_button.set_color(Color::Light1); // You can use one of the provided colors in the fltk enums
    some_button.set_color(Color::from_rgb(255, 0, 0)); // Or you can specify a color by rgb or hex/u32 value
    some_button.set_color(Color::from_u32(0xffebee));
    some_button.set_frame(FrameType::RoundUpBox);
    some_button.set_font(Font::TimesItalic);

For default application colors, fltk-rs provides app::background(), app::background2() and app::foreground(). You can also specify the default application selection/inactive colors, font, label size, frame type, scrollbar size, menu line-spacing. Additionally the fltk-theme crate offers some other predefined color maps (dark theme, tan etc) and widget themes which can be loaded into your application.

Build Dependencies

Rust (version > 1.63), CMake (version > 3.15), Git and a C++17 compiler need to be installed and in your PATH for a cross-platform build from source. Ninja is recommended, but not required. This crate also offers a bundled form of fltk on selected x86_64 and aarch64 platforms (Windows (msvc and gnu), MacOS, Linux), this can be enabled using the fltk-bundled feature flag as mentioned in the usage section (this requires curl and tar to download and unpack the bundled libraries).

  • Windows:
    • MSVC: Windows SDK
    • Gnu: No dependencies
  • MacOS: MacOS SDK (installed as part of xcode or the xcode command line tools).
  • Linux/BSD: X11 (and wayland for use-wayland feature flag) and OpenGL development headers need to be installed for development. The libraries themselves are normally available on linux/bsd distros with a graphical user interface.

For Debian-based GUI distributions, that means running:

sudo apt-get install libx11-dev libxext-dev libxft-dev libxinerama-dev libxcursor-dev libxrender-dev libxfixes-dev libpango1.0-dev libgl1-mesa-dev libglu1-mesa-dev

For RHEL-based GUI distributions, that means running:

sudo yum groupinstall "X Software Development" && sudo yum install pango-devel libXinerama-devel libstdc++-static

For Arch-based GUI distributions, that means running:

sudo pacman -S libx11 libxext libxft libxinerama libxcursor libxrender libxfixes pango cairo libgl mesa --needed

For Alpine linux:

apk add pango-dev fontconfig-dev libxinerama-dev libxfixes-dev libxcursor-dev mesa-gl

For NixOS (Linux distribution) this nix-shell environment can be used:

nix-shell --packages rustc cmake git gcc xorg.libXext xorg.libXft xorg.libXinerama xorg.libXcursor xorg.libXrender xorg.libXfixes libcerf pango cairo libGL mesa pkg-config

For Freebsd:

pkg install -y cairo pango fontconfig freetype2 libX11 libXext libXfixes mesa-libs
# building might require setting `CPATH=/usr/local/include` and `LIBRARY_PATH=$LIBRARY_PATH:/usr/local/lib

Runtime Dependencies

  • Windows: None
  • MacOS: None
  • Linux: You need X11 libraries, as well as pango and cairo for drawing (and OpenGL if you want to enable the enable-glwindow feature):
apt-get install -qq --no-install-recommends libx11-6 libxinerama1 libxft2 libxext6 libxcursor1 libxrender1 libxfixes3 libcairo2 libpango-1.0-0 libpangocairo-1.0-0 libpangoxft-1.0-0 libglib2.0-0 libfontconfig1 libglu1-mesa libgl1

Note that if you installed the build dependencies, it will also install the runtime dependencies automatically as well.

Also note that most graphical desktop environments already have these libs already installed. This list can be useful if you want to test your already built package in CI/docker (where there is no graphical user interface).

Features

The following are the features offered by the crate:

  • use-ninja: Uses the ninja build system if available for a faster build, especially on Windows.
  • no-pango: Build without pango support on Linux/BSD, if rtl/cjk font support is not needed.
  • fltk-bundled: Support for bundled versions of cfltk and fltk on selected platforms (requires curl and tar)
  • enable-glwindow: Support for drawing using OpenGL functions.
  • system-libpng: Uses the system libpng
  • system-libjpeg: Uses the system libjpeg
  • system-zlib: Uses the system zlib
  • use-wayland: Uses FLTK's wayland hybrid backend (runs on wayland when present, and on X11 when not present). Requires libwayland-dev, wayland-protocols, libdbus-1-dev, libxkbcommon-dev, libgtk-3-dev (optional, for the GTK-style titlebar), in addition to the X11 development packages. Sample CI.
  • fltk-config: Uses an already installed FLTK's fltk-config to build this crate against. This still requires FLTK 1.4. Useful for reducing build times, testing against a locally built FLTK and doesn't need to invoke neither git nor cmake.

FAQ

please check the FAQ page for frequently asked questions, encountered issues, guides on deployment, and contribution.

Building

To build, just run:

git clone https://github.com/fltk-rs/fltk-rs --recurse-submodules
cd fltk-rs
cargo build

Currently implemented types:

Image types:

  • SharedImage
  • BmpImage
  • JpegImage
  • GifImage
  • AnimGifImage
  • PngImage
  • SvgImage
  • Pixmap
  • RgbImage
  • XpmImage
  • XbmImage
  • PnmImage
  • TiledImage

Widgets:

  • Buttons
    • Button
    • RadioButton
    • ToggleButton
    • RoundButton
    • CheckButton
    • LightButton
    • RepeatButton
    • RadioLightButton
    • RadioRoundButton
    • ReturnButton
    • ShortcutButton
  • Dialogs
    • Native FileDialog
    • FileChooser
    • HelpDialog
    • Message dialog
    • Alert dialog
    • Password dialog
    • Choice dialog
    • Input dialog
    • ColorChooser dialog
  • Frame (Fl_Box)
  • Windows
    • Window
    • SingleWindow (single buffered)
    • DoubleWindow (double buffered)
    • MenuWindow
    • OverlayWindow
    • GlWindow (requires the "enable-glwindow" flag)
    • Experimental GlWidgetWindow (requires the "enable-glwindow" flag)
  • Groups
  • Text display widgets
    • TextDisplay
    • TextEditor
    • SimpleTerminal
  • Input widgets
    • Input
    • IntInput
    • FloatInput
    • MultilineInput
    • SecretInput
    • FileInput
  • Output widgets
    • Output
    • MultilineOutput
  • Menu widgets
    • MenuBar
    • MenuItem
    • Choice (dropdown list)
    • SysMenuBar (MacOS menu bar which appears at the top of the screen)
    • MenuButton
  • Valuator widgets
    • Slider
    • NiceSlider
    • ValueSlider
    • Dial
    • LineDial
    • Counter
    • Scrollbar
    • Roller
    • Adjuster
    • ValueInput
    • ValueOutput
    • FillSlider
    • FillDial
    • HorSlider (Horizontal slider)
    • HorFillSlider
    • HorNiceSlider
    • HorValueSlider
  • Browsing widgets
    • Browser
    • SelectBrowser
    • HoldBrowser
    • MultiBrowser
    • FileBrowser
    • CheckBrowser
  • Miscelaneous widgets
    • Spinner
    • Clock (Round and Square)
    • Chart (several chart types are available)
    • Progress (progress bar)
    • Tooltip
    • InputChoice
    • HelpView
  • Table widgets
  • Trees
    • Tree
    • TreeItem

Drawing primitives

(In the draw module)

Surface types:

  • Printer.
  • ImageSurface.
  • SvgFileSurface.

GUI designer

fltk-rs supports FLUID, the RAD wysiwyg designer for FLTK. Checkout the fl2rust crate and fl2rust template.

Examples

To run the examples:

cargo run --example editor
cargo run --example calculator
cargo run --example calculator2
cargo run --example counter
cargo run --example hello_svg
cargo run --example hello_button
cargo run --example fb
cargo run --example pong
cargo run --example custom_widgets
cargo run --example custom_dial
...

Using custom theming and also FLTK provided default schemes like Gtk:

Different frame types which can be used with many different widgets such as Frame, Button widgets, In/Output widgets...etc.

More interesting examples can be found in the fltk-rs-demos repo. Also a nice implementation of the 7guis tasks can be found here. Various advanced examples can also be found here.

Themes

Additional themes can be found in the fltk-theme crate.

  • screenshots/aero.jpg

  • screenshots/black.jpg

And more...

Extra widgets

This crate exposes FLTK's set of widgets, which are all customizable. Additional custom widgets can be found in the fltk-extras crate.

image

image

ss

image

Tutorials

More videos in the playlist here. Some of the demo projects can be found here.