Introduction to GUI Toolkits by Civet

VIEWS: 55 PAGES: 38

									Introduction to GUI Toolkits
                    Abstract
• GUI programming basics
• Popular GUI Toolkits
  – language
  – Implementation
  – support, doc, license.etc
  • Bonus
    I. GUI programming basics
                             GUI
                             GUI)
• Graphical User Interface (GUI
• IS a type of user interface which allows
  people to interact with a computer and
  computer-controlled devices. It presents
  graphical icons, visual indicators or special
  graphical elements called "widgets".
           Concepts:Event
• An event is usually some form of input or
  interaction that occurs externally to a GUI
  but can be detected by the GUI toolkit.
  Examples include keyboard key presses,
  mouse movements and button presses,
  drag and drop, and so on.
    Typical windows messages
•   WM_CREATE
•   WM_PAINT
•   WM_KEYDOWN
•   WM_MOUSEMOVE
•   WM_DESTROY
              Event Loop
• A loop which is used to dispatch callbacks
  in response to events. Usually the event
  loop for a GUI is provided by the toolkit
  and doesn't need to be written from
  scratch.
  Typical windows event loop
MSG msg ;
while ( GetMessage (&msg, NULL, 0, 0))
{
   TranslateMessage (&msg) ;
   DispatchMessage (&msg) ;
}
                Callback
• A callback or event handler is a piece of
  code (usually a function or method) which
  is executed when an event occurs. For
  example, an callback called 'onQuit' may
  be run when the key accelerator Alt-F4 is
  pressed by the user.
             Glut code snippets
int main(int argc, char *argv[])
    main(int
{
            (&argc,
    glutInit(&argc, argv);
    // ....
                    ("GLUT");
    glutCreateWindow("GLUT");

    glutReshapeFunc(resize);
                   (resize);
                   (display);
    glutDisplayFunc(display);
                    (key);
    glutKeyboardFunc(key);
                (idle);
    glutIdleFunc(idle);

                ();
    glutMainLoop();
    return 0;
}
             Glut code snippets
static void display(void)
            display(void)
{
    const double t = glutGet(GLUT_ELAPSED_TIME) / 1000.0;
                                                  1000.0;
    const double a = t*90.0;
                       90.0;
           (GL_COLOR_BUFFER_BIT
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
             (
    glColor3d(1,0,0);

                ();
    glPushMatrix();
                     (-2.4,1.2,-
        glTranslated(-2.4,1.2,-6);
                     (-2.4    ,-6
                 (60,
        glRotated(60,1,0,0);
                 (a,
        glRotated(a,0,0,1);
                 (a,0
                        (
        glutSolidSphere(1,slices,stacks);
               ();
    glPopMatrix();
}
                Binding:
• Binding is the process of associating an
  event (such as a key press or mouse
  movement) with a callback or event
  handler. For example, we might bind the
  key accelerator Ctrl-S with the callback
  onSave.
     II. Popular GUI Toolkits
(Sorted by lang)
• C++: MFC, Qt, wxWidgets, WTL, CEGUI
• C: GTK, Glut
• Java: swt, swing
• Script Lang: PyGTK, wxPython, Tk
                     MFC
• The Microsoft Foundation Class Library (MFC)
• IS a library that wraps portions of the Windows
  API in C++ classes, including functionality that
  enables them to use a default application
  framework. Classes are defined for many of the
  handle-managed Windows objects and also for
  predefined windows and common controls.
                 The MFC way
/// PngButton.h
/// Button with png format image
class PngButton : public CButton
{
public :
public:
             ();
    PngButton();
    virtual ~PngButton ();

    bool SetImage(Png32Image * pngImage);
protected :
protected:
     DECLARE_MESSAGE_MAP()
     afx_msg void OnNotifyCustomDraw ( NMHDR *
   pNotifyStruct, LRESULT * result );
                   LRESULT*
};
/// PngButton.cpp
BEGIN_MESSAGE_MAP (PngButton , CButton)
                   PngButton,
    ON_NOTIFY_REFLECT (NM_CUSTOMDRAW , OnNotifyCustomDraw)
END_MESSAGE_MAP ()

void PngButton::OnNotifyCustomDraw ( NMHDR *
   pNotifyStruct, LRESULT * result )
                  LRESULT*
{

      LPNMCUSTOMDRAW pCustomDraw = (LPNMCUSTOMDRAW)
    pNotifyStruct;
      /// ...
}
                   Under the hood
const AFX_MSGMAP* PngButton ::GetMessageMap() const
{
    return GetThisMessageMap();
}
const AFX_MSGMAP* PngButton ::GetThisMessageMap()
{
    static const AFX_MSGMAP_ENTRY _messageEntries[] =
    {
                                     NM_CUSTOMDRAW,
        { WM_NOTIFY+WM_REFLECT_BASE, NM_CUSTOMDRAW 0, 0, AfxSigNotify_v,
   OnNotifyCustomDraw },
        {0, 0, 0, 0, AfxSig_end, (AFX_PMSG)0 }
    };
    static const AFX_MSGMAP messageMap =
    { & CButton::GetThisMessageMap, &_messageEntries[0] };

    return &messageMap;
}
                      MFC
• It is outdated!
• The disadvantages of MFC
  – It is a thin wrapper for windows API(written in C)
  – It is not so Object Oriented
  – Rough layout mechanism
  – Code style is not elegant
  – Full of nasty tricks
                                 MFC
• Example(object-based C API)
• CDialog::OnInitDialog()
  Return Value
  Specifies whether the application has set the input focus to one of the
  controls in the dialog box. If OnInitDialog returns nonzero, Windows sets the
  input focus to the first control in the dialog box. (msdn)
• CWnd::UpdateData(BOOL)
  Input param
                                   FALSE
                                   FALSE)
  Dialog box is being initialized (FALSE
                            TRUE
                            TRUE)
  Data is being retrieved (TRUE
                        MFC
• It still works…
• Why?
  – It is free
  – It is compatible with windows(98~Vista)
  – It has official support
  – There have been tens of thousands KLOC.
  – It is not just a gui toolkit, in fact, it is an
    application framework.
 MFC - Runback over these pages
• Why MFC is designed this way?
• In one word : it is developed in 1992
  – When performance is really important
  – When C++ lacks a lot of modern features
  – When Object Oriented design
  – Microsoft keep up the tradition of backward
    compatibility
                       Qt
•   The best GUI solution
•   Qt offers reliable commercial support
•   A powerful designer
•   Cross-platform
•   Support for C++ and java
•   It has open source versions, but not free!
Qt Designer
                    Qt
• Diff between open source and free
• Trolltech's Commercial licenses allow
  customers to develop, use and distribute
  their applications under standard
  commercial terms.
• Trolltech's Open Source versions are
  available under the terms of the GPL -
  General Public License.
                 Feature
•   Memory management
•   Layout
•   Internationalization
•   Signals and slots
                        The Qt way
Form1::Form1( QWidget * parent, const char* name, WFlags fl )
     ::Form1( QWidget*                char*
    : QWidget( parent, name, fl )
{
    cpusage = new QLabel( this, "cpusage" );
                           this,
           ->setGeometry(
    cpusage->setGeometry( QRect( 271, 522, 80, 21 ) );
                                  271, 522, 80,

                           this,
    memusage = new QLabel( this, "memusage" );
            ->setGeometry(
    memusage->setGeometry( QRect( 460, 522, 50 , 21 ) );
                                  460, 522, 50,

    nowtime = new QLabel( this, "nowtime" );
                           this,
           ->setGeometry(
    nowtime->setGeometry( QRect( 93, 522, 80, 21 ) );
                                  93, 522, 80,
                  ();
    languageChange();
          ( QSize(532 543).expandedTo(minimumSizeHint())
    resize( QSize(532 , 543).expandedTo(minimumSizeHint()) );
                  532,
               (
    clearWState( WState_Polished );
        ();
    init();
}
             wxWidgets
• Looks like MFC
• License: LGPL
• Language
  C++, Python, Perl, and C#/.NET
wxSmith
            The wxWidgets way
class MainFrame
: public wxFrame
{
public :
public:
    void OnQuit(wxCommandEvent &event);
private :
private:
       DECLARE_EVENT_TABLE ()
};

// MainFrame.cpp
BEGIN_EVENT_TABLE (MainFrame, wxFrame)
           (ID_MAINWIN_QUIT,
   EVT_MENU(ID_MAINWIN_QUIT, MainFrame::OnQuit)
END_EVENT_TABLE ()
Code::Blocks
                  WTL
• The Windows Template Library (WTL)
• IS a free software, object-oriented C++
  template library for Win32 development.
• Combines a series of light weight
  components.
• WTL tutorial in Chinese
  http://www.imyaker.com/wtl/
                   The WTL way
class    StartDialog
: public CDialogImpl < StartDialog >
{
public:
public:
        // Dialog ID
        enum { IDD = IDD_START };
        // Maps
                      (StartDialog)
        BEGIN_MSG_MAP(StartDialog)
                            (WM_INITDIALOG,
            MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
                            (WM_SIZE,
            MESSAGE_HANDLER(WM_SIZE, OnResize)
            COMMAND_ID_HANDLER (IDC_SINGLE_START, OnStart)
            COMMAND_ID_HANDLER (IDC_MULTIPLE_START, OnMultiStart)
                   ()
        END_MSG_MAP()
            Another example
class CMainDlg : public CDialogImpl<CMainDlg>,
                         CDialogImpl<CMainDlg>,
                  public CWinDataExchange<CMainDlg>
                         CWinDataExchange<CMainDlg>
{
    //...
                  (CMainDlg)
    BEGIN_DDX_MAP(CMainDlg)
                    (IDC_EDIT,
        DDX_CONTROL(IDC_EDIT, m_wndEdit)
               ()
    END_DDX_MAP()
protected:
protected:
    CEditImpl   m_wndEdit;;
};
                  GTK
• Based on Callbacks
• An editor called Glade
• Glade 2, Glade 3 and libglade
GTK with Glade
               The GTK way
                              (void)
GtkWidget* create_main_window(void)
         *
{
    GtkWidget *button = gtk_button_new_with_mnemonic
  (_("OK"));
     "OK"));
  (_("OK"
    gtk_widget_show (button);
    gtk_container_add (GTK_CONTAINER (hbuttonbox2),
  button);
    GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
    g_signal_connect ( (gpointer) button, "clicked",
                                          "clicked",
                    G_CALLBACK (on_button_clicked),
                        );
                    NULL);
    /* ... */
                Discussion
• Which features should a splendid GUI
  Toolkit should provide?
• Minimize overload of Dev
  – Designer, Layout
• Separate UI from code(for instance:XAML)
• Cross-platform, Unicode support, friendly
  license, Support, doc
              Conclusion
• Each GUI Toolkit has its own advantage s
  and disadvantages .As a programmer, you
  should have the wisdom to chose the right
  one.
                   III. SVN   (as bonus)


• A joke first
                 “自从咱用了Subversion,腰不酸了,
                 背不痛了,腿也不抽筋了.”

• Subversion suite
  – Subversion
  – TortoiseSvn
  – AnkhSvn

								
To top