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!

Modules

prelude

Traits and essential types inteded for blanket imports.

Structs

AboutDialog
AccelFlags
AccelGroup
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
Expander
FileChooser
FileChooserButton
FileChooserDialog
FileChooserWidget
FileFilter
FileFilterFlags
Fixed
FontButton
FontChooser
FontChooserDialog
FontChooserWidget
Frame
Grid
IconFactory
IconSource
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
PrintSettings
ProgressBar
RadioButton
RadioMenuItem
Range
RecentChooser
RecentChooserDialog
RecentChooserWidget
RecentData
RecentFilter
RecentFilterFlags
RecentInfo
RecentManager
Rectangle
RegionFlags
Requisition
Scale
ScaleButton
Scrollable
Scrollbar
ScrolledWindow
SelectionData
Separator
SeparatorMenuItem
SeparatorToolItem
Settings
ShortcutsWindow
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
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
PrintPages
PrintQuality
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

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
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

ActionableExt
BinExt
BoxExt
ButtonExt
Cast

Upcasting and downcasting support.

CellAreaExt
CellEditableExt
CellLayoutExt
CellRendererExt
CellRendererTextExt
CheckButtonExt
CheckMenuItemExt
ColorChooserExt
ComboBoxExt
ContainerExt
DialogExt
EditableExt
EditableSignals
EntryExt
FileChooserExt
FontChooserExt
FrameExt
IsA

Declares the "is a" relationship.

MenuItemExt
MenuShellExt
MiscExt
OrientableExt
RangeExt
RecentChooserExt
ScaleButtonExt
ScrollableExt
ScrolledWindowExt
SpinButtonSignals
StaticType

Types that are supported by GLib dynamic typing.

StyleProviderExt
ToValue

Converts to Value.

ToggleButtonExt
ToolButtonExt
ToolItemExt
ToolShellExt
TreeModelExt
TreeSortableExt
WidgetExt
WindowExt

Functions

check_version
events_pending
get_binary_age
get_interface_age
get_major_version
get_micro_version
get_minor_version
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_iteration
main_iteration_do
main_level
main_quit
set_initialized

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

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.