Skip to content

keys

KeyEvents

Key events handling class for processing keyboard input and converting to CDP format.

This class manages keyboard events and converts them into appropriate CDP commands. It handles ASCII characters, special keys, and modifier combinations.

Reference: https://stackoverflow.com/a/79194672

Source code in zendriver/core/keys.py
 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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
class KeyEvents:
    """
    Key events handling class for processing keyboard input and converting to CDP format.

    This class manages keyboard events and converts them into appropriate CDP commands.
    It handles ASCII characters, special keys, and modifier combinations.

    Reference: https://stackoverflow.com/a/79194672
    """

    @staticmethod
    def is_english_alphabet(char: str) -> bool:
        """
        Check if a character is an English alphabet letter (A-Z, a-z).

        Args:
            char: The character to check.

        Returns:
            True if the character is an English alphabet letter, False otherwise.
        """
        if char.isalpha() and char.isascii():
            if len(char) != 1:
                raise ValueError(
                    "Key must be a single ASCII character. If you want to send multiple characters, try using `KeyEvents.from_text` or `KeyEvents.from_mixed_input`."
                )

            return True
        return False

    # Class constants for character mappings
    NUM_SHIFT = ")!@#$%^&*("

    SPECIAL_CHAR_MAP = {
        ";": ("Semicolon", 186),
        "=": ("Equal", 187),
        ",": ("Comma", 188),
        "-": ("Minus", 189),
        ".": ("Period", 190),
        "/": ("Slash", 191),
        "`": ("Backquote", 192),
        "[": ("BracketLeft", 219),
        "\\": ("Backslash", 220),
        "]": ("BracketRight", 221),
        "'": ("Quote", 222),
    }

    SPECIAL_CHAR_SHIFT_MAP = {
        ":": ";",
        "+": "=",
        "<": ",",
        "_": "-",
        ">": ".",
        "?": "/",
        "~": "`",
        "{": "[",
        "|": "\\",
        "}": "]",
        '"': "'",
    }
    SPECIAL_CHAR_REVERSE_MAP = {v: k for k, v in SPECIAL_CHAR_SHIFT_MAP.items()}

    MODIFIER_KEYS = [
        SpecialKeys.SHIFT,
        SpecialKeys.ALT,
        SpecialKeys.CTRL,
        SpecialKeys.META,
    ]

    SPECIAL_KEY_CHAR_MAP = {
        SpecialKeys.SPACE: " ",
        SpecialKeys.ENTER: "\r",
        SpecialKeys.TAB: "\t",
    }

    class Payload(TypedDict):
        type_: str
        modifiers: int
        text: Optional[str]
        key: Optional[str]
        code: Optional[str]
        windows_virtual_key_code: Optional[int]
        native_virtual_key_code: Optional[int]

    def __init__(
        self,
        key: Union[str, SpecialKeys],
        modifiers: Union[KeyModifiers, int] = KeyModifiers.Default,
    ):
        """
        Initialize a KeyEvents instance.

        Args:
            key: The key to be processed (single character string or SpecialKeys enum)
            modifiers: Modifier keys to be applied (can be combined with bitwise OR)
        """

        # modifiers = modifiers
        self.key = key
        self.modifiers = modifiers

        self.code, self.keyCode = (
            self._handle_string_key_lookup(self.key)
            if isinstance(self.key, str)
            else self._handle_special_key_lookup(self.key)
        )

    def conv_to_str(self, specialKey_key: SpecialKeys) -> str:
        if specialKey_key == SpecialKeys.SPACE:
            return " "
        elif specialKey_key == SpecialKeys.ENTER:
            return "\n"
        elif specialKey_key == SpecialKeys.TAB:
            return "\t"
        raise ValueError(
            f"Cannot convert {specialKey_key} to string, only SPACE, ENTER and TAB are supported."
        )

    def _get_key_and_text(
        self, key_press_event: KeyPressEvent, modifiers: Union[KeyModifiers, int]
    ) -> Tuple[str, Optional[str]]:
        """
        Create the appropriate action for this key event.

        Args:
            key_press_event: The type of key press event to generate (Currently supported are `DOWN_AND_UP` and `CHAR`)
            modifiers: Modifier keys to apply

        Returns:
            Action object containing the processed key information

        Raises:
            ValueError: If key is invalid for CHAR event type
        """
        if key_press_event == KeyPressEvent.CHAR:
            if isinstance(self.key, SpecialKeys):
                self.key = self.conv_to_str(self.key)
            return self.key, self.key

        return self._build_action_data(modifiers)

    def _normalise_key(
        self, key: Union[str, SpecialKeys], modifiers: Union[KeyModifiers, int]
    ) -> Tuple[Union[str, SpecialKeys], Union[KeyModifiers, int]]:
        """
        Convert a shifted key to its non-shifted equivalent.

        Args:
            key: The key to convert (may be shifted)
            modifiers: Current modifier keys to apply

        Returns:
            The non-shifted equivalent of the key

        Raises:
            ValueError: If the key is not recognized or supported
        """
        lowercase_key: Optional[str] = None
        if isinstance(key, SpecialKeys):
            return key, modifiers  # all the special keys dont have shifted variants

        if key in self.NUM_SHIFT:
            modifiers |= KeyModifiers.Shift
            lowercase_key = str(self.NUM_SHIFT.index(key))
        elif key in self.SPECIAL_CHAR_SHIFT_MAP:
            modifiers |= KeyModifiers.Shift
            lowercase_key = self.SPECIAL_CHAR_SHIFT_MAP[key]
        elif KeyEvents.is_english_alphabet(key) and key.isupper():
            modifiers |= KeyModifiers.Shift
            lowercase_key = key.lower()
        elif key in "\n\r":
            return SpecialKeys.ENTER, modifiers
        elif key == "\t":
            return SpecialKeys.TAB, modifiers
        elif key == " ":
            return SpecialKeys.SPACE, modifiers

        if (
            modifiers != KeyModifiers.Default | KeyModifiers.Shift
            and lowercase_key is not None
        ):
            raise ValueError(
                f"Key '{key}' is not supported with modifiers {modifiers}."
            )

        if lowercase_key is None:
            return key, modifiers

        modifiers |= KeyModifiers.Shift
        return lowercase_key, modifiers

    def _to_basic_event(
        self,
        key_press_event: KeyPressEvent,
        modifiers: Union[KeyModifiers, int] = KeyModifiers.Default,
    ) -> "KeyEvents.Payload":
        """
        Convert the key event to a basic event format.
        Args:
            key_press_event: The type of key press event to generate
            modifiers: Modifier keys to apply
        Returns:
            A dictionary containing the basic event payload
        """

        key, text = self._get_key_and_text(key_press_event, modifiers)
        if key_press_event == KeyPressEvent.CHAR:
            if text is None:
                raise ValueError(
                    f"Key '{self.key}' is not supported for CHAR event type. Only single ASCII characters are allowed."
                )
            return self.Payload(
                type_=key_press_event.value,
                modifiers=modifiers,
                text=text,
                key=None,
                code=None,
                windows_virtual_key_code=None,
                native_virtual_key_code=None,
            )

        return self.Payload(
            type_=key_press_event.value,
            modifiers=modifiers,
            text=text,
            key=key,
            code=self.code,
            windows_virtual_key_code=self.keyCode,
            native_virtual_key_code=self.keyCode,
        )

    def to_cdp_events(
        self,
        key_press_event: KeyPressEvent,
        override_modifiers: Optional[Union[KeyModifiers, int]] = None,
    ) -> List["KeyEvents.Payload"]:
        """
        Convert the key event to CDP format.

        Args:
            key_press_event: The type of key press event to generate (Currently supported are `DOWN_AND_UP` and `CHAR`)
            override_modifiers: Optional modifiers to override the current ones

        Returns:
            List of dictionaries containing CDP `payload`
        """
        if isinstance(self.key, str):
            if emoji.is_emoji(self.key) or (
                self.key is not None and self.keyCode is None
            ):
                key_press_event = KeyPressEvent.CHAR

        match key_press_event:
            case (
                KeyPressEvent.KEY_DOWN
                | KeyPressEvent.RAW_KEY_DOWN
                | KeyPressEvent.KEY_UP
            ):
                raise NotImplementedError(
                    "Not supported by itself, use CHAR or DOWN_AND_UP instead."
                )

            case KeyPressEvent.CHAR:
                if (
                    not isinstance(self.key, str)
                    and self.key not in self.SPECIAL_KEY_CHAR_MAP.keys()
                ):
                    raise ValueError(
                        f"Key '{self.key}' is not supported for CHAR event type. Only str characters are allowed"
                    )
                return [self._to_basic_event(key_press_event)]

            case KeyPressEvent.DOWN_AND_UP:
                cur_modifier = (
                    self.modifiers if override_modifiers is None else override_modifiers
                )
                self.key, override_modifiers = self._normalise_key(
                    self.key, cur_modifier
                )
                return self.to_down_up_sequence(override_modifiers)

            case _:
                raise ValueError(f"Unsupported key press event type: {key_press_event}")

    def _handle_string_key_lookup(
        self, key: str
    ) -> Tuple[Optional[str], Optional[int]]:
        """Handle string key lookup logic."""

        if KeyEvents.is_english_alphabet(key):
            return f"Key{key.upper()}", ord(key.upper())
        elif key.isdigit() or key in KeyEvents.NUM_SHIFT:
            digit = (
                str(KeyEvents.NUM_SHIFT.index(key))
                if key in KeyEvents.NUM_SHIFT
                else key
            )
            return f"Digit{digit}", ord(digit)
        elif key in "\n\r":
            return SpecialKeys.ENTER.value
        elif key == "\t":
            return SpecialKeys.TAB.value
        elif key == " ":
            return SpecialKeys.SPACE.value
        elif key in KeyEvents.SPECIAL_CHAR_MAP:
            return KeyEvents.SPECIAL_CHAR_MAP[key]
        elif key in KeyEvents.SPECIAL_CHAR_SHIFT_MAP.keys():
            return KeyEvents.SPECIAL_CHAR_MAP[KeyEvents.SPECIAL_CHAR_SHIFT_MAP[key]]

        return None, None  # non english characters

    def _handle_special_key_lookup(self, key: SpecialKeys) -> Tuple[str, int]:
        """Handle special key lookup logic."""
        if key in KeyEvents.MODIFIER_KEYS:
            return f"{key.value[0]}Left", key.value[1]
        return key.value

    def _decompose_modifiers(
        self, modifiers: Union[KeyModifiers, int]
    ) -> List[Tuple[SpecialKeys, KeyModifiers]]:
        """
        Extract individual modifier keys from a modifier bitmask.

        Args:
            modifiers: The modifier bitmask to process

        Returns:
            List of tuples containing (SpecialKey, KeyModifier) pairs
        """
        if modifiers == KeyModifiers.Default:
            return []

        modifier_keys = []
        if modifiers & KeyModifiers.Alt:
            modifier_keys.append((SpecialKeys.ALT, KeyModifiers.Alt))
        if modifiers & KeyModifiers.Ctrl:
            modifier_keys.append((SpecialKeys.CTRL, KeyModifiers.Ctrl))
        if modifiers & KeyModifiers.Meta:
            modifier_keys.append((SpecialKeys.META, KeyModifiers.Meta))
        if modifiers & KeyModifiers.Shift:
            modifier_keys.append((SpecialKeys.SHIFT, KeyModifiers.Shift))

        if not modifier_keys:
            raise ValueError("No valid modifier keys found.")

        return modifier_keys

    def _build_action_data(
        self, modifiers: Union[KeyModifiers, int]
    ) -> Tuple[str, Optional[str]]:
        """
        Build the data needed for a key press action.

        Args:
            key: The key to process
            modifiers: Modifier keys to apply

        Returns:
            Tuple containing (text, key, code, windowsVirtualKeyCode, nativeVirtualKeyCode)
        """

        # Handle printable characters with potential shift modifier
        if isinstance(self.key, str):
            return self._handle_printable_char(self.key, modifiers)

        # Handle modifier keys
        if self.key in KeyEvents.SPECIAL_KEY_CHAR_MAP:
            # Special keys that are not modifiers
            return (
                self.SPECIAL_KEY_CHAR_MAP[self.key],
                self.SPECIAL_KEY_CHAR_MAP[self.key],
            )

        # Handle other special keys
        return self.key.value[0], None

    def _handle_printable_char(
        self, key: str, modifiers: Union[KeyModifiers, int]
    ) -> Tuple[str, str]:
        """Handle printable character with potential shift modifier."""
        if modifiers != KeyModifiers.Shift:
            return key, key

        # Apply shift transformation
        if KeyEvents.is_english_alphabet(key):
            shifted_key = key.upper()
        elif key.isdigit():
            shifted_key = KeyEvents.NUM_SHIFT[int(key)]
        else:
            shifted_key = self.SPECIAL_CHAR_REVERSE_MAP[key]

        return shifted_key, shifted_key

    def to_down_up_sequence(
        self, modifiers: Union[KeyModifiers, int]
    ) -> List["KeyEvents.Payload"]:
        """
        Create a complete key down/up sequence with modifiers.

        This method generates a sequence of key events that properly handles
        modifier keys by sending modifier key down events before the main key,
        and modifier key up events after the main key.

        Args:
            modifiers: Modifier keys to apply

        Returns:
            List of `KeyEvents.Payload` containing the complete key event sequence
        """
        # Validate that all required properties are set
        events: List[KeyEvents.Payload] = []
        modifier_events = [
            (KeyEvents(key), _modifier)
            for key, _modifier in self._decompose_modifiers(modifiers)
        ]
        is_modifier_key = any(key.key == self.key for key, _ in modifier_events)

        # 1: Add modifier key down events
        current_modifiers = 0
        for modifier_key, modifier_flag in modifier_events:
            current_modifiers |= modifier_flag  # done like this since all the keys are not pressed or processed at once
            modifier_payload = modifier_key._to_basic_event(
                KeyPressEvent.KEY_DOWN, current_modifiers
            )
            events.append(modifier_payload)

        # 2: Add main key down (if itself is not a modifier key)
        if not is_modifier_key:
            events.append(
                self._to_basic_event(KeyPressEvent.KEY_DOWN, current_modifiers)
            )

        # 3: Add modifier key up events (in reverse order)
        for modifier_key, modifier_flag in modifier_events:
            current_modifiers &= ~modifier_flag
            # remove the modifier from current modifiers (the same idea)
            modifier_payload = modifier_key._to_basic_event(
                KeyPressEvent.KEY_UP, current_modifiers
            )
            events.append(modifier_payload)

        # 4: Add main key up (if itself is not a modifier key)
        if not is_modifier_key:
            events.append(self._to_basic_event(KeyPressEvent.KEY_UP, current_modifiers))

        return events

    @classmethod
    def from_text(
        cls, text: str, ascii_keypress: KeyPressEvent
    ) -> List["KeyEvents.Payload"]:
        """
        Create KeyEvents payloads from a text string, automatically handling special characters and graphemes.

        Args:
            text: The text to convert to key events
            ascii_keypress: The key press event to use for the ASCII characters (default is DOWN_AND_UP)

        Returns:
            List of KeyEvents.Payload objects ready for CDP
        """

        all_payload: List[KeyEvents.Payload] = []

        for grapheme_char in grapheme.graphemes(text):
            if grapheme_char is None or grapheme_char == "":
                continue

            # Handle special characters
            key_events: KeyEvents
            if grapheme_char in ["\n", "\r"]:
                key_events = cls(SpecialKeys.ENTER)
            elif grapheme_char == "\t":
                key_events = cls(SpecialKeys.TAB)
            elif grapheme_char == " ":
                key_events = cls(SpecialKeys.SPACE)
            else:
                key_events = cls(grapheme_char)

            all_payload.extend(
                key_events.to_cdp_events(
                    KeyPressEvent.CHAR
                    if emoji.is_emoji(grapheme_char)
                    else ascii_keypress
                )
            )

        return all_payload

    @classmethod
    def from_mixed_input(
        cls,
        input_sequence: List[
            Union[str, SpecialKeys, Tuple[Union[str, SpecialKeys], KeyModifiers]]
        ],
        ascii_keypress: KeyPressEvent = KeyPressEvent.DOWN_AND_UP,
    ) -> List["KeyEvents.Payload"]:
        """
        Create KeyEvents payloads from a mixed sequence of strings, special keys, and key+modifier combinations.

        Args:
            input_sequence: List containing:
                - str: Regular text (will be processed character by character)
                - SpecialKeys: Special keys (will use DOWN_AND_UP)
                - Tuple[key, modifiers]: Key with modifiers (will use DOWN_AND_UP)
            - priority_keypress: The key press event to use for the ascii characters (default is DOWN_AND_UP)

        Returns:
            List of KeyEvents.Payload objects ready for CDP

        Example:
            >>> KeyEvents.from_mixed_input([
            ...     "Hello ",
            ...     SpecialKeys.ENTER,
            ...     "World",
            ...     SpecialKeys.ARROW_DOWN,
            ...     ("a", KeyModifiers.Ctrl),  # Ctrl+A
            ...     ("c", KeyModifiers.Ctrl),  # Ctrl+C
            ... ],
            ... ascii_keypress=KeyPressEvent.DOWN_AND_UP)
        """
        all_payload: List[KeyEvents.Payload] = []

        for item in input_sequence:
            if isinstance(item, str):
                # Process string character by character
                all_payload.extend(cls.from_text(item, ascii_keypress))
            elif isinstance(item, SpecialKeys):
                # Process special key
                key_events = cls(item)
                all_payload.extend(key_events.to_cdp_events(KeyPressEvent.DOWN_AND_UP))
            elif isinstance(item, tuple) and len(item) == 2:
                # Process key with modifiers
                key, modifiers = item
                key_events = cls(key, modifiers)
                all_payload.extend(key_events.to_cdp_events(KeyPressEvent.DOWN_AND_UP))
            else:
                raise ValueError(f"Unsupported input type: {type(item)}")

        return all_payload

