1.. default-domain:: c
2.. highlight:: c
3
4***************
5Handling Events
6***************
7
8Events are sent to a view when it has received user input,
9must be drawn, or in other situations that may need to be handled such as resizing.
10
11Events are sent to the event handler as a :union:`PuglEvent` union.
12The ``type`` field defines the type of the event and which field of the union is active.
13The application must handle at least :enumerator:`PUGL_CONFIGURE <PuglEventType.PUGL_CONFIGURE>`
14and :enumerator:`PUGL_EXPOSE <PuglEventType.PUGL_EXPOSE>` to draw anything,
15but there are many other :enum:`event types <PuglEventType>`.
16
17For example, a basic event handler might look something like this:
18
19.. code-block:: c
20
21   static PuglStatus
22   onEvent(PuglView* view, const PuglEvent* event)
23   {
24     MyApp* app = (MyApp*)puglGetHandle(view);
25
26     switch (event->type) {
27     case PUGL_CREATE:
28       return setupGraphics(app);
29     case PUGL_DESTROY:
30       return teardownGraphics(app);
31     case PUGL_CONFIGURE:
32       return resize(app, event->configure.width, event->configure.height);
33     case PUGL_EXPOSE:
34       return draw(app, view);
35     case PUGL_CLOSE:
36       return quit(app);
37     case PUGL_BUTTON_PRESS:
38        return onButtonPress(app, view, event->button);
39     default:
40       break;
41     }
42
43     return PUGL_SUCCESS;
44   }
45
46Using the Graphics Context
47==========================
48
49Drawing
50-------
51
52Note that Pugl uses a different drawing model than many libraries,
53particularly those designed for game-style main loops like `SDL <https://libsdl.org/>`_ and `GLFW <https://www.glfw.org/>`_.
54
55In that style of code, drawing is performed imperatively in the main loop,
56but with Pugl, the application must draw only while handling an expose event.
57This is because Pugl supports event-driven applications that only draw the damaged region when necessary,
58and handles exposure internally to provide optimized and consistent behavior across platforms.
59
60Cairo Context
61-------------
62
63A Cairo context is created for each :struct:`PuglEventExpose`,
64and only exists during the handling of that event.
65Null is returned by :func:`puglGetContext` at any other time.
66
67OpenGL Context
68--------------
69
70The OpenGL context is only active during the handling of these events:
71
72- :struct:`PuglEventCreate`
73- :struct:`PuglEventDestroy`
74- :struct:`PuglEventConfigure`
75- :struct:`PuglEventExpose`
76
77As always, drawing is only possible during an expose.
78
79Vulkan Context
80--------------
81
82With Vulkan, the graphics context is managed by the application rather than Pugl.
83However, drawing must still only be performed during an expose.
84
85