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:

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 inteded for blanket imports.

Structs

AboutDialog
AccelFlags
AccelGroup
ActionBar
Actionable
Adjustment
Alignment
Allocation
AppChooser
AppChooserDialog
AppChooserWidget
Application
ApplicationInhibitFlags
ApplicationWindow
Arrow
AspectFrame
Assistant
Bin
Box
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
EventController
Expander
FileChooser
FileChooserButton
FileChooserDialog
FileChooserWidget
FileFilter
FileFilterFlags
Fixed
FlowBox
FlowBoxChild
FontButton
FontChooser
FontChooserDialog
FontChooserWidget
Frame
GLArea
Gesture
GestureDrag
GestureLongPress
GestureMultiPress
GesturePan
GestureRotate
GestureSingle
GestureSwipe
GestureZoom
Grid
HeaderBar
IMContext
IMMulticontext
IconFactory
IconInfo
IconLookupFlags
IconSet
IconSource
IconTheme
IconView
Image
ImageMenuItem
InfoBar
Inhibit

Whether to propagate the signal to the default handler.

InputHints
JunctionSides
Label
Layout
LevelBar
LinkButton
ListBox
ListBoxRow
ListStore
Menu
MenuBar
MenuButton
MenuItem
MenuShell
MenuToolButton
MessageDialog
Misc
ModelButton
Notebook
Object

The base class in the object hierarchy.

Orientable
Overlay
PageSetup
Paned
PaperSize
PlacesOpenFlags
PlacesSidebar
Popover
PopoverMenu
PrintContext
PrintSettings
ProgressBar
RadioButton
RadioMenuItem
Range
RecentChooser
RecentChooserDialog
RecentChooserWidget
RecentData
RecentFilter
RecentFilterFlags
RecentInfo
RecentManager
Rectangle
RegionFlags
Requisition
Revealer
Scale
ScaleButton
Scrollable
Scrollbar
ScrolledWindow
SearchBar
SearchEntry
SelectionData
Separator
SeparatorMenuItem
SeparatorToolItem
Settings
ShortcutsWindow
SizeGroup
Socket
SpinButton
Spinner
Stack
StackSidebar
StackSwitcher
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
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
BaselinePosition
BuilderError
ButtonBoxStyle
ButtonRole
ButtonsType
CellRendererAccelMode
CellRendererMode
CornerType
CssProviderError
CssSectionType
DeleteType
DirectionType
DragResult
EntryIconPosition
EventSequenceState
FileChooserAction
FileChooserConfirmation
FileChooserError
IMPreeditStyle
IMStatusStyle
IconSize
IconThemeError
IconViewDropPosition
ImageType
InputPurpose
Justification
LevelBarMode
License
MenuDirectionType
MessageType
MovementStep
NotebookTab
NumberUpLayout
Orientation
PackDirection
PackType
PageOrientation
PageSet
PanDirection
PolicyType
PopoverConstraint
PositionType
PrintDuplex
PrintError
PrintPages
PrintQuality
PropagationPhase
RecentChooserError
RecentManagerError
RecentSortType
ReliefStyle
ResizeMode
ResponseType
RevealerTransitionType
ScrollStep
ScrollType
ScrollablePolicy
SelectionMode
SensitivityType
ShadowType
SizeGroupMode
SizeRequestMode
SortColumn
SortType
SpinButtonUpdatePolicy
SpinType
StackTransitionType
StateType
TextDirection
TextExtendSelection
TextWindowType
ToolbarStyle
TreeViewColumnSizing
TreeViewDropPosition
TreeViewGridLines
Type

A GLib or GLib-based library type

Unit
WidgetHelpType
WindowPosition
WindowType
WrapMode

Constants

