+// The following code is a combination of the code listed here:
+// http://lists.apple.com/archives/cocoa-dev/2008/Apr/msg01582.html
+// (which can't be used because KLGetCurrentKeyboardLayout etc aren't 64-bit)
+// and the code here:
+// http://inquisitivecocoa.com/category/objective-c/
+@interface NSEvent (OsGuiUtilsAdditions)
+- (NSString*) charactersIgnoringModifiersIncludingShift;
+@end
+
+@implementation NSEvent (OsGuiUtilsAdditions)
+- (NSString*) charactersIgnoringModifiersIncludingShift {
+ // First try -charactersIgnoringModifiers and look for keys which UCKeyTranslate translates
+ // differently than AppKit.
+ NSString* c = [self charactersIgnoringModifiers];
+ if ([c length] == 1) {
+ unichar codepoint = [c characterAtIndex:0];
+ if ((codepoint >= 0xF700 && codepoint <= 0xF8FF) || codepoint == 0x7F) {
+ return c;
+ }
+ }
+ // This is not a "special" key, so ask UCKeyTranslate to give us the character with no
+ // modifiers attached. Actually, that's not quite accurate; we attach the Command modifier
+ // which hints the OS to use Latin characters where possible, which is generally what we want.
+ NSString* result = @"";
+ TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
+ CFDataRef uchr = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
+ CFRelease(currentKeyboard);
+ if (uchr == NULL) {
+ // this can happen for some non-U.S. input methods (eg. Romaji or Hiragana)
+ return c;
+ }
+ const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout*)CFDataGetBytePtr(uchr);
+ if (keyboardLayout) {
+ UInt32 deadKeyState = 0;
+ UniCharCount maxStringLength = 255;
+ UniCharCount actualStringLength = 0;
+ UniChar unicodeString[maxStringLength];
+
+ OSStatus status = UCKeyTranslate(keyboardLayout,
+ [self keyCode],
+ kUCKeyActionDown,
+ cmdKey >> 8, // force the Command key to "on"
+ LMGetKbdType(),
+ kUCKeyTranslateNoDeadKeysMask,
+ &deadKeyState,
+ maxStringLength,
+ &actualStringLength,
+ unicodeString);
+
+ if(status == noErr)
+ result = [NSString stringWithCharacters:unicodeString length:(NSInteger)actualStringLength];
+ }
+ return result;
+}
+@end
+