Merge branch 'master' into multi-monitor

Conflicts:
	.gitignore
	examples/CMakeLists.txt
	include/GL/glfw3.h
	src/CMakeLists.txt
	src/internal.h
	src/win32_platform.h
	src/win32_window.c
	src/x11_fullscreen.c
	src/x11_platform.h
	tests/listmodes.c
This commit is contained in:
Camilla Berglund
2012-07-05 16:15:01 +02:00
82 changed files with 4090 additions and 6527 deletions
+44 -59
View File
@@ -1,72 +1,57 @@
if(WIN32)
add_definitions(-DWINVER=0x0501)
endif(WIN32)
if(UNIX)
if(_GLFW_HAS_XRANDR)
set(GLFW_PKGLIBS "${GLFW_PKGLIBS} xrandr")
endif(_GLFW_HAS_XRANDR)
if(_GLFW_HAS_XF86VIDMODE)
set(GLFW_PKGLIBS "${GLFW_PKGLIBS} xxf86vm")
endif(_GLFW_HAS_XF86VIDMODE)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/libglfw.pc.cmake
${CMAKE_CURRENT_BINARY_DIR}/libglfw.pc @ONLY)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/libglfw.pc DESTINATION lib/pkgconfig)
endif(UNIX)
include_directories(${GLFW_SOURCE_DIR}/src
${GLFW_BINARY_DIR}/src
${GLFW_INCLUDE_DIR})
${glfw_INCLUDE_DIRS})
set(common_SOURCES error.c fullscreen.c gamma.c init.c input.c
set(common_HEADERS ${GLFW_SOURCE_DIR}/include/GL/glfw3.h internal.h)
set(common_SOURCES clipboard.c error.c fullscreen.c gamma.c init.c input.c
joystick.c monitor.c opengl.c time.c window.c)
if(_GLFW_COCOA_NSGL)
set(libglfw_SOURCES ${common_SOURCES} cocoa_fullscreen.m cocoa_gamma.m
cocoa_init.m cocoa_input.m cocoa_joystick.m
cocoa_opengl.m cocoa_time.m cocoa_window.m)
if (_GLFW_COCOA_NSGL)
set(glfw_HEADERS ${common_HEADERS} cocoa_platform.h)
set(glfw_SOURCES ${common_SOURCES} cocoa_clipboard.m cocoa_fullscreen.m
cocoa_gamma.c cocoa_init.m cocoa_input.m cocoa_joystick.m
cocoa_opengl.m cocoa_time.c cocoa_window.m)
# For some reason, CMake doesn't know about .m
set_source_files_properties(${libglfw_SOURCES} PROPERTIES LANGUAGE C)
elseif(_GLFW_WIN32_WGL)
set(libglfw_SOURCES ${common_SOURCES} win32_fullscreen.c win32_gamma.c
win32_init.c win32_input.c win32_joystick.c
win32_opengl.c win32_time.c win32_window.c
win32_dllmain.c win32_monitor.c)
elseif(_GLFW_X11_GLX)
set(libglfw_SOURCES ${common_SOURCES} x11_fullscreen.c x11_gamma.c
x11_init.c x11_input.c x11_joystick.c
x11_keysym2unicode.c x11_monitor.c x11_opengl.c
x11_time.c x11_window.c)
else()
message(FATAL_ERROR "No supported platform was selected")
endif(_GLFW_COCOA_NSGL)
set_source_files_properties(${glfw_SOURCES} PROPERTIES LANGUAGE C)
elseif (_GLFW_WIN32_WGL)
set(glfw_HEADERS ${common_HEADERS} win32_platform.h)
set(glfw_SOURCES ${common_SOURCES} win32_clipboard.c win32_dllmain.c
win32_fullscreen.c win32_gamma.c win32_init.c win32_input.c
win32_joystick.c win32_monitor.c win32_opengl.c
win32_time.c win32_window.c)
elseif (_GLFW_X11_GLX)
set(glfw_HEADERS ${common_HEADERS} x11_platform.h)
set(glfw_SOURCES ${common_SOURCES} x11_clipboard.c x11_fullscreen.c
x11_gamma.c x11_init.c x11_input.c x11_joystick.c
x11_keysym2unicode.c x11_monitor.c x11_opengl.c x11_time.c
x11_window.c)
endif()
add_library(libglfwStatic STATIC ${libglfw_SOURCES})
add_library(libglfwShared SHARED ${libglfw_SOURCES})
target_link_libraries(libglfwShared ${GLFW_LIBRARIES})
set_target_properties(libglfwStatic libglfwShared PROPERTIES
CLEAN_DIRECT_OUTPUT 1
OUTPUT_NAME glfw)
add_library(glfw ${glfw_SOURCES} ${glfw_HEADERS})
if(WIN32)
# The GLFW DLL needs a special compile-time macro and import library name
set_target_properties(libglfwShared PROPERTIES
DEFINE_SYMBOL GLFW_BUILD_DLL
PREFIX ""
IMPORT_PREFIX ""
IMPORT_SUFFIX "dll.lib")
endif(WIN32)
if (BUILD_SHARED_LIBS)
if(APPLE)
# Append -fno-common to the compile flags to work around a bug in the Apple GCC
get_target_property(CFLAGS libglfwShared COMPILE_FLAGS)
if(NOT CFLAGS)
set(CFLAGS "")
endif(NOT CFLAGS)
set_target_properties(libglfwShared PROPERTIES COMPILE_FLAGS "${CFLAGS} -fno-common")
endif(APPLE)
if (_GLFW_WIN32_WGL)
# The GLFW DLL needs a special compile-time macro and import library name
set_target_properties(glfw PROPERTIES
PREFIX ""
IMPORT_PREFIX ""
IMPORT_SUFFIX "dll.lib")
elseif (_GLFW_COCOA_NSGL)
# Append -fno-common to the compile flags to work around a bug in the Apple GCC
get_target_property(glfw_CFLAGS glfw COMPILE_FLAGS)
if (NOT glfw_CFLAGS)
set(glfw_CFLAGS "")
endif()
set_target_properties(glfw PROPERTIES
COMPILE_FLAGS "${glfw_CFLAGS} -fno-common")
endif()
install(TARGETS libglfwStatic libglfwShared DESTINATION lib)
target_link_libraries(glfw ${glfw_LIBRARIES})
target_link_libraries(glfw LINK_INTERFACE_LIBRARIES)
endif()
install(TARGETS glfw DESTINATION lib)
+30 -12
View File
@@ -1,10 +1,10 @@
//========================================================================
// GLFW - An OpenGL library
// Platform: Cocoa/NSOpenGL
// API Version: 3.0
// Platform: Any
// API version: 3.0
// WWW: http://www.glfw.org/
//------------------------------------------------------------------------
// Copyright (c) 2009-2010 Camilla Berglund <elmindreda@elmindreda.org>
// Copyright (c) 2010 Camilla Berglund <elmindreda@elmindreda.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
@@ -29,28 +29,46 @@
#include "internal.h"
#include <math.h>
#include <string.h>
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
////// GLFW public API //////
//////////////////////////////////////////////////////////////////////////
//========================================================================
// Return timer value in seconds
// Set the clipboard contents
//========================================================================
double _glfwPlatformGetTime(void)
GLFWAPI void glfwSetClipboardString(GLFWwindow handle, const char* string)
{
return [NSDate timeIntervalSinceReferenceDate] -
_glfwLibrary.NS.timer.t0;
_GLFWwindow* window = (_GLFWwindow*) handle;
if (!_glfwInitialized)
{
_glfwSetError(GLFW_NOT_INITIALIZED, NULL);
return;
}
_glfwPlatformSetClipboardString(window, string);
}
//========================================================================
// Set timer value in seconds
// Return the current clipboard contents
//========================================================================
void _glfwPlatformSetTime(double time)
GLFWAPI const char* glfwGetClipboardString(GLFWwindow handle)
{
_glfwLibrary.NS.timer.t0 =
[NSDate timeIntervalSinceReferenceDate] - time;
_GLFWwindow* window = (_GLFWwindow*) handle;
if (!_glfwInitialized)
{
_glfwSetError(GLFW_NOT_INITIALIZED, NULL);
return NULL;
}
return _glfwPlatformGetClipboardString(window);
}
+82
View File
@@ -0,0 +1,82 @@
//========================================================================
// GLFW - An OpenGL library
// Platform: Cocoa/NSOpenGL
// API version: 3.0
// WWW: http://www.glfw.org/
//------------------------------------------------------------------------
// Copyright (c) 2010 Camilla Berglund <elmindreda@elmindreda.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#include "internal.h"
#include <limits.h>
#include <string.h>
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
//========================================================================
// Set the clipboard contents
//========================================================================
void _glfwPlatformSetClipboardString(_GLFWwindow* window, const char* string)
{
NSArray* types = [NSArray arrayWithObjects:NSStringPboardType, nil];
NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
[pasteboard declareTypes:types owner:nil];
[pasteboard setString:[NSString stringWithUTF8String:string]
forType:NSStringPboardType];
}
//========================================================================
// Return the current clipboard contents
//========================================================================
const char* _glfwPlatformGetClipboardString(_GLFWwindow* window)
{
NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
if (![[pasteboard types] containsObject:NSStringPboardType])
{
_glfwSetError(GLFW_FORMAT_UNAVAILABLE, NULL);
return NULL;
}
NSString* object = [pasteboard stringForType:NSStringPboardType];
if (!object)
{
_glfwSetError(GLFW_PLATFORM_ERROR,
"Cocoa/NSGL: Failed to retrieve object from pasteboard");
return NULL;
}
free(_glfwLibrary.NS.clipboardString);
_glfwLibrary.NS.clipboardString = strdup([object UTF8String]);
return _glfwLibrary.NS.clipboardString;
}
+155 -29
View File
@@ -29,47 +29,166 @@
#include "internal.h"
#include <stdlib.h>
#include <limits.h>
//========================================================================
// Check whether the display mode should be included in enumeration
//========================================================================
static BOOL modeIsGood(NSDictionary* mode)
static GLboolean modeIsGood(CGDisplayModeRef mode)
{
// This is a bit controversial, if you've got something other than an
// LCD computer monitor as an output device you might not want these
// checks. You might also want to reject modes which are interlaced,
// or TV out. There is no one-size-fits-all policy that can work here.
// This seems like a decent compromise, but certain applications may
// wish to patch this...
return [[mode objectForKey:(id)kCGDisplayBitsPerPixel] intValue] >= 15 &&
[mode objectForKey:(id)kCGDisplayModeIsSafeForHardware] != nil &&
[mode objectForKey:(id)kCGDisplayModeIsStretched] == nil;
uint32_t flags = CGDisplayModeGetIOFlags(mode);
if (!(flags & kDisplayModeValidFlag) || !(flags & kDisplayModeSafeFlag))
return GL_FALSE;
if (flags & kDisplayModeInterlacedFlag)
return GL_FALSE;
if (flags & kDisplayModeTelevisionFlag)
return GL_FALSE;
if (flags & kDisplayModeStretchedFlag)
return GL_FALSE;
CFStringRef format = CGDisplayModeCopyPixelEncoding(mode);
if (CFStringCompare(format, CFSTR(IO16BitDirectPixels), 0) &&
CFStringCompare(format, CFSTR(IO32BitDirectPixels), 0))
{
CFRelease(format);
return GL_FALSE;
}
CFRelease(format);
return GL_TRUE;
}
//========================================================================
// Convert Core Graphics display mode to GLFW video mode
//========================================================================
static GLFWvidmode vidmodeFromCGDisplayMode(NSDictionary* mode)
static GLFWvidmode vidmodeFromCGDisplayMode(CGDisplayModeRef mode)
{
unsigned int width =
[[mode objectForKey:(id)kCGDisplayWidth] unsignedIntValue];
unsigned int height =
[[mode objectForKey:(id)kCGDisplayHeight] unsignedIntValue];
unsigned int bps =
[[mode objectForKey:(id)kCGDisplayBitsPerSample] unsignedIntValue];
GLFWvidmode result;
result.width = width;
result.height = height;
result.redBits = bps;
result.greenBits = bps;
result.blueBits = bps;
result.width = CGDisplayModeGetWidth(mode);
result.height = CGDisplayModeGetHeight(mode);
CFStringRef format = CGDisplayModeCopyPixelEncoding(mode);
if (CFStringCompare(format, CFSTR(IO16BitDirectPixels), 0) == 0)
{
result.redBits = 5;
result.greenBits = 5;
result.blueBits = 5;
}
else
{
result.redBits = 8;
result.greenBits = 8;
result.blueBits = 8;
}
CFRelease(format);
return result;
}
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
//========================================================================
// Change the current video mode
//========================================================================
GLboolean _glfwSetVideoMode(int* width, int* height, int* bpp, int* refreshRate)
{
CGDisplayModeRef bestMode = NULL;
CFArrayRef modes;
CFIndex count, i;
unsigned int leastSizeDiff = UINT_MAX;
double leastRateDiff = DBL_MAX;
modes = CGDisplayCopyAllDisplayModes(CGMainDisplayID(), NULL);
count = CFArrayGetCount(modes);
for (i = 0; i < count; i++)
{
CGDisplayModeRef mode = (CGDisplayModeRef) CFArrayGetValueAtIndex(modes, i);
if (!modeIsGood(mode))
continue;
int modeBPP;
// Identify display mode pixel encoding
{
CFStringRef format = CGDisplayModeCopyPixelEncoding(mode);
if (CFStringCompare(format, CFSTR(IO16BitDirectPixels), 0) == 0)
modeBPP = 16;
else
modeBPP = 32;
CFRelease(format);
}
int modeWidth = (int) CGDisplayModeGetWidth(mode);
int modeHeight = (int) CGDisplayModeGetHeight(mode);
unsigned int sizeDiff = (abs(modeBPP - *bpp) << 25) |
((modeWidth - *width) * (modeWidth - *width) +
(modeHeight - *height) * (modeHeight - *height));
double rateDiff;
if (*refreshRate > 0)
rateDiff = fabs(CGDisplayModeGetRefreshRate(mode) - *refreshRate);
else
{
// If no refresh rate was specified, then they're all the same
rateDiff = 0;
}
if ((sizeDiff < leastSizeDiff) ||
(sizeDiff == leastSizeDiff && (rateDiff < leastRateDiff)))
{
bestMode = mode;
leastSizeDiff = sizeDiff;
leastRateDiff = rateDiff;
}
}
if (!bestMode)
{
CFRelease(modes);
return GL_FALSE;
}
CGDisplayCapture(CGMainDisplayID());
CGDisplaySetDisplayMode(CGMainDisplayID(), bestMode, NULL);
CFRelease(modes);
return GL_TRUE;
}
//========================================================================
// Restore the previously saved (original) video mode
//========================================================================
void _glfwRestoreVideoMode(void)
{
CGDisplaySetDisplayMode(CGMainDisplayID(),
_glfwLibrary.NS.desktopMode,
NULL);
CGDisplayRelease(CGMainDisplayID());
}
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
@@ -80,19 +199,26 @@ static GLFWvidmode vidmodeFromCGDisplayMode(NSDictionary* mode)
int _glfwPlatformGetVideoModes(GLFWvidmode* list, int maxcount)
{
NSArray* modes = (NSArray*) CGDisplayAvailableModes(CGMainDisplayID());
unsigned int i, j = 0, n = [modes count];
CGDisplayModeRef mode;
CFArrayRef modes;
CFIndex count, i;
int stored = 0;
for (i = 0; i < n && j < (unsigned)maxcount; i++)
modes = CGDisplayCopyAllDisplayModes(CGMainDisplayID(), NULL);
count = CFArrayGetCount(modes);
for (i = 0; i < count && stored < maxcount; i++)
{
NSDictionary *mode = [modes objectAtIndex:i];
mode = (CGDisplayModeRef) CFArrayGetValueAtIndex(modes, i);
if (modeIsGood(mode))
list[j++] = vidmodeFromCGDisplayMode(mode);
list[stored++] = vidmodeFromCGDisplayMode(mode);
}
return j;
CFRelease(modes);
return stored;
}
//========================================================================
// Get the desktop video mode
//========================================================================
+2
View File
@@ -32,6 +32,8 @@
#include <limits.h>
#include <string.h>
#include <ApplicationServices/ApplicationServices.h>
//************************************************************************
//**** GLFW internal functions ****
+52 -160
View File
@@ -27,162 +27,45 @@
//
//========================================================================
// Needed for _NSGetProgname
#include <crt_externs.h>
#include "internal.h"
#include <sys/param.h> // For MAXPATHLEN
//========================================================================
// GLFW application class
// Change to our application bundle's resources directory, if present
//========================================================================
@interface GLFWApplication : NSApplication
@end
@implementation GLFWApplication
// From http://cocoadev.com/index.pl?GameKeyboardHandlingAlmost
// This works around an AppKit bug, where key up events while holding
// down the command key don't get sent to the key window.
- (void)sendEvent:(NSEvent *)event
static void changeToResourcesDirectory(void)
{
if ([event type] == NSKeyUp && ([event modifierFlags] & NSCommandKeyMask))
[[self keyWindow] sendEvent:event];
else
[super sendEvent:event];
}
char resourcesPath[MAXPATHLEN];
@end
CFBundleRef bundle = CFBundleGetMainBundle();
if (!bundle)
return;
CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(bundle);
// Prior to Snow Leopard, we need to use this oddly-named semi-private API
// to get the application menu working properly. Need to be careful in
// case it goes away in a future OS update.
@interface NSApplication (NSAppleMenu)
- (void)setAppleMenu:(NSMenu*)m;
@end
// Keys to search for as potential application names
NSString* GLFWNameKeys[] =
{
@"CFBundleDisplayName",
@"CFBundleName",
@"CFBundleExecutable",
};
//========================================================================
// Try to figure out what the calling application is called
//========================================================================
static NSString* findAppName(void)
{
unsigned int i;
NSDictionary* infoDictionary = [[NSBundle mainBundle] infoDictionary];
for (i = 0; i < sizeof(GLFWNameKeys) / sizeof(GLFWNameKeys[0]); i++)
CFStringRef last = CFURLCopyLastPathComponent(resourcesURL);
if (CFStringCompare(CFSTR("Resources"), last, 0) != kCFCompareEqualTo)
{
id name = [infoDictionary objectForKey:GLFWNameKeys[i]];
if (name &&
[name isKindOfClass:[NSString class]] &&
![@"" isEqualToString:name])
{
return name;
}
CFRelease(last);
CFRelease(resourcesURL);
return;
}
// If we get here, we're unbundled
if (!_glfwLibrary.NS.unbundled)
CFRelease(last);
if (!CFURLGetFileSystemRepresentation(resourcesURL,
true,
(UInt8*) resourcesPath,
MAXPATHLEN))
{
// Could do this only if we discover we're unbundled, but it should
// do no harm...
ProcessSerialNumber psn = { 0, kCurrentProcess };
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
// Having the app in front of the terminal window is also generally
// handy. There is an NSApplication API to do this, but...
SetFrontProcess(&psn);
_glfwLibrary.NS.unbundled = GL_TRUE;
CFRelease(resourcesURL);
return;
}
char** progname = _NSGetProgname();
if (progname && *progname)
{
// TODO: UTF-8?
return [NSString stringWithUTF8String:*progname];
}
CFRelease(resourcesURL);
// Really shouldn't get here
return @"GLFW Application";
}
//========================================================================
// Set up the menu bar (manually)
// This is nasty, nasty stuff -- calls to undocumented semi-private APIs that
// could go away at any moment, lots of stuff that really should be
// localize(d|able), etc. Loading a nib would save us this horror, but that
// doesn't seem like a good thing to require of GLFW's clients.
//========================================================================
static void setUpMenuBar(void)
{
NSString* appName = findAppName();
NSMenu* bar = [[NSMenu alloc] init];
[NSApp setMainMenu:bar];
NSMenuItem* appMenuItem =
[bar addItemWithTitle:@"" action:NULL keyEquivalent:@""];
NSMenu* appMenu = [[NSMenu alloc] init];
[appMenuItem setSubmenu:appMenu];
[appMenu addItemWithTitle:[NSString stringWithFormat:@"About %@", appName]
action:@selector(orderFrontStandardAboutPanel:)
keyEquivalent:@""];
[appMenu addItem:[NSMenuItem separatorItem]];
NSMenu* servicesMenu = [[NSMenu alloc] init];
[NSApp setServicesMenu:servicesMenu];
[[appMenu addItemWithTitle:@"Services"
action:NULL
keyEquivalent:@""] setSubmenu:servicesMenu];
[appMenu addItem:[NSMenuItem separatorItem]];
[appMenu addItemWithTitle:[NSString stringWithFormat:@"Hide %@", appName]
action:@selector(hide:)
keyEquivalent:@"h"];
[[appMenu addItemWithTitle:@"Hide Others"
action:@selector(hideOtherApplications:)
keyEquivalent:@"h"]
setKeyEquivalentModifierMask:NSAlternateKeyMask | NSCommandKeyMask];
[appMenu addItemWithTitle:@"Show All"
action:@selector(unhideAllApplications:)
keyEquivalent:@""];
[appMenu addItem:[NSMenuItem separatorItem]];
[appMenu addItemWithTitle:[NSString stringWithFormat:@"Quit %@", appName]
action:@selector(terminate:)
keyEquivalent:@"q"];
NSMenuItem* windowMenuItem =
[bar addItemWithTitle:@"" action:NULL keyEquivalent:@""];
NSMenu* windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
[NSApp setWindowsMenu:windowMenu];
[windowMenuItem setSubmenu:windowMenu];
[windowMenu addItemWithTitle:@"Miniaturize"
action:@selector(performMiniaturize:)
keyEquivalent:@"m"];
[windowMenu addItemWithTitle:@"Zoom"
action:@selector(performZoom:)
keyEquivalent:@""];
[windowMenu addItem:[NSMenuItem separatorItem]];
[windowMenu addItemWithTitle:@"Bring All to Front"
action:@selector(arrangeInFront:)
keyEquivalent:@""];
// At least guard the call to private API to avoid an exception if it
// goes away. Hopefully that means the worst we'll break in future is to
// look ugly...
if ([NSApp respondsToSelector:@selector(setAppleMenu:)])
[NSApp setAppleMenu:appMenu];
chdir(resourcesPath);
}
@@ -198,43 +81,39 @@ int _glfwPlatformInit(void)
{
_glfwLibrary.NS.autoreleasePool = [[NSAutoreleasePool alloc] init];
// Implicitly create shared NSApplication instance
[GLFWApplication sharedApplication];
_glfwLibrary.NS.OpenGLFramework =
_glfwLibrary.NSGL.framework =
CFBundleGetBundleWithIdentifier(CFSTR("com.apple.opengl"));
if (_glfwLibrary.NS.OpenGLFramework == NULL)
if (_glfwLibrary.NSGL.framework == NULL)
{
_glfwSetError(GLFW_PLATFORM_ERROR,
"glfwInit: Failed to locate OpenGL framework");
return GL_FALSE;
}
NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
changeToResourcesDirectory();
if (access([resourcePath cStringUsingEncoding:NSUTF8StringEncoding], R_OK) == 0)
chdir([resourcePath cStringUsingEncoding:NSUTF8StringEncoding]);
// Setting up menu bar must go exactly here else weirdness ensues
setUpMenuBar();
[NSApp finishLaunching];
_glfwPlatformSetTime(0.0);
_glfwLibrary.NS.desktopMode =
(NSDictionary*) CGDisplayCurrentMode(CGMainDisplayID());
_glfwLibrary.NS.desktopMode = CGDisplayCopyDisplayMode(CGMainDisplayID());
// Save the original gamma ramp
_glfwLibrary.originalRampSize = CGDisplayGammaTableCapacity(CGMainDisplayID());
_glfwPlatformGetGammaRamp(&_glfwLibrary.originalRamp);
_glfwLibrary.currentRamp = _glfwLibrary.originalRamp;
_glfwInitTimer();
_glfwInitJoysticks();
_glfwLibrary.NS.eventSource = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
if (!_glfwLibrary.NS.eventSource)
return GL_FALSE;
CGEventSourceSetLocalEventsSuppressionInterval(_glfwLibrary.NS.eventSource,
0.0);
return GL_TRUE;
}
//========================================================================
// Close window, if open, and shut down GLFW
//========================================================================
@@ -243,8 +122,17 @@ int _glfwPlatformTerminate(void)
{
// TODO: Probably other cleanup
if (_glfwLibrary.NS.eventSource)
{
CFRelease(_glfwLibrary.NS.eventSource);
_glfwLibrary.NS.eventSource = NULL;
}
// Restore the original gamma ramp
_glfwPlatformSetGammaRamp(&_glfwLibrary.originalRamp);
if (_glfwLibrary.rampChanged)
_glfwPlatformSetGammaRamp(&_glfwLibrary.originalRamp);
CGDisplayModeRelease(_glfwLibrary.NS.desktopMode);
[NSApp setDelegate:nil];
[_glfwLibrary.NS.delegate release];
@@ -265,7 +153,11 @@ int _glfwPlatformTerminate(void)
const char* _glfwPlatformGetVersionString(void)
{
const char* version = _GLFW_VERSION_FULL " Cocoa";
const char* version = _GLFW_VERSION_FULL
#if defined(_GLFW_BUILD_DLL)
" dynamic"
#endif
;
return version;
}
+55 -22
View File
@@ -152,7 +152,7 @@ static void addJoystickElement(_glfwJoystick* joystick, CFTypeRef refElement)
long number;
CFTypeRef refType;
_glfwJoystickElement* element = (_glfwJoystickElement*) _glfwMalloc(sizeof(_glfwJoystickElement));
_glfwJoystickElement* element = (_glfwJoystickElement*) malloc(sizeof(_glfwJoystickElement));
CFArrayAppendValue(elementsArray, element);
@@ -242,7 +242,7 @@ static void removeJoystick(_glfwJoystick* joystick)
{
_glfwJoystickElement* axes =
(_glfwJoystickElement*) CFArrayGetValueAtIndex(joystick->axes, i);
_glfwFree(axes);
free(axes);
}
CFArrayRemoveAllValues(joystick->axes);
joystick->numAxes = 0;
@@ -251,7 +251,7 @@ static void removeJoystick(_glfwJoystick* joystick)
{
_glfwJoystickElement* button =
(_glfwJoystickElement*) CFArrayGetValueAtIndex(joystick->buttons, i);
_glfwFree(button);
free(button);
}
CFArrayRemoveAllValues(joystick->buttons);
joystick->numButtons = 0;
@@ -260,7 +260,7 @@ static void removeJoystick(_glfwJoystick* joystick)
{
_glfwJoystickElement* hat =
(_glfwJoystickElement*) CFArrayGetValueAtIndex(joystick->hats, i);
_glfwFree(hat);
free(hat);
}
CFArrayRemoveAllValues(joystick->hats);
joystick->hats = 0;
@@ -311,6 +311,13 @@ static void pollJoystickEvents(void)
(_glfwJoystickElement*) CFArrayGetValueAtIndex(joystick->axes, j);
axes->value = getElementValue(joystick, axes);
}
for (j = 0; j < joystick->numHats; j++)
{
_glfwJoystickElement* hat =
(_glfwJoystickElement*) CFArrayGetValueAtIndex(joystick->hats, j);
hat->value = getElementValue(joystick, hat);
}
}
}
}
@@ -336,7 +343,12 @@ void _glfwInitJoysticks(void)
result = IOMasterPort(bootstrap_port, &masterPort);
hidMatchDictionary = IOServiceMatching(kIOHIDDeviceKey);
if (kIOReturnSuccess != result || !hidMatchDictionary)
{
if (hidMatchDictionary)
CFRelease(hidMatchDictionary);
return;
}
result = IOServiceGetMatchingServices(masterPort,
hidMatchDictionary,
@@ -370,19 +382,27 @@ void _glfwInitJoysticks(void)
/* Check device type */
refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDPrimaryUsagePageKey));
if (refCF)
{
CFNumberGetValue(refCF, kCFNumberLongType, &usagePage);
if (usagePage != kHIDPage_GenericDesktop)
{
/* We are not interested in this device */
continue;
}
}
refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDPrimaryUsageKey));
if (refCF)
CFNumberGetValue(refCF, kCFNumberLongType, &usage);
if ((usagePage != kHIDPage_GenericDesktop) ||
(usage != kHIDUsage_GD_Joystick &&
usage != kHIDUsage_GD_GamePad &&
usage != kHIDUsage_GD_MultiAxisController))
{
/* We don't interested in this device */
continue;
CFNumberGetValue(refCF, kCFNumberLongType, &usage);
if ((usage != kHIDUsage_GD_Joystick &&
usage != kHIDUsage_GD_GamePad &&
usage != kHIDUsage_GD_MultiAxisController))
{
/* We are not interested in this device */
continue;
}
}
_glfwJoystick* joystick = &_glfwJoysticks[deviceCounter];
@@ -489,7 +509,7 @@ int _glfwPlatformGetJoystickParam(int joy, int param)
return (int) CFArrayGetCount(_glfwJoysticks[joy].axes);
case GLFW_BUTTONS:
return (int) CFArrayGetCount(_glfwJoysticks[joy].buttons);
return (int) CFArrayGetCount(_glfwJoysticks[joy].buttons) + ((int) CFArrayGetCount(_glfwJoysticks[joy].hats)) * 4;
default:
break;
@@ -552,7 +572,7 @@ int _glfwPlatformGetJoystickPos(int joy, float* pos, int numaxes)
int _glfwPlatformGetJoystickButtons(int joy, unsigned char* buttons,
int numbuttons)
{
int i;
int i, j, button;
if (joy < GLFW_JOYSTICK_1 || joy > GLFW_JOYSTICK_LAST)
return 0;
@@ -565,18 +585,31 @@ int _glfwPlatformGetJoystickButtons(int joy, unsigned char* buttons,
return 0;
}
numbuttons = numbuttons < joystick.numButtons ? numbuttons : joystick.numButtons;
// Update joystick state
pollJoystickEvents();
for (i = 0; i < numbuttons; i++)
for (button = 0; button < numbuttons && button < joystick.numButtons; button++)
{
_glfwJoystickElement* button = (_glfwJoystickElement*) CFArrayGetValueAtIndex(joystick.buttons, i);
buttons[i] = button->value ? GLFW_PRESS : GLFW_RELEASE;
_glfwJoystickElement* element = (_glfwJoystickElement*) CFArrayGetValueAtIndex(joystick.buttons, button);
buttons[button] = element->value ? GLFW_PRESS : GLFW_RELEASE;
}
return numbuttons;
// Virtual buttons - Inject data from hats
// Each hat is exposed as 4 buttons which exposes 8 directions with concurrent button presses
const int directions[9] = { 1, 3, 2, 6, 4, 12, 8, 9, 0 }; // Bit fields of button presses for each direction, including nil
for (i = 0; i < joystick.numHats; i++)
{
_glfwJoystickElement* hat = (_glfwJoystickElement*) CFArrayGetValueAtIndex(joystick.hats, i);
int value = hat->value;
if (value < 0 || value > 8) value = 8;
for (j = 0; j < 4 && button < numbuttons; j++)
{
buttons[button++] = directions[value] & (1 << j) ? GLFW_PRESS : GLFW_RELEASE;
}
}
return button;
}
+7 -3
View File
@@ -59,6 +59,7 @@ void _glfwPlatformSwapBuffers(void)
[window->NSGL.context flushBuffer];
}
//========================================================================
// Set double buffering swap interval
//========================================================================
@@ -71,6 +72,7 @@ void _glfwPlatformSwapInterval(int interval)
[window->NSGL.context setValues:&sync forParameter:NSOpenGLCPSwapInterval];
}
//========================================================================
// Check if an OpenGL extension is available at runtime
//========================================================================
@@ -81,24 +83,26 @@ int _glfwPlatformExtensionSupported(const char* extension)
return GL_FALSE;
}
//========================================================================
// Get the function pointer to an OpenGL function
//========================================================================
void* _glfwPlatformGetProcAddress(const char* procname)
GLFWglproc _glfwPlatformGetProcAddress(const char* procname)
{
CFStringRef symbolName = CFStringCreateWithCString(kCFAllocatorDefault,
procname,
kCFStringEncodingASCII);
void* symbol = CFBundleGetFunctionPointerForName(_glfwLibrary.NS.OpenGLFramework,
symbolName);
GLFWglproc symbol = CFBundleGetFunctionPointerForName(_glfwLibrary.NSGL.framework,
symbolName);
CFRelease(symbolName);
return symbol;
}
//========================================================================
// Copies the specified OpenGL state categories from src to dst
//========================================================================
+30 -12
View File
@@ -37,13 +37,15 @@
#if defined(__OBJC__)
#import <Cocoa/Cocoa.h>
#else
#include <ApplicationServices/ApplicationServices.h>
typedef void* id;
#endif
#define _GLFW_PLATFORM_WINDOW_STATE _GLFWwindowNS NS
#define _GLFW_PLATFORM_LIBRARY_STATE _GLFWlibraryNS NS
#define _GLFW_PLATFORM_CONTEXT_STATE _GLFWcontextNSGL NSGL
#define _GLFW_PLATFORM_LIBRARY_WINDOW_STATE _GLFWlibraryNS NS
#define _GLFW_PLATFORM_LIBRARY_OPENGL_STATE _GLFWlibraryNSGL NSGL
//========================================================================
@@ -71,39 +73,55 @@ typedef struct _GLFWcontextNSGL
//------------------------------------------------------------------------
typedef struct _GLFWwindowNS
{
id window;
id object;
id delegate;
id view;
unsigned int modifierFlags;
double fracScrollX;
double fracScrollY;
} _GLFWwindowNS;
//------------------------------------------------------------------------
// Platform-specific library global data
// Platform-specific library global data for Cocoa
//------------------------------------------------------------------------
typedef struct _GLFWlibraryNS
{
struct {
double t0;
double base;
double resolution;
} timer;
// dlopen handle for dynamically loading OpenGL extension entry points
void* OpenGLFramework;
GLboolean unbundled;
id desktopMode;
id delegate;
id autoreleasePool;
CGDisplayModeRef desktopMode;
CGEventSourceRef eventSource;
id delegate;
id autoreleasePool;
char* clipboardString;
} _GLFWlibraryNS;
//------------------------------------------------------------------------
// Platform-specific library global data for NSGL
//------------------------------------------------------------------------
typedef struct _GLFWlibraryNSGL
{
// dlopen handle for dynamically loading OpenGL extension entry points
void* framework;
} _GLFWlibraryNSGL;
//========================================================================
// Prototypes for platform specific internal functions
//========================================================================
// Time
void _glfwInitTimer(void);
// Joystick input
void _glfwInitJoysticks(void);
void _glfwTerminateJoysticks(void);
// Fullscreen
GLboolean _glfwSetVideoMode(int* width, int* height, int* bpp, int* refreshRate);
void _glfwRestoreVideoMode(void);
#endif // _platform_h_
+87
View File
@@ -0,0 +1,87 @@
//========================================================================
// GLFW - An OpenGL library
// Platform: Cocoa/NSOpenGL
// API Version: 3.0
// WWW: http://www.glfw.org/
//------------------------------------------------------------------------
// Copyright (c) 2009-2010 Camilla Berglund <elmindreda@elmindreda.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#include "internal.h"
#include <mach/mach_time.h>
//========================================================================
// Return raw time
//========================================================================
static uint64_t getRawTime(void)
{
return mach_absolute_time();
}
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
//========================================================================
// Initialise timer
//========================================================================
void _glfwInitTimer(void)
{
mach_timebase_info_data_t info;
mach_timebase_info(&info);
_glfwLibrary.NS.timer.resolution = (double) info.numer / (info.denom * 1.0e9);
_glfwLibrary.NS.timer.base = getRawTime();
}
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
//========================================================================
// Return timer value in seconds
//========================================================================
double _glfwPlatformGetTime(void)
{
return (double) (getRawTime() - _glfwLibrary.NS.timer.base) *
_glfwLibrary.NS.timer.resolution;
}
//========================================================================
// Set timer value in seconds
//========================================================================
void _glfwPlatformSetTime(double time)
{
_glfwLibrary.NS.timer.base = getRawTime() -
(uint64_t) (time / _glfwLibrary.NS.timer.resolution);
}
+457 -252
View File
@@ -29,6 +29,9 @@
#include "internal.h"
// Needed for _NSGetProgname
#include <crt_externs.h>
//========================================================================
// Delegate for window related notifications
@@ -66,7 +69,7 @@
[window->NSGL.context update];
NSRect contentRect =
[window->NS.window contentRectForFrameRect:[window->NS.window frame]];
[window->NS.object contentRectForFrameRect:[window->NS.object frame]];
_glfwInputWindowSize(window, contentRect.size.width, contentRect.size.height);
}
@@ -76,7 +79,7 @@
[window->NSGL.context update];
NSRect contentRect =
[window->NS.window contentRectForFrameRect:[window->NS.window frame]];
[window->NS.object contentRectForFrameRect:[window->NS.object frame]];
CGPoint mainScreenOrigin = CGDisplayBounds(CGMainDisplayID()).origin;
double mainScreenHeight = CGDisplayBounds(CGMainDisplayID()).size.height;
@@ -109,6 +112,7 @@
@end
//========================================================================
// Delegate for application related notifications
//========================================================================
@@ -130,142 +134,6 @@
@end
//========================================================================
// Keyboard symbol translation table
//========================================================================
// TODO: Need to find mappings for F13-F15, volume down/up/mute, and eject.
static const unsigned int MAC_TO_GLFW_KEYCODE_MAPPING[128] =
{
/* 00 */ GLFW_KEY_A,
/* 01 */ GLFW_KEY_S,
/* 02 */ GLFW_KEY_D,
/* 03 */ GLFW_KEY_F,
/* 04 */ GLFW_KEY_H,
/* 05 */ GLFW_KEY_G,
/* 06 */ GLFW_KEY_Z,
/* 07 */ GLFW_KEY_X,
/* 08 */ GLFW_KEY_C,
/* 09 */ GLFW_KEY_V,
/* 0a */ GLFW_KEY_GRAVE_ACCENT,
/* 0b */ GLFW_KEY_B,
/* 0c */ GLFW_KEY_Q,
/* 0d */ GLFW_KEY_W,
/* 0e */ GLFW_KEY_E,
/* 0f */ GLFW_KEY_R,
/* 10 */ GLFW_KEY_Y,
/* 11 */ GLFW_KEY_T,
/* 12 */ GLFW_KEY_1,
/* 13 */ GLFW_KEY_2,
/* 14 */ GLFW_KEY_3,
/* 15 */ GLFW_KEY_4,
/* 16 */ GLFW_KEY_6,
/* 17 */ GLFW_KEY_5,
/* 18 */ GLFW_KEY_EQUAL,
/* 19 */ GLFW_KEY_9,
/* 1a */ GLFW_KEY_7,
/* 1b */ GLFW_KEY_MINUS,
/* 1c */ GLFW_KEY_8,
/* 1d */ GLFW_KEY_0,
/* 1e */ GLFW_KEY_RIGHT_BRACKET,
/* 1f */ GLFW_KEY_O,
/* 20 */ GLFW_KEY_U,
/* 21 */ GLFW_KEY_LEFT_BRACKET,
/* 22 */ GLFW_KEY_I,
/* 23 */ GLFW_KEY_P,
/* 24 */ GLFW_KEY_ENTER,
/* 25 */ GLFW_KEY_L,
/* 26 */ GLFW_KEY_J,
/* 27 */ GLFW_KEY_APOSTROPHE,
/* 28 */ GLFW_KEY_K,
/* 29 */ GLFW_KEY_SEMICOLON,
/* 2a */ GLFW_KEY_BACKSLASH,
/* 2b */ GLFW_KEY_COMMA,
/* 2c */ GLFW_KEY_SLASH,
/* 2d */ GLFW_KEY_N,
/* 2e */ GLFW_KEY_M,
/* 2f */ GLFW_KEY_PERIOD,
/* 30 */ GLFW_KEY_TAB,
/* 31 */ GLFW_KEY_SPACE,
/* 32 */ GLFW_KEY_WORLD_1,
/* 33 */ GLFW_KEY_BACKSPACE,
/* 34 */ -1,
/* 35 */ GLFW_KEY_ESCAPE,
/* 36 */ GLFW_KEY_RIGHT_SUPER,
/* 37 */ GLFW_KEY_LEFT_SUPER,
/* 38 */ GLFW_KEY_LEFT_SHIFT,
/* 39 */ GLFW_KEY_CAPS_LOCK,
/* 3a */ GLFW_KEY_LEFT_ALT,
/* 3b */ GLFW_KEY_LEFT_CONTROL,
/* 3c */ GLFW_KEY_RIGHT_SHIFT,
/* 3d */ GLFW_KEY_RIGHT_ALT,
/* 3e */ GLFW_KEY_RIGHT_CONTROL,
/* 3f */ -1, /* Function */
/* 40 */ GLFW_KEY_F17,
/* 41 */ GLFW_KEY_KP_DECIMAL,
/* 42 */ -1,
/* 43 */ GLFW_KEY_KP_MULTIPLY,
/* 44 */ -1,
/* 45 */ GLFW_KEY_KP_ADD,
/* 46 */ -1,
/* 47 */ GLFW_KEY_NUM_LOCK, /* Really KeypadClear... */
/* 48 */ -1, /* VolumeUp */
/* 49 */ -1, /* VolumeDown */
/* 4a */ -1, /* Mute */
/* 4b */ GLFW_KEY_KP_DIVIDE,
/* 4c */ GLFW_KEY_KP_ENTER,
/* 4d */ -1,
/* 4e */ GLFW_KEY_KP_SUBTRACT,
/* 4f */ GLFW_KEY_F18,
/* 50 */ GLFW_KEY_F19,
/* 51 */ GLFW_KEY_KP_EQUAL,
/* 52 */ GLFW_KEY_KP_0,
/* 53 */ GLFW_KEY_KP_1,
/* 54 */ GLFW_KEY_KP_2,
/* 55 */ GLFW_KEY_KP_3,
/* 56 */ GLFW_KEY_KP_4,
/* 57 */ GLFW_KEY_KP_5,
/* 58 */ GLFW_KEY_KP_6,
/* 59 */ GLFW_KEY_KP_7,
/* 5a */ GLFW_KEY_F20,
/* 5b */ GLFW_KEY_KP_8,
/* 5c */ GLFW_KEY_KP_9,
/* 5d */ -1,
/* 5e */ -1,
/* 5f */ -1,
/* 60 */ GLFW_KEY_F5,
/* 61 */ GLFW_KEY_F6,
/* 62 */ GLFW_KEY_F7,
/* 63 */ GLFW_KEY_F3,
/* 64 */ GLFW_KEY_F8,
/* 65 */ GLFW_KEY_F9,
/* 66 */ -1,
/* 67 */ GLFW_KEY_F11,
/* 68 */ -1,
/* 69 */ GLFW_KEY_F13,
/* 6a */ GLFW_KEY_F16,
/* 6b */ GLFW_KEY_F14,
/* 6c */ -1,
/* 6d */ GLFW_KEY_F10,
/* 6e */ -1,
/* 6f */ GLFW_KEY_F12,
/* 70 */ -1,
/* 71 */ GLFW_KEY_F15,
/* 72 */ GLFW_KEY_INSERT, /* Really Help... */
/* 73 */ GLFW_KEY_HOME,
/* 74 */ GLFW_KEY_PAGE_UP,
/* 75 */ GLFW_KEY_DELETE,
/* 76 */ GLFW_KEY_F4,
/* 77 */ GLFW_KEY_END,
/* 78 */ GLFW_KEY_F2,
/* 79 */ GLFW_KEY_PAGE_DOWN,
/* 7a */ GLFW_KEY_F1,
/* 7b */ GLFW_KEY_LEFT,
/* 7c */ GLFW_KEY_RIGHT,
/* 7d */ GLFW_KEY_DOWN,
/* 7e */ GLFW_KEY_UP,
/* 7f */ -1,
};
//========================================================================
// Converts a Mac OS X keycode to a GLFW keycode
@@ -273,15 +141,150 @@ static const unsigned int MAC_TO_GLFW_KEYCODE_MAPPING[128] =
static int convertMacKeyCode(unsigned int macKeyCode)
{
// Keyboard symbol translation table
// TODO: Need to find mappings for F13-F15, volume down/up/mute, and eject.
static const unsigned int table[128] =
{
/* 00 */ GLFW_KEY_A,
/* 01 */ GLFW_KEY_S,
/* 02 */ GLFW_KEY_D,
/* 03 */ GLFW_KEY_F,
/* 04 */ GLFW_KEY_H,
/* 05 */ GLFW_KEY_G,
/* 06 */ GLFW_KEY_Z,
/* 07 */ GLFW_KEY_X,
/* 08 */ GLFW_KEY_C,
/* 09 */ GLFW_KEY_V,
/* 0a */ GLFW_KEY_GRAVE_ACCENT,
/* 0b */ GLFW_KEY_B,
/* 0c */ GLFW_KEY_Q,
/* 0d */ GLFW_KEY_W,
/* 0e */ GLFW_KEY_E,
/* 0f */ GLFW_KEY_R,
/* 10 */ GLFW_KEY_Y,
/* 11 */ GLFW_KEY_T,
/* 12 */ GLFW_KEY_1,
/* 13 */ GLFW_KEY_2,
/* 14 */ GLFW_KEY_3,
/* 15 */ GLFW_KEY_4,
/* 16 */ GLFW_KEY_6,
/* 17 */ GLFW_KEY_5,
/* 18 */ GLFW_KEY_EQUAL,
/* 19 */ GLFW_KEY_9,
/* 1a */ GLFW_KEY_7,
/* 1b */ GLFW_KEY_MINUS,
/* 1c */ GLFW_KEY_8,
/* 1d */ GLFW_KEY_0,
/* 1e */ GLFW_KEY_RIGHT_BRACKET,
/* 1f */ GLFW_KEY_O,
/* 20 */ GLFW_KEY_U,
/* 21 */ GLFW_KEY_LEFT_BRACKET,
/* 22 */ GLFW_KEY_I,
/* 23 */ GLFW_KEY_P,
/* 24 */ GLFW_KEY_ENTER,
/* 25 */ GLFW_KEY_L,
/* 26 */ GLFW_KEY_J,
/* 27 */ GLFW_KEY_APOSTROPHE,
/* 28 */ GLFW_KEY_K,
/* 29 */ GLFW_KEY_SEMICOLON,
/* 2a */ GLFW_KEY_BACKSLASH,
/* 2b */ GLFW_KEY_COMMA,
/* 2c */ GLFW_KEY_SLASH,
/* 2d */ GLFW_KEY_N,
/* 2e */ GLFW_KEY_M,
/* 2f */ GLFW_KEY_PERIOD,
/* 30 */ GLFW_KEY_TAB,
/* 31 */ GLFW_KEY_SPACE,
/* 32 */ GLFW_KEY_WORLD_1,
/* 33 */ GLFW_KEY_BACKSPACE,
/* 34 */ -1,
/* 35 */ GLFW_KEY_ESCAPE,
/* 36 */ GLFW_KEY_RIGHT_SUPER,
/* 37 */ GLFW_KEY_LEFT_SUPER,
/* 38 */ GLFW_KEY_LEFT_SHIFT,
/* 39 */ GLFW_KEY_CAPS_LOCK,
/* 3a */ GLFW_KEY_LEFT_ALT,
/* 3b */ GLFW_KEY_LEFT_CONTROL,
/* 3c */ GLFW_KEY_RIGHT_SHIFT,
/* 3d */ GLFW_KEY_RIGHT_ALT,
/* 3e */ GLFW_KEY_RIGHT_CONTROL,
/* 3f */ -1, /* Function */
/* 40 */ GLFW_KEY_F17,
/* 41 */ GLFW_KEY_KP_DECIMAL,
/* 42 */ -1,
/* 43 */ GLFW_KEY_KP_MULTIPLY,
/* 44 */ -1,
/* 45 */ GLFW_KEY_KP_ADD,
/* 46 */ -1,
/* 47 */ GLFW_KEY_NUM_LOCK, /* Really KeypadClear... */
/* 48 */ -1, /* VolumeUp */
/* 49 */ -1, /* VolumeDown */
/* 4a */ -1, /* Mute */
/* 4b */ GLFW_KEY_KP_DIVIDE,
/* 4c */ GLFW_KEY_KP_ENTER,
/* 4d */ -1,
/* 4e */ GLFW_KEY_KP_SUBTRACT,
/* 4f */ GLFW_KEY_F18,
/* 50 */ GLFW_KEY_F19,
/* 51 */ GLFW_KEY_KP_EQUAL,
/* 52 */ GLFW_KEY_KP_0,
/* 53 */ GLFW_KEY_KP_1,
/* 54 */ GLFW_KEY_KP_2,
/* 55 */ GLFW_KEY_KP_3,
/* 56 */ GLFW_KEY_KP_4,
/* 57 */ GLFW_KEY_KP_5,
/* 58 */ GLFW_KEY_KP_6,
/* 59 */ GLFW_KEY_KP_7,
/* 5a */ GLFW_KEY_F20,
/* 5b */ GLFW_KEY_KP_8,
/* 5c */ GLFW_KEY_KP_9,
/* 5d */ -1,
/* 5e */ -1,
/* 5f */ -1,
/* 60 */ GLFW_KEY_F5,
/* 61 */ GLFW_KEY_F6,
/* 62 */ GLFW_KEY_F7,
/* 63 */ GLFW_KEY_F3,
/* 64 */ GLFW_KEY_F8,
/* 65 */ GLFW_KEY_F9,
/* 66 */ -1,
/* 67 */ GLFW_KEY_F11,
/* 68 */ -1,
/* 69 */ GLFW_KEY_F13,
/* 6a */ GLFW_KEY_F16,
/* 6b */ GLFW_KEY_F14,
/* 6c */ -1,
/* 6d */ GLFW_KEY_F10,
/* 6e */ -1,
/* 6f */ GLFW_KEY_F12,
/* 70 */ -1,
/* 71 */ GLFW_KEY_F15,
/* 72 */ GLFW_KEY_INSERT, /* Really Help... */
/* 73 */ GLFW_KEY_HOME,
/* 74 */ GLFW_KEY_PAGE_UP,
/* 75 */ GLFW_KEY_DELETE,
/* 76 */ GLFW_KEY_F4,
/* 77 */ GLFW_KEY_END,
/* 78 */ GLFW_KEY_F2,
/* 79 */ GLFW_KEY_PAGE_DOWN,
/* 7a */ GLFW_KEY_F1,
/* 7b */ GLFW_KEY_LEFT,
/* 7c */ GLFW_KEY_RIGHT,
/* 7d */ GLFW_KEY_DOWN,
/* 7e */ GLFW_KEY_UP,
/* 7f */ -1,
};
if (macKeyCode >= 128)
return -1;
// This treats keycodes as *positional*; that is, we'll return 'a'
// for the key left of 's', even on an AZERTY keyboard. The charInput
// function should still get 'q' though.
return MAC_TO_GLFW_KEYCODE_MAPPING[macKeyCode];
return table[macKeyCode];
}
//========================================================================
// Content view class for the GLFW window
//========================================================================
@@ -289,6 +292,7 @@ static int convertMacKeyCode(unsigned int macKeyCode)
@interface GLFWContentView : NSView
{
_GLFWwindow* window;
NSTrackingArea* trackingArea;
}
- (id)initWithGlfwWindow:(_GLFWwindow *)initWindow;
@@ -301,11 +305,22 @@ static int convertMacKeyCode(unsigned int macKeyCode)
{
self = [super init];
if (self != nil)
{
window = initWindow;
trackingArea = nil;
[self updateTrackingAreas];
}
return self;
}
-(void)dealloc
{
[trackingArea release];
[super dealloc];
}
- (BOOL)isOpaque
{
return YES;
@@ -342,12 +357,13 @@ static int convertMacKeyCode(unsigned int macKeyCode)
_glfwInputCursorMotion(window, [event deltaX], [event deltaY]);
else
{
NSPoint p = [event locationInWindow];
const NSPoint p = [event locationInWindow];
// Cocoa coordinate system has origin at lower left
p.y = [[window->NS.window contentView] bounds].size.height - p.y;
const int x = lround(floor(p.x));
const int y = window->height - lround(ceil(p.y));
_glfwInputCursorMotion(window, p.x, p.y);
_glfwInputCursorMotion(window, x, y);
}
}
@@ -381,15 +397,45 @@ static int convertMacKeyCode(unsigned int macKeyCode)
_glfwInputMouseClick(window, [event buttonNumber], GLFW_RELEASE);
}
- (void)mouseExited:(NSEvent *)event
{
_glfwInputCursorEnter(window, GL_FALSE);
}
- (void)mouseEntered:(NSEvent *)event
{
_glfwInputCursorEnter(window, GL_TRUE);
}
- (void)updateTrackingAreas
{
if (trackingArea != nil)
{
[self removeTrackingArea:trackingArea];
[trackingArea release];
}
NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited |
NSTrackingActiveAlways |
NSTrackingInVisibleRect;
trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds]
options:options
owner:self
userInfo:nil];
[self addTrackingArea:trackingArea];
}
- (void)keyDown:(NSEvent *)event
{
NSUInteger i, length;
NSString* characters;
int code = convertMacKeyCode([event keyCode]);
int key = convertMacKeyCode([event keyCode]);
if (code != -1)
if (key != -1)
{
_glfwInputKey(window, code, GLFW_PRESS);
_glfwInputKey(window, key, GLFW_PRESS);
if ([event modifierFlags] & NSCommandKeyMask)
{
@@ -409,7 +455,7 @@ static int convertMacKeyCode(unsigned int macKeyCode)
- (void)flagsChanged:(NSEvent *)event
{
int mode;
int mode, key;
unsigned int newModifierFlags =
[event modifierFlags] | NSDeviceIndependentModifierFlagsMask;
@@ -419,30 +465,193 @@ static int convertMacKeyCode(unsigned int macKeyCode)
mode = GLFW_RELEASE;
window->NS.modifierFlags = newModifierFlags;
_glfwInputKey(window, MAC_TO_GLFW_KEYCODE_MAPPING[[event keyCode]], mode);
key = convertMacKeyCode([event keyCode]);
if (key != -1)
_glfwInputKey(window, key, mode);
}
- (void)keyUp:(NSEvent *)event
{
int code = convertMacKeyCode([event keyCode]);
if (code != -1)
_glfwInputKey(window, code, GLFW_RELEASE);
int key = convertMacKeyCode([event keyCode]);
if (key != -1)
_glfwInputKey(window, key, GLFW_RELEASE);
}
- (void)scrollWheel:(NSEvent *)event
{
double deltaX = window->NS.fracScrollX + [event deltaX];
double deltaY = window->NS.fracScrollY + [event deltaY];
double deltaX = [event deltaX];
double deltaY = [event deltaY];
if ((int) deltaX || (int) deltaY)
_glfwInputScroll(window, (int) deltaX, (int) deltaY);
window->NS.fracScrollX = (int) (deltaX - floor(deltaX));
window->NS.fracScrollY = (int) (deltaY - floor(deltaY));
if (fabs(deltaX) > 0.0 || fabs(deltaY) > 0.0)
_glfwInputScroll(window, deltaX, deltaY);
}
@end
//========================================================================
// GLFW application class
//========================================================================
@interface GLFWApplication : NSApplication
@end
@implementation GLFWApplication
// From http://cocoadev.com/index.pl?GameKeyboardHandlingAlmost
// This works around an AppKit bug, where key up events while holding
// down the command key don't get sent to the key window.
- (void)sendEvent:(NSEvent *)event
{
if ([event type] == NSKeyUp && ([event modifierFlags] & NSCommandKeyMask))
[[self keyWindow] sendEvent:event];
else
[super sendEvent:event];
}
@end
//========================================================================
// Try to figure out what the calling application is called
//========================================================================
static NSString* findAppName(void)
{
unsigned int i;
NSDictionary* infoDictionary = [[NSBundle mainBundle] infoDictionary];
// Keys to search for as potential application names
NSString* GLFWNameKeys[] =
{
@"CFBundleDisplayName",
@"CFBundleName",
@"CFBundleExecutable",
};
for (i = 0; i < sizeof(GLFWNameKeys) / sizeof(GLFWNameKeys[0]); i++)
{
id name = [infoDictionary objectForKey:GLFWNameKeys[i]];
if (name &&
[name isKindOfClass:[NSString class]] &&
![@"" isEqualToString:name])
{
return name;
}
}
// If we get here, we're unbundled
ProcessSerialNumber psn = { 0, kCurrentProcess };
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
// Having the app in front of the terminal window is also generally
// handy. There is an NSApplication API to do this, but...
SetFrontProcess(&psn);
char** progname = _NSGetProgname();
if (progname && *progname)
{
// TODO: UTF-8?
return [NSString stringWithUTF8String:*progname];
}
// Really shouldn't get here
return @"GLFW Application";
}
//========================================================================
// Set up the menu bar (manually)
// This is nasty, nasty stuff -- calls to undocumented semi-private APIs that
// could go away at any moment, lots of stuff that really should be
// localize(d|able), etc. Loading a nib would save us this horror, but that
// doesn't seem like a good thing to require of GLFW's clients.
//========================================================================
static void createMenuBar(void)
{
NSString* appName = findAppName();
NSMenu* bar = [[NSMenu alloc] init];
[NSApp setMainMenu:bar];
NSMenuItem* appMenuItem =
[bar addItemWithTitle:@"" action:NULL keyEquivalent:@""];
NSMenu* appMenu = [[NSMenu alloc] init];
[appMenuItem setSubmenu:appMenu];
[appMenu addItemWithTitle:[NSString stringWithFormat:@"About %@", appName]
action:@selector(orderFrontStandardAboutPanel:)
keyEquivalent:@""];
[appMenu addItem:[NSMenuItem separatorItem]];
NSMenu* servicesMenu = [[NSMenu alloc] init];
[NSApp setServicesMenu:servicesMenu];
[[appMenu addItemWithTitle:@"Services"
action:NULL
keyEquivalent:@""] setSubmenu:servicesMenu];
[appMenu addItem:[NSMenuItem separatorItem]];
[appMenu addItemWithTitle:[NSString stringWithFormat:@"Hide %@", appName]
action:@selector(hide:)
keyEquivalent:@"h"];
[[appMenu addItemWithTitle:@"Hide Others"
action:@selector(hideOtherApplications:)
keyEquivalent:@"h"]
setKeyEquivalentModifierMask:NSAlternateKeyMask | NSCommandKeyMask];
[appMenu addItemWithTitle:@"Show All"
action:@selector(unhideAllApplications:)
keyEquivalent:@""];
[appMenu addItem:[NSMenuItem separatorItem]];
[appMenu addItemWithTitle:[NSString stringWithFormat:@"Quit %@", appName]
action:@selector(terminate:)
keyEquivalent:@"q"];
NSMenuItem* windowMenuItem =
[bar addItemWithTitle:@"" action:NULL keyEquivalent:@""];
NSMenu* windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
[NSApp setWindowsMenu:windowMenu];
[windowMenuItem setSubmenu:windowMenu];
[windowMenu addItemWithTitle:@"Miniaturize"
action:@selector(performMiniaturize:)
keyEquivalent:@"m"];
[windowMenu addItemWithTitle:@"Zoom"
action:@selector(performZoom:)
keyEquivalent:@""];
[windowMenu addItem:[NSMenuItem separatorItem]];
[windowMenu addItemWithTitle:@"Bring All to Front"
action:@selector(arrangeInFront:)
keyEquivalent:@""];
// Prior to Snow Leopard, we need to use this oddly-named semi-private API
// to get the application menu working properly.
[NSApp performSelector:@selector(setAppleMenu:) withObject:appMenu];
}
//========================================================================
// Initialize the Cocoa Application Kit
//========================================================================
static GLboolean initializeAppKit(void)
{
if (NSApp)
return GL_TRUE;
// Implicitly create shared NSApplication instance
[GLFWApplication sharedApplication];
// Setting up the menu bar must go between sharedApplication
// above and finishLaunching below, in order to properly emulate the
// behavior of NSApplicationMain
createMenuBar();
[NSApp finishLaunching];
return GL_TRUE;
}
//========================================================================
// Create the Cocoa window
//========================================================================
@@ -463,29 +672,34 @@ static GLboolean createWindow(_GLFWwindow* window,
else
styleMask = NSBorderlessWindowMask;
window->NS.window = [[NSWindow alloc]
window->NS.object = [[NSWindow alloc]
initWithContentRect:NSMakeRect(0, 0, window->width, window->height)
styleMask:styleMask
backing:NSBackingStoreBuffered
defer:NO];
if (window->NS.window == nil)
if (window->NS.object == nil)
{
_glfwSetError(GLFW_PLATFORM_ERROR,
"Cocoa/NSOpenGL: Failed to create window");
return GL_FALSE;
}
[window->NS.window setTitle:[NSString stringWithUTF8String:wndconfig->title]];
[window->NS.window setContentView:[[GLFWContentView alloc]
initWithGlfwWindow:window]];
[window->NS.window setDelegate:window->NS.delegate];
[window->NS.window setAcceptsMouseMovedEvents:YES];
[window->NS.window center];
window->NS.view = [[GLFWContentView alloc] initWithGlfwWindow:window];
[window->NS.object setTitle:[NSString stringWithUTF8String:wndconfig->title]];
[window->NS.object setContentView:window->NS.view];
[window->NS.object setDelegate:window->NS.delegate];
[window->NS.object setAcceptsMouseMovedEvents:YES];
[window->NS.object center];
if ([window->NS.object respondsToSelector:@selector(setRestorable)])
[window->NS.object setRestorable:NO];
return GL_TRUE;
}
//========================================================================
// Create the OpenGL context
//========================================================================
@@ -514,14 +728,23 @@ static GLboolean createContext(_GLFWwindow* window,
return GL_FALSE;
}
if (wndconfig->glProfile)
if (wndconfig->glMajor > 2)
{
// Fail if a profile other than core was explicitly selected
if (!wndconfig->glForward)
{
_glfwSetError(GLFW_VERSION_UNAVAILABLE,
"Cocoa/NSOpenGL: The targeted version of Mac OS X "
"only supports OpenGL 3.2 contexts if they are "
"forward-compatible");
return GL_FALSE;
}
if (wndconfig->glProfile != GLFW_OPENGL_CORE_PROFILE)
{
_glfwSetError(GLFW_VERSION_UNAVAILABLE,
"Cocoa/NSOpenGL: The targeted version of Mac OS X "
"only supports the OpenGL core profile");
"only supports OpenGL 3.2 contexts if they use the "
"core profile");
return GL_FALSE;
}
}
@@ -549,13 +772,12 @@ static GLboolean createContext(_GLFWwindow* window,
#define ADD_ATTR2(x, y) { ADD_ATTR(x); ADD_ATTR(y); }
// Arbitrary array size here
NSOpenGLPixelFormatAttribute attributes[24];
NSOpenGLPixelFormatAttribute attributes[40];
ADD_ATTR(NSOpenGLPFADoubleBuffer);
if (wndconfig->mode == GLFW_FULLSCREEN)
{
ADD_ATTR(NSOpenGLPFAFullScreen);
ADD_ATTR(NSOpenGLPFANoRecovery);
ADD_ATTR2(NSOpenGLPFAScreenMask,
CGDisplayIDToOpenGLDisplayMask(CGMainDisplayID()));
@@ -587,7 +809,7 @@ static GLboolean createContext(_GLFWwindow* window,
ADD_ATTR2(NSOpenGLPFAAuxBuffers, fbconfig->auxBuffers);
if (fbconfig->stereo)
ADD_ATTR(NSOpenGLPFAStereo );
ADD_ATTR(NSOpenGLPFAStereo);
if (fbconfig->samples > 0)
{
@@ -605,7 +827,7 @@ static GLboolean createContext(_GLFWwindow* window,
if (window->NSGL.pixelFormat == nil)
{
_glfwSetError(GLFW_PLATFORM_ERROR,
"Cocoa/NSOpenGL: Failed to create pixel format");
"Cocoa/NSOpenGL: Failed to create OpenGL pixel format");
return GL_FALSE;
}
@@ -638,9 +860,14 @@ static GLboolean createContext(_GLFWwindow* window,
//========================================================================
int _glfwPlatformOpenWindow(_GLFWwindow* window,
const _GLFWwndconfig *wndconfig,
const _GLFWfbconfig *fbconfig)
const _GLFWwndconfig* wndconfig,
const _GLFWfbconfig* fbconfig)
{
if (!initializeAppKit())
return GL_FALSE;
window->resizable = wndconfig->resizable;
// We can only have one application delegate, but we only allocate it the
// first time we create a window to keep all window code in this file
if (_glfwLibrary.NS.delegate == nil)
@@ -672,56 +899,31 @@ int _glfwPlatformOpenWindow(_GLFWwindow* window,
else if (colorBits < 15)
colorBits = 15;
// Ignored hints:
// OpenGLMajor, OpenGLMinor, OpenGLForward:
// pending Mac OS X support for OpenGL 3.x
// OpenGLDebug
// pending it meaning anything on Mac OS X
// Don't use accumulation buffer support; it's not accelerated
// Aux buffers probably aren't accelerated either
CFDictionaryRef fullscreenMode = NULL;
if (wndconfig->mode == GLFW_FULLSCREEN)
{
// I think it's safe to pass 0 to the refresh rate for this function
// rather than conditionalizing the code to call the version which
// doesn't specify refresh...
fullscreenMode =
CGDisplayBestModeForParametersAndRefreshRateWithProperty(
CGMainDisplayID(),
colorBits + fbconfig->alphaBits,
window->width, window->height,
wndconfig->refreshRate,
// Controversial, see macosx_fullscreen.m for discussion
kCGDisplayModeIsSafeForHardware,
NULL);
window->width =
[[(id)fullscreenMode objectForKey:(id)kCGDisplayWidth] intValue];
window->height =
[[(id)fullscreenMode objectForKey:(id)kCGDisplayHeight] intValue];
}
if (!createWindow(window, wndconfig))
return GL_FALSE;
if (!createContext(window, wndconfig, fbconfig))
return GL_FALSE;
[window->NS.window makeKeyAndOrderFront:nil];
[window->NSGL.context setView:[window->NS.window contentView]];
[window->NS.object makeKeyAndOrderFront:nil];
[window->NSGL.context setView:[window->NS.object contentView]];
if (wndconfig->mode == GLFW_FULLSCREEN)
{
CGCaptureAllDisplays();
CGDisplaySwitchToMode(CGMainDisplayID(), fullscreenMode);
}
int bpp = colorBits + fbconfig->alphaBits;
if (wndconfig->mode == GLFW_FULLSCREEN)
{
// TODO: Make this work on pre-Leopard systems
[[window->NS.window contentView] enterFullScreenMode:[NSScreen mainScreen]
if (!_glfwSetVideoMode(&window->width,
&window->height,
&bpp,
&window->refreshRate))
{
return GL_FALSE;
}
[[window->NS.object contentView] enterFullScreenMode:[NSScreen mainScreen]
withOptions:nil];
}
@@ -743,15 +945,13 @@ int _glfwPlatformOpenWindow(_GLFWwindow* window,
void _glfwPlatformCloseWindow(_GLFWwindow* window)
{
[window->NS.window orderOut:nil];
[window->NS.object orderOut:nil];
if (window->mode == GLFW_FULLSCREEN)
{
[[window->NS.window contentView] exitFullScreenModeWithOptions:nil];
[[window->NS.object contentView] exitFullScreenModeWithOptions:nil];
CGDisplaySwitchToMode(CGMainDisplayID(),
(CFDictionaryRef) _glfwLibrary.NS.desktopMode);
CGReleaseAllDisplays();
_glfwRestoreVideoMode();
}
[window->NSGL.pixelFormat release];
@@ -761,34 +961,40 @@ void _glfwPlatformCloseWindow(_GLFWwindow* window)
[window->NSGL.context release];
window->NSGL.context = nil;
[window->NS.window setDelegate:nil];
[window->NS.object setDelegate:nil];
[window->NS.delegate release];
window->NS.delegate = nil;
[window->NS.window close];
window->NS.window = nil;
[window->NS.view release];
window->NS.view = nil;
[window->NS.object close];
window->NS.object = nil;
// TODO: Probably more cleanup
}
//========================================================================
// Set the window title
//========================================================================
void _glfwPlatformSetWindowTitle(_GLFWwindow* window, const char *title)
{
[window->NS.window setTitle:[NSString stringWithUTF8String:title]];
[window->NS.object setTitle:[NSString stringWithUTF8String:title]];
}
//========================================================================
// Set the window size
//========================================================================
void _glfwPlatformSetWindowSize(_GLFWwindow* window, int width, int height)
{
[window->NS.window setContentSize:NSMakeSize(width, height)];
[window->NS.object setContentSize:NSMakeSize(width, height)];
}
//========================================================================
// Set the window position
//========================================================================
@@ -796,37 +1002,40 @@ void _glfwPlatformSetWindowSize(_GLFWwindow* window, int width, int height)
void _glfwPlatformSetWindowPos(_GLFWwindow* window, int x, int y)
{
NSRect contentRect =
[window->NS.window contentRectForFrameRect:[window->NS.window frame]];
[window->NS.object contentRectForFrameRect:[window->NS.object frame]];
// We assume here that the client code wants to position the window within the
// screen the window currently occupies
NSRect screenRect = [[window->NS.window screen] visibleFrame];
NSRect screenRect = [[window->NS.object screen] visibleFrame];
contentRect.origin = NSMakePoint(screenRect.origin.x + x,
screenRect.origin.y + screenRect.size.height -
y - contentRect.size.height);
[window->NS.window setFrame:[window->NS.window frameRectForContentRect:contentRect]
[window->NS.object setFrame:[window->NS.object frameRectForContentRect:contentRect]
display:YES];
}
//========================================================================
// Iconify the window
//========================================================================
void _glfwPlatformIconifyWindow(_GLFWwindow* window)
{
[window->NS.window miniaturize:nil];
[window->NS.object miniaturize:nil];
}
//========================================================================
// Restore (un-iconify) the window
//========================================================================
void _glfwPlatformRestoreWindow(_GLFWwindow* window)
{
[window->NS.window deminiaturize:nil];
[window->NS.object deminiaturize:nil];
}
//========================================================================
// Write back window parameters into GLFW window structure
//========================================================================
@@ -901,6 +1110,7 @@ void _glfwPlatformRefreshWindowParams(void)
window->glDebug = GL_FALSE;
}
//========================================================================
// Poll for new window and input events
//========================================================================
@@ -925,6 +1135,7 @@ void _glfwPlatformPollEvents(void)
_glfwLibrary.NS.autoreleasePool = [[NSAutoreleasePool alloc] init];
}
//========================================================================
// Wait for new window and input events
//========================================================================
@@ -943,38 +1154,32 @@ void _glfwPlatformWaitEvents( void )
_glfwPlatformPollEvents();
}
//========================================================================
// Set physical mouse cursor position
// Set physical cursor position
//========================================================================
void _glfwPlatformSetMouseCursorPos(_GLFWwindow* window, int x, int y)
void _glfwPlatformSetCursorPos(_GLFWwindow* window, int x, int y)
{
// The library seems to assume that after calling this the mouse won't move,
// but obviously it will, and escape the app's window, and activate other apps,
// and other badness in pain. I think the API's just silly, but maybe I'm
// misunderstanding it...
// Also, (x, y) are window coords...
// Also, it doesn't seem possible to write this robustly without
// calculating the maximum y coordinate of all screens, since Cocoa's
// "global coordinates" are upside down from CG's...
// Without this (once per app run, but it's convenient to do it here)
// events will be suppressed for a default of 0.25 seconds after we
// move the cursor.
CGSetLocalEventsSuppressionInterval(0.0);
NSPoint localPoint = NSMakePoint(x, y);
NSPoint globalPoint = [window->NS.window convertBaseToScreen:localPoint];
CGPoint mainScreenOrigin = CGDisplayBounds(CGMainDisplayID()).origin;
double mainScreenHeight = CGDisplayBounds(CGMainDisplayID()).size.height;
CGPoint targetPoint = CGPointMake(globalPoint.x - mainScreenOrigin.x,
mainScreenHeight - globalPoint.y -
mainScreenOrigin.y);
CGDisplayMoveCursorToPoint(CGMainDisplayID(), targetPoint);
if (window->mode == GLFW_FULLSCREEN)
{
NSPoint globalPoint = NSMakePoint(x, y);
CGDisplayMoveCursorToPoint(CGMainDisplayID(), globalPoint);
}
else
{
NSPoint localPoint = NSMakePoint(x, window->height - y - 1);
NSPoint globalPoint = [window->NS.object convertBaseToScreen:localPoint];
CGPoint mainScreenOrigin = CGDisplayBounds(CGMainDisplayID()).origin;
double mainScreenHeight = CGDisplayBounds(CGMainDisplayID()).size.height;
CGPoint targetPoint = CGPointMake(globalPoint.x - mainScreenOrigin.x,
mainScreenHeight - globalPoint.y -
mainScreenOrigin.y);
CGDisplayMoveCursorToPoint(CGMainDisplayID(), targetPoint);
}
}
//========================================================================
// Set physical mouse cursor mode
//========================================================================
+13 -12
View File
@@ -42,28 +42,29 @@
// Define this to 1 if building GLFW for Cocoa/NSOpenGL
#cmakedefine _GLFW_COCOA_NSGL
// Define this to 1 if building as a shared library / dynamic library / DLL
#cmakedefine _GLFW_BUILD_DLL
// Define this to 1 to disable dynamic loading of winmm
#cmakedefine _GLFW_NO_DLOAD_WINMM
// Define this to 1 if XRandR is available
#cmakedefine _GLFW_HAS_XRANDR 1
#cmakedefine _GLFW_HAS_XRANDR
// Define this to 1 if Xf86VidMode is available
#cmakedefine _GLFW_HAS_XF86VIDMODE 1
#cmakedefine _GLFW_HAS_XF86VIDMODE
// Define this to 1 if Xkb is available
#cmakedefine _GLFW_HAS_XKB 1
#cmakedefine _GLFW_HAS_XKB
// Define this to 1 if glXGetProcAddress is available
#cmakedefine _GLFW_HAS_GLXGETPROCADDRESS 1
#cmakedefine _GLFW_HAS_GLXGETPROCADDRESS
// Define this to 1 if glXGetProcAddressARB is available
#cmakedefine _GLFW_HAS_GLXGETPROCADDRESSARB 1
#cmakedefine _GLFW_HAS_GLXGETPROCADDRESSARB
// Define this to 1 if glXGetProcAddressEXT is available
#cmakedefine _GLFW_HAS_GLXGETPROCADDRESSEXT 1
#cmakedefine _GLFW_HAS_GLXGETPROCADDRESSEXT
// Define this to 1 if the Linux joystick API is available
#cmakedefine _GLFW_USE_LINUX_JOYSTICKS 1
// Define this to 1 to not load gdi32.dll dynamically
#cmakedefine _GLFW_NO_DLOAD_GDI32 1
// Define this to 1 to not load winmm.dll dynamically
#cmakedefine _GLFW_NO_DLOAD_WINMM 1
#cmakedefine _GLFW_USE_LINUX_JOYSTICKS
// The GLFW version as used by glfwGetVersionString
#define _GLFW_VERSION_FULL "@GLFW_VERSION_FULL@"
+2
View File
@@ -109,6 +109,8 @@ GLFWAPI const char* glfwErrorString(int error)
return "A platform-specific error occurred";
case GLFW_WINDOW_NOT_ACTIVE:
return "The specified window is not active";
case GLFW_FORMAT_UNAVAILABLE:
return "The requested format is unavailable";
}
return "ERROR: UNKNOWN ERROR TOKEN PASSED TO glfwErrorString";
+1
View File
@@ -112,5 +112,6 @@ GLFWAPI void glfwSetGammaRamp(const GLFWgammaramp* ramp)
_glfwPlatformSetGammaRamp(ramp);
_glfwLibrary.currentRamp = *ramp;
_glfwLibrary.rampChanged = GL_TRUE;
}
+1 -43
View File
@@ -35,30 +35,6 @@
#include <stdlib.h>
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
//========================================================================
// Allocate memory using the allocator
//========================================================================
void* _glfwMalloc(size_t size)
{
return _glfwLibrary.allocator.malloc(size);
}
//========================================================================
// Free memory using the allocator
//========================================================================
void _glfwFree(void* ptr)
{
_glfwLibrary.allocator.free(ptr);
}
//////////////////////////////////////////////////////////////////////////
////// GLFW public API //////
//////////////////////////////////////////////////////////////////////////
@@ -67,31 +43,13 @@ void _glfwFree(void* ptr)
// Initialize various GLFW state
//========================================================================
GLFWAPI int glfwInit(GLFWallocator* allocator)
GLFWAPI int glfwInit(void)
{
if (_glfwInitialized)
return GL_TRUE;
memset(&_glfwLibrary, 0, sizeof(_glfwLibrary));
if (allocator)
{
// Verify that the specified model is complete
if (!allocator->malloc || !allocator->free)
{
_glfwSetError(GLFW_INVALID_VALUE, NULL);
return GL_FALSE;
}
_glfwLibrary.allocator = *allocator;
}
else
{
// Use the libc malloc and free
_glfwLibrary.allocator.malloc = malloc;
_glfwLibrary.allocator.free = free;
}
// Not all window hints have zero as their default value, so this
// needs to be here despite the memset above
_glfwSetDefaultWindowHints();
+55 -38
View File
@@ -35,37 +35,33 @@
// Sets the cursor mode for the specified window
//========================================================================
static void setCursorMode(_GLFWwindow* window, int mode)
static void setCursorMode(_GLFWwindow* window, int newMode)
{
int centerPosX, centerPosY;
int oldMode, centerPosX, centerPosY;
if (mode != GLFW_CURSOR_NORMAL &&
mode != GLFW_CURSOR_HIDDEN &&
mode != GLFW_CURSOR_CAPTURED)
if (newMode != GLFW_CURSOR_NORMAL &&
newMode != GLFW_CURSOR_HIDDEN &&
newMode != GLFW_CURSOR_CAPTURED)
{
_glfwSetError(GLFW_INVALID_ENUM, NULL);
return;
}
if (window->cursorMode == mode)
oldMode = window->cursorMode;
if (oldMode == newMode)
return;
centerPosX = window->width / 2;
centerPosY = window->height / 2;
if (mode == GLFW_CURSOR_CAPTURED)
_glfwPlatformSetMouseCursorPos(window, centerPosX, centerPosY);
else if (window->cursorMode == GLFW_CURSOR_CAPTURED)
{
_glfwPlatformSetMouseCursorPos(window, centerPosX, centerPosY);
_glfwInputCursorMotion(window,
centerPosX - window->cursorPosX,
centerPosY - window->cursorPosY);
}
if (oldMode == GLFW_CURSOR_CAPTURED || newMode == GLFW_CURSOR_CAPTURED)
_glfwPlatformSetCursorPos(window, centerPosX, centerPosY);
_glfwPlatformSetCursorMode(window, mode);
_glfwPlatformSetCursorMode(window, newMode);
window->cursorMode = newMode;
window->cursorMode = mode;
if (oldMode == GLFW_CURSOR_CAPTURED)
_glfwInputCursorMotion(window, window->cursorPosX, window->cursorPosY);
}
@@ -167,7 +163,7 @@ void _glfwInputKey(_GLFWwindow* window, int key, int action)
return;
// Register key action
if(action == GLFW_RELEASE && window->stickyKeys)
if (action == GLFW_RELEASE && window->stickyKeys)
window->key[key] = GLFW_STICK;
else
{
@@ -200,7 +196,7 @@ void _glfwInputChar(_GLFWwindow* window, int character)
// Register scroll events
//========================================================================
void _glfwInputScroll(_GLFWwindow* window, int xoffset, int yoffset)
void _glfwInputScroll(_GLFWwindow* window, double xoffset, double yoffset)
{
window->scrollX += xoffset;
window->scrollY += yoffset;
@@ -253,15 +249,26 @@ void _glfwInputCursorMotion(_GLFWwindow* window, int x, int y)
window->cursorPosY = y;
}
if (_glfwLibrary.mousePosCallback)
if (_glfwLibrary.cursorPosCallback)
{
_glfwLibrary.mousePosCallback(window,
window->cursorPosX,
window->cursorPosY);
_glfwLibrary.cursorPosCallback(window,
window->cursorPosX,
window->cursorPosY);
}
}
//========================================================================
// Register cursor enter/leave events
//========================================================================
void _glfwInputCursorEnter(_GLFWwindow* window, int entered)
{
if (_glfwLibrary.cursorEnterCallback)
_glfwLibrary.cursorEnterCallback(window, entered);
}
//////////////////////////////////////////////////////////////////////////
////// GLFW public API //////
//////////////////////////////////////////////////////////////////////////
@@ -351,10 +358,8 @@ GLFWAPI int glfwGetKey(GLFWwindow handle, int key)
return GLFW_RELEASE;
}
// Is it a valid key?
if (key < 0 || key > GLFW_KEY_LAST)
{
// TODO: Decide whether key is a value or enum
_glfwSetError(GLFW_INVALID_ENUM,
"glfwGetKey: The specified key is invalid");
return GLFW_RELEASE;
@@ -385,7 +390,6 @@ GLFWAPI int glfwGetMouseButton(GLFWwindow handle, int button)
return GLFW_RELEASE;
}
// Is it a valid mouse button?
if (button < 0 || button > GLFW_MOUSE_BUTTON_LAST)
{
_glfwSetError(GLFW_INVALID_ENUM,
@@ -408,7 +412,7 @@ GLFWAPI int glfwGetMouseButton(GLFWwindow handle, int button)
// Returns the last reported cursor position for the specified window
//========================================================================
GLFWAPI void glfwGetMousePos(GLFWwindow handle, int* xpos, int* ypos)
GLFWAPI void glfwGetCursorPos(GLFWwindow handle, int* xpos, int* ypos)
{
_GLFWwindow* window = (_GLFWwindow*) handle;
@@ -418,7 +422,6 @@ GLFWAPI void glfwGetMousePos(GLFWwindow handle, int* xpos, int* ypos)
return;
}
// Return mouse position
if (xpos != NULL)
*xpos = window->cursorPosX;
@@ -432,7 +435,7 @@ GLFWAPI void glfwGetMousePos(GLFWwindow handle, int* xpos, int* ypos)
// the specified window
//========================================================================
GLFWAPI void glfwSetMousePos(GLFWwindow handle, int xpos, int ypos)
GLFWAPI void glfwSetCursorPos(GLFWwindow handle, int xpos, int ypos)
{
_GLFWwindow* window = (_GLFWwindow*) handle;
@@ -448,11 +451,11 @@ GLFWAPI void glfwSetMousePos(GLFWwindow handle, int xpos, int ypos)
return;
}
// Don't do anything if the mouse position did not change
// Don't do anything if the cursor position did not change
if (xpos == window->cursorPosX && ypos == window->cursorPosY)
return;
// Set GLFW mouse position
// Set GLFW cursor position
window->cursorPosX = xpos;
window->cursorPosY = ypos;
@@ -461,7 +464,7 @@ GLFWAPI void glfwSetMousePos(GLFWwindow handle, int xpos, int ypos)
return;
// Update physical cursor position
_glfwPlatformSetMouseCursorPos(window, xpos, ypos);
_glfwPlatformSetCursorPos(window, xpos, ypos);
}
@@ -469,7 +472,7 @@ GLFWAPI void glfwSetMousePos(GLFWwindow handle, int xpos, int ypos)
// Returns the scroll offset for the specified window
//========================================================================
GLFWAPI void glfwGetScrollOffset(GLFWwindow handle, int* xoffset, int* yoffset)
GLFWAPI void glfwGetScrollOffset(GLFWwindow handle, double* xoffset, double* yoffset)
{
_GLFWwindow* window = (_GLFWwindow*) handle;
@@ -539,7 +542,7 @@ GLFWAPI void glfwSetMouseButtonCallback(GLFWmousebuttonfun cbfun)
// Set callback function for mouse moves
//========================================================================
GLFWAPI void glfwSetMousePosCallback(GLFWmouseposfun cbfun)
GLFWAPI void glfwSetCursorPosCallback(GLFWcursorposfun cbfun)
{
if (!_glfwInitialized)
{
@@ -547,11 +550,10 @@ GLFWAPI void glfwSetMousePosCallback(GLFWmouseposfun cbfun)
return;
}
// Set callback function
_glfwLibrary.mousePosCallback = cbfun;
_glfwLibrary.cursorPosCallback = cbfun;
// Call the callback function to let the application know the current
// mouse position
// cursor position
if (cbfun)
{
_GLFWwindow* window;
@@ -562,6 +564,22 @@ GLFWAPI void glfwSetMousePosCallback(GLFWmouseposfun cbfun)
}
//========================================================================
// Set callback function for cursor enter/leave events
//========================================================================
GLFWAPI void glfwSetCursorEnterCallback(GLFWcursorenterfun cbfun)
{
if (!_glfwInitialized)
{
_glfwSetError(GLFW_NOT_INITIALIZED, NULL);
return;
}
_glfwLibrary.cursorEnterCallback = cbfun;
}
//========================================================================
// Set callback function for scroll events
//========================================================================
@@ -574,7 +592,6 @@ GLFWAPI void glfwSetScrollCallback(GLFWscrollfun cbfun)
return;
}
// Set callback function
_glfwLibrary.scrollCallback = cbfun;
}
+33 -19
View File
@@ -37,9 +37,9 @@
//========================================================================
#if defined(_init_c_)
#define GLFWGLOBAL
#define GLFWGLOBAL
#else
#define GLFWGLOBAL extern
#define GLFWGLOBAL extern
#endif
@@ -51,6 +51,17 @@
#define GLFW_STICK 2
//========================================================================
// Internal type declarations
//========================================================================
typedef struct _GLFWhints _GLFWhints;
typedef struct _GLFWwndconfig _GLFWwndconfig;
typedef struct _GLFWfbconfig _GLFWfbconfig;
typedef struct _GLFWwindow _GLFWwindow;
typedef struct _GLFWlibrary _GLFWlibrary;
//------------------------------------------------------------------------
// Platform specific definitions goes in platform.h (which also includes
// glfw.h)
@@ -73,15 +84,16 @@ typedef struct _GLFWlibrary _GLFWlibrary;
typedef struct _GLFWmonitor _GLFWmonitor;
#if defined(_GLFW_COCOA_NSGL)
#include "cocoa_platform.h"
#include "cocoa_platform.h"
#elif defined(_GLFW_WIN32_WGL)
#include "win32_platform.h"
#include "win32_platform.h"
#elif defined(_GLFW_X11_GLX)
#include "x11_platform.h"
#include "x11_platform.h"
#else
#error "No supported platform selected"
#error "No supported platform selected"
#endif
//------------------------------------------------------------------------
// Window hints, set by glfwOpenWindowHint and consumed by glfwOpenWindow
// A bucket of semi-random stuff lumped together for historical reasons
@@ -186,7 +198,7 @@ struct _GLFWwindow
GLboolean systemKeys; // system keys enabled flag
int cursorPosX, cursorPosY;
int cursorMode;
int scrollX, scrollY;
double scrollX, scrollY;
char mouseButton[GLFW_MOUSE_BUTTON_LAST + 1];
char key[GLFW_KEY_LAST + 1];
@@ -259,20 +271,21 @@ struct _GLFWlibrary
GLFWwindowfocusfun windowFocusCallback;
GLFWwindowiconifyfun windowIconifyCallback;
GLFWmousebuttonfun mouseButtonCallback;
GLFWmouseposfun mousePosCallback;
GLFWcursorposfun cursorPosCallback;
GLFWcursorenterfun cursorEnterCallback;
GLFWscrollfun scrollCallback;
GLFWkeyfun keyCallback;
GLFWcharfun charCallback;
GLFWmonitordevicefun monitorCallback;
GLFWallocator allocator;
GLFWgammaramp currentRamp;
GLFWgammaramp originalRamp;
int originalRampSize;
GLboolean rampChanged;
// This is defined in the current port's platform.h
_GLFW_PLATFORM_LIBRARY_STATE;
_GLFW_PLATFORM_LIBRARY_WINDOW_STATE;
_GLFW_PLATFORM_LIBRARY_OPENGL_STATE;
};
@@ -302,6 +315,8 @@ const char* _glfwPlatformGetVersionString(void);
// Input
void _glfwPlatformEnableSystemKeys(_GLFWwindow* window);
void _glfwPlatformDisableSystemKeys(_GLFWwindow* window);
void _glfwPlatformSetCursorPos(_GLFWwindow* window, int x, int y);
void _glfwPlatformSetCursorMode(_GLFWwindow* window, int mode);
// Fullscreen
int _glfwPlatformGetVideoModes(_GLFWmonitor* monitor, GLFWvidmode* list, int maxcount);
@@ -311,6 +326,10 @@ void _glfwPlatformGetDesktopMode(GLFWvidmode* mode);
void _glfwPlatformGetGammaRamp(GLFWgammaramp* ramp);
void _glfwPlatformSetGammaRamp(const GLFWgammaramp* ramp);
// Clipboard
void _glfwPlatformSetClipboardString(_GLFWwindow* window, const char* string);
const char* _glfwPlatformGetClipboardString(_GLFWwindow* window);
// Joystick
int _glfwPlatformGetJoystickParam(int joy, int param);
int _glfwPlatformGetJoystickPos(int joy, float* pos, int numaxes);
@@ -328,8 +347,6 @@ void _glfwPlatformSetWindowSize(_GLFWwindow* window, int width, int height);
void _glfwPlatformSetWindowPos(_GLFWwindow* window, int x, int y);
void _glfwPlatformIconifyWindow(_GLFWwindow* window);
void _glfwPlatformRestoreWindow(_GLFWwindow* window);
void _glfwPlatformSetMouseCursorPos(_GLFWwindow* window, int x, int y);
void _glfwPlatformSetCursorMode(_GLFWwindow* window, int mode);
// Event management
void _glfwPlatformPollEvents(void);
@@ -341,7 +358,7 @@ void _glfwPlatformSwapBuffers(void);
void _glfwPlatformSwapInterval(int interval);
void _glfwPlatformRefreshWindowParams(void);
int _glfwPlatformExtensionSupported(const char* extension);
void* _glfwPlatformGetProcAddress(const char* procname);
GLFWglproc _glfwPlatformGetProcAddress(const char* procname);
void _glfwPlatformCopyContext(_GLFWwindow* src, _GLFWwindow* dst, unsigned long mask);
@@ -349,10 +366,6 @@ void _glfwPlatformCopyContext(_GLFWwindow* src, _GLFWwindow* dst, unsigned long
// Prototypes for platform independent internal functions
//========================================================================
// Memory management (init.c)
void* _glfwMalloc(size_t size);
void _glfwFree(void* ptr);
// Fullscren management (fullscreen.c)
void _glfwSplitBPP(int bpp, int* red, int* green, int* blue);
int _glfwCompareVideoModes(const void* firstPtr, const void* secondPtr);
@@ -373,9 +386,10 @@ void _glfwInputWindowDamage(_GLFWwindow* window);
// Input event notification (input.c)
void _glfwInputKey(_GLFWwindow* window, int key, int action);
void _glfwInputChar(_GLFWwindow* window, int character);
void _glfwInputScroll(_GLFWwindow* window, int x, int y);
void _glfwInputScroll(_GLFWwindow* window, double x, double y);
void _glfwInputMouseClick(_GLFWwindow* window, int button, int action);
void _glfwInputCursorMotion(_GLFWwindow* window, int x, int y);
void _glfwInputCursorEnter(_GLFWwindow* window, int entered);
// OpenGL context helpers (opengl.c)
int _glfwStringInExtensionString(const char* string, const GLubyte* extensions);
+4 -3
View File
@@ -5,8 +5,9 @@ libdir=${exec_prefix}/lib
Name: GLFW
Description: A portable library for OpenGL, window and input
Version: 3.0.0
Version: @GLFW_VERSION_FULL@
URL: http://www.glfw.org/
Requires.private: gl x11 @GLFW_PKGLIBS@
Libs: -L${libdir} -lglfw
Requires.private: @GLFW_PKG_DEPS@
Libs: -L${libdir} -lglfw
Libs.private: @GLFW_PKG_LIBS@
Cflags: -I${includedir}
+2
View File
@@ -30,6 +30,8 @@
#include "internal.h"
#include <string.h>
//////////////////////////////////////////////////////////////////////////
////// GLFW public API //////
+2 -3
View File
@@ -517,8 +517,7 @@ GLFWAPI void glfwSwapBuffers(void)
return;
}
if (_glfwLibrary.currentWindow)
_glfwPlatformSwapBuffers();
_glfwPlatformSwapBuffers();
}
@@ -614,7 +613,7 @@ GLFWAPI int glfwExtensionSupported(const char* extension)
// This function can be used to get access to extended OpenGL functions.
//========================================================================
GLFWAPI void* glfwGetProcAddress(const char* procname)
GLFWAPI GLFWglproc glfwGetProcAddress(const char* procname)
{
if (!_glfwInitialized)
{
+140
View File
@@ -0,0 +1,140 @@
//========================================================================
// GLFW - An OpenGL library
// Platform: Win32/WGL
// API version: 3.0
// WWW: http://www.glfw.org/
//------------------------------------------------------------------------
// Copyright (c) 2010 Camilla Berglund <elmindreda@elmindreda.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#include "internal.h"
#include <limits.h>
#include <string.h>
#include <stdlib.h>
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
//========================================================================
// Set the clipboard contents
//========================================================================
void _glfwPlatformSetClipboardString(_GLFWwindow* window, const char* string)
{
WCHAR* wideString;
HANDLE stringHandle;
size_t wideSize;
wideString = _glfwCreateWideStringFromUTF8(string);
if (!wideString)
{
_glfwSetError(GLFW_PLATFORM_ERROR,
"Win32/WGL: Failed to convert clipboard string to "
"wide string");
return;
}
wideSize = (wcslen(wideString) + 1) * sizeof(WCHAR);
stringHandle = GlobalAlloc(GMEM_MOVEABLE, wideSize);
if (!stringHandle)
{
free(wideString);
_glfwSetError(GLFW_PLATFORM_ERROR,
"Win32/WGL: Failed to allocate global handle for clipboard");
return;
}
memcpy(GlobalLock(stringHandle), wideString, wideSize);
GlobalUnlock(stringHandle);
if (!OpenClipboard(window->Win32.handle))
{
GlobalFree(stringHandle);
free(wideString);
_glfwSetError(GLFW_PLATFORM_ERROR,
"Win32/WGL: Failed to open clipboard");
return;
}
EmptyClipboard();
SetClipboardData(CF_UNICODETEXT, stringHandle);
CloseClipboard();
free(wideString);
}
//========================================================================
// Return the current clipboard contents
//========================================================================
const char* _glfwPlatformGetClipboardString(_GLFWwindow* window)
{
HANDLE stringHandle;
if (!IsClipboardFormatAvailable(CF_UNICODETEXT))
{
_glfwSetError(GLFW_FORMAT_UNAVAILABLE, NULL);
return NULL;
}
if (!OpenClipboard(window->Win32.handle))
{
_glfwSetError(GLFW_PLATFORM_ERROR,
"Win32/WGL: Failed to open clipboard");
return NULL;
}
stringHandle = GetClipboardData(CF_UNICODETEXT);
if (!stringHandle)
{
CloseClipboard();
_glfwSetError(GLFW_PLATFORM_ERROR,
"Win32/WGL: Failed to retrieve clipboard data");
return NULL;
}
free(_glfwLibrary.Win32.clipboardString);
_glfwLibrary.Win32.clipboardString =
_glfwCreateUTF8FromWideString(GlobalLock(stringHandle));
GlobalUnlock(stringHandle);
CloseClipboard();
if (!_glfwLibrary.Win32.clipboardString)
{
_glfwSetError(GLFW_PLATFORM_ERROR,
"Win32/WGL: Failed to convert wide string to UTF-8");
return NULL;
}
return _glfwLibrary.Win32.clipboardString;
}
+2 -2
View File
@@ -31,7 +31,7 @@
#include "internal.h"
#if defined(GLFW_BUILD_DLL)
#if defined(_GLFW_BUILD_DLL)
//========================================================================
// GLFW DLL entry point
@@ -45,5 +45,5 @@ BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved)
return TRUE;
}
#endif // GLFW_BUILD_DLL
#endif // _GLFW_BUILD_DLL
+2 -2
View File
@@ -42,7 +42,7 @@
void _glfwPlatformGetGammaRamp(GLFWgammaramp* ramp)
{
_glfw_GetDeviceGammaRamp(GetDC(GetDesktopWindow()), (WORD*) ramp);
GetDeviceGammaRamp(GetDC(GetDesktopWindow()), (WORD*) ramp);
}
@@ -52,6 +52,6 @@ void _glfwPlatformGetGammaRamp(GLFWgammaramp* ramp)
void _glfwPlatformSetGammaRamp(const GLFWgammaramp* ramp)
{
_glfw_SetDeviceGammaRamp(GetDC(GetDesktopWindow()), (WORD*) ramp);
SetDeviceGammaRamp(GetDC(GetDesktopWindow()), (WORD*) ramp);
}
+59 -51
View File
@@ -44,40 +44,6 @@
static GLboolean initLibraries(void)
{
#ifndef _GLFW_NO_DLOAD_GDI32
// gdi32.dll (OpenGL pixel format functions & SwapBuffers)
_glfwLibrary.Win32.gdi.instance = LoadLibrary(L"gdi32.dll");
if (!_glfwLibrary.Win32.gdi.instance)
return GL_FALSE;
_glfwLibrary.Win32.gdi.ChoosePixelFormat = (CHOOSEPIXELFORMAT_T)
GetProcAddress(_glfwLibrary.Win32.gdi.instance, "ChoosePixelFormat");
_glfwLibrary.Win32.gdi.DescribePixelFormat = (DESCRIBEPIXELFORMAT_T)
GetProcAddress(_glfwLibrary.Win32.gdi.instance, "DescribePixelFormat");
_glfwLibrary.Win32.gdi.GetPixelFormat = (GETPIXELFORMAT_T)
GetProcAddress(_glfwLibrary.Win32.gdi.instance, "GetPixelFormat");
_glfwLibrary.Win32.gdi.SetPixelFormat = (SETPIXELFORMAT_T)
GetProcAddress(_glfwLibrary.Win32.gdi.instance, "SetPixelFormat");
_glfwLibrary.Win32.gdi.SwapBuffers = (SWAPBUFFERS_T)
GetProcAddress(_glfwLibrary.Win32.gdi.instance, "SwapBuffers");
_glfwLibrary.Win32.gdi.GetDeviceGammaRamp = (GETDEVICEGAMMARAMP_T)
GetProcAddress(_glfwLibrary.Win32.gdi.instance, "GetDeviceGammaRamp");
_glfwLibrary.Win32.gdi.SetDeviceGammaRamp = (SETDEVICEGAMMARAMP_T)
GetProcAddress(_glfwLibrary.Win32.gdi.instance, "SetDeviceGammaRamp");
if (!_glfwLibrary.Win32.gdi.ChoosePixelFormat ||
!_glfwLibrary.Win32.gdi.DescribePixelFormat ||
!_glfwLibrary.Win32.gdi.GetPixelFormat ||
!_glfwLibrary.Win32.gdi.SetPixelFormat ||
!_glfwLibrary.Win32.gdi.SwapBuffers ||
!_glfwLibrary.Win32.gdi.GetDeviceGammaRamp ||
!_glfwLibrary.Win32.gdi.SetDeviceGammaRamp)
{
return GL_FALSE;
}
#endif // _GLFW_NO_DLOAD_GDI32
#ifndef _GLFW_NO_DLOAD_WINMM
// winmm.dll (for joystick and timer support)
@@ -113,14 +79,6 @@ static GLboolean initLibraries(void)
static void freeLibraries(void)
{
#ifndef _GLFW_NO_DLOAD_GDI32
if (_glfwLibrary.Win32.gdi.instance != NULL)
{
FreeLibrary(_glfwLibrary.Win32.gdi.instance);
_glfwLibrary.Win32.gdi.instance = NULL;
}
#endif // _GLFW_NO_DLOAD_GDI32
#ifndef _GLFW_NO_DLOAD_WINMM
if (_glfwLibrary.Win32.winmm.instance != NULL)
{
@@ -131,6 +89,60 @@ static void freeLibraries(void)
}
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
//========================================================================
// Returns a wide string version of the specified UTF-8 string
//========================================================================
WCHAR* _glfwCreateWideStringFromUTF8(const char* source)
{
WCHAR* target;
int length;
length = MultiByteToWideChar(CP_UTF8, 0, source, -1, NULL, 0);
if (!length)
return NULL;
target = (WCHAR*) malloc(sizeof(WCHAR) * (length + 1));
if (!MultiByteToWideChar(CP_UTF8, 0, source, -1, target, length + 1))
{
free(target);
return NULL;
}
return target;
}
//========================================================================
// Returns a UTF-8 string version of the specified wide string
//========================================================================
char* _glfwCreateUTF8FromWideString(const WCHAR* source)
{
char* target;
int length;
length = WideCharToMultiByte(CP_UTF8, 0, source, -1, NULL, 0, NULL, NULL);
if (!length)
return NULL;
target = (char*) malloc(length + 1);
if (!WideCharToMultiByte(CP_UTF8, 0, source, -1, target, length + 1, NULL, NULL))
{
free(target);
return NULL;
}
return target;
}
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
@@ -146,7 +158,7 @@ int _glfwPlatformInit(void)
// as possible in the hope of still being the foreground process)
SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0,
&_glfwLibrary.Win32.foregroundLockTimeout, 0);
SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (LPVOID) 0,
SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, UIntToPtr(0),
SPIF_SENDCHANGE);
if (!initLibraries())
@@ -180,7 +192,8 @@ int _glfwPlatformInit(void)
int _glfwPlatformTerminate(void)
{
// Restore the original gamma ramp
_glfwPlatformSetGammaRamp(&_glfwLibrary.originalRamp);
if (_glfwLibrary.rampChanged)
_glfwPlatformSetGammaRamp(&_glfwLibrary.originalRamp);
_glfwTerminateMonitors();
@@ -196,7 +209,7 @@ int _glfwPlatformTerminate(void)
// Restore previous FOREGROUNDLOCKTIMEOUT system setting
SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0,
(LPVOID) _glfwLibrary.Win32.foregroundLockTimeout,
UIntToPtr(_glfwLibrary.Win32.foregroundLockTimeout),
SPIF_SENDCHANGE);
return GL_TRUE;
@@ -212,8 +225,6 @@ const char* _glfwPlatformGetVersionString(void)
const char* version = _GLFW_VERSION_FULL
#if defined(__MINGW32__)
" MinGW"
#elif defined(__CYGWIN__)
" Cygwin"
#elif defined(_MSC_VER)
" Visual C++ "
#elif defined(__BORLANDC__)
@@ -221,12 +232,9 @@ const char* _glfwPlatformGetVersionString(void)
#else
" (unknown compiler)"
#endif
#if defined(GLFW_BUILD_DLL)
#if defined(_GLFW_BUILD_DLL)
" DLL"
#endif
#if !defined(_GLFW_NO_DLOAD_GDI32)
" load(gdi32)"
#endif
#if !defined(_GLFW_NO_DLOAD_WINMM)
" load(winmm)"
#endif
+29 -5
View File
@@ -80,6 +80,7 @@ static float calcJoystickPos(DWORD pos, DWORD min, DWORD max)
int _glfwPlatformGetJoystickParam(int joy, int param)
{
JOYCAPS jc;
int hats;
if (!isJoystickPresent(joy))
return 0;
@@ -91,6 +92,8 @@ int _glfwPlatformGetJoystickParam(int joy, int param)
// Get joystick capabilities
_glfw_joyGetDevCaps(joy - GLFW_JOYSTICK_1, &jc, sizeof(JOYCAPS));
hats = (jc.wCaps & JOYCAPS_HASPOV) && (jc.wCaps & JOYCAPS_POV4DIR) ? 1 : 0;
switch (param)
{
case GLFW_AXES:
@@ -98,8 +101,8 @@ int _glfwPlatformGetJoystickParam(int joy, int param)
return jc.wNumAxes;
case GLFW_BUTTONS:
// Return number of joystick axes
return jc.wNumButtons;
// Return number of joystick buttons
return jc.wNumButtons + hats * 4;
default:
break;
@@ -164,7 +167,10 @@ int _glfwPlatformGetJoystickButtons(int joy, unsigned char* buttons,
{
JOYCAPS jc;
JOYINFOEX ji;
int button;
int button, hats;
// Bit fields of button presses for each direction, including nil
const int directions[9] = { 1, 3, 2, 6, 4, 12, 8, 9, 0 };
if (!isJoystickPresent(joy))
return 0;
@@ -174,7 +180,7 @@ int _glfwPlatformGetJoystickButtons(int joy, unsigned char* buttons,
// Get joystick state
ji.dwSize = sizeof(JOYINFOEX);
ji.dwFlags = JOY_RETURNBUTTONS;
ji.dwFlags = JOY_RETURNBUTTONS | JOY_RETURNPOV;
_glfw_joyGetPosEx(joy - GLFW_JOYSTICK_1, &ji);
// Get states of all requested buttons
@@ -184,6 +190,24 @@ int _glfwPlatformGetJoystickButtons(int joy, unsigned char* buttons,
(ji.dwButtons & (1UL << button) ? GLFW_PRESS : GLFW_RELEASE);
}
// Virtual buttons - Inject data from hats
// Each hat is exposed as 4 buttons which exposes 8 directions with
// concurrent button presses
// NOTE: this API exposes only one hat
hats = (jc.wCaps & JOYCAPS_HASPOV) && (jc.wCaps & JOYCAPS_POV4DIR) ? 1 : 0;
if (hats > 0)
{
int j;
int value = ji.dwPOV / 100 / 45;
if (value < 0 || value > 8) value = 8;
for (j = 0; j < 4 && button < numbuttons; j++)
{
buttons[button++] = directions[value] & (1 << j) ? GLFW_PRESS : GLFW_RELEASE;
}
}
return button;
}
+3 -3
View File
@@ -56,7 +56,7 @@ void _glfwPlatformSwapBuffers(void)
{
_GLFWwindow* window = _glfwLibrary.currentWindow;
_glfw_SwapBuffers(window->WGL.DC);
SwapBuffers(window->WGL.DC);
}
@@ -111,9 +111,9 @@ int _glfwPlatformExtensionSupported(const char* extension)
// Get the function pointer to an OpenGL function
//========================================================================
void* _glfwPlatformGetProcAddress(const char* procname)
GLFWglproc _glfwPlatformGetProcAddress(const char* procname)
{
return (void*) wglGetProcAddress(procname);
return (GLFWglproc) wglGetProcAddress(procname);
}
+47 -141
View File
@@ -33,8 +33,13 @@
// We don't need all the fancy stuff
#define NOMINMAX
#define VC_EXTRALEAN
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifndef VC_EXTRALEAN
#define VC_EXTRALEAN
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
@@ -45,7 +50,15 @@
// thinks it is the only one that gets to do so
#undef APIENTRY
#define UNICODE
// GLFW on Windows is Unicode only and does not work in MBCS mode
#ifndef UNICODE
#define UNICODE
#endif
// GLFW requires Windows XP
#ifndef WINVER
#define WINVER 0x0501
#endif
#include <windows.h>
#include <mmsystem.h>
@@ -61,90 +74,8 @@
// Hack: Define things that some windows.h variants don't
//========================================================================
// Some old versions of w32api (used by MinGW and Cygwin) define
// WH_KEYBOARD_LL without typedef:ing KBDLLHOOKSTRUCT (!)
#if defined(__MINGW32__) || defined(__CYGWIN__)
#include <w32api.h>
#if defined(WH_KEYBOARD_LL) && (__W32API_MAJOR_VERSION == 1) && (__W32API_MINOR_VERSION <= 2)
#undef WH_KEYBOARD_LL
#endif
#endif
//------------------------------------------------------------------------
// ** NOTE ** If this gives you compiler errors and you are using MinGW
// (or Dev-C++), update to w32api version 1.3 or later:
// http://sourceforge.net/project/showfiles.php?group_id=2435
//------------------------------------------------------------------------
#ifndef WH_KEYBOARD_LL
#define WH_KEYBOARD_LL 13
typedef struct tagKBDLLHOOKSTRUCT {
DWORD vkCode;
DWORD scanCode;
DWORD flags;
DWORD time;
DWORD dwExtraInfo;
} KBDLLHOOKSTRUCT, FAR *LPKBDLLHOOKSTRUCT, *PKBDLLHOOKSTRUCT;
#endif // WH_KEYBOARD_LL
#ifndef LLKHF_ALTDOWN
#define LLKHF_ALTDOWN 0x00000020
#endif
#ifndef SPI_SETSCREENSAVERRUNNING
#define SPI_SETSCREENSAVERRUNNING 97
#endif
#ifndef SPI_GETANIMATION
#define SPI_GETANIMATION 72
#endif
#ifndef SPI_SETANIMATION
#define SPI_SETANIMATION 73
#endif
#ifndef SPI_GETFOREGROUNDLOCKTIMEOUT
#define SPI_GETFOREGROUNDLOCKTIMEOUT 0x2000
#endif
#ifndef SPI_SETFOREGROUNDLOCKTIMEOUT
#define SPI_SETFOREGROUNDLOCKTIMEOUT 0x2001
#endif
#ifndef CDS_FULLSCREEN
#define CDS_FULLSCREEN 4
#endif
#ifndef PFD_GENERIC_ACCELERATED
#define PFD_GENERIC_ACCELERATED 0x00001000
#endif
#ifndef PFD_DEPTH_DONTCARE
#define PFD_DEPTH_DONTCARE 0x20000000
#endif
#ifndef ENUM_CURRENT_SETTINGS
#define ENUM_CURRENT_SETTINGS -1
#endif
#ifndef ENUM_REGISTRY_SETTINGS
#define ENUM_REGISTRY_SETTINGS -2
#endif
#ifndef WM_MOUSEWHEEL
#define WM_MOUSEWHEEL 0x020A
#endif
#ifndef WHEEL_DELTA
#define WHEEL_DELTA 120
#endif
#ifndef WM_MOUSEHWHEEL
#define WM_MOUSEHWHEEL 0x020E
#endif
#ifndef WM_XBUTTONDOWN
#define WM_XBUTTONDOWN 0x020B
#endif
#ifndef WM_XBUTTONUP
#define WM_XBUTTONUP 0x020C
#endif
#ifndef XBUTTON1
#define XBUTTON1 1
#endif
#ifndef XBUTTON2
#define XBUTTON2 2
#define WM_MOUSEHWHEEL 0x020E
#endif
@@ -152,17 +83,6 @@ typedef struct tagKBDLLHOOKSTRUCT {
// DLLs that are loaded at glfwInit()
//========================================================================
// gdi32.dll function pointer typedefs
#ifndef _GLFW_NO_DLOAD_GDI32
typedef int (WINAPI * CHOOSEPIXELFORMAT_T) (HDC,CONST PIXELFORMATDESCRIPTOR*);
typedef int (WINAPI * DESCRIBEPIXELFORMAT_T) (HDC,int,UINT,LPPIXELFORMATDESCRIPTOR);
typedef int (WINAPI * GETPIXELFORMAT_T) (HDC);
typedef BOOL (WINAPI * SETPIXELFORMAT_T) (HDC,int,const PIXELFORMATDESCRIPTOR*);
typedef BOOL (WINAPI * SWAPBUFFERS_T) (HDC);
typedef BOOL (WINAPI * GETDEVICEGAMMARAMP_T) (HDC,PVOID);
typedef BOOL (WINAPI * SETDEVICEGAMMARAMP_T) (HDC,PVOID);
#endif // _GLFW_NO_DLOAD_GDI32
// winmm.dll function pointer typedefs
#ifndef _GLFW_NO_DLOAD_WINMM
typedef MMRESULT (WINAPI * JOYGETDEVCAPS_T) (UINT,LPJOYCAPS,UINT);
@@ -172,36 +92,17 @@ typedef DWORD (WINAPI * TIMEGETTIME_T) (void);
#endif // _GLFW_NO_DLOAD_WINMM
// gdi32.dll shortcuts
#ifndef _GLFW_NO_DLOAD_GDI32
#define _glfw_ChoosePixelFormat _glfwLibrary.Win32.gdi.ChoosePixelFormat
#define _glfw_DescribePixelFormat _glfwLibrary.Win32.gdi.DescribePixelFormat
#define _glfw_GetPixelFormat _glfwLibrary.Win32.gdi.GetPixelFormat
#define _glfw_SetPixelFormat _glfwLibrary.Win32.gdi.SetPixelFormat
#define _glfw_SwapBuffers _glfwLibrary.Win32.gdi.SwapBuffers
#define _glfw_GetDeviceGammaRamp _glfwLibrary.Win32.gdi.GetDeviceGammaRamp
#define _glfw_SetDeviceGammaRamp _glfwLibrary.Win32.gdi.SetDeviceGammaRamp
#else
#define _glfw_ChoosePixelFormat ChoosePixelFormat
#define _glfw_DescribePixelFormat DescribePixelFormat
#define _glfw_GetPixelFormat GetPixelFormat
#define _glfw_SetPixelFormat SetPixelFormat
#define _glfw_SwapBuffers SwapBuffers
#define _glfw_GetDeviceGammaRamp GetDeviceGammaRamp
#define _glfw_SetDeviceGammaRamp SetDeviceGammaRamp
#endif // _GLFW_NO_DLOAD_GDI32
// winmm.dll shortcuts
#ifndef _GLFW_NO_DLOAD_WINMM
#define _glfw_joyGetDevCaps _glfwLibrary.Win32.winmm.joyGetDevCaps
#define _glfw_joyGetPos _glfwLibrary.Win32.winmm.joyGetPos
#define _glfw_joyGetPosEx _glfwLibrary.Win32.winmm.joyGetPosEx
#define _glfw_timeGetTime _glfwLibrary.Win32.winmm.timeGetTime
#define _glfw_joyGetDevCaps _glfwLibrary.Win32.winmm.joyGetDevCaps
#define _glfw_joyGetPos _glfwLibrary.Win32.winmm.joyGetPos
#define _glfw_joyGetPosEx _glfwLibrary.Win32.winmm.joyGetPosEx
#define _glfw_timeGetTime _glfwLibrary.Win32.winmm.timeGetTime
#else
#define _glfw_joyGetDevCaps joyGetDevCaps
#define _glfw_joyGetPos joyGetPos
#define _glfw_joyGetPosEx joyGetPosEx
#define _glfw_timeGetTime timeGetTime
#define _glfw_joyGetDevCaps joyGetDevCaps
#define _glfw_joyGetPos joyGetPos
#define _glfw_joyGetPosEx joyGetPosEx
#define _glfw_timeGetTime timeGetTime
#endif // _GLFW_NO_DLOAD_WINMM
@@ -211,10 +112,13 @@ typedef DWORD (WINAPI * TIMEGETTIME_T) (void);
#define _GLFW_PLATFORM_WINDOW_STATE _GLFWwindowWin32 Win32
#define _GLFW_PLATFORM_LIBRARY_STATE _GLFWlibraryWin32 Win32
#define _GLFW_PLATFORM_CONTEXT_STATE _GLFWcontextWGL WGL
#define _GLFW_PLATFORM_MONITOR_STATE _GLFWmonitorWin32 Win32
#define _GLFW_PLATFORM_LIBRARY_WINDOW_STATE _GLFWlibraryWin32 Win32
#define _GLFW_PLATFORM_LIBRARY_OPENGL_STATE _GLFWlibraryWGL WGL
//========================================================================
// GLFW platform specific types
@@ -264,12 +168,13 @@ typedef struct _GLFWwindowWin32
// Various platform specific internal variables
int desiredRefreshRate; // Desired vertical monitor refresh rate
GLboolean cursorCentered;
int oldMouseX, oldMouseY;
GLboolean cursorInside;
int oldCursorX, oldCursorY;
} _GLFWwindowWin32;
//------------------------------------------------------------------------
// Platform-specific library global data
// Platform-specific library global data for Win32
//------------------------------------------------------------------------
typedef struct _GLFWlibraryWin32
{
@@ -277,6 +182,7 @@ typedef struct _GLFWlibraryWin32
ATOM classAtom; // Window class atom
HHOOK keyboardHook; // Keyboard hook handle
DWORD foregroundLockTimeout;
char* clipboardString;
// Default monitor
struct {
@@ -295,20 +201,6 @@ typedef struct _GLFWlibraryWin32
__int64 t0_64;
} timer;
#ifndef _GLFW_NO_DLOAD_GDI32
// gdi32.dll
struct {
HINSTANCE instance;
CHOOSEPIXELFORMAT_T ChoosePixelFormat;
DESCRIBEPIXELFORMAT_T DescribePixelFormat;
GETPIXELFORMAT_T GetPixelFormat;
SETPIXELFORMAT_T SetPixelFormat;
SWAPBUFFERS_T SwapBuffers;
GETDEVICEGAMMARAMP_T GetDeviceGammaRamp;
SETDEVICEGAMMARAMP_T SetDeviceGammaRamp;
} gdi;
#endif // _GLFW_NO_DLOAD_GDI32
#ifndef _GLFW_NO_DLOAD_WINMM
// winmm.dll
struct {
@@ -331,10 +223,24 @@ typedef struct _GLFWmonitorWin32
} _GLFWmonitorWin32;
//------------------------------------------------------------------------
// Platform-specific library global data for WGL
//------------------------------------------------------------------------
typedef struct _GLFWlibraryWGL
{
int dummy;
} _GLFWlibraryWGL;
//========================================================================
// Prototypes for platform specific internal functions
//========================================================================
// Wide strings
WCHAR* _glfwCreateWideStringFromUTF8(const char* source);
char* _glfwCreateUTF8FromWideString(const WCHAR* source);
// Time
void _glfwInitTimer(void);
Regular → Executable
+135 -180
View File
@@ -33,55 +33,6 @@
#include <stdlib.h>
//========================================================================
// Convert the specified UTF-8 string to a wide string
//========================================================================
static WCHAR* createWideStringFromUTF8(const char* source)
{
WCHAR* target;
int length;
length = MultiByteToWideChar(CP_UTF8, 0, source, -1, NULL, 0);
if (!length)
return NULL;
target = (WCHAR*) _glfwMalloc(sizeof(WCHAR) * (length + 1));
if (!MultiByteToWideChar(CP_UTF8, 0, source, -1, target, length + 1))
{
_glfwFree(target);
return NULL;
}
return target;
}
//========================================================================
// Convert BPP to RGB bits based on "best guess"
//========================================================================
static void bpp2rgb(int bpp, int* r, int* g, int* b)
{
int delta;
// We assume that by 32 they really meant 24
if (bpp == 32)
bpp = 24;
// Convert "bits per pixel" to red, green & blue sizes
*r = *g = *b = bpp / 3;
delta = bpp - (*r * 3);
if (delta >= 1)
*g = *g + 1;
if (delta == 2)
*r = *r + 1;
}
//========================================================================
// Enable/disable minimize/restore animations
//========================================================================
@@ -197,38 +148,44 @@ static int getPixelFormatAttrib(_GLFWwindow* window, int pixelFormat, int attrib
static _GLFWfbconfig* getFBConfigs(_GLFWwindow* window, unsigned int* found)
{
_GLFWfbconfig* result;
_GLFWfbconfig* fbconfigs;
PIXELFORMATDESCRIPTOR pfd;
int i, count;
int i, available;
*found = 0;
if (window->WGL.ARB_pixel_format)
count = getPixelFormatAttrib(window, 1, WGL_NUMBER_PIXEL_FORMATS_ARB);
{
available = getPixelFormatAttrib(window,
1,
WGL_NUMBER_PIXEL_FORMATS_ARB);
}
else
{
count = _glfw_DescribePixelFormat(window->WGL.DC,
1,
sizeof(PIXELFORMATDESCRIPTOR),
NULL);
available = DescribePixelFormat(window->WGL.DC,
1,
sizeof(PIXELFORMATDESCRIPTOR),
NULL);
}
if (!count)
if (!available)
{
_glfwSetError(GLFW_OPENGL_UNAVAILABLE, "Win32/WGL: No pixel formats found");
return NULL;
}
result = (_GLFWfbconfig*) _glfwMalloc(sizeof(_GLFWfbconfig) * count);
if (!result)
fbconfigs = (_GLFWfbconfig*) malloc(sizeof(_GLFWfbconfig) * available);
if (!fbconfigs)
{
_glfwSetError(GLFW_OUT_OF_MEMORY,
"Win32/WGL: Failed to allocate _GLFWfbconfig array");
return NULL;
}
for (i = 1; i <= count; i++)
for (i = 1; i <= available; i++)
{
_GLFWfbconfig* f = fbconfigs + *found;
if (window->WGL.ARB_pixel_format)
{
// Get pixel format attributes through WGL_ARB_pixel_format
@@ -251,50 +208,35 @@ static _GLFWfbconfig* getFBConfigs(_GLFWwindow* window, unsigned int* found)
continue;
}
result[*found].redBits =
getPixelFormatAttrib(window, i, WGL_RED_BITS_ARB);
result[*found].greenBits =
getPixelFormatAttrib(window, i, WGL_GREEN_BITS_ARB);
result[*found].blueBits =
getPixelFormatAttrib(window, i, WGL_BLUE_BITS_ARB);
result[*found].alphaBits =
getPixelFormatAttrib(window, i, WGL_ALPHA_BITS_ARB);
f->redBits = getPixelFormatAttrib(window, i, WGL_RED_BITS_ARB);
f->greenBits = getPixelFormatAttrib(window, i, WGL_GREEN_BITS_ARB);
f->blueBits = getPixelFormatAttrib(window, i, WGL_BLUE_BITS_ARB);
f->alphaBits = getPixelFormatAttrib(window, i, WGL_ALPHA_BITS_ARB);
result[*found].depthBits =
getPixelFormatAttrib(window, i, WGL_DEPTH_BITS_ARB);
result[*found].stencilBits =
getPixelFormatAttrib(window, i, WGL_STENCIL_BITS_ARB);
f->depthBits = getPixelFormatAttrib(window, i, WGL_DEPTH_BITS_ARB);
f->stencilBits = getPixelFormatAttrib(window, i, WGL_STENCIL_BITS_ARB);
result[*found].accumRedBits =
getPixelFormatAttrib(window, i, WGL_ACCUM_RED_BITS_ARB);
result[*found].accumGreenBits =
getPixelFormatAttrib(window, i, WGL_ACCUM_GREEN_BITS_ARB);
result[*found].accumBlueBits =
getPixelFormatAttrib(window, i, WGL_ACCUM_BLUE_BITS_ARB);
result[*found].accumAlphaBits =
getPixelFormatAttrib(window, i, WGL_ACCUM_ALPHA_BITS_ARB);
f->accumRedBits = getPixelFormatAttrib(window, i, WGL_ACCUM_RED_BITS_ARB);
f->accumGreenBits = getPixelFormatAttrib(window, i, WGL_ACCUM_GREEN_BITS_ARB);
f->accumBlueBits = getPixelFormatAttrib(window, i, WGL_ACCUM_BLUE_BITS_ARB);
f->accumAlphaBits = getPixelFormatAttrib(window, i, WGL_ACCUM_ALPHA_BITS_ARB);
result[*found].auxBuffers =
getPixelFormatAttrib(window, i, WGL_AUX_BUFFERS_ARB);
result[*found].stereo =
getPixelFormatAttrib(window, i, WGL_STEREO_ARB);
f->auxBuffers = getPixelFormatAttrib(window, i, WGL_AUX_BUFFERS_ARB);
f->stereo = getPixelFormatAttrib(window, i, WGL_STEREO_ARB);
if (window->WGL.ARB_multisample)
{
result[*found].samples =
getPixelFormatAttrib(window, i, WGL_SAMPLES_ARB);
}
f->samples = getPixelFormatAttrib(window, i, WGL_SAMPLES_ARB);
else
result[*found].samples = 0;
f->samples = 0;
}
else
{
// Get pixel format attributes through old-fashioned PFDs
if (!_glfw_DescribePixelFormat(window->WGL.DC,
i,
sizeof(PIXELFORMATDESCRIPTOR),
&pfd))
if (!DescribePixelFormat(window->WGL.DC,
i,
sizeof(PIXELFORMATDESCRIPTOR),
&pfd))
{
continue;
}
@@ -315,32 +257,38 @@ static _GLFWfbconfig* getFBConfigs(_GLFWwindow* window, unsigned int* found)
if (pfd.iPixelType != PFD_TYPE_RGBA)
continue;
result[*found].redBits = pfd.cRedBits;
result[*found].greenBits = pfd.cGreenBits;
result[*found].blueBits = pfd.cBlueBits;
result[*found].alphaBits = pfd.cAlphaBits;
f->redBits = pfd.cRedBits;
f->greenBits = pfd.cGreenBits;
f->blueBits = pfd.cBlueBits;
f->alphaBits = pfd.cAlphaBits;
result[*found].depthBits = pfd.cDepthBits;
result[*found].stencilBits = pfd.cStencilBits;
f->depthBits = pfd.cDepthBits;
f->stencilBits = pfd.cStencilBits;
result[*found].accumRedBits = pfd.cAccumRedBits;
result[*found].accumGreenBits = pfd.cAccumGreenBits;
result[*found].accumBlueBits = pfd.cAccumBlueBits;
result[*found].accumAlphaBits = pfd.cAccumAlphaBits;
f->accumRedBits = pfd.cAccumRedBits;
f->accumGreenBits = pfd.cAccumGreenBits;
f->accumBlueBits = pfd.cAccumBlueBits;
f->accumAlphaBits = pfd.cAccumAlphaBits;
result[*found].auxBuffers = pfd.cAuxBuffers;
result[*found].stereo = (pfd.dwFlags & PFD_STEREO) ? GL_TRUE : GL_FALSE;
f->auxBuffers = pfd.cAuxBuffers;
f->stereo = (pfd.dwFlags & PFD_STEREO) ? GL_TRUE : GL_FALSE;
// PFD pixel formats do not support FSAA
result[*found].samples = 0;
f->samples = 0;
}
result[*found].platformID = i;
f->platformID = i;
(*found)++;
}
return result;
if (*found == 0)
{
free(fbconfigs);
return NULL;
}
return fbconfigs;
}
@@ -359,14 +307,14 @@ static GLboolean createContext(_GLFWwindow* window,
if (wndconfig->share)
share = wndconfig->share->WGL.context;
if (!_glfw_DescribePixelFormat(window->WGL.DC, pixelFormat, sizeof(pfd), &pfd))
if (!DescribePixelFormat(window->WGL.DC, pixelFormat, sizeof(pfd), &pfd))
{
_glfwSetError(GLFW_OPENGL_UNAVAILABLE,
"Win32/WGL: Failed to retrieve PFD for selected pixel format");
return GL_FALSE;
}
if (!_glfw_SetPixelFormat(window->WGL.DC, pixelFormat, &pfd))
if (!SetPixelFormat(window->WGL.DC, pixelFormat, &pfd))
{
_glfwSetError(GLFW_OPENGL_UNAVAILABLE,
"Win32/WGL: Failed to set selected pixel format");
@@ -500,7 +448,7 @@ static GLboolean createContext(_GLFWwindow* window,
// Hide mouse cursor
//========================================================================
static void hideMouseCursor(_GLFWwindow* window)
static void hideCursor(_GLFWwindow* window)
{
}
@@ -509,7 +457,7 @@ static void hideMouseCursor(_GLFWwindow* window)
// Capture mouse cursor
//========================================================================
static void captureMouseCursor(_GLFWwindow* window)
static void captureCursor(_GLFWwindow* window)
{
RECT ClipWindowRect;
@@ -528,7 +476,7 @@ static void captureMouseCursor(_GLFWwindow* window)
// Show mouse cursor
//========================================================================
static void showMouseCursor(_GLFWwindow* window)
static void showCursor(_GLFWwindow* window)
{
// Un-capture cursor
ReleaseCapture();
@@ -835,7 +783,7 @@ static LRESULT CALLBACK windowProc(HWND hWnd, UINT uMsg,
// The window was deactivated (or iconified, see above)
if (window->cursorMode == GLFW_CURSOR_CAPTURED)
showMouseCursor(window);
showCursor(window);
if (window->mode == GLFW_FULLSCREEN)
{
@@ -858,7 +806,7 @@ static LRESULT CALLBACK windowProc(HWND hWnd, UINT uMsg,
// The window was activated
if (window->cursorMode == GLFW_CURSOR_CAPTURED)
captureMouseCursor(window);
captureCursor(window);
if (window->mode == GLFW_FULLSCREEN)
{
@@ -919,7 +867,7 @@ static LRESULT CALLBACK windowProc(HWND hWnd, UINT uMsg,
if (_glfwLibrary.charCallback)
translateChar(window, (DWORD) wParam, (DWORD) lParam);
return 0;
break;
}
case WM_KEYUP:
@@ -934,7 +882,7 @@ static LRESULT CALLBACK windowProc(HWND hWnd, UINT uMsg,
else
_glfwInputKey(window, translateKey(wParam, lParam), GLFW_RELEASE);
return 0;
break;
}
case WM_LBUTTONDOWN:
@@ -1013,14 +961,14 @@ static LRESULT CALLBACK windowProc(HWND hWnd, UINT uMsg,
case WM_MOUSEMOVE:
{
int newMouseX, newMouseY;
int newCursorX, newCursorY;
// Get signed (!) mouse position
newMouseX = (int)((short)LOWORD(lParam));
newMouseY = (int)((short)HIWORD(lParam));
// Get signed (!) cursor position
newCursorX = (int)((short)LOWORD(lParam));
newCursorY = (int)((short)HIWORD(lParam));
if (newMouseX != window->Win32.oldMouseX ||
newMouseY != window->Win32.oldMouseY)
if (newCursorX != window->Win32.oldCursorX ||
newCursorY != window->Win32.oldCursorY)
{
int x, y;
@@ -1029,28 +977,48 @@ static LRESULT CALLBACK windowProc(HWND hWnd, UINT uMsg,
if (_glfwLibrary.activeWindow != window)
return 0;
x = newMouseX - window->Win32.oldMouseX;
y = newMouseY - window->Win32.oldMouseY;
x = newCursorX - window->Win32.oldCursorX;
y = newCursorY - window->Win32.oldCursorY;
}
else
{
x = newMouseX;
y = newMouseY;
x = newCursorX;
y = newCursorY;
}
window->Win32.oldMouseX = newMouseX;
window->Win32.oldMouseY = newMouseY;
window->Win32.oldCursorX = newCursorX;
window->Win32.oldCursorY = newCursorY;
window->Win32.cursorCentered = GL_FALSE;
_glfwInputCursorMotion(window, x, y);
}
if (!window->Win32.cursorInside)
{
TRACKMOUSEEVENT tme;
ZeroMemory(&tme, sizeof(tme));
tme.cbSize = sizeof(tme);
tme.dwFlags = TME_LEAVE;
tme.hwndTrack = window->Win32.handle;
TrackMouseEvent(&tme);
window->Win32.cursorInside = GL_TRUE;
_glfwInputCursorEnter(window, GL_TRUE);
}
return 0;
}
case WM_MOUSELEAVE:
{
window->Win32.cursorInside = GL_FALSE;
_glfwInputCursorEnter(window, GL_FALSE);
return 0;
}
case WM_MOUSEWHEEL:
{
_glfwInputScroll(window, 0, (((int) wParam) >> 16) / WHEEL_DELTA);
_glfwInputScroll(window, 0.0, (SHORT) HIWORD(wParam) / (double) WHEEL_DELTA);
return 0;
}
@@ -1058,7 +1026,7 @@ static LRESULT CALLBACK windowProc(HWND hWnd, UINT uMsg,
{
// This message is only sent on Windows Vista and later
_glfwInputScroll(window, (((int) wParam) >> 16) / WHEEL_DELTA, 0);
_glfwInputScroll(window, (SHORT) HIWORD(wParam) / (double) WHEEL_DELTA, 0.0);
return 0;
}
@@ -1291,13 +1259,13 @@ static int choosePixelFormat(_GLFWwindow* window, const _GLFWfbconfig* fbconfig)
closest = _glfwChooseFBConfig(fbconfig, fbconfigs, fbcount);
if (!closest)
{
_glfwFree(fbconfigs);
free(fbconfigs);
return 0;
}
pixelFormat = (int) closest->platformID;
_glfwFree(fbconfigs);
free(fbconfigs);
fbconfigs = NULL;
closest = NULL;
@@ -1314,7 +1282,7 @@ static int createWindow(_GLFWwindow* window,
const _GLFWfbconfig* fbconfig)
{
DWORD dwStyle, dwExStyle;
int length, pixelFormat, fullWidth, fullHeight;
int pixelFormat, fullWidth, fullHeight;
RECT wa;
POINT pos;
WCHAR* wideTitle;
@@ -1366,12 +1334,12 @@ static int createWindow(_GLFWwindow* window,
else
SystemParametersInfo(SPI_GETWORKAREA, 0, &wa, 0);
wideTitle = createWideStringFromUTF8(wndconfig->title);
wideTitle = _glfwCreateWideStringFromUTF8(wndconfig->title);
if (!wideTitle)
{
_glfwSetError(GLFW_PLATFORM_ERROR,
"glfwOpenWindow: Failed to convert title to wide string");
return;
return GL_FALSE;
}
window->Win32.handle = CreateWindowEx(window->Win32.dwExStyle,
@@ -1392,7 +1360,7 @@ static int createWindow(_GLFWwindow* window,
return GL_FALSE;
}
_glfwFree(wideTitle);
free(wideTitle);
window->WGL.DC = GetDC(window->Win32.handle);
if (!window->WGL.DC)
@@ -1413,11 +1381,11 @@ static int createWindow(_GLFWwindow* window,
initWGLExtensions(window);
// Initialize mouse position data
// Initialize cursor position data
GetCursorPos(&pos);
ScreenToClient(window->Win32.handle, &pos);
window->Win32.oldMouseX = window->cursorPosX = pos.x;
window->Win32.oldMouseY = window->cursorPosY = pos.y;
window->Win32.oldCursorX = window->cursorPosX = pos.x;
window->Win32.oldCursorY = window->cursorPosY = pos.y;
return GL_TRUE;
}
@@ -1475,6 +1443,7 @@ int _glfwPlatformOpenWindow(_GLFWwindow* window,
GLboolean recreateContext = GL_FALSE;
window->Win32.desiredRefreshRate = wndconfig->refreshRate;
window->resizable = wndconfig->resizable;
if (!_glfwLibrary.Win32.classAtom)
{
@@ -1613,7 +1582,7 @@ void _glfwPlatformCloseWindow(_GLFWwindow* window)
void _glfwPlatformSetWindowTitle(_GLFWwindow* window, const char* title)
{
WCHAR* wideTitle = createWideStringFromUTF8(title);
WCHAR* wideTitle = _glfwCreateWideStringFromUTF8(title);
if (!wideTitle)
{
_glfwSetError(GLFW_PLATFORM_ERROR,
@@ -1623,7 +1592,7 @@ void _glfwPlatformSetWindowTitle(_GLFWwindow* window, const char* title)
SetWindowText(window->Win32.handle, wideTitle);
_glfwFree(wideTitle);
free(wideTitle);
}
@@ -1633,29 +1602,10 @@ void _glfwPlatformSetWindowTitle(_GLFWwindow* window, const char* title)
void _glfwPlatformSetWindowSize(_GLFWwindow* window, int width, int height)
{
//int bpp, refresh;
int newMode = 0;
GLboolean sizeChanged = GL_FALSE;
if (window->mode == GLFW_FULLSCREEN)
{
// Get some info about the current mode
DEVMODE dm;
dm.dmSize = sizeof(DEVMODE);
//if (EnumDisplaySettings(NULL, window->Win32.modeID, &dm))
//{
// We need to keep BPP the same for the OpenGL context to keep working
//bpp = dm.dmBitsPerPel;
// Get closest match for target video mode
//refresh = window->Win32.desiredRefreshRate;
//newMode = _glfwGetClosestVideoModeBPP(&width, &height, &bpp, &refresh);
//}
//else
//newMode = window->Win32.modeID;
if (width > window->width || height > window->height)
{
// The new video mode is larger than the current one, so we resize
@@ -1667,8 +1617,7 @@ void _glfwPlatformSetWindowSize(_GLFWwindow* window, int width, int height)
sizeChanged = GL_TRUE;
}
//if (newMode != window->Win32.modeID)
//_glfwSetVideoModeMODE(newMode);
// TODO: Change video mode
}
else
{
@@ -1692,7 +1641,13 @@ void _glfwPlatformSetWindowSize(_GLFWwindow* window, int width, int height)
void _glfwPlatformSetWindowPos(_GLFWwindow* window, int x, int y)
{
SetWindowPos(window->Win32.handle, HWND_TOP, x, y, 0, 0,
RECT rect;
GetClientRect(window->Win32.handle, &rect);
AdjustWindowRectEx(&rect, window->Win32.dwStyle, FALSE, window->Win32.dwExStyle);
SetWindowPos(window->Win32.handle, HWND_TOP,
x + rect.left, y + rect.top, 0, 0,
SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOZORDER);
}
@@ -1730,7 +1685,7 @@ void _glfwPlatformRefreshWindowParams(void)
_GLFWwindow* window = _glfwLibrary.currentWindow;
// Obtain a detailed description of current pixel format
pixelFormat = _glfw_GetPixelFormat(window->WGL.DC);
pixelFormat = GetPixelFormat(window->WGL.DC);
if (window->WGL.ARB_pixel_format)
{
@@ -1784,8 +1739,8 @@ void _glfwPlatformRefreshWindowParams(void)
}
else
{
_glfw_DescribePixelFormat(window->WGL.DC, pixelFormat,
sizeof(PIXELFORMATDESCRIPTOR), &pfd);
DescribePixelFormat(window->WGL.DC, pixelFormat,
sizeof(PIXELFORMATDESCRIPTOR), &pfd);
// Is current OpenGL context accelerated?
window->accelerated = (pfd.dwFlags & PFD_GENERIC_ACCELERATED) ||
@@ -1835,14 +1790,14 @@ void _glfwPlatformPollEvents(void)
window = _glfwLibrary.activeWindow;
if (window)
{
window->Win32.cursorCentered = GL_TRUE;
window->Win32.oldMouseX = window->width / 2;
window->Win32.oldMouseY = window->height / 2;
window->Win32.cursorCentered = GL_FALSE;
window->Win32.oldCursorX = window->width / 2;
window->Win32.oldCursorY = window->height / 2;
}
else
{
//window->Win32.oldMouseX = window->cursorPosX;
//window->Win32.oldMouseY = window->cursorPosY;
//window->Win32.oldCursorX = window->cursorPosX;
//window->Win32.oldCursorY = window->cursorPosY;
}
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
@@ -1899,9 +1854,9 @@ void _glfwPlatformPollEvents(void)
if (window->cursorMode == GLFW_CURSOR_CAPTURED &&
!window->Win32.cursorCentered)
{
_glfwPlatformSetMouseCursorPos(window,
window->width / 2,
window->height / 2);
_glfwPlatformSetCursorPos(window,
window->width / 2,
window->height / 2);
window->Win32.cursorCentered = GL_TRUE;
}
}
@@ -1921,10 +1876,10 @@ void _glfwPlatformWaitEvents(void)
//========================================================================
// Set physical mouse cursor position
// Set physical cursor position
//========================================================================
void _glfwPlatformSetMouseCursorPos(_GLFWwindow* window, int x, int y)
void _glfwPlatformSetCursorPos(_GLFWwindow* window, int x, int y)
{
POINT pos;
@@ -1946,13 +1901,13 @@ void _glfwPlatformSetCursorMode(_GLFWwindow* window, int mode)
switch (mode)
{
case GLFW_CURSOR_NORMAL:
showMouseCursor(window);
showCursor(window);
break;
case GLFW_CURSOR_HIDDEN:
hideMouseCursor(window);
hideCursor(window);
break;
case GLFW_CURSOR_CAPTURED:
captureMouseCursor(window);
captureCursor(window);
break;
}
}
+2 -3
View File
@@ -291,7 +291,7 @@ GLFWAPI GLFWwindow glfwOpenWindow(int width, int height,
height = 480;
}
window = (_GLFWwindow*) _glfwMalloc(sizeof(_GLFWwindow));
window = (_GLFWwindow*) malloc(sizeof(_GLFWwindow));
if (!window)
{
_glfwSetError(GLFW_OUT_OF_MEMORY,
@@ -492,7 +492,7 @@ GLFWAPI void glfwCloseWindow(GLFWwindow handle)
*prev = window->next;
}
_glfwFree(window);
free(window);
}
@@ -655,7 +655,6 @@ GLFWAPI void glfwRestoreWindow(GLFWwindow handle)
if (!window->iconified)
return;
// Restore iconified window
_glfwPlatformRestoreWindow(window);
if (window->mode == GLFW_FULLSCREEN)
+191
View File
@@ -0,0 +1,191 @@
//========================================================================
// GLFW - An OpenGL library
// Platform: X11/GLX
// API version: 3.0
// WWW: http://www.glfw.org/
//------------------------------------------------------------------------
// Copyright (c) 2010 Camilla Berglund <elmindreda@elmindreda.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#include "internal.h"
#include <stdio.h>
#include <limits.h>
#include <string.h>
#include <stdlib.h>
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
//========================================================================
// Save the contents of the specified property
//========================================================================
GLboolean _glfwReadSelection(XSelectionEvent* request)
{
Atom actualType;
int actualFormat;
unsigned long itemCount, bytesAfter;
char* data;
if (request->property == None)
return GL_FALSE;
XGetWindowProperty(_glfwLibrary.X11.display,
request->requestor,
request->property,
0, LONG_MAX,
False,
request->target,
&actualType,
&actualFormat,
&itemCount,
&bytesAfter,
(unsigned char**) &data);
if (actualType == None)
return GL_FALSE;
free(_glfwLibrary.X11.selection.string);
_glfwLibrary.X11.selection.string = strdup(data);
XFree(data);
return GL_TRUE;
}
//========================================================================
// Set the specified property to the contents of the requested selection
//========================================================================
Atom _glfwWriteSelection(XSelectionRequestEvent* request)
{
int i;
Atom property = request->property;
if (property == None)
property = _glfwLibrary.X11.selection.property;
if (request->target == _glfwLibrary.X11.selection.targets)
{
// The list of supported targets was requested
XChangeProperty(_glfwLibrary.X11.display,
request->requestor,
property,
XA_ATOM,
32,
PropModeReplace,
(unsigned char*) _glfwLibrary.X11.selection.formats,
_GLFW_CLIPBOARD_FORMAT_COUNT);
return property;
}
for (i = 0; i < _GLFW_CLIPBOARD_FORMAT_COUNT; i++)
{
if (request->target == _glfwLibrary.X11.selection.formats[i])
{
// The requested target is one we support
XChangeProperty(_glfwLibrary.X11.display,
request->requestor,
property,
request->target,
8,
PropModeReplace,
(unsigned char*) _glfwLibrary.X11.selection.string,
strlen(_glfwLibrary.X11.selection.string));
return property;
}
}
return None;
}
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
//========================================================================
// Set the clipboard contents
//========================================================================
void _glfwPlatformSetClipboardString(_GLFWwindow* window, const char* string)
{
// Store the new string in preparation for a selection request event
free(_glfwLibrary.X11.selection.string);
_glfwLibrary.X11.selection.string = strdup(string);
// Set the specified window as owner of the selection
XSetSelectionOwner(_glfwLibrary.X11.display,
_glfwLibrary.X11.selection.atom,
window->X11.handle, CurrentTime);
}
//========================================================================
// Return the current clipboard contents
//========================================================================
const char* _glfwPlatformGetClipboardString(_GLFWwindow* window)
{
int i;
_glfwLibrary.X11.selection.status = _GLFW_CONVERSION_INACTIVE;
for (i = 0; i < _GLFW_CLIPBOARD_FORMAT_COUNT; i++)
{
// Request conversion to the selected format
_glfwLibrary.X11.selection.target =
_glfwLibrary.X11.selection.formats[i];
XConvertSelection(_glfwLibrary.X11.display,
_glfwLibrary.X11.selection.atom,
_glfwLibrary.X11.selection.target,
_glfwLibrary.X11.selection.property,
window->X11.handle, CurrentTime);
// Process the resulting SelectionNotify event
XSync(_glfwLibrary.X11.display, False);
while (_glfwLibrary.X11.selection.status == _GLFW_CONVERSION_INACTIVE)
_glfwPlatformWaitEvents();
if (_glfwLibrary.X11.selection.status == _GLFW_CONVERSION_SUCCEEDED)
break;
}
if (_glfwLibrary.X11.selection.status == _GLFW_CONVERSION_FAILED)
{
_glfwSetError(GLFW_FORMAT_UNAVAILABLE,
"X11/GLX: Failed to convert selection to string");
return NULL;
}
return _glfwLibrary.X11.selection.string;
}
+52 -33
View File
@@ -42,7 +42,7 @@
// Finds the video mode closest in size to the specified desired size
//========================================================================
int _glfwGetClosestVideoMode(int screen, int* width, int* height, int* rate)
int _glfwGetClosestVideoMode(int* width, int* height, int* rate)
{
int i, match, bestmatch;
@@ -55,8 +55,7 @@ int _glfwGetClosestVideoMode(int screen, int* width, int* height, int* rate)
XRRScreenConfiguration* sc;
XRRScreenSize* sizelist;
sc = XRRGetScreenInfo(_glfwLibrary.X11.display,
RootWindow(_glfwLibrary.X11.display, screen));
sc = XRRGetScreenInfo(_glfwLibrary.X11.display, _glfwLibrary.X11.root);
sizelist = XRRConfigSizes(sc, &sizecount);
@@ -116,7 +115,8 @@ int _glfwGetClosestVideoMode(int screen, int* width, int* height, int* rate)
int bestmode, modecount;
// Get a list of all available display modes
XF86VidModeGetAllModeLines(_glfwLibrary.X11.display, screen,
XF86VidModeGetAllModeLines(_glfwLibrary.X11.display,
_glfwLibrary.X11.screen,
&modecount, &modelist);
// Find the best matching mode
@@ -150,8 +150,8 @@ int _glfwGetClosestVideoMode(int screen, int* width, int* height, int* rate)
}
// Default: Simply use the screen resolution
*width = DisplayWidth(_glfwLibrary.X11.display, screen);
*height = DisplayHeight(_glfwLibrary.X11.display, screen);
*width = DisplayWidth(_glfwLibrary.X11.display, _glfwLibrary.X11.screen);
*height = DisplayHeight(_glfwLibrary.X11.display, _glfwLibrary.X11.screen);
return 0;
}
@@ -161,7 +161,7 @@ int _glfwGetClosestVideoMode(int screen, int* width, int* height, int* rate)
// Change the current video mode
//========================================================================
void _glfwSetVideoModeMODE(int screen, int mode, int rate)
void _glfwSetVideoModeMODE(int mode, int rate)
{
if (_glfwLibrary.X11.RandR.available)
{
@@ -169,15 +169,17 @@ void _glfwSetVideoModeMODE(int screen, int mode, int rate)
XRRScreenConfiguration* sc;
Window root;
root = RootWindow(_glfwLibrary.X11.display, screen);
root = _glfwLibrary.X11.root;
sc = XRRGetScreenInfo(_glfwLibrary.X11.display, root);
// Remember old size and flag that we have changed the mode
if (!_glfwLibrary.X11.FS.modeChanged)
{
_glfwLibrary.X11.FS.oldSizeID = XRRConfigCurrentConfiguration(sc, &_glfwLibrary.X11.FS.oldRotation);
_glfwLibrary.X11.FS.oldWidth = DisplayWidth(_glfwLibrary.X11.display, screen);
_glfwLibrary.X11.FS.oldHeight = DisplayHeight(_glfwLibrary.X11.display, screen);
_glfwLibrary.X11.FS.oldWidth = DisplayWidth(_glfwLibrary.X11.display,
_glfwLibrary.X11.screen);
_glfwLibrary.X11.FS.oldHeight = DisplayHeight(_glfwLibrary.X11.display,
_glfwLibrary.X11.screen);
_glfwLibrary.X11.FS.modeChanged = GL_TRUE;
}
@@ -214,21 +216,32 @@ void _glfwSetVideoModeMODE(int screen, int mode, int rate)
int modecount;
// Get a list of all available display modes
XF86VidModeGetAllModeLines(_glfwLibrary.X11.display, screen,
XF86VidModeGetAllModeLines(_glfwLibrary.X11.display,
_glfwLibrary.X11.screen,
&modecount, &modelist);
// Unlock mode switch if necessary
if (_glfwLibrary.X11.FS.modeChanged)
XF86VidModeLockModeSwitch(_glfwLibrary.X11.display, screen, 0);
{
XF86VidModeLockModeSwitch(_glfwLibrary.X11.display,
_glfwLibrary.X11.screen,
0);
}
// Change the video mode to the desired mode
XF86VidModeSwitchToMode(_glfwLibrary.X11.display, screen, modelist[mode]);
XF86VidModeSwitchToMode(_glfwLibrary.X11.display,
_glfwLibrary.X11.screen,
modelist[mode]);
// Set viewport to upper left corner (where our window will be)
XF86VidModeSetViewPort(_glfwLibrary.X11.display, screen, 0, 0);
XF86VidModeSetViewPort(_glfwLibrary.X11.display,
_glfwLibrary.X11.screen,
0, 0);
// Lock mode switch
XF86VidModeLockModeSwitch(_glfwLibrary.X11.display, screen, 1);
XF86VidModeLockModeSwitch(_glfwLibrary.X11.display,
_glfwLibrary.X11.screen,
1);
// Remember old mode and flag that we have changed the mode
if (!_glfwLibrary.X11.FS.modeChanged)
@@ -247,15 +260,15 @@ void _glfwSetVideoModeMODE(int screen, int mode, int rate)
// Change the current video mode
//========================================================================
void _glfwSetVideoMode(int screen, int* width, int* height, int* rate)
void _glfwSetVideoMode(int* width, int* height, int* rate)
{
int bestmode;
// Find a best match mode
bestmode = _glfwGetClosestVideoMode(screen, width, height, rate);
bestmode = _glfwGetClosestVideoMode(width, height, rate);
// Change mode
_glfwSetVideoModeMODE(screen, bestmode, *rate);
_glfwSetVideoModeMODE(bestmode, *rate);
}
@@ -263,7 +276,7 @@ void _glfwSetVideoMode(int screen, int* width, int* height, int* rate)
// Restore the previously saved (original) video mode
//========================================================================
void _glfwRestoreVideoMode(int screen)
void _glfwRestoreVideoMode(void)
{
if (_glfwLibrary.X11.FS.modeChanged)
{
@@ -292,11 +305,13 @@ void _glfwRestoreVideoMode(int screen)
{
#if defined(_GLFW_HAS_XF86VIDMODE)
// Unlock mode switch
XF86VidModeLockModeSwitch(_glfwLibrary.X11.display, screen, 0);
XF86VidModeLockModeSwitch(_glfwLibrary.X11.display,
_glfwLibrary.X11.screen,
0);
// Change the video mode back to the old mode
XF86VidModeSwitchToMode(_glfwLibrary.X11.display,
screen,
_glfwLibrary.X11.screen,
&_glfwLibrary.X11.FS.oldMode);
#endif /*_GLFW_HAS_XF86VIDMODE*/
}
@@ -338,7 +353,7 @@ int _glfwCompareResolution(const void* left, const void* right)
int _glfwPlatformGetVideoModes(_GLFWmonitor* monitor, GLFWvidmode* list, int maxcount)
{
int count, k, l, r, g, b, rgba, gl;
int depth, screen;
int depth;
XVisualInfo* vislist;
XVisualInfo dummy;
int viscount, rgbcount, rescount;
@@ -354,7 +369,7 @@ int _glfwPlatformGetVideoModes(_GLFWmonitor* monitor, GLFWvidmode* list, int max
return 0;
}
rgbarray = (int*) _glfwMalloc(sizeof(int) * viscount);
rgbarray = (int*) malloc(sizeof(int) * viscount);
rgbcount = 0;
// Build RGB array
@@ -387,6 +402,8 @@ int _glfwPlatformGetVideoModes(_GLFWmonitor* monitor, GLFWvidmode* list, int max
}
}
XFree(vislist);
rescount = 0;
resarray = NULL;
@@ -399,7 +416,7 @@ int _glfwPlatformGetVideoModes(_GLFWmonitor* monitor, GLFWvidmode* list, int max
unsigned int a;
resource = XRRGetScreenResources(_glfwLibrary.X11.display, _glfwLibrary.X11.root);
resarray = (struct _glfwResolution*) _glfwMalloc(sizeof(struct _glfwResolution) * monitor->X11.output->nmode);
resarray = (struct _glfwResolution*) malloc(sizeof(struct _glfwResolution) * monitor->X11.output->nmode);
for (k = 0; k < monitor->X11.output->nmode; k++)
{
@@ -434,9 +451,11 @@ int _glfwPlatformGetVideoModes(_GLFWmonitor* monitor, GLFWvidmode* list, int max
XF86VidModeModeInfo** modelist;
int modecount, width, height;
XF86VidModeGetAllModeLines(_glfwLibrary.X11.display, screen, &modecount, &modelist);
XF86VidModeGetAllModeLines(_glfwLibrary.X11.display,
_glfwLibrary.X11.screen,
&modecount, &modelist);
resarray = (struct _glfwResolution*) _glfwMalloc(sizeof(struct _glfwResolution) * modecount);
resarray = (struct _glfwResolution*) malloc(sizeof(struct _glfwResolution) * modecount);
for (k = 0; k < modecount; k++)
{
@@ -465,10 +484,12 @@ int _glfwPlatformGetVideoModes(_GLFWmonitor* monitor, GLFWvidmode* list, int max
if (!resarray)
{
rescount = 1;
resarray = (struct _glfwResolution*) _glfwMalloc(sizeof(struct _glfwResolution) * rescount);
resarray = (struct _glfwResolution*) malloc(sizeof(struct _glfwResolution) * rescount);
resarray[0].width = DisplayWidth(_glfwLibrary.X11.display, screen);
resarray[0].height = DisplayHeight(_glfwLibrary.X11.display, screen);
resarray[0].width = DisplayWidth(_glfwLibrary.X11.display,
_glfwLibrary.X11.screen);
resarray[0].height = DisplayHeight(_glfwLibrary.X11.display,
_glfwLibrary.X11.screen);
}
// Build permutations of colors and resolutions
@@ -486,10 +507,8 @@ int _glfwPlatformGetVideoModes(_GLFWmonitor* monitor, GLFWvidmode* list, int max
}
}
XFree(vislist);
_glfwFree(resarray);
_glfwFree(rgbarray);
free(resarray);
free(rgbarray);
return count;
}
+86
View File
@@ -33,6 +33,74 @@
#include <string.h>
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
//========================================================================
// Detect gamma ramp support and save original gamma ramp, if available
//========================================================================
void _glfwInitGammaRamp(void)
{
#ifdef _GLFW_HAS_XRANDR
// RandR gamma support is only available with version 1.2 and above
if (_glfwLibrary.X11.RandR.available &&
(_glfwLibrary.X11.RandR.majorVersion > 1 ||
(_glfwLibrary.X11.RandR.majorVersion == 1 &&
_glfwLibrary.X11.RandR.minorVersion >= 2)))
{
// FIXME: Assumes that all monitors have the same size gamma tables
// This is reasonable as I suspect the that if they did differ, it
// would imply that setting the gamma size to an arbitary size is
// possible as well.
XRRScreenResources* rr = XRRGetScreenResources(_glfwLibrary.X11.display,
_glfwLibrary.X11.root);
_glfwLibrary.originalRampSize = XRRGetCrtcGammaSize(_glfwLibrary.X11.display,
rr->crtcs[0]);
if (!_glfwLibrary.originalRampSize)
{
// This is probably Nvidia RandR with broken gamma support
// Flag it as useless and try Xf86VidMode below, if available
_glfwLibrary.X11.RandR.gammaBroken = GL_TRUE;
}
XRRFreeScreenResources(rr);
}
#endif /*_GLFW_HAS_XRANDR*/
#if defined(_GLFW_HAS_XF86VIDMODE)
if (_glfwLibrary.X11.VidMode.available &&
!_glfwLibrary.originalRampSize)
{
// Get the gamma size using XF86VidMode
XF86VidModeGetGammaRampSize(_glfwLibrary.X11.display,
_glfwLibrary.X11.screen,
&_glfwLibrary.originalRampSize);
}
#endif /*_GLFW_HAS_XF86VIDMODE*/
if (_glfwLibrary.originalRampSize)
{
// Save the original gamma ramp
_glfwPlatformGetGammaRamp(&_glfwLibrary.originalRamp);
_glfwLibrary.currentRamp = _glfwLibrary.originalRamp;
}
}
//========================================================================
// Restore original gamma ramp if necessary
//========================================================================
void _glfwTerminateGammaRamp(void)
{
if (_glfwLibrary.originalRampSize && _glfwLibrary.rampChanged)
_glfwPlatformSetGammaRamp(&_glfwLibrary.originalRamp);
}
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
@@ -43,6 +111,15 @@
void _glfwPlatformGetGammaRamp(GLFWgammaramp* ramp)
{
// For now, don't support anything that is not GLFW_GAMMA_RAMP_SIZE
if (_glfwLibrary.originalRampSize != GLFW_GAMMA_RAMP_SIZE)
{
_glfwSetError(GLFW_PLATFORM_ERROR,
"X11/GLX: Failed to get gamma ramp due to size "
"incompatibility");
return;
}
if (_glfwLibrary.X11.RandR.available &&
!_glfwLibrary.X11.RandR.gammaBroken)
{
@@ -85,6 +162,15 @@ void _glfwPlatformGetGammaRamp(GLFWgammaramp* ramp)
void _glfwPlatformSetGammaRamp(const GLFWgammaramp* ramp)
{
// For now, don't support anything that is not GLFW_GAMMA_RAMP_SIZE
if (_glfwLibrary.originalRampSize != GLFW_GAMMA_RAMP_SIZE)
{
_glfwSetError(GLFW_PLATFORM_ERROR,
"X11/GLX: Failed to set gamma ramp due to size "
"incompatibility");
return;
}
if (_glfwLibrary.X11.RandR.available &&
!_glfwLibrary.X11.RandR.gammaBroken)
{
+197 -125
View File
@@ -30,37 +30,9 @@
#include "internal.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//========================================================================
// Dynamically load libraries
//========================================================================
static void initLibraries(void)
{
#ifdef _GLFW_DLOPEN_LIBGL
int i;
char* libGL_names[ ] =
{
"libGL.so",
"libGL.so.1",
"/usr/lib/libGL.so",
"/usr/lib/libGL.so.1",
NULL
};
_glfwLibrary.X11.libGL = NULL;
for (i = 0; libGL_names[i] != NULL; i++)
{
_glfwLibrary.X11.libGL = dlopen(libGL_names[i], RTLD_LAZY | RTLD_GLOBAL);
if (_glfwLibrary.X11.libGL)
break;
}
#endif
}
#include <limits.h>
//========================================================================
@@ -79,7 +51,11 @@ static int keyCodeToGLFWKeyCode(int keyCode)
// Note: This way we always force "NumLock = ON", which is intentional
// since the returned key code should correspond to a physical
// location.
#if defined(_GLFW_HAS_XKB)
keySym = XkbKeycodeToKeysym(_glfwLibrary.X11.display, keyCode, 1, 0);
#else
keySym = XKeycodeToKeysym(_glfwLibrary.X11.display, keyCode, 1);
#endif
switch (keySym)
{
case XK_KP_0: return GLFW_KEY_KP_0;
@@ -102,7 +78,12 @@ static int keyCodeToGLFWKeyCode(int keyCode)
// Now try pimary keysym for function keys (non-printable keys). These
// should not be layout dependent (i.e. US layout and international
// layouts should give the same result).
#if defined(_GLFW_HAS_XKB)
keySym = XkbKeycodeToKeysym(_glfwLibrary.X11.display, keyCode, 0, 0);
#else
keySym = XKeycodeToKeysym(_glfwLibrary.X11.display, keyCode, 0);
#endif
switch (keySym)
{
case XK_Escape: return GLFW_KEY_ESCAPE;
@@ -252,10 +233,8 @@ static void updateKeyCodeLUT(void)
int keyCode;
// Clear the LUT
for (keyCode = 0; keyCode < 256; ++keyCode)
{
for (keyCode = 0; keyCode < 256; keyCode++)
_glfwLibrary.X11.keyCodeLUT[keyCode] = -1;
}
#if defined(_GLFW_HAS_XKB)
// If the Xkb extension is available, use it to determine physical key
@@ -263,7 +242,7 @@ static void updateKeyCodeLUT(void)
if (_glfwLibrary.X11.Xkb.available)
{
int i, keyCodeGLFW;
char name[XkbKeyNameLength+1];
char name[XkbKeyNameLength + 1];
XkbDescPtr descr;
// Get keyboard description
@@ -275,10 +254,9 @@ static void updateKeyCodeLUT(void)
for (keyCode = descr->min_key_code; keyCode <= descr->max_key_code; ++keyCode)
{
// Get the key name
for (i = 0; i < XkbKeyNameLength; ++i)
{
for (i = 0; i < XkbKeyNameLength; i++)
name[i] = descr->names->keys[keyCode].name[i];
}
name[XkbKeyNameLength] = 0;
// Map the key name to a GLFW key code. Note: We only map printable
@@ -337,9 +315,7 @@ static void updateKeyCodeLUT(void)
// Update the key code LUT
if ((keyCode >= 0) && (keyCode < 256))
{
_glfwLibrary.X11.keyCodeLUT[keyCode] = keyCodeGLFW;
}
}
// Free the keyboard description
@@ -349,7 +325,7 @@ static void updateKeyCodeLUT(void)
// Translate the un-translated key codes using traditional X11 KeySym
// lookups
for (keyCode = 0; keyCode < 256; ++keyCode)
for (keyCode = 0; keyCode < 256; keyCode++)
{
if (_glfwLibrary.X11.keyCodeLUT[keyCode] < 0)
{
@@ -360,6 +336,152 @@ static void updateKeyCodeLUT(void)
}
//========================================================================
// Retrieve a single window property of the specified type
// Inspired by fghGetWindowProperty from freeglut
//========================================================================
static unsigned long getWindowProperty(Window window,
Atom property,
Atom type,
unsigned char** value)
{
Atom actualType;
int actualFormat;
unsigned long itemCount, bytesAfter;
XGetWindowProperty(_glfwLibrary.X11.display,
window,
property,
0,
LONG_MAX,
False,
type,
&actualType,
&actualFormat,
&itemCount,
&bytesAfter,
value);
if (actualType != type)
return 0;
return itemCount;
}
//========================================================================
// Check whether the specified atom is supported
//========================================================================
static Atom getSupportedAtom(Atom* supportedAtoms,
unsigned long atomCount,
const char* atomName)
{
Atom atom = XInternAtom(_glfwLibrary.X11.display, atomName, True);
if (atom != None)
{
unsigned long i;
for (i = 0; i < atomCount; i++)
{
if (supportedAtoms[i] == atom)
return atom;
}
}
return None;
}
//========================================================================
// Check whether the running window manager is EWMH-compliant
//========================================================================
static void initEWMH(void)
{
Window* windowFromRoot = NULL;
Window* windowFromChild = NULL;
// First we need a couple of atoms, which should already be there
Atom supportingWmCheck =
XInternAtom(_glfwLibrary.X11.display, "_NET_SUPPORTING_WM_CHECK", True);
Atom wmSupported =
XInternAtom(_glfwLibrary.X11.display, "_NET_SUPPORTED", True);
if (supportingWmCheck == None || wmSupported == None)
return;
// Then we look for the _NET_SUPPORTING_WM_CHECK property of the root window
if (getWindowProperty(_glfwLibrary.X11.root,
supportingWmCheck,
XA_WINDOW,
(unsigned char**) &windowFromRoot) != 1)
{
XFree(windowFromRoot);
return;
}
// It should be the ID of a child window (of the root)
// Then we look for the same property on the child window
if (getWindowProperty(*windowFromRoot,
supportingWmCheck,
XA_WINDOW,
(unsigned char**) &windowFromChild) != 1)
{
XFree(windowFromRoot);
XFree(windowFromChild);
return;
}
// It should be the ID of that same child window
if (*windowFromRoot != *windowFromChild)
{
XFree(windowFromRoot);
XFree(windowFromChild);
return;
}
XFree(windowFromRoot);
XFree(windowFromChild);
// We are now fairly sure that an EWMH-compliant window manager is running
Atom* supportedAtoms;
unsigned long atomCount;
// Now we need to check the _NET_SUPPORTED property of the root window
// It should be a list of supported WM protocol and state atoms
atomCount = getWindowProperty(_glfwLibrary.X11.root,
wmSupported,
XA_ATOM,
(unsigned char**) &supportedAtoms);
// See which of the atoms we support that are supported by the WM
_glfwLibrary.X11.wmState =
getSupportedAtom(supportedAtoms, atomCount, "_NET_WM_STATE");
_glfwLibrary.X11.wmStateFullscreen =
getSupportedAtom(supportedAtoms, atomCount, "_NET_WM_STATE_FULLSCREEN");
_glfwLibrary.X11.wmName =
getSupportedAtom(supportedAtoms, atomCount, "_NET_WM_NAME");
_glfwLibrary.X11.wmIconName =
getSupportedAtom(supportedAtoms, atomCount, "_NET_WM_ICON_NAME");
_glfwLibrary.X11.wmPing =
getSupportedAtom(supportedAtoms, atomCount, "_NET_WM_PING");
_glfwLibrary.X11.wmActiveWindow =
getSupportedAtom(supportedAtoms, atomCount, "_NET_ACTIVE_WINDOW");
XFree(supportedAtoms);
_glfwLibrary.X11.hasEWMH = GL_TRUE;
}
//========================================================================
// Initialize X11 display and look for supported X11 extensions
//========================================================================
@@ -411,22 +533,6 @@ static GLboolean initDisplay(void)
_glfwLibrary.X11.RandR.available = GL_FALSE;
#endif /*_GLFW_HAS_XRANDR*/
// Check if GLX is supported on this display
if (!glXQueryExtension(_glfwLibrary.X11.display, NULL, NULL))
{
_glfwSetError(GLFW_OPENGL_UNAVAILABLE, "X11/GLX: GLX supported not found");
return GL_FALSE;
}
if (!glXQueryVersion(_glfwLibrary.X11.display,
&_glfwLibrary.X11.glxMajor,
&_glfwLibrary.X11.glxMinor))
{
_glfwSetError(GLFW_OPENGL_UNAVAILABLE,
"X11/GLX: Failed to query GLX version");
return GL_FALSE;
}
// Check if Xkb is supported on this display
#if defined(_GLFW_HAS_XKB)
_glfwLibrary.X11.Xkb.majorVersion = 1;
@@ -447,65 +553,30 @@ static GLboolean initDisplay(void)
// the keyboard mapping.
updateKeyCodeLUT();
// Find or create selection property atom
_glfwLibrary.X11.selection.property =
XInternAtom(_glfwLibrary.X11.display, "GLFW_SELECTION", False);
// Find or create clipboard atom
_glfwLibrary.X11.selection.atom =
XInternAtom(_glfwLibrary.X11.display, "CLIPBOARD", False);
// Find or create selection target atoms
_glfwLibrary.X11.selection.formats[_GLFW_CLIPBOARD_FORMAT_UTF8] =
XInternAtom(_glfwLibrary.X11.display, "UTF8_STRING", False);
_glfwLibrary.X11.selection.formats[_GLFW_CLIPBOARD_FORMAT_COMPOUND] =
XInternAtom(_glfwLibrary.X11.display, "COMPOUND_STRING", False);
_glfwLibrary.X11.selection.formats[_GLFW_CLIPBOARD_FORMAT_STRING] =
XA_STRING;
_glfwLibrary.X11.selection.targets = XInternAtom(_glfwLibrary.X11.display,
"TARGETS",
False);
return GL_TRUE;
}
//========================================================================
// Detect gamma ramp support and save original gamma ramp, if available
//========================================================================
static void initGammaRamp(void)
{
#ifdef _GLFW_HAS_XRANDR
// RandR gamma support is only available with version 1.2 and above
if (_glfwLibrary.X11.RandR.available &&
(_glfwLibrary.X11.RandR.majorVersion > 1 ||
_glfwLibrary.X11.RandR.majorVersion == 1 &&
_glfwLibrary.X11.RandR.minorVersion >= 2))
{
// FIXME: Assumes that all monitors have the same size gamma tables
// This is reasonable as I suspect the that if they did differ, it
// would imply that setting the gamma size to an arbitary size is
// possible as well.
XRRScreenResources* rr = XRRGetScreenResources(_glfwLibrary.X11.display,
_glfwLibrary.X11.root);
_glfwLibrary.originalRampSize = XRRGetCrtcGammaSize(_glfwLibrary.X11.display,
rr->crtcs[0]);
if (!_glfwLibrary.originalRampSize)
{
// This is probably Nvidia RandR with broken gamma support
// Flag it as useless and try Xf86VidMode below, if available
_glfwLibrary.X11.RandR.gammaBroken = GL_TRUE;
fprintf(stderr,
"Ignoring broken nVidia implementation of RandR 1.2+ gamma\n");
}
XRRFreeScreenResources(rr);
}
#endif /*_GLFW_HAS_XRANDR*/
#if defined(_GLFW_HAS_XF86VIDMODE)
if (_glfwLibrary.X11.VidMode.available &&
!_glfwLibrary.originalRampSize)
{
// Get the gamma size using XF86VidMode
XF86VidModeGetGammaRampSize(_glfwLibrary.X11.display,
_glfwLibrary.X11.screen,
&_glfwLibrary.originalRampSize);
}
#endif /*_GLFW_HAS_XF86VIDMODE*/
if (!_glfwLibrary.originalRampSize)
fprintf(stderr, "No supported gamma ramp API found\n");
// Save the original gamma ramp
_glfwPlatformGetGammaRamp(&_glfwLibrary.originalRamp);
_glfwLibrary.currentRamp = _glfwLibrary.originalRamp;
}
//========================================================================
// Create a blank cursor (for locked mouse mode)
//========================================================================
@@ -545,9 +616,6 @@ static Cursor createNULLCursor(void)
static void terminateDisplay(void)
{
if (_glfwLibrary.originalRampSize)
_glfwPlatformSetGammaRamp(&_glfwLibrary.originalRamp);
if (_glfwLibrary.X11.display)
{
XCloseDisplay(_glfwLibrary.X11.display);
@@ -569,13 +637,15 @@ int _glfwPlatformInit(void)
if (!initDisplay())
return GL_FALSE;
initGammaRamp();
_glfwInitGammaRamp();
if (!_glfwInitOpenGL())
return GL_FALSE;
initEWMH();
_glfwLibrary.X11.cursor = createNULLCursor();
// Try to load libGL.so if necessary
initLibraries();
_glfwInitJoysticks();
_glfwInitMonitors();
@@ -599,20 +669,19 @@ int _glfwPlatformTerminate(void)
_glfwLibrary.X11.cursor = (Cursor) 0;
}
_glfwTerminateGammaRamp();
terminateDisplay();
_glfwTerminateMonitors();
_glfwTerminateJoysticks();
// Unload libGL.so if necessary
#ifdef _GLFW_DLOPEN_LIBGL
if (_glfwLibrary.X11.libGL != NULL)
{
dlclose(_glfwLibrary.X11.libGL);
_glfwLibrary.X11.libGL = NULL;
}
#endif
_glfwTerminateOpenGL();
// Free clipboard memory
if (_glfwLibrary.X11.selection.string)
free(_glfwLibrary.X11.selection.string);
return GL_TRUE;
}
@@ -655,6 +724,9 @@ const char* _glfwPlatformGetVersionString(void)
" Linux-joystick-API"
#else
" no-joystick-support"
#endif
#if defined(_GLFW_BUILD_DLL)
" shared"
#endif
;
+4 -4
View File
@@ -43,13 +43,13 @@ _GLFWmonitor** _glfwCreateMonitor(_GLFWmonitor** current,
XRROutputInfo* outputInfo,
XRRCrtcInfo* crtcInfo)
{
*current = _glfwMalloc(sizeof(_GLFWmonitor));
*current = malloc(sizeof(_GLFWmonitor));
memset(*current, 0, sizeof(_GLFWmonitor));
(*current)->physicalWidth = outputInfo->mm_width;
(*current)->physicalHeight = outputInfo->mm_height;
(*current)->name = _glfwMalloc(strlen(outputInfo->name) + 1);
(*current)->name = malloc(strlen(outputInfo->name) + 1);
memcpy((*current)->name, outputInfo->name, strlen(outputInfo->name) + 1);
(*current)->name[strlen(outputInfo->name)] = '\0';
@@ -71,8 +71,8 @@ _GLFWmonitor* _glfwDestroyMonitor(_GLFWmonitor* monitor)
XRRFreeOutputInfo(monitor->X11.output);
#endif /*_GLFW_HAS_XRANDR*/
_glfwFree(monitor->name);
_glfwFree(monitor);
free(monitor->name);
free(monitor);
return result;
}
+649 -8
View File
@@ -30,15 +30,656 @@
#include "internal.h"
#include <string.h>
#include <stdlib.h>
// This is the only glXGetProcAddress variant not declared by glxext.h
void (*glXGetProcAddressEXT(const GLubyte* procName))();
//========================================================================
// Returns the specified attribute of the specified GLXFBConfig
// NOTE: Do not call this unless we have found GLX 1.3+ or GLX_SGIX_fbconfig
//========================================================================
static int getFBConfigAttrib(_GLFWwindow* window, GLXFBConfig fbconfig, int attrib)
{
int value;
if (_glfwLibrary.GLX.SGIX_fbconfig)
{
_glfwLibrary.GLX.GetFBConfigAttribSGIX(_glfwLibrary.X11.display,
fbconfig, attrib, &value);
}
else
glXGetFBConfigAttrib(_glfwLibrary.X11.display, fbconfig, attrib, &value);
return value;
}
//========================================================================
// Return a list of available and usable framebuffer configs
//========================================================================
static _GLFWfbconfig* getFBConfigs(_GLFWwindow* window, unsigned int* found)
{
GLXFBConfig* fbconfigs;
_GLFWfbconfig* result;
int i, count = 0;
const char* vendor;
GLboolean trustWindowBit = GL_TRUE;
*found = 0;
if (_glfwLibrary.GLX.majorVersion == 1 && _glfwLibrary.GLX.minorVersion < 3)
{
if (!_glfwLibrary.GLX.SGIX_fbconfig)
{
_glfwSetError(GLFW_OPENGL_UNAVAILABLE,
"X11/GLX: GLXFBConfig support not found");
return NULL;
}
}
vendor = glXGetClientString(_glfwLibrary.X11.display, GLX_VENDOR);
if (strcmp(vendor, "Chromium") == 0)
{
// This is a (hopefully temporary) workaround for Chromium (VirtualBox
// GL) not setting the window bit on any GLXFBConfigs
trustWindowBit = GL_FALSE;
}
if (_glfwLibrary.GLX.SGIX_fbconfig)
{
fbconfigs = _glfwLibrary.GLX.ChooseFBConfigSGIX(_glfwLibrary.X11.display,
_glfwLibrary.X11.screen,
NULL,
&count);
if (!count)
{
_glfwSetError(GLFW_OPENGL_UNAVAILABLE,
"X11/GLX: No GLXFBConfigs returned");
return NULL;
}
}
else
{
fbconfigs = glXGetFBConfigs(_glfwLibrary.X11.display,
_glfwLibrary.X11.screen,
&count);
if (!count)
{
_glfwSetError(GLFW_OPENGL_UNAVAILABLE,
"X11/GLX: No GLXFBConfigs returned");
return NULL;
}
}
result = (_GLFWfbconfig*) malloc(sizeof(_GLFWfbconfig) * count);
if (!result)
{
_glfwSetError(GLFW_OUT_OF_MEMORY,
"X11/GLX: Failed to allocate _GLFWfbconfig array");
return NULL;
}
for (i = 0; i < count; i++)
{
_GLFWfbconfig* f = result + *found;
if (!getFBConfigAttrib(window, fbconfigs[i], GLX_DOUBLEBUFFER) ||
!getFBConfigAttrib(window, fbconfigs[i], GLX_VISUAL_ID))
{
// Only consider double-buffered GLXFBConfigs with associated visuals
continue;
}
if (!(getFBConfigAttrib(window,
fbconfigs[i],
GLX_RENDER_TYPE) & GLX_RGBA_BIT))
{
// Only consider RGBA GLXFBConfigs
continue;
}
if (!(getFBConfigAttrib(window, fbconfigs[i], GLX_DRAWABLE_TYPE) & GLX_WINDOW_BIT))
{
if (trustWindowBit)
{
// Only consider window GLXFBConfigs
continue;
}
}
f->redBits = getFBConfigAttrib(window, fbconfigs[i], GLX_RED_SIZE);
f->greenBits = getFBConfigAttrib(window, fbconfigs[i], GLX_GREEN_SIZE);
f->blueBits = getFBConfigAttrib(window, fbconfigs[i], GLX_BLUE_SIZE);
f->alphaBits = getFBConfigAttrib(window, fbconfigs[i], GLX_ALPHA_SIZE);
f->depthBits = getFBConfigAttrib(window, fbconfigs[i], GLX_DEPTH_SIZE);
f->stencilBits = getFBConfigAttrib(window, fbconfigs[i], GLX_STENCIL_SIZE);
f->accumRedBits = getFBConfigAttrib(window, fbconfigs[i], GLX_ACCUM_RED_SIZE);
f->accumGreenBits = getFBConfigAttrib(window, fbconfigs[i], GLX_ACCUM_GREEN_SIZE);
f->accumBlueBits = getFBConfigAttrib(window, fbconfigs[i], GLX_ACCUM_BLUE_SIZE);
f->accumAlphaBits = getFBConfigAttrib(window, fbconfigs[i], GLX_ACCUM_ALPHA_SIZE);
f->auxBuffers = getFBConfigAttrib(window, fbconfigs[i], GLX_AUX_BUFFERS);
f->stereo = getFBConfigAttrib(window, fbconfigs[i], GLX_STEREO);
if (_glfwLibrary.GLX.ARB_multisample)
f->samples = getFBConfigAttrib(window, fbconfigs[i], GLX_SAMPLES);
else
f->samples = 0;
f->platformID = (GLFWintptr) getFBConfigAttrib(window, fbconfigs[i], GLX_FBCONFIG_ID);
(*found)++;
}
XFree(fbconfigs);
return result;
}
//========================================================================
// Error handler for BadMatch errors when requesting context with
// unavailable OpenGL versions using the GLX_ARB_create_context extension
//========================================================================
static int errorHandler(Display *display, XErrorEvent* event)
{
return 0;
}
//========================================================================
// Read back framebuffer parameters from the context
//========================================================================
static void refreshContextParams(_GLFWwindow* window, GLXFBConfigID fbconfigID)
{
int dummy;
GLXFBConfig* fbconfig;
int attribs[] = { GLX_FBCONFIG_ID, fbconfigID, None };
if (_glfwLibrary.GLX.SGIX_fbconfig)
{
fbconfig = _glfwLibrary.GLX.ChooseFBConfigSGIX(_glfwLibrary.X11.display,
_glfwLibrary.X11.screen,
attribs,
&dummy);
}
else
{
fbconfig = glXChooseFBConfig(_glfwLibrary.X11.display,
_glfwLibrary.X11.screen,
attribs,
&dummy);
}
if (fbconfig == NULL)
{
// This should never ever happen
// TODO: Flag this as an error and propagate up
_glfwSetError(GLFW_PLATFORM_ERROR, "X11/GLX: Cannot find known "
"GLXFBConfig by ID. This cannot "
"happen. Have a nice day.\n");
abort();
}
// There is no clear definition of an "accelerated" context on X11/GLX, and
// true sounds better than false, so we hardcode true here
window->accelerated = GL_TRUE;
window->redBits = getFBConfigAttrib(window, *fbconfig, GLX_RED_SIZE);
window->greenBits = getFBConfigAttrib(window, *fbconfig, GLX_GREEN_SIZE);
window->blueBits = getFBConfigAttrib(window, *fbconfig, GLX_BLUE_SIZE);
window->alphaBits = getFBConfigAttrib(window, *fbconfig, GLX_ALPHA_SIZE);
window->depthBits = getFBConfigAttrib(window, *fbconfig, GLX_DEPTH_SIZE);
window->stencilBits = getFBConfigAttrib(window, *fbconfig, GLX_STENCIL_SIZE);
window->accumRedBits = getFBConfigAttrib(window, *fbconfig, GLX_ACCUM_RED_SIZE);
window->accumGreenBits = getFBConfigAttrib(window, *fbconfig, GLX_ACCUM_GREEN_SIZE);
window->accumBlueBits = getFBConfigAttrib(window, *fbconfig, GLX_ACCUM_BLUE_SIZE);
window->accumAlphaBits = getFBConfigAttrib(window, *fbconfig, GLX_ACCUM_ALPHA_SIZE);
window->auxBuffers = getFBConfigAttrib(window, *fbconfig, GLX_AUX_BUFFERS);
window->stereo = getFBConfigAttrib(window, *fbconfig, GLX_STEREO) ? GL_TRUE : GL_FALSE;
// Get FSAA buffer sample count
if (_glfwLibrary.GLX.ARB_multisample)
window->samples = getFBConfigAttrib(window, *fbconfig, GLX_SAMPLES);
else
window->samples = 0;
XFree(fbconfig);
}
//========================================================================
// Create the actual OpenGL context
//========================================================================
#define setGLXattrib(attribs, index, attribName, attribValue) \
attribs[index++] = attribName; \
attribs[index++] = attribValue;
static int createContext(_GLFWwindow* window,
const _GLFWwndconfig* wndconfig,
GLXFBConfigID fbconfigID)
{
int attribs[40];
int dummy, index;
GLXFBConfig* fbconfig;
GLXContext share = NULL;
if (wndconfig->share)
share = wndconfig->share->GLX.context;
// Retrieve the previously selected GLXFBConfig
{
index = 0;
setGLXattrib(attribs, index, GLX_FBCONFIG_ID, (int) fbconfigID);
setGLXattrib(attribs, index, None, None);
if (_glfwLibrary.GLX.SGIX_fbconfig)
{
fbconfig = _glfwLibrary.GLX.ChooseFBConfigSGIX(_glfwLibrary.X11.display,
_glfwLibrary.X11.screen,
attribs,
&dummy);
}
else
{
fbconfig = glXChooseFBConfig(_glfwLibrary.X11.display,
_glfwLibrary.X11.screen,
attribs,
&dummy);
}
if (fbconfig == NULL)
{
_glfwSetError(GLFW_PLATFORM_ERROR,
"X11/GLX: Failed to retrieve the selected GLXFBConfig");
return GL_FALSE;
}
}
// Retrieve the corresponding visual
if (_glfwLibrary.GLX.SGIX_fbconfig)
{
window->GLX.visual = _glfwLibrary.GLX.GetVisualFromFBConfigSGIX(_glfwLibrary.X11.display,
*fbconfig);
}
else
{
window->GLX.visual = glXGetVisualFromFBConfig(_glfwLibrary.X11.display,
*fbconfig);
}
if (window->GLX.visual == NULL)
{
XFree(fbconfig);
_glfwSetError(GLFW_PLATFORM_ERROR,
"X11/GLX: Failed to retrieve visual for GLXFBConfig");
return GL_FALSE;
}
if (_glfwLibrary.GLX.ARB_create_context)
{
index = 0;
if (wndconfig->glMajor != 1 || wndconfig->glMinor != 0)
{
// Request an explicitly versioned context
setGLXattrib(attribs, index, GLX_CONTEXT_MAJOR_VERSION_ARB, wndconfig->glMajor);
setGLXattrib(attribs, index, GLX_CONTEXT_MINOR_VERSION_ARB, wndconfig->glMinor);
}
if (wndconfig->glForward || wndconfig->glDebug || wndconfig->glRobustness)
{
int flags = 0;
if (wndconfig->glForward)
flags |= GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
if (wndconfig->glDebug)
flags |= GLX_CONTEXT_DEBUG_BIT_ARB;
if (wndconfig->glRobustness)
flags |= GLX_CONTEXT_ROBUST_ACCESS_BIT_ARB;
setGLXattrib(attribs, index, GLX_CONTEXT_FLAGS_ARB, flags);
}
if (wndconfig->glProfile)
{
int flags = 0;
if (!_glfwLibrary.GLX.ARB_create_context_profile)
{
_glfwSetError(GLFW_VERSION_UNAVAILABLE,
"X11/GLX: An OpenGL profile requested but "
"GLX_ARB_create_context_profile is unavailable");
return GL_FALSE;
}
if (wndconfig->glProfile == GLFW_OPENGL_ES2_PROFILE &&
!_glfwLibrary.GLX.EXT_create_context_es2_profile)
{
_glfwSetError(GLFW_VERSION_UNAVAILABLE,
"X11/GLX: OpenGL ES 2.x profile requested but "
"GLX_EXT_create_context_es2_profile is unavailable");
return GL_FALSE;
}
if (wndconfig->glProfile == GLFW_OPENGL_CORE_PROFILE)
flags = GLX_CONTEXT_CORE_PROFILE_BIT_ARB;
else if (wndconfig->glProfile == GLFW_OPENGL_COMPAT_PROFILE)
flags = GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
else if (wndconfig->glProfile == GLFW_OPENGL_ES2_PROFILE)
flags = GLX_CONTEXT_ES2_PROFILE_BIT_EXT;
setGLXattrib(attribs, index, GLX_CONTEXT_PROFILE_MASK_ARB, flags);
}
if (wndconfig->glRobustness)
{
int strategy;
if (!_glfwLibrary.GLX.ARB_create_context_robustness)
{
_glfwSetError(GLFW_VERSION_UNAVAILABLE,
"X11/GLX: An OpenGL robustness strategy was "
"requested but GLX_ARB_create_context_robustness "
"is unavailable");
return GL_FALSE;
}
if (wndconfig->glRobustness == GLFW_OPENGL_NO_RESET_NOTIFICATION)
strategy = GLX_NO_RESET_NOTIFICATION_ARB;
else if (wndconfig->glRobustness == GLFW_OPENGL_LOSE_CONTEXT_ON_RESET)
strategy = GLX_LOSE_CONTEXT_ON_RESET_ARB;
setGLXattrib(attribs,
index,
GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB,
strategy);
}
setGLXattrib(attribs, index, None, None);
// This is the only place we set an Xlib error handler, and we only do
// it because glXCreateContextAttribsARB generates a BadMatch error if
// the requested OpenGL version is unavailable (instead of a civilized
// response like returning NULL)
XSetErrorHandler(errorHandler);
window->GLX.context =
_glfwLibrary.GLX.CreateContextAttribsARB(_glfwLibrary.X11.display,
*fbconfig,
share,
True,
attribs);
// We are done, so unset the error handler again (see above)
XSetErrorHandler(NULL);
}
else
{
if (_glfwLibrary.GLX.SGIX_fbconfig)
{
window->GLX.context =
_glfwLibrary.GLX.CreateContextWithConfigSGIX(_glfwLibrary.X11.display,
*fbconfig,
GLX_RGBA_TYPE,
share,
True);
}
else
{
window->GLX.context = glXCreateNewContext(_glfwLibrary.X11.display,
*fbconfig,
GLX_RGBA_TYPE,
share,
True);
}
}
XFree(fbconfig);
if (window->GLX.context == NULL)
{
// TODO: Handle all the various error codes here
_glfwSetError(GLFW_PLATFORM_ERROR,
"X11/GLX: Failed to create OpenGL context");
return GL_FALSE;
}
refreshContextParams(window, fbconfigID);
return GL_TRUE;
}
#undef setGLXattrib
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
//========================================================================
// Initialize GLX
//========================================================================
int _glfwInitOpenGL(void)
{
#ifdef _GLFW_DLOPEN_LIBGL
int i;
char* libGL_names[ ] =
{
"libGL.so",
"libGL.so.1",
"/usr/lib/libGL.so",
"/usr/lib/libGL.so.1",
NULL
};
for (i = 0; libGL_names[i] != NULL; i++)
{
_glfwLibrary.GLX.libGL = dlopen(libGL_names[i], RTLD_LAZY | RTLD_GLOBAL);
if (_glfwLibrary.GLX.libGL)
break;
}
if (!_glfwLibrary.GLX.libGL)
{
_glfwSetError(GLFW_PLATFORM_ERROR, "X11/GLX: Failed to find libGL");
return GL_FALSE;
}
#endif
// Check if GLX is supported on this display
if (!glXQueryExtension(_glfwLibrary.X11.display, NULL, NULL))
{
_glfwSetError(GLFW_OPENGL_UNAVAILABLE, "X11/GLX: GLX supported not found");
return GL_FALSE;
}
if (!glXQueryVersion(_glfwLibrary.X11.display,
&_glfwLibrary.GLX.majorVersion,
&_glfwLibrary.GLX.minorVersion))
{
_glfwSetError(GLFW_OPENGL_UNAVAILABLE,
"X11/GLX: Failed to query GLX version");
return GL_FALSE;
}
if (_glfwPlatformExtensionSupported("GLX_EXT_swap_control"))
{
_glfwLibrary.GLX.SwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC)
_glfwPlatformGetProcAddress("glXSwapIntervalEXT");
if (_glfwLibrary.GLX.SwapIntervalEXT)
_glfwLibrary.GLX.EXT_swap_control = GL_TRUE;
}
if (_glfwPlatformExtensionSupported("GLX_SGI_swap_control"))
{
_glfwLibrary.GLX.SwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC)
_glfwPlatformGetProcAddress("glXSwapIntervalSGI");
if (_glfwLibrary.GLX.SwapIntervalSGI)
_glfwLibrary.GLX.SGI_swap_control = GL_TRUE;
}
if (_glfwPlatformExtensionSupported("GLX_SGIX_fbconfig"))
{
_glfwLibrary.GLX.GetFBConfigAttribSGIX = (PFNGLXGETFBCONFIGATTRIBSGIXPROC)
_glfwPlatformGetProcAddress("glXGetFBConfigAttribSGIX");
_glfwLibrary.GLX.ChooseFBConfigSGIX = (PFNGLXCHOOSEFBCONFIGSGIXPROC)
_glfwPlatformGetProcAddress("glXChooseFBConfigSGIX");
_glfwLibrary.GLX.CreateContextWithConfigSGIX = (PFNGLXCREATECONTEXTWITHCONFIGSGIXPROC)
_glfwPlatformGetProcAddress("glXCreateContextWithConfigSGIX");
_glfwLibrary.GLX.GetVisualFromFBConfigSGIX = (PFNGLXGETVISUALFROMFBCONFIGSGIXPROC)
_glfwPlatformGetProcAddress("glXGetVisualFromFBConfigSGIX");
if (_glfwLibrary.GLX.GetFBConfigAttribSGIX &&
_glfwLibrary.GLX.ChooseFBConfigSGIX &&
_glfwLibrary.GLX.CreateContextWithConfigSGIX &&
_glfwLibrary.GLX.GetVisualFromFBConfigSGIX)
{
_glfwLibrary.GLX.SGIX_fbconfig = GL_TRUE;
}
}
if (_glfwPlatformExtensionSupported("GLX_ARB_multisample"))
_glfwLibrary.GLX.ARB_multisample = GL_TRUE;
if (_glfwPlatformExtensionSupported("GLX_ARB_create_context"))
{
_glfwLibrary.GLX.CreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC)
_glfwPlatformGetProcAddress("glXCreateContextAttribsARB");
if (_glfwLibrary.GLX.CreateContextAttribsARB)
_glfwLibrary.GLX.ARB_create_context = GL_TRUE;
}
if (_glfwPlatformExtensionSupported("GLX_ARB_create_context_robustness"))
_glfwLibrary.GLX.ARB_create_context_robustness = GL_TRUE;
if (_glfwPlatformExtensionSupported("GLX_ARB_create_context_profile"))
_glfwLibrary.GLX.ARB_create_context_profile = GL_TRUE;
if (_glfwPlatformExtensionSupported("GLX_EXT_create_context_es2_profile"))
_glfwLibrary.GLX.EXT_create_context_es2_profile = GL_TRUE;
return GL_TRUE;
}
//========================================================================
// Terminate GLX
//========================================================================
void _glfwTerminateOpenGL(void)
{
// Unload libGL.so if necessary
#ifdef _GLFW_DLOPEN_LIBGL
if (_glfwLibrary.GLX.libGL != NULL)
{
dlclose(_glfwLibrary.GLX.libGL);
_glfwLibrary.GLX.libGL = NULL;
}
#endif
}
//========================================================================
// Prepare for creation of the OpenGL context
//========================================================================
int _glfwCreateContext(_GLFWwindow* window,
const _GLFWwndconfig* wndconfig,
const _GLFWfbconfig* fbconfig)
{
_GLFWfbconfig closest;
// Choose the best available fbconfig
{
unsigned int fbcount;
_GLFWfbconfig* fbconfigs;
const _GLFWfbconfig* result;
fbconfigs = getFBConfigs(window, &fbcount);
if (!fbconfigs)
{
_glfwSetError(GLFW_PLATFORM_ERROR,
"X11/GLX: No usable GLXFBConfigs found");
return GL_FALSE;
}
result = _glfwChooseFBConfig(fbconfig, fbconfigs, fbcount);
if (!result)
{
_glfwSetError(GLFW_PLATFORM_ERROR,
"X11/GLX: No GLXFBConfig matched the criteria");
free(fbconfigs);
return GL_FALSE;
}
closest = *result;
free(fbconfigs);
}
return createContext(window, wndconfig, closest.platformID);
}
//========================================================================
// Destroy the OpenGL context
//========================================================================
void _glfwDestroyContext(_GLFWwindow* window)
{
if (window->GLX.visual)
{
XFree(window->GLX.visual);
window->GLX.visual = NULL;
}
if (window->GLX.context)
{
// Release and destroy the context
glXMakeCurrent(_glfwLibrary.X11.display, None, NULL);
glXDestroyContext(_glfwLibrary.X11.display, window->GLX.context);
window->GLX.context = NULL;
}
}
//========================================================================
// Return the X visual associated with the specified context
//========================================================================
XVisualInfo* _glfwGetContextVisual(_GLFWwindow* window)
{
return window->GLX.visual;
}
//========================================================================
// Make the OpenGL context associated with the specified window current
//========================================================================
@@ -75,14 +716,14 @@ void _glfwPlatformSwapInterval(int interval)
{
_GLFWwindow* window = _glfwLibrary.currentWindow;
if (window->GLX.EXT_swap_control)
if (_glfwLibrary.GLX.EXT_swap_control)
{
window->GLX.SwapIntervalEXT(_glfwLibrary.X11.display,
window->X11.handle,
interval);
_glfwLibrary.GLX.SwapIntervalEXT(_glfwLibrary.X11.display,
window->X11.handle,
interval);
}
else if (window->GLX.SGI_swap_control)
window->GLX.SwapIntervalSGI(interval);
else if (_glfwLibrary.GLX.SGI_swap_control)
_glfwLibrary.GLX.SwapIntervalSGI(interval);
}
@@ -111,9 +752,9 @@ int _glfwPlatformExtensionSupported(const char* extension)
// Get the function pointer to an OpenGL function
//========================================================================
void* _glfwPlatformGetProcAddress(const char* procname)
GLFWglproc _glfwPlatformGetProcAddress(const char* procname)
{
return (void*) _glfw_glXGetProcAddress((const GLubyte*) procname);
return _glfw_glXGetProcAddress((const GLubyte*) procname);
}
+90 -36
View File
@@ -75,17 +75,31 @@
#elif defined(_GLFW_HAS_GLXGETPROCADDRESSEXT)
#define _glfw_glXGetProcAddress(x) glXGetProcAddressEXT(x)
#elif defined(_GLFW_HAS_DLOPEN)
#define _glfw_glXGetProcAddress(x) dlsym(_glfwLibrary.X11.libGL, x)
#define _glfw_glXGetProcAddress(x) dlsym(_glfwLibrary.GLX.libGL, x)
#define _GLFW_DLOPEN_LIBGL
#else
#error "No OpenGL entry point retrieval mechanism was enabled"
#endif
#define _GLFW_PLATFORM_WINDOW_STATE _GLFWwindowX11 X11
#define _GLFW_PLATFORM_LIBRARY_STATE _GLFWlibraryX11 X11
#define _GLFW_PLATFORM_CONTEXT_STATE _GLFWcontextGLX GLX
#define _GLFW_PLATFORM_MONITOR_STATE _GLFWmonitorX11 X11
#define _GLFW_PLATFORM_LIBRARY_WINDOW_STATE _GLFWlibraryX11 X11
#define _GLFW_PLATFORM_LIBRARY_OPENGL_STATE _GLFWlibraryGLX GLX
// Clipboard format atom indices
#define _GLFW_CLIPBOARD_FORMAT_UTF8 0
#define _GLFW_CLIPBOARD_FORMAT_COMPOUND 1
#define _GLFW_CLIPBOARD_FORMAT_STRING 2
#define _GLFW_CLIPBOARD_FORMAT_COUNT 3
// Clipboard conversion status tokens
#define _GLFW_CONVERSION_INACTIVE 0
#define _GLFW_CONVERSION_SUCCEEDED 1
#define _GLFW_CONVERSION_FAILED 2
//========================================================================
// GLFW platform specific types
@@ -102,27 +116,9 @@ typedef intptr_t GLFWintptr;
//------------------------------------------------------------------------
typedef struct _GLFWcontextGLX
{
GLXFBConfigID fbconfigID; // ID of selected GLXFBConfig
GLXContext context; // OpenGL rendering context
XVisualInfo* visual; // Visual for selected GLXFBConfig
// GLX extensions
PFNGLXSWAPINTERVALSGIPROC SwapIntervalSGI;
PFNGLXSWAPINTERVALEXTPROC SwapIntervalEXT;
PFNGLXGETFBCONFIGATTRIBSGIXPROC GetFBConfigAttribSGIX;
PFNGLXCHOOSEFBCONFIGSGIXPROC ChooseFBConfigSGIX;
PFNGLXCREATECONTEXTWITHCONFIGSGIXPROC CreateContextWithConfigSGIX;
PFNGLXGETVISUALFROMFBCONFIGSGIXPROC GetVisualFromFBConfigSGIX;
PFNGLXCREATECONTEXTATTRIBSARBPROC CreateContextAttribsARB;
GLboolean SGIX_fbconfig;
GLboolean SGI_swap_control;
GLboolean EXT_swap_control;
GLboolean ARB_multisample;
GLboolean ARB_create_context;
GLboolean ARB_create_context_profile;
GLboolean ARB_create_context_robustness;
GLboolean EXT_create_context_es2_profile;
} _GLFWcontextGLX;
@@ -134,16 +130,8 @@ typedef struct _GLFWwindowX11
// Platform specific window resources
Colormap colormap; // Window colormap
Window handle; // Window handle
Atom wmDeleteWindow; // WM_DELETE_WINDOW atom
Atom wmName; // _NET_WM_NAME atom
Atom wmIconName; // _NET_WM_ICON_NAME atom
Atom wmPing; // _NET_WM_PING atom
Atom wmState; // _NET_WM_STATE atom
Atom wmStateFullscreen; // _NET_WM_STATE_FULLSCREEN atom
Atom wmActiveWindow; // _NET_ACTIVE_WINDOW atom
// Various platform specific internal variables
GLboolean hasEWMH; // True if window manager supports EWMH
GLboolean overrideRedirect; // True if window is OverrideRedirect
GLboolean keyboardGrabbed; // True if keyboard is currently grabbed
GLboolean cursorGrabbed; // True if cursor is currently grabbed
@@ -155,7 +143,7 @@ typedef struct _GLFWwindowX11
//------------------------------------------------------------------------
// Platform-specific library global data
// Platform-specific library global data for X11
//------------------------------------------------------------------------
typedef struct _GLFWlibraryX11
{
@@ -164,8 +152,16 @@ typedef struct _GLFWlibraryX11
Window root;
Cursor cursor; // Invisible cursor for hidden cursor
// Server-side GLX version
int glxMajor, glxMinor;
Atom wmDeleteWindow; // WM_DELETE_WINDOW atom
Atom wmName; // _NET_WM_NAME atom
Atom wmIconName; // _NET_WM_ICON_NAME atom
Atom wmPing; // _NET_WM_PING atom
Atom wmState; // _NET_WM_STATE atom
Atom wmStateFullscreen; // _NET_WM_STATE_FULLSCREEN atom
Atom wmActiveWindow; // _NET_ACTIVE_WINDOW atom
// True if window manager supports EWMH
GLboolean hasEWMH;
struct {
GLboolean available;
@@ -224,10 +220,49 @@ typedef struct _GLFWlibraryX11
uint64_t base;
} timer;
// Selection data
struct {
Atom atom;
Atom formats[_GLFW_CLIPBOARD_FORMAT_COUNT];
char* string;
Atom target;
Atom targets;
Atom property;
int status;
} selection;
} _GLFWlibraryX11;
//------------------------------------------------------------------------
// Platform-specific library global data for GLX
//------------------------------------------------------------------------
typedef struct _GLFWlibraryGLX
{
// Server-side GLX version
int majorVersion, minorVersion;
// GLX extensions
PFNGLXSWAPINTERVALSGIPROC SwapIntervalSGI;
PFNGLXSWAPINTERVALEXTPROC SwapIntervalEXT;
PFNGLXGETFBCONFIGATTRIBSGIXPROC GetFBConfigAttribSGIX;
PFNGLXCHOOSEFBCONFIGSGIXPROC ChooseFBConfigSGIX;
PFNGLXCREATECONTEXTWITHCONFIGSGIXPROC CreateContextWithConfigSGIX;
PFNGLXGETVISUALFROMFBCONFIGSGIXPROC GetVisualFromFBConfigSGIX;
PFNGLXCREATECONTEXTATTRIBSARBPROC CreateContextAttribsARB;
GLboolean SGIX_fbconfig;
GLboolean SGI_swap_control;
GLboolean EXT_swap_control;
GLboolean ARB_multisample;
GLboolean ARB_create_context;
GLboolean ARB_create_context_profile;
GLboolean ARB_create_context_robustness;
GLboolean EXT_create_context_es2_profile;
#if defined(_GLFW_DLOPEN_LIBGL)
void* libGL; // dlopen handle for libGL.so
#endif
} _GLFWlibraryX11;
} _GLFWlibraryGLX;
//------------------------------------------------------------------------
@@ -264,11 +299,24 @@ typedef struct _GLFWmonitorX11
// Time
void _glfwInitTimer(void);
// Gamma
void _glfwInitGammaRamp(void);
void _glfwTerminateGammaRamp(void);
// OpenGL support
int _glfwInitOpenGL(void);
void _glfwTerminateOpenGL(void);
int _glfwCreateContext(_GLFWwindow* window,
const _GLFWwndconfig* wndconfig,
const _GLFWfbconfig* fbconfig);
void _glfwDestroyContext(_GLFWwindow* window);
XVisualInfo* _glfwGetContextVisual(_GLFWwindow* window);
// Fullscreen support
int _glfwGetClosestVideoMode(int screen, int* width, int* height, int* rate);
void _glfwSetVideoModeMODE(int screen, int mode, int rate);
void _glfwSetVideoMode(int screen, int* width, int* height, int* rate);
void _glfwRestoreVideoMode(int screen);
int _glfwGetClosestVideoMode(int* width, int* height, int* rate);
void _glfwSetVideoModeMODE(int mode, int rate);
void _glfwSetVideoMode(int* width, int* height, int* rate);
void _glfwRestoreVideoMode(void);
// Joystick input
void _glfwInitJoysticks(void);
@@ -281,5 +329,11 @@ _GLFWmonitor* _glfwDestroyMonitor(_GLFWmonitor* monitor);
// Unicode support
long _glfwKeySym2Unicode(KeySym keysym);
// Clipboard handling
GLboolean _glfwReadSelection(XSelectionEvent* request);
Atom _glfwWriteSelection(XSelectionRequestEvent* request);
// Event processing
void _glfwProcessPendingEvents(void);
#endif // _platform_h_
+3 -2
View File
@@ -30,6 +30,7 @@
#include "internal.h"
#include <sys/time.h>
#include <time.h>
@@ -39,7 +40,7 @@
static uint64_t getRawTime(void)
{
#if defined(_POSIX_TIMERS) && defined(_POSIX_MONOTONIC_CLOCK)
#if defined(CLOCK_MONOTONIC)
if (_glfwLibrary.X11.timer.monotonic)
{
struct timespec ts;
@@ -64,7 +65,7 @@ static uint64_t getRawTime(void)
void _glfwInitTimer(void)
{
#if defined(_POSIX_TIMERS) && defined(_POSIX_MONOTONIC_CLOCK)
#if defined(CLOCK_MONOTONIC)
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
+165 -736
View File
File diff suppressed because it is too large Load Diff