MODIFIER_KEYS = [SpecialKeys.SHIFT, SpecialKeys.ALT, SpecialKeys.CTRL, SpecialKeys.META] class-attribute instance-attribute

NUM_SHIFT = ')!@#$%^&*(' class-attribute instance-attribute

SPECIAL_CHAR_MAP = {';': ('Semicolon', 186), '=': ('Equal', 187), ',': ('Comma', 188), '-': ('Minus', 189), '.': ('Period', 190), '/': ('Slash', 191), '`': ('Backquote', 192), '[': ('BracketLeft', 219), '\\': ('Backslash', 220), ']': ('BracketRight', 221), "'": ('Quote', 222)} class-attribute instance-attribute

SPECIAL_CHAR_REVERSE_MAP = {v: kfor (k, v) in SPECIAL_CHAR_SHIFT_MAP.items()} class-attribute instance-attribute

SPECIAL_CHAR_SHIFT_MAP = {':': ';', '+': '=', '<': ',', '_': '-', '>': '.', '?': '/', '~': '`', '{': '[', '|': '\\', '}': ']', '"': "'"} class-attribute instance-attribute

SPECIAL_KEY_CHAR_MAP = {SpecialKeys.SPACE: ' ', SpecialKeys.ENTER: '\r', SpecialKeys.TAB: '\t'} class-attribute instance-attribute

