Amazing-Python-Scripts

Форк
0
88 строк · 3.0 Кб
1
import shlex
2

3
from cecmap.commands import Command
4
from cecmap.keycodes import KEYCODES
5

6

7
class Config:
8

9
    def __init__(self, keycodes=KEYCODES):
10
        self.keycodes = keycodes.copy()
11
        self.bindings = {'*': {}}
12
        self.mode = None
13
        self.modes = []
14

15
    def bind(self, keybindings):
16
        """Set keybindings according to mode."""
17
        for mode, bindings in keybindings.items():
18
            if mode != '*':
19
                if self.mode is None:
20
                    self.mode = mode
21
                if mode not in self.modes:
22
                    self.modes.append(mode)
23
                    self.bindings[mode] = {}
24
            self.bindings[mode].update(bindings)
25

26
    def keybinding(self, mode, keycode):
27
        """Get command associated to keycode in current mode."""
28
        default = self.bindings['*'].get(keycode)
29
        handler = self.bindings[mode].get(keycode, default)
30
        return handler
31

32
    def load(self, parser, client):
33
        """
34
        Load keycodes and keybindings from config parser.
35

36
        Returns a new ``Config`` object that is a copy of this config merged
37
        with the loaded settings.
38

39
        See the ``cecmap/config/default.cfg`` file for example.
40
        """
41
        keycodes = self.keycodes.copy()
42
        modes = {}
43

44
        if parser.has_section('keycode'):
45
            section = parser['keycode']
46
            for name, value in section.items():
47
                if not value.isnumeric():
48
                    raise ValueError(
49
                        "Invalid key code for {}: {!r}".format(name, value))
50
                keycodes[name] = int(value)
51

52
        for section in parser.sections():
53
            if section.lower().startswith('mode.'):
54
                mode_name = section[len('mode.'):]
55
                modes[mode_name] = parser.items(section)
56
            elif section != 'keycode':
57
                print("Warning: Unused section in config file:", section)
58

59
        all_modes = set(self.modes) | set(modes)
60
        keybindings = {mode: {} for mode in modes}
61

62
        for mode, items in modes.items():
63
            for key, binding in items:
64
                command, *args = shlex.split(binding)
65

66
                if key.isnumeric():
67
                    keycode = int(key)
68
                elif key in keycodes:
69
                    keycode = keycodes[key]
70
                else:
71
                    raise ValueError("Undefined key: {!r}".format(key))
72

73
                if command == 'switch' and args and args[0] not in all_modes:
74
                    raise ValueError("Unknown mode: {!r}".format(args[0]))
75

76
                if command in Command.commands:
77
                    command = Command.commands[command](client, *args)
78
                else:
79
                    raise ValueError(
80
                        "Invalid command: {!r} = {!r}".format(key, binding))
81

82
                keybindings[mode][keycode] = command
83

84
        config = Config()
85
        config.keycodes = keycodes
86
        config.bind(self.bindings)
87
        config.bind(keybindings)
88
        return config
89

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.