Skip to content

Instantly share code, notes, and snippets.

@tonyarnold
Created June 10, 2009 01:01
Show Gist options
  • Save tonyarnold/126944 to your computer and use it in GitHub Desktop.
Save tonyarnold/126944 to your computer and use it in GitHub Desktop.
//----------------------------------------------------------
// SRCharacterForKeyCodeAndCocoaFlags()
//----------------------------------------------------------
NSString *SRCharacterForKeyCodeAndCocoaFlags(NSInteger keyCode, NSUInteger cocoaFlags) {
// Fall back to string based on key code:
#define FailWithNaiveString SRStringForKeyCode(keyCode)
UCKeyboardLayout *uchrData = nil;
UInt32 deadKeyState;
// OSStatus err = noErr;
CFLocaleRef locale = CFLocaleCopyCurrent();
[(id)locale autorelease]; // Autorelease here so that it gets released no matter what
CFMutableStringRef resultString;
TISInputSourceRef inputSource = TISCopyCurrentKeyboardLayoutInputSource();
if (inputSource) {
CFDataRef uchrDataRef = TISGetInputSourceProperty(inputSource, kTISPropertyUnicodeKeyLayoutData);
if(uchrDataRef) {
uchrData = (UCKeyboardLayout*)CFDataGetBytePtr(uchrDataRef);
}
CFRelease(inputSource);
}
EventModifiers modifiers = 0;
if (cocoaFlags & NSAlternateKeyMask) modifiers |= optionKey;
if (cocoaFlags & NSShiftKeyMask) modifiers |= shiftKey;
UniCharCount maxStringLength = 4, actualStringLength;
UniChar unicodeString[4];
// err =
UCKeyTranslate( uchrData, (UInt16)keyCode, kUCKeyActionDisplay, modifiers, LMGetKbdType(), kUCKeyTranslateNoDeadKeysBit, &deadKeyState, maxStringLength, &actualStringLength, unicodeString );
CFStringRef temp = CFStringCreateWithCharacters(kCFAllocatorDefault, unicodeString, 1);
resultString = CFStringCreateMutableCopy(kCFAllocatorDefault, 0,temp);
if (temp) CFRelease(temp);
CFStringCapitalize(resultString, locale);
return (NSString *)resultString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment