This repository has been archived by the owner on May 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
internals.py
300 lines (209 loc) · 7.26 KB
/
internals.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
import re
from PyQt5 import QtCore
from abc import abstractmethod, ABCMeta
from inspect import isclass
from types import MethodType
from anki.hooks import wrap
from anki.lang import _
from aqt.utils import showWarning
try:
from_utf8 = QtCore.QString.fromUtf8
except AttributeError:
from_utf8 = lambda s: s
def alert(info):
showWarning(_(info))
class PropertyDescriptor:
def __init__(self, value=None):
self.value = value
def __get__(self, obj, obj_type):
return self.value(obj)
def __set__(self, obj, value):
self.value = value
class css(PropertyDescriptor):
is_css = True
def abstract_property(func):
return property(abstractmethod(func))
def snake_case(camel_case):
return re.sub('(?!^)([A-Z]+)', r'_\1', camel_case).lower()
class AbstractRegisteringType(ABCMeta):
def __init__(cls, name, bases, attributes):
super().__init__(name, bases, attributes)
if not hasattr(cls, 'members'):
cls.members = set()
cls.members.add(cls)
cls.members -= set(bases)
class SnakeNameMixin:
@property
def name(self):
"""Nice looking internal identifier."""
return snake_case(
self.__class__.__name__
if hasattr(self, '__class__')
else self.__name__
)
class MenuAction(SnakeNameMixin, metaclass=AbstractRegisteringType):
def __init__(self, app):
self.app = app
@abstract_property
def label(self):
"""Text to be shown on menu entry.
Use ampersand ('&') to set that the following
character as a menu shortcut for this action.
Use double ampersand ('&&') to display '&'.
"""
pass
@property
def checkable(self):
"""Add 'checked' sign to menu item when active"""
return False
@property
def shortcut(self):
"""Global shortcut for this menu action.
The shortcut should be given as a string, like:
shortcut = 'Ctrl+n'
"""
return None
@abstractmethod
def action(self):
"""Callback for menu entry clicking/selection"""
pass
@property
def is_checked(self):
"""Should the menu item be checked (assuming that checkable is True)"""
return bool(self.value)
def singleton_creator(old_creator):
def one_to_rule_them_all(cls, *args, **kwargs):
if not cls.instance:
cls.instance = old_creator(cls)
return cls.instance
return one_to_rule_them_all
class SingletonMetaclass(AbstractRegisteringType):
def __init__(cls, name, bases, attributes):
super().__init__(name, bases, attributes)
# singleton
cls.instance = None
old_creator = cls.__new__
cls.__new__ = singleton_creator(old_creator)
class RequiringMixin:
require = set()
dependencies = {}
def __init__(self, app):
for requirement in self.require:
instance = requirement(app)
key = instance.name
self.dependencies[key] = instance
def __getattr__(self, attr):
if attr in self.dependencies:
return self.dependencies[attr]
class Setting(RequiringMixin, SnakeNameMixin, metaclass=SingletonMetaclass):
def __init__(self, app):
RequiringMixin.__init__(self, app)
self.default_value = self.value
self.app = app
@abstract_property
def value(self):
"""Default value of a setting"""
pass
def on_load(self):
"""Callback called after loading of initial value"""
pass
def on_save(self):
pass
def reset(self):
if hasattr(self, 'default_value'):
self.value = self.default_value
def decorate_or_call(operator):
def outer_decorator(method_or_value):
if callable(method_or_value):
method = method_or_value
def decorated(*args, **kwargs):
return operator(method(*args, **kwargs))
return decorated
else:
return operator(method_or_value)
return outer_decorator
@decorate_or_call
def style_tag(some_css):
return '<style>' + some_css + '</style>'
@decorate_or_call
def percent_escaped(text):
return text.replace('%', '%%')
class StylerMetaclass(AbstractRegisteringType):
"""
Makes classes: singletons, work with:
wraps,
appends_in_night_mode,
replaces_in_night_mode
decorators
"""
def __init__(cls, name, bases, attributes):
super().__init__(name, bases, attributes)
# singleton
cls.instance = None
old_creator = cls.__new__
cls.__new__ = singleton_creator(old_creator)
# additions and replacements
cls.additions = {}
cls.replacements = {}
target = attributes.get('target', None)
def callback_maker(wrapper):
def raw_new(*args, **kwargs):
return wrapper(cls.instance, *args, **kwargs)
return raw_new
for key, attr in attributes.items():
if key == 'init':
key = '__init__'
if hasattr(attr, 'wraps'):
if not target:
raise Exception(f'Asked to wrap "{key}" but target of {name} not defined')
original = getattr(target, key)
if type(original) is MethodType:
original = original.__func__
new = wrap(original, callback_maker(attr), attr.position)
# for classes, just add the new function, it will be bound later,
# but instances need some more work: we need to bind!
if not isclass(target):
new = MethodType(new, target)
cls.replacements[key] = new
if hasattr(attr, 'appends_in_night_mode'):
if not target:
raise Exception(f'Asked to replace "{key}" but target of {name} not defined')
cls.additions[key] = attr
if hasattr(attr, 'replaces_in_night_mode'):
if not target:
raise Exception(f'Asked to replace "{key}" but target of {name} not defined')
cls.replacements[key] = attr
# TODO: invoke and cache css?
if hasattr(attr, 'is_css'):
pass
def wraps(method=None, position='after'):
"""Decorator for methods extending Anki QT methods.
Args:
method: a function method to be wrapped
position: after, before or around
"""
if not method:
def wraps_inner(func):
return wraps(method=func, position=position)
return wraps_inner
method.wraps = True
method.position = position
return method
class appends_in_night_mode(PropertyDescriptor):
appends_in_night_mode = True
class replaces_in_night_mode(PropertyDescriptor):
replaces_in_night_mode = True
def move_args_to_kwargs(original_function, args, kwargs):
args = list(args)
import inspect
signature = inspect.signature(original_function)
i = 0
for name, parameter in signature.parameters.items():
if i >= len(args):
break
if parameter.default is not inspect._empty:
value = args.pop(i)
kwargs[name] = value
else:
i += 1
return args, kwargs