ZTWHHH commited on
Commit
581842d
·
verified ·
1 Parent(s): 663aae8

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. llava/lib/python3.10/collections/__init__.py +1556 -0
  2. llava/lib/python3.10/collections/__pycache__/abc.cpython-310.pyc +0 -0
  3. llava/lib/python3.10/collections/abc.py +3 -0
  4. llava/lib/python3.10/distutils/command/__pycache__/__init__.cpython-310.pyc +0 -0
  5. llava/lib/python3.10/distutils/command/__pycache__/bdist.cpython-310.pyc +0 -0
  6. llava/lib/python3.10/distutils/command/__pycache__/bdist_msi.cpython-310.pyc +0 -0
  7. llava/lib/python3.10/distutils/command/__pycache__/bdist_rpm.cpython-310.pyc +0 -0
  8. llava/lib/python3.10/distutils/command/__pycache__/build.cpython-310.pyc +0 -0
  9. llava/lib/python3.10/distutils/command/__pycache__/build_ext.cpython-310.pyc +0 -0
  10. llava/lib/python3.10/distutils/command/__pycache__/build_py.cpython-310.pyc +0 -0
  11. llava/lib/python3.10/distutils/command/__pycache__/build_scripts.cpython-310.pyc +0 -0
  12. llava/lib/python3.10/distutils/command/__pycache__/clean.cpython-310.pyc +0 -0
  13. llava/lib/python3.10/distutils/command/__pycache__/config.cpython-310.pyc +0 -0
  14. llava/lib/python3.10/distutils/command/__pycache__/install.cpython-310.pyc +0 -0
  15. llava/lib/python3.10/distutils/command/__pycache__/install_data.cpython-310.pyc +0 -0
  16. llava/lib/python3.10/distutils/command/__pycache__/install_egg_info.cpython-310.pyc +0 -0
  17. llava/lib/python3.10/distutils/command/__pycache__/install_headers.cpython-310.pyc +0 -0
  18. llava/lib/python3.10/distutils/command/__pycache__/install_lib.cpython-310.pyc +0 -0
  19. llava/lib/python3.10/distutils/command/__pycache__/install_scripts.cpython-310.pyc +0 -0
  20. llava/lib/python3.10/distutils/command/__pycache__/register.cpython-310.pyc +0 -0
  21. llava/lib/python3.10/distutils/command/__pycache__/upload.cpython-310.pyc +0 -0
  22. llava/lib/python3.10/distutils/command/bdist.py +141 -0
  23. llava/lib/python3.10/distutils/command/bdist_msi.py +747 -0
  24. llava/lib/python3.10/distutils/command/build.py +157 -0
  25. llava/lib/python3.10/distutils/command/build_clib.py +209 -0
  26. llava/lib/python3.10/distutils/command/build_scripts.py +160 -0
  27. llava/lib/python3.10/distutils/command/check.py +148 -0
  28. llava/lib/python3.10/distutils/command/install.py +679 -0
  29. llava/lib/python3.10/distutils/command/install_data.py +79 -0
  30. llava/lib/python3.10/distutils/command/install_egg_info.py +77 -0
  31. llava/lib/python3.10/distutils/command/upload.py +215 -0
  32. llava/lib/python3.10/json/__pycache__/__init__.cpython-310.pyc +0 -0
  33. llava/lib/python3.10/json/__pycache__/decoder.cpython-310.pyc +0 -0
  34. llava/lib/python3.10/json/__pycache__/encoder.cpython-310.pyc +0 -0
  35. llava/lib/python3.10/json/__pycache__/scanner.cpython-310.pyc +0 -0
  36. llava/lib/python3.10/json/__pycache__/tool.cpython-310.pyc +0 -0
  37. llava/lib/python3.10/json/encoder.py +442 -0
  38. llava/lib/python3.10/tkinter/__init__.py +0 -0
  39. llava/lib/python3.10/tkinter/__main__.py +7 -0
  40. llava/lib/python3.10/tkinter/colorchooser.py +86 -0
  41. llava/lib/python3.10/tkinter/commondialog.py +53 -0
  42. llava/lib/python3.10/tkinter/constants.py +110 -0
  43. llava/lib/python3.10/tkinter/dialog.py +49 -0
  44. llava/lib/python3.10/tkinter/dnd.py +324 -0
  45. llava/lib/python3.10/tkinter/filedialog.py +493 -0
  46. llava/lib/python3.10/tkinter/font.py +239 -0
  47. llava/lib/python3.10/tkinter/scrolledtext.py +56 -0
  48. llava/lib/python3.10/tkinter/simpledialog.py +441 -0
  49. llava/lib/python3.10/tkinter/ttk.py +1662 -0
  50. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_int_mm_cpu_dispatch.h +25 -0
