2024-05-29 15:56:08 +02:00
|
|
|
import textwrap, sys, re, string, json, os
|
2024-06-09 10:35:38 +02:00
|
|
|
from array import array
|
2024-02-11 20:46:36 +01:00
|
|
|
|
2024-06-09 11:10:20 +02:00
|
|
|
# Compile compose sequences from Xorg's format or from JSON files into an
|
|
|
|
# efficient state machine.
|
|
|
|
# See [ComposeKey.java] for the interpreter.
|
|
|
|
#
|
|
|
|
# Takes input files as arguments and generate a Java file.
|
|
|
|
# The initial state for each input is generated as a constant named after the
|
|
|
|
# input file.
|
|
|
|
|
2024-05-29 15:56:08 +02:00
|
|
|
# Parse symbol names from keysymdef.h. Many compose sequences in
|
|
|
|
# en_US_UTF_8_Compose.pre reference theses. For example, all the sequences on
|
|
|
|
# the Greek, Cyrillic and Hebrew scripts need these symbols.
|
2024-07-21 23:37:07 +02:00
|
|
|
def parse_keysymdef_h(fname):
|
|
|
|
with open(fname, "r") as inp:
|
2024-05-29 15:56:08 +02:00
|
|
|
keysym_re = re.compile(r'^#define XK_(\S+)\s+\S+\s*/\*.U\+([0-9a-fA-F]+)\s')
|
|
|
|
for line in inp:
|
|
|
|
m = re.match(keysym_re, line)
|
|
|
|
if m != None:
|
|
|
|
yield (m.group(1), chr(int(m.group(2), 16)))
|
|
|
|
|
2024-02-12 23:23:38 +01:00
|
|
|
dropped_sequences = 0
|
|
|
|
|
|
|
|
# Parse XKB's Compose.pre files
|
2024-07-21 23:37:07 +02:00
|
|
|
def parse_sequences_file_xkb(fname, xkb_char_extra_names):
|
2024-02-12 23:23:38 +01:00
|
|
|
# Parse a line of the form:
|
|
|
|
# <Multi_key> <minus> <space> : "~" asciitilde # TILDE
|
|
|
|
# Sequences not starting with <Multi_key> are ignored.
|
|
|
|
line_re = re.compile(r'^((?:\s*<[^>]+>)+)\s*:\s*"((?:[^"\\]+|\\.)+)"\s*(\S+)?\s*(?:#.+)?$')
|
|
|
|
char_re = re.compile(r'\s*<(?:U([a-fA-F0-9]{4,6})|([^>]+))>')
|
|
|
|
def parse_seq_line(line):
|
|
|
|
global dropped_sequences
|
|
|
|
prefix = "<Multi_key>"
|
|
|
|
if not line.startswith(prefix):
|
|
|
|
return None
|
|
|
|
m = re.match(line_re, line[len(prefix):])
|
|
|
|
if m == None:
|
|
|
|
return None
|
|
|
|
def_ = m.group(1)
|
|
|
|
try:
|
|
|
|
def_ = parse_seq_chars(def_)
|
|
|
|
result = parse_seq_result(m.group(2))
|
|
|
|
except Exception as e:
|
|
|
|
# print(str(e) + ". Sequence dropped: " + line.strip(), file=sys.stderr)
|
|
|
|
dropped_sequences += 1
|
|
|
|
return None
|
|
|
|
return def_, result
|
|
|
|
char_names = { **xkb_char_extra_names }
|
|
|
|
# Interpret character names of the form "U0000" or using [char_names].
|
2024-06-09 10:35:38 +02:00
|
|
|
def parse_seq_char(sc):
|
|
|
|
uchar, named_char = sc
|
2024-02-12 23:23:38 +01:00
|
|
|
if uchar != "":
|
2024-06-09 10:35:38 +02:00
|
|
|
c = chr(int(uchar, 16))
|
|
|
|
elif len(named_char) == 1:
|
|
|
|
c = named_char
|
|
|
|
else:
|
|
|
|
if not named_char in char_names:
|
|
|
|
raise Exception("Unknown char: " + named_char)
|
|
|
|
c = char_names[named_char]
|
|
|
|
# The state machine can't represent sequence characters that do not fit
|
|
|
|
# in a 16-bit char.
|
|
|
|
if len(c) > 1 or ord(c[0]) > 65535:
|
|
|
|
raise Exception("Char out of range: " + r)
|
|
|
|
return c
|
2024-02-12 23:23:38 +01:00
|
|
|
# Interpret the left hand side of a sequence.
|
|
|
|
def parse_seq_chars(def_):
|
|
|
|
return list(map(parse_seq_char, re.findall(char_re, def_)))
|
|
|
|
# Interpret the result of a sequence, as outputed by [line_re].
|
|
|
|
def parse_seq_result(r):
|
|
|
|
if len(r) == 2 and r[0] == '\\':
|
|
|
|
return r[1]
|
|
|
|
return r
|
|
|
|
# Populate [char_names] with the information present in the file.
|
|
|
|
with open(fname, "r") as inp:
|
|
|
|
for line in inp:
|
|
|
|
m = re.match(line_re, line)
|
|
|
|
if m == None or m.group(3) == None:
|
|
|
|
continue
|
|
|
|
try:
|
|
|
|
char_names[m.group(3)] = parse_seq_result(m.group(2))
|
|
|
|
except Exception:
|
|
|
|
pass
|
|
|
|
# Parse the sequences
|
2024-02-11 20:46:36 +01:00
|
|
|
with open(fname, "r") as inp:
|
2024-02-12 23:23:38 +01:00
|
|
|
seqs = []
|
|
|
|
for line in inp:
|
|
|
|
s = parse_seq_line(line)
|
|
|
|
if s != None:
|
|
|
|
seqs.append(s)
|
|
|
|
return seqs
|
|
|
|
|
2024-09-10 22:43:05 +02:00
|
|
|
# Basic support for comments in json files. Reads a file
|
|
|
|
def strip_cstyle_comments(inp):
|
|
|
|
def strip_line(line):
|
|
|
|
i = line.find("//")
|
|
|
|
return line[:i] + "\n" if i >= 0 else line
|
|
|
|
return "".join(map(strip_line, inp))
|
|
|
|
|
2024-03-02 19:12:37 +01:00
|
|
|
# Parse from a json file containing a dictionary sequence → result string.
|
|
|
|
def parse_sequences_file_json(fname):
|
2024-09-29 22:47:57 +02:00
|
|
|
try:
|
|
|
|
with open(fname, "r") as inp:
|
|
|
|
seqs = json.loads(strip_cstyle_comments(inp))
|
|
|
|
return list(seqs.items())
|
|
|
|
except Exception as e:
|
|
|
|
print("Failed parsing '%s': %s" % (fname, str(e)), file=sys.stderr)
|
2024-03-02 19:12:37 +01:00
|
|
|
|
2024-02-12 23:23:38 +01:00
|
|
|
# Format of the sequences file is determined by its extension
|
2024-07-21 23:37:07 +02:00
|
|
|
def parse_sequences_file(fname, xkb_char_extra_names={}):
|
2024-02-12 23:23:38 +01:00
|
|
|
if fname.endswith(".pre"):
|
2024-07-21 23:37:07 +02:00
|
|
|
return parse_sequences_file_xkb(fname, xkb_char_extra_names)
|
2024-03-02 19:12:37 +01:00
|
|
|
if fname.endswith(".json"):
|
|
|
|
return parse_sequences_file_json(fname)
|
2024-02-12 23:23:38 +01:00
|
|
|
raise Exception(fname + ": Unsupported format")
|
2024-02-11 20:46:36 +01:00
|
|
|
|
2024-07-21 23:37:07 +02:00
|
|
|
# A sequence directory can contain several sequence files as well as
|
|
|
|
# 'keysymdef.h'.
|
|
|
|
def parse_sequences_dir(dname):
|
|
|
|
compose_files = []
|
|
|
|
xkb_char_extra_names = {}
|
|
|
|
# Parse keysymdef.h first if present
|
|
|
|
for fbasename in os.listdir(dname):
|
|
|
|
fname = os.path.join(dname, fbasename)
|
|
|
|
if fbasename == "keysymdef.h":
|
|
|
|
xkb_char_extra_names = dict(parse_keysymdef_h(fname))
|
|
|
|
else:
|
|
|
|
compose_files.append(fname)
|
|
|
|
sequences = []
|
|
|
|
for fname in compose_files:
|
|
|
|
sequences.extend(parse_sequences_file(fname, xkb_char_extra_names))
|
|
|
|
return sequences
|
|
|
|
|
2024-02-11 20:46:36 +01:00
|
|
|
# Turn a list of sequences into a trie.
|
|
|
|
def add_sequences_to_trie(seqs, trie):
|
2024-03-02 19:12:37 +01:00
|
|
|
def add_seq_to_trie(t_, seq, result):
|
2024-02-11 20:46:36 +01:00
|
|
|
t_ = trie
|
|
|
|
i = 0
|
|
|
|
while i < len(seq) - 1:
|
|
|
|
c = seq[i]
|
|
|
|
if c not in t_:
|
|
|
|
t_[c] = {}
|
2024-03-02 19:12:37 +01:00
|
|
|
if isinstance(t_[c], str):
|
|
|
|
global dropped_sequences
|
|
|
|
dropped_sequences += 1
|
|
|
|
print("Sequence collide: '%s = %s' '%s = %s'" % (
|
|
|
|
seq[:i+1], t_[c], seq, result),
|
|
|
|
file=sys.stderr)
|
|
|
|
return
|
2024-02-11 20:46:36 +01:00
|
|
|
t_ = t_[c]
|
|
|
|
i += 1
|
|
|
|
c = seq[i]
|
|
|
|
t_[c] = result
|
2024-03-02 19:12:37 +01:00
|
|
|
for seq, result in seqs:
|
|
|
|
add_seq_to_trie(trie, seq, result)
|
2024-02-11 20:46:36 +01:00
|
|
|
|
|
|
|
# Compile the trie into a state machine.
|
2024-06-09 11:10:20 +02:00
|
|
|
def make_automata(tries):
|
2024-09-14 15:13:04 +02:00
|
|
|
previous_leafs = {} # Deduplicate leafs
|
2024-02-11 20:46:36 +01:00
|
|
|
states = []
|
|
|
|
def add_tree(t):
|
2024-09-14 15:13:04 +02:00
|
|
|
this_node_index = len(states)
|
2024-02-11 20:46:36 +01:00
|
|
|
# Index and size of the new node
|
|
|
|
i = len(states)
|
|
|
|
s = len(t.keys())
|
|
|
|
# Add node header
|
2024-02-12 23:23:38 +01:00
|
|
|
states.append(("\0", s + 1))
|
2024-02-11 20:46:36 +01:00
|
|
|
i += 1
|
|
|
|
# Reserve space for the current node in both arrays
|
|
|
|
for c in range(s):
|
|
|
|
states.append((None, None))
|
|
|
|
# Add nested nodes and fill the current node
|
|
|
|
for c in sorted(t.keys()):
|
2024-09-14 15:13:04 +02:00
|
|
|
states[i] = (c, add_node(t[c]))
|
2024-02-11 20:46:36 +01:00
|
|
|
i += 1
|
2024-09-14 15:13:04 +02:00
|
|
|
return this_node_index
|
2024-02-11 20:46:36 +01:00
|
|
|
def add_leaf(c):
|
2024-09-14 15:13:04 +02:00
|
|
|
if c in previous_leafs:
|
|
|
|
return previous_leafs[c]
|
|
|
|
this_node_index = len(states)
|
|
|
|
previous_leafs[c] = this_node_index
|
2024-05-29 15:02:08 +02:00
|
|
|
# There are two encoding for leafs: character final state for 15-bit
|
|
|
|
# characters and string final state for the rest.
|
|
|
|
if len(c) > 1 or ord(c[0]) > 32767: # String final state
|
2024-06-09 10:35:38 +02:00
|
|
|
javachars = array('H', c.encode("UTF-16-LE"))
|
|
|
|
states.append((-1, len(javachars) + 1))
|
|
|
|
for c in javachars:
|
2024-05-29 15:02:08 +02:00
|
|
|
states.append((c, 0))
|
|
|
|
else: # Character final state
|
|
|
|
states.append((c, 1))
|
2024-09-14 15:13:04 +02:00
|
|
|
return this_node_index
|
2024-02-11 20:46:36 +01:00
|
|
|
def add_node(n):
|
|
|
|
if type(n) == str:
|
2024-09-14 15:13:04 +02:00
|
|
|
return add_leaf(n)
|
2024-02-11 20:46:36 +01:00
|
|
|
else:
|
2024-09-14 15:13:04 +02:00
|
|
|
return add_tree(n)
|
2024-06-09 11:10:20 +02:00
|
|
|
states.append((1, 1)) # Add an empty state at the beginning.
|
2024-09-14 15:13:04 +02:00
|
|
|
entry_states = { n: add_tree(root) for n, root in tries.items() }
|
2024-06-09 11:10:20 +02:00
|
|
|
return entry_states, states
|
2024-02-11 20:46:36 +01:00
|
|
|
|
2024-06-09 10:35:38 +02:00
|
|
|
# Debug
|
|
|
|
def print_automata(automata):
|
|
|
|
i = 0
|
|
|
|
for (s, e) in automata:
|
|
|
|
s = "%#06x" % s if isinstance(s, int) else '"%s"' % str(s)
|
|
|
|
print("%3d %8s %d" % (i, s, e), file=sys.stderr)
|
|
|
|
i += 1
|
|
|
|
|
2024-02-12 23:23:38 +01:00
|
|
|
def batched(ar, n):
|
|
|
|
i = 0
|
|
|
|
while i + n < len(ar):
|
|
|
|
yield ar[i:i+n]
|
|
|
|
i += n
|
|
|
|
if i < len(ar):
|
|
|
|
yield ar[i:]
|
|
|
|
|
2024-02-11 20:46:36 +01:00
|
|
|
# Print the state machine compiled by make_automata into java code that can be
|
|
|
|
# used by [ComposeKeyData.java].
|
2024-06-09 11:10:20 +02:00
|
|
|
def gen_java(entry_states, machine):
|
2024-02-12 23:23:38 +01:00
|
|
|
chars_map = {
|
|
|
|
# These characters cannot be used in unicode form as Java's parser
|
|
|
|
# unescape unicode sequences before parsing.
|
2024-05-29 15:02:08 +02:00
|
|
|
-1: "\\uFFFF",
|
2024-02-12 23:23:38 +01:00
|
|
|
"\"": "\\\"",
|
|
|
|
"\\": "\\\\",
|
|
|
|
"\n": "\\n",
|
2024-03-02 19:12:37 +01:00
|
|
|
"\r": "\\r",
|
2024-02-12 23:23:38 +01:00
|
|
|
ord("\""): "\\\"",
|
|
|
|
ord("\\"): "\\\\",
|
|
|
|
ord("\n"): "\\n",
|
2024-03-02 19:12:37 +01:00
|
|
|
ord("\r"): "\\r",
|
2024-02-12 23:23:38 +01:00
|
|
|
}
|
|
|
|
def char_repr(c):
|
|
|
|
if c in chars_map:
|
|
|
|
return chars_map[c]
|
|
|
|
if type(c) == int: # The edges array contains ints
|
|
|
|
return "\\u%04x" % c
|
|
|
|
if c in string.printable:
|
|
|
|
return c
|
|
|
|
return "\\u%04x" % ord(c)
|
|
|
|
def gen_array(array):
|
|
|
|
chars = list(map(char_repr, array))
|
|
|
|
return "\" +\n \"".join(map(lambda b: "".join(b), batched(chars, 72)))
|
2024-06-09 11:10:20 +02:00
|
|
|
def gen_entry_state(s):
|
|
|
|
name, state = s
|
|
|
|
return " public static final int %s = %d;" % (name, state)
|
2024-02-11 20:46:36 +01:00
|
|
|
print("""package juloo.keyboard2;
|
|
|
|
|
|
|
|
/** This file is generated, see [srcs/compose/compile.py]. */
|
|
|
|
|
|
|
|
public final class ComposeKeyData
|
|
|
|
{
|
2024-02-12 23:23:38 +01:00
|
|
|
public static final char[] states =
|
|
|
|
("%s").toCharArray();
|
2024-02-11 20:46:36 +01:00
|
|
|
|
2024-02-12 23:23:38 +01:00
|
|
|
public static final char[] edges =
|
|
|
|
("%s").toCharArray();
|
2024-06-09 11:10:20 +02:00
|
|
|
|
|
|
|
%s
|
2024-02-11 20:46:36 +01:00
|
|
|
}""" % (
|
2024-02-12 23:23:38 +01:00
|
|
|
# Break the edges array every few characters using string concatenation.
|
|
|
|
gen_array(map(lambda s: s[0], machine)),
|
|
|
|
gen_array(map(lambda s: s[1], machine)),
|
2024-06-09 11:10:20 +02:00
|
|
|
"\n".join(map(gen_entry_state, entry_states.items())),
|
2024-02-11 20:46:36 +01:00
|
|
|
))
|
|
|
|
|
|
|
|
total_sequences = 0
|
2024-06-09 11:10:20 +02:00
|
|
|
tries = {} # Orderred dict
|
2024-07-21 23:37:07 +02:00
|
|
|
for fname in sorted(sys.argv[1:]):
|
2024-06-09 11:10:20 +02:00
|
|
|
tname, _ = os.path.splitext(os.path.basename(fname))
|
2024-07-21 23:37:07 +02:00
|
|
|
if os.path.isdir(fname):
|
|
|
|
sequences = parse_sequences_dir(fname)
|
|
|
|
else:
|
|
|
|
sequences = parse_sequences_file(fname)
|
2024-06-09 11:10:20 +02:00
|
|
|
add_sequences_to_trie(sequences, tries.setdefault(tname, {}))
|
2024-02-11 20:46:36 +01:00
|
|
|
total_sequences += len(sequences)
|
2024-06-09 11:10:20 +02:00
|
|
|
entry_states, automata = make_automata(tries)
|
|
|
|
gen_java(entry_states, automata)
|
2024-02-12 23:23:38 +01:00
|
|
|
print("Compiled %d sequences into %d states. Dropped %d sequences." % (total_sequences, len(automata), dropped_sequences), file=sys.stderr)
|
2024-06-09 10:35:38 +02:00
|
|
|
# print_automata(automata)
|