]> git.ipfire.org Git - thirdparty/systemd.git/blobdiff - hwdb.d/parse_hwdb.py
install-file: make fs_make_very_read_only() static
[thirdparty/systemd.git] / hwdb.d / parse_hwdb.py
index dea71acfe93309f96928ad2676b1c19eda68a9e0..4c970dcbc80d7c0679cc0e5da1404519c7c85611 100755 (executable)
@@ -1,4 +1,6 @@
 #!/usr/bin/env python3
+# pylint: disable=line-too-long,invalid-name,global-statement,redefined-outer-name
+# pylint: disable=missing-function-docstring,missing-class-docstring,missing-module-docstring
 # SPDX-License-Identifier: MIT
 #
 # This file is distributed under the MIT license, see below.
@@ -33,11 +35,22 @@ try:
                            OneOrMore, Combine, Or, Optional, Suppress, Group,
                            nums, alphanums, printables,
                            stringEnd, pythonStyleComment,
-                           ParseBaseException, __diag__)
+                           ParseBaseException)
 except ImportError:
     print('pyparsing is not available')
     sys.exit(77)
 
+try:
+    from pyparsing import __diag__
+
+    __diag__.warn_multiple_tokens_in_named_alternation = True
+    __diag__.warn_ungrouped_named_tokens_in_collection = True
+    __diag__.warn_name_set_on_empty_Forward = True
+    __diag__.warn_on_multiple_string_args_to_oneof = True
+    __diag__.enable_debug_on_named_expressions = True
+except ImportError:
+    pass
+
 try:
     from evdev.ecodes import ecodes
 except ImportError:
@@ -50,12 +63,6 @@ except ImportError:
     # don't do caching on old python
     lru_cache = lambda: (lambda f: f)
 
-__diag__.warn_multiple_tokens_in_named_alternation = True
-__diag__.warn_ungrouped_named_tokens_in_collection = True
-__diag__.warn_name_set_on_empty_Forward = True
-__diag__.warn_on_multiple_string_args_to_oneof = True
-__diag__.enable_debug_on_named_expressions = True
-
 EOL = LineEnd().suppress()
 EMPTYLINE = LineEnd()
 COMMENTLINE = pythonStyleComment + EOL
@@ -72,8 +79,22 @@ TYPES = {'mouse':    ('usb', 'bluetooth', 'ps2', '*'),
          'touchpad': ('i8042', 'rmi', 'bluetooth', 'usb'),
          'joystick': ('i8042', 'rmi', 'bluetooth', 'usb'),
          'keyboard': ('name', ),
-         'sensor':   ('modalias', ),
+         'sensor':   ('modalias',
+                      'accel-base',
+                      'accel-display',
+                      'accel-camera',
+                      'proximity-palmrest',
+                      'proximity-palmrest-left',
+                      'proximity-palmrest-right',
+                      'proximity-lap',
+                      'proximity-wifi',
+                      'proximity-lte',
+                      'proximity-wifi-lte',
+                      'proximity-wifi-left',
+                      'proximity-wifi-right',
+                      ),
          'ieee1394-unit-function' : ('node', ),
+         'camera':   ('usb'),
         }
 
 # Patterns that are used to set general properties on a device
@@ -120,10 +141,11 @@ def hwdb_grammar():
 def property_grammar():
     ParserElement.setDefaultWhitespaceChars(' ')
 
-    dpi_setting = Group(Optional('*')('DEFAULT') + INTEGER('DPI') + Suppress('@') + INTEGER('HZ'))('SETTINGS*')
+    dpi_setting = Group(Optional('*')('DEFAULT') + INTEGER('DPI') + Optional(Suppress('@') + INTEGER('HZ')))('SETTINGS*')
     mount_matrix_row = SIGNED_REAL + ',' + SIGNED_REAL + ',' + SIGNED_REAL
     mount_matrix = Group(mount_matrix_row + ';' + mount_matrix_row + ';' + mount_matrix_row)('MOUNT_MATRIX')
     xkb_setting = Optional(Word(alphanums + '+-/@._'))
