Crate gtk [] [src]

GTK+ 3 bindings

This library contains safe Rust bindings for GTK+ 3, a multi-platform GUI toolkit. It's a part of Gtk-rs.

The library is a work in progress: expect missing bindings and breaking changes. A steadily increasing share of the code is machine-generated from GObject introspection metadata. The API docs were converted from the upstream ones so until they've all been reviewed there will be incongruities with actual Rust APIs.

See also:

Hello World

extern crate gtk;
use gtk::prelude::*;
use gtk::{ButtonsType, DialogFlags, MessageType, MessageDialog, Window};

fn main() {
    if gtk::init().is_err() {
        println!("Failed to initialize GTK.");
        return;
    }
    MessageDialog::new(None::<&Window>,
                       DialogFlags::empty(),
                       MessageType::Info,
                       ButtonsType::Ok,
                       "Hello World").run();
}

Initialization

GTK+ needs to be initialized before use by calling init or Application::new. You only need to do it once and there is no 'finalize'.

The main loop

In a typical GTK+ application you set up the UI, assign signal handlers and run the main event loop:

fn main() {
    gtk::init().unwrap();
    // Create the main window.
    let window = Window::new(WindowType::Toplevel);
    // UI initialization.
    // ...
    // Don't forget to make all widgets visible.
    window.show_all();
    // Handle closing of the window.
    window.connect_delete_event(|_, _| {
        // Stop the main loop.
        gtk::main_quit();
        // Let the default handler destroy the window.
        Inhibit(false)
    });
    // Run the main loop.
    gtk::main();
}

Threads

GTK+ is not thread-safe. Accordingly, none of this crate's structs implement Send or Sync.

The thread where init was called is considered the main thread. OS X has its own notion of the main thread and init must be called on that thread. After successful initialization, calling any gtk or gdk functions (including init) from other threads will panic.

Any thread can schedule a closure to be run by the main loop on the main thread via glib::idle_add or glib::timeout_add. This crate has versions of those functions without the Send bound, which may only be called from the main thread: idle_add, timeout_add.

Panics

This and the gdk crate have some run-time safety and contract checks:

  • Any constructor or free function will panic if called before init or on a non-main thread.

  • Any &str or &Path parameter with an interior null (\0) character will cause a panic.

  • Some functions will panic if supplied out-of-range integer parameters. All such cases will be documented individually but they're not yet.

A panic in a closure will abort the process.

Crate features

Library versions

By default this crate provides only GTK+ 3.4 APIs. You can access more modern APIs by selecting one of the following features: v3_6, v3_8, v3_10, v3_12, v3_14, v3_16.

Cargo.toml example:

[dependencies.gtk]
version = "0.x.y"
features = ["v3_16"]

Take care when choosing the version to target: some of your users might not have easy access to the latest ones. The higher the version, the fewer users will have it installed.

Lgpl-docs

The Gtk-rs crates come with API docs missing because of licensing incompatibilty. You can embed those docs locally via the embed-lgpl-docs feature, e.g.

> cargo doc --features embed-lgpl-docs

Its counterpart purge-lgpl-docs removes those docs regardless of edits.

These features rewrite the crate sources so it's sufficient to enable them once. Omitting them in the following cargo invocations will not undo their effects!

Reexports

pub use prelude::*;

Modules

functions
prelude

Traits and essential types intended for blanket imports.

Structs

AboutDialog
AccelFlags
AccelGroup
Actionable
Adjustment
Alignment
Allocation
AppChooser
AppChooserDialog
AppChooserWidget
Application
ApplicationInhibitFlags
ApplicationWindow
Arrow
AspectFrame
Assistant
Bin
Box
Buildable
Builder
Button
ButtonBox
Calendar
CalendarDisplayOptions
CellArea
CellAreaBox
CellAreaContext
CellEditable
CellLayout
CellRenderer
CellRendererAccel
CellRendererCombo
CellRendererPixbuf
CellRendererProgress
CellRendererSpin
CellRendererSpinner
CellRendererState
CellRendererText
CellRendererToggle
CheckButton
CheckMenuItem
Clipboard
ColorButton
ColorChooser
ColorChooserDialog
ColorChooserWidget
ComboBox
ComboBoxText
Container
Continue

Continue calling the closure in the future iterations or drop it.

CssProvider
CssSection
DestDefaults
Dialog
DialogFlags
DrawingArea
Editable
Entry
EntryBuffer
EntryCompletion
Error

A generic error capable of representing various error domains (types).

EventBox
Expander
FileChooser
FileChooserButton
FileChooserDialog
FileChooserWidget
FileFilter
FileFilterFlags
Fixed
FontButton
FontChooser
FontChooserDialog
FontChooserWidget
Frame
Grid
IMContext
IMMulticontext
IconFactory
IconInfo
IconLookupFlags
IconSet
IconSource
IconTheme
IconView
Image
ImageMenuItem
InfoBar
Inhibit

Whether to propagate the signal to the default handler.

JunctionSides
Label
Layout
LinkButton
ListStore
Menu
MenuBar
MenuItem
MenuShell
MenuToolButton
MessageDialog
Misc
Notebook
Object

The base class in the object hierarchy.

Orientable
Overlay
PageSetup
Paned
PaperSize
PlacesOpenFlags
PlacesSidebar
PrintContext
PrintOperation
PrintOperationPreview
PrintSettings
ProgressBar
RadioButton
RadioMenuItem
RadioToolButton
Range
RecentChooser
RecentChooserDialog
RecentChooserWidget
RecentData
RecentFilter
RecentFilterFlags
RecentInfo
RecentManager
Rectangle
RegionFlags
Requisition
Scale
ScaleButton
Scrollable
Scrollbar
ScrolledWindow
SelectionData
Separator
SeparatorMenuItem
SeparatorToolItem
Settings
SizeGroup
Socket
SpinButton
Spinner
StateFlags
StatusIcon
Statusbar
StyleContext
StyleContextPrintFlags
StyleProperties
StyleProvider
Switch
SymbolicColor
TargetEntry
TargetFlags
TargetList
TextAttributes
TextBuffer
TextChildAnchor
TextIter
TextMark
TextSearchFlags
TextTag
TextTagTable
TextView
ToggleButton
ToggleToolButton
ToolButton
ToolItem
ToolItemGroup
ToolPalette
ToolPaletteDragTargets
ToolShell
Toolbar
Tooltip
TreeIter
TreeModel
TreeModelFilter
TreeModelFlags
TreePath
TreeRowReference
TreeSelection
TreeSortable
TreeStore
TreeView
TreeViewColumn
TypedValue

A statically typed Value.

Value

A generic value capable of carrying various types.

Viewport
VolumeButton
Widget
Window
WindowGroup

Enums

Align
ArrowType
AssistantPageType
BuilderError
ButtonBoxStyle
ButtonRole
ButtonsType
CellRendererAccelMode
CellRendererMode
CornerType
CssProviderError
CssSectionType
DeleteType
DirectionType
DragResult
EntryIconPosition
FileChooserAction
FileChooserConfirmation
FileChooserError
IMPreeditStyle
IMStatusStyle
IconSize
IconThemeError
IconViewDropPosition
ImageType
Justification
License
MenuDirectionType
MessageType
MovementStep
NotebookTab
NumberUpLayout
Orientation
PackDirection
PackType
PageOrientation
PageSet
PolicyType
PositionType
PrintDuplex
PrintError
PrintOperationAction
PrintOperationResult
PrintPages
PrintQuality
PrintStatus
RecentChooserError
RecentManagerError
RecentSortType
ReliefStyle
ResizeMode
ResponseType
RevealerTransitionType
ScrollStep
ScrollType
ScrollablePolicy
SelectionMode
SensitivityType
ShadowType
SizeGroupMode
SizeRequestMode
SortColumn
SortType
SpinButtonUpdatePolicy
SpinType
StackTransitionType
StateType
TextDirection
TextWindowType
ToolbarStyle
TreeViewColumnSizing
TreeViewDropPosition
TreeViewGridLines
Type

A GLib or GLib-based library type

Unit
WidgetHelpType
WindowPosition
WindowType
WrapMode

Constants

STYLE_PROVIDER_PRIORITY_APPLICATION
STYLE_PROVIDER_PRIORITY_FALLBACK
STYLE_PROVIDER_PRIORITY_SETTINGS
STYLE_PROVIDER_PRIORITY_THEME
STYLE_PROVIDER_PRIORITY_USER

Traits

AboutDialogExt
AccelGroupExt
ActionableExt
AdjustmentExt
AlignmentExt
AppChooserDialogExt
AppChooserWidgetExt
ApplicationWindowExt
ArrowExt
AspectFrameExt
AssistantExt
BinExt
BoxExt
BuildableExt
BuilderExt
ButtonBoxExt
ButtonExt
CalendarExt
Cast

Upcasting and downcasting support.

