-
Notifications
You must be signed in to change notification settings - Fork 0
/
anchor.py
1424 lines (1188 loc) · 46.5 KB
/
anchor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding: utf-8
"""
Pythonista UI layouts using relative constraints instead of coordinate
placement
"""
__version__ = '1.0'
import objc_util
import ui
import inspect, gc, types, sys, random, math
import keyword
from types import SimpleNamespace
from copy import copy
from collections import defaultdict
from functools import partial
NSLayoutConstraint = objc_util.ObjCClass('NSLayoutConstraint')
UILayoutGuide = objc_util.ObjCClass('UILayoutGuide')
UIDevice = objc_util.ObjCClass('UIDevice')
UIViewPropertyAnimator = objc_util.ObjCClass('UIViewPropertyAnimator')
def prop(func):
"""Combined getter/setter property"""
return property(func, func)
class At:
standard = 8
def __init__(self, view, priority=1000):
"""
Initialize a constraint manager for a view with the given priority.
"""
self.view = view
self.attribute = 0
self.attribute_name = 'na'
self.attribute_type = 'NNN'
self.operator = 0
self.other_view = None
self.other_attribute = 0
self.other_attribute_name = 'na'
self.other_attribute_type = 'NNN'
self.multiplier = 1
self.description = None
self._constant = 0
self._priority = priority
@property
def objc_constraint(self):
if self.description is None:
return None
return find_constraint(self.view, self.description)
@property
def constant(self):
"""
Constant part of the constraint equation:
`target.attribute == source.attribute * multiplier + constant`.
This is the only part of the equation that can be changed
after the constraint has been created.
"""
return self._constant
@constant.setter
def constant(self, value):
self._constant = value
def __str__(self):
operators = ['<=', '==', '>=']
view = self.view.name if self.view.name else type(self.view).__name__
operator = operators[self.operator + 1]
other_view = self.other_view.name if \
self.other_view and self.other_view.name \
else (type(
self.other_view).__name__ if self.other_view is not None else '')
other_attribute_str = '' \
if self.other_attribute == 0 \
else f'.{self.other_attribute_name} '
multiplier_str = f'* {self.multiplier} ' \
if self.multiplier != 1 else ''
constant_str = ''
if self.constant < 0:
constant_str = f'- {abs(self.constant)}'
elif self.constant > 0:
constant_str = f'+ {self.constant}'
return (f'{view}.{self.attribute_name} {operator} '
f'{other_view}{other_attribute_str}'
f'{multiplier_str}{constant_str}')
# CONSTRAINT OPERATORS
def __mul__(self, other):
self.multiplier *= other
return self
def __truediv__(self, other):
self.multiplier *= 1 / other
return self
def __add__(self, other):
self._constant += other
return self
def __sub__(self, other):
self._constant -= other
return self
def __le__(self, other):
c = copy(self)
c.operator = -1
c._create_constraint(other)
return c
def __eq__(self, other):
# c = copy(self)
self.operator = 0
self._create_constraint(other)
return self
def __ge__(self, other):
c = copy(self)
c.operator = 1
c._create_constraint(other)
return c
def _get(prop, attribute, name, type_str):
"""Property creator for constraint attributes."""
p = property(
lambda self:
partial(prop, self, attribute, name, type_str)(),
lambda self, value:
partial(prop, self, attribute, name, type_str, value)()
)
return p
def _prop(self, attribute, name, type_str, *values):
"""
Combined getter/setter for constraint attributes.
Effectively makes using assignment ('=') and equality comparison
('==') equal.
"""
if type(self.view) is Guide:
if attribute > 10:
raise AttributeError(
f"Cannot use attribute '{name}' with a layout guide")
c = copy(self)
c.attribute = attribute
c.attribute_name = name
c.attribute_type = type_str
return (c == values[0]) if len(values) else c
# Attribute properties - numbers are
# Apple NSLayoutConstraint constants
# Magical code contains three letters:
# 1. Position/Size
# 2. Horizontal/Vertical/NA
# 3. Absolute/Relative/NA
# These are used to check constraint
# compatibility
left = _get(_prop, 1, 'left', 'PHA')
right = _get(_prop, 2, 'right', 'PHA')
top = _get(_prop, 3, 'top', 'PVN')
bottom = _get(_prop, 4, 'bottom', 'PVN')
leading = _get(_prop, 5, 'leading', 'PHR')
trailing = _get(_prop, 6, 'trailing', 'PHR')
width = _get(_prop, 7, 'width', 'SNN')
height = _get(_prop, 8, 'height', 'SNN')
center_x = _get(_prop, 9, 'center_x', 'PHN')
center_y = _get(_prop, 10, 'center_y', 'PVN')
last_baseline = _get(_prop, 11, 'last_baseline', 'PVN')
first_baseline = _get(_prop, 12, 'first_baseline', 'PVN')
left_margin = _get(_prop, 13, 'left_margin', 'PHA')
right_margin = _get(_prop, 14, 'right_margin', 'PHA')
top_margin = _get(_prop, 15, 'top_margin', 'PVN')
bottom_margin = _get(_prop, 16, 'bottom_margin', 'PVN')
leading_margin = _get(_prop, 17, 'leading_margin', 'PHR')
trailing_margin = _get(_prop, 18, 'trailing_margin', 'PHR')
# Padding attributes have different
# property setup because of the additional
# constant needed
@prop
def left_padding(self, *values):
c = copy(self)
c = c.left
c._constant -= c.margin_inset().leading
return (c == values[0]) if len(values) else c
@prop
def right_padding(self, *values):
c = copy(self)
c = c.right
c._constant += c.margin_inset().trailing
return (c == values[0]) if len(values) else c
@prop
def top_padding(self, *values):
c = copy(self)
c = c.top
c._constant -= c.margin_inset().top
return (c == values[0]) if len(values) else c
@prop
def bottom_padding(self, *values):
c = copy(self)
c = c.bottom
c._constant += c.margin_inset().bottom
return (c == values[0]) if len(values) else c
@prop
def leading_padding(self, *values):
c = copy(self)
c = c.leading
c._constant -= c.margin_inset().leading
return (c == values[0]) if len(values) else c
@prop
def trailing_padding(self, *values):
c = copy(self)
c = c.trailing
c._constant += c.margin_inset().trailing
return (c == values[0]) if len(values) else c
def margin_inset(self):
return SimpleNamespace(
bottom=At.standard,
leading=At.standard,
trailing=At.standard,
top=At.standard)
@property
def safe_area(self):
return At(view=SimpleNamespace(
objc_instance=self.view.objc_instance.safeAreaLayoutGuide(),
name='Safe area',
superview=self.view))
@property
def margins(self):
return At(view=SimpleNamespace(
objc_instance=self.view.objc_instance.layoutMarginsGuide(),
name='Margins',
superview=self.view))
@objc_util.on_main_thread
def _create_constraint(self, other):
if isinstance(other, At):
self.other_view = other.view
self.other_attribute = other.attribute
self.other_attribute_name = other.attribute_name
self.other_attribute_type = other.attribute_type
self.constant = other.constant
self.multiplier = other.multiplier
elif isinstance(other, (int, float)):
self.constant = other
else:
raise TypeError(
f'Cannot use object of type {str(type(other))} in a constraint'
f' comparison: ' + str(other))
for i in range(3):
t = self.attribute_type
ot = self.other_attribute_type
if t[i] == 'N' or ot[i] == 'N':
continue
if t[i] != ot[i]:
raise TypeError(
f'Incompatible attributes in constraint: {str(self)}')
try:
view_first_seen = \
self.view.objc_instance.translatesAutoresizingMaskIntoConstraints()
except AttributeError:
view_first_seen = False
if view_first_seen:
self.view.objc_instance.setTranslatesAutoresizingMaskIntoConstraints_(
False)
# C._set_defaults(self.view)
# if type(self.view) in C.autofit_types:
# self.size_to_fit()
objc_constraint = NSLayoutConstraint. \
PG_constraintWithItem_attribute_relatedBy_toItem_attribute_multiplier_constant_priority_(
self.view.objc_instance,
self.attribute,
self.operator,
None if not self.other_view else self.other_view.objc_instance,
self.other_attribute,
self.multiplier,
self.constant,
self._priority
)
objc_constraint.setActive_(True)
self.description = str(objc_constraint._deallocSafeDescription())
def priority(self, *value):
"""
Without value, returns the current priority of the constraint. With
value, sets the constraint to a priority expressed as an integer
between 0 and 1000, where 1000 means a required constraint,
and values 0-999 optional constraints.
For example:
view.at.priority(500).width == 300
Note: You cannot change priority between required and optional after
present(), but you can change between different optional priority
levels.
"""
if len(value) == 0:
return objc_constraint.priority() if self.objc_constraint else None
value = value[0]
if type(value) is not int or value < 0 or value > 1000:
raise ValueError(
'priority must be an integer in the range [0, 1000]')
if self.objc_constraint:
previous_value = self.objc_constraint.priority()
if self.view.on_screen and \
((value == 1000 and \
previous_value != 1000) or \
(value != 1000 and \
previous_value == 1000)):
raise ValueError(
'Cannot change priority value between required (1000) '
'and lower value')
self.objc_constraint.setPriority_(value)
return self
@property
def is_ambiguous(self):
'''Returns true if the constraints for this view are ambiguous
(position and size are not defined in a way that can be resolved by the
system.)'''
return self.view.objc_instance.hasAmbiguousLayout()
def exercise_ambiguity(self):
self.view.objc_instance.exerciseAmbiguityInLayout()
class Dock:
"""
Dock methods are focused on connecting different sides of the view to
its superview.
"""
def __init__(self, view):
self.view = view
@property
def superview(self):
if self.view:
return self.view.superview
@property
def subviews(self):
if self.view:
return self.view.subviews
extra_width_types = [ui.Label, ui.Button]
@objc_util.on_main_thread
def fit(self):
"Set size constraints according to the view‘s preferred size."
view = self.view
size = view.objc_instance.sizeThatFits_((0, 0))
extra_width = 0
if type(view) in self.extra_width_types:
margins = self.view.at.margin_inset()
extra_width = margins.leading + margins.trailing
self.view.at.width == size.width + extra_width
self.view.at.height == size.height
return view
TIGHT = 0
MARGIN = 1
SAFE = 2
default_fit = MARGIN
def _fit(self, fit):
s = self.superview
enable(s)
if fit == Dock.TIGHT:
return s.at
elif fit == Dock.MARGIN:
return s.at.margins
elif fit == Dock.SAFE:
return s.at.safe_area
def all(self, constant=0, fit=default_fit):
'Dock the view on all sides.'
view = self.view
sf = self._fit(fit)
view.at.top == self._fit(fit).top + constant
view.at.bottom == self._fit(fit).bottom - constant
view.at.leading == self._fit(fit).leading + constant
view.at.trailing == self._fit(fit).trailing - constant
def center(self, share=None):
view = self.view
s = enable(self.superview)
view.at.center_x == s.at.center_x
view.at.center_y == s.at.center_y
self._set_size(share)
def sides(self, share=None, constant=0, fit=default_fit):
view = self.view
view.at.leading == self._fit(fit).leading + constant
view.at.trailing == self._fit(fit).trailing - constant
self._set_size(share)
horizontal = sides
def vertical(self, constant=0, fit=default_fit):
at = self.view.at
at.top == self._fit(fit).top + constant
at.bottom == self._fit(fit).bottom - constant
def between(self,
top=None, bottom=None,
leading=None, trailing=None,
fit=default_fit, constant=0):
at = self.view.at
if top:
enable(top)
at.top == (
top.at.bottom if fit == Dock.TIGHT
else top.at.bottom_padding
+ constant)
else:
at.top == self._fit(fit).top + constant
if bottom:
enable(bottom)
at.bottom == (
bottom.at.top if fit == Dock.TIGHT
else bottom.at.top_padding
- constant)
else:
at.bottom == self._fit(fit).bottom - constant
if leading:
enable(leading)
at.leading == (
leading.at.trailing if fit == Dock.TIGHT
else leading.at.trailing_padding
+ constant)
else:
at.leading == self._fit(fit).leading + constant
if trailing:
enable(trailing)
at.trailing == (
trailing.at.leading if fit == Dock.TIGHT
else trailing.at.leading_padding
- constant)
else:
at.trailing == self._fit(fit).trailing - constant
def horizontal_between(self, top_view, bottom_view, constant=0,
fit=default_fit):
at = self.view.at
enable(top_view, bottom_view)
self.horizontal(constant=constant, fit=fit)
if fit == Dock.TIGHT:
at.top == top_view.at.bottom + constant
at.bottom == top_view.at.top + constant
else:
at.top == top_view.at.bottom_padding + constant
at.bottom == bottom_view.at.top_padding + constant
def vertical_between(self, leading_view, trailing_view, constant=0,
fit=default_fit):
at = self.view.at
enable(leading_view, trailing_view)
self.vertical(constant, fit)
if fit == Dock.TIGHT:
at.leading == leading_view.at.trailing + constant
at.trailing == trailing_view.at.leading + constant
elif fit == Dock.MARGIN:
at.leading == leading_view.at.trailing_padding + constant
at.trailing == trailing_view.at.leading_padding + constant
def _set_size(self, share):
if share is not None:
share_x, share_y = share if type(share) in (list, tuple) else (
share, share)
at = self.view.at
s = enable(self.superview)
at.width == s.width * share_x
at.height == s.height * share_y
def top(self, share=None, constant=0, fit=default_fit):
at = self.view.at
at.top == self._fit(fit).top + constant
at.leading == self._fit(fit).leading + constant
at.trailing == self._fit(fit).trailing - constant
if share is not None:
at.height == enable(self.superview).at.height * share
def bottom(self, share=None, constant=0, fit=default_fit):
at = self.view.at
at.bottom == self._fit(fit).bottom - constant
at.leading == self._fit(fit).leading + constant
at.trailing == self._fit(fit).trailing - constant
if share is not None:
at.height == enable(self.superview).at.height * share
def leading(self, share=None, constant=0, fit=default_fit):
at = self.view.at
at.leading == self._fit(fit).leading + constant
at.top == self._fit(fit).top + constant
at.bottom == self._fit(fit).bottom - constant
if share is not None:
at.width == enable(self.superview).at.width * share
def trailing(self, share=None, constant=0, fit=default_fit):
at = self.view.at
at.trailing == self._fit(fit).trailing - constant
at.top == self._fit(fit).top + constant
at.bottom == self._fit(fit).bottom - constant
if share is not None:
at.width == enable(self.superview).at.width * share
def top_leading(self, share=None, constant=0, fit=default_fit):
at = self.view.at
at.top == self._fit(fit).top + constant
at.leading == self._fit(fit).leading + constant
self._set_size(share)
def top_trailing(self, share=None, constant=0, fit=default_fit):
at = self.view.at
at.top == self._fit(fit).top + constant
at.trailing == self._fit(fit).trailing - constant
self._set_size(share)
def bottom_leading(self, share=None, constant=0, fit=default_fit):
at = self.view.at
at.bottom == self._fit(fit).bottom - constant
at.leading == self._fit(fit).leading + constant
self._set_size(share)
def bottom_trailing(self, share=None, constant=0, fit=default_fit):
at = self.view.at
at.bottom == self._fit(fit).bottom - constant
at.trailing == self._fit(fit).trailing - constant
self._set_size(share)
class Align:
'''Align methods are convenient for aligning same properties of views:
view_a.align.top(view_b)
They are especially convenient when you need to align several views at
once:
view_a.align.center_x(view_b, view_c)
'''
def __init__(self, view):
self.view = view
def _align(self, other_views):
attribute_name = inspect.currentframe().f_back.f_code.co_name
for other_view in other_views:
enable(other_view)
last_constraint = (
getattr(self.view.at, attribute_name) ==
getattr(other_view.at, attribute_name))
return last_constraint
def left(self, *others):
return self._align(others)
def right(self, *others):
return self._align(others)
def top(self, *others):
return self._align(others)
def bottom(self, *others):
return self._align(others)
def leading(self, *others):
return self._align(others)
def trailing(self, *others):
return self._align(others)
def width(self, *others):
return self._align(others)
def height(self, *others):
return self._align(others)
def center_x(self, *others):
return self._align(others)
def center_y(self, *others):
return self._align(others)
def last_baseline(self, *others):
return self._align(others)
def first_baseline(self, *others):
return self._align(others)
def left_margin(self, *others):
return self._align(others)
def right_margin(self, *others):
return self._align(others)
def top_margin(self, *others):
return self._align(others)
def bottom_margin(self, *others):
return self._align(others)
def leading_margin(self, *others):
return self._align(others)
def trailing_margin(self, *others):
return self._align(others)
def left_padding(self, *others):
return self._align(others)
def right_padding(self, *others):
return self._align(others)
def top_padding(self, *others):
return self._align(others)
def bottom_padding(self, *others):
return self._align(others)
def leading_padding(self, *others):
return self._align(others)
def trailing_padding(self, *others):
return self._align(others)
def size(self, *others):
self.width(*others)
return self.height(*others)
def center(self, *others):
self.center_x(*others)
return self.center_y(*others)
class ConstraintView:
@property
def at(self):
return At(self)
@property
def align(self):
return Align(self)
@property
def dock(self):
return Dock(self)
class Constrainer():
def __new__(extender_subclass, *args, **kwargs):
target_instance = extender_subclass._builtin_class(*args, **kwargs)
target_instance.at = At(target_instance)
target_instance.align = Align(target_instance)
target_instance.dock = Dock(target_instance)
return target_instance
# Generate enabled versions for all ui views
for key in ui.__dict__:
value = getattr(ui, key, None)
if type(value) is type and ui.View in value.mro():
globals()[key] = type(key, (Constrainer,), {'_builtin_class': value})
def enable(*views):
""" All views must be enabled before constraints can be applied. It is safe
to enable an already-enabled view.
You can provide several views to be enabled. First view is returned."""
for view in views:
assert hasattr(view, 'objc_instance')
view.at = At(view)
view.dock = Dock(view)
view.align = Align(view)
return views[0]
def fit(*views):
""" Convenience method to both enable and apply natural fit width and
height constraints with one call. Useful mainly for Buttons and Labels.
You can provide several views, first view is returned. """
for view in views:
enable(view)
view.dock.fit()
return views[0]
@objc_util.on_main_thread
def find_constraint(view, description):
objc_view = view.objc_instance
while view:
for c in view.objc_instance.constraints():
if str(c._deallocSafeDescription()) == description:
return c
view = view.superview
@objc_util.on_main_thread
def find_constraints(view, first=True, second=False, active_only=True,
filter=None):
objc_view = view.objc_instance
constraints = []
if filter is None:
filter = []
elif type(filter) not in (tuple, list):
filter = [filter]
filter = [inspect.getclosurevars(filter_prop.fget).nonlocals['attribute']
for filter_prop in filter]
while view:
for c in view.objc_instance.constraints():
if (
(first and c.firstItem() == objc_view) or
(second and c.secondItem() == objc_view)
) and (
c.active() or not active_only
) and (
len(filter) == 0 or c.firstAttribute() in filter
):
constraints.append(c)
view = view.superview
return constraints
def remove_constraints(view, filter=None):
if hasattr(view, 'layout_constraints'):
for constraint in view.layout_constraints.copy():
if filter is not None and constraint.attribute_name not in filter:
print('skipping', constraint.attribute_name)
continue
remove_constraint(constraint)
# remove_constraint(view.layout_constraints)
@objc_util.on_main_thread
def remove_guides(view):
''' Removes all layout guides from a view. '''
vo = view.objc_instance
guides = view.objc_instance.layoutGuides()
if type(guides) is list:
for guide in vo.layoutGuides():
vo.removeLayoutGuide_(guide)
@objc_util.on_main_thread
def remove_guide(guide):
''' Remove the given guide from its owner. '''
vo = guide.view.objc_instance
vo.removeLayoutGuide_(guide.objc_instance)
guide.view = None
guide.objc_instance = None
def check_ambiguity(view, indent=0):
"""Prints all views in the view hierarchy starting with the given view,
marking the ones that have ambiguous layout.
Returns a list of ambiguous views."""
ambiguous_views = []
layout = '- Frames'
if not view.objc_instance.translatesAutoresizingMaskIntoConstraints():
layout = '- Constraints'
if view.at.is_ambiguous:
layout += ' AMBIGUOUS'
ambiguous_views.append(view)
view_name = view.name
if view_name is None or len(view_name) == 0:
view_name = str(view)
print(' ' * indent, view_name, layout)
for subview in view.subviews:
ambiguous_views += check_ambiguity(subview, indent + 1)
return ambiguous_views
class Guide(SimpleNamespace):
@objc_util.on_main_thread
def __init__(self, view):
guide = UILayoutGuide.new().autorelease()
view.objc_instance.addLayoutGuide_(guide)
super().__init__(
objc_instance=guide,
view=view,
name='LayoutGuide')
enable(self)
@property
def superview(self):
if self.view:
return self.view.superview
@property
def subviews(self):
if self.view:
return self.view.subviews
class Dimensions:
@classmethod
def horizontal_size_class(cls):
return 'constrained' \
if cls.is_phone() and cls.is_portrait() \
else 'regular'
# This does not currently work on
# iPhone X iOS 12.1.3:
# return ['constrained', 'regular'][UIApplication.sharedApplication().\
# keyWindow().traitCollection().\
# horizontalSizeClass() - 1]
@classmethod
def vertical_size_class(cls):
return ['constrained', 'regular'][UIApplication.sharedApplication().\
keyWindow().traitCollection().\
verticalSizeClass() - 1]
@classmethod
def is_portrait(cls):
"Returns true if the device thinks it is in portrait orientation."
w, h = ui.get_screen_size()
return w < h
@classmethod
def is_landscape(cls):
"Returns true if the device thinks it is in landscape orientation."
w, h = ui.get_screen_size()
return w > h
@classmethod
def is_phone(cls):
"Returns true if the device is a phone-type device."
return objc_util.UIApplication.sharedApplication().keyWindow().\
traitCollection().userInterfaceIdiom() == 0
@classmethod
def is_pad(cls):
"Returns true if the device is a pad-type device."
return UIApplication.sharedApplication().keyWindow().\
traitCollection().userInterfaceIdiom() == 1
@classmethod
def is_width_constrained(cls):
"""Returns true if the display is relatively narrow in the current
orientation (e.g. phone in the portrait orientation). """
return cls.horizontal_size_class() == 'constrained'
@classmethod
def is_width_regular(cls):
"""Returns true if the display is relatively wide in the current
orientation (e.g. phone in the landscape orientation, or an iPad in
any orientation). """
return cls.horizontal_size_class() == 'regular'
@classmethod
def is_height_constrained(cls):
"""Returns true if the display is relatively small in the vertical
direction (e.g. phone in the landscape orientation). """
return cls.vertical_size_class() == 'constrained'
@classmethod
def is_height_regular(cls):
"""Returns true if the display is relatively tall in the current
orientation (e.g. phone held in the portrait orientation, or an iPad
in any orientation). """
return cls.vertical_size_class() == 'regular'
def add_subviews(view):
"""
Convenience method to add all members of a view that are views as its
subviews.
"""
for key in view.__dict__:
value = getattr(view, key)
if isinstance(value, ui.View):
view.add_subview(value)
class GridView(ui.View):
'Places subviews as squares that fill the available space.'
FILL = 'III'
SPREAD = '___'
CENTER = '_I_'
START = 'II_'
END = '_II'
SIDES = 'I_I'
START_SPREAD = 'I__'
END_SPREAD = '__I'
MARGIN = At.standard
TIGHT = 0
def __init__(self,
pack_x=None, pack_y=None, pack=CENTER,
count_x=None, count_y=None,
gap=MARGIN, **kwargs):
"""By default, subviews are laid out in a grid as squares of optimal
size and centered in the view.
You can fix the amount of views in either dimension with the
`count_x` or `count_y` parameter, or change the packing behaviour by
providing the `pack` parameter with one of the following values:
* `CENTER` - Clustered in the center (the default)
* `SPREAD` - Distributed evenly
* `FILL` - Fill the available space with only margins in between
(no longer squares)
* `LEADING, TRAILING` (`pack_x` only)
* `TOP, BOTTOM` (`pack_y` only)
"""
super().__init__(**kwargs)
self.pack_x = pack_x or pack
self.pack_y = pack_y or pack
self.leading_free = self.pack_x[0] == '_'
self.center_x_free = self.pack_x[1] == '_'
self.trailing_free = self.pack_x[2] == '_'
self.top_free = self.pack_y[0] == '_'
self.center_y_free = self.pack_y[1] == '_'
self.bottom_free = self.pack_y[2] == '_'
self.count_x = count_x
self.count_y = count_y
self.gap = gap
enable(self)
def dimensions(self, count):
if self.height == 0:
return 1, count
ratio = self.width / self.height
count_x = math.sqrt(count * self.width / self.height)
count_y = math.sqrt(count * self.height / self.width)
operations = (
(math.floor, math.floor),
(math.floor, math.ceil),
(math.ceil, math.floor),
(math.ceil, math.ceil)
)
best = None
best_x = None
best_y = None
for oper in operations:
cand_x = oper[0](count_x)
cand_y = oper[1](count_y)
diff = cand_x * cand_y - count
if diff >= 0:
if best is None or diff < best:
best = diff
best_x = cand_x
best_y = cand_y
return (best_x, best_y)
def layout(self):
count = len(self.subviews)
if count == 0: return
count_x, count_y = self.count_x, self.count_y
if count_x is None and count_y is None:
count_x, count_y = self.dimensions(count)
elif count_x is None: