Package: glfw-cffi
GLFW-CFFI---------[![Build Status](https://travis-ci.org/brianbruggeman/glfw-cffi.svg)](https://travis-ci.org/brianbruggeman/glfw-cffi)[![PyPI version](https://img.shields.io/pypi/v/glfw-cffi.svg)](https://pypi.python.org/pypi/glfw-cffi)[![Status](https://img.shields.io/pypi/status/glfw-cffi.svg)](https://pypi.python.org/pypi/glfw-cffi)[![Python Compatibility](https://img.shields.io/pypi/pyversions/glfw-cffi.svg)](https://pypi.python.org/pypi/glfw-cffi)[![Downloads](https://img.shields.io/pypi/dm/glfw-cffi.svg?period=week)](https://pypi.python.org/pypi/glfw-cffi)[![Coverage Status](https://coveralls.io/repos/brianbruggeman/glfw-cffi/badge.svg?branch=develop&service=github)](https://coveralls.io/github/brianbruggeman/glfw-cffi?branch=develop)A wrapper for GLFW3 using Python's CFFI.## Motivation:After being frustrated with the options available, I decided to roll myown version of glfw3 using cffi for python.  This package inspects theheader file for glfw's api, and then creates python-wrapped functions.For the most part, this should be transparent.  However, I have nottested the package well enough to know where the bugs are.  So you mayuse at your own risk.Additionally, I have provided a straight copy of the GLFW3 api directlyavailable from the module.  So the module has python friendly functionsas well as the direct C-library calls.  Note that the latter API requiresmore setup to use because you must manage the object conversion fromPython into C and back.The goal for this package is that the user won't know they're usinga C library underneath and the package interface will feel completelynatural within Python.## License:This package is released as Apache 2.0 license.However, at your option, you may apply any OSI approved free softwarelicense you choose provided that you adhere to the free software licensechosen and additionally follow these criteria:a. list the author's name of this software as a contributor to yourfinal productb. provide credit to your end user of your product or software withoutyour end user asking for where you obtained your softwarec. notify the author of this software that you are using this softwared. If you believe there can be some benefit in providing your changesupstream, you'll submit a change request.  While this criteria iscompletely optional, please consider not being a dick.## Installation:GLFW-CFFI uses GLFW3 and attempts to find the header file associated with yourspecific library version to autogenerate the FFI interface.  So a version ofGLFW3 must be available during installation.  If a development version isunavailable, then a version of the `glfw3.h` is included within the `glfw-cffi`package itself.### Installing via pipInstall via `pip install glfw-cffi`.### Installing GLFW3GLFW3 is available for several different platforms:- Ubuntu/Debian: `sudo apt-get install -y libglfw3-dev`- Fedora/Red Hat: `sudo yum install -y libglfw3-dev`- Mac OS X with Homebrew: `brew install glfw3`- Windows: There is are pre-compiled binaries available[64-bit Windows](https://github.com/glfw/glfw/releases/download/3.1.2/glfw-3.1.2.bin.WIN64.zip) or[32-bit Windows](https://github.com/glfw/glfw/releases/download/3.1.2/glfw-3.1.2.bin.WIN32.zip)GLFW3 is relatively new, so some older installations of Linux may not have`libglfw` directly available.  You may check out the [travis.yml](https://github.com/brianbruggeman/glfw-cffi/blob/master/.travis.yml#L34-L52)file within our github repo for more information on setup on older systems.#### A special note for installing GLFW3 on WindowsThe current state requires that an environment variable, 'GLFW_LIBRARY', be setand pointing to a compiled .dll found within a known path.  In addition,glfw-cffi expects that a header file be present within an 'include' folderwithin the same folder structure as the .dll.  So for example, if thelibrary binary were added to:C:\GLFW\lib\glfw3.dllThe python library, glfw-cffi, would search for a glfw3.h file within any ofthese folders:C:\GLFW\lib\includeC:\GLFW\includeC:\includeWhen testing, we used the 32-bit binary and lib-mingw on a 64-bit Windows 10system.## Usage:### Sample Usage:This is the required code to produce a window on the screen:import glfw# Initialize glfwif not glfw.init():glfw.terminate()  # Cleans up if necessaryraise RuntimeError('Could not initialize GLFW3')# Create window and set OpenGL Contextwin = glfw.create_window(title='Simple Window', width=640, height=480)glfw.make_context_current(win)# Main Loopwhile not glfw.window_should_close(win):glfw.swap_buffers(win)# To handle/process events use:glfw.poll_events()  # for continuous rendering (like in games)# or use:# glfw.wait_events()  # for on-event UIs (like an editing tool)# Proper shutdownglfw.terminate()A more complex window example can be found within the examples folder on the github repo.### DecoratorsExtra decorators have been added to aid with developing a full user interface, including:- keyboard handling- mouse handling- joystick handling- window events- text events- path drop callbacks  (for drag and drop)- error callbacksEach decorator may be used with a standalone function or decorating a class method.Examples of each type are found in the subsections below.  When decorating a classmethod, use: @[staticmethod](https://docs.python.org/2/library/functions.html#staticmethod).What follows is only the more commonly used.  Better documentation on callbacks canbe found on the [glfw website](http://www.glfw.org/docs/latest/).#### Handling keyboard eventsKeyboard events have a single decorator:- keyboard event:  glfw.decorators.key_callbackExample:import glfw@glfw.decorators.key_callbackdef on_key(win, key, code, action, mods):'''Converts key into an event'''if key in [glfw.KEY_ESCAPE] and action in [glfw.PRESS]:glfw.set_window_should_close(win, gl.GL_TRUE)In addition, helper functions have been added to convert data into strings:def display_data(key, action, mods):'''Converts keystroke into string data'''# Convert datakey_action = glfw.get_key_string(key)action_string = glfw.get_action_string(action)mods_string = glfw.get_mod_string(mods)# Display dataprint('key: {key} -> "{string}"'.format(key=key, string=key_string))print('action: {action} -> "{string}"'.format(action=action, string=action_string))print('mods: {mods} -> "{string}"'.format(mods=mods, string=mods_string))Finally, sometimes keystroke handling may make sense to be included within a class.import glfwfrom OpenGL import GL as glclass Foo(object):@staticmethod@glfw.decorators.key_callbackdef on_key(win, key, code, action, mods):'''Handles a key event'''if key in [glfw.KEY_ESCAPE] and action in [glfw.PRESS]:glfw.set_window_should_close(win, gl.GL_TRUE)# Display what just happenedkey = glfw.get_key_string(key)amapping = {'press': '+', 'release': '-', 'repeat': '*'}action = amapping.get(glfw.get_action_string(action))mods = glfw.get_mod_string(mods)string = '{}|{}'.format(action[0], '+'.join(str(_) for _ in (mods, key) if _))print(string)#### Handling mouse eventsMouse events have three decorators:- mouse button click:  glfw.decorators.mouse_button_callback- mouse wheel/scroll: glfw.decorators.scroll_callback- mouse movement: glfw.decorators.cursor_pos_callbackExample:import glfwfrom OpenGL import GL as glclass Foo(object):@staticmethod@glfw.decorators.mouse_button_callbackdef on_mouse_button(win, button, action, mods):'''Handles a mouse button event'''# Not used here, but having the position where the mouse was at the#  time of the click can be useful.position = glfw.get_cursor_pos(win)# Handle buttonif button in [glfw.MOUSE_BUTTON_1] and action in [glfw.PRESS]:glfw.set_window_should_close(win, gl.GL_TRUE)# Display what just happenedbutton = glfw.get_mouse_button_string(button)amapping = {'press': '+', 'release': '-', 'repeat': '*'}action = amapping.get(glfw.get_action_string(action))mods = glfw.get_mod_string(mods)position = '({:>.0f}, {:>.0f})'.format(*position)string = '{} {}|{}'.format(position, action[0], '+'.join(str(_) for _ in (mods, button) if _))print(string)@staticmethod@glfw.decorators.scroll_callbackdef on_mouse_scroll(win, x_offset, y_offset):'''Handles a mouse scroll/wheel event'''@staticmethod@glfw.decorators.cursor_pos_callbackdef on_mouse_move(win, x_offset, y_offset):'''Handles a mouse move event'''#### Handling window eventsThere are other available decorators that handle window events.##### Gaining and Losing FocusWindows client areas may gain or lose focus and an event istriggered each time.- client focus: glfw.decorators.cursor_enter_callback- window focus: glfw.decorators.window_focus_callbackExample:import glfwclass Foo(object):@staticmethod@glfw.decorators.cursor_enter_callbackdef on_enter(win, status):'''Handles focus event for a window client areastatus is a boolean:  True for focused and False for unfocused'''@staticmethod@glfw.decorators.window_focus_callbackdef on_enter(win, status):'''Handles focus event for a windowstatus is a boolean:  True for focused and False for unfocused'''##### ResizingWindows may be resized.- resize: glfw.decorators.window_size_callbackExample:import glfwclass Foo(object):@staticmethod@glfw.decorators.window_size_callbackdef on_enter(win, width, height):'''Handles resize event'''## Examples:More examples can be within the github repo under the [examples/](https://github.com/brianbruggeman/glfw-cffi/tree/develop/examples) folder.Some of the examples require more packages to be installed:- [docopt](https://pypi.python.org/pypi/docopt):  Creates beautiful command-line interfaces- [numpy](https://pypi.python.org/pypi/numpy):  is a general-purpose array-processing package designed to efficiently manipulate large multi-dimensional arrays of arbitrary records without sacrificing too much speed for small multi-dimensional arrays- [freetype-py](https://pypi.python.org/pypi/freetype-py/): Freetype python provides bindings for the FreeType library. Only the high-level API is bound.## Contributions:Contributions are welcome. When opening a PR, please keep the following guidelines in mind:- Before implementing, please open an issue for discussion.- Make sure you have tests for the new logic.- Make sure your code passes `flake8`- Add yourself to contributors at `README.md` and/or  your contributions.## Contributors* [Brian Bruggeman](https://github.com/brianbruggeman) - Originator