llava/lib/python3.10/collections/__init__.py ADDED
@@ -0,0 +1,1556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''This module implements specialized container datatypes providing
2
+ alternatives to Python's general purpose built-in containers, dict,
3
+ list, set, and tuple.
4
+
5
+ * namedtuple factory function for creating tuple subclasses with named fields
6
+ * deque list-like container with fast appends and pops on either end
7
+ * ChainMap dict-like class for creating a single view of multiple mappings
8
+ * Counter dict subclass for counting hashable objects
9
+ * OrderedDict dict subclass that remembers the order entries were added
10
+ * defaultdict dict subclass that calls a factory function to supply missing values
11
+ * UserDict wrapper around dictionary objects for easier dict subclassing
12
+ * UserList wrapper around list objects for easier list subclassing
13
+ * UserString wrapper around string objects for easier string subclassing
14
+
15
+ '''
16
+
17
+ __all__ = [
18
+ 'ChainMap',
19
+ 'Counter',
20
+ 'OrderedDict',
21
+ 'UserDict',
22
+ 'UserList',
23
+ 'UserString',
24
+ 'defaultdict',
25
+ 'deque',
26
+ 'namedtuple',
27
+ ]
28
+
29
+ import _collections_abc
30
+ import sys as _sys
31
+
32
+ from itertools import chain as _chain
33
+ from itertools import repeat as _repeat
34
+ from itertools import starmap as _starmap
35
+ from keyword import iskeyword as _iskeyword
36
+ from operator import eq as _eq
37
+ from operator import itemgetter as _itemgetter
38
+ from reprlib import recursive_repr as _recursive_repr
39
+ from _weakref import proxy as _proxy
40
+
41
+ try:
42
+ from _collections import deque
43
+ except ImportError:
44
+ pass
45
+ else:
46
+ _collections_abc.MutableSequence.register(deque)
47
+
48
+ try:
49
+ from _collections import defaultdict
50
+ except ImportError:
51
+ pass
52
+
53
+
54
+ ################################################################################
55
+ ### OrderedDict
56
+ ################################################################################
57
+
58
+ class _OrderedDictKeysView(_collections_abc.KeysView):
59
+
60
+ def __reversed__(self):
61
+ yield from reversed(self._mapping)
62
+
63
+ class _OrderedDictItemsView(_collections_abc.ItemsView):
64
+
65
+ def __reversed__(self):
66
+ for key in reversed(self._mapping):
67
+ yield (key, self._mapping[key])
68
+
69
+ class _OrderedDictValuesView(_collections_abc.ValuesView):
70
+
71
+ def __reversed__(self):
72
+ for key in reversed(self._mapping):
73
+ yield self._mapping[key]
74
+
75
+ class _Link(object):
76
+ __slots__ = 'prev', 'next', 'key', '__weakref__'
77
+
78
+ class OrderedDict(dict):
79
+ 'Dictionary that remembers insertion order'
80
+ # An inherited dict maps keys to values.
81
+ # The inherited dict provides __getitem__, __len__, __contains__, and get.
82
+ # The remaining methods are order-aware.
83
+ # Big-O running times for all methods are the same as regular dictionaries.
84
+
85
+ # The internal self.__map dict maps keys to links in a doubly linked list.
86
+ # The circular doubly linked list starts and ends with a sentinel element.
87
+ # The sentinel element never gets deleted (this simplifies the algorithm).
88
+ # The sentinel is in self.__hardroot with a weakref proxy in self.__root.
89
+ # The prev links are weakref proxies (to prevent circular references).
90
+ # Individual links are kept alive by the hard reference in self.__map.
91
+ # Those hard references disappear when a key is deleted from an OrderedDict.
92
+
93
+ def __init__(self, other=(), /, **kwds):
94
+ '''Initialize an ordered dictionary. The signature is the same as
95
+ regular dictionaries. Keyword argument order is preserved.
96
+ '''
97
+ try:
98
+ self.__root
99
+ except AttributeError:
100
+ self.__hardroot = _Link()
101
+ self.__root = root = _proxy(self.__hardroot)
102
+ root.prev = root.next = root
103
+ self.__map = {}
104
+ self.__update(other, **kwds)
105
+
106
+ def __setitem__(self, key, value,
107
+ dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link):
108
+ 'od.__setitem__(i, y) <==> od[i]=y'
109
+ # Setting a new item creates a new link at the end of the linked list,
110
+ # and the inherited dictionary is updated with the new key/value pair.
111
+ if key not in self:
112
+ self.__map[key] = link = Link()
113
+ root = self.__root
114
+ last = root.prev
115
+ link.prev, link.next, link.key = last, root, key
116
+ last.next = link
117
+ root.prev = proxy(link)
118
+ dict_setitem(self, key, value)
119
+
120
+ def __delitem__(self, key, dict_delitem=dict.__delitem__):
121
+ 'od.__delitem__(y) <==> del od[y]'
122
+ # Deleting an existing item uses self.__map to find the link which gets
123
+ # removed by updating the links in the predecessor and successor nodes.
124
+ dict_delitem(self, key)
125
+ link = self.__map.pop(key)
126
+ link_prev = link.prev
127
+ link_next = link.next
128
+ link_prev.next = link_next
129
+ link_next.prev = link_prev
130
+ link.prev = None
131
+ link.next = None
132
+
133
+ def __iter__(self):
134
+ 'od.__iter__() <==> iter(od)'
135
+ # Traverse the linked list in order.
136
+ root = self.__root
137
+ curr = root.next
138
+ while curr is not root:
139
+ yield curr.key
140
+ curr = curr.next
141
+
142
+ def __reversed__(self):
143
+ 'od.__reversed__() <==> reversed(od)'
144
+ # Traverse the linked list in reverse order.
145
+ root = self.__root
146
+ curr = root.prev
147
+ while curr is not root:
148
+ yield curr.key
149
+ curr = curr.prev
150
+
151
+ def clear(self):
152
+ 'od.clear() -> None. Remove all items from od.'
153
+ root = self.__root
154
+ root.prev = root.next = root
155
+ self.__map.clear()
156
+ dict.clear(self)
157
+
158
+ def popitem(self, last=True):
159
+ '''Remove and return a (key, value) pair from the dictionary.
160
+
161
+ Pairs are returned in LIFO order if last is true or FIFO order if false.
162
+ '''
163
+ if not self:
164
+ raise KeyError('dictionary is empty')
165
+ root = self.__root
166
+ if last:
167
+ link = root.prev
168
+ link_prev = link.prev
169
+ link_prev.next = root
170
+ root.prev = link_prev
171
+ else:
172
+ link = root.next
173
+ link_next = link.next
174
+ root.next = link_next
175
+ link_next.prev = root
176
+ key = link.key
177
+ del self.__map[key]
178
+ value = dict.pop(self, key)
179
+ return key, value
180
+
181
+ def move_to_end(self, key, last=True):
182
+ '''Move an existing element to the end (or beginning if last is false).
183
+
184
+ Raise KeyError if the element does not exist.
185
+ '''
186
+ link = self.__map[key]
187
+ link_prev = link.prev
188
+ link_next = link.next
189
+ soft_link = link_next.prev
190
+ link_prev.next = link_next
191
+ link_next.prev = link_prev
192
+ root = self.__root
193
+ if last:
194
+ last = root.prev
195
+ link.prev = last
196
+ link.next = root
197
+ root.prev = soft_link
198
+ last.next = link
199
+ else:
200
+ first = root.next
201
+ link.prev = root
202
+ link.next = first
203
+ first.prev = soft_link
204
+ root.next = link
205
+
206
+ def __sizeof__(self):
207
+ sizeof = _sys.getsizeof
208
+ n = len(self) + 1 # number of links including root
209
+ size = sizeof(self.__dict__) # instance dictionary
210
+ size += sizeof(self.__map) * 2 # internal dict and inherited dict
211
+ size += sizeof(self.__hardroot) * n # link objects
212
+ size += sizeof(self.__root) * n # proxy objects
213
+ return size
214
+
215
+ update = __update = _collections_abc.MutableMapping.update
216
+
217
+ def keys(self):
218
+ "D.keys() -> a set-like object providing a view on D's keys"
219
+ return _OrderedDictKeysView(self)
220
+
221
+ def items(self):
222
+ "D.items() -> a set-like object providing a view on D's items"
223
+ return _OrderedDictItemsView(self)
224
+
225
+ def values(self):
226
+ "D.values() -> an object providing a view on D's values"
227
+ return _OrderedDictValuesView(self)
228
+
229
+ __ne__ = _collections_abc.MutableMapping.__ne__
230
+
231
+ __marker = object()
232
+
233
+ def pop(self, key, default=__marker):
234
+ '''od.pop(k[,d]) -> v, remove specified key and return the corresponding
235
+ value. If key is not found, d is returned if given, otherwise KeyError
236
+ is raised.
237
+
238
+ '''
239
+ if key in self:
240
+ result = self[key]
241
+ del self[key]
242
+ return result
243
+ if default is self.__marker:
244
+ raise KeyError(key)
245
+ return default
246
+
247
+ def setdefault(self, key, default=None):
248
+ '''Insert key with a value of default if key is not in the dictionary.
249
+
250
+ Return the value for key if key is in the dictionary, else default.
251
+ '''
252
+ if key in self:
253
+ return self[key]
254
+ self[key] = default
255
+ return default
256
+
257
+ @_recursive_repr()
258
+ def __repr__(self):
259
+ 'od.__repr__() <==> repr(od)'
260
+ if not self:
261
+ return '%s()' % (self.__class__.__name__,)
262
+ return '%s(%r)' % (self.__class__.__name__, list(self.items()))
263
+
264
+ def __reduce__(self):
265
+ 'Return state information for pickling'
266
+ inst_dict = vars(self).copy()
267
+ for k in vars(OrderedDict()):
268
+ inst_dict.pop(k, None)
269
+ return self.__class__, (), inst_dict or None, None, iter(self.items())
270
+
271
+ def copy(self):
272
+ 'od.copy() -> a shallow copy of od'
273
+ return self.__class__(self)
274
+
275
+ @classmethod
276
+ def fromkeys(cls, iterable, value=None):
277
+ '''Create a new ordered dictionary with keys from iterable and values set to value.
278
+ '''
279
+ self = cls()
280
+ for key in iterable:
281
+ self[key] = value
282
+ return self
283
+
284
+ def __eq__(self, other):
285
+ '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
286
+ while comparison to a regular mapping is order-insensitive.
287
+
288
+ '''
289
+ if isinstance(other, OrderedDict):
290
+ return dict.__eq__(self, other) and all(map(_eq, self, other))
291
+ return dict.__eq__(self, other)
292
+
293
+ def __ior__(self, other):
294
+ self.update(other)
295
+ return self
296
+
297
+ def __or__(self, other):
298
+ if not isinstance(other, dict):
299
+ return NotImplemented
300
+ new = self.__class__(self)
301
+ new.update(other)
302
+ return new
303
+
304
+ def __ror__(self, other):
305
+ if not isinstance(other, dict):
306
+ return NotImplemented
307
+ new = self.__class__(other)
308
+ new.update(self)
309
+ return new
310
+
311
+
312
+ try:
313
+ from _collections import OrderedDict
314
+ except ImportError:
315
+ # Leave the pure Python version in place.
316
+ pass
317
+
318
+
319
+ ################################################################################
320
+ ### namedtuple
321
+ ################################################################################
322
+
323
+ try:
324
+ from _collections import _tuplegetter
325
+ except ImportError:
326
+ _tuplegetter = lambda index, doc: property(_itemgetter(index), doc=doc)
327
+
328
+ def namedtuple(typename, field_names, *, rename=False, defaults=None, module=None):
329
+ """Returns a new subclass of tuple with named fields.
330
+
331
+ >>> Point = namedtuple('Point', ['x', 'y'])
332
+ >>> Point.__doc__ # docstring for the new class
333
+ 'Point(x, y)'
334
+ >>> p = Point(11, y=22) # instantiate with positional args or keywords
335
+ >>> p[0] + p[1] # indexable like a plain tuple
336
+ 33
337
+ >>> x, y = p # unpack like a regular tuple
338
+ >>> x, y
339
+ (11, 22)
340
+ >>> p.x + p.y # fields also accessible by name
341
+ 33
342
+ >>> d = p._asdict() # convert to a dictionary
343
+ >>> d['x']
344
+ 11
345
+ >>> Point(**d) # convert from a dictionary
346
+ Point(x=11, y=22)
347
+ >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
348
+ Point(x=100, y=22)
349
+
350
+ """
351
+
352
+ # Validate the field names. At the user's option, either generate an error
353
+ # message or automatically replace the field name with a valid name.
354
+ if isinstance(field_names, str):
355
+ field_names = field_names.replace(',', ' ').split()
356
+ field_names = list(map(str, field_names))
357
+ typename = _sys.intern(str(typename))
358
+
359
+ if rename:
360
+ seen = set()
361
+ for index, name in enumerate(field_names):
362
+ if (not name.isidentifier()
363
+ or _iskeyword(name)
364
+ or name.startswith('_')
365
+ or name in seen):
366
+ field_names[index] = f'_{index}'
367
+ seen.add(name)
368
+
369
+ for name in [typename] + field_names:
370
+ if type(name) is not str:
371
+ raise TypeError('Type names and field names must be strings')
372
+ if not name.isidentifier():
373
+ raise ValueError('Type names and field names must be valid '
374
+ f'identifiers: {name!r}')
375
+ if _iskeyword(name):
376
+ raise ValueError('Type names and field names cannot be a '
377
+ f'keyword: {name!r}')
378
+
379
+ seen = set()
380
+ for name in field_names:
381
+ if name.startswith('_') and not rename:
382
+ raise ValueError('Field names cannot start with an underscore: '
383
+ f'{name!r}')
384
+ if name in seen:
385
+ raise ValueError(f'Encountered duplicate field name: {name!r}')
386
+ seen.add(name)
387
+
388
+ field_defaults = {}
389
+ if defaults is not None:
390
+ defaults = tuple(defaults)
391
+ if len(defaults) > len(field_names):
392
+ raise TypeError('Got more default values than field names')
393
+ field_defaults = dict(reversed(list(zip(reversed(field_names),
394
+ reversed(defaults)))))
395
+
396
+ # Variables used in the methods and docstrings
397
+ field_names = tuple(map(_sys.intern, field_names))
398
+ num_fields = len(field_names)
399
+ arg_list = ', '.join(field_names)
400
+ if num_fields == 1:
401
+ arg_list += ','
402
+ repr_fmt = '(' + ', '.join(f'{name}=%r' for name in field_names) + ')'
403
+ tuple_new = tuple.__new__
404
+ _dict, _tuple, _len, _map, _zip = dict, tuple, len, map, zip
405
+
406
+ # Create all the named tuple methods to be added to the class namespace
407
+
408
+ namespace = {
409
+ '_tuple_new': tuple_new,
410
+ '__builtins__': {},
411
+ '__name__': f'namedtuple_{typename}',
412
+ }
413
+ code = f'lambda _cls, {arg_list}: _tuple_new(_cls, ({arg_list}))'
414
+ __new__ = eval(code, namespace)
415
+ __new__.__name__ = '__new__'
416
+ __new__.__doc__ = f'Create new instance of {typename}({arg_list})'
417
+ if defaults is not None:
418
+ __new__.__defaults__ = defaults
419
+
420
+ @classmethod
421
+ def _make(cls, iterable):
422
+ result = tuple_new(cls, iterable)
423
+ if _len(result) != num_fields:
424
+ raise TypeError(f'Expected {num_fields} arguments, got {len(result)}')
425
+ return result
426
+
427
+ _make.__func__.__doc__ = (f'Make a new {typename} object from a sequence '
428
+ 'or iterable')
429
+
430
+ def _replace(self, /, **kwds):
431
+ result = self._make(_map(kwds.pop, field_names, self))
432
+ if kwds:
433
+ raise ValueError(f'Got unexpected field names: {list(kwds)!r}')
434
+ return result
435
+
436
+ _replace.__doc__ = (f'Return a new {typename} object replacing specified '
437
+ 'fields with new values')
438
+
439
+ def __repr__(self):
440
+ 'Return a nicely formatted representation string'
441
+ return self.__class__.__name__ + repr_fmt % self
442
+
443
+ def _asdict(self):
444
+ 'Return a new dict which maps field names to their values.'
445
+ return _dict(_zip(self._fields, self))
446
+
447
+ def __getnewargs__(self):
448
+ 'Return self as a plain tuple. Used by copy and pickle.'
449
+ return _tuple(self)
450
+
451
+ # Modify function metadata to help with introspection and debugging
452
+ for method in (
453
+ __new__,
454
+ _make.__func__,
455
+ _replace,
456
+ __repr__,
457
+ _asdict,
458
+ __getnewargs__,
459
+ ):
460
+ method.__qualname__ = f'{typename}.{method.__name__}'
461
+
462
+ # Build-up the class namespace dictionary
463
+ # and use type() to build the result class
464
+ class_namespace = {
465
+ '__doc__': f'{typename}({arg_list})',
466
+ '__slots__': (),
467
+ '_fields': field_names,
468
+ '_field_defaults': field_defaults,
469
+ '__new__': __new__,
470
+ '_make': _make,
471
+ '_replace': _replace,
472
+ '__repr__': __repr__,
473
+ '_asdict': _asdict,
474
+ '__getnewargs__': __getnewargs__,
475
+ '__match_args__': field_names,
476
+ }
477
+ for index, name in enumerate(field_names):
478
+ doc = _sys.intern(f'Alias for field number {index}')
479
+ class_namespace[name] = _tuplegetter(index, doc)
480
+
481
+ result = type(typename, (tuple,), class_namespace)
482
+
483
+ # For pickling to work, the __module__ variable needs to be set to the frame
484
+ # where the named tuple is created. Bypass this step in environments where
485
+ # sys._getframe is not defined (Jython for example) or sys._getframe is not
486
+ # defined for arguments greater than 0 (IronPython), or where the user has
487
+ # specified a particular module.
488
+ if module is None:
489
+ try:
490
+ module = _sys._getframe(1).f_globals.get('__name__', '__main__')
491
+ except (AttributeError, ValueError):
492
+ pass
493
+ if module is not None:
494
+ result.__module__ = module
495
+
496
+ return result
497
+
498
+
499
+ ########################################################################
500
+ ### Counter
501
+ ########################################################################
502
+
503
+ def _count_elements(mapping, iterable):
504
+ 'Tally elements from the iterable.'
505
+ mapping_get = mapping.get
506
+ for elem in iterable:
507
+ mapping[elem] = mapping_get(elem, 0) + 1
508
+
509
+ try: # Load C helper function if available
510
+ from _collections import _count_elements
511
+ except ImportError:
512
+ pass
513
+
514
+ class Counter(dict):
515
+ '''Dict subclass for counting hashable items. Sometimes called a bag
516
+ or multiset. Elements are stored as dictionary keys and their counts
517
+ are stored as dictionary values.
518
+
519
+ >>> c = Counter('abcdeabcdabcaba') # count elements from a string
520
+
521
+ >>> c.most_common(3) # three most common elements
522
+ [('a', 5), ('b', 4), ('c', 3)]
523
+ >>> sorted(c) # list all unique elements
524
+ ['a', 'b', 'c', 'd', 'e']
525
+ >>> ''.join(sorted(c.elements())) # list elements with repetitions
526
+ 'aaaaabbbbcccdde'
527
+ >>> sum(c.values()) # total of all counts
528
+ 15
529
+
530
+ >>> c['a'] # count of letter 'a'
531
+ 5
532
+ >>> for elem in 'shazam': # update counts from an iterable
533
+ ... c[elem] += 1 # by adding 1 to each element's count
534
+ >>> c['a'] # now there are seven 'a'
535
+ 7
536
+ >>> del c['b'] # remove all 'b'
537
+ >>> c['b'] # now there are zero 'b'
538
+ 0
539
+
540
+ >>> d = Counter('simsalabim') # make another counter
541
+ >>> c.update(d) # add in the second counter
542
+ >>> c['a'] # now there are nine 'a'
543
+ 9
544
+
545
+ >>> c.clear() # empty the counter
546
+ >>> c
547
+ Counter()
548
+
549
+ Note: If a count is set to zero or reduced to zero, it will remain
550
+ in the counter until the entry is deleted or the counter is cleared:
551
+
552
+ >>> c = Counter('aaabbc')
553
+ >>> c['b'] -= 2 # reduce the count of 'b' by two
554
+ >>> c.most_common() # 'b' is still in, but its count is zero
555
+ [('a', 3), ('c', 1), ('b', 0)]
556
+
557
+ '''
558
+ # References:
559
+ # http://en.wikipedia.org/wiki/Multiset
560
+ # http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html
561
+ # http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
562
+ # http://code.activestate.com/recipes/259174/
563
+ # Knuth, TAOCP Vol. II section 4.6.3
564
+
565
+ def __init__(self, iterable=None, /, **kwds):
566
+ '''Create a new, empty Counter object. And if given, count elements
567
+ from an input iterable. Or, initialize the count from another mapping
568
+ of elements to their counts.
569
+
570
+ >>> c = Counter() # a new, empty counter
571
+ >>> c = Counter('gallahad') # a new counter from an iterable
572
+ >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
573
+ >>> c = Counter(a=4, b=2) # a new counter from keyword args
574
+
575
+ '''
576
+ super().__init__()
577
+ self.update(iterable, **kwds)
578
+
579
+ def __missing__(self, key):
580
+ 'The count of elements not in the Counter is zero.'
581
+ # Needed so that self[missing_item] does not raise KeyError
582
+ return 0
583
+
584
+ def total(self):
585
+ 'Sum of the counts'
586
+ return sum(self.values())
587
+
588
+ def most_common(self, n=None):
589
+ '''List the n most common elements and their counts from the most
590
+ common to the least. If n is None, then list all element counts.
591
+
592
+ >>> Counter('abracadabra').most_common(3)
593
+ [('a', 5), ('b', 2), ('r', 2)]
594
+
595
+ '''
596
+ # Emulate Bag.sortedByCount from Smalltalk
597
+ if n is None:
598
+ return sorted(self.items(), key=_itemgetter(1), reverse=True)
599
+
600
+ # Lazy import to speedup Python startup time
601
+ import heapq
602
+ return heapq.nlargest(n, self.items(), key=_itemgetter(1))
603
+
604
+ def elements(self):
605
+ '''Iterator over elements repeating each as many times as its count.
606
+
607
+ >>> c = Counter('ABCABC')
608
+ >>> sorted(c.elements())
609
+ ['A', 'A', 'B', 'B', 'C', 'C']
610
+
611
+ # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1
612
+ >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
613
+ >>> product = 1
614
+ >>> for factor in prime_factors.elements(): # loop over factors
615
+ ... product *= factor # and multiply them
616
+ >>> product
617
+ 1836
618
+
619
+ Note, if an element's count has been set to zero or is a negative
620
+ number, elements() will ignore it.
621
+
622
+ '''
623
+ # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
624
+ return _chain.from_iterable(_starmap(_repeat, self.items()))
625
+
626
+ # Override dict methods where necessary
627
+
628
+ @classmethod
629
+ def fromkeys(cls, iterable, v=None):
630
+ # There is no equivalent method for counters because the semantics
631
+ # would be ambiguous in cases such as Counter.fromkeys('aaabbc', v=2).
632
+ # Initializing counters to zero values isn't necessary because zero
633
+ # is already the default value for counter lookups. Initializing
634
+ # to one is easily accomplished with Counter(set(iterable)). For
635
+ # more exotic cases, create a dictionary first using a dictionary
636
+ # comprehension or dict.fromkeys().
637
+ raise NotImplementedError(
638
+ 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.')
639
+
640
+ def update(self, iterable=None, /, **kwds):
641
+ '''Like dict.update() but add counts instead of replacing them.
642
+
643
+ Source can be an iterable, a dictionary, or another Counter instance.
644
+
645
+ >>> c = Counter('which')
646
+ >>> c.update('witch') # add elements from another iterable
647
+ >>> d = Counter('watch')
648
+ >>> c.update(d) # add elements from another counter
649
+ >>> c['h'] # four 'h' in which, witch, and watch
650
+ 4
651
+
652
+ '''
653
+ # The regular dict.update() operation makes no sense here because the
654
+ # replace behavior results in the some of original untouched counts
655
+ # being mixed-in with all of the other counts for a mismash that
656
+ # doesn't have a straight-forward interpretation in most counting
657
+ # contexts. Instead, we implement straight-addition. Both the inputs
658
+ # and outputs are allowed to contain zero and negative counts.
659
+
660
+ if iterable is not None:
661
+ if isinstance(iterable, _collections_abc.Mapping):
662
+ if self:
663
+ self_get = self.get
664
+ for elem, count in iterable.items():
665
+ self[elem] = count + self_get(elem, 0)
666
+ else:
667
+ # fast path when counter is empty
668
+ super().update(iterable)
669
+ else:
670
+ _count_elements(self, iterable)
671
+ if kwds:
672
+ self.update(kwds)
673
+
674
+ def subtract(self, iterable=None, /, **kwds):
675
+ '''Like dict.update() but subtracts counts instead of replacing them.
676
+ Counts can be reduced below zero. Both the inputs and outputs are
677
+ allowed to contain zero and negative counts.
678
+
679
+ Source can be an iterable, a dictionary, or another Counter instance.
680
+
681
+ >>> c = Counter('which')
682
+ >>> c.subtract('witch') # subtract elements from another iterable
683
+ >>> c.subtract(Counter('watch')) # subtract elements from another counter
684
+ >>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch
685
+ 0
686
+ >>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch
687
+ -1
688
+
689
+ '''
690
+ if iterable is not None:
691
+ self_get = self.get
692
+ if isinstance(iterable, _collections_abc.Mapping):
693
+ for elem, count in iterable.items():
694
+ self[elem] = self_get(elem, 0) - count
695
+ else:
696
+ for elem in iterable:
697
+ self[elem] = self_get(elem, 0) - 1
698
+ if kwds:
699
+ self.subtract(kwds)
700
+
701
+ def copy(self):
702
+ 'Return a shallow copy.'
703
+ return self.__class__(self)
704
+
705
+ def __reduce__(self):
706
+ return self.__class__, (dict(self),)
707
+
708
+ def __delitem__(self, elem):
709
+ 'Like dict.__delitem__() but does not raise KeyError for missing values.'
710
+ if elem in self:
711
+ super().__delitem__(elem)
712
+
713
+ def __eq__(self, other):
714
+ 'True if all counts agree. Missing counts are treated as zero.'
715
+ if not isinstance(other, Counter):
716
+ return NotImplemented
717
+ return all(self[e] == other[e] for c in (self, other) for e in c)
718
+
719
+ def __ne__(self, other):
720
+ 'True if any counts disagree. Missing counts are treated as zero.'
721
+ if not isinstance(other, Counter):
722
+ return NotImplemented
723
+ return not self == other
724
+
725
+ def __le__(self, other):
726
+ 'True if all counts in self are a subset of those in other.'
727
+ if not isinstance(other, Counter):
728
+ return NotImplemented
729
+ return all(self[e] <= other[e] for c in (self, other) for e in c)
730
+
731
+ def __lt__(self, other):
732
+ 'True if all counts in self are a proper subset of those in other.'
733
+ if not isinstance(other, Counter):
734
+ return NotImplemented
735
+ return self <= other and self != other
736
+
737
+ def __ge__(self, other):
738
+ 'True if all counts in self are a superset of those in other.'
739
+ if not isinstance(other, Counter):
740
+ return NotImplemented
741
+ return all(self[e] >= other[e] for c in (self, other) for e in c)
742
+
743
+ def __gt__(self, other):
744
+ 'True if all counts in self are a proper superset of those in other.'
745
+ if not isinstance(other, Counter):
746
+ return NotImplemented
747
+ return self >= other and self != other
748
+
749
+ def __repr__(self):
750
+ if not self:
751
+ return f'{self.__class__.__name__}()'
752
+ try:
753
+ # dict() preserves the ordering returned by most_common()
754
+ d = dict(self.most_common())
755
+ except TypeError:
756
+ # handle case where values are not orderable
757
+ d = dict(self)
758
+ return f'{self.__class__.__name__}({d!r})'
759
+
760
+ # Multiset-style mathematical operations discussed in:
761
+ # Knuth TAOCP Volume II section 4.6.3 exercise 19
762
+ # and at http://en.wikipedia.org/wiki/Multiset
763
+ #
764
+ # Outputs guaranteed to only include positive counts.
765
+ #
766
+ # To strip negative and zero counts, add-in an empty counter:
767
+ # c += Counter()
768
+ #
769
+ # Results are ordered according to when an element is first
770
+ # encountered in the left operand and then by the order
771
+ # encountered in the right operand.
772
+ #
773
+ # When the multiplicities are all zero or one, multiset operations
774
+ # are guaranteed to be equivalent to the corresponding operations
775
+ # for regular sets.
776
+ # Given counter multisets such as:
777
+ # cp = Counter(a=1, b=0, c=1)
778
+ # cq = Counter(c=1, d=0, e=1)
779
+ # The corresponding regular sets would be:
780
+ # sp = {'a', 'c'}
781
+ # sq = {'c', 'e'}
782
+ # All of the following relations would hold:
783
+ # set(cp + cq) == sp | sq
784
+ # set(cp - cq) == sp - sq
785
+ # set(cp | cq) == sp | sq
786
+ # set(cp & cq) == sp & sq
787
+ # (cp == cq) == (sp == sq)
788
+ # (cp != cq) == (sp != sq)
789
+ # (cp <= cq) == (sp <= sq)
790
+ # (cp < cq) == (sp < sq)
791
+ # (cp >= cq) == (sp >= sq)
792
+ # (cp > cq) == (sp > sq)
793
+
794
+ def __add__(self, other):
795
+ '''Add counts from two counters.
796
+
797
+ >>> Counter('abbb') + Counter('bcc')
798
+ Counter({'b': 4, 'c': 2, 'a': 1})
799
+
800
+ '''
801
+ if not isinstance(other, Counter):
802
+ return NotImplemented
803
+ result = Counter()
804
+ for elem, count in self.items():
805
+ newcount = count + other[elem]
806
+ if newcount > 0:
807
+ result[elem] = newcount
808
+ for elem, count in other.items():
809
+ if elem not in self and count > 0:
810
+ result[elem] = count
811
+ return result
812
+
813
+ def __sub__(self, other):
814
+ ''' Subtract count, but keep only results with positive counts.
815
+
816
+ >>> Counter('abbbc') - Counter('bccd')
817
+ Counter({'b': 2, 'a': 1})
818
+
819
+ '''
820
+ if not isinstance(other, Counter):
821
+ return NotImplemented
822
+ result = Counter()
823
+ for elem, count in self.items():
824
+ newcount = count - other[elem]
825
+ if newcount > 0:
826
+ result[elem] = newcount
827
+ for elem, count in other.items():
828
+ if elem not in self and count < 0:
829
+ result[elem] = 0 - count
830
+ return result
831
+
832
+ def __or__(self, other):
833
+ '''Union is the maximum of value in either of the input counters.
834
+
835
+ >>> Counter('abbb') | Counter('bcc')
836
+ Counter({'b': 3, 'c': 2, 'a': 1})
837
+
838
+ '''
839
+ if not isinstance(other, Counter):
840
+ return NotImplemented
841
+ result = Counter()
842
+ for elem, count in self.items():
843
+ other_count = other[elem]
844
+ newcount = other_count if count < other_count else count
845
+ if newcount > 0:
846
+ result[elem] = newcount
847
+ for elem, count in other.items():
848
+ if elem not in self and count > 0:
849
+ result[elem] = count
850
+ return result
851
+
852
+ def __and__(self, other):
853
+ ''' Intersection is the minimum of corresponding counts.
854
+
855
+ >>> Counter('abbb') & Counter('bcc')
856
+ Counter({'b': 1})
857
+
858
+ '''
859
+ if not isinstance(other, Counter):
860
+ return NotImplemented
861
+ result = Counter()
862
+ for elem, count in self.items():
863
+ other_count = other[elem]
864
+ newcount = count if count < other_count else other_count
865
+ if newcount > 0:
866
+ result[elem] = newcount
867
+ return result
868
+
869
+ def __pos__(self):
870
+ 'Adds an empty counter, effectively stripping negative and zero counts'
871
+ result = Counter()
872
+ for elem, count in self.items():
873
+ if count > 0:
874
+ result[elem] = count
875
+ return result
876
+
877
+ def __neg__(self):
878
+ '''Subtracts from an empty counter. Strips positive and zero counts,
879
+ and flips the sign on negative counts.
880
+
881
+ '''
882
+ result = Counter()
883
+ for elem, count in self.items():
884
+ if count < 0:
885
+ result[elem] = 0 - count
886
+ return result
887
+
888
+ def _keep_positive(self):
889
+ '''Internal method to strip elements with a negative or zero count'''
890
+ nonpositive = [elem for elem, count in self.items() if not count > 0]
891
+ for elem in nonpositive:
892
+ del self[elem]
893
+ return self
894
+
895
+ def __iadd__(self, other):
896
+ '''Inplace add from another counter, keeping only positive counts.
897
+
898
+ >>> c = Counter('abbb')
899
+ >>> c += Counter('bcc')
900
+ >>> c
901
+ Counter({'b': 4, 'c': 2, 'a': 1})
902
+
903
+ '''
904
+ for elem, count in other.items():
905
+ self[elem] += count
906
+ return self._keep_positive()
907
+
908
+ def __isub__(self, other):
909
+ '''Inplace subtract counter, but keep only results with positive counts.
910
+
911
+ >>> c = Counter('abbbc')
912
+ >>> c -= Counter('bccd')
913
+ >>> c
914
+ Counter({'b': 2, 'a': 1})
915
+
916
+ '''
917
+ for elem, count in other.items():
918
+ self[elem] -= count
919
+ return self._keep_positive()
920
+
921
+ def __ior__(self, other):
922
+ '''Inplace union is the maximum of value from either counter.
923
+
924
+ >>> c = Counter('abbb')
925
+ >>> c |= Counter('bcc')
926
+ >>> c
927
+ Counter({'b': 3, 'c': 2, 'a': 1})
928
+
929
+ '''
930
+ for elem, other_count in other.items():
931
+ count = self[elem]
932
+ if other_count > count:
933
+ self[elem] = other_count
934
+ return self._keep_positive()
935
+
936
+ def __iand__(self, other):
937
+ '''Inplace intersection is the minimum of corresponding counts.
938
+
939
+ >>> c = Counter('abbb')
940
+ >>> c &= Counter('bcc')
941
+ >>> c
942
+ Counter({'b': 1})
943
+
944
+ '''
945
+ for elem, count in self.items():
946
+ other_count = other[elem]
947
+ if other_count < count:
948
+ self[elem] = other_count
949
+ return self._keep_positive()
950
+
951
+
952
+ ########################################################################
953
+ ### ChainMap
954
+ ########################################################################
955
+
956
+ class ChainMap(_collections_abc.MutableMapping):
957
+ ''' A ChainMap groups multiple dicts (or other mappings) together
958
+ to create a single, updateable view.
959
+
960
+ The underlying mappings are stored in a list. That list is public and can
961
+ be accessed or updated using the *maps* attribute. There is no other
962
+ state.
963
+
964
+ Lookups search the underlying mappings successively until a key is found.
965
+ In contrast, writes, updates, and deletions only operate on the first
966
+ mapping.
967
+
968
+ '''
969
+
970
+ def __init__(self, *maps):
971
+ '''Initialize a ChainMap by setting *maps* to the given mappings.
972
+ If no mappings are provided, a single empty dictionary is used.
973
+
974
+ '''
975
+ self.maps = list(maps) or [{}] # always at least one map
976
+
977
+ def __missing__(self, key):
978
+ raise KeyError(key)
979
+
980
+ def __getitem__(self, key):
981
+ for mapping in self.maps:
982
+ try:
983
+ return mapping[key] # can't use 'key in mapping' with defaultdict
984
+ except KeyError:
985
+ pass
986
+ return self.__missing__(key) # support subclasses that define __missing__
987
+
988
+ def get(self, key, default=None):
989
+ return self[key] if key in self else default
990
+
991
+ def __len__(self):
992
+ return len(set().union(*self.maps)) # reuses stored hash values if possible
993
+
994
+ def __iter__(self):
995
+ d = {}
996
+ for mapping in reversed(self.maps):
997
+ d.update(dict.fromkeys(mapping)) # reuses stored hash values if possible
998
+ return iter(d)
999
+
1000
+ def __contains__(self, key):
1001
+ return any(key in m for m in self.maps)
1002
+
1003
+ def __bool__(self):
1004
+ return any(self.maps)
1005
+
1006
+ @_recursive_repr()
1007
+ def __repr__(self):
1008
+ return f'{self.__class__.__name__}({", ".join(map(repr, self.maps))})'
1009
+
1010
+ @classmethod
1011
+ def fromkeys(cls, iterable, *args):
1012
+ 'Create a ChainMap with a single dict created from the iterable.'
1013
+ return cls(dict.fromkeys(iterable, *args))
1014
+
1015
+ def copy(self):
1016
+ 'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]'
1017
+ return self.__class__(self.maps[0].copy(), *self.maps[1:])
1018
+
1019
+ __copy__ = copy
1020
+
1021
+ def new_child(self, m=None, **kwargs): # like Django's Context.push()
1022
+ '''New ChainMap with a new map followed by all previous maps.
1023
+ If no map is provided, an empty dict is used.
1024
+ Keyword arguments update the map or new empty dict.
1025
+ '''
1026
+ if m is None:
1027
+ m = kwargs
1028
+ elif kwargs:
1029
+ m.update(kwargs)
1030
+ return self.__class__(m, *self.maps)
1031
+
1032
+ @property
1033
+ def parents(self): # like Django's Context.pop()
1034
+ 'New ChainMap from maps[1:].'
1035
+ return self.__class__(*self.maps[1:])
1036
+
1037
+ def __setitem__(self, key, value):
1038
+ self.maps[0][key] = value
1039
+
1040
+ def __delitem__(self, key):
1041
+ try:
1042
+ del self.maps[0][key]
1043
+ except KeyError:
1044
+ raise KeyError(f'Key not found in the first mapping: {key!r}')
1045
+
1046
+ def popitem(self):
1047
+ 'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.'
1048
+ try:
1049
+ return self.maps[0].popitem()
1050
+ except KeyError:
1051
+ raise KeyError('No keys found in the first mapping.')
1052
+
1053
+ def pop(self, key, *args):
1054
+ 'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].'
1055
+ try:
1056
+ return self.maps[0].pop(key, *args)
1057
+ except KeyError:
1058
+ raise KeyError(f'Key not found in the first mapping: {key!r}')
1059
+
1060
+ def clear(self):
1061
+ 'Clear maps[0], leaving maps[1:] intact.'
1062
+ self.maps[0].clear()
1063
+
1064
+ def __ior__(self, other):
1065
+ self.maps[0].update(other)
1066
+ return self
1067
+
1068
+ def __or__(self, other):
1069
+ if not isinstance(other, _collections_abc.Mapping):
1070
+ return NotImplemented
1071
+ m = self.copy()
1072
+ m.maps[0].update(other)
1073
+ return m
1074
+
1075
+ def __ror__(self, other):
1076
+ if not isinstance(other, _collections_abc.Mapping):
1077
+ return NotImplemented
1078
+ m = dict(other)
1079
+ for child in reversed(self.maps):
1080
+ m.update(child)
1081
+ return self.__class__(m)
1082
+
1083
+
1084
+ ################################################################################
1085
+ ### UserDict
1086
+ ################################################################################
1087
+
1088
+ class UserDict(_collections_abc.MutableMapping):
1089
+
1090
+ # Start by filling-out the abstract methods
1091
+ def __init__(self, dict=None, /, **kwargs):
1092
+ self.data = {}
1093
+ if dict is not None:
1094
+ self.update(dict)
1095
+ if kwargs:
1096
+ self.update(kwargs)
1097
+
1098
+ def __len__(self):
1099
+ return len(self.data)
1100
+
1101
+ def __getitem__(self, key):
1102
+ if key in self.data:
1103
+ return self.data[key]
1104
+ if hasattr(self.__class__, "__missing__"):
1105
+ return self.__class__.__missing__(self, key)
1106
+ raise KeyError(key)
1107
+
1108
+ def __setitem__(self, key, item):
1109
+ self.data[key] = item
1110
+
1111
+ def __delitem__(self, key):
1112
+ del self.data[key]
1113
+
1114
+ def __iter__(self):
1115
+ return iter(self.data)
1116
+
1117
+ # Modify __contains__ to work correctly when __missing__ is present
1118
+ def __contains__(self, key):
1119
+ return key in self.data
1120
+
1121
+ # Now, add the methods in dicts but not in MutableMapping
1122
+ def __repr__(self):
1123
+ return repr(self.data)
1124
+
1125
+ def __or__(self, other):
1126
+ if isinstance(other, UserDict):
1127
+ return self.__class__(self.data | other.data)
1128
+ if isinstance(other, dict):
1129
+ return self.__class__(self.data | other)
1130
+ return NotImplemented
1131
+
1132
+ def __ror__(self, other):
1133
+ if isinstance(other, UserDict):
1134
+ return self.__class__(other.data | self.data)
1135
+ if isinstance(other, dict):
1136
+ return self.__class__(other | self.data)
1137
+ return NotImplemented
1138
+
1139
+ def __ior__(self, other):
1140
+ if isinstance(other, UserDict):
1141
+ self.data |= other.data
1142
+ else:
1143
+ self.data |= other
1144
+ return self
1145
+
1146
+ def __copy__(self):
1147
+ inst = self.__class__.__new__(self.__class__)
1148
+ inst.__dict__.update(self.__dict__)
1149
+ # Create a copy and avoid triggering descriptors
1150
+ inst.__dict__["data"] = self.__dict__["data"].copy()
1151
+ return inst
1152
+
1153
+ def copy(self):
1154
+ if self.__class__ is UserDict:
1155
+ return UserDict(self.data.copy())
1156
+ import copy
1157
+ data = self.data
1158
+ try:
1159
+ self.data = {}
1160
+ c = copy.copy(self)
1161
+ finally:
1162
+ self.data = data
1163
+ c.update(self)
1164
+ return c
1165
+
1166
+ @classmethod
1167
+ def fromkeys(cls, iterable, value=None):
1168
+ d = cls()
1169
+ for key in iterable:
1170
+ d[key] = value
1171
+ return d
1172
+
1173
+
1174
+ ################################################################################
1175
+ ### UserList
1176
+ ################################################################################
1177
+
1178
+ class UserList(_collections_abc.MutableSequence):
1179
+ """A more or less complete user-defined wrapper around list objects."""
1180
+
1181
+ def __init__(self, initlist=None):
1182
+ self.data = []
1183
+ if initlist is not None:
1184
+ # XXX should this accept an arbitrary sequence?
1185
+ if type(initlist) == type(self.data):
1186
+ self.data[:] = initlist
1187
+ elif isinstance(initlist, UserList):
1188
+ self.data[:] = initlist.data[:]
1189
+ else:
1190
+ self.data = list(initlist)
1191
+
1192
+ def __repr__(self):
1193
+ return repr(self.data)
1194
+
1195
+ def __lt__(self, other):
1196
+ return self.data < self.__cast(other)
1197
+
1198
+ def __le__(self, other):
1199
+ return self.data <= self.__cast(other)
1200
+
1201
+ def __eq__(self, other):
1202
+ return self.data == self.__cast(other)
1203
+
1204
+ def __gt__(self, other):
1205
+ return self.data > self.__cast(other)
1206
+
1207
+ def __ge__(self, other):
1208
+ return self.data >= self.__cast(other)
1209
+
1210
+ def __cast(self, other):
1211
+ return other.data if isinstance(other, UserList) else other
1212
+
1213
+ def __contains__(self, item):
1214
+ return item in self.data
1215
+
1216
+ def __len__(self):
1217
+ return len(self.data)
1218
+
1219
+ def __getitem__(self, i):
1220
+ if isinstance(i, slice):
1221
+ return self.__class__(self.data[i])
1222
+ else:
1223
+ return self.data[i]
1224
+
1225
+ def __setitem__(self, i, item):
1226
+ self.data[i] = item
1227
+
1228
+ def __delitem__(self, i):
1229
+ del self.data[i]
1230
+
1231
+ def __add__(self, other):
1232
+ if isinstance(other, UserList):
1233
+ return self.__class__(self.data + other.data)
1234
+ elif isinstance(other, type(self.data)):
1235
+ return self.__class__(self.data + other)
1236
+ return self.__class__(self.data + list(other))
1237
+
1238
+ def __radd__(self, other):
1239
+ if isinstance(other, UserList):
1240
+ return self.__class__(other.data + self.data)
1241
+ elif isinstance(other, type(self.data)):
1242
+ return self.__class__(other + self.data)
1243
+ return self.__class__(list(other) + self.data)
1244
+
1245
+ def __iadd__(self, other):
1246
+ if isinstance(other, UserList):
1247
+ self.data += other.data
1248
+ elif isinstance(other, type(self.data)):
1249
+ self.data += other
1250
+ else:
1251
+ self.data += list(other)
1252
+ return self
1253
+
1254
+ def __mul__(self, n):
1255
+ return self.__class__(self.data * n)
1256
+
1257
+ __rmul__ = __mul__
1258
+
1259
+ def __imul__(self, n):
1260
+ self.data *= n
1261
+ return self
1262
+
1263
+ def __copy__(self):
1264
+ inst = self.__class__.__new__(self.__class__)
1265
+ inst.__dict__.update(self.__dict__)
1266
+ # Create a copy and avoid triggering descriptors
1267
+ inst.__dict__["data"] = self.__dict__["data"][:]
1268
+ return inst
1269
+
1270
+ def append(self, item):
1271
+ self.data.append(item)
1272
+
1273
+ def insert(self, i, item):
1274
+ self.data.insert(i, item)
1275
+
1276
+ def pop(self, i=-1):
1277
+ return self.data.pop(i)
1278
+
1279
+ def remove(self, item):
1280
+ self.data.remove(item)
1281
+
1282
+ def clear(self):
1283
+ self.data.clear()
1284
+
1285
+ def copy(self):
1286
+ return self.__class__(self)
1287
+
1288
+ def count(self, item):
1289
+ return self.data.count(item)
1290
+
1291
+ def index(self, item, *args):
1292
+ return self.data.index(item, *args)
1293
+
1294
+ def reverse(self):
1295
+ self.data.reverse()
1296
+
1297
+ def sort(self, /, *args, **kwds):
1298
+ self.data.sort(*args, **kwds)
1299
+
1300
+ def extend(self, other):
1301
+ if isinstance(other, UserList):
1302
+ self.data.extend(other.data)
1303
+ else:
1304
+ self.data.extend(other)
1305
+
1306
+
1307
+ ################################################################################
1308
+ ### UserString
1309
+ ################################################################################
1310
+
1311
+ class UserString(_collections_abc.Sequence):
1312
+
1313
+ def __init__(self, seq):
1314
+ if isinstance(seq, str):
1315
+ self.data = seq
1316
+ elif isinstance(seq, UserString):
1317
+ self.data = seq.data[:]
1318
+ else:
1319
+ self.data = str(seq)
1320
+
1321
+ def __str__(self):
1322
+ return str(self.data)
1323
+
1324
+ def __repr__(self):
1325
+ return repr(self.data)
1326
+
1327
+ def __int__(self):
1328
+ return int(self.data)
1329
+
1330
+ def __float__(self):
1331
+ return float(self.data)
1332
+
1333
+ def __complex__(self):
1334
+ return complex(self.data)
1335
+
1336
+ def __hash__(self):
1337
+ return hash(self.data)
1338
+
1339
+ def __getnewargs__(self):
1340
+ return (self.data[:],)
1341
+
1342
+ def __eq__(self, string):
1343
+ if isinstance(string, UserString):
1344
+ return self.data == string.data
1345
+ return self.data == string
1346
+
1347
+ def __lt__(self, string):
1348
+ if isinstance(string, UserString):
1349
+ return self.data < string.data
1350
+ return self.data < string
1351
+
1352
+ def __le__(self, string):
1353
+ if isinstance(string, UserString):
1354
+ return self.data <= string.data
1355
+ return self.data <= string
1356
+
1357
+ def __gt__(self, string):
1358
+ if isinstance(string, UserString):
1359
+ return self.data > string.data
1360
+ return self.data > string
1361
+
1362
+ def __ge__(self, string):
1363
+ if isinstance(string, UserString):
1364
+ return self.data >= string.data
1365
+ return self.data >= string
1366
+
1367
+ def __contains__(self, char):
1368
+ if isinstance(char, UserString):
1369
+ char = char.data
1370
+ return char in self.data
1371
+
1372
+ def __len__(self):
1373
+ return len(self.data)
1374
+
1375
+ def __getitem__(self, index):
1376
+ return self.__class__(self.data[index])
1377
+
1378
+ def __add__(self, other):
1379
+ if isinstance(other, UserString):
1380
+ return self.__class__(self.data + other.data)
1381
+ elif isinstance(other, str):
1382
+ return self.__class__(self.data + other)
1383
+ return self.__class__(self.data + str(other))
1384
+
1385
+ def __radd__(self, other):
1386
+ if isinstance(other, str):
1387
+ return self.__class__(other + self.data)
1388
+ return self.__class__(str(other) + self.data)
1389
+
1390
+ def __mul__(self, n):
1391
+ return self.__class__(self.data * n)
1392
+
1393
+ __rmul__ = __mul__
1394
+
1395
+ def __mod__(self, args):
1396
+ return self.__class__(self.data % args)
1397
+
1398
+ def __rmod__(self, template):
1399
+ return self.__class__(str(template) % self)
1400
+
1401
+ # the following methods are defined in alphabetical order:
1402
+ def capitalize(self):
1403
+ return self.__class__(self.data.capitalize())
1404
+
1405
+ def casefold(self):
1406
+ return self.__class__(self.data.casefold())
1407
+
1408
+ def center(self, width, *args):
1409
+ return self.__class__(self.data.center(width, *args))
1410
+
1411
+ def count(self, sub, start=0, end=_sys.maxsize):
1412
+ if isinstance(sub, UserString):
1413
+ sub = sub.data
1414
+ return self.data.count(sub, start, end)
1415
+
1416
+ def removeprefix(self, prefix, /):
1417
+ if isinstance(prefix, UserString):
1418
+ prefix = prefix.data
1419
+ return self.__class__(self.data.removeprefix(prefix))
1420
+
1421
+ def removesuffix(self, suffix, /):
1422
+ if isinstance(suffix, UserString):
1423
+ suffix = suffix.data
1424
+ return self.__class__(self.data.removesuffix(suffix))
1425
+
1426
+ def encode(self, encoding='utf-8', errors='strict'):
1427
+ encoding = 'utf-8' if encoding is None else encoding
1428
+ errors = 'strict' if errors is None else errors
1429
+ return self.data.encode(encoding, errors)
1430
+
1431
+ def endswith(self, suffix, start=0, end=_sys.maxsize):
1432
+ return self.data.endswith(suffix, start, end)
1433
+
1434
+ def expandtabs(self, tabsize=8):
1435
+ return self.__class__(self.data.expandtabs(tabsize))
1436
+
1437
+ def find(self, sub, start=0, end=_sys.maxsize):
1438
+ if isinstance(sub, UserString):
1439
+ sub = sub.data
1440
+ return self.data.find(sub, start, end)
1441
+
1442
+ def format(self, /, *args, **kwds):
1443
+ return self.data.format(*args, **kwds)
1444
+
1445
+ def format_map(self, mapping):
1446
+ return self.data.format_map(mapping)
1447
+
1448
+ def index(self, sub, start=0, end=_sys.maxsize):
1449
+ return self.data.index(sub, start, end)
1450
+
1451
+ def isalpha(self):
1452
+ return self.data.isalpha()
1453
+
1454
+ def isalnum(self):
1455
+ return self.data.isalnum()
1456
+
1457
+ def isascii(self):
1458
+ return self.data.isascii()
1459
+
1460
+ def isdecimal(self):
1461
+ return self.data.isdecimal()
1462
+
1463
+ def isdigit(self):
1464
+ return self.data.isdigit()
1465
+
1466
+ def isidentifier(self):
1467
+ return self.data.isidentifier()
1468
+
1469
+ def islower(self):
1470
+ return self.data.islower()
1471
+
1472
+ def isnumeric(self):
1473
+ return self.data.isnumeric()
1474
+
1475
+ def isprintable(self):
1476
+ return self.data.isprintable()
1477
+
1478
+ def isspace(self):
1479
+ return self.data.isspace()
1480
+
1481
+ def istitle(self):
1482
+ return self.data.istitle()
1483
+
1484
+ def isupper(self):
1485
+ return self.data.isupper()
1486
+
1487
+ def join(self, seq):
1488
+ return self.data.join(seq)
1489
+
1490
+ def ljust(self, width, *args):
1491
+ return self.__class__(self.data.ljust(width, *args))
1492
+
1493
+ def lower(self):
1494
+ return self.__class__(self.data.lower())
1495
+
1496
+ def lstrip(self, chars=None):
1497
+ return self.__class__(self.data.lstrip(chars))
1498
+
1499
+ maketrans = str.maketrans
1500
+
1501
+ def partition(self, sep):
1502
+ return self.data.partition(sep)
1503
+
1504
+ def replace(self, old, new, maxsplit=-1):
1505
+ if isinstance(old, UserString):
1506
+ old = old.data
1507
+ if isinstance(new, UserString):
1508
+ new = new.data
1509
+ return self.__class__(self.data.replace(old, new, maxsplit))
1510
+
1511
+ def rfind(self, sub, start=0, end=_sys.maxsize):
1512
+ if isinstance(sub, UserString):
1513
+ sub = sub.data
1514
+ return self.data.rfind(sub, start, end)
1515
+
1516
+ def rindex(self, sub, start=0, end=_sys.maxsize):
1517
+ return self.data.rindex(sub, start, end)
1518
+
1519
+ def rjust(self, width, *args):
1520
+ return self.__class__(self.data.rjust(width, *args))
1521
+
1522
+ def rpartition(self, sep):
1523
+ return self.data.rpartition(sep)
1524
+
1525
+ def rstrip(self, chars=None):
1526
+ return self.__class__(self.data.rstrip(chars))
1527
+
1528
+ def split(self, sep=None, maxsplit=-1):
1529
+ return self.data.split(sep, maxsplit)
1530
+
1531
+ def rsplit(self, sep=None, maxsplit=-1):
1532
+ return self.data.rsplit(sep, maxsplit)
1533
+
1534
+ def splitlines(self, keepends=False):
1535
+ return self.data.splitlines(keepends)
1536
+
1537
+ def startswith(self, prefix, start=0, end=_sys.maxsize):
1538
+ return self.data.startswith(prefix, start, end)
1539
+
1540
+ def strip(self, chars=None):
1541
+ return self.__class__(self.data.strip(chars))
1542
+
1543
+ def swapcase(self):
1544
+ return self.__class__(self.data.swapcase())
1545
+
1546
+ def title(self):
1547
+ return self.__class__(self.data.title())
1548
+
1549
+ def translate(self, *args):
1550
+ return self.__class__(self.data.translate(*args))
1551
+
1552
+ def upper(self):
1553
+ return self.__class__(self.data.upper())
1554
+
1555
+ def zfill(self, width):
1556
+ return self.__class__(self.data.zfill(width))
llava/lib/python3.10/collections/__pycache__/abc.cpython-310.pyc ADDED
Binary file (492 Bytes). View file
 
llava/lib/python3.10/collections/abc.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from _collections_abc import *
2
+ from _collections_abc import __all__
3
+ from _collections_abc import _CallableGenericAlias
llava/lib/python3.10/distutils/command/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (715 Bytes). View file
 
llava/lib/python3.10/distutils/command/__pycache__/bdist.cpython-310.pyc ADDED
Binary file (3.8 kB). View file
 
llava/lib/python3.10/distutils/command/__pycache__/bdist_msi.cpython-310.pyc ADDED
Binary file (19.7 kB). View file
 
llava/lib/python3.10/distutils/command/__pycache__/bdist_rpm.cpython-310.pyc ADDED
Binary file (12.5 kB). View file
 
llava/lib/python3.10/distutils/command/__pycache__/build.cpython-310.pyc ADDED
Binary file (4.1 kB). View file
 
llava/lib/python3.10/distutils/command/__pycache__/build_ext.cpython-310.pyc ADDED
Binary file (16.4 kB). View file
 
llava/lib/python3.10/distutils/command/__pycache__/build_py.cpython-310.pyc ADDED
Binary file (10.7 kB). View file
 
llava/lib/python3.10/distutils/command/__pycache__/build_scripts.cpython-310.pyc ADDED
Binary file (4.32 kB). View file
 
llava/lib/python3.10/distutils/command/__pycache__/clean.cpython-310.pyc ADDED
Binary file (2.09 kB). View file
 
llava/lib/python3.10/distutils/command/__pycache__/config.cpython-310.pyc ADDED
Binary file (10.5 kB). View file
 
llava/lib/python3.10/distutils/command/__pycache__/install.cpython-310.pyc ADDED
Binary file (14.1 kB). View file
 
llava/lib/python3.10/distutils/command/__pycache__/install_data.cpython-310.pyc ADDED
Binary file (2.29 kB). View file
 
llava/lib/python3.10/distutils/command/__pycache__/install_egg_info.cpython-310.pyc ADDED
Binary file (3.03 kB). View file
 
llava/lib/python3.10/distutils/command/__pycache__/install_headers.cpython-310.pyc ADDED
Binary file (1.71 kB). View file
 
llava/lib/python3.10/distutils/command/__pycache__/install_lib.cpython-310.pyc ADDED
Binary file (5.11 kB). View file
 
llava/lib/python3.10/distutils/command/__pycache__/install_scripts.cpython-310.pyc ADDED
Binary file (2.4 kB). View file
 
llava/lib/python3.10/distutils/command/__pycache__/register.cpython-310.pyc ADDED
Binary file (8.88 kB). View file
 
llava/lib/python3.10/distutils/command/__pycache__/upload.cpython-310.pyc ADDED
Binary file (5.34 kB). View file
 
llava/lib/python3.10/distutils/command/bdist.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.bdist
2
+
3
+ Implements the Distutils 'bdist' command (create a built [binary]
4
+ distribution)."""
5
+
6
+ import os
7
+ from distutils.core import Command
8
+ from distutils.errors import *
9
+ from distutils.util import get_platform
10
+
11
+
12
+ def show_formats():
13
+ """Print list of available formats (arguments to "--format" option).
14
+ """
15
+ from distutils.fancy_getopt import FancyGetopt
16
+ formats = []
17
+ for format in bdist.format_commands:
18
+ formats.append(("formats=" + format, None,
19
+ bdist.format_command[format][1]))
20
+ pretty_printer = FancyGetopt(formats)
21
+ pretty_printer.print_help("List of available distribution formats:")
22
+
23
+
24
+ class bdist(Command):
25
+
26
+ description = "create a built (binary) distribution"
27
+
28
+ user_options = [('bdist-base=', 'b',
29
+ "temporary directory for creating built distributions"),
30
+ ('plat-name=', 'p',
31
+ "platform name to embed in generated filenames "
32
+ "(default: %s)" % get_platform()),
33
+ ('formats=', None,
34
+ "formats for distribution (comma-separated list)"),
35
+ ('dist-dir=', 'd',
36
+ "directory to put final built distributions in "
37
+ "[default: dist]"),
38
+ ('skip-build', None,
39
+ "skip rebuilding everything (for testing/debugging)"),
40
+ ('owner=', 'u',
41
+ "Owner name used when creating a tar file"
42
+ " [default: current user]"),
43
+ ('group=', 'g',
44
+ "Group name used when creating a tar file"
45
+ " [default: current group]"),
46
+ ]
47
+
48
+ boolean_options = ['skip-build']
49
+
50
+ help_options = [
51
+ ('help-formats', None,
52
+ "lists available distribution formats", show_formats),
53
+ ]
54
+
55
+ # The following commands do not take a format option from bdist
56
+ no_format_option = ('bdist_rpm',)
57
+
58
+ # This won't do in reality: will need to distinguish RPM-ish Linux,
59
+ # Debian-ish Linux, Solaris, FreeBSD, ..., Windows, Mac OS.
60
+ default_format = {'posix': 'gztar',
61
+ 'nt': 'zip'}
62
+
63
+ # Establish the preferred order (for the --help-formats option).
64
+ format_commands = ['rpm', 'gztar', 'bztar', 'xztar', 'ztar', 'tar',
65
+ 'zip', 'msi']
66
+
67
+ # And the real information.
68
+ format_command = {'rpm': ('bdist_rpm', "RPM distribution"),
69
+ 'gztar': ('bdist_dumb', "gzip'ed tar file"),
70
+ 'bztar': ('bdist_dumb', "bzip2'ed tar file"),
71
+ 'xztar': ('bdist_dumb', "xz'ed tar file"),
72
+ 'ztar': ('bdist_dumb', "compressed tar file"),
73
+ 'tar': ('bdist_dumb', "tar file"),
74
+ 'zip': ('bdist_dumb', "ZIP file"),
75
+ 'msi': ('bdist_msi', "Microsoft Installer")
76
+ }
77
+
78
+
79
+ def initialize_options(self):
80
+ self.bdist_base = None
81
+ self.plat_name = None
82
+ self.formats = None
83
+ self.dist_dir = None
84
+ self.skip_build = 0
85
+ self.group = None
86
+ self.owner = None
87
+
88
+ def finalize_options(self):
89
+ # have to finalize 'plat_name' before 'bdist_base'
90
+ if self.plat_name is None:
91
+ if self.skip_build:
92
+ self.plat_name = get_platform()
93
+ else:
94
+ self.plat_name = self.get_finalized_command('build').plat_name
95
+
96
+ # 'bdist_base' -- parent of per-built-distribution-format
97
+ # temporary directories (eg. we'll probably have
98
+ # "build/bdist.<plat>/dumb", "build/bdist.<plat>/rpm", etc.)
99
+ if self.bdist_base is None:
100
+ build_base = self.get_finalized_command('build').build_base
101
+ self.bdist_base = os.path.join(build_base,
102
+ 'bdist.' + self.plat_name)
103
+
104
+ self.ensure_string_list('formats')
105
+ if self.formats is None:
106
+ try:
107
+ self.formats = [self.default_format[os.name]]
108
+ except KeyError:
109
+ raise DistutilsPlatformError(
110
+ "don't know how to create built distributions "
111
+ "on platform %s" % os.name)
112
+
113
+ if self.dist_dir is None:
114
+ self.dist_dir = "dist"
115
+
116
+ def run(self):
117
+ # Figure out which sub-commands we need to run.
118
+ commands = []
119
+ for format in self.formats:
120
+ try:
121
+ commands.append(self.format_command[format][0])
122
+ except KeyError:
123
+ raise DistutilsOptionError("invalid format '%s'" % format)
124
+
125
+ # Reinitialize and run each command.
126
+ for i in range(len(self.formats)):
127
+ cmd_name = commands[i]
128
+ sub_cmd = self.reinitialize_command(cmd_name)
129
+ if cmd_name not in self.no_format_option:
130
+ sub_cmd.format = self.formats[i]
131
+
132
+ # passing the owner and group names for tar archiving
133
+ if cmd_name == 'bdist_dumb':
134
+ sub_cmd.owner = self.owner
135
+ sub_cmd.group = self.group
136
+
137
+ # If we're going to need to run this command again, tell it to
138
+ # keep its temporary files around so subsequent runs go faster.
139
+ if cmd_name in commands[i+1:]:
140
+ sub_cmd.keep_temp = 1
141
+ self.run_command(cmd_name)
llava/lib/python3.10/distutils/command/bdist_msi.py ADDED
@@ -0,0 +1,747 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2005, 2006 Martin von Löwis
2
+ # Licensed to PSF under a Contributor Agreement.
3
+ """
4
+ Implements the bdist_msi command.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ import warnings
10
+ from distutils.core import Command
11
+ from distutils.dir_util import remove_tree
12
+ from distutils.sysconfig import get_python_version
13
+ from distutils.version import StrictVersion
14
+ from distutils.errors import DistutilsOptionError
15
+ from distutils.util import get_platform
16
+ from distutils import log
17
+ import msilib
18
+ from msilib import schema, sequence, text
19
+ from msilib import Directory, Feature, Dialog, add_data
20
+
21
+ class PyDialog(Dialog):
22
+ """Dialog class with a fixed layout: controls at the top, then a ruler,
23
+ then a list of buttons: back, next, cancel. Optionally a bitmap at the
24
+ left."""
25
+ def __init__(self, *args, **kw):
26
+ """Dialog(database, name, x, y, w, h, attributes, title, first,
27
+ default, cancel, bitmap=true)"""
28
+ Dialog.__init__(self, *args)
29
+ ruler = self.h - 36
30
+ bmwidth = 152*ruler/328
31
+ #if kw.get("bitmap", True):
32
+ # self.bitmap("Bitmap", 0, 0, bmwidth, ruler, "PythonWin")
33
+ self.line("BottomLine", 0, ruler, self.w, 0)
34
+
35
+ def title(self, title):
36
+ "Set the title text of the dialog at the top."
37
+ # name, x, y, w, h, flags=Visible|Enabled|Transparent|NoPrefix,
38
+ # text, in VerdanaBold10
39
+ self.text("Title", 15, 10, 320, 60, 0x30003,
40
+ r"{\VerdanaBold10}%s" % title)
41
+
42
+ def back(self, title, next, name = "Back", active = 1):
43
+ """Add a back button with a given title, the tab-next button,
44
+ its name in the Control table, possibly initially disabled.
45
+
46
+ Return the button, so that events can be associated"""
47
+ if active:
48
+ flags = 3 # Visible|Enabled
49
+ else:
50
+ flags = 1 # Visible
51
+ return self.pushbutton(name, 180, self.h-27 , 56, 17, flags, title, next)
52
+
53
+ def cancel(self, title, next, name = "Cancel", active = 1):
54
+ """Add a cancel button with a given title, the tab-next button,
55
+ its name in the Control table, possibly initially disabled.
56
+
57
+ Return the button, so that events can be associated"""
58
+ if active:
59
+ flags = 3 # Visible|Enabled
60
+ else:
61
+ flags = 1 # Visible
62
+ return self.pushbutton(name, 304, self.h-27, 56, 17, flags, title, next)
63
+
64
+ def next(self, title, next, name = "Next", active = 1):
65
+ """Add a Next button with a given title, the tab-next button,
66
+ its name in the Control table, possibly initially disabled.
67
+
68
+ Return the button, so that events can be associated"""
69
+ if active:
70
+ flags = 3 # Visible|Enabled
71
+ else:
72
+ flags = 1 # Visible
73
+ return self.pushbutton(name, 236, self.h-27, 56, 17, flags, title, next)
74
+
75
+ def xbutton(self, name, title, next, xpos):
76
+ """Add a button with a given title, the tab-next button,
77
+ its name in the Control table, giving its x position; the
78
+ y-position is aligned with the other buttons.
79
+
80
+ Return the button, so that events can be associated"""
81
+ return self.pushbutton(name, int(self.w*xpos - 28), self.h-27, 56, 17, 3, title, next)
82
+
83
+ class bdist_msi(Command):
84
+
85
+ description = "create a Microsoft Installer (.msi) binary distribution"
86
+
87
+ user_options = [('bdist-dir=', None,
88
+ "temporary directory for creating the distribution"),
89
+ ('plat-name=', 'p',
90
+ "platform name to embed in generated filenames "
91
+ "(default: %s)" % get_platform()),
92
+ ('keep-temp', 'k',
93
+ "keep the pseudo-installation tree around after " +
94
+ "creating the distribution archive"),
95
+ ('target-version=', None,
96
+ "require a specific python version" +
97
+ " on the target system"),
98
+ ('no-target-compile', 'c',
99
+ "do not compile .py to .pyc on the target system"),
100
+ ('no-target-optimize', 'o',
101
+ "do not compile .py to .pyo (optimized) "
102
+ "on the target system"),
103
+ ('dist-dir=', 'd',
104
+ "directory to put final built distributions in"),
105
+ ('skip-build', None,
106
+ "skip rebuilding everything (for testing/debugging)"),
107
+ ('install-script=', None,
108
+ "basename of installation script to be run after "
109
+ "installation or before deinstallation"),
110
+ ('pre-install-script=', None,
111
+ "Fully qualified filename of a script to be run before "
112
+ "any files are installed. This script need not be in the "
113
+ "distribution"),
114
+ ]
115
+
116
+ boolean_options = ['keep-temp', 'no-target-compile', 'no-target-optimize',
117
+ 'skip-build']
118
+
119
+ all_versions = ['2.0', '2.1', '2.2', '2.3', '2.4',
120
+ '2.5', '2.6', '2.7', '2.8', '2.9',
121
+ '3.0', '3.1', '3.2', '3.3', '3.4',
122
+ '3.5', '3.6', '3.7', '3.8', '3.9']
123
+ other_version = 'X'
124
+
125
+ def __init__(self, *args, **kw):
126
+ super().__init__(*args, **kw)
127
+ warnings.warn("bdist_msi command is deprecated since Python 3.9, "
128
+ "use bdist_wheel (wheel packages) instead",
129
+ DeprecationWarning, 2)
130
+
131
+ def initialize_options(self):
132
+ self.bdist_dir = None
133
+ self.plat_name = None
134
+ self.keep_temp = 0
135
+ self.no_target_compile = 0
136
+ self.no_target_optimize = 0
137
+ self.target_version = None
138
+ self.dist_dir = None
139
+ self.skip_build = None
140
+ self.install_script = None
141
+ self.pre_install_script = None
142
+ self.versions = None
143
+
144
+ def finalize_options(self):
145
+ self.set_undefined_options('bdist', ('skip_build', 'skip_build'))
146
+
147
+ if self.bdist_dir is None:
148
+ bdist_base = self.get_finalized_command('bdist').bdist_base
149
+ self.bdist_dir = os.path.join(bdist_base, 'msi')
150
+
151
+ short_version = get_python_version()
152
+ if (not self.target_version) and self.distribution.has_ext_modules():
153
+ self.target_version = short_version
154
+
155
+ if self.target_version:
156
+ self.versions = [self.target_version]
157
+ if not self.skip_build and self.distribution.has_ext_modules()\
158
+ and self.target_version != short_version:
159
+ raise DistutilsOptionError(
160
+ "target version can only be %s, or the '--skip-build'"
161
+ " option must be specified" % (short_version,))
162
+ else:
163
+ self.versions = list(self.all_versions)
164
+
165
+ self.set_undefined_options('bdist',
166
+ ('dist_dir', 'dist_dir'),
167
+ ('plat_name', 'plat_name'),
168
+ )
169
+
170
+ if self.pre_install_script:
171
+ raise DistutilsOptionError(
172
+ "the pre-install-script feature is not yet implemented")
173
+
174
+ if self.install_script:
175
+ for script in self.distribution.scripts:
176
+ if self.install_script == os.path.basename(script):
177
+ break
178
+ else:
179
+ raise DistutilsOptionError(
180
+ "install_script '%s' not found in scripts"
181
+ % self.install_script)
182
+ self.install_script_key = None
183
+
184
+ def run(self):
185
+ if not self.skip_build:
186
+ self.run_command('build')
187
+
188
+ install = self.reinitialize_command('install', reinit_subcommands=1)
189
+ install.prefix = self.bdist_dir
190
+ install.skip_build = self.skip_build
191
+ install.warn_dir = 0
192
+
193
+ install_lib = self.reinitialize_command('install_lib')
194
+ # we do not want to include pyc or pyo files
195
+ install_lib.compile = 0
196
+ install_lib.optimize = 0
197
+
198
+ if self.distribution.has_ext_modules():
199
+ # If we are building an installer for a Python version other
200
+ # than the one we are currently running, then we need to ensure
201
+ # our build_lib reflects the other Python version rather than ours.
202
+ # Note that for target_version!=sys.version, we must have skipped the
203
+ # build step, so there is no issue with enforcing the build of this
204
+ # version.
205
+ target_version = self.target_version
206
+ if not target_version:
207
+ assert self.skip_build, "Should have already checked this"
208
+ target_version = '%d.%d' % sys.version_info[:2]
209
+ plat_specifier = ".%s-%s" % (self.plat_name, target_version)
210
+ build = self.get_finalized_command('build')
211
+ build.build_lib = os.path.join(build.build_base,
212
+ 'lib' + plat_specifier)
213
+
214
+ log.info("installing to %s", self.bdist_dir)
215
+ install.ensure_finalized()
216
+
217
+ # avoid warning of 'install_lib' about installing
218
+ # into a directory not in sys.path
219
+ sys.path.insert(0, os.path.join(self.bdist_dir, 'PURELIB'))
220
+
221
+ install.run()
222
+
223
+ del sys.path[0]
224
+
225
+ self.mkpath(self.dist_dir)
226
+ fullname = self.distribution.get_fullname()
227
+ installer_name = self.get_installer_filename(fullname)
228
+ installer_name = os.path.abspath(installer_name)
229
+ if os.path.exists(installer_name): os.unlink(installer_name)
230
+
231
+ metadata = self.distribution.metadata
232
+ author = metadata.author
233
+ if not author:
234
+ author = metadata.maintainer
235
+ if not author:
236
+ author = "UNKNOWN"
237
+ version = metadata.get_version()
238
+ # ProductVersion must be strictly numeric
239
+ # XXX need to deal with prerelease versions
240
+ sversion = "%d.%d.%d" % StrictVersion(version).version
241
+ # Prefix ProductName with Python x.y, so that
242
+ # it sorts together with the other Python packages
243
+ # in Add-Remove-Programs (APR)
244
+ fullname = self.distribution.get_fullname()
245
+ if self.target_version:
246
+ product_name = "Python %s %s" % (self.target_version, fullname)
247
+ else:
248
+ product_name = "Python %s" % (fullname)
249
+ self.db = msilib.init_database(installer_name, schema,
250
+ product_name, msilib.gen_uuid(),
251
+ sversion, author)
252
+ msilib.add_tables(self.db, sequence)
253
+ props = [('DistVersion', version)]
254
+ email = metadata.author_email or metadata.maintainer_email
255
+ if email:
256
+ props.append(("ARPCONTACT", email))
257
+ if metadata.url:
258
+ props.append(("ARPURLINFOABOUT", metadata.url))
259
+ if props:
260
+ add_data(self.db, 'Property', props)
261
+
262
+ self.add_find_python()
263
+ self.add_files()
264
+ self.add_scripts()
265
+ self.add_ui()
266
+ self.db.Commit()
267
+
268
+ if hasattr(self.distribution, 'dist_files'):
269
+ tup = 'bdist_msi', self.target_version or 'any', fullname
270
+ self.distribution.dist_files.append(tup)
271
+
272
+ if not self.keep_temp:
273
+ remove_tree(self.bdist_dir, dry_run=self.dry_run)
274
+
275
+ def add_files(self):
276
+ db = self.db
277
+ cab = msilib.CAB("distfiles")
278
+ rootdir = os.path.abspath(self.bdist_dir)
279
+
280
+ root = Directory(db, cab, None, rootdir, "TARGETDIR", "SourceDir")
281
+ f = Feature(db, "Python", "Python", "Everything",
282
+ 0, 1, directory="TARGETDIR")
283
+
284
+ items = [(f, root, '')]
285
+ for version in self.versions + [self.other_version]:
286
+ target = "TARGETDIR" + version
287
+ name = default = "Python" + version
288
+ desc = "Everything"
289
+ if version is self.other_version:
290
+ title = "Python from another location"
291
+ level = 2
292
+ else:
293
+ title = "Python %s from registry" % version
294
+ level = 1
295
+ f = Feature(db, name, title, desc, 1, level, directory=target)
296
+ dir = Directory(db, cab, root, rootdir, target, default)
297
+ items.append((f, dir, version))
298
+ db.Commit()
299
+
300
+ seen = {}
301
+ for feature, dir, version in items:
302
+ todo = [dir]
303
+ while todo:
304
+ dir = todo.pop()
305
+ for file in os.listdir(dir.absolute):
306
+ afile = os.path.join(dir.absolute, file)
307
+ if os.path.isdir(afile):
308
+ short = "%s|%s" % (dir.make_short(file), file)
309
+ default = file + version
310
+ newdir = Directory(db, cab, dir, file, default, short)
311
+ todo.append(newdir)
312
+ else:
313
+ if not dir.component:
314
+ dir.start_component(dir.logical, feature, 0)
315
+ if afile not in seen:
316
+ key = seen[afile] = dir.add_file(file)
317
+ if file==self.install_script:
318
+ if self.install_script_key:
319
+ raise DistutilsOptionError(
320
+ "Multiple files with name %s" % file)
321
+ self.install_script_key = '[#%s]' % key
322
+ else:
323
+ key = seen[afile]
324
+ add_data(self.db, "DuplicateFile",
325
+ [(key + version, dir.component, key, None, dir.logical)])
326
+ db.Commit()
327
+ cab.commit(db)
328
+
329
+ def add_find_python(self):
330
+ """Adds code to the installer to compute the location of Python.
331
+
332
+ Properties PYTHON.MACHINE.X.Y and PYTHON.USER.X.Y will be set from the
333
+ registry for each version of Python.
334
+
335
+ Properties TARGETDIRX.Y will be set from PYTHON.USER.X.Y if defined,
336
+ else from PYTHON.MACHINE.X.Y.
337
+
338
+ Properties PYTHONX.Y will be set to TARGETDIRX.Y\\python.exe"""
339
+
340
+ start = 402
341
+ for ver in self.versions:
342
+ install_path = r"SOFTWARE\Python\PythonCore\%s\InstallPath" % ver
343
+ machine_reg = "python.machine." + ver
344
+ user_reg = "python.user." + ver
345
+ machine_prop = "PYTHON.MACHINE." + ver
346
+ user_prop = "PYTHON.USER." + ver
347
+ machine_action = "PythonFromMachine" + ver
348
+ user_action = "PythonFromUser" + ver
349
+ exe_action = "PythonExe" + ver
350
+ target_dir_prop = "TARGETDIR" + ver
351
+ exe_prop = "PYTHON" + ver
352
+ if msilib.Win64:
353
+ # type: msidbLocatorTypeRawValue + msidbLocatorType64bit
354
+ Type = 2+16
355
+ else:
356
+ Type = 2
357
+ add_data(self.db, "RegLocator",
358
+ [(machine_reg, 2, install_path, None, Type),
359
+ (user_reg, 1, install_path, None, Type)])
360
+ add_data(self.db, "AppSearch",
361
+ [(machine_prop, machine_reg),
362
+ (user_prop, user_reg)])
363
+ add_data(self.db, "CustomAction",
364
+ [(machine_action, 51+256, target_dir_prop, "[" + machine_prop + "]"),
365
+ (user_action, 51+256, target_dir_prop, "[" + user_prop + "]"),
366
+ (exe_action, 51+256, exe_prop, "[" + target_dir_prop + "]\\python.exe"),
367
+ ])
368
+ add_data(self.db, "InstallExecuteSequence",
369
+ [(machine_action, machine_prop, start),
370
+ (user_action, user_prop, start + 1),
371
+ (exe_action, None, start + 2),
372
+ ])
373
+ add_data(self.db, "InstallUISequence",
374
+ [(machine_action, machine_prop, start),
375
+ (user_action, user_prop, start + 1),
376
+ (exe_action, None, start + 2),
377
+ ])
378
+ add_data(self.db, "Condition",
379
+ [("Python" + ver, 0, "NOT TARGETDIR" + ver)])
380
+ start += 4
381
+ assert start < 500
382
+
383
+ def add_scripts(self):
384
+ if self.install_script:
385
+ start = 6800
386
+ for ver in self.versions + [self.other_version]:
387
+ install_action = "install_script." + ver
388
+ exe_prop = "PYTHON" + ver
389
+ add_data(self.db, "CustomAction",
390
+ [(install_action, 50, exe_prop, self.install_script_key)])
391
+ add_data(self.db, "InstallExecuteSequence",
392
+ [(install_action, "&Python%s=3" % ver, start)])
393
+ start += 1
394
+ # XXX pre-install scripts are currently refused in finalize_options()
395
+ # but if this feature is completed, it will also need to add
396
+ # entries for each version as the above code does
397
+ if self.pre_install_script:
398
+ scriptfn = os.path.join(self.bdist_dir, "preinstall.bat")
399
+ with open(scriptfn, "w") as f:
400
+ # The batch file will be executed with [PYTHON], so that %1
401
+ # is the path to the Python interpreter; %0 will be the path
402
+ # of the batch file.
403
+ # rem ="""
404
+ # %1 %0
405
+ # exit
406
+ # """
407
+ # <actual script>
408
+ f.write('rem ="""\n%1 %0\nexit\n"""\n')
409
+ with open(self.pre_install_script) as fin:
410
+ f.write(fin.read())
411
+ add_data(self.db, "Binary",
412
+ [("PreInstall", msilib.Binary(scriptfn))
413
+ ])
414
+ add_data(self.db, "CustomAction",
415
+ [("PreInstall", 2, "PreInstall", None)
416
+ ])
417
+ add_data(self.db, "InstallExecuteSequence",
418
+ [("PreInstall", "NOT Installed", 450)])
419
+
420
+
421
+ def add_ui(self):
422
+ db = self.db
423
+ x = y = 50
424
+ w = 370
425
+ h = 300
426
+ title = "[ProductName] Setup"
427
+
428
+ # see "Dialog Style Bits"
429
+ modal = 3 # visible | modal
430
+ modeless = 1 # visible
431
+ track_disk_space = 32
432
+
433
+ # UI customization properties
434
+ add_data(db, "Property",
435
+ # See "DefaultUIFont Property"
436
+ [("DefaultUIFont", "DlgFont8"),
437
+ # See "ErrorDialog Style Bit"
438
+ ("ErrorDialog", "ErrorDlg"),
439
+ ("Progress1", "Install"), # modified in maintenance type dlg
440
+ ("Progress2", "installs"),
441
+ ("MaintenanceForm_Action", "Repair"),
442
+ # possible values: ALL, JUSTME
443
+ ("WhichUsers", "ALL")
444
+ ])
445
+
446
+ # Fonts, see "TextStyle Table"
447
+ add_data(db, "TextStyle",
448
+ [("DlgFont8", "Tahoma", 9, None, 0),
449
+ ("DlgFontBold8", "Tahoma", 8, None, 1), #bold
450
+ ("VerdanaBold10", "Verdana", 10, None, 1),
451
+ ("VerdanaRed9", "Verdana", 9, 255, 0),
452
+ ])
453
+
454
+ # UI Sequences, see "InstallUISequence Table", "Using a Sequence Table"
455
+ # Numbers indicate sequence; see sequence.py for how these action integrate
456
+ add_data(db, "InstallUISequence",
457
+ [("PrepareDlg", "Not Privileged or Windows9x or Installed", 140),
458
+ ("WhichUsersDlg", "Privileged and not Windows9x and not Installed", 141),
459
+ # In the user interface, assume all-users installation if privileged.
460
+ ("SelectFeaturesDlg", "Not Installed", 1230),
461
+ # XXX no support for resume installations yet
462
+ #("ResumeDlg", "Installed AND (RESUME OR Preselected)", 1240),
463
+ ("MaintenanceTypeDlg", "Installed AND NOT RESUME AND NOT Preselected", 1250),
464
+ ("ProgressDlg", None, 1280)])
465
+
466
+ add_data(db, 'ActionText', text.ActionText)
467
+ add_data(db, 'UIText', text.UIText)
468
+ #####################################################################
469
+ # Standard dialogs: FatalError, UserExit, ExitDialog
470
+ fatal=PyDialog(db, "FatalError", x, y, w, h, modal, title,
471
+ "Finish", "Finish", "Finish")
472
+ fatal.title("[ProductName] Installer ended prematurely")
473
+ fatal.back("< Back", "Finish", active = 0)
474
+ fatal.cancel("Cancel", "Back", active = 0)
475
+ fatal.text("Description1", 15, 70, 320, 80, 0x30003,
476
+ "[ProductName] setup ended prematurely because of an error. Your system has not been modified. To install this program at a later time, please run the installation again.")
477
+ fatal.text("Description2", 15, 155, 320, 20, 0x30003,
478
+ "Click the Finish button to exit the Installer.")
479
+ c=fatal.next("Finish", "Cancel", name="Finish")
480
+ c.event("EndDialog", "Exit")
481
+
482
+ user_exit=PyDialog(db, "UserExit", x, y, w, h, modal, title,
483
+ "Finish", "Finish", "Finish")
484
+ user_exit.title("[ProductName] Installer was interrupted")
485
+ user_exit.back("< Back", "Finish", active = 0)
486
+ user_exit.cancel("Cancel", "Back", active = 0)
487
+ user_exit.text("Description1", 15, 70, 320, 80, 0x30003,
488
+ "[ProductName] setup was interrupted. Your system has not been modified. "
489
+ "To install this program at a later time, please run the installation again.")
490
+ user_exit.text("Description2", 15, 155, 320, 20, 0x30003,
491
+ "Click the Finish button to exit the Installer.")
492
+ c = user_exit.next("Finish", "Cancel", name="Finish")
493
+ c.event("EndDialog", "Exit")
494
+
495
+ exit_dialog = PyDialog(db, "ExitDialog", x, y, w, h, modal, title,
496
+ "Finish", "Finish", "Finish")
497
+ exit_dialog.title("Completing the [ProductName] Installer")
498
+ exit_dialog.back("< Back", "Finish", active = 0)
499
+ exit_dialog.cancel("Cancel", "Back", active = 0)
500
+ exit_dialog.text("Description", 15, 235, 320, 20, 0x30003,
501
+ "Click the Finish button to exit the Installer.")
502
+ c = exit_dialog.next("Finish", "Cancel", name="Finish")
503
+ c.event("EndDialog", "Return")
504
+
505
+ #####################################################################
506
+ # Required dialog: FilesInUse, ErrorDlg
507
+ inuse = PyDialog(db, "FilesInUse",
508
+ x, y, w, h,
509
+ 19, # KeepModeless|Modal|Visible
510
+ title,
511
+ "Retry", "Retry", "Retry", bitmap=False)
512
+ inuse.text("Title", 15, 6, 200, 15, 0x30003,
513
+ r"{\DlgFontBold8}Files in Use")
514
+ inuse.text("Description", 20, 23, 280, 20, 0x30003,
515
+ "Some files that need to be updated are currently in use.")
516
+ inuse.text("Text", 20, 55, 330, 50, 3,
517
+ "The following applications are using files that need to be updated by this setup. Close these applications and then click Retry to continue the installation or Cancel to exit it.")
518
+ inuse.control("List", "ListBox", 20, 107, 330, 130, 7, "FileInUseProcess",
519
+ None, None, None)
520
+ c=inuse.back("Exit", "Ignore", name="Exit")
521
+ c.event("EndDialog", "Exit")
522
+ c=inuse.next("Ignore", "Retry", name="Ignore")
523
+ c.event("EndDialog", "Ignore")
524
+ c=inuse.cancel("Retry", "Exit", name="Retry")
525
+ c.event("EndDialog","Retry")
526
+
527
+ # See "Error Dialog". See "ICE20" for the required names of the controls.
528
+ error = Dialog(db, "ErrorDlg",
529
+ 50, 10, 330, 101,
530
+ 65543, # Error|Minimize|Modal|Visible
531
+ title,
532
+ "ErrorText", None, None)
533
+ error.text("ErrorText", 50,9,280,48,3, "")
534
+ #error.control("ErrorIcon", "Icon", 15, 9, 24, 24, 5242881, None, "py.ico", None, None)
535
+ error.pushbutton("N",120,72,81,21,3,"No",None).event("EndDialog","ErrorNo")
536
+ error.pushbutton("Y",240,72,81,21,3,"Yes",None).event("EndDialog","ErrorYes")
537
+ error.pushbutton("A",0,72,81,21,3,"Abort",None).event("EndDialog","ErrorAbort")
538
+ error.pushbutton("C",42,72,81,21,3,"Cancel",None).event("EndDialog","ErrorCancel")
539
+ error.pushbutton("I",81,72,81,21,3,"Ignore",None).event("EndDialog","ErrorIgnore")
540
+ error.pushbutton("O",159,72,81,21,3,"Ok",None).event("EndDialog","ErrorOk")
541
+ error.pushbutton("R",198,72,81,21,3,"Retry",None).event("EndDialog","ErrorRetry")
542
+
543
+ #####################################################################
544
+ # Global "Query Cancel" dialog
545
+ cancel = Dialog(db, "CancelDlg", 50, 10, 260, 85, 3, title,
546
+ "No", "No", "No")
547
+ cancel.text("Text", 48, 15, 194, 30, 3,
548
+ "Are you sure you want to cancel [ProductName] installation?")
549
+ #cancel.control("Icon", "Icon", 15, 15, 24, 24, 5242881, None,
550
+ # "py.ico", None, None)
551
+ c=cancel.pushbutton("Yes", 72, 57, 56, 17, 3, "Yes", "No")
552
+ c.event("EndDialog", "Exit")
553
+
554
+ c=cancel.pushbutton("No", 132, 57, 56, 17, 3, "No", "Yes")
555
+ c.event("EndDialog", "Return")
556
+
557
+ #####################################################################
558
+ # Global "Wait for costing" dialog
559
+ costing = Dialog(db, "WaitForCostingDlg", 50, 10, 260, 85, modal, title,
560
+ "Return", "Return", "Return")
561
+ costing.text("Text", 48, 15, 194, 30, 3,
562
+ "Please wait while the installer finishes determining your disk space requirements.")
563
+ c = costing.pushbutton("Return", 102, 57, 56, 17, 3, "Return", None)
564
+ c.event("EndDialog", "Exit")
565
+
566
+ #####################################################################
567
+ # Preparation dialog: no user input except cancellation
568
+ prep = PyDialog(db, "PrepareDlg", x, y, w, h, modeless, title,
569
+ "Cancel", "Cancel", "Cancel")
570
+ prep.text("Description", 15, 70, 320, 40, 0x30003,
571
+ "Please wait while the Installer prepares to guide you through the installation.")
572
+ prep.title("Welcome to the [ProductName] Installer")
573
+ c=prep.text("ActionText", 15, 110, 320, 20, 0x30003, "Pondering...")
574
+ c.mapping("ActionText", "Text")
575
+ c=prep.text("ActionData", 15, 135, 320, 30, 0x30003, None)
576
+ c.mapping("ActionData", "Text")
577
+ prep.back("Back", None, active=0)
578
+ prep.next("Next", None, active=0)
579
+ c=prep.cancel("Cancel", None)
580
+ c.event("SpawnDialog", "CancelDlg")
581
+
582
+ #####################################################################
583
+ # Feature (Python directory) selection
584
+ seldlg = PyDialog(db, "SelectFeaturesDlg", x, y, w, h, modal, title,
585
+ "Next", "Next", "Cancel")
586
+ seldlg.title("Select Python Installations")
587
+
588
+ seldlg.text("Hint", 15, 30, 300, 20, 3,
589
+ "Select the Python locations where %s should be installed."
590
+ % self.distribution.get_fullname())
591
+
592
+ seldlg.back("< Back", None, active=0)
593
+ c = seldlg.next("Next >", "Cancel")
594
+ order = 1
595
+ c.event("[TARGETDIR]", "[SourceDir]", ordering=order)
596
+ for version in self.versions + [self.other_version]:
597
+ order += 1
598
+ c.event("[TARGETDIR]", "[TARGETDIR%s]" % version,
599
+ "FEATURE_SELECTED AND &Python%s=3" % version,
600
+ ordering=order)
601
+ c.event("SpawnWaitDialog", "WaitForCostingDlg", ordering=order + 1)
602
+ c.event("EndDialog", "Return", ordering=order + 2)
603
+ c = seldlg.cancel("Cancel", "Features")
604
+ c.event("SpawnDialog", "CancelDlg")
605
+
606
+ c = seldlg.control("Features", "SelectionTree", 15, 60, 300, 120, 3,
607
+ "FEATURE", None, "PathEdit", None)
608
+ c.event("[FEATURE_SELECTED]", "1")
609
+ ver = self.other_version
610
+ install_other_cond = "FEATURE_SELECTED AND &Python%s=3" % ver
611
+ dont_install_other_cond = "FEATURE_SELECTED AND &Python%s<>3" % ver
612
+
613
+ c = seldlg.text("Other", 15, 200, 300, 15, 3,
614
+ "Provide an alternate Python location")
615
+ c.condition("Enable", install_other_cond)
616
+ c.condition("Show", install_other_cond)
617
+ c.condition("Disable", dont_install_other_cond)
618
+ c.condition("Hide", dont_install_other_cond)
619
+
620
+ c = seldlg.control("PathEdit", "PathEdit", 15, 215, 300, 16, 1,
621
+ "TARGETDIR" + ver, None, "Next", None)
622
+ c.condition("Enable", install_other_cond)
623
+ c.condition("Show", install_other_cond)
624
+ c.condition("Disable", dont_install_other_cond)
625
+ c.condition("Hide", dont_install_other_cond)
626
+
627
+ #####################################################################
628
+ # Disk cost
629
+ cost = PyDialog(db, "DiskCostDlg", x, y, w, h, modal, title,
630
+ "OK", "OK", "OK", bitmap=False)
631
+ cost.text("Title", 15, 6, 200, 15, 0x30003,
632
+ r"{\DlgFontBold8}Disk Space Requirements")
633
+ cost.text("Description", 20, 20, 280, 20, 0x30003,
634
+ "The disk space required for the installation of the selected features.")
635
+ cost.text("Text", 20, 53, 330, 60, 3,
636
+ "The highlighted volumes (if any) do not have enough disk space "
637
+ "available for the currently selected features. You can either "
638
+ "remove some files from the highlighted volumes, or choose to "
639
+ "install less features onto local drive(s), or select different "
640
+ "destination drive(s).")
641
+ cost.control("VolumeList", "VolumeCostList", 20, 100, 330, 150, 393223,
642
+ None, "{120}{70}{70}{70}{70}", None, None)
643
+ cost.xbutton("OK", "Ok", None, 0.5).event("EndDialog", "Return")
644
+
645
+ #####################################################################
646
+ # WhichUsers Dialog. Only available on NT, and for privileged users.
647
+ # This must be run before FindRelatedProducts, because that will
648
+ # take into account whether the previous installation was per-user
649
+ # or per-machine. We currently don't support going back to this
650
+ # dialog after "Next" was selected; to support this, we would need to
651
+ # find how to reset the ALLUSERS property, and how to re-run
652
+ # FindRelatedProducts.
653
+ # On Windows9x, the ALLUSERS property is ignored on the command line
654
+ # and in the Property table, but installer fails according to the documentation
655
+ # if a dialog attempts to set ALLUSERS.
656
+ whichusers = PyDialog(db, "WhichUsersDlg", x, y, w, h, modal, title,
657
+ "AdminInstall", "Next", "Cancel")
658
+ whichusers.title("Select whether to install [ProductName] for all users of this computer.")
659
+ # A radio group with two options: allusers, justme
660
+ g = whichusers.radiogroup("AdminInstall", 15, 60, 260, 50, 3,
661
+ "WhichUsers", "", "Next")
662
+ g.add("ALL", 0, 5, 150, 20, "Install for all users")
663
+ g.add("JUSTME", 0, 25, 150, 20, "Install just for me")
664
+
665
+ whichusers.back("Back", None, active=0)
666
+
667
+ c = whichusers.next("Next >", "Cancel")
668
+ c.event("[ALLUSERS]", "1", 'WhichUsers="ALL"', 1)
669
+ c.event("EndDialog", "Return", ordering = 2)
670
+
671
+ c = whichusers.cancel("Cancel", "AdminInstall")
672
+ c.event("SpawnDialog", "CancelDlg")
673
+
674
+ #####################################################################
675
+ # Installation Progress dialog (modeless)
676
+ progress = PyDialog(db, "ProgressDlg", x, y, w, h, modeless, title,
677
+ "Cancel", "Cancel", "Cancel", bitmap=False)
678
+ progress.text("Title", 20, 15, 200, 15, 0x30003,
679
+ r"{\DlgFontBold8}[Progress1] [ProductName]")
680
+ progress.text("Text", 35, 65, 300, 30, 3,
681
+ "Please wait while the Installer [Progress2] [ProductName]. "
682
+ "This may take several minutes.")
683
+ progress.text("StatusLabel", 35, 100, 35, 20, 3, "Status:")
684
+
685
+ c=progress.text("ActionText", 70, 100, w-70, 20, 3, "Pondering...")
686
+ c.mapping("ActionText", "Text")
687
+
688
+ #c=progress.text("ActionData", 35, 140, 300, 20, 3, None)
689
+ #c.mapping("ActionData", "Text")
690
+
691
+ c=progress.control("ProgressBar", "ProgressBar", 35, 120, 300, 10, 65537,
692
+ None, "Progress done", None, None)
693
+ c.mapping("SetProgress", "Progress")
694
+
695
+ progress.back("< Back", "Next", active=False)
696
+ progress.next("Next >", "Cancel", active=False)
697
+ progress.cancel("Cancel", "Back").event("SpawnDialog", "CancelDlg")
698
+
699
+ ###################################################################
700
+ # Maintenance type: repair/uninstall
701
+ maint = PyDialog(db, "MaintenanceTypeDlg", x, y, w, h, modal, title,
702
+ "Next", "Next", "Cancel")
703
+ maint.title("Welcome to the [ProductName] Setup Wizard")
704
+ maint.text("BodyText", 15, 63, 330, 42, 3,
705
+ "Select whether you want to repair or remove [ProductName].")
706
+ g=maint.radiogroup("RepairRadioGroup", 15, 108, 330, 60, 3,
707
+ "MaintenanceForm_Action", "", "Next")
708
+ #g.add("Change", 0, 0, 200, 17, "&Change [ProductName]")
709
+ g.add("Repair", 0, 18, 200, 17, "&Repair [ProductName]")
710
+ g.add("Remove", 0, 36, 200, 17, "Re&move [ProductName]")
711
+
712
+ maint.back("< Back", None, active=False)
713
+ c=maint.next("Finish", "Cancel")
714
+ # Change installation: Change progress dialog to "Change", then ask
715
+ # for feature selection
716
+ #c.event("[Progress1]", "Change", 'MaintenanceForm_Action="Change"', 1)
717
+ #c.event("[Progress2]", "changes", 'MaintenanceForm_Action="Change"', 2)
718
+
719
+ # Reinstall: Change progress dialog to "Repair", then invoke reinstall
720
+ # Also set list of reinstalled features to "ALL"
721
+ c.event("[REINSTALL]", "ALL", 'MaintenanceForm_Action="Repair"', 5)
722
+ c.event("[Progress1]", "Repairing", 'MaintenanceForm_Action="Repair"', 6)
723
+ c.event("[Progress2]", "repairs", 'MaintenanceForm_Action="Repair"', 7)
724
+ c.event("Reinstall", "ALL", 'MaintenanceForm_Action="Repair"', 8)
725
+
726
+ # Uninstall: Change progress to "Remove", then invoke uninstall
727
+ # Also set list of removed features to "ALL"
728
+ c.event("[REMOVE]", "ALL", 'MaintenanceForm_Action="Remove"', 11)
729
+ c.event("[Progress1]", "Removing", 'MaintenanceForm_Action="Remove"', 12)
730
+ c.event("[Progress2]", "removes", 'MaintenanceForm_Action="Remove"', 13)
731
+ c.event("Remove", "ALL", 'MaintenanceForm_Action="Remove"', 14)
732
+
733
+ # Close dialog when maintenance action scheduled
734
+ c.event("EndDialog", "Return", 'MaintenanceForm_Action<>"Change"', 20)
735
+ #c.event("NewDialog", "SelectFeaturesDlg", 'MaintenanceForm_Action="Change"', 21)
736
+
737
+ maint.cancel("Cancel", "RepairRadioGroup").event("SpawnDialog", "CancelDlg")
738
+
739
+ def get_installer_filename(self, fullname):
740
+ # Factored out to allow overriding in subclasses
741
+ if self.target_version:
742
+ base_name = "%s.%s-py%s.msi" % (fullname, self.plat_name,
743
+ self.target_version)
744
+ else:
745
+ base_name = "%s.%s.msi" % (fullname, self.plat_name)
746
+ installer_name = os.path.join(self.dist_dir, base_name)
747
+ return installer_name
llava/lib/python3.10/distutils/command/build.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.build
2
+
3
+ Implements the Distutils 'build' command."""
4
+
5
+ import sys, os
6
+ from distutils.core import Command
7
+ from distutils.errors import DistutilsOptionError
8
+ from distutils.util import get_platform
9
+
10
+
11
+ def show_compilers():
12
+ from distutils.ccompiler import show_compilers
13
+ show_compilers()
14
+
15
+
16
+ class build(Command):
17
+
18
+ description = "build everything needed to install"
19
+
20
+ user_options = [
21
+ ('build-base=', 'b',
22
+ "base directory for build library"),
23
+ ('build-purelib=', None,
24
+ "build directory for platform-neutral distributions"),
25
+ ('build-platlib=', None,
26
+ "build directory for platform-specific distributions"),
27
+ ('build-lib=', None,
28
+ "build directory for all distribution (defaults to either " +
29
+ "build-purelib or build-platlib"),
30
+ ('build-scripts=', None,
31
+ "build directory for scripts"),
32
+ ('build-temp=', 't',
33
+ "temporary build directory"),
34
+ ('plat-name=', 'p',
35
+ "platform name to build for, if supported "
36
+ "(default: %s)" % get_platform()),
37
+ ('compiler=', 'c',
38
+ "specify the compiler type"),
39
+ ('parallel=', 'j',
40
+ "number of parallel build jobs"),
41
+ ('debug', 'g',
42
+ "compile extensions and libraries with debugging information"),
43
+ ('force', 'f',
44
+ "forcibly build everything (ignore file timestamps)"),
45
+ ('executable=', 'e',
46
+ "specify final destination interpreter path (build.py)"),
47
+ ]
48
+
49
+ boolean_options = ['debug', 'force']
50
+
51
+ help_options = [
52
+ ('help-compiler', None,
53
+ "list available compilers", show_compilers),
54
+ ]
55
+
56
+ def initialize_options(self):
57
+ self.build_base = 'build'
58
+ # these are decided only after 'build_base' has its final value
59
+ # (unless overridden by the user or client)
60
+ self.build_purelib = None
61
+ self.build_platlib = None
62
+ self.build_lib = None
63
+ self.build_temp = None
64
+ self.build_scripts = None
65
+ self.compiler = None
66
+ self.plat_name = None
67
+ self.debug = None
68
+ self.force = 0
69
+ self.executable = None
70
+ self.parallel = None
71
+
72
+ def finalize_options(self):
73
+ if self.plat_name is None:
74
+ self.plat_name = get_platform()
75
+ else:
76
+ # plat-name only supported for windows (other platforms are
77
+ # supported via ./configure flags, if at all). Avoid misleading
78
+ # other platforms.
79
+ if os.name != 'nt':
80
+ raise DistutilsOptionError(
81
+ "--plat-name only supported on Windows (try "
82
+ "using './configure --help' on your platform)")
83
+
84
+ plat_specifier = ".%s-%d.%d" % (self.plat_name, *sys.version_info[:2])
85
+
86
+ # Make it so Python 2.x and Python 2.x with --with-pydebug don't
87
+ # share the same build directories. Doing so confuses the build
88
+ # process for C modules
89
+ if hasattr(sys, 'gettotalrefcount'):
90
+ plat_specifier += '-pydebug'
91
+
92
+ # 'build_purelib' and 'build_platlib' just default to 'lib' and
93
+ # 'lib.<plat>' under the base build directory. We only use one of
94
+ # them for a given distribution, though --
95
+ if self.build_purelib is None:
96
+ self.build_purelib = os.path.join(self.build_base, 'lib')
97
+ if self.build_platlib is None:
98
+ self.build_platlib = os.path.join(self.build_base,
99
+ 'lib' + plat_specifier)
100
+
101
+ # 'build_lib' is the actual directory that we will use for this
102
+ # particular module distribution -- if user didn't supply it, pick
103
+ # one of 'build_purelib' or 'build_platlib'.
104
+ if self.build_lib is None:
105
+ if self.distribution.ext_modules:
106
+ self.build_lib = self.build_platlib
107
+ else:
108
+ self.build_lib = self.build_purelib
109
+
110
+ # 'build_temp' -- temporary directory for compiler turds,
111
+ # "build/temp.<plat>"
112
+ if self.build_temp is None:
113
+ self.build_temp = os.path.join(self.build_base,
114
+ 'temp' + plat_specifier)
115
+ if self.build_scripts is None:
116
+ self.build_scripts = os.path.join(self.build_base,
117
+ 'scripts-%d.%d' % sys.version_info[:2])
118
+
119
+ if self.executable is None and sys.executable:
120
+ self.executable = os.path.normpath(sys.executable)
121
+
122
+ if isinstance(self.parallel, str):
123
+ try:
124
+ self.parallel = int(self.parallel)
125
+ except ValueError:
126
+ raise DistutilsOptionError("parallel should be an integer")
127
+
128
+ def run(self):
129
+ # Run all relevant sub-commands. This will be some subset of:
130
+ # - build_py - pure Python modules
131
+ # - build_clib - standalone C libraries
132
+ # - build_ext - Python extensions
133
+ # - build_scripts - (Python) scripts
134
+ for cmd_name in self.get_sub_commands():
135
+ self.run_command(cmd_name)
136
+
137
+
138
+ # -- Predicates for the sub-command list ---------------------------
139
+
140
+ def has_pure_modules(self):
141
+ return self.distribution.has_pure_modules()
142
+
143
+ def has_c_libraries(self):
144
+ return self.distribution.has_c_libraries()
145
+
146
+ def has_ext_modules(self):
147
+ return self.distribution.has_ext_modules()
148
+
149
+ def has_scripts(self):
150
+ return self.distribution.has_scripts()
151
+
152
+
153
+ sub_commands = [('build_py', has_pure_modules),
154
+ ('build_clib', has_c_libraries),
155
+ ('build_ext', has_ext_modules),
156
+ ('build_scripts', has_scripts),
157
+ ]
llava/lib/python3.10/distutils/command/build_clib.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.build_clib
2
+
3
+ Implements the Distutils 'build_clib' command, to build a C/C++ library
4
+ that is included in the module distribution and needed by an extension
5
+ module."""
6
+
7
+
8
+ # XXX this module has *lots* of code ripped-off quite transparently from
9
+ # build_ext.py -- not surprisingly really, as the work required to build
10
+ # a static library from a collection of C source files is not really all
11
+ # that different from what's required to build a shared object file from
12
+ # a collection of C source files. Nevertheless, I haven't done the
13
+ # necessary refactoring to account for the overlap in code between the
14
+ # two modules, mainly because a number of subtle details changed in the
15
+ # cut 'n paste. Sigh.
16
+
17
+ import os
18
+ from distutils.core import Command
19
+ from distutils.errors import *
20
+ from distutils.sysconfig import customize_compiler
21
+ from distutils import log
22
+
23
+ def show_compilers():
24
+ from distutils.ccompiler import show_compilers
25
+ show_compilers()
26
+
27
+
28
+ class build_clib(Command):
29
+
30
+ description = "build C/C++ libraries used by Python extensions"
31
+
32
+ user_options = [
33
+ ('build-clib=', 'b',
34
+ "directory to build C/C++ libraries to"),
35
+ ('build-temp=', 't',
36
+ "directory to put temporary build by-products"),
37
+ ('debug', 'g',
38
+ "compile with debugging information"),
39
+ ('force', 'f',
40
+ "forcibly build everything (ignore file timestamps)"),
41
+ ('compiler=', 'c',
42
+ "specify the compiler type"),
43
+ ]
44
+
45
+ boolean_options = ['debug', 'force']
46
+
47
+ help_options = [
48
+ ('help-compiler', None,
49
+ "list available compilers", show_compilers),
50
+ ]
51
+
52
+ def initialize_options(self):
53
+ self.build_clib = None
54
+ self.build_temp = None
55
+
56
+ # List of libraries to build
57
+ self.libraries = None
58
+
59
+ # Compilation options for all libraries
60
+ self.include_dirs = None
61
+ self.define = None
62
+ self.undef = None
63
+ self.debug = None
64
+ self.force = 0
65
+ self.compiler = None
66
+
67
+
68
+ def finalize_options(self):
69
+ # This might be confusing: both build-clib and build-temp default
70
+ # to build-temp as defined by the "build" command. This is because
71
+ # I think that C libraries are really just temporary build
72
+ # by-products, at least from the point of view of building Python
73
+ # extensions -- but I want to keep my options open.
74
+ self.set_undefined_options('build',
75
+ ('build_temp', 'build_clib'),
76
+ ('build_temp', 'build_temp'),
77
+ ('compiler', 'compiler'),
78
+ ('debug', 'debug'),
79
+ ('force', 'force'))
80
+
81
+ self.libraries = self.distribution.libraries
82
+ if self.libraries:
83
+ self.check_library_list(self.libraries)
84
+
85
+ if self.include_dirs is None:
86
+ self.include_dirs = self.distribution.include_dirs or []
87
+ if isinstance(self.include_dirs, str):
88
+ self.include_dirs = self.include_dirs.split(os.pathsep)
89
+
90
+ # XXX same as for build_ext -- what about 'self.define' and
91
+ # 'self.undef' ?
92
+
93
+
94
+ def run(self):
95
+ if not self.libraries:
96
+ return
97
+
98
+ # Yech -- this is cut 'n pasted from build_ext.py!
99
+ from distutils.ccompiler import new_compiler
100
+ self.compiler = new_compiler(compiler=self.compiler,
101
+ dry_run=self.dry_run,
102
+ force=self.force)
103
+ customize_compiler(self.compiler)
104
+
105
+ if self.include_dirs is not None:
106
+ self.compiler.set_include_dirs(self.include_dirs)
107
+ if self.define is not None:
108
+ # 'define' option is a list of (name,value) tuples
109
+ for (name,value) in self.define:
110
+ self.compiler.define_macro(name, value)
111
+ if self.undef is not None:
112
+ for macro in self.undef:
113
+ self.compiler.undefine_macro(macro)
114
+
115
+ self.build_libraries(self.libraries)
116
+
117
+
118
+ def check_library_list(self, libraries):
119
+ """Ensure that the list of libraries is valid.
120
+
121
+ `library` is presumably provided as a command option 'libraries'.
122
+ This method checks that it is a list of 2-tuples, where the tuples
123
+ are (library_name, build_info_dict).
124
+
125
+ Raise DistutilsSetupError if the structure is invalid anywhere;
126
+ just returns otherwise.
127
+ """
128
+ if not isinstance(libraries, list):
129
+ raise DistutilsSetupError(
130
+ "'libraries' option must be a list of tuples")
131
+
132
+ for lib in libraries:
133
+ if not isinstance(lib, tuple) and len(lib) != 2:
134
+ raise DistutilsSetupError(
135
+ "each element of 'libraries' must a 2-tuple")
136
+
137
+ name, build_info = lib
138
+
139
+ if not isinstance(name, str):
140
+ raise DistutilsSetupError(
141
+ "first element of each tuple in 'libraries' "
142
+ "must be a string (the library name)")
143
+
144
+ if '/' in name or (os.sep != '/' and os.sep in name):
145
+ raise DistutilsSetupError("bad library name '%s': "
146
+ "may not contain directory separators" % lib[0])
147
+
148
+ if not isinstance(build_info, dict):
149
+ raise DistutilsSetupError(
150
+ "second element of each tuple in 'libraries' "
151
+ "must be a dictionary (build info)")
152
+
153
+
154
+ def get_library_names(self):
155
+ # Assume the library list is valid -- 'check_library_list()' is
156
+ # called from 'finalize_options()', so it should be!
157
+ if not self.libraries:
158
+ return None
159
+
160
+ lib_names = []
161
+ for (lib_name, build_info) in self.libraries:
162
+ lib_names.append(lib_name)
163
+ return lib_names
164
+
165
+
166
+ def get_source_files(self):
167
+ self.check_library_list(self.libraries)
168
+ filenames = []
169
+ for (lib_name, build_info) in self.libraries:
170
+ sources = build_info.get('sources')
171
+ if sources is None or not isinstance(sources, (list, tuple)):
172
+ raise DistutilsSetupError(
173
+ "in 'libraries' option (library '%s'), "
174
+ "'sources' must be present and must be "
175
+ "a list of source filenames" % lib_name)
176
+
177
+ filenames.extend(sources)
178
+ return filenames
179
+
180
+
181
+ def build_libraries(self, libraries):
182
+ for (lib_name, build_info) in libraries:
183
+ sources = build_info.get('sources')
184
+ if sources is None or not isinstance(sources, (list, tuple)):
185
+ raise DistutilsSetupError(
186
+ "in 'libraries' option (library '%s'), "
187
+ "'sources' must be present and must be "
188
+ "a list of source filenames" % lib_name)
189
+ sources = list(sources)
190
+
191
+ log.info("building '%s' library", lib_name)
192
+
193
+ # First, compile the source code to object files in the library
194
+ # directory. (This should probably change to putting object
195
+ # files in a temporary build directory.)
196
+ macros = build_info.get('macros')
197
+ include_dirs = build_info.get('include_dirs')
198
+ objects = self.compiler.compile(sources,
199
+ output_dir=self.build_temp,
200
+ macros=macros,
201
+ include_dirs=include_dirs,
202
+ debug=self.debug)
203
+
204
+ # Now "link" the object files together into a static library.
205
+ # (On Unix at least, this isn't really linking -- it just
206
+ # builds an archive. Whatever.)
207
+ self.compiler.create_static_lib(objects, lib_name,
208
+ output_dir=self.build_clib,
209
+ debug=self.debug)
llava/lib/python3.10/distutils/command/build_scripts.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.build_scripts
2
+
3
+ Implements the Distutils 'build_scripts' command."""
4
+
5
+ import os, re
6
+ from stat import ST_MODE
7
+ from distutils import sysconfig
8
+ from distutils.core import Command
9
+ from distutils.dep_util import newer
10
+ from distutils.util import convert_path, Mixin2to3
11
+ from distutils import log
12
+ import tokenize
13
+
14
+ # check if Python is called on the first line with this expression
15
+ first_line_re = re.compile(b'^#!.*python[0-9.]*([ \t].*)?$')
16
+
17
+ class build_scripts(Command):
18
+
19
+ description = "\"build\" scripts (copy and fixup #! line)"
20
+
21
+ user_options = [
22
+ ('build-dir=', 'd', "directory to \"build\" (copy) to"),
23
+ ('force', 'f', "forcibly build everything (ignore file timestamps"),
24
+ ('executable=', 'e', "specify final destination interpreter path"),
25
+ ]
26
+
27
+ boolean_options = ['force']
28
+
29
+
30
+ def initialize_options(self):
31
+ self.build_dir = None
32
+ self.scripts = None
33
+ self.force = None
34
+ self.executable = None
35
+ self.outfiles = None
36
+
37
+ def finalize_options(self):
38
+ self.set_undefined_options('build',
39
+ ('build_scripts', 'build_dir'),
40
+ ('force', 'force'),
41
+ ('executable', 'executable'))
42
+ self.scripts = self.distribution.scripts
43
+
44
+ def get_source_files(self):
45
+ return self.scripts
46
+
47
+ def run(self):
48
+ if not self.scripts:
49
+ return
50
+ self.copy_scripts()
51
+
52
+
53
+ def copy_scripts(self):
54
+ r"""Copy each script listed in 'self.scripts'; if it's marked as a
55
+ Python script in the Unix way (first line matches 'first_line_re',
56
+ ie. starts with "\#!" and contains "python"), then adjust the first
57
+ line to refer to the current Python interpreter as we copy.
58
+ """
59
+ self.mkpath(self.build_dir)
60
+ outfiles = []
61
+ updated_files = []
62
+ for script in self.scripts:
63
+ adjust = False
64
+ script = convert_path(script)
65
+ outfile = os.path.join(self.build_dir, os.path.basename(script))
66
+ outfiles.append(outfile)
67
+
68
+ if not self.force and not newer(script, outfile):
69
+ log.debug("not copying %s (up-to-date)", script)
70
+ continue
71
+
72
+ # Always open the file, but ignore failures in dry-run mode --
73
+ # that way, we'll get accurate feedback if we can read the
74
+ # script.
75
+ try:
76
+ f = open(script, "rb")
77
+ except OSError:
78
+ if not self.dry_run:
79
+ raise
80
+ f = None
81
+ else:
82
+ encoding, lines = tokenize.detect_encoding(f.readline)
83
+ f.seek(0)
84
+ first_line = f.readline()
85
+ if not first_line:
86
+ self.warn("%s is an empty file (skipping)" % script)
87
+ continue
88
+
89
+ match = first_line_re.match(first_line)
90
+ if match:
91
+ adjust = True
92
+ post_interp = match.group(1) or b''
93
+
94
+ if adjust:
95
+ log.info("copying and adjusting %s -> %s", script,
96
+ self.build_dir)
97
+ updated_files.append(outfile)
98
+ if not self.dry_run:
99
+ if not sysconfig.python_build:
100
+ executable = self.executable
101
+ else:
102
+ executable = os.path.join(
103
+ sysconfig.get_config_var("BINDIR"),
104
+ "python%s%s" % (sysconfig.get_config_var("VERSION"),
105
+ sysconfig.get_config_var("EXE")))
106
+ executable = os.fsencode(executable)
107
+ shebang = b"#!" + executable + post_interp + b"\n"
108
+ # Python parser starts to read a script using UTF-8 until
109
+ # it gets a #coding:xxx cookie. The shebang has to be the
110
+ # first line of a file, the #coding:xxx cookie cannot be
111
+ # written before. So the shebang has to be decodable from
112
+ # UTF-8.
113
+ try:
114
+ shebang.decode('utf-8')
115
+ except UnicodeDecodeError:
116
+ raise ValueError(
117
+ "The shebang ({!r}) is not decodable "
118
+ "from utf-8".format(shebang))
119
+ # If the script is encoded to a custom encoding (use a
120
+ # #coding:xxx cookie), the shebang has to be decodable from
121
+ # the script encoding too.
122
+ try:
123
+ shebang.decode(encoding)
124
+ except UnicodeDecodeError:
125
+ raise ValueError(
126
+ "The shebang ({!r}) is not decodable "
127
+ "from the script encoding ({})"
128
+ .format(shebang, encoding))
129
+ with open(outfile, "wb") as outf:
130
+ outf.write(shebang)
131
+ outf.writelines(f.readlines())
132
+ if f:
133
+ f.close()
134
+ else:
135
+ if f:
136
+ f.close()
137
+ updated_files.append(outfile)
138
+ self.copy_file(script, outfile)
139
+
140
+ if os.name == 'posix':
141
+ for file in outfiles:
142
+ if self.dry_run:
143
+ log.info("changing mode of %s", file)
144
+ else:
145
+ oldmode = os.stat(file)[ST_MODE] & 0o7777
146
+ newmode = (oldmode | 0o555) & 0o7777
147
+ if newmode != oldmode:
148
+ log.info("changing mode of %s from %o to %o",
149
+ file, oldmode, newmode)
150
+ os.chmod(file, newmode)
151
+ # XXX should we modify self.outfiles?
152
+ return outfiles, updated_files
153
+
154
+ class build_scripts_2to3(build_scripts, Mixin2to3):
155
+
156
+ def copy_scripts(self):
157
+ outfiles, updated_files = build_scripts.copy_scripts(self)
158
+ if not self.dry_run:
159
+ self.run_2to3(updated_files)
160
+ return outfiles, updated_files
llava/lib/python3.10/distutils/command/check.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.check
2
+
3
+ Implements the Distutils 'check' command.
4
+ """
5
+ from distutils.core import Command
6
+ from distutils.errors import DistutilsSetupError
7
+
8
+ try:
9
+ # docutils is installed
10
+ from docutils.utils import Reporter
11
+ from docutils.parsers.rst import Parser
12
+ from docutils import frontend
13
+ from docutils import nodes
14
+
15
+ class SilentReporter(Reporter):
16
+
17
+ def __init__(self, source, report_level, halt_level, stream=None,
18
+ debug=0, encoding='ascii', error_handler='replace'):
19
+ self.messages = []
20
+ Reporter.__init__(self, source, report_level, halt_level, stream,
21
+ debug, encoding, error_handler)
22
+
23
+ def system_message(self, level, message, *children, **kwargs):
24
+ self.messages.append((level, message, children, kwargs))
25
+ return nodes.system_message(message, level=level,
26
+ type=self.levels[level],
27
+ *children, **kwargs)
28
+
29
+ HAS_DOCUTILS = True
30
+ except Exception:
31
+ # Catch all exceptions because exceptions besides ImportError probably
32
+ # indicate that docutils is not ported to Py3k.
33
+ HAS_DOCUTILS = False
34
+
35
+ class check(Command):
36
+ """This command checks the meta-data of the package.
37
+ """
38
+ description = ("perform some checks on the package")
39
+ user_options = [('metadata', 'm', 'Verify meta-data'),
40
+ ('restructuredtext', 'r',
41
+ ('Checks if long string meta-data syntax '
42
+ 'are reStructuredText-compliant')),
43
+ ('strict', 's',
44
+ 'Will exit with an error if a check fails')]
45
+
46
+ boolean_options = ['metadata', 'restructuredtext', 'strict']
47
+
48
+ def initialize_options(self):
49
+ """Sets default values for options."""
50
+ self.restructuredtext = 0
51
+ self.metadata = 1
52
+ self.strict = 0
53
+ self._warnings = 0
54
+
55
+ def finalize_options(self):
56
+ pass
57
+
58
+ def warn(self, msg):
59
+ """Counts the number of warnings that occurs."""
60
+ self._warnings += 1
61
+ return Command.warn(self, msg)
62
+
63
+ def run(self):
64
+ """Runs the command."""
65
+ # perform the various tests
66
+ if self.metadata:
67
+ self.check_metadata()
68
+ if self.restructuredtext:
69
+ if HAS_DOCUTILS:
70
+ self.check_restructuredtext()
71
+ elif self.strict:
72
+ raise DistutilsSetupError('The docutils package is needed.')
73
+
74
+ # let's raise an error in strict mode, if we have at least
75
+ # one warning
76
+ if self.strict and self._warnings > 0:
77
+ raise DistutilsSetupError('Please correct your package.')
78
+
79
+ def check_metadata(self):
80
+ """Ensures that all required elements of meta-data are supplied.
81
+
82
+ Required fields:
83
+ name, version, URL
84
+
85
+ Recommended fields:
86
+ (author and author_email) or (maintainer and maintainer_email)
87
+
88
+ Warns if any are missing.
89
+ """
90
+ metadata = self.distribution.metadata
91
+
92
+ missing = []
93
+ for attr in ('name', 'version', 'url'):
94
+ if not (hasattr(metadata, attr) and getattr(metadata, attr)):
95
+ missing.append(attr)
96
+
97
+ if missing:
98
+ self.warn("missing required meta-data: %s" % ', '.join(missing))
99
+ if metadata.author:
100
+ if not metadata.author_email:
101
+ self.warn("missing meta-data: if 'author' supplied, " +
102
+ "'author_email' should be supplied too")
103
+ elif metadata.maintainer:
104
+ if not metadata.maintainer_email:
105
+ self.warn("missing meta-data: if 'maintainer' supplied, " +
106
+ "'maintainer_email' should be supplied too")
107
+ else:
108
+ self.warn("missing meta-data: either (author and author_email) " +
109
+ "or (maintainer and maintainer_email) " +
110
+ "should be supplied")
111
+
112
+ def check_restructuredtext(self):
113
+ """Checks if the long string fields are reST-compliant."""
114
+ data = self.distribution.get_long_description()
115
+ for warning in self._check_rst_data(data):
116
+ line = warning[-1].get('line')
117
+ if line is None:
118
+ warning = warning[1]
119
+ else:
120
+ warning = '%s (line %s)' % (warning[1], line)
121
+ self.warn(warning)
122
+
123
+ def _check_rst_data(self, data):
124
+ """Returns warnings when the provided data doesn't compile."""
125
+ # the include and csv_table directives need this to be a path
126
+ source_path = self.distribution.script_name or 'setup.py'
127
+ parser = Parser()
128
+ settings = frontend.OptionParser(components=(Parser,)).get_default_values()
129
+ settings.tab_width = 4
130
+ settings.pep_references = None
131
+ settings.rfc_references = None
132
+ reporter = SilentReporter(source_path,
133
+ settings.report_level,
134
+ settings.halt_level,
135
+ stream=settings.warning_stream,
136
+ debug=settings.debug,
137
+ encoding=settings.error_encoding,
138
+ error_handler=settings.error_encoding_error_handler)
139
+
140
+ document = nodes.document(settings, reporter, source=source_path)
141
+ document.note_source(source_path, -1)
142
+ try:
143
+ parser.parse(data, document)
144
+ except AttributeError as e:
145
+ reporter.messages.append(
146
+ (-1, 'Could not finish the parsing: %s.' % e, '', {}))
147
+
148
+ return reporter.messages
llava/lib/python3.10/distutils/command/install.py ADDED
@@ -0,0 +1,679 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.install
2
+
3
+ Implements the Distutils 'install' command."""
4
+
5
+ import sys
6
+ import sysconfig
7
+ import os
8
+ import re
9
+
10
+ from distutils import log
11
+ from distutils.core import Command
12
+ from distutils.debug import DEBUG
13
+ from distutils.sysconfig import get_config_vars
14
+ from distutils.errors import DistutilsPlatformError
15
+ from distutils.file_util import write_file
16
+ from distutils.util import convert_path, subst_vars, change_root
17
+ from distutils.util import get_platform
18
+ from distutils.errors import DistutilsOptionError
19
+
20
+ from site import USER_BASE
21
+ from site import USER_SITE
22
+
23
+ HAS_USER_SITE = (USER_SITE is not None)
24
+
25
+ # The keys to an installation scheme; if any new types of files are to be
26
+ # installed, be sure to add an entry to every scheme in
27
+ # sysconfig._INSTALL_SCHEMES, and to SCHEME_KEYS here.
28
+ SCHEME_KEYS = ('purelib', 'platlib', 'headers', 'scripts', 'data')
29
+
30
+ # The following code provides backward-compatible INSTALL_SCHEMES
31
+ # while making the sysconfig module the single point of truth.
32
+ # This makes it easier for OS distributions where they need to
33
+ # alter locations for packages installations in a single place.
34
+ # Note that this module is deprecated (PEP 632); all consumers
35
+ # of this information should switch to using sysconfig directly.
36
+ INSTALL_SCHEMES = {"unix_prefix": {}, "unix_home": {}, "nt": {}}
37
+
38
+ # Copy from sysconfig._INSTALL_SCHEMES
39
+ for key in SCHEME_KEYS:
40
+ for distutils_scheme_name, sys_scheme_name in (
41
+ ("unix_prefix", "posix_prefix"), ("unix_home", "posix_home"),
42
+ ("nt", "nt")):
43
+ sys_key = key
44
+ sys_scheme = sysconfig._INSTALL_SCHEMES[sys_scheme_name]
45
+ if key == "headers" and key not in sys_scheme:
46
+ # On POSIX-y platforms, Python will:
47
+ # - Build from .h files in 'headers' (only there when
48
+ # building CPython)
49
+ # - Install .h files to 'include'
50
+ # When 'headers' is missing, fall back to 'include'
51
+ sys_key = 'include'
52
+ INSTALL_SCHEMES[distutils_scheme_name][key] = sys_scheme[sys_key]
53
+
54
+ # Transformation to different template format
55
+ for main_key in INSTALL_SCHEMES:
56
+ for key, value in INSTALL_SCHEMES[main_key].items():
57
+ # Change all ocurences of {variable} to $variable
58
+ value = re.sub(r"\{(.+?)\}", r"$\g<1>", value)
59
+ value = value.replace("$installed_base", "$base")
60
+ value = value.replace("$py_version_nodot_plat", "$py_version_nodot")
61
+ if key == "headers":
62
+ value += "/$dist_name"
63
+ if sys.version_info >= (3, 9) and key == "platlib":
64
+ # platlibdir is available since 3.9: bpo-1294959
65
+ value = value.replace("/lib/", "/$platlibdir/")
66
+ INSTALL_SCHEMES[main_key][key] = value
67
+
68
+ # The following part of INSTALL_SCHEMES has a different definition
69
+ # than the one in sysconfig, but because both depend on the site module,
70
+ # the outcomes should be the same.
71
+ if HAS_USER_SITE:
72
+ INSTALL_SCHEMES['nt_user'] = {
73
+ 'purelib': '$usersite',
74
+ 'platlib': '$usersite',
75
+ 'headers': '$userbase/Python$py_version_nodot/Include/$dist_name',
76
+ 'scripts': '$userbase/Python$py_version_nodot/Scripts',
77
+ 'data' : '$userbase',
78
+ }
79
+
80
+ INSTALL_SCHEMES['unix_user'] = {
81
+ 'purelib': '$usersite',
82
+ 'platlib': '$usersite',
83
+ 'headers':
84
+ '$userbase/include/python$py_version_short$abiflags/$dist_name',
85
+ 'scripts': '$userbase/bin',
86
+ 'data' : '$userbase',
87
+ }
88
+
89
+
90
+ class install(Command):
91
+
92
+ description = "install everything from build directory"
93
+
94
+ user_options = [
95
+ # Select installation scheme and set base director(y|ies)
96
+ ('prefix=', None,
97
+ "installation prefix"),
98
+ ('exec-prefix=', None,
99
+ "(Unix only) prefix for platform-specific files"),
100
+ ('home=', None,
101
+ "(Unix only) home directory to install under"),
102
+
103
+ # Or, just set the base director(y|ies)
104
+ ('install-base=', None,
105
+ "base installation directory (instead of --prefix or --home)"),
106
+ ('install-platbase=', None,
107
+ "base installation directory for platform-specific files " +
108
+ "(instead of --exec-prefix or --home)"),
109
+ ('root=', None,
110
+ "install everything relative to this alternate root directory"),
111
+
112
+ # Or, explicitly set the installation scheme
113
+ ('install-purelib=', None,
114
+ "installation directory for pure Python module distributions"),
115
+ ('install-platlib=', None,
116
+ "installation directory for non-pure module distributions"),
117
+ ('install-lib=', None,
118
+ "installation directory for all module distributions " +
119
+ "(overrides --install-purelib and --install-platlib)"),
120
+
121
+ ('install-headers=', None,
122
+ "installation directory for C/C++ headers"),
123
+ ('install-scripts=', None,
124
+ "installation directory for Python scripts"),
125
+ ('install-data=', None,
126
+ "installation directory for data files"),
127
+
128
+ # Byte-compilation options -- see install_lib.py for details, as
129
+ # these are duplicated from there (but only install_lib does
130
+ # anything with them).
131
+ ('compile', 'c', "compile .py to .pyc [default]"),
132
+ ('no-compile', None, "don't compile .py files"),
133
+ ('optimize=', 'O',
134
+ "also compile with optimization: -O1 for \"python -O\", "
135
+ "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),
136
+
137
+ # Miscellaneous control options
138
+ ('force', 'f',
139
+ "force installation (overwrite any existing files)"),
140
+ ('skip-build', None,
141
+ "skip rebuilding everything (for testing/debugging)"),
142
+
143
+ # Where to install documentation (eventually!)
144
+ #('doc-format=', None, "format of documentation to generate"),
145
+ #('install-man=', None, "directory for Unix man pages"),
146
+ #('install-html=', None, "directory for HTML documentation"),
147
+ #('install-info=', None, "directory for GNU info files"),
148
+
149
+ ('record=', None,
150
+ "filename in which to record list of installed files"),
151
+ ]
152
+
153
+ boolean_options = ['compile', 'force', 'skip-build']
154
+
155
+ if HAS_USER_SITE:
156
+ user_options.append(('user', None,
157
+ "install in user site-package '%s'" % USER_SITE))
158
+ boolean_options.append('user')
159
+
160
+ negative_opt = {'no-compile' : 'compile'}
161
+
162
+
163
+ def initialize_options(self):
164
+ """Initializes options."""
165
+ # High-level options: these select both an installation base
166
+ # and scheme.
167
+ self.prefix = None
168
+ self.exec_prefix = None
169
+ self.home = None
170
+ self.user = 0
171
+
172
+ # These select only the installation base; it's up to the user to
173
+ # specify the installation scheme (currently, that means supplying
174
+ # the --install-{platlib,purelib,scripts,data} options).
175
+ self.install_base = None
176
+ self.install_platbase = None
177
+ self.root = None
178
+
179
+ # These options are the actual installation directories; if not
180
+ # supplied by the user, they are filled in using the installation
181
+ # scheme implied by prefix/exec-prefix/home and the contents of
182
+ # that installation scheme.
183
+ self.install_purelib = None # for pure module distributions
184
+ self.install_platlib = None # non-pure (dists w/ extensions)
185
+ self.install_headers = None # for C/C++ headers
186
+ self.install_lib = None # set to either purelib or platlib
187
+ self.install_scripts = None
188
+ self.install_data = None
189
+ if HAS_USER_SITE:
190
+ self.install_userbase = USER_BASE
191
+ self.install_usersite = USER_SITE
192
+
193
+ self.compile = None
194
+ self.optimize = None
195
+
196
+ # Deprecated
197
+ # These two are for putting non-packagized distributions into their
198
+ # own directory and creating a .pth file if it makes sense.
199
+ # 'extra_path' comes from the setup file; 'install_path_file' can
200
+ # be turned off if it makes no sense to install a .pth file. (But
201
+ # better to install it uselessly than to guess wrong and not
202
+ # install it when it's necessary and would be used!) Currently,
203
+ # 'install_path_file' is always true unless some outsider meddles
204
+ # with it.
205
+ self.extra_path = None
206
+ self.install_path_file = 1
207
+
208
+ # 'force' forces installation, even if target files are not
209
+ # out-of-date. 'skip_build' skips running the "build" command,
210
+ # handy if you know it's not necessary. 'warn_dir' (which is *not*
211
+ # a user option, it's just there so the bdist_* commands can turn
212
+ # it off) determines whether we warn about installing to a
213
+ # directory not in sys.path.
214
+ self.force = 0
215
+ self.skip_build = 0
216
+ self.warn_dir = 1
217
+
218
+ # These are only here as a conduit from the 'build' command to the
219
+ # 'install_*' commands that do the real work. ('build_base' isn't
220
+ # actually used anywhere, but it might be useful in future.) They
221
+ # are not user options, because if the user told the install
222
+ # command where the build directory is, that wouldn't affect the
223
+ # build command.
224
+ self.build_base = None
225
+ self.build_lib = None
226
+
227
+ # Not defined yet because we don't know anything about
228
+ # documentation yet.
229
+ #self.install_man = None
230
+ #self.install_html = None
231
+ #self.install_info = None
232
+
233
+ self.record = None
234
+
235
+
236
+ # -- Option finalizing methods -------------------------------------
237
+ # (This is rather more involved than for most commands,
238
+ # because this is where the policy for installing third-
239
+ # party Python modules on various platforms given a wide
240
+ # array of user input is decided. Yes, it's quite complex!)
241
+
242
+ def finalize_options(self):
243
+ """Finalizes options."""
244
+ # This method (and its helpers, like 'finalize_unix()',
245
+ # 'finalize_other()', and 'select_scheme()') is where the default
246
+ # installation directories for modules, extension modules, and
247
+ # anything else we care to install from a Python module
248
+ # distribution. Thus, this code makes a pretty important policy
249
+ # statement about how third-party stuff is added to a Python
250
+ # installation! Note that the actual work of installation is done
251
+ # by the relatively simple 'install_*' commands; they just take
252
+ # their orders from the installation directory options determined
253
+ # here.
254
+
255
+ # Check for errors/inconsistencies in the options; first, stuff
256
+ # that's wrong on any platform.
257
+
258
+ if ((self.prefix or self.exec_prefix or self.home) and
259
+ (self.install_base or self.install_platbase)):
260
+ raise DistutilsOptionError(
261
+ "must supply either prefix/exec-prefix/home or " +
262
+ "install-base/install-platbase -- not both")
263
+
264
+ if self.home and (self.prefix or self.exec_prefix):
265
+ raise DistutilsOptionError(
266
+ "must supply either home or prefix/exec-prefix -- not both")
267
+
268
+ if self.user and (self.prefix or self.exec_prefix or self.home or
269
+ self.install_base or self.install_platbase):
270
+ raise DistutilsOptionError("can't combine user with prefix, "
271
+ "exec_prefix/home, or install_(plat)base")
272
+
273
+ # Next, stuff that's wrong (or dubious) only on certain platforms.
274
+ if os.name != "posix":
275
+ if self.exec_prefix:
276
+ self.warn("exec-prefix option ignored on this platform")
277
+ self.exec_prefix = None
278
+
279
+ # Now the interesting logic -- so interesting that we farm it out
280
+ # to other methods. The goal of these methods is to set the final
281
+ # values for the install_{lib,scripts,data,...} options, using as
282
+ # input a heady brew of prefix, exec_prefix, home, install_base,
283
+ # install_platbase, user-supplied versions of
284
+ # install_{purelib,platlib,lib,scripts,data,...}, and the
285
+ # INSTALL_SCHEME dictionary above. Phew!
286
+
287
+ self.dump_dirs("pre-finalize_{unix,other}")
288
+
289
+ if os.name == 'posix':
290
+ self.finalize_unix()
291
+ else:
292
+ self.finalize_other()
293
+
294
+ self.dump_dirs("post-finalize_{unix,other}()")
295
+
296
+ # Expand configuration variables, tilde, etc. in self.install_base
297
+ # and self.install_platbase -- that way, we can use $base or
298
+ # $platbase in the other installation directories and not worry
299
+ # about needing recursive variable expansion (shudder).
300
+
301
+ py_version = sys.version.split()[0]
302
+ (prefix, exec_prefix) = get_config_vars('prefix', 'exec_prefix')
303
+ try:
304
+ abiflags = sys.abiflags
305
+ except AttributeError:
306
+ # sys.abiflags may not be defined on all platforms.
307
+ abiflags = ''
308
+ self.config_vars = {'dist_name': self.distribution.get_name(),
309
+ 'dist_version': self.distribution.get_version(),
310
+ 'dist_fullname': self.distribution.get_fullname(),
311
+ 'py_version': py_version,
312
+ 'py_version_short': '%d.%d' % sys.version_info[:2],
313
+ 'py_version_nodot': '%d%d' % sys.version_info[:2],
314
+ 'sys_prefix': prefix,
315
+ 'prefix': prefix,
316
+ 'sys_exec_prefix': exec_prefix,
317
+ 'exec_prefix': exec_prefix,
318
+ 'abiflags': abiflags,
319
+ 'platlibdir': sys.platlibdir,
320
+ }
321
+
322
+ if HAS_USER_SITE:
323
+ self.config_vars['userbase'] = self.install_userbase
324
+ self.config_vars['usersite'] = self.install_usersite
325
+
326
+ if sysconfig.is_python_build(True):
327
+ self.config_vars['srcdir'] = sysconfig.get_config_var('srcdir')
328
+
329
+ self.expand_basedirs()
330
+
331
+ self.dump_dirs("post-expand_basedirs()")
332
+
333
+ # Now define config vars for the base directories so we can expand
334
+ # everything else.
335
+ self.config_vars['base'] = self.install_base
336
+ self.config_vars['platbase'] = self.install_platbase
337
+
338
+ if DEBUG:
339
+ from pprint import pprint
340
+ print("config vars:")
341
+ pprint(self.config_vars)
342
+
343
+ # Expand "~" and configuration variables in the installation
344
+ # directories.
345
+ self.expand_dirs()
346
+
347
+ self.dump_dirs("post-expand_dirs()")
348
+
349
+ # Create directories in the home dir:
350
+ if self.user:
351
+ self.create_home_path()
352
+
353
+ # Pick the actual directory to install all modules to: either
354
+ # install_purelib or install_platlib, depending on whether this
355
+ # module distribution is pure or not. Of course, if the user
356
+ # already specified install_lib, use their selection.
357
+ if self.install_lib is None:
358
+ if self.distribution.ext_modules: # has extensions: non-pure
359
+ self.install_lib = self.install_platlib
360
+ else:
361
+ self.install_lib = self.install_purelib
362
+
363
+
364
+ # Convert directories from Unix /-separated syntax to the local
365
+ # convention.
366
+ self.convert_paths('lib', 'purelib', 'platlib',
367
+ 'scripts', 'data', 'headers')
368
+ if HAS_USER_SITE:
369
+ self.convert_paths('userbase', 'usersite')
370
+
371
+ # Deprecated
372
+ # Well, we're not actually fully completely finalized yet: we still
373
+ # have to deal with 'extra_path', which is the hack for allowing
374
+ # non-packagized module distributions (hello, Numerical Python!) to
375
+ # get their own directories.
376
+ self.handle_extra_path()
377
+ self.install_libbase = self.install_lib # needed for .pth file
378
+ self.install_lib = os.path.join(self.install_lib, self.extra_dirs)
379
+
380
+ # If a new root directory was supplied, make all the installation
381
+ # dirs relative to it.
382
+ if self.root is not None:
383
+ self.change_roots('libbase', 'lib', 'purelib', 'platlib',
384
+ 'scripts', 'data', 'headers')
385
+
386
+ self.dump_dirs("after prepending root")
387
+
388
+ # Find out the build directories, ie. where to install from.
389
+ self.set_undefined_options('build',
390
+ ('build_base', 'build_base'),
391
+ ('build_lib', 'build_lib'))
392
+
393
+ # Punt on doc directories for now -- after all, we're punting on
394
+ # documentation completely!
395
+
396
+ def dump_dirs(self, msg):
397
+ """Dumps the list of user options."""
398
+ if not DEBUG:
399
+ return
400
+ from distutils.fancy_getopt import longopt_xlate
401
+ log.debug(msg + ":")
402
+ for opt in self.user_options:
403
+ opt_name = opt[0]
404
+ if opt_name[-1] == "=":
405
+ opt_name = opt_name[0:-1]
406
+ if opt_name in self.negative_opt:
407
+ opt_name = self.negative_opt[opt_name]
408
+ opt_name = opt_name.translate(longopt_xlate)
409
+ val = not getattr(self, opt_name)
410
+ else:
411
+ opt_name = opt_name.translate(longopt_xlate)
412
+ val = getattr(self, opt_name)
413
+ log.debug(" %s: %s", opt_name, val)
414
+
415
+ def finalize_unix(self):
416
+ """Finalizes options for posix platforms."""
417
+ if self.install_base is not None or self.install_platbase is not None:
418
+ if ((self.install_lib is None and
419
+ self.install_purelib is None and
420
+ self.install_platlib is None) or
421
+ self.install_headers is None or
422
+ self.install_scripts is None or
423
+ self.install_data is None):
424
+ raise DistutilsOptionError(
425
+ "install-base or install-platbase supplied, but "
426
+ "installation scheme is incomplete")
427
+ return
428
+
429
+ if self.user:
430
+ if self.install_userbase is None:
431
+ raise DistutilsPlatformError(
432
+ "User base directory is not specified")
433
+ self.install_base = self.install_platbase = self.install_userbase
434
+ self.select_scheme("unix_user")
435
+ elif self.home is not None:
436
+ self.install_base = self.install_platbase = self.home
437
+ self.select_scheme("unix_home")
438
+ else:
439
+ if self.prefix is None:
440
+ if self.exec_prefix is not None:
441
+ raise DistutilsOptionError(
442
+ "must not supply exec-prefix without prefix")
443
+
444
+ self.prefix = os.path.normpath(sys.prefix)
445
+ self.exec_prefix = os.path.normpath(sys.exec_prefix)
446
+
447
+ else:
448
+ if self.exec_prefix is None:
449
+ self.exec_prefix = self.prefix
450
+
451
+ self.install_base = self.prefix
452
+ self.install_platbase = self.exec_prefix
453
+ self.select_scheme("unix_prefix")
454
+
455
+ def finalize_other(self):
456
+ """Finalizes options for non-posix platforms"""
457
+ if self.user:
458
+ if self.install_userbase is None:
459
+ raise DistutilsPlatformError(
460
+ "User base directory is not specified")
461
+ self.install_base = self.install_platbase = self.install_userbase
462
+ self.select_scheme(os.name + "_user")
463
+ elif self.home is not None:
464
+ self.install_base = self.install_platbase = self.home
465
+ self.select_scheme("unix_home")
466
+ else:
467
+ if self.prefix is None:
468
+ self.prefix = os.path.normpath(sys.prefix)
469
+
470
+ self.install_base = self.install_platbase = self.prefix
471
+ try:
472
+ self.select_scheme(os.name)
473
+ except KeyError:
474
+ raise DistutilsPlatformError(
475
+ "I don't know how to install stuff on '%s'" % os.name)
476
+
477
+ def select_scheme(self, name):
478
+ """Sets the install directories by applying the install schemes."""
479
+ # it's the caller's problem if they supply a bad name!
480
+ scheme = INSTALL_SCHEMES[name]
481
+ for key in SCHEME_KEYS:
482
+ attrname = 'install_' + key
483
+ if getattr(self, attrname) is None:
484
+ setattr(self, attrname, scheme[key])
485
+
486
+ def _expand_attrs(self, attrs):
487
+ for attr in attrs:
488
+ val = getattr(self, attr)
489
+ if val is not None:
490
+ if os.name == 'posix' or os.name == 'nt':
491
+ val = os.path.expanduser(val)
492
+ val = subst_vars(val, self.config_vars)
493
+ setattr(self, attr, val)
494
+
495
+ def expand_basedirs(self):
496
+ """Calls `os.path.expanduser` on install_base, install_platbase and
497
+ root."""
498
+ self._expand_attrs(['install_base', 'install_platbase', 'root'])
499
+
500
+ def expand_dirs(self):
501
+ """Calls `os.path.expanduser` on install dirs."""
502
+ self._expand_attrs(['install_purelib', 'install_platlib',
503
+ 'install_lib', 'install_headers',
504
+ 'install_scripts', 'install_data',])
505
+
506
+ def convert_paths(self, *names):
507
+ """Call `convert_path` over `names`."""
508
+ for name in names:
509
+ attr = "install_" + name
510
+ setattr(self, attr, convert_path(getattr(self, attr)))
511
+
512
+ def handle_extra_path(self):
513
+ """Set `path_file` and `extra_dirs` using `extra_path`."""
514
+ if self.extra_path is None:
515
+ self.extra_path = self.distribution.extra_path
516
+
517
+ if self.extra_path is not None:
518
+ log.warn(
519
+ "Distribution option extra_path is deprecated. "
520
+ "See issue27919 for details."
521
+ )
522
+ if isinstance(self.extra_path, str):
523
+ self.extra_path = self.extra_path.split(',')
524
+
525
+ if len(self.extra_path) == 1:
526
+ path_file = extra_dirs = self.extra_path[0]
527
+ elif len(self.extra_path) == 2:
528
+ path_file, extra_dirs = self.extra_path
529
+ else:
530
+ raise DistutilsOptionError(
531
+ "'extra_path' option must be a list, tuple, or "
532
+ "comma-separated string with 1 or 2 elements")
533
+
534
+ # convert to local form in case Unix notation used (as it
535
+ # should be in setup scripts)
536
+ extra_dirs = convert_path(extra_dirs)
537
+ else:
538
+ path_file = None
539
+ extra_dirs = ''
540
+
541
+ # XXX should we warn if path_file and not extra_dirs? (in which
542
+ # case the path file would be harmless but pointless)
543
+ self.path_file = path_file
544
+ self.extra_dirs = extra_dirs
545
+
546
+ def change_roots(self, *names):
547
+ """Change the install directories pointed by name using root."""
548
+ for name in names:
549
+ attr = "install_" + name
550
+ setattr(self, attr, change_root(self.root, getattr(self, attr)))
551
+
552
+ def create_home_path(self):
553
+ """Create directories under ~."""
554
+ if not self.user:
555
+ return
556
+ home = convert_path(os.path.expanduser("~"))
557
+ for name, path in self.config_vars.items():
558
+ if path.startswith(home) and not os.path.isdir(path):
559
+ self.debug_print("os.makedirs('%s', 0o700)" % path)
560
+ os.makedirs(path, 0o700)
561
+
562
+ # -- Command execution methods -------------------------------------
563
+
564
+ def run(self):
565
+ """Runs the command."""
566
+ # Obviously have to build before we can install
567
+ if not self.skip_build:
568
+ self.run_command('build')
569
+ # If we built for any other platform, we can't install.
570
+ build_plat = self.distribution.get_command_obj('build').plat_name
571
+ # check warn_dir - it is a clue that the 'install' is happening
572
+ # internally, and not to sys.path, so we don't check the platform
573
+ # matches what we are running.
574
+ if self.warn_dir and build_plat != get_platform():
575
+ raise DistutilsPlatformError("Can't install when "
576
+ "cross-compiling")
577
+
578
+ # Run all sub-commands (at least those that need to be run)
579
+ for cmd_name in self.get_sub_commands():
580
+ self.run_command(cmd_name)
581
+
582
+ if self.path_file:
583
+ self.create_path_file()
584
+
585
+ # write list of installed files, if requested.
586
+ if self.record:
587
+ outputs = self.get_outputs()
588
+ if self.root: # strip any package prefix
589
+ root_len = len(self.root)
590
+ for counter in range(len(outputs)):
591
+ outputs[counter] = outputs[counter][root_len:]
592
+ self.execute(write_file,
593
+ (self.record, outputs),
594
+ "writing list of installed files to '%s'" %
595
+ self.record)
596
+
597
+ sys_path = map(os.path.normpath, sys.path)
598
+ sys_path = map(os.path.normcase, sys_path)
599
+ install_lib = os.path.normcase(os.path.normpath(self.install_lib))
600
+ if (self.warn_dir and
601
+ not (self.path_file and self.install_path_file) and
602
+ install_lib not in sys_path):
603
+ log.debug(("modules installed to '%s', which is not in "
604
+ "Python's module search path (sys.path) -- "
605
+ "you'll have to change the search path yourself"),
606
+ self.install_lib)
607
+
608
+ def create_path_file(self):
609
+ """Creates the .pth file"""
610
+ filename = os.path.join(self.install_libbase,
611
+ self.path_file + ".pth")
612
+ if self.install_path_file:
613
+ self.execute(write_file,
614
+ (filename, [self.extra_dirs]),
615
+ "creating %s" % filename)
616
+ else:
617
+ self.warn("path file '%s' not created" % filename)
618
+
619
+
620
+ # -- Reporting methods ---------------------------------------------
621
+
622
+ def get_outputs(self):
623
+ """Assembles the outputs of all the sub-commands."""
624
+ outputs = []
625
+ for cmd_name in self.get_sub_commands():
626
+ cmd = self.get_finalized_command(cmd_name)
627
+ # Add the contents of cmd.get_outputs(), ensuring
628
+ # that outputs doesn't contain duplicate entries
629
+ for filename in cmd.get_outputs():
630
+ if filename not in outputs:
631
+ outputs.append(filename)
632
+
633
+ if self.path_file and self.install_path_file:
634
+ outputs.append(os.path.join(self.install_libbase,
635
+ self.path_file + ".pth"))
636
+
637
+ return outputs
638
+
639
+ def get_inputs(self):
640
+ """Returns the inputs of all the sub-commands"""
641
+ # XXX gee, this looks familiar ;-(
642
+ inputs = []
643
+ for cmd_name in self.get_sub_commands():
644
+ cmd = self.get_finalized_command(cmd_name)
645
+ inputs.extend(cmd.get_inputs())
646
+
647
+ return inputs
648
+
649
+ # -- Predicates for sub-command list -------------------------------
650
+
651
+ def has_lib(self):
652
+ """Returns true if the current distribution has any Python
653
+ modules to install."""
654
+ return (self.distribution.has_pure_modules() or
655
+ self.distribution.has_ext_modules())
656
+
657
+ def has_headers(self):
658
+ """Returns true if the current distribution has any headers to
659
+ install."""
660
+ return self.distribution.has_headers()
661
+
662
+ def has_scripts(self):
663
+ """Returns true if the current distribution has any scripts to.
664
+ install."""
665
+ return self.distribution.has_scripts()
666
+
667
+ def has_data(self):
668
+ """Returns true if the current distribution has any data to.
669
+ install."""
670
+ return self.distribution.has_data_files()
671
+
672
+ # 'sub_commands': a list of commands this command might have to run to
673
+ # get its work done. See cmd.py for more info.
674
+ sub_commands = [('install_lib', has_lib),
675
+ ('install_headers', has_headers),
676
+ ('install_scripts', has_scripts),
677
+ ('install_data', has_data),
678
+ ('install_egg_info', lambda self:True),
679
+ ]
llava/lib/python3.10/distutils/command/install_data.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.install_data
2
+
3
+ Implements the Distutils 'install_data' command, for installing
4
+ platform-independent data files."""
5
+
6
+ # contributed by Bastian Kleineidam
7
+
8
+ import os
9
+ from distutils.core import Command
10
+ from distutils.util import change_root, convert_path
11
+
12
+ class install_data(Command):
13
+
14
+ description = "install data files"
15
+
16
+ user_options = [
17
+ ('install-dir=', 'd',
18
+ "base directory for installing data files "
19
+ "(default: installation base dir)"),
20
+ ('root=', None,
21
+ "install everything relative to this alternate root directory"),
22
+ ('force', 'f', "force installation (overwrite existing files)"),
23
+ ]
24
+
25
+ boolean_options = ['force']
26
+
27
+ def initialize_options(self):
28
+ self.install_dir = None
29
+ self.outfiles = []
30
+ self.root = None
31
+ self.force = 0
32
+ self.data_files = self.distribution.data_files
33
+ self.warn_dir = 1
34
+
35
+ def finalize_options(self):
36
+ self.set_undefined_options('install',
37
+ ('install_data', 'install_dir'),
38
+ ('root', 'root'),
39
+ ('force', 'force'),
40
+ )
41
+
42
+ def run(self):
43
+ self.mkpath(self.install_dir)
44
+ for f in self.data_files:
45
+ if isinstance(f, str):
46
+ # it's a simple file, so copy it
47
+ f = convert_path(f)
48
+ if self.warn_dir:
49
+ self.warn("setup script did not provide a directory for "
50
+ "'%s' -- installing right in '%s'" %
51
+ (f, self.install_dir))
52
+ (out, _) = self.copy_file(f, self.install_dir)
53
+ self.outfiles.append(out)
54
+ else:
55
+ # it's a tuple with path to install to and a list of files
56
+ dir = convert_path(f[0])
57
+ if not os.path.isabs(dir):
58
+ dir = os.path.join(self.install_dir, dir)
59
+ elif self.root:
60
+ dir = change_root(self.root, dir)
61
+ self.mkpath(dir)
62
+
63
+ if f[1] == []:
64
+ # If there are no files listed, the user must be
65
+ # trying to create an empty directory, so add the
66
+ # directory to the list of output files.
67
+ self.outfiles.append(dir)
68
+ else:
69
+ # Copy files, adding them to the list of output files.
70
+ for data in f[1]:
71
+ data = convert_path(data)
72
+ (out, _) = self.copy_file(data, dir)
73
+ self.outfiles.append(out)
74
+
75
+ def get_inputs(self):
76
+ return self.data_files or []
77
+
78
+ def get_outputs(self):
79
+ return self.outfiles
llava/lib/python3.10/distutils/command/install_egg_info.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """distutils.command.install_egg_info
2
+
3
+ Implements the Distutils 'install_egg_info' command, for installing
4
+ a package's PKG-INFO metadata."""
5
+
6
+
7
+ from distutils.cmd import Command
8
+ from distutils import log, dir_util
9
+ import os, sys, re
10
+
11
+ class install_egg_info(Command):
12
+ """Install an .egg-info file for the package"""
13
+
14
+ description = "Install package's PKG-INFO metadata as an .egg-info file"
15
+ user_options = [
16
+ ('install-dir=', 'd', "directory to install to"),
17
+ ]
18
+
19
+ def initialize_options(self):
20
+ self.install_dir = None
21
+
22
+ def finalize_options(self):
23
+ self.set_undefined_options('install_lib',('install_dir','install_dir'))
24
+ basename = "%s-%s-py%d.%d.egg-info" % (
25
+ to_filename(safe_name(self.distribution.get_name())),
26
+ to_filename(safe_version(self.distribution.get_version())),
27
+ *sys.version_info[:2]
28
+ )
29
+ self.target = os.path.join(self.install_dir, basename)
30
+ self.outputs = [self.target]
31
+
32
+ def run(self):
33
+ target = self.target
34
+ if os.path.isdir(target) and not os.path.islink(target):
35
+ dir_util.remove_tree(target, dry_run=self.dry_run)
36
+ elif os.path.exists(target):
37
+ self.execute(os.unlink,(self.target,),"Removing "+target)
38
+ elif not os.path.isdir(self.install_dir):
39
+ self.execute(os.makedirs, (self.install_dir,),
40
+ "Creating "+self.install_dir)
41
+ log.info("Writing %s", target)
42
+ if not self.dry_run:
43
+ with open(target, 'w', encoding='UTF-8') as f:
44
+ self.distribution.metadata.write_pkg_file(f)
45
+
46
+ def get_outputs(self):
47
+ return self.outputs
48
+
49
+
50
+ # The following routines are taken from setuptools' pkg_resources module and
51
+ # can be replaced by importing them from pkg_resources once it is included
52
+ # in the stdlib.
53
+
54
+ def safe_name(name):
55
+ """Convert an arbitrary string to a standard distribution name
56
+
57
+ Any runs of non-alphanumeric/. characters are replaced with a single '-'.
58
+ """
59
+ return re.sub('[^A-Za-z0-9.]+', '-', name)
60
+
61
+
62
+ def safe_version(version):
63
+ """Convert an arbitrary string to a standard version string
64
+
65
+ Spaces become dots, and all other non-alphanumeric characters become
66
+ dashes, with runs of multiple dashes condensed to a single dash.
67
+ """
68
+ version = version.replace(' ','.')
69
+ return re.sub('[^A-Za-z0-9.]+', '-', version)
70
+
71
+
72
+ def to_filename(name):
73
+ """Convert a project or version name to its filename-escaped form
74
+
75
+ Any '-' characters are currently replaced with '_'.
76
+ """
77
+ return name.replace('-','_')
llava/lib/python3.10/distutils/command/upload.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ distutils.command.upload
3
+
4
+ Implements the Distutils 'upload' subcommand (upload package to a package
5
+ index).
6
+ """
7
+
8
+ import os
9
+ import io
10
+ import hashlib
11
+ from base64 import standard_b64encode
12
+ from urllib.error import HTTPError
13
+ from urllib.request import urlopen, Request
14
+ from urllib.parse import urlparse
15
+ from distutils.errors import DistutilsError, DistutilsOptionError
16
+ from distutils.core import PyPIRCCommand
17
+ from distutils.spawn import spawn
18
+ from distutils import log
19
+
20
+
21
+ # PyPI Warehouse supports MD5, SHA256, and Blake2 (blake2-256)
22
+ # https://bugs.python.org/issue40698
23
+ _FILE_CONTENT_DIGESTS = {
24
+ "md5_digest": getattr(hashlib, "md5", None),
25
+ "sha256_digest": getattr(hashlib, "sha256", None),
26
+ "blake2_256_digest": getattr(hashlib, "blake2b", None),
27
+ }
28
+
29
+
30
+ class upload(PyPIRCCommand):
31
+
32
+ description = "upload binary package to PyPI"
33
+
34
+ user_options = PyPIRCCommand.user_options + [
35
+ ('sign', 's',
36
+ 'sign files to upload using gpg'),
37
+ ('identity=', 'i', 'GPG identity used to sign files'),
38
+ ]
39
+
40
+ boolean_options = PyPIRCCommand.boolean_options + ['sign']
41
+
42
+ def initialize_options(self):
43
+ PyPIRCCommand.initialize_options(self)
44
+ self.username = ''
45
+ self.password = ''
46
+ self.show_response = 0
47
+ self.sign = False
48
+ self.identity = None
49
+
50
+ def finalize_options(self):
51
+ PyPIRCCommand.finalize_options(self)
52
+ if self.identity and not self.sign:
53
+ raise DistutilsOptionError(
54
+ "Must use --sign for --identity to have meaning"
55
+ )
56
+ config = self._read_pypirc()
57
+ if config != {}:
58
+ self.username = config['username']
59
+ self.password = config['password']
60
+ self.repository = config['repository']
61
+ self.realm = config['realm']
62
+
63
+ # getting the password from the distribution
64
+ # if previously set by the register command
65
+ if not self.password and self.distribution.password:
66
+ self.password = self.distribution.password
67
+
68
+ def run(self):
69
+ if not self.distribution.dist_files:
70
+ msg = ("Must create and upload files in one command "
71
+ "(e.g. setup.py sdist upload)")
72
+ raise DistutilsOptionError(msg)
73
+ for command, pyversion, filename in self.distribution.dist_files:
74
+ self.upload_file(command, pyversion, filename)
75
+
76
+ def upload_file(self, command, pyversion, filename):
77
+ # Makes sure the repository URL is compliant
78
+ schema, netloc, url, params, query, fragments = \
79
+ urlparse(self.repository)
80
+ if params or query or fragments:
81
+ raise AssertionError("Incompatible url %s" % self.repository)
82
+
83
+ if schema not in ('http', 'https'):
84
+ raise AssertionError("unsupported schema " + schema)
85
+
86
+ # Sign if requested
87
+ if self.sign:
88
+ gpg_args = ["gpg", "--detach-sign", "-a", filename]
89
+ if self.identity:
90
+ gpg_args[2:2] = ["--local-user", self.identity]
91
+ spawn(gpg_args,
92
+ dry_run=self.dry_run)
93
+
94
+ # Fill in the data - send all the meta-data in case we need to
95
+ # register a new release
96
+ f = open(filename,'rb')
97
+ try:
98
+ content = f.read()
99
+ finally:
100
+ f.close()
101
+
102
+ meta = self.distribution.metadata
103
+ data = {
104
+ # action
105
+ ':action': 'file_upload',
106
+ 'protocol_version': '1',
107
+
108
+ # identify release
109
+ 'name': meta.get_name(),
110
+ 'version': meta.get_version(),
111
+
112
+ # file content
113
+ 'content': (os.path.basename(filename),content),
114
+ 'filetype': command,
115
+ 'pyversion': pyversion,
116
+
117
+ # additional meta-data
118
+ 'metadata_version': '1.0',
119
+ 'summary': meta.get_description(),
120
+ 'home_page': meta.get_url(),
121
+ 'author': meta.get_contact(),
122
+ 'author_email': meta.get_contact_email(),
123
+ 'license': meta.get_licence(),
124
+ 'description': meta.get_long_description(),
125
+ 'keywords': meta.get_keywords(),
126
+ 'platform': meta.get_platforms(),
127
+ 'classifiers': meta.get_classifiers(),
128
+ 'download_url': meta.get_download_url(),
129
+ # PEP 314
130
+ 'provides': meta.get_provides(),
131
+ 'requires': meta.get_requires(),
132
+ 'obsoletes': meta.get_obsoletes(),
133
+ }
134
+
135
+ data['comment'] = ''
136
+
137
+ # file content digests
138
+ for digest_name, digest_cons in _FILE_CONTENT_DIGESTS.items():
139
+ if digest_cons is None:
140
+ continue
141
+ try:
142
+ data[digest_name] = digest_cons(content).hexdigest()
143
+ except ValueError:
144
+ # hash digest not available or blocked by security policy
145
+ pass
146
+
147
+ if self.sign:
148
+ with open(filename + ".asc", "rb") as f:
149
+ data['gpg_signature'] = (os.path.basename(filename) + ".asc",
150
+ f.read())
151
+
152
+ # set up the authentication
153
+ user_pass = (self.username + ":" + self.password).encode('ascii')
154
+ # The exact encoding of the authentication string is debated.
155
+ # Anyway PyPI only accepts ascii for both username or password.
156
+ auth = "Basic " + standard_b64encode(user_pass).decode('ascii')
157
+
158
+ # Build up the MIME payload for the POST data
159
+ boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
160
+ sep_boundary = b'\r\n--' + boundary.encode('ascii')
161
+ end_boundary = sep_boundary + b'--\r\n'
162
+ body = io.BytesIO()
163
+ for key, value in data.items():
164
+ title = '\r\nContent-Disposition: form-data; name="%s"' % key
165
+ # handle multiple entries for the same name
166
+ if not isinstance(value, list):
167
+ value = [value]
168
+ for value in value:
169
+ if type(value) is tuple:
170
+ title += '; filename="%s"' % value[0]
171
+ value = value[1]
172
+ else:
173
+ value = str(value).encode('utf-8')
174
+ body.write(sep_boundary)
175
+ body.write(title.encode('utf-8'))
176
+ body.write(b"\r\n\r\n")
177
+ body.write(value)
178
+ body.write(end_boundary)
179
+ body = body.getvalue()
180
+
181
+ msg = "Submitting %s to %s" % (filename, self.repository)
182
+ self.announce(msg, log.INFO)
183
+
184
+ # build the Request
185
+ headers = {
186
+ 'Content-type': 'multipart/form-data; boundary=%s' % boundary,
187
+ 'Content-length': str(len(body)),
188
+ 'Authorization': auth,
189
+ }
190
+
191
+ request = Request(self.repository, data=body,
192
+ headers=headers)
193
+ # send the data
194
+ try:
195
+ result = urlopen(request)
196
+ status = result.getcode()
197
+ reason = result.msg
198
+ except HTTPError as e:
199
+ status = e.code
200
+ reason = e.msg
201
+ except OSError as e:
202
+ self.announce(str(e), log.ERROR)
203
+ raise
204
+
205
+ if status == 200:
206
+ self.announce('Server response (%s): %s' % (status, reason),
207
+ log.INFO)
208
+ if self.show_response:
209
+ text = self._read_pypi_response(result)
210
+ msg = '\n'.join(('-' * 75, text, '-' * 75))
211
+ self.announce(msg, log.INFO)
212
+ else:
213
+ msg = 'Upload failed (%s): %s' % (status, reason)
214
+ self.announce(msg, log.ERROR)
215
+ raise DistutilsError(msg)
llava/lib/python3.10/json/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (12.5 kB). View file
 
llava/lib/python3.10/json/__pycache__/decoder.cpython-310.pyc ADDED
Binary file (10 kB). View file
 
llava/lib/python3.10/json/__pycache__/encoder.cpython-310.pyc ADDED
Binary file (11.4 kB). View file
 
llava/lib/python3.10/json/__pycache__/scanner.cpython-310.pyc ADDED
Binary file (1.91 kB). View file
 
llava/lib/python3.10/json/__pycache__/tool.cpython-310.pyc ADDED
Binary file (3.07 kB). View file
 
llava/lib/python3.10/json/encoder.py ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of JSONEncoder
2
+ """
3
+ import re
4
+
5
+ try:
6
+ from _json import encode_basestring_ascii as c_encode_basestring_ascii
7
+ except ImportError:
8
+ c_encode_basestring_ascii = None
9
+ try:
10
+ from _json import encode_basestring as c_encode_basestring
11
+ except ImportError:
12
+ c_encode_basestring = None
13
+ try:
14
+ from _json import make_encoder as c_make_encoder
15
+ except ImportError:
16
+ c_make_encoder = None
17
+
18
+ ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')
19
+ ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
20
+ HAS_UTF8 = re.compile(b'[\x80-\xff]')
21
+ ESCAPE_DCT = {
22
+ '\\': '\\\\',
23
+ '"': '\\"',
24
+ '\b': '\\b',
25
+ '\f': '\\f',
26
+ '\n': '\\n',
27
+ '\r': '\\r',
28
+ '\t': '\\t',
29
+ }
30
+ for i in range(0x20):
31
+ ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i))
32
+ #ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
33
+
34
+ INFINITY = float('inf')
35
+
36
+ def py_encode_basestring(s):
37
+ """Return a JSON representation of a Python string
38
+
39
+ """
40
+ def replace(match):
41
+ return ESCAPE_DCT[match.group(0)]
42
+ return '"' + ESCAPE.sub(replace, s) + '"'
43
+
44
+
45
+ encode_basestring = (c_encode_basestring or py_encode_basestring)
46
+
47
+
48
+ def py_encode_basestring_ascii(s):
49
+ """Return an ASCII-only JSON representation of a Python string
50
+
51
+ """
52
+ def replace(match):
53
+ s = match.group(0)
54
+ try:
55
+ return ESCAPE_DCT[s]
56
+ except KeyError:
57
+ n = ord(s)
58
+ if n < 0x10000:
59
+ return '\\u{0:04x}'.format(n)
60
+ #return '\\u%04x' % (n,)
61
+ else:
62
+ # surrogate pair
63
+ n -= 0x10000
64
+ s1 = 0xd800 | ((n >> 10) & 0x3ff)
65
+ s2 = 0xdc00 | (n & 0x3ff)
66
+ return '\\u{0:04x}\\u{1:04x}'.format(s1, s2)
67
+ return '"' + ESCAPE_ASCII.sub(replace, s) + '"'
68
+
69
+
70
+ encode_basestring_ascii = (
71
+ c_encode_basestring_ascii or py_encode_basestring_ascii)
72
+
73
+ class JSONEncoder(object):
74
+ """Extensible JSON <https://json.org> encoder for Python data structures.
75
+
76
+ Supports the following objects and types by default:
77
+
78
+ +-------------------+---------------+
79
+ | Python | JSON |
80
+ +===================+===============+
81
+ | dict | object |
82
+ +-------------------+---------------+
83
+ | list, tuple | array |
84
+ +-------------------+---------------+
85
+ | str | string |
86
+ +-------------------+---------------+
87
+ | int, float | number |
88
+ +-------------------+---------------+
89
+ | True | true |
90
+ +-------------------+---------------+
91
+ | False | false |
92
+ +-------------------+---------------+
93
+ | None | null |
94
+ +-------------------+---------------+
95
+
96
+ To extend this to recognize other objects, subclass and implement a
97
+ ``.default()`` method with another method that returns a serializable
98
+ object for ``o`` if possible, otherwise it should call the superclass
99
+ implementation (to raise ``TypeError``).
100
+
101
+ """
102
+ item_separator = ', '
103
+ key_separator = ': '
104
+ def __init__(self, *, skipkeys=False, ensure_ascii=True,
105
+ check_circular=True, allow_nan=True, sort_keys=False,
106
+ indent=None, separators=None, default=None):
107
+ """Constructor for JSONEncoder, with sensible defaults.
108
+
109
+ If skipkeys is false, then it is a TypeError to attempt
110
+ encoding of keys that are not str, int, float or None. If
111
+ skipkeys is True, such items are simply skipped.
112
+
113
+ If ensure_ascii is true, the output is guaranteed to be str
114
+ objects with all incoming non-ASCII characters escaped. If
115
+ ensure_ascii is false, the output can contain non-ASCII characters.
116
+
117
+ If check_circular is true, then lists, dicts, and custom encoded
118
+ objects will be checked for circular references during encoding to
119
+ prevent an infinite recursion (which would cause an RecursionError).
120
+ Otherwise, no such check takes place.
121
+
122
+ If allow_nan is true, then NaN, Infinity, and -Infinity will be
123
+ encoded as such. This behavior is not JSON specification compliant,
124
+ but is consistent with most JavaScript based encoders and decoders.
125
+ Otherwise, it will be a ValueError to encode such floats.
126
+
127
+ If sort_keys is true, then the output of dictionaries will be
128
+ sorted by key; this is useful for regression tests to ensure
129
+ that JSON serializations can be compared on a day-to-day basis.
130
+
131
+ If indent is a non-negative integer, then JSON array
132
+ elements and object members will be pretty-printed with that
133
+ indent level. An indent level of 0 will only insert newlines.
134
+ None is the most compact representation.
135
+
136
+ If specified, separators should be an (item_separator, key_separator)
137
+ tuple. The default is (', ', ': ') if *indent* is ``None`` and
138
+ (',', ': ') otherwise. To get the most compact JSON representation,
139
+ you should specify (',', ':') to eliminate whitespace.
140
+
141
+ If specified, default is a function that gets called for objects
142
+ that can't otherwise be serialized. It should return a JSON encodable
143
+ version of the object or raise a ``TypeError``.
144
+
145
+ """
146
+
147
+ self.skipkeys = skipkeys
148
+ self.ensure_ascii = ensure_ascii
149
+ self.check_circular = check_circular
150
+ self.allow_nan = allow_nan
151
+ self.sort_keys = sort_keys
152
+ self.indent = indent
153
+ if separators is not None:
154
+ self.item_separator, self.key_separator = separators
155
+ elif indent is not None:
156
+ self.item_separator = ','
157
+ if default is not None:
158
+ self.default = default
159
+
160
+ def default(self, o):
161
+ """Implement this method in a subclass such that it returns
162
+ a serializable object for ``o``, or calls the base implementation
163
+ (to raise a ``TypeError``).
164
+
165
+ For example, to support arbitrary iterators, you could
166
+ implement default like this::
167
+
168
+ def default(self, o):
169
+ try:
170
+ iterable = iter(o)
171
+ except TypeError:
172
+ pass
173
+ else:
174
+ return list(iterable)
175
+ # Let the base class default method raise the TypeError
176
+ return JSONEncoder.default(self, o)
177
+
178
+ """
179
+ raise TypeError(f'Object of type {o.__class__.__name__} '
180
+ f'is not JSON serializable')
181
+
182
+ def encode(self, o):
183
+ """Return a JSON string representation of a Python data structure.
184
+
185
+ >>> from json.encoder import JSONEncoder
186
+ >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
187
+ '{"foo": ["bar", "baz"]}'
188
+
189
+ """
190
+ # This is for extremely simple cases and benchmarks.
191
+ if isinstance(o, str):
192
+ if self.ensure_ascii:
193
+ return encode_basestring_ascii(o)
194
+ else:
195
+ return encode_basestring(o)
196
+ # This doesn't pass the iterator directly to ''.join() because the
197
+ # exceptions aren't as detailed. The list call should be roughly
198
+ # equivalent to the PySequence_Fast that ''.join() would do.
199
+ chunks = self.iterencode(o, _one_shot=True)
200
+ if not isinstance(chunks, (list, tuple)):
201
+ chunks = list(chunks)
202
+ return ''.join(chunks)
203
+
204
+ def iterencode(self, o, _one_shot=False):
205
+ """Encode the given object and yield each string
206
+ representation as available.
207
+
208
+ For example::
209
+
210
+ for chunk in JSONEncoder().iterencode(bigobject):
211
+ mysocket.write(chunk)
212
+
213
+ """
214
+ if self.check_circular:
215
+ markers = {}
216
+ else:
217
+ markers = None
218
+ if self.ensure_ascii:
219
+ _encoder = encode_basestring_ascii
220
+ else:
221
+ _encoder = encode_basestring
222
+
223
+ def floatstr(o, allow_nan=self.allow_nan,
224
+ _repr=float.__repr__, _inf=INFINITY, _neginf=-INFINITY):
225
+ # Check for specials. Note that this type of test is processor
226
+ # and/or platform-specific, so do tests which don't depend on the
227
+ # internals.
228
+
229
+ if o != o:
230
+ text = 'NaN'
231
+ elif o == _inf:
232
+ text = 'Infinity'
233
+ elif o == _neginf:
234
+ text = '-Infinity'
235
+ else:
236
+ return _repr(o)
237
+
238
+ if not allow_nan:
239
+ raise ValueError(
240
+ "Out of range float values are not JSON compliant: " +
241
+ repr(o))
242
+
243
+ return text
244
+
245
+
246
+ if (_one_shot and c_make_encoder is not None
247
+ and self.indent is None):
248
+ _iterencode = c_make_encoder(
249
+ markers, self.default, _encoder, self.indent,
250
+ self.key_separator, self.item_separator, self.sort_keys,
251
+ self.skipkeys, self.allow_nan)
252
+ else:
253
+ _iterencode = _make_iterencode(
254
+ markers, self.default, _encoder, self.indent, floatstr,
255
+ self.key_separator, self.item_separator, self.sort_keys,
256
+ self.skipkeys, _one_shot)
257
+ return _iterencode(o, 0)
258
+
259
+ def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
260
+ _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
261
+ ## HACK: hand-optimized bytecode; turn globals into locals
262
+ ValueError=ValueError,
263
+ dict=dict,
264
+ float=float,
265
+ id=id,
266
+ int=int,
267
+ isinstance=isinstance,
268
+ list=list,
269
+ str=str,
270
+ tuple=tuple,
271
+ _intstr=int.__repr__,
272
+ ):
273
+
274
+ if _indent is not None and not isinstance(_indent, str):
275
+ _indent = ' ' * _indent
276
+
277
+ def _iterencode_list(lst, _current_indent_level):
278
+ if not lst:
279
+ yield '[]'
280
+ return
281
+ if markers is not None:
282
+ markerid = id(lst)
283
+ if markerid in markers:
284
+ raise ValueError("Circular reference detected")
285
+ markers[markerid] = lst
286
+ buf = '['
287
+ if _indent is not None:
288
+ _current_indent_level += 1
289
+ newline_indent = '\n' + _indent * _current_indent_level
290
+ separator = _item_separator + newline_indent
291
+ buf += newline_indent
292
+ else:
293
+ newline_indent = None
294
+ separator = _item_separator
295
+ first = True
296
+ for value in lst:
297
+ if first:
298
+ first = False
299
+ else:
300
+ buf = separator
301
+ if isinstance(value, str):
302
+ yield buf + _encoder(value)
303
+ elif value is None:
304
+ yield buf + 'null'
305
+ elif value is True:
306
+ yield buf + 'true'
307
+ elif value is False:
308
+ yield buf + 'false'
309
+ elif isinstance(value, int):
310
+ # Subclasses of int/float may override __repr__, but we still
311
+ # want to encode them as integers/floats in JSON. One example
312
+ # within the standard library is IntEnum.
313
+ yield buf + _intstr(value)
314
+ elif isinstance(value, float):
315
+ # see comment above for int
316
+ yield buf + _floatstr(value)
317
+ else:
318
+ yield buf
319
+ if isinstance(value, (list, tuple)):
320
+ chunks = _iterencode_list(value, _current_indent_level)
321
+ elif isinstance(value, dict):
322
+ chunks = _iterencode_dict(value, _current_indent_level)
323
+ else:
324
+ chunks = _iterencode(value, _current_indent_level)
325
+ yield from chunks
326
+ if newline_indent is not None:
327
+ _current_indent_level -= 1
328
+ yield '\n' + _indent * _current_indent_level
329
+ yield ']'
330
+ if markers is not None:
331
+ del markers[markerid]
332
+
333
+ def _iterencode_dict(dct, _current_indent_level):
334
+ if not dct:
335
+ yield '{}'
336
+ return
337
+ if markers is not None:
338
+ markerid = id(dct)
339
+ if markerid in markers:
340
+ raise ValueError("Circular reference detected")
341
+ markers[markerid] = dct
342
+ yield '{'
343
+ if _indent is not None:
344
+ _current_indent_level += 1
345
+ newline_indent = '\n' + _indent * _current_indent_level
346
+ item_separator = _item_separator + newline_indent
347
+ yield newline_indent
348
+ else:
349
+ newline_indent = None
350
+ item_separator = _item_separator
351
+ first = True
352
+ if _sort_keys:
353
+ items = sorted(dct.items())
354
+ else:
355
+ items = dct.items()
356
+ for key, value in items:
357
+ if isinstance(key, str):
358
+ pass
359
+ # JavaScript is weakly typed for these, so it makes sense to
360
+ # also allow them. Many encoders seem to do something like this.
361
+ elif isinstance(key, float):
362
+ # see comment for int/float in _make_iterencode
363
+ key = _floatstr(key)
364
+ elif key is True:
365
+ key = 'true'
366
+ elif key is False:
367
+ key = 'false'
368
+ elif key is None:
369
+ key = 'null'
370
+ elif isinstance(key, int):
371
+ # see comment for int/float in _make_iterencode
372
+ key = _intstr(key)
373
+ elif _skipkeys:
374
+ continue
375
+ else:
376
+ raise TypeError(f'keys must be str, int, float, bool or None, '
377
+ f'not {key.__class__.__name__}')
378
+ if first:
379
+ first = False
380
+ else:
381
+ yield item_separator
382
+ yield _encoder(key)
383
+ yield _key_separator
384
+ if isinstance(value, str):
385
+ yield _encoder(value)
386
+ elif value is None:
387
+ yield 'null'
388
+ elif value is True:
389
+ yield 'true'
390
+ elif value is False:
391
+ yield 'false'
392
+ elif isinstance(value, int):
393
+ # see comment for int/float in _make_iterencode
394
+ yield _intstr(value)
395
+ elif isinstance(value, float):
396
+ # see comment for int/float in _make_iterencode
397
+ yield _floatstr(value)
398
+ else:
399
+ if isinstance(value, (list, tuple)):
400
+ chunks = _iterencode_list(value, _current_indent_level)
401
+ elif isinstance(value, dict):
402
+ chunks = _iterencode_dict(value, _current_indent_level)
403
+ else:
404
+ chunks = _iterencode(value, _current_indent_level)
405
+ yield from chunks
406
+ if newline_indent is not None:
407
+ _current_indent_level -= 1
408
+ yield '\n' + _indent * _current_indent_level
409
+ yield '}'
410
+ if markers is not None:
411
+ del markers[markerid]
412
+
413
+ def _iterencode(o, _current_indent_level):
414
+ if isinstance(o, str):
415
+ yield _encoder(o)
416
+ elif o is None:
417
+ yield 'null'
418
+ elif o is True:
419
+ yield 'true'
420
+ elif o is False:
421
+ yield 'false'
422
+ elif isinstance(o, int):
423
+ # see comment for int/float in _make_iterencode
424
+ yield _intstr(o)
425
+ elif isinstance(o, float):
426
+ # see comment for int/float in _make_iterencode
427
+ yield _floatstr(o)
428
+ elif isinstance(o, (list, tuple)):
429
+ yield from _iterencode_list(o, _current_indent_level)
430
+ elif isinstance(o, dict):
431
+ yield from _iterencode_dict(o, _current_indent_level)
432
+ else:
433
+ if markers is not None:
434
+ markerid = id(o)
435
+ if markerid in markers:
436
+ raise ValueError("Circular reference detected")
437
+ markers[markerid] = o
438
+ o = _default(o)
439
+ yield from _iterencode(o, _current_indent_level)
440
+ if markers is not None:
441
+ del markers[markerid]
442
+ return _iterencode
llava/lib/python3.10/tkinter/__init__.py ADDED
The diff for this file is too large to render. See raw diff
 