key = key instance-attribute

modifiers = modifiers instance-attribute

Payload

Bases: TypedDict

Source code in zendriver/core/keys.py
class Payload(TypedDict):
    type_: str
    modifiers: int
    text: Optional[str]
    key: Optional[str]
    code: Optional[str]
    windows_virtual_key_code: Optional[int]
    native_virtual_key_code: Optional[int]

code: Optional[str] instance-attribute

key: Optional[str] instance-attribute

modifiers: int instance-attribute

native_virtual_key_code: Optional[int] instance-attribute

text: Optional[str] instance-attribute

type_: str instance-attribute

windows_virtual_key_code: Optional[int] instance-attribute

__init__(key, modifiers=KeyModifiers.Default)

Initialize a KeyEvents instance.

Args: key: The key to be processed (single character string or SpecialKeys enum) modifiers: Modifier keys to be applied (can be combined with bitwise OR)

Source code in zendriver/core/keys.py
def __init__(
    self,
    key: Union[str, SpecialKeys],
    modifiers: Union[KeyModifiers, int] = KeyModifiers.Default,
):
    """
    Initialize a KeyEvents instance.

    Args:
        key: The key to be processed (single character string or SpecialKeys enum)
        modifiers: Modifier keys to be applied (can be combined with bitwise OR)
    """

    # modifiers = modifiers
    self.key = key
    self.modifiers = modifiers

    self.code, self.keyCode = (
        self._handle_string_key_lookup(self.key)
        if isinstance(self.key, str)
        else self._handle_special_key_lookup(self.key)
    )

