1# Input guide {#input_guide}
2
3[TOC]
4
5This guide introduces the input related functions of GLFW.  For details on
6a specific function in this category, see the @ref input.  There are also guides
7for the other areas of GLFW.
8
9 - @ref intro_guide
10 - @ref window_guide
11 - @ref context_guide
12 - @ref vulkan_guide
13 - @ref monitor_guide
14
15GLFW provides many kinds of input.  While some can only be polled, like time, or
16only received via callbacks, like scrolling, many provide both callbacks and
17polling.  Callbacks are more work to use than polling but is less CPU intensive
18and guarantees that you do not miss state changes.
19
20All input callbacks receive a window handle.  By using the
21[window user pointer](@ref window_userptr), you can access non-global structures
22or objects from your callbacks.
23
24To get a better feel for how the various events callbacks behave, run the
25`events` test program.  It registers every callback supported by GLFW and prints
26out all arguments provided for every event, along with time and sequence
27information.
28
29
30## Event processing {#events}
31
32GLFW needs to poll the window system for events both to provide input to the
33application and to prove to the window system that the application hasn't locked
34up.  Event processing is normally done each frame after
35[buffer swapping](@ref buffer_swap).  Even when you have no windows, event
36polling needs to be done in order to receive monitor and joystick connection
37events.
38
39There are three functions for processing pending events.  @ref glfwPollEvents,
40processes only those events that have already been received and then returns
41immediately.
42
43```c
44glfwPollEvents();
45```
46
47This is the best choice when rendering continuously, like most games do.
48
49If you only need to update the contents of the window when you receive new
50input, @ref glfwWaitEvents is a better choice.
51
52```c
53glfwWaitEvents();
54```
55
56It puts the thread to sleep until at least one event has been received and then
57processes all received events.  This saves a great deal of CPU cycles and is
58useful for, for example, editing tools.
59
60If you want to wait for events but have UI elements or other tasks that need
61periodic updates, @ref glfwWaitEventsTimeout lets you specify a timeout.
62
63```c
64glfwWaitEventsTimeout(0.7);
65```
66
67It puts the thread to sleep until at least one event has been received, or until
68the specified number of seconds have elapsed.  It then processes any received
69events.
70
71If the main thread is sleeping in @ref glfwWaitEvents, you can wake it from
72another thread by posting an empty event to the event queue with @ref
73glfwPostEmptyEvent.
74
75```c
76glfwPostEmptyEvent();
77```
78
79Do not assume that callbacks will _only_ be called in response to the above
80functions.  While it is necessary to process events in one or more of the ways
81above, window systems that require GLFW to register callbacks of its own can
82pass events to GLFW in response to many window system function calls.  GLFW will
83pass those events on to the application callbacks before returning.
84
85For example, on Windows the system function that @ref glfwSetWindowSize is
86implemented with will send window size events directly to the event callback
87that every window has and that GLFW implements for its windows.  If you have set
88a [window size callback](@ref window_size) GLFW will call it in turn with the
89new size before everything returns back out of the @ref glfwSetWindowSize call.
90
91
92## Keyboard input {#input_keyboard}
93
94GLFW divides keyboard input into two categories; key events and character
95events.  Key events relate to actual physical keyboard keys, whereas character
96events relate to the text that is generated by pressing some of them.
97
98Keys and characters do not map 1:1.  A single key press may produce several
99characters, and a single character may require several keys to produce.  This
100may not be the case on your machine, but your users are likely not all using the
101same keyboard layout, input method or even operating system as you.
102
103
104### Key input {#input_key}
105
106If you wish to be notified when a physical key is pressed or released or when it
107repeats, set a key callback.
108
109```c
110glfwSetKeyCallback(window, key_callback);
111```
112
113The callback function receives the [keyboard key](@ref keys), platform-specific
114scancode, key action and [modifier bits](@ref mods).
115
116```c
117void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
118{
119    if (key == GLFW_KEY_E && action == GLFW_PRESS)
120        activate_airship();
121}
122```
123
124The action is one of `GLFW_PRESS`, `GLFW_REPEAT` or `GLFW_RELEASE`.  Events with
125`GLFW_PRESS` and `GLFW_RELEASE` actions are emitted for every key press.  Most
126keys will also emit events with `GLFW_REPEAT` actions while a key is held down.
127
128Note that many keyboards have a limit on how many keys being simultaneous held
129down that they can detect.  This limit is called
130[key rollover](https://en.wikipedia.org/wiki/Key_rollover).
131
132Key events with `GLFW_REPEAT` actions are intended for text input.  They are
133emitted at the rate set in the user's keyboard settings.  At most one key is
134repeated even if several keys are held down.  `GLFW_REPEAT` actions should not
135be relied on to know which keys are being held down or to drive animation.
136Instead you should either save the state of relevant keys based on `GLFW_PRESS`
137and `GLFW_RELEASE` actions, or call @ref glfwGetKey, which provides basic cached
138key state.
139
140The key will be one of the existing [key tokens](@ref keys), or
141`GLFW_KEY_UNKNOWN` if GLFW lacks a token for it, for example _E-mail_ and _Play_
142keys.
143
144The scancode is unique for every key, regardless of whether it has a key token.
145Scancodes are platform-specific but consistent over time, so keys will have
146different scancodes depending on the platform but they are safe to save to disk.
147You can query the scancode for any [key token](@ref keys) supported on the
148current platform with @ref glfwGetKeyScancode.
149
150```c
151const int scancode = glfwGetKeyScancode(GLFW_KEY_X);
152set_key_mapping(scancode, swap_weapons);
153```
154
155The last reported state for every physical key with a [key token](@ref keys) is
156also saved in per-window state arrays that can be polled with @ref glfwGetKey.
157
158```c
159int state = glfwGetKey(window, GLFW_KEY_E);
160if (state == GLFW_PRESS)
161{
162    activate_airship();
163}
164```
165
166The returned state is one of `GLFW_PRESS` or `GLFW_RELEASE`.
167
168This function only returns cached key event state.  It does not poll the
169system for the current state of the physical key.  It also does not provide any
170key repeat information.
171
172@anchor GLFW_STICKY_KEYS
173Whenever you poll state, you risk missing the state change you are looking for.
174If a pressed key is released again before you poll its state, you will have
175missed the key press.  The recommended solution for this is to use a
176key callback, but there is also the `GLFW_STICKY_KEYS` input mode.
177
178```c
179glfwSetInputMode(window, GLFW_STICKY_KEYS, GLFW_TRUE);
180```
181
182When sticky keys mode is enabled, the pollable state of a key will remain
183`GLFW_PRESS` until the state of that key is polled with @ref glfwGetKey.  Once
184it has been polled, if a key release event had been processed in the meantime,
185the state will reset to `GLFW_RELEASE`, otherwise it will remain `GLFW_PRESS`.
186
187@anchor GLFW_LOCK_KEY_MODS
188If you wish to know what the state of the Caps Lock and Num Lock keys was when
189input events were generated, set the `GLFW_LOCK_KEY_MODS` input mode.
190
191```c
192glfwSetInputMode(window, GLFW_LOCK_KEY_MODS, GLFW_TRUE);
193```
194
195When this input mode is enabled, any callback that receives
196[modifier bits](@ref mods) will have the @ref GLFW_MOD_CAPS_LOCK bit set if Caps
197Lock was on when the event occurred and the @ref GLFW_MOD_NUM_LOCK bit set if
198Num Lock was on.
199
200The `GLFW_KEY_LAST` constant holds the highest value of any
201[key token](@ref keys).
202
203
204### Text input {#input_char}
205
206GLFW supports text input in the form of a stream of
207[Unicode code points](https://en.wikipedia.org/wiki/Unicode), as produced by the
208operating system text input system.  Unlike key input, text input is affected by
209keyboard layouts and modifier keys and supports composing characters using
210[dead keys](https://en.wikipedia.org/wiki/Dead_key).  Once received, you can
211encode the code points into UTF-8 or any other encoding you prefer.
212
213Because an `unsigned int` is 32 bits long on all platforms supported by GLFW,
214you can treat the code point argument as native endian UTF-32.
215
216If you wish to offer regular text input, set a character callback.
217
218```c
219glfwSetCharCallback(window, character_callback);
220```
221
222The callback function receives Unicode code points for key events that would
223have led to regular text input and generally behaves as a standard text field on
224that platform.
225
226```c
227void character_callback(GLFWwindow* window, unsigned int codepoint)
228{
229}
230```
231
232
233### Key names {#input_key_name}
234
235If you wish to refer to keys by name, you can query the keyboard layout
236dependent name of printable keys with @ref glfwGetKeyName.
237
238```c
239const char* key_name = glfwGetKeyName(GLFW_KEY_W, 0);
240show_tutorial_hint("Press %s to move forward", key_name);
241```
242
243This function can handle both [keys and scancodes](@ref input_key).  If the
244specified key is `GLFW_KEY_UNKNOWN` then the scancode is used, otherwise it is
245ignored.  This matches the behavior of the key callback, meaning the callback
246arguments can always be passed unmodified to this function.
247
248
249## Mouse input {#input_mouse}
250
251Mouse input comes in many forms, including mouse motion, button presses and
252scrolling offsets.  The cursor appearance can also be changed, either to
253a custom image or a standard cursor shape from the system theme.
254
255
256### Cursor position {#cursor_pos}
257
258If you wish to be notified when the cursor moves over the window, set a cursor
259position callback.
260
261```c
262glfwSetCursorPosCallback(window, cursor_position_callback);
263```
264
265The callback functions receives the cursor position, measured in screen
266coordinates but relative to the top-left corner of the window content area.  On
267platforms that provide it, the full sub-pixel cursor position is passed on.
268
269```c
270static void cursor_position_callback(GLFWwindow* window, double xpos, double ypos)
271{
272}
273```
274
275The cursor position is also saved per-window and can be polled with @ref
276glfwGetCursorPos.
277
278```c
279double xpos, ypos;
280glfwGetCursorPos(window, &xpos, &ypos);
281```
282
283
284### Cursor mode {#cursor_mode}
285
286@anchor GLFW_CURSOR
287The `GLFW_CURSOR` input mode provides several cursor modes for special forms of
288mouse motion input.  By default, the cursor mode is `GLFW_CURSOR_NORMAL`,
289meaning the regular arrow cursor (or another cursor set with @ref glfwSetCursor)
290is used and cursor motion is not limited.
291
292If you wish to implement mouse motion based camera controls or other input
293schemes that require unlimited mouse movement, set the cursor mode to
294`GLFW_CURSOR_DISABLED`.
295
296```c
297glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
298```
299
300This will hide the cursor and lock it to the specified window.  GLFW will then
301take care of all the details of cursor re-centering and offset calculation and
302providing the application with a virtual cursor position.  This virtual position
303is provided normally via both the cursor position callback and through polling.
304
305@note You should not implement your own version of this functionality using
306other features of GLFW.  It is not supported and will not work as robustly as
307`GLFW_CURSOR_DISABLED`.
308
309If you only wish the cursor to become hidden when it is over a window but still
310want it to behave normally, set the cursor mode to `GLFW_CURSOR_HIDDEN`.
311
312```c
313glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
314```
315
316This mode puts no limit on the motion of the cursor.
317
318If you wish the cursor to be visible but confined to the content area of the
319window, set the cursor mode to `GLFW_CURSOR_CAPTURED`.
320
321```c
322glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_CAPTURED);
323```
324
325The cursor will behave normally inside the content area but will not be able to
326leave unless the window loses focus.
327
328To exit out of either of these special modes, restore the `GLFW_CURSOR_NORMAL`
329cursor mode.
330
331```c
332glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
333```
334
335If the cursor was disabled, this will move it back to its last visible position.
336
337
338@anchor GLFW_RAW_MOUSE_MOTION
339### Raw mouse motion {#raw_mouse_motion}
340
341When the cursor is disabled, raw (unscaled and unaccelerated) mouse motion can
342be enabled if available.
343
344Raw mouse motion is closer to the actual motion of the mouse across a surface.
345It is not affected by the scaling and acceleration applied to the motion of the
346desktop cursor.  That processing is suitable for a cursor while raw motion is
347better for controlling for example a 3D camera.  Because of this, raw mouse
348motion is only provided when the cursor is disabled.
349
350Call @ref glfwRawMouseMotionSupported to check if the current machine provides
351raw motion and set the `GLFW_RAW_MOUSE_MOTION` input mode to enable it.  It is
352disabled by default.
353
354```c
355if (glfwRawMouseMotionSupported())
356    glfwSetInputMode(window, GLFW_RAW_MOUSE_MOTION, GLFW_TRUE);
357```
358
359If supported, raw mouse motion can be enabled or disabled per-window and at any
360time but it will only be provided when the cursor is disabled.
361
362
363### Cursor objects {#cursor_object}
364
365GLFW supports creating both custom and system theme cursor images, encapsulated
366as @ref GLFWcursor objects.  They are created with @ref glfwCreateCursor or @ref
367glfwCreateStandardCursor and destroyed with @ref glfwDestroyCursor, or @ref
368glfwTerminate, if any remain.
369
370
371#### Custom cursor creation {#cursor_custom}
372
373A custom cursor is created with @ref glfwCreateCursor, which returns a handle to
374the created cursor object.  For example, this creates a 16x16 white square
375cursor with the hot-spot in the upper-left corner:
376
377```c
378unsigned char pixels[16 * 16 * 4];
379memset(pixels, 0xff, sizeof(pixels));
380
381GLFWimage image;
382image.width = 16;
383image.height = 16;
384image.pixels = pixels;
385
386GLFWcursor* cursor = glfwCreateCursor(&image, 0, 0);
387```
388
389If cursor creation fails, `NULL` will be returned, so it is necessary to check
390the return value.
391
392The image data is 32-bit, little-endian, non-premultiplied RGBA, i.e. eight bits
393per channel with the red channel first.  The pixels are arranged canonically as
394sequential rows, starting from the top-left corner.
395
396
397#### Standard cursor creation {#cursor_standard}
398
399A cursor with a [standard shape](@ref shapes) from the current system cursor
400theme can be created with @ref glfwCreateStandardCursor.
401
402```c
403GLFWcursor* url_cursor = glfwCreateStandardCursor(GLFW_POINTING_HAND_CURSOR);
404```
405
406These cursor objects behave in the exact same way as those created with @ref
407glfwCreateCursor except that the system cursor theme provides the actual image.
408
409A few of these shapes are not available everywhere.  If a shape is unavailable,
410`NULL` is returned.  See @ref glfwCreateStandardCursor for details.
411
412
413#### Cursor destruction {#cursor_destruction}
414
415When a cursor is no longer needed, destroy it with @ref glfwDestroyCursor.
416
417```c
418glfwDestroyCursor(cursor);
419```
420
421Cursor destruction always succeeds.  If the cursor is current for any window,
422that window will revert to the default cursor.  This does not affect the cursor
423mode.  All remaining cursors are destroyed when @ref glfwTerminate is called.
424
425
426#### Cursor setting {#cursor_set}
427
428A cursor can be set as current for a window with @ref glfwSetCursor.
429
430```c
431glfwSetCursor(window, cursor);
432```
433
434Once set, the cursor image will be used as long as the system cursor is over the
435content area of the window and the [cursor mode](@ref cursor_mode) is set
436to `GLFW_CURSOR_NORMAL`.
437
438A single cursor may be set for any number of windows.
439
440To revert to the default cursor, set the cursor of that window to `NULL`.
441
442```c
443glfwSetCursor(window, NULL);
444```
445
446When a cursor is destroyed, any window that has it set will revert to the
447default cursor.  This does not affect the cursor mode.
448
449
450### Cursor enter/leave events {#cursor_enter}
451
452If you wish to be notified when the cursor enters or leaves the content area of
453a window, set a cursor enter/leave callback.
454
455```c
456glfwSetCursorEnterCallback(window, cursor_enter_callback);
457```
458
459The callback function receives the new classification of the cursor.
460
461```c
462void cursor_enter_callback(GLFWwindow* window, int entered)
463{
464    if (entered)
465    {
466        // The cursor entered the content area of the window
467    }
468    else
469    {
470        // The cursor left the content area of the window
471    }
472}
473```
474
475You can query whether the cursor is currently inside the content area of the
476window with the [GLFW_HOVERED](@ref GLFW_HOVERED_attrib) window attribute.
477
478```c
479if (glfwGetWindowAttrib(window, GLFW_HOVERED))
480{
481    highlight_interface();
482}
483```
484
485
486### Mouse button input {#input_mouse_button}
487
488If you wish to be notified when a mouse button is pressed or released, set
489a mouse button callback.
490
491```c
492glfwSetMouseButtonCallback(window, mouse_button_callback);
493```
494
495@anchor GLFW_UNLIMITED_MOUSE_BUTTONS
496To handle all mouse buttons in the callback, instead of only ones with associated
497[button tokens](@ref buttons), set the @ref GLFW_UNLIMITED_MOUSE_BUTTONS
498input mode.
499
500```c
501glfwSetInputMode(window, GLFW_UNLIMITED_MOUSE_BUTTONS, GLFW_TRUE);
502```
503
504When this input mode is enabled, GLFW doesn't limit the reported mouse buttons
505to only those that have an associated button token, for compatibility with
506earlier versions of GLFW, which never reported any buttons over
507@ref GLFW_MOUSE_BUTTON_LAST, on which users could have relied on.
508
509The callback function receives the [mouse button](@ref buttons), button action
510and [modifier bits](@ref mods).
511
512```c
513void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
514{
515    if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS)
516        popup_menu();
517}
518```
519
520The mouse button is an integer that can be one of the
521[mouse button tokens](@ref buttons) or, if the
522@ref GLFW_UNLIMITED_MOUSE_BUTTONS input mode is set, any other positive value.
523
524The action is one of `GLFW_PRESS` or `GLFW_RELEASE`.
525
526The last reported state for every [mouse button token](@ref buttons) is also
527saved in per-window state arrays that can be polled with @ref
528glfwGetMouseButton. This is not effected by the @ref GLFW_UNLIMITED_MOUSE_BUTTONS
529input mode.
530
531```c
532int state = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT);
533if (state == GLFW_PRESS)
534{
535    upgrade_cow();
536}
537```
538
539The returned state is one of `GLFW_PRESS` or `GLFW_RELEASE`.
540
541This function only returns cached mouse button event state.  It does not poll
542the system for the current state of the mouse button.
543
544@anchor GLFW_STICKY_MOUSE_BUTTONS
545Whenever you poll state, you risk missing the state change you are looking for.
546If a pressed mouse button is released again before you poll its state, you will have
547missed the button press.  The recommended solution for this is to use a
548mouse button callback, but there is also the `GLFW_STICKY_MOUSE_BUTTONS`
549input mode.
550
551```c
552glfwSetInputMode(window, GLFW_STICKY_MOUSE_BUTTONS, GLFW_TRUE);
553```
554
555When sticky mouse buttons mode is enabled, the pollable state of a mouse button
556will remain `GLFW_PRESS` until the state of that button is polled with @ref
557glfwGetMouseButton.  Once it has been polled, if a mouse button release event
558had been processed in the meantime, the state will reset to `GLFW_RELEASE`,
559otherwise it will remain `GLFW_PRESS`.
560
561The `GLFW_MOUSE_BUTTON_LAST` constant holds the highest value of any
562[mouse button token](@ref buttons).
563
564
565### Scroll input {#scrolling}
566
567If you wish to be notified when the user scrolls, whether with a mouse wheel or
568touchpad gesture, set a scroll callback.
569
570```c
571glfwSetScrollCallback(window, scroll_callback);
572```
573
574The callback function receives two-dimensional scroll offsets.
575
576```c
577void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
578{
579}
580```
581
582A normal mouse wheel, being vertical, provides offsets along the Y-axis.
583
584
585## Joystick input {#joystick}
586
587The joystick functions expose connected joysticks and controllers, with both
588referred to as joysticks.  It supports up to sixteen joysticks, ranging from
589`GLFW_JOYSTICK_1`, `GLFW_JOYSTICK_2` up to and including `GLFW_JOYSTICK_16` or
590`GLFW_JOYSTICK_LAST`.  You can test whether a [joystick](@ref joysticks) is
591present with @ref glfwJoystickPresent.
592
593```c
594int present = glfwJoystickPresent(GLFW_JOYSTICK_1);
595```
596
597Each joystick has zero or more axes, zero or more buttons, zero or more hats,
598a human-readable name, a user pointer and an SDL compatible GUID.
599
600Detected joysticks are added to the beginning of the array.  Once a joystick is
601detected, it keeps its assigned ID until it is disconnected or the library is
602terminated, so as joysticks are connected and disconnected, there may appear
603gaps in the IDs.
604
605Joystick axis, button and hat state is updated when polled and does not require
606a window to be created or events to be processed.  However, if you want joystick
607connection and disconnection events reliably delivered to the
608[joystick callback](@ref joystick_event) then you must
609[process events](@ref events).
610
611To see all the properties of all connected joysticks in real-time, run the
612`joysticks` test program.
613
614
615### Joystick axis states {#joystick_axis}
616
617The positions of all axes of a joystick are returned by @ref
618glfwGetJoystickAxes.  See the reference documentation for the lifetime of the
619returned array.
620
621```c
622int count;
623const float* axes = glfwGetJoystickAxes(GLFW_JOYSTICK_5, &count);
624```
625
626Each element in the returned array is a value between -1.0 and 1.0.
627
628
629### Joystick button states {#joystick_button}
630
631The states of all buttons of a joystick are returned by @ref
632glfwGetJoystickButtons.  See the reference documentation for the lifetime of the
633returned array.
634
635```c
636int count;
637const unsigned char* buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_3, &count);
638```
639
640Each element in the returned array is either `GLFW_PRESS` or `GLFW_RELEASE`.
641
642For backward compatibility with earlier versions that did not have @ref
643glfwGetJoystickHats, the button array by default also includes all hats.  See
644the reference documentation for @ref glfwGetJoystickButtons for details.
645
646
647### Joystick hat states {#joystick_hat}
648
649The states of all hats are returned by @ref glfwGetJoystickHats.  See the
650reference documentation for the lifetime of the returned array.
651
652```c
653int count;
654const unsigned char* hats = glfwGetJoystickHats(GLFW_JOYSTICK_7, &count);
655```
656
657Each element in the returned array is one of the following:
658
659Name                  | Value
660----                  | -----
661`GLFW_HAT_CENTERED`   | 0
662`GLFW_HAT_UP`         | 1
663`GLFW_HAT_RIGHT`      | 2
664`GLFW_HAT_DOWN`       | 4
665`GLFW_HAT_LEFT`       | 8
666`GLFW_HAT_RIGHT_UP`   | `GLFW_HAT_RIGHT` \| `GLFW_HAT_UP`
667`GLFW_HAT_RIGHT_DOWN` | `GLFW_HAT_RIGHT` \| `GLFW_HAT_DOWN`
668`GLFW_HAT_LEFT_UP`    | `GLFW_HAT_LEFT` \| `GLFW_HAT_UP`
669`GLFW_HAT_LEFT_DOWN`  | `GLFW_HAT_LEFT` \| `GLFW_HAT_DOWN`
670
671The diagonal directions are bitwise combinations of the primary (up, right, down
672and left) directions and you can test for these individually by ANDing it with
673the corresponding direction.
674
675```c
676if (hats[2] & GLFW_HAT_RIGHT)
677{
678    // State of hat 2 could be right-up, right or right-down
679}
680```
681
682For backward compatibility with earlier versions that did not have @ref
683glfwGetJoystickHats, all hats are by default also included in the button array.
684See the reference documentation for @ref glfwGetJoystickButtons for details.
685
686
687### Joystick name {#joystick_name}
688
689The human-readable, UTF-8 encoded name of a joystick is returned by @ref
690glfwGetJoystickName.  See the reference documentation for the lifetime of the
691returned string.
692
693```c
694const char* name = glfwGetJoystickName(GLFW_JOYSTICK_4);
695```
696
697Joystick names are not guaranteed to be unique.  Two joysticks of the same model
698and make may have the same name.  Only the [joystick ID](@ref joysticks) is
699guaranteed to be unique, and only until that joystick is disconnected.
700
701
702### Joystick user pointer {#joystick_userptr}
703
704Each joystick has a user pointer that can be set with @ref
705glfwSetJoystickUserPointer and queried with @ref glfwGetJoystickUserPointer.
706This can be used for any purpose you need and will not be modified by GLFW.  The
707value will be kept until the joystick is disconnected or until the library is
708terminated.
709
710The initial value of the pointer is `NULL`.
711
712
713### Joystick configuration changes {#joystick_event}
714
715If you wish to be notified when a joystick is connected or disconnected, set
716a joystick callback.
717
718```c
719glfwSetJoystickCallback(joystick_callback);
720```
721
722The callback function receives the ID of the joystick that has been connected
723and disconnected and the event that occurred.
724
725```c
726void joystick_callback(int jid, int event)
727{
728    if (event == GLFW_CONNECTED)
729    {
730        // The joystick was connected
731    }
732    else if (event == GLFW_DISCONNECTED)
733    {
734        // The joystick was disconnected
735    }
736}
737```
738
739For joystick connection and disconnection events to be delivered on all
740platforms, you need to call one of the [event processing](@ref events)
741functions.  Joystick disconnection may also be detected and the callback
742called by joystick functions.  The function will then return whatever it
743returns for a disconnected joystick.
744
745Only @ref glfwGetJoystickName and @ref glfwGetJoystickUserPointer will return
746useful values for a disconnected joystick and only before the monitor callback
747returns.
748
749
750### Gamepad input {#gamepad}
751
752The joystick functions provide unlabeled axes, buttons and hats, with no
753indication of where they are located on the device.  Their order may also vary
754between platforms even with the same device.
755
756To solve this problem the SDL community crowdsourced the
757[SDL_GameControllerDB][] project, a database of mappings from many different
758devices to an Xbox-like gamepad.
759
760[SDL_GameControllerDB]: https://github.com/gabomdq/SDL_GameControllerDB
761
762GLFW supports this mapping format and contains a copy of the mappings
763available at the time of release.  See @ref gamepad_mapping for how to update
764this at runtime.  Mappings will be assigned to joysticks automatically any time
765a joystick is connected or the mappings are updated.
766
767You can check whether a joystick is both present and has a gamepad mapping with
768@ref glfwJoystickIsGamepad.
769
770```c
771if (glfwJoystickIsGamepad(GLFW_JOYSTICK_2))
772{
773    // Use as gamepad
774}
775```
776
777If you are only interested in gamepad input you can use this function instead of
778@ref glfwJoystickPresent.
779
780You can query the human-readable name provided by the gamepad mapping with @ref
781glfwGetGamepadName.  This may or may not be the same as the
782[joystick name](@ref joystick_name).
783
784```c
785const char* name = glfwGetGamepadName(GLFW_JOYSTICK_7);
786```
787
788To retrieve the gamepad state of a joystick, call @ref glfwGetGamepadState.
789
790```c
791GLFWgamepadstate state;
792
793if (glfwGetGamepadState(GLFW_JOYSTICK_3, &state))
794{
795    if (state.buttons[GLFW_GAMEPAD_BUTTON_A])
796    {
797        input_jump();
798    }
799
800    input_speed(state.axes[GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER]);
801}
802```
803
804The @ref GLFWgamepadstate struct has two arrays; one for button states and one
805for axis states.  The values for each button and axis are the same as for the
806@ref glfwGetJoystickButtons and @ref glfwGetJoystickAxes functions, i.e.
807`GLFW_PRESS` or `GLFW_RELEASE` for buttons and -1.0 to 1.0 inclusive for axes.
808
809The sizes of the arrays and the positions within each array are fixed.
810
811The [button indices](@ref gamepad_buttons) are `GLFW_GAMEPAD_BUTTON_A`,
812`GLFW_GAMEPAD_BUTTON_B`, `GLFW_GAMEPAD_BUTTON_X`, `GLFW_GAMEPAD_BUTTON_Y`,
813`GLFW_GAMEPAD_BUTTON_LEFT_BUMPER`, `GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER`,
814`GLFW_GAMEPAD_BUTTON_BACK`, `GLFW_GAMEPAD_BUTTON_START`,
815`GLFW_GAMEPAD_BUTTON_GUIDE`, `GLFW_GAMEPAD_BUTTON_LEFT_THUMB`,
816`GLFW_GAMEPAD_BUTTON_RIGHT_THUMB`, `GLFW_GAMEPAD_BUTTON_DPAD_UP`,
817`GLFW_GAMEPAD_BUTTON_DPAD_RIGHT`, `GLFW_GAMEPAD_BUTTON_DPAD_DOWN` and
818`GLFW_GAMEPAD_BUTTON_DPAD_LEFT`.
819
820For those who prefer, there are also the `GLFW_GAMEPAD_BUTTON_CROSS`,
821`GLFW_GAMEPAD_BUTTON_CIRCLE`, `GLFW_GAMEPAD_BUTTON_SQUARE` and
822`GLFW_GAMEPAD_BUTTON_TRIANGLE` aliases for the A, B, X and Y button indices.
823
824The [axis indices](@ref gamepad_axes) are `GLFW_GAMEPAD_AXIS_LEFT_X`,
825`GLFW_GAMEPAD_AXIS_LEFT_Y`, `GLFW_GAMEPAD_AXIS_RIGHT_X`,
826`GLFW_GAMEPAD_AXIS_RIGHT_Y`, `GLFW_GAMEPAD_AXIS_LEFT_TRIGGER` and
827`GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER`.
828
829The `GLFW_GAMEPAD_BUTTON_LAST` and `GLFW_GAMEPAD_AXIS_LAST` constants equal
830the largest available index for each array.
831
832
833### Gamepad mappings {#gamepad_mapping}
834
835GLFW contains a copy of the mappings available in [SDL_GameControllerDB][] at
836the time of release.  Newer ones can be added at runtime with @ref
837glfwUpdateGamepadMappings.
838
839```c
840const char* mappings = load_file_contents("game/data/gamecontrollerdb.txt");
841
842glfwUpdateGamepadMappings(mappings);
843```
844
845This function supports everything from single lines up to and including the
846unmodified contents of the whole `gamecontrollerdb.txt` file.
847
848If you are compiling GLFW from source with CMake you can update the built-in mappings by
849building the _update_mappings_ target.  This runs the `GenerateMappings.cmake` CMake
850script, which downloads `gamecontrollerdb.txt` and regenerates the `mappings.h` header
851file.
852
853Below is a description of the mapping format.  Please keep in mind that __this
854description is not authoritative__.  The format is defined by the SDL and
855SDL_GameControllerDB projects and their documentation and code takes precedence.
856
857Each mapping is a single line of comma-separated values describing the GUID,
858name and layout of the gamepad.  Lines that do not begin with a hexadecimal
859digit are ignored.
860
861The first value is always the gamepad GUID, a 32 character long hexadecimal
862string that typically identifies its make, model, revision and the type of
863connection to the computer.  When this information is not available, the GUID is
864generated using the gamepad name.  GLFW uses the SDL 2.0.5+ GUID format but can
865convert from the older formats.
866
867The second value is always the human-readable name of the gamepad.
868
869All subsequent values are in the form `<field>:<value>` and describe the layout
870of the mapping.  These fields may not all be present and may occur in any order.
871
872The button fields are `a`, `b`, `x`, `y`, `back`, `start`, `guide`, `dpup`,
873`dpright`, `dpdown`, `dpleft`, `leftshoulder`, `rightshoulder`, `leftstick` and
874`rightstick`.
875
876The axis fields are `leftx`, `lefty`, `rightx`, `righty`, `lefttrigger` and
877`righttrigger`.
878
879The value of an axis or button field can be a joystick button, a joystick axis,
880a hat bitmask or empty.  Joystick buttons are specified as `bN`, for example
881`b2` for the third button.  Joystick axes are specified as `aN`, for example
882`a7` for the eighth button.  Joystick hat bit masks are specified as `hN.N`, for
883example `h0.8` for left on the first hat.  More than one bit may be set in the
884mask.
885
886Before an axis there may be a `+` or `-` range modifier, for example `+a3` for
887the positive half of the fourth axis.  This restricts input to only the positive
888or negative halves of the joystick axis.  After an axis or half-axis there may
889be the `~` inversion modifier, for example `a2~` or `-a7~`.  This negates the
890values of the gamepad axis.
891
892The hat bit mask match the [hat states](@ref hat_state) in the joystick
893functions.
894
895There is also the special `platform` field that specifies which platform the
896mapping is valid for.  Possible values are `Windows`, `Mac OS X` and `Linux`.
897
898Below is an example of what a gamepad mapping might look like.  It is the
899one built into GLFW for Xbox controllers accessed via the XInput API on Windows.
900This example has been broken into several lines to fit on the page, but real
901gamepad mappings must be a single line.
902
903```
90478696e70757401000000000000000000,XInput Gamepad (GLFW),platform:Windows,a:b0,
905b:b1,x:b2,y:b3,leftshoulder:b4,rightshoulder:b5,back:b6,start:b7,leftstick:b8,
906rightstick:b9,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:a4,
907righttrigger:a5,dpup:h0.1,dpright:h0.2,dpdown:h0.4,dpleft:h0.8,
908```
909
910@note GLFW does not yet support the output range and modifiers `+` and `-` that
911were recently added to SDL.  The input modifiers `+`, `-` and `~` are supported
912and described above.
913
914
915## Time input {#time}
916
917GLFW provides high-resolution time input, in seconds, with @ref glfwGetTime.
918
919```c
920double seconds = glfwGetTime();
921```
922
923It returns the number of seconds since the library was initialized with @ref
924glfwInit.  The platform-specific time sources used typically have micro- or
925nanosecond resolution.
926
927You can modify the base time with @ref glfwSetTime.
928
929```c
930glfwSetTime(4.0);
931```
932
933This sets the time to the specified time, in seconds, and it continues to count
934from there.
935
936You can also access the raw timer used to implement the functions above,
937with @ref glfwGetTimerValue.
938
939```c
940uint64_t value = glfwGetTimerValue();
941```
942
943This value is in 1&nbsp;/&nbsp;frequency seconds.  The frequency of the raw
944timer varies depending on the operating system and hardware.  You can query the
945frequency, in Hz, with @ref glfwGetTimerFrequency.
946
947```c
948uint64_t frequency = glfwGetTimerFrequency();
949```
950
951
952## Clipboard input and output {#clipboard}
953
954If the system clipboard contains a UTF-8 encoded string or if it can be
955converted to one, you can retrieve it with @ref glfwGetClipboardString.  See the
956reference documentation for the lifetime of the returned string.
957
958```c
959const char* text = glfwGetClipboardString(NULL);
960if (text)
961{
962    insert_text(text);
963}
964```
965
966If the clipboard is empty or if its contents could not be converted, `NULL` is
967returned.
968
969The contents of the system clipboard can be set to a UTF-8 encoded string with
970@ref glfwSetClipboardString.
971
972```c
973glfwSetClipboardString(NULL, "A string with words in it");
974```
975
976
977## Path drop input {#path_drop}
978
979If you wish to receive the paths of files and/or directories dropped on
980a window, set a file drop callback.
981
982```c
983glfwSetDropCallback(window, drop_callback);
984```
985
986The callback function receives an array of paths encoded as UTF-8.
987
988```c
989void drop_callback(GLFWwindow* window, int count, const char** paths)
990{
991    int i;
992    for (i = 0;  i < count;  i++)
993        handle_dropped_file(paths[i]);
994}
995```
996
997The path array and its strings are only valid until the file drop callback
998returns, as they may have been generated specifically for that event.  You need
999to make a deep copy of the array if you want to keep the paths.
1000
1001