aboutsummaryrefslogtreecommitdiff
path: root/fbxkb.c
blob: 3890fbbb24f0a8c219495643b5c41da030413716 (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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554




#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <locale.h>
#include <string.h>
#include <signal.h>

#include <X11/Xlib.h>
#include <gtk/gtk.h>
#include <gdk/gdk.h>

#include <X11/XKBlib.h>

#include "config.h"
#include "eggtrayicon.h"
#include "version.h"

static gchar version[] = VERSION;


//#define DEBUG
#include "dbg.h"

/******************************************************************
 * TYPEDEFS                                                        *
 ******************************************************************/
typedef struct _kbd_info {
    gchar *sym;
    gchar *name;
    GdkPixbuf *flag;
} kbd_info;

#define IMGPREFIX PREFIX "/share/fbxkb/images/"
/******************************************************************
 * GLOBAL VARIABLES                                               *
 ******************************************************************/

/* X11 common stuff */
static Atom a_XKB_RULES_NAMES;
static Display *dpy;
static int xkb_event_type;

/* internal state machine */
static int cur_group;
static int ngroups;
static GHashTable *sym2pix;
static kbd_info group2info[XkbNumKbdGroups];
static GdkPixbuf *zzflag;
static int active;
/* gtk gui */
static GtkWidget *flag_menu;
static GtkWidget *app_menu;
static GtkWidget *docklet;
static GtkWidget *image;
static GtkWidget *about_dialog = NULL;
/******************************************************************
 * DECLARATION                                                    *
 ******************************************************************/

static int init();
static void read_kbd_description();
static void update_flag(int no);
static GdkFilterReturn filter( XEvent *xev, GdkEvent *event, gpointer data);
static void Xerror_handler(Display * d, XErrorEvent * ev);
static GdkPixbuf *sym2flag(char *sym);
static void flag_menu_create();
static void flag_menu_destroy();
static void flag_menu_activated(GtkWidget *widget, gpointer data);
static void app_menu_create();
static void app_menu_about(GtkWidget *widget, gpointer data);
static void app_menu_exit(GtkWidget *widget, gpointer data);

static int docklet_create();

static int create_all();

/******************************************************************
 * CODE                                                           *
 ******************************************************************/

/******************************************************************
 * gtk gui                                                        *
 ******************************************************************/
static void
flag_menu_create()
{
    int i;
    GdkPixbuf *flag;
    GtkWidget *mi, *img;
    //static GString *s = NULL;;
    
    ENTER;
    flag_menu =  gtk_menu_new();
    for (i = 0; i < ngroups; i++) {
        mi = gtk_image_menu_item_new_with_label(
            group2info[i].name ? group2info[i].name : group2info[i].sym);
        g_signal_connect(G_OBJECT(mi), "activate", (GCallback)flag_menu_activated, GINT_TO_POINTER(i));
        gtk_menu_shell_append (GTK_MENU_SHELL (flag_menu), mi);
        gtk_widget_show (mi);
        flag = sym2flag(group2info[i].sym);
        img = gtk_image_new_from_pixbuf(flag);
        gtk_widget_show(img);
        gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(mi), img);
    }
    RET();
}

static void
flag_menu_destroy()
{
    if (flag_menu) {
        gtk_widget_destroy(flag_menu);
        flag_menu = NULL;
    }
}

static void
flag_menu_activated(GtkWidget *widget, gpointer data)
{
    int i;

    ENTER;    
    i = GPOINTER_TO_INT(data);
    DBG("asking %d group\n", i);
    XkbLockGroup(dpy, XkbUseCoreKbd, i);
    RET();
}

static void
app_menu_create()
{
    GtkWidget *mi;
    
    ENTER;
    app_menu =  gtk_menu_new();

    mi = gtk_image_menu_item_new_from_stock(GTK_STOCK_DIALOG_INFO, NULL);
    g_signal_connect(G_OBJECT(mi), "activate", (GCallback)app_menu_about, NULL);
    gtk_menu_shell_append (GTK_MENU_SHELL (app_menu), mi);
    gtk_widget_show (mi);

    
    mi = gtk_menu_item_new ();
    gtk_widget_show (mi);
    gtk_menu_shell_append (GTK_MENU_SHELL (app_menu), mi);
    gtk_widget_set_sensitive (mi, FALSE);

    mi = gtk_image_menu_item_new_from_stock(GTK_STOCK_QUIT, NULL);
    g_signal_connect(G_OBJECT(mi), "activate", (GCallback)app_menu_exit, NULL);
    gtk_menu_shell_append (GTK_MENU_SHELL (app_menu), mi);
    gtk_widget_show (mi);
    RET();

} 

static void
app_menu_about(GtkWidget *widget, gpointer data)
{
    ENTER;
    if (!about_dialog) {
        about_dialog = gtk_message_dialog_new (NULL,
              GTK_DIALOG_DESTROY_WITH_PARENT,
              GTK_MESSAGE_INFO,
              GTK_BUTTONS_CLOSE,
              "fbxkb %s\nX11 Keyboard switcher\nAuthor: Anatoly Asviyan <aanatoly@users.sf.net>", version);
        /* Destroy the dialog when the user responds to it (e.g. clicks a button) */
        g_signal_connect_swapped (about_dialog, "response",
              G_CALLBACK (gtk_widget_hide),
              about_dialog);
    }
    gtk_widget_show (about_dialog);
    RET();
}


static void
app_menu_exit(GtkWidget *widget, gpointer data)
{
    ENTER;    
    exit(0);
    RET();
}


static void docklet_embedded(GtkWidget *widget, void *data) 
{
    ENTER;
    RET();
}

static void docklet_destroyed(GtkWidget *widget, void *data) 
{
    ENTER;
    //g_object_unref(G_OBJECT(docklet));
    docklet = NULL;
    g_idle_add(create_all, NULL);
    RET();
}


void docklet_clicked(GtkWidget *button, GdkEventButton *event, void *data) 
{
    //GtkWidget *menu;
    ENTER;
    if (event->type != GDK_BUTTON_PRESS)
        RET();

    if (event->button == 1) {
        int no;

        no =  (cur_group + 1) % ngroups;
        DBG("no=%d\n", no);
        XkbLockGroup(dpy, XkbUseCoreKbd, no);
    } else if (event->button == 2) {
        gtk_menu_popup(GTK_MENU(flag_menu), NULL, NULL, NULL, NULL, event->button, event->time);
    } else if (event->button == 3) {
        gtk_menu_popup(GTK_MENU(app_menu), NULL, NULL, NULL, NULL, event->button, event->time);
    }
    RET();
}

static int 
docklet_create() 
{
    GtkWidget *box;
    
    ENTER;
    docklet = (GtkWidget*)egg_tray_icon_new("fbxkb");
    box     = gtk_event_box_new();
    image   = gtk_image_new(); 
    //image   = gtk_image_new();
    g_signal_connect(G_OBJECT(docklet), "embedded", G_CALLBACK(docklet_embedded), NULL);
    g_signal_connect(G_OBJECT(docklet), "destroy", G_CALLBACK(docklet_destroyed), NULL);
    g_signal_connect(G_OBJECT(box), "button-press-event", G_CALLBACK(docklet_clicked), NULL);

    gtk_container_set_border_width(GTK_CONTAINER(box), 0);
    
    gtk_container_add(GTK_CONTAINER(box), image);
    gtk_container_add(GTK_CONTAINER(docklet), box);
    gtk_widget_show_all(GTK_WIDGET(docklet));
    
    RET(1);
}


/******************************************************************
 * internal state machine                                         *
 ******************************************************************/
static gboolean
my_str_equal (gchar *a, gchar *b)
{
    return strcmp(a,b) == 0;
}

    
static GdkPixbuf *
sym2flag(char *sym)
{
    GdkPixbuf *flag;
    static GString *s = NULL;
    
    ENTER;
    g_assert(sym != NULL && strlen(sym) > 1);
    flag = g_hash_table_lookup(sym2pix, sym);
    if (flag)
        RET(flag);

    if (!s)
        s = g_string_new(IMGPREFIX);
    else
        s = g_string_assign(s,IMGPREFIX);
    s = g_string_append(s, sym);
    s = g_string_append(s, ".png");
    flag = gdk_pixbuf_new_from_file_at_size(s->str, 24, 24, NULL);
    if (!flag)
        RET(zzflag);
    g_hash_table_insert(sym2pix, g_strdup(sym), flag);
    RET(flag);
}