ACCEL_LOCKED
ACCEL_MASK
ACCEL_VISIBLE
APPLICATION_INHIBIT_IDLE
APPLICATION_INHIBIT_LOGOUT
APPLICATION_INHIBIT_SUSPEND
APPLICATION_INHIBIT_SWITCH
CALENDAR_NO_MONTH_CHANGE
CALENDAR_SHOW_DAY_NAMES
CALENDAR_SHOW_DETAILS
CALENDAR_SHOW_HEADING
CALENDAR_SHOW_WEEK_NUMBERS
CELL_RENDERER_EXPANDABLE
CELL_RENDERER_EXPANDED
CELL_RENDERER_FOCUSED
CELL_RENDERER_INSENSITIVE
CELL_RENDERER_PRELIT
CELL_RENDERER_SELECTED
CELL_RENDERER_SORTED
DEST_DEFAULT_ALL
DEST_DEFAULT_DROP
DEST_DEFAULT_HIGHLIGHT
DEST_DEFAULT_MOTION
DIALOG_DESTROY_WITH_PARENT
DIALOG_MODAL
DIALOG_USE_HEADER_BAR
FILE_FILTER_DISPLAY_NAME
FILE_FILTER_FILENAME
FILE_FILTER_MIME_TYPE
FILE_FILTER_URI
ICON_LOOKUP_DIR_LTR
ICON_LOOKUP_DIR_RTL
ICON_LOOKUP_FORCE_REGULAR
ICON_LOOKUP_FORCE_SIZE
ICON_LOOKUP_FORCE_SVG
ICON_LOOKUP_FORCE_SYMBOLIC
ICON_LOOKUP_GENERIC_FALLBACK
ICON_LOOKUP_NO_SVG
ICON_LOOKUP_USE_BUILTIN
INPUT_HINT_INHIBIT_OSK
INPUT_HINT_LOWERCASE
INPUT_HINT_NONE
INPUT_HINT_NO_SPELLCHECK
INPUT_HINT_SPELLCHECK
INPUT_HINT_UPPERCASE_CHARS
INPUT_HINT_UPPERCASE_SENTENCES
INPUT_HINT_UPPERCASE_WORDS
INPUT_HINT_VERTICAL_WRITING
INPUT_HINT_WORD_COMPLETION
JUNCTION_BOTTOM
JUNCTION_CORNER_BOTTOMLEFT
JUNCTION_CORNER_BOTTOMRIGHT
JUNCTION_CORNER_TOPLEFT
JUNCTION_CORNER_TOPRIGHT
JUNCTION_LEFT
JUNCTION_NONE
JUNCTION_RIGHT
JUNCTION_TOP
PLACES_OPEN_NEW_TAB
PLACES_OPEN_NEW_WINDOW
PLACES_OPEN_NORMAL
RECENT_FILTER_AGE
RECENT_FILTER_APPLICATION
RECENT_FILTER_DISPLAY_NAME
RECENT_FILTER_GROUP
RECENT_FILTER_MIME_TYPE
RECENT_FILTER_URI
REGION_EVEN
REGION_FIRST
REGION_LAST
REGION_ODD
REGION_ONLY
REGION_SORTED
STATE_FLAG_ACTIVE
STATE_FLAG_BACKDROP
STATE_FLAG_CHECKED
STATE_FLAG_DIR_LTR
STATE_FLAG_DIR_RTL
STATE_FLAG_DROP_ACTIVE
STATE_FLAG_FOCUSED
STATE_FLAG_INCONSISTENT
STATE_FLAG_INSENSITIVE
STATE_FLAG_LINK
STATE_FLAG_NORMAL
STATE_FLAG_PRELIGHT
STATE_FLAG_SELECTED
STATE_FLAG_VISITED
STYLE_CONTEXT_PRINT_NONE
STYLE_CONTEXT_PRINT_RECURSE
STYLE_CONTEXT_PRINT_SHOW_STYLE
STYLE_PROVIDER_PRIORITY_APPLICATION
STYLE_PROVIDER_PRIORITY_FALLBACK
STYLE_PROVIDER_PRIORITY_SETTINGS
STYLE_PROVIDER_PRIORITY_THEME
STYLE_PROVIDER_PRIORITY_USER
TARGET_OTHER_APP
TARGET_OTHER_WIDGET
TARGET_SAME_APP
TARGET_SAME_WIDGET
TEXT_SEARCH_CASE_INSENSITIVE
TEXT_SEARCH_TEXT_ONLY
TEXT_SEARCH_VISIBLE_ONLY
TOOL_PALETTE_DRAG_GROUPS
TOOL_PALETTE_DRAG_ITEMS
TREE_MODEL_ITERS_PERSIST
TREE_MODEL_LIST_ONLY

Traits

AboutDialogExt
AccelGroupExt
ActionBarExt
ActionableExt
AdjustmentExt
AlignmentExt
AppChooserDialogExt
AppChooserWidgetExt
ApplicationExt
ApplicationWindowExt
ArrowExt
AspectFrameExt
AssistantExt
BinExt
BoxExt
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
EventControllerExt
ExpanderExt
FileChooserButtonExt
FileChooserExt
FileChooserWidgetExt
FileFilterExt
FixedExt
FlowBoxChildExt
FlowBoxExt
FontButtonExt
FontChooserExt
FrameExt
GLAreaExt
GestureDragExt
GestureExt
GestureLongPressExt
GestureMultiPressExt
GesturePanExt
GestureRotateExt
GestureSingleExt
GestureSwipeExt
GestureZoomExt
GridExt
HeaderBarExt
IMContextExt
IMMulticontextExt
IconFactoryExt
IconInfoExt
IconThemeExt
IconViewExt
ImageExt
ImageMenuItemExt
InfoBarExt
IsA

Declares the "is a" relationship.

LabelExt
LayoutExt
LevelBarExt
LinkButtonExt
ListBoxExt
ListBoxRowExt
ListStoreExt
MenuBarExt
MenuButtonExt
MenuExt
MenuItemExt
MenuShellExt
MenuToolButtonExt
MessageDialogExt
MiscExt
ModelButtonExt
NotebookExt
OrientableExt
OverlayExt
PageSetupExt
PanedExt
PlacesSidebarExt
PopoverExt
PopoverMenuExt
PrintContextExt
PrintSettingsExt
ProgressBarExt
RadioButtonExt
RadioMenuItemExt
RangeExt
RecentChooserExt
RecentFilterExt
RecentManagerExt
RevealerExt
ScaleButtonExt
ScaleExt
ScrollableExt
ScrolledWindowExt
SearchBarExt
SearchEntryExt
SeparatorToolItemExt
SettingsExt
ShortcutsWindowExt
SizeGroupExt
SpinButtonExt
SpinButtonSignals
SpinnerExt
StackExt
StackSidebarExt
StackSwitcherExt
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
WindowExt
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_locale_direction
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_background_get_clip
render_check
render_expander
render_extension
render_focus
render_frame
render_frame_gap
render_handle
render_icon
render_icon_pixbuf
render_icon_surface
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
show_uri_on_window
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
test_widget_wait_for_draw
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_