Source file key.ml

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
(*********************************************************************************)
(*                OCaml-Stk                                                      *)
(*                                                                               *)
(*    Copyright (C) 2023-2024 INRIA All rights reserved.                         *)
(*    Author: Maxence Guesdon, INRIA Saclay                                      *)
(*                                                                               *)
(*    This program is free software; you can redistribute it and/or modify       *)
(*    it under the terms of the GNU General Public License as                    *)
(*    published by the Free Software Foundation, version 3 of the License.       *)
(*                                                                               *)
(*    This program 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 General Public License for more details.                               *)
(*                                                                               *)
(*    You should have received a copy of the GNU General Public                  *)
(*    License along with this program; if not, write to the Free Software        *)
(*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA                   *)
(*    02111-1307  USA                                                            *)
(*                                                                               *)
(*    As a special exception, you have permission to link this program           *)
(*    with the OCaml compiler and distribute executables, as long as you         *)
(*    follow the requirements of the GNU GPL in regard to all of the             *)
(*    software in the executable aside from the OCaml compiler.                  *)
(*                                                                               *)
(*    Contact: Maxence.Guesdon@inria.fr                                          *)
(*                                                                               *)
(*********************************************************************************)

open Tsdl

let key_is_mod =
  let module I = Set.Make(Int) in
  let mod_keys = I.of_list
    Sdl.K.( [
       lctrl ; lshift ; lalt ; lgui ;
       rctrl ; rshift ; ralt ; rgui ;
       mode ])
  in
  fun k -> I.mem k mod_keys

type keystate = {
    key: Sdl.keycode ;
    mask: Sdl.keymod ;
    mods: Sdl.keymod ;
    pred: Sdl.keymod -> bool ;
  }

let compare_keystate k1 k2 =
  match Stdlib.compare k1.key k2.key with
  | 0 ->
      (match Stdlib.compare k1.mask k2.mask with
       | 0 -> Stdlib.compare k1.mods k2.mods
       | n -> n
      )
  | n -> n

let keystate_equal k1 k2 =
  k1.key = k2.key &&
  k1.mask = k2.mask &&
  k1.mods = k2.mods

let pp_keystate ppf k =
  Format.fprintf ppf "{key=%s, mask=%x, mods=%x}"
    Sdl.(get_key_name k.key) k.mask k.mods

(**/**)

let lr_mods = Sdl.Kmod.(gui + alt + shift + ctrl)

let lr_test left right kmod =
  let both = left lor right in
(*  prerr_endline (Printf.sprintf "lr_test: left=%x right=%x both=%x" left right both);*)
  let kmod_both = kmod land both in
(*  prerr_endline (Printf.sprintf "lr_test: kmod_both=%x" kmod_both);*)
  if kmod_both = both then
    (fun m ->
       let b = m land left > 0 || m land right > 0 in
(*       [%debug "fun m=%x -> m land %x > 0 || m land %x > 0 = %b"
         m left right b);*)
       b
    )
  else
    if kmod_both = 0 then
      (fun m -> m land both = 0)
    else
      if kmod_both = left then
        (fun m -> m land left > 0)
      else
        (fun m -> m land right > 0)

let mk_lr_tests =
  let open Sdl.Kmod in
  let l =
    [ lr_test lshift rshift ;
      lr_test lalt ralt ;
      lr_test lctrl rctrl ;
      lr_test lgui rgui ;
    ]
  in
  fun mods ->
    let l = List.map (fun f -> f mods) l in
    fun m -> List.for_all (fun f -> f m) l

let build_pred mods =
(*  prerr_endline (Printf.sprintf "build_pred: mods=%x" mods);*)
  let lr_pred = mk_lr_tests mods in
  let mods = mods land (lnot lr_mods) in
(*  prerr_endline (Printf.sprintf "build_pred: mods land (lnot lr_mods)=%x" mods);*)
  let eq m = m land mods = mods in
  fun m -> lr_pred m && eq m
(**/**)

let default_keymask = ref Sdl.Kmod.(reserved+mode)
let set_default_keymask n = default_keymask := n
let default_keymask () = !default_keymask