static void
read_kbd_description()
{
    unsigned int mask;
    XkbDescRec *kbd_desc_ptr;
    XkbStateRec xkb_state;
    Atom sym_name_atom;
    int i;

    ENTER;
    // clean up
    cur_group = ngroups = 0;
    for (i = 0; i < XkbNumKbdGroups; i++) {
        g_free(group2info[i].sym);
        g_free(group2info[i].name);
        /*
          if (group2info[i].flag)
            g_object_unref(G_OBJECT(group2info[i].flag));
        */
    }
    bzero(group2info, sizeof(group2info));

    // get kbd info
    mask = XkbControlsMask | XkbServerMapMask;
    kbd_desc_ptr = XkbAllocKeyboard();
    if (!kbd_desc_ptr) {
        ERR("can't alloc kbd info\n");
        goto out_us;
    }
    kbd_desc_ptr->dpy = dpy;
    if (XkbGetControls(dpy, XkbAllControlsMask, kbd_desc_ptr) != Success) {
        ERR("can't get Xkb controls\n");
        goto out;
    }
    ngroups = kbd_desc_ptr->ctrls->num_groups;
    if (ngroups < 1)
        goto out;
    if (XkbGetState(dpy, XkbUseCoreKbd, &xkb_state) != Success) {
        ERR("can't get Xkb state\n");
        goto out;
    }
    cur_group = xkb_state.group;
    DBG("cur_group = %d ngroups = %d\n", cur_group, ngroups);
    g_assert(cur_group < ngroups);
    
    if (XkbGetNames(dpy, XkbSymbolsNameMask, kbd_desc_ptr) != Success) {
        ERR("can't get Xkb symbol description\n");
        goto out;
    }
    if (XkbGetNames(dpy, XkbGroupNamesMask, kbd_desc_ptr) != Success)
        ERR("Failed to get keyboard description\n");
    g_assert(kbd_desc_ptr->names);
    sym_name_atom = kbd_desc_ptr->names->symbols;

    // parse kbd info
    if (sym_name_atom != None) {
        char *sym_name, *tmp, *tok, *tmp2, *tmp3;
        int no;
        
        sym_name = XGetAtomName(dpy, sym_name_atom);
        if (!sym_name)
            goto out;
        /* to know how sym_name might look like do this:
         *    % xlsatoms | grep pc
         *    150 pc/pc(pc101)+pc/us+pc/ru(phonetic):2+group(shift_toggle)
         *    470 pc(pc105)+us+ru(phonetic):2+il(phonetic):3+group(shifts_toggle)+group(switch)
         */
        tmp3 = malloc(30 * sizeof(char));
        DBG("sym_name=%s\n", sym_name);
        for (tok = strtok(sym_name, "+"); tok; tok = strtok(NULL, "+")) {
            DBG("tok=%s\n", tok);
            tmp = strchr(tok, ':');
            if (tmp) {
                if (sscanf(tmp+1, "%d", &no) != 1) 
                    ERR("can't read kbd number\n");
                no--;
                *tmp = 0;
            } else {
                no = 0;
            }
            if((tmp2 = strchr(tok, '('))) {
                // these next two statements could be done cleverly in one statement but the compiler warns if you try it.
                // strip left paren, and then right paren
                tmp2++;
                tmp2[strlen(tmp2)-1] = '\0';
            }
            for (tmp = tok; isalpha(*tmp); tmp++);
            *tmp = 0;

            DBG("map=%s no=%d\n", tok, no);
            if (!strcmp(tok, "pc") || (strlen(tok) != 2))
                continue;
          
            g_assert((no >= 0) && (no < ngroups));
            if (group2info[no].sym != NULL) {
                ERR("xkb group #%d is already defined\n", no);
            }
            strcpy(tmp3, tok);
            strcat(tmp3,",");
            // add variant to end of string for the png lookup
            strcat(tmp3,tmp2);
            group2info[no].sym = g_strdup(tmp3);
            group2info[no].flag = sym2flag(tmp3);
            group2info[no].name = XGetAtomName(dpy, kbd_desc_ptr->names->groups[no]);           
            *tmp2 = 0;
            *tmp3 = 0;
        }
        XFree(sym_name);
    }
 out:
    XkbFreeKeyboard(kbd_desc_ptr, 0, True);
    // sanity check: group numbering must be continuous
    for (i = 0; (i < XkbNumKbdGroups) && (group2info[i].sym != NULL); i++);
    if (i != ngroups) {
        ERR("kbd group numbering is not continuous\n");
        ERR("run 'xlsatoms | grep pc' to know what happens\n");
        exit(1);
    }
 out_us:
    //if no groups were defined just add default 'us' kbd group
    if (!ngroups) {
        ngroups = 1;
        cur_group = 0;
        group2info[0].sym = g_strdup("us");
        group2info[0].flag = sym2flag("us");
        group2info[0].name = NULL;
        ERR("no kbd groups defined. adding default 'us' group\n");
    }
    RET();
}



