Magnum::Platform::GlfwApplication class

GLFW application.

Application using the GLFW toolkit. Supports keyboard and mouse handling with support for changing cursor and mouse tracking and warping. Available on all platforms where GLFW is ported.

Bootstrap application

Fully contained base application using GlfwApplication along with CMake setup is available in base-glfw branch of Magnum Bootstrap repository, download it as tar.gz or zip file. After extracting the downloaded archive you can build and run the application with these four commands:

mkdir build && cd build
cmake ..
cmake --build .
./src/MyApplication # or ./src/Debug/MyApplication

See Usage with CMake for more information.

General usage

This application library depends on the GLFW library and is built if MAGNUM_WITH_GLFWAPPLICATION is enabled when building Magnum. To use this library with CMake, put FindGLFW.cmake into your modules/ directory, request the GlfwApplication component of the Magnum package and link to the Magnum::GlfwApplication target:

find_package(Magnum REQUIRED GlfwApplication)

# ...
target_link_libraries(your-app PRIVATE Magnum::GlfwApplication)

Additionally, if you're using Magnum as a CMake subproject, bundle the glfw repository and do the following before calling find_package() to ensure it's enabled, as the library is not built by default. If you want to use system-installed GLFW, omit the first part and point CMAKE_PREFIX_PATH to its installation dir if necessary.

set(GLFW_BUILD_DOCS OFF CACHE BOOL "" FORCE)
# These two will be off-by-default when GLFW 3.4 gets released
set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
add_subdirectory(glfw EXCLUDE_FROM_ALL)

set(MAGNUM_WITH_GLFWAPPLICATION ON CACHE BOOL "" FORCE)
add_subdirectory(magnum EXCLUDE_FROM_ALL)

If no other application is requested, you can also use the generic Magnum::Application alias to simplify porting. Again, see Downloading and building and Usage with CMake for more information.

In C++ code you need to implement at least drawEvent() to be able to draw on the screen. The subclass can be then used directly in main() — see convenience macro MAGNUM_GLFWAPPLICATION_MAIN(). See Platform support for more information.

class MyApplication: public Platform::GlfwApplication {
    // implement required methods...
};
MAGNUM_GLFWAPPLICATION_MAIN(MyApplication)

If no other application header is included, this class is also aliased to Platform::Application and the macro is aliased to MAGNUM_APPLICATION_MAIN() to simplify porting.

DPI awareness

DPI awareness behavior is consistent with Sdl2Application except that iOS or Emscripten specifics don't apply here. In addition, on Windows, GLFW is implicitly advertising DPI awareness, so the manifest file described in HiDPI support doesn't necessarily need to be supplied. See Sdl2Application DPI awareness documentation for more information.

Public types

struct Arguments
Application arguments.
class Configuration
Configuration.
class ExitEvent
Exit event.
class GLConfiguration
OpenGL context configuration.
class InputEvent
Base for input events.
class KeyEvent
Key event.
class MouseEvent
Mouse event.
class MouseMoveEvent
Mouse move event.
class MouseScrollEvent
Mouse scroll event.
class TextInputEvent
Text input event.
class ViewportEvent
Viewport event.

Constructors, destructors, conversion operators

GlfwApplication(const Arguments& arguments, const Configuration& configuration, const GLConfiguration& glConfiguration) explicit
Construct with an OpenGL context.
GlfwApplication(const Arguments& arguments, const Configuration& configuration = Configuration{}) explicit
Construct without explicit GPU context configuration.
GlfwApplication(const Arguments& arguments, NoCreateT) explicit
Construct without creating a window.
GlfwApplication(const GlfwApplication&) deleted
Copying is not allowed.
GlfwApplication(GlfwApplication&&) deleted
Moving is not allowed.

Public functions

auto operator=(const GlfwApplication&) -> GlfwApplication& deleted
Copying is not allowed.
auto operator=(GlfwApplication&&) -> GlfwApplication& deleted
Moving is not allowed.
auto exec() -> int
Execute main loop.
auto mainLoopIteration() -> bool new in 2020.06
Run one iteration of application main loop.
void exit(int exitCode = 0)
Exit application.
auto window() -> GLFWwindow*
Underlying window handle.

Protected functions

void create(const Configuration& configuration, const GLConfiguration& glConfiguration)
Create a window with given configuration for OpenGL context.
void create(const Configuration& configuration)
Create a window with given configuration.
void create()
Create a window with default configuration and OpenGL context.
auto tryCreate(const Configuration& configuration, const GLConfiguration& glConfiguration) -> bool
Try to create context with given configuration for OpenGL context.
auto tryCreate(const Configuration& configuration) -> bool
Try to create context with given configuration.

Screen handling

auto windowSize() const -> Vector2i
Window size.
void setWindowSize(const Vector2i& size) new in 2020.06
Set window size.
void setMinWindowSize(const Vector2i& size = {-1, -1}) new in 2019.10
Set window minimum size.
void setMaxWindowSize(const Vector2i& size = {-1, -1}) new in 2019.10
Set window maximum size.
auto framebufferSize() const -> Vector2i
Framebuffer size.
auto dpiScaling() const -> Vector2
DPI scaling.
auto dpiScaling(const Configuration& configuration) -> Vector2
DPI scaling for given configuration.
void setWindowTitle(Containers::StringView title) new in 2019.10
Set window title.
void setWindowIcon(Containers::ArrayView<const ImageView2D> images) new in Git master
Set window icon.
void setWindowIcon(std::initializer_list<ImageView2D> images) new in 2020.06
void setWindowIcon(const ImageView2D& image) new in 2020.06
void swapBuffers()
Swap buffers.
void setSwapInterval(Int interval)
Set swap interval.
void redraw()
Redraw immediately.
void viewportEvent(ViewportEvent& event) private virtual
Viewport event.
void drawEvent() private pure virtual
Draw event.

Keyboard handling

void keyPressEvent(KeyEvent& event) private virtual
Key press event.
void keyReleaseEvent(KeyEvent& event) private virtual
Key release event.

Mouse handling

enum class Cursor: UnsignedInt { Arrow, TextInput, Crosshair, ResizeNWSE, ResizeNESW, ResizeWE, ResizeNS, ResizeAll, No, Hand, Hidden, HiddenLocked } new in 2020.06
Cursor type.
void setCursor(Cursor cursor) new in 2020.06
Set cursor type.
auto cursor() -> Cursor new in 2020.06
Get current cursor type.
void warpCursor(const Vector2i& position) new in 2020.06
Warp mouse cursor to given coordinates.
void mousePressEvent(MouseEvent& event) private virtual
Mouse press event.
void mouseReleaseEvent(MouseEvent& event) private virtual
Mouse release event.
void mouseMoveEvent(MouseMoveEvent& event) private virtual
Mouse move event.
void mouseScrollEvent(MouseScrollEvent& event) private virtual
Mouse scroll event.

Text input handling

auto isTextInputActive() const -> bool
Whether text input is active.
void startTextInput()
Start text input.
void stopTextInput()
Stop text input.
void textInputEvent(TextInputEvent& event) private virtual
Text input event.

Special events

void exitEvent(ExitEvent& event) private virtual
Exit event.

Enum documentation

enum class Magnum::Platform::GlfwApplication::Cursor: UnsignedInt new in 2020.06

Cursor type.

Enumerators
Arrow

Arrow

TextInput

Text input

Crosshair

Crosshair

ResizeNWSE

Double arrow pointing northwest and southeast

ResizeNESW

Double arrow pointing northeast and southwest

ResizeWE

Double arrow pointing west and east

ResizeNS

Double arrow pointing north and south

ResizeAll

Four pointed arrow pointing north, south, east, and west

No

Slashed circle or crossbones

Hand

Hand

Hidden

Hidden

HiddenLocked

Hidden and locked

Function documentation

Magnum::Platform::GlfwApplication::GlfwApplication(const Arguments& arguments, const Configuration& configuration, const GLConfiguration& glConfiguration) explicit

Construct with an OpenGL context.

Parameters
arguments Application arguments
configuration Application configuration
glConfiguration OpenGL context configuration

Creates application with default or user-specified configuration. See Configuration for more information. The program exits if the context cannot be created, see tryCreate() for an alternative.

Magnum::Platform::GlfwApplication::GlfwApplication(const Arguments& arguments, const Configuration& configuration = Configuration{}) explicit

Construct without explicit GPU context configuration.

If Configuration::WindowFlag::Contextless is present or Magnum was not built with MAGNUM_TARGET_GL, this creates a window without any GPU context attached, leaving that part on the user.

If none of the flags is present and Magnum was built with MAGNUM_TARGET_GL, this is equivalent to calling GlfwApplication(const Arguments&, const Configuration&, const GLConfiguration&) with default-constructed GLConfiguration.

See also Enabling or disabling features for more information.

Magnum::Platform::GlfwApplication::GlfwApplication(const Arguments& arguments, NoCreateT) explicit

Construct without creating a window.

Parameters
arguments Application arguments

Unlike above, the window is not created and must be created later with create() or tryCreate().

int Magnum::Platform::GlfwApplication::exec()

Execute main loop.

Returns Value for returning from main()

Calls mainLoopIteration() in a loop until exit() is called. See MAGNUM_GLFWAPPLICATION_MAIN() for usage information.

bool Magnum::Platform::GlfwApplication::mainLoopIteration() new in 2020.06

Run one iteration of application main loop.

Returns false if exit() was called and the application should exit, true otherwise

Called internally from exec(). If you want to have better control over how the main loop behaves, you can call this function yourself from your own main() function instead of it being called automatically from exec() / MAGNUM_GLFWAPPLICATION_MAIN().

void Magnum::Platform::GlfwApplication::exit(int exitCode = 0)

Exit application.

Parameters
exitCode The exit code the application should return

When called from application constructor, it will cause the application to exit immediately after constructor ends, without entering the event loop. When called from within an event handler, it will cause it to exit at the start of next event loop iteration. Compared to requesting an application exit using the window close button or the Alt F4 / Cmd Q keyboard shortcut, the exitEvent() isn't called when using this function.

Calling this function from an application constructor is recommended over std::exit() or Fatal, which exit without calling destructors on local scope. Note that, however, you need to explicitly return after calling it, as it can't exit the constructor on its own:

MyApplication::MyApplication(const Arguments& arguments):
    Platform::Application{arguments, NoCreate}
{
    // …

    if(!everythingGoingAsExpected) {
        exit(1);
        return;
    }

    // …
}

GLFWwindow* Magnum::Platform::GlfwApplication::window()

Underlying window handle.

Use in case you need to call GLFW functionality directly.

void Magnum::Platform::GlfwApplication::create(const Configuration& configuration, const GLConfiguration& glConfiguration) protected

Create a window with given configuration for OpenGL context.

Parameters
configuration Application configuration
glConfiguration OpenGL context configuration

Must be called only if the context wasn't created by the constructor itself, i.e. when passing NoCreate to it. Error message is printed and the program exits if the context cannot be created, see tryCreate() for an alternative.

On desktop GL, if version is not specified in glConfiguration, the application first tries to create core context (OpenGL 3.2+) and if that fails, falls back to compatibility OpenGL 2.1 context.

void Magnum::Platform::GlfwApplication::create(const Configuration& configuration) protected

Create a window with given configuration.

If Configuration::WindowFlag::Contextless is present or Magnum was not built with MAGNUM_TARGET_GL, this creates a window without any GPU context attached, leaving that part on the user.

If none of the flags is present and Magnum was built with MAGNUM_TARGET_GL, this is equivalent to calling create(const Configuration&, const GLConfiguration&) with default-constructed GLConfiguration.

See also Enabling or disabling features for more information.

void Magnum::Platform::GlfwApplication::create() protected

Create a window with default configuration and OpenGL context.

Equivalent to calling create(const Configuration&) with default-constructed Configuration.

bool Magnum::Platform::GlfwApplication::tryCreate(const Configuration& configuration, const GLConfiguration& glConfiguration) protected

Try to create context with given configuration for OpenGL context.

Unlike create(const Configuration&, const GLConfiguration&) returns false if the context cannot be created, true otherwise.

bool Magnum::Platform::GlfwApplication::tryCreate(const Configuration& configuration) protected

Try to create context with given configuration.

Unlike create(const Configuration&) returns false if the context cannot be created, true otherwise.

Vector2i Magnum::Platform::GlfwApplication::windowSize() const

Window size.

Window size to which all input event coordinates can be related. Note that, especially on HiDPI systems, it may be different from framebufferSize(). Expects that a window is already created. See DPI awareness for more information.

void Magnum::Platform::GlfwApplication::setWindowSize(const Vector2i& size) new in 2020.06

Set window size.

Parameters
size The size, in screen coordinates

To make the sizing work independently of the display DPI, size is internally multiplied with dpiScaling() before getting applied. Expects that a window is already created.

void Magnum::Platform::GlfwApplication::setMinWindowSize(const Vector2i& size = {-1, -1}) new in 2019.10

Set window minimum size.

Parameters
size The minimum size, in screen coordinates

If a value is set to -1, it will disable/remove the corresponding limit. To make the sizing work independently of the display DPI, size is internally multiplied with dpiScaling() before getting applied. Expects that a window is already created.

void Magnum::Platform::GlfwApplication::setMaxWindowSize(const Vector2i& size = {-1, -1}) new in 2019.10

Set window maximum size.

Parameters
size The maximum size, in screen coordinates

If a value is set to -1, it will disable/remove the corresponding limit. To make the sizing work independently of the display DPI, size is internally multiplied with dpiScaling() before getting applied. Expects that a window is already created.

Vector2i Magnum::Platform::GlfwApplication::framebufferSize() const

Framebuffer size.

Size of the default framebuffer. Note that, especially on HiDPI systems, it may be different from windowSize(). Expects that a window is already created. See DPI awareness for more information.

Vector2 Magnum::Platform::GlfwApplication::dpiScaling() const

DPI scaling.

How the content should be scaled relative to system defaults for given windowSize(). If a window is not created yet, returns zero vector, use dpiScaling(const Configuration&) for calculating a value independently. See DPI awareness for more information.

Vector2 Magnum::Platform::GlfwApplication::dpiScaling(const Configuration& configuration)

DPI scaling for given configuration.

Calculates DPI scaling that would be used when creating a window with given configuration. Takes into account DPI scaling policy and custom scaling specified on the command-line. See DPI awareness for more information.

void Magnum::Platform::GlfwApplication::setWindowTitle(Containers::StringView title) new in 2019.10

Set window title.

The title is expected to be encoded in UTF-8.

void Magnum::Platform::GlfwApplication::setWindowIcon(Containers::ArrayView<const ImageView2D> images) new in Git master

Set window icon.

The images are expected to be with origin at bottom left (which is the default for imported images) and in one of PixelFormat::RGB8Unorm, PixelFormat::RGB8Srgb, PixelFormat::RGBA8Unorm or PixelFormat::RGBA8Srgb formats. If you have just one image, you can use setWindowIcon(const ImageView2D&) instead.

void Magnum::Platform::GlfwApplication::setWindowIcon(std::initializer_list<ImageView2D> images) new in 2020.06

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