conv_to_str(specialKey_key)

Source code in zendriver/core/keys.py
def conv_to_str(self, specialKey_key: SpecialKeys) -> str:
    if specialKey_key == SpecialKeys.SPACE:
        return " "
    elif specialKey_key == SpecialKeys.ENTER:
        return "\n"
    elif specialKey_key == SpecialKeys.TAB:
        return "\t"
    raise ValueError(
        f"Cannot convert {specialKey_key} to string, only SPACE, ENTER and TAB are supported."
    )

from_mixed_input(input_sequence, ascii_keypress=KeyPressEvent.DOWN_AND_UP) classmethod

Create KeyEvents payloads from a mixed sequence of strings, special keys, and key+modifier combinations.

Args: input_sequence: List containing: - str: Regular text (will be processed character by character) - SpecialKeys: Special keys (will use DOWN_AND_UP) - Tuple[key, modifiers]: Key with modifiers (will use DOWN_AND_UP) - priority_keypress: The key press event to use for the ascii characters (default is DOWN_AND_UP)

Returns: List of KeyEvents.Payload objects ready for CDP

Example: >>> KeyEvents.from_mixed_input([ ... "Hello ", ... SpecialKeys.ENTER, ... "World", ... SpecialKeys.ARROW_DOWN, ... ("a", KeyModifiers.Ctrl), # Ctrl+A ... ("c", KeyModifiers.Ctrl), # Ctrl+C ... ], ... ascii_keypress=KeyPressEvent.DOWN_AND_UP)

Source code in zendriver/core/keys.py
@classmethod
def from_mixed_input(
    cls,
    input_sequence: List[
        Union[str, SpecialKeys, Tuple[Union[str, SpecialKeys], KeyModifiers]]
    ],
    ascii_keypress: KeyPressEvent = KeyPressEvent.DOWN_AND_UP,
) -> List["KeyEvents.Payload"]:
    """
    Create KeyEvents payloads from a mixed sequence of strings, special keys, and key+modifier combinations.

    Args:
        input_sequence: List containing:
            - str: Regular text (will be processed character by character)
            - SpecialKeys: Special keys (will use DOWN_AND_UP)
            - Tuple[key, modifiers]: Key with modifiers (will use DOWN_AND_UP)
        - priority_keypress: The key press event to use for the ascii characters (default is DOWN_AND_UP)

    Returns:
        List of KeyEvents.Payload objects ready for CDP

    Example:
        >>> KeyEvents.from_mixed_input([
        ...     "Hello ",
        ...     SpecialKeys.ENTER,
        ...     "World",
        ...     SpecialKeys.ARROW_DOWN,
        ...     ("a", KeyModifiers.Ctrl),  # Ctrl+A
        ...     ("c", KeyModifiers.Ctrl),  # Ctrl+C
        ... ],
        ... ascii_keypress=KeyPressEvent.DOWN_AND_UP)
    """
    all_payload: List[KeyEvents.Payload] = []

    for item in input_sequence:
        if isinstance(item, str):
            # Process string character by character
            all_payload.extend(cls.from_text(item, ascii_keypress))
        elif isinstance(item, SpecialKeys):
            # Process special key
            key_events = cls(item)
            all_payload.extend(key_events.to_cdp_events(KeyPressEvent.DOWN_AND_UP))
        elif isinstance(item, tuple) and len(item) == 2:
            # Process key with modifiers
            key, modifiers = item
            key_events = cls(key, modifiers)
            all_payload.extend(key_events.to_cdp_events(KeyPressEvent.DOWN_AND_UP))
        else:
            raise ValueError(f"Unsupported input type: {type(item)}")

    return all_payload

from_text(text, ascii_keypress) classmethod

Create KeyEvents payloads from a text string, automatically handling special characters and graphemes.

Args: text: The text to convert to key events ascii_keypress: The key press event to use for the ASCII characters (default is DOWN_AND_UP)

Returns: List of KeyEvents.Payload objects ready for CDP

Source code in zendriver/core/keys.py
@classmethod
def from_text(
    cls, text: str, ascii_keypress: KeyPressEvent
) -> List["KeyEvents.Payload"]:
    """
    Create KeyEvents payloads from a text string, automatically handling special characters and graphemes.

    Args:
        text: The text to convert to key events
        ascii_keypress: The key press event to use for the ASCII characters (default is DOWN_AND_UP)

    Returns:
        List of KeyEvents.Payload objects ready for CDP
    """

    all_payload: List[KeyEvents.Payload] = []

    for grapheme_char in grapheme.graphemes(text):
        if grapheme_char is None or grapheme_char == "":
            continue

        # Handle special characters
        key_events: KeyEvents
        if grapheme_char in ["\n", "\r"]:
            key_events = cls(SpecialKeys.ENTER)
        elif grapheme_char == "\t":
            key_events = cls(SpecialKeys.TAB)
        elif grapheme_char == " ":
            key_events = cls(SpecialKeys.SPACE)
        else:
            key_events = cls(grapheme_char)

        all_payload.extend(
            key_events.to_cdp_events(
                KeyPressEvent.CHAR
                if emoji.is_emoji(grapheme_char)
                else ascii_keypress
            )
        )

    return all_payload

is_english_alphabet(char) staticmethod

Check if a character is an English alphabet letter (A-Z, a-z).

Args: char: The character to check.

Returns: True if the character is an English alphabet letter, False otherwise.

Source code in zendriver/core/keys.py
@staticmethod
def is_english_alphabet(char: str) -> bool:
    """
    Check if a character is an English alphabet letter (A-Z, a-z).

    Args:
        char: The character to check.

    Returns:
        True if the character is an English alphabet letter, False otherwise.
    """
    if char.isalpha() and char.isascii():
        if len(char) != 1:
            raise ValueError(
                "Key must be a single ASCII character. If you want to send multiple characters, try using `KeyEvents.from_text` or `KeyEvents.from_mixed_input`."
            )

        return True
    return False

to_cdp_events(key_press_event, override_modifiers=None)

Convert the key event to CDP format.

Args: key_press_event: The type of key press event to generate (Currently supported are DOWN_AND_UP and CHAR) override_modifiers: Optional modifiers to override the current ones

Returns: List of dictionaries containing CDP payload

Source code in zendriver/core/keys.py
def to_cdp_events(
    self,
    key_press_event: KeyPressEvent,
    override_modifiers: Optional[Union[KeyModifiers, int]] = None,
) -> List["KeyEvents.Payload"]:
    """
    Convert the key event to CDP format.

    Args:
        key_press_event: The type of key press event to generate (Currently supported are `DOWN_AND_UP` and `CHAR`)
        override_modifiers: Optional modifiers to override the current ones

    Returns:
        List of dictionaries containing CDP `payload`
    """
    if isinstance(self.key, str):
        if emoji.is_emoji(self.key) or (
            self.key is not None and self.keyCode is None
        ):
            key_press_event = KeyPressEvent.CHAR

    match key_press_event:
        case (
            KeyPressEvent.KEY_DOWN
            | KeyPressEvent.RAW_KEY_DOWN
            | KeyPressEvent.KEY_UP
        ):
            raise NotImplementedError(
                "Not supported by itself, use CHAR or DOWN_AND_UP instead."
            )

        case KeyPressEvent.CHAR:
            if (
                not isinstance(self.key, str)
                and self.key not in self.SPECIAL_KEY_CHAR_MAP.keys()
            ):
                raise ValueError(
                    f"Key '{self.key}' is not supported for CHAR event type. Only str characters are allowed"
                )
            return [self._to_basic_event(key_press_event)]

        case KeyPressEvent.DOWN_AND_UP:
            cur_modifier = (
                self.modifiers if override_modifiers is None else override_modifiers
            )
            self.key, override_modifiers = self._normalise_key(
                self.key, cur_modifier
            )
            return self.to_down_up_sequence(override_modifiers)

        case _:
            raise ValueError(f"Unsupported key press event type: {key_press_event}")

to_down_up_sequence(modifiers)

Create a complete key down/up sequence with modifiers.

This method generates a sequence of key events that properly handles modifier keys by sending modifier key down events before the main key, and modifier key up events after the main key.

Args: modifiers: Modifier keys to apply

Returns: List of KeyEvents.Payload containing the complete key event sequence

Source code in zendriver/core/keys.py
def to_down_up_sequence(
    self, modifiers: Union[KeyModifiers, int]
) -> List["KeyEvents.Payload"]:
    """
    Create a complete key down/up sequence with modifiers.

    This method generates a sequence of key events that properly handles
    modifier keys by sending modifier key down events before the main key,
    and modifier key up events after the main key.

    Args:
        modifiers: Modifier keys to apply

    Returns:
        List of `KeyEvents.Payload` containing the complete key event sequence
    """
    # Validate that all required properties are set
    events: List[KeyEvents.Payload] = []
    modifier_events = [
        (KeyEvents(key), _modifier)
        for key, _modifier in self._decompose_modifiers(modifiers)
    ]
    is_modifier_key = any(key.key == self.key for key, _ in modifier_events)

    # 1: Add modifier key down events
    current_modifiers = 0
    for modifier_key, modifier_flag in modifier_events:
        current_modifiers |= modifier_flag  # done like this since all the keys are not pressed or processed at once
        modifier_payload = modifier_key._to_basic_event(
            KeyPressEvent.KEY_DOWN, current_modifiers
        )
        events.append(modifier_payload)

    # 2: Add main key down (if itself is not a modifier key)
    if not is_modifier_key:
        events.append(
            self._to_basic_event(KeyPressEvent.KEY_DOWN, current_modifiers)
        )

    # 3: Add modifier key up events (in reverse order)
    for modifier_key, modifier_flag in modifier_events:
        current_modifiers &= ~modifier_flag
        # remove the modifier from current modifiers (the same idea)
        modifier_payload = modifier_key._to_basic_event(
            KeyPressEvent.KEY_UP, current_modifiers
        )
        events.append(modifier_payload)

    # 4: Add main key up (if itself is not a modifier key)
    if not is_modifier_key:
        events.append(self._to_basic_event(KeyPressEvent.KEY_UP, current_modifiers))

    return events

KeyModifiers

Bases: IntEnum

Enumeration of keyboard modifiers used in key events. For multiple modifiers, use bitwise OR to combine them.

Example: >>> modifiers = KeyModifiers.Alt | KeyModifiers.Shift # Combines Alt and Shift modifiers

Source code in zendriver/core/keys.py
class KeyModifiers(IntEnum):
    """Enumeration of keyboard modifiers used in key events.
    For multiple modifiers, use bitwise OR to combine them.

       Example:
        >>> modifiers = KeyModifiers.Alt | KeyModifiers.Shift # Combines Alt and Shift modifiers
    """

    Default = 0
    Alt = 1
    Ctrl = 2
    Meta = 4
    Shift = 8

Alt = 1 class-attribute instance-attribute

Ctrl = 2 class-attribute instance-attribute

Default = 0 class-attribute instance-attribute

Meta = 4 class-attribute instance-attribute

Shift = 8 class-attribute instance-attribute

KeyPressEvent

Bases: str, Enum

Enumeration of different types of key press events.

Source code in zendriver/core/keys.py
class KeyPressEvent(str, Enum):
    """Enumeration of different types of key press events."""

    KEY_DOWN = "keyDown"
    KEY_UP = "keyUp"
    RAW_KEY_DOWN = "rawKeyDown"

    CHAR = "char"
    """Directly sends ASCII character to the element. Cannot send non-ASCII characters and commands (Ctrl+A, etc.)"""
    DOWN_AND_UP = "downAndUp"
    """Way to give both key down and up events in one go for non-ASCII characters, **not standard implementation**"""

CHAR = 'char' class-attribute instance-attribute

Directly sends ASCII character to the element. Cannot send non-ASCII characters and commands (Ctrl+A, etc.)

DOWN_AND_UP = 'downAndUp' class-attribute instance-attribute

Way to give both key down and up events in one go for non-ASCII characters, not standard implementation

KEY_DOWN = 'keyDown' class-attribute instance-attribute

KEY_UP = 'keyUp' class-attribute instance-attribute

RAW_KEY_DOWN = 'rawKeyDown' class-attribute instance-attribute

SpecialKeys

Bases: Enum

Enumeration of special keys with their corresponding names and key codes.

Source code in zendriver/core/keys.py
class SpecialKeys(Enum):
    """Enumeration of special keys with their corresponding names and key codes."""

    SPACE = (" ", 32)  # space key
    ENTER = ("Enter", 13)
    TAB = ("Tab", 9)

    BACKSPACE = ("Backspace", 8)
    ESCAPE = ("Escape", 27)
    DELETE = ("Delete", 46)
    ARROW_LEFT = ("ArrowLeft", 37)
    ARROW_UP = ("ArrowUp", 38)
    ARROW_RIGHT = ("ArrowRight", 39)
    ARROW_DOWN = ("ArrowDown", 40)
    SHIFT = ("Shift", 16)  # internal use only
    ALT = ("Alt", 18)  # internal use only
    CTRL = ("Control", 17)  # internal use only
    META = ("Meta", 91)  # internal use only

ALT = ('Alt', 18) class-attribute instance-attribute

ARROW_DOWN = ('ArrowDown', 40) class-attribute instance-attribute

ARROW_LEFT = ('ArrowLeft', 37) class-attribute instance-attribute

ARROW_RIGHT = ('ArrowRight', 39) class-attribute instance-attribute

ARROW_UP = ('ArrowUp', 38) class-attribute instance-attribute

BACKSPACE = ('Backspace', 8) class-attribute instance-attribute

CTRL = ('Control', 17) class-attribute instance-attribute

DELETE = ('Delete', 46) class-attribute instance-attribute

ENTER = ('Enter', 13) class-attribute instance-attribute

ESCAPE = ('Escape', 27) class-attribute instance-attribute

META = ('Meta', 91) class-attribute instance-attribute

SHIFT = ('Shift', 16) class-attribute instance-attribute

SPACE = (' ', 32) class-attribute instance-attribute

TAB = ('Tab', 9) class-attribute instance-attribute