Skip to content

Commit

Permalink
Support Unicode Characters for .typeString()
Browse files Browse the repository at this point in the history
- rudimentary UTF-8 parsing
- tested with Chinese characters
- doesn't work with emojis yet
- tested on mac but not other platforms
  • Loading branch information
zz85 committed Mar 16, 2017
1 parent 6f8d2b6 commit 7236ff3
Showing 1 changed file with 35 additions and 4 deletions.
39 changes: 35 additions & 4 deletions src/keypress.c
Original file line number Diff line number Diff line change
Expand Up @@ -191,15 +191,13 @@ void tapKey(char c, MMKeyFlags flags)
}

#if defined(IS_MACOSX)
void toggleUniKey(char c, const bool down)
void toggleUnicodeKey(UniChar ch, const bool down)
{
/* This function relies on the convenient
* CGEventKeyboardSetUnicodeString(), which allows us to not have to
* convert characters to a keycode, but does not support adding modifier
* flags. It is therefore only used in typeString() and typeStringDelayed()
* -- if you need modifier keys, use the above functions instead. */
UniChar ch = (UniChar)c; /* Convert to unsigned char */

CGEventRef keyEvent = CGEventCreateKeyboardEvent(NULL, 0, down);
if (keyEvent == NULL) {
fputs("Could not create keyboard event.\n", stderr);
Expand All @@ -211,6 +209,12 @@ void toggleUniKey(char c, const bool down)
CGEventPost(kCGSessionEventTap, keyEvent);
CFRelease(keyEvent);
}

void toggleUniKey(char c, const bool down)
{
UniChar ch = (UniChar)c; /* Convert to unsigned char */
toggleUnicodeKey(ch, down);
}
#else
#define toggleUniKey(c, down) toggleKey(c, down, MOD_NONE)
#endif
Expand All @@ -223,8 +227,35 @@ static void tapUniKey(char c)

void typeString(const char *str)
{
uint c, c1, c2, c3, n;

while (*str != '\0') {
tapUniKey(*str++);
c = *str++;

// warning, the following utf8 decoder
// doesn't perform validation
if (c <= 0x7F) {
// 0xxxxxxx one byte
n = c;
} else if ((c & 0xE0) == 0xC0) {
// 110xxxxx two bytes
c1 = (*str++) & 0x3F;
n = ((c & 0x1F) << 6) | c1;
} else if ((c & 0xF0) == 0xE0) {
// 1110xxxx three bytes
c1 = (*str++) & 0x3F;
c2 = (*str++) & 0x3F;
n = ((c & 0x0F) << 12) | (c1 << 6) | c2;
} else if ((c & 0xF8) == 0xF0) {
// 11110xxx four bytes
c1 = (*str++) & 0x3F;
c2 = (*str++) & 0x3F;
c3 = (*str++) & 0x3F;
n = ((c & 0x07) << 18) | (c1 << 12) | (c2 << 6) | c3;
}

toggleUnicodeKey(n, true);
toggleUnicodeKey(n, false);
}
}

Expand Down

0 comments on commit 7236ff3

Please sign in to comment.