void Magnum::Platform::GlfwApplication::setWindowIcon(const ImageView2D& image) new in 2020.06

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

void Magnum::Platform::GlfwApplication::swapBuffers()

Swap buffers.

Paints currently rendered framebuffer on screen.

void Magnum::Platform::GlfwApplication::setSwapInterval(Int interval)

Set swap interval.

Set 0 for no VSync, 1 for enabled VSync. Some platforms support -1 for late swap tearing. Default is driver-dependent.

void Magnum::Platform::GlfwApplication::redraw()

Redraw immediately.

Marks the window for redrawing, resulting in call to drawEvent() in the next iteration. You can call it from drawEvent() itself to redraw immediately without waiting for user input.

void Magnum::Platform::GlfwApplication::viewportEvent(ViewportEvent& event) virtual private

Viewport event.

Called when window size changes. The default implementation does nothing. If you want to respond to size changes, you should pass the new size to GL::DefaultFramebuffer::setViewport() (if using OpenGL) and possibly elsewhere (to SceneGraph::Camera::setViewport(), other framebuffers...).

Note that this function might not get called at all if the window size doesn't change. You should configure the initial state of your cameras, framebuffers etc. in application constructor rather than relying on this function to be called. Size of the window can be retrieved using windowSize(), size of the backing framebuffer via framebufferSize() and DPI scaling using dpiScaling(). See DPI awareness for detailed info about these values.

void Magnum::Platform::GlfwApplication::drawEvent() pure virtual private

Draw event.

Called when the screen is redrawn. You should clean the framebuffer using GL::DefaultFramebuffer::clear() (if using OpenGL) and then add your own drawing functions. After drawing is finished, call swapBuffers(). If you want to draw immediately again, call also redraw().

void Magnum::Platform::GlfwApplication::keyPressEvent(KeyEvent& event) virtual private

Key press event.

Called when an key is pressed. Default implementation does nothing.

void Magnum::Platform::GlfwApplication::keyReleaseEvent(KeyEvent& event) virtual private

Key release event.

Called when an key is released. Default implementation does nothing.

void Magnum::Platform::GlfwApplication::setCursor(Cursor cursor) new in 2020.06

Set cursor type.

Expects that a window is already created. Default is Cursor::Arrow.

void Magnum::Platform::GlfwApplication::mousePressEvent(MouseEvent& event) virtual private

Mouse press event.

Called when mouse button is pressed. Default implementation does nothing.

void Magnum::Platform::GlfwApplication::mouseReleaseEvent(MouseEvent& event) virtual private

Mouse release event.

Called when mouse button is released. Default implementation does nothing.

void Magnum::Platform::GlfwApplication::mouseMoveEvent(MouseMoveEvent& event) virtual private

Mouse move event.

Called when any mouse button is pressed and mouse is moved. Default implementation does nothing.

void Magnum::Platform::GlfwApplication::mouseScrollEvent(MouseScrollEvent& event) virtual private

Mouse scroll event.

Called when a scrolling device is used (mouse wheel or scrolling area on a touchpad). Default implementation does nothing.

bool Magnum::Platform::GlfwApplication::isTextInputActive() const

Whether text input is active.

If text input is active, text input events go to textInputEvent().

void Magnum::Platform::GlfwApplication::startTextInput()

Start text input.

Starts text input that will go to textInputEvent().

void Magnum::Platform::GlfwApplication::stopTextInput()

Stop text input.

Stops text input that went to textInputEvent().

void Magnum::Platform::GlfwApplication::textInputEvent(TextInputEvent& event) virtual private

Text input event.

Called when text input is active and the text is being input.

void Magnum::Platform::GlfwApplication::exitEvent(ExitEvent& event) virtual private

Exit event.

If implemented, it allows the application to react to an application exit (for example to save its internal state) and suppress it as well (for example to show a exit confirmation dialog). The default implementation calls ExitEvent::setAccepted() on event, which tells the application that it's safe to exit.