let default_keymods = ref Sdl.Kmod.none
let set_default_keymods n = default_keymods := n
let default_keymods () = !default_keymods

let keystate ?(mask=default_keymask())?(mods=default_keymods()) key =
  { key ; mask ; mods ; pred = build_pred mods }

let match_keys ks ~key ~kmod =
  [%debug "match_keys ks=%a key=%s kmod=%x lr_mods=%x"
    pp_keystate ks
    Sdl.(get_key_name key) kmod lr_mods];
  key = ks.key && ks.pred (kmod land lnot ks.mask)

module Lexer =
  struct
    let shift = [%sedlex.regexp? 'S']
    let lshift = [%sedlex.regexp? "lS"]
    let rshift = [%sedlex.regexp? "rS"]
    let ctrl = [%sedlex.regexp? 'C']
    let lctrl = [%sedlex.regexp? "lC"]
    let rctrl = [%sedlex.regexp? "rC"]
    let alt = [%sedlex.regexp? 'A']
    let lalt = [%sedlex.regexp? "lA"]
    let ralt = [%sedlex.regexp? "rA"]
    let gui = [%sedlex.regexp? 'G']
    let lgui = [%sedlex.regexp? "lG"]
    let rgui = [%sedlex.regexp? "rG"]
    let num = [%sedlex.regexp? 'N']
    let caps = [%sedlex.regexp? 'L']
    let mode = [%sedlex.regexp? 'M']

    let mods = [%sedlex.regexp? shift | lshift | rshift | ctrl | lctrl | rctrl
      | alt | lalt | ralt | gui | lgui | rgui | num | caps | mode ]
(*    let key = [%sedlex.regexp? Plus(alphabetic | 'a'..'z' | 'A'..'Z' | '0'..'9' |
      Chars(" _-#&*@^:$!>(<%+?'\").[]={},`"))]*)

    let key = [%sedlex.regexp? Plus(20 .. 65000) ]

    let keystate = [%sedlex.regexp? Opt(mods,'/'),Opt(Plus(mods),'-'),key]

(*
    let mod_of_string =
      let open Sdl.Kmod in
      function
      | "S" -> shift
      | "lS" -> lshift
      | "rS" -> rshift
      | "C" -> ctrl
      | "lC" -> lctrl
      | "rC" -> rctrl
      | "A" -> alt
      | "lA" -> lalt
      | "rA" -> ralt
      | "G" -> gui
      | "lG" -> lgui
      | "rG" -> rgui
      | "N" -> num
      | "L" -> caps
      | "M" -> mode
      | _ -> assert false

*)
    let rec parse_mods acc lb =
      let module K = Sdl.Kmod in
      match
        match%sedlex lb with
        | shift -> Some K.shift
        | lshift -> Some K.lshift
        | rshift -> Some K.rshift
        | ctrl -> Some K.ctrl
        | lctrl -> Some K.lctrl
        | rctrl -> Some K.rctrl
        | alt -> Some K.alt
        | lalt -> Some K.lalt
        | ralt -> Some K.ralt
        | gui -> Some K.gui
        | lgui -> Some K.lgui
        | rgui -> Some K.rgui
        | num -> Some K.num
        | caps -> Some K.caps
        | mode -> Some K.mode
        | eof -> None
        | any -> None
        | _ -> None
      with
      | Some m -> parse_mods (acc lor m) lb
      | None -> acc

    let parse spec =
      let lb = Sedlexing.Utf8.from_string spec in
      let m = parse_mods 0 lb in
      let str = Sedlexing.Utf8.lexeme lb in
      let (mask, mods, lb) =
        match str with
        | "/" -> (* parsed a mask *)
            (
             let p = Sedlexing.lexeme_end lb in
             let mo = parse_mods 0 lb in
             match Sedlexing.Utf8.lexeme lb with
             | "-" -> (* parsed a modifier *)
                 (Some m, Some mo, lb)
             | _ -> (* parsed a key identifier or eof, rollback *)
                 let lb = Sedlexing.Utf8.from_string
                   (String.sub spec p (String.length spec - p))
                 in
                 (Some m, None, lb)
            )
        | "-" -> (* parsed a mod *)
            (None, Some m, lb)
        | _ -> (* parsed key identifier or eof, rollback *)
            let lb = Sedlexing.Utf8.from_string spec in
            (None, None, lb)
      in
      match%sedlex lb with
      | key ->
          (
           let str = Sedlexing.Utf8.lexeme lb in
           match Sdl.get_key_from_name str with
           | k when k = Sdl.K.unknown ->
               Ocf.json_error (Printf.sprintf
                "Unknown key name %S in keystate %S" str spec)
           | k -> keystate ?mask ?mods k
          )
      | any ->
          let lexeme = Sedlexing.Utf8.lexeme lb in
          Ocf.json_error (Printf.sprintf
           "Invalid character %s at %d in keystate %S" lexeme
             (Sedlexing.lexeme_start lb) spec)
      | eof ->
          Ocf.json_error (Printf.sprintf
           "Unexpected end of string at character %d in keystate %S"
             (Sedlexing.lexeme_start lb) spec)
      | _ -> assert false

  end