llava/lib/python3.10/tkinter/__main__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """Main entry point"""
2
+
3
+ import sys
4
+ if sys.argv[0].endswith("__main__.py"):
5
+ sys.argv[0] = "python -m tkinter"
6
+ from . import _test as main
7
+ main()
llava/lib/python3.10/tkinter/colorchooser.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # tk common color chooser dialogue
2
+ #
3
+ # this module provides an interface to the native color dialogue
4
+ # available in Tk 4.2 and newer.
5
+ #
6
+ # written by Fredrik Lundh, May 1997
7
+ #
8
+ # fixed initialcolor handling in August 1998
9
+ #
10
+
11
+
12
+ from tkinter.commondialog import Dialog
13
+
14
+ __all__ = ["Chooser", "askcolor"]
15
+
16
+
17
+ class Chooser(Dialog):
18
+ """Create a dialog for the tk_chooseColor command.
19
+
20
+ Args:
21
+ master: The master widget for this dialog. If not provided,
22
+ defaults to options['parent'] (if defined).
23
+ options: Dictionary of options for the tk_chooseColor call.
24
+ initialcolor: Specifies the selected color when the
25
+ dialog is first displayed. This can be a tk color
26
+ string or a 3-tuple of ints in the range (0, 255)
27
+ for an RGB triplet.
28
+ parent: The parent window of the color dialog. The
29
+ color dialog is displayed on top of this.
30
+ title: A string for the title of the dialog box.
31
+ """
32
+
33
+ command = "tk_chooseColor"
34
+
35
+ def _fixoptions(self):
36
+ """Ensure initialcolor is a tk color string.
37
+
38
+ Convert initialcolor from a RGB triplet to a color string.
39
+ """
40
+ try:
41
+ color = self.options["initialcolor"]
42
+ if isinstance(color, tuple):
43
+ # Assume an RGB triplet.
44
+ self.options["initialcolor"] = "#%02x%02x%02x" % color
45
+ except KeyError:
46
+ pass
47
+
48
+ def _fixresult(self, widget, result):
49
+ """Adjust result returned from call to tk_chooseColor.
50
+
51
+ Return both an RGB tuple of ints in the range (0, 255) and the
52
+ tk color string in the form #rrggbb.
53
+ """
54
+ # Result can be many things: an empty tuple, an empty string, or
55
+ # a _tkinter.Tcl_Obj, so this somewhat weird check handles that.
56
+ if not result or not str(result):
57
+ return None, None # canceled
58
+
59
+ # To simplify application code, the color chooser returns
60
+ # an RGB tuple together with the Tk color string.
61
+ r, g, b = widget.winfo_rgb(result)
62
+ return (r//256, g//256, b//256), str(result)
63
+
64
+
65
+ #
66
+ # convenience stuff
67
+
68
+ def askcolor(color=None, **options):
69
+ """Display dialog window for selection of a color.
70
+
71
+ Convenience wrapper for the Chooser class. Displays the color
72
+ chooser dialog with color as the initial value.
73
+ """
74
+
75
+ if color:
76
+ options = options.copy()
77
+ options["initialcolor"] = color
78
+
79
+ return Chooser(**options).show()
80
+
81
+
82
+ # --------------------------------------------------------------------
83
+ # test stuff
84
+
85
+ if __name__ == "__main__":
86
+ print("color", askcolor())
llava/lib/python3.10/tkinter/commondialog.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # base class for tk common dialogues
2
+ #
3
+ # this module provides a base class for accessing the common
4
+ # dialogues available in Tk 4.2 and newer. use filedialog,
5
+ # colorchooser, and messagebox to access the individual
6
+ # dialogs.
7
+ #
8
+ # written by Fredrik Lundh, May 1997
9
+ #
10
+
11
+ __all__ = ["Dialog"]
12
+
13
+ from tkinter import Frame, _get_temp_root, _destroy_temp_root
14
+
15
+
16
+ class Dialog:
17
+
18
+ command = None
19
+
20
+ def __init__(self, master=None, **options):
21
+ if master is None:
22
+ master = options.get('parent')
23
+ self.master = master
24
+ self.options = options
25
+
26
+ def _fixoptions(self):
27
+ pass # hook
28
+
29
+ def _fixresult(self, widget, result):
30
+ return result # hook
31
+
32
+ def show(self, **options):
33
+
34
+ # update instance options
35
+ for k, v in options.items():
36
+ self.options[k] = v
37
+
38
+ self._fixoptions()
39
+
40
+ master = self.master
41
+ if master is None:
42
+ master = _get_temp_root()
43
+ try:
44
+ self._test_callback(master) # The function below is replaced for some tests.
45
+ s = master.tk.call(self.command, *master._options(self.options))
46
+ s = self._fixresult(master, s)
47
+ finally:
48
+ _destroy_temp_root(master)
49
+
50
+ return s
51
+
52
+ def _test_callback(self, master):
53
+ pass
llava/lib/python3.10/tkinter/constants.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Symbolic constants for Tk
2
+
3
+ # Booleans
4
+ NO=FALSE=OFF=0
5
+ YES=TRUE=ON=1
6
+
7
+ # -anchor and -sticky
8
+ N='n'
9
+ S='s'
10
+ W='w'
11
+ E='e'
12
+ NW='nw'
13
+ SW='sw'
14
+ NE='ne'
15
+ SE='se'
16
+ NS='ns'
17
+ EW='ew'
18
+ NSEW='nsew'
19
+ CENTER='center'
20
+
21
+ # -fill
22
+ NONE='none'
23
+ X='x'
24
+ Y='y'
25
+ BOTH='both'
26
+
27
+ # -side
28
+ LEFT='left'
29
+ TOP='top'
30
+ RIGHT='right'
31
+ BOTTOM='bottom'
32
+
33
+ # -relief
34
+ RAISED='raised'
35
+ SUNKEN='sunken'
36
+ FLAT='flat'
37
+ RIDGE='ridge'
38
+ GROOVE='groove'
39
+ SOLID = 'solid'
40
+
41
+ # -orient
42
+ HORIZONTAL='horizontal'
43
+ VERTICAL='vertical'
44
+
45
+ # -tabs
46
+ NUMERIC='numeric'
47
+
48
+ # -wrap
49
+ CHAR='char'
50
+ WORD='word'
51
+
52
+ # -align
53
+ BASELINE='baseline'
54
+
55
+ # -bordermode
56
+ INSIDE='inside'
57
+ OUTSIDE='outside'
58
+
59
+ # Special tags, marks and insert positions
60
+ SEL='sel'
61
+ SEL_FIRST='sel.first'
62
+ SEL_LAST='sel.last'
63
+ END='end'
64
+ INSERT='insert'
65
+ CURRENT='current'
66
+ ANCHOR='anchor'
67
+ ALL='all' # e.g. Canvas.delete(ALL)
68
+
69
+ # Text widget and button states
70
+ NORMAL='normal'
71
+ DISABLED='disabled'
72
+ ACTIVE='active'
73
+ # Canvas state
74
+ HIDDEN='hidden'
75
+
76
+ # Menu item types
77
+ CASCADE='cascade'
78
+ CHECKBUTTON='checkbutton'
79
+ COMMAND='command'
80
+ RADIOBUTTON='radiobutton'
81
+ SEPARATOR='separator'
82
+
83
+ # Selection modes for list boxes
84
+ SINGLE='single'
85
+ BROWSE='browse'
86
+ MULTIPLE='multiple'
87
+ EXTENDED='extended'
88
+
89
+ # Activestyle for list boxes
90
+ # NONE='none' is also valid
91
+ DOTBOX='dotbox'
92
+ UNDERLINE='underline'
93
+
94
+ # Various canvas styles
95
+ PIESLICE='pieslice'
96
+ CHORD='chord'
97
+ ARC='arc'
98
+ FIRST='first'
99
+ LAST='last'
100
+ BUTT='butt'
101
+ PROJECTING='projecting'
102
+ ROUND='round'
103
+ BEVEL='bevel'
104
+ MITER='miter'
105
+
106
+ # Arguments to xview/yview
107
+ MOVETO='moveto'
108
+ SCROLL='scroll'
109
+ UNITS='units'
110
+ PAGES='pages'
llava/lib/python3.10/tkinter/dialog.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialog.py -- Tkinter interface to the tk_dialog script.
2
+
3
+ from tkinter import _cnfmerge, Widget, TclError, Button, Pack
4
+
5
+ __all__ = ["Dialog"]
6
+
7
+ DIALOG_ICON = 'questhead'
8
+
9
+
10
+ class Dialog(Widget):
11
+ def __init__(self, master=None, cnf={}, **kw):
12
+ cnf = _cnfmerge((cnf, kw))
13
+ self.widgetName = '__dialog__'
14
+ self._setup(master, cnf)
15
+ self.num = self.tk.getint(
16
+ self.tk.call(
17
+ 'tk_dialog', self._w,
18
+ cnf['title'], cnf['text'],
19
+ cnf['bitmap'], cnf['default'],
20
+ *cnf['strings']))
21
+ try: Widget.destroy(self)
22
+ except TclError: pass
23
+
24
+ def destroy(self): pass
25
+
26
+
27
+ def _test():
28
+ d = Dialog(None, {'title': 'File Modified',
29
+ 'text':
30
+ 'File "Python.h" has been modified'
31
+ ' since the last time it was saved.'
32
+ ' Do you want to save it before'
33
+ ' exiting the application.',
34
+ 'bitmap': DIALOG_ICON,
35
+ 'default': 0,
36
+ 'strings': ('Save File',
37
+ 'Discard Changes',
38
+ 'Return to Editor')})
39
+ print(d.num)
40
+
41
+
42
+ if __name__ == '__main__':
43
+ t = Button(None, {'text': 'Test',
44
+ 'command': _test,
45
+ Pack: {}})
46
+ q = Button(None, {'text': 'Quit',
47
+ 'command': t.quit,
48
+ Pack: {}})
49
+ t.mainloop()
llava/lib/python3.10/tkinter/dnd.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Drag-and-drop support for Tkinter.
2
+
3
+ This is very preliminary. I currently only support dnd *within* one
4
+ application, between different windows (or within the same window).
5
+
6
+ I am trying to make this as generic as possible -- not dependent on
7
+ the use of a particular widget or icon type, etc. I also hope that
8
+ this will work with Pmw.
9
+
10
+ To enable an object to be dragged, you must create an event binding
11
+ for it that starts the drag-and-drop process. Typically, you should
12
+ bind <ButtonPress> to a callback function that you write. The function
13
+ should call Tkdnd.dnd_start(source, event), where 'source' is the
14
+ object to be dragged, and 'event' is the event that invoked the call
15
+ (the argument to your callback function). Even though this is a class
16
+ instantiation, the returned instance should not be stored -- it will
17
+ be kept alive automatically for the duration of the drag-and-drop.
18
+
19
+ When a drag-and-drop is already in process for the Tk interpreter, the
20
+ call is *ignored*; this normally averts starting multiple simultaneous
21
+ dnd processes, e.g. because different button callbacks all
22
+ dnd_start().
23
+
24
+ The object is *not* necessarily a widget -- it can be any
25
+ application-specific object that is meaningful to potential
26
+ drag-and-drop targets.
27
+
28
+ Potential drag-and-drop targets are discovered as follows. Whenever
29
+ the mouse moves, and at the start and end of a drag-and-drop move, the
30
+ Tk widget directly under the mouse is inspected. This is the target
31
+ widget (not to be confused with the target object, yet to be
32
+ determined). If there is no target widget, there is no dnd target
33
+ object. If there is a target widget, and it has an attribute
34
+ dnd_accept, this should be a function (or any callable object). The
35
+ function is called as dnd_accept(source, event), where 'source' is the
36
+ object being dragged (the object passed to dnd_start() above), and
37
+ 'event' is the most recent event object (generally a <Motion> event;
38
+ it can also be <ButtonPress> or <ButtonRelease>). If the dnd_accept()
39
+ function returns something other than None, this is the new dnd target
40
+ object. If dnd_accept() returns None, or if the target widget has no
41
+ dnd_accept attribute, the target widget's parent is considered as the
42
+ target widget, and the search for a target object is repeated from
43
+ there. If necessary, the search is repeated all the way up to the
44
+ root widget. If none of the target widgets can produce a target
45
+ object, there is no target object (the target object is None).
46
+
47
+ The target object thus produced, if any, is called the new target
48
+ object. It is compared with the old target object (or None, if there
49
+ was no old target widget). There are several cases ('source' is the
50
+ source object, and 'event' is the most recent event object):
51
+
52
+ - Both the old and new target objects are None. Nothing happens.
53
+
54
+ - The old and new target objects are the same object. Its method
55
+ dnd_motion(source, event) is called.
56
+
57
+ - The old target object was None, and the new target object is not
58
+ None. The new target object's method dnd_enter(source, event) is
59
+ called.
60
+
61
+ - The new target object is None, and the old target object is not
62
+ None. The old target object's method dnd_leave(source, event) is
63
+ called.
64
+
65
+ - The old and new target objects differ and neither is None. The old
66
+ target object's method dnd_leave(source, event), and then the new
67
+ target object's method dnd_enter(source, event) is called.
68
+
69
+ Once this is done, the new target object replaces the old one, and the
70
+ Tk mainloop proceeds. The return value of the methods mentioned above
71
+ is ignored; if they raise an exception, the normal exception handling
72
+ mechanisms take over.
73
+
74
+ The drag-and-drop processes can end in two ways: a final target object
75
+ is selected, or no final target object is selected. When a final
76
+ target object is selected, it will always have been notified of the
77
+ potential drop by a call to its dnd_enter() method, as described
78
+ above, and possibly one or more calls to its dnd_motion() method; its
79
+ dnd_leave() method has not been called since the last call to
80
+ dnd_enter(). The target is notified of the drop by a call to its
81
+ method dnd_commit(source, event).
82
+
83
+ If no final target object is selected, and there was an old target
84
+ object, its dnd_leave(source, event) method is called to complete the
85
+ dnd sequence.
86
+
87
+ Finally, the source object is notified that the drag-and-drop process
88
+ is over, by a call to source.dnd_end(target, event), specifying either
89
+ the selected target object, or None if no target object was selected.
90
+ The source object can use this to implement the commit action; this is
91
+ sometimes simpler than to do it in the target's dnd_commit(). The
92
+ target's dnd_commit() method could then simply be aliased to
93
+ dnd_leave().
94
+
95
+ At any time during a dnd sequence, the application can cancel the
96
+ sequence by calling the cancel() method on the object returned by
97
+ dnd_start(). This will call dnd_leave() if a target is currently
98
+ active; it will never call dnd_commit().
99
+
100
+ """
101
+
102
+ import tkinter
103
+
104
+ __all__ = ["dnd_start", "DndHandler"]
105
+
106
+
107
+ # The factory function
108
+
109
+ def dnd_start(source, event):
110
+ h = DndHandler(source, event)
111
+ if h.root is not None:
112
+ return h
113
+ else:
114
+ return None
115
+
116
+
117
+ # The class that does the work
118
+
119
+ class DndHandler:
120
+
121
+ root = None
122
+
123
+ def __init__(self, source, event):
124
+ if event.num > 5:
125
+ return
126
+ root = event.widget._root()
127
+ try:
128
+ root.__dnd
129
+ return # Don't start recursive dnd
130
+ except AttributeError:
131
+ root.__dnd = self
132
+ self.root = root
133
+ self.source = source
134
+ self.target = None
135
+ self.initial_button = button = event.num
136
+ self.initial_widget = widget = event.widget
137
+ self.release_pattern = "<B%d-ButtonRelease-%d>" % (button, button)
138
+ self.save_cursor = widget['cursor'] or ""
139
+ widget.bind(self.release_pattern, self.on_release)
140
+ widget.bind("<Motion>", self.on_motion)
141
+ widget['cursor'] = "hand2"
142
+
143
+ def __del__(self):
144
+ root = self.root
145
+ self.root = None
146
+ if root is not None:
147
+ try:
148
+ del root.__dnd
149
+ except AttributeError:
150
+ pass
151
+
152
+ def on_motion(self, event):
153
+ x, y = event.x_root, event.y_root
154
+ target_widget = self.initial_widget.winfo_containing(x, y)
155
+ source = self.source
156
+ new_target = None
157
+ while target_widget is not None:
158
+ try:
159
+ attr = target_widget.dnd_accept
160
+ except AttributeError:
161
+ pass
162
+ else:
163
+ new_target = attr(source, event)
164
+ if new_target is not None:
165
+ break
166
+ target_widget = target_widget.master
167
+ old_target = self.target
168
+ if old_target is new_target:
169
+ if old_target is not None:
170
+ old_target.dnd_motion(source, event)
171
+ else:
172
+ if old_target is not None:
173
+ self.target = None
174
+ old_target.dnd_leave(source, event)
175
+ if new_target is not None:
176
+ new_target.dnd_enter(source, event)
177
+ self.target = new_target
178
+
179
+ def on_release(self, event):
180
+ self.finish(event, 1)
181
+
182
+ def cancel(self, event=None):
183
+ self.finish(event, 0)
184
+
185
+ def finish(self, event, commit=0):
186
+ target = self.target
187
+ source = self.source
188
+ widget = self.initial_widget
189
+ root = self.root
190
+ try:
191
+ del root.__dnd
192
+ self.initial_widget.unbind(self.release_pattern)
193
+ self.initial_widget.unbind("<Motion>")
194
+ widget['cursor'] = self.save_cursor
195
+ self.target = self.source = self.initial_widget = self.root = None
196
+ if target is not None:
197
+ if commit:
198
+ target.dnd_commit(source, event)
199
+ else:
200
+ target.dnd_leave(source, event)
201
+ finally:
202
+ source.dnd_end(target, event)
203
+
204
+
205
+ # ----------------------------------------------------------------------
206
+ # The rest is here for testing and demonstration purposes only!
207
+
208
+ class Icon:
209
+
210
+ def __init__(self, name):
211
+ self.name = name
212
+ self.canvas = self.label = self.id = None
213
+
214
+ def attach(self, canvas, x=10, y=10):
215
+ if canvas is self.canvas:
216
+ self.canvas.coords(self.id, x, y)
217
+ return
218
+ if self.canvas is not None:
219
+ self.detach()
220
+ if canvas is None:
221
+ return
222
+ label = tkinter.Label(canvas, text=self.name,
223
+ borderwidth=2, relief="raised")
224
+ id = canvas.create_window(x, y, window=label, anchor="nw")
225
+ self.canvas = canvas
226
+ self.label = label
227
+ self.id = id
228
+ label.bind("<ButtonPress>", self.press)
229
+
230
+ def detach(self):
231
+ canvas = self.canvas
232
+ if canvas is None:
233
+ return
234
+ id = self.id
235
+ label = self.label
236
+ self.canvas = self.label = self.id = None
237
+ canvas.delete(id)
238
+ label.destroy()
239
+
240
+ def press(self, event):
241
+ if dnd_start(self, event):
242
+ # where the pointer is relative to the label widget:
243
+ self.x_off = event.x
244
+ self.y_off = event.y
245
+ # where the widget is relative to the canvas:
246
+ self.x_orig, self.y_orig = self.canvas.coords(self.id)
247
+
248
+ def move(self, event):
249
+ x, y = self.where(self.canvas, event)
250
+ self.canvas.coords(self.id, x, y)
251
+
252
+ def putback(self):
253
+ self.canvas.coords(self.id, self.x_orig, self.y_orig)
254
+
255
+ def where(self, canvas, event):
256
+ # where the corner of the canvas is relative to the screen:
257
+ x_org = canvas.winfo_rootx()
258
+ y_org = canvas.winfo_rooty()
259
+ # where the pointer is relative to the canvas widget:
260
+ x = event.x_root - x_org
261
+ y = event.y_root - y_org
262
+ # compensate for initial pointer offset
263
+ return x - self.x_off, y - self.y_off
264
+
265
+ def dnd_end(self, target, event):
266
+ pass
267
+
268
+
269
+ class Tester:
270
+
271
+ def __init__(self, root):
272
+ self.top = tkinter.Toplevel(root)
273
+ self.canvas = tkinter.Canvas(self.top, width=100, height=100)
274
+ self.canvas.pack(fill="both", expand=1)
275
+ self.canvas.dnd_accept = self.dnd_accept
276
+
277
+ def dnd_accept(self, source, event):
278
+ return self
279
+
280
+ def dnd_enter(self, source, event):
281
+ self.canvas.focus_set() # Show highlight border
282
+ x, y = source.where(self.canvas, event)
283
+ x1, y1, x2, y2 = source.canvas.bbox(source.id)
284
+ dx, dy = x2-x1, y2-y1
285
+ self.dndid = self.canvas.create_rectangle(x, y, x+dx, y+dy)
286
+ self.dnd_motion(source, event)
287
+
288
+ def dnd_motion(self, source, event):
289
+ x, y = source.where(self.canvas, event)
290
+ x1, y1, x2, y2 = self.canvas.bbox(self.dndid)
291
+ self.canvas.move(self.dndid, x-x1, y-y1)
292
+
293
+ def dnd_leave(self, source, event):
294
+ self.top.focus_set() # Hide highlight border
295
+ self.canvas.delete(self.dndid)
296
+ self.dndid = None
297
+
298
+ def dnd_commit(self, source, event):
299
+ self.dnd_leave(source, event)
300
+ x, y = source.where(self.canvas, event)
301
+ source.attach(self.canvas, x, y)
302
+
303
+
304
+ def test():
305
+ root = tkinter.Tk()
306
+ root.geometry("+1+1")
307
+ tkinter.Button(command=root.quit, text="Quit").pack()
308
+ t1 = Tester(root)
309
+ t1.top.geometry("+1+60")
310
+ t2 = Tester(root)
311
+ t2.top.geometry("+120+60")
312
+ t3 = Tester(root)
313
+ t3.top.geometry("+240+60")
314
+ i1 = Icon("ICON1")
315
+ i2 = Icon("ICON2")
316
+ i3 = Icon("ICON3")
317
+ i1.attach(t1.canvas)
318
+ i2.attach(t2.canvas)
319
+ i3.attach(t3.canvas)
320
+ root.mainloop()
321
+
322
+
323
+ if __name__ == '__main__':
324
+ test()
llava/lib/python3.10/tkinter/filedialog.py ADDED
@@ -0,0 +1,493 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """File selection dialog classes.
2
+
3
+ Classes:
4
+
5
+ - FileDialog
6
+ - LoadFileDialog
7
+ - SaveFileDialog
8
+
9
+ This module also presents tk common file dialogues, it provides interfaces
10
+ to the native file dialogues available in Tk 4.2 and newer, and the
11
+ directory dialogue available in Tk 8.3 and newer.
12
+ These interfaces were written by Fredrik Lundh, May 1997.
13
+ """
14
+ __all__ = ["FileDialog", "LoadFileDialog", "SaveFileDialog",
15
+ "Open", "SaveAs", "Directory",
16
+ "askopenfilename", "asksaveasfilename", "askopenfilenames",
17
+ "askopenfile", "askopenfiles", "asksaveasfile", "askdirectory"]
18
+
19
+ import fnmatch
20
+ import os
21
+ from tkinter import (
22
+ Frame, LEFT, YES, BOTTOM, Entry, TOP, Button, Tk, X,
23
+ Toplevel, RIGHT, Y, END, Listbox, BOTH, Scrollbar,
24
+ )
25
+ from tkinter.dialog import Dialog
26
+ from tkinter import commondialog
27
+ from tkinter.simpledialog import _setup_dialog
28
+
29
+
30
+ dialogstates = {}
31
+
32
+
33
+ class FileDialog:
34
+
35
+ """Standard file selection dialog -- no checks on selected file.
36
+
37
+ Usage:
38
+
39
+ d = FileDialog(master)
40
+ fname = d.go(dir_or_file, pattern, default, key)
41
+ if fname is None: ...canceled...
42
+ else: ...open file...
43
+
44
+ All arguments to go() are optional.
45
+
46
+ The 'key' argument specifies a key in the global dictionary
47
+ 'dialogstates', which keeps track of the values for the directory
48
+ and pattern arguments, overriding the values passed in (it does
49
+ not keep track of the default argument!). If no key is specified,
50
+ the dialog keeps no memory of previous state. Note that memory is
51
+ kept even when the dialog is canceled. (All this emulates the
52
+ behavior of the Macintosh file selection dialogs.)
53
+
54
+ """
55
+
56
+ title = "File Selection Dialog"
57
+
58
+ def __init__(self, master, title=None):
59
+ if title is None: title = self.title
60
+ self.master = master
61
+ self.directory = None
62
+
63
+ self.top = Toplevel(master)
64
+ self.top.title(title)
65
+ self.top.iconname(title)
66
+ _setup_dialog(self.top)
67
+
68
+ self.botframe = Frame(self.top)
69
+ self.botframe.pack(side=BOTTOM, fill=X)
70
+
71
+ self.selection = Entry(self.top)
72
+ self.selection.pack(side=BOTTOM, fill=X)
73
+ self.selection.bind('<Return>', self.ok_event)
74
+
75
+ self.filter = Entry(self.top)
76
+ self.filter.pack(side=TOP, fill=X)
77
+ self.filter.bind('<Return>', self.filter_command)
78
+
79
+ self.midframe = Frame(self.top)
80
+ self.midframe.pack(expand=YES, fill=BOTH)
81
+
82
+ self.filesbar = Scrollbar(self.midframe)
83
+ self.filesbar.pack(side=RIGHT, fill=Y)
84
+ self.files = Listbox(self.midframe, exportselection=0,
85
+ yscrollcommand=(self.filesbar, 'set'))
86
+ self.files.pack(side=RIGHT, expand=YES, fill=BOTH)
87
+ btags = self.files.bindtags()
88
+ self.files.bindtags(btags[1:] + btags[:1])
89
+ self.files.bind('<ButtonRelease-1>', self.files_select_event)
90
+ self.files.bind('<Double-ButtonRelease-1>', self.files_double_event)
91
+ self.filesbar.config(command=(self.files, 'yview'))
92
+
93
+ self.dirsbar = Scrollbar(self.midframe)
94
+ self.dirsbar.pack(side=LEFT, fill=Y)
95
+ self.dirs = Listbox(self.midframe, exportselection=0,
96
+ yscrollcommand=(self.dirsbar, 'set'))
97
+ self.dirs.pack(side=LEFT, expand=YES, fill=BOTH)
98
+ self.dirsbar.config(command=(self.dirs, 'yview'))
99
+ btags = self.dirs.bindtags()
100
+ self.dirs.bindtags(btags[1:] + btags[:1])
101
+ self.dirs.bind('<ButtonRelease-1>', self.dirs_select_event)
102
+ self.dirs.bind('<Double-ButtonRelease-1>', self.dirs_double_event)
103
+
104
+ self.ok_button = Button(self.botframe,
105
+ text="OK",
106
+ command=self.ok_command)
107
+ self.ok_button.pack(side=LEFT)
108
+ self.filter_button = Button(self.botframe,
109
+ text="Filter",
110
+ command=self.filter_command)
111
+ self.filter_button.pack(side=LEFT, expand=YES)
112
+ self.cancel_button = Button(self.botframe,
113
+ text="Cancel",
114
+ command=self.cancel_command)
115
+ self.cancel_button.pack(side=RIGHT)
116
+
117
+ self.top.protocol('WM_DELETE_WINDOW', self.cancel_command)
118
+ # XXX Are the following okay for a general audience?
119
+ self.top.bind('<Alt-w>', self.cancel_command)
120
+ self.top.bind('<Alt-W>', self.cancel_command)
121
+
122
+ def go(self, dir_or_file=os.curdir, pattern="*", default="", key=None):
123
+ if key and key in dialogstates:
124
+ self.directory, pattern = dialogstates[key]
125
+ else:
126
+ dir_or_file = os.path.expanduser(dir_or_file)
127
+ if os.path.isdir(dir_or_file):
128
+ self.directory = dir_or_file
129
+ else:
130
+ self.directory, default = os.path.split(dir_or_file)
131
+ self.set_filter(self.directory, pattern)
132
+ self.set_selection(default)
133
+ self.filter_command()
134
+ self.selection.focus_set()
135
+ self.top.wait_visibility() # window needs to be visible for the grab
136
+ self.top.grab_set()
137
+ self.how = None
138
+ self.master.mainloop() # Exited by self.quit(how)
139
+ if key:
140
+ directory, pattern = self.get_filter()
141
+ if self.how:
142
+ directory = os.path.dirname(self.how)
143
+ dialogstates[key] = directory, pattern
144
+ self.top.destroy()
145
+ return self.how
146
+
147
+ def quit(self, how=None):
148
+ self.how = how
149
+ self.master.quit() # Exit mainloop()
150
+
151
+ def dirs_double_event(self, event):
152
+ self.filter_command()
153
+
154
+ def dirs_select_event(self, event):
155
+ dir, pat = self.get_filter()
156
+ subdir = self.dirs.get('active')
157
+ dir = os.path.normpath(os.path.join(self.directory, subdir))
158
+ self.set_filter(dir, pat)
159
+
160
+ def files_double_event(self, event):
161
+ self.ok_command()
162
+
163
+ def files_select_event(self, event):
164
+ file = self.files.get('active')
165
+ self.set_selection(file)
166
+
167
+ def ok_event(self, event):
168
+ self.ok_command()
169
+
170
+ def ok_command(self):
171
+ self.quit(self.get_selection())
172
+
173
+ def filter_command(self, event=None):
174
+ dir, pat = self.get_filter()
175
+ try:
176
+ names = os.listdir(dir)
177
+ except OSError:
178
+ self.master.bell()
179
+ return
180
+ self.directory = dir
181
+ self.set_filter(dir, pat)
182
+ names.sort()
183
+ subdirs = [os.pardir]
184
+ matchingfiles = []
185
+ for name in names:
186
+ fullname = os.path.join(dir, name)
187
+ if os.path.isdir(fullname):
188
+ subdirs.append(name)
189
+ elif fnmatch.fnmatch(name, pat):
190
+ matchingfiles.append(name)
191
+ self.dirs.delete(0, END)
192
+ for name in subdirs:
193
+ self.dirs.insert(END, name)
194
+ self.files.delete(0, END)
195
+ for name in matchingfiles:
196
+ self.files.insert(END, name)
197
+ head, tail = os.path.split(self.get_selection())
198
+ if tail == os.curdir: tail = ''
199
+ self.set_selection(tail)
200
+
201
+ def get_filter(self):
202
+ filter = self.filter.get()
203
+ filter = os.path.expanduser(filter)
204
+ if filter[-1:] == os.sep or os.path.isdir(filter):
205
+ filter = os.path.join(filter, "*")
206
+ return os.path.split(filter)
207
+
208
+ def get_selection(self):
209
+ file = self.selection.get()
210
+ file = os.path.expanduser(file)
211
+ return file
212
+
213
+ def cancel_command(self, event=None):
214
+ self.quit()
215
+
216
+ def set_filter(self, dir, pat):
217
+ if not os.path.isabs(dir):
218
+ try:
219
+ pwd = os.getcwd()
220
+ except OSError:
221
+ pwd = None
222
+ if pwd:
223
+ dir = os.path.join(pwd, dir)
224
+ dir = os.path.normpath(dir)
225
+ self.filter.delete(0, END)
226
+ self.filter.insert(END, os.path.join(dir or os.curdir, pat or "*"))
227
+
228
+ def set_selection(self, file):
229
+ self.selection.delete(0, END)
230
+ self.selection.insert(END, os.path.join(self.directory, file))
231
+
232
+
233
+ class LoadFileDialog(FileDialog):
234
+
235
+ """File selection dialog which checks that the file exists."""
236
+
237
+ title = "Load File Selection Dialog"
238
+
239
+ def ok_command(self):
240
+ file = self.get_selection()
241
+ if not os.path.isfile(file):
242
+ self.master.bell()
243
+ else:
244
+ self.quit(file)
245
+
246
+
247
+ class SaveFileDialog(FileDialog):
248
+
249
+ """File selection dialog which checks that the file may be created."""
250
+
251
+ title = "Save File Selection Dialog"
252
+
253
+ def ok_command(self):
254
+ file = self.get_selection()
255
+ if os.path.exists(file):
256
+ if os.path.isdir(file):
257
+ self.master.bell()
258
+ return
259
+ d = Dialog(self.top,
260
+ title="Overwrite Existing File Question",
261
+ text="Overwrite existing file %r?" % (file,),
262
+ bitmap='questhead',
263
+ default=1,
264
+ strings=("Yes", "Cancel"))
265
+ if d.num != 0:
266
+ return
267
+ else:
268
+ head, tail = os.path.split(file)
269
+ if not os.path.isdir(head):
270
+ self.master.bell()
271
+ return
272
+ self.quit(file)
273
+
274
+
275
+ # For the following classes and modules:
276
+ #
277
+ # options (all have default values):
278
+ #
279
+ # - defaultextension: added to filename if not explicitly given
280
+ #
281
+ # - filetypes: sequence of (label, pattern) tuples. the same pattern
282
+ # may occur with several patterns. use "*" as pattern to indicate
283
+ # all files.
284
+ #
285
+ # - initialdir: initial directory. preserved by dialog instance.
286
+ #
287
+ # - initialfile: initial file (ignored by the open dialog). preserved
288
+ # by dialog instance.
289
+ #
290
+ # - parent: which window to place the dialog on top of
291
+ #
292
+ # - title: dialog title
293
+ #
294
+ # - multiple: if true user may select more than one file
295
+ #
296
+ # options for the directory chooser:
297
+ #
298
+ # - initialdir, parent, title: see above
299
+ #
300
+ # - mustexist: if true, user must pick an existing directory
301
+ #
302
+
303
+
304
+ class _Dialog(commondialog.Dialog):
305
+
306
+ def _fixoptions(self):
307
+ try:
308
+ # make sure "filetypes" is a tuple
309
+ self.options["filetypes"] = tuple(self.options["filetypes"])
310
+ except KeyError:
311
+ pass
312
+
313
+ def _fixresult(self, widget, result):
314
+ if result:
315
+ # keep directory and filename until next time
316
+ # convert Tcl path objects to strings
317
+ try:
318
+ result = result.string
319
+ except AttributeError:
320
+ # it already is a string
321
+ pass
322
+ path, file = os.path.split(result)
323
+ self.options["initialdir"] = path
324
+ self.options["initialfile"] = file
325
+ self.filename = result # compatibility
326
+ return result
327
+
328
+
329
+ #
330
+ # file dialogs
331
+
332
+ class Open(_Dialog):
333
+ "Ask for a filename to open"
334
+
335
+ command = "tk_getOpenFile"
336
+
337
+ def _fixresult(self, widget, result):
338
+ if isinstance(result, tuple):
339
+ # multiple results:
340
+ result = tuple([getattr(r, "string", r) for r in result])
341
+ if result:
342
+ path, file = os.path.split(result[0])
343
+ self.options["initialdir"] = path
344
+ # don't set initialfile or filename, as we have multiple of these
345
+ return result
346
+ if not widget.tk.wantobjects() and "multiple" in self.options:
347
+ # Need to split result explicitly
348
+ return self._fixresult(widget, widget.tk.splitlist(result))
349
+ return _Dialog._fixresult(self, widget, result)
350
+
351
+
352
+ class SaveAs(_Dialog):
353
+ "Ask for a filename to save as"
354
+
355
+ command = "tk_getSaveFile"
356
+
357
+
358
+ # the directory dialog has its own _fix routines.
359
+ class Directory(commondialog.Dialog):
360
+ "Ask for a directory"
361
+
362
+ command = "tk_chooseDirectory"
363
+
364
+ def _fixresult(self, widget, result):
365
+ if result:
366
+ # convert Tcl path objects to strings
367
+ try:
368
+ result = result.string
369
+ except AttributeError:
370
+ # it already is a string
371
+ pass
372
+ # keep directory until next time
373
+ self.options["initialdir"] = result
374
+ self.directory = result # compatibility
375
+ return result
376
+
377
+ #
378
+ # convenience stuff
379
+
380
+
381
+ def askopenfilename(**options):
382
+ "Ask for a filename to open"
383
+
384
+ return Open(**options).show()
385
+
386
+
387
+ def asksaveasfilename(**options):
388
+ "Ask for a filename to save as"
389
+
390
+ return SaveAs(**options).show()
391
+
392
+
393
+ def askopenfilenames(**options):
394
+ """Ask for multiple filenames to open
395
+
396
+ Returns a list of filenames or empty list if
397
+ cancel button selected
398
+ """
399
+ options["multiple"]=1
400
+ return Open(**options).show()
401
+
402
+ # FIXME: are the following perhaps a bit too convenient?
403
+
404
+
405
+ def askopenfile(mode = "r", **options):
406
+ "Ask for a filename to open, and returned the opened file"
407
+
408
+ filename = Open(**options).show()
409
+ if filename:
410
+ return open(filename, mode)
411
+ return None
412
+
413
+
414
+ def askopenfiles(mode = "r", **options):
415
+ """Ask for multiple filenames and return the open file
416
+ objects
417
+
418
+ returns a list of open file objects or an empty list if
419
+ cancel selected
420
+ """
421
+
422
+ files = askopenfilenames(**options)
423
+ if files:
424
+ ofiles=[]
425
+ for filename in files:
426
+ ofiles.append(open(filename, mode))
427
+ files=ofiles
428
+ return files
429
+
430
+
431
+ def asksaveasfile(mode = "w", **options):
432
+ "Ask for a filename to save as, and returned the opened file"
433
+
434
+ filename = SaveAs(**options).show()
435
+ if filename:
436
+ return open(filename, mode)
437
+ return None
438
+
439
+
440
+ def askdirectory (**options):
441
+ "Ask for a directory, and return the file name"
442
+ return Directory(**options).show()
443
+
444
+
445
+ # --------------------------------------------------------------------
446
+ # test stuff
447
+
448
+ def test():
449
+ """Simple test program."""
450
+ root = Tk()
451
+ root.withdraw()
452
+ fd = LoadFileDialog(root)
453
+ loadfile = fd.go(key="test")
454
+ fd = SaveFileDialog(root)
455
+ savefile = fd.go(key="test")
456
+ print(loadfile, savefile)
457
+
458
+ # Since the file name may contain non-ASCII characters, we need
459
+ # to find an encoding that likely supports the file name, and
460
+ # displays correctly on the terminal.
461
+
462
+ # Start off with UTF-8
463
+ enc = "utf-8"
464
+ import sys
465
+
466
+ # See whether CODESET is defined
467
+ try:
468
+ import locale
469
+ locale.setlocale(locale.LC_ALL,'')
470
+ enc = locale.nl_langinfo(locale.CODESET)
471
+ except (ImportError, AttributeError):
472
+ pass
473
+
474
+ # dialog for opening files
475
+
476
+ openfilename=askopenfilename(filetypes=[("all files", "*")])
477
+ try:
478
+ fp=open(openfilename,"r")
479
+ fp.close()
480
+ except:
481
+ print("Could not open File: ")
482
+ print(sys.exc_info()[1])
483
+
484
+ print("open", openfilename.encode(enc))
485
+
486
+ # dialog for saving files
487
+
488
+ saveasfilename=asksaveasfilename()
489
+ print("saveas", saveasfilename.encode(enc))
490
+
491
+
492
+ if __name__ == '__main__':
493
+ test()
llava/lib/python3.10/tkinter/font.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tkinter font wrapper
2
+ #
3
+ # written by Fredrik Lundh, February 1998
4
+ #
5
+
6
+ import itertools
7
+ import tkinter
8
+
9
+ __version__ = "0.9"
10
+ __all__ = ["NORMAL", "ROMAN", "BOLD", "ITALIC",
11
+ "nametofont", "Font", "families", "names"]
12
+
13
+ # weight/slant
14
+ NORMAL = "normal"
15
+ ROMAN = "roman"
16
+ BOLD = "bold"
17
+ ITALIC = "italic"
18
+
19
+
20
+ def nametofont(name, root=None):
21
+ """Given the name of a tk named font, returns a Font representation.
22
+ """
23
+ return Font(name=name, exists=True, root=root)
24
+
25
+
26
+ class Font:
27
+ """Represents a named font.
28
+
29
+ Constructor options are:
30
+
31
+ font -- font specifier (name, system font, or (family, size, style)-tuple)
32
+ name -- name to use for this font configuration (defaults to a unique name)
33
+ exists -- does a named font by this name already exist?
34
+ Creates a new named font if False, points to the existing font if True.
35
+ Raises _tkinter.TclError if the assertion is false.
36
+
37
+ the following are ignored if font is specified:
38
+
39
+ family -- font 'family', e.g. Courier, Times, Helvetica
40
+ size -- font size in points
41
+ weight -- font thickness: NORMAL, BOLD
42
+ slant -- font slant: ROMAN, ITALIC
43
+ underline -- font underlining: false (0), true (1)
44
+ overstrike -- font strikeout: false (0), true (1)
45
+
46
+ """
47
+
48
+ counter = itertools.count(1)
49
+
50
+ def _set(self, kw):
51
+ options = []
52
+ for k, v in kw.items():
53
+ options.append("-"+k)
54
+ options.append(str(v))
55
+ return tuple(options)
56
+
57
+ def _get(self, args):
58
+ options = []
59
+ for k in args:
60
+ options.append("-"+k)
61
+ return tuple(options)
62
+
63
+ def _mkdict(self, args):
64
+ options = {}
65
+ for i in range(0, len(args), 2):
66
+ options[args[i][1:]] = args[i+1]
67
+ return options
68
+
69
+ def __init__(self, root=None, font=None, name=None, exists=False,
70
+ **options):
71
+ if root is None:
72
+ root = tkinter._get_default_root('use font')
73
+ tk = getattr(root, 'tk', root)
74
+ if font:
75
+ # get actual settings corresponding to the given font
76
+ font = tk.splitlist(tk.call("font", "actual", font))
77
+ else:
78
+ font = self._set(options)
79
+ if not name:
80
+ name = "font" + str(next(self.counter))
81
+ self.name = name
82
+
83
+ if exists:
84
+ self.delete_font = False
85
+ # confirm font exists
86
+ if self.name not in tk.splitlist(tk.call("font", "names")):
87
+ raise tkinter._tkinter.TclError(
88
+ "named font %s does not already exist" % (self.name,))
89
+ # if font config info supplied, apply it
90
+ if font:
91
+ tk.call("font", "configure", self.name, *font)
92
+ else:
93
+ # create new font (raises TclError if the font exists)
94
+ tk.call("font", "create", self.name, *font)
95
+ self.delete_font = True
96
+ self._tk = tk
97
+ self._split = tk.splitlist
98
+ self._call = tk.call
99
+
100
+ def __str__(self):
101
+ return self.name
102
+
103
+ def __repr__(self):
104
+ return f"<{self.__class__.__module__}.{self.__class__.__qualname__}" \
105
+ f" object {self.name!r}>"
106
+
107
+ def __eq__(self, other):
108
+ if not isinstance(other, Font):
109
+ return NotImplemented
110
+ return self.name == other.name and self._tk == other._tk
111
+
112
+ def __getitem__(self, key):
113
+ return self.cget(key)
114
+
115
+ def __setitem__(self, key, value):
116
+ self.configure(**{key: value})
117
+
118
+ def __del__(self):
119
+ try:
120
+ if self.delete_font:
121
+ self._call("font", "delete", self.name)
122
+ except Exception:
123
+ pass
124
+
125
+ def copy(self):
126
+ "Return a distinct copy of the current font"
127
+ return Font(self._tk, **self.actual())
128
+
129
+ def actual(self, option=None, displayof=None):
130
+ "Return actual font attributes"
131
+ args = ()
132
+ if displayof:
133
+ args = ('-displayof', displayof)
134
+ if option:
135
+ args = args + ('-' + option, )
136
+ return self._call("font", "actual", self.name, *args)
137
+ else:
138
+ return self._mkdict(
139
+ self._split(self._call("font", "actual", self.name, *args)))
140
+
141
+ def cget(self, option):
142
+ "Get font attribute"
143
+ return self._call("font", "config", self.name, "-"+option)
144
+
145
+ def config(self, **options):
146
+ "Modify font attributes"
147
+ if options:
148
+ self._call("font", "config", self.name,
149
+ *self._set(options))
150
+ else:
151
+ return self._mkdict(
152
+ self._split(self._call("font", "config", self.name)))
153
+
154
+ configure = config
155
+
156
+ def measure(self, text, displayof=None):
157
+ "Return text width"
158
+ args = (text,)
159
+ if displayof:
160
+ args = ('-displayof', displayof, text)
161
+ return self._tk.getint(self._call("font", "measure", self.name, *args))
162
+
163
+ def metrics(self, *options, **kw):
164
+ """Return font metrics.
165
+
166
+ For best performance, create a dummy widget
167
+ using this font before calling this method."""
168
+ args = ()
169
+ displayof = kw.pop('displayof', None)
170
+ if displayof:
171
+ args = ('-displayof', displayof)
172
+ if options:
173
+ args = args + self._get(options)
174
+ return self._tk.getint(
175
+ self._call("font", "metrics", self.name, *args))
176
+ else:
177
+ res = self._split(self._call("font", "metrics", self.name, *args))
178
+ options = {}
179
+ for i in range(0, len(res), 2):
180
+ options[res[i][1:]] = self._tk.getint(res[i+1])
181
+ return options
182
+
183
+
184
+ def families(root=None, displayof=None):
185
+ "Get font families (as a tuple)"
186
+ if root is None:
187
+ root = tkinter._get_default_root('use font.families()')
188
+ args = ()
189
+ if displayof:
190
+ args = ('-displayof', displayof)
191
+ return root.tk.splitlist(root.tk.call("font", "families", *args))
192
+
193
+
194
+ def names(root=None):
195
+ "Get names of defined fonts (as a tuple)"
196
+ if root is None:
197
+ root = tkinter._get_default_root('use font.names()')
198
+ return root.tk.splitlist(root.tk.call("font", "names"))
199
+
200
+
201
+ # --------------------------------------------------------------------
202
+ # test stuff
203
+
204
+ if __name__ == "__main__":
205
+
206
+ root = tkinter.Tk()
207
+
208
+ # create a font
209
+ f = Font(family="times", size=30, weight=NORMAL)
210
+
211
+ print(f.actual())
212
+ print(f.actual("family"))
213
+ print(f.actual("weight"))
214
+
215
+ print(f.config())
216
+ print(f.cget("family"))
217
+ print(f.cget("weight"))
218
+
219
+ print(names())
220
+
221
+ print(f.measure("hello"), f.metrics("linespace"))
222
+
223
+ print(f.metrics(displayof=root))
224
+
225
+ f = Font(font=("Courier", 20, "bold"))
226
+ print(f.measure("hello"), f.metrics("linespace", displayof=root))
227
+
228
+ w = tkinter.Label(root, text="Hello, world", font=f)
229
+ w.pack()
230
+
231
+ w = tkinter.Button(root, text="Quit!", command=root.destroy)
232
+ w.pack()
233
+
234
+ fb = Font(font=w["font"]).copy()
235
+ fb.config(weight=BOLD)
236
+
237
+ w.config(font=fb)
238
+
239
+ tkinter.mainloop()
llava/lib/python3.10/tkinter/scrolledtext.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A ScrolledText widget feels like a text widget but also has a
2
+ vertical scroll bar on its right. (Later, options may be added to
3
+ add a horizontal bar as well, to make the bars disappear
4
+ automatically when not needed, to move them to the other side of the
5
+ window, etc.)
6
+
7
+ Configuration options are passed to the Text widget.
8
+ A Frame widget is inserted between the master and the text, to hold
9
+ the Scrollbar widget.
10
+ Most methods calls are inherited from the Text widget; Pack, Grid and
11
+ Place methods are redirected to the Frame widget however.
12
+ """
13
+
14
+ from tkinter import Frame, Text, Scrollbar, Pack, Grid, Place
15
+ from tkinter.constants import RIGHT, LEFT, Y, BOTH
16
+
17
+ __all__ = ['ScrolledText']
18
+
19
+
20
+ class ScrolledText(Text):
21
+ def __init__(self, master=None, **kw):
22
+ self.frame = Frame(master)
23
+ self.vbar = Scrollbar(self.frame)
24
+ self.vbar.pack(side=RIGHT, fill=Y)
25
+
26
+ kw.update({'yscrollcommand': self.vbar.set})
27
+ Text.__init__(self, self.frame, **kw)
28
+ self.pack(side=LEFT, fill=BOTH, expand=True)
29
+ self.vbar['command'] = self.yview
30
+
31
+ # Copy geometry methods of self.frame without overriding Text
32
+ # methods -- hack!
33
+ text_meths = vars(Text).keys()
34
+ methods = vars(Pack).keys() | vars(Grid).keys() | vars(Place).keys()
35
+ methods = methods.difference(text_meths)
36
+
37
+ for m in methods:
38
+ if m[0] != '_' and m != 'config' and m != 'configure':
39
+ setattr(self, m, getattr(self.frame, m))
40
+
41
+ def __str__(self):
42
+ return str(self.frame)
43
+
44
+
45
+ def example():
46
+ from tkinter.constants import END
47
+
48
+ stext = ScrolledText(bg='white', height=10)
49
+ stext.insert(END, __doc__)
50
+ stext.pack(fill=BOTH, side=LEFT, expand=True)
51
+ stext.focus_set()
52
+ stext.mainloop()
53
+
54
+
55
+ if __name__ == "__main__":
56
+ example()
llava/lib/python3.10/tkinter/simpledialog.py ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # An Introduction to Tkinter
3
+ #
4
+ # Copyright (c) 1997 by Fredrik Lundh
5
+ #
6
+ # This copyright applies to Dialog, askinteger, askfloat and asktring
7
+ #
8
+ # fredrik@pythonware.com
9
+ # http://www.pythonware.com
10
+ #
11
+ """This modules handles dialog boxes.
12
+
13
+ It contains the following public symbols:
14
+
15
+ SimpleDialog -- A simple but flexible modal dialog box
16
+
17
+ Dialog -- a base class for dialogs
18
+
19
+ askinteger -- get an integer from the user
20
+
21
+ askfloat -- get a float from the user
22
+
23
+ askstring -- get a string from the user
24
+ """
25
+
26
+ from tkinter import *
27
+ from tkinter import _get_temp_root, _destroy_temp_root
28
+ from tkinter import messagebox
29
+
30
+
31
+ class SimpleDialog:
32
+
33
+ def __init__(self, master,
34
+ text='', buttons=[], default=None, cancel=None,
35
+ title=None, class_=None):
36
+ if class_:
37
+ self.root = Toplevel(master, class_=class_)
38
+ else:
39
+ self.root = Toplevel(master)
40
+ if title:
41
+ self.root.title(title)
42
+ self.root.iconname(title)
43
+
44
+ _setup_dialog(self.root)
45
+
46
+ self.message = Message(self.root, text=text, aspect=400)
47
+ self.message.pack(expand=1, fill=BOTH)
48
+ self.frame = Frame(self.root)
49
+ self.frame.pack()
50
+ self.num = default
51
+ self.cancel = cancel
52
+ self.default = default
53
+ self.root.bind('<Return>', self.return_event)
54
+ for num in range(len(buttons)):
55
+ s = buttons[num]
56
+ b = Button(self.frame, text=s,
57
+ command=(lambda self=self, num=num: self.done(num)))
58
+ if num == default:
59
+ b.config(relief=RIDGE, borderwidth=8)
60
+ b.pack(side=LEFT, fill=BOTH, expand=1)
61
+ self.root.protocol('WM_DELETE_WINDOW', self.wm_delete_window)
62
+ self.root.transient(master)
63
+ _place_window(self.root, master)
64
+
65
+ def go(self):
66
+ self.root.wait_visibility()
67
+ self.root.grab_set()
68
+ self.root.mainloop()
69
+ self.root.destroy()
70
+ return self.num
71
+
72
+ def return_event(self, event):
73
+ if self.default is None:
74
+ self.root.bell()
75
+ else:
76
+ self.done(self.default)
77
+
78
+ def wm_delete_window(self):
79
+ if self.cancel is None:
80
+ self.root.bell()
81
+ else:
82
+ self.done(self.cancel)
83
+
84
+ def done(self, num):
85
+ self.num = num
86
+ self.root.quit()
87
+
88
+
89
+ class Dialog(Toplevel):
90
+
91
+ '''Class to open dialogs.
92
+
93
+ This class is intended as a base class for custom dialogs
94
+ '''
95
+
96
+ def __init__(self, parent, title = None):
97
+ '''Initialize a dialog.
98
+
99
+ Arguments:
100
+
101
+ parent -- a parent window (the application window)
102
+
103
+ title -- the dialog title
104
+ '''
105
+ master = parent
106
+ if master is None:
107
+ master = _get_temp_root()
108
+
109
+ Toplevel.__init__(self, master)
110
+
111
+ self.withdraw() # remain invisible for now
112
+ # If the parent is not viewable, don't
113
+ # make the child transient, or else it
114
+ # would be opened withdrawn
115
+ if parent is not None and parent.winfo_viewable():
116
+ self.transient(parent)
117
+
118
+ if title:
119
+ self.title(title)
120
+
121
+ _setup_dialog(self)
122
+
123
+ self.parent = parent
124
+
125
+ self.result = None
126
+
127
+ body = Frame(self)
128
+ self.initial_focus = self.body(body)
129
+ body.pack(padx=5, pady=5)
130
+
131
+ self.buttonbox()
132
+
133
+ if self.initial_focus is None:
134
+ self.initial_focus = self
135
+
136
+ self.protocol("WM_DELETE_WINDOW", self.cancel)
137
+
138
+ _place_window(self, parent)
139
+
140
+ self.initial_focus.focus_set()
141
+
142
+ # wait for window to appear on screen before calling grab_set
143
+ self.wait_visibility()
144
+ self.grab_set()
145
+ self.wait_window(self)
146
+
147
+ def destroy(self):
148
+ '''Destroy the window'''
149
+ self.initial_focus = None
150
+ Toplevel.destroy(self)
151
+ _destroy_temp_root(self.master)
152
+
153
+ #
154
+ # construction hooks
155
+
156
+ def body(self, master):
157
+ '''create dialog body.
158
+
159
+ return widget that should have initial focus.
160
+ This method should be overridden, and is called
161
+ by the __init__ method.
162
+ '''
163
+ pass
164
+
165
+ def buttonbox(self):
166
+ '''add standard button box.
167
+
168
+ override if you do not want the standard buttons
169
+ '''
170
+
171
+ box = Frame(self)
172
+
173
+ w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE)
174
+ w.pack(side=LEFT, padx=5, pady=5)
175
+ w = Button(box, text="Cancel", width=10, command=self.cancel)
176
+ w.pack(side=LEFT, padx=5, pady=5)
177
+
178
+ self.bind("<Return>", self.ok)
179
+ self.bind("<Escape>", self.cancel)
180
+
181
+ box.pack()
182
+
183
+ #
184
+ # standard button semantics
185
+
186
+ def ok(self, event=None):
187
+
188
+ if not self.validate():
189
+ self.initial_focus.focus_set() # put focus back
190
+ return
191
+
192
+ self.withdraw()
193
+ self.update_idletasks()
194
+
195
+ try:
196
+ self.apply()
197
+ finally:
198
+ self.cancel()
199
+
200
+ def cancel(self, event=None):
201
+
202
+ # put focus back to the parent window
203
+ if self.parent is not None:
204
+ self.parent.focus_set()
205
+ self.destroy()
206
+
207
+ #
208
+ # command hooks
209
+
210
+ def validate(self):
211
+ '''validate the data
212
+
213
+ This method is called automatically to validate the data before the
214
+ dialog is destroyed. By default, it always validates OK.
215
+ '''
216
+
217
+ return 1 # override
218
+
219
+ def apply(self):
220
+ '''process the data
221
+
222
+ This method is called automatically to process the data, *after*
223
+ the dialog is destroyed. By default, it does nothing.
224
+ '''
225
+
226
+ pass # override
227
+
228
+
229
+ # Place a toplevel window at the center of parent or screen
230
+ # It is a Python implementation of ::tk::PlaceWindow.
231
+ def _place_window(w, parent=None):
232
+ w.wm_withdraw() # Remain invisible while we figure out the geometry
233
+ w.update_idletasks() # Actualize geometry information
234
+
235
+ minwidth = w.winfo_reqwidth()
236
+ minheight = w.winfo_reqheight()
237
+ maxwidth = w.winfo_vrootwidth()
238
+ maxheight = w.winfo_vrootheight()
239
+ if parent is not None and parent.winfo_ismapped():
240
+ x = parent.winfo_rootx() + (parent.winfo_width() - minwidth) // 2
241
+ y = parent.winfo_rooty() + (parent.winfo_height() - minheight) // 2
242
+ vrootx = w.winfo_vrootx()
243
+ vrooty = w.winfo_vrooty()
244
+ x = min(x, vrootx + maxwidth - minwidth)
245
+ x = max(x, vrootx)
246
+ y = min(y, vrooty + maxheight - minheight)
247
+ y = max(y, vrooty)
248
+ if w._windowingsystem == 'aqua':
249
+ # Avoid the native menu bar which sits on top of everything.
250
+ y = max(y, 22)
251
+ else:
252
+ x = (w.winfo_screenwidth() - minwidth) // 2
253
+ y = (w.winfo_screenheight() - minheight) // 2
254
+
255
+ w.wm_maxsize(maxwidth, maxheight)
256
+ w.wm_geometry('+%d+%d' % (x, y))
257
+ w.wm_deiconify() # Become visible at the desired location
258
+
259
+
260
+ def _setup_dialog(w):
261
+ if w._windowingsystem == "aqua":
262
+ w.tk.call("::tk::unsupported::MacWindowStyle", "style",
263
+ w, "moveableModal", "")
264
+ elif w._windowingsystem == "x11":
265
+ w.wm_attributes("-type", "dialog")
266
+
267
+ # --------------------------------------------------------------------
268
+ # convenience dialogues
269
+
270
+ class _QueryDialog(Dialog):
271
+
272
+ def __init__(self, title, prompt,
273
+ initialvalue=None,
274
+ minvalue = None, maxvalue = None,
275
+ parent = None):
276
+
277
+ self.prompt = prompt
278
+ self.minvalue = minvalue
279
+ self.maxvalue = maxvalue
280
+
281
+ self.initialvalue = initialvalue
282
+
283
+ Dialog.__init__(self, parent, title)
284
+
285
+ def destroy(self):
286
+ self.entry = None
287
+ Dialog.destroy(self)
288
+
289
+ def body(self, master):
290
+
291
+ w = Label(master, text=self.prompt, justify=LEFT)
292
+ w.grid(row=0, padx=5, sticky=W)
293
+
294
+ self.entry = Entry(master, name="entry")
295
+ self.entry.grid(row=1, padx=5, sticky=W+E)
296
+
297
+ if self.initialvalue is not None:
298
+ self.entry.insert(0, self.initialvalue)
299
+ self.entry.select_range(0, END)
300
+
301
+ return self.entry
302
+
303
+ def validate(self):
304
+ try:
305
+ result = self.getresult()
306
+ except ValueError:
307
+ messagebox.showwarning(
308
+ "Illegal value",
309
+ self.errormessage + "\nPlease try again",
310
+ parent = self
311
+ )
312
+ return 0
313
+
314
+ if self.minvalue is not None and result < self.minvalue:
315
+ messagebox.showwarning(
316
+ "Too small",
317
+ "The allowed minimum value is %s. "
318
+ "Please try again." % self.minvalue,
319
+ parent = self
320
+ )
321
+ return 0
322
+
323
+ if self.maxvalue is not None and result > self.maxvalue:
324
+ messagebox.showwarning(
325
+ "Too large",
326
+ "The allowed maximum value is %s. "
327
+ "Please try again." % self.maxvalue,
328
+ parent = self
329
+ )
330
+ return 0
331
+
332
+ self.result = result
333
+
334
+ return 1
335
+
336
+
337
+ class _QueryInteger(_QueryDialog):
338
+ errormessage = "Not an integer."
339
+
340
+ def getresult(self):
341
+ return self.getint(self.entry.get())
342
+
343
+
344
+ def askinteger(title, prompt, **kw):
345
+ '''get an integer from the user
346
+
347
+ Arguments:
348
+
349
+ title -- the dialog title
350
+ prompt -- the label text
351
+ **kw -- see SimpleDialog class
352
+
353
+ Return value is an integer
354
+ '''
355
+ d = _QueryInteger(title, prompt, **kw)
356
+ return d.result
357
+
358
+
359
+ class _QueryFloat(_QueryDialog):
360
+ errormessage = "Not a floating point value."
361
+
362
+ def getresult(self):
363
+ return self.getdouble(self.entry.get())
364
+
365
+
366
+ def askfloat(title, prompt, **kw):
367
+ '''get a float from the user
368
+
369
+ Arguments:
370
+
371
+ title -- the dialog title
372
+ prompt -- the label text
373
+ **kw -- see SimpleDialog class
374
+
375
+ Return value is a float
376
+ '''
377
+ d = _QueryFloat(title, prompt, **kw)
378
+ return d.result
379
+
380
+
381
+ class _QueryString(_QueryDialog):
382
+ def __init__(self, *args, **kw):
383
+ if "show" in kw:
384
+ self.__show = kw["show"]
385
+ del kw["show"]
386
+ else:
387
+ self.__show = None
388
+ _QueryDialog.__init__(self, *args, **kw)
389
+
390
+ def body(self, master):
391
+ entry = _QueryDialog.body(self, master)
392
+ if self.__show is not None:
393
+ entry.configure(show=self.__show)
394
+ return entry
395
+
396
+ def getresult(self):
397
+ return self.entry.get()
398
+
399
+
400
+ def askstring(title, prompt, **kw):
401
+ '''get a string from the user
402
+
403
+ Arguments:
404
+
405
+ title -- the dialog title
406
+ prompt -- the label text
407
+ **kw -- see SimpleDialog class
408
+
409
+ Return value is a string
410
+ '''
411
+ d = _QueryString(title, prompt, **kw)
412
+ return d.result
413
+
414
+
415
+ if __name__ == '__main__':
416
+
417
+ def test():
418
+ root = Tk()
419
+ def doit(root=root):
420
+ d = SimpleDialog(root,
421
+ text="This is a test dialog. "
422
+ "Would this have been an actual dialog, "
423
+ "the buttons below would have been glowing "
424
+ "in soft pink light.\n"
425
+ "Do you believe this?",
426
+ buttons=["Yes", "No", "Cancel"],
427
+ default=0,
428
+ cancel=2,
429
+ title="Test Dialog")
430
+ print(d.go())
431
+ print(askinteger("Spam", "Egg count", initialvalue=12*12))
432
+ print(askfloat("Spam", "Egg weight\n(in tons)", minvalue=1,
433
+ maxvalue=100))
434
+ print(askstring("Spam", "Egg label"))
435
+ t = Button(root, text='Test', command=doit)
436
+ t.pack()
437
+ q = Button(root, text='Quit', command=t.quit)
438
+ q.pack()
439
+ t.mainloop()
440
+
441
+ test()
llava/lib/python3.10/tkinter/ttk.py ADDED
@@ -0,0 +1,1662 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ttk wrapper.
2
+
3
+ This module provides classes to allow using Tk themed widget set.
4
+
5
+ Ttk is based on a revised and enhanced version of
6
+ TIP #48 (http://tip.tcl.tk/48) specified style engine.
7
+
8
+ Its basic idea is to separate, to the extent possible, the code
9
+ implementing a widget's behavior from the code implementing its
10
+ appearance. Widget class bindings are primarily responsible for
11
+ maintaining the widget state and invoking callbacks, all aspects
12
+ of the widgets appearance lies at Themes.
13
+ """
14
+
15
+ __version__ = "0.3.1"
16
+
17
+ __author__ = "Guilherme Polo <ggpolo@gmail.com>"
18
+
19
+ __all__ = ["Button", "Checkbutton", "Combobox", "Entry", "Frame", "Label",
20
+ "Labelframe", "LabelFrame", "Menubutton", "Notebook", "Panedwindow",
21
+ "PanedWindow", "Progressbar", "Radiobutton", "Scale", "Scrollbar",
22
+ "Separator", "Sizegrip", "Spinbox", "Style", "Treeview",
23
+ # Extensions
24
+ "LabeledScale", "OptionMenu",
25
+ # functions
26
+ "tclobjs_to_py", "setup_master"]
27
+
28
+ import tkinter
29
+ from tkinter import _flatten, _join, _stringify, _splitdict
30
+
31
+ # Verify if Tk is new enough to not need the Tile package
32
+ _REQUIRE_TILE = True if tkinter.TkVersion < 8.5 else False
33
+
34
+ def _load_tile(master):
35
+ if _REQUIRE_TILE:
36
+ import os
37
+ tilelib = os.environ.get('TILE_LIBRARY')
38
+ if tilelib:
39
+ # append custom tile path to the list of directories that
40
+ # Tcl uses when attempting to resolve packages with the package
41
+ # command
42
+ master.tk.eval(
43
+ 'global auto_path; '
44
+ 'lappend auto_path {%s}' % tilelib)
45
+
46
+ master.tk.eval('package require tile') # TclError may be raised here
47
+ master._tile_loaded = True
48
+
49
+ def _format_optvalue(value, script=False):
50
+ """Internal function."""
51
+ if script:
52
+ # if caller passes a Tcl script to tk.call, all the values need to
53
+ # be grouped into words (arguments to a command in Tcl dialect)
54
+ value = _stringify(value)
55
+ elif isinstance(value, (list, tuple)):
56
+ value = _join(value)
57
+ return value
58
+
59
+ def _format_optdict(optdict, script=False, ignore=None):
60
+ """Formats optdict to a tuple to pass it to tk.call.
61
+
62
+ E.g. (script=False):
63
+ {'foreground': 'blue', 'padding': [1, 2, 3, 4]} returns:
64
+ ('-foreground', 'blue', '-padding', '1 2 3 4')"""
65
+
66
+ opts = []
67
+ for opt, value in optdict.items():
68
+ if not ignore or opt not in ignore:
69
+ opts.append("-%s" % opt)
70
+ if value is not None:
71
+ opts.append(_format_optvalue(value, script))
72
+
73
+ return _flatten(opts)
74
+
75
+ def _mapdict_values(items):
76
+ # each value in mapdict is expected to be a sequence, where each item
77
+ # is another sequence containing a state (or several) and a value
78
+ # E.g. (script=False):
79
+ # [('active', 'selected', 'grey'), ('focus', [1, 2, 3, 4])]
80
+ # returns:
81
+ # ['active selected', 'grey', 'focus', [1, 2, 3, 4]]
82
+ opt_val = []
83
+ for *state, val in items:
84
+ if len(state) == 1:
85
+ # if it is empty (something that evaluates to False), then
86
+ # format it to Tcl code to denote the "normal" state
87
+ state = state[0] or ''
88
+ else:
89
+ # group multiple states
90
+ state = ' '.join(state) # raise TypeError if not str
91
+ opt_val.append(state)
92
+ if val is not None:
93
+ opt_val.append(val)
94
+ return opt_val
95
+
96
+ def _format_mapdict(mapdict, script=False):
97
+ """Formats mapdict to pass it to tk.call.
98
+
99
+ E.g. (script=False):
100
+ {'expand': [('active', 'selected', 'grey'), ('focus', [1, 2, 3, 4])]}
101
+
102
+ returns:
103
+
104
+ ('-expand', '{active selected} grey focus {1, 2, 3, 4}')"""
105
+
106
+ opts = []
107
+ for opt, value in mapdict.items():
108
+ opts.extend(("-%s" % opt,
109
+ _format_optvalue(_mapdict_values(value), script)))
110
+
111
+ return _flatten(opts)
112
+
113
+ def _format_elemcreate(etype, script=False, *args, **kw):
114
+ """Formats args and kw according to the given element factory etype."""
115
+ spec = None
116
+ opts = ()
117
+ if etype in ("image", "vsapi"):
118
+ if etype == "image": # define an element based on an image
119
+ # first arg should be the default image name
120
+ iname = args[0]
121
+ # next args, if any, are statespec/value pairs which is almost
122
+ # a mapdict, but we just need the value
123
+ imagespec = _join(_mapdict_values(args[1:]))
124
+ spec = "%s %s" % (iname, imagespec)
125
+
126
+ else:
127
+ # define an element whose visual appearance is drawn using the
128
+ # Microsoft Visual Styles API which is responsible for the
129
+ # themed styles on Windows XP and Vista.
130
+ # Availability: Tk 8.6, Windows XP and Vista.
131
+ class_name, part_id = args[:2]
132
+ statemap = _join(_mapdict_values(args[2:]))
133
+ spec = "%s %s %s" % (class_name, part_id, statemap)
134
+
135
+ opts = _format_optdict(kw, script)
136
+
137
+ elif etype == "from": # clone an element
138
+ # it expects a themename and optionally an element to clone from,
139
+ # otherwise it will clone {} (empty element)
140
+ spec = args[0] # theme name
141
+ if len(args) > 1: # elementfrom specified
142
+ opts = (_format_optvalue(args[1], script),)
143
+
144
+ if script:
145
+ spec = '{%s}' % spec
146
+ opts = ' '.join(opts)
147
+
148
+ return spec, opts
149
+
150
+ def _format_layoutlist(layout, indent=0, indent_size=2):
151
+ """Formats a layout list so we can pass the result to ttk::style
152
+ layout and ttk::style settings. Note that the layout doesn't have to
153
+ be a list necessarily.
154
+
155
+ E.g.:
156
+ [("Menubutton.background", None),
157
+ ("Menubutton.button", {"children":
158
+ [("Menubutton.focus", {"children":
159
+ [("Menubutton.padding", {"children":
160
+ [("Menubutton.label", {"side": "left", "expand": 1})]
161
+ })]
162
+ })]
163
+ }),
164
+ ("Menubutton.indicator", {"side": "right"})
165
+ ]
166
+
167
+ returns:
168
+
169
+ Menubutton.background
170
+ Menubutton.button -children {
171
+ Menubutton.focus -children {
172
+ Menubutton.padding -children {
173
+ Menubutton.label -side left -expand 1
174
+ }
175
+ }
176
+ }
177
+ Menubutton.indicator -side right"""
178
+ script = []
179
+
180
+ for layout_elem in layout:
181
+ elem, opts = layout_elem
182
+ opts = opts or {}
183
+ fopts = ' '.join(_format_optdict(opts, True, ("children",)))
184
+ head = "%s%s%s" % (' ' * indent, elem, (" %s" % fopts) if fopts else '')
185
+
186
+ if "children" in opts:
187
+ script.append(head + " -children {")
188
+ indent += indent_size
189
+ newscript, indent = _format_layoutlist(opts['children'], indent,
190
+ indent_size)
191
+ script.append(newscript)
192
+ indent -= indent_size
193
+ script.append('%s}' % (' ' * indent))
194
+ else:
195
+ script.append(head)
196
+
197
+ return '\n'.join(script), indent
198
+
199
+ def _script_from_settings(settings):
200
+ """Returns an appropriate script, based on settings, according to
201
+ theme_settings definition to be used by theme_settings and
202
+ theme_create."""
203
+ script = []
204
+ # a script will be generated according to settings passed, which
205
+ # will then be evaluated by Tcl
206
+ for name, opts in settings.items():
207
+ # will format specific keys according to Tcl code
208
+ if opts.get('configure'): # format 'configure'
209
+ s = ' '.join(_format_optdict(opts['configure'], True))
210
+ script.append("ttk::style configure %s %s;" % (name, s))
211
+
212
+ if opts.get('map'): # format 'map'
213
+ s = ' '.join(_format_mapdict(opts['map'], True))
214
+ script.append("ttk::style map %s %s;" % (name, s))
215
+
216
+ if 'layout' in opts: # format 'layout' which may be empty
217
+ if not opts['layout']:
218
+ s = 'null' # could be any other word, but this one makes sense
219
+ else:
220
+ s, _ = _format_layoutlist(opts['layout'])
221
+ script.append("ttk::style layout %s {\n%s\n}" % (name, s))
222
+
223
+ if opts.get('element create'): # format 'element create'
224
+ eopts = opts['element create']
225
+ etype = eopts[0]
226
+
227
+ # find where args end, and where kwargs start
228
+ argc = 1 # etype was the first one
229
+ while argc < len(eopts) and not hasattr(eopts[argc], 'items'):
230
+ argc += 1
231
+
232
+ elemargs = eopts[1:argc]
233
+ elemkw = eopts[argc] if argc < len(eopts) and eopts[argc] else {}
234
+ spec, opts = _format_elemcreate(etype, True, *elemargs, **elemkw)
235
+
236
+ script.append("ttk::style element create %s %s %s %s" % (
237
+ name, etype, spec, opts))
238
+
239
+ return '\n'.join(script)
240
+
241
+ def _list_from_statespec(stuple):
242
+ """Construct a list from the given statespec tuple according to the
243
+ accepted statespec accepted by _format_mapdict."""
244
+ if isinstance(stuple, str):
245
+ return stuple
246
+ result = []
247
+ it = iter(stuple)
248
+ for state, val in zip(it, it):
249
+ if hasattr(state, 'typename'): # this is a Tcl object
250
+ state = str(state).split()
251
+ elif isinstance(state, str):
252
+ state = state.split()
253
+ elif not isinstance(state, (tuple, list)):
254
+ state = (state,)
255
+ if hasattr(val, 'typename'):
256
+ val = str(val)
257
+ result.append((*state, val))
258
+
259
+ return result
260
+
261
+ def _list_from_layouttuple(tk, ltuple):
262
+ """Construct a list from the tuple returned by ttk::layout, this is
263
+ somewhat the reverse of _format_layoutlist."""
264
+ ltuple = tk.splitlist(ltuple)
265
+ res = []
266
+
267
+ indx = 0
268
+ while indx < len(ltuple):
269
+ name = ltuple[indx]
270
+ opts = {}
271
+ res.append((name, opts))
272
+ indx += 1
273
+
274
+ while indx < len(ltuple): # grab name's options
275
+ opt, val = ltuple[indx:indx + 2]
276
+ if not opt.startswith('-'): # found next name
277
+ break
278
+
279
+ opt = opt[1:] # remove the '-' from the option
280
+ indx += 2
281
+
282
+ if opt == 'children':
283
+ val = _list_from_layouttuple(tk, val)
284
+
285
+ opts[opt] = val
286
+
287
+ return res
288
+
289
+ def _val_or_dict(tk, options, *args):
290
+ """Format options then call Tk command with args and options and return
291
+ the appropriate result.
292
+
293
+ If no option is specified, a dict is returned. If an option is
294
+ specified with the None value, the value for that option is returned.
295
+ Otherwise, the function just sets the passed options and the caller
296
+ shouldn't be expecting a return value anyway."""
297
+ options = _format_optdict(options)
298
+ res = tk.call(*(args + options))
299
+
300
+ if len(options) % 2: # option specified without a value, return its value
301
+ return res
302
+
303
+ return _splitdict(tk, res, conv=_tclobj_to_py)
304
+
305
+ def _convert_stringval(value):
306
+ """Converts a value to, hopefully, a more appropriate Python object."""
307
+ value = str(value)
308
+ try:
309
+ value = int(value)
310
+ except (ValueError, TypeError):
311
+ pass
312
+
313
+ return value
314
+
315
+ def _to_number(x):
316
+ if isinstance(x, str):
317
+ if '.' in x:
318
+ x = float(x)
319
+ else:
320
+ x = int(x)
321
+ return x
322
+
323
+ def _tclobj_to_py(val):
324
+ """Return value converted from Tcl object to Python object."""
325
+ if val and hasattr(val, '__len__') and not isinstance(val, str):
326
+ if getattr(val[0], 'typename', None) == 'StateSpec':
327
+ val = _list_from_statespec(val)
328
+ else:
329
+ val = list(map(_convert_stringval, val))
330
+
331
+ elif hasattr(val, 'typename'): # some other (single) Tcl object
332
+ val = _convert_stringval(val)
333
+
334
+ return val
335
+
336
+ def tclobjs_to_py(adict):
337
+ """Returns adict with its values converted from Tcl objects to Python
338
+ objects."""
339
+ for opt, val in adict.items():
340
+ adict[opt] = _tclobj_to_py(val)
341
+
342
+ return adict
343
+
344
+ def setup_master(master=None):
345
+ """If master is not None, itself is returned. If master is None,
346
+ the default master is returned if there is one, otherwise a new
347
+ master is created and returned.
348
+
349
+ If it is not allowed to use the default root and master is None,
350
+ RuntimeError is raised."""
351
+ if master is None:
352
+ master = tkinter._get_default_root()
353
+ return master
354
+
355
+
356
+ class Style(object):
357
+ """Manipulate style database."""
358
+
359
+ _name = "ttk::style"
360
+
361
+ def __init__(self, master=None):
362
+ master = setup_master(master)
363
+
364
+ if not getattr(master, '_tile_loaded', False):
365
+ # Load tile now, if needed
366
+ _load_tile(master)
367
+
368
+ self.master = master
369
+ self.tk = self.master.tk
370
+
371
+
372
+ def configure(self, style, query_opt=None, **kw):
373
+ """Query or sets the default value of the specified option(s) in
374
+ style.
375
+
376
+ Each key in kw is an option and each value is either a string or
377
+ a sequence identifying the value for that option."""
378
+ if query_opt is not None:
379
+ kw[query_opt] = None
380
+ result = _val_or_dict(self.tk, kw, self._name, "configure", style)
381
+ if result or query_opt:
382
+ return result
383
+
384
+
385
+ def map(self, style, query_opt=None, **kw):
386
+ """Query or sets dynamic values of the specified option(s) in
387
+ style.
388
+
389
+ Each key in kw is an option and each value should be a list or a
390
+ tuple (usually) containing statespecs grouped in tuples, or list,
391
+ or something else of your preference. A statespec is compound of
392
+ one or more states and then a value."""
393
+ if query_opt is not None:
394
+ result = self.tk.call(self._name, "map", style, '-%s' % query_opt)
395
+ return _list_from_statespec(self.tk.splitlist(result))
396
+
397
+ result = self.tk.call(self._name, "map", style, *_format_mapdict(kw))
398
+ return {k: _list_from_statespec(self.tk.splitlist(v))
399
+ for k, v in _splitdict(self.tk, result).items()}
400
+
401
+
402
+ def lookup(self, style, option, state=None, default=None):
403
+ """Returns the value specified for option in style.
404
+
405
+ If state is specified it is expected to be a sequence of one
406
+ or more states. If the default argument is set, it is used as
407
+ a fallback value in case no specification for option is found."""
408
+ state = ' '.join(state) if state else ''
409
+
410
+ return self.tk.call(self._name, "lookup", style, '-%s' % option,
411
+ state, default)
412
+
413
+
414
+ def layout(self, style, layoutspec=None):
415
+ """Define the widget layout for given style. If layoutspec is
416
+ omitted, return the layout specification for given style.
417
+
418
+ layoutspec is expected to be a list or an object different than
419
+ None that evaluates to False if you want to "turn off" that style.
420
+ If it is a list (or tuple, or something else), each item should be
421
+ a tuple where the first item is the layout name and the second item
422
+ should have the format described below:
423
+
424
+ LAYOUTS
425
+
426
+ A layout can contain the value None, if takes no options, or
427
+ a dict of options specifying how to arrange the element.
428
+ The layout mechanism uses a simplified version of the pack
429
+ geometry manager: given an initial cavity, each element is
430
+ allocated a parcel. Valid options/values are:
431
+
432
+ side: whichside
433
+ Specifies which side of the cavity to place the
434
+ element; one of top, right, bottom or left. If
435
+ omitted, the element occupies the entire cavity.
436
+
437
+ sticky: nswe
438
+ Specifies where the element is placed inside its
439
+ allocated parcel.
440
+
441
+ children: [sublayout... ]
442
+ Specifies a list of elements to place inside the
443
+ element. Each element is a tuple (or other sequence)
444
+ where the first item is the layout name, and the other
445
+ is a LAYOUT."""
446
+ lspec = None
447
+ if layoutspec:
448
+ lspec = _format_layoutlist(layoutspec)[0]
449
+ elif layoutspec is not None: # will disable the layout ({}, '', etc)
450
+ lspec = "null" # could be any other word, but this may make sense
451
+ # when calling layout(style) later
452
+
453
+ return _list_from_layouttuple(self.tk,
454
+ self.tk.call(self._name, "layout", style, lspec))
455
+
456
+
457
+ def element_create(self, elementname, etype, *args, **kw):
458
+ """Create a new element in the current theme of given etype."""
459
+ spec, opts = _format_elemcreate(etype, False, *args, **kw)
460
+ self.tk.call(self._name, "element", "create", elementname, etype,
461
+ spec, *opts)
462
+
463
+
464
+ def element_names(self):
465
+ """Returns the list of elements defined in the current theme."""
466
+ return tuple(n.lstrip('-') for n in self.tk.splitlist(
467
+ self.tk.call(self._name, "element", "names")))
468
+
469
+
470
+ def element_options(self, elementname):
471
+ """Return the list of elementname's options."""
472
+ return tuple(o.lstrip('-') for o in self.tk.splitlist(
473
+ self.tk.call(self._name, "element", "options", elementname)))
474
+
475
+
476
+ def theme_create(self, themename, parent=None, settings=None):
477
+ """Creates a new theme.
478
+
479
+ It is an error if themename already exists. If parent is
480
+ specified, the new theme will inherit styles, elements and
481
+ layouts from the specified parent theme. If settings are present,
482
+ they are expected to have the same syntax used for theme_settings."""
483
+ script = _script_from_settings(settings) if settings else ''
484
+
485
+ if parent:
486
+ self.tk.call(self._name, "theme", "create", themename,
487
+ "-parent", parent, "-settings", script)
488
+ else:
489
+ self.tk.call(self._name, "theme", "create", themename,
490
+ "-settings", script)
491
+
492
+
493
+ def theme_settings(self, themename, settings):
494
+ """Temporarily sets the current theme to themename, apply specified
495
+ settings and then restore the previous theme.
496
+
497
+ Each key in settings is a style and each value may contain the
498
+ keys 'configure', 'map', 'layout' and 'element create' and they
499
+ are expected to have the same format as specified by the methods
500
+ configure, map, layout and element_create respectively."""
501
+ script = _script_from_settings(settings)
502
+ self.tk.call(self._name, "theme", "settings", themename, script)
503
+
504
+
505
+ def theme_names(self):
506
+ """Returns a list of all known themes."""
507
+ return self.tk.splitlist(self.tk.call(self._name, "theme", "names"))
508
+
509
+
510
+ def theme_use(self, themename=None):
511
+ """If themename is None, returns the theme in use, otherwise, set
512
+ the current theme to themename, refreshes all widgets and emits
513
+ a <<ThemeChanged>> event."""
514
+ if themename is None:
515
+ # Starting on Tk 8.6, checking this global is no longer needed
516
+ # since it allows doing self.tk.call(self._name, "theme", "use")
517
+ return self.tk.eval("return $ttk::currentTheme")
518
+
519
+ # using "ttk::setTheme" instead of "ttk::style theme use" causes
520
+ # the variable currentTheme to be updated, also, ttk::setTheme calls
521
+ # "ttk::style theme use" in order to change theme.
522
+ self.tk.call("ttk::setTheme", themename)
523
+
524
+
525
+ class Widget(tkinter.Widget):
526
+ """Base class for Tk themed widgets."""
527
+
528
+ def __init__(self, master, widgetname, kw=None):
529
+ """Constructs a Ttk Widget with the parent master.
530
+
531
+ STANDARD OPTIONS
532
+
533
+ class, cursor, takefocus, style
534
+
535
+ SCROLLABLE WIDGET OPTIONS
536
+
537
+ xscrollcommand, yscrollcommand
538
+
539
+ LABEL WIDGET OPTIONS
540
+
541
+ text, textvariable, underline, image, compound, width
542
+
543
+ WIDGET STATES
544
+
545
+ active, disabled, focus, pressed, selected, background,
546
+ readonly, alternate, invalid
547
+ """
548
+ master = setup_master(master)
549
+ if not getattr(master, '_tile_loaded', False):
550
+ # Load tile now, if needed
551
+ _load_tile(master)
552
+ tkinter.Widget.__init__(self, master, widgetname, kw=kw)
553
+
554
+
555
+ def identify(self, x, y):
556
+ """Returns the name of the element at position x, y, or the empty
557
+ string if the point does not lie within any element.
558
+
559
+ x and y are pixel coordinates relative to the widget."""
560
+ return self.tk.call(self._w, "identify", x, y)
561
+
562
+
563
+ def instate(self, statespec, callback=None, *args, **kw):
564
+ """Test the widget's state.
565
+
566
+ If callback is not specified, returns True if the widget state
567
+ matches statespec and False otherwise. If callback is specified,
568
+ then it will be invoked with *args, **kw if the widget state
569
+ matches statespec. statespec is expected to be a sequence."""
570
+ ret = self.tk.getboolean(
571
+ self.tk.call(self._w, "instate", ' '.join(statespec)))
572
+ if ret and callback is not None:
573
+ return callback(*args, **kw)
574
+
575
+ return ret
576
+
577
+
578
+ def state(self, statespec=None):
579
+ """Modify or inquire widget state.
580
+
581
+ Widget state is returned if statespec is None, otherwise it is
582
+ set according to the statespec flags and then a new state spec
583
+ is returned indicating which flags were changed. statespec is
584
+ expected to be a sequence."""
585
+ if statespec is not None:
586
+ statespec = ' '.join(statespec)
587
+
588
+ return self.tk.splitlist(str(self.tk.call(self._w, "state", statespec)))
589
+
590
+
591
+ class Button(Widget):
592
+ """Ttk Button widget, displays a textual label and/or image, and
593
+ evaluates a command when pressed."""
594
+
595
+ def __init__(self, master=None, **kw):
596
+ """Construct a Ttk Button widget with the parent master.
597
+
598
+ STANDARD OPTIONS
599
+
600
+ class, compound, cursor, image, state, style, takefocus,
601
+ text, textvariable, underline, width
602
+
603
+ WIDGET-SPECIFIC OPTIONS
604
+
605
+ command, default, width
606
+ """
607
+ Widget.__init__(self, master, "ttk::button", kw)
608
+
609
+
610
+ def invoke(self):
611
+ """Invokes the command associated with the button."""
612
+ return self.tk.call(self._w, "invoke")
613
+
614
+
615
+ class Checkbutton(Widget):
616
+ """Ttk Checkbutton widget which is either in on- or off-state."""
617
+
618
+ def __init__(self, master=None, **kw):
619
+ """Construct a Ttk Checkbutton widget with the parent master.
620
+
621
+ STANDARD OPTIONS
622
+
623
+ class, compound, cursor, image, state, style, takefocus,
624
+ text, textvariable, underline, width
625
+
626
+ WIDGET-SPECIFIC OPTIONS
627
+
628
+ command, offvalue, onvalue, variable
629
+ """
630
+ Widget.__init__(self, master, "ttk::checkbutton", kw)
631
+
632
+
633
+ def invoke(self):
634
+ """Toggles between the selected and deselected states and
635
+ invokes the associated command. If the widget is currently
636
+ selected, sets the option variable to the offvalue option
637
+ and deselects the widget; otherwise, sets the option variable
638
+ to the option onvalue.
639
+
640
+ Returns the result of the associated command."""
641
+ return self.tk.call(self._w, "invoke")
642
+
643
+
644
+ class Entry(Widget, tkinter.Entry):
645
+ """Ttk Entry widget displays a one-line text string and allows that
646
+ string to be edited by the user."""
647
+
648
+ def __init__(self, master=None, widget=None, **kw):
649
+ """Constructs a Ttk Entry widget with the parent master.
650
+
651
+ STANDARD OPTIONS
652
+
653
+ class, cursor, style, takefocus, xscrollcommand
654
+
655
+ WIDGET-SPECIFIC OPTIONS
656
+
657
+ exportselection, invalidcommand, justify, show, state,
658
+ textvariable, validate, validatecommand, width
659
+
660
+ VALIDATION MODES
661
+
662
+ none, key, focus, focusin, focusout, all
663
+ """
664
+ Widget.__init__(self, master, widget or "ttk::entry", kw)
665
+
666
+
667
+ def bbox(self, index):
668
+ """Return a tuple of (x, y, width, height) which describes the
669
+ bounding box of the character given by index."""
670
+ return self._getints(self.tk.call(self._w, "bbox", index))
671
+
672
+
673
+ def identify(self, x, y):
674
+ """Returns the name of the element at position x, y, or the
675
+ empty string if the coordinates are outside the window."""
676
+ return self.tk.call(self._w, "identify", x, y)
677
+
678
+
679
+ def validate(self):
680
+ """Force revalidation, independent of the conditions specified
681
+ by the validate option. Returns False if validation fails, True
682
+ if it succeeds. Sets or clears the invalid state accordingly."""
683
+ return self.tk.getboolean(self.tk.call(self._w, "validate"))
684
+
685
+
686
+ class Combobox(Entry):
687
+ """Ttk Combobox widget combines a text field with a pop-down list of
688
+ values."""
689
+
690
+ def __init__(self, master=None, **kw):
691
+ """Construct a Ttk Combobox widget with the parent master.
692
+
693
+ STANDARD OPTIONS
694
+
695
+ class, cursor, style, takefocus
696
+
697
+ WIDGET-SPECIFIC OPTIONS
698
+
699
+ exportselection, justify, height, postcommand, state,
700
+ textvariable, values, width
701
+ """
702
+ Entry.__init__(self, master, "ttk::combobox", **kw)
703
+
704
+
705
+ def current(self, newindex=None):
706
+ """If newindex is supplied, sets the combobox value to the
707
+ element at position newindex in the list of values. Otherwise,
708
+ returns the index of the current value in the list of values
709
+ or -1 if the current value does not appear in the list."""
710
+ if newindex is None:
711
+ return self.tk.getint(self.tk.call(self._w, "current"))
712
+ return self.tk.call(self._w, "current", newindex)
713
+
714
+
715
+ def set(self, value):
716
+ """Sets the value of the combobox to value."""
717
+ self.tk.call(self._w, "set", value)
718
+
719
+
720
+ class Frame(Widget):
721
+ """Ttk Frame widget is a container, used to group other widgets
722
+ together."""
723
+
724
+ def __init__(self, master=None, **kw):
725
+ """Construct a Ttk Frame with parent master.
726
+
727
+ STANDARD OPTIONS
728
+
729
+ class, cursor, style, takefocus
730
+
731
+ WIDGET-SPECIFIC OPTIONS
732
+
733
+ borderwidth, relief, padding, width, height
734
+ """
735
+ Widget.__init__(self, master, "ttk::frame", kw)
736
+
737
+
738
+ class Label(Widget):
739
+ """Ttk Label widget displays a textual label and/or image."""
740
+
741
+ def __init__(self, master=None, **kw):
742
+ """Construct a Ttk Label with parent master.
743
+
744
+ STANDARD OPTIONS
745
+
746
+ class, compound, cursor, image, style, takefocus, text,
747
+ textvariable, underline, width
748
+
749
+ WIDGET-SPECIFIC OPTIONS
750
+
751
+ anchor, background, font, foreground, justify, padding,
752
+ relief, text, wraplength
753
+ """
754
+ Widget.__init__(self, master, "ttk::label", kw)
755
+
756
+
757
+ class Labelframe(Widget):
758
+ """Ttk Labelframe widget is a container used to group other widgets
759
+ together. It has an optional label, which may be a plain text string
760
+ or another widget."""
761
+
762
+ def __init__(self, master=None, **kw):
763
+ """Construct a Ttk Labelframe with parent master.
764
+
765
+ STANDARD OPTIONS
766
+
767
+ class, cursor, style, takefocus
768
+
769
+ WIDGET-SPECIFIC OPTIONS
770
+ labelanchor, text, underline, padding, labelwidget, width,
771
+ height
772
+ """
773
+ Widget.__init__(self, master, "ttk::labelframe", kw)
774
+
775
+ LabelFrame = Labelframe # tkinter name compatibility
776
+
777
+
778
+ class Menubutton(Widget):
779
+ """Ttk Menubutton widget displays a textual label and/or image, and
780
+ displays a menu when pressed."""
781
+
782
+ def __init__(self, master=None, **kw):
783
+ """Construct a Ttk Menubutton with parent master.
784
+
785
+ STANDARD OPTIONS
786
+
787
+ class, compound, cursor, image, state, style, takefocus,
788
+ text, textvariable, underline, width
789
+
790
+ WIDGET-SPECIFIC OPTIONS
791
+
792
+ direction, menu
793
+ """
794
+ Widget.__init__(self, master, "ttk::menubutton", kw)
795
+
796
+
797
+ class Notebook(Widget):
798
+ """Ttk Notebook widget manages a collection of windows and displays
799
+ a single one at a time. Each child window is associated with a tab,
800
+ which the user may select to change the currently-displayed window."""
801
+
802
+ def __init__(self, master=None, **kw):
803
+ """Construct a Ttk Notebook with parent master.
804
+
805
+ STANDARD OPTIONS
806
+
807
+ class, cursor, style, takefocus
808
+
809
+ WIDGET-SPECIFIC OPTIONS
810
+
811
+ height, padding, width
812
+
813
+ TAB OPTIONS
814
+
815
+ state, sticky, padding, text, image, compound, underline
816
+
817
+ TAB IDENTIFIERS (tab_id)
818
+
819
+ The tab_id argument found in several methods may take any of
820
+ the following forms:
821
+
822
+ * An integer between zero and the number of tabs
823
+ * The name of a child window
824
+ * A positional specification of the form "@x,y", which
825
+ defines the tab
826
+ * The string "current", which identifies the
827
+ currently-selected tab
828
+ * The string "end", which returns the number of tabs (only
829
+ valid for method index)
830
+ """
831
+ Widget.__init__(self, master, "ttk::notebook", kw)
832
+
833
+
834
+ def add(self, child, **kw):
835
+ """Adds a new tab to the notebook.
836
+
837
+ If window is currently managed by the notebook but hidden, it is
838
+ restored to its previous position."""
839
+ self.tk.call(self._w, "add", child, *(_format_optdict(kw)))
840
+
841
+
842
+ def forget(self, tab_id):
843
+ """Removes the tab specified by tab_id, unmaps and unmanages the
844
+ associated window."""
845
+ self.tk.call(self._w, "forget", tab_id)
846
+
847
+
848
+ def hide(self, tab_id):
849
+ """Hides the tab specified by tab_id.
850
+
851
+ The tab will not be displayed, but the associated window remains
852
+ managed by the notebook and its configuration remembered. Hidden
853
+ tabs may be restored with the add command."""
854
+ self.tk.call(self._w, "hide", tab_id)
855
+
856
+
857
+ def identify(self, x, y):
858
+ """Returns the name of the tab element at position x, y, or the
859
+ empty string if none."""
860
+ return self.tk.call(self._w, "identify", x, y)
861
+
862
+
863
+ def index(self, tab_id):
864
+ """Returns the numeric index of the tab specified by tab_id, or
865
+ the total number of tabs if tab_id is the string "end"."""
866
+ return self.tk.getint(self.tk.call(self._w, "index", tab_id))
867
+
868
+
869
+ def insert(self, pos, child, **kw):
870
+ """Inserts a pane at the specified position.
871
+
872
+ pos is either the string end, an integer index, or the name of
873
+ a managed child. If child is already managed by the notebook,
874
+ moves it to the specified position."""
875
+ self.tk.call(self._w, "insert", pos, child, *(_format_optdict(kw)))
876
+
877
+
878
+ def select(self, tab_id=None):
879
+ """Selects the specified tab.
880
+
881
+ The associated child window will be displayed, and the
882
+ previously-selected window (if different) is unmapped. If tab_id
883
+ is omitted, returns the widget name of the currently selected
884
+ pane."""
885
+ return self.tk.call(self._w, "select", tab_id)
886
+
887
+
888
+ def tab(self, tab_id, option=None, **kw):
889
+ """Query or modify the options of the specific tab_id.
890
+
891
+ If kw is not given, returns a dict of the tab option values. If option
892
+ is specified, returns the value of that option. Otherwise, sets the
893
+ options to the corresponding values."""
894
+ if option is not None:
895
+ kw[option] = None
896
+ return _val_or_dict(self.tk, kw, self._w, "tab", tab_id)
897
+
898
+
899
+ def tabs(self):
900
+ """Returns a list of windows managed by the notebook."""
901
+ return self.tk.splitlist(self.tk.call(self._w, "tabs") or ())
902
+
903
+
904
+ def enable_traversal(self):
905
+ """Enable keyboard traversal for a toplevel window containing
906
+ this notebook.
907
+
908
+ This will extend the bindings for the toplevel window containing
909
+ this notebook as follows:
910
+
911
+ Control-Tab: selects the tab following the currently selected
912
+ one
913
+
914
+ Shift-Control-Tab: selects the tab preceding the currently
915
+ selected one
916
+
917
+ Alt-K: where K is the mnemonic (underlined) character of any
918
+ tab, will select that tab.
919
+
920
+ Multiple notebooks in a single toplevel may be enabled for
921
+ traversal, including nested notebooks. However, notebook traversal
922
+ only works properly if all panes are direct children of the
923
+ notebook."""
924
+ # The only, and good, difference I see is about mnemonics, which works
925
+ # after calling this method. Control-Tab and Shift-Control-Tab always
926
+ # works (here at least).
927
+ self.tk.call("ttk::notebook::enableTraversal", self._w)
928
+
929
+
930
+ class Panedwindow(Widget, tkinter.PanedWindow):
931
+ """Ttk Panedwindow widget displays a number of subwindows, stacked
932
+ either vertically or horizontally."""
933
+
934
+ def __init__(self, master=None, **kw):
935
+ """Construct a Ttk Panedwindow with parent master.
936
+
937
+ STANDARD OPTIONS
938
+
939
+ class, cursor, style, takefocus
940
+
941
+ WIDGET-SPECIFIC OPTIONS
942
+
943
+ orient, width, height
944
+
945
+ PANE OPTIONS
946
+
947
+ weight
948
+ """
949
+ Widget.__init__(self, master, "ttk::panedwindow", kw)
950
+
951
+
952
+ forget = tkinter.PanedWindow.forget # overrides Pack.forget
953
+
954
+
955
+ def insert(self, pos, child, **kw):
956
+ """Inserts a pane at the specified positions.
957
+
958
+ pos is either the string end, and integer index, or the name
959
+ of a child. If child is already managed by the paned window,
960
+ moves it to the specified position."""
961
+ self.tk.call(self._w, "insert", pos, child, *(_format_optdict(kw)))
962
+
963
+
964
+ def pane(self, pane, option=None, **kw):
965
+ """Query or modify the options of the specified pane.
966
+
967
+ pane is either an integer index or the name of a managed subwindow.
968
+ If kw is not given, returns a dict of the pane option values. If
969
+ option is specified then the value for that option is returned.
970
+ Otherwise, sets the options to the corresponding values."""
971
+ if option is not None:
972
+ kw[option] = None
973
+ return _val_or_dict(self.tk, kw, self._w, "pane", pane)
974
+
975
+
976
+ def sashpos(self, index, newpos=None):
977
+ """If newpos is specified, sets the position of sash number index.
978
+
979
+ May adjust the positions of adjacent sashes to ensure that
980
+ positions are monotonically increasing. Sash positions are further
981
+ constrained to be between 0 and the total size of the widget.
982
+
983
+ Returns the new position of sash number index."""
984
+ return self.tk.getint(self.tk.call(self._w, "sashpos", index, newpos))
985
+
986
+ PanedWindow = Panedwindow # tkinter name compatibility
987
+
988
+
989
+ class Progressbar(Widget):
990
+ """Ttk Progressbar widget shows the status of a long-running
991
+ operation. They can operate in two modes: determinate mode shows the
992
+ amount completed relative to the total amount of work to be done, and
993
+ indeterminate mode provides an animated display to let the user know
994
+ that something is happening."""
995
+
996
+ def __init__(self, master=None, **kw):
997
+ """Construct a Ttk Progressbar with parent master.
998
+
999
+ STANDARD OPTIONS
1000
+
1001
+ class, cursor, style, takefocus
1002
+
1003
+ WIDGET-SPECIFIC OPTIONS
1004
+
1005
+ orient, length, mode, maximum, value, variable, phase
1006
+ """
1007
+ Widget.__init__(self, master, "ttk::progressbar", kw)
1008
+
1009
+
1010
+ def start(self, interval=None):
1011
+ """Begin autoincrement mode: schedules a recurring timer event
1012
+ that calls method step every interval milliseconds.
1013
+
1014
+ interval defaults to 50 milliseconds (20 steps/second) if omitted."""
1015
+ self.tk.call(self._w, "start", interval)
1016
+
1017
+
1018
+ def step(self, amount=None):
1019
+ """Increments the value option by amount.
1020
+
1021
+ amount defaults to 1.0 if omitted."""
1022
+ self.tk.call(self._w, "step", amount)
1023
+
1024
+
1025
+ def stop(self):
1026
+ """Stop autoincrement mode: cancels any recurring timer event
1027
+ initiated by start."""
1028
+ self.tk.call(self._w, "stop")
1029
+
1030
+
1031
+ class Radiobutton(Widget):
1032
+ """Ttk Radiobutton widgets are used in groups to show or change a
1033
+ set of mutually-exclusive options."""
1034
+
1035
+ def __init__(self, master=None, **kw):
1036
+ """Construct a Ttk Radiobutton with parent master.
1037
+
1038
+ STANDARD OPTIONS
1039
+
1040
+ class, compound, cursor, image, state, style, takefocus,
1041
+ text, textvariable, underline, width
1042
+
1043
+ WIDGET-SPECIFIC OPTIONS
1044
+
1045
+ command, value, variable
1046
+ """
1047
+ Widget.__init__(self, master, "ttk::radiobutton", kw)
1048
+
1049
+
1050
+ def invoke(self):
1051
+ """Sets the option variable to the option value, selects the
1052
+ widget, and invokes the associated command.
1053
+
1054
+ Returns the result of the command, or an empty string if
1055
+ no command is specified."""
1056
+ return self.tk.call(self._w, "invoke")
1057
+
1058
+
1059
+ class Scale(Widget, tkinter.Scale):
1060
+ """Ttk Scale widget is typically used to control the numeric value of
1061
+ a linked variable that varies uniformly over some range."""
1062
+
1063
+ def __init__(self, master=None, **kw):
1064
+ """Construct a Ttk Scale with parent master.
1065
+
1066
+ STANDARD OPTIONS
1067
+
1068
+ class, cursor, style, takefocus
1069
+
1070
+ WIDGET-SPECIFIC OPTIONS
1071
+
1072
+ command, from, length, orient, to, value, variable
1073
+ """
1074
+ Widget.__init__(self, master, "ttk::scale", kw)
1075
+
1076
+
1077
+ def configure(self, cnf=None, **kw):
1078
+ """Modify or query scale options.
1079
+
1080
+ Setting a value for any of the "from", "from_" or "to" options
1081
+ generates a <<RangeChanged>> event."""
1082
+ retval = Widget.configure(self, cnf, **kw)
1083
+ if not isinstance(cnf, (type(None), str)):
1084
+ kw.update(cnf)
1085
+ if any(['from' in kw, 'from_' in kw, 'to' in kw]):
1086
+ self.event_generate('<<RangeChanged>>')
1087
+ return retval
1088
+
1089
+
1090
+ def get(self, x=None, y=None):
1091
+ """Get the current value of the value option, or the value
1092
+ corresponding to the coordinates x, y if they are specified.
1093
+
1094
+ x and y are pixel coordinates relative to the scale widget
1095
+ origin."""
1096
+ return self.tk.call(self._w, 'get', x, y)
1097
+
1098
+
1099
+ class Scrollbar(Widget, tkinter.Scrollbar):
1100
+ """Ttk Scrollbar controls the viewport of a scrollable widget."""
1101
+
1102
+ def __init__(self, master=None, **kw):
1103
+ """Construct a Ttk Scrollbar with parent master.
1104
+
1105
+ STANDARD OPTIONS
1106
+
1107
+ class, cursor, style, takefocus
1108
+
1109
+ WIDGET-SPECIFIC OPTIONS
1110
+
1111
+ command, orient
1112
+ """
1113
+ Widget.__init__(self, master, "ttk::scrollbar", kw)
1114
+
1115
+
1116
+ class Separator(Widget):
1117
+ """Ttk Separator widget displays a horizontal or vertical separator
1118
+ bar."""
1119
+
1120
+ def __init__(self, master=None, **kw):
1121
+ """Construct a Ttk Separator with parent master.
1122
+
1123
+ STANDARD OPTIONS
1124
+
1125
+ class, cursor, style, takefocus
1126
+
1127
+ WIDGET-SPECIFIC OPTIONS
1128
+
1129
+ orient
1130
+ """
1131
+ Widget.__init__(self, master, "ttk::separator", kw)
1132
+
1133
+
1134
+ class Sizegrip(Widget):
1135
+ """Ttk Sizegrip allows the user to resize the containing toplevel
1136
+ window by pressing and dragging the grip."""
1137
+
1138
+ def __init__(self, master=None, **kw):
1139
+ """Construct a Ttk Sizegrip with parent master.
1140
+
1141
+ STANDARD OPTIONS
1142
+
1143
+ class, cursor, state, style, takefocus
1144
+ """
1145
+ Widget.__init__(self, master, "ttk::sizegrip", kw)
1146
+
1147
+
1148
+ class Spinbox(Entry):
1149
+ """Ttk Spinbox is an Entry with increment and decrement arrows
1150
+
1151
+ It is commonly used for number entry or to select from a list of
1152
+ string values.
1153
+ """
1154
+
1155
+ def __init__(self, master=None, **kw):
1156
+ """Construct a Ttk Spinbox widget with the parent master.
1157
+
1158
+ STANDARD OPTIONS
1159
+
1160
+ class, cursor, style, takefocus, validate,
1161
+ validatecommand, xscrollcommand, invalidcommand
1162
+
1163
+ WIDGET-SPECIFIC OPTIONS
1164
+
1165
+ to, from_, increment, values, wrap, format, command
1166
+ """
1167
+ Entry.__init__(self, master, "ttk::spinbox", **kw)
1168
+
1169
+
1170
+ def set(self, value):
1171
+ """Sets the value of the Spinbox to value."""
1172
+ self.tk.call(self._w, "set", value)
1173
+
1174
+
1175
+ class Treeview(Widget, tkinter.XView, tkinter.YView):
1176
+ """Ttk Treeview widget displays a hierarchical collection of items.
1177
+
1178
+ Each item has a textual label, an optional image, and an optional list
1179
+ of data values. The data values are displayed in successive columns
1180
+ after the tree label."""
1181
+
1182
+ def __init__(self, master=None, **kw):
1183
+ """Construct a Ttk Treeview with parent master.
1184
+
1185
+ STANDARD OPTIONS
1186
+
1187
+ class, cursor, style, takefocus, xscrollcommand,
1188
+ yscrollcommand
1189
+
1190
+ WIDGET-SPECIFIC OPTIONS
1191
+
1192
+ columns, displaycolumns, height, padding, selectmode, show
1193
+
1194
+ ITEM OPTIONS
1195
+
1196
+ text, image, values, open, tags
1197
+
1198
+ TAG OPTIONS
1199
+
1200
+ foreground, background, font, image
1201
+ """
1202
+ Widget.__init__(self, master, "ttk::treeview", kw)
1203
+
1204
+
1205
+ def bbox(self, item, column=None):
1206
+ """Returns the bounding box (relative to the treeview widget's
1207
+ window) of the specified item in the form x y width height.
1208
+
1209
+ If column is specified, returns the bounding box of that cell.
1210
+ If the item is not visible (i.e., if it is a descendant of a
1211
+ closed item or is scrolled offscreen), returns an empty string."""
1212
+ return self._getints(self.tk.call(self._w, "bbox", item, column)) or ''
1213
+
1214
+
1215
+ def get_children(self, item=None):
1216
+ """Returns a tuple of children belonging to item.
1217
+
1218
+ If item is not specified, returns root children."""
1219
+ return self.tk.splitlist(
1220
+ self.tk.call(self._w, "children", item or '') or ())
1221
+
1222
+
1223
+ def set_children(self, item, *newchildren):
1224
+ """Replaces item's child with newchildren.
1225
+
1226
+ Children present in item that are not present in newchildren
1227
+ are detached from tree. No items in newchildren may be an
1228
+ ancestor of item."""
1229
+ self.tk.call(self._w, "children", item, newchildren)
1230
+
1231
+
1232
+ def column(self, column, option=None, **kw):
1233
+ """Query or modify the options for the specified column.
1234
+
1235
+ If kw is not given, returns a dict of the column option values. If
1236
+ option is specified then the value for that option is returned.
1237
+ Otherwise, sets the options to the corresponding values."""
1238
+ if option is not None:
1239
+ kw[option] = None
1240
+ return _val_or_dict(self.tk, kw, self._w, "column", column)
1241
+
1242
+
1243
+ def delete(self, *items):
1244
+ """Delete all specified items and all their descendants. The root
1245
+ item may not be deleted."""
1246
+ self.tk.call(self._w, "delete", items)
1247
+
1248
+
1249
+ def detach(self, *items):
1250
+ """Unlinks all of the specified items from the tree.
1251
+
1252
+ The items and all of their descendants are still present, and may
1253
+ be reinserted at another point in the tree, but will not be
1254
+ displayed. The root item may not be detached."""
1255
+ self.tk.call(self._w, "detach", items)
1256
+
1257
+
1258
+ def exists(self, item):
1259
+ """Returns True if the specified item is present in the tree,
1260
+ False otherwise."""
1261
+ return self.tk.getboolean(self.tk.call(self._w, "exists", item))
1262
+
1263
+
1264
+ def focus(self, item=None):
1265
+ """If item is specified, sets the focus item to item. Otherwise,
1266
+ returns the current focus item, or '' if there is none."""
1267
+ return self.tk.call(self._w, "focus", item)
1268
+
1269
+
1270
+ def heading(self, column, option=None, **kw):
1271
+ """Query or modify the heading options for the specified column.
1272
+
1273
+ If kw is not given, returns a dict of the heading option values. If
1274
+ option is specified then the value for that option is returned.
1275
+ Otherwise, sets the options to the corresponding values.
1276
+
1277
+ Valid options/values are:
1278
+ text: text
1279
+ The text to display in the column heading
1280
+ image: image_name
1281
+ Specifies an image to display to the right of the column
1282
+ heading
1283
+ anchor: anchor
1284
+ Specifies how the heading text should be aligned. One of
1285
+ the standard Tk anchor values
1286
+ command: callback
1287
+ A callback to be invoked when the heading label is
1288
+ pressed.
1289
+
1290
+ To configure the tree column heading, call this with column = "#0" """
1291
+ cmd = kw.get('command')
1292
+ if cmd and not isinstance(cmd, str):
1293
+ # callback not registered yet, do it now
1294
+ kw['command'] = self.master.register(cmd, self._substitute)
1295
+
1296
+ if option is not None:
1297
+ kw[option] = None
1298
+
1299
+ return _val_or_dict(self.tk, kw, self._w, 'heading', column)
1300
+
1301
+
1302
+ def identify(self, component, x, y):
1303
+ """Returns a description of the specified component under the
1304
+ point given by x and y, or the empty string if no such component
1305
+ is present at that position."""
1306
+ return self.tk.call(self._w, "identify", component, x, y)
1307
+
1308
+
1309
+ def identify_row(self, y):
1310
+ """Returns the item ID of the item at position y."""
1311
+ return self.identify("row", 0, y)
1312
+
1313
+
1314
+ def identify_column(self, x):
1315
+ """Returns the data column identifier of the cell at position x.
1316
+
1317
+ The tree column has ID #0."""
1318
+ return self.identify("column", x, 0)
1319
+
1320
+
1321
+ def identify_region(self, x, y):
1322
+ """Returns one of:
1323
+
1324
+ heading: Tree heading area.
1325
+ separator: Space between two columns headings;
1326
+ tree: The tree area.
1327
+ cell: A data cell.
1328
+
1329
+ * Availability: Tk 8.6"""
1330
+ return self.identify("region", x, y)
1331
+
1332
+
1333
+ def identify_element(self, x, y):
1334
+ """Returns the element at position x, y.
1335
+
1336
+ * Availability: Tk 8.6"""
1337
+ return self.identify("element", x, y)
1338
+
1339
+
1340
+ def index(self, item):
1341
+ """Returns the integer index of item within its parent's list
1342
+ of children."""
1343
+ return self.tk.getint(self.tk.call(self._w, "index", item))
1344
+
1345
+
1346
+ def insert(self, parent, index, iid=None, **kw):
1347
+ """Creates a new item and return the item identifier of the newly
1348
+ created item.
1349
+
1350
+ parent is the item ID of the parent item, or the empty string
1351
+ to create a new top-level item. index is an integer, or the value
1352
+ end, specifying where in the list of parent's children to insert
1353
+ the new item. If index is less than or equal to zero, the new node
1354
+ is inserted at the beginning, if index is greater than or equal to
1355
+ the current number of children, it is inserted at the end. If iid
1356
+ is specified, it is used as the item identifier, iid must not
1357
+ already exist in the tree. Otherwise, a new unique identifier
1358
+ is generated."""
1359
+ opts = _format_optdict(kw)
1360
+ if iid is not None:
1361
+ res = self.tk.call(self._w, "insert", parent, index,
1362
+ "-id", iid, *opts)
1363
+ else:
1364
+ res = self.tk.call(self._w, "insert", parent, index, *opts)
1365
+
1366
+ return res
1367
+
1368
+
1369
+ def item(self, item, option=None, **kw):
1370
+ """Query or modify the options for the specified item.
1371
+
1372
+ If no options are given, a dict with options/values for the item
1373
+ is returned. If option is specified then the value for that option
1374
+ is returned. Otherwise, sets the options to the corresponding
1375
+ values as given by kw."""
1376
+ if option is not None:
1377
+ kw[option] = None
1378
+ return _val_or_dict(self.tk, kw, self._w, "item", item)
1379
+
1380
+
1381
+ def move(self, item, parent, index):
1382
+ """Moves item to position index in parent's list of children.
1383
+
1384
+ It is illegal to move an item under one of its descendants. If
1385
+ index is less than or equal to zero, item is moved to the
1386
+ beginning, if greater than or equal to the number of children,
1387
+ it is moved to the end. If item was detached it is reattached."""
1388
+ self.tk.call(self._w, "move", item, parent, index)
1389
+
1390
+ reattach = move # A sensible method name for reattaching detached items
1391
+
1392
+
1393
+ def next(self, item):
1394
+ """Returns the identifier of item's next sibling, or '' if item
1395
+ is the last child of its parent."""
1396
+ return self.tk.call(self._w, "next", item)
1397
+
1398
+
1399
+ def parent(self, item):
1400
+ """Returns the ID of the parent of item, or '' if item is at the
1401
+ top level of the hierarchy."""
1402
+ return self.tk.call(self._w, "parent", item)
1403
+
1404
+
1405
+ def prev(self, item):
1406
+ """Returns the identifier of item's previous sibling, or '' if
1407
+ item is the first child of its parent."""
1408
+ return self.tk.call(self._w, "prev", item)
1409
+
1410
+
1411
+ def see(self, item):
1412
+ """Ensure that item is visible.
1413
+
1414
+ Sets all of item's ancestors open option to True, and scrolls
1415
+ the widget if necessary so that item is within the visible
1416
+ portion of the tree."""
1417
+ self.tk.call(self._w, "see", item)
1418
+
1419
+
1420
+ def selection(self):
1421
+ """Returns the tuple of selected items."""
1422
+ return self.tk.splitlist(self.tk.call(self._w, "selection"))
1423
+
1424
+
1425
+ def _selection(self, selop, items):
1426
+ if len(items) == 1 and isinstance(items[0], (tuple, list)):
1427
+ items = items[0]
1428
+
1429
+ self.tk.call(self._w, "selection", selop, items)
1430
+
1431
+
1432
+ def selection_set(self, *items):
1433
+ """The specified items becomes the new selection."""
1434
+ self._selection("set", items)
1435
+
1436
+
1437
+ def selection_add(self, *items):
1438
+ """Add all of the specified items to the selection."""
1439
+ self._selection("add", items)
1440
+
1441
+
1442
+ def selection_remove(self, *items):
1443
+ """Remove all of the specified items from the selection."""
1444
+ self._selection("remove", items)
1445
+
1446
+
1447
+ def selection_toggle(self, *items):
1448
+ """Toggle the selection state of each specified item."""
1449
+ self._selection("toggle", items)
1450
+
1451
+
1452
+ def set(self, item, column=None, value=None):
1453
+ """Query or set the value of given item.
1454
+
1455
+ With one argument, return a dictionary of column/value pairs
1456
+ for the specified item. With two arguments, return the current
1457
+ value of the specified column. With three arguments, set the
1458
+ value of given column in given item to the specified value."""
1459
+ res = self.tk.call(self._w, "set", item, column, value)
1460
+ if column is None and value is None:
1461
+ return _splitdict(self.tk, res,
1462
+ cut_minus=False, conv=_tclobj_to_py)
1463
+ else:
1464
+ return res
1465
+
1466
+
1467
+ def tag_bind(self, tagname, sequence=None, callback=None):
1468
+ """Bind a callback for the given event sequence to the tag tagname.
1469
+ When an event is delivered to an item, the callbacks for each
1470
+ of the item's tags option are called."""
1471
+ self._bind((self._w, "tag", "bind", tagname), sequence, callback, add=0)
1472
+
1473
+
1474
+ def tag_configure(self, tagname, option=None, **kw):
1475
+ """Query or modify the options for the specified tagname.
1476
+
1477
+ If kw is not given, returns a dict of the option settings for tagname.
1478
+ If option is specified, returns the value for that option for the
1479
+ specified tagname. Otherwise, sets the options to the corresponding
1480
+ values for the given tagname."""
1481
+ if option is not None:
1482
+ kw[option] = None
1483
+ return _val_or_dict(self.tk, kw, self._w, "tag", "configure",
1484
+ tagname)
1485
+
1486
+
1487
+ def tag_has(self, tagname, item=None):
1488
+ """If item is specified, returns 1 or 0 depending on whether the
1489
+ specified item has the given tagname. Otherwise, returns a list of
1490
+ all items which have the specified tag.
1491
+
1492
+ * Availability: Tk 8.6"""
1493
+ if item is None:
1494
+ return self.tk.splitlist(
1495
+ self.tk.call(self._w, "tag", "has", tagname))
1496
+ else:
1497
+ return self.tk.getboolean(
1498
+ self.tk.call(self._w, "tag", "has", tagname, item))
1499
+
1500
+
1501
+ # Extensions
1502
+
1503
+ class LabeledScale(Frame):
1504
+ """A Ttk Scale widget with a Ttk Label widget indicating its
1505
+ current value.
1506
+
1507
+ The Ttk Scale can be accessed through instance.scale, and Ttk Label
1508
+ can be accessed through instance.label"""
1509
+
1510
+ def __init__(self, master=None, variable=None, from_=0, to=10, **kw):
1511
+ """Construct a horizontal LabeledScale with parent master, a
1512
+ variable to be associated with the Ttk Scale widget and its range.
1513
+ If variable is not specified, a tkinter.IntVar is created.
1514
+
1515
+ WIDGET-SPECIFIC OPTIONS
1516
+
1517
+ compound: 'top' or 'bottom'
1518
+ Specifies how to display the label relative to the scale.
1519
+ Defaults to 'top'.
1520
+ """
1521
+ self._label_top = kw.pop('compound', 'top') == 'top'
1522
+
1523
+ Frame.__init__(self, master, **kw)
1524
+ self._variable = variable or tkinter.IntVar(master)
1525
+ self._variable.set(from_)
1526
+ self._last_valid = from_
1527
+
1528
+ self.label = Label(self)
1529
+ self.scale = Scale(self, variable=self._variable, from_=from_, to=to)
1530
+ self.scale.bind('<<RangeChanged>>', self._adjust)
1531
+
1532
+ # position scale and label according to the compound option
1533
+ scale_side = 'bottom' if self._label_top else 'top'
1534
+ label_side = 'top' if scale_side == 'bottom' else 'bottom'
1535
+ self.scale.pack(side=scale_side, fill='x')
1536
+ # Dummy required to make frame correct height
1537
+ dummy = Label(self)
1538
+ dummy.pack(side=label_side)
1539
+ dummy.lower()
1540
+ self.label.place(anchor='n' if label_side == 'top' else 's')
1541
+
1542
+ # update the label as scale or variable changes
1543
+ self.__tracecb = self._variable.trace_variable('w', self._adjust)
1544
+ self.bind('<Configure>', self._adjust)
1545
+ self.bind('<Map>', self._adjust)
1546
+
1547
+
1548
+ def destroy(self):
1549
+ """Destroy this widget and possibly its associated variable."""
1550
+ try:
1551
+ self._variable.trace_vdelete('w', self.__tracecb)
1552
+ except AttributeError:
1553
+ pass
1554
+ else:
1555
+ del self._variable
1556
+ super().destroy()
1557
+ self.label = None
1558
+ self.scale = None
1559
+
1560
+
1561
+ def _adjust(self, *args):
1562
+ """Adjust the label position according to the scale."""
1563
+ def adjust_label():
1564
+ self.update_idletasks() # "force" scale redraw
1565
+
1566
+ x, y = self.scale.coords()
1567
+ if self._label_top:
1568
+ y = self.scale.winfo_y() - self.label.winfo_reqheight()
1569
+ else:
1570
+ y = self.scale.winfo_reqheight() + self.label.winfo_reqheight()
1571
+
1572
+ self.label.place_configure(x=x, y=y)
1573
+
1574
+ from_ = _to_number(self.scale['from'])
1575
+ to = _to_number(self.scale['to'])
1576
+ if to < from_:
1577
+ from_, to = to, from_
1578
+ newval = self._variable.get()
1579
+ if not from_ <= newval <= to:
1580
+ # value outside range, set value back to the last valid one
1581
+ self.value = self._last_valid
1582
+ return
1583
+
1584
+ self._last_valid = newval
1585
+ self.label['text'] = newval
1586
+ self.after_idle(adjust_label)
1587
+
1588
+ @property
1589
+ def value(self):
1590
+ """Return current scale value."""
1591
+ return self._variable.get()
1592
+
1593
+ @value.setter
1594
+ def value(self, val):
1595
+ """Set new scale value."""
1596
+ self._variable.set(val)
1597
+
1598
+
1599
+ class OptionMenu(Menubutton):
1600
+ """Themed OptionMenu, based after tkinter's OptionMenu, which allows
1601
+ the user to select a value from a menu."""
1602
+
1603
+ def __init__(self, master, variable, default=None, *values, **kwargs):
1604
+ """Construct a themed OptionMenu widget with master as the parent,
1605
+ the resource textvariable set to variable, the initially selected
1606
+ value specified by the default parameter, the menu values given by
1607
+ *values and additional keywords.
1608
+
1609
+ WIDGET-SPECIFIC OPTIONS
1610
+
1611
+ style: stylename
1612
+ Menubutton style.
1613
+ direction: 'above', 'below', 'left', 'right', or 'flush'
1614
+ Menubutton direction.
1615
+ command: callback
1616
+ A callback that will be invoked after selecting an item.
1617
+ """
1618
+ kw = {'textvariable': variable, 'style': kwargs.pop('style', None),
1619
+ 'direction': kwargs.pop('direction', None)}
1620
+ Menubutton.__init__(self, master, **kw)
1621
+ self['menu'] = tkinter.Menu(self, tearoff=False)
1622
+
1623
+ self._variable = variable
1624
+ self._callback = kwargs.pop('command', None)
1625
+ if kwargs:
1626
+ raise tkinter.TclError('unknown option -%s' % (
1627
+ next(iter(kwargs.keys()))))
1628
+
1629
+ self.set_menu(default, *values)
1630
+
1631
+
1632
+ def __getitem__(self, item):
1633
+ if item == 'menu':
1634
+ return self.nametowidget(Menubutton.__getitem__(self, item))
1635
+
1636
+ return Menubutton.__getitem__(self, item)
1637
+
1638
+
1639
+ def set_menu(self, default=None, *values):
1640
+ """Build a new menu of radiobuttons with *values and optionally
1641
+ a default value."""
1642
+ menu = self['menu']
1643
+ menu.delete(0, 'end')
1644
+ for val in values:
1645
+ menu.add_radiobutton(label=val,
1646
+ command=(
1647
+ None if self._callback is None
1648
+ else lambda val=val: self._callback(val)
1649
+ ),
1650
+ variable=self._variable)
1651
+
1652
+ if default:
1653
+ self._variable.set(default)
1654
+
1655
+
1656
+ def destroy(self):
1657
+ """Destroy this widget and its associated variable."""
1658
+ try:
1659
+ del self._variable
1660
+ except AttributeError:
1661
+ pass
1662
+ super().destroy()
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_int_mm_cpu_dispatch.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API at::Tensor _int_mm(const at::Tensor & self, const at::Tensor & mat2);
21
+ TORCH_API at::Tensor & _int_mm_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & mat2);
22
+ TORCH_API at::Tensor & _int_mm_outf(const at::Tensor & self, const at::Tensor & mat2, at::Tensor & out);
23
+
24
+ } // namespace cpu
25
+ } // namespace at