+    id_input_setting = Optional(Or((Literal('0'), Literal('1'))))
 
     # Although this set doesn't cover all of characters in database entries, it's enough for test targets.
     name_literal = Word(printables + ' ')
@@ -134,22 +156,25 @@ def property_grammar():
              ('MOUSE_WHEEL_CLICK_COUNT', INTEGER),
              ('MOUSE_WHEEL_CLICK_COUNT_HORIZONTAL', INTEGER),
              ('ID_AUTOSUSPEND', Or((Literal('0'), Literal('1')))),
-             ('ID_INPUT', Or((Literal('0'), Literal('1')))),
-             ('ID_INPUT_ACCELEROMETER', Or((Literal('0'), Literal('1')))),
-             ('ID_INPUT_JOYSTICK', Or((Literal('0'), Literal('1')))),
-             ('ID_INPUT_KEY', Or((Literal('0'), Literal('1')))),
-             ('ID_INPUT_KEYBOARD', Or((Literal('0'), Literal('1')))),
-             ('ID_INPUT_MOUSE', Or((Literal('0'), Literal('1')))),
-             ('ID_INPUT_POINTINGSTICK', Or((Literal('0'), Literal('1')))),
-             ('ID_INPUT_SWITCH', Or((Literal('0'), Literal('1')))),
-             ('ID_INPUT_TABLET', Or((Literal('0'), Literal('1')))),
-             ('ID_INPUT_TABLET_PAD', Or((Literal('0'), Literal('1')))),
-             ('ID_INPUT_TOUCHPAD', Or((Literal('0'), Literal('1')))),
-             ('ID_INPUT_TOUCHSCREEN', Or((Literal('0'), Literal('1')))),
-             ('ID_INPUT_TRACKBALL', Or((Literal('0'), Literal('1')))),
+             ('ID_AUTOSUSPEND_DELAY_MS', INTEGER),
+             ('ID_AV_PRODUCTION_CONTROLLER', Or((Literal('0'), Literal('1')))),
+             ('ID_PERSIST', Or((Literal('0'), Literal('1')))),
+             ('ID_PDA', Or((Literal('0'), Literal('1')))),
+             ('ID_INPUT', id_input_setting),
+             ('ID_INPUT_ACCELEROMETER', id_input_setting),
+             ('ID_INPUT_JOYSTICK', id_input_setting),
+             ('ID_INPUT_KEY', id_input_setting),
+             ('ID_INPUT_KEYBOARD', id_input_setting),
+             ('ID_INPUT_MOUSE', id_input_setting),
+             ('ID_INPUT_POINTINGSTICK', id_input_setting),
+             ('ID_INPUT_SWITCH', id_input_setting),
+             ('ID_INPUT_TABLET', id_input_setting),
+             ('ID_INPUT_TABLET_PAD', id_input_setting),
+             ('ID_INPUT_TOUCHPAD', id_input_setting),
+             ('ID_INPUT_TOUCHSCREEN', id_input_setting),
+             ('ID_INPUT_TRACKBALL', id_input_setting),
              ('ID_SIGNAL_ANALYZER', Or((Literal('0'), Literal('1')))),
              ('POINTINGSTICK_SENSITIVITY', INTEGER),
-             ('POINTINGSTICK_CONST_ACCEL', REAL),
              ('ID_INPUT_JOYSTICK_INTEGRATION', Or(('internal', 'external'))),
              ('ID_INPUT_TOUCHPAD_INTEGRATION', Or(('internal', 'external'))),
              ('XKB_FIXED_LAYOUT', xkb_setting),
@@ -166,6 +191,9 @@ def property_grammar():
              ('ID_VENDOR_FROM_DATABASE', name_literal),
              ('ID_MODEL_FROM_DATABASE', name_literal),
              ('ID_TAG_MASTER_OF_SEAT', Literal('1')),
