aboutsummaryrefslogtreecommitdiffstats
path: root/src/libfakekey.c
blob: edf3006ae77d5d543d59c0e1a7ce919cc061aadf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
/* -*- mode:C; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * libFakeKey
 *
 * A simple library for converting utf8 chars into 'fake' keypresses.
 *
 * Uses ideas from Fontconfig, libvirtkeys.c, keysym2ucs.c and dasher. 
 *
 * Authored By Matthew Allum  <amllum@openedhand.com>
 *
 * Copyright (C) 2004 OpenedHand
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */


#include <fakekey/fakekey.h>

#if HAVE_CONFIG_H
#include "config.h"
#endif

#if (WANT_DEBUG)
#define DBG(x, a...) \
 fprintf (stderr,  __FILE__ ":%d,%s() " x "\n", __LINE__, __func__, ##a)
#else
#define DBG(x, a...) do {} while (0)
#endif

#define MARK() DBG("mark")

#define N_MODIFIER_INDEXES (Mod5MapIndex + 1)

typedef unsigned int FkChar32;

struct FakeKey
{
  Display *xdpy;
  int      min_keycode, max_keycode;
  int      n_keysyms_per_keycode;
  KeySym  *keysyms;
  int      held_keycode;
  int      held_state_flags;
  KeyCode  modifier_table[N_MODIFIER_INDEXES];
  int      shift_mod_index, alt_mod_index, meta_mod_index;
};


/* utf8_to_ucs4() Borrowed from fontconfig 
 *
 * Converts the next Unicode char from src into dst and returns the 
 * number of bytes containing the char. src nust be at least len bytes 
 * long.
 */
static int 
utf8_to_ucs4 (const unsigned char *src_orig,
	      FkChar32	          *dst,
	      int	           len)
{
    const unsigned char *src = src_orig;
    unsigned char 	 s;
    int		         extra;
    FkChar32	         result;

    if (len == 0)
	return 0;
    
    s = *src++;
    len--;
    
    if (!(s & 0x80))
    {
	result = s;
	extra = 0;
    } 
    else if (!(s & 0x40))
    {
	return -1;
    }
    else if (!(s & 0x20))
    {
	result = s & 0x1f;
	extra = 1;
    }
    else if (!(s & 0x10))
    {
	result = s & 0xf;
	extra = 2;
    }
    else if (!(s & 0x08))
    {
	result = s & 0x07;
	extra = 3;
    }
    else if (!(s & 0x04))
    {
	result = s & 0x03;
	extra = 4;
    }
    else if ( ! (s & 0x02))
    {
	result = s & 0x01;
	extra = 5;
    }
    else
    {
	return -1;
    }
    if (extra > len)
	return -1;
    
    while (extra--)
    {
	result <<= 6;
	s = *src++;
	
	if ((s & 0xc0) != 0x80)
	    return -1;
	
	result |= s & 0x3f;
    }
    *dst = result;
    return src - src_orig;
}

FakeKey*
fakekey_init(Display *xdpy)
{
  FakeKey         *fk = NULL;
  int              event, error, major, minor;
  XModifierKeymap *modifiers;
  int              mod_index;
  int              mod_key;
  KeyCode         *kp;
  
  if (xdpy == NULL) return NULL;
  
  if (!XTestQueryExtension(xdpy, &event, &error, &major, &minor))
    {
      return NULL;
    }

  fk = malloc(sizeof(FakeKey));
  memset(fk,0,sizeof(FakeKey));

  fk->xdpy = xdpy;

  /* Find keycode limits */

  XDisplayKeycodes(fk->xdpy, &fk->min_keycode, &fk->max_keycode);

  /* Get the mapping  */

  /* TODO: Below needs to be kept in sync with anything else  	 
   *       that may change the keyboard mapping. 
   *
   *   case MappingNotify:
   *    XRefreshKeyboardMapping(&ev.xmapping);
   *
   */

  fk->keysyms = XGetKeyboardMapping(fk->xdpy, 
				    fk->min_keycode, 
				    fk->max_keycode - fk->min_keycode + 1, 
				    &fk->n_keysyms_per_keycode);


  modifiers = XGetModifierMapping(fk->xdpy);

  kp = modifiers->modifiermap;    

  for (mod_index = 0; mod_index < 8; mod_index++)
    {
      fk->modifier_table[mod_index] = 0;
      
      for (mod_key = 0; mod_key < modifiers->max_keypermod; mod_key++)
	{
	  int keycode = kp[mod_index * modifiers->max_keypermod + mod_key]; 
	  
	  if (keycode != 0)
	    {
	      fk->modifier_table[mod_index] = keycode;
	      break;
	    }
	}
    }
  
  for (mod_index = Mod1MapIndex; mod_index <= Mod5MapIndex; mod_index++)
    {
      if (fk->modifier_table[mod_index])
	{
	  KeySym ks = XKeycodeToKeysym(fk->xdpy, 
				       fk->modifier_table[mod_index], 0);
	  
	  /* 
	   *  Note: ControlMapIndex is already defined by xlib
	   *        ShiftMapIndex
	   */
	  
	  switch (ks)
	    {
	    case XK_Meta_R:
	    case XK_Meta_L:
	      fk->meta_mod_index = mod_index;
	      break;
	      
	    case XK_Alt_R:
	    case XK_Alt_L:
	      fk->alt_mod_index = mod_index;
	      break;
	      
	    case XK_Shift_R:
	    case XK_Shift_L:
	      fk->shift_mod_index = mod_index;
	      break;
	    }
	}
    }
  
  if (modifiers)
    XFreeModifiermap(modifiers);

  return fk;
}

int
fakekey_reload_keysyms(FakeKey *fk)
{
  if (fk->keysyms) 
    XFree(fk->keysyms);

  fk->keysyms = XGetKeyboardMapping(fk->xdpy, 
				    fk->min_keycode, 
				    fk->max_keycode - fk->min_keycode + 1, 
				    &fk->n_keysyms_per_keycode);
  return 1;
}

int 
fakekey_send_keyevent(FakeKey *fk, 
		      KeyCode  keycode,
		      Bool     is_press,
		      int      flags)
{
  if (flags)
    {
      if (flags & FAKEKEYMOD_SHIFT)
	XTestFakeKeyEvent(fk->xdpy, fk->modifier_table[ShiftMapIndex], 
			  is_press, CurrentTime);

      if (flags & FAKEKEYMOD_CONTROL)
	XTestFakeKeyEvent(fk->xdpy, fk->modifier_table[ControlMapIndex], 
			  is_press, CurrentTime);

      if (flags & FAKEKEYMOD_ALT)
	XTestFakeKeyEvent(fk->xdpy, fk->modifier_table[fk->alt_mod_index], 
			  is_press, CurrentTime);

      XSync(fk->xdpy, False);
    }

  XTestFakeKeyEvent(fk->xdpy, keycode, is_press, CurrentTime);

  XSync(fk->xdpy, False);

  return 1;
}

int
fakekey_press_keysym(FakeKey *fk, 
		     KeySym   keysym,
		     int      flags)
{
  static int modifiedkey;
  KeyCode    code = 0;

  if ((code = XKeysymToKeycode(fk->xdpy, keysym)) != 0)
    {
      DBG("got keycode, no remap\n");

      /* we already have a keycode for this keysym */
      /* Does it need a shift key though ? */
      if (XKeycodeToKeysym(fk->xdpy, code, 0) != keysym)
	{
	  DBG("does not equal code for index o, needs shift?\n");
	  /* TODO: Assumes 1st modifier is shifted  */
	  if (XKeycodeToKeysym(fk->xdpy, code, 1) == keysym)
	    flags |= FAKEKEYMOD_SHIFT; 	/* can get at it via shift */
	  else
	    code = 0; /* urg, some other modifier do it the heavy way */
	}
      else
        {
          /* the keysym is unshifted; clear the shift flag if it is set */
          flags &= ~FAKEKEYMOD_SHIFT;
	}
    }

  if (!code)
    {
      int index;

      DBG("remapping kbd to get code\n");

      /* Change one of the last 10 keysyms to our converted utf8,
       * remapping the x keyboard on the fly. 
       *
       * This make assumption the last 10 arn't already used.
       * TODO: probably safer to check for this. 
       */

      modifiedkey = (modifiedkey+1) % 10;

      /* Point at the end of keysyms, modifier 0 */

      index = (fk->max_keycode - fk->min_keycode - modifiedkey - 1) * fk->n_keysyms_per_keycode;

      fk->keysyms[index] = keysym;
      
      XChangeKeyboardMapping(fk->xdpy, 
			     fk->min_keycode, 
			     fk->n_keysyms_per_keycode, 
			     fk->keysyms, 
			     (fk->max_keycode-fk->min_keycode));

      XSync(fk->xdpy, False);
	
      /* From dasher src;
       * There's no way whatsoever that this could ever possibly
       * be guaranteed to work (ever), but it does.
       *    
       */

      code = fk->max_keycode - modifiedkey - 1;

      /* The below is lightly safer;
       *
       *  code = XKeysymToKeycode(fk->xdpy, keysym);
       *
       * but this appears to break in that the new mapping is not immediatly 
       * put to work. It would seem a MappingNotify event is needed so
       * Xlib can do some changes internally ? ( xlib is doing something 
       * related to above ? )
       * 
       * Probably better to try and grab the mapping notify *here* ?
       */

      if (XKeycodeToKeysym(fk->xdpy, code, 0) != keysym)
        {
          DBG("does not equal code for index 0, needs shift?\n");
          /* TODO: Assumes 1st modifier is shifted  */
          if (XKeycodeToKeysym(fk->xdpy, code, 1) == keysym)
            flags |= FAKEKEYMOD_SHIFT; 	/* can get at it via shift */
          else
            DBG("attempted to add keycode to keymap but seem to have failed");
        }
    }

  if (code != 0) 
    {
      fakekey_send_keyevent(fk, code, True, flags);

      fk->held_state_flags = flags;
      fk->held_keycode     = code;

      return 1;
    }

  fk->held_state_flags = 0;
  fk->held_keycode     = 0;

  return 0; 			/* failed */
}

int
fakekey_press(FakeKey             *fk, 
	      const unsigned char *utf8_char_in,
	      int                  len_bytes,
	      int                  flags)
{
  FkChar32   ucs4_out;

  if (fk->held_keycode) 	/* key is already held down */
    return 0;

  /* TODO: check for Return key here and other chars */

  if (len_bytes < 0)
    {
      /*
      unsigned char *p = utf8_char_in;
      while (*p != '\0') { len_bytes++; p++; } 
      */
      len_bytes = strlen(utf8_char_in); 	/* OK ? */
    }

  if (utf8_to_ucs4 (utf8_char_in, &ucs4_out, len_bytes) < 1)
    {
      DBG("failed with %i. len is %i\n", 
	     utf8_to_ucs4 (utf8_char_in, &ucs4_out, len_bytes), len_bytes);
      return 0;
    }

    /* first check for Latin-1 characters (1:1 mapping) 
    if ((keysym >= 0x0020 && keysym <= 0x007e) ||
        (keysym >= 0x00a0 && keysym <= 0x00ff))
        return keysym;
    */

  if (ucs4_out > 0x00ff)	       /* < 0xff assume Latin-1 1:1 mapping */
    ucs4_out = ucs4_out | 0x01000000;  /* This gives us the magic X keysym */

  return fakekey_press_keysym(fk, (KeySym)ucs4_out, flags);
}

void
fakekey_repeat(FakeKey *fk)
{
  if (!fk->held_keycode)
    return;

  fakekey_send_keyevent(fk, fk->held_keycode, True, fk->held_state_flags);
}

void
fakekey_release(FakeKey *fk)
{
  if (!fk->held_keycode)
    return;

  fakekey_send_keyevent(fk, fk->held_keycode, False, fk->held_state_flags);

  fk->held_state_flags = 0;
  fk->held_keycode     = 0;
}