static void update_flag(int no)
{
    kbd_info *k = &group2info[no];
    ENTER;
    g_assert(k != NULL);
    DBG("k->sym=%s\n", k->sym);
    gtk_image_set_from_pixbuf(GTK_IMAGE(image), k->flag);
    gtk_widget_set_tooltip_text(docklet, k->name);
    RET();
}



static GdkFilterReturn
filter( XEvent *xev, GdkEvent *event, gpointer data)
{
    ENTER;
    if (!active)
        RET(GDK_FILTER_CONTINUE);
   
    if (xev->type ==  xkb_event_type) {
        XkbEvent *xkbev = (XkbEvent *) xev;
        DBG("XkbTypeEvent %d \n", xkbev->any.xkb_type);
        if (xkbev->any.xkb_type == XkbStateNotify) {
            DBG("XkbStateNotify: %d\n", xkbev->state.group);
            cur_group = xkbev->state.group;
            if (cur_group < ngroups) {
                update_flag(cur_group);
            }
        } else if (xkbev->any.xkb_type == XkbNewKeyboardNotify) {         
            DBG("XkbNewKeyboardNotify\n");
            read_kbd_description();
            //cur_group = 0;
            update_flag(cur_group);
            flag_menu_destroy();
            flag_menu_create();  
        }
        RET(GDK_FILTER_REMOVE);
    }
    RET(GDK_FILTER_CONTINUE);
}

static int
init()
{
    int dummy;

    ENTER;
    sym2pix  = g_hash_table_new(g_str_hash, (GEqualFunc) my_str_equal);
    dpy = gdk_x11_get_default_xdisplay();
    a_XKB_RULES_NAMES = XInternAtom(dpy, "_XKB_RULES_NAMES", False);
    if (a_XKB_RULES_NAMES == None)
        ERR("_XKB_RULES_NAMES - can't get this atom\n");

    if (!XkbQueryExtension(dpy, &dummy, &xkb_event_type, &dummy, &dummy, &dummy))
        RET(0);
    DBG("xkb_event_type=%d\n", xkb_event_type);
    XkbSelectEventDetails(dpy, XkbUseCoreKbd, XkbStateNotify,
          XkbAllStateComponentsMask, XkbGroupStateMask);
    gdk_window_add_filter(NULL, (GdkFilterFunc)filter, NULL);
    zzflag = gdk_pixbuf_new_from_file_at_size(IMGPREFIX "zz.png", 24, 24, NULL);
    RET(1);
}

#if 0


static void
app_menu_destroy()
{
    ENTER;
    if (app_menu) {
        gtk_widget_destroy(app_menu);
        app_menu = NULL;
    }
    RET();
}

static void
destroy_all()
{
    active = 0;
    gdk_window_remove_filter(NULL, (GdkFilterFunc)filter, NULL);
    XkbSelectEventDetails(dpy, XkbUseCoreKbd, XkbStateNotify,
          XkbAllStateComponentsMask, 0UL);
    flag_menu_destroy();
    app_menu_destroy();
}
#endif

static int
create_all()
{
    ENTER;
    read_kbd_description();
    docklet_create();
    flag_menu_create();
    app_menu_create();
    update_flag(cur_group);
    active = 1;
    RET(FALSE);// FALSE will remove us from idle func
}

int
main(int argc, char *argv[], char *env[])
{
    ENTER;
    setlocale(LC_ALL, "");
    gtk_init(&argc, &argv);
    XSetLocaleModifiers("");
    XSetErrorHandler((XErrorHandler) Xerror_handler);

    if (!init())
        ERR("can't init. exiting\n");
    create_all();
    gtk_main ();
    RET(0);
}


/********************************************************************/

void
Xerror_handler(Display * d, XErrorEvent * ev)
{
    char buf[256];

    ENTER;
    XGetErrorText(gdk_x11_get_default_xdisplay(), ev->error_code, buf, 256);
    ERR( "fbxkb : X error: %s\n", buf);
    RET();
}
bgstack15