Names of keyboard codes

I am trying to translate pressed key into name of the key.
This is the source of my information:

Has somebody done it before? Ifnot, how can I use ctypes to import the data from the file? Part of the problem is the fact that GDK library for GTK4 is not available on Ubuntu like systems.

I vowed to give up on OCaml, but I have discovered solution to my problems, so I wonder how far I will progress this time.

I’m embarrassed by my solution. It will read and process the file on every key press.

But I need to have a break from OCaml until next weekend.

if the codes are contiguous, I suggest first transforming your list into a string array, then accessing like key_name.(i-offset) will be much faster

otherwise you may also convert you list into a Map, it will also be quite faster

You can use the constant function for retrieving the values of constants. There are a few steps, though:

  1. Create a constant binding for every symbols that you want to bind, e.g.

          let _GDK_KEY_VoidSymbol = constant "GDK_KEY_VoidSymbol" int64_t
    
  2. Add them to a parameterized module Bindings:

    module Bindings(C: Cstubs_structs.TYPE) = struct
       open C
       let _GDK_KEY_VoidSymbol = constant "GDK_KEY_VoidSymbol" int64_t
       let _GDK_KEY_BackSpace = constant "GDK_KEY_BackSpace" int64_t
       [...]
    end
    
  3. Pass the Bindings module to Cstubs_structs.write_c:

    Cstubs_structs.write_c Format.std_formatter (module Bindings)
    

    which will generate a C program that builds an OCaml module with an entry for each of the symbols you bound with constant.

It’s a slightly complex workflow, since (a) it needs to handle lots of other cases (b) it generates efficient code that allows the extracted constants to be inlined, and (c) it provides some degree of safety. For a simple case you might find it easier just to extract the constants and build the module directly (i.e. without using ctypes).

1 Like

I also thought about it.

Using constants is a very interesting approach. For the time being, when I have time to come back to my project, I will try to use Hash. But it’s nice to see the ability to make it even faster.

Thank you very much for advice.