CellAreaBoxExt
CellAreaContextExt
CellAreaExt
CellEditableExt
CellLayoutExt
CellRendererAccelExt
CellRendererComboExt
CellRendererExt
CellRendererPixbufExt
CellRendererProgressExt
CellRendererSpinExt
CellRendererSpinnerExt
CellRendererTextExt
CellRendererToggleExt
CheckMenuItemExt
ClipboardExt
ColorButtonExt
ColorChooserDialogExt
ColorChooserExt
ColorChooserWidgetExt
ComboBoxExt
ComboBoxTextExt
ContainerExt
CssProviderExt
DialogExt
EditableExt
EditableSignals
EntryCompletionExt
EntryExt
EventBoxExt
ExpanderExt
FileChooserButtonExt
FileChooserExt
FileChooserWidgetExt
FileFilterExt
FixedExt
FontButtonExt
FontChooserExt
FrameExt
GridExt
GtkApplicationExt
GtkWindowExt
IMContextExt
IMMulticontextExt
IconFactoryExt
IconInfoExt
IconThemeExt
IconViewExt
ImageExt
ImageMenuItemExt
InfoBarExt
IsA

Declares the "is a" relationship.

LabelExt
LayoutExt
LinkButtonExt
ListStoreExt
MenuBarExt
MenuExt
MenuItemExt
MenuShellExt
MenuToolButtonExt
MessageDialogExt
MiscExt
NotebookExt
OrientableExt
OverlayExt
PageSetupExt
PanedExt
PlacesSidebarExt
PrintContextExt
PrintOperationExt
PrintOperationPreviewExt
PrintSettingsExt
ProgressBarExt
RadioButtonExt
RadioMenuItemExt
RadioToolButtonExt
RangeExt
RecentChooserExt
RecentFilterExt
RecentManagerExt
ScaleButtonExt
ScaleExt
ScrollableExt
ScrolledWindowExt
SeparatorToolItemExt
SettingsExt
SizeGroupExt
SpinButtonExt
SpinButtonSignals
SpinnerExt
StaticType

Types that are supported by GLib dynamic typing.

StatusIconExt
StatusbarExt
StyleContextExt
StylePropertiesExt
StyleProviderExt
SwitchExt
TextBufferExt
TextChildAnchorExt
TextMarkExt
TextTagExt
TextTagTableExt
TextViewExt
ToValue

Converts to Value.

ToggleButtonExt
ToggleToolButtonExt
ToolButtonExt
ToolItemExt
ToolItemGroupExt
ToolPaletteExt
ToolShellExt
ToolbarExt
TooltipExt
TreeModelExt
TreeModelFilterExt
TreeSelectionExt
TreeSortableExt
TreeStoreExt
TreeViewColumnExt
TreeViewExt
ViewportExt
VolumeButtonExt
WidgetExt
WindowGroupExt

Functions

accel_groups_activate
accel_groups_from_object
accelerator_get_default_mod_mask
accelerator_get_label
accelerator_get_label_with_keycode
accelerator_name
accelerator_name_with_keycode
accelerator_parse
accelerator_set_default_mod_mask
accelerator_valid
alternative_dialog_button_order
bindings_activate
bindings_activate_event
cairo_should_draw_window
cairo_transform_to_window
check_version
device_grab_add
device_grab_remove
disable_setlocale
events_pending
false_
get_binary_age
get_current_event
get_current_event_device
get_current_event_state
get_current_event_time
get_debug_flags
get_default_language
get_event_widget
get_interface_age
get_major_version
get_micro_version
get_minor_version
grab_get_current
idle_add

Adds a closure to be called by the default main loop when it's idle.

init

Tries to initialize GTK+.

is_initialized

Returns true if GTK has been initialized.

is_initialized_main_thread

Returns true if GTK has been initialized and this is the main thread.

main
main_do_event
main_iteration
main_iteration_do
main_level
main_quit
print_run_page_setup_dialog
propagate_event
render_activity
render_arrow
render_background
render_check
render_expander
render_extension
render_focus
render_frame
render_frame_gap
render_handle
render_icon
render_icon_pixbuf
render_insertion_cursor
render_layout
render_line
render_option
render_slider
rgb_to_hsv
selection_add_target
selection_clear_targets
selection_convert
selection_owner_set
selection_owner_set_for_display
selection_remove_all
set_debug_flags
set_initialized

Informs this crate that GTK has been initialized and the current thread is the main one.

show_uri
stock_list_ids
targets_include_image
targets_include_rich_text
targets_include_text
targets_include_uri
test_create_simple_window
test_find_label
test_find_sibling
test_find_widget
test_register_all_types
test_slider_get_value
test_slider_set_perc
test_spin_button_click
test_text_get
test_text_set
test_widget_click
test_widget_send_key
timeout_add

Adds a closure to be called by the default main loop at regular intervals with millisecond granularity.

timeout_add_seconds

Adds a closure to be called by the default main loop at regular intervals with second granularity.

tree_get_row_drag_data
tree_set_row_drag_data
true_