+             ('ID_INFRARED_CAMERA', Or((Literal('0'), Literal('1')))),
+             ('ID_CAMERA_DIRECTION', Or(('front', 'rear'))),
+             ('SOUND_FORM_FACTOR', Or(('internal', 'webcam', 'speaker', 'headphone', 'headset', 'handset', 'microphone'))),
             )
     fixed_props = [Literal(name)('NAME') - Suppress('=') - val('VALUE')
                    for name, val in props]
@@ -175,7 +203,7 @@ def property_grammar():
                 ]
     abs_props = [Regex(r'EVDEV_ABS_[0-9a-f]{2}')('NAME')
                  - Suppress('=') -
-                 Word(nums + ':')('VALUE')
+                 Word('-' + nums + ':')('VALUE')
                 ]
 
     grammar = Or(fixed_props + kbd_props + abs_props) + EOL
@@ -208,21 +236,23 @@ def check_matches(groups):
 
     # This is a partial check. The other cases could be also done, but those
     # two are most commonly wrong.
-    grammars = { 'usb' : 'v' + upperhex_word(4) + Optional('p' + upperhex_word(4)),
-                 'pci' : 'v' + upperhex_word(8) + Optional('d' + upperhex_word(8)),
+    grammars = { 'usb' : 'v' + upperhex_word(4) + Optional('p' + upperhex_word(4) + Optional(':')) + '*',
+                 'pci' : 'v' + upperhex_word(8) + Optional('d' + upperhex_word(8) + Optional(':')) + '*',
     }
 
     for match in matches:
         prefix, rest = match.split(':', maxsplit=1)
         gr = grammars.get(prefix)
         if gr:
+            # we check this first to provide an easy error message
+            if rest[-1] not in '*:':
+                error('pattern {} does not end with "*" or ":"', match)
+
             try:
                 gr.parseString(rest)
             except ParseBaseException as e:
                 error('Pattern {!r} is invalid: {}', rest, e)
                 continue
-            if rest[-1] not in '*:':
-                error('pattern {} does not end with "*" or ":"', match)
 
     matches.sort()
     prev = None
@@ -250,7 +280,7 @@ def check_one_mount_matrix(prop, value):
               'x' if bad_x else ('y' if bad_y else 'z'),
               prop)
 
-def check_one_keycode(prop, value):
+def check_one_keycode(value):
     if value != '!' and ecodes is not None:
         key = 'KEY_' + value.upper()
         if not (key in ecodes or
@@ -270,14 +300,14 @@ def check_wheel_clicks(properties):
 
 def check_properties(groups):
     grammar = property_grammar()
-    for matches, props in groups:
+    for _, props in groups:
         seen_props = {}
         for prop in props:
             # print('--', prop)
             prop = prop.partition('#')[0].rstrip()
             try:
                 parsed = grammar.parseString(prop)
-            except ParseBaseException as e:
+            except ParseBaseException:
                 error('Failed to parse: {!r}', prop)
                 continue
             # print('{!r}'.format(parsed))
@@ -290,18 +320,17 @@ def check_properties(groups):
                 check_one_mount_matrix(prop, parsed.VALUE)
             elif parsed.NAME.startswith('KEYBOARD_KEY_'):
                 val = parsed.VALUE if isinstance(parsed.VALUE, str) else parsed.VALUE[0]
-                check_one_keycode(prop, val)
+                check_one_keycode(val)
 
         check_wheel_clicks(seen_props)
 
 def print_summary(fname, groups):
     n_matches = sum(len(matches) for matches, props in groups)
     n_props = sum(len(props) for matches, props in groups)
-    print('{}: {} match groups, {} matches, {} properties'
-          .format(fname, len(groups), n_matches, n_props))
+    print(f'{fname}: {len(groups)} match groups, {n_matches} matches, {n_props} properties')
 
     if n_matches == 0 or n_props == 0:
-        error('{}: no matches or props'.format(fname))
+        error(f'{fname}: no matches or props')
 
 if __name__ == '__main__':
     args = sys.argv[1:] or sorted(glob.glob(os.path.dirname(sys.argv[0]) + '/[678][0-9]-*.hwdb'))