2 # pylint: disable=line-too-long,invalid-name,global-statement,redefined-outer-name
3 # pylint: disable=missing-function-docstring,missing-class-docstring,missing-module-docstring
4 # SPDX-License-Identifier: MIT
6 # This file is distributed under the MIT license, see below.
8 # The MIT License (MIT)
10 # Permission is hereby granted, free of charge, to any person obtaining a copy
11 # of this software and associated documentation files (the "Software"), to deal
12 # in the Software without restriction, including without limitation the rights
13 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 # copies of the Software, and to permit persons to whom the Software is
15 # furnished to do so, subject to the following conditions:
17 # The above copyright notice and this permission notice shall be included in
18 # all copies or substantial portions of the Software.
20 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
34 from pyparsing
import (Word
, White
, Literal
, ParserElement
, Regex
, LineEnd
,
35 OneOrMore
, Combine
, Or
, Optional
, Suppress
, Group
,
36 nums
, alphanums
, printables
,
37 stringEnd
, pythonStyleComment
,
40 print('pyparsing is not available')
44 from pyparsing
import __diag__
46 __diag__
.warn_multiple_tokens_in_named_alternation
= True
47 __diag__
.warn_ungrouped_named_tokens_in_collection
= True
48 __diag__
.warn_name_set_on_empty_Forward
= True
49 __diag__
.warn_on_multiple_string_args_to_oneof
= True
50 __diag__
.enable_debug_on_named_expressions
= True
55 from evdev
.ecodes
import ecodes
58 print('WARNING: evdev is not available')
61 from functools
import lru_cache
63 # don't do caching on old python
64 lru_cache
= lambda: (lambda f
: f
)
66 EOL
= LineEnd().suppress()
68 COMMENTLINE
= pythonStyleComment
+ EOL
70 REAL
= Combine((INTEGER
+ Optional('.' + Optional(INTEGER
))) ^
('.' + INTEGER
))
71 SIGNED_REAL
= Combine(Optional(Word('-+')) + REAL
)
72 UDEV_TAG
= Word(string
.ascii_uppercase
, alphanums
+ '_')
74 # Those patterns are used in type-specific matches
75 TYPES
= {'mouse': ('usb', 'bluetooth', 'ps2', '*'),
76 'evdev': ('name', 'atkbd', 'input'),
78 'id-input': ('modalias'),
79 'touchpad': ('i8042', 'rmi', 'bluetooth', 'usb'),
80 'joystick': ('i8042', 'rmi', 'bluetooth', 'usb'),
81 'keyboard': ('name', ),
82 'sensor': ('modalias',
87 'proximity-palmrest-left',
88 'proximity-palmrest-right',
93 'proximity-wifi-left',
94 'proximity-wifi-right',
96 'ieee1394-unit-function' : ('node', ),
100 # Patterns that are used to set general properties on a device
101 GENERAL_MATCHES
= {'acpi',
111 def upperhex_word(length
):
112 return Word(nums
+ 'ABCDEF', exact
=length
)
116 ParserElement
.setDefaultWhitespaceChars('')
118 prefix
= Or(category
+ ':' + Or(conn
) + ':'
119 for category
, conn
in TYPES
.items())
121 matchline_typed
= Combine(prefix
+ Word(printables
+ ' ' + '®'))
122 matchline_general
= Combine(Or(GENERAL_MATCHES
) + ':' + Word(printables
+ ' ' + '®'))
123 matchline
= (matchline_typed | matchline_general
) + EOL
125 propertyline
= (White(' ', exact
=1).suppress() +
126 Combine(UDEV_TAG
- '=' - Optional(Word(alphanums
+ '_=:@*.!-;, "/'))
127 - Optional(pythonStyleComment
)) +
129 propertycomment
= White(' ', exact
=1) + pythonStyleComment
+ EOL
131 group
= (OneOrMore(matchline('MATCHES*') ^ COMMENTLINE
.suppress()) -
132 OneOrMore(propertyline('PROPERTIES*') ^ propertycomment
.suppress()) -
133 (EMPTYLINE ^
stringEnd()).suppress())
134 commentgroup
= OneOrMore(COMMENTLINE
).suppress() - EMPTYLINE
.suppress()
136 grammar
= OneOrMore(Group(group
)('GROUPS*') ^ commentgroup
) + stringEnd()
141 def property_grammar():
142 ParserElement
.setDefaultWhitespaceChars(' ')
144 dpi_setting
= Group(Optional('*')('DEFAULT') + INTEGER('DPI') + Optional(Suppress('@') + INTEGER('HZ')))('SETTINGS*')
145 mount_matrix_row
= SIGNED_REAL
+ ',' + SIGNED_REAL
+ ',' + SIGNED_REAL
146 mount_matrix
= Group(mount_matrix_row
+ ';' + mount_matrix_row
+ ';' + mount_matrix_row
)('MOUNT_MATRIX')
147 xkb_setting
= Optional(Word(alphanums
+ '+-/@._'))
148 id_input_setting
= Optional(Or((Literal('0'), Literal('1'))))
150 # Although this set doesn't cover all of characters in database entries, it's enough for test targets.
151 name_literal
= Word(printables
+ ' ')
153 props
= (('MOUSE_DPI', Group(OneOrMore(dpi_setting
))),
154 ('MOUSE_WHEEL_CLICK_ANGLE', INTEGER
),
155 ('MOUSE_WHEEL_CLICK_ANGLE_HORIZONTAL', INTEGER
),
156 ('MOUSE_WHEEL_CLICK_COUNT', INTEGER
),
157 ('MOUSE_WHEEL_CLICK_COUNT_HORIZONTAL', INTEGER
),
158 ('ID_AUTOSUSPEND', Or((Literal('0'), Literal('1')))),
159 ('ID_AUTOSUSPEND_DELAY_MS', INTEGER
),
160 ('ID_AV_PRODUCTION_CONTROLLER', Or((Literal('0'), Literal('1')))),
161 ('ID_PERSIST', Or((Literal('0'), Literal('1')))),
162 ('ID_PDA', Or((Literal('0'), Literal('1')))),
163 ('ID_INPUT', id_input_setting
),
164 ('ID_INPUT_ACCELEROMETER', id_input_setting
),
165 ('ID_INPUT_JOYSTICK', id_input_setting
),
166 ('ID_INPUT_KEY', id_input_setting
),
167 ('ID_INPUT_KEYBOARD', id_input_setting
),
168 ('ID_INPUT_MOUSE', id_input_setting
),
169 ('ID_INPUT_POINTINGSTICK', id_input_setting
),
170 ('ID_INPUT_SWITCH', id_input_setting
),
171 ('ID_INPUT_TABLET', id_input_setting
),
172 ('ID_INPUT_TABLET_PAD', id_input_setting
),
173 ('ID_INPUT_TOUCHPAD', id_input_setting
),
174 ('ID_INPUT_TOUCHSCREEN', id_input_setting
),
175 ('ID_INPUT_TRACKBALL', id_input_setting
),
176 ('ID_SIGNAL_ANALYZER', Or((Literal('0'), Literal('1')))),
177 ('POINTINGSTICK_SENSITIVITY', INTEGER
),
178 ('ID_INPUT_JOYSTICK_INTEGRATION', Or(('internal', 'external'))),
179 ('ID_INPUT_TOUCHPAD_INTEGRATION', Or(('internal', 'external'))),
180 ('XKB_FIXED_LAYOUT', xkb_setting
),
181 ('XKB_FIXED_VARIANT', xkb_setting
),
182 ('XKB_FIXED_MODEL', xkb_setting
),
183 ('KEYBOARD_LED_NUMLOCK', Literal('0')),
184 ('KEYBOARD_LED_CAPSLOCK', Literal('0')),
185 ('ACCEL_MOUNT_MATRIX', mount_matrix
),
186 ('ACCEL_LOCATION', Or(('display', 'base'))),
187 ('PROXIMITY_NEAR_LEVEL', INTEGER
),
188 ('IEEE1394_UNIT_FUNCTION_MIDI', Or((Literal('0'), Literal('1')))),
189 ('IEEE1394_UNIT_FUNCTION_AUDIO', Or((Literal('0'), Literal('1')))),
190 ('IEEE1394_UNIT_FUNCTION_VIDEO', Or((Literal('0'), Literal('1')))),
191 ('ID_VENDOR_FROM_DATABASE', name_literal
),
192 ('ID_MODEL_FROM_DATABASE', name_literal
),
193 ('ID_TAG_MASTER_OF_SEAT', Literal('1')),
194 ('ID_INFRARED_CAMERA', Or((Literal('0'), Literal('1')))),
195 ('ID_CAMERA_DIRECTION', Or(('front', 'rear'))),
196 ('SOUND_FORM_FACTOR', Or(('internal', 'webcam', 'speaker', 'headphone', 'headset', 'handset', 'microphone'))),
198 fixed_props
= [Literal(name
)('NAME') - Suppress('=') - val('VALUE')
199 for name
, val
in props
]
200 kbd_props
= [Regex(r
'KEYBOARD_KEY_[0-9a-f]+')('NAME')
202 ('!' ^
(Optional('!') - Word(alphanums
+ '_')))('VALUE')
204 abs_props
= [Regex(r
'EVDEV_ABS_[0-9a-f]{2}')('NAME')
206 Word('-' + nums
+ ':')('VALUE')
209 grammar
= Or(fixed_props
+ kbd_props
+ abs_props
) + EOL
214 def error(fmt
, *args
, **kwargs
):
217 print(fmt
.format(*args
, **kwargs
))
219 def convert_properties(group
):
220 matches
= [m
[0] for m
in group
.MATCHES
]
221 props
= [p
[0] for p
in group
.PROPERTIES
]
222 return matches
, props
225 grammar
= hwdb_grammar()
227 with
open(fname
, 'r', encoding
='UTF-8') as f
:
228 parsed
= grammar
.parseFile(f
)
229 except ParseBaseException
as e
:
230 error('Cannot parse {}: {}', fname
, e
)
232 return [convert_properties(g
) for g
in parsed
.GROUPS
]
234 def check_matches(groups
):
235 matches
= sum((group
[0] for group
in groups
), [])
237 # This is a partial check. The other cases could be also done, but those
238 # two are most commonly wrong.
239 grammars
= { 'usb' : 'v' + upperhex_word(4) + Optional('p' + upperhex_word(4) + Optional(':')) + '*',
240 'pci' : 'v' + upperhex_word(8) + Optional('d' + upperhex_word(8) + Optional(':')) + '*',
243 for match
in matches
:
244 prefix
, rest
= match
.split(':', maxsplit
=1)
245 gr
= grammars
.get(prefix
)
247 # we check this first to provide an easy error message
248 if rest
[-1] not in '*:':
249 error('pattern {} does not end with "*" or ":"', match
)
253 except ParseBaseException
as e
:
254 error('Pattern {!r} is invalid: {}', rest
, e
)
259 for match
in matches
:
261 error('Match {!r} is duplicated', match
)
264 def check_one_default(prop
, settings
):
265 defaults
= [s
for s
in settings
if s
.DEFAULT
]
266 if len(defaults
) > 1:
267 error('More than one star entry: {!r}', prop
)
269 def check_one_mount_matrix(prop
, value
):
270 numbers
= [s
for s
in value
if s
not in {';', ','}]
271 if len(numbers
) != 9:
272 error('Wrong accel matrix: {!r}', prop
)
274 numbers
= [abs(float(number
)) for number
in numbers
]
276 error('Wrong accel matrix: {!r}', prop
)
277 bad_x
, bad_y
, bad_z
= max(numbers
[0:3]) == 0, max(numbers
[3:6]) == 0, max(numbers
[6:9]) == 0
278 if bad_x
or bad_y
or bad_z
:
279 error('Mount matrix is all zero in {} row: {!r}',
280 'x' if bad_x
else ('y' if bad_y
else 'z'),
283 def check_one_keycode(value
):
284 if value
!= '!' and ecodes
is not None:
285 key
= 'KEY_' + value
.upper()
286 if not (key
in ecodes
or
287 value
.upper() in ecodes
or
288 # new keys added in kernel 5.5
289 'KBD_LCD_MENU' in key
):
290 error('Keycode {} unknown', key
)
292 def check_wheel_clicks(properties
):
293 pairs
= (('MOUSE_WHEEL_CLICK_COUNT_HORIZONTAL', 'MOUSE_WHEEL_CLICK_COUNT'),
294 ('MOUSE_WHEEL_CLICK_ANGLE_HORIZONTAL', 'MOUSE_WHEEL_CLICK_ANGLE'),
295 ('MOUSE_WHEEL_CLICK_COUNT_HORIZONTAL', 'MOUSE_WHEEL_CLICK_ANGLE_HORIZONTAL'),
296 ('MOUSE_WHEEL_CLICK_COUNT', 'MOUSE_WHEEL_CLICK_ANGLE'))
298 if pair
[0] in properties
and pair
[1] not in properties
:
299 error('{} requires {} to be specified', *pair
)
301 def check_properties(groups
):
302 grammar
= property_grammar()
303 for _
, props
in groups
:
307 prop
= prop
.partition('#')[0].rstrip()
309 parsed
= grammar
.parseString(prop
)
310 except ParseBaseException
:
311 error('Failed to parse: {!r}', prop
)
313 # print('{!r}'.format(parsed))
314 if parsed
.NAME
in seen_props
:
315 error('Property {} is duplicated', parsed
.NAME
)
316 seen_props
[parsed
.NAME
] = parsed
.VALUE
317 if parsed
.NAME
== 'MOUSE_DPI':
318 check_one_default(prop
, parsed
.VALUE
.SETTINGS
)
319 elif parsed
.NAME
== 'ACCEL_MOUNT_MATRIX':
320 check_one_mount_matrix(prop
, parsed
.VALUE
)
321 elif parsed
.NAME
.startswith('KEYBOARD_KEY_'):
322 val
= parsed
.VALUE
if isinstance(parsed
.VALUE
, str) else parsed
.VALUE
[0]
323 check_one_keycode(val
)
325 check_wheel_clicks(seen_props
)
327 def print_summary(fname
, groups
):
328 n_matches
= sum(len(matches
) for matches
, props
in groups
)
329 n_props
= sum(len(props
) for matches
, props
in groups
)
330 print(f
'{fname}: {len(groups)} match groups, {n_matches} matches, {n_props} properties')
332 if n_matches
== 0 or n_props
== 0:
333 error(f
'{fname}: no matches or props')
335 if __name__
== '__main__':
336 args
= sys
.argv
[1:] or sorted(glob
.glob(os
.path
.dirname(sys
.argv
[0]) + '/[678][0-9]-*.hwdb'))
339 groups
= parse(fname
)
340 print_summary(fname
, groups
)
341 check_matches(groups
)
342 check_properties(groups
)