• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*!
2
3@page input_guide Input guide
4
5@tableofcontents
6
7This guide introduces the input related functions of GLFW.  For details on
8a specific function in this category, see the @ref input.  There are also guides
9for the other areas of GLFW.
10
11 - @ref intro_guide
12 - @ref window_guide
13 - @ref context_guide
14 - @ref vulkan_guide
15 - @ref monitor_guide
16
17GLFW provides many kinds of input.  While some can only be polled, like time, or
18only received via callbacks, like scrolling, there are those that provide both
19callbacks and polling.  Where a callback is provided, that is the recommended
20way to receive that kind of input.  The more you can use callbacks the less time
21your users' machines will need to spend polling.
22
23All input callbacks receive a window handle.  By using the
24[window user pointer](@ref window_userptr), you can access non-global structures
25or objects from your callbacks.
26
27To get a better feel for how the various events callbacks behave, run the
28`events` test program.  It register every callback supported by GLFW and prints
29out all arguments provided for every event, along with time and sequence
30information.
31
32
33@section events Event processing
34
35GLFW needs to communicate regularly with the window system both in order to
36receive events and to show that the application hasn't locked up.  Event
37processing must be done regularly while you have any windows and is normally
38done each frame after [buffer swapping](@ref buffer_swap).  Even when you have
39no windows, event polling needs to be done in order to receive monitor
40connection events.
41
42There are two functions for processing pending events.  @ref glfwPollEvents,
43processes only those events that have already been received and then returns
44immediately.
45
46@code
47glfwPollEvents();
48@endcode
49
50This is the best choice when rendering continually, like most games do.
51
52If you only need to update the contents of the window when you receive new
53input, @ref glfwWaitEvents is a better choice.
54
55@code
56glfwWaitEvents();
57@endcode
58
59It puts the thread to sleep until at least one event has been received and then
60processes all received events.  This saves a great deal of CPU cycles and is
61useful for, for example, editing tools.  There must be at least one GLFW window
62for this function to sleep.
63
64If you want to wait for events but have UI elements that need periodic updates,
65call @ref glfwWaitEventsTimeout.
66
67@code
68glfwWaitEventsTimeout(0.7);
69@endcode
70
71It puts the thread to sleep until at least one event has been received, or until
72the specified number of seconds have elapsed.  It then processes any received
73events.
74
75If the main thread is sleeping in @ref glfwWaitEvents, you can wake it from
76another thread by posting an empty event to the event queue with @ref
77glfwPostEmptyEvent.
78
79@code
80glfwPostEmptyEvent();
81@endcode
82
83Do not assume that callbacks will _only_ be called through either of the above
84functions.  While it is necessary to process events in the event queue, some
85window systems will send some events directly to the application, which in turn
86causes callbacks to be called outside of regular event processing.
87
88
89@section input_keyboard Keyboard input
90
91GLFW divides keyboard input into two categories; key events and character
92events.  Key events relate to actual physical keyboard keys, whereas character
93events relate to the Unicode code points generated by pressing some of them.
94
95Keys and characters do not map 1:1.  A single key press may produce several
96characters, and a single character may require several keys to produce.  This
97may not be the case on your machine, but your users are likely not all using the
98same keyboard layout, input method or even operating system as you.
99
100
101@subsection input_key Key input
102
103If you wish to be notified when a physical key is pressed or released or when it
104repeats, set a key callback.
105
106@code
107glfwSetKeyCallback(window, key_callback);
108@endcode
109
110The callback function receives the [keyboard key](@ref keys), platform-specific
111scancode, key action and [modifier bits](@ref mods).
112
113@code
114void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
115{
116    if (key == GLFW_KEY_E && action == GLFW_PRESS)
117        activate_airship();
118}
119@endcode
120
121The action is one of `GLFW_PRESS`, `GLFW_REPEAT` or `GLFW_RELEASE`.  The key
122will be `GLFW_KEY_UNKNOWN` if GLFW lacks a key token for it, for example
123_E-mail_ and _Play_ keys.
124
125The scancode is unique for every key, regardless of whether it has a key token.
126Scancodes are platform-specific but consistent over time, so keys will have
127different scancodes depending on the platform but they are safe to save to disk.
128
129Key states for [named keys](@ref keys) are also saved in per-window state arrays
130that can be polled with @ref glfwGetKey.
131
132@code
133int state = glfwGetKey(window, GLFW_KEY_E);
134if (state == GLFW_PRESS)
135    activate_airship();
136@endcode
137
138The returned state is one of `GLFW_PRESS` or `GLFW_RELEASE`.
139
140This function only returns cached key event state.  It does not poll the
141system for the current state of the key.
142
143Whenever you poll state, you risk missing the state change you are looking for.
144If a pressed key is released again before you poll its state, you will have
145missed the key press.  The recommended solution for this is to use a
146key callback, but there is also the `GLFW_STICKY_KEYS` input mode.
147
148@code
149glfwSetInputMode(window, GLFW_STICKY_KEYS, 1);
150@endcode
151
152When sticky keys mode is enabled, the pollable state of a key will remain
153`GLFW_PRESS` until the state of that key is polled with @ref glfwGetKey.  Once
154it has been polled, if a key release event had been processed in the meantime,
155the state will reset to `GLFW_RELEASE`, otherwise it will remain `GLFW_PRESS`.
156
157The `GLFW_KEY_LAST` constant holds the highest value of any
158[named key](@ref keys).
159
160
161@subsection input_char Text input
162
163GLFW supports text input in the form of a stream of
164[Unicode code points](https://en.wikipedia.org/wiki/Unicode), as produced by the
165operating system text input system.  Unlike key input, text input obeys keyboard
166layouts and modifier keys and supports composing characters using
167[dead keys](https://en.wikipedia.org/wiki/Dead_key).  Once received, you can
168encode the code points into
169[UTF-8](https://en.wikipedia.org/wiki/UTF-8) or any other encoding you prefer.
170
171Because an `unsigned int` is 32 bits long on all platforms supported by GLFW,
172you can treat the code point argument as native endian
173[UTF-32](https://en.wikipedia.org/wiki/UTF-32).
174
175There are two callbacks for receiving Unicode code points.  If you wish to
176offer regular text input, set a character callback.
177
178@code
179glfwSetCharCallback(window, character_callback);
180@endcode
181
182The callback function receives Unicode code points for key events that would
183have led to regular text input and generally behaves as a standard text field on
184that platform.
185
186@code
187void character_callback(GLFWwindow* window, unsigned int codepoint)
188{
189}
190@endcode
191
192If you wish to receive even those Unicode code points generated with modifier
193key combinations that a plain text field would ignore, or just want to know
194exactly what modifier keys were used, set a character with modifiers callback.
195
196@code
197glfwSetCharModsCallback(window, charmods_callback);
198@endcode
199
200The callback function receives Unicode code points and
201[modifier bits](@ref mods).
202
203@code
204void charmods_callback(GLFWwindow* window, unsigned int codepoint, int mods)
205{
206}
207@endcode
208
209
210@subsection input_key_name Key names
211
212If you wish to refer to keys by name, you can query the keyboard layout
213dependent name of printable keys with @ref glfwGetKeyName.
214
215@code
216const char* key_name = glfwGetKeyName(GLFW_KEY_W, 0);
217show_tutorial_hint("Press %s to move forward", key_name);
218@endcode
219
220This function can handle both [keys and scancodes](@ref input_key).  If the
221specified key is `GLFW_KEY_UNKNOWN` then the scancode is used, otherwise it is
222ignored.  This matches the behavior of the key callback, meaning the callback
223arguments can always be passed unmodified to this function.
224
225
226@section input_mouse Mouse input
227
228Mouse input comes in many forms, including cursor motion, button presses and
229scrolling offsets.  The cursor appearance can also be changed, either to
230a custom image or a standard cursor shape from the system theme.
231
232
233@subsection cursor_pos Cursor position
234
235If you wish to be notified when the cursor moves over the window, set a cursor
236position callback.
237
238@code
239glfwSetCursorPosCallback(window, cursor_pos_callback);
240@endcode
241
242The callback functions receives the cursor position, measured in screen
243coordinates but relative to the top-left corner of the window client area.  On
244platforms that provide it, the full sub-pixel cursor position is passed on.
245
246@code
247static void cursor_position_callback(GLFWwindow* window, double xpos, double ypos)
248{
249}
250@endcode
251
252The cursor position is also saved per-window and can be polled with @ref
253glfwGetCursorPos.
254
255@code
256double xpos, ypos;
257glfwGetCursorPos(window, &xpos, &ypos);
258@endcode
259
260
261@subsection cursor_mode Cursor modes
262
263The `GLFW_CURSOR` input mode provides several cursor modes for special forms of
264mouse motion input.  By default, the cursor mode is `GLFW_CURSOR_NORMAL`,
265meaning the regular arrow cursor (or another cursor set with @ref glfwSetCursor)
266is used and cursor motion is not limited.
267
268If you wish to implement mouse motion based camera controls or other input
269schemes that require unlimited mouse movement, set the cursor mode to
270`GLFW_CURSOR_DISABLED`.
271
272@code
273glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
274@endcode
275
276This will hide the cursor and lock it to the specified window.  GLFW will then
277take care of all the details of cursor re-centering and offset calculation and
278providing the application with a virtual cursor position.  This virtual position
279is provided normally via both the cursor position callback and through polling.
280
281@note You should not implement your own version of this functionality using
282other features of GLFW.  It is not supported and will not work as robustly as
283`GLFW_CURSOR_DISABLED`.
284
285If you just wish the cursor to become hidden when it is over a window, set
286the cursor mode to `GLFW_CURSOR_HIDDEN`.
287
288@code
289glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
290@endcode
291
292This mode puts no limit on the motion of the cursor.
293
294To exit out of either of these special modes, restore the `GLFW_CURSOR_NORMAL`
295cursor mode.
296
297@code
298glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
299@endcode
300
301
302@subsection cursor_object Cursor objects
303
304GLFW supports creating both custom and system theme cursor images, encapsulated
305as @ref GLFWcursor objects.  They are created with @ref glfwCreateCursor or @ref
306glfwCreateStandardCursor and destroyed with @ref glfwDestroyCursor, or @ref
307glfwTerminate, if any remain.
308
309
310@subsubsection cursor_custom Custom cursor creation
311
312A custom cursor is created with @ref glfwCreateCursor, which returns a handle to
313the created cursor object.  For example, this creates a 16x16 white square
314cursor with the hot-spot in the upper-left corner:
315
316@code
317unsigned char pixels[16 * 16 * 4];
318memset(pixels, 0xff, sizeof(pixels));
319
320GLFWimage image;
321image.width = 16;
322image.height = 16;
323image.pixels = pixels;
324
325GLFWcursor* cursor = glfwCreateCursor(&image, 0, 0);
326@endcode
327
328If cursor creation fails, `NULL` will be returned, so it is necessary to check
329the return value.
330
331The image data is 32-bit, little-endian, non-premultiplied RGBA, i.e. eight bits
332per channel.  The pixels are arranged canonically as sequential rows, starting
333from the top-left corner.
334
335
336@subsubsection cursor_standard Standard cursor creation
337
338A cursor with a [standard shape](@ref shapes) from the current system cursor
339theme can be can be created with @ref glfwCreateStandardCursor.
340
341@code
342GLFWcursor* cursor = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR);
343@endcode
344
345These cursor objects behave in the exact same way as those created with @ref
346glfwCreateCursor except that the system cursor theme provides the actual image.
347
348
349@subsubsection cursor_destruction Cursor destruction
350
351When a cursor is no longer needed, destroy it with @ref glfwDestroyCursor.
352
353@code
354glfwDestroyCursor(cursor);
355@endcode
356
357Cursor destruction always succeeds.  All cursors remaining when @ref
358glfwTerminate is called are destroyed as well.
359
360
361@subsubsection cursor_set Cursor setting
362
363A cursor can be set as current for a window with @ref glfwSetCursor.
364
365@code
366glfwSetCursor(window, cursor);
367@endcode
368
369Once set, the cursor image will be used as long as the system cursor is over the
370client area of the window and the [cursor mode](@ref cursor_mode) is set
371to `GLFW_CURSOR_NORMAL`.
372
373A single cursor may be set for any number of windows.
374
375To remove a cursor from a window, set the cursor of that window to `NULL`.
376
377@code
378glfwSetCursor(window, NULL);
379@endcode
380
381When a cursor is destroyed, it is removed from any window where it is set.  This
382does not affect the cursor modes of those windows.
383
384
385@subsection cursor_enter Cursor enter/leave events
386
387If you wish to be notified when the cursor enters or leaves the client area of
388a window, set a cursor enter/leave callback.
389
390@code
391glfwSetCursorEnterCallback(window, cursor_enter_callback);
392@endcode
393
394The callback function receives the new classification of the cursor.
395
396@code
397void cursor_enter_callback(GLFWwindow* window, int entered)
398{
399    if (entered)
400    {
401        // The cursor entered the client area of the window
402    }
403    else
404    {
405        // The cursor left the client area of the window
406    }
407}
408@endcode
409
410
411@subsection input_mouse_button Mouse button input
412
413If you wish to be notified when a mouse button is pressed or released, set
414a mouse button callback.
415
416@code
417glfwSetMouseButtonCallback(window, mouse_button_callback);
418@endcode
419
420The callback function receives the [mouse button](@ref buttons), button action
421and [modifier bits](@ref mods).
422
423@code
424void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
425{
426    if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS)
427        popup_menu();
428}
429@endcode
430
431The action is one of `GLFW_PRESS` or `GLFW_RELEASE`.
432
433Mouse button states for [named buttons](@ref buttons) are also saved in
434per-window state arrays that can be polled with @ref glfwGetMouseButton.
435
436@code
437int state = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT);
438if (state == GLFW_PRESS)
439    upgrade_cow();
440@endcode
441
442The returned state is one of `GLFW_PRESS` or `GLFW_RELEASE`.
443
444This function only returns cached mouse button event state.  It does not poll
445the system for the current state of the mouse button.
446
447Whenever you poll state, you risk missing the state change you are looking for.
448If a pressed mouse button is released again before you poll its state, you will have
449missed the button press.  The recommended solution for this is to use a
450mouse button callback, but there is also the `GLFW_STICKY_MOUSE_BUTTONS`
451input mode.
452
453@code
454glfwSetInputMode(window, GLFW_STICKY_MOUSE_BUTTONS, 1);
455@endcode
456
457When sticky mouse buttons mode is enabled, the pollable state of a mouse button
458will remain `GLFW_PRESS` until the state of that button is polled with @ref
459glfwGetMouseButton.  Once it has been polled, if a mouse button release event
460had been processed in the meantime, the state will reset to `GLFW_RELEASE`,
461otherwise it will remain `GLFW_PRESS`.
462
463The `GLFW_MOUSE_BUTTON_LAST` constant holds the highest value of any
464[named button](@ref buttons).
465
466
467@subsection scrolling Scroll input
468
469If you wish to be notified when the user scrolls, whether with a mouse wheel or
470touchpad gesture, set a scroll callback.
471
472@code
473glfwSetScrollCallback(window, scroll_callback);
474@endcode
475
476The callback function receives two-dimensional scroll offsets.
477
478@code
479void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
480{
481}
482@endcode
483
484A simple mouse wheel, being vertical, provides offsets along the Y-axis.
485
486
487@section joystick Joystick input
488
489The joystick functions expose connected joysticks and controllers, with both
490referred to as joysticks.  It supports up to sixteen joysticks, ranging from
491`GLFW_JOYSTICK_1`, `GLFW_JOYSTICK_2` up to `GLFW_JOYSTICK_LAST`.  You can test
492whether a [joystick](@ref joysticks) is present with @ref glfwJoystickPresent.
493
494@code
495int present = glfwJoystickPresent(GLFW_JOYSTICK_1);
496@endcode
497
498When GLFW is initialized, detected joysticks are added to to the beginning of
499the array, starting with `GLFW_JOYSTICK_1`.  Once a joystick is detected, it
500keeps its assigned index until it is disconnected, so as joysticks are connected
501and disconnected, they will become spread out.
502
503Joystick state is updated as needed when a joystick function is called and does
504not require a window to be created or @ref glfwPollEvents or @ref glfwWaitEvents
505to be called.
506
507
508@subsection joystick_axis Joystick axis states
509
510The positions of all axes of a joystick are returned by @ref
511glfwGetJoystickAxes.  See the reference documentation for the lifetime of the
512returned array.
513
514@code
515int count;
516const float* axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &count);
517@endcode
518
519Each element in the returned array is a value between -1.0 and 1.0.
520
521
522@subsection joystick_button Joystick button states
523
524The states of all buttons of a joystick are returned by @ref
525glfwGetJoystickButtons.  See the reference documentation for the lifetime of the
526returned array.
527
528@code
529int count;
530const unsigned char* axes = glfwGetJoystickButtons(GLFW_JOYSTICK_1, &count);
531@endcode
532
533Each element in the returned array is either `GLFW_PRESS` or `GLFW_RELEASE`.
534
535
536@subsection joystick_name Joystick name
537
538The human-readable, UTF-8 encoded name of a joystick is returned by @ref
539glfwGetJoystickName.  See the reference documentation for the lifetime of the
540returned string.
541
542@code
543const char* name = glfwGetJoystickName(GLFW_JOYSTICK_1);
544@endcode
545
546Joystick names are not guaranteed to be unique.  Two joysticks of the same model
547and make may have the same name.  Only the [joystick token](@ref joysticks) is
548guaranteed to be unique, and only until that joystick is disconnected.
549
550
551@subsection joystick_event Joystick configuration changes
552
553If you wish to be notified when a joystick is connected or disconnected, set
554a joystick callback.
555
556@code
557glfwSetJoystickCallback(joystick_callback);
558@endcode
559
560The callback function receives the ID of the joystick that has been connected
561and disconnected and the event that occurred.
562
563@code
564void joystick_callback(int joy, int event)
565{
566    if (event == GLFW_CONNECTED)
567    {
568        // The joystick was connected
569    }
570    else if (event == GLFW_DISCONNECTED)
571    {
572        // The joystick was disconnected
573    }
574}
575@endcode
576
577
578@section time Time input
579
580GLFW provides high-resolution time input, in seconds, with @ref glfwGetTime.
581
582@code
583double seconds = glfwGetTime();
584@endcode
585
586It returns the number of seconds since the timer was started when the library
587was initialized with @ref glfwInit.  The platform-specific time sources used
588usually have micro- or nanosecond resolution.
589
590You can modify the reference time with @ref glfwSetTime.
591
592@code
593glfwSetTime(4.0);
594@endcode
595
596This sets the timer to the specified time, in seconds.
597
598You can also access the raw timer value, measured in 1 / frequency
599seconds, with @ref glfwGetTimerValue.
600
601@code
602uint64_t value = glfwGetTimerValue();
603@endcode
604
605The frequency of the raw timer varies depending on what time sources are
606available on the machine.  You can query its frequency, in Hz, with @ref
607glfwGetTimerFrequency.
608
609@code
610uint64_t freqency = glfwGetTimerFrequency();
611@endcode
612
613
614@section clipboard Clipboard input and output
615
616If the system clipboard contains a UTF-8 encoded string or if it can be
617converted to one, you can retrieve it with @ref glfwGetClipboardString.  See the
618reference documentation for the lifetime of the returned string.
619
620@code
621const char* text = glfwGetClipboardString(window);
622if (text)
623    insert_text(text);
624@endcode
625
626If the clipboard is empty or if its contents could not be converted, `NULL` is
627returned.
628
629The contents of the system clipboard can be set to a UTF-8 encoded string with
630@ref glfwSetClipboardString.
631
632@code
633glfwSetClipboardString(window, "A string with words in it");
634@endcode
635
636The clipboard functions take a window handle argument because some window
637systems require a window to communicate with the system clipboard.  Any valid
638window may be used.
639
640
641@section path_drop Path drop input
642
643If you wish to receive the paths of files and/or directories dropped on
644a window, set a file drop callback.
645
646@code
647glfwSetDropCallback(window, drop_callback);
648@endcode
649
650The callback function receives an array of paths encoded as UTF-8.
651
652@code
653void drop_callback(GLFWwindow* window, int count, const char** paths)
654{
655    int i;
656    for (i = 0;  i < count;  i++)
657        handle_dropped_file(paths[i]);
658}
659@endcode
660
661The path array and its strings are only valid until the file drop callback
662returns, as they may have been generated specifically for that event.  You need
663to make a deep copy of the array if you want to keep the paths.
664
665*/
666