let lr_spec =
  let open Sdl.Kmod in
  [
    'S', (shift, lshift, rshift) ;
    'A', (alt, lalt, ralt) ;
    'C', (ctrl, lctrl, ctrl) ;
    'G', (gui, lgui, rgui) ;
  ]
let simple_spec =
  let open Sdl.Kmod in
  [ 'N', num ; 'L', caps ;'M', mode]

let keystate_of_string = Lexer.parse

let string_of_mods mods =
  let b = Buffer.create 25 in
  List.iter
    (fun (c, (both,left,right)) ->
       if mods land both > 0 then
         Buffer.add_char b c
       else
         if mods land left > 0 then
           Printf.bprintf b "l%c" c
         else if mods land right > 0 then
             Printf.bprintf b "r%c" c
    )
    lr_spec;
  List.iter (fun (c, m) ->
     if mods land m > 0 then Buffer.add_char b c)
    simple_spec;
  Buffer.contents b

let string_of_keystate t =
  let mods =
    if t.mods = Sdl.Kmod.none then
      ""
    else
      Printf.sprintf "%s-" (string_of_mods t.mods)
  in
  let mask =
    if t.mask <> default_keymask () then
      (Printf.sprintf "%s/" (string_of_mods t.mask))
    else
      ""
  in
  let key = Sdl.get_key_name t.key in
  Printf.sprintf "%s%s%s" mask mods key

let keystate_ocf_wrapper =
  let to_j ?with_doc t = `String (string_of_keystate t) in
  let from_j ?def = function
  | `String str -> keystate_of_string str
  | json -> Ocf.invalid_value json
  in
  Ocf.Wrapper.make to_j from_j

let keystate_list_ocf_wrapper =
  let from_j ?def json =
    let l =
      match  json with
      | `String s -> [keystate_of_string s]
      | `List l ->
          List.fold_left (fun acc json ->
             (keystate_ocf_wrapper.from_json json :: acc))
            [] l
      | json -> Ocf.invalid_value json
    in
    List.rev l
  in
  let to_j ?with_doc = function
  | [ks] -> keystate_ocf_wrapper.to_json ks
  | l -> `List (List.map (keystate_ocf_wrapper.to_json ?with_doc) l)
  in
  Ocf.Wrapper.make to_j from_j

let keystate_list_of_string str =
  let json = Yojson.Safe.from_string str in
  keystate_list_ocf_wrapper.from_json json

let string_of_keystate_list l =
  Yojson.Safe.to_string (keystate_list_ocf_wrapper.to_json l)

let is_mod_pressed kmod =
  let m = Sdl.get_mod_state () in
  m land kmod <> 0

let shift_pressed () =
  Sdl.Kmod.(is_mod_pressed (lshift lor rshift))

let ctrl_pressed () =
  Sdl.Kmod.(is_mod_pressed (lctrl lor rctrl))

let css_keystate_parser ctx =
 let open Angstrom in
  (Css.Vp.string ctx >>= fun s -> Css.U.ws ctx *>
    take_while1 (fun c -> not (Css.U.is_ws c)) >>= fun s ->
    return (keystate_of_string s)
  ) <?> "keystate"