Gtk2Hs

An introduction to writing graphical user interfaces in Haskell with Gtk2Hs

Duncan Coutts and Axel Simon

Oxford University Computing Laboratory,
University of Kent at Canterbury Computing Laboratory

Gtk+

[any material that should appear in print but not on the slide]

Gtk+ platform components

UI Building Blocks

Custom Interface Elements

Under the Hood

Gtk2Hs

Where Gtk2Hs fits in

GUI toolkit concepts

Event-driven control flow

Difficulties with event loops

Widgets

Widgets

Widget attributes

Signals

Hello World

Hello World screenshot import Graphics.UI.Gtk main = do initGUI window <- windowNew button <- buttonNew set window [ windowTitle := "Hello World" , containerChild := button ] set button [ buttonLabel := "Hello World" ] onDestroy window mainQuit onClicked button $ do putStrLn "Hello World" widgetShowAll window mainGUI

Layout

Layout

Custom drawn widgets

  • Two phase (re)painting system:
    • invalidate rectangles
    • redraw invalidated rectangles
    Gives non-flickering drawing and animation
  • Typically use a DrawingArea widget
  • Must respond to expose signal and redraw the exposed region:
    onExpose drawingArea $ \Expose { eventRegion = region } -> do ...
  • A good data model will allow us to redraw just the exposed region rather than the whole widget

Cairo graphics

  • High quality 2D vector graphics library
  • Multiple backends: screen, PNG, PS and PDF
  • Makes use of hardware acceleration if possible
  • Allows reusing drawing code for screen and print
  • Provides PDF-style drawing model with:
    • stroking and filling lines and Bézier curves
    • filling using gradients and bitmap patterns
    • compositing translucent images
    • affine transformations
    • anti-aliased text rendering

Drawing widgets using Cairo

  • Simple monadic Haskell API
  • Easy to use with Gtk+ (since version 2.8)
    onExpose drawingArea $ \e -> do win <- drawingAreaGetDrawWindow drawingArea renderWithDrawable win $ do setSourceRGBA 1 0 0 0.5 setLineWidth 2.5 scale 2.0 2.0 rotate (pi/2) moveTo 10 10 lineTo 20 20 stroke showText "Hello World!"

Gtk2Hs extensions

    There are a few extension packages:
  • OpenGL extension allows rendering using HOpenGL
  • SVG extension for cairo
  • A version of the Haskell School of Expression API
  • Mozilla HTML rendering engine in a widget
  • "SourceView" - an editor widget with syntax highlighting
  • "GConf" - to use